main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // Dear ImGui: standalone example application for GLFW + WebGPU
  2. // - Emscripten is supported for publishing on web. See https://emscripten.org.
  3. // - Dawn is used as a WebGPU implementation on desktop.
  4. // Learn about Dear ImGui:
  5. // - FAQ https://dearimgui.com/faq
  6. // - Getting Started https://dearimgui.com/getting-started
  7. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  8. // - Introduction, links and more at the top of imgui.cpp
  9. #include "imgui.h"
  10. #include "imgui_impl_glfw.h"
  11. #include "imgui_impl_wgpu.h"
  12. #include <stdio.h>
  13. #include <GLFW/glfw3.h>
  14. // This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details.
  15. #ifdef __EMSCRIPTEN__
  16. #include <emscripten.h>
  17. #include <emscripten/html5.h>
  18. #include <emscripten/html5_webgpu.h>
  19. #include "../libs/emscripten/emscripten_mainloop_stub.h"
  20. #else
  21. #include <webgpu/webgpu_glfw.h>
  22. #endif
  23. #include <webgpu/webgpu.h>
  24. #include <webgpu/webgpu_cpp.h>
  25. // Data
  26. static WGPUInstance wgpu_instance = nullptr;
  27. static WGPUDevice wgpu_device = nullptr;
  28. static WGPUSurface wgpu_surface = nullptr;
  29. static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm;
  30. static WGPUSwapChain wgpu_swap_chain = nullptr;
  31. static int wgpu_surface_width = 1280;
  32. static int wgpu_surface_height = 800;
  33. // Forward declarations
  34. static bool InitWGPU(GLFWwindow* window);
  35. static void ResizeSurface(int width, int height);
  36. static void glfw_error_callback(int error, const char* description)
  37. {
  38. printf("GLFW Error %d: %s\n", error, description);
  39. }
  40. static void wgpu_error_callback(WGPUErrorType error_type, const char* message, void*)
  41. {
  42. const char* error_type_lbl = "";
  43. switch (error_type)
  44. {
  45. case WGPUErrorType_Validation: error_type_lbl = "Validation"; break;
  46. case WGPUErrorType_OutOfMemory: error_type_lbl = "Out of memory"; break;
  47. case WGPUErrorType_Unknown: error_type_lbl = "Unknown"; break;
  48. case WGPUErrorType_DeviceLost: error_type_lbl = "Device lost"; break;
  49. default: error_type_lbl = "Unknown";
  50. }
  51. printf("%s error: %s\n", error_type_lbl, message);
  52. }
  53. // Main code
  54. int main(int, char**)
  55. {
  56. glfwSetErrorCallback(glfw_error_callback);
  57. if (!glfwInit())
  58. return 1;
  59. // Make sure GLFW does not initialize any graphics context.
  60. // This needs to be done explicitly later.
  61. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
  62. // Create window
  63. float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); // Valid on GLFW 3.3+ only
  64. wgpu_surface_width *= main_scale;
  65. wgpu_surface_height *= main_scale;
  66. GLFWwindow* window = glfwCreateWindow(wgpu_surface_width, wgpu_surface_height, "Dear ImGui GLFW+WebGPU example", nullptr, nullptr);
  67. if (window == nullptr)
  68. return 1;
  69. // Initialize the WebGPU environment
  70. if (!InitWGPU(window))
  71. {
  72. glfwDestroyWindow(window);
  73. glfwTerminate();
  74. return 1;
  75. }
  76. ResizeSurface(wgpu_surface_width, wgpu_surface_height);
  77. glfwShowWindow(window);
  78. // Setup Dear ImGui context
  79. IMGUI_CHECKVERSION();
  80. ImGui::CreateContext();
  81. ImGuiIO& io = ImGui::GetIO(); (void)io;
  82. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  83. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  84. // Setup Dear ImGui style
  85. ImGui::StyleColorsDark();
  86. //ImGui::StyleColorsLight();
  87. // Setup scaling
  88. ImGuiStyle& style = ImGui::GetStyle();
  89. style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
  90. style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose)
  91. // Setup Platform/Renderer backends
  92. ImGui_ImplGlfw_InitForOther(window, true);
  93. #ifdef __EMSCRIPTEN__
  94. ImGui_ImplGlfw_InstallEmscriptenCallbacks(window, "#canvas");
  95. #endif
  96. ImGui_ImplWGPU_InitInfo init_info;
  97. init_info.Device = wgpu_device;
  98. init_info.NumFramesInFlight = 3;
  99. init_info.RenderTargetFormat = wgpu_preferred_fmt;
  100. init_info.DepthStencilFormat = WGPUTextureFormat_Undefined;
  101. ImGui_ImplWGPU_Init(&init_info);
  102. // Load Fonts
  103. // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
  104. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  105. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
  106. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  107. // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author!
  108. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  109. // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details.
  110. //style.FontSizeBase = 20.0f;
  111. //io.Fonts->AddFontDefault();
  112. #ifndef IMGUI_DISABLE_FILE_FUNCTIONS
  113. //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf");
  114. //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf");
  115. //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf");
  116. //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf");
  117. //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf");
  118. //IM_ASSERT(font != nullptr);
  119. #endif
  120. // Our state
  121. bool show_demo_window = true;
  122. bool show_another_window = false;
  123. ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  124. // Main loop
  125. #ifdef __EMSCRIPTEN__
  126. // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
  127. // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
  128. io.IniFilename = nullptr;
  129. EMSCRIPTEN_MAINLOOP_BEGIN
  130. #else
  131. while (!glfwWindowShouldClose(window))
  132. #endif
  133. {
  134. // Poll and handle events (inputs, window resize, etc.)
  135. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  136. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  137. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  138. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  139. glfwPollEvents();
  140. if (glfwGetWindowAttrib(window, GLFW_ICONIFIED) != 0)
  141. {
  142. ImGui_ImplGlfw_Sleep(10);
  143. continue;
  144. }
  145. // React to changes in screen size
  146. int width, height;
  147. glfwGetFramebufferSize((GLFWwindow*)window, &width, &height);
  148. if (width != wgpu_surface_width || height != wgpu_surface_height)
  149. {
  150. ImGui_ImplWGPU_InvalidateDeviceObjects();
  151. ResizeSurface(width, height);
  152. ImGui_ImplWGPU_CreateDeviceObjects();
  153. }
  154. // Start the Dear ImGui frame
  155. ImGui_ImplWGPU_NewFrame();
  156. ImGui_ImplGlfw_NewFrame();
  157. ImGui::NewFrame();
  158. // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
  159. if (show_demo_window)
  160. ImGui::ShowDemoWindow(&show_demo_window);
  161. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  162. {
  163. static float f = 0.0f;
  164. static int counter = 0;
  165. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  166. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  167. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  168. ImGui::Checkbox("Another Window", &show_another_window);
  169. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  170. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  171. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  172. counter++;
  173. ImGui::SameLine();
  174. ImGui::Text("counter = %d", counter);
  175. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  176. ImGui::End();
  177. }
  178. // 3. Show another simple window.
  179. if (show_another_window)
  180. {
  181. ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
  182. ImGui::Text("Hello from another window!");
  183. if (ImGui::Button("Close Me"))
  184. show_another_window = false;
  185. ImGui::End();
  186. }
  187. // Rendering
  188. ImGui::Render();
  189. #ifndef __EMSCRIPTEN__
  190. // Tick needs to be called in Dawn to display validation errors
  191. wgpuDeviceTick(wgpu_device);
  192. #endif
  193. WGPURenderPassColorAttachment color_attachments = {};
  194. color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
  195. color_attachments.loadOp = WGPULoadOp_Clear;
  196. color_attachments.storeOp = WGPUStoreOp_Store;
  197. color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
  198. color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain);
  199. WGPURenderPassDescriptor render_pass_desc = {};
  200. render_pass_desc.colorAttachmentCount = 1;
  201. render_pass_desc.colorAttachments = &color_attachments;
  202. render_pass_desc.depthStencilAttachment = nullptr;
  203. WGPUCommandEncoderDescriptor enc_desc = {};
  204. WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc);
  205. WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
  206. ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass);
  207. wgpuRenderPassEncoderEnd(pass);
  208. WGPUCommandBufferDescriptor cmd_buffer_desc = {};
  209. WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc);
  210. WGPUQueue wgpu_queue = wgpuDeviceGetQueue(wgpu_device);
  211. wgpuQueueSubmit(wgpu_queue, 1, &cmd_buffer);
  212. #ifndef __EMSCRIPTEN__
  213. wgpuSwapChainPresent(wgpu_swap_chain);
  214. #endif
  215. wgpuTextureViewRelease(color_attachments.view);
  216. wgpuRenderPassEncoderRelease(pass);
  217. wgpuCommandEncoderRelease(encoder);
  218. wgpuCommandBufferRelease(cmd_buffer);
  219. }
  220. #ifdef __EMSCRIPTEN__
  221. EMSCRIPTEN_MAINLOOP_END;
  222. #endif
  223. // Cleanup
  224. ImGui_ImplWGPU_Shutdown();
  225. ImGui_ImplGlfw_Shutdown();
  226. ImGui::DestroyContext();
  227. glfwDestroyWindow(window);
  228. glfwTerminate();
  229. return 0;
  230. }
  231. #ifndef __EMSCRIPTEN__
  232. static WGPUAdapter RequestAdapter(WGPUInstance instance)
  233. {
  234. auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* message, void* pUserData)
  235. {
  236. if (status == WGPURequestAdapterStatus_Success)
  237. *(WGPUAdapter*)(pUserData) = adapter;
  238. else
  239. printf("Could not get WebGPU adapter: %s\n", message);
  240. };
  241. WGPUAdapter adapter;
  242. wgpuInstanceRequestAdapter(instance, nullptr, onAdapterRequestEnded, (void*)&adapter);
  243. return adapter;
  244. }
  245. static WGPUDevice RequestDevice(WGPUAdapter& adapter)
  246. {
  247. auto onDeviceRequestEnded = [](WGPURequestDeviceStatus status, WGPUDevice device, const char* message, void* pUserData)
  248. {
  249. if (status == WGPURequestDeviceStatus_Success)
  250. *(WGPUDevice*)(pUserData) = device;
  251. else
  252. printf("Could not get WebGPU device: %s\n", message);
  253. };
  254. WGPUDevice device;
  255. wgpuAdapterRequestDevice(adapter, nullptr, onDeviceRequestEnded, (void*)&device);
  256. return device;
  257. }
  258. #endif
  259. static bool InitWGPU(GLFWwindow* window)
  260. {
  261. wgpu::Instance instance = wgpuCreateInstance(nullptr);
  262. #ifdef __EMSCRIPTEN__
  263. wgpu_device = emscripten_webgpu_get_device();
  264. if (!wgpu_device)
  265. return false;
  266. #else
  267. WGPUAdapter adapter = RequestAdapter(instance.Get());
  268. if (!adapter)
  269. return false;
  270. wgpu_device = RequestDevice(adapter);
  271. #endif
  272. #ifdef __EMSCRIPTEN__
  273. wgpu::SurfaceDescriptorFromCanvasHTMLSelector canvas_desc = {};
  274. canvas_desc.selector = "#canvas";
  275. wgpu::SurfaceDescriptor surface_desc = {};
  276. surface_desc.nextInChain = &canvas_desc;
  277. wgpu::Surface surface = instance.CreateSurface(&surface_desc);
  278. wgpu::Adapter adapter = {};
  279. wgpu_preferred_fmt = (WGPUTextureFormat)surface.GetPreferredFormat(adapter);
  280. #else
  281. wgpu::Surface surface = wgpu::glfw::CreateSurfaceForWindow(instance, window);
  282. if (!surface)
  283. return false;
  284. wgpu_preferred_fmt = WGPUTextureFormat_BGRA8Unorm;
  285. #endif
  286. // Moving Dawn objects into WGPU handles
  287. wgpu_instance = instance.MoveToCHandle();
  288. wgpu_surface = surface.MoveToCHandle();
  289. wgpuDeviceSetUncapturedErrorCallback(wgpu_device, wgpu_error_callback, nullptr);
  290. return true;
  291. }
  292. static void ResizeSurface(int width, int height)
  293. {
  294. if (wgpu_swap_chain)
  295. wgpuSwapChainRelease(wgpu_swap_chain);
  296. wgpu_surface_width = width;
  297. wgpu_surface_height = height;
  298. WGPUSwapChainDescriptor swap_chain_desc = {};
  299. swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment;
  300. swap_chain_desc.format = wgpu_preferred_fmt;
  301. swap_chain_desc.width = width;
  302. swap_chain_desc.height = height;
  303. swap_chain_desc.presentMode = WGPUPresentMode_Fifo;
  304. wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc);
  305. }