Engine.cpp 38 KB

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