imgui_impl_dx12.cpp 27 KB

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