imgui_impl_dx12.cpp 37 KB

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