imgui_impl_dx12.cpp 44 KB

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