imgui_impl_wgpu.cpp 33 KB

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