imgui_impl_dx12.cpp 34 KB

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