Engine.cpp 32 KB

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