App.cpp 18 KB

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