imgui_impl_wgpu.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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: Support for large meshes (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. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
  10. // Read online: https://github.com/ocornut/imgui/tree/master/docs
  11. // CHANGELOG
  12. // (minor and older changes stripped away, please see git history for details)
  13. // 2021-11-29: Passing explicit buffer sizes to wgpuRenderPassEncoderSetVertexBuffer()/wgpuRenderPassEncoderSetIndexBuffer().
  14. // 2021-08-24: Fix for latest specs.
  15. // 2021-05-24: Add support for draw_data->FramebufferScale.
  16. // 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  17. // 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
  18. // 2021-02-18: Change blending equation to preserve alpha in output buffer.
  19. // 2021-01-28: Initial version.
  20. #include "imgui.h"
  21. #include "imgui_impl_wgpu.h"
  22. #include <limits.h>
  23. #include <webgpu/webgpu.h>
  24. #define HAS_EMSCRIPTEN_VERSION(major, minor, tiny) (__EMSCRIPTEN_major__ > (major) || (__EMSCRIPTEN_major__ == (major) && __EMSCRIPTEN_minor__ > (minor)) || (__EMSCRIPTEN_major__ == (major) && __EMSCRIPTEN_minor__ == (minor) && __EMSCRIPTEN_tiny__ >= (tiny)))
  25. #if defined(__EMSCRIPTEN__) && !HAS_EMSCRIPTEN_VERSION(2, 0, 20)
  26. #error "Requires at least emscripten 2.0.20"
  27. #endif
  28. // Dear ImGui prototypes from imgui_internal.h
  29. extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0);
  30. // WebGPU data
  31. static WGPUDevice g_wgpuDevice = NULL;
  32. static WGPUQueue g_defaultQueue = NULL;
  33. static WGPUTextureFormat g_renderTargetFormat = WGPUTextureFormat_Undefined;
  34. static WGPURenderPipeline g_pipelineState = NULL;
  35. struct RenderResources
  36. {
  37. WGPUTexture FontTexture; // Font texture
  38. WGPUTextureView FontTextureView; // Texture view for font texture
  39. WGPUSampler Sampler; // Sampler for the font texture
  40. WGPUBuffer Uniforms; // Shader uniforms
  41. WGPUBindGroup CommonBindGroup; // Resources bind-group to bind the common resources to pipeline
  42. ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map)
  43. WGPUBindGroup ImageBindGroup; // Default font-resource of Dear ImGui
  44. WGPUBindGroupLayout ImageBindGroupLayout; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM
  45. };
  46. static RenderResources g_resources;
  47. struct FrameResources
  48. {
  49. WGPUBuffer IndexBuffer;
  50. WGPUBuffer VertexBuffer;
  51. ImDrawIdx* IndexBufferHost;
  52. ImDrawVert* VertexBufferHost;
  53. int IndexBufferSize;
  54. int VertexBufferSize;
  55. };
  56. static FrameResources* g_pFrameResources = NULL;
  57. static unsigned int g_numFramesInFlight = 0;
  58. static unsigned int g_frameIndex = UINT_MAX;
  59. struct Uniforms
  60. {
  61. float MVP[4][4];
  62. };
  63. //-----------------------------------------------------------------------------
  64. // SHADERS
  65. //-----------------------------------------------------------------------------
  66. // glsl_shader.vert, compiled with:
  67. // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
  68. /*
  69. #version 450 core
  70. layout(location = 0) in vec2 aPos;
  71. layout(location = 1) in vec2 aUV;
  72. layout(location = 2) in vec4 aColor;
  73. layout(set=0, binding = 0) uniform transform { mat4 mvp; };
  74. out gl_PerVertex { vec4 gl_Position; };
  75. layout(location = 0) out struct { vec4 Color; vec2 UV; } Out;
  76. void main()
  77. {
  78. Out.Color = aColor;
  79. Out.UV = aUV;
  80. gl_Position = mvp * vec4(aPos, 0, 1);
  81. }
  82. */
  83. static uint32_t __glsl_shader_vert_spv[] =
  84. {
  85. 0x07230203,0x00010000,0x00080007,0x0000002c,0x00000000,0x00020011,0x00000001,0x0006000b,
  86. 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
  87. 0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015,
  88. 0x0000001b,0x00000023,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
  89. 0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43,
  90. 0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f,
  91. 0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005,
  92. 0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000,
  93. 0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00050005,0x0000001d,
  94. 0x6e617274,0x726f6673,0x0000006d,0x00040006,0x0000001d,0x00000000,0x0070766d,0x00030005,
  95. 0x0000001f,0x00000000,0x00040005,0x00000023,0x736f5061,0x00000000,0x00040047,0x0000000b,
  96. 0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015,
  97. 0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047,
  98. 0x00000019,0x00000002,0x00040048,0x0000001d,0x00000000,0x00000005,0x00050048,0x0000001d,
  99. 0x00000000,0x00000023,0x00000000,0x00050048,0x0000001d,0x00000000,0x00000007,0x00000010,
  100. 0x00030047,0x0000001d,0x00000002,0x00040047,0x0000001f,0x00000022,0x00000000,0x00040047,
  101. 0x0000001f,0x00000021,0x00000000,0x00040047,0x00000023,0x0000001e,0x00000000,0x00020013,
  102. 0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,
  103. 0x00000007,0x00000006,0x00000004,0x00040017,0x00000008,0x00000006,0x00000002,0x0004001e,
  104. 0x00000009,0x00000007,0x00000008,0x00040020,0x0000000a,0x00000003,0x00000009,0x0004003b,
  105. 0x0000000a,0x0000000b,0x00000003,0x00040015,0x0000000c,0x00000020,0x00000001,0x0004002b,
  106. 0x0000000c,0x0000000d,0x00000000,0x00040020,0x0000000e,0x00000001,0x00000007,0x0004003b,
  107. 0x0000000e,0x0000000f,0x00000001,0x00040020,0x00000011,0x00000003,0x00000007,0x0004002b,
  108. 0x0000000c,0x00000013,0x00000001,0x00040020,0x00000014,0x00000001,0x00000008,0x0004003b,
  109. 0x00000014,0x00000015,0x00000001,0x00040020,0x00000017,0x00000003,0x00000008,0x0003001e,
  110. 0x00000019,0x00000007,0x00040020,0x0000001a,0x00000003,0x00000019,0x0004003b,0x0000001a,
  111. 0x0000001b,0x00000003,0x00040018,0x0000001c,0x00000007,0x00000004,0x0003001e,0x0000001d,
  112. 0x0000001c,0x00040020,0x0000001e,0x00000002,0x0000001d,0x0004003b,0x0000001e,0x0000001f,
  113. 0x00000002,0x00040020,0x00000020,0x00000002,0x0000001c,0x0004003b,0x00000014,0x00000023,
  114. 0x00000001,0x0004002b,0x00000006,0x00000025,0x00000000,0x0004002b,0x00000006,0x00000026,
  115. 0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,
  116. 0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012,0x0000000b,
  117. 0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016,0x00000015,
  118. 0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018,0x00000016,
  119. 0x00050041,0x00000020,0x00000021,0x0000001f,0x0000000d,0x0004003d,0x0000001c,0x00000022,
  120. 0x00000021,0x0004003d,0x00000008,0x00000024,0x00000023,0x00050051,0x00000006,0x00000027,
  121. 0x00000024,0x00000000,0x00050051,0x00000006,0x00000028,0x00000024,0x00000001,0x00070050,
  122. 0x00000007,0x00000029,0x00000027,0x00000028,0x00000025,0x00000026,0x00050091,0x00000007,
  123. 0x0000002a,0x00000022,0x00000029,0x00050041,0x00000011,0x0000002b,0x0000001b,0x0000000d,
  124. 0x0003003e,0x0000002b,0x0000002a,0x000100fd,0x00010038
  125. };
  126. // glsl_shader.frag, compiled with:
  127. // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
  128. /*
  129. #version 450 core
  130. layout(location = 0) out vec4 fColor;
  131. layout(set=0, binding=1) uniform sampler s;
  132. layout(set=1, binding=0) uniform texture2D t;
  133. layout(location = 0) in struct { vec4 Color; vec2 UV; } In;
  134. void main()
  135. {
  136. fColor = In.Color * texture(sampler2D(t, s), In.UV.st);
  137. }
  138. */
  139. static uint32_t __glsl_shader_frag_spv[] =
  140. {
  141. 0x07230203,0x00010000,0x00080007,0x00000023,0x00000000,0x00020011,0x00000001,0x0006000b,
  142. 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
  143. 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010,
  144. 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
  145. 0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000,
  146. 0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001,
  147. 0x00005655,0x00030005,0x0000000d,0x00006e49,0x00030005,0x00000015,0x00000074,0x00030005,
  148. 0x00000019,0x00000073,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,
  149. 0x0000001e,0x00000000,0x00040047,0x00000015,0x00000022,0x00000001,0x00040047,0x00000015,
  150. 0x00000021,0x00000000,0x00040047,0x00000019,0x00000022,0x00000000,0x00040047,0x00000019,
  151. 0x00000021,0x00000001,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,
  152. 0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,
  153. 0x00000003,0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,
  154. 0x00000006,0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,
  155. 0x00000001,0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,
  156. 0x00000020,0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,
  157. 0x00000001,0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,
  158. 0x00000000,0x00000001,0x00000000,0x00040020,0x00000014,0x00000000,0x00000013,0x0004003b,
  159. 0x00000014,0x00000015,0x00000000,0x0002001a,0x00000017,0x00040020,0x00000018,0x00000000,
  160. 0x00000017,0x0004003b,0x00000018,0x00000019,0x00000000,0x0003001b,0x0000001b,0x00000013,
  161. 0x0004002b,0x0000000e,0x0000001d,0x00000001,0x00040020,0x0000001e,0x00000001,0x0000000a,
  162. 0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,
  163. 0x00000010,0x00000011,0x0000000d,0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,
  164. 0x0004003d,0x00000013,0x00000016,0x00000015,0x0004003d,0x00000017,0x0000001a,0x00000019,
  165. 0x00050056,0x0000001b,0x0000001c,0x00000016,0x0000001a,0x00050041,0x0000001e,0x0000001f,
  166. 0x0000000d,0x0000001d,0x0004003d,0x0000000a,0x00000020,0x0000001f,0x00050057,0x00000007,
  167. 0x00000021,0x0000001c,0x00000020,0x00050085,0x00000007,0x00000022,0x00000012,0x00000021,
  168. 0x0003003e,0x00000009,0x00000022,0x000100fd,0x00010038
  169. };
  170. static void SafeRelease(ImDrawIdx*& res)
  171. {
  172. if (res)
  173. delete[] res;
  174. res = NULL;
  175. }
  176. static void SafeRelease(ImDrawVert*& res)
  177. {
  178. if (res)
  179. delete[] res;
  180. res = NULL;
  181. }
  182. static void SafeRelease(WGPUBindGroupLayout& res)
  183. {
  184. if (res)
  185. wgpuBindGroupLayoutRelease(res);
  186. res = NULL;
  187. }
  188. static void SafeRelease(WGPUBindGroup& res)
  189. {
  190. if (res)
  191. wgpuBindGroupRelease(res);
  192. res = NULL;
  193. }
  194. static void SafeRelease(WGPUBuffer& res)
  195. {
  196. if (res)
  197. wgpuBufferRelease(res);
  198. res = NULL;
  199. }
  200. static void SafeRelease(WGPURenderPipeline& res)
  201. {
  202. if (res)
  203. wgpuRenderPipelineRelease(res);
  204. res = NULL;
  205. }
  206. static void SafeRelease(WGPUSampler& res)
  207. {
  208. if (res)
  209. wgpuSamplerRelease(res);
  210. res = NULL;
  211. }
  212. static void SafeRelease(WGPUShaderModule& res)
  213. {
  214. if (res)
  215. wgpuShaderModuleRelease(res);
  216. res = NULL;
  217. }
  218. static void SafeRelease(WGPUTextureView& res)
  219. {
  220. if (res)
  221. wgpuTextureViewRelease(res);
  222. res = NULL;
  223. }
  224. static void SafeRelease(WGPUTexture& res)
  225. {
  226. if (res)
  227. wgpuTextureRelease(res);
  228. res = NULL;
  229. }
  230. static void SafeRelease(RenderResources& res)
  231. {
  232. SafeRelease(res.FontTexture);
  233. SafeRelease(res.FontTextureView);
  234. SafeRelease(res.Sampler);
  235. SafeRelease(res.Uniforms);
  236. SafeRelease(res.CommonBindGroup);
  237. SafeRelease(res.ImageBindGroup);
  238. SafeRelease(res.ImageBindGroupLayout);
  239. };
  240. static void SafeRelease(FrameResources& res)
  241. {
  242. SafeRelease(res.IndexBuffer);
  243. SafeRelease(res.VertexBuffer);
  244. SafeRelease(res.IndexBufferHost);
  245. SafeRelease(res.VertexBufferHost);
  246. }
  247. static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(uint32_t* binary_data, uint32_t binary_data_size)
  248. {
  249. WGPUShaderModuleSPIRVDescriptor spirv_desc = {};
  250. spirv_desc.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor;
  251. spirv_desc.codeSize = binary_data_size;
  252. spirv_desc.code = binary_data;
  253. WGPUShaderModuleDescriptor desc = {};
  254. desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&spirv_desc);
  255. WGPUProgrammableStageDescriptor stage_desc = {};
  256. stage_desc.module = wgpuDeviceCreateShaderModule(g_wgpuDevice, &desc);
  257. stage_desc.entryPoint = "main";
  258. return stage_desc;
  259. }
  260. static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture)
  261. {
  262. WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } };
  263. WGPUBindGroupDescriptor image_bg_descriptor = {};
  264. image_bg_descriptor.layout = layout;
  265. image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry);
  266. image_bg_descriptor.entries = image_bg_entries;
  267. return wgpuDeviceCreateBindGroup(g_wgpuDevice, &image_bg_descriptor);
  268. }
  269. static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr)
  270. {
  271. // Setup orthographic projection matrix into our constant buffer
  272. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  273. {
  274. float L = draw_data->DisplayPos.x;
  275. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  276. float T = draw_data->DisplayPos.y;
  277. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  278. float mvp[4][4] =
  279. {
  280. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  281. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  282. { 0.0f, 0.0f, 0.5f, 0.0f },
  283. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  284. };
  285. wgpuQueueWriteBuffer(g_defaultQueue, g_resources.Uniforms, 0, mvp, sizeof(mvp));
  286. }
  287. // Setup viewport
  288. wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1);
  289. // Bind shader and vertex buffers
  290. wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize * sizeof(ImDrawVert));
  291. wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize * sizeof(ImDrawIdx));
  292. wgpuRenderPassEncoderSetPipeline(ctx, g_pipelineState);
  293. wgpuRenderPassEncoderSetBindGroup(ctx, 0, g_resources.CommonBindGroup, 0, NULL);
  294. // Setup blend factor
  295. WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f };
  296. wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color);
  297. }
  298. // Render function
  299. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  300. void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
  301. {
  302. // Avoid rendering when minimized
  303. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  304. return;
  305. // FIXME: Assuming that this only gets called once per frame!
  306. // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
  307. g_frameIndex = g_frameIndex + 1;
  308. FrameResources* fr = &g_pFrameResources[g_frameIndex % g_numFramesInFlight];
  309. // Create and grow vertex/index buffers if needed
  310. if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount)
  311. {
  312. if (fr->VertexBuffer)
  313. {
  314. wgpuBufferDestroy(fr->VertexBuffer);
  315. wgpuBufferRelease(fr->VertexBuffer);
  316. }
  317. SafeRelease(fr->VertexBufferHost);
  318. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  319. WGPUBufferDescriptor vb_desc =
  320. {
  321. NULL,
  322. "Dear ImGui Vertex buffer",
  323. WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
  324. fr->VertexBufferSize * sizeof(ImDrawVert),
  325. false
  326. };
  327. fr->VertexBuffer = wgpuDeviceCreateBuffer(g_wgpuDevice, &vb_desc);
  328. if (!fr->VertexBuffer)
  329. return;
  330. fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize];
  331. }
  332. if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount)
  333. {
  334. if (fr->IndexBuffer)
  335. {
  336. wgpuBufferDestroy(fr->IndexBuffer);
  337. wgpuBufferRelease(fr->IndexBuffer);
  338. }
  339. SafeRelease(fr->IndexBufferHost);
  340. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  341. WGPUBufferDescriptor ib_desc =
  342. {
  343. NULL,
  344. "Dear ImGui Index buffer",
  345. WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
  346. fr->IndexBufferSize * sizeof(ImDrawIdx),
  347. false
  348. };
  349. fr->IndexBuffer = wgpuDeviceCreateBuffer(g_wgpuDevice, &ib_desc);
  350. if (!fr->IndexBuffer)
  351. return;
  352. fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize];
  353. }
  354. // Upload vertex/index data into a single contiguous GPU buffer
  355. ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost;
  356. ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
  357. for (int n = 0; n < draw_data->CmdListsCount; n++)
  358. {
  359. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  360. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  361. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  362. vtx_dst += cmd_list->VtxBuffer.Size;
  363. idx_dst += cmd_list->IdxBuffer.Size;
  364. }
  365. int64_t vb_write_size = ((char*)vtx_dst - (char*)fr->VertexBufferHost + 3) & ~3;
  366. int64_t ib_write_size = ((char*)idx_dst - (char*)fr->IndexBufferHost + 3) & ~3;
  367. wgpuQueueWriteBuffer(g_defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size);
  368. wgpuQueueWriteBuffer(g_defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size);
  369. // Setup desired render state
  370. ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
  371. // Render command lists
  372. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  373. int global_vtx_offset = 0;
  374. int global_idx_offset = 0;
  375. ImVec2 clip_scale = draw_data->FramebufferScale;
  376. ImVec2 clip_off = draw_data->DisplayPos;
  377. for (int n = 0; n < draw_data->CmdListsCount; n++)
  378. {
  379. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  380. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  381. {
  382. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  383. if (pcmd->UserCallback != NULL)
  384. {
  385. // User callback, registered via ImDrawList::AddCallback()
  386. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  387. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  388. ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
  389. else
  390. pcmd->UserCallback(cmd_list, pcmd);
  391. }
  392. else
  393. {
  394. // Bind custom texture
  395. ImTextureID tex_id = pcmd->GetTexID();
  396. ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id));
  397. auto bind_group = g_resources.ImageBindGroups.GetVoidPtr(tex_id_hash);
  398. if (bind_group)
  399. {
  400. wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, NULL);
  401. }
  402. else
  403. {
  404. WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(g_resources.ImageBindGroupLayout, (WGPUTextureView)tex_id);
  405. g_resources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group);
  406. wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, NULL);
  407. }
  408. // Project scissor/clipping rectangles into framebuffer space
  409. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  410. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  411. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  412. continue;
  413. // Apply scissor/clipping rectangle, Draw
  414. 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));
  415. wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  416. }
  417. }
  418. global_idx_offset += cmd_list->IdxBuffer.Size;
  419. global_vtx_offset += cmd_list->VtxBuffer.Size;
  420. }
  421. }
  422. static void ImGui_ImplWGPU_CreateFontsTexture()
  423. {
  424. // Build texture atlas
  425. ImGuiIO& io = ImGui::GetIO();
  426. unsigned char* pixels;
  427. int width, height, size_pp;
  428. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &size_pp);
  429. // Upload texture to graphics system
  430. {
  431. WGPUTextureDescriptor tex_desc = {};
  432. tex_desc.label = "Dear ImGui Font Texture";
  433. tex_desc.dimension = WGPUTextureDimension_2D;
  434. tex_desc.size.width = width;
  435. tex_desc.size.height = height;
  436. tex_desc.size.depthOrArrayLayers = 1;
  437. tex_desc.sampleCount = 1;
  438. tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
  439. tex_desc.mipLevelCount = 1;
  440. tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding;
  441. g_resources.FontTexture = wgpuDeviceCreateTexture(g_wgpuDevice, &tex_desc);
  442. WGPUTextureViewDescriptor tex_view_desc = {};
  443. tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
  444. tex_view_desc.dimension = WGPUTextureViewDimension_2D;
  445. tex_view_desc.baseMipLevel = 0;
  446. tex_view_desc.mipLevelCount = 1;
  447. tex_view_desc.baseArrayLayer = 0;
  448. tex_view_desc.arrayLayerCount = 1;
  449. tex_view_desc.aspect = WGPUTextureAspect_All;
  450. g_resources.FontTextureView = wgpuTextureCreateView(g_resources.FontTexture, &tex_view_desc);
  451. }
  452. // Upload texture data
  453. {
  454. WGPUImageCopyTexture dst_view = {};
  455. dst_view.texture = g_resources.FontTexture;
  456. dst_view.mipLevel = 0;
  457. dst_view.origin = { 0, 0, 0 };
  458. dst_view.aspect = WGPUTextureAspect_All;
  459. WGPUTextureDataLayout layout = {};
  460. layout.offset = 0;
  461. layout.bytesPerRow = width * size_pp;
  462. layout.rowsPerImage = height;
  463. WGPUExtent3D size = { (uint32_t)width, (uint32_t)height, 1 };
  464. wgpuQueueWriteTexture(g_defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size);
  465. }
  466. // Create the associated sampler
  467. {
  468. WGPUSamplerDescriptor sampler_desc = {};
  469. sampler_desc.minFilter = WGPUFilterMode_Linear;
  470. sampler_desc.magFilter = WGPUFilterMode_Linear;
  471. sampler_desc.mipmapFilter = WGPUFilterMode_Linear;
  472. sampler_desc.addressModeU = WGPUAddressMode_Repeat;
  473. sampler_desc.addressModeV = WGPUAddressMode_Repeat;
  474. sampler_desc.addressModeW = WGPUAddressMode_Repeat;
  475. sampler_desc.maxAnisotropy = 1;
  476. g_resources.Sampler = wgpuDeviceCreateSampler(g_wgpuDevice, &sampler_desc);
  477. }
  478. // Store our identifier
  479. static_assert(sizeof(ImTextureID) >= sizeof(g_resources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
  480. io.Fonts->SetTexID((ImTextureID)g_resources.FontTextureView);
  481. }
  482. static void ImGui_ImplWGPU_CreateUniformBuffer()
  483. {
  484. WGPUBufferDescriptor ub_desc =
  485. {
  486. NULL,
  487. "Dear ImGui Uniform buffer",
  488. WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
  489. sizeof(Uniforms),
  490. false
  491. };
  492. g_resources.Uniforms = wgpuDeviceCreateBuffer(g_wgpuDevice, &ub_desc);
  493. }
  494. bool ImGui_ImplWGPU_CreateDeviceObjects()
  495. {
  496. if (!g_wgpuDevice)
  497. return false;
  498. if (g_pipelineState)
  499. ImGui_ImplWGPU_InvalidateDeviceObjects();
  500. // Create render pipeline
  501. WGPURenderPipelineDescriptor graphics_pipeline_desc = {};
  502. graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
  503. graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
  504. graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
  505. graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
  506. graphics_pipeline_desc.multisample.count = 1;
  507. graphics_pipeline_desc.multisample.mask = UINT_MAX;
  508. graphics_pipeline_desc.multisample.alphaToCoverageEnabled = false;
  509. graphics_pipeline_desc.layout = nullptr; // Use automatic layout generation
  510. // Create the vertex shader
  511. WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_vert_spv, sizeof(__glsl_shader_vert_spv) / sizeof(uint32_t));
  512. graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
  513. graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
  514. // Vertex input configuration
  515. WGPUVertexAttribute attribute_desc[] =
  516. {
  517. { WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, pos), 0 },
  518. { WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, uv), 1 },
  519. { WGPUVertexFormat_Unorm8x4, (uint64_t)IM_OFFSETOF(ImDrawVert, col), 2 },
  520. };
  521. WGPUVertexBufferLayout buffer_layouts[1];
  522. buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
  523. buffer_layouts[0].stepMode = WGPUVertexStepMode_Vertex;
  524. buffer_layouts[0].attributeCount = 3;
  525. buffer_layouts[0].attributes = attribute_desc;
  526. graphics_pipeline_desc.vertex.bufferCount = 1;
  527. graphics_pipeline_desc.vertex.buffers = buffer_layouts;
  528. // Create the pixel shader
  529. WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_frag_spv, sizeof(__glsl_shader_frag_spv) / sizeof(uint32_t));
  530. // Create the blending setup
  531. WGPUBlendState blend_state = {};
  532. blend_state.alpha.operation = WGPUBlendOperation_Add;
  533. blend_state.alpha.srcFactor = WGPUBlendFactor_One;
  534. blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
  535. blend_state.color.operation = WGPUBlendOperation_Add;
  536. blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
  537. blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
  538. WGPUColorTargetState color_state = {};
  539. color_state.format = g_renderTargetFormat;
  540. color_state.blend = &blend_state;
  541. color_state.writeMask = WGPUColorWriteMask_All;
  542. WGPUFragmentState fragment_state = {};
  543. fragment_state.module = pixel_shader_desc.module;
  544. fragment_state.entryPoint = pixel_shader_desc.entryPoint;
  545. fragment_state.targetCount = 1;
  546. fragment_state.targets = &color_state;
  547. graphics_pipeline_desc.fragment = &fragment_state;
  548. // Create depth-stencil State
  549. WGPUDepthStencilState depth_stencil_state = {};
  550. depth_stencil_state.depthBias = 0;
  551. depth_stencil_state.depthBiasClamp = 0;
  552. depth_stencil_state.depthBiasSlopeScale = 0;
  553. // Configure disabled depth-stencil state
  554. graphics_pipeline_desc.depthStencil = nullptr;
  555. g_pipelineState = wgpuDeviceCreateRenderPipeline(g_wgpuDevice, &graphics_pipeline_desc);
  556. ImGui_ImplWGPU_CreateFontsTexture();
  557. ImGui_ImplWGPU_CreateUniformBuffer();
  558. // Create resource bind group
  559. WGPUBindGroupLayout bg_layouts[2];
  560. bg_layouts[0] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 0);
  561. bg_layouts[1] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 1);
  562. WGPUBindGroupEntry common_bg_entries[] =
  563. {
  564. { nullptr, 0, g_resources.Uniforms, 0, sizeof(Uniforms), 0, 0 },
  565. { nullptr, 1, 0, 0, 0, g_resources.Sampler, 0 },
  566. };
  567. WGPUBindGroupDescriptor common_bg_descriptor = {};
  568. common_bg_descriptor.layout = bg_layouts[0];
  569. common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
  570. common_bg_descriptor.entries = common_bg_entries;
  571. g_resources.CommonBindGroup = wgpuDeviceCreateBindGroup(g_wgpuDevice, &common_bg_descriptor);
  572. WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], g_resources.FontTextureView);
  573. g_resources.ImageBindGroup = image_bind_group;
  574. g_resources.ImageBindGroupLayout = bg_layouts[1];
  575. g_resources.ImageBindGroups.SetVoidPtr(ImHashData(&g_resources.FontTextureView, sizeof(ImTextureID)), image_bind_group);
  576. SafeRelease(vertex_shader_desc.module);
  577. SafeRelease(pixel_shader_desc.module);
  578. SafeRelease(bg_layouts[0]);
  579. return true;
  580. }
  581. void ImGui_ImplWGPU_InvalidateDeviceObjects()
  582. {
  583. if (!g_wgpuDevice)
  584. return;
  585. SafeRelease(g_pipelineState);
  586. SafeRelease(g_resources);
  587. ImGuiIO& io = ImGui::GetIO();
  588. io.Fonts->SetTexID(NULL); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
  589. for (unsigned int i = 0; i < g_numFramesInFlight; i++)
  590. SafeRelease(g_pFrameResources[i]);
  591. }
  592. bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format)
  593. {
  594. // Setup backend capabilities flags
  595. ImGuiIO& io = ImGui::GetIO();
  596. io.BackendRendererName = "imgui_impl_webgpu";
  597. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  598. g_wgpuDevice = device;
  599. g_defaultQueue = wgpuDeviceGetQueue(g_wgpuDevice);
  600. g_renderTargetFormat = rt_format;
  601. g_pFrameResources = new FrameResources[num_frames_in_flight];
  602. g_numFramesInFlight = num_frames_in_flight;
  603. g_frameIndex = UINT_MAX;
  604. g_resources.FontTexture = NULL;
  605. g_resources.FontTextureView = NULL;
  606. g_resources.Sampler = NULL;
  607. g_resources.Uniforms = NULL;
  608. g_resources.CommonBindGroup = NULL;
  609. g_resources.ImageBindGroups.Data.reserve(100);
  610. g_resources.ImageBindGroup = NULL;
  611. g_resources.ImageBindGroupLayout = NULL;
  612. // Create buffers with a default size (they will later be grown as needed)
  613. for (int i = 0; i < num_frames_in_flight; i++)
  614. {
  615. FrameResources* fr = &g_pFrameResources[i];
  616. fr->IndexBuffer = NULL;
  617. fr->VertexBuffer = NULL;
  618. fr->IndexBufferHost = NULL;
  619. fr->VertexBufferHost = NULL;
  620. fr->IndexBufferSize = 10000;
  621. fr->VertexBufferSize = 5000;
  622. }
  623. return true;
  624. }
  625. void ImGui_ImplWGPU_Shutdown()
  626. {
  627. ImGui_ImplWGPU_InvalidateDeviceObjects();
  628. delete[] g_pFrameResources;
  629. g_pFrameResources = NULL;
  630. wgpuQueueRelease(g_defaultQueue);
  631. g_wgpuDevice = NULL;
  632. g_numFramesInFlight = 0;
  633. g_frameIndex = UINT_MAX;
  634. }
  635. void ImGui_ImplWGPU_NewFrame()
  636. {
  637. if (!g_pipelineState)
  638. ImGui_ImplWGPU_CreateDeviceObjects();
  639. }