imgui_impl_wgpu.cpp 37 KB

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