Engine.cpp 33 KB

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