imgui_impl_dx12.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. // dear imgui: Renderer Backend for DirectX12
  2. // This needs to be used along with a Platform Backend (e.g. Win32)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
  7. // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
  8. // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
  9. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
  10. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  11. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  12. // Learn about Dear ImGui:
  13. // - FAQ https://dearimgui.com/faq
  14. // - Getting Started https://dearimgui.com/getting-started
  15. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  16. // - Introduction, links and more at the top of imgui.cpp
  17. // CHANGELOG
  18. // (minor and older changes stripped away, please see git history for details)
  19. // 2025-10-11: DirectX12: Reuse texture upload buffer and grow it only when necessary. (#9002)
  20. // 2025-09-29: DirectX12: Rework synchronization logic. (#8961)
  21. // 2025-09-29: DirectX12: Enable swapchain tearing to eliminate viewports framerate throttling. (#8965)
  22. // 2025-09-29: DirectX12: Reuse a command list and allocator for texture uploads instead of recreating them each time. (#8963)
  23. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
  24. // 2025-06-19: Fixed build on MinGW. (#8702, #4594)
  25. // 2025-06-11: DirectX12: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas.
  26. // 2025-05-07: DirectX12: Honor draw_data->FramebufferScale to allow for custom backends and experiment using it (consistently with other renderer backends, even though in normal condition it is not set under Windows).
  27. // 2025-02-24: DirectX12: Fixed an issue where ImGui_ImplDX12_Init() signature change from 2024-11-15 combined with change from 2025-01-15 made legacy ImGui_ImplDX12_Init() crash. (#8429)
  28. // 2025-01-15: DirectX12: Texture upload use the command queue provided in ImGui_ImplDX12_InitInfo instead of creating its own.
  29. // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat.
  30. // 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).
  31. // 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.
  32. // 2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
  33. // 2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  34. // 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.
  35. // 2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
  36. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  37. // 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).
  38. // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  39. // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
  40. // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
  41. // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
  42. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
  43. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
  44. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  45. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  46. // 2019-03-29: Misc: Various minor tidying up.
  47. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  48. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  49. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
  50. // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
  51. // 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).
  52. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
  53. #include "imgui.h"
  54. #ifndef IMGUI_DISABLE
  55. #include "imgui_impl_dx12.h"
  56. // DirectX
  57. #include <d3d12.h>
  58. #include <dxgi1_5.h>
  59. #include <d3dcompiler.h>
  60. #ifdef _MSC_VER
  61. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  62. #endif
  63. // Clang/GCC warnings with -Weverything
  64. #if defined(__clang__)
  65. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
  66. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  67. #endif
  68. // MinGW workaround, see #4594
  69. typedef decltype(D3D12SerializeRootSignature) *_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE;
  70. // DirectX12 data
  71. struct ImGui_ImplDX12_RenderBuffers;
  72. struct ImGui_ImplDX12_Texture
  73. {
  74. ID3D12Resource* pTextureResource;
  75. D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
  76. D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
  77. ImGui_ImplDX12_Texture() { memset((void*)this, 0, sizeof(*this)); }
  78. };
  79. struct ImGui_ImplDX12_Data
  80. {
  81. ImGui_ImplDX12_InitInfo InitInfo;
  82. IDXGIFactory5* pdxgiFactory;
  83. ID3D12Device* pd3dDevice;
  84. ID3D12RootSignature* pRootSignatureLinear;
  85. ID3D12RootSignature* pRootSignatureNearest;
  86. ID3D12PipelineState* pPipelineStateLinear;
  87. ID3D12PipelineState* pPipelineStateNearest;
  88. ID3D12CommandQueue* pCommandQueue;
  89. bool commandQueueOwned;
  90. DXGI_FORMAT RTVFormat;
  91. DXGI_FORMAT DSVFormat;
  92. ID3D12DescriptorHeap* pd3dSrvDescHeap;
  93. ID3D12Fence* Fence;
  94. UINT64 FenceLastSignaledValue;
  95. HANDLE FenceEvent;
  96. UINT numFramesInFlight;
  97. bool tearingSupport;
  98. bool LegacySingleDescriptorUsed;
  99. ID3D12CommandAllocator* pTexCmdAllocator;
  100. ID3D12GraphicsCommandList* pTexCmdList;
  101. ID3D12Resource* pTexUploadBuffer;
  102. UINT pTexUploadBufferSize;
  103. void* pTexUploadBufferMapped;
  104. ImGui_ImplDX12_RenderBuffers* pFrameResources;
  105. UINT frameIndex;
  106. ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); }
  107. };
  108. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  109. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  110. static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
  111. {
  112. return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  113. }
  114. // Buffers used during the rendering of a frame
  115. struct ImGui_ImplDX12_RenderBuffers
  116. {
  117. ID3D12Resource* IndexBuffer;
  118. ID3D12Resource* VertexBuffer;
  119. int IndexBufferSize;
  120. int VertexBufferSize;
  121. };
  122. struct VERTEX_CONSTANT_BUFFER_DX12
  123. {
  124. float mvp[4][4];
  125. };
  126. // FIXME-WIP: Allow user to forward declare those two, for until we come up with a backend agnostic API to do this. (#9173)
  127. void ImGui_ImplDX12_SetupSamplerLinear(ID3D12GraphicsCommandList* command_list);
  128. void ImGui_ImplDX12_SetupSamplerNearest(ID3D12GraphicsCommandList* command_list);
  129. // Functions
  130. void ImGui_ImplDX12_SetupSamplerLinear(ID3D12GraphicsCommandList* command_list)
  131. {
  132. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  133. command_list->SetPipelineState(bd->pPipelineStateLinear);
  134. command_list->SetGraphicsRootSignature(bd->pRootSignatureLinear);
  135. }
  136. void ImGui_ImplDX12_SetupSamplerNearest(ID3D12GraphicsCommandList* command_list)
  137. {
  138. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  139. command_list->SetPipelineState(bd->pPipelineStateNearest);
  140. command_list->SetGraphicsRootSignature(bd->pRootSignatureNearest);
  141. }
  142. static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
  143. {
  144. // Setup orthographic projection matrix into our constant buffer
  145. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  146. VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
  147. {
  148. float L = draw_data->DisplayPos.x;
  149. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  150. float T = draw_data->DisplayPos.y;
  151. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  152. float mvp[4][4] =
  153. {
  154. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  155. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  156. { 0.0f, 0.0f, 0.5f, 0.0f },
  157. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  158. };
  159. memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
  160. }
  161. // Setup viewport
  162. D3D12_VIEWPORT vp = {};
  163. vp.Width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x;
  164. vp.Height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y;
  165. vp.MinDepth = 0.0f;
  166. vp.MaxDepth = 1.0f;
  167. vp.TopLeftX = vp.TopLeftY = 0.0f;
  168. command_list->RSSetViewports(1, &vp);
  169. // Bind shader and vertex buffers
  170. unsigned int stride = sizeof(ImDrawVert);
  171. unsigned int offset = 0;
  172. D3D12_VERTEX_BUFFER_VIEW vbv = {};
  173. vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
  174. vbv.SizeInBytes = fr->VertexBufferSize * stride;
  175. vbv.StrideInBytes = stride;
  176. command_list->IASetVertexBuffers(0, 1, &vbv);
  177. D3D12_INDEX_BUFFER_VIEW ibv = {};
  178. ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
  179. ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
  180. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  181. command_list->IASetIndexBuffer(&ibv);
  182. command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  183. ImGui_ImplDX12_SetupSamplerLinear(command_list);
  184. command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  185. // Setup blend factor
  186. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  187. command_list->OMSetBlendFactor(blend_factor);
  188. }
  189. template<typename T>
  190. static inline void SafeRelease(T*& res)
  191. {
  192. if (res)
  193. res->Release();
  194. res = nullptr;
  195. }
  196. // Render function
  197. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
  198. {
  199. // Avoid rendering when minimized
  200. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  201. return;
  202. // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
  203. // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
  204. if (draw_data->Textures != nullptr)
  205. for (ImTextureData* tex : *draw_data->Textures)
  206. if (tex->Status != ImTextureStatus_OK)
  207. ImGui_ImplDX12_UpdateTexture(tex);
  208. // FIXME: We are assuming that this only gets called once per frame!
  209. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  210. bd->frameIndex = bd->frameIndex + 1;
  211. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
  212. // Create and grow vertex/index buffers if needed
  213. if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
  214. {
  215. SafeRelease(fr->VertexBuffer);
  216. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  217. D3D12_HEAP_PROPERTIES props = {};
  218. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  219. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  220. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  221. D3D12_RESOURCE_DESC desc = {};
  222. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  223. desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
  224. desc.Height = 1;
  225. desc.DepthOrArraySize = 1;
  226. desc.MipLevels = 1;
  227. desc.Format = DXGI_FORMAT_UNKNOWN;
  228. desc.SampleDesc.Count = 1;
  229. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  230. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  231. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
  232. return;
  233. }
  234. if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
  235. {
  236. SafeRelease(fr->IndexBuffer);
  237. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  238. D3D12_HEAP_PROPERTIES props = {};
  239. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  240. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  241. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  242. D3D12_RESOURCE_DESC desc = {};
  243. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  244. desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
  245. desc.Height = 1;
  246. desc.DepthOrArraySize = 1;
  247. desc.MipLevels = 1;
  248. desc.Format = DXGI_FORMAT_UNKNOWN;
  249. desc.SampleDesc.Count = 1;
  250. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  251. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  252. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
  253. return;
  254. }
  255. // Upload vertex/index data into a single contiguous GPU buffer
  256. // During Map() we specify a null read range (as per DX12 API, this is informational and for tooling only)
  257. void* vtx_resource, *idx_resource;
  258. D3D12_RANGE range = { 0, 0 };
  259. if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
  260. return;
  261. if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
  262. return;
  263. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
  264. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
  265. for (const ImDrawList* draw_list : draw_data->CmdLists)
  266. {
  267. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  268. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  269. vtx_dst += draw_list->VtxBuffer.Size;
  270. idx_dst += draw_list->IdxBuffer.Size;
  271. }
  272. // During Unmap() we specify the written range (as per DX12 API, this is informational and for tooling only)
  273. range.End = (SIZE_T)((intptr_t)vtx_dst - (intptr_t)vtx_resource);
  274. IM_ASSERT(range.End == draw_data->TotalVtxCount * sizeof(ImDrawVert));
  275. fr->VertexBuffer->Unmap(0, &range);
  276. range.End = (SIZE_T)((intptr_t)idx_dst - (intptr_t)idx_resource);
  277. IM_ASSERT(range.End == draw_data->TotalIdxCount * sizeof(ImDrawIdx));
  278. fr->IndexBuffer->Unmap(0, &range);
  279. // Setup desired DX state
  280. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  281. // Setup render state structure (for callbacks and custom texture bindings)
  282. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  283. ImGui_ImplDX12_RenderState render_state;
  284. render_state.Device = bd->pd3dDevice;
  285. render_state.CommandList = command_list;
  286. platform_io.Renderer_RenderState = &render_state;
  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. ImVec2 clip_scale = draw_data->FramebufferScale;
  293. for (const ImDrawList* draw_list : draw_data->CmdLists)
  294. {
  295. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  296. {
  297. const ImDrawCmd* pcmd = &draw_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, command_list, fr);
  304. else
  305. pcmd->UserCallback(draw_list, pcmd);
  306. }
  307. else
  308. {
  309. // Project scissor/clipping rectangles into framebuffer space
  310. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  311. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  312. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  313. continue;
  314. // Apply scissor/clipping rectangle
  315. const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  316. command_list->RSSetScissorRects(1, &r);
  317. // Bind texture, Draw
  318. D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
  319. texture_handle.ptr = (UINT64)pcmd->GetTexID();
  320. command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
  321. command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  322. }
  323. }
  324. global_idx_offset += draw_list->IdxBuffer.Size;
  325. global_vtx_offset += draw_list->VtxBuffer.Size;
  326. }
  327. platform_io.Renderer_RenderState = nullptr;
  328. }
  329. static void ImGui_ImplDX12_DestroyTexture(ImTextureData* tex)
  330. {
  331. if (ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData)
  332. {
  333. IM_ASSERT(backend_tex->hFontSrvGpuDescHandle.ptr == (UINT64)tex->TexID);
  334. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  335. bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, backend_tex->hFontSrvCpuDescHandle, backend_tex->hFontSrvGpuDescHandle);
  336. SafeRelease(backend_tex->pTextureResource);
  337. backend_tex->hFontSrvCpuDescHandle.ptr = 0;
  338. backend_tex->hFontSrvGpuDescHandle.ptr = 0;
  339. IM_DELETE(backend_tex);
  340. // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
  341. tex->SetTexID(ImTextureID_Invalid);
  342. tex->BackendUserData = nullptr;
  343. }
  344. tex->SetStatus(ImTextureStatus_Destroyed);
  345. }
  346. void ImGui_ImplDX12_UpdateTexture(ImTextureData* tex)
  347. {
  348. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  349. bool need_barrier_before_copy = true; // Do we need a resource barrier before we copy new data in?
  350. if (tex->Status == ImTextureStatus_WantCreate)
  351. {
  352. // Create and upload new texture to graphics system
  353. //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
  354. IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
  355. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  356. ImGui_ImplDX12_Texture* backend_tex = IM_NEW(ImGui_ImplDX12_Texture)();
  357. bd->InitInfo.SrvDescriptorAllocFn(&bd->InitInfo, &backend_tex->hFontSrvCpuDescHandle, &backend_tex->hFontSrvGpuDescHandle); // Allocate a desctriptor handle
  358. D3D12_HEAP_PROPERTIES props = {};
  359. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  360. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  361. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  362. D3D12_RESOURCE_DESC desc;
  363. ZeroMemory(&desc, sizeof(desc));
  364. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  365. desc.Alignment = 0;
  366. desc.Width = tex->Width;
  367. desc.Height = tex->Height;
  368. desc.DepthOrArraySize = 1;
  369. desc.MipLevels = 1;
  370. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  371. desc.SampleDesc.Count = 1;
  372. desc.SampleDesc.Quality = 0;
  373. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  374. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  375. ID3D12Resource* pTexture = nullptr;
  376. bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  377. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
  378. // Create SRV
  379. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  380. ZeroMemory(&srvDesc, sizeof(srvDesc));
  381. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  382. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  383. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  384. srvDesc.Texture2D.MostDetailedMip = 0;
  385. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  386. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, backend_tex->hFontSrvCpuDescHandle);
  387. SafeRelease(backend_tex->pTextureResource);
  388. backend_tex->pTextureResource = pTexture;
  389. // Store identifiers
  390. tex->SetTexID((ImTextureID)backend_tex->hFontSrvGpuDescHandle.ptr);
  391. tex->BackendUserData = backend_tex;
  392. need_barrier_before_copy = false; // Because this is a newly-created texture it will be in D3D12_RESOURCE_STATE_COMMON and thus we don't need a barrier
  393. // We don't set tex->Status to ImTextureStatus_OK to let the code fallthrough below.
  394. }
  395. if (tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates)
  396. {
  397. ImGui_ImplDX12_Texture* backend_tex = (ImGui_ImplDX12_Texture*)tex->BackendUserData;
  398. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  399. // We could use the smaller rect on _WantCreate but using the full rect allows us to clear the texture.
  400. // FIXME-OPT: Uploading single box even when using ImTextureStatus_WantUpdates. Could use tex->Updates[]
  401. // - Copy all blocks contiguously in upload buffer.
  402. // - Barrier before copy, submit all CopyTextureRegion(), barrier after copy.
  403. const int upload_x = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.x;
  404. const int upload_y = (tex->Status == ImTextureStatus_WantCreate) ? 0 : tex->UpdateRect.y;
  405. const int upload_w = (tex->Status == ImTextureStatus_WantCreate) ? tex->Width : tex->UpdateRect.w;
  406. const int upload_h = (tex->Status == ImTextureStatus_WantCreate) ? tex->Height : tex->UpdateRect.h;
  407. // Update full texture or selected blocks. We only ever write to textures regions which have never been used before!
  408. // This backend choose to use tex->UpdateRect but you can use tex->Updates[] to upload individual regions.
  409. UINT upload_pitch_src = upload_w * tex->BytesPerPixel;
  410. UINT upload_pitch_dst = (upload_pitch_src + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  411. UINT upload_size = upload_pitch_dst * upload_h;
  412. if (bd->pTexUploadBuffer == nullptr || upload_size > bd->pTexUploadBufferSize)
  413. {
  414. if (bd->pTexUploadBufferMapped)
  415. {
  416. D3D12_RANGE range = { 0, bd->pTexUploadBufferSize };
  417. bd->pTexUploadBuffer->Unmap(0, &range);
  418. bd->pTexUploadBufferMapped = nullptr;
  419. }
  420. SafeRelease(bd->pTexUploadBuffer);
  421. D3D12_RESOURCE_DESC desc;
  422. ZeroMemory(&desc, sizeof(desc));
  423. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  424. desc.Alignment = 0;
  425. desc.Width = upload_size;
  426. desc.Height = 1;
  427. desc.DepthOrArraySize = 1;
  428. desc.MipLevels = 1;
  429. desc.Format = DXGI_FORMAT_UNKNOWN;
  430. desc.SampleDesc.Count = 1;
  431. desc.SampleDesc.Quality = 0;
  432. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  433. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  434. D3D12_HEAP_PROPERTIES props;
  435. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  436. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  437. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  438. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  439. HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  440. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&bd->pTexUploadBuffer));
  441. IM_ASSERT(SUCCEEDED(hr));
  442. D3D12_RANGE range = {0, upload_size};
  443. hr = bd->pTexUploadBuffer->Map(0, &range, &bd->pTexUploadBufferMapped);
  444. IM_ASSERT(SUCCEEDED(hr));
  445. bd->pTexUploadBufferSize = upload_size;
  446. }
  447. bd->pTexCmdAllocator->Reset();
  448. bd->pTexCmdList->Reset(bd->pTexCmdAllocator, nullptr);
  449. ID3D12GraphicsCommandList* cmdList = bd->pTexCmdList;
  450. // Copy to upload buffer
  451. for (int y = 0; y < upload_h; y++)
  452. memcpy((void*)((uintptr_t)bd->pTexUploadBufferMapped + y * upload_pitch_dst), tex->GetPixelsAt(upload_x, upload_y + y), upload_pitch_src);
  453. if (need_barrier_before_copy)
  454. {
  455. D3D12_RESOURCE_BARRIER barrier = {};
  456. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  457. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  458. barrier.Transition.pResource = backend_tex->pTextureResource;
  459. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  460. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  461. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
  462. cmdList->ResourceBarrier(1, &barrier);
  463. }
  464. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  465. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  466. {
  467. srcLocation.pResource = bd->pTexUploadBuffer;
  468. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  469. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  470. srcLocation.PlacedFootprint.Footprint.Width = upload_w;
  471. srcLocation.PlacedFootprint.Footprint.Height = upload_h;
  472. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  473. srcLocation.PlacedFootprint.Footprint.RowPitch = upload_pitch_dst;
  474. dstLocation.pResource = backend_tex->pTextureResource;
  475. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  476. dstLocation.SubresourceIndex = 0;
  477. }
  478. cmdList->CopyTextureRegion(&dstLocation, upload_x, upload_y, 0, &srcLocation, nullptr);
  479. {
  480. D3D12_RESOURCE_BARRIER barrier = {};
  481. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  482. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  483. barrier.Transition.pResource = backend_tex->pTextureResource;
  484. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  485. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  486. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  487. cmdList->ResourceBarrier(1, &barrier);
  488. }
  489. HRESULT hr = cmdList->Close();
  490. IM_ASSERT(SUCCEEDED(hr));
  491. ID3D12CommandQueue* cmdQueue = bd->pCommandQueue;
  492. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
  493. hr = cmdQueue->Signal(bd->Fence, ++bd->FenceLastSignaledValue);
  494. IM_ASSERT(SUCCEEDED(hr));
  495. // FIXME-OPT: Suboptimal?
  496. // - To remove this may need to create NumFramesInFlight x ImGui_ImplDX12_FrameContext in backend data (mimick docking version)
  497. // - Store per-frame in flight: upload buffer?
  498. // - Where do cmdList and cmdAlloc fit?
  499. bd->Fence->SetEventOnCompletion(bd->FenceLastSignaledValue, bd->FenceEvent);
  500. ::WaitForSingleObject(bd->FenceEvent, INFINITE);
  501. tex->SetStatus(ImTextureStatus_OK);
  502. }
  503. if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames >= (int)bd->numFramesInFlight)
  504. ImGui_ImplDX12_DestroyTexture(tex);
  505. }
  506. bool ImGui_ImplDX12_CreateDeviceObjects()
  507. {
  508. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  509. if (!bd || !bd->pd3dDevice)
  510. return false;
  511. if (bd->pPipelineStateLinear)
  512. ImGui_ImplDX12_InvalidateDeviceObjects();
  513. HRESULT hr = ::CreateDXGIFactory1(IID_PPV_ARGS(&bd->pdxgiFactory));
  514. IM_ASSERT(hr == S_OK);
  515. BOOL allow_tearing = FALSE;
  516. bd->pdxgiFactory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing, sizeof(allow_tearing));
  517. bd->tearingSupport = (allow_tearing == TRUE);
  518. // Create the root signature
  519. {
  520. D3D12_DESCRIPTOR_RANGE descRange = {};
  521. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  522. descRange.NumDescriptors = 1;
  523. descRange.BaseShaderRegister = 0;
  524. descRange.RegisterSpace = 0;
  525. descRange.OffsetInDescriptorsFromTableStart = 0;
  526. D3D12_ROOT_PARAMETER param[2] = {};
  527. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  528. param[0].Constants.ShaderRegister = 0;
  529. param[0].Constants.RegisterSpace = 0;
  530. param[0].Constants.Num32BitValues = 16;
  531. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  532. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  533. param[1].DescriptorTable.NumDescriptorRanges = 1;
  534. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  535. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  536. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  537. D3D12_STATIC_SAMPLER_DESC staticSampler[1] = {};
  538. staticSampler[0].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  539. staticSampler[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  540. staticSampler[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  541. staticSampler[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  542. staticSampler[0].MipLODBias = 0.f;
  543. staticSampler[0].MaxAnisotropy = 0;
  544. staticSampler[0].ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  545. staticSampler[0].BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  546. staticSampler[0].MinLOD = 0.f;
  547. staticSampler[0].MaxLOD = D3D12_FLOAT32_MAX;
  548. staticSampler[0].ShaderRegister = 0;
  549. staticSampler[0].RegisterSpace = 0;
  550. staticSampler[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  551. D3D12_ROOT_SIGNATURE_DESC desc = {};
  552. desc.NumParameters = _countof(param);
  553. desc.pParameters = param;
  554. desc.NumStaticSamplers = 1;
  555. desc.pStaticSamplers = &staticSampler[0];
  556. desc.Flags =
  557. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  558. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  559. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  560. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  561. // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
  562. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
  563. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
  564. if (d3d12_dll == nullptr)
  565. {
  566. // Attempt to load d3d12.dll from local directories. This will only succeed if
  567. // (1) the current OS is Windows 7, and
  568. // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
  569. // See https://github.com/ocornut/imgui/pull/3696 for details.
  570. 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
  571. for (int i = 0; i < IM_COUNTOF(localD3d12Paths); i++)
  572. if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
  573. break;
  574. // If failed, we are on Windows >= 10.
  575. if (d3d12_dll == nullptr)
  576. d3d12_dll = ::LoadLibraryA("d3d12.dll");
  577. if (d3d12_dll == nullptr)
  578. return false;
  579. }
  580. _PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (_PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)(void*)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
  581. if (D3D12SerializeRootSignatureFn == nullptr)
  582. return false;
  583. ID3DBlob* blob = nullptr;
  584. if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
  585. return false;
  586. bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignatureLinear));
  587. blob->Release();
  588. // Root Signature for ImDrawCallback_SetSamplerNearest
  589. staticSampler[0].Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
  590. if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
  591. return false;
  592. bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignatureNearest));
  593. blob->Release();
  594. }
  595. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  596. // If you would like to use this DX12 sample code but remove this dependency you can:
  597. // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
  598. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  599. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  600. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
  601. psoDesc.NodeMask = 1;
  602. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  603. psoDesc.pRootSignature = bd->pRootSignatureLinear;
  604. psoDesc.SampleMask = UINT_MAX;
  605. psoDesc.NumRenderTargets = 1;
  606. psoDesc.RTVFormats[0] = bd->RTVFormat;
  607. psoDesc.DSVFormat = bd->DSVFormat;
  608. psoDesc.SampleDesc.Count = 1;
  609. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  610. ID3DBlob* vertexShaderBlob;
  611. ID3DBlob* pixelShaderBlob;
  612. // Create the vertex shader
  613. {
  614. static const char* vertexShader =
  615. "cbuffer vertexBuffer : register(b0) \
  616. {\
  617. float4x4 ProjectionMatrix; \
  618. };\
  619. struct VS_INPUT\
  620. {\
  621. float2 pos : POSITION;\
  622. float4 col : COLOR0;\
  623. float2 uv : TEXCOORD0;\
  624. };\
  625. \
  626. struct PS_INPUT\
  627. {\
  628. float4 pos : SV_POSITION;\
  629. float4 col : COLOR0;\
  630. float2 uv : TEXCOORD0;\
  631. };\
  632. \
  633. PS_INPUT main(VS_INPUT input)\
  634. {\
  635. PS_INPUT output;\
  636. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  637. output.col = input.col;\
  638. output.uv = input.uv;\
  639. return output;\
  640. }";
  641. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
  642. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  643. psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
  644. // Create the input layout
  645. static D3D12_INPUT_ELEMENT_DESC local_layout[] =
  646. {
  647. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  648. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  649. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  650. };
  651. psoDesc.InputLayout = { local_layout, 3 };
  652. }
  653. // Create the pixel shader
  654. {
  655. static const char* pixelShader =
  656. "struct PS_INPUT\
  657. {\
  658. float4 pos : SV_POSITION;\
  659. float4 col : COLOR0;\
  660. float2 uv : TEXCOORD0;\
  661. };\
  662. SamplerState sampler0 : register(s0);\
  663. Texture2D texture0 : register(t0);\
  664. \
  665. float4 main(PS_INPUT input) : SV_Target\
  666. {\
  667. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  668. return out_col; \
  669. }";
  670. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
  671. {
  672. vertexShaderBlob->Release();
  673. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  674. }
  675. psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
  676. }
  677. // Create the blending setup
  678. {
  679. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  680. desc.AlphaToCoverageEnable = false;
  681. desc.RenderTarget[0].BlendEnable = true;
  682. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  683. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  684. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  685. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
  686. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  687. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  688. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  689. }
  690. // Create the rasterizer state
  691. {
  692. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  693. desc.FillMode = D3D12_FILL_MODE_SOLID;
  694. desc.CullMode = D3D12_CULL_MODE_NONE;
  695. desc.FrontCounterClockwise = FALSE;
  696. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  697. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  698. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  699. desc.DepthClipEnable = true;
  700. desc.MultisampleEnable = FALSE;
  701. desc.AntialiasedLineEnable = FALSE;
  702. desc.ForcedSampleCount = 0;
  703. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  704. }
  705. // Create depth-stencil State
  706. {
  707. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  708. desc.DepthEnable = false;
  709. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  710. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  711. desc.StencilEnable = false;
  712. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  713. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  714. desc.BackFace = desc.FrontFace;
  715. }
  716. HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineStateLinear));
  717. if (result_pipeline_state != S_OK)
  718. {
  719. vertexShaderBlob->Release();
  720. pixelShaderBlob->Release();
  721. return false;
  722. }
  723. // Pipeline State for ImDrawCallback_SetSamplerNearest
  724. psoDesc.pRootSignature = bd->pRootSignatureNearest;
  725. result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineStateNearest));
  726. vertexShaderBlob->Release();
  727. pixelShaderBlob->Release();
  728. if (result_pipeline_state != S_OK)
  729. return false;
  730. // Create command allocator and command list for ImGui_ImplDX12_UpdateTexture()
  731. hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&bd->pTexCmdAllocator));
  732. IM_ASSERT(SUCCEEDED(hr));
  733. hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, bd->pTexCmdAllocator, nullptr, IID_PPV_ARGS(&bd->pTexCmdList));
  734. IM_ASSERT(SUCCEEDED(hr));
  735. hr = bd->pTexCmdList->Close();
  736. IM_ASSERT(SUCCEEDED(hr));
  737. // Create fence.
  738. hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&bd->Fence));
  739. IM_ASSERT(hr == S_OK);
  740. bd->FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  741. IM_ASSERT(bd->FenceEvent != nullptr);
  742. return true;
  743. }
  744. void ImGui_ImplDX12_InvalidateDeviceObjects()
  745. {
  746. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  747. if (!bd || !bd->pd3dDevice)
  748. return;
  749. SafeRelease(bd->pdxgiFactory);
  750. if (bd->commandQueueOwned)
  751. SafeRelease(bd->pCommandQueue);
  752. bd->commandQueueOwned = false;
  753. SafeRelease(bd->pRootSignatureLinear);
  754. SafeRelease(bd->pRootSignatureNearest);
  755. SafeRelease(bd->pPipelineStateLinear);
  756. SafeRelease(bd->pPipelineStateNearest);
  757. if (bd->pTexUploadBufferMapped)
  758. {
  759. D3D12_RANGE range = { 0, bd->pTexUploadBufferSize };
  760. bd->pTexUploadBuffer->Unmap(0, &range);
  761. bd->pTexUploadBufferMapped = nullptr;
  762. }
  763. SafeRelease(bd->pTexUploadBuffer);
  764. SafeRelease(bd->pTexCmdList);
  765. SafeRelease(bd->pTexCmdAllocator);
  766. SafeRelease(bd->Fence);
  767. CloseHandle(bd->FenceEvent);
  768. bd->FenceEvent = nullptr;
  769. // Destroy all textures
  770. for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
  771. if (tex->RefCount == 1)
  772. ImGui_ImplDX12_DestroyTexture(tex);
  773. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  774. {
  775. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
  776. SafeRelease(fr->IndexBuffer);
  777. SafeRelease(fr->VertexBuffer);
  778. }
  779. }
  780. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  781. static void ImGui_ImplDX12_InitLegacySingleDescriptorMode(ImGui_ImplDX12_InitInfo* init_info)
  782. {
  783. // Wrap legacy behavior of passing space for a single descriptor
  784. IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
  785. init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle)
  786. {
  787. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  788. IM_ASSERT(bd->LegacySingleDescriptorUsed == false && "Only 1 simultaneous texture allowed with legacy ImGui_ImplDX12_Init() signature!");
  789. *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor;
  790. *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor;
  791. bd->LegacySingleDescriptorUsed = true;
  792. };
  793. init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE)
  794. {
  795. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  796. IM_ASSERT(bd->LegacySingleDescriptorUsed == true);
  797. bd->LegacySingleDescriptorUsed = false;
  798. };
  799. }
  800. #endif
  801. bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
  802. {
  803. ImGuiIO& io = ImGui::GetIO();
  804. IMGUI_CHECKVERSION();
  805. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  806. // Setup backend capabilities flags
  807. ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
  808. bd->InitInfo = *init_info; // Deep copy
  809. init_info = &bd->InitInfo;
  810. bd->pd3dDevice = init_info->Device;
  811. IM_ASSERT(init_info->CommandQueue != nullptr);
  812. bd->pCommandQueue = init_info->CommandQueue;
  813. bd->RTVFormat = init_info->RTVFormat;
  814. bd->DSVFormat = init_info->DSVFormat;
  815. bd->numFramesInFlight = init_info->NumFramesInFlight;
  816. bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
  817. bd->tearingSupport = false;
  818. io.BackendRendererUserData = (void*)bd;
  819. io.BackendRendererName = "imgui_impl_dx12";
  820. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  821. io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
  822. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  823. if (init_info->SrvDescriptorAllocFn == nullptr)
  824. ImGui_ImplDX12_InitLegacySingleDescriptorMode(init_info);
  825. #endif
  826. IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr);
  827. // Create buffers with a default size (they will later be grown as needed)
  828. bd->frameIndex = UINT_MAX;
  829. bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[bd->numFramesInFlight];
  830. for (int i = 0; i < (int)bd->numFramesInFlight; i++)
  831. {
  832. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
  833. fr->IndexBuffer = nullptr;
  834. fr->VertexBuffer = nullptr;
  835. fr->IndexBufferSize = 10000;
  836. fr->VertexBufferSize = 5000;
  837. }
  838. return true;
  839. }
  840. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
  841. // Legacy initialization API Obsoleted in 1.91.5
  842. // 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'
  843. 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)
  844. {
  845. ImGui_ImplDX12_InitInfo init_info;
  846. init_info.Device = device;
  847. init_info.NumFramesInFlight = num_frames_in_flight;
  848. init_info.RTVFormat = rtv_format;
  849. init_info.SrvDescriptorHeap = srv_descriptor_heap;
  850. init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle;
  851. init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;
  852. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  853. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  854. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  855. queueDesc.NodeMask = 1;
  856. HRESULT hr = device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&init_info.CommandQueue));
  857. IM_ASSERT(SUCCEEDED(hr));
  858. bool ret = ImGui_ImplDX12_Init(&init_info);
  859. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  860. bd->commandQueueOwned = true;
  861. ImGuiIO& io = ImGui::GetIO();
  862. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasTextures; // Using legacy ImGui_ImplDX12_Init() call with 1 SRV descriptor we cannot support multiple textures.
  863. return ret;
  864. }
  865. #endif
  866. void ImGui_ImplDX12_Shutdown()
  867. {
  868. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  869. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  870. ImGuiIO& io = ImGui::GetIO();
  871. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  872. ImGui_ImplDX12_InvalidateDeviceObjects();
  873. delete[] bd->pFrameResources;
  874. io.BackendRendererName = nullptr;
  875. io.BackendRendererUserData = nullptr;
  876. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
  877. platform_io.ClearRendererHandlers();
  878. IM_DELETE(bd);
  879. }
  880. void ImGui_ImplDX12_NewFrame()
  881. {
  882. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  883. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
  884. if (!bd->pPipelineStateLinear)
  885. if (!ImGui_ImplDX12_CreateDeviceObjects())
  886. IM_ASSERT(0 && "ImGui_ImplDX12_CreateDeviceObjects() failed!");
  887. }
  888. //-----------------------------------------------------------------------------
  889. #endif // #ifndef IMGUI_DISABLE