Engine.cpp 29 KB

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