main.cpp 14 KB

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