Engine.cpp 37 KB

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