App.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Core/App.h>
  6. #include <AnKi/Core/ConfigSet.h>
  7. #include <AnKi/Util/Logger.h>
  8. #include <AnKi/Util/File.h>
  9. #include <AnKi/Util/Filesystem.h>
  10. #include <AnKi/Util/System.h>
  11. #include <AnKi/Util/ThreadHive.h>
  12. #include <AnKi/Util/Tracer.h>
  13. #include <AnKi/Util/HighRezTimer.h>
  14. #include <AnKi/Core/CoreTracer.h>
  15. #include <AnKi/Core/DeveloperConsole.h>
  16. #include <AnKi/Core/StatsUi.h>
  17. #include <AnKi/Core/NativeWindow.h>
  18. #include <AnKi/Core/MaliHwCounters.h>
  19. #include <AnKi/Input/Input.h>
  20. #include <AnKi/Scene/SceneGraph.h>
  21. #include <AnKi/Renderer/RenderQueue.h>
  22. #include <AnKi/Resource/ResourceManager.h>
  23. #include <AnKi/Physics/PhysicsWorld.h>
  24. #include <AnKi/Renderer/MainRenderer.h>
  25. #include <AnKi/Script/ScriptManager.h>
  26. #include <AnKi/Resource/ResourceFilesystem.h>
  27. #include <AnKi/Resource/AsyncLoader.h>
  28. #include <AnKi/Core/GpuMemoryPools.h>
  29. #include <AnKi/Ui/UiManager.h>
  30. #include <AnKi/Ui/Canvas.h>
  31. #include <csignal>
  32. #if ANKI_OS_ANDROID
  33. # include <android_native_app_glue.h>
  34. #endif
  35. namespace anki {
  36. #if ANKI_OS_ANDROID
  37. /// The one and only android hack
  38. android_app* g_androidApp = nullptr;
  39. #endif
  40. void* App::MemStats::allocCallback(void* userData, void* ptr, PtrSize size, [[maybe_unused]] PtrSize alignment)
  41. {
  42. ANKI_ASSERT(userData);
  43. constexpr PtrSize kMaxAlignment = 64;
  44. struct alignas(kMaxAlignment) Header
  45. {
  46. PtrSize m_allocatedSize;
  47. Array<U8, kMaxAlignment - sizeof(PtrSize)> _m_padding;
  48. };
  49. static_assert(sizeof(Header) == kMaxAlignment, "See file");
  50. static_assert(alignof(Header) == kMaxAlignment, "See file");
  51. void* out = nullptr;
  52. if(ptr == nullptr)
  53. {
  54. // Need to allocate
  55. ANKI_ASSERT(size > 0);
  56. ANKI_ASSERT(alignment > 0 && alignment <= kMaxAlignment);
  57. const PtrSize newAlignment = kMaxAlignment;
  58. const PtrSize newSize = sizeof(Header) + size;
  59. // Allocate
  60. MemStats* self = static_cast<MemStats*>(userData);
  61. Header* allocation = static_cast<Header*>(
  62. self->m_originalAllocCallback(self->m_originalUserData, nullptr, newSize, newAlignment));
  63. allocation->m_allocatedSize = size;
  64. ++allocation;
  65. out = static_cast<void*>(allocation);
  66. // Update stats
  67. self->m_allocatedMem.fetchAdd(size);
  68. self->m_allocCount.fetchAdd(1);
  69. }
  70. else
  71. {
  72. // Need to free
  73. MemStats* self = static_cast<MemStats*>(userData);
  74. Header* allocation = static_cast<Header*>(ptr);
  75. --allocation;
  76. ANKI_ASSERT(allocation->m_allocatedSize > 0);
  77. // Update stats
  78. self->m_freeCount.fetchAdd(1);
  79. self->m_allocatedMem.fetchSub(allocation->m_allocatedSize);
  80. // Free
  81. self->m_originalAllocCallback(self->m_originalUserData, allocation, 0, 0);
  82. }
  83. return out;
  84. }
  85. App::App()
  86. {
  87. }
  88. App::~App()
  89. {
  90. ANKI_CORE_LOGI("Destroying application");
  91. cleanup();
  92. }
  93. void App::cleanup()
  94. {
  95. m_statsUi.reset(nullptr);
  96. m_console.reset(nullptr);
  97. deleteInstance(m_mainPool, m_scene);
  98. m_scene = nullptr;
  99. deleteInstance(m_mainPool, m_script);
  100. m_script = nullptr;
  101. deleteInstance(m_mainPool, m_renderer);
  102. m_renderer = nullptr;
  103. deleteInstance(m_mainPool, m_ui);
  104. m_ui = nullptr;
  105. deleteInstance(m_mainPool, m_gpuSceneMicroPatcher);
  106. m_gpuSceneMicroPatcher = nullptr;
  107. deleteInstance(m_mainPool, m_resources);
  108. m_resources = nullptr;
  109. deleteInstance(m_mainPool, m_resourceFs);
  110. m_resourceFs = nullptr;
  111. PhysicsWorld::freeSingleton();
  112. deleteInstance(m_mainPool, m_rebarPool);
  113. m_rebarPool = nullptr;
  114. deleteInstance(m_mainPool, m_unifiedGometryMemPool);
  115. m_unifiedGometryMemPool = nullptr;
  116. deleteInstance(m_mainPool, m_gpuSceneMemPool);
  117. m_gpuSceneMemPool = nullptr;
  118. deleteInstance(m_mainPool, m_threadHive);
  119. m_threadHive = nullptr;
  120. deleteInstance(m_mainPool, m_maliHwCounters);
  121. m_maliHwCounters = nullptr;
  122. GrManager::deleteInstance(m_gr);
  123. m_gr = nullptr;
  124. Input::deleteInstance(m_input);
  125. m_input = nullptr;
  126. NativeWindow::deleteInstance(m_window);
  127. m_window = nullptr;
  128. #if ANKI_ENABLE_TRACE
  129. deleteInstance(m_mainPool, m_coreTracer);
  130. m_coreTracer = nullptr;
  131. #endif
  132. m_settingsDir.destroy(m_mainPool);
  133. m_cacheDir.destroy(m_mainPool);
  134. }
  135. Error App::init(ConfigSet* config, AllocAlignedCallback allocCb, void* allocCbUserData)
  136. {
  137. ANKI_ASSERT(config);
  138. m_config = config;
  139. const Error err = initInternal(allocCb, allocCbUserData);
  140. if(err)
  141. {
  142. ANKI_CORE_LOGE("App initialization failed. Shutting down");
  143. cleanup();
  144. }
  145. return err;
  146. }
  147. Error App::initInternal(AllocAlignedCallback allocCb, void* allocCbUserData)
  148. {
  149. Logger::getSingleton().enableVerbosity(m_config->getCoreVerboseLog());
  150. setSignalHandlers();
  151. initMemoryCallbacks(allocCb, allocCbUserData);
  152. m_mainPool.init(allocCb, allocCbUserData, "Core");
  153. ANKI_CHECK(initDirs());
  154. // Print a message
  155. const char* buildType =
  156. #if ANKI_OPTIMIZE
  157. "optimized, "
  158. #else
  159. "NOT optimized, "
  160. #endif
  161. #if ANKI_DEBUG_SYMBOLS
  162. "dbg symbols, "
  163. #else
  164. "NO dbg symbols, "
  165. #endif
  166. #if ANKI_EXTRA_CHECKS
  167. "extra checks, "
  168. #else
  169. "NO extra checks, "
  170. #endif
  171. #if ANKI_ENABLE_TRACE
  172. "built with tracing";
  173. #else
  174. "NOT built with tracing";
  175. #endif
  176. ANKI_CORE_LOGI("Initializing application ("
  177. "version %u.%u, "
  178. "%s, "
  179. "compiler %s, "
  180. "build date %s, "
  181. "commit %s)",
  182. ANKI_VERSION_MAJOR, ANKI_VERSION_MINOR, buildType, ANKI_COMPILER_STR, __DATE__, ANKI_REVISION);
  183. // Check SIMD support
  184. #if ANKI_SIMD_SSE && ANKI_COMPILER_GCC_COMPATIBLE
  185. if(!__builtin_cpu_supports("sse4.2"))
  186. {
  187. ANKI_CORE_LOGF(
  188. "AnKi is built with sse4.2 support but your CPU doesn't support it. Try bulding without SSE support");
  189. }
  190. #endif
  191. ANKI_CORE_LOGI("Number of job threads: %u", m_config->getCoreJobThreadCount());
  192. if(m_config->getCoreBenchmarkMode() && m_config->getGrVsync())
  193. {
  194. ANKI_CORE_LOGW("Vsync is enabled and benchmark mode as well. Will turn vsync off");
  195. m_config->setGrVsync(false);
  196. }
  197. //
  198. // Core tracer
  199. //
  200. #if ANKI_ENABLE_TRACE
  201. m_coreTracer = newInstance<CoreTracer>(m_mainPool);
  202. ANKI_CHECK(m_coreTracer->init(&m_mainPool, m_settingsDir));
  203. #endif
  204. //
  205. // Window
  206. //
  207. NativeWindowInitInfo nwinit;
  208. nwinit.m_allocCallback = m_mainPool.getAllocationCallback();
  209. nwinit.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  210. nwinit.m_width = m_config->getWidth();
  211. nwinit.m_height = m_config->getHeight();
  212. nwinit.m_depthBits = 0;
  213. nwinit.m_stencilBits = 0;
  214. nwinit.m_fullscreenDesktopRez = m_config->getWindowFullscreen() > 0;
  215. nwinit.m_exclusiveFullscreen = m_config->getWindowFullscreen() == 2;
  216. nwinit.m_targetFps = m_config->getCoreTargetFps();
  217. ANKI_CHECK(NativeWindow::newInstance(nwinit, m_window));
  218. //
  219. // Input
  220. //
  221. ANKI_CHECK(Input::newInstance(m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData(),
  222. m_window, m_input));
  223. //
  224. // ThreadPool
  225. //
  226. const Bool pinThreads = !ANKI_OS_ANDROID;
  227. m_threadHive = newInstance<ThreadHive>(m_mainPool, m_config->getCoreJobThreadCount(), &m_mainPool, pinThreads);
  228. //
  229. // Graphics API
  230. //
  231. GrManagerInitInfo grInit;
  232. grInit.m_allocCallback = m_mainPool.getAllocationCallback();
  233. grInit.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  234. grInit.m_cacheDirectory = m_cacheDir.toCString();
  235. grInit.m_config = m_config;
  236. grInit.m_window = m_window;
  237. ANKI_CHECK(GrManager::newInstance(grInit, m_gr));
  238. //
  239. // Mali HW counters
  240. //
  241. if(m_gr->getDeviceCapabilities().m_gpuVendor == GpuVendor::kArm && m_config->getCoreMaliHwCounters())
  242. {
  243. m_maliHwCounters = newInstance<MaliHwCounters>(m_mainPool, &m_mainPool);
  244. }
  245. //
  246. // GPU mem
  247. //
  248. m_unifiedGometryMemPool = newInstance<UnifiedGeometryMemoryPool>(m_mainPool);
  249. m_unifiedGometryMemPool->init(&m_mainPool, m_gr, *m_config);
  250. m_gpuSceneMemPool = newInstance<GpuSceneMemoryPool>(m_mainPool);
  251. m_gpuSceneMemPool->init(&m_mainPool, m_gr, *m_config);
  252. m_rebarPool = newInstance<RebarStagingGpuMemoryPool>(m_mainPool);
  253. ANKI_CHECK(m_rebarPool->init(m_gr, *m_config));
  254. //
  255. // Physics
  256. //
  257. PhysicsWorld::allocateSingleton();
  258. ANKI_CHECK(PhysicsWorld::getSingleton().init(m_mainPool.getAllocationCallback(),
  259. m_mainPool.getAllocationCallbackUserData()));
  260. //
  261. // Resource FS
  262. //
  263. #if !ANKI_OS_ANDROID
  264. // Add the location of the executable where the shaders are supposed to be
  265. StringRaii executableFname(&m_mainPool);
  266. ANKI_CHECK(getApplicationPath(executableFname));
  267. ANKI_CORE_LOGI("Executable path is: %s", executableFname.cstr());
  268. StringRaii shadersPath(&m_mainPool);
  269. getParentFilepath(executableFname, shadersPath);
  270. shadersPath.append(":");
  271. shadersPath.append(m_config->getRsrcDataPaths());
  272. m_config->setRsrcDataPaths(shadersPath);
  273. #endif
  274. m_resourceFs = newInstance<ResourceFilesystem>(m_mainPool);
  275. ANKI_CHECK(
  276. m_resourceFs->init(*m_config, m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData()));
  277. //
  278. // Resources
  279. //
  280. ResourceManagerInitInfo rinit;
  281. rinit.m_grManager = m_gr;
  282. rinit.m_resourceFilesystem = m_resourceFs;
  283. rinit.m_unifiedGometryMemoryPool = m_unifiedGometryMemPool;
  284. rinit.m_config = m_config;
  285. rinit.m_allocCallback = m_mainPool.getAllocationCallback();
  286. rinit.m_allocCallbackData = m_mainPool.getAllocationCallbackUserData();
  287. m_resources = newInstance<ResourceManager>(m_mainPool);
  288. ANKI_CHECK(m_resources->init(rinit));
  289. //
  290. // UI
  291. //
  292. UiManagerInitInfo uiInitInfo;
  293. uiInitInfo.m_allocCallback = m_mainPool.getAllocationCallback();
  294. uiInitInfo.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  295. uiInitInfo.m_grManager = m_gr;
  296. uiInitInfo.m_input = m_input;
  297. uiInitInfo.m_resourceFilesystem = m_resourceFs;
  298. uiInitInfo.m_resourceManager = m_resources;
  299. uiInitInfo.m_rebarPool = m_rebarPool;
  300. m_ui = newInstance<UiManager>(m_mainPool);
  301. ANKI_CHECK(m_ui->init(uiInitInfo));
  302. //
  303. // GPU scene
  304. //
  305. m_gpuSceneMicroPatcher = newInstance<GpuSceneMicroPatcher>(m_mainPool);
  306. ANKI_CHECK(m_gpuSceneMicroPatcher->init(m_resources));
  307. //
  308. // Renderer
  309. //
  310. MainRendererInitInfo renderInit;
  311. renderInit.m_swapchainSize = UVec2(m_window->getWidth(), m_window->getHeight());
  312. renderInit.m_allocCallback = m_mainPool.getAllocationCallback();
  313. renderInit.m_allocCallbackUserData = m_mainPool.getAllocationCallbackUserData();
  314. renderInit.m_threadHive = m_threadHive;
  315. renderInit.m_resourceManager = m_resources;
  316. renderInit.m_grManager = m_gr;
  317. renderInit.m_rebarStagingPool = m_rebarPool;
  318. renderInit.m_uiManager = m_ui;
  319. renderInit.m_config = m_config;
  320. renderInit.m_globTimestamp = &m_globalTimestamp;
  321. renderInit.m_gpuScenePool = m_gpuSceneMemPool;
  322. renderInit.m_gpuSceneMicroPatcher = m_gpuSceneMicroPatcher;
  323. renderInit.m_unifiedGometryMemoryPool = m_unifiedGometryMemPool;
  324. m_renderer = newInstance<MainRenderer>(m_mainPool);
  325. ANKI_CHECK(m_renderer->init(renderInit));
  326. //
  327. // Script
  328. //
  329. m_script = newInstance<ScriptManager>(m_mainPool);
  330. ANKI_CHECK(m_script->init(m_mainPool.getAllocationCallback(), m_mainPool.getAllocationCallbackUserData()));
  331. //
  332. // Scene
  333. //
  334. m_scene = newInstance<SceneGraph>(m_mainPool);
  335. SceneGraphInitInfo sceneInit;
  336. sceneInit.m_allocCallback = m_mainPool.getAllocationCallback();
  337. sceneInit.m_allocCallbackData = m_mainPool.getAllocationCallbackUserData();
  338. sceneInit.m_config = m_config;
  339. sceneInit.m_globalTimestamp = &m_globalTimestamp;
  340. sceneInit.m_gpuSceneMemoryPool = m_gpuSceneMemPool;
  341. sceneInit.m_gpuSceneMicroPatcher = m_gpuSceneMicroPatcher;
  342. sceneInit.m_input = m_input;
  343. sceneInit.m_resourceManager = m_resources;
  344. sceneInit.m_scriptManager = m_script;
  345. sceneInit.m_threadHive = m_threadHive;
  346. sceneInit.m_uiManager = m_ui;
  347. sceneInit.m_unifiedGeometryMemPool = m_unifiedGometryMemPool;
  348. sceneInit.m_grManager = m_gr;
  349. ANKI_CHECK(m_scene->init(sceneInit));
  350. // Inform the script engine about some subsystems
  351. m_script->setRenderer(m_renderer);
  352. m_script->setSceneGraph(m_scene);
  353. //
  354. // Misc
  355. //
  356. ANKI_CHECK(m_ui->newInstance<StatsUi>(m_statsUi));
  357. ANKI_CHECK(m_ui->newInstance<DeveloperConsole>(m_console, m_script));
  358. ANKI_CORE_LOGI("Application initialized");
  359. return Error::kNone;
  360. }
  361. Error App::initDirs()
  362. {
  363. // Settings path
  364. #if !ANKI_OS_ANDROID
  365. StringRaii home(&m_mainPool);
  366. ANKI_CHECK(getHomeDirectory(home));
  367. m_settingsDir.sprintf(m_mainPool, "%s/.anki", &home[0]);
  368. #else
  369. m_settingsDir.sprintf(m_mainPool, "%s/.anki", g_androidApp->activity->internalDataPath);
  370. #endif
  371. if(!directoryExists(m_settingsDir.toCString()))
  372. {
  373. ANKI_CORE_LOGI("Creating settings dir \"%s\"", &m_settingsDir[0]);
  374. ANKI_CHECK(createDirectory(m_settingsDir.toCString()));
  375. }
  376. else
  377. {
  378. ANKI_CORE_LOGI("Using settings dir \"%s\"", &m_settingsDir[0]);
  379. }
  380. // Cache
  381. m_cacheDir.sprintf(m_mainPool, "%s/cache", &m_settingsDir[0]);
  382. const Bool cacheDirExists = directoryExists(m_cacheDir.toCString());
  383. if(m_config->getCoreClearCaches() && cacheDirExists)
  384. {
  385. ANKI_CORE_LOGI("Will delete the cache dir and start fresh: %s", &m_cacheDir[0]);
  386. ANKI_CHECK(removeDirectory(m_cacheDir.toCString(), m_mainPool));
  387. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  388. }
  389. else if(!cacheDirExists)
  390. {
  391. ANKI_CORE_LOGI("Will create cache dir: %s", &m_cacheDir[0]);
  392. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  393. }
  394. return Error::kNone;
  395. }
  396. Error App::mainLoop()
  397. {
  398. ANKI_CORE_LOGI("Entering main loop");
  399. Bool quit = false;
  400. Second prevUpdateTime = HighRezTimer::getCurrentTime();
  401. Second crntTime = prevUpdateTime;
  402. // Benchmark mode stuff:
  403. const Bool benchmarkMode = m_config->getCoreBenchmarkMode();
  404. Second aggregatedCpuTime = 0.0;
  405. Second aggregatedGpuTime = 0.0;
  406. constexpr U32 kBenchmarkFramesToGatherBeforeFlush = 60;
  407. U32 benchmarkFramesGathered = 0;
  408. File benchmarkCsvFile;
  409. StringRaii benchmarkCsvFileFilename(&m_mainPool);
  410. if(benchmarkMode)
  411. {
  412. benchmarkCsvFileFilename.sprintf("%s/Benchmark.csv", m_settingsDir.cstr());
  413. ANKI_CHECK(benchmarkCsvFile.open(benchmarkCsvFileFilename, FileOpenFlag::kWrite));
  414. ANKI_CHECK(benchmarkCsvFile.writeText("CPU, GPU\n"));
  415. }
  416. while(!quit)
  417. {
  418. {
  419. ANKI_TRACE_SCOPED_EVENT(Frame);
  420. const Second startTime = HighRezTimer::getCurrentTime();
  421. prevUpdateTime = crntTime;
  422. crntTime = (!benchmarkMode) ? HighRezTimer::getCurrentTime() : (prevUpdateTime + 1.0_sec / 60.0_sec);
  423. // Update
  424. ANKI_CHECK(m_input->handleEvents());
  425. // User update
  426. ANKI_CHECK(userMainLoop(quit, crntTime - prevUpdateTime));
  427. ANKI_CHECK(m_scene->update(prevUpdateTime, crntTime));
  428. RenderQueue rqueue;
  429. m_scene->doVisibilityTests(rqueue);
  430. // Inject stats UI
  431. DynamicArrayRaii<UiQueueElement> newUiElementArr(&m_mainPool);
  432. injectUiElements(newUiElementArr, rqueue);
  433. // Render
  434. TexturePtr presentableTex = m_gr->acquireNextPresentableTexture();
  435. m_renderer->setStatsEnabled(m_config->getCoreDisplayStats() > 0 || benchmarkMode
  436. #if ANKI_ENABLE_TRACE
  437. || Tracer::getSingleton().getEnabled()
  438. #endif
  439. );
  440. ANKI_CHECK(m_renderer->render(rqueue, presentableTex));
  441. // Pause and sync async loader. That will force all tasks before the pause to finish in this frame.
  442. m_resources->getAsyncLoader().pause();
  443. // If we get stats exclude the time of GR because it forces some GPU-CPU serialization. We don't want to
  444. // count that
  445. Second grTime = 0.0;
  446. if(benchmarkMode || m_config->getCoreDisplayStats() > 0) [[unlikely]]
  447. {
  448. grTime = HighRezTimer::getCurrentTime();
  449. }
  450. m_gr->swapBuffers();
  451. if(benchmarkMode || m_config->getCoreDisplayStats() > 0) [[unlikely]]
  452. {
  453. grTime = HighRezTimer::getCurrentTime() - grTime;
  454. }
  455. const PtrSize rebarMemUsed = m_rebarPool->endFrame();
  456. m_unifiedGometryMemPool->endFrame();
  457. m_gpuSceneMemPool->endFrame();
  458. // Update the trace info with some async loader stats
  459. U64 asyncTaskCount = m_resources->getAsyncLoader().getCompletedTaskCount();
  460. ANKI_TRACE_INC_COUNTER(RsrcAsyncTasks, asyncTaskCount - m_resourceCompletedAsyncTaskCount);
  461. m_resourceCompletedAsyncTaskCount = asyncTaskCount;
  462. // Now resume the loader
  463. m_resources->getAsyncLoader().resume();
  464. // Sleep
  465. const Second endTime = HighRezTimer::getCurrentTime();
  466. const Second frameTime = endTime - startTime;
  467. if(!benchmarkMode) [[likely]]
  468. {
  469. const Second timerTick = 1.0_sec / Second(m_config->getCoreTargetFps());
  470. if(frameTime < timerTick)
  471. {
  472. ANKI_TRACE_SCOPED_EVENT(TimerTickSleep);
  473. HighRezTimer::sleep(timerTick - frameTime);
  474. }
  475. }
  476. // Benchmark stats
  477. else
  478. {
  479. aggregatedCpuTime += frameTime - grTime;
  480. aggregatedGpuTime += m_renderer->getStats().m_renderingGpuTime;
  481. ++benchmarkFramesGathered;
  482. if(benchmarkFramesGathered >= kBenchmarkFramesToGatherBeforeFlush)
  483. {
  484. aggregatedCpuTime = aggregatedCpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  485. aggregatedGpuTime = aggregatedGpuTime / Second(kBenchmarkFramesToGatherBeforeFlush) * 1000.0;
  486. ANKI_CHECK(benchmarkCsvFile.writeTextf("%f,%f\n", aggregatedCpuTime, aggregatedGpuTime));
  487. benchmarkFramesGathered = 0;
  488. aggregatedCpuTime = 0.0;
  489. aggregatedGpuTime = 0.0;
  490. }
  491. }
  492. // Stats
  493. if(m_config->getCoreDisplayStats() > 0)
  494. {
  495. StatsUiInput in;
  496. in.m_cpuFrameTime = frameTime - grTime;
  497. in.m_rendererTime = m_renderer->getStats().m_renderingCpuTime;
  498. in.m_sceneUpdateTime = m_scene->getStats().m_updateTime;
  499. in.m_visibilityTestsTime = m_scene->getStats().m_visibilityTestsTime;
  500. in.m_physicsTime = m_scene->getStats().m_physicsUpdate;
  501. in.m_gpuFrameTime = m_renderer->getStats().m_renderingGpuTime;
  502. if(m_maliHwCounters)
  503. {
  504. MaliHwCountersOut out;
  505. m_maliHwCounters->sample(out);
  506. in.m_gpuActiveCycles = out.m_gpuActive;
  507. in.m_gpuReadBandwidth = out.m_readBandwidth;
  508. in.m_gpuWriteBandwidth = out.m_writeBandwidth;
  509. }
  510. in.m_cpuAllocatedMemory = m_memStats.m_allocatedMem.load();
  511. in.m_cpuAllocationCount = m_memStats.m_allocCount.load();
  512. in.m_cpuFreeCount = m_memStats.m_freeCount.load();
  513. const GrManagerStats grStats = m_gr->getStats();
  514. m_unifiedGometryMemPool->getStats(in.m_unifiedGometryExternalFragmentation,
  515. in.m_unifiedGeometryAllocated, in.m_unifiedGeometryTotal);
  516. m_gpuSceneMemPool->getStats(in.m_gpuSceneExternalFragmentation, in.m_gpuSceneAllocated,
  517. in.m_gpuSceneTotal);
  518. in.m_gpuDeviceMemoryAllocated = grStats.m_deviceMemoryAllocated;
  519. in.m_gpuDeviceMemoryInUse = grStats.m_deviceMemoryInUse;
  520. in.m_reBar = rebarMemUsed;
  521. in.m_drawableCount = rqueue.countAllRenderables();
  522. in.m_vkCommandBufferCount = grStats.m_commandBufferCount;
  523. StatsUi& statsUi = *static_cast<StatsUi*>(m_statsUi.get());
  524. const StatsUiDetail detail =
  525. (m_config->getCoreDisplayStats() == 1) ? StatsUiDetail::kFpsOnly : StatsUiDetail::kDetailed;
  526. statsUi.setStats(in, detail);
  527. }
  528. #if ANKI_ENABLE_TRACE
  529. if(m_renderer->getStats().m_renderingGpuTime >= 0.0)
  530. {
  531. ANKI_TRACE_CUSTOM_EVENT(Gpu, m_renderer->getStats().m_renderingGpuSubmitTimestamp,
  532. m_renderer->getStats().m_renderingGpuTime);
  533. }
  534. #endif
  535. ++m_globalTimestamp;
  536. if(benchmarkMode) [[unlikely]]
  537. {
  538. if(m_globalTimestamp >= m_config->getCoreBenchmarkModeFrameCount())
  539. {
  540. quit = true;
  541. }
  542. }
  543. }
  544. #if ANKI_ENABLE_TRACE
  545. static U64 frame = 1;
  546. m_coreTracer->flushFrame(frame++);
  547. #endif
  548. }
  549. if(benchmarkMode) [[unlikely]]
  550. {
  551. ANKI_CORE_LOGI("Benchmark file saved in: %s", benchmarkCsvFileFilename.cstr());
  552. }
  553. return Error::kNone;
  554. }
  555. void App::injectUiElements(DynamicArrayRaii<UiQueueElement>& newUiElementArr, RenderQueue& rqueue)
  556. {
  557. const U32 originalCount = rqueue.m_uis.getSize();
  558. if(m_config->getCoreDisplayStats() > 0 || m_consoleEnabled)
  559. {
  560. const U32 extraElements = (m_config->getCoreDisplayStats() > 0) + (m_consoleEnabled != 0);
  561. newUiElementArr.create(originalCount + extraElements);
  562. if(originalCount > 0)
  563. {
  564. memcpy(&newUiElementArr[0], &rqueue.m_uis[0], rqueue.m_uis.getSizeInBytes());
  565. }
  566. rqueue.m_uis = WeakArray<UiQueueElement>(newUiElementArr);
  567. }
  568. U32 count = originalCount;
  569. if(m_config->getCoreDisplayStats() > 0)
  570. {
  571. newUiElementArr[count].m_userData = m_statsUi.get();
  572. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  573. static_cast<StatsUi*>(userData)->build(canvas);
  574. };
  575. ++count;
  576. }
  577. if(m_consoleEnabled)
  578. {
  579. newUiElementArr[count].m_userData = m_console.get();
  580. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  581. static_cast<DeveloperConsole*>(userData)->build(canvas);
  582. };
  583. ++count;
  584. }
  585. }
  586. void App::initMemoryCallbacks(AllocAlignedCallback& allocCb, void*& allocCbUserData)
  587. {
  588. if(m_config->getCoreDisplayStats() > 1)
  589. {
  590. m_memStats.m_originalAllocCallback = allocCb;
  591. m_memStats.m_originalUserData = allocCbUserData;
  592. allocCb = MemStats::allocCallback;
  593. allocCbUserData = &m_memStats;
  594. }
  595. else
  596. {
  597. // Leave the default
  598. }
  599. }
  600. void App::setSignalHandlers()
  601. {
  602. auto handler = [](int signum) -> void {
  603. const char* name = nullptr;
  604. switch(signum)
  605. {
  606. case SIGABRT:
  607. name = "SIGABRT";
  608. break;
  609. case SIGSEGV:
  610. name = "SIGSEGV";
  611. break;
  612. #if ANKI_POSIX
  613. case SIGBUS:
  614. name = "SIGBUS";
  615. break;
  616. #endif
  617. case SIGILL:
  618. name = "SIGILL";
  619. break;
  620. case SIGFPE:
  621. name = "SIGFPE";
  622. break;
  623. }
  624. if(name)
  625. printf("Caught signal %d (%s)\n", signum, name);
  626. else
  627. printf("Caught signal %d\n", signum);
  628. U32 count = 0;
  629. printf("Backtrace:\n");
  630. HeapMemoryPool pool(allocAligned, nullptr);
  631. backtrace(pool, [&count](CString symbol) {
  632. printf("%.2u: %s\n", count++, symbol.cstr());
  633. });
  634. ANKI_DEBUG_BREAK();
  635. };
  636. signal(SIGSEGV, handler);
  637. signal(SIGILL, handler);
  638. signal(SIGFPE, handler);
  639. #if ANKI_POSIX
  640. signal(SIGBUS, handler);
  641. #endif
  642. // Ignore for now: signal(SIGABRT, handler);
  643. }
  644. } // end namespace anki