Engine.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. //
  2. // Copyright (c) 2008-2013 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.h"
  24. #include "Console.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "DebugHud.h"
  28. #include "Engine.h"
  29. #include "FileSystem.h"
  30. #include "Graphics.h"
  31. #include "Input.h"
  32. #include "InputEvents.h"
  33. #include "Log.h"
  34. #include "Navigation.h"
  35. #include "Network.h"
  36. #include "PackageFile.h"
  37. #include "PhysicsWorld.h"
  38. #include "ProcessUtils.h"
  39. #include "Profiler.h"
  40. #include "Renderer.h"
  41. #include "ResourceCache.h"
  42. #include "Scene.h"
  43. #include "SceneEvents.h"
  44. #include "StringUtils.h"
  45. #include "UI.h"
  46. #include "WorkQueue.h"
  47. #include "XMLFile.h"
  48. #include "DebugNew.h"
  49. #if defined(_MSC_VER) && defined(_DEBUG)
  50. // From dbgint.h
  51. #define nNoMansLandSize 4
  52. typedef struct _CrtMemBlockHeader
  53. {
  54. struct _CrtMemBlockHeader* pBlockHeaderNext;
  55. struct _CrtMemBlockHeader* pBlockHeaderPrev;
  56. char* szFileName;
  57. int nLine;
  58. size_t nDataSize;
  59. int nBlockUse;
  60. long lRequest;
  61. unsigned char gap[nNoMansLandSize];
  62. } _CrtMemBlockHeader;
  63. #endif
  64. namespace Urho3D
  65. {
  66. extern const char* logLevelPrefixes[];
  67. OBJECTTYPESTATIC(Engine);
  68. Engine::Engine(Context* context) :
  69. Object(context),
  70. timeStep_(0.0f),
  71. minFps_(10),
  72. #if defined(ANDROID) || defined(IOS)
  73. maxFps_(60),
  74. maxInactiveFps_(10),
  75. pauseMinimized_(true),
  76. #else
  77. maxFps_(200),
  78. maxInactiveFps_(60),
  79. pauseMinimized_(false),
  80. autoExit_(true),
  81. #endif
  82. initialized_(false),
  83. exiting_(false),
  84. headless_(false),
  85. audioPaused_(false)
  86. {
  87. SubscribeToEvent(E_EXITREQUESTED, HANDLER(Engine, HandleExitRequested));
  88. }
  89. Engine::~Engine()
  90. {
  91. // Remove subsystems that use SDL in reverse order of construction
  92. context_->RemoveSubsystem<Audio>();
  93. context_->RemoveSubsystem<UI>();
  94. context_->RemoveSubsystem<Input>();
  95. context_->RemoveSubsystem<Renderer>();
  96. context_->RemoveSubsystem<Graphics>();
  97. }
  98. bool Engine::Initialize(const VariantMap& parameters)
  99. {
  100. if (initialized_)
  101. return true;
  102. // Set headless mode
  103. headless_ = GetParameter(parameters, "Headless", false).GetBool();
  104. // Register subsystems and object factories
  105. RegisterSubsystems();
  106. PROFILE(InitEngine);
  107. // Start logging
  108. Log* log = GetSubsystem<Log>();
  109. if (log)
  110. {
  111. if (HasParameter(parameters, "LogLevel"))
  112. log->SetLevel(GetParameter(parameters, "LogLevel").GetInt());
  113. log->SetQuiet(GetParameter(parameters, "LogQuiet", false).GetBool());
  114. log->Open(GetParameter(parameters, "LogName", "Urho3D.log").GetString());
  115. }
  116. // Set maximally accurate low res timer
  117. GetSubsystem<Time>()->SetTimerPeriod(1);
  118. // Configure max FPS
  119. if (GetParameter(parameters, "FrameLimiter", true) == false)
  120. SetMaxFps(0);
  121. // Set amount of worker threads according to the available physical CPU cores. Using also hyperthreaded cores results in
  122. // unpredictable extra synchronization overhead. Also reserve one core for the main thread
  123. unsigned numThreads = GetParameter(parameters, "WorkerThreads", true).GetBool() ? GetNumPhysicalCPUs() - 1 : 0;
  124. if (numThreads)
  125. {
  126. GetSubsystem<WorkQueue>()->CreateThreads(numThreads);
  127. LOGINFO(ToString("Created %u worker thread%s", numThreads, numThreads > 1 ? "s" : ""));
  128. }
  129. // Add resource paths
  130. ResourceCache* cache = GetSubsystem<ResourceCache>();
  131. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  132. String exePath = fileSystem->GetProgramDir();
  133. Vector<String> resourcePaths = GetParameter(parameters, "ResourcePaths", "CoreData;Data").GetString().Split(';');
  134. Vector<String> resourcePackages = GetParameter(parameters, "ResourcePackages").GetString().Split(';');
  135. // Prefer to add the resource paths as packages if possible
  136. for (unsigned i = 0; i < resourcePaths.Size(); ++i)
  137. {
  138. bool success = false;
  139. String packageName = exePath + resourcePaths[i] + ".pak";
  140. if (fileSystem->FileExists(packageName))
  141. {
  142. SharedPtr<PackageFile> package(new PackageFile(context_));
  143. if (package->Open(packageName))
  144. {
  145. cache->AddPackageFile(package);
  146. success = true;
  147. }
  148. }
  149. if (!success && fileSystem->DirExists(exePath + resourcePaths[i]))
  150. success = cache->AddResourceDir(exePath + resourcePaths[i]);
  151. if (!success)
  152. {
  153. LOGERROR("Failed to add resource path " + resourcePaths[i]);
  154. return false;
  155. }
  156. }
  157. // Then add specified packages
  158. for (unsigned i = 0; i < resourcePackages.Size(); ++i)
  159. {
  160. bool success = false;
  161. if (fileSystem->FileExists(exePath + resourcePackages[i]))
  162. {
  163. SharedPtr<PackageFile> package(new PackageFile(context_));
  164. if (package->Open(exePath + resourcePackages[i]))
  165. {
  166. cache->AddPackageFile(package);
  167. success = true;
  168. }
  169. }
  170. if (!success)
  171. {
  172. LOGERROR("Failed to add resource package " + resourcePackages[i]);
  173. return false;
  174. }
  175. }
  176. // Initialize graphics & audio output
  177. if (!headless_)
  178. {
  179. Graphics* graphics = GetSubsystem<Graphics>();
  180. Renderer* renderer = GetSubsystem<Renderer>();
  181. if (HasParameter(parameters, "ExternalWindow"))
  182. graphics->SetExternalWindow(GetParameter(parameters, "ExternalWindow").GetPtr());
  183. graphics->SetForceSM2(GetParameter(parameters, "ForceSM2", false).GetBool());
  184. graphics->SetWindowTitle(GetParameter(parameters, "WindowTitle", "Urho3D").GetString());
  185. if (!graphics->SetMode(
  186. GetParameter(parameters, "WindowWidth", 0).GetInt(),
  187. GetParameter(parameters, "WindowHeight", 0).GetInt(),
  188. GetParameter(parameters, "FullScreen", true).GetBool(),
  189. GetParameter(parameters, "WindowResizable", false).GetBool(),
  190. GetParameter(parameters, "VSync", false).GetBool(),
  191. GetParameter(parameters, "TripleBuffer", false).GetBool(),
  192. GetParameter(parameters, "MultiSample", 1).GetInt()
  193. ))
  194. return false;
  195. if (HasParameter(parameters, "RenderPath"))
  196. renderer->SetDefaultRenderPath(cache->GetResource<XMLFile>(GetParameter(parameters, "RenderPath").GetString()));
  197. renderer->SetDrawShadows(GetParameter(parameters, "Shadows", true).GetBool());
  198. if (renderer->GetDrawShadows() && GetParameter(parameters, "LowQualityShadows", false).GetBool())
  199. renderer->SetShadowQuality(SHADOWQUALITY_LOW_16BIT);
  200. if (GetParameter(parameters, "Sound", true).GetBool())
  201. {
  202. GetSubsystem<Audio>()->SetMode(
  203. GetParameter(parameters, "SoundBuffer", 100).GetInt(),
  204. GetParameter(parameters, "SoundMixRate", 44100).GetInt(),
  205. GetParameter(parameters, "SoundStereo", true).GetBool(),
  206. GetParameter(parameters, "SoundInterpolation", true).GetBool()
  207. );
  208. }
  209. }
  210. // Init FPU state of main thread
  211. InitFPU();
  212. frameTimer_.Reset();
  213. initialized_ = true;
  214. return true;
  215. }
  216. void Engine::RunFrame()
  217. {
  218. assert(initialized_);
  219. // If graphics subsystem exists, but does not have a window open, assume we should exit
  220. Graphics* graphics = GetSubsystem<Graphics>();
  221. if (graphics && !graphics->IsInitialized())
  222. exiting_ = true;
  223. if (exiting_)
  224. return;
  225. // Note: there is a minimal performance cost to looking up subsystems (uses a hashmap); if they would be looked up several
  226. // times per frame it would be better to cache the pointers
  227. Time* time = GetSubsystem<Time>();
  228. Input* input = GetSubsystem<Input>();
  229. Audio* audio = GetSubsystem<Audio>();
  230. time->BeginFrame(timeStep_);
  231. // If pause when minimized -mode is in use, stop updates and audio as necessary
  232. if (pauseMinimized_ && input->IsMinimized())
  233. {
  234. if (audio->IsPlaying())
  235. {
  236. audio->Stop();
  237. audioPaused_ = true;
  238. }
  239. }
  240. else
  241. {
  242. // Only unpause when it was paused by the engine
  243. if (audioPaused_)
  244. {
  245. audio->Play();
  246. audioPaused_ = false;
  247. }
  248. Update();
  249. }
  250. Render();
  251. ApplyFrameLimit();
  252. time->EndFrame();
  253. }
  254. Console* Engine::CreateConsole()
  255. {
  256. if (headless_ || !initialized_)
  257. return 0;
  258. // Return existing console if possible
  259. Console* console = GetSubsystem<Console>();
  260. if (!console)
  261. {
  262. console = new Console(context_);
  263. context_->RegisterSubsystem(console);
  264. }
  265. return console;
  266. }
  267. DebugHud* Engine::CreateDebugHud()
  268. {
  269. if (headless_ || !initialized_)
  270. return 0;
  271. // Return existing debug HUD if possible
  272. DebugHud* debugHud = GetSubsystem<DebugHud>();
  273. if (!debugHud)
  274. {
  275. debugHud = new DebugHud(context_);
  276. context_->RegisterSubsystem(debugHud);
  277. }
  278. return debugHud;
  279. }
  280. void Engine::SetMinFps(int fps)
  281. {
  282. minFps_ = Max(fps, 0);
  283. }
  284. void Engine::SetMaxFps(int fps)
  285. {
  286. maxFps_ = Max(fps, 0);
  287. }
  288. void Engine::SetMaxInactiveFps(int fps)
  289. {
  290. maxInactiveFps_ = Max(fps, 0);
  291. }
  292. void Engine::SetPauseMinimized(bool enable)
  293. {
  294. pauseMinimized_ = enable;
  295. }
  296. void Engine::SetAutoExit(bool enable)
  297. {
  298. autoExit_ = enable;
  299. }
  300. void Engine::Exit()
  301. {
  302. Graphics* graphics = GetSubsystem<Graphics>();
  303. if (graphics)
  304. graphics->Close();
  305. exiting_ = true;
  306. }
  307. void Engine::DumpProfiler()
  308. {
  309. Profiler* profiler = GetSubsystem<Profiler>();
  310. if (profiler)
  311. LOGRAW(profiler->GetData(true, true) + "\n");
  312. }
  313. void Engine::DumpResources()
  314. {
  315. #ifdef ENABLE_LOGGING
  316. ResourceCache* cache = GetSubsystem<ResourceCache>();
  317. const HashMap<ShortStringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  318. LOGRAW("\n");
  319. for (HashMap<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
  320. i != resourceGroups.End(); ++i)
  321. {
  322. unsigned num = i->second_.resources_.Size();
  323. unsigned memoryUse = i->second_.memoryUse_;
  324. if (num)
  325. {
  326. LOGRAW("Resource type " + i->second_.resources_.Begin()->second_->GetTypeName() +
  327. ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
  328. }
  329. }
  330. LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
  331. #endif
  332. }
  333. void Engine::DumpMemory()
  334. {
  335. #ifdef ENABLE_LOGGING
  336. #if defined(_MSC_VER) && defined(_DEBUG)
  337. _CrtMemState state;
  338. _CrtMemCheckpoint(&state);
  339. _CrtMemBlockHeader* block = state.pBlockHeader;
  340. unsigned total = 0;
  341. unsigned blocks = 0;
  342. for (;;)
  343. {
  344. if (block && block->pBlockHeaderNext)
  345. block = block->pBlockHeaderNext;
  346. else
  347. break;
  348. }
  349. while (block)
  350. {
  351. if (block->nBlockUse > 0)
  352. {
  353. if (block->szFileName)
  354. LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes, file " + String(block->szFileName) + " line " + String(block->nLine) + "\n");
  355. else
  356. LOGRAW("Block " + String((int)block->lRequest) + ": " + String(block->nDataSize) + " bytes\n");
  357. total += block->nDataSize;
  358. ++blocks;
  359. }
  360. block = block->pBlockHeaderPrev;
  361. }
  362. LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
  363. #else
  364. LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
  365. #endif
  366. #endif
  367. }
  368. void Engine::Update()
  369. {
  370. PROFILE(Update);
  371. // Logic update event
  372. using namespace Update;
  373. VariantMap eventData;
  374. eventData[P_TIMESTEP] = timeStep_;
  375. SendEvent(E_UPDATE, eventData);
  376. // Logic post-update event
  377. SendEvent(E_POSTUPDATE, eventData);
  378. // Rendering update event
  379. SendEvent(E_RENDERUPDATE, eventData);
  380. // Post-render update event
  381. SendEvent(E_POSTRENDERUPDATE, eventData);
  382. }
  383. void Engine::Render()
  384. {
  385. PROFILE(Render);
  386. // Do not render if device lost
  387. Graphics* graphics = GetSubsystem<Graphics>();
  388. if (!graphics || !graphics->BeginFrame())
  389. return;
  390. GetSubsystem<Renderer>()->Render();
  391. GetSubsystem<UI>()->Render();
  392. graphics->EndFrame();
  393. }
  394. void Engine::ApplyFrameLimit()
  395. {
  396. if (!initialized_)
  397. return;
  398. int maxFps = maxFps_;
  399. Input* input = GetSubsystem<Input>();
  400. if (input && !input->HasFocus())
  401. maxFps = Min(maxInactiveFps_, maxFps);
  402. long long elapsed = 0;
  403. // Perform waiting loop if maximum FPS set
  404. if (maxFps)
  405. {
  406. PROFILE(ApplyFrameLimit);
  407. long long targetMax = 1000000LL / maxFps;
  408. for (;;)
  409. {
  410. elapsed = frameTimer_.GetUSec(false);
  411. if (elapsed >= targetMax)
  412. break;
  413. // Sleep if 1 ms or more off the frame limiting goal
  414. if (targetMax - elapsed >= 1000LL)
  415. {
  416. unsigned sleepTime = (unsigned)((targetMax - elapsed) / 1000LL);
  417. Time::Sleep(sleepTime);
  418. }
  419. }
  420. }
  421. elapsed = frameTimer_.GetUSec(true);
  422. // If FPS lower than minimum, clamp elapsed time
  423. if (minFps_)
  424. {
  425. long long targetMin = 1000000LL / minFps_;
  426. if (elapsed > targetMin)
  427. elapsed = targetMin;
  428. }
  429. timeStep_ = elapsed / 1000000.0f;
  430. }
  431. VariantMap Engine::ParseParameters(const Vector<String>& arguments)
  432. {
  433. VariantMap ret;
  434. for (unsigned i = 0; i < arguments.Size(); ++i)
  435. {
  436. if (arguments[i][0] == '-' && arguments[i].Length() >= 2)
  437. {
  438. String argument = arguments[i].Substring(1).ToLower();
  439. if (argument == "headless")
  440. ret["Headless"] = true;
  441. else if (argument.Substring(0, 3) == "log")
  442. {
  443. argument = argument.Substring(3);
  444. int logLevel = GetStringListIndex(argument.CString(), logLevelPrefixes, -1);
  445. if (logLevel != -1)
  446. ret["LogLevel"] = logLevel;
  447. }
  448. else if (argument == "nolimit")
  449. ret["FrameLimiter"] = false;
  450. else if (argument == "nosound")
  451. ret["Sound"] = false;
  452. else if (argument == "noip")
  453. ret["SoundInterpolation"] = false;
  454. else if (argument == "mono")
  455. ret["SoundStereo"] = false;
  456. else if (argument == "prepass")
  457. ret["RenderPath"] = "RenderPaths/Prepass.xml";
  458. else if (argument == "deferred")
  459. ret["RenderPath"] = "RenderPaths/Deferred.xml";
  460. else if (argument == "noshadows")
  461. ret["Shadows"] = false;
  462. else if (argument == "lqshadows")
  463. ret["LowQualityShadows"] = true;
  464. else if (argument == "nothreads")
  465. ret["WorkerThreads"] = false;
  466. else if (argument == "sm2")
  467. ret["ForceSM2"] = true;
  468. else
  469. {
  470. int value;
  471. if (argument.Length() > 1)
  472. value = ToInt(argument.Substring(1));
  473. switch (tolower(argument[0]))
  474. {
  475. case 'x':
  476. ret["WindowWidth"] = value;
  477. break;
  478. case 'y':
  479. ret["WindowHeight"] = value;
  480. break;
  481. case 'm':
  482. ret["MultiSample"] = value;
  483. break;
  484. case 'b':
  485. ret["SoundBuffer"] = value;
  486. break;
  487. case 'r':
  488. ret["SoundMixRate"] = value;
  489. break;
  490. case 'v':
  491. ret["VSync"] = true;
  492. break;
  493. case 't':
  494. ret["TripleBuffer"] = true;
  495. break;
  496. case 'w':
  497. ret["FullScreen"] = false;
  498. break;
  499. case 's':
  500. ret["WindowResizable"] = true;
  501. break;
  502. case 'q':
  503. ret["LogQuiet"] = true;
  504. break;
  505. }
  506. }
  507. }
  508. }
  509. return ret;
  510. }
  511. bool Engine::HasParameter(const VariantMap& parameters, const String& parameter)
  512. {
  513. ShortStringHash nameHash(parameter);
  514. return parameters.Find(nameHash) != parameters.End();
  515. }
  516. const Variant& Engine::GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue)
  517. {
  518. ShortStringHash nameHash(parameter);
  519. VariantMap::ConstIterator i = parameters.Find(nameHash);
  520. return i != parameters.End() ? i->second_ : defaultValue;
  521. }
  522. void Engine::RegisterSubsystems()
  523. {
  524. // Register self as a subsystem
  525. context_->RegisterSubsystem(this);
  526. // Create and register the rest of the subsystems. They will register object factories for their own libraries
  527. context_->RegisterSubsystem(new Time(context_));
  528. context_->RegisterSubsystem(new WorkQueue(context_));
  529. #ifdef ENABLE_PROFILING
  530. context_->RegisterSubsystem(new Profiler(context_));
  531. #endif
  532. context_->RegisterSubsystem(new FileSystem(context_));
  533. context_->RegisterSubsystem(new ResourceCache(context_));
  534. context_->RegisterSubsystem(new Network(context_));
  535. if (!headless_)
  536. {
  537. context_->RegisterSubsystem(new Graphics(context_));
  538. context_->RegisterSubsystem(new Renderer(context_));
  539. }
  540. else
  541. {
  542. // Register Graphics library object factories also in headless mode; the objects will function without allocating
  543. // actual GPU resources
  544. RegisterGraphicsLibrary(context_);
  545. }
  546. context_->RegisterSubsystem(new Input(context_));
  547. context_->RegisterSubsystem(new UI(context_));
  548. context_->RegisterSubsystem(new Audio(context_));
  549. #ifdef ENABLE_LOGGING
  550. context_->RegisterSubsystem(new Log(context_));
  551. #endif
  552. // Scene, Physics & Navigation libraries do not have a corresponding subsystem which would register their object factories.
  553. // Register manually now
  554. RegisterSceneLibrary(context_);
  555. RegisterPhysicsLibrary(context_);
  556. RegisterNavigationLibrary(context_);
  557. // In debug mode, check that all factory created objects can be created without crashing
  558. #ifdef _DEBUG
  559. const HashMap<ShortStringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
  560. for (HashMap<ShortStringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories.Begin(); i != factories.End(); ++i)
  561. SharedPtr<Object> object = i->second_->CreateObject();
  562. #endif
  563. }
  564. void Engine::HandleExitRequested(StringHash eventType, VariantMap& eventData)
  565. {
  566. if (autoExit_)
  567. Exit();
  568. }
  569. }