2
0

imgui_impl_dx12.cpp 52 KB

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