imgui_impl_dx12.cpp 34 KB

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