imgui_impl_dx12.cpp 30 KB

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