imgui_impl_sdlgpu3.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. // dear imgui: Renderer Backend for SDL_GPU
  2. // This needs to be used along with the SDL3 Platform Backend
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use simply cast a reference to your SDL_GPUTextureSamplerBinding to ImTextureID.
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  7. // The aim of imgui_impl_sdlgpu3.h/.cpp is to be usable in your engine without any modification.
  8. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
  9. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  10. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  11. // Learn about Dear ImGui:
  12. // - FAQ https://dearimgui.com/faq
  13. // - Getting Started https://dearimgui.com/getting-started
  14. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  15. // - Introduction, links and more at the top of imgui.cpp
  16. // Important note to the reader who wish to integrate imgui_impl_sdlgpu3.cpp/.h in their own engine/app.
  17. // - Unlike other backends, the user must call the function ImGui_ImplSDLGPU3_PrepareDrawData() BEFORE issuing a SDL_GPURenderPass containing ImGui_ImplSDLGPU3_RenderDrawData.
  18. // Calling the function is MANDATORY, otherwise the ImGui will not upload neither the vertex nor the index buffer for the GPU. See imgui_impl_sdlgpu3.cpp for more info.
  19. // CHANGELOG
  20. // 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  21. // 2025-04-28: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  22. // 2025-03-30: Made ImGui_ImplSDLGPU3_PrepareDrawData() reuse GPU Transfer Buffers which were unusually slow to recreate every frame. Much faster now.
  23. // 2025-03-21: Fixed typo in function name Imgui_ImplSDLGPU3_PrepareDrawData() -> ImGui_ImplSDLGPU3_PrepareDrawData().
  24. // 2025-01-16: Renamed ImGui_ImplSDLGPU3_InitInfo::GpuDevice to Device.
  25. // 2025-01-09: SDL_GPU: Added the SDL_GPU3 backend.
  26. #include "imgui.h"
  27. #ifndef IMGUI_DISABLE
  28. #include "imgui_impl_sdlgpu3.h"
  29. #include "imgui_impl_sdlgpu3_shaders.h"
  30. // SDL_GPU Data
  31. // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplSDLGPU3_RenderDrawData()
  32. struct ImGui_ImplSDLGPU3_FrameData
  33. {
  34. SDL_GPUBuffer* VertexBuffer = nullptr;
  35. SDL_GPUTransferBuffer* VertexTransferBuffer = nullptr;
  36. uint32_t VertexBufferSize = 0;
  37. SDL_GPUBuffer* IndexBuffer = nullptr;
  38. SDL_GPUTransferBuffer* IndexTransferBuffer = nullptr;
  39. uint32_t IndexBufferSize = 0;
  40. };
  41. struct ImGui_ImplSDLGPU3_Data
  42. {
  43. ImGui_ImplSDLGPU3_InitInfo InitInfo;
  44. // Graphics pipeline & shaders
  45. SDL_GPUShader* VertexShader = nullptr;
  46. SDL_GPUShader* FragmentShader = nullptr;
  47. SDL_GPUGraphicsPipeline* Pipeline = nullptr;
  48. // Font data
  49. SDL_GPUSampler* FontSampler = nullptr;
  50. SDL_GPUTexture* FontTexture = nullptr;
  51. SDL_GPUTextureSamplerBinding FontBinding = { nullptr, nullptr };
  52. // Frame data for main window
  53. ImGui_ImplSDLGPU3_FrameData MainWindowFrameData;
  54. };
  55. // Forward Declarations
  56. static void ImGui_ImplSDLGPU3_DestroyFrameData();
  57. //-----------------------------------------------------------------------------
  58. // FUNCTIONS
  59. //-----------------------------------------------------------------------------
  60. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  61. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  62. // FIXME: multi-context support has never been tested.
  63. static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData()
  64. {
  65. return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  66. }
  67. static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass * render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height)
  68. {
  69. //ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  70. // Bind graphics pipeline
  71. SDL_BindGPUGraphicsPipeline(render_pass,pipeline);
  72. // Bind Vertex And Index Buffers
  73. if (draw_data->TotalVtxCount > 0)
  74. {
  75. SDL_GPUBufferBinding vertex_buffer_binding = {};
  76. vertex_buffer_binding.buffer = fd->VertexBuffer;
  77. vertex_buffer_binding.offset = 0;
  78. SDL_GPUBufferBinding index_buffer_binding = {};
  79. index_buffer_binding.buffer = fd->IndexBuffer;
  80. index_buffer_binding.offset = 0;
  81. SDL_BindGPUVertexBuffers(render_pass,0, &vertex_buffer_binding, 1);
  82. SDL_BindGPUIndexBuffer(render_pass, &index_buffer_binding, sizeof(ImDrawIdx) == 2 ? SDL_GPU_INDEXELEMENTSIZE_16BIT : SDL_GPU_INDEXELEMENTSIZE_32BIT);
  83. }
  84. // Setup viewport
  85. SDL_GPUViewport viewport = {};
  86. viewport.x = 0;
  87. viewport.y = 0;
  88. viewport.w = (float)fb_width;
  89. viewport.h = (float)fb_height;
  90. viewport.min_depth = 0.0f;
  91. viewport.max_depth = 1.0f;
  92. SDL_SetGPUViewport(render_pass, &viewport);
  93. // Setup scale and translation
  94. // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
  95. struct UBO { float scale[2]; float translation[2]; } ubo;
  96. ubo.scale[0] = 2.0f / draw_data->DisplaySize.x;
  97. ubo.scale[1] = 2.0f / draw_data->DisplaySize.y;
  98. ubo.translation[0] = -1.0f - draw_data->DisplayPos.x * ubo.scale[0];
  99. ubo.translation[1] = -1.0f - draw_data->DisplayPos.y * ubo.scale[1];
  100. SDL_PushGPUVertexUniformData(command_buffer, 0, &ubo, sizeof(UBO));
  101. }
  102. static void CreateOrResizeBuffers(SDL_GPUBuffer** buffer, SDL_GPUTransferBuffer** transferbuffer, uint32_t* old_size, uint32_t new_size, SDL_GPUBufferUsageFlags usage)
  103. {
  104. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  105. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  106. // FIXME-OPT: Not optimal, but this is fairly rarely called.
  107. SDL_WaitForGPUIdle(v->Device);
  108. SDL_ReleaseGPUBuffer(v->Device, *buffer);
  109. SDL_ReleaseGPUTransferBuffer(v->Device, *transferbuffer);
  110. SDL_GPUBufferCreateInfo buffer_info = {};
  111. buffer_info.usage = usage;
  112. buffer_info.size = new_size;
  113. buffer_info.props = 0;
  114. *buffer = SDL_CreateGPUBuffer(v->Device, &buffer_info);
  115. *old_size = new_size;
  116. IM_ASSERT(*buffer != nullptr && "Failed to create GPU Buffer, call SDL_GetError() for more information");
  117. SDL_GPUTransferBufferCreateInfo transferbuffer_info = {};
  118. transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
  119. transferbuffer_info.size = new_size;
  120. *transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info);
  121. IM_ASSERT(*transferbuffer != nullptr && "Failed to create GPU Transfer Buffer, call SDL_GetError() for more information");
  122. }
  123. // SDL_GPU doesn't allow copy passes to occur while a render or compute pass is bound!
  124. // The only way to allow a user to supply their own RenderPass (to render to a texture instead of the window for example),
  125. // is to split the upload part of ImGui_ImplSDLGPU3_RenderDrawData() to another function that needs to be called by the user before rendering.
  126. void ImGui_ImplSDLGPU3_PrepareDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer)
  127. {
  128. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  129. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  130. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  131. if (fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount <= 0)
  132. return;
  133. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  134. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  135. ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData;
  136. uint32_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
  137. uint32_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
  138. if (fd->VertexBuffer == nullptr || fd->VertexBufferSize < vertex_size)
  139. CreateOrResizeBuffers(&fd->VertexBuffer, &fd->VertexTransferBuffer, &fd->VertexBufferSize, vertex_size, SDL_GPU_BUFFERUSAGE_VERTEX);
  140. if (fd->IndexBuffer == nullptr || fd->IndexBufferSize < index_size)
  141. CreateOrResizeBuffers(&fd->IndexBuffer, &fd->IndexTransferBuffer, &fd->IndexBufferSize, index_size, SDL_GPU_BUFFERUSAGE_INDEX);
  142. ImDrawVert* vtx_dst = (ImDrawVert*)SDL_MapGPUTransferBuffer(v->Device, fd->VertexTransferBuffer, true);
  143. ImDrawIdx* idx_dst = (ImDrawIdx*)SDL_MapGPUTransferBuffer(v->Device, fd->IndexTransferBuffer, true);
  144. for (int n = 0; n < draw_data->CmdListsCount; n++)
  145. {
  146. const ImDrawList* draw_list = draw_data->CmdLists[n];
  147. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  148. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  149. vtx_dst += draw_list->VtxBuffer.Size;
  150. idx_dst += draw_list->IdxBuffer.Size;
  151. }
  152. SDL_UnmapGPUTransferBuffer(v->Device, fd->VertexTransferBuffer);
  153. SDL_UnmapGPUTransferBuffer(v->Device, fd->IndexTransferBuffer);
  154. SDL_GPUTransferBufferLocation vertex_buffer_location = {};
  155. vertex_buffer_location.offset = 0;
  156. vertex_buffer_location.transfer_buffer = fd->VertexTransferBuffer;
  157. SDL_GPUTransferBufferLocation index_buffer_location = {};
  158. index_buffer_location.offset = 0;
  159. index_buffer_location.transfer_buffer = fd->IndexTransferBuffer;
  160. SDL_GPUBufferRegion vertex_buffer_region = {};
  161. vertex_buffer_region.buffer = fd->VertexBuffer;
  162. vertex_buffer_region.offset = 0;
  163. vertex_buffer_region.size = vertex_size;
  164. SDL_GPUBufferRegion index_buffer_region = {};
  165. index_buffer_region.buffer = fd->IndexBuffer;
  166. index_buffer_region.offset = 0;
  167. index_buffer_region.size = index_size;
  168. SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(command_buffer);
  169. SDL_UploadToGPUBuffer(copy_pass, &vertex_buffer_location, &vertex_buffer_region, true);
  170. SDL_UploadToGPUBuffer(copy_pass, &index_buffer_location, &index_buffer_region, true);
  171. SDL_EndGPUCopyPass(copy_pass);
  172. }
  173. void ImGui_ImplSDLGPU3_RenderDrawData(ImDrawData* draw_data, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, SDL_GPUGraphicsPipeline* pipeline)
  174. {
  175. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  176. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  177. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  178. if (fb_width <= 0 || fb_height <= 0)
  179. return;
  180. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  181. ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData;
  182. if (pipeline == nullptr)
  183. pipeline = bd->Pipeline;
  184. ImGui_ImplSDLGPU3_SetupRenderState(draw_data, pipeline, command_buffer, render_pass, fd, fb_width, fb_height);
  185. // Will project scissor/clipping rectangles into framebuffer space
  186. ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
  187. ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  188. // Render command lists
  189. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  190. int global_vtx_offset = 0;
  191. int global_idx_offset = 0;
  192. for (int n = 0; n < draw_data->CmdListsCount; n++)
  193. {
  194. const ImDrawList* draw_list = draw_data->CmdLists[n];
  195. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  196. {
  197. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  198. if (pcmd->UserCallback != nullptr)
  199. {
  200. // User callback, registered via ImDrawList::AddCallback()
  201. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  202. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  203. ImGui_ImplSDLGPU3_SetupRenderState(draw_data, pipeline, command_buffer, render_pass, fd, fb_width, fb_height);
  204. else
  205. pcmd->UserCallback(draw_list, pcmd);
  206. }
  207. else
  208. {
  209. // Project scissor/clipping rectangles into framebuffer space
  210. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  211. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  212. // Clamp to viewport as SDL_SetGPUScissor() won't accept values that are off bounds
  213. if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
  214. if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
  215. if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
  216. if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
  217. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  218. continue;
  219. // Apply scissor/clipping rectangle
  220. SDL_Rect scissor_rect = {};
  221. scissor_rect.x = (int)clip_min.x;
  222. scissor_rect.y = (int)clip_min.y;
  223. scissor_rect.w = (int)(clip_max.x - clip_min.x);
  224. scissor_rect.h = (int)(clip_max.y - clip_min.y);
  225. SDL_SetGPUScissor(render_pass,&scissor_rect);
  226. // Bind DescriptorSet with font or user texture
  227. SDL_BindGPUFragmentSamplers(render_pass, 0, (SDL_GPUTextureSamplerBinding*)pcmd->GetTexID(), 1);
  228. // Draw
  229. SDL_DrawGPUIndexedPrimitives(render_pass, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  230. }
  231. }
  232. global_idx_offset += draw_list->IdxBuffer.Size;
  233. global_vtx_offset += draw_list->VtxBuffer.Size;
  234. }
  235. // Note: at this point both SDL_SetGPUViewport() and SDL_SetGPUScissor() have been called.
  236. // Our last values will leak into user/application rendering if you forgot to call SDL_SetGPUViewport() and SDL_SetGPUScissor() yourself to explicitly set that state
  237. // In theory we should aim to backup/restore those values but I am not sure this is possible.
  238. // We perform a call to SDL_SetGPUScissor() to set back a full viewport which is likely to fix things for 99% users but technically this is not perfect. (See github #4644)
  239. SDL_Rect scissor_rect { 0, 0, fb_width, fb_height };
  240. SDL_SetGPUScissor(render_pass, &scissor_rect);
  241. }
  242. void ImGui_ImplSDLGPU3_CreateFontsTexture()
  243. {
  244. ImGuiIO& io = ImGui::GetIO();
  245. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  246. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  247. // Destroy existing texture (if any)
  248. if (bd->FontTexture)
  249. {
  250. SDL_WaitForGPUIdle(v->Device);
  251. ImGui_ImplSDLGPU3_DestroyFontsTexture();
  252. }
  253. unsigned char* pixels;
  254. int width, height;
  255. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  256. uint32_t upload_size = width * height * 4 * sizeof(char);
  257. // Create the Image:
  258. {
  259. SDL_GPUTextureCreateInfo texture_info = {};
  260. texture_info.type = SDL_GPU_TEXTURETYPE_2D;
  261. texture_info.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
  262. texture_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER;
  263. texture_info.width = width;
  264. texture_info.height = height;
  265. texture_info.layer_count_or_depth = 1;
  266. texture_info.num_levels = 1;
  267. texture_info.sample_count = SDL_GPU_SAMPLECOUNT_1;
  268. bd->FontTexture = SDL_CreateGPUTexture(v->Device, &texture_info);
  269. IM_ASSERT(bd->FontTexture && "Failed to create font texture, call SDL_GetError() for more info");
  270. }
  271. // Assign the texture to the TextureSamplerBinding
  272. bd->FontBinding.texture = bd->FontTexture;
  273. // Create all the upload structures and upload:
  274. {
  275. SDL_GPUTransferBufferCreateInfo transferbuffer_info = {};
  276. transferbuffer_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
  277. transferbuffer_info.size = upload_size;
  278. SDL_GPUTransferBuffer* transferbuffer = SDL_CreateGPUTransferBuffer(v->Device, &transferbuffer_info);
  279. IM_ASSERT(transferbuffer != nullptr && "Failed to create font transfer buffer, call SDL_GetError() for more information");
  280. void* texture_ptr = SDL_MapGPUTransferBuffer(v->Device, transferbuffer, false);
  281. memcpy(texture_ptr, pixels, upload_size);
  282. SDL_UnmapGPUTransferBuffer(v->Device, transferbuffer);
  283. SDL_GPUTextureTransferInfo transfer_info = {};
  284. transfer_info.offset = 0;
  285. transfer_info.transfer_buffer = transferbuffer;
  286. SDL_GPUTextureRegion texture_region = {};
  287. texture_region.texture = bd->FontTexture;
  288. texture_region.w = width;
  289. texture_region.h = height;
  290. texture_region.d = 1;
  291. SDL_GPUCommandBuffer* cmd = SDL_AcquireGPUCommandBuffer(v->Device);
  292. SDL_GPUCopyPass* copy_pass = SDL_BeginGPUCopyPass(cmd);
  293. SDL_UploadToGPUTexture(copy_pass, &transfer_info, &texture_region, false);
  294. SDL_EndGPUCopyPass(copy_pass);
  295. SDL_SubmitGPUCommandBuffer(cmd);
  296. SDL_ReleaseGPUTransferBuffer(v->Device, transferbuffer);
  297. }
  298. // Store our identifier
  299. io.Fonts->SetTexID((ImTextureID)&bd->FontBinding);
  300. }
  301. // You probably never need to call this, as it is called by ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_Shutdown().
  302. void ImGui_ImplSDLGPU3_DestroyFontsTexture()
  303. {
  304. ImGuiIO& io = ImGui::GetIO();
  305. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  306. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  307. if (bd->FontTexture)
  308. {
  309. SDL_ReleaseGPUTexture(v->Device, bd->FontTexture);
  310. bd->FontBinding.texture = nullptr;
  311. bd->FontTexture = nullptr;
  312. }
  313. io.Fonts->SetTexID(0);
  314. }
  315. static void ImGui_ImplSDLGPU3_CreateShaders()
  316. {
  317. // Create the shader modules
  318. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  319. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  320. const char* driver = SDL_GetGPUDeviceDriver(v->Device);
  321. SDL_GPUShaderCreateInfo vertex_shader_info = {};
  322. vertex_shader_info.entrypoint = "main";
  323. vertex_shader_info.stage = SDL_GPU_SHADERSTAGE_VERTEX;
  324. vertex_shader_info.num_uniform_buffers = 1;
  325. vertex_shader_info.num_storage_buffers = 0;
  326. vertex_shader_info.num_storage_textures = 0;
  327. vertex_shader_info.num_samplers = 0;
  328. SDL_GPUShaderCreateInfo fragment_shader_info = {};
  329. fragment_shader_info.entrypoint = "main";
  330. fragment_shader_info.stage = SDL_GPU_SHADERSTAGE_FRAGMENT;
  331. fragment_shader_info.num_samplers = 1;
  332. fragment_shader_info.num_storage_buffers = 0;
  333. fragment_shader_info.num_storage_textures = 0;
  334. fragment_shader_info.num_uniform_buffers = 0;
  335. if (strcmp(driver, "vulkan") == 0)
  336. {
  337. vertex_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV;
  338. vertex_shader_info.code = spirv_vertex;
  339. vertex_shader_info.code_size = sizeof(spirv_vertex);
  340. fragment_shader_info.format = SDL_GPU_SHADERFORMAT_SPIRV;
  341. fragment_shader_info.code = spirv_fragment;
  342. fragment_shader_info.code_size = sizeof(spirv_fragment);
  343. }
  344. else if (strcmp(driver, "direct3d12") == 0)
  345. {
  346. vertex_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC;
  347. vertex_shader_info.code = dxbc_vertex;
  348. vertex_shader_info.code_size = sizeof(dxbc_vertex);
  349. fragment_shader_info.format = SDL_GPU_SHADERFORMAT_DXBC;
  350. fragment_shader_info.code = dxbc_fragment;
  351. fragment_shader_info.code_size = sizeof(dxbc_fragment);
  352. }
  353. #ifdef __APPLE__
  354. else
  355. {
  356. vertex_shader_info.entrypoint = "main0";
  357. vertex_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB;
  358. vertex_shader_info.code = metallib_vertex;
  359. vertex_shader_info.code_size = sizeof(metallib_vertex);
  360. fragment_shader_info.entrypoint = "main0";
  361. fragment_shader_info.format = SDL_GPU_SHADERFORMAT_METALLIB;
  362. fragment_shader_info.code = metallib_fragment;
  363. fragment_shader_info.code_size = sizeof(metallib_fragment);
  364. }
  365. #endif
  366. bd->VertexShader = SDL_CreateGPUShader(v->Device, &vertex_shader_info);
  367. bd->FragmentShader = SDL_CreateGPUShader(v->Device, &fragment_shader_info);
  368. IM_ASSERT(bd->VertexShader != nullptr && "Failed to create vertex shader, call SDL_GetError() for more information");
  369. IM_ASSERT(bd->FragmentShader != nullptr && "Failed to create fragment shader, call SDL_GetError() for more information");
  370. }
  371. static void ImGui_ImplSDLGPU3_CreateGraphicsPipeline()
  372. {
  373. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  374. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  375. ImGui_ImplSDLGPU3_CreateShaders();
  376. SDL_GPUVertexBufferDescription vertex_buffer_desc[1];
  377. vertex_buffer_desc[0].slot = 0;
  378. vertex_buffer_desc[0].input_rate = SDL_GPU_VERTEXINPUTRATE_VERTEX;
  379. vertex_buffer_desc[0].instance_step_rate = 0;
  380. vertex_buffer_desc[0].pitch = sizeof(ImDrawVert);
  381. SDL_GPUVertexAttribute vertex_attributes[3];
  382. vertex_attributes[0].buffer_slot = 0;
  383. vertex_attributes[0].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2;
  384. vertex_attributes[0].location = 0;
  385. vertex_attributes[0].offset = offsetof(ImDrawVert,pos);
  386. vertex_attributes[1].buffer_slot = 0;
  387. vertex_attributes[1].format = SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2;
  388. vertex_attributes[1].location = 1;
  389. vertex_attributes[1].offset = offsetof(ImDrawVert, uv);
  390. vertex_attributes[2].buffer_slot = 0;
  391. vertex_attributes[2].format = SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM;
  392. vertex_attributes[2].location = 2;
  393. vertex_attributes[2].offset = offsetof(ImDrawVert, col);
  394. SDL_GPUVertexInputState vertex_input_state = {};
  395. vertex_input_state.num_vertex_attributes = 3;
  396. vertex_input_state.vertex_attributes = vertex_attributes;
  397. vertex_input_state.num_vertex_buffers = 1;
  398. vertex_input_state.vertex_buffer_descriptions = vertex_buffer_desc;
  399. SDL_GPURasterizerState rasterizer_state = {};
  400. rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL;
  401. rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE;
  402. rasterizer_state.front_face = SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE;
  403. rasterizer_state.enable_depth_bias = false;
  404. rasterizer_state.enable_depth_clip = false;
  405. SDL_GPUMultisampleState multisample_state = {};
  406. multisample_state.sample_count = v->MSAASamples;
  407. multisample_state.enable_mask = false;
  408. SDL_GPUDepthStencilState depth_stencil_state = {};
  409. depth_stencil_state.enable_depth_test = false;
  410. depth_stencil_state.enable_depth_write = false;
  411. depth_stencil_state.enable_stencil_test = false;
  412. SDL_GPUColorTargetBlendState blend_state = {};
  413. blend_state.enable_blend = true;
  414. blend_state.src_color_blendfactor = SDL_GPU_BLENDFACTOR_SRC_ALPHA;
  415. blend_state.dst_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
  416. blend_state.color_blend_op = SDL_GPU_BLENDOP_ADD;
  417. blend_state.src_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE;
  418. blend_state.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
  419. blend_state.alpha_blend_op = SDL_GPU_BLENDOP_ADD;
  420. blend_state.color_write_mask = SDL_GPU_COLORCOMPONENT_R | SDL_GPU_COLORCOMPONENT_G | SDL_GPU_COLORCOMPONENT_B | SDL_GPU_COLORCOMPONENT_A;
  421. SDL_GPUColorTargetDescription color_target_desc[1];
  422. color_target_desc[0].format = v->ColorTargetFormat;
  423. color_target_desc[0].blend_state = blend_state;
  424. SDL_GPUGraphicsPipelineTargetInfo target_info = {};
  425. target_info.num_color_targets = 1;
  426. target_info.color_target_descriptions = color_target_desc;
  427. target_info.has_depth_stencil_target = false;
  428. SDL_GPUGraphicsPipelineCreateInfo pipeline_info = {};
  429. pipeline_info.vertex_shader = bd->VertexShader;
  430. pipeline_info.fragment_shader = bd->FragmentShader;
  431. pipeline_info.vertex_input_state = vertex_input_state;
  432. pipeline_info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
  433. pipeline_info.rasterizer_state = rasterizer_state;
  434. pipeline_info.multisample_state = multisample_state;
  435. pipeline_info.depth_stencil_state = depth_stencil_state;
  436. pipeline_info.target_info = target_info;
  437. bd->Pipeline = SDL_CreateGPUGraphicsPipeline(v->Device, &pipeline_info);
  438. IM_ASSERT(bd->Pipeline != nullptr && "Failed to create graphics pipeline, call SDL_GetError() for more information");
  439. }
  440. void ImGui_ImplSDLGPU3_CreateDeviceObjects()
  441. {
  442. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  443. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  444. if (!bd->FontSampler)
  445. {
  446. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  447. SDL_GPUSamplerCreateInfo sampler_info = {};
  448. sampler_info.min_filter = SDL_GPU_FILTER_LINEAR;
  449. sampler_info.mag_filter = SDL_GPU_FILTER_LINEAR;
  450. sampler_info.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
  451. sampler_info.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  452. sampler_info.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  453. sampler_info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  454. sampler_info.mip_lod_bias = 0.0f;
  455. sampler_info.min_lod = -1000.0f;
  456. sampler_info.max_lod = 1000.0f;
  457. sampler_info.enable_anisotropy = false;
  458. sampler_info.max_anisotropy = 1.0f;
  459. sampler_info.enable_compare = false;
  460. bd->FontSampler = SDL_CreateGPUSampler(v->Device, &sampler_info);
  461. bd->FontBinding.sampler = bd->FontSampler;
  462. IM_ASSERT(bd->FontSampler != nullptr && "Failed to create font sampler, call SDL_GetError() for more information");
  463. }
  464. ImGui_ImplSDLGPU3_CreateGraphicsPipeline();
  465. ImGui_ImplSDLGPU3_CreateFontsTexture();
  466. }
  467. void ImGui_ImplSDLGPU3_DestroyFrameData()
  468. {
  469. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  470. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  471. ImGui_ImplSDLGPU3_FrameData* fd = &bd->MainWindowFrameData;
  472. SDL_ReleaseGPUBuffer(v->Device, fd->VertexBuffer);
  473. SDL_ReleaseGPUBuffer(v->Device, fd->IndexBuffer);
  474. SDL_ReleaseGPUTransferBuffer(v->Device, fd->VertexTransferBuffer);
  475. SDL_ReleaseGPUTransferBuffer(v->Device, fd->IndexTransferBuffer);
  476. fd->VertexBuffer = fd->IndexBuffer = nullptr;
  477. fd->VertexTransferBuffer = fd->IndexTransferBuffer = nullptr;
  478. fd->VertexBufferSize = fd->IndexBufferSize = 0;
  479. }
  480. void ImGui_ImplSDLGPU3_DestroyDeviceObjects()
  481. {
  482. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  483. ImGui_ImplSDLGPU3_InitInfo* v = &bd->InitInfo;
  484. ImGui_ImplSDLGPU3_DestroyFrameData();
  485. ImGui_ImplSDLGPU3_DestroyFontsTexture();
  486. if (bd->VertexShader) { SDL_ReleaseGPUShader(v->Device, bd->VertexShader); bd->VertexShader = nullptr;}
  487. if (bd->FragmentShader) { SDL_ReleaseGPUShader(v->Device, bd->FragmentShader); bd->FragmentShader = nullptr;}
  488. if (bd->FontSampler) { SDL_ReleaseGPUSampler(v->Device, bd->FontSampler); bd->FontSampler = nullptr;}
  489. if (bd->Pipeline) { SDL_ReleaseGPUGraphicsPipeline(v->Device, bd->Pipeline); bd->Pipeline = nullptr;}
  490. }
  491. static void ImGui_ImplSDLGPU3_InitMultiViewportSupport();
  492. static void ImGui_ImplSDLGPU3_ShutdownMultiViewportSupport();
  493. bool ImGui_ImplSDLGPU3_Init(ImGui_ImplSDLGPU3_InitInfo* info)
  494. {
  495. ImGuiIO& io = ImGui::GetIO();
  496. IMGUI_CHECKVERSION();
  497. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  498. // Setup backend capabilities flags
  499. ImGui_ImplSDLGPU3_Data* bd = IM_NEW(ImGui_ImplSDLGPU3_Data)();
  500. io.BackendRendererUserData = (void*)bd;
  501. io.BackendRendererName = "imgui_impl_sdlgpu3";
  502. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  503. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  504. IM_ASSERT(info->Device != nullptr);
  505. IM_ASSERT(info->ColorTargetFormat != SDL_GPU_TEXTUREFORMAT_INVALID);
  506. bd->InitInfo = *info;
  507. ImGui_ImplSDLGPU3_InitMultiViewportSupport();
  508. return true;
  509. }
  510. void ImGui_ImplSDLGPU3_Shutdown()
  511. {
  512. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  513. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  514. ImGuiIO& io = ImGui::GetIO();
  515. ImGui_ImplSDLGPU3_ShutdownMultiViewportSupport();
  516. ImGui_ImplSDLGPU3_DestroyDeviceObjects();
  517. io.BackendRendererName = nullptr;
  518. io.BackendRendererUserData = nullptr;
  519. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
  520. IM_DELETE(bd);
  521. }
  522. void ImGui_ImplSDLGPU3_NewFrame()
  523. {
  524. ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData();
  525. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLGPU3_Init()?");
  526. if (!bd->FontSampler)
  527. ImGui_ImplSDLGPU3_CreateDeviceObjects();
  528. if (!bd->FontTexture)
  529. ImGui_ImplSDLGPU3_CreateFontsTexture();
  530. }
  531. //--------------------------------------------------------------------------------------------------------
  532. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  533. // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
  534. // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
  535. //--------------------------------------------------------------------------------------------------------
  536. static void ImGui_ImplSDLGPU3_CreateWindow(ImGuiViewport* viewport)
  537. {
  538. ImGui_ImplSDLGPU3_Data* data = ImGui_ImplSDLGPU3_GetBackendData();
  539. SDL_Window* window = SDL_GetWindowFromID((SDL_WindowID)(intptr_t)viewport->PlatformHandle);
  540. SDL_ClaimWindowForGPUDevice(data->InitInfo.Device, window);
  541. viewport->RendererUserData = (void*)1;
  542. }
  543. static void ImGui_ImplSDLGPU3_RenderWindow(ImGuiViewport* viewport, void*)
  544. {
  545. ImGui_ImplSDLGPU3_Data* data = ImGui_ImplSDLGPU3_GetBackendData();
  546. SDL_Window* window = SDL_GetWindowFromID((SDL_WindowID)(intptr_t)viewport->PlatformHandle);
  547. ImDrawData* draw_data = viewport->DrawData;
  548. SDL_GPUCommandBuffer* command_buffer = SDL_AcquireGPUCommandBuffer(data->InitInfo.Device);
  549. SDL_GPUTexture* swapchain_texture;
  550. SDL_AcquireGPUSwapchainTexture(command_buffer, window, &swapchain_texture, nullptr, nullptr);
  551. if (swapchain_texture != nullptr)
  552. {
  553. ImGui_ImplSDLGPU3_PrepareDrawData(draw_data, command_buffer); // FIXME-OPT: Not optimal, may this be done earlier?
  554. SDL_GPUColorTargetInfo target_info = {};
  555. target_info.texture = swapchain_texture;
  556. target_info.clear_color = SDL_FColor{ 0.0f,0.0f,0.0f,1.0f };
  557. target_info.load_op = SDL_GPU_LOADOP_CLEAR;
  558. target_info.store_op = SDL_GPU_STOREOP_STORE;
  559. target_info.mip_level = 0;
  560. target_info.layer_or_depth_plane = 0;
  561. target_info.cycle = false;
  562. SDL_GPURenderPass* render_pass = SDL_BeginGPURenderPass(command_buffer, &target_info, 1, nullptr);
  563. ImGui_ImplSDLGPU3_RenderDrawData(draw_data, command_buffer, render_pass);
  564. SDL_EndGPURenderPass(render_pass);
  565. }
  566. SDL_SubmitGPUCommandBuffer(command_buffer);
  567. }
  568. static void ImGui_ImplSDLGPU3_DestroyWindow(ImGuiViewport* viewport)
  569. {
  570. ImGui_ImplSDLGPU3_Data* data = ImGui_ImplSDLGPU3_GetBackendData();
  571. if (viewport->RendererUserData)
  572. {
  573. SDL_Window* window = SDL_GetWindowFromID((SDL_WindowID)(intptr_t)viewport->PlatformHandle);
  574. SDL_ReleaseWindowFromGPUDevice(data->InitInfo.Device, window);
  575. }
  576. viewport->RendererUserData = nullptr;
  577. }
  578. static void ImGui_ImplSDLGPU3_InitMultiViewportSupport()
  579. {
  580. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  581. platform_io.Renderer_RenderWindow = ImGui_ImplSDLGPU3_RenderWindow;
  582. platform_io.Renderer_CreateWindow = ImGui_ImplSDLGPU3_CreateWindow;
  583. platform_io.Renderer_DestroyWindow = ImGui_ImplSDLGPU3_DestroyWindow;
  584. }
  585. static void ImGui_ImplSDLGPU3_ShutdownMultiViewportSupport()
  586. {
  587. ImGui::DestroyPlatformWindows();
  588. }
  589. //-----------------------------------------------------------------------------
  590. #endif // #ifndef IMGUI_DISABLE