imgui_impl_dx12.cpp 60 KB

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