main_impl.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. #include "main_impl.h"
  2. #include "core/object_manager.h"
  3. #include "apps/app_selector/app_selector.h"
  4. #include "core_v2/memory_manager.h"
  5. #include "core_v2/utility.hpp"
  6. // from sophiar
  7. #include "core/local_connection.h"
  8. #include <boost/asio/io_context.hpp>
  9. #include <boost/asio/post.hpp>
  10. #include <boost/asio/steady_timer.hpp>
  11. #include <glad/gl.h>
  12. #include <GLFW/glfw3.h>
  13. #include <imgui.h>
  14. #include <imgui_impl_glfw.h>
  15. #include <imgui_impl_opengl3.h>
  16. // make glad happy
  17. #include "core/imgui_utility.hpp"
  18. using boost::asio::io_context;
  19. using boost::asio::post;
  20. using boost::asio::steady_timer;
  21. using boost::system::error_code;
  22. GLFWwindow *window = nullptr;
  23. smart_cuda_stream *default_cuda_stream = nullptr;
  24. io_context *main_ctx;
  25. BS::thread_pool *g_thread_pool;
  26. sophiar::local_connection *g_sophiar_conn = nullptr;
  27. using cleanup_list_type =
  28. std::vector<cleanup_func_type>;
  29. cleanup_list_type cleanup_list;
  30. //event_timer perf_timer; // performance timer
  31. std::unique_ptr<steady_timer> ui_timer;
  32. std::chrono::milliseconds ui_interval;
  33. std::unique_ptr<app_base> app;
  34. bool hide_app_ui = false;
  35. bool hide_debug_ui = true;
  36. bool show_demo = false;
  37. // display config
  38. bool full_screen = false;
  39. int chose_monitor = 0;
  40. struct {
  41. int x_pos, y_pos;
  42. int width, height;
  43. } win_info; // windowed mode info
  44. void init_cuda() {
  45. CUDA_API_CHECK(cuInit(0));
  46. auto cuda_dev = CUdevice();
  47. CUDA_API_CHECK(cuDeviceGet(&cuda_dev, 0)); // TODO: select device
  48. CUDA_API_CHECK(cuCtxCreate(&cuda_ctx, CU_CTX_SCHED_AUTO, cuda_dev));
  49. default_cuda_stream = new smart_cuda_stream();
  50. g_cuda_event_pool = new cuda_event_pool();
  51. std::atexit([] {
  52. // elegant cleanup
  53. cuCtxDestroy(cuda_ctx);
  54. });
  55. }
  56. void init_window() {
  57. // set GLFW error handler
  58. glfwSetErrorCallback([](int error, const char *desc) {
  59. SPDLOG_ERROR("GLFW error: code = {}, description = {}", error, desc);
  60. });
  61. // create main window
  62. auto ret = glfwInit();
  63. assert(ret == GLFW_TRUE);
  64. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  65. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
  66. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
  67. // TODO: select width and height
  68. window = glfwCreateWindow(800, 600, "An not simple platform for visual navigation", nullptr, nullptr);
  69. assert(window != nullptr);
  70. glfwMakeContextCurrent(window);
  71. glfwSwapInterval(0);
  72. // load opengl functions
  73. auto version = gladLoadGL(glfwGetProcAddress);
  74. assert(version > 0);
  75. SPDLOG_INFO("Loaded OpenGL {}.{}", GLAD_VERSION_MAJOR(version), GLAD_VERSION_MINOR(version));
  76. // enable color blending
  77. glEnable(GL_BLEND);
  78. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  79. #ifndef NDEBUG
  80. // log opengl error
  81. glEnable(GL_DEBUG_OUTPUT);
  82. glDebugMessageCallback([](GLenum source, GLenum type, GLuint id, GLenum severity,
  83. GLsizei length, const GLchar *message, const void *user_data) {
  84. if (type == GL_DEBUG_TYPE_ERROR) {
  85. SPDLOG_ERROR("OpenGL error: type = {}, severity = {}, message = {}", type, severity, message);
  86. assert(false);
  87. }
  88. }, nullptr);
  89. #endif
  90. // setup imgui context
  91. IMGUI_CHECKVERSION();
  92. ImGui::CreateContext();
  93. auto io = ImGui::GetIO();
  94. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
  95. ImGui::StyleColorsDark();
  96. ImGui_ImplGlfw_InitForOpenGL(window, true);
  97. ImGui_ImplOpenGL3_Init();
  98. // elegant cleanup
  99. std::atexit([] {
  100. ImGui_ImplOpenGL3_Shutdown();
  101. ImGui_ImplGlfw_Shutdown();
  102. ImGui::DestroyContext();
  103. glfwDestroyWindow(window);
  104. glfwTerminate();
  105. });
  106. }
  107. void ui_timer_func(error_code ec) {
  108. if (ec == boost::asio::error::operation_aborted) return;
  109. assert(ec == error_code());
  110. show_ui();
  111. ui_timer->expires_after(ui_interval);
  112. ui_timer->async_wait(ui_timer_func);
  113. }
  114. void init_all() {
  115. init_cuda();
  116. init_window();
  117. main_ctx = new io_context();
  118. main_ob = new object_manager_v2({.ctx = main_ctx});
  119. g_memory_manager = new memory_manager();
  120. constexpr auto background_thread_count = 6; // TODO: load this in config file
  121. g_thread_pool = new BS::thread_pool(background_thread_count);
  122. auto app_conf = app_selector::create_config();
  123. app_conf.asio_ctx = main_ctx;
  124. app_conf.cuda_ctx = &cuda_ctx;
  125. app_conf.app_ptr = &app;
  126. app = std::make_unique<app_selector>(app_conf);
  127. glfwSetWindowTitle(window, app->window_name());
  128. ui_interval = std::chrono::milliseconds(33); // TODO: select refresh rate
  129. ui_timer = std::make_unique<steady_timer>(*main_ctx, ui_interval);
  130. ui_timer->async_wait(ui_timer_func);
  131. }
  132. void process_keys() {
  133. auto &io = ImGui::GetIO();
  134. if (io.WantCaptureKeyboard) return;
  135. if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_H)) {
  136. // Ctrl+H
  137. hide_app_ui ^= true;
  138. }
  139. if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_D)) {
  140. // Ctrl+D
  141. hide_debug_ui ^= true;
  142. }
  143. }
  144. void update_display() {
  145. auto win = glfwGetCurrentContext();
  146. if (!full_screen) {
  147. glfwSetWindowMonitor(win, nullptr, win_info.x_pos, win_info.y_pos,
  148. win_info.width, win_info.height, GLFW_DONT_CARE);
  149. } else {
  150. assert(full_screen);
  151. int monitor_num = 0;
  152. auto monitors = glfwGetMonitors(&monitor_num);
  153. assert(chose_monitor < monitor_num);
  154. auto monitor = monitors[chose_monitor];
  155. auto mode = glfwGetVideoMode(monitor);
  156. glfwSetWindowMonitor(win, monitor, 0, 0, mode->width, mode->height, mode->refreshRate);
  157. }
  158. }
  159. void recorde_window_info() {
  160. auto win = glfwGetCurrentContext();
  161. glfwGetWindowPos(win, &win_info.x_pos, &win_info.y_pos);
  162. glfwGetWindowSize(win, &win_info.width, &win_info.height);
  163. }
  164. void show_display_config() {
  165. // display mode
  166. if (ImGui::RadioButton("Windowed", !full_screen)) {
  167. if (full_screen) {
  168. full_screen = false;
  169. update_display();
  170. }
  171. }
  172. ImGui::SameLine();
  173. if (ImGui::RadioButton("Full Screen", full_screen)) {
  174. if (!full_screen) {
  175. recorde_window_info();
  176. full_screen = true;
  177. update_display();
  178. }
  179. }
  180. if (full_screen) {
  181. int monitor_count;
  182. auto monitors = glfwGetMonitors(&monitor_count);
  183. if (chose_monitor >= monitor_count) {
  184. chose_monitor = 0;
  185. }
  186. auto monitor_name_preview = glfwGetMonitorName(monitors[chose_monitor]);
  187. if (ImGui::BeginCombo("Monitor", monitor_name_preview)) {
  188. // let user select monitors
  189. for (int k = 0; k < monitor_count; ++k) {
  190. auto is_selected = (chose_monitor == k);
  191. auto monitor_name = fmt::format("{} - {}", k, glfwGetMonitorName(monitors[k]));
  192. if (ImGui::Selectable(monitor_name.c_str(), is_selected)) {
  193. if (chose_monitor != k) {
  194. chose_monitor = k;
  195. update_display();
  196. }
  197. }
  198. if (is_selected) {
  199. ImGui::SetItemDefaultFocus();
  200. }
  201. }
  202. ImGui::EndCombo();
  203. }
  204. }
  205. }
  206. void show_memory_usage() {
  207. auto status = g_memory_manager->status();
  208. constexpr float kb_to_mb = 1.0 / 1e6f;
  209. ImGui::Text("Host: %.2f MB (%.2f MB)",
  210. status.host_allocated * kb_to_mb, status.host_cached * kb_to_mb);
  211. ImGui::Text("CUDA: %.2f MB (%.2f MB)",
  212. status.cuda_allocated * kb_to_mb, status.cuda_cached * kb_to_mb);
  213. }
  214. void show_thread_pool_usage() {
  215. ImGui::Text("Running: %ld", g_thread_pool->get_tasks_running());
  216. ImGui::Text("Queued: %ld", g_thread_pool->get_tasks_queued());
  217. }
  218. void show_debug_ui() {
  219. if (ImGui::Begin("Debug")) {
  220. ImGui::SeparatorText("Display Config");
  221. show_display_config();
  222. ImGui::SeparatorText("Memory Usage");
  223. show_memory_usage();
  224. ImGui::SeparatorText("Thread Pool Usage");
  225. show_thread_pool_usage();
  226. ImGui::SeparatorText("Miscellaneous");
  227. ImGui::Checkbox("Show Demo", &show_demo);
  228. }
  229. ImGui::End();
  230. }
  231. void show_ui() {
  232. glfwPollEvents();
  233. ImGui_ImplOpenGL3_NewFrame();
  234. ImGui_ImplGlfw_NewFrame();
  235. ImGui::NewFrame();
  236. if (glfwWindowShouldClose(window)) {
  237. ui_timer->cancel();
  238. main_ctx->stop();
  239. return;
  240. }
  241. process_keys();
  242. assert(app != nullptr);
  243. if (!hide_app_ui) {
  244. app->show_ui();
  245. }
  246. if (!hide_debug_ui) {
  247. show_debug_ui();
  248. }
  249. if (show_demo) {
  250. ImGui::ShowDemoWindow();
  251. }
  252. cv::Size frame_size;
  253. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  254. glfwGetFramebufferSize(window, &frame_size.width, &frame_size.height);
  255. glViewport(0, 0, frame_size.width, frame_size.height);
  256. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  257. app->render_background();
  258. ImGui::Render();
  259. ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
  260. glfwSwapBuffers(window);
  261. }
  262. void register_cleanup_func(cleanup_func_type func) {
  263. cleanup_list.push_back(func);
  264. }
  265. void cleanup() {
  266. app = nullptr;
  267. ui_timer = nullptr;
  268. // custom cleanup funcs
  269. for (auto func: cleanup_list) {
  270. func();
  271. }
  272. delete main_ob;
  273. delete main_ctx;
  274. delete g_memory_manager;
  275. delete g_sophiar_conn;
  276. }