imgui_impl_dx12.cpp 52 KB

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