Engine.cpp 30 KB

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