imgui_impl_dx12.cpp 48 KB

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