imgui_impl_dx12.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. // dear imgui: Renderer Backend for DirectX12
  2. // This needs to be used along with a Platform Backend (e.g. Win32)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
  5. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
  6. // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
  7. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  8. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  9. // Learn about Dear ImGui:
  10. // - FAQ https://dearimgui.com/faq
  11. // - Getting Started https://dearimgui.com/getting-started
  12. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  13. // - Introduction, links and more at the top of imgui.cpp
  14. // CHANGELOG
  15. // (minor and older changes stripped away, please see git history for details)
  16. // 2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
  17. // 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.
  18. // 2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
  19. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
  20. // 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).
  21. // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  22. // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
  23. // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
  24. // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
  25. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
  26. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
  27. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  28. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  29. // 2019-03-29: Misc: Various minor tidying up.
  30. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
  31. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  32. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
  33. // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
  34. // 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).
  35. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
  36. #include "imgui.h"
  37. #ifndef IMGUI_DISABLE
  38. #include "imgui_impl_dx12.h"
  39. // DirectX
  40. #include <d3d12.h>
  41. #include <dxgi1_4.h>
  42. #include <d3dcompiler.h>
  43. #ifdef _MSC_VER
  44. #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
  45. #endif
  46. // DirectX data
  47. struct ImGui_ImplDX12_RenderBuffers;
  48. struct ImGui_ImplDX12_Data
  49. {
  50. ID3D12Device* pd3dDevice;
  51. ID3D12RootSignature* pRootSignature;
  52. ID3D12PipelineState* pPipelineState;
  53. DXGI_FORMAT RTVFormat;
  54. ID3D12Resource* pFontTextureResource;
  55. D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
  56. D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
  57. ID3D12DescriptorHeap* pd3dSrvDescHeap;
  58. UINT numFramesInFlight;
  59. ImGui_ImplDX12_RenderBuffers* pFrameResources;
  60. UINT frameIndex;
  61. ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; }
  62. };
  63. // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
  64. // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
  65. static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
  66. {
  67. return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
  68. }
  69. // Buffers used during the rendering of a frame
  70. struct ImGui_ImplDX12_RenderBuffers
  71. {
  72. ID3D12Resource* IndexBuffer;
  73. ID3D12Resource* VertexBuffer;
  74. int IndexBufferSize;
  75. int VertexBufferSize;
  76. };
  77. struct VERTEX_CONSTANT_BUFFER_DX12
  78. {
  79. float mvp[4][4];
  80. };
  81. // Functions
  82. static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
  83. {
  84. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  85. // Setup orthographic projection matrix into our constant buffer
  86. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
  87. VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
  88. {
  89. float L = draw_data->DisplayPos.x;
  90. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  91. float T = draw_data->DisplayPos.y;
  92. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  93. float mvp[4][4] =
  94. {
  95. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  96. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  97. { 0.0f, 0.0f, 0.5f, 0.0f },
  98. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  99. };
  100. memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
  101. }
  102. // Setup viewport
  103. D3D12_VIEWPORT vp;
  104. memset(&vp, 0, sizeof(D3D12_VIEWPORT));
  105. vp.Width = draw_data->DisplaySize.x;
  106. vp.Height = draw_data->DisplaySize.y;
  107. vp.MinDepth = 0.0f;
  108. vp.MaxDepth = 1.0f;
  109. vp.TopLeftX = vp.TopLeftY = 0.0f;
  110. command_list->RSSetViewports(1, &vp);
  111. // Bind shader and vertex buffers
  112. unsigned int stride = sizeof(ImDrawVert);
  113. unsigned int offset = 0;
  114. D3D12_VERTEX_BUFFER_VIEW vbv;
  115. memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
  116. vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
  117. vbv.SizeInBytes = fr->VertexBufferSize * stride;
  118. vbv.StrideInBytes = stride;
  119. command_list->IASetVertexBuffers(0, 1, &vbv);
  120. D3D12_INDEX_BUFFER_VIEW ibv;
  121. memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
  122. ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
  123. ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
  124. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  125. command_list->IASetIndexBuffer(&ibv);
  126. command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  127. command_list->SetPipelineState(bd->pPipelineState);
  128. command_list->SetGraphicsRootSignature(bd->pRootSignature);
  129. command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  130. // Setup blend factor
  131. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  132. command_list->OMSetBlendFactor(blend_factor);
  133. }
  134. template<typename T>
  135. static inline void SafeRelease(T*& res)
  136. {
  137. if (res)
  138. res->Release();
  139. res = nullptr;
  140. }
  141. // Render function
  142. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
  143. {
  144. // Avoid rendering when minimized
  145. if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
  146. return;
  147. // FIXME: I'm assuming that this only gets called once per frame!
  148. // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
  149. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  150. bd->frameIndex = bd->frameIndex + 1;
  151. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
  152. // Create and grow vertex/index buffers if needed
  153. if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
  154. {
  155. SafeRelease(fr->VertexBuffer);
  156. fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
  157. D3D12_HEAP_PROPERTIES props;
  158. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  159. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  160. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  161. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  162. D3D12_RESOURCE_DESC desc;
  163. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  164. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  165. desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
  166. desc.Height = 1;
  167. desc.DepthOrArraySize = 1;
  168. desc.MipLevels = 1;
  169. desc.Format = DXGI_FORMAT_UNKNOWN;
  170. desc.SampleDesc.Count = 1;
  171. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  172. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  173. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
  174. return;
  175. }
  176. if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
  177. {
  178. SafeRelease(fr->IndexBuffer);
  179. fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
  180. D3D12_HEAP_PROPERTIES props;
  181. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  182. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  183. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  184. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  185. D3D12_RESOURCE_DESC desc;
  186. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  187. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  188. desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
  189. desc.Height = 1;
  190. desc.DepthOrArraySize = 1;
  191. desc.MipLevels = 1;
  192. desc.Format = DXGI_FORMAT_UNKNOWN;
  193. desc.SampleDesc.Count = 1;
  194. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  195. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  196. if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
  197. return;
  198. }
  199. // Upload vertex/index data into a single contiguous GPU buffer
  200. void* vtx_resource, *idx_resource;
  201. D3D12_RANGE range;
  202. memset(&range, 0, sizeof(D3D12_RANGE));
  203. if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
  204. return;
  205. if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
  206. return;
  207. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
  208. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
  209. for (int n = 0; n < draw_data->CmdListsCount; n++)
  210. {
  211. const ImDrawList* draw_list = draw_data->CmdLists[n];
  212. memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  213. memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  214. vtx_dst += draw_list->VtxBuffer.Size;
  215. idx_dst += draw_list->IdxBuffer.Size;
  216. }
  217. fr->VertexBuffer->Unmap(0, &range);
  218. fr->IndexBuffer->Unmap(0, &range);
  219. // Setup desired DX state
  220. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  221. // Setup render state structure (for callbacks and custom texture bindings)
  222. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  223. ImGui_ImplDX12_RenderState render_state;
  224. render_state.Device = bd->pd3dDevice;
  225. render_state.CommandList = command_list;
  226. platform_io.Renderer_RenderState = &render_state;
  227. // Render command lists
  228. // (Because we merged all buffers into a single one, we maintain our own offset into them)
  229. int global_vtx_offset = 0;
  230. int global_idx_offset = 0;
  231. ImVec2 clip_off = draw_data->DisplayPos;
  232. for (int n = 0; n < draw_data->CmdListsCount; n++)
  233. {
  234. const ImDrawList* draw_list = draw_data->CmdLists[n];
  235. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  236. {
  237. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  238. if (pcmd->UserCallback != nullptr)
  239. {
  240. // User callback, registered via ImDrawList::AddCallback()
  241. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  242. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  243. ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
  244. else
  245. pcmd->UserCallback(draw_list, pcmd);
  246. }
  247. else
  248. {
  249. // Project scissor/clipping rectangles into framebuffer space
  250. ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
  251. ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
  252. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  253. continue;
  254. // Apply scissor/clipping rectangle
  255. const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
  256. command_list->RSSetScissorRects(1, &r);
  257. // Bind texture, Draw
  258. D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
  259. texture_handle.ptr = (UINT64)pcmd->GetTexID();
  260. command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
  261. command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
  262. }
  263. }
  264. global_idx_offset += draw_list->IdxBuffer.Size;
  265. global_vtx_offset += draw_list->VtxBuffer.Size;
  266. }
  267. platform_io.Renderer_RenderState = NULL;
  268. }
  269. static void ImGui_ImplDX12_CreateFontsTexture()
  270. {
  271. // Build texture atlas
  272. ImGuiIO& io = ImGui::GetIO();
  273. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  274. unsigned char* pixels;
  275. int width, height;
  276. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  277. // Upload texture to graphics system
  278. {
  279. D3D12_HEAP_PROPERTIES props;
  280. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  281. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  282. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  283. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  284. D3D12_RESOURCE_DESC desc;
  285. ZeroMemory(&desc, sizeof(desc));
  286. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  287. desc.Alignment = 0;
  288. desc.Width = width;
  289. desc.Height = height;
  290. desc.DepthOrArraySize = 1;
  291. desc.MipLevels = 1;
  292. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  293. desc.SampleDesc.Count = 1;
  294. desc.SampleDesc.Quality = 0;
  295. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  296. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  297. ID3D12Resource* pTexture = nullptr;
  298. bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  299. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
  300. UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  301. UINT uploadSize = height * uploadPitch;
  302. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  303. desc.Alignment = 0;
  304. desc.Width = uploadSize;
  305. desc.Height = 1;
  306. desc.DepthOrArraySize = 1;
  307. desc.MipLevels = 1;
  308. desc.Format = DXGI_FORMAT_UNKNOWN;
  309. desc.SampleDesc.Count = 1;
  310. desc.SampleDesc.Quality = 0;
  311. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  312. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  313. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  314. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  315. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  316. ID3D12Resource* uploadBuffer = nullptr;
  317. HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  318. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer));
  319. IM_ASSERT(SUCCEEDED(hr));
  320. void* mapped = nullptr;
  321. D3D12_RANGE range = { 0, uploadSize };
  322. hr = uploadBuffer->Map(0, &range, &mapped);
  323. IM_ASSERT(SUCCEEDED(hr));
  324. for (int y = 0; y < height; y++)
  325. memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4);
  326. uploadBuffer->Unmap(0, &range);
  327. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  328. srcLocation.pResource = uploadBuffer;
  329. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  330. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  331. srcLocation.PlacedFootprint.Footprint.Width = width;
  332. srcLocation.PlacedFootprint.Footprint.Height = height;
  333. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  334. srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
  335. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  336. dstLocation.pResource = pTexture;
  337. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  338. dstLocation.SubresourceIndex = 0;
  339. D3D12_RESOURCE_BARRIER barrier = {};
  340. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  341. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  342. barrier.Transition.pResource = pTexture;
  343. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  344. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  345. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  346. ID3D12Fence* fence = nullptr;
  347. hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
  348. IM_ASSERT(SUCCEEDED(hr));
  349. HANDLE event = CreateEvent(0, 0, 0, 0);
  350. IM_ASSERT(event != nullptr);
  351. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  352. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  353. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  354. queueDesc.NodeMask = 1;
  355. ID3D12CommandQueue* cmdQueue = nullptr;
  356. hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
  357. IM_ASSERT(SUCCEEDED(hr));
  358. ID3D12CommandAllocator* cmdAlloc = nullptr;
  359. hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
  360. IM_ASSERT(SUCCEEDED(hr));
  361. ID3D12GraphicsCommandList* cmdList = nullptr;
  362. hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList));
  363. IM_ASSERT(SUCCEEDED(hr));
  364. cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr);
  365. cmdList->ResourceBarrier(1, &barrier);
  366. hr = cmdList->Close();
  367. IM_ASSERT(SUCCEEDED(hr));
  368. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
  369. hr = cmdQueue->Signal(fence, 1);
  370. IM_ASSERT(SUCCEEDED(hr));
  371. fence->SetEventOnCompletion(1, event);
  372. WaitForSingleObject(event, INFINITE);
  373. cmdList->Release();
  374. cmdAlloc->Release();
  375. cmdQueue->Release();
  376. CloseHandle(event);
  377. fence->Release();
  378. uploadBuffer->Release();
  379. // Create texture view
  380. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  381. ZeroMemory(&srvDesc, sizeof(srvDesc));
  382. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  383. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  384. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  385. srvDesc.Texture2D.MostDetailedMip = 0;
  386. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  387. bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle);
  388. SafeRelease(bd->pFontTextureResource);
  389. bd->pFontTextureResource = pTexture;
  390. }
  391. // Store our identifier
  392. io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr);
  393. }
  394. bool ImGui_ImplDX12_CreateDeviceObjects()
  395. {
  396. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  397. if (!bd || !bd->pd3dDevice)
  398. return false;
  399. if (bd->pPipelineState)
  400. ImGui_ImplDX12_InvalidateDeviceObjects();
  401. // Create the root signature
  402. {
  403. D3D12_DESCRIPTOR_RANGE descRange = {};
  404. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  405. descRange.NumDescriptors = 1;
  406. descRange.BaseShaderRegister = 0;
  407. descRange.RegisterSpace = 0;
  408. descRange.OffsetInDescriptorsFromTableStart = 0;
  409. D3D12_ROOT_PARAMETER param[2] = {};
  410. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  411. param[0].Constants.ShaderRegister = 0;
  412. param[0].Constants.RegisterSpace = 0;
  413. param[0].Constants.Num32BitValues = 16;
  414. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  415. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  416. param[1].DescriptorTable.NumDescriptorRanges = 1;
  417. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  418. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  419. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  420. D3D12_STATIC_SAMPLER_DESC staticSampler = {};
  421. staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  422. staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  423. staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  424. staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  425. staticSampler.MipLODBias = 0.f;
  426. staticSampler.MaxAnisotropy = 0;
  427. staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  428. staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  429. staticSampler.MinLOD = 0.f;
  430. staticSampler.MaxLOD = 0.f;
  431. staticSampler.ShaderRegister = 0;
  432. staticSampler.RegisterSpace = 0;
  433. staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  434. D3D12_ROOT_SIGNATURE_DESC desc = {};
  435. desc.NumParameters = _countof(param);
  436. desc.pParameters = param;
  437. desc.NumStaticSamplers = 1;
  438. desc.pStaticSamplers = &staticSampler;
  439. desc.Flags =
  440. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  441. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  442. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  443. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  444. // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
  445. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
  446. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
  447. if (d3d12_dll == nullptr)
  448. {
  449. // Attempt to load d3d12.dll from local directories. This will only succeed if
  450. // (1) the current OS is Windows 7, and
  451. // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
  452. // See https://github.com/ocornut/imgui/pull/3696 for details.
  453. 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
  454. for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
  455. if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
  456. break;
  457. // If failed, we are on Windows >= 10.
  458. if (d3d12_dll == nullptr)
  459. d3d12_dll = ::LoadLibraryA("d3d12.dll");
  460. if (d3d12_dll == nullptr)
  461. return false;
  462. }
  463. PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
  464. if (D3D12SerializeRootSignatureFn == nullptr)
  465. return false;
  466. ID3DBlob* blob = nullptr;
  467. if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
  468. return false;
  469. bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
  470. blob->Release();
  471. }
  472. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  473. // If you would like to use this DX12 sample code but remove this dependency you can:
  474. // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
  475. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  476. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  477. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
  478. memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
  479. psoDesc.NodeMask = 1;
  480. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  481. psoDesc.pRootSignature = bd->pRootSignature;
  482. psoDesc.SampleMask = UINT_MAX;
  483. psoDesc.NumRenderTargets = 1;
  484. psoDesc.RTVFormats[0] = bd->RTVFormat;
  485. psoDesc.SampleDesc.Count = 1;
  486. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  487. ID3DBlob* vertexShaderBlob;
  488. ID3DBlob* pixelShaderBlob;
  489. // Create the vertex shader
  490. {
  491. static const char* vertexShader =
  492. "cbuffer vertexBuffer : register(b0) \
  493. {\
  494. float4x4 ProjectionMatrix; \
  495. };\
  496. struct VS_INPUT\
  497. {\
  498. float2 pos : POSITION;\
  499. float4 col : COLOR0;\
  500. float2 uv : TEXCOORD0;\
  501. };\
  502. \
  503. struct PS_INPUT\
  504. {\
  505. float4 pos : SV_POSITION;\
  506. float4 col : COLOR0;\
  507. float2 uv : TEXCOORD0;\
  508. };\
  509. \
  510. PS_INPUT main(VS_INPUT input)\
  511. {\
  512. PS_INPUT output;\
  513. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  514. output.col = input.col;\
  515. output.uv = input.uv;\
  516. return output;\
  517. }";
  518. if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
  519. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  520. psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
  521. // Create the input layout
  522. static D3D12_INPUT_ELEMENT_DESC local_layout[] =
  523. {
  524. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  525. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  526. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  527. };
  528. psoDesc.InputLayout = { local_layout, 3 };
  529. }
  530. // Create the pixel shader
  531. {
  532. static const char* pixelShader =
  533. "struct PS_INPUT\
  534. {\
  535. float4 pos : SV_POSITION;\
  536. float4 col : COLOR0;\
  537. float2 uv : TEXCOORD0;\
  538. };\
  539. SamplerState sampler0 : register(s0);\
  540. Texture2D texture0 : register(t0);\
  541. \
  542. float4 main(PS_INPUT input) : SV_Target\
  543. {\
  544. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  545. return out_col; \
  546. }";
  547. if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
  548. {
  549. vertexShaderBlob->Release();
  550. return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
  551. }
  552. psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
  553. }
  554. // Create the blending setup
  555. {
  556. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  557. desc.AlphaToCoverageEnable = false;
  558. desc.RenderTarget[0].BlendEnable = true;
  559. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  560. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  561. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  562. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
  563. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  564. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  565. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  566. }
  567. // Create the rasterizer state
  568. {
  569. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  570. desc.FillMode = D3D12_FILL_MODE_SOLID;
  571. desc.CullMode = D3D12_CULL_MODE_NONE;
  572. desc.FrontCounterClockwise = FALSE;
  573. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  574. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  575. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  576. desc.DepthClipEnable = true;
  577. desc.MultisampleEnable = FALSE;
  578. desc.AntialiasedLineEnable = FALSE;
  579. desc.ForcedSampleCount = 0;
  580. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  581. }
  582. // Create depth-stencil State
  583. {
  584. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  585. desc.DepthEnable = false;
  586. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  587. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  588. desc.StencilEnable = false;
  589. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  590. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  591. desc.BackFace = desc.FrontFace;
  592. }
  593. HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
  594. vertexShaderBlob->Release();
  595. pixelShaderBlob->Release();
  596. if (result_pipeline_state != S_OK)
  597. return false;
  598. ImGui_ImplDX12_CreateFontsTexture();
  599. return true;
  600. }
  601. void ImGui_ImplDX12_InvalidateDeviceObjects()
  602. {
  603. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  604. if (!bd || !bd->pd3dDevice)
  605. return;
  606. ImGuiIO& io = ImGui::GetIO();
  607. SafeRelease(bd->pRootSignature);
  608. SafeRelease(bd->pPipelineState);
  609. SafeRelease(bd->pFontTextureResource);
  610. io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
  611. for (UINT i = 0; i < bd->numFramesInFlight; i++)
  612. {
  613. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
  614. SafeRelease(fr->IndexBuffer);
  615. SafeRelease(fr->VertexBuffer);
  616. }
  617. }
  618. bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap,
  619. D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
  620. {
  621. ImGuiIO& io = ImGui::GetIO();
  622. IMGUI_CHECKVERSION();
  623. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  624. // Setup backend capabilities flags
  625. ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
  626. io.BackendRendererUserData = (void*)bd;
  627. io.BackendRendererName = "imgui_impl_dx12";
  628. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  629. bd->pd3dDevice = device;
  630. bd->RTVFormat = rtv_format;
  631. bd->hFontSrvCpuDescHandle = font_srv_cpu_desc_handle;
  632. bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle;
  633. bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[num_frames_in_flight];
  634. bd->numFramesInFlight = num_frames_in_flight;
  635. bd->pd3dSrvDescHeap = cbv_srv_heap;
  636. bd->frameIndex = UINT_MAX;
  637. // Create buffers with a default size (they will later be grown as needed)
  638. for (int i = 0; i < num_frames_in_flight; i++)
  639. {
  640. ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
  641. fr->IndexBuffer = nullptr;
  642. fr->VertexBuffer = nullptr;
  643. fr->IndexBufferSize = 10000;
  644. fr->VertexBufferSize = 5000;
  645. }
  646. return true;
  647. }
  648. void ImGui_ImplDX12_Shutdown()
  649. {
  650. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  651. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  652. ImGuiIO& io = ImGui::GetIO();
  653. // Clean up windows and device objects
  654. ImGui_ImplDX12_InvalidateDeviceObjects();
  655. delete[] bd->pFrameResources;
  656. io.BackendRendererName = nullptr;
  657. io.BackendRendererUserData = nullptr;
  658. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
  659. IM_DELETE(bd);
  660. }
  661. void ImGui_ImplDX12_NewFrame()
  662. {
  663. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
  664. IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
  665. if (!bd->pPipelineState)
  666. ImGui_ImplDX12_CreateDeviceObjects();
  667. }
  668. //-----------------------------------------------------------------------------
  669. #endif // #ifndef IMGUI_DISABLE