imgui_impl_wgpu.cpp 31 KB

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