Engine.cpp 33 KB

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