Engine.cpp 30 KB

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