imgui_impl_dx12.cpp 32 KB

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