Debian Codegraph @

subprojects/imgui-1.91.6/backends/imgui_impl_wgpu.cpp

raw
1 // dear imgui: Renderer for WebGPU
2 // This needs to be used along with a Platform Binding (e.g. GLFW)
3 // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.)
4
5 // Implemented features:
6 // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
7 // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
8 // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
9
10 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12 // Learn about Dear ImGui:
13 // - FAQ https://dearimgui.com/faq
14 // - Getting Started https://dearimgui.com/getting-started
15 // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16 // - Introduction, links and more at the top of imgui.cpp
17
18 // CHANGELOG
19 // (minor and older changes stripped away, please see git history for details)
20 // 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083)
21 // 2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
22 // 2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap.
23 // 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)
24 // 2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
25 // 2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
26 // 2024-01-22: Fixed pipeline layout leak. (#7245)
27 // 2024-01-17: Explicitly fill all of WGPUDepthStencilState since standard removed defaults.
28 // 2023-07-13: Use WGPUShaderModuleWGSLDescriptor's code instead of source. use WGPUMipmapFilterMode_Linear instead of WGPUFilterMode_Linear. (#6602)
29 // 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V.
30 // 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).
31 // 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470)
32 // 2022-11-24: Fixed validation error with default depth buffer settings.
33 // 2022-11-10: Fixed rendering when a depth buffer is enabled. Added 'WGPUTextureFormat depth_format' parameter to ImGui_ImplWGPU_Init().
34 // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
35 // 2021-11-29: Passing explicit buffer sizes to wgpuRenderPassEncoderSetVertexBuffer()/wgpuRenderPassEncoderSetIndexBuffer().
36 // 2021-08-24: Fixed for latest specs.
37 // 2021-05-24: Add support for draw_data->FramebufferScale.
38 // 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
39 // 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
40 // 2021-02-18: Change blending equation to preserve alpha in output buffer.
41 // 2021-01-28: Initial version.
42
43 // When targeting native platforms (i.e. NOT emscripten), one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN
44 // or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details.
45 #ifndef __EMSCRIPTEN__
46 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
47 #error exactly one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be defined!
48 #endif
49 #else
50 #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
51 #error neither IMGUI_IMPL_WEBGPU_BACKEND_DAWN nor IMGUI_IMPL_WEBGPU_BACKEND_WGPU may be defined if targeting emscripten!
52 #endif
53 #endif
54
55 #include "imgui.h"
56 #ifndef IMGUI_DISABLE
57 #include "imgui_impl_wgpu.h"
58 #include <limits.h>
59 #include <webgpu/webgpu.h>
60
61 // Dear ImGui prototypes from imgui_internal.h
62 extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0);
63 #define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro).
64
65 // WebGPU data
66 struct RenderResources
67 {
68 WGPUTexture FontTexture = nullptr; // Font texture
69 WGPUTextureView FontTextureView = nullptr; // Texture view for font texture
70 WGPUSampler Sampler = nullptr; // Sampler for the font texture
71 WGPUBuffer Uniforms = nullptr; // Shader uniforms
72 WGPUBindGroup CommonBindGroup = nullptr; // Resources bind-group to bind the common resources to pipeline
73 ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map)
74 WGPUBindGroup ImageBindGroup = nullptr; // Default font-resource of Dear ImGui
75 WGPUBindGroupLayout ImageBindGroupLayout = nullptr; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM
76 };
77
78 struct FrameResources
79 {
80 WGPUBuffer IndexBuffer;
81 WGPUBuffer VertexBuffer;
82 ImDrawIdx* IndexBufferHost;
83 ImDrawVert* VertexBufferHost;
84 int IndexBufferSize;
85 int VertexBufferSize;
86 };
87
88 struct Uniforms
89 {
90 float MVP[4][4];
91 float Gamma;
92 };
93
94 struct ImGui_ImplWGPU_Data
95 {
96 ImGui_ImplWGPU_InitInfo initInfo;
97 WGPUDevice wgpuDevice = nullptr;
98 WGPUQueue defaultQueue = nullptr;
99 WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined;
100 WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined;
101 WGPURenderPipeline pipelineState = nullptr;
102
103 RenderResources renderResources;
104 FrameResources* pFrameResources = nullptr;
105 unsigned int numFramesInFlight = 0;
106 unsigned int frameIndex = UINT_MAX;
107 };
108
109 // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
110 // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
111 static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData()
112 {
113 return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
114 }
115
116 //-----------------------------------------------------------------------------
117 // SHADERS
118 //-----------------------------------------------------------------------------
119
120 static const char __shader_vert_wgsl[] = R"(
121 struct VertexInput {
122 @location(0) position: vec2<f32>,
123 @location(1) uv: vec2<f32>,
124 @location(2) color: vec4<f32>,
125 };
126
127 struct VertexOutput {
128 @builtin(position) position: vec4<f32>,
129 @location(0) color: vec4<f32>,
130 @location(1) uv: vec2<f32>,
131 };
132
133 struct Uniforms {
134 mvp: mat4x4<f32>,
135 gamma: f32,
136 };
137
138 @group(0) @binding(0) var<uniform> uniforms: Uniforms;
139
140 @vertex
141 fn main(in: VertexInput) -> VertexOutput {
142 var out: VertexOutput;
143 out.position = uniforms.mvp * vec4<f32>(in.position, 0.0, 1.0);
144 out.color = in.color;
145 out.uv = in.uv;
146 return out;
147 }
148 )";
149
150 static const char __shader_frag_wgsl[] = R"(
151 struct VertexOutput {
152 @builtin(position) position: vec4<f32>,
153 @location(0) color: vec4<f32>,
154 @location(1) uv: vec2<f32>,
155 };
156
157 struct Uniforms {
158 mvp: mat4x4<f32>,
159 gamma: f32,
160 };
161
162 @group(0) @binding(0) var<uniform> uniforms: Uniforms;
163 @group(0) @binding(1) var s: sampler;
164 @group(1) @binding(0) var t: texture_2d<f32>;
165
166 @fragment
167 fn main(in: VertexOutput) -> @location(0) vec4<f32> {
168 let color = in.color * textureSample(t, s, in.uv);
169 let corrected_color = pow(color.rgb, vec3<f32>(uniforms.gamma));
170 return vec4<f32>(corrected_color, color.a);
171 }
172 )";
173
174 static void SafeRelease(ImDrawIdx*& res)
175 {
176 if (res)
177 delete[] res;
178 res = nullptr;
179 }
180 static void SafeRelease(ImDrawVert*& res)
181 {
182 if (res)
183 delete[] res;
184 res = nullptr;
185 }
186 static void SafeRelease(WGPUBindGroupLayout& res)
187 {
188 if (res)
189 wgpuBindGroupLayoutRelease(res);
190 res = nullptr;
191 }
192 static void SafeRelease(WGPUBindGroup& res)
193 {
194 if (res)
195 wgpuBindGroupRelease(res);
196 res = nullptr;
197 }
198 static void SafeRelease(WGPUBuffer& res)
199 {
200 if (res)
201 wgpuBufferRelease(res);
202 res = nullptr;
203 }
204 static void SafeRelease(WGPUPipelineLayout& res)
205 {
206 if (res)
207 wgpuPipelineLayoutRelease(res);
208 res = nullptr;
209 }
210 static void SafeRelease(WGPURenderPipeline& res)
211 {
212 if (res)
213 wgpuRenderPipelineRelease(res);
214 res = nullptr;
215 }
216 static void SafeRelease(WGPUSampler& res)
217 {
218 if (res)
219 wgpuSamplerRelease(res);
220 res = nullptr;
221 }
222 static void SafeRelease(WGPUShaderModule& res)
223 {
224 if (res)
225 wgpuShaderModuleRelease(res);
226 res = nullptr;
227 }
228 static void SafeRelease(WGPUTextureView& res)
229 {
230 if (res)
231 wgpuTextureViewRelease(res);
232 res = nullptr;
233 }
234 static void SafeRelease(WGPUTexture& res)
235 {
236 if (res)
237 wgpuTextureRelease(res);
238 res = nullptr;
239 }
240
241 static void SafeRelease(RenderResources& res)
242 {
243 SafeRelease(res.FontTexture);
244 SafeRelease(res.FontTextureView);
245 SafeRelease(res.Sampler);
246 SafeRelease(res.Uniforms);
247 SafeRelease(res.CommonBindGroup);
248 SafeRelease(res.ImageBindGroup);
249 SafeRelease(res.ImageBindGroupLayout);
250 };
251
252 static void SafeRelease(FrameResources& res)
253 {
254 SafeRelease(res.IndexBuffer);
255 SafeRelease(res.VertexBuffer);
256 SafeRelease(res.IndexBufferHost);
257 SafeRelease(res.VertexBufferHost);
258 }
259
260 static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const char* wgsl_source)
261 {
262 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
263
264 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
265 WGPUShaderSourceWGSL wgsl_desc = {};
266 wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
267 wgsl_desc.code = { wgsl_source, WGPU_STRLEN };
268 #else
269 WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
270 wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
271 wgsl_desc.code = wgsl_source;
272 #endif
273
274 WGPUShaderModuleDescriptor desc = {};
275 desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgsl_desc);
276
277 WGPUProgrammableStageDescriptor stage_desc = {};
278 stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc);
279 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
280 stage_desc.entryPoint = { "main", WGPU_STRLEN };
281 #else
282 stage_desc.entryPoint = "main";
283 #endif
284 return stage_desc;
285 }
286
287 static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture)
288 {
289 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
290 WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } };
291
292 WGPUBindGroupDescriptor image_bg_descriptor = {};
293 image_bg_descriptor.layout = layout;
294 image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry);
295 image_bg_descriptor.entries = image_bg_entries;
296 return wgpuDeviceCreateBindGroup(bd->wgpuDevice, &image_bg_descriptor);
297 }
298
299 static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr)
300 {
301 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
302
303 // Setup orthographic projection matrix into our constant buffer
304 // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
305 {
306 float L = draw_data->DisplayPos.x;
307 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
308 float T = draw_data->DisplayPos.y;
309 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
310 float mvp[4][4] =
311 {
312 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
313 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
314 { 0.0f, 0.0f, 0.5f, 0.0f },
315 { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
316 };
317 wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, MVP), mvp, sizeof(Uniforms::MVP));
318 float gamma;
319 switch (bd->renderTargetFormat)
320 {
321 case WGPUTextureFormat_ASTC10x10UnormSrgb:
322 case WGPUTextureFormat_ASTC10x5UnormSrgb:
323 case WGPUTextureFormat_ASTC10x6UnormSrgb:
324 case WGPUTextureFormat_ASTC10x8UnormSrgb:
325 case WGPUTextureFormat_ASTC12x10UnormSrgb:
326 case WGPUTextureFormat_ASTC12x12UnormSrgb:
327 case WGPUTextureFormat_ASTC4x4UnormSrgb:
328 case WGPUTextureFormat_ASTC5x5UnormSrgb:
329 case WGPUTextureFormat_ASTC6x5UnormSrgb:
330 case WGPUTextureFormat_ASTC6x6UnormSrgb:
331 case WGPUTextureFormat_ASTC8x5UnormSrgb:
332 case WGPUTextureFormat_ASTC8x6UnormSrgb:
333 case WGPUTextureFormat_ASTC8x8UnormSrgb:
334 case WGPUTextureFormat_BC1RGBAUnormSrgb:
335 case WGPUTextureFormat_BC2RGBAUnormSrgb:
336 case WGPUTextureFormat_BC3RGBAUnormSrgb:
337 case WGPUTextureFormat_BC7RGBAUnormSrgb:
338 case WGPUTextureFormat_BGRA8UnormSrgb:
339 case WGPUTextureFormat_ETC2RGB8A1UnormSrgb:
340 case WGPUTextureFormat_ETC2RGB8UnormSrgb:
341 case WGPUTextureFormat_ETC2RGBA8UnormSrgb:
342 case WGPUTextureFormat_RGBA8UnormSrgb:
343 gamma = 2.2f;
344 break;
345 default:
346 gamma = 1.0f;
347 }
348 wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, Gamma), &gamma, sizeof(Uniforms::Gamma));
349 }
350
351 // Setup viewport
352 wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1);
353
354 // Bind shader and vertex buffers
355 wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize * sizeof(ImDrawVert));
356 wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize * sizeof(ImDrawIdx));
357 wgpuRenderPassEncoderSetPipeline(ctx, bd->pipelineState);
358 wgpuRenderPassEncoderSetBindGroup(ctx, 0, bd->renderResources.CommonBindGroup, 0, nullptr);
359
360 // Setup blend factor
361 WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f };
362 wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color);
363 }
364
365 // Render function
366 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
367 void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
368 {
369 // Avoid rendering when minimized
370 int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
371 int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
372 if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0)
373 return;
374
375 // FIXME: Assuming that this only gets called once per frame!
376 // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
377 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
378 bd->frameIndex = bd->frameIndex + 1;
379 FrameResources* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
380
381 // Create and grow vertex/index buffers if needed
382 if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
383 {
384 if (fr->VertexBuffer)
385 {
386 wgpuBufferDestroy(fr->VertexBuffer);
387 wgpuBufferRelease(fr->VertexBuffer);
388 }
389 SafeRelease(fr->VertexBufferHost);
390 fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
391
392 WGPUBufferDescriptor vb_desc =
393 {
394 nullptr,
395 "Dear ImGui Vertex buffer",
396 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
397 WGPU_STRLEN,
398 #endif
399 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
400 MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4),
401 false
402 };
403 fr->VertexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &vb_desc);
404 if (!fr->VertexBuffer)
405 return;
406
407 fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize];
408 }
409 if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
410 {
411 if (fr->IndexBuffer)
412 {
413 wgpuBufferDestroy(fr->IndexBuffer);
414 wgpuBufferRelease(fr->IndexBuffer);
415 }
416 SafeRelease(fr->IndexBufferHost);
417 fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
418
419 WGPUBufferDescriptor ib_desc =
420 {
421 nullptr,
422 "Dear ImGui Index buffer",
423 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
424 WGPU_STRLEN,
425 #endif
426 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
427 MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4),
428 false
429 };
430 fr->IndexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ib_desc);
431 if (!fr->IndexBuffer)
432 return;
433
434 fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize];
435 }
436
437 // Upload vertex/index data into a single contiguous GPU buffer
438 ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost;
439 ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
440 for (int n = 0; n < draw_data->CmdListsCount; n++)
441 {
442 const ImDrawList* draw_list = draw_data->CmdLists[n];
443 memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
444 memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
445 vtx_dst += draw_list->VtxBuffer.Size;
446 idx_dst += draw_list->IdxBuffer.Size;
447 }
448 int64_t vb_write_size = MEMALIGN((char*)vtx_dst - (char*)fr->VertexBufferHost, 4);
449 int64_t ib_write_size = MEMALIGN((char*)idx_dst - (char*)fr->IndexBufferHost, 4);
450 wgpuQueueWriteBuffer(bd->defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size);
451 wgpuQueueWriteBuffer(bd->defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size);
452
453 // Setup desired render state
454 ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
455
456 // Setup render state structure (for callbacks and custom texture bindings)
457 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
458 ImGui_ImplWGPU_RenderState render_state;
459 render_state.Device = bd->wgpuDevice;
460 render_state.RenderPassEncoder = pass_encoder;
461 platform_io.Renderer_RenderState = &render_state;
462
463 // Render command lists
464 // (Because we merged all buffers into a single one, we maintain our own offset into them)
465 int global_vtx_offset = 0;
466 int global_idx_offset = 0;
467 ImVec2 clip_scale = draw_data->FramebufferScale;
468 ImVec2 clip_off = draw_data->DisplayPos;
469 for (int n = 0; n < draw_data->CmdListsCount; n++)
470 {
471 const ImDrawList* draw_list = draw_data->CmdLists[n];
472 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
473 {
474 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
475 if (pcmd->UserCallback != nullptr)
476 {
477 // User callback, registered via ImDrawList::AddCallback()
478 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
479 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
480 ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
481 else
482 pcmd->UserCallback(draw_list, pcmd);
483 }
484 else
485 {
486 // Bind custom texture
487 ImTextureID tex_id = pcmd->GetTexID();
488 ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id));
489 auto bind_group = bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash);
490 if (bind_group)
491 {
492 wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr);
493 }
494 else
495 {
496 WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id);
497 bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group);
498 wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, nullptr);
499 }
500
501 // Project scissor/clipping rectangles into framebuffer space
502 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
503 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
504
505 // Clamp to viewport as wgpuRenderPassEncoderSetScissorRect() won't accept values that are off bounds
506 if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
507 if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
508 if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
509 if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
510 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
511 continue;
512
513 // Apply scissor/clipping rectangle, Draw
514 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));
515 wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
516 }
517 }
518 global_idx_offset += draw_list->IdxBuffer.Size;
519 global_vtx_offset += draw_list->VtxBuffer.Size;
520 }
521 platform_io.Renderer_RenderState = nullptr;
522 }
523
524 static void ImGui_ImplWGPU_CreateFontsTexture()
525 {
526 // Build texture atlas
527 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
528 ImGuiIO& io = ImGui::GetIO();
529 unsigned char* pixels;
530 int width, height, size_pp;
531 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &size_pp);
532
533 // Upload texture to graphics system
534 {
535 WGPUTextureDescriptor tex_desc = {};
536 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
537 tex_desc.label = { "Dear ImGui Font Texture", WGPU_STRLEN };
538 #else
539 tex_desc.label = "Dear ImGui Font Texture";
540 #endif
541 tex_desc.dimension = WGPUTextureDimension_2D;
542 tex_desc.size.width = width;
543 tex_desc.size.height = height;
544 tex_desc.size.depthOrArrayLayers = 1;
545 tex_desc.sampleCount = 1;
546 tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
547 tex_desc.mipLevelCount = 1;
548 tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding;
549 bd->renderResources.FontTexture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc);
550
551 WGPUTextureViewDescriptor tex_view_desc = {};
552 tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
553 tex_view_desc.dimension = WGPUTextureViewDimension_2D;
554 tex_view_desc.baseMipLevel = 0;
555 tex_view_desc.mipLevelCount = 1;
556 tex_view_desc.baseArrayLayer = 0;
557 tex_view_desc.arrayLayerCount = 1;
558 tex_view_desc.aspect = WGPUTextureAspect_All;
559 bd->renderResources.FontTextureView = wgpuTextureCreateView(bd->renderResources.FontTexture, &tex_view_desc);
560 }
561
562 // Upload texture data
563 {
564 WGPUImageCopyTexture dst_view = {};
565 dst_view.texture = bd->renderResources.FontTexture;
566 dst_view.mipLevel = 0;
567 dst_view.origin = { 0, 0, 0 };
568 dst_view.aspect = WGPUTextureAspect_All;
569 WGPUTextureDataLayout layout = {};
570 layout.offset = 0;
571 layout.bytesPerRow = width * size_pp;
572 layout.rowsPerImage = height;
573 WGPUExtent3D size = { (uint32_t)width, (uint32_t)height, 1 };
574 wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size);
575 }
576
577 // Create the associated sampler
578 // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
579 {
580 WGPUSamplerDescriptor sampler_desc = {};
581 sampler_desc.minFilter = WGPUFilterMode_Linear;
582 sampler_desc.magFilter = WGPUFilterMode_Linear;
583 sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear;
584 sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge;
585 sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge;
586 sampler_desc.addressModeW = WGPUAddressMode_ClampToEdge;
587 sampler_desc.maxAnisotropy = 1;
588 bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc);
589 }
590
591 // Store our identifier
592 static_assert(sizeof(ImTextureID) >= sizeof(bd->renderResources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
593 io.Fonts->SetTexID((ImTextureID)bd->renderResources.FontTextureView);
594 }
595
596 static void ImGui_ImplWGPU_CreateUniformBuffer()
597 {
598 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
599 WGPUBufferDescriptor ub_desc =
600 {
601 nullptr,
602 "Dear ImGui Uniform buffer",
603 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
604 WGPU_STRLEN,
605 #endif
606 WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
607 MEMALIGN(sizeof(Uniforms), 16),
608 false
609 };
610 bd->renderResources.Uniforms = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ub_desc);
611 }
612
613 bool ImGui_ImplWGPU_CreateDeviceObjects()
614 {
615 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
616 if (!bd->wgpuDevice)
617 return false;
618 if (bd->pipelineState)
619 ImGui_ImplWGPU_InvalidateDeviceObjects();
620
621 // Create render pipeline
622 WGPURenderPipelineDescriptor graphics_pipeline_desc = {};
623 graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
624 graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
625 graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
626 graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
627 graphics_pipeline_desc.multisample = bd->initInfo.PipelineMultisampleState;
628
629 // Bind group layouts
630 WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {};
631 common_bg_layout_entries[0].binding = 0;
632 common_bg_layout_entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
633 common_bg_layout_entries[0].buffer.type = WGPUBufferBindingType_Uniform;
634 common_bg_layout_entries[1].binding = 1;
635 common_bg_layout_entries[1].visibility = WGPUShaderStage_Fragment;
636 common_bg_layout_entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
637
638 WGPUBindGroupLayoutEntry image_bg_layout_entries[1] = {};
639 image_bg_layout_entries[0].binding = 0;
640 image_bg_layout_entries[0].visibility = WGPUShaderStage_Fragment;
641 image_bg_layout_entries[0].texture.sampleType = WGPUTextureSampleType_Float;
642 image_bg_layout_entries[0].texture.viewDimension = WGPUTextureViewDimension_2D;
643
644 WGPUBindGroupLayoutDescriptor common_bg_layout_desc = {};
645 common_bg_layout_desc.entryCount = 2;
646 common_bg_layout_desc.entries = common_bg_layout_entries;
647
648 WGPUBindGroupLayoutDescriptor image_bg_layout_desc = {};
649 image_bg_layout_desc.entryCount = 1;
650 image_bg_layout_desc.entries = image_bg_layout_entries;
651
652 WGPUBindGroupLayout bg_layouts[2];
653 bg_layouts[0] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &common_bg_layout_desc);
654 bg_layouts[1] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &image_bg_layout_desc);
655
656 WGPUPipelineLayoutDescriptor layout_desc = {};
657 layout_desc.bindGroupLayoutCount = 2;
658 layout_desc.bindGroupLayouts = bg_layouts;
659 graphics_pipeline_desc.layout = wgpuDeviceCreatePipelineLayout(bd->wgpuDevice, &layout_desc);
660
661 // Create the vertex shader
662 WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_vert_wgsl);
663 graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
664 graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
665
666 // Vertex input configuration
667 WGPUVertexAttribute attribute_desc[] =
668 {
669 { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
670 { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
671 { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
672 };
673
674 WGPUVertexBufferLayout buffer_layouts[1];
675 buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
676 buffer_layouts[0].stepMode = WGPUVertexStepMode_Vertex;
677 buffer_layouts[0].attributeCount = 3;
678 buffer_layouts[0].attributes = attribute_desc;
679
680 graphics_pipeline_desc.vertex.bufferCount = 1;
681 graphics_pipeline_desc.vertex.buffers = buffer_layouts;
682
683 // Create the pixel shader
684 WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_frag_wgsl);
685
686 // Create the blending setup
687 WGPUBlendState blend_state = {};
688 blend_state.alpha.operation = WGPUBlendOperation_Add;
689 blend_state.alpha.srcFactor = WGPUBlendFactor_One;
690 blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
691 blend_state.color.operation = WGPUBlendOperation_Add;
692 blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
693 blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
694
695 WGPUColorTargetState color_state = {};
696 color_state.format = bd->renderTargetFormat;
697 color_state.blend = &blend_state;
698 color_state.writeMask = WGPUColorWriteMask_All;
699
700 WGPUFragmentState fragment_state = {};
701 fragment_state.module = pixel_shader_desc.module;
702 fragment_state.entryPoint = pixel_shader_desc.entryPoint;
703 fragment_state.targetCount = 1;
704 fragment_state.targets = &color_state;
705
706 graphics_pipeline_desc.fragment = &fragment_state;
707
708 // Create depth-stencil State
709 WGPUDepthStencilState depth_stencil_state = {};
710 depth_stencil_state.format = bd->depthStencilFormat;
711 #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
712 depth_stencil_state.depthWriteEnabled = WGPUOptionalBool_False;
713 #else
714 depth_stencil_state.depthWriteEnabled = false;
715 #endif
716 depth_stencil_state.depthCompare = WGPUCompareFunction_Always;
717 depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always;
718 depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep;
719 depth_stencil_state.stencilFront.depthFailOp = WGPUStencilOperation_Keep;
720 depth_stencil_state.stencilFront.passOp = WGPUStencilOperation_Keep;
721 depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always;
722 depth_stencil_state.stencilBack.failOp = WGPUStencilOperation_Keep;
723 depth_stencil_state.stencilBack.depthFailOp = WGPUStencilOperation_Keep;
724 depth_stencil_state.stencilBack.passOp = WGPUStencilOperation_Keep;
725
726 // Configure disabled depth-stencil state
727 graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state;
728
729 bd->pipelineState = wgpuDeviceCreateRenderPipeline(bd->wgpuDevice, &graphics_pipeline_desc);
730
731 ImGui_ImplWGPU_CreateFontsTexture();
732 ImGui_ImplWGPU_CreateUniformBuffer();
733
734 // Create resource bind group
735 WGPUBindGroupEntry common_bg_entries[] =
736 {
737 { nullptr, 0, bd->renderResources.Uniforms, 0, MEMALIGN(sizeof(Uniforms), 16), 0, 0 },
738 { nullptr, 1, 0, 0, 0, bd->renderResources.Sampler, 0 },
739 };
740
741 WGPUBindGroupDescriptor common_bg_descriptor = {};
742 common_bg_descriptor.layout = bg_layouts[0];
743 common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
744 common_bg_descriptor.entries = common_bg_entries;
745 bd->renderResources.CommonBindGroup = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor);
746
747 WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], bd->renderResources.FontTextureView);
748 bd->renderResources.ImageBindGroup = image_bind_group;
749 bd->renderResources.ImageBindGroupLayout = bg_layouts[1];
750 bd->renderResources.ImageBindGroups.SetVoidPtr(ImHashData(&bd->renderResources.FontTextureView, sizeof(ImTextureID)), image_bind_group);
751
752 SafeRelease(vertex_shader_desc.module);
753 SafeRelease(pixel_shader_desc.module);
754 SafeRelease(graphics_pipeline_desc.layout);
755 SafeRelease(bg_layouts[0]);
756
757 return true;
758 }
759
760 void ImGui_ImplWGPU_InvalidateDeviceObjects()
761 {
762 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
763 if (!bd->wgpuDevice)
764 return;
765
766 SafeRelease(bd->pipelineState);
767 SafeRelease(bd->renderResources);
768
769 ImGuiIO& io = ImGui::GetIO();
770 io.Fonts->SetTexID(0); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
771
772 for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
773 SafeRelease(bd->pFrameResources[i]);
774 }
775
776 bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info)
777 {
778 ImGuiIO& io = ImGui::GetIO();
779 IMGUI_CHECKVERSION();
780 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
781
782 // Setup backend capabilities flags
783 ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)();
784 io.BackendRendererUserData = (void*)bd;
785 #if defined(__EMSCRIPTEN__)
786 io.BackendRendererName = "imgui_impl_webgpu_emscripten";
787 #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
788 io.BackendRendererName = "imgui_impl_webgpu_dawn";
789 #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
790 io.BackendRendererName = "imgui_impl_webgpu_wgpu";
791 #else
792 io.BackendRendererName = "imgui_impl_webgpu";
793 #endif
794 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
795
796 bd->initInfo = *init_info;
797 bd->wgpuDevice = init_info->Device;
798 bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice);
799 bd->renderTargetFormat = init_info->RenderTargetFormat;
800 bd->depthStencilFormat = init_info->DepthStencilFormat;
801 bd->numFramesInFlight = init_info->NumFramesInFlight;
802 bd->frameIndex = UINT_MAX;
803
804 bd->renderResources.FontTexture = nullptr;
805 bd->renderResources.FontTextureView = nullptr;
806 bd->renderResources.Sampler = nullptr;
807 bd->renderResources.Uniforms = nullptr;
808 bd->renderResources.CommonBindGroup = nullptr;
809 bd->renderResources.ImageBindGroups.Data.reserve(100);
810 bd->renderResources.ImageBindGroup = nullptr;
811 bd->renderResources.ImageBindGroupLayout = nullptr;
812
813 // Create buffers with a default size (they will later be grown as needed)
814 bd->pFrameResources = new FrameResources[bd->numFramesInFlight];
815 for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
816 {
817 FrameResources* fr = &bd->pFrameResources[i];
818 fr->IndexBuffer = nullptr;
819 fr->VertexBuffer = nullptr;
820 fr->IndexBufferHost = nullptr;
821 fr->VertexBufferHost = nullptr;
822 fr->IndexBufferSize = 10000;
823 fr->VertexBufferSize = 5000;
824 }
825
826 return true;
827 }
828
829 void ImGui_ImplWGPU_Shutdown()
830 {
831 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
832 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
833 ImGuiIO& io = ImGui::GetIO();
834
835 ImGui_ImplWGPU_InvalidateDeviceObjects();
836 delete[] bd->pFrameResources;
837 bd->pFrameResources = nullptr;
838 wgpuQueueRelease(bd->defaultQueue);
839 bd->wgpuDevice = nullptr;
840 bd->numFramesInFlight = 0;
841 bd->frameIndex = UINT_MAX;
842
843 io.BackendRendererName = nullptr;
844 io.BackendRendererUserData = nullptr;
845 io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
846 IM_DELETE(bd);
847 }
848
849 void ImGui_ImplWGPU_NewFrame()
850 {
851 ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
852 if (!bd->pipelineState)
853 ImGui_ImplWGPU_CreateDeviceObjects();
854 }
855
856 //-----------------------------------------------------------------------------
857
858 #endif // #ifndef IMGUI_DISABLE