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