imgui_impl_wgpu.cpp 34 KB

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