imgui_impl_dx12.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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-02-22: Merged into master with all Win32 code synchronized to other examples.
  12. #include "imgui.h"
  13. #include "imgui_impl_dx12.h"
  14. // DirectX
  15. #include <d3d12.h>
  16. #include <dxgi1_4.h>
  17. #include <d3dcompiler.h>
  18. // DirectX data
  19. static ID3D12Device* g_pd3dDevice = NULL;
  20. static ID3D12GraphicsCommandList* g_pd3dCommandList = NULL;
  21. static ID3D10Blob* g_pVertexShaderBlob = NULL;
  22. static ID3D10Blob* g_pPixelShaderBlob = NULL;
  23. static ID3D12RootSignature* g_pRootSignature = NULL;
  24. static ID3D12PipelineState* g_pPipelineState = NULL;
  25. static DXGI_FORMAT g_RTVFormat = DXGI_FORMAT_UNKNOWN;
  26. static ID3D12Resource* g_pFontTextureResource = NULL;
  27. static D3D12_CPU_DESCRIPTOR_HANDLE g_hFontSrvCpuDescHandle = {};
  28. static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {};
  29. struct FrameResources
  30. {
  31. ID3D12Resource* IB;
  32. ID3D12Resource* VB;
  33. int VertexBufferSize;
  34. int IndexBufferSize;
  35. };
  36. static FrameResources* g_pFrameResources = NULL;
  37. static UINT g_numFramesInFlight = 0;
  38. static UINT g_frameIndex = UINT_MAX;
  39. struct VERTEX_CONSTANT_BUFFER
  40. {
  41. float mvp[4][4];
  42. };
  43. // Forward Declarations
  44. static void ImGui_ImplDX12_InitPlatformInterface();
  45. static void ImGui_ImplDX12_ShutdownPlatformInterface();
  46. // Render function
  47. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  48. void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data)
  49. {
  50. // NOTE: I'm assuming that this only get's called once per frame!
  51. // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
  52. g_frameIndex = g_frameIndex + 1;
  53. FrameResources* frameResources = &g_pFrameResources[g_frameIndex % g_numFramesInFlight];
  54. ID3D12Resource* g_pVB = frameResources->VB;
  55. ID3D12Resource* g_pIB = frameResources->IB;
  56. int g_VertexBufferSize = frameResources->VertexBufferSize;
  57. int g_IndexBufferSize = frameResources->IndexBufferSize;
  58. ID3D12GraphicsCommandList* ctx = g_pd3dCommandList;
  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,
  81. &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&g_pVB)) < 0)
  82. return;
  83. frameResources->VB = g_pVB;
  84. frameResources->VertexBufferSize = g_VertexBufferSize;
  85. }
  86. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  87. {
  88. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  89. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  90. D3D12_HEAP_PROPERTIES props;
  91. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  92. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  93. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  94. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  95. D3D12_RESOURCE_DESC desc;
  96. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  97. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  98. desc.Width = g_IndexBufferSize * sizeof(ImDrawIdx);
  99. desc.Height = 1;
  100. desc.DepthOrArraySize = 1;
  101. desc.MipLevels = 1;
  102. desc.Format = DXGI_FORMAT_UNKNOWN;
  103. desc.SampleDesc.Count = 1;
  104. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  105. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  106. if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE,
  107. &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. VERTEX_CONSTANT_BUFFER vertex_constant_buffer;
  134. {
  135. VERTEX_CONSTANT_BUFFER* constant_buffer = &vertex_constant_buffer;
  136. float L = 0.0f;
  137. float R = ImGui::GetIO().DisplaySize.x;
  138. float B = ImGui::GetIO().DisplaySize.y;
  139. float T = 0.0f;
  140. float mvp[4][4] =
  141. {
  142. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  143. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  144. { 0.0f, 0.0f, 0.5f, 0.0f },
  145. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  146. };
  147. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  148. }
  149. // Setup viewport
  150. D3D12_VIEWPORT vp;
  151. memset(&vp, 0, sizeof(D3D12_VIEWPORT));
  152. vp.Width = ImGui::GetIO().DisplaySize.x;
  153. vp.Height = ImGui::GetIO().DisplaySize.y;
  154. vp.MinDepth = 0.0f;
  155. vp.MaxDepth = 1.0f;
  156. vp.TopLeftX = vp.TopLeftY = 0.0f;
  157. ctx->RSSetViewports(1, &vp);
  158. // Bind shader and vertex buffers
  159. unsigned int stride = sizeof(ImDrawVert);
  160. unsigned int offset = 0;
  161. D3D12_VERTEX_BUFFER_VIEW vbv;
  162. memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
  163. vbv.BufferLocation = g_pVB->GetGPUVirtualAddress() + offset;
  164. vbv.SizeInBytes = g_VertexBufferSize * stride;
  165. vbv.StrideInBytes = stride;
  166. ctx->IASetVertexBuffers(0, 1, &vbv);
  167. D3D12_INDEX_BUFFER_VIEW ibv;
  168. memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
  169. ibv.BufferLocation = g_pIB->GetGPUVirtualAddress();
  170. ibv.SizeInBytes = g_IndexBufferSize * sizeof(ImDrawIdx);
  171. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  172. ctx->IASetIndexBuffer(&ibv);
  173. ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  174. ctx->SetPipelineState(g_pPipelineState);
  175. ctx->SetGraphicsRootSignature(g_pRootSignature);
  176. ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  177. // Setup render state
  178. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  179. ctx->OMSetBlendFactor(blend_factor);
  180. // Render command lists
  181. int vtx_offset = 0;
  182. int idx_offset = 0;
  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, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  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. for (int i = 0; i < num_frames_in_flight; i++)
  533. {
  534. g_pFrameResources[i].IB = NULL;
  535. g_pFrameResources[i].VB = NULL;
  536. g_pFrameResources[i].VertexBufferSize = 5000;
  537. g_pFrameResources[i].IndexBufferSize = 10000;
  538. }
  539. ImGuiIO& io = ImGui::GetIO();
  540. if (io.ConfigFlags & ImGuiConfigFlags_MultiViewports)
  541. ImGui_ImplDX12_InitPlatformInterface();
  542. return true;
  543. }
  544. void ImGui_ImplDX12_Shutdown()
  545. {
  546. ImGui_ImplDX12_ShutdownPlatformInterface();
  547. ImGui_ImplDX12_InvalidateDeviceObjects();
  548. delete[] g_pFrameResources;
  549. g_pd3dDevice = NULL;
  550. g_pd3dCommandList = NULL;
  551. g_hFontSrvCpuDescHandle.ptr = 0;
  552. g_hFontSrvGpuDescHandle.ptr = 0;
  553. g_pFrameResources = NULL;
  554. g_numFramesInFlight = 0;
  555. g_frameIndex = UINT_MAX;
  556. }
  557. void ImGui_ImplDX12_NewFrame(ID3D12GraphicsCommandList* command_list)
  558. {
  559. if (!g_pPipelineState)
  560. ImGui_ImplDX12_CreateDeviceObjects();
  561. g_pd3dCommandList = command_list;
  562. }
  563. // --------------------------------------------------------------------------------------------------------
  564. // Platform Windows
  565. // --------------------------------------------------------------------------------------------------------
  566. #include "imgui_internal.h" // ImGuiViewport
  567. struct ImGuiPlatformDataDx12
  568. {
  569. IDXGISwapChain3* SwapChain;
  570. ImGuiPlatformDataDx12() { SwapChain = NULL; }
  571. ~ImGuiPlatformDataDx12() { IM_ASSERT(SwapChain == NULL); }
  572. };
  573. static void ImGui_ImplDX12_CreateViewport(ImGuiViewport* viewport)
  574. {
  575. ImGuiPlatformDataDx12* data = IM_NEW(ImGuiPlatformDataDx12)();
  576. viewport->RendererUserData = data;
  577. IM_ASSERT(0);
  578. /*
  579. // FIXME-PLATFORM
  580. HWND hwnd = (HWND)viewport->PlatformHandle;
  581. IM_ASSERT(hwnd != 0);
  582. // Create swap chain
  583. DXGI_SWAP_CHAIN_DESC sd;
  584. ZeroMemory(&sd, sizeof(sd));
  585. sd.BufferDesc.Width = (UINT)viewport->Size.x;
  586. sd.BufferDesc.Height = (UINT)viewport->Size.y;
  587. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  588. sd.SampleDesc.Count = 1;
  589. sd.SampleDesc.Quality = 0;
  590. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  591. sd.BufferCount = 1;
  592. sd.OutputWindow = hwnd;
  593. sd.Windowed = TRUE;
  594. sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  595. sd.Flags = 0;
  596. IM_ASSERT(data->SwapChain == NULL && data->RTView == NULL);
  597. g_pFactory->CreateSwapChain(g_pd3dDevice, &sd, &data->SwapChain);
  598. // Create the render target
  599. if (data->SwapChain)
  600. {
  601. ID3D11Texture2D* pBackBuffer;
  602. data->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  603. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &data->RTView);
  604. pBackBuffer->Release();
  605. }
  606. */
  607. }
  608. static void ImGui_ImplDX12_DestroyViewport(ImGuiViewport* viewport)
  609. {
  610. if (ImGuiPlatformDataDx12* data = (ImGuiPlatformDataDx12*)viewport->RendererUserData)
  611. {
  612. IM_ASSERT(0);
  613. /*
  614. if (data->SwapChain)
  615. data->SwapChain->Release();
  616. data->SwapChain = NULL;
  617. if (data->RTView)
  618. data->RTView->Release();
  619. data->RTView = NULL;
  620. IM_DELETE(data);
  621. */
  622. }
  623. viewport->RendererUserData = NULL;
  624. }
  625. static void ImGui_ImplDX12_ResizeViewport(ImGuiViewport* viewport, int w, int h)
  626. {
  627. ImGuiPlatformDataDx12* data = (ImGuiPlatformDataDx12*)viewport->RendererUserData;
  628. IM_ASSERT(0);
  629. /*
  630. if (data->RTView)
  631. {
  632. data->RTView->Release();
  633. data->RTView = NULL;
  634. }
  635. if (data->SwapChain)
  636. {
  637. ID3D11Texture2D* pBackBuffer = NULL;
  638. data->SwapChain->ResizeBuffers(0, w, h, DXGI_FORMAT_UNKNOWN, 0);
  639. data->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  640. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &data->RTView);
  641. pBackBuffer->Release();
  642. }
  643. */
  644. }
  645. static void ImGui_ImplDX12_RenderViewport(ImGuiViewport* viewport)
  646. {
  647. ImGuiPlatformDataDx12* data = (ImGuiPlatformDataDx12*)viewport->RendererUserData;
  648. IM_ASSERT(0);
  649. /*
  650. ImVec4 clear_color = ImGui::GetStyle().Colors[ImGuiCol_WindowBg]; // FIXME-PLATFORM
  651. clear_color.w = 1.0f;
  652. g_pd3dDeviceContext->OMSetRenderTargets(1, &data->RTView, NULL);
  653. g_pd3dDeviceContext->ClearRenderTargetView(data->RTView, (float*)&clear_color);
  654. */
  655. ImGui_ImplDX12_RenderDrawData(&viewport->DrawData);
  656. }
  657. static void ImGui_ImplDX12_SwapBuffers(ImGuiViewport* viewport)
  658. {
  659. ImGuiPlatformDataDx12* data = (ImGuiPlatformDataDx12*)viewport->RendererUserData;
  660. IM_ASSERT(0);
  661. /*
  662. data->SwapChain->Present(0, 0); // Present without vsync
  663. */
  664. }
  665. void ImGui_ImplDX12_InitPlatformInterface()
  666. {
  667. ImGuiIO& io = ImGui::GetIO();
  668. io.RendererInterface.CreateViewport = ImGui_ImplDX12_CreateViewport;
  669. io.RendererInterface.DestroyViewport = ImGui_ImplDX12_DestroyViewport;
  670. io.RendererInterface.ResizeViewport = ImGui_ImplDX12_ResizeViewport;
  671. io.RendererInterface.RenderViewport = ImGui_ImplDX12_RenderViewport;
  672. io.RendererInterface.SwapBuffers = ImGui_ImplDX12_SwapBuffers;
  673. }
  674. void ImGui_ImplDX12_ShutdownPlatformInterface()
  675. {
  676. ImGuiIO& io = ImGui::GetIO();
  677. memset(&io.RendererInterface, 0, sizeof(io.RendererInterface));
  678. }