Engine.cpp 31 KB

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