imgui_impl_wgpu.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. // dear imgui: Renderer for WebGPU
  2. // This needs to be used along with a Platform Binding (e.g. GLFW, SDL2, SDL3)
  3. // (Please note that WebGPU is a recent API, may not be supported by all browser, and its ecosystem is generally a mess)
  4. // Implemented features:
  5. // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID/ImTextureRef!
  6. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  7. // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
  8. // [X] Renderer: Texture updates support for dynamic font system (ImGuiBackendFlags_RendererHasTextures).
  9. // Missing features or Issues:
  10. // [ ] Renderer: Multi-viewport support (multiple windows), useful for desktop.
  11. // Read imgui_impl_wgpu.h about how to use the IMGUI_IMPL_WEBGPU_BACKEND_WGPU or IMGUI_IMPL_WEBGPU_BACKEND_DAWN flags.
  12. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  13. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  14. // Learn about Dear ImGui:
  15. // - FAQ https://dearimgui.com/faq
  16. // - Getting Started https://dearimgui.com/getting-started
  17. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  18. // - Introduction, links and more at the top of imgui.cpp
  19. // CHANGELOG
  20. // (minor and older changes stripped away, please see git history for details)
  21. // 2025-10-16: Update to compile with Dawn and Emscripten's 4.0.10+ '--use-port=emdawnwebgpu' ports. (#8381, #8898)
  22. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
  23. // 2025-06-12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. (#8465)
  24. // 2025-02-26: Recreate image bind groups during render. (#8426, #8046, #7765, #8027) + Update for latest webgpu-native changes.
  25. // 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083)
  26. // 2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
  27. // 2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  28. // 2024-09-16: Added support for optional IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU define to handle ever-changing native implementations. (#7977)
  29. // 2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
  30. // 2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
  31. // 2024-01-22: Fixed pipeline layout leak. (#7245)
  32. // 2024-01-17: Explicitly fill all of WGPUDepthStencilState since standard removed defaults.
  33. // 2023-07-13: Use WGPUShaderModuleWGSLDescriptor's code instead of source. use WGPUMipmapFilterMode_Linear instead of WGPUFilterMode_Linear. (#6602)
  34. // 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V.
  35. // 2023-04-11: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
  36. // 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470)
  37. // 2022-11-24: Fixed validation error with default depth buffer settings.
  38. // 2022-11-10: Fixed rendering when a depth buffer is enabled. Added 'WGPUTextureFormat depth_format' parameter to ImGui_ImplWGPU_Init().
  39. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  40. // 2021-11-29: Passing explicit buffer sizes to wgpuRenderPassEncoderSetVertexBuffer()/wgpuRenderPassEncoderSetIndexBuffer().
  41. // 2021-08-24: Fixed for latest specs.
  42. // 2021-05-24: Add support for draw_data->FramebufferScale.
  43. // 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  44. // 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
  45. // 2021-02-18: Change blending equation to preserve alpha in output buffer.
  46. // 2021-01-28: Initial version.
  47. #include "imgui.h"
  48. #ifndef IMGUI_DISABLE
  49. #include "imgui_impl_wgpu.h"
  50. #include <limits.h>
  51. #include <stdio.h>
  52. // One of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details.
  53. #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
  54. #error Exactly one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be defined!
  55. #endif
  56. // This condition is true when it's built with EMSCRIPTEN using -sUSE_WEBGPU=1 flag (deprecated from 4.0.10)
  57. // This condition is false for all other 3 cases: WGPU-Native, DAWN-Native or DAWN-EMSCRIPTEN (using --use-port=emdawnwebgpu flag)
  58. #if defined(__EMSCRIPTEN__) && defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
  59. #define IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN
  60. #endif
  61. #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
  62. // Dawn renamed WGPUProgrammableStageDescriptor to WGPUComputeState (see: https://github.com/webgpu-native/webgpu-headers/pull/413)
  63. // Using type alias until WGPU adopts the same naming convention (#8369)
  64. using WGPUProgrammableStageDescriptor = WGPUComputeState;
  65. #endif
  66. // Dear ImGui prototypes from imgui_internal.h
  67. extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed);
  68. #define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro).
  69. // WebGPU data
  70. struct ImGui_ImplWGPU_Texture
  71. {
  72. WGPUTexture Texture = nullptr;
  73. WGPUTextureView TextureView = nullptr;
  74. };
  75. struct RenderResources
  76. {
  77. WGPUSampler Sampler = nullptr; // Sampler for textures
  78. WGPUBuffer Uniforms = nullptr; // Shader uniforms
  79. WGPUBindGroup CommonBindGroup = nullptr; // Resources bind-group to bind the common resources to pipeline
  80. ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map)
  81. WGPUBindGroupLayout ImageBindGroupLayout = nullptr; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM
  82. };
  83. struct FrameResources
  84. {
  85. WGPUBuffer IndexBuffer;
  86. WGPUBuffer VertexBuffer;
  87. ImDrawIdx* IndexBufferHost;
  88. ImDrawVert* VertexBufferHost;
  89. int IndexBufferSize;
  90. int VertexBufferSize;
  91. };
  92. struct Uniforms
  93. {
  94. float MVP[4][4];
  95. float Gamma;
  96. };
  97. struct ImGui_ImplWGPU_Data
  98. {
  99. ImGui_ImplWGPU_InitInfo initInfo;
  100. WGPUDevice wgpuDevice = nullptr;
  101. WGPUQueue defaultQueue = nullptr;
  102. WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined;
  103. WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined;
  104. WGPURenderPipeline pipelineState = nullptr;
  105. RenderResources renderResources;
  106. FrameResources* pFrameResources = nullptr;
  107. unsigned int numFramesInFlight = 0;
  108. unsigned int frameIndex = UINT_MAX;
  109. };
  110. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  111. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  112. static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData()
  113. {
  114. return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  115. }
  116. //-----------------------------------------------------------------------------
  117. // SHADERS
  118. //-----------------------------------------------------------------------------
  119. static const char __shader_vert_wgsl[] = R"(
  120. struct VertexInput {
  121. @location(0) position: vec2<f32>,
  122. @location(1) uv: vec2<f32>,
  123. @location(2) color: vec4<f32>,
  124. };
  125. struct VertexOutput {
  126. @builtin(position) position: vec4<f32>,
  127. @location(0) color: vec4<f32>,
  128. @location(1) uv: vec2<f32>,
  129. };
  130. struct Uniforms {
  131. mvp: mat4x4<f32>,
  132. gamma: f32,
  133. };
  134. @group(0) @binding(0) var<uniform> uniforms: Uniforms;
  135. @vertex
  136. fn main(in: VertexInput) -> VertexOutput {
  137. var out: VertexOutput;
  138. out.position = uniforms.mvp * vec4<f32>(in.position, 0.0, 1.0);
  139. out.color = in.color;
  140. out.uv = in.uv;
  141. return out;
  142. }
  143. )";
  144. static const char __shader_frag_wgsl[] = R"(
  145. struct VertexOutput {
  146. @builtin(position) position: vec4<f32>,
  147. @location(0) color: vec4<f32>,
  148. @location(1) uv: vec2<f32>,
  149. };
  150. struct Uniforms {
  151. mvp: mat4x4<f32>,
  152. gamma: f32,
  153. };
  154. @group(0) @binding(0) var<uniform> uniforms: Uniforms;
  155. @group(0) @binding(1) var s: sampler;
  156. @group(1) @binding(0) var t: texture_2d<f32>;
  157. @fragment
  158. fn main(in: VertexOutput) -> @location(0) vec4<f32> {
  159. let color = in.color * textureSample(t, s, in.uv);
  160. let corrected_color = pow(color.rgb, vec3<f32>(uniforms.gamma));
  161. return vec4<f32>(corrected_color, color.a);
  162. }
  163. )";
  164. static void SafeRelease(ImDrawIdx*& res)
  165. {
  166. if (res)
  167. delete[] res;
  168. res = nullptr;
  169. }
  170. static void SafeRelease(ImDrawVert*& res)
  171. {
  172. if (res)
  173. delete[] res;
  174. res = nullptr;
  175. }
  176. static void SafeRelease(WGPUBindGroupLayout& res)
  177. {
  178. if (res)
  179. wgpuBindGroupLayoutRelease(res);
  180. res = nullptr;
  181. }
  182. static void SafeRelease(WGPUBindGroup& res)
  183. {
  184. if (res)
  185. wgpuBindGroupRelease(res);
  186. res = nullptr;
  187. }
  188. static void SafeRelease(WGPUBuffer& res)
  189. {
  190. if (res)
  191. wgpuBufferRelease(res);
  192. res = nullptr;
  193. }
  194. static void SafeRelease(WGPUPipelineLayout& res)
  195. {
  196. if (res)
  197. wgpuPipelineLayoutRelease(res);
  198. res = nullptr;
  199. }
  200. static void SafeRelease(WGPURenderPipeline& res)
  201. {
  202. if (res)
  203. wgpuRenderPipelineRelease(res);
  204. res = nullptr;
  205. }
  206. static void SafeRelease(WGPUSampler& res)
  207. {
  208. if (res)
  209. wgpuSamplerRelease(res);
  210. res = nullptr;
  211. }
  212. static void SafeRelease(WGPUShaderModule& res)
  213. {
  214. if (res)
  215. wgpuShaderModuleRelease(res);
  216. res = nullptr;
  217. }
  218. static void SafeRelease(RenderResources& res)
  219. {
  220. SafeRelease(res.Sampler);
  221. SafeRelease(res.Uniforms);
  222. SafeRelease(res.CommonBindGroup);
  223. SafeRelease(res.ImageBindGroupLayout);
  224. };
  225. static void SafeRelease(FrameResources& res)
  226. {
  227. SafeRelease(res.IndexBuffer);
  228. SafeRelease(res.VertexBuffer);
  229. SafeRelease(res.IndexBufferHost);
  230. SafeRelease(res.VertexBufferHost);
  231. }
  232. static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const char* wgsl_source)
  233. {
  234. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  235. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  236. WGPUShaderSourceWGSL wgsl_desc = {};
  237. wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
  238. wgsl_desc.code = { wgsl_source, WGPU_STRLEN };
  239. #else
  240. WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
  241. wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
  242. wgsl_desc.code = wgsl_source;
  243. #endif
  244. WGPUShaderModuleDescriptor desc = {};
  245. desc.nextInChain = (WGPUChainedStruct*)&wgsl_desc;
  246. WGPUProgrammableStageDescriptor stage_desc = {};
  247. stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc);
  248. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  249. stage_desc.entryPoint = { "main", WGPU_STRLEN };
  250. #else
  251. stage_desc.entryPoint = "main";
  252. #endif
  253. return stage_desc;
  254. }
  255. static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture)
  256. {
  257. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  258. WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } };
  259. WGPUBindGroupDescriptor image_bg_descriptor = {};
  260. image_bg_descriptor.layout = layout;
  261. image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry);
  262. image_bg_descriptor.entries = image_bg_entries;
  263. return wgpuDeviceCreateBindGroup(bd->wgpuDevice, &image_bg_descriptor);
  264. }
  265. static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr)
  266. {
  267. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  268. // Setup orthographic projection matrix into our constant buffer
  269. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  270. {
  271. float L = draw_data->DisplayPos.x;
  272. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  273. float T = draw_data->DisplayPos.y;
  274. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  275. float mvp[4][4] =
  276. {
  277. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  278. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  279. { 0.0f, 0.0f, 0.5f, 0.0f },
  280. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  281. };
  282. wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, MVP), mvp, sizeof(Uniforms::MVP));
  283. float gamma;
  284. switch (bd->renderTargetFormat)
  285. {
  286. case WGPUTextureFormat_ASTC10x10UnormSrgb:
  287. case WGPUTextureFormat_ASTC10x5UnormSrgb:
  288. case WGPUTextureFormat_ASTC10x6UnormSrgb:
  289. case WGPUTextureFormat_ASTC10x8UnormSrgb:
  290. case WGPUTextureFormat_ASTC12x10UnormSrgb:
  291. case WGPUTextureFormat_ASTC12x12UnormSrgb:
  292. case WGPUTextureFormat_ASTC4x4UnormSrgb:
  293. case WGPUTextureFormat_ASTC5x5UnormSrgb:
  294. case WGPUTextureFormat_ASTC6x5UnormSrgb:
  295. case WGPUTextureFormat_ASTC6x6UnormSrgb:
  296. case WGPUTextureFormat_ASTC8x5UnormSrgb:
  297. case WGPUTextureFormat_ASTC8x6UnormSrgb:
  298. case WGPUTextureFormat_ASTC8x8UnormSrgb:
  299. case WGPUTextureFormat_BC1RGBAUnormSrgb:
  300. case WGPUTextureFormat_BC2RGBAUnormSrgb:
  301. case WGPUTextureFormat_BC3RGBAUnormSrgb:
  302. case WGPUTextureFormat_BC7RGBAUnormSrgb:
  303. case WGPUTextureFormat_BGRA8UnormSrgb:
  304. case WGPUTextureFormat_ETC2RGB8A1UnormSrgb:
  305. case WGPUTextureFormat_ETC2RGB8UnormSrgb:
  306. case WGPUTextureFormat_ETC2RGBA8UnormSrgb:
  307. case WGPUTextureFormat_RGBA8UnormSrgb:
  308. gamma = 2.2f;
  309. break;
  310. default:
  311. gamma = 1.0f;
  312. }
  313. wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, Gamma), &gamma, sizeof(Uniforms::Gamma));
  314. }
  315. // Setup viewport
  316. wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1);
  317. // Bind shader and vertex buffers
  318. wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize * sizeof(ImDrawVert));
  319. wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize * sizeof(ImDrawIdx));
  320. wgpuRenderPassEncoderSetPipeline(ctx, bd->pipelineState);
  321. wgpuRenderPassEncoderSetBindGroup(ctx, 0, bd->renderResources.CommonBindGroup, 0, nullptr);
  322. // Setup blend factor
  323. WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f };
  324. wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color);
  325. }
  326. // Render function
  327. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  328. void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
  329. {
  330. // Avoid rendering when minimized
  331. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  332. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  333. if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdLists.Size == 0)
  334. return;
  335. // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
  336. // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
  337. if (draw_data->Textures != nullptr)
  338. for (ImTextureData* tex : *draw_data->Textures)
  339. if (tex->Status != ImTextureStatus_OK)
  340. ImGui_ImplWGPU_UpdateTexture(tex);
  341. // FIXME: Assuming that this only gets called once per frame!
  342. // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
  343. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  344. bd->frameIndex = bd->frameIndex + 1;
  345. FrameResources* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
  346. // Create and grow vertex/index buffers if needed
  347. if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
  348. {
  349. if (fr->VertexBuffer)
  350. {
  351. wgpuBufferDestroy(fr->VertexBuffer);
  352. wgpuBufferRelease(fr->VertexBuffer);
  353. }
  354. SafeRelease(fr->VertexBufferHost);
  355. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  356. WGPUBufferDescriptor vb_desc =
  357. {
  358. nullptr,
  359. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  360. { "Dear ImGui Vertex buffer", WGPU_STRLEN, },
  361. #else
  362. "Dear ImGui Vertex buffer",
  363. #endif
  364. WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
  365. MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4),
  366. false
  367. };
  368. fr->VertexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &vb_desc);
  369. if (!fr->VertexBuffer)
  370. return;
  371. fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize];
  372. }
  373. if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
  374. {
  375. if (fr->IndexBuffer)
  376. {
  377. wgpuBufferDestroy(fr->IndexBuffer);
  378. wgpuBufferRelease(fr->IndexBuffer);
  379. }
  380. SafeRelease(fr->IndexBufferHost);
  381. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  382. WGPUBufferDescriptor ib_desc =
  383. {
  384. nullptr,
  385. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  386. { "Dear ImGui Index buffer", WGPU_STRLEN, },
  387. #else
  388. "Dear ImGui Index buffer",
  389. #endif
  390. WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
  391. MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4),
  392. false
  393. };
  394. fr->IndexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ib_desc);
  395. if (!fr->IndexBuffer)
  396. return;
  397. fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize];
  398. }
  399. // Upload vertex/index data into a single contiguous GPU buffer
  400. ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost;
  401. ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
  402. for (const ImDrawList* draw_list : draw_data->CmdLists)
  403. {
  404. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  405. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  406. vtx_dst += draw_list->VtxBuffer.Size;
  407. idx_dst += draw_list->IdxBuffer.Size;
  408. }
  409. int64_t vb_write_size = MEMALIGN((char*)vtx_dst - (char*)fr->VertexBufferHost, 4);
  410. int64_t ib_write_size = MEMALIGN((char*)idx_dst - (char*)fr->IndexBufferHost, 4);
  411. wgpuQueueWriteBuffer(bd->defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size);
  412. wgpuQueueWriteBuffer(bd->defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size);
  413. // Setup desired render state
  414. ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
  415. // Setup render state structure (for callbacks and custom texture bindings)
  416. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  417. ImGui_ImplWGPU_RenderState render_state;
  418. render_state.Device = bd->wgpuDevice;
  419. render_state.RenderPassEncoder = pass_encoder;
  420. platform_io.Renderer_RenderState = &render_state;
  421. // Render command lists
  422. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  423. int global_vtx_offset = 0;
  424. int global_idx_offset = 0;
  425. ImVec2 clip_scale = draw_data->FramebufferScale;
  426. ImVec2 clip_off = draw_data->DisplayPos;
  427. for (const ImDrawList* draw_list : draw_data->CmdLists)
  428. {
  429. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  430. {
  431. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  432. if (pcmd->UserCallback != nullptr)
  433. {
  434. // User callback, registered via ImDrawList::AddCallback()
  435. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  436. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  437. ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
  438. else
  439. pcmd->UserCallback(draw_list, pcmd);
  440. }
  441. else
  442. {
  443. // Bind custom texture
  444. ImTextureID tex_id = pcmd->GetTexID();
  445. ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id), 0);
  446. WGPUBindGroup bind_group = (WGPUBindGroup)bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash);
  447. if (!bind_group)
  448. {
  449. bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id);
  450. bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, bind_group);
  451. }
  452. wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr);
  453. // Project scissor/clipping rectangles into framebuffer space
  454. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  455. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  456. // Clamp to viewport as wgpuRenderPassEncoderSetScissorRect() won't accept values that are off bounds
  457. if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
  458. if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
  459. if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
  460. if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
  461. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  462. continue;
  463. // Apply scissor/clipping rectangle, Draw
  464. wgpuRenderPassEncoderSetScissorRect(pass_encoder, (uint32_t)clip_min.x, (uint32_t)clip_min.y, (uint32_t)(clip_max.x - clip_min.x), (uint32_t)(clip_max.y - clip_min.y));
  465. wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  466. }
  467. }
  468. global_idx_offset += draw_list->IdxBuffer.Size;
  469. global_vtx_offset += draw_list->VtxBuffer.Size;
  470. }
  471. // Remove all ImageBindGroups
  472. ImGuiStorage& image_bind_groups = bd->renderResources.ImageBindGroups;
  473. for (int i = 0; i < image_bind_groups.Data.Size; i++)
  474. {
  475. WGPUBindGroup bind_group = (WGPUBindGroup)image_bind_groups.Data[i].val_p;
  476. SafeRelease(bind_group);
  477. }
  478. image_bind_groups.Data.resize(0);
  479. platform_io.Renderer_RenderState = nullptr;
  480. }
  481. static void ImGui_ImplWGPU_DestroyTexture(ImTextureData* tex)
  482. {
  483. if (ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData)
  484. {
  485. IM_ASSERT(backend_tex->TextureView == (WGPUTextureView)(intptr_t)tex->TexID);
  486. wgpuTextureViewRelease(backend_tex->TextureView);
  487. wgpuTextureRelease(backend_tex->Texture);
  488. IM_DELETE(backend_tex);
  489. // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
  490. tex->SetTexID(ImTextureID_Invalid);
  491. tex->BackendUserData = nullptr;
  492. }
  493. tex->SetStatus(ImTextureStatus_Destroyed);
  494. }
  495. void ImGui_ImplWGPU_UpdateTexture(ImTextureData* tex)
  496. {
  497. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  498. if (tex->Status == ImTextureStatus_WantCreate)
  499. {
  500. // Create and upload new texture to graphics system
  501. //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
  502. IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
  503. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  504. ImGui_ImplWGPU_Texture* backend_tex = IM_NEW(ImGui_ImplWGPU_Texture)();
  505. // Create texture
  506. WGPUTextureDescriptor tex_desc = {};
  507. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  508. tex_desc.label = { "Dear ImGui Texture", WGPU_STRLEN };
  509. #else
  510. tex_desc.label = "Dear ImGui Texture";
  511. #endif
  512. tex_desc.dimension = WGPUTextureDimension_2D;
  513. tex_desc.size.width = tex->Width;
  514. tex_desc.size.height = tex->Height;
  515. tex_desc.size.depthOrArrayLayers = 1;
  516. tex_desc.sampleCount = 1;
  517. tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
  518. tex_desc.mipLevelCount = 1;
  519. tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding;
  520. backend_tex->Texture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc);
  521. // Create texture view
  522. WGPUTextureViewDescriptor tex_view_desc = {};
  523. tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
  524. tex_view_desc.dimension = WGPUTextureViewDimension_2D;
  525. tex_view_desc.baseMipLevel = 0;
  526. tex_view_desc.mipLevelCount = 1;
  527. tex_view_desc.baseArrayLayer = 0;
  528. tex_view_desc.arrayLayerCount = 1;
  529. tex_view_desc.aspect = WGPUTextureAspect_All;
  530. backend_tex->TextureView = wgpuTextureCreateView(backend_tex->Texture, &tex_view_desc);
  531. // Store identifiers
  532. tex->SetTexID((ImTextureID)(intptr_t)backend_tex->TextureView);
  533. tex->BackendUserData = backend_tex;
  534. // We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below.
  535. }
  536. if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
  537. {
  538. ImGui_ImplWGPU_Texture* backend_tex = (ImGui_ImplWGPU_Texture*)tex->BackendUserData;
  539. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  540. // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture.
  541. const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x;
  542. const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y;
  543. const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w;
  544. const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h;
  545. // Update full texture or selected blocks. We only ever write to textures regions which have never been used before!
  546. // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions.
  547. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  548. WGPUTexelCopyTextureInfo dst_view = {};
  549. #else
  550. WGPUImageCopyTexture dst_view = {};
  551. #endif
  552. dst_view.texture = backend_tex->Texture;
  553. dst_view.mipLevel = 0;
  554. dst_view.origin = { (uint32_t)upload_x, (uint32_t)upload_y, 0 };
  555. dst_view.aspect = WGPUTextureAspect_All;
  556. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  557. WGPUTexelCopyBufferLayout layout = {};
  558. #else
  559. WGPUTextureDataLayout layout = {};
  560. #endif
  561. layout.offset = 0;
  562. layout.bytesPerRow = tex->Width * tex->BytesPerPixel;
  563. layout.rowsPerImage = upload_h;
  564. WGPUExtent3D write_size = { (uint32_t)upload_w, (uint32_t)upload_h, 1 };
  565. wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, tex->GetPixelsAt(upload_x, upload_y), (uint32_t)(tex->Width * upload_h * tex->BytesPerPixel), &layout, &write_size);
  566. tex->SetStatus(ImTextureStatus_OK);
  567. }
  568. if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
  569. ImGui_ImplWGPU_DestroyTexture(tex);
  570. }
  571. static void ImGui_ImplWGPU_CreateUniformBuffer()
  572. {
  573. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  574. WGPUBufferDescriptor ub_desc =
  575. {
  576. nullptr,
  577. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  578. { "Dear ImGui Uniform buffer", WGPU_STRLEN, },
  579. #else
  580. "Dear ImGui Uniform buffer",
  581. #endif
  582. WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
  583. MEMALIGN(sizeof(Uniforms), 16),
  584. false
  585. };
  586. bd->renderResources.Uniforms = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ub_desc);
  587. }
  588. bool ImGui_ImplWGPU_CreateDeviceObjects()
  589. {
  590. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  591. if (!bd->wgpuDevice)
  592. return false;
  593. if (bd->pipelineState)
  594. ImGui_ImplWGPU_InvalidateDeviceObjects();
  595. // Create render pipeline
  596. WGPURenderPipelineDescriptor graphics_pipeline_desc = {};
  597. graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
  598. graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
  599. graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
  600. graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
  601. graphics_pipeline_desc.multisample = bd->initInfo.PipelineMultisampleState;
  602. // Bind group layouts
  603. WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {};
  604. common_bg_layout_entries[0].binding = 0;
  605. common_bg_layout_entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
  606. common_bg_layout_entries[0].buffer.type = WGPUBufferBindingType_Uniform;
  607. common_bg_layout_entries[1].binding = 1;
  608. common_bg_layout_entries[1].visibility = WGPUShaderStage_Fragment;
  609. common_bg_layout_entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
  610. WGPUBindGroupLayoutEntry image_bg_layout_entries[1] = {};
  611. image_bg_layout_entries[0].binding = 0;
  612. image_bg_layout_entries[0].visibility = WGPUShaderStage_Fragment;
  613. image_bg_layout_entries[0].texture.sampleType = WGPUTextureSampleType_Float;
  614. image_bg_layout_entries[0].texture.viewDimension = WGPUTextureViewDimension_2D;
  615. WGPUBindGroupLayoutDescriptor common_bg_layout_desc = {};
  616. common_bg_layout_desc.entryCount = 2;
  617. common_bg_layout_desc.entries = common_bg_layout_entries;
  618. WGPUBindGroupLayoutDescriptor image_bg_layout_desc = {};
  619. image_bg_layout_desc.entryCount = 1;
  620. image_bg_layout_desc.entries = image_bg_layout_entries;
  621. WGPUBindGroupLayout bg_layouts[2];
  622. bg_layouts[0] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &common_bg_layout_desc);
  623. bg_layouts[1] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &image_bg_layout_desc);
  624. WGPUPipelineLayoutDescriptor layout_desc = {};
  625. layout_desc.bindGroupLayoutCount = 2;
  626. layout_desc.bindGroupLayouts = bg_layouts;
  627. graphics_pipeline_desc.layout = wgpuDeviceCreatePipelineLayout(bd->wgpuDevice, &layout_desc);
  628. // Create the vertex shader
  629. WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_vert_wgsl);
  630. graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
  631. graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
  632. // Vertex input configuration
  633. WGPUVertexAttribute attribute_desc[] =
  634. {
  635. #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
  636. { nullptr, WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
  637. { nullptr, WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
  638. { nullptr, WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
  639. #else
  640. { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
  641. { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
  642. { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
  643. #endif
  644. };
  645. WGPUVertexBufferLayout buffer_layouts[1];
  646. buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
  647. buffer_layouts[0].stepMode = WGPUVertexStepMode_Vertex;
  648. buffer_layouts[0].attributeCount = 3;
  649. buffer_layouts[0].attributes = attribute_desc;
  650. graphics_pipeline_desc.vertex.bufferCount = 1;
  651. graphics_pipeline_desc.vertex.buffers = buffer_layouts;
  652. // Create the pixel shader
  653. WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_frag_wgsl);
  654. // Create the blending setup
  655. WGPUBlendState blend_state = {};
  656. blend_state.alpha.operation = WGPUBlendOperation_Add;
  657. blend_state.alpha.srcFactor = WGPUBlendFactor_One;
  658. blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
  659. blend_state.color.operation = WGPUBlendOperation_Add;
  660. blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
  661. blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
  662. WGPUColorTargetState color_state = {};
  663. color_state.format = bd->renderTargetFormat;
  664. color_state.blend = &blend_state;
  665. color_state.writeMask = WGPUColorWriteMask_All;
  666. WGPUFragmentState fragment_state = {};
  667. fragment_state.module = pixel_shader_desc.module;
  668. fragment_state.entryPoint = pixel_shader_desc.entryPoint;
  669. fragment_state.targetCount = 1;
  670. fragment_state.targets = &color_state;
  671. graphics_pipeline_desc.fragment = &fragment_state;
  672. // Create depth-stencil State
  673. WGPUDepthStencilState depth_stencil_state = {};
  674. depth_stencil_state.format = bd->depthStencilFormat;
  675. #if !defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU_EMSCRIPTEN)
  676. depth_stencil_state.depthWriteEnabled = WGPUOptionalBool_False;
  677. #else
  678. depth_stencil_state.depthWriteEnabled = false;
  679. #endif
  680. depth_stencil_state.depthCompare = WGPUCompareFunction_Always;
  681. depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always;
  682. depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep;
  683. depth_stencil_state.stencilFront.depthFailOp = WGPUStencilOperation_Keep;
  684. depth_stencil_state.stencilFront.passOp = WGPUStencilOperation_Keep;
  685. depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always;
  686. depth_stencil_state.stencilBack.failOp = WGPUStencilOperation_Keep;
  687. depth_stencil_state.stencilBack.depthFailOp = WGPUStencilOperation_Keep;
  688. depth_stencil_state.stencilBack.passOp = WGPUStencilOperation_Keep;
  689. // Configure disabled depth-stencil state
  690. graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state;
  691. bd->pipelineState = wgpuDeviceCreateRenderPipeline(bd->wgpuDevice, &graphics_pipeline_desc);
  692. ImGui_ImplWGPU_CreateUniformBuffer();
  693. // Create sampler
  694. // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
  695. WGPUSamplerDescriptor sampler_desc = {};
  696. sampler_desc.minFilter = WGPUFilterMode_Linear;
  697. sampler_desc.magFilter = WGPUFilterMode_Linear;
  698. sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear;
  699. sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge;
  700. sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge;
  701. sampler_desc.addressModeW = WGPUAddressMode_ClampToEdge;
  702. sampler_desc.maxAnisotropy = 1;
  703. bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc);
  704. // Create resource bind group
  705. WGPUBindGroupEntry common_bg_entries[] =
  706. {
  707. { nullptr, 0, bd->renderResources.Uniforms, 0, MEMALIGN(sizeof(Uniforms), 16), 0, 0 },
  708. { nullptr, 1, 0, 0, 0, bd->renderResources.Sampler, 0 },
  709. };
  710. WGPUBindGroupDescriptor common_bg_descriptor = {};
  711. common_bg_descriptor.layout = bg_layouts[0];
  712. common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
  713. common_bg_descriptor.entries = common_bg_entries;
  714. bd->renderResources.CommonBindGroup = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor);
  715. bd->renderResources.ImageBindGroupLayout = bg_layouts[1];
  716. SafeRelease(vertex_shader_desc.module);
  717. SafeRelease(pixel_shader_desc.module);
  718. SafeRelease(graphics_pipeline_desc.layout);
  719. SafeRelease(bg_layouts[0]);
  720. return true;
  721. }
  722. void ImGui_ImplWGPU_InvalidateDeviceObjects()
  723. {
  724. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  725. if (!bd->wgpuDevice)
  726. return;
  727. SafeRelease(bd->pipelineState);
  728. SafeRelease(bd->renderResources);
  729. // Destroy all textures
  730. for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
  731. if (tex->RefCount == 1)
  732. ImGui_ImplWGPU_DestroyTexture(tex);
  733. for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
  734. SafeRelease(bd->pFrameResources[i]);
  735. }
  736. bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info)
  737. {
  738. ImGuiIO& io = ImGui::GetIO();
  739. IMGUI_CHECKVERSION();
  740. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  741. // Setup backend capabilities flags
  742. ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)();
  743. io.BackendRendererUserData = (void*)bd;
  744. #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
  745. #if defined(__EMSCRIPTEN__)
  746. io.BackendRendererName = "imgui_impl_wgpu (Dawn, Emscripten)"; // compiled & linked using EMSCRIPTEN with "--use-port=emdawnwebgpu" flag
  747. #else
  748. io.BackendRendererName = "imgui_impl_wgpu (Dawn, Native)";
  749. #endif
  750. #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
  751. #if defined(__EMSCRIPTEN__)
  752. io.BackendRendererName = "imgui_impl_wgpu (WGPU, Emscripten)"; // linked using EMSCRIPTEN with "-sUSE_WEBGPU=1" flag, deprecated from EMSCRIPTEN 4.0.10
  753. #else
  754. io.BackendRendererName = "imgui_impl_wgpu (WGPU, Native)";
  755. #endif
  756. #endif
  757. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  758. io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
  759. bd->initInfo = *init_info;
  760. bd->wgpuDevice = init_info->Device;
  761. bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice);
  762. bd->renderTargetFormat = init_info->RenderTargetFormat;
  763. bd->depthStencilFormat = init_info->DepthStencilFormat;
  764. bd->numFramesInFlight = init_info->NumFramesInFlight;
  765. bd->frameIndex = UINT_MAX;
  766. bd->renderResources.Sampler = nullptr;
  767. bd->renderResources.Uniforms = nullptr;
  768. bd->renderResources.CommonBindGroup = nullptr;
  769. bd->renderResources.ImageBindGroups.Data.reserve(100);
  770. bd->renderResources.ImageBindGroupLayout = nullptr;
  771. // Create buffers with a default size (they will later be grown as needed)
  772. bd->pFrameResources = new FrameResources[bd->numFramesInFlight];
  773. for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
  774. {
  775. FrameResources* fr = &bd->pFrameResources[i];
  776. fr->IndexBuffer = nullptr;
  777. fr->VertexBuffer = nullptr;
  778. fr->IndexBufferHost = nullptr;
  779. fr->VertexBufferHost = nullptr;
  780. fr->IndexBufferSize = 10000;
  781. fr->VertexBufferSize = 5000;
  782. }
  783. return true;
  784. }
  785. void ImGui_ImplWGPU_Shutdown()
  786. {
  787. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  788. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  789. ImGuiIO& io = ImGui::GetIO();
  790. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  791. ImGui_ImplWGPU_InvalidateDeviceObjects();
  792. delete[] bd->pFrameResources;
  793. bd->pFrameResources = nullptr;
  794. wgpuQueueRelease(bd->defaultQueue);
  795. bd->wgpuDevice = nullptr;
  796. bd->numFramesInFlight = 0;
  797. bd->frameIndex = UINT_MAX;
  798. io.BackendRendererName = nullptr;
  799. io.BackendRendererUserData = nullptr;
  800. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
  801. platform_io.ClearRendererHandlers();
  802. IM_DELETE(bd);
  803. }
  804. void ImGui_ImplWGPU_NewFrame()
  805. {
  806. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
  807. if (!bd->pipelineState)
  808. if (!ImGui_ImplWGPU_CreateDeviceObjects())
  809. IM_ASSERT(0 && "ImGui_ImplWGPU_CreateDeviceObjects() failed!");
  810. }
  811. //-------------------------------------------------------------------------
  812. // Internal Helpers
  813. // Those are currently used by our example applications.
  814. //-------------------------------------------------------------------------
  815. bool ImGui_ImplWGPU_IsSurfaceStatusError(WGPUSurfaceGetCurrentTextureStatus status)
  816. {
  817. #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
  818. return (status == WGPUSurfaceGetCurrentTextureStatus_Error);
  819. #else
  820. return (status == WGPUSurfaceGetCurrentTextureStatus_OutOfMemory || status == WGPUSurfaceGetCurrentTextureStatus_DeviceLost);
  821. #endif
  822. }
  823. bool ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(WGPUSurfaceGetCurrentTextureStatus status)
  824. {
  825. #if defined(__EMSCRIPTEN__) && !defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
  826. return (status == WGPUSurfaceGetCurrentTextureStatus_Timeout || status == WGPUSurfaceGetCurrentTextureStatus_Outdated || status == WGPUSurfaceGetCurrentTextureStatus_Lost);
  827. #else
  828. return (status == WGPUSurfaceGetCurrentTextureStatus_Timeout || status == WGPUSurfaceGetCurrentTextureStatus_Outdated || status == WGPUSurfaceGetCurrentTextureStatus_Lost || status == WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal);
  829. #endif
  830. }
  831. // Helpers to obtain a string
  832. #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
  833. const char* ImGui_ImplWGPU_GetErrorTypeName(WGPUErrorType type)
  834. {
  835. switch (type)
  836. {
  837. case WGPUErrorType_Validation: return "Validation";
  838. case WGPUErrorType_OutOfMemory: return "OutOfMemory";
  839. case WGPUErrorType_Unknown: return "Unknown";
  840. case WGPUErrorType_Internal: return "Internal";
  841. default: return "Unknown";
  842. }
  843. }
  844. const char* ImGui_ImplWGPU_GetDeviceLostReasonName(WGPUDeviceLostReason type)
  845. {
  846. switch (type)
  847. {
  848. case WGPUDeviceLostReason_Unknown: return "Unknown";
  849. case WGPUDeviceLostReason_Destroyed: return "Destroyed";
  850. case WGPUDeviceLostReason_CallbackCancelled: return "CallbackCancelled";
  851. case WGPUDeviceLostReason_FailedCreation: return "FailedCreation";
  852. default: return "Unknown";
  853. }
  854. }
  855. #elif !defined(__EMSCRIPTEN__)
  856. const char* ImGui_ImplWGPU_GetLogLevelName(WGPULogLevel level)
  857. {
  858. switch (level)
  859. {
  860. case WGPULogLevel_Error: return "Error";
  861. case WGPULogLevel_Warn: return "Warn";
  862. case WGPULogLevel_Info: return "Info";
  863. case WGPULogLevel_Debug: return "Debug";
  864. case WGPULogLevel_Trace: return "Trace";
  865. default: return "Unknown";
  866. }
  867. }
  868. #endif
  869. const char* ImGui_ImplWGPU_GetBackendTypeName(WGPUBackendType type)
  870. {
  871. switch (type)
  872. {
  873. case WGPUBackendType_WebGPU: return "WebGPU";
  874. case WGPUBackendType_D3D11: return "D3D11";
  875. case WGPUBackendType_D3D12: return "D3D12";
  876. case WGPUBackendType_Metal: return "Metal";
  877. case WGPUBackendType_Vulkan: return "Vulkan";
  878. case WGPUBackendType_OpenGL: return "OpenGL";
  879. case WGPUBackendType_OpenGLES: return "OpenGLES";
  880. default: return "Unknown";
  881. }
  882. }
  883. const char* ImGui_ImplWGPU_GetAdapterTypeName(WGPUAdapterType type)
  884. {
  885. switch (type)
  886. {
  887. case WGPUAdapterType_DiscreteGPU: return "DiscreteGPU";
  888. case WGPUAdapterType_IntegratedGPU: return "IntegratedGPU";
  889. case WGPUAdapterType_CPU: return "CPU";
  890. default: return "Unknown";
  891. }
  892. }
  893. void ImGui_ImplWGPU_DebugPrintAdapterInfo(const WGPUAdapter& adapter)
  894. {
  895. WGPUAdapterInfo info = {};
  896. wgpuAdapterGetInfo(adapter, &info);
  897. printf("description: \"%.*s\"\n", (int)info.description.length, info.description.data);
  898. printf("vendor: \"%.*s\", vendorID: %x\n", (int)info.vendor.length, info.vendor.data, info.vendorID);
  899. printf("architecture: \"%.*s\"\n", (int) info.architecture.length, info.architecture.data);
  900. printf("device: \"%.*s\", deviceID: %x\n", (int)info.device.length, info.device.data, info.deviceID);
  901. printf("backendType: \"%s\"\n", ImGui_ImplWGPU_GetBackendTypeName(info.backendType));
  902. printf("adapterType: \"%s\"\n", ImGui_ImplWGPU_GetAdapterTypeName(info.adapterType));
  903. wgpuAdapterInfoFreeMembers(info);
  904. }
  905. #ifndef __EMSCRIPTEN__
  906. #if defined(__APPLE__)
  907. // MacOS specific: is necessary to compile with "-x objective-c++" flags
  908. // (e.g. using cmake: set_source_files_properties(${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") )
  909. #include <Cocoa/Cocoa.h>
  910. #include <QuartzCore/CAMetalLayer.h>
  911. #endif
  912. WGPUSurface ImGui_ImplWGPU_CreateWGPUSurfaceHelper(ImGui_ImplWGPU_CreateSurfaceInfo* info)
  913. {
  914. WGPUSurfaceDescriptor surface_descriptor = {};
  915. WGPUSurface surface = {};
  916. #if defined(__APPLE__)
  917. if (strcmp(info->System, "cocoa") == 0)
  918. {
  919. IM_ASSERT(info->RawWindow != nullptr);
  920. NSWindow* ns_window = (NSWindow*)info->RawWindow;
  921. id metal_layer = [CAMetalLayer layer];
  922. [ns_window.contentView setWantsLayer : YES] ;
  923. [ns_window.contentView setLayer : metal_layer] ;
  924. WGPUSurfaceSourceMetalLayer surface_src_metal = {};
  925. surface_src_metal.chain.sType = WGPUSType_SurfaceSourceMetalLayer;
  926. surface_src_metal.layer = metal_layer;
  927. surface_descriptor.nextInChain = &surface_src_metal.chain;
  928. surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor);
  929. }
  930. #elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  931. if (strcmp(info->System, "wayland") == 0)
  932. {
  933. IM_ASSERT(info->RawDisplay != nullptr && info->RawSurface != nullptr);
  934. WGPUSurfaceSourceWaylandSurface surface_src_wayland = {};
  935. surface_src_wayland.chain.sType = WGPUSType_SurfaceSourceWaylandSurface;
  936. surface_src_wayland.display = info->RawDisplay;
  937. surface_src_wayland.surface = info->RawSurface;
  938. surface_descriptor.nextInChain = &surface_src_wayland.chain;
  939. surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor);
  940. }
  941. else if (strcmp(info->System, "x11") == 0)
  942. {
  943. IM_ASSERT(info->RawDisplay != nullptr && info->RawWindow != nullptr);
  944. WGPUSurfaceSourceXlibWindow surface_src_xlib = {};
  945. surface_src_xlib.chain.sType = WGPUSType_SurfaceSourceXlibWindow;
  946. surface_src_xlib.display = info->RawDisplay;
  947. surface_src_xlib.window = (uint64_t)info->RawWindow;
  948. surface_descriptor.nextInChain = &surface_src_xlib.chain;
  949. surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor);
  950. }
  951. #elif defined(_WIN32)
  952. if (strcmp(info->System, "win32") == 0)
  953. {
  954. IM_ASSERT(info->RawWindow != nullptr && info->RawInstance != nullptr);
  955. WGPUSurfaceSourceWindowsHWND surface_src_hwnd = {};
  956. surface_src_hwnd.chain.sType = WGPUSType_SurfaceSourceWindowsHWND;
  957. surface_src_hwnd.hinstance = info->RawInstance;
  958. surface_src_hwnd.hwnd = info->RawWindow;
  959. surface_descriptor.nextInChain = &surface_src_hwnd.chain;
  960. surface = wgpuInstanceCreateSurface(info->Instance, &surface_descriptor);
  961. }
  962. #else
  963. #error "Unsupported WebGPU native platform!"
  964. #endif
  965. return surface;
  966. }
  967. #endif // #ifndef __EMSCRIPTEN__
  968. //-----------------------------------------------------------------------------
  969. #endif // #ifndef IMGUI_DISABLE