imgui_impl_dx12.cpp 28 KB

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