App.cpp 20 KB

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