main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. // Setup Dear ImGui style
  84. ImGui::StyleColorsDark();
  85. //ImGui::StyleColorsLight();
  86. // Setup Platform/Renderer backends
  87. ImGui_ImplGlfw_InitForOther(window, true);
  88. #ifdef __EMSCRIPTEN__
  89. ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas");
  90. #endif
  91. ImGui_ImplWGPU_InitInfo init_info;
  92. init_info.Device = wgpu_device;
  93. init_info.NumFramesInFlight = 3;
  94. init_info.RenderTargetFormat = wgpu_preferred_fmt;
  95. init_info.DepthStencilFormat = WGPUTextureFormat_Undefined;
  96. ImGui_ImplWGPU_Init(&init_info);
  97. // Load Fonts
  98. // - 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.
  99. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  100. // - 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).
  101. // - 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.
  102. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  103. // - Read 'docs/FONTS.md' for more instructions and details.
  104. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  105. // - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details.
  106. //io.Fonts->AddFontDefault();
  107. #ifndef IMGUI_DISABLE_FILE_FUNCTIONS
  108. //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf", 18.0f);
  109. //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f);
  110. //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f);
  111. //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f);
  112. //io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f);
  113. //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
  114. //IM_ASSERT(font != nullptr);
  115. #endif
  116. // Our state
  117. bool show_demo_window = true;
  118. bool show_another_window = false;
  119. ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  120. // Main loop
  121. #ifdef __EMSCRIPTEN__
  122. // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
  123. // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
  124. io.IniFilename = nullptr;
  125. EMSCRIPTEN_MAINLOOP_BEGIN
  126. #else
  127. while (!glfwWindowShouldClose(window))
  128. #endif
  129. {
  130. // Poll and handle events (inputs, window resize, etc.)
  131. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  132. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  133. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  134. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  135. glfwPollEvents();
  136. // React to changes in screen size
  137. int width, height;
  138. glfwGetFramebufferSize((GLFWwindow*)window, &width, &height);
  139. if (width != wgpu_swap_chain_width || height != wgpu_swap_chain_height)
  140. {
  141. ImGui_ImplWGPU_InvalidateDeviceObjects();
  142. CreateSwapChain(width, height);
  143. ImGui_ImplWGPU_CreateDeviceObjects();
  144. }
  145. // Start the Dear ImGui frame
  146. ImGui_ImplWGPU_NewFrame();
  147. ImGui_ImplGlfw_NewFrame();
  148. ImGui::NewFrame();
  149. // 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!).
  150. if (show_demo_window)
  151. ImGui::ShowDemoWindow(&show_demo_window);
  152. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  153. {
  154. static float f = 0.0f;
  155. static int counter = 0;
  156. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  157. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  158. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  159. ImGui::Checkbox("Another Window", &show_another_window);
  160. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  161. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  162. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  163. counter++;
  164. ImGui::SameLine();
  165. ImGui::Text("counter = %d", counter);
  166. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  167. ImGui::End();
  168. }
  169. // 3. Show another simple window.
  170. if (show_another_window)
  171. {
  172. 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)
  173. ImGui::Text("Hello from another window!");
  174. if (ImGui::Button("Close Me"))
  175. show_another_window = false;
  176. ImGui::End();
  177. }
  178. // Rendering
  179. ImGui::Render();
  180. #ifndef __EMSCRIPTEN__
  181. // Tick needs to be called in Dawn to display validation errors
  182. wgpuDeviceTick(wgpu_device);
  183. #endif
  184. WGPURenderPassColorAttachment color_attachments = {};
  185. color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
  186. color_attachments.loadOp = WGPULoadOp_Clear;
  187. color_attachments.storeOp = WGPUStoreOp_Store;
  188. color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
  189. color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain);
  190. WGPURenderPassDescriptor render_pass_desc = {};
  191. render_pass_desc.colorAttachmentCount = 1;
  192. render_pass_desc.colorAttachments = &color_attachments;
  193. render_pass_desc.depthStencilAttachment = nullptr;
  194. WGPUCommandEncoderDescriptor enc_desc = {};
  195. WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc);
  196. WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
  197. ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass);
  198. wgpuRenderPassEncoderEnd(pass);
  199. WGPUCommandBufferDescriptor cmd_buffer_desc = {};
  200. WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc);
  201. WGPUQueue queue = wgpuDeviceGetQueue(wgpu_device);
  202. wgpuQueueSubmit(queue, 1, &cmd_buffer);
  203. #ifndef __EMSCRIPTEN__
  204. wgpuSwapChainPresent(wgpu_swap_chain);
  205. #endif
  206. wgpuTextureViewRelease(color_attachments.view);
  207. wgpuRenderPassEncoderRelease(pass);
  208. wgpuCommandEncoderRelease(encoder);
  209. wgpuCommandBufferRelease(cmd_buffer);
  210. }
  211. #ifdef __EMSCRIPTEN__
  212. EMSCRIPTEN_MAINLOOP_END;
  213. #endif
  214. // Cleanup
  215. ImGui_ImplWGPU_Shutdown();
  216. ImGui_ImplGlfw_Shutdown();
  217. ImGui::DestroyContext();
  218. glfwDestroyWindow(window);
  219. glfwTerminate();
  220. return 0;
  221. }
  222. #ifndef __EMSCRIPTEN__
  223. static WGPUAdapter RequestAdapter(WGPUInstance instance)
  224. {
  225. auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* message, void* pUserData)
  226. {
  227. if (status == WGPURequestAdapterStatus_Success)
  228. *(WGPUAdapter*)(pUserData) = adapter;
  229. else
  230. printf("Could not get WebGPU adapter: %s\n", message);
  231. };
  232. WGPUAdapter adapter;
  233. wgpuInstanceRequestAdapter(instance, nullptr, onAdapterRequestEnded, (void*)&adapter);
  234. return adapter;
  235. }
  236. static WGPUDevice RequestDevice(WGPUAdapter& adapter)
  237. {
  238. auto onDeviceRequestEnded = [](WGPURequestDeviceStatus status, WGPUDevice device, const char* message, void* pUserData)
  239. {
  240. if (status == WGPURequestDeviceStatus_Success)
  241. *(WGPUDevice*)(pUserData) = device;
  242. else
  243. printf("Could not get WebGPU device: %s\n", message);
  244. };
  245. WGPUDevice device;
  246. wgpuAdapterRequestDevice(adapter, nullptr, onDeviceRequestEnded, (void*)&device);
  247. return device;
  248. }
  249. #endif
  250. static bool InitWGPU(GLFWwindow* window)
  251. {
  252. wgpu::Instance instance = wgpuCreateInstance(nullptr);
  253. #ifdef __EMSCRIPTEN__
  254. wgpu_device = emscripten_webgpu_get_device();
  255. if (!wgpu_device)
  256. return false;
  257. #else
  258. WGPUAdapter adapter = RequestAdapter(instance.Get());
  259. if (!adapter)
  260. return false;
  261. wgpu_device = RequestDevice(adapter);
  262. #endif
  263. #ifdef __EMSCRIPTEN__
  264. wgpu::SurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {};
  265. html_surface_desc.selector = "#canvas";
  266. wgpu::SurfaceDescriptor surface_desc = {};
  267. surface_desc.nextInChain = &html_surface_desc;
  268. wgpu::Surface surface = instance.CreateSurface(&surface_desc);
  269. wgpu::Adapter adapter = {};
  270. wgpu_preferred_fmt = (WGPUTextureFormat)surface.GetPreferredFormat(adapter);
  271. #else
  272. wgpu::Surface surface = wgpu::glfw::CreateSurfaceForWindow(instance, window);
  273. if (!surface)
  274. return false;
  275. wgpu_preferred_fmt = WGPUTextureFormat_BGRA8Unorm;
  276. #endif
  277. wgpu_instance = instance.MoveToCHandle();
  278. wgpu_surface = surface.MoveToCHandle();
  279. wgpuDeviceSetUncapturedErrorCallback(wgpu_device, wgpu_error_callback, nullptr);
  280. return true;
  281. }
  282. static void CreateSwapChain(int width, int height)
  283. {
  284. if (wgpu_swap_chain)
  285. wgpuSwapChainRelease(wgpu_swap_chain);
  286. wgpu_swap_chain_width = width;
  287. wgpu_swap_chain_height = height;
  288. WGPUSwapChainDescriptor swap_chain_desc = {};
  289. swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment;
  290. swap_chain_desc.format = wgpu_preferred_fmt;
  291. swap_chain_desc.width = width;
  292. swap_chain_desc.height = height;
  293. swap_chain_desc.presentMode = WGPUPresentMode_Fifo;
  294. wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc);
  295. }