Engine.cpp 30 KB

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