imgui_impl_dx12.cpp 58 KB

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