imgui_impl_dx12.cpp 48 KB

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