App.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. // Copyright (C) 2009-2021, 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/NativeWindow.h>
  17. #include <AnKi/Input/Input.h>
  18. #include <AnKi/Scene/SceneGraph.h>
  19. #include <AnKi/Renderer/RenderQueue.h>
  20. #include <AnKi/Resource/ResourceManager.h>
  21. #include <AnKi/Physics/PhysicsWorld.h>
  22. #include <AnKi/Renderer/MainRenderer.h>
  23. #include <AnKi/Script/ScriptManager.h>
  24. #include <AnKi/Resource/ResourceFilesystem.h>
  25. #include <AnKi/Resource/AsyncLoader.h>
  26. #include <AnKi/Core/StagingGpuMemoryManager.h>
  27. #include <AnKi/Ui/UiManager.h>
  28. #include <AnKi/Ui/Canvas.h>
  29. #include <csignal>
  30. #if ANKI_OS_ANDROID
  31. # include <android_native_app_glue.h>
  32. #endif
  33. namespace anki
  34. {
  35. #if ANKI_OS_ANDROID
  36. /// The one and only android hack
  37. android_app* g_androidApp = nullptr;
  38. #endif
  39. class App::StatsUi
  40. {
  41. public:
  42. template<typename T>
  43. class BufferedValue
  44. {
  45. public:
  46. void set(T x)
  47. {
  48. m_total += x;
  49. ++m_count;
  50. }
  51. F64 get(Bool flush)
  52. {
  53. if(flush)
  54. {
  55. m_avg = F64(m_total) / m_count;
  56. m_count = 0;
  57. m_total = 0.0;
  58. }
  59. return m_avg;
  60. }
  61. private:
  62. T m_total = T(0);
  63. F64 m_avg = 0.0;
  64. U32 m_count = 0;
  65. };
  66. GenericMemoryPoolAllocator<U8> m_alloc;
  67. BufferedValue<Second> m_frameTime;
  68. BufferedValue<Second> m_renderTime;
  69. BufferedValue<Second> m_sceneUpdateTime;
  70. BufferedValue<Second> m_visTestsTime;
  71. BufferedValue<Second> m_physicsTime;
  72. BufferedValue<Second> m_gpuTime;
  73. PtrSize m_allocatedCpuMem = 0;
  74. U64 m_allocCount = 0;
  75. U64 m_freeCount = 0;
  76. U64 m_vkCpuMem = 0;
  77. U64 m_vkGpuMem = 0;
  78. U32 m_vkCmdbCount = 0;
  79. PtrSize m_drawableCount = 0;
  80. static const U32 BUFFERED_FRAMES = 16;
  81. U32 m_bufferedFrames = 0;
  82. StatsUi(const GenericMemoryPoolAllocator<U8>& alloc)
  83. : m_alloc(alloc)
  84. {
  85. }
  86. void build(CanvasPtr canvas)
  87. {
  88. // Misc
  89. ++m_bufferedFrames;
  90. Bool flush = false;
  91. if(m_bufferedFrames == BUFFERED_FRAMES)
  92. {
  93. flush = true;
  94. m_bufferedFrames = 0;
  95. }
  96. // Start drawing the UI
  97. canvas->pushFont(canvas->getDefaultFont(), 16);
  98. const Vec4 oldWindowColor = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];
  99. ImGui::GetStyle().Colors[ImGuiCol_WindowBg].w = 0.3f;
  100. if(ImGui::Begin("Stats", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize))
  101. {
  102. ImGui::SetWindowPos(Vec2(5.0f, 5.0f));
  103. ImGui::SetWindowSize(Vec2(230.0f, 450.0f));
  104. ImGui::Text("CPU Time:");
  105. labelTime(m_frameTime.get(flush), "Total frame");
  106. labelTime(m_renderTime.get(flush), "Renderer");
  107. labelTime(m_sceneUpdateTime.get(flush), "Scene update");
  108. labelTime(m_visTestsTime.get(flush), "Visibility");
  109. labelTime(m_physicsTime.get(flush), "Physics");
  110. ImGui::Text("----");
  111. ImGui::Text("GPU Time:");
  112. labelTime(m_gpuTime.get(flush), "Total frame");
  113. ImGui::Text("----");
  114. ImGui::Text("Memory:");
  115. labelBytes(m_allocatedCpuMem, "Total CPU");
  116. labelUint(m_allocCount, "Total allocations");
  117. labelUint(m_freeCount, "Total frees");
  118. labelBytes(m_vkCpuMem, "Vulkan CPU");
  119. labelBytes(m_vkGpuMem, "Vulkan GPU");
  120. ImGui::Text("----");
  121. ImGui::Text("Vulkan:");
  122. labelUint(m_vkCmdbCount, "Cmd buffers");
  123. ImGui::Text("----");
  124. ImGui::Text("Other:");
  125. labelUint(m_drawableCount, "Drawbles");
  126. }
  127. ImGui::End();
  128. ImGui::GetStyle().Colors[ImGuiCol_WindowBg] = oldWindowColor;
  129. canvas->popFont();
  130. }
  131. void labelTime(Second val, CString name)
  132. {
  133. ImGui::Text("%s: %fms", name.cstr(), val * 1000.0);
  134. }
  135. void labelBytes(PtrSize val, CString name)
  136. {
  137. PtrSize gb, mb, kb, b;
  138. gb = val / 1_GB;
  139. val -= gb * 1_GB;
  140. mb = val / 1_MB;
  141. val -= mb * 1_MB;
  142. kb = val / 1_KB;
  143. val -= kb * 1_KB;
  144. b = val;
  145. StringAuto timestamp(m_alloc);
  146. if(gb)
  147. {
  148. timestamp.sprintf("%s: %4u,%04u,%04u,%04u", name.cstr(), gb, mb, kb, b);
  149. }
  150. else if(mb)
  151. {
  152. timestamp.sprintf("%s: %4u,%04u,%04u", name.cstr(), mb, kb, b);
  153. }
  154. else if(kb)
  155. {
  156. timestamp.sprintf("%s: %4u,%04u", name.cstr(), kb, b);
  157. }
  158. else
  159. {
  160. timestamp.sprintf("%s: %4u", name.cstr(), b);
  161. }
  162. ImGui::TextUnformatted(timestamp.cstr());
  163. }
  164. void labelUint(U64 val, CString name)
  165. {
  166. ImGui::Text("%s: %lu", name.cstr(), val);
  167. }
  168. };
  169. void* App::MemStats::allocCallback(void* userData, void* ptr, PtrSize size, PtrSize alignment)
  170. {
  171. ANKI_ASSERT(userData);
  172. static const PtrSize MAX_ALIGNMENT = 64;
  173. struct alignas(MAX_ALIGNMENT) Header
  174. {
  175. PtrSize m_allocatedSize;
  176. Array<U8, MAX_ALIGNMENT - sizeof(PtrSize)> _m_padding;
  177. };
  178. static_assert(sizeof(Header) == MAX_ALIGNMENT, "See file");
  179. static_assert(alignof(Header) == MAX_ALIGNMENT, "See file");
  180. void* out = nullptr;
  181. if(ptr == nullptr)
  182. {
  183. // Need to allocate
  184. ANKI_ASSERT(size > 0);
  185. ANKI_ASSERT(alignment > 0 && alignment <= MAX_ALIGNMENT);
  186. const PtrSize newAlignment = MAX_ALIGNMENT;
  187. const PtrSize newSize = sizeof(Header) + size;
  188. // Allocate
  189. MemStats* self = static_cast<MemStats*>(userData);
  190. Header* allocation = static_cast<Header*>(
  191. self->m_originalAllocCallback(self->m_originalUserData, nullptr, newSize, newAlignment));
  192. allocation->m_allocatedSize = size;
  193. ++allocation;
  194. out = static_cast<void*>(allocation);
  195. // Update stats
  196. self->m_allocatedMem.fetchAdd(size);
  197. self->m_allocCount.fetchAdd(1);
  198. }
  199. else
  200. {
  201. // Need to free
  202. MemStats* self = static_cast<MemStats*>(userData);
  203. Header* allocation = static_cast<Header*>(ptr);
  204. --allocation;
  205. ANKI_ASSERT(allocation->m_allocatedSize > 0);
  206. // Update stats
  207. self->m_freeCount.fetchAdd(1);
  208. self->m_allocatedMem.fetchSub(allocation->m_allocatedSize);
  209. // Free
  210. self->m_originalAllocCallback(self->m_originalUserData, allocation, 0, 0);
  211. }
  212. return out;
  213. }
  214. App::App()
  215. {
  216. }
  217. App::~App()
  218. {
  219. cleanup();
  220. }
  221. void App::cleanup()
  222. {
  223. m_heapAlloc.deleteInstance(m_statsUi);
  224. m_console.reset(nullptr);
  225. m_heapAlloc.deleteInstance(m_scene);
  226. m_scene = nullptr;
  227. m_heapAlloc.deleteInstance(m_script);
  228. m_script = nullptr;
  229. m_heapAlloc.deleteInstance(m_renderer);
  230. m_renderer = nullptr;
  231. m_heapAlloc.deleteInstance(m_ui);
  232. m_ui = nullptr;
  233. m_heapAlloc.deleteInstance(m_resources);
  234. m_resources = nullptr;
  235. m_heapAlloc.deleteInstance(m_resourceFs);
  236. m_resourceFs = nullptr;
  237. m_heapAlloc.deleteInstance(m_physics);
  238. m_physics = nullptr;
  239. m_heapAlloc.deleteInstance(m_stagingMem);
  240. m_stagingMem = nullptr;
  241. m_heapAlloc.deleteInstance(m_threadHive);
  242. m_threadHive = nullptr;
  243. GrManager::deleteInstance(m_gr);
  244. m_gr = nullptr;
  245. m_heapAlloc.deleteInstance(m_input);
  246. m_input = nullptr;
  247. m_heapAlloc.deleteInstance(m_window);
  248. m_window = nullptr;
  249. #if ANKI_ENABLE_TRACE
  250. m_heapAlloc.deleteInstance(m_coreTracer);
  251. m_coreTracer = nullptr;
  252. #endif
  253. m_settingsDir.destroy(m_heapAlloc);
  254. m_cacheDir.destroy(m_heapAlloc);
  255. }
  256. Error App::init(const ConfigSet& config, AllocAlignedCallback allocCb, void* allocCbUserData)
  257. {
  258. const Error err = initInternal(config, allocCb, allocCbUserData);
  259. if(err)
  260. {
  261. ANKI_CORE_LOGE("App initialization failed. Shutting down");
  262. cleanup();
  263. }
  264. return err;
  265. }
  266. Error App::initInternal(const ConfigSet& config_, AllocAlignedCallback allocCb, void* allocCbUserData)
  267. {
  268. setSignalHandlers();
  269. Thread::setNameOfCurrentThread("anki_main");
  270. ConfigSet config = config_;
  271. m_displayStats = config.getNumberU32("core_displayStats");
  272. initMemoryCallbacks(allocCb, allocCbUserData);
  273. m_heapAlloc = HeapAllocator<U8>(m_allocCb, m_allocCbData);
  274. ANKI_CHECK(initDirs(config));
  275. // Print a message
  276. const char* buildType =
  277. #if ANKI_OPTIMIZE
  278. "optimized, "
  279. #else
  280. "NOT optimized, "
  281. #endif
  282. #if ANKI_DEBUG_SYMBOLS
  283. "dbg symbols, "
  284. #else
  285. "NO dbg symbols, "
  286. #endif
  287. #if ANKI_EXTRA_CHECKS
  288. "extra checks, "
  289. #else
  290. "NO extra checks, "
  291. #endif
  292. #if ANKI_ENABLE_TRACE
  293. "built with tracing";
  294. #else
  295. "NOT built with tracing";
  296. #endif
  297. ANKI_CORE_LOGI("Initializing application ("
  298. "version %u.%u, "
  299. "%s, "
  300. "compiler %s, "
  301. "build date %s, "
  302. "commit %s)",
  303. ANKI_VERSION_MAJOR, ANKI_VERSION_MINOR, buildType, ANKI_COMPILER_STR, __DATE__, ANKI_REVISION);
  304. m_timerTick = 1.0 / F32(config.getNumberU32("core_targetFps")); // in sec. 1.0 / period
  305. // Check SIMD support
  306. #if ANKI_SIMD_SSE && ANKI_COMPILER_GCC_COMPATIBLE
  307. if(!__builtin_cpu_supports("sse4.2"))
  308. {
  309. ANKI_CORE_LOGF(
  310. "AnKi is built with sse4.2 support but your CPU doesn't support it. Try bulding without SSE support");
  311. }
  312. #endif
  313. ANKI_CORE_LOGI("Number of main threads: %u", config.getNumberU32("core_mainThreadCount"));
  314. //
  315. // Core tracer
  316. //
  317. #if ANKI_ENABLE_TRACE
  318. m_coreTracer = m_heapAlloc.newInstance<CoreTracer>();
  319. ANKI_CHECK(m_coreTracer->init(m_heapAlloc, m_settingsDir));
  320. #endif
  321. //
  322. // Window
  323. //
  324. NativeWindowInitInfo nwinit;
  325. nwinit.m_width = config.getNumberU32("width");
  326. nwinit.m_height = config.getNumberU32("height");
  327. nwinit.m_depthBits = 0;
  328. nwinit.m_stencilBits = 0;
  329. nwinit.m_fullscreenDesktopRez = config.getBool("window_fullscreen");
  330. m_window = m_heapAlloc.newInstance<NativeWindow>();
  331. ANKI_CHECK(m_window->init(nwinit, m_heapAlloc));
  332. //
  333. // Input
  334. //
  335. m_input = m_heapAlloc.newInstance<Input>();
  336. ANKI_CHECK(m_input->init(m_window));
  337. //
  338. // ThreadPool
  339. //
  340. m_threadHive = m_heapAlloc.newInstance<ThreadHive>(config.getNumberU32("core_mainThreadCount"), m_heapAlloc, true);
  341. //
  342. // Graphics API
  343. //
  344. GrManagerInitInfo grInit;
  345. grInit.m_allocCallback = m_allocCb;
  346. grInit.m_allocCallbackUserData = m_allocCbData;
  347. grInit.m_cacheDirectory = m_cacheDir.toCString();
  348. grInit.m_config = &config;
  349. grInit.m_window = m_window;
  350. ANKI_CHECK(GrManager::newInstance(grInit, m_gr));
  351. //
  352. // Staging mem
  353. //
  354. m_stagingMem = m_heapAlloc.newInstance<StagingGpuMemoryManager>();
  355. ANKI_CHECK(m_stagingMem->init(m_gr, config));
  356. //
  357. // Physics
  358. //
  359. m_physics = m_heapAlloc.newInstance<PhysicsWorld>();
  360. ANKI_CHECK(m_physics->init(m_allocCb, m_allocCbData));
  361. //
  362. // Resource FS
  363. //
  364. m_resourceFs = m_heapAlloc.newInstance<ResourceFilesystem>(m_heapAlloc);
  365. ANKI_CHECK(m_resourceFs->init(config, m_cacheDir.toCString()));
  366. //
  367. // Resources
  368. //
  369. ResourceManagerInitInfo rinit;
  370. rinit.m_gr = m_gr;
  371. rinit.m_physics = m_physics;
  372. rinit.m_resourceFs = m_resourceFs;
  373. rinit.m_config = &config;
  374. rinit.m_cacheDir = m_cacheDir.toCString();
  375. rinit.m_allocCallback = m_allocCb;
  376. rinit.m_allocCallbackData = m_allocCbData;
  377. m_resources = m_heapAlloc.newInstance<ResourceManager>();
  378. ANKI_CHECK(m_resources->init(rinit));
  379. //
  380. // UI
  381. //
  382. m_ui = m_heapAlloc.newInstance<UiManager>();
  383. ANKI_CHECK(m_ui->init(m_allocCb, m_allocCbData, m_resources, m_gr, m_stagingMem, m_input));
  384. //
  385. // Renderer
  386. //
  387. if(nwinit.m_fullscreenDesktopRez)
  388. {
  389. config.set("width", m_window->getWidth());
  390. config.set("height", m_window->getHeight());
  391. }
  392. m_renderer = m_heapAlloc.newInstance<MainRenderer>();
  393. ANKI_CHECK(m_renderer->init(m_threadHive, m_resources, m_gr, m_stagingMem, m_ui, m_allocCb, m_allocCbData, config,
  394. &m_globalTimestamp));
  395. //
  396. // Script
  397. //
  398. m_script = m_heapAlloc.newInstance<ScriptManager>();
  399. ANKI_CHECK(m_script->init(m_allocCb, m_allocCbData));
  400. //
  401. // Scene
  402. //
  403. m_scene = m_heapAlloc.newInstance<SceneGraph>();
  404. ANKI_CHECK(m_scene->init(m_allocCb, m_allocCbData, m_threadHive, m_resources, m_input, m_script, m_ui,
  405. &m_globalTimestamp, config));
  406. // Inform the script engine about some subsystems
  407. m_script->setRenderer(m_renderer);
  408. m_script->setSceneGraph(m_scene);
  409. //
  410. // Misc
  411. //
  412. m_statsUi = m_heapAlloc.newInstance<StatsUi>(m_heapAlloc);
  413. ANKI_CHECK(m_ui->newInstance<DeveloperConsole>(m_console, m_allocCb, m_allocCbData, m_script));
  414. ANKI_CORE_LOGI("Application initialized");
  415. return Error::NONE;
  416. }
  417. Error App::initDirs(const ConfigSet& cfg)
  418. {
  419. // Settings path
  420. #if !ANKI_OS_ANDROID
  421. StringAuto home(m_heapAlloc);
  422. ANKI_CHECK(getHomeDirectory(home));
  423. m_settingsDir.sprintf(m_heapAlloc, "%s/.anki", &home[0]);
  424. #else
  425. m_settingsDir.sprintf(m_heapAlloc, "%s/.anki", g_androidApp->activity->internalDataPath);
  426. #endif
  427. if(!directoryExists(m_settingsDir.toCString()))
  428. {
  429. ANKI_CORE_LOGI("Creating settings dir \"%s\"", &m_settingsDir[0]);
  430. ANKI_CHECK(createDirectory(m_settingsDir.toCString()));
  431. }
  432. else
  433. {
  434. ANKI_CORE_LOGI("Using settings dir \"%s\"", &m_settingsDir[0]);
  435. }
  436. // Cache
  437. m_cacheDir.sprintf(m_heapAlloc, "%s/cache", &m_settingsDir[0]);
  438. const Bool cacheDirExists = directoryExists(m_cacheDir.toCString());
  439. if(cfg.getBool("core_clearCaches") && cacheDirExists)
  440. {
  441. ANKI_CORE_LOGI("Will delete the cache dir and start fresh: %s", &m_cacheDir[0]);
  442. ANKI_CHECK(removeDirectory(m_cacheDir.toCString(), m_heapAlloc));
  443. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  444. }
  445. else if(!cacheDirExists)
  446. {
  447. ANKI_CORE_LOGI("Will create cache dir: %s", &m_cacheDir[0]);
  448. ANKI_CHECK(createDirectory(m_cacheDir.toCString()));
  449. }
  450. return Error::NONE;
  451. }
  452. Error App::mainLoop()
  453. {
  454. ANKI_CORE_LOGI("Entering main loop");
  455. Bool quit = false;
  456. Second prevUpdateTime = HighRezTimer::getCurrentTime();
  457. Second crntTime = prevUpdateTime;
  458. while(!quit)
  459. {
  460. {
  461. ANKI_TRACE_SCOPED_EVENT(FRAME);
  462. const Second startTime = HighRezTimer::getCurrentTime();
  463. prevUpdateTime = crntTime;
  464. crntTime = HighRezTimer::getCurrentTime();
  465. // Update
  466. ANKI_CHECK(m_input->handleEvents());
  467. // User update
  468. ANKI_CHECK(userMainLoop(quit, crntTime - prevUpdateTime));
  469. ANKI_CHECK(m_scene->update(prevUpdateTime, crntTime));
  470. RenderQueue rqueue;
  471. m_scene->doVisibilityTests(rqueue);
  472. // Inject stats UI
  473. DynamicArrayAuto<UiQueueElement> newUiElementArr(m_heapAlloc);
  474. injectUiElements(newUiElementArr, rqueue);
  475. // Render
  476. TexturePtr presentableTex = m_gr->acquireNextPresentableTexture();
  477. m_renderer->setStatsEnabled(m_displayStats
  478. #if ANKI_ENABLE_TRACE
  479. || TracerSingleton::get().getEnabled()
  480. #endif
  481. );
  482. ANKI_CHECK(m_renderer->render(rqueue, presentableTex));
  483. // Pause and sync async loader. That will force all tasks before the pause to finish in this frame.
  484. m_resources->getAsyncLoader().pause();
  485. m_gr->swapBuffers();
  486. m_stagingMem->endFrame();
  487. // Update the trace info with some async loader stats
  488. U64 asyncTaskCount = m_resources->getAsyncLoader().getCompletedTaskCount();
  489. ANKI_TRACE_INC_COUNTER(RESOURCE_ASYNC_TASKS, asyncTaskCount - m_resourceCompletedAsyncTaskCount);
  490. m_resourceCompletedAsyncTaskCount = asyncTaskCount;
  491. // Now resume the loader
  492. m_resources->getAsyncLoader().resume();
  493. // Sleep
  494. const Second endTime = HighRezTimer::getCurrentTime();
  495. const Second frameTime = endTime - startTime;
  496. if(frameTime < m_timerTick)
  497. {
  498. ANKI_TRACE_SCOPED_EVENT(TIMER_TICK_SLEEP);
  499. HighRezTimer::sleep(m_timerTick - frameTime);
  500. }
  501. // Stats
  502. if(m_displayStats)
  503. {
  504. m_statsUi->m_frameTime.set(frameTime);
  505. m_statsUi->m_renderTime.set(m_renderer->getStats().m_renderingCpuTime);
  506. m_statsUi->m_sceneUpdateTime.set(m_scene->getStats().m_updateTime);
  507. m_statsUi->m_visTestsTime.set(m_scene->getStats().m_visibilityTestsTime);
  508. m_statsUi->m_physicsTime.set(m_scene->getStats().m_physicsUpdate);
  509. m_statsUi->m_gpuTime.set(m_renderer->getStats().m_renderingGpuTime);
  510. m_statsUi->m_allocatedCpuMem = m_memStats.m_allocatedMem.load();
  511. m_statsUi->m_allocCount = m_memStats.m_allocCount.load();
  512. m_statsUi->m_freeCount = m_memStats.m_freeCount.load();
  513. GrManagerStats grStats = m_gr->getStats();
  514. m_statsUi->m_vkCpuMem = grStats.m_cpuMemory;
  515. m_statsUi->m_vkGpuMem = grStats.m_gpuMemory;
  516. m_statsUi->m_vkCmdbCount = grStats.m_commandBufferCount;
  517. m_statsUi->m_drawableCount = rqueue.countAllRenderables();
  518. }
  519. #if ANKI_ENABLE_TRACE
  520. if(m_renderer->getStats().m_renderingGpuTime >= 0.0)
  521. {
  522. ANKI_TRACE_CUSTOM_EVENT(GPU_TIME, m_renderer->getStats().m_renderingGpuSubmitTimestamp,
  523. m_renderer->getStats().m_renderingGpuTime);
  524. }
  525. #endif
  526. ++m_globalTimestamp;
  527. }
  528. #if ANKI_ENABLE_TRACE
  529. static U64 frame = 1;
  530. m_coreTracer->flushFrame(frame++);
  531. #endif
  532. }
  533. return Error::NONE;
  534. }
  535. void App::injectUiElements(DynamicArrayAuto<UiQueueElement>& newUiElementArr, RenderQueue& rqueue)
  536. {
  537. const U32 originalCount = rqueue.m_uis.getSize();
  538. if(m_displayStats || m_consoleEnabled)
  539. {
  540. const U32 extraElements = (m_displayStats != 0) + (m_consoleEnabled != 0);
  541. newUiElementArr.create(originalCount + extraElements);
  542. if(originalCount > 0)
  543. {
  544. memcpy(&newUiElementArr[0], &rqueue.m_uis[0], rqueue.m_uis.getSizeInBytes());
  545. }
  546. rqueue.m_uis = WeakArray<UiQueueElement>(newUiElementArr);
  547. }
  548. U32 count = originalCount;
  549. if(m_displayStats)
  550. {
  551. newUiElementArr[count].m_userData = m_statsUi;
  552. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  553. static_cast<StatsUi*>(userData)->build(canvas);
  554. };
  555. ++count;
  556. }
  557. if(m_consoleEnabled)
  558. {
  559. newUiElementArr[count].m_userData = m_console.get();
  560. newUiElementArr[count].m_drawCallback = [](CanvasPtr& canvas, void* userData) -> void {
  561. static_cast<DeveloperConsole*>(userData)->build(canvas);
  562. };
  563. ++count;
  564. }
  565. }
  566. void App::initMemoryCallbacks(AllocAlignedCallback allocCb, void* allocCbUserData)
  567. {
  568. if(m_displayStats)
  569. {
  570. m_memStats.m_originalAllocCallback = allocCb;
  571. m_memStats.m_originalUserData = allocCbUserData;
  572. m_allocCb = MemStats::allocCallback;
  573. m_allocCbData = &m_memStats;
  574. }
  575. else
  576. {
  577. m_allocCb = allocCb;
  578. m_allocCbData = allocCbUserData;
  579. }
  580. }
  581. void App::setSignalHandlers()
  582. {
  583. auto handler = [](int signum) -> void {
  584. const char* name = nullptr;
  585. switch(signum)
  586. {
  587. case SIGABRT:
  588. name = "SIGABRT";
  589. break;
  590. case SIGSEGV:
  591. name = "SIGSEGV";
  592. break;
  593. #if ANKI_POSIX
  594. case SIGBUS:
  595. name = "SIGBUS";
  596. break;
  597. #endif
  598. case SIGILL:
  599. name = "SIGILL";
  600. break;
  601. case SIGFPE:
  602. name = "SIGFPE";
  603. break;
  604. }
  605. if(name)
  606. printf("Caught signal %d (%s)\n", signum, name);
  607. else
  608. printf("Caught signal %d\n", signum);
  609. U32 count = 0;
  610. printf("Backtrace:\n");
  611. backtrace(HeapAllocator<U8>(allocAligned, nullptr),
  612. [&count](CString symbol) { printf("%.2u: %s\n", count++, symbol.cstr()); });
  613. ANKI_DEBUG_BREAK();
  614. };
  615. signal(SIGSEGV, handler);
  616. signal(SIGILL, handler);
  617. signal(SIGFPE, handler);
  618. #if ANKI_POSIX
  619. signal(SIGBUS, handler);
  620. #endif
  621. // Ignore for now: signal(SIGABRT, handler);
  622. }
  623. } // end namespace anki