Engine.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Audio.h"
  24. #include "Console.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "DebugHud.h"
  28. #include "Engine.h"
  29. #include "FileSystem.h"
  30. #include "Graphics.h"
  31. #include "Input.h"
  32. #include "InputEvents.h"
  33. #include "Log.h"
  34. #include "Navigation.h"
  35. #include "Network.h"
  36. #include "PackageFile.h"
  37. #include "PhysicsWorld.h"
  38. #include "ProcessUtils.h"
  39. #include "Profiler.h"
  40. #include "Renderer.h"
  41. #include "ResourceCache.h"
  42. #include "Scene.h"
  43. #include "SceneEvents.h"
  44. #include "UI.h"
  45. #include "Urho2D.h"
  46. #include "WorkQueue.h"
  47. #include "XMLFile.h"
  48. #include "DebugNew.h"
  49. #if defined(_MSC_VER) && defined(_DEBUG)
  50. // From dbgint.h
  51. #define nNoMansLandSize 4
  52. typedef struct _CrtMemBlockHeader
  53. {
  54. struct _CrtMemBlockHeader* pBlockHeaderNext;
  55. struct _CrtMemBlockHeader* pBlockHeaderPrev;
  56. char* szFileName;
  57. int nLine;
  58. size_t nDataSize;
  59. int nBlockUse;
  60. long lRequest;
  61. unsigned char gap[nNoMansLandSize];
  62. } _CrtMemBlockHeader;
  63. #endif
  64. #ifdef ANDROID
  65. extern "C"
  66. {
  67. void Android_JNI_FinishActivity();
  68. }
  69. #endif
  70. namespace Urho3D
  71. {
  72. extern const char* logLevelPrefixes[];
  73. Engine::Engine(Context* context) :
  74. Object(context),
  75. timeStep_(0.0f),
  76. timeStepSmoothing_(2),
  77. minFps_(10),
  78. #if defined(ANDROID) || defined(IOS) || defined(RASPI)
  79. maxFps_(60),
  80. maxInactiveFps_(10),
  81. pauseMinimized_(true),
  82. #else
  83. maxFps_(200),
  84. maxInactiveFps_(60),
  85. pauseMinimized_(false),
  86. #endif
  87. #ifdef ENABLE_TESTING
  88. timeOut_(0),
  89. #endif
  90. autoExit_(true),
  91. initialized_(false),
  92. #ifdef ANDROID
  93. exitRequested_(false),
  94. #endif
  95. exiting_(false),
  96. headless_(false),
  97. audioPaused_(false)
  98. {
  99. // Register self as a subsystem
  100. context_->RegisterSubsystem(this);
  101. // Create subsystems which do not depend on engine initialization or startup parameters
  102. context_->RegisterSubsystem(new Time(context_));
  103. context_->RegisterSubsystem(new WorkQueue(context_));
  104. #ifdef ENABLE_PROFILING
  105. context_->RegisterSubsystem(new Profiler(context_));
  106. #endif
  107. context_->RegisterSubsystem(new FileSystem(context_));
  108. #ifdef ENABLE_LOGGING
  109. context_->RegisterSubsystem(new Log(context_));
  110. #endif
  111. context_->RegisterSubsystem(new ResourceCache(context_));
  112. context_->RegisterSubsystem(new Network(context_));
  113. context_->RegisterSubsystem(new Input(context_));
  114. context_->RegisterSubsystem(new Audio(context_));
  115. context_->RegisterSubsystem(new UI(context_));
  116. // Register object factories for libraries which are not automatically registered along with subsystem creation
  117. RegisterSceneLibrary(context_);
  118. RegisterPhysicsLibrary(context_);
  119. RegisterNavigationLibrary(context_);
  120. SubscribeToEvent(E_EXITREQUESTED, HANDLER(Engine, HandleExitRequested));
  121. }
  122. Engine::~Engine()
  123. {
  124. }
  125. bool Engine::Initialize(const VariantMap& parameters)
  126. {
  127. if (initialized_)
  128. return true;
  129. PROFILE(InitEngine);
  130. // Set headless mode
  131. headless_ = GetParameter(parameters, "Headless", false).GetBool();
  132. // Register the rest of the subsystems
  133. if (!headless_)
  134. {
  135. context_->RegisterSubsystem(new Graphics(context_));
  136. context_->RegisterSubsystem(new Renderer(context_));
  137. }
  138. else
  139. {
  140. // Register graphics library objects explicitly in headless mode to allow them to work without using actual GPU resources
  141. RegisterGraphicsLibrary(context_);
  142. }
  143. // 2D graphics library is dependent on 3D graphics library
  144. RegisterUrho2DLibrary(context_);
  145. // Start logging
  146. Log* log = GetSubsystem<Log>();
  147. if (log)
  148. {
  149. if (HasParameter(parameters, "LogLevel"))
  150. log->SetLevel(GetParameter(parameters, "LogLevel").GetInt());
  151. log->SetQuiet(GetParameter(parameters, "LogQuiet", false).GetBool());
  152. log->Open(GetParameter(parameters, "LogName", "Urho3D.log").GetString());
  153. }
  154. // Set maximally accurate low res timer
  155. GetSubsystem<Time>()->SetTimerPeriod(1);
  156. // Configure max FPS
  157. if (GetParameter(parameters, "FrameLimiter", true) == false)
  158. SetMaxFps(0);
  159. // Set amount of worker threads according to the available physical CPU cores. Using also hyperthreaded cores results in
  160. // unpredictable extra synchronization overhead. Also reserve one core for the main thread
  161. unsigned numThreads = GetParameter(parameters, "WorkerThreads", true).GetBool() ? GetNumPhysicalCPUs() - 1 : 0;
  162. if (numThreads)
  163. {
  164. GetSubsystem<WorkQueue>()->CreateThreads(numThreads);
  165. LOGINFOF("Created %u worker thread%s", numThreads, numThreads > 1 ? "s" : "");
  166. }
  167. // Add resource paths
  168. ResourceCache* cache = GetSubsystem<ResourceCache>();
  169. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  170. String exePath = fileSystem->GetProgramDir();
  171. Vector<String> resourcePaths = GetParameter(parameters, "ResourcePaths", "CoreData;Data").GetString().Split(';');
  172. Vector<String> resourcePackages = GetParameter(parameters, "ResourcePackages").GetString().Split(';');
  173. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  174. {
  175. bool success = false;
  176. // If path is not absolute, prefer to add it as a package if possible
  177. if (!IsAbsolutePath(resourcePaths[i]))
  178. {
  179. String packageName = exePath + resourcePaths[i] + ".pak";
  180. if (fileSystem->FileExists(packageName))
  181. {
  182. SharedPtr<PackageFile> package(new PackageFile(context_));
  183. if (package->Open(packageName))
  184. {
  185. cache->AddPackageFile(package);
  186. success = true;
  187. }
  188. }
  189. if (!success)
  190. {
  191. String pathName = exePath + resourcePaths[i];
  192. if (fileSystem->DirExists(pathName))
  193. success = cache->AddResourceDir(pathName);
  194. }
  195. }
  196. else
  197. {
  198. String pathName = resourcePaths[i];
  199. if (fileSystem->DirExists(pathName))
  200. success = cache->AddResourceDir(pathName);
  201. }
  202. if (!success)
  203. {
  204. LOGERROR("Failed to add resource path " + resourcePaths[i]);
  205. return false;
  206. }
  207. }
  208. // Then add specified packages
  209. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  210. {
  211. bool success = false;
  212. String packageName = exePath + resourcePackages[i];
  213. if (fileSystem->FileExists(packageName))
  214. {
  215. SharedPtr<PackageFile> package(new PackageFile(context_));
  216. if (package->Open(packageName))
  217. {
  218. cache->AddPackageFile(package);
  219. success = true;
  220. }
  221. }
  222. if (!success)
  223. {
  224. LOGERROR("Failed to add resource package " + resourcePackages[i]);
  225. return false;
  226. }
  227. }
  228. // Initialize graphics & audio output
  229. if (!headless_)
  230. {
  231. Graphics* graphics = GetSubsystem<Graphics>();
  232. Renderer* renderer = GetSubsystem<Renderer>();
  233. if (HasParameter(parameters, "ExternalWindow"))
  234. graphics->SetExternalWindow(GetParameter(parameters, "ExternalWindow").GetVoidPtr());
  235. graphics->SetForceSM2(GetParameter(parameters, "ForceSM2", false).GetBool());
  236. graphics->SetWindowTitle(GetParameter(parameters, "WindowTitle", "Urho3D").GetString());
  237. graphics->SetWindowIcon(cache->GetResource<Image>(GetParameter(parameters, "WindowIcon", String::EMPTY).GetString()));
  238. if (!graphics->SetMode(
  239. GetParameter(parameters, "WindowWidth", 0).GetInt(),
  240. GetParameter(parameters, "WindowHeight", 0).GetInt(),
  241. GetParameter(parameters, "FullScreen", true).GetBool(),
  242. GetParameter(parameters, "Borderless", false).GetBool(),
  243. GetParameter(parameters, "WindowResizable", false).GetBool(),
  244. GetParameter(parameters, "VSync", false).GetBool(),
  245. GetParameter(parameters, "TripleBuffer", false).GetBool(),
  246. GetParameter(parameters, "MultiSample", 1).GetInt()
  247. ))
  248. return false;
  249. if (HasParameter(parameters, "DumpShaders"))
  250. graphics->BeginDumpShaders(GetParameter(parameters, "DumpShaders", String::EMPTY).GetString());
  251. if (HasParameter(parameters, "RenderPath"))
  252. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, "RenderPath").GetString()));
  253. renderer->SetDrawShadows(GetParameter(parameters, "Shadows", true).GetBool());
  254. if (renderer->GetDrawShadows() && GetParameter(parameters, "LowQualityShadows", false).GetBool())
  255. renderer->SetShadowQuality(SHADOWQUALITY_LOW_16BIT);
  256. if (GetParameter(parameters, "Sound", true).GetBool())
  257. {
  258. GetSubsystem<Audio>()->SetMode(
  259. GetParameter(parameters, "SoundBuffer", 100).GetInt(),
  260. GetParameter(parameters, "SoundMixRate", 44100).GetInt(),
  261. GetParameter(parameters, "SoundStereo", true).GetBool(),
  262. GetParameter(parameters, "SoundInterpolation", true).GetBool()
  263. );
  264. }
  265. }
  266. // Init FPU state of main thread
  267. InitFPU();
  268. #ifdef ENABLE_TESTING
  269. if (HasParameter(parameters, "TimeOut"))
  270. timeOut_ = GetParameter(parameters, "TimeOut", 0).GetInt() * 1000000LL;
  271. #endif
  272. // In debug mode, check now that all factory created objects can be created without crashing
  273. #ifdef _DEBUG
  274. const HashMap<ShortStringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
  275. for (HashMap<ShortStringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories.Begin(); i != factories.End(); ++i)
  276. SharedPtr<Object> object = i->second_->CreateObject();
  277. #endif
  278. frameTimer_.Reset();
  279. initialized_ = true;
  280. return true;
  281. }
  282. void Engine::RunFrame()
  283. {
  284. assert(initialized_);
  285. // If not headless, and the graphics subsystem no longer has a window open, assume we should exit
  286. if (!headless_ && !GetSubsystem<Graphics>()->IsInitialized())
  287. exiting_ = true;
  288. if (exiting_)
  289. return;
  290. // Note: there is a minimal performance cost to looking up subsystems (uses a hashmap); if they would be looked up several
  291. // times per frame it would be better to cache the pointers
  292. Time* time = GetSubsystem<Time>();
  293. Input* input = GetSubsystem<Input>();
  294. Audio* audio = GetSubsystem<Audio>();
  295. time->BeginFrame(timeStep_);
  296. // If pause when minimized -mode is in use, stop updates and audio as necessary
  297. if (pauseMinimized_ && input->IsMinimized())
  298. {
  299. if (audio->IsPlaying())
  300. {
  301. audio->Stop();
  302. audioPaused_ = true;
  303. }
  304. }
  305. else
  306. {
  307. // Only unpause when it was paused by the engine
  308. if (audioPaused_)
  309. {
  310. audio->Play();
  311. audioPaused_ = false;
  312. }
  313. Update();
  314. }
  315. Render();
  316. ApplyFrameLimit();
  317. time->EndFrame();
  318. }
  319. Console* Engine::CreateConsole()
  320. {
  321. if (headless_ || !initialized_)
  322. return 0;
  323. // Return existing console if possible
  324. Console* console = GetSubsystem<Console>();
  325. if (!console)
  326. {
  327. console = new Console(context_);
  328. context_->RegisterSubsystem(console);
  329. }
  330. return console;
  331. }
  332. DebugHud* Engine::CreateDebugHud()
  333. {
  334. if (headless_ || !initialized_)
  335. return 0;
  336. // Return existing debug HUD if possible
  337. DebugHud* debugHud = GetSubsystem<DebugHud>();
  338. if (!debugHud)
  339. {
  340. debugHud = new DebugHud(context_);
  341. context_->RegisterSubsystem(debugHud);
  342. }
  343. return debugHud;
  344. }
  345. void Engine::SetTimeStepSmoothing(int frames)
  346. {
  347. timeStepSmoothing_ = Clamp(frames, 1, 20);
  348. }
  349. void Engine::SetMinFps(int fps)
  350. {
  351. minFps_ = Max(fps, 0);
  352. }
  353. void Engine::SetMaxFps(int fps)
  354. {
  355. maxFps_ = Max(fps, 0);
  356. }
  357. void Engine::SetMaxInactiveFps(int fps)
  358. {
  359. maxInactiveFps_ = Max(fps, 0);
  360. }
  361. void Engine::SetPauseMinimized(bool enable)
  362. {
  363. pauseMinimized_ = enable;
  364. }
  365. void Engine::SetAutoExit(bool enable)
  366. {
  367. // On mobile platforms exit is mandatory if requested by the platform itself and should not be attempted to be disabled
  368. #if defined(ANDROID) || defined(IOS)
  369. enable = true;
  370. #endif
  371. autoExit_ = enable;
  372. }
  373. void Engine::Exit()
  374. {
  375. #if defined(IOS)
  376. // On iOS it's not legal for the application to exit on its own, instead it will be minimized with the home key
  377. #elif defined(ANDROID)
  378. // On Android we request the Java activity to finish itself
  379. if (!exitRequested_)
  380. {
  381. Android_JNI_FinishActivity();
  382. exitRequested_ = true;
  383. }
  384. #else
  385. DoExit();
  386. #endif
  387. }
  388. void Engine::DumpProfiler()
  389. {
  390. Profiler* profiler = GetSubsystem<Profiler>();
  391. if (profiler)
  392. LOGRAW(profiler->GetData(true, true) + "\n");
  393. }
  394. void Engine::DumpResources()
  395. {
  396. #ifdef ENABLE_LOGGING
  397. ResourceCache* cache = GetSubsystem<ResourceCache>();
  398. const HashMap<ShortStringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  399. LOGRAW("\n");
  400. for (HashMap<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
  401. i != resourceGroups.End(); ++i)
  402. {
  403. unsigned num = i->second_.resources_.Size();
  404. unsigned memoryUse = i->second_.memoryUse_;
  405. if (num)
  406. {
  407. LOGRAW("Resource type " + i->second_.resources_.Begin()->second_->GetTypeName() +
  408. ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
  409. }
  410. }
  411. LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
  412. #endif
  413. }
  414. void Engine::DumpMemory()
  415. {
  416. #ifdef ENABLE_LOGGING
  417. #if defined(_MSC_VER) && defined(_DEBUG)
  418. _CrtMemState state;
  419. _CrtMemCheckpoint(&state);
  420. _CrtMemBlockHeader* block = state.pBlockHeader;
  421. unsigned total = 0;
  422. unsigned blocks = 0;
  423. for (;;)
  424. {
  425. if (block && block->pBlockHeaderNext)
  426. block = block->pBlockHeaderNext;
  427. else
  428. break;
  429. }
  430. while (block)
  431. {
  432. if (block->nBlockUse > 0)
  433. {
  434. if (block->szFileName)
  435. LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes, file " + String(block->szFileName) + " line " + String(block->nLine) + "\n");
  436. else
  437. LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes\n");
  438. total += block->nDataSize;
  439. ++blocks;
  440. }
  441. block = block->pBlockHeaderPrev;
  442. }
  443. LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
  444. #else
  445. LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
  446. #endif
  447. #endif
  448. }
  449. void Engine::Update()
  450. {
  451. PROFILE(Update);
  452. // Logic update event
  453. using namespace Update;
  454. VariantMap& eventData = GetEventDataMap();
  455. eventData[P_TIMESTEP] = timeStep_;
  456. SendEvent(E_UPDATE, eventData);
  457. // Logic post-update event
  458. SendEvent(E_POSTUPDATE, eventData);
  459. // Rendering update event
  460. SendEvent(E_RENDERUPDATE, eventData);
  461. // Post-render update event
  462. SendEvent(E_POSTRENDERUPDATE, eventData);
  463. }
  464. void Engine::Render()
  465. {
  466. if (headless_)
  467. return;
  468. PROFILE(Render);
  469. // If device is lost, BeginFrame will fail and we skip rendering
  470. Graphics* graphics = GetSubsystem<Graphics>();
  471. if (!graphics->BeginFrame())
  472. return;
  473. GetSubsystem<Renderer>()->Render();
  474. GetSubsystem<UI>()->Render();
  475. graphics->EndFrame();
  476. }
  477. void Engine::ApplyFrameLimit()
  478. {
  479. if (!initialized_)
  480. return;
  481. int maxFps = maxFps_;
  482. Input* input = GetSubsystem<Input>();
  483. if (input && !input->HasFocus())
  484. maxFps = Min(maxInactiveFps_, maxFps);
  485. long long elapsed = 0;
  486. // Perform waiting loop if maximum FPS set
  487. if (maxFps)
  488. {
  489. PROFILE(ApplyFrameLimit);
  490. long long targetMax = 1000000LL / maxFps;
  491. for (;;)
  492. {
  493. elapsed = frameTimer_.GetUSec(false);
  494. if (elapsed >= targetMax)
  495. break;
  496. // Sleep if 1 ms or more off the frame limiting goal
  497. if (targetMax - elapsed >= 1000LL)
  498. {
  499. unsigned sleepTime = (unsigned)((targetMax - elapsed) / 1000LL);
  500. Time::Sleep(sleepTime);
  501. }
  502. }
  503. }
  504. elapsed = frameTimer_.GetUSec(true);
  505. #ifdef ENABLE_TESTING
  506. if (timeOut_ > 0)
  507. {
  508. timeOut_ -= elapsed;
  509. if (timeOut_ <= 0)
  510. Exit();
  511. }
  512. #endif
  513. // If FPS lower than minimum, clamp elapsed time
  514. if (minFps_)
  515. {
  516. long long targetMin = 1000000LL / minFps_;
  517. if (elapsed > targetMin)
  518. elapsed = targetMin;
  519. }
  520. // Perform timestep smoothing
  521. timeStep_ = 0.0f;
  522. lastTimeSteps_.Push(elapsed / 1000000.0f);
  523. if (lastTimeSteps_.Size() > timeStepSmoothing_)
  524. {
  525. // If the smoothing configuration was changed, ensure correct amount of samples
  526. lastTimeSteps_.Erase(0, lastTimeSteps_.Size() - timeStepSmoothing_);
  527. for (unsigned i = 0; i < lastTimeSteps_.Size(); ++i)
  528. timeStep_ += lastTimeSteps_[i];
  529. timeStep_ /= lastTimeSteps_.Size();
  530. }
  531. else
  532. timeStep_ = lastTimeSteps_.Back();
  533. }
  534. VariantMap Engine::ParseParameters(const Vector<String>& arguments)
  535. {
  536. VariantMap ret;
  537. for (unsigned i = 0; i < arguments.Size(); ++i)
  538. {
  539. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  540. {
  541. String argument = arguments[i].Substring(1).ToLower();
  542. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  543. if (argument == "headless")
  544. ret["Headless"] = true;
  545. else if (argument == "nolimit")
  546. ret["FrameLimiter"] = false;
  547. else if (argument == "nosound")
  548. ret["Sound"] = false;
  549. else if (argument == "noip")
  550. ret["SoundInterpolation"] = false;
  551. else if (argument == "mono")
  552. ret["SoundStereo"] = false;
  553. else if (argument == "prepass")
  554. ret["RenderPath"] = "RenderPaths/Prepass.xml";
  555. else if (argument == "deferred")
  556. ret["RenderPath"] = "RenderPaths/Deferred.xml";
  557. else if (argument == "noshadows")
  558. ret["Shadows"] = false;
  559. else if (argument == "lqshadows")
  560. ret["LowQualityShadows"] = true;
  561. else if (argument == "nothreads")
  562. ret["WorkerThreads"] = false;
  563. else if (argument == "sm2")
  564. ret["ForceSM2"] = true;
  565. else if (argument == "v")
  566. ret["VSync"] = true;
  567. else if (argument == "t")
  568. ret["TripleBuffer"] = true;
  569. else if (argument == "w")
  570. ret["FullScreen"] = false;
  571. else if (argument == "s")
  572. ret["WindowResizable"] = true;
  573. else if (argument == "borderless")
  574. ret["Borderless"] = true;
  575. else if (argument == "q")
  576. ret["LogQuiet"] = true;
  577. else if (argument == "log" && !value.Empty())
  578. {
  579. int logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, -1);
  580. if (logLevel != -1)
  581. {
  582. ret["LogLevel"] = logLevel;
  583. ++i;
  584. }
  585. }
  586. else if (argument == "x" && !value.Empty())
  587. {
  588. ret["WindowWidth"] = ToInt(value);
  589. ++i;
  590. }
  591. else if (argument == "y" && !value.Empty())
  592. {
  593. ret["WindowHeight"] = ToInt(value);
  594. ++i;
  595. }
  596. else if (argument == "m" && !value.Empty())
  597. {
  598. ret["MultiSample"] = ToInt(value);
  599. ++i;
  600. }
  601. else if (argument == "b" && !value.Empty())
  602. {
  603. ret["SoundBuffer"] = ToInt(value);
  604. ++i;
  605. }
  606. else if (argument == "r" && !value.Empty())
  607. {
  608. ret["SoundMixRate"] = ToInt(value);
  609. ++i;
  610. }
  611. else if (argument == "p" && !value.Empty())
  612. {
  613. ret["ResourcePaths"] = value;
  614. ++i;
  615. }
  616. else if (argument == "ds" && !value.Empty())
  617. {
  618. ret["DumpShaders"] = value;
  619. ++i;
  620. }
  621. #ifdef ENABLE_TESTING
  622. else if (argument == "timeout" && !value.Empty())
  623. {
  624. ret["TimeOut"] = ToInt(value);
  625. ++i;
  626. }
  627. #endif
  628. }
  629. }
  630. return ret;
  631. }
  632. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  633. {
  634. ShortStringHash nameHash(parameter);
  635. return parameters.Find(nameHash) != parameters.End();
  636. }
  637. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  638. {
  639. ShortStringHash nameHash(parameter);
  640. VariantMap::ConstIterator i = parameters.Find(nameHash);
  641. return i != parameters.End() ? i->second_ : defaultValue;
  642. }
  643. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  644. {
  645. if (autoExit_)
  646. {
  647. // Do not call Exit() here, as it contains mobile platform -specific tests to not exit.
  648. // If we do receive an exit request from the system on those platforms, we must comply
  649. DoExit();
  650. }
  651. }
  652. void Engine::DoExit()
  653. {
  654. Graphics* graphics = GetSubsystem<Graphics>();
  655. if (graphics)
  656. graphics->Close();
  657. exiting_ = true;
  658. }
  659. }