main.cpp 14 KB

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