imgui_impl_dx12.cpp 52 KB

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