Engine.cpp 32 KB

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