imgui_impl_dx12.cpp 29 KB

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