Engine.cpp 38 KB

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