imgui_impl_wgpu.cpp 31 KB

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