Engine.cpp 30 KB

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