imgui_impl_dx12.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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. // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  9. // FIXME: The transition from removing a viewport and moving the window in an existing hosted viewport tends to flicker.
  10. // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
  11. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
  12. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  13. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  14. // Learn about Dear ImGui:
  15. // - FAQ https://dearimgui.com/faq
  16. // - Getting Started https://dearimgui.com/getting-started
  17. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  18. // - Introduction, links and more at the top of imgui.cpp
  19. // CHANGELOG
  20. // (minor and older changes stripped away, please see git history for details)
  21. // 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
  22. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
  23. // 2025-06-19: Fixed build on MinGW. (#8702, #4594)
  24. // 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
  25. // 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).
  26. // 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)
  27. // 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own.
  28. // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat.
  29. // 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).
  30. // 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.
  31. // 2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
  32. // 2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  33. // 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.
  34. // 2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
  35. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  36. // 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).
  37. // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  38. // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
  39. // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
  40. // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
  41. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
  42. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
  43. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  44. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  45. // 2019-03-29: Misc: Various minor tidying up.
  46. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  47. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  48. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
  49. // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
  50. // 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).
  51. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
  52. #include "imgui.h"
  53. #ifndef IMGUI_DISABLE
  54. #include "imgui_impl_dx12.h"
  55. // DirectX
  56. #include <d3d12.h>
  57. #include <dxgi1_4.h>
  58. #include <d3dcompiler.h>
  59. #ifdef _MSC_VER
  60. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  61. #endif
  62. // Clang/GCC warnings with -Weverything
  63. #if defined(__clang__)
  64. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
  65. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  66. #endif
  67. // MinGW workaround, see #4594
  68. typedef decltype(D3D12SerializeRootSignature) *_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE;
  69. // DirectX12 data
  70. struct ImGui_ImplDX12_RenderBuffers;
  71. struct ImGui_ImplDX12_Texture
  72. {
  73. ID3D12Resource* pTextureResource;
  74. D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
  75. D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
  76. ImGui_ImplDX12_Texture() { memset((void*)this, 0, sizeof(*this)); }
  77. };
  78. struct ImGui_ImplDX12_Data
  79. {
  80. ImGui_ImplDX12_InitInfo InitInfo;
  81. ID3D12Device* pd3dDevice;
  82. ID3D12RootSignature* pRootSignature;
  83. ID3D12PipelineState* pPipelineState;
  84. ID3D12CommandQueue* pCommandQueue;
  85. bool commandQueueOwned;
  86. DXGI_FORMAT RTVFormat;
  87. DXGI_FORMAT DSVFormat;
  88. ID3D12DescriptorHeap* pd3dSrvDescHeap;
  89. UINT numFramesInFlight;
  90. ImGui_ImplDX12_RenderBuffers* pFrameResources;
  91. UINT frameIndex;
  92. bool LegacySingleDescriptorUsed;
  93. ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); }
  94. };
  95. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  96. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  97. static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
  98. {
  99. return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  100. }
  101. // Buffers used during the rendering of a frame
  102. struct ImGui_ImplDX12_RenderBuffers
  103. {
  104. ID3D12Resource* IndexBuffer;
  105. ID3D12Resource* VertexBuffer;
  106. int IndexBufferSize;
  107. int VertexBufferSize;
  108. };
  109. // Buffers used for secondary viewports created by the multi-viewports systems
  110. struct ImGui_ImplDX12_FrameContext
  111. {
  112. ID3D12CommandAllocator* CommandAllocator;
  113. ID3D12Resource* RenderTarget;
  114. D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors;
  115. };
  116. // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
  117. // Main viewport created by application will only use the Resources field.
  118. // Secondary viewports created by this backend will use all the fields (including Window fields),
  119. struct ImGui_ImplDX12_ViewportData
  120. {
  121. // Window
  122. ID3D12CommandQueue* CommandQueue;
  123. ID3D12GraphicsCommandList* CommandList;
  124. ID3D12DescriptorHeap* RtvDescHeap;
  125. IDXGISwapChain3* SwapChain;
  126. ID3D12Fence* Fence;
  127. UINT64 FenceSignaledValue;
  128. HANDLE FenceEvent;
  129. UINT NumFramesInFlight;
  130. ImGui_ImplDX12_FrameContext* FrameCtx;
  131. // Render buffers
  132. UINT FrameIndex;
  133. ImGui_ImplDX12_RenderBuffers* FrameRenderBuffers;
  134. ImGui_ImplDX12_ViewportData(UINT num_frames_in_flight)
  135. {
  136. CommandQueue = nullptr;
  137. CommandList = nullptr;
  138. RtvDescHeap = nullptr;
  139. SwapChain = nullptr;
  140. Fence = nullptr;
  141. FenceSignaledValue = 0;
  142. FenceEvent = nullptr;
  143. NumFramesInFlight = num_frames_in_flight;
  144. FrameCtx = new ImGui_ImplDX12_FrameContext[NumFramesInFlight];
  145. FrameIndex = UINT_MAX;
  146. FrameRenderBuffers = new ImGui_ImplDX12_RenderBuffers[NumFramesInFlight];
  147. for (UINT i = 0; i < NumFramesInFlight; ++i)
  148. {
  149. FrameCtx[i].CommandAllocator = nullptr;
  150. FrameCtx[i].RenderTarget = nullptr;
  151. // Create buffers with a default size (they will later be grown as needed)
  152. FrameRenderBuffers[i].IndexBuffer = nullptr;
  153. FrameRenderBuffers[i].VertexBuffer = nullptr;
  154. FrameRenderBuffers[i].VertexBufferSize = 5000;
  155. FrameRenderBuffers[i].IndexBufferSize = 10000;
  156. }
  157. }
  158. ~ImGui_ImplDX12_ViewportData()
  159. {
  160. IM_ASSERT(CommandQueue == nullptr && CommandList == nullptr);
  161. IM_ASSERT(RtvDescHeap == nullptr);
  162. IM_ASSERT(SwapChain == nullptr);
  163. IM_ASSERT(Fence == nullptr);
  164. IM_ASSERT(FenceEvent == nullptr);
  165. for (UINT i = 0; i < NumFramesInFlight; ++i)
  166. {
  167. IM_ASSERT(FrameCtx[i].CommandAllocator == nullptr && FrameCtx[i].RenderTarget == nullptr);
  168. IM_ASSERT(FrameRenderBuffers[i].IndexBuffer == nullptr && FrameRenderBuffers[i].VertexBuffer == nullptr);
  169. }
  170. delete[] FrameCtx; FrameCtx = nullptr;
  171. delete[] FrameRenderBuffers; FrameRenderBuffers = nullptr;
  172. }
  173. };
  174. struct VERTEX_CONSTANT_BUFFER_DX12
  175. {
  176. float mvp[4][4];
  177. };
  178. // Forward Declarations
  179. static void ImGui_ImplDX12_InitMultiViewportSupport();
  180. static void ImGui_ImplDX12_ShutdownMultiViewportSupport();
  181. // Functions
  182. static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
  183. {
  184. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  185. // Setup orthographic projection matrix into our constant buffer
  186. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  187. VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
  188. {
  189. float L = draw_data->DisplayPos.x;
  190. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  191. float T = draw_data->DisplayPos.y;
  192. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  193. float mvp[4][4] =
  194. {
  195. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  196. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  197. { 0.0f, 0.0f, 0.5f, 0.0f },
  198. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  199. };
  200. memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
  201. }
  202. // Setup viewport
  203. D3D12_VIEWPORT vp = {};
  204. vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x;
  205. vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y;
  206. vp.MinDepth = 0.0f;
  207. vp.MaxDepth = 1.0f;
  208. vp.TopLeftX = vp.TopLeftY = 0.0f;
  209. command_list->RSSetViewports(1, &vp);
  210. // Bind shader and vertex buffers
  211. unsigned int stride = sizeof(ImDrawVert);
  212. unsigned int offset = 0;
  213. D3D12_VERTEX_BUFFER_VIEW vbv = {};
  214. vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
  215. vbv.SizeInBytes = fr->VertexBufferSize * stride;
  216. vbv.StrideInBytes = stride;
  217. command_list->IASetVertexBuffers(0, 1, &vbv);
  218. D3D12_INDEX_BUFFER_VIEW ibv = {};
  219. ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
  220. ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
  221. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  222. command_list->IASetIndexBuffer(&ibv);
  223. command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  224. command_list->SetPipelineState(bd->pPipelineState);
  225. command_list->SetGraphicsRootSignature(bd->pRootSignature);
  226. command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  227. // Setup blend factor
  228. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  229. command_list->OMSetBlendFactor(blend_factor);
  230. }
  231. template<typename T>
  232. static inline void SafeRelease(T*& res)
  233. {
  234. if (res)
  235. res->Release();
  236. res = nullptr;
  237. }
  238. // Render function
  239. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
  240. {
  241. // Avoid rendering when minimized
  242. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  243. return;
  244. // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
  245. // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
  246. if (draw_data->Textures != nullptr)
  247. for (ImTextureData* tex : *draw_data->Textures)
  248. if (tex->Status != ImTextureStatus_OK)
  249. ImGui_ImplDX12_UpdateTexture(tex);
  250. // FIXME: We are assuming that this only gets called once per frame!
  251. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  252. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)draw_data->OwnerViewport->RendererUserData;
  253. vd->FrameIndex++;
  254. ImGui_ImplDX12_RenderBuffers* fr = &vd->FrameRenderBuffers[vd->FrameIndex % bd->numFramesInFlight];
  255. // Create and grow vertex/index buffers if needed
  256. if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
  257. {
  258. SafeRelease(fr->VertexBuffer);
  259. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  260. D3D12_HEAP_PROPERTIES props = {};
  261. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  262. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  263. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  264. D3D12_RESOURCE_DESC desc = {};
  265. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  266. desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
  267. desc.Height = 1;
  268. desc.DepthOrArraySize = 1;
  269. desc.MipLevels = 1;
  270. desc.Format = DXGI_FORMAT_UNKNOWN;
  271. desc.SampleDesc.Count = 1;
  272. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  273. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  274. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
  275. return;
  276. }
  277. if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
  278. {
  279. SafeRelease(fr->IndexBuffer);
  280. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  281. D3D12_HEAP_PROPERTIES props = {};
  282. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  283. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  284. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  285. D3D12_RESOURCE_DESC desc = {};
  286. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  287. desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
  288. desc.Height = 1;
  289. desc.DepthOrArraySize = 1;
  290. desc.MipLevels = 1;
  291. desc.Format = DXGI_FORMAT_UNKNOWN;
  292. desc.SampleDesc.Count = 1;
  293. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  294. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  295. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
  296. return;
  297. }
  298. // Upload vertex/index data into a single contiguous GPU buffer
  299. // During Map() we specify a null read range (as per DX12 API, this is informational and for tooling only)
  300. void* vtx_resource, *idx_resource;
  301. D3D12_RANGE range = { 0, 0 };
  302. if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
  303. return;
  304. if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
  305. return;
  306. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
  307. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
  308. for (const ImDrawList* draw_list : draw_data->CmdLists)
  309. {
  310. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  311. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  312. vtx_dst += draw_list->VtxBuffer.Size;
  313. idx_dst += draw_list->IdxBuffer.Size;
  314. }
  315. // During Unmap() we specify the written range (as per DX12 API, this is informational and for tooling only)
  316. range.End = (SIZE_T)((intptr_t)vtx_dst - (intptr_t)vtx_resource);
  317. IM_ASSERT(range.End == draw_data->TotalVtxCount * sizeof(ImDrawVert));
  318. fr->VertexBuffer->Unmap(0, &range);
  319. range.End = (SIZE_T)((intptr_t)idx_dst - (intptr_t)idx_resource);
  320. IM_ASSERT(range.End == draw_data->TotalIdxCount * sizeof(ImDrawIdx));
  321. fr->IndexBuffer->Unmap(0, &range);
  322. // Setup desired DX state
  323. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  324. // Setup render state structure (for callbacks and custom texture bindings)
  325. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  326. ImGui_ImplDX12_RenderState render_state;
  327. render_state.Device = bd->pd3dDevice;
  328. render_state.CommandList = command_list;
  329. platform_io.Renderer_RenderState = &render_state;
  330. // Render command lists
  331. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  332. int global_vtx_offset = 0;
  333. int global_idx_offset = 0;
  334. ImVec2 clip_off = draw_data->DisplayPos;
  335. ImVec2 clip_scale = draw_data->FramebufferScale;
  336. for (const ImDrawList* draw_list : draw_data->CmdLists)
  337. {
  338. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  339. {
  340. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  341. if (pcmd->UserCallback != nullptr)
  342. {
  343. // User callback, registered via ImDrawList::AddCallback()
  344. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  345. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  346. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  347. else
  348. pcmd->UserCallback(draw_list, pcmd);
  349. }
  350. else
  351. {
  352. // Project scissor/clipping rectangles into framebuffer space
  353. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  354. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  355. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  356. continue;
  357. // Apply scissor/clipping rectangle
  358. const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  359. command_list->RSSetScissorRects(1, &r);
  360. // Bind texture, Draw
  361. D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
  362. texture_handle.ptr = (UINT64)pcmd->GetTexID();
  363. command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
  364. command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  365. }
  366. }
  367. global_idx_offset += draw_list->IdxBuffer.Size;
  368. global_vtx_offset += draw_list->VtxBuffer.Size;
  369. }
  370. platform_io.Renderer_RenderState = nullptr;
  371. }
  372. static void ImGui_ImplDX12_DestroyTexture(ImTextureData* tex)
  373. {
  374. ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData;
  375. if (backend_tex == nullptr)
  376. return;
  377. IM_ASSERT(backend_tex->hFontSrvGpuDescHandle.ptr == (UINT64)tex->TexID);
  378. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  379. bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, backend_tex->hFontSrvCpuDescHandle, backend_tex->hFontSrvGpuDescHandle);
  380. SafeRelease(backend_tex->pTextureResource);
  381. backend_tex->hFontSrvCpuDescHandle.ptr = 0;
  382. backend_tex->hFontSrvGpuDescHandle.ptr = 0;
  383. IM_DELETE(backend_tex);
  384. // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
  385. tex->SetTexID(ImTextureID_Invalid);
  386. tex->SetStatus(ImTextureStatus_Destroyed);
  387. tex->BackendUserData = nullptr;
  388. }
  389. void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex)
  390. {
  391. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  392. bool need_barrier_before_copy = true; // Do we need a resource barrier before we copy new data in?
  393. if (tex->Status == ImTextureStatus_WantCreate)
  394. {
  395. // Create and upload new texture to graphics system
  396. //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
  397. IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
  398. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  399. ImGui_ImplDX12_Texture* backend_tex = IM_NEW(ImGui_ImplDX12_Texture)();
  400. bd->InitInfo.SrvDescriptorAllocFn(&bd->InitInfo, &backend_tex->hFontSrvCpuDescHandle, &backend_tex->hFontSrvGpuDescHandle); // Allocate a desctriptor handle
  401. D3D12_HEAP_PROPERTIES props = {};
  402. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  403. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  404. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  405. D3D12_RESOURCE_DESC desc;
  406. ZeroMemory(&desc, sizeof(desc));
  407. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  408. desc.Alignment = 0;
  409. desc.Width = tex->Width;
  410. desc.Height = tex->Height;
  411. desc.DepthOrArraySize = 1;
  412. desc.MipLevels = 1;
  413. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  414. desc.SampleDesc.Count = 1;
  415. desc.SampleDesc.Quality = 0;
  416. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  417. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  418. ID3D12Resource* pTexture = nullptr;
  419. bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  420. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
  421. // Create SRV
  422. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  423. ZeroMemory(&srvDesc, sizeof(srvDesc));
  424. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  425. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  426. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  427. srvDesc.Texture2D.MostDetailedMip = 0;
  428. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  429. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, backend_tex->hFontSrvCpuDescHandle);
  430. SafeRelease(backend_tex->pTextureResource);
  431. backend_tex->pTextureResource = pTexture;
  432. // Store identifiers
  433. tex->SetTexID((ImTextureID)backend_tex->hFontSrvGpuDescHandle.ptr);
  434. tex->BackendUserData = backend_tex;
  435. 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
  436. // We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below.
  437. }
  438. if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
  439. {
  440. ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData;
  441. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  442. // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture.
  443. // FIXME-OPT: Uploading single box even when using ImTextureStatus_WantUpdates. Could use tex->Updates[]
  444. // - Copy all blocks contiguously in upload buffer.
  445. // - Barrier before copy, submit all CopyTextureRegion(), barrier after copy.
  446. const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x;
  447. const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y;
  448. const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w;
  449. const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h;
  450. // Update full texture or selected blocks. We only ever write to textures regions which have never been used before!
  451. // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions.
  452. UINT upload_pitch_src = upload_w * tex->BytesPerPixel;
  453. UINT upload_pitch_dst = (upload_pitch_src + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  454. UINT upload_size = upload_pitch_dst * upload_h;
  455. D3D12_RESOURCE_DESC desc;
  456. ZeroMemory(&desc, sizeof(desc));
  457. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  458. desc.Alignment = 0;
  459. desc.Width = upload_size;
  460. desc.Height = 1;
  461. desc.DepthOrArraySize = 1;
  462. desc.MipLevels = 1;
  463. desc.Format = DXGI_FORMAT_UNKNOWN;
  464. desc.SampleDesc.Count = 1;
  465. desc.SampleDesc.Quality = 0;
  466. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  467. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  468. D3D12_HEAP_PROPERTIES props;
  469. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  470. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  471. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  472. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  473. // FIXME-OPT: Can upload buffer be reused?
  474. ID3D12Resource* uploadBuffer = nullptr;
  475. HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  476. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer));
  477. IM_ASSERT(SUCCEEDED(hr));
  478. // Create temporary command list and execute immediately
  479. ID3D12Fence* fence = nullptr;
  480. hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
  481. IM_ASSERT(SUCCEEDED(hr));
  482. HANDLE event = ::CreateEvent(0, 0, 0, 0);
  483. IM_ASSERT(event != nullptr);
  484. // FIXME-OPT: Create once and reuse?
  485. ID3D12CommandAllocator* cmdAlloc = nullptr;
  486. hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
  487. IM_ASSERT(SUCCEEDED(hr));
  488. // FIXME-OPT: Can be use the one from user? (pass ID3D12GraphicsCommandList* to ImGui_ImplDX12_UpdateTextures)
  489. ID3D12GraphicsCommandList* cmdList = nullptr;
  490. hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList));
  491. IM_ASSERT(SUCCEEDED(hr));
  492. // Copy to upload buffer
  493. void* mapped = nullptr;
  494. D3D12_RANGE range = { 0, upload_size };
  495. hr = uploadBuffer->Map(0, &range, &mapped);
  496. IM_ASSERT(SUCCEEDED(hr));
  497. for (int y = 0; y < upload_h; y++)
  498. memcpy((void*)((uintptr_t)mapped + y * upload_pitch_dst), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch_src);
  499. uploadBuffer->Unmap(0, &range);
  500. if (need_barrier_before_copy)
  501. {
  502. D3D12_RESOURCE_BARRIER barrier = {};
  503. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  504. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  505. barrier.Transition.pResource = backend_tex->pTextureResource;
  506. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  507. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  508. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
  509. cmdList->ResourceBarrier(1, &barrier);
  510. }
  511. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  512. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  513. {
  514. srcLocation.pResource = uploadBuffer;
  515. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  516. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  517. srcLocation.PlacedFootprint.Footprint.Width = upload_w;
  518. srcLocation.PlacedFootprint.Footprint.Height = upload_h;
  519. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  520. srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch_dst;
  521. dstLocation.pResource = backend_tex->pTextureResource;
  522. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  523. dstLocation.SubresourceIndex = 0;
  524. }
  525. cmdList->CopyTextureRegion(&dstLocation, upload_x, upload_y, 0, &srcLocation, nullptr);
  526. {
  527. D3D12_RESOURCE_BARRIER barrier = {};
  528. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  529. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  530. barrier.Transition.pResource = backend_tex->pTextureResource;
  531. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  532. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  533. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  534. cmdList->ResourceBarrier(1, &barrier);
  535. }
  536. hr = cmdList->Close();
  537. IM_ASSERT(SUCCEEDED(hr));
  538. ID3D12CommandQueue* cmdQueue = bd->pCommandQueue;
  539. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
  540. hr = cmdQueue->Signal(fence, 1);
  541. IM_ASSERT(SUCCEEDED(hr));
  542. // FIXME-OPT: Suboptimal?
  543. // - To remove this may need to create NumFramesInFlight x ImGui_ImplDX12_FrameContext in backend data (mimick docking version)
  544. // - Store per-frame in flight: upload buffer?
  545. // - Where do cmdList and cmdAlloc fit?
  546. fence->SetEventOnCompletion(1, event);
  547. ::WaitForSingleObject(event, INFINITE);
  548. cmdList->Release();
  549. cmdAlloc->Release();
  550. ::CloseHandle(event);
  551. fence->Release();
  552. uploadBuffer->Release();
  553. tex->SetStatus(ImTextureStatus_OK);
  554. }
  555. if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames >= (int)bd->numFramesInFlight)
  556. ImGui_ImplDX12_DestroyTexture(tex);
  557. }
  558. bool ImGui_ImplDX12_CreateDeviceObjects()
  559. {
  560. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  561. if (!bd || !bd->pd3dDevice)
  562. return false;
  563. if (bd->pPipelineState)
  564. ImGui_ImplDX12_InvalidateDeviceObjects();
  565. // Create the root signature
  566. {
  567. D3D12_DESCRIPTOR_RANGE descRange = {};
  568. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  569. descRange.NumDescriptors = 1;
  570. descRange.BaseShaderRegister = 0;
  571. descRange.RegisterSpace = 0;
  572. descRange.OffsetInDescriptorsFromTableStart = 0;
  573. D3D12_ROOT_PARAMETER param[2] = {};
  574. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  575. param[0].Constants.ShaderRegister = 0;
  576. param[0].Constants.RegisterSpace = 0;
  577. param[0].Constants.Num32BitValues = 16;
  578. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  579. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  580. param[1].DescriptorTable.NumDescriptorRanges = 1;
  581. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  582. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  583. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  584. D3D12_STATIC_SAMPLER_DESC staticSampler[1] = {};
  585. staticSampler[0].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  586. staticSampler[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  587. staticSampler[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  588. staticSampler[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  589. staticSampler[0].MipLODBias = 0.f;
  590. staticSampler[0].MaxAnisotropy = 0;
  591. staticSampler[0].ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  592. staticSampler[0].BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  593. staticSampler[0].MinLOD = 0.f;
  594. staticSampler[0].MaxLOD = D3D12_FLOAT32_MAX;
  595. staticSampler[0].ShaderRegister = 0;
  596. staticSampler[0].RegisterSpace = 0;
  597. staticSampler[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  598. D3D12_ROOT_SIGNATURE_DESC desc = {};
  599. desc.NumParameters = _countof(param);
  600. desc.pParameters = param;
  601. desc.NumStaticSamplers = 1;
  602. desc.pStaticSamplers = &staticSampler[0];
  603. desc.Flags =
  604. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  605. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  606. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  607. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  608. // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
  609. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
  610. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
  611. if (d3d12_dll == nullptr)
  612. {
  613. // Attempt to load d3d12.dll from local directories. This will only succeed if
  614. // (1) the current OS is Windows 7, and
  615. // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
  616. // See https://github.com/ocornut/imgui/pull/3696 for details.
  617. 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
  618. for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
  619. if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
  620. break;
  621. // If failed, we are on Windows >= 10.
  622. if (d3d12_dll == nullptr)
  623. d3d12_dll = ::LoadLibraryA("d3d12.dll");
  624. if (d3d12_dll == nullptr)
  625. return false;
  626. }
  627. _PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)(void*)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
  628. if (D3D12SerializeRootSignatureFn == nullptr)
  629. return false;
  630. ID3DBlob* blob = nullptr;
  631. if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
  632. return false;
  633. bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
  634. blob->Release();
  635. }
  636. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  637. // If you would like to use this DX12 sample code but remove this dependency you can:
  638. // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
  639. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  640. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  641. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
  642. psoDesc.NodeMask = 1;
  643. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  644. psoDesc.pRootSignature = bd->pRootSignature;
  645. psoDesc.SampleMask = UINT_MAX;
  646. psoDesc.NumRenderTargets = 1;
  647. psoDesc.RTVFormats[0] = bd->RTVFormat;
  648. psoDesc.DSVFormat = bd->DSVFormat;
  649. psoDesc.SampleDesc.Count = 1;
  650. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  651. ID3DBlob* vertexShaderBlob;
  652. ID3DBlob* pixelShaderBlob;
  653. // Create the vertex shader
  654. {
  655. static const char* vertexShader =
  656. "cbuffer vertexBuffer : register(b0) \
  657. {\
  658. float4x4 ProjectionMatrix; \
  659. };\
  660. struct VS_INPUT\
  661. {\
  662. float2 pos : POSITION;\
  663. float4 col : COLOR0;\
  664. float2 uv : TEXCOORD0;\
  665. };\
  666. \
  667. struct PS_INPUT\
  668. {\
  669. float4 pos : SV_POSITION;\
  670. float4 col : COLOR0;\
  671. float2 uv : TEXCOORD0;\
  672. };\
  673. \
  674. PS_INPUT main(VS_INPUT input)\
  675. {\
  676. PS_INPUT output;\
  677. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  678. output.col = input.col;\
  679. output.uv = input.uv;\
  680. return output;\
  681. }";
  682. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
  683. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  684. psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
  685. // Create the input layout
  686. static D3D12_INPUT_ELEMENT_DESC local_layout[] =
  687. {
  688. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  689. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  690. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  691. };
  692. psoDesc.InputLayout = { local_layout, 3 };
  693. }
  694. // Create the pixel shader
  695. {
  696. static const char* pixelShader =
  697. "struct PS_INPUT\
  698. {\
  699. float4 pos : SV_POSITION;\
  700. float4 col : COLOR0;\
  701. float2 uv : TEXCOORD0;\
  702. };\
  703. SamplerState sampler0 : register(s0);\
  704. Texture2D texture0 : register(t0);\
  705. \
  706. float4 main(PS_INPUT input) : SV_Target\
  707. {\
  708. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  709. return out_col; \
  710. }";
  711. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
  712. {
  713. vertexShaderBlob->Release();
  714. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  715. }
  716. psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
  717. }
  718. // Create the blending setup
  719. {
  720. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  721. desc.AlphaToCoverageEnable = false;
  722. desc.RenderTarget[0].BlendEnable = true;
  723. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  724. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  725. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  726. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
  727. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  728. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  729. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  730. }
  731. // Create the rasterizer state
  732. {
  733. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  734. desc.FillMode = D3D12_FILL_MODE_SOLID;
  735. desc.CullMode = D3D12_CULL_MODE_NONE;
  736. desc.FrontCounterClockwise = FALSE;
  737. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  738. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  739. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  740. desc.DepthClipEnable = true;
  741. desc.MultisampleEnable = FALSE;
  742. desc.AntialiasedLineEnable = FALSE;
  743. desc.ForcedSampleCount = 0;
  744. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  745. }
  746. // Create depth-stencil State
  747. {
  748. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  749. desc.DepthEnable = false;
  750. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  751. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  752. desc.StencilEnable = false;
  753. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  754. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  755. desc.BackFace = desc.FrontFace;
  756. }
  757. HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
  758. vertexShaderBlob->Release();
  759. pixelShaderBlob->Release();
  760. if (result_pipeline_state != S_OK)
  761. return false;
  762. return true;
  763. }
  764. static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers)
  765. {
  766. SafeRelease(render_buffers->IndexBuffer);
  767. SafeRelease(render_buffers->VertexBuffer);
  768. render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0;
  769. }
  770. void ImGui_ImplDX12_InvalidateDeviceObjects()
  771. {
  772. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  773. if (!bd || !bd->pd3dDevice)
  774. return;
  775. if (bd->commandQueueOwned)
  776. SafeRelease(bd->pCommandQueue);
  777. bd->commandQueueOwned = false;
  778. SafeRelease(bd->pRootSignature);
  779. SafeRelease(bd->pPipelineState);
  780. // Destroy all textures
  781. for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
  782. if (tex->RefCount == 1)
  783. ImGui_ImplDX12_DestroyTexture(tex);
  784. }
  785. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  786. static void ImGui_ImplDX12_InitLegacySingleDescriptorMode(ImGui_ImplDX12_InitInfo* init_info)
  787. {
  788. // Wrap legacy behavior of passing space for a single descriptor
  789. IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
  790. init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle)
  791. {
  792. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  793. IM_ASSERT(bd->LegacySingleDescriptorUsed == false && "Only 1 simultaneous texture allowed with legacy ImGui_ImplDX12_Init() signature!");
  794. *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor;
  795. *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor;
  796. bd->LegacySingleDescriptorUsed = true;
  797. };
  798. init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE)
  799. {
  800. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  801. IM_ASSERT(bd->LegacySingleDescriptorUsed == true);
  802. bd->LegacySingleDescriptorUsed = false;
  803. };
  804. }
  805. #endif
  806. bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
  807. {
  808. ImGuiIO& io = ImGui::GetIO();
  809. IMGUI_CHECKVERSION();
  810. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  811. // Setup backend capabilities flags
  812. ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
  813. bd->InitInfo = *init_info; // Deep copy
  814. init_info = &bd->InitInfo;
  815. bd->pd3dDevice = init_info->Device;
  816. IM_ASSERT(init_info->CommandQueue != NULL);
  817. bd->pCommandQueue = init_info->CommandQueue;
  818. bd->RTVFormat = init_info->RTVFormat;
  819. bd->DSVFormat = init_info->DSVFormat;
  820. bd->numFramesInFlight = init_info->NumFramesInFlight;
  821. bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
  822. io.BackendRendererUserData = (void*)bd;
  823. io.BackendRendererName = "imgui_impl_dx12";
  824. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  825. io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
  826. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  827. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  828. ImGui_ImplDX12_InitMultiViewportSupport();
  829. // Create a dummy ImGui_ImplDX12_ViewportData holder for the main viewport,
  830. // Since this is created and managed by the application, we will only use the ->Resources[] fields.
  831. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  832. main_viewport->RendererUserData = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight);
  833. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  834. if (init_info->SrvDescriptorAllocFn == nullptr)
  835. ImGui_ImplDX12_InitLegacySingleDescriptorMode(init_info);
  836. #endif
  837. IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr);
  838. return true;
  839. }
  840. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  841. // Legacy initialization API Obsoleted in 1.91.5
  842. // 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'
  843. 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)
  844. {
  845. ImGui_ImplDX12_InitInfo init_info;
  846. init_info.Device = device;
  847. init_info.NumFramesInFlight = num_frames_in_flight;
  848. init_info.RTVFormat = rtv_format;
  849. init_info.SrvDescriptorHeap = srv_descriptor_heap;
  850. init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle;
  851. init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;
  852. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  853. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  854. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  855. queueDesc.NodeMask = 1;
  856. HRESULT hr = device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&init_info.CommandQueue));
  857. IM_ASSERT(SUCCEEDED(hr));
  858. bool ret = ImGui_ImplDX12_Init(&init_info);
  859. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  860. bd->commandQueueOwned = true;
  861. ImGuiIO& io = ImGui::GetIO();
  862. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasTextures; // Using legacy ImGui_ImplDX12_Init() call with 1 SRV descriptor we cannot support multiple textures.
  863. return ret;
  864. }
  865. #endif
  866. void ImGui_ImplDX12_Shutdown()
  867. {
  868. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  869. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  870. ImGuiIO& io = ImGui::GetIO();
  871. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  872. // Manually delete main viewport render resources in-case we haven't initialized for viewports
  873. ImGuiViewport* main_viewport = ImGui::GetMainViewport();
  874. if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)main_viewport->RendererUserData)
  875. {
  876. // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[]
  877. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  878. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  879. IM_DELETE(vd);
  880. main_viewport->RendererUserData = nullptr;
  881. }
  882. ImGui_ImplDX12_ShutdownMultiViewportSupport();
  883. ImGui_ImplDX12_InvalidateDeviceObjects();
  884. io.BackendRendererName = nullptr;
  885. io.BackendRendererUserData = nullptr;
  886. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports);
  887. platform_io.ClearRendererHandlers();
  888. IM_DELETE(bd);
  889. }
  890. void ImGui_ImplDX12_NewFrame()
  891. {
  892. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  893. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
  894. if (!bd->pPipelineState)
  895. if (!ImGui_ImplDX12_CreateDeviceObjects())
  896. IM_ASSERT(0 && "ImGui_ImplDX12_CreateDeviceObjects() failed!");
  897. }
  898. //--------------------------------------------------------------------------------------------------------
  899. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  900. // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
  901. // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
  902. //--------------------------------------------------------------------------------------------------------
  903. static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport)
  904. {
  905. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  906. ImGui_ImplDX12_ViewportData* vd = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight);
  907. viewport->RendererUserData = vd;
  908. // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL's WindowID).
  909. // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
  910. HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
  911. IM_ASSERT(hwnd != 0);
  912. vd->FrameIndex = UINT_MAX;
  913. // Create command queue.
  914. D3D12_COMMAND_QUEUE_DESC queue_desc = {};
  915. queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  916. queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  917. HRESULT res = S_OK;
  918. res = bd->pd3dDevice->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&vd->CommandQueue));
  919. IM_ASSERT(res == S_OK);
  920. // Create command allocator.
  921. for (UINT i = 0; i < bd->numFramesInFlight; ++i)
  922. {
  923. res = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&vd->FrameCtx[i].CommandAllocator));
  924. IM_ASSERT(res == S_OK);
  925. }
  926. // Create command list.
  927. res = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, vd->FrameCtx[0].CommandAllocator, nullptr, IID_PPV_ARGS(&vd->CommandList));
  928. IM_ASSERT(res == S_OK);
  929. vd->CommandList->Close();
  930. // Create fence.
  931. res = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&vd->Fence));
  932. IM_ASSERT(res == S_OK);
  933. vd->FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  934. IM_ASSERT(vd->FenceEvent != nullptr);
  935. // Create swap chain
  936. // FIXME-VIEWPORT: May want to copy/inherit swap chain settings from the user/application.
  937. DXGI_SWAP_CHAIN_DESC1 sd1;
  938. ZeroMemory(&sd1, sizeof(sd1));
  939. sd1.BufferCount = bd->numFramesInFlight;
  940. sd1.Width = (UINT)viewport->Size.x;
  941. sd1.Height = (UINT)viewport->Size.y;
  942. sd1.Format = bd->RTVFormat;
  943. sd1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  944. sd1.SampleDesc.Count = 1;
  945. sd1.SampleDesc.Quality = 0;
  946. sd1.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  947. sd1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
  948. sd1.Scaling = DXGI_SCALING_NONE;
  949. sd1.Stereo = FALSE;
  950. IDXGIFactory4* dxgi_factory = nullptr;
  951. res = ::CreateDXGIFactory1(IID_PPV_ARGS(&dxgi_factory));
  952. IM_ASSERT(res == S_OK);
  953. IDXGISwapChain1* swap_chain = nullptr;
  954. res = dxgi_factory->CreateSwapChainForHwnd(vd->CommandQueue, hwnd, &sd1, nullptr, nullptr, &swap_chain);
  955. IM_ASSERT(res == S_OK);
  956. res = dxgi_factory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES); // Disable e.g. Alt+Enter
  957. IM_ASSERT(res == S_OK);
  958. dxgi_factory->Release();
  959. // Or swapChain.As(&mSwapChain)
  960. IM_ASSERT(vd->SwapChain == nullptr);
  961. swap_chain->QueryInterface(IID_PPV_ARGS(&vd->SwapChain));
  962. swap_chain->Release();
  963. // Create the render targets
  964. if (vd->SwapChain)
  965. {
  966. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  967. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  968. desc.NumDescriptors = bd->numFramesInFlight;
  969. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  970. desc.NodeMask = 1;
  971. HRESULT hr = bd->pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&vd->RtvDescHeap));
  972. IM_ASSERT(hr == S_OK);
  973. SIZE_T rtv_descriptor_size = bd->pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  974. D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = vd->RtvDescHeap->GetCPUDescriptorHandleForHeapStart();
  975. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  976. {
  977. vd->FrameCtx[i].RenderTargetCpuDescriptors = rtv_handle;
  978. rtv_handle.ptr += rtv_descriptor_size;
  979. }
  980. ID3D12Resource* back_buffer;
  981. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  982. {
  983. IM_ASSERT(vd->FrameCtx[i].RenderTarget == nullptr);
  984. vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer));
  985. bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors);
  986. vd->FrameCtx[i].RenderTarget = back_buffer;
  987. }
  988. }
  989. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  990. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  991. }
  992. static void ImGui_WaitForPendingOperations(ImGui_ImplDX12_ViewportData* vd)
  993. {
  994. HRESULT hr = S_FALSE;
  995. if (vd && vd->CommandQueue && vd->Fence && vd->FenceEvent)
  996. {
  997. hr = vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue);
  998. IM_ASSERT(hr == S_OK);
  999. ::WaitForSingleObject(vd->FenceEvent, 0); // Reset any forgotten waits
  1000. hr = vd->Fence->SetEventOnCompletion(vd->FenceSignaledValue, vd->FenceEvent);
  1001. IM_ASSERT(hr == S_OK);
  1002. ::WaitForSingleObject(vd->FenceEvent, INFINITE);
  1003. }
  1004. }
  1005. static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport)
  1006. {
  1007. // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
  1008. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1009. if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData)
  1010. {
  1011. ImGui_WaitForPendingOperations(vd);
  1012. SafeRelease(vd->CommandQueue);
  1013. SafeRelease(vd->CommandList);
  1014. SafeRelease(vd->SwapChain);
  1015. SafeRelease(vd->RtvDescHeap);
  1016. SafeRelease(vd->Fence);
  1017. ::CloseHandle(vd->FenceEvent);
  1018. vd->FenceEvent = nullptr;
  1019. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  1020. {
  1021. SafeRelease(vd->FrameCtx[i].RenderTarget);
  1022. SafeRelease(vd->FrameCtx[i].CommandAllocator);
  1023. ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
  1024. }
  1025. IM_DELETE(vd);
  1026. }
  1027. viewport->RendererUserData = nullptr;
  1028. }
  1029. static void ImGui_ImplDX12_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  1030. {
  1031. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1032. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  1033. ImGui_WaitForPendingOperations(vd);
  1034. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  1035. SafeRelease(vd->FrameCtx[i].RenderTarget);
  1036. if (vd->SwapChain)
  1037. {
  1038. ID3D12Resource* back_buffer = nullptr;
  1039. vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
  1040. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  1041. {
  1042. vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer));
  1043. bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors);
  1044. vd->FrameCtx[i].RenderTarget = back_buffer;
  1045. }
  1046. }
  1047. }
  1048. static void ImGui_ImplDX12_RenderWindow(ImGuiViewport* viewport, void*)
  1049. {
  1050. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  1051. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  1052. ImGui_ImplDX12_FrameContext* frame_context = &vd->FrameCtx[vd->FrameIndex % bd->numFramesInFlight];
  1053. UINT back_buffer_idx = vd->SwapChain->GetCurrentBackBufferIndex();
  1054. const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
  1055. D3D12_RESOURCE_BARRIER barrier = {};
  1056. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  1057. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  1058. barrier.Transition.pResource = vd->FrameCtx[back_buffer_idx].RenderTarget;
  1059. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  1060. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  1061. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  1062. // Draw
  1063. ID3D12GraphicsCommandList* cmd_list = vd->CommandList;
  1064. frame_context->CommandAllocator->Reset();
  1065. cmd_list->Reset(frame_context->CommandAllocator, nullptr);
  1066. cmd_list->ResourceBarrier(1, &barrier);
  1067. cmd_list->OMSetRenderTargets(1, &vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, FALSE, nullptr);
  1068. if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
  1069. cmd_list->ClearRenderTargetView(vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, (const float*)&clear_color, 0, nullptr);
  1070. cmd_list->SetDescriptorHeaps(1, &bd->pd3dSrvDescHeap);
  1071. ImGui_ImplDX12_RenderDrawData(viewport->DrawData, cmd_list);
  1072. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  1073. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  1074. cmd_list->ResourceBarrier(1, &barrier);
  1075. cmd_list->Close();
  1076. vd->CommandQueue->Wait(vd->Fence, vd->FenceSignaledValue);
  1077. vd->CommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmd_list);
  1078. vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue);
  1079. }
  1080. static void ImGui_ImplDX12_SwapBuffers(ImGuiViewport* viewport, void*)
  1081. {
  1082. ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
  1083. vd->SwapChain->Present(0, 0);
  1084. while (vd->Fence->GetCompletedValue() < vd->FenceSignaledValue)
  1085. ::SwitchToThread();
  1086. }
  1087. void ImGui_ImplDX12_InitMultiViewportSupport()
  1088. {
  1089. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  1090. platform_io.Renderer_CreateWindow = ImGui_ImplDX12_CreateWindow;
  1091. platform_io.Renderer_DestroyWindow = ImGui_ImplDX12_DestroyWindow;
  1092. platform_io.Renderer_SetWindowSize = ImGui_ImplDX12_SetWindowSize;
  1093. platform_io.Renderer_RenderWindow = ImGui_ImplDX12_RenderWindow;
  1094. platform_io.Renderer_SwapBuffers = ImGui_ImplDX12_SwapBuffers;
  1095. }
  1096. void ImGui_ImplDX12_ShutdownMultiViewportSupport()
  1097. {
  1098. ImGui::DestroyPlatformWindows();
  1099. }
  1100. //-----------------------------------------------------------------------------
  1101. #endif // #ifndef IMGUI_DISABLE