Engine.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. //
  2. // Copyright (c) 2008-2016 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/Audio.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/CoreEvents.h"
  26. #include "../Core/ProcessUtils.h"
  27. #include "../Core/Profiler.h"
  28. #include "../Core/EventProfiler.h"
  29. #include "../Core/WorkQueue.h"
  30. #include "../Engine/Engine.h"
  31. #include "../Graphics/Graphics.h"
  32. #include "../Graphics/Renderer.h"
  33. #include "../IO/FileSystem.h"
  34. #include "../Input/Input.h"
  35. #include "../IO/Log.h"
  36. #include "../IO/PackageFile.h"
  37. // ATOMIC BEGIN
  38. #include "../Resource/XMLFile.h"
  39. // ATOMIC END
  40. #ifdef ATOMIC_NAVIGATION
  41. #include "../Navigation/NavigationMesh.h"
  42. #endif
  43. #ifdef ATOMIC_NETWORK
  44. #include "../Network/Network.h"
  45. #endif
  46. #ifdef ATOMIC_DATABASE
  47. #include "../Database/Database.h"
  48. #endif
  49. #ifdef ATOMIC_PHYSICS
  50. #include "../Physics/PhysicsWorld.h"
  51. #endif
  52. #include "../Resource/ResourceCache.h"
  53. #include "../Resource/Localization.h"
  54. #include "../Scene/Scene.h"
  55. #include "../Scene/SceneEvents.h"
  56. #include "../UI/UI.h"
  57. #ifdef ATOMIC_ATOMIC2D
  58. #include "../Atomic2D/Atomic2D.h"
  59. #endif
  60. #if defined(__EMSCRIPTEN__) && defined(ATOMIC_TESTING)
  61. #include <emscripten/emscripten.h>
  62. #endif
  63. #include "../DebugNew.h"
  64. #if defined(_MSC_VER) && defined(_DEBUG)
  65. // From dbgint.h
  66. #define nNoMansLandSize 4
  67. typedef struct _CrtMemBlockHeader
  68. {
  69. struct _CrtMemBlockHeader* pBlockHeaderNext;
  70. struct _CrtMemBlockHeader* pBlockHeaderPrev;
  71. char* szFileName;
  72. int nLine;
  73. size_t nDataSize;
  74. int nBlockUse;
  75. long lRequest;
  76. unsigned char gap[nNoMansLandSize];
  77. } _CrtMemBlockHeader;
  78. #endif
  79. namespace Atomic
  80. {
  81. extern const char* logLevelPrefixes[];
  82. Engine::Engine(Context* context) :
  83. Object(context),
  84. timeStep_(0.0f),
  85. timeStepSmoothing_(2),
  86. minFps_(10),
  87. #if defined(IOS) || defined(__ANDROID__) || defined(__arm__) || defined(__aarch64__)
  88. maxFps_(60),
  89. maxInactiveFps_(10),
  90. pauseMinimized_(true),
  91. #else
  92. maxFps_(200),
  93. maxInactiveFps_(60),
  94. pauseMinimized_(false),
  95. #endif
  96. #ifdef ATOMIC_TESTING
  97. timeOut_(0),
  98. #endif
  99. autoExit_(true),
  100. initialized_(false),
  101. exiting_(false),
  102. headless_(false),
  103. audioPaused_(false)
  104. {
  105. // Register self as a subsystem
  106. context_->RegisterSubsystem(this);
  107. // Create subsystems which do not depend on engine initialization or startup parameters
  108. context_->RegisterSubsystem(new Time(context_));
  109. context_->RegisterSubsystem(new WorkQueue(context_));
  110. #ifdef ATOMIC_PROFILING
  111. context_->RegisterSubsystem(new Profiler(context_));
  112. #endif
  113. context_->RegisterSubsystem(new FileSystem(context_));
  114. #ifdef ATOMIC_LOGGING
  115. context_->RegisterSubsystem(new Log(context_));
  116. #endif
  117. context_->RegisterSubsystem(new ResourceCache(context_));
  118. context_->RegisterSubsystem(new Localization(context_));
  119. #ifdef ATOMIC_NETWORK
  120. context_->RegisterSubsystem(new Network(context_));
  121. #endif
  122. #ifdef ATOMIC_DATABASE
  123. context_->RegisterSubsystem(new Database(context_));
  124. #endif
  125. context_->RegisterSubsystem(new Input(context_));
  126. context_->RegisterSubsystem(new Audio(context_));
  127. context_->RegisterSubsystem(new UI(context_));
  128. // Register object factories for libraries which are not automatically registered along with subsystem creation
  129. RegisterSceneLibrary(context_);
  130. #ifdef ATOMIC_PHYSICS
  131. RegisterPhysicsLibrary(context_);
  132. #endif
  133. #ifdef ATOMIC_NAVIGATION
  134. RegisterNavigationLibrary(context_);
  135. #endif
  136. SubscribeToEvent(E_EXITREQUESTED, ATOMIC_HANDLER(Engine, HandleExitRequested));
  137. }
  138. Engine::~Engine()
  139. {
  140. }
  141. bool Engine::Initialize(const VariantMap& parameters)
  142. {
  143. if (initialized_)
  144. return true;
  145. ATOMIC_PROFILE(InitEngine);
  146. // Set headless mode
  147. headless_ = GetParameter(parameters, "Headless", false).GetBool();
  148. // Register the rest of the subsystems
  149. if (!headless_)
  150. {
  151. context_->RegisterSubsystem(new Graphics(context_));
  152. context_->RegisterSubsystem(new Renderer(context_));
  153. }
  154. else
  155. {
  156. // Register graphics library objects explicitly in headless mode to allow them to work without using actual GPU resources
  157. RegisterGraphicsLibrary(context_);
  158. }
  159. #ifdef ATOMIC_ATOMIC2D
  160. // 2D graphics library is dependent on 3D graphics library
  161. RegisterAtomic2DLibrary(context_);
  162. #endif
  163. // Start logging
  164. Log* log = GetSubsystem<Log>();
  165. if (log)
  166. {
  167. if (HasParameter(parameters, "LogLevel"))
  168. log->SetLevel(GetParameter(parameters, "LogLevel").GetInt());
  169. log->SetQuiet(GetParameter(parameters, "LogQuiet", false).GetBool());
  170. log->Open(GetParameter(parameters, "LogName", "Urho3D.log").GetString());
  171. }
  172. // Set maximally accurate low res timer
  173. GetSubsystem<Time>()->SetTimerPeriod(1);
  174. // Configure max FPS
  175. if (GetParameter(parameters, "FrameLimiter", true) == false)
  176. SetMaxFps(0);
  177. // Set amount of worker threads according to the available physical CPU cores. Using also hyperthreaded cores results in
  178. // unpredictable extra synchronization overhead. Also reserve one core for the main thread
  179. #ifdef ATOMIC_THREADING
  180. unsigned numThreads = GetParameter(parameters, "WorkerThreads", true).GetBool() ? GetNumPhysicalCPUs() - 1 : 0;
  181. if (numThreads)
  182. {
  183. GetSubsystem<WorkQueue>()->CreateThreads(numThreads);
  184. ATOMIC_LOGINFOF("Created %u worker thread%s", numThreads, numThreads > 1 ? "s" : "");
  185. }
  186. #endif
  187. // Add resource paths
  188. ResourceCache* cache = GetSubsystem<ResourceCache>();
  189. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  190. Vector<String> resourcePrefixPaths = GetParameter(parameters, "ResourcePrefixPaths", String::EMPTY).GetString().Split(';', true);
  191. for (unsigned i = 0; i < resourcePrefixPaths.Size(); ++i)
  192. resourcePrefixPaths[i] = AddTrailingSlash(
  193. IsAbsolutePath(resourcePrefixPaths[i]) ? resourcePrefixPaths[i] : fileSystem->GetProgramDir() + resourcePrefixPaths[i]);
  194. Vector<String> resourcePaths = GetParameter(parameters, "ResourcePaths", "Data;CoreData").GetString().Split(';');
  195. Vector<String> resourcePackages = GetParameter(parameters, "ResourcePackages").GetString().Split(';');
  196. Vector<String> autoLoadPaths = GetParameter(parameters, "AutoloadPaths", "Autoload").GetString().Split(';');
  197. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  198. {
  199. // If path is not absolute, prefer to add it as a package if possible
  200. if (!IsAbsolutePath(resourcePaths[i]))
  201. {
  202. unsigned j = 0;
  203. for (; j < resourcePrefixPaths.Size(); ++j)
  204. {
  205. String packageName = resourcePrefixPaths[j] + resourcePaths[i] + ".pak";
  206. if (fileSystem->FileExists(packageName))
  207. {
  208. if (cache->AddPackageFile(packageName))
  209. break;
  210. else
  211. return false; // The root cause of the error should have already been logged
  212. }
  213. String pathName = resourcePrefixPaths[j] + resourcePaths[i];
  214. if (fileSystem->DirExists(pathName))
  215. {
  216. if (cache->AddResourceDir(pathName))
  217. break;
  218. else
  219. return false;
  220. }
  221. }
  222. if (j == resourcePrefixPaths.Size())
  223. {
  224. ATOMIC_LOGERRORF(
  225. "Failed to add resource path '%s', check the documentation on how to set the 'resource prefix path'",
  226. resourcePaths[i].CString());
  227. return false;
  228. }
  229. }
  230. else
  231. {
  232. String pathName = resourcePaths[i];
  233. if (fileSystem->DirExists(pathName))
  234. if (!cache->AddResourceDir(pathName))
  235. return false;
  236. }
  237. }
  238. // Then add specified packages
  239. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  240. {
  241. unsigned j = 0;
  242. for (; j < resourcePrefixPaths.Size(); ++j)
  243. {
  244. String packageName = resourcePrefixPaths[j] + resourcePackages[i];
  245. if (fileSystem->FileExists(packageName))
  246. {
  247. if (cache->AddPackageFile(packageName))
  248. break;
  249. else
  250. return false;
  251. }
  252. }
  253. if (j == resourcePrefixPaths.Size())
  254. {
  255. ATOMIC_LOGERRORF(
  256. "Failed to add resource package '%s', check the documentation on how to set the 'resource prefix path'",
  257. resourcePackages[i].CString());
  258. return false;
  259. }
  260. }
  261. // Add auto load folders. Prioritize these (if exist) before the default folders
  262. for (unsigned i = 0; i < autoLoadPaths.Size(); ++i)
  263. {
  264. bool autoLoadPathExist = false;
  265. for (unsigned j = 0; j < resourcePrefixPaths.Size(); ++j)
  266. {
  267. String autoLoadPath(autoLoadPaths[i]);
  268. if (!IsAbsolutePath(autoLoadPath))
  269. autoLoadPath = resourcePrefixPaths[j] + autoLoadPath;
  270. if (fileSystem->DirExists(autoLoadPath))
  271. {
  272. autoLoadPathExist = true;
  273. // Add all the subdirs (non-recursive) as resource directory
  274. Vector<String> subdirs;
  275. fileSystem->ScanDir(subdirs, autoLoadPath, "*", SCAN_DIRS, false);
  276. for (unsigned y = 0; y < subdirs.Size(); ++y)
  277. {
  278. String dir = subdirs[y];
  279. if (dir.StartsWith("."))
  280. continue;
  281. String autoResourceDir = autoLoadPath + "/" + dir;
  282. if (!cache->AddResourceDir(autoResourceDir, 0))
  283. return false;
  284. }
  285. // Add all the found package files (non-recursive)
  286. Vector<String> paks;
  287. fileSystem->ScanDir(paks, autoLoadPath, "*.pak", SCAN_FILES, false);
  288. for (unsigned y = 0; y < paks.Size(); ++y)
  289. {
  290. String pak = paks[y];
  291. if (pak.StartsWith("."))
  292. continue;
  293. String autoPackageName = autoLoadPath + "/" + pak;
  294. if (!cache->AddPackageFile(autoPackageName, 0))
  295. return false;
  296. }
  297. }
  298. }
  299. // The following debug message is confusing when user is not aware of the autoload feature
  300. // Especially because the autoload feature is enabled by default without user intervention
  301. // The following extra conditional check below is to suppress unnecessary debug log entry under such default situation
  302. // The cleaner approach is to not enable the autoload by default, i.e. do not use 'Autoload' as default value for 'AutoloadPaths' engine parameter
  303. // However, doing so will break the existing applications that rely on this
  304. if (!autoLoadPathExist && (autoLoadPaths.Size() > 1 || autoLoadPaths[0] != "Autoload"))
  305. ATOMIC_LOGDEBUGF(
  306. "Skipped autoload path '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'",
  307. autoLoadPaths[i].CString());
  308. }
  309. // Initialize graphics & audio output
  310. if (!headless_)
  311. {
  312. Graphics* graphics = GetSubsystem<Graphics>();
  313. Renderer* renderer = GetSubsystem<Renderer>();
  314. if (HasParameter(parameters, "ExternalWindow"))
  315. graphics->SetExternalWindow(GetParameter(parameters, "ExternalWindow").GetVoidPtr());
  316. graphics->SetWindowTitle(GetParameter(parameters, "WindowTitle", "Urho3D").GetString());
  317. graphics->SetWindowIcon(cache->GetResource<Image>(GetParameter(parameters, "WindowIcon", String::EMPTY).GetString()));
  318. graphics->SetFlushGPU(GetParameter(parameters, "FlushGPU", false).GetBool());
  319. graphics->SetOrientations(GetParameter(parameters, "Orientations", "LandscapeLeft LandscapeRight").GetString());
  320. if (HasParameter(parameters, "WindowPositionX") && HasParameter(parameters, "WindowPositionY"))
  321. graphics->SetWindowPosition(GetParameter(parameters, "WindowPositionX").GetInt(),
  322. GetParameter(parameters, "WindowPositionY").GetInt());
  323. #ifdef ATOMIC_OPENGL
  324. if (HasParameter(parameters, "ForceGL2"))
  325. graphics->SetForceGL2(GetParameter(parameters, "ForceGL2").GetBool());
  326. #endif
  327. if (!graphics->SetMode(
  328. GetParameter(parameters, "WindowWidth", 0).GetInt(),
  329. GetParameter(parameters, "WindowHeight", 0).GetInt(),
  330. GetParameter(parameters, "FullScreen", true).GetBool(),
  331. GetParameter(parameters, "Borderless", false).GetBool(),
  332. GetParameter(parameters, "WindowResizable", false).GetBool(),
  333. GetParameter(parameters, "HighDPI", false).GetBool(),
  334. GetParameter(parameters, "VSync", false).GetBool(),
  335. GetParameter(parameters, "TripleBuffer", false).GetBool(),
  336. GetParameter(parameters, "MultiSample", 1).GetInt()
  337. ))
  338. return false;
  339. if (HasParameter(parameters, "DumpShaders"))
  340. graphics->BeginDumpShaders(GetParameter(parameters, "DumpShaders", String::EMPTY).GetString());
  341. if (HasParameter(parameters, "RenderPath"))
  342. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, "RenderPath").GetString()));
  343. renderer->SetDrawShadows(GetParameter(parameters, "Shadows", true).GetBool());
  344. if (renderer->GetDrawShadows() && GetParameter(parameters, "LowQualityShadows", false).GetBool())
  345. renderer->SetShadowQuality(SHADOWQUALITY_SIMPLE_16BIT);
  346. renderer->SetMaterialQuality(GetParameter(parameters, "MaterialQuality", QUALITY_HIGH).GetInt());
  347. renderer->SetTextureQuality(GetParameter(parameters, "TextureQuality", QUALITY_HIGH).GetInt());
  348. renderer->SetTextureFilterMode((TextureFilterMode)GetParameter(parameters, "TextureFilterMode", FILTER_TRILINEAR).GetInt());
  349. renderer->SetTextureAnisotropy(GetParameter(parameters, "TextureAnisotropy", 4).GetInt());
  350. if (GetParameter(parameters, "Sound", true).GetBool())
  351. {
  352. GetSubsystem<Audio>()->SetMode(
  353. GetParameter(parameters, "SoundBuffer", 100).GetInt(),
  354. GetParameter(parameters, "SoundMixRate", 44100).GetInt(),
  355. GetParameter(parameters, "SoundStereo", true).GetBool(),
  356. GetParameter(parameters, "SoundInterpolation", true).GetBool()
  357. );
  358. }
  359. }
  360. // Init FPU state of main thread
  361. InitFPU();
  362. // Initialize input
  363. if (HasParameter(parameters, "TouchEmulation"))
  364. GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, "TouchEmulation").GetBool());
  365. #ifdef ATOMIC_TESTING
  366. if (HasParameter(parameters, "TimeOut"))
  367. timeOut_ = GetParameter(parameters, "TimeOut", 0).GetInt() * 1000000LL;
  368. #endif
  369. #ifdef ATOMIC_PROFILING
  370. if (GetParameter(parameters, "EventProfiler", true).GetBool())
  371. {
  372. context_->RegisterSubsystem(new EventProfiler(context_));
  373. EventProfiler::SetActive(true);
  374. }
  375. #endif
  376. frameTimer_.Reset();
  377. ATOMIC_LOGINFO("Initialized engine");
  378. initialized_ = true;
  379. return true;
  380. }
  381. void Engine::RunFrame()
  382. {
  383. assert(initialized_);
  384. // If not headless, and the graphics subsystem no longer has a window open, assume we should exit
  385. if (!headless_ && !GetSubsystem<Graphics>()->IsInitialized())
  386. exiting_ = true;
  387. if (exiting_)
  388. return;
  389. // Note: there is a minimal performance cost to looking up subsystems (uses a hashmap); if they would be looked up several
  390. // times per frame it would be better to cache the pointers
  391. Time* time = GetSubsystem<Time>();
  392. Input* input = GetSubsystem<Input>();
  393. Audio* audio = GetSubsystem<Audio>();
  394. #ifdef ATOMIC_PROFILING
  395. if (EventProfiler::IsActive())
  396. {
  397. EventProfiler* eventProfiler = GetSubsystem<EventProfiler>();
  398. if (eventProfiler)
  399. eventProfiler->BeginFrame();
  400. }
  401. #endif
  402. time->BeginFrame(timeStep_);
  403. // If pause when minimized -mode is in use, stop updates and audio as necessary
  404. if (pauseMinimized_ && input->IsMinimized())
  405. {
  406. if (audio->IsPlaying())
  407. {
  408. audio->Stop();
  409. audioPaused_ = true;
  410. }
  411. }
  412. else
  413. {
  414. // Only unpause when it was paused by the engine
  415. if (audioPaused_)
  416. {
  417. audio->Play();
  418. audioPaused_ = false;
  419. }
  420. Update();
  421. }
  422. Render();
  423. ApplyFrameLimit();
  424. time->EndFrame();
  425. }
  426. Console* Engine::CreateConsole()
  427. {
  428. // ATOMIC BEGIN
  429. /*
  430. if (headless_ || !initialized_)
  431. return 0;
  432. // Return existing console if possible
  433. Console* console = GetSubsystem<Console>();
  434. if (!console)
  435. {
  436. console = new Console(context_);
  437. context_->RegisterSubsystem(console);
  438. }
  439. return console;
  440. */
  441. // ATOMIC END
  442. return 0;
  443. }
  444. DebugHud* Engine::CreateDebugHud()
  445. {
  446. // ATOMIC BEGIN
  447. /*
  448. if (headless_ || !initialized_)
  449. return 0;
  450. // Return existing debug HUD if possible
  451. DebugHud* debugHud = GetSubsystem<DebugHud>();
  452. if (!debugHud)
  453. {
  454. debugHud = new DebugHud(context_);
  455. context_->RegisterSubsystem(debugHud);
  456. }
  457. return debugHud;
  458. */
  459. // ATOMIC END
  460. return 0;
  461. }
  462. void Engine::SetTimeStepSmoothing(int frames)
  463. {
  464. timeStepSmoothing_ = (unsigned)Clamp(frames, 1, 20);
  465. }
  466. void Engine::SetMinFps(int fps)
  467. {
  468. minFps_ = (unsigned)Max(fps, 0);
  469. }
  470. void Engine::SetMaxFps(int fps)
  471. {
  472. maxFps_ = (unsigned)Max(fps, 0);
  473. }
  474. void Engine::SetMaxInactiveFps(int fps)
  475. {
  476. maxInactiveFps_ = (unsigned)Max(fps, 0);
  477. }
  478. void Engine::SetPauseMinimized(bool enable)
  479. {
  480. pauseMinimized_ = enable;
  481. }
  482. void Engine::SetAutoExit(bool enable)
  483. {
  484. // On mobile platforms exit is mandatory if requested by the platform itself and should not be attempted to be disabled
  485. #if defined(__ANDROID__) || defined(IOS)
  486. enable = true;
  487. #endif
  488. autoExit_ = enable;
  489. }
  490. void Engine::SetNextTimeStep(float seconds)
  491. {
  492. timeStep_ = Max(seconds, 0.0f);
  493. }
  494. void Engine::Exit()
  495. {
  496. #if defined(IOS)
  497. // On iOS it's not legal for the application to exit on its own, instead it will be minimized with the home key
  498. #else
  499. DoExit();
  500. #endif
  501. }
  502. void Engine::DumpProfiler()
  503. {
  504. Profiler* profiler = GetSubsystem<Profiler>();
  505. if (profiler)
  506. ATOMIC_LOGRAW(profiler->PrintData(true, true) + "\n");
  507. }
  508. void Engine::DumpResources(bool dumpFileName)
  509. {
  510. #ifdef ATOMIC_LOGGING
  511. ResourceCache* cache = GetSubsystem<ResourceCache>();
  512. const HashMap<StringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  513. ATOMIC_LOGRAW("\n");
  514. if (dumpFileName)
  515. {
  516. ATOMIC_LOGRAW("Used resources:\n");
  517. for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
  518. i != resourceGroups.End(); ++i)
  519. {
  520. const HashMap<StringHash, SharedPtr<Resource> >& resources = i->second_.resources_;
  521. if (dumpFileName)
  522. {
  523. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = resources.Begin();
  524. j != resources.End(); ++j)
  525. ATOMIC_LOGRAW(j->second_->GetName() + "\n");
  526. }
  527. }
  528. }
  529. else
  530. ATOMIC_LOGRAW(cache->PrintMemoryUsage());
  531. #endif
  532. }
  533. void Engine::DumpMemory()
  534. {
  535. #ifdef ATOMIC_LOGGING
  536. #if defined(_MSC_VER) && defined(_DEBUG)
  537. _CrtMemState state;
  538. _CrtMemCheckpoint(&state);
  539. _CrtMemBlockHeader* block = state.pBlockHeader;
  540. unsigned total = 0;
  541. unsigned blocks = 0;
  542. for (;;)
  543. {
  544. if (block && block->pBlockHeaderNext)
  545. block = block->pBlockHeaderNext;
  546. else
  547. break;
  548. }
  549. while (block)
  550. {
  551. if (block->nBlockUse > 0)
  552. {
  553. if (block->szFileName)
  554. ATOMIC_LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes, file " + String(block->szFileName) + " line " + String(block->nLine) + "\n");
  555. else
  556. ATOMIC_LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes\n");
  557. total += block->nDataSize;
  558. ++blocks;
  559. }
  560. block = block->pBlockHeaderPrev;
  561. }
  562. ATOMIC_LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
  563. #else
  564. ATOMIC_LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
  565. #endif
  566. #endif
  567. }
  568. void Engine::Update()
  569. {
  570. ATOMIC_PROFILE(Update);
  571. // Logic update event
  572. using namespace Update;
  573. VariantMap& eventData = GetEventDataMap();
  574. eventData[P_TIMESTEP] = timeStep_;
  575. SendEvent(E_UPDATE, eventData);
  576. // Logic post-update event
  577. SendEvent(E_POSTUPDATE, eventData);
  578. // Rendering update event
  579. SendEvent(E_RENDERUPDATE, eventData);
  580. // Post-render update event
  581. SendEvent(E_POSTRENDERUPDATE, eventData);
  582. }
  583. void Engine::Render()
  584. {
  585. if (headless_)
  586. return;
  587. ATOMIC_PROFILE(Render);
  588. // If device is lost, BeginFrame will fail and we skip rendering
  589. Graphics* graphics = GetSubsystem<Graphics>();
  590. if (!graphics->BeginFrame())
  591. return;
  592. GetSubsystem<Renderer>()->Render();
  593. GetSubsystem<UI>()->Render();
  594. graphics->EndFrame();
  595. }
  596. void Engine::ApplyFrameLimit()
  597. {
  598. if (!initialized_)
  599. return;
  600. unsigned maxFps = maxFps_;
  601. Input* input = GetSubsystem<Input>();
  602. if (input && !input->HasFocus())
  603. maxFps = Min(maxInactiveFps_, maxFps);
  604. long long elapsed = 0;
  605. #ifndef __EMSCRIPTEN__
  606. // Perform waiting loop if maximum FPS set
  607. #ifndef IOS
  608. if (maxFps)
  609. #else
  610. // If on iOS and target framerate is 60 or above, just let the animation callback handle frame timing
  611. // instead of waiting ourselves
  612. if (maxFps < 60)
  613. #endif
  614. {
  615. ATOMIC_PROFILE(ApplyFrameLimit);
  616. long long targetMax = 1000000LL / maxFps;
  617. for (;;)
  618. {
  619. elapsed = frameTimer_.GetUSec(false);
  620. if (elapsed >= targetMax)
  621. break;
  622. // Sleep if 1 ms or more off the frame limiting goal
  623. if (targetMax - elapsed >= 1000LL)
  624. {
  625. unsigned sleepTime = (unsigned)((targetMax - elapsed) / 1000LL);
  626. Time::Sleep(sleepTime);
  627. }
  628. }
  629. }
  630. #endif
  631. elapsed = frameTimer_.GetUSec(true);
  632. #ifdef ATOMIC_TESTING
  633. if (timeOut_ > 0)
  634. {
  635. timeOut_ -= elapsed;
  636. if (timeOut_ <= 0)
  637. Exit();
  638. }
  639. #endif
  640. // If FPS lower than minimum, clamp elapsed time
  641. if (minFps_)
  642. {
  643. long long targetMin = 1000000LL / minFps_;
  644. if (elapsed > targetMin)
  645. elapsed = targetMin;
  646. }
  647. // Perform timestep smoothing
  648. timeStep_ = 0.0f;
  649. lastTimeSteps_.Push(elapsed / 1000000.0f);
  650. if (lastTimeSteps_.Size() > timeStepSmoothing_)
  651. {
  652. // If the smoothing configuration was changed, ensure correct amount of samples
  653. lastTimeSteps_.Erase(0, lastTimeSteps_.Size() - timeStepSmoothing_);
  654. for (unsigned i = 0; i < lastTimeSteps_.Size(); ++i)
  655. timeStep_ += lastTimeSteps_[i];
  656. timeStep_ /= lastTimeSteps_.Size();
  657. }
  658. else
  659. timeStep_ = lastTimeSteps_.Back();
  660. }
  661. VariantMap Engine::ParseParameters(const Vector<String>& arguments)
  662. {
  663. VariantMap ret;
  664. // Pre-initialize the parameters with environment variable values when they are set
  665. if (const char* paths = getenv("ATOMIC_PREFIX_PATH"))
  666. ret["ResourcePrefixPaths"] = paths;
  667. for (unsigned i = 0; i < arguments.Size(); ++i)
  668. {
  669. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  670. {
  671. String argument = arguments[i].Substring(1).ToLower();
  672. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  673. if (argument == "headless")
  674. ret["Headless"] = true;
  675. else if (argument == "nolimit")
  676. ret["FrameLimiter"] = false;
  677. else if (argument == "flushgpu")
  678. ret["FlushGPU"] = true;
  679. else if (argument == "gl2")
  680. ret["ForceGL2"] = true;
  681. else if (argument == "landscape")
  682. ret["Orientations"] = "LandscapeLeft LandscapeRight " + ret["Orientations"].GetString();
  683. else if (argument == "portrait")
  684. ret["Orientations"] = "Portrait PortraitUpsideDown " + ret["Orientations"].GetString();
  685. else if (argument == "nosound")
  686. ret["Sound"] = false;
  687. else if (argument == "noip")
  688. ret["SoundInterpolation"] = false;
  689. else if (argument == "mono")
  690. ret["SoundStereo"] = false;
  691. else if (argument == "prepass")
  692. ret["RenderPath"] = "RenderPaths/Prepass.xml";
  693. else if (argument == "deferred")
  694. ret["RenderPath"] = "RenderPaths/Deferred.xml";
  695. else if (argument == "renderpath" && !value.Empty())
  696. {
  697. ret["RenderPath"] = value;
  698. ++i;
  699. }
  700. else if (argument == "noshadows")
  701. ret["Shadows"] = false;
  702. else if (argument == "lqshadows")
  703. ret["LowQualityShadows"] = true;
  704. else if (argument == "nothreads")
  705. ret["WorkerThreads"] = false;
  706. else if (argument == "v")
  707. ret["VSync"] = true;
  708. else if (argument == "t")
  709. ret["TripleBuffer"] = true;
  710. else if (argument == "w")
  711. ret["FullScreen"] = false;
  712. else if (argument == "borderless")
  713. ret["Borderless"] = true;
  714. else if (argument == "s")
  715. ret["WindowResizable"] = true;
  716. else if (argument == "hd")
  717. ret["HighDPI"] = true;
  718. else if (argument == "q")
  719. ret["LogQuiet"] = true;
  720. else if (argument == "log" && !value.Empty())
  721. {
  722. unsigned logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, M_MAX_UNSIGNED);
  723. if (logLevel != M_MAX_UNSIGNED)
  724. {
  725. ret["LogLevel"] = logLevel;
  726. ++i;
  727. }
  728. }
  729. else if (argument == "x" && !value.Empty())
  730. {
  731. ret["WindowWidth"] = ToInt(value);
  732. ++i;
  733. }
  734. else if (argument == "y" && !value.Empty())
  735. {
  736. ret["WindowHeight"] = ToInt(value);
  737. ++i;
  738. }
  739. else if (argument == "m" && !value.Empty())
  740. {
  741. ret["MultiSample"] = ToInt(value);
  742. ++i;
  743. }
  744. else if (argument == "b" && !value.Empty())
  745. {
  746. ret["SoundBuffer"] = ToInt(value);
  747. ++i;
  748. }
  749. else if (argument == "r" && !value.Empty())
  750. {
  751. ret["SoundMixRate"] = ToInt(value);
  752. ++i;
  753. }
  754. else if (argument == "pp" && !value.Empty())
  755. {
  756. ret["ResourcePrefixPaths"] = value;
  757. ++i;
  758. }
  759. else if (argument == "p" && !value.Empty())
  760. {
  761. ret["ResourcePaths"] = value;
  762. ++i;
  763. }
  764. else if (argument == "pf" && !value.Empty())
  765. {
  766. ret["ResourcePackages"] = value;
  767. ++i;
  768. }
  769. else if (argument == "ap" && !value.Empty())
  770. {
  771. ret["AutoloadPaths"] = value;
  772. ++i;
  773. }
  774. else if (argument == "ds" && !value.Empty())
  775. {
  776. ret["DumpShaders"] = value;
  777. ++i;
  778. }
  779. else if (argument == "mq" && !value.Empty())
  780. {
  781. ret["MaterialQuality"] = ToInt(value);
  782. ++i;
  783. }
  784. else if (argument == "tq" && !value.Empty())
  785. {
  786. ret["TextureQuality"] = ToInt(value);
  787. ++i;
  788. }
  789. else if (argument == "tf" && !value.Empty())
  790. {
  791. ret["TextureFilterMode"] = ToInt(value);
  792. ++i;
  793. }
  794. else if (argument == "af" && !value.Empty())
  795. {
  796. ret["TextureFilterMode"] = FILTER_ANISOTROPIC;
  797. ret["TextureAnisotropy"] = ToInt(value);
  798. ++i;
  799. }
  800. else if (argument == "touch")
  801. ret["TouchEmulation"] = true;
  802. #ifdef ATOMIC_TESTING
  803. else if (argument == "timeout" && !value.Empty())
  804. {
  805. ret["TimeOut"] = ToInt(value);
  806. ++i;
  807. }
  808. #endif
  809. }
  810. }
  811. return ret;
  812. }
  813. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  814. {
  815. StringHash nameHash(parameter);
  816. return parameters.Find(nameHash) != parameters.End();
  817. }
  818. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  819. {
  820. StringHash nameHash(parameter);
  821. VariantMap::ConstIterator i = parameters.Find(nameHash);
  822. return i != parameters.End() ? i->second_ : defaultValue;
  823. }
  824. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  825. {
  826. if (autoExit_)
  827. {
  828. // Do not call Exit() here, as it contains mobile platform -specific tests to not exit.
  829. // If we do receive an exit request from the system on those platforms, we must comply
  830. DoExit();
  831. }
  832. }
  833. void Engine::DoExit()
  834. {
  835. Graphics* graphics = GetSubsystem<Graphics>();
  836. if (graphics)
  837. graphics->Close();
  838. exiting_ = true;
  839. #if defined(__EMSCRIPTEN__) && defined(ATOMIC_TESTING)
  840. emscripten_force_exit(EXIT_SUCCESS); // Some how this is required to signal emrun to stop
  841. #endif
  842. }
  843. // ATOMIC BEGIN
  844. bool Engine::GetDebugBuild() const
  845. {
  846. #ifdef ATOMIC_DEBUG
  847. return true;
  848. #else
  849. return false;
  850. #endif
  851. }
  852. // ATOMIC END
  853. }