imgui_impl_dx12.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. // dear imgui: Renderer Backend for DirectX12
  2. // This needs to be used along with a Platform Backend (e.g. Win32)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
  7. // The aim of imgui_impl_dx12.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. // CHANGELOG
  17. // (minor and older changes stripped away, please see git history for details)
  18. // 2025-05-07: DirectX12: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows).
  19. // 2025-02-24: DirectX12: Fixed an issue where ImGui_ImplDX12_Init() signature change from 2024-11-15 combined with change from 2025-01-15 made legacy ImGui_ImplDX12_Init() crash. (#8429)
  20. // 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own.
  21. // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat.
  22. // 2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
  23. // 2024-11-15: DirectX12: *BREAKING CHANGE* User is now required to pass function pointers to allocate/free SRV Descriptors. We provide convenience legacy fields to pass a single descriptor, matching the old API, but upcoming features will want multiple.
  24. // 2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
  25. // 2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  26. // 2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
  27. // 2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
  28. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  29. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
  30. // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  31. // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
  32. // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
  33. // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
  34. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
  35. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
  36. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  37. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  38. // 2019-03-29: Misc: Various minor tidying up.
  39. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  40. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  41. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
  42. // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
  43. // 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport).
  44. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
  45. #include "imgui.h"
  46. #ifndef IMGUI_DISABLE
  47. #include "imgui_impl_dx12.h"
  48. // DirectX
  49. #include <d3d12.h>
  50. #include <dxgi1_4.h>
  51. #include <d3dcompiler.h>
  52. #ifdef _MSC_VER
  53. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  54. #endif
  55. // DirectX12 data
  56. struct ImGui_ImplDX12_RenderBuffers;
  57. struct ImGui_ImplDX12_Texture
  58. {
  59. ID3D12Resource* pTextureResource;
  60. D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
  61. D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
  62. ImGui_ImplDX12_Texture() { memset((void*)this, 0, sizeof(*this)); }
  63. };
  64. struct ImGui_ImplDX12_Data
  65. {
  66. ImGui_ImplDX12_InitInfo InitInfo;
  67. ID3D12Device* pd3dDevice;
  68. ID3D12RootSignature* pRootSignature;
  69. ID3D12PipelineState* pPipelineState;
  70. ID3D12CommandQueue* pCommandQueue;
  71. bool commandQueueOwned;
  72. DXGI_FORMAT RTVFormat;
  73. DXGI_FORMAT DSVFormat;
  74. ID3D12DescriptorHeap* pd3dSrvDescHeap;
  75. UINT numFramesInFlight;
  76. ImGui_ImplDX12_RenderBuffers* pFrameResources;
  77. UINT frameIndex;
  78. ImGui_ImplDX12_Texture FontTexture;
  79. bool LegacySingleDescriptorUsed;
  80. ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; }
  81. };
  82. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  83. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  84. static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
  85. {
  86. return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  87. }
  88. // Buffers used during the rendering of a frame
  89. struct ImGui_ImplDX12_RenderBuffers
  90. {
  91. ID3D12Resource* IndexBuffer;
  92. ID3D12Resource* VertexBuffer;
  93. int IndexBufferSize;
  94. int VertexBufferSize;
  95. };
  96. struct VERTEX_CONSTANT_BUFFER_DX12
  97. {
  98. float mvp[4][4];
  99. };
  100. // Functions
  101. static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
  102. {
  103. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  104. // Setup orthographic projection matrix into our constant buffer
  105. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  106. VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
  107. {
  108. float L = draw_data->DisplayPos.x;
  109. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  110. float T = draw_data->DisplayPos.y;
  111. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  112. float mvp[4][4] =
  113. {
  114. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  115. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  116. { 0.0f, 0.0f, 0.5f, 0.0f },
  117. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  118. };
  119. memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
  120. }
  121. // Setup viewport
  122. D3D12_VIEWPORT vp = {};
  123. vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x;
  124. vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y;
  125. vp.MinDepth = 0.0f;
  126. vp.MaxDepth = 1.0f;
  127. vp.TopLeftX = vp.TopLeftY = 0.0f;
  128. command_list->RSSetViewports(1, &vp);
  129. // Bind shader and vertex buffers
  130. unsigned int stride = sizeof(ImDrawVert);
  131. unsigned int offset = 0;
  132. D3D12_VERTEX_BUFFER_VIEW vbv = {};
  133. vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
  134. vbv.SizeInBytes = fr->VertexBufferSize * stride;
  135. vbv.StrideInBytes = stride;
  136. command_list->IASetVertexBuffers(0, 1, &vbv);
  137. D3D12_INDEX_BUFFER_VIEW ibv = {};
  138. ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
  139. ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
  140. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  141. command_list->IASetIndexBuffer(&ibv);
  142. command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  143. command_list->SetPipelineState(bd->pPipelineState);
  144. command_list->SetGraphicsRootSignature(bd->pRootSignature);
  145. command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  146. // Setup blend factor
  147. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  148. command_list->OMSetBlendFactor(blend_factor);
  149. }
  150. template<typename T>
  151. static inline void SafeRelease(T*& res)
  152. {
  153. if (res)
  154. res->Release();
  155. res = nullptr;
  156. }
  157. // Render function
  158. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
  159. {
  160. // Avoid rendering when minimized
  161. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  162. return;
  163. // FIXME: We are assuming that this only gets called once per frame!
  164. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  165. bd->frameIndex = bd->frameIndex + 1;
  166. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
  167. // Create and grow vertex/index buffers if needed
  168. if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
  169. {
  170. SafeRelease(fr->VertexBuffer);
  171. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  172. D3D12_HEAP_PROPERTIES props = {};
  173. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  174. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  175. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  176. D3D12_RESOURCE_DESC desc = {};
  177. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  178. desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
  179. desc.Height = 1;
  180. desc.DepthOrArraySize = 1;
  181. desc.MipLevels = 1;
  182. desc.Format = DXGI_FORMAT_UNKNOWN;
  183. desc.SampleDesc.Count = 1;
  184. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  185. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  186. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
  187. return;
  188. }
  189. if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
  190. {
  191. SafeRelease(fr->IndexBuffer);
  192. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  193. D3D12_HEAP_PROPERTIES props = {};
  194. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  195. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  196. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  197. D3D12_RESOURCE_DESC desc = {};
  198. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  199. desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
  200. desc.Height = 1;
  201. desc.DepthOrArraySize = 1;
  202. desc.MipLevels = 1;
  203. desc.Format = DXGI_FORMAT_UNKNOWN;
  204. desc.SampleDesc.Count = 1;
  205. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  206. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  207. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
  208. return;
  209. }
  210. // Upload vertex/index data into a single contiguous GPU buffer
  211. // During Map() we specify a null read range (as per DX12 API, this is informational and for tooling only)
  212. void* vtx_resource, *idx_resource;
  213. D3D12_RANGE range = { 0, 0 };
  214. if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
  215. return;
  216. if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
  217. return;
  218. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
  219. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
  220. for (int n = 0; n < draw_data->CmdListsCount; n++)
  221. {
  222. const ImDrawList* draw_list = draw_data->CmdLists[n];
  223. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  224. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  225. vtx_dst += draw_list->VtxBuffer.Size;
  226. idx_dst += draw_list->IdxBuffer.Size;
  227. }
  228. // During Unmap() we specify the written range (as per DX12 API, this is informational and for tooling only)
  229. range.End = (SIZE_T)((intptr_t)vtx_dst - (intptr_t)vtx_resource);
  230. IM_ASSERT(range.End == draw_data->TotalVtxCount * sizeof(ImDrawVert));
  231. fr->VertexBuffer->Unmap(0, &range);
  232. range.End = (SIZE_T)((intptr_t)idx_dst - (intptr_t)idx_resource);
  233. IM_ASSERT(range.End == draw_data->TotalIdxCount * sizeof(ImDrawIdx));
  234. fr->IndexBuffer->Unmap(0, &range);
  235. // Setup desired DX state
  236. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  237. // Setup render state structure (for callbacks and custom texture bindings)
  238. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  239. ImGui_ImplDX12_RenderState render_state;
  240. render_state.Device = bd->pd3dDevice;
  241. render_state.CommandList = command_list;
  242. platform_io.Renderer_RenderState = &render_state;
  243. // Render command lists
  244. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  245. int global_vtx_offset = 0;
  246. int global_idx_offset = 0;
  247. ImVec2 clip_off = draw_data->DisplayPos;
  248. ImVec2 clip_scale = draw_data->FramebufferScale;
  249. for (int n = 0; n < draw_data->CmdListsCount; n++)
  250. {
  251. const ImDrawList* draw_list = draw_data->CmdLists[n];
  252. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  253. {
  254. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  255. if (pcmd->UserCallback != nullptr)
  256. {
  257. // User callback, registered via ImDrawList::AddCallback()
  258. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  259. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  260. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  261. else
  262. pcmd->UserCallback(draw_list, pcmd);
  263. }
  264. else
  265. {
  266. // Project scissor/clipping rectangles into framebuffer space
  267. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  268. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  269. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  270. continue;
  271. // Apply scissor/clipping rectangle
  272. const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  273. command_list->RSSetScissorRects(1, &r);
  274. // Bind texture, Draw
  275. D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
  276. texture_handle.ptr = (UINT64)pcmd->GetTexID();
  277. command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
  278. command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  279. }
  280. }
  281. global_idx_offset += draw_list->IdxBuffer.Size;
  282. global_vtx_offset += draw_list->VtxBuffer.Size;
  283. }
  284. platform_io.Renderer_RenderState = nullptr;
  285. }
  286. static void ImGui_ImplDX12_CreateFontsTexture()
  287. {
  288. // Build texture atlas
  289. ImGuiIO& io = ImGui::GetIO();
  290. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  291. unsigned char* pixels;
  292. int width, height;
  293. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  294. // Upload texture to graphics system
  295. ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
  296. {
  297. D3D12_HEAP_PROPERTIES props = {};
  298. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  299. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  300. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  301. D3D12_RESOURCE_DESC desc;
  302. ZeroMemory(&desc, sizeof(desc));
  303. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  304. desc.Alignment = 0;
  305. desc.Width = width;
  306. desc.Height = height;
  307. desc.DepthOrArraySize = 1;
  308. desc.MipLevels = 1;
  309. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  310. desc.SampleDesc.Count = 1;
  311. desc.SampleDesc.Quality = 0;
  312. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  313. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  314. ID3D12Resource* pTexture = nullptr;
  315. bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  316. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
  317. UINT upload_pitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  318. UINT upload_size = height * upload_pitch;
  319. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  320. desc.Alignment = 0;
  321. desc.Width = upload_size;
  322. desc.Height = 1;
  323. desc.DepthOrArraySize = 1;
  324. desc.MipLevels = 1;
  325. desc.Format = DXGI_FORMAT_UNKNOWN;
  326. desc.SampleDesc.Count = 1;
  327. desc.SampleDesc.Quality = 0;
  328. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  329. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  330. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  331. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  332. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  333. ID3D12Resource* uploadBuffer = nullptr;
  334. HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  335. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer));
  336. IM_ASSERT(SUCCEEDED(hr));
  337. void* mapped = nullptr;
  338. D3D12_RANGE range = { 0, upload_size };
  339. hr = uploadBuffer->Map(0, &range, &mapped);
  340. IM_ASSERT(SUCCEEDED(hr));
  341. for (int y = 0; y < height; y++)
  342. memcpy((void*) ((uintptr_t) mapped + y * upload_pitch), pixels + y * width * 4, width * 4);
  343. uploadBuffer->Unmap(0, &range);
  344. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  345. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  346. {
  347. srcLocation.pResource = uploadBuffer;
  348. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  349. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  350. srcLocation.PlacedFootprint.Footprint.Width = width;
  351. srcLocation.PlacedFootprint.Footprint.Height = height;
  352. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  353. srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch;
  354. dstLocation.pResource = pTexture;
  355. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  356. dstLocation.SubresourceIndex = 0;
  357. }
  358. D3D12_RESOURCE_BARRIER barrier = {};
  359. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  360. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  361. barrier.Transition.pResource = pTexture;
  362. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  363. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  364. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  365. ID3D12Fence* fence = nullptr;
  366. hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
  367. IM_ASSERT(SUCCEEDED(hr));
  368. HANDLE event = ::CreateEvent(0, 0, 0, 0);
  369. IM_ASSERT(event != nullptr);
  370. ID3D12CommandAllocator* cmdAlloc = nullptr;
  371. hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
  372. IM_ASSERT(SUCCEEDED(hr));
  373. ID3D12GraphicsCommandList* cmdList = nullptr;
  374. hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList));
  375. IM_ASSERT(SUCCEEDED(hr));
  376. cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr);
  377. cmdList->ResourceBarrier(1, &barrier);
  378. hr = cmdList->Close();
  379. IM_ASSERT(SUCCEEDED(hr));
  380. ID3D12CommandQueue* cmdQueue = bd->pCommandQueue;
  381. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
  382. hr = cmdQueue->Signal(fence, 1);
  383. IM_ASSERT(SUCCEEDED(hr));
  384. fence->SetEventOnCompletion(1, event);
  385. ::WaitForSingleObject(event, INFINITE);
  386. cmdList->Release();
  387. cmdAlloc->Release();
  388. ::CloseHandle(event);
  389. fence->Release();
  390. uploadBuffer->Release();
  391. // Create texture view
  392. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  393. ZeroMemory(&srvDesc, sizeof(srvDesc));
  394. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  395. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  396. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  397. srvDesc.Texture2D.MostDetailedMip = 0;
  398. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  399. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, font_tex->hFontSrvCpuDescHandle);
  400. SafeRelease(font_tex->pTextureResource);
  401. font_tex->pTextureResource = pTexture;
  402. }
  403. // Store our identifier
  404. io.Fonts->SetTexID((ImTextureID)font_tex->hFontSrvGpuDescHandle.ptr);
  405. }
  406. bool ImGui_ImplDX12_CreateDeviceObjects()
  407. {
  408. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  409. if (!bd || !bd->pd3dDevice)
  410. return false;
  411. if (bd->pPipelineState)
  412. ImGui_ImplDX12_InvalidateDeviceObjects();
  413. // Create the root signature
  414. {
  415. D3D12_DESCRIPTOR_RANGE descRange = {};
  416. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  417. descRange.NumDescriptors = 1;
  418. descRange.BaseShaderRegister = 0;
  419. descRange.RegisterSpace = 0;
  420. descRange.OffsetInDescriptorsFromTableStart = 0;
  421. D3D12_ROOT_PARAMETER param[2] = {};
  422. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  423. param[0].Constants.ShaderRegister = 0;
  424. param[0].Constants.RegisterSpace = 0;
  425. param[0].Constants.Num32BitValues = 16;
  426. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  427. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  428. param[1].DescriptorTable.NumDescriptorRanges = 1;
  429. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  430. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  431. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  432. D3D12_STATIC_SAMPLER_DESC staticSampler = {};
  433. staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  434. staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  435. staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  436. staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  437. staticSampler.MipLODBias = 0.f;
  438. staticSampler.MaxAnisotropy = 0;
  439. staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  440. staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  441. staticSampler.MinLOD = 0.f;
  442. staticSampler.MaxLOD = D3D12_FLOAT32_MAX;
  443. staticSampler.ShaderRegister = 0;
  444. staticSampler.RegisterSpace = 0;
  445. staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  446. D3D12_ROOT_SIGNATURE_DESC desc = {};
  447. desc.NumParameters = _countof(param);
  448. desc.pParameters = param;
  449. desc.NumStaticSamplers = 1;
  450. desc.pStaticSamplers = &staticSampler;
  451. desc.Flags =
  452. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  453. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  454. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  455. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  456. // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
  457. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
  458. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
  459. if (d3d12_dll == nullptr)
  460. {
  461. // Attempt to load d3d12.dll from local directories. This will only succeed if
  462. // (1) the current OS is Windows 7, and
  463. // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
  464. // See https://github.com/ocornut/imgui/pull/3696 for details.
  465. const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample
  466. for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
  467. if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
  468. break;
  469. // If failed, we are on Windows >= 10.
  470. if (d3d12_dll == nullptr)
  471. d3d12_dll = ::LoadLibraryA("d3d12.dll");
  472. if (d3d12_dll == nullptr)
  473. return false;
  474. }
  475. PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)(void*)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
  476. if (D3D12SerializeRootSignatureFn == nullptr)
  477. return false;
  478. ID3DBlob* blob = nullptr;
  479. if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
  480. return false;
  481. bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
  482. blob->Release();
  483. }
  484. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  485. // If you would like to use this DX12 sample code but remove this dependency you can:
  486. // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
  487. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  488. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  489. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
  490. psoDesc.NodeMask = 1;
  491. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  492. psoDesc.pRootSignature = bd->pRootSignature;
  493. psoDesc.SampleMask = UINT_MAX;
  494. psoDesc.NumRenderTargets = 1;
  495. psoDesc.RTVFormats[0] = bd->RTVFormat;
  496. psoDesc.DSVFormat = bd->DSVFormat;
  497. psoDesc.SampleDesc.Count = 1;
  498. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  499. ID3DBlob* vertexShaderBlob;
  500. ID3DBlob* pixelShaderBlob;
  501. // Create the vertex shader
  502. {
  503. static const char* vertexShader =
  504. "cbuffer vertexBuffer : register(b0) \
  505. {\
  506. float4x4 ProjectionMatrix; \
  507. };\
  508. struct VS_INPUT\
  509. {\
  510. float2 pos : POSITION;\
  511. float4 col : COLOR0;\
  512. float2 uv : TEXCOORD0;\
  513. };\
  514. \
  515. struct PS_INPUT\
  516. {\
  517. float4 pos : SV_POSITION;\
  518. float4 col : COLOR0;\
  519. float2 uv : TEXCOORD0;\
  520. };\
  521. \
  522. PS_INPUT main(VS_INPUT input)\
  523. {\
  524. PS_INPUT output;\
  525. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  526. output.col = input.col;\
  527. output.uv = input.uv;\
  528. return output;\
  529. }";
  530. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
  531. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  532. psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
  533. // Create the input layout
  534. static D3D12_INPUT_ELEMENT_DESC local_layout[] =
  535. {
  536. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  537. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  538. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  539. };
  540. psoDesc.InputLayout = { local_layout, 3 };
  541. }
  542. // Create the pixel shader
  543. {
  544. static const char* pixelShader =
  545. "struct PS_INPUT\
  546. {\
  547. float4 pos : SV_POSITION;\
  548. float4 col : COLOR0;\
  549. float2 uv : TEXCOORD0;\
  550. };\
  551. SamplerState sampler0 : register(s0);\
  552. Texture2D texture0 : register(t0);\
  553. \
  554. float4 main(PS_INPUT input) : SV_Target\
  555. {\
  556. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  557. return out_col; \
  558. }";
  559. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
  560. {
  561. vertexShaderBlob->Release();
  562. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  563. }
  564. psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
  565. }
  566. // Create the blending setup
  567. {
  568. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  569. desc.AlphaToCoverageEnable = false;
  570. desc.RenderTarget[0].BlendEnable = true;
  571. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  572. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  573. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  574. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
  575. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  576. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  577. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  578. }
  579. // Create the rasterizer state
  580. {
  581. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  582. desc.FillMode = D3D12_FILL_MODE_SOLID;
  583. desc.CullMode = D3D12_CULL_MODE_NONE;
  584. desc.FrontCounterClockwise = FALSE;
  585. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  586. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  587. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  588. desc.DepthClipEnable = true;
  589. desc.MultisampleEnable = FALSE;
  590. desc.AntialiasedLineEnable = FALSE;
  591. desc.ForcedSampleCount = 0;
  592. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  593. }
  594. // Create depth-stencil State
  595. {
  596. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  597. desc.DepthEnable = false;
  598. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  599. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  600. desc.StencilEnable = false;
  601. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  602. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  603. desc.BackFace = desc.FrontFace;
  604. }
  605. HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
  606. vertexShaderBlob->Release();
  607. pixelShaderBlob->Release();
  608. if (result_pipeline_state != S_OK)
  609. return false;
  610. ImGui_ImplDX12_CreateFontsTexture();
  611. return true;
  612. }
  613. void ImGui_ImplDX12_InvalidateDeviceObjects()
  614. {
  615. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  616. if (!bd || !bd->pd3dDevice)
  617. return;
  618. if (bd->commandQueueOwned)
  619. SafeRelease(bd->pCommandQueue);
  620. bd->commandQueueOwned = false;
  621. SafeRelease(bd->pRootSignature);
  622. SafeRelease(bd->pPipelineState);
  623. // Free SRV descriptor used by texture
  624. ImGuiIO& io = ImGui::GetIO();
  625. ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
  626. bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, font_tex->hFontSrvCpuDescHandle, font_tex->hFontSrvGpuDescHandle);
  627. SafeRelease(font_tex->pTextureResource);
  628. io.Fonts->SetTexID(0); // We copied bd->hFontSrvGpuDescHandle to io.Fonts->TexID so let's clear that as well.
  629. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  630. {
  631. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
  632. SafeRelease(fr->IndexBuffer);
  633. SafeRelease(fr->VertexBuffer);
  634. }
  635. }
  636. bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
  637. {
  638. ImGuiIO& io = ImGui::GetIO();
  639. IMGUI_CHECKVERSION();
  640. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  641. // Setup backend capabilities flags
  642. ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
  643. bd->InitInfo = *init_info; // Deep copy
  644. init_info = &bd->InitInfo;
  645. bd->pd3dDevice = init_info->Device;
  646. IM_ASSERT(init_info->CommandQueue != NULL);
  647. bd->pCommandQueue = init_info->CommandQueue;
  648. bd->RTVFormat = init_info->RTVFormat;
  649. bd->DSVFormat = init_info->DSVFormat;
  650. bd->numFramesInFlight = init_info->NumFramesInFlight;
  651. bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
  652. io.BackendRendererUserData = (void*)bd;
  653. io.BackendRendererName = "imgui_impl_dx12";
  654. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  655. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  656. if (init_info->SrvDescriptorAllocFn == nullptr)
  657. {
  658. // Wrap legacy behavior of passing space for a single descriptor
  659. IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
  660. init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle)
  661. {
  662. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  663. IM_ASSERT(bd->LegacySingleDescriptorUsed == false && "Only 1 simultaneous texture allowed with legacy ImGui_ImplDX12_Init() signature!");
  664. *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor;
  665. *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor;
  666. bd->LegacySingleDescriptorUsed = true;
  667. };
  668. init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE)
  669. {
  670. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  671. IM_ASSERT(bd->LegacySingleDescriptorUsed == true);
  672. bd->LegacySingleDescriptorUsed = false;
  673. };
  674. }
  675. #endif
  676. // Allocate 1 SRV descriptor for the font texture
  677. IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr);
  678. init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->FontTexture.hFontSrvCpuDescHandle, &bd->FontTexture.hFontSrvGpuDescHandle);
  679. // Create buffers with a default size (they will later be grown as needed)
  680. bd->frameIndex = UINT_MAX;
  681. bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[bd->numFramesInFlight];
  682. for (int i = 0; i < (int)bd->numFramesInFlight; i++)
  683. {
  684. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
  685. fr->IndexBuffer = nullptr;
  686. fr->VertexBuffer = nullptr;
  687. fr->IndexBufferSize = 10000;
  688. fr->VertexBufferSize = 5000;
  689. }
  690. return true;
  691. }
  692. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  693. // Legacy initialization API Obsoleted in 1.91.5
  694. // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap'
  695. bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
  696. {
  697. ImGui_ImplDX12_InitInfo init_info;
  698. init_info.Device = device;
  699. init_info.NumFramesInFlight = num_frames_in_flight;
  700. init_info.RTVFormat = rtv_format;
  701. init_info.SrvDescriptorHeap = srv_descriptor_heap;
  702. init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle;
  703. init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;
  704. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  705. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  706. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  707. queueDesc.NodeMask = 1;
  708. HRESULT hr = device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&init_info.CommandQueue));
  709. IM_ASSERT(SUCCEEDED(hr));
  710. bool ret = ImGui_ImplDX12_Init(&init_info);
  711. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  712. bd->commandQueueOwned = true;
  713. return ret;
  714. }
  715. #endif
  716. void ImGui_ImplDX12_Shutdown()
  717. {
  718. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  719. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  720. ImGuiIO& io = ImGui::GetIO();
  721. // Clean up windows and device objects
  722. ImGui_ImplDX12_InvalidateDeviceObjects();
  723. delete[] bd->pFrameResources;
  724. io.BackendRendererName = nullptr;
  725. io.BackendRendererUserData = nullptr;
  726. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
  727. IM_DELETE(bd);
  728. }
  729. void ImGui_ImplDX12_NewFrame()
  730. {
  731. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  732. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
  733. if (!bd->pPipelineState)
  734. ImGui_ImplDX12_CreateDeviceObjects();
  735. }
  736. //-----------------------------------------------------------------------------
  737. #endif // #ifndef IMGUI_DISABLE