Engine.cpp 30 KB

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