imgui_impl_dx12.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. // ImGui Win32 + DirectX12 binding
  2. // In this binding, ImTextureID is used to store a 'D3D12_GPU_DESCRIPTOR_HANDLE' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
  3. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  4. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  5. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  6. // https://github.com/ocornut/imgui
  7. #include <imgui.h>
  8. #include "imgui_impl_dx12.h"
  9. // DirectX
  10. #include <d3d12.h>
  11. #include <d3dcompiler.h>
  12. struct FrameResources
  13. {
  14. ID3D12Resource* IB;
  15. ID3D12Resource* VB;
  16. int VertexBufferSize;
  17. int IndexBufferSize;
  18. };
  19. // Data
  20. static INT64 g_Time = 0;
  21. static INT64 g_TicksPerSecond = 0;
  22. static HWND g_hWnd = 0;
  23. static ID3D12Device* g_pd3dDevice = NULL;
  24. static ID3D12GraphicsCommandList* g_pd3dCommandList = NULL;
  25. static ID3D10Blob* g_pVertexShaderBlob = NULL;
  26. static ID3D10Blob* g_pPixelShaderBlob = NULL;
  27. static ID3D12RootSignature* g_pRootSignature = NULL;
  28. static ID3D12PipelineState* g_pPipelineState = NULL;
  29. static DXGI_FORMAT g_RTVFormat = DXGI_FORMAT_UNKNOWN;
  30. static ID3D12Resource* g_pFontTextureResource = NULL;
  31. static D3D12_CPU_DESCRIPTOR_HANDLE g_hFontSrvCpuDescHandle = {};
  32. static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {};
  33. static FrameResources* g_pFrameResources = NULL;
  34. static UINT g_numFramesInFlight = 0;
  35. static UINT g_frameIndex = UINT_MAX;
  36. struct VERTEX_CONSTANT_BUFFER
  37. {
  38. float mvp[4][4];
  39. };
  40. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  41. // If text or lines are blurry when integrating ImGui in your engine:
  42. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  43. void ImGui_ImplDX12_RenderDrawLists(ImDrawData* draw_data)
  44. {
  45. // NOTE: I'm assuming that this only get's called once per frame! If not,
  46. // we can't just re-allocate the IB or VB, we'll have to do a proper
  47. // allocator.
  48. g_frameIndex = g_frameIndex + 1;
  49. FrameResources* frameResources = &g_pFrameResources[g_frameIndex % g_numFramesInFlight];
  50. ID3D12Resource* g_pVB = frameResources->VB;
  51. ID3D12Resource* g_pIB = frameResources->IB;
  52. int g_VertexBufferSize = frameResources->VertexBufferSize;
  53. int g_IndexBufferSize = frameResources->IndexBufferSize;
  54. ID3D12GraphicsCommandList* ctx = g_pd3dCommandList;
  55. // Create and grow vertex/index buffers if needed
  56. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  57. {
  58. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  59. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  60. D3D12_HEAP_PROPERTIES props;
  61. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  62. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  63. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  64. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  65. D3D12_RESOURCE_DESC desc;
  66. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  67. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  68. desc.Width = g_VertexBufferSize * sizeof(ImDrawVert);
  69. desc.Height = 1;
  70. desc.DepthOrArraySize = 1;
  71. desc.MipLevels = 1;
  72. desc.Format = DXGI_FORMAT_UNKNOWN;
  73. desc.SampleDesc.Count = 1;
  74. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  75. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  76. if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE,
  77. &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&g_pVB)) < 0)
  78. return;
  79. frameResources->VB = g_pVB;
  80. frameResources->VertexBufferSize = g_VertexBufferSize;
  81. }
  82. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  83. {
  84. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  85. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  86. D3D12_HEAP_PROPERTIES props;
  87. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  88. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  89. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  90. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  91. D3D12_RESOURCE_DESC desc;
  92. memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
  93. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  94. desc.Width = g_IndexBufferSize * sizeof(ImDrawIdx);
  95. desc.Height = 1;
  96. desc.DepthOrArraySize = 1;
  97. desc.MipLevels = 1;
  98. desc.Format = DXGI_FORMAT_UNKNOWN;
  99. desc.SampleDesc.Count = 1;
  100. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  101. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  102. if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE,
  103. &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&g_pIB)) < 0)
  104. return;
  105. frameResources->IB = g_pIB;
  106. frameResources->IndexBufferSize = g_IndexBufferSize;
  107. }
  108. // Copy and convert all vertices into a single contiguous buffer
  109. void* vtx_resource, *idx_resource;
  110. D3D12_RANGE range;
  111. memset(&range, 0, sizeof(D3D12_RANGE));
  112. if (g_pVB->Map(0, &range, &vtx_resource) != S_OK)
  113. return;
  114. if (g_pIB->Map(0, &range, &idx_resource) != S_OK)
  115. return;
  116. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
  117. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
  118. for (int n = 0; n < draw_data->CmdListsCount; n++)
  119. {
  120. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  121. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  122. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  123. vtx_dst += cmd_list->VtxBuffer.Size;
  124. idx_dst += cmd_list->IdxBuffer.Size;
  125. }
  126. g_pVB->Unmap(0, &range);
  127. g_pIB->Unmap(0, &range);
  128. // Setup orthographic projection matrix into our constant buffer
  129. VERTEX_CONSTANT_BUFFER vertex_constant_buffer;
  130. {
  131. VERTEX_CONSTANT_BUFFER* constant_buffer = &vertex_constant_buffer;
  132. float L = 0.0f;
  133. float R = ImGui::GetIO().DisplaySize.x;
  134. float B = ImGui::GetIO().DisplaySize.y;
  135. float T = 0.0f;
  136. float mvp[4][4] =
  137. {
  138. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  139. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  140. { 0.0f, 0.0f, 0.5f, 0.0f },
  141. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  142. };
  143. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  144. }
  145. // Setup viewport
  146. D3D12_VIEWPORT vp;
  147. memset(&vp, 0, sizeof(D3D12_VIEWPORT));
  148. vp.Width = ImGui::GetIO().DisplaySize.x;
  149. vp.Height = ImGui::GetIO().DisplaySize.y;
  150. vp.MinDepth = 0.0f;
  151. vp.MaxDepth = 1.0f;
  152. vp.TopLeftX = vp.TopLeftY = 0.0f;
  153. ctx->RSSetViewports(1, &vp);
  154. // Bind shader and vertex buffers
  155. unsigned int stride = sizeof(ImDrawVert);
  156. unsigned int offset = 0;
  157. D3D12_VERTEX_BUFFER_VIEW vbv;
  158. memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
  159. vbv.BufferLocation = g_pVB->GetGPUVirtualAddress() + offset;
  160. vbv.SizeInBytes = g_VertexBufferSize * stride;
  161. vbv.StrideInBytes = stride;
  162. ctx->IASetVertexBuffers(0, 1, &vbv);
  163. D3D12_INDEX_BUFFER_VIEW ibv;
  164. memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
  165. ibv.BufferLocation = g_pIB->GetGPUVirtualAddress();
  166. ibv.SizeInBytes = g_IndexBufferSize * sizeof(ImDrawIdx);
  167. ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  168. ctx->IASetIndexBuffer(&ibv);
  169. ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  170. ctx->SetPipelineState(g_pPipelineState);
  171. ctx->SetGraphicsRootSignature(g_pRootSignature);
  172. ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
  173. // Setup render state
  174. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  175. ctx->OMSetBlendFactor(blend_factor);
  176. // Render command lists
  177. int vtx_offset = 0;
  178. int idx_offset = 0;
  179. for (int n = 0; n < draw_data->CmdListsCount; n++)
  180. {
  181. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  182. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  183. {
  184. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  185. if (pcmd->UserCallback)
  186. {
  187. pcmd->UserCallback(cmd_list, pcmd);
  188. }
  189. else
  190. {
  191. const D3D12_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  192. ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId);
  193. ctx->RSSetScissorRects(1, &r);
  194. ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
  195. }
  196. idx_offset += pcmd->ElemCount;
  197. }
  198. vtx_offset += cmd_list->VtxBuffer.Size;
  199. }
  200. }
  201. IMGUI_API LRESULT ImGui_ImplDX12_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
  202. {
  203. ImGuiIO& io = ImGui::GetIO();
  204. switch (msg)
  205. {
  206. case WM_LBUTTONDOWN:
  207. io.MouseDown[0] = true;
  208. return true;
  209. case WM_LBUTTONUP:
  210. io.MouseDown[0] = false;
  211. return true;
  212. case WM_RBUTTONDOWN:
  213. io.MouseDown[1] = true;
  214. return true;
  215. case WM_RBUTTONUP:
  216. io.MouseDown[1] = false;
  217. return true;
  218. case WM_MBUTTONDOWN:
  219. io.MouseDown[2] = true;
  220. return true;
  221. case WM_MBUTTONUP:
  222. io.MouseDown[2] = false;
  223. return true;
  224. case WM_MOUSEWHEEL:
  225. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  226. return true;
  227. case WM_MOUSEMOVE:
  228. io.MousePos.x = (signed short)(lParam);
  229. io.MousePos.y = (signed short)(lParam >> 16);
  230. return true;
  231. case WM_KEYDOWN:
  232. if (wParam < 256)
  233. io.KeysDown[wParam] = 1;
  234. return true;
  235. case WM_KEYUP:
  236. if (wParam < 256)
  237. io.KeysDown[wParam] = 0;
  238. return true;
  239. case WM_CHAR:
  240. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  241. if (wParam > 0 && wParam < 0x10000)
  242. io.AddInputCharacter((unsigned short)wParam);
  243. return true;
  244. }
  245. return 0;
  246. }
  247. static void ImGui_ImplDX12_CreateFontsTexture()
  248. {
  249. // Build texture atlas
  250. ImGuiIO& io = ImGui::GetIO();
  251. unsigned char* pixels;
  252. int width, height;
  253. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  254. // Upload texture to graphics system
  255. {
  256. D3D12_HEAP_PROPERTIES props;
  257. memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
  258. props.Type = D3D12_HEAP_TYPE_DEFAULT;
  259. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  260. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  261. D3D12_RESOURCE_DESC desc;
  262. ZeroMemory(&desc, sizeof(desc));
  263. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  264. desc.Alignment = 0;
  265. desc.Width = width;
  266. desc.Height = height;
  267. desc.DepthOrArraySize = 1;
  268. desc.MipLevels = 1;
  269. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  270. desc.SampleDesc.Count = 1;
  271. desc.SampleDesc.Quality = 0;
  272. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  273. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  274. ID3D12Resource* pTexture = NULL;
  275. g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  276. D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture));
  277. UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
  278. UINT uploadSize = height * uploadPitch;
  279. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  280. desc.Alignment = 0;
  281. desc.Width = uploadSize;
  282. desc.Height = 1;
  283. desc.DepthOrArraySize = 1;
  284. desc.MipLevels = 1;
  285. desc.Format = DXGI_FORMAT_UNKNOWN;
  286. desc.SampleDesc.Count = 1;
  287. desc.SampleDesc.Quality = 0;
  288. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  289. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  290. props.Type = D3D12_HEAP_TYPE_UPLOAD;
  291. props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  292. props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  293. ID3D12Resource* uploadBuffer = NULL;
  294. HRESULT hr = g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
  295. D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer));
  296. assert(SUCCEEDED(hr));
  297. void* mapped = NULL;
  298. D3D12_RANGE range = { 0, uploadSize };
  299. hr = uploadBuffer->Map(0, &range, &mapped);
  300. assert(SUCCEEDED(hr));
  301. for (int y = 0; y < height; ++y)
  302. {
  303. memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4);
  304. }
  305. uploadBuffer->Unmap(0, &range);
  306. D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
  307. srcLocation.pResource = uploadBuffer;
  308. srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  309. srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  310. srcLocation.PlacedFootprint.Footprint.Width = width;
  311. srcLocation.PlacedFootprint.Footprint.Height = height;
  312. srcLocation.PlacedFootprint.Footprint.Depth = 1;
  313. srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
  314. D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
  315. dstLocation.pResource = pTexture;
  316. dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  317. dstLocation.SubresourceIndex = 0;
  318. D3D12_RESOURCE_BARRIER barrier = {};
  319. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  320. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  321. barrier.Transition.pResource = pTexture;
  322. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  323. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  324. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  325. ID3D12Fence* fence = NULL;
  326. hr = g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
  327. assert(SUCCEEDED(hr));
  328. HANDLE event = CreateEvent(0, 0, 0, 0);
  329. assert(event != NULL);
  330. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  331. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  332. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  333. queueDesc.NodeMask = 1;
  334. ID3D12CommandQueue* cmdQueue = NULL;
  335. hr = g_pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
  336. assert(SUCCEEDED(hr));
  337. ID3D12CommandAllocator* cmdAlloc = NULL;
  338. hr = g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
  339. assert(SUCCEEDED(hr));
  340. ID3D12GraphicsCommandList* cmdList = NULL;
  341. hr = g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList));
  342. assert(SUCCEEDED(hr));
  343. cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL);
  344. cmdList->ResourceBarrier(1, &barrier);
  345. hr = cmdList->Close();
  346. assert(SUCCEEDED(hr));
  347. cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*) &cmdList);
  348. hr = cmdQueue->Signal(fence, 1);
  349. assert(SUCCEEDED(hr));
  350. fence->SetEventOnCompletion(1, event);
  351. WaitForSingleObject(event, INFINITE);
  352. cmdList->Release();
  353. cmdAlloc->Release();
  354. cmdQueue->Release();
  355. CloseHandle(event);
  356. fence->Release();
  357. uploadBuffer->Release();
  358. // Create texture view
  359. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  360. ZeroMemory(&srvDesc, sizeof(srvDesc));
  361. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  362. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  363. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  364. srvDesc.Texture2D.MostDetailedMip = 0;
  365. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  366. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, g_hFontSrvCpuDescHandle);
  367. if (g_pFontTextureResource != NULL)
  368. g_pFontTextureResource->Release();
  369. g_pFontTextureResource = pTexture;
  370. }
  371. // Store our identifier
  372. static_assert(sizeof(void*) >= sizeof(g_hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID");
  373. io.Fonts->TexID = (void *)g_hFontSrvGpuDescHandle.ptr;
  374. }
  375. bool ImGui_ImplDX12_CreateDeviceObjects()
  376. {
  377. if (!g_pd3dDevice)
  378. return false;
  379. if (g_pPipelineState)
  380. ImGui_ImplDX12_InvalidateDeviceObjects();
  381. // Create the root signature
  382. {
  383. D3D12_DESCRIPTOR_RANGE descRange = {};
  384. descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  385. descRange.NumDescriptors = 1;
  386. descRange.BaseShaderRegister = 0;
  387. descRange.RegisterSpace = 0;
  388. descRange.OffsetInDescriptorsFromTableStart = 0;
  389. D3D12_ROOT_PARAMETER param[2] = {};
  390. param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
  391. param[0].Constants.ShaderRegister = 0;
  392. param[0].Constants.RegisterSpace = 0;
  393. param[0].Constants.Num32BitValues = 16;
  394. param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  395. param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  396. param[1].DescriptorTable.NumDescriptorRanges = 1;
  397. param[1].DescriptorTable.pDescriptorRanges = &descRange;
  398. param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  399. D3D12_STATIC_SAMPLER_DESC staticSampler = {};
  400. staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  401. staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  402. staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  403. staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  404. staticSampler.MipLODBias = 0.f;
  405. staticSampler.MaxAnisotropy = 0;
  406. staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  407. staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  408. staticSampler.MinLOD = 0.f;
  409. staticSampler.MaxLOD = 0.f;
  410. staticSampler.ShaderRegister = 0;
  411. staticSampler.RegisterSpace = 0;
  412. staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  413. D3D12_ROOT_SIGNATURE_DESC desc = {};
  414. desc.NumParameters = _countof(param);
  415. desc.pParameters = param;
  416. desc.NumStaticSamplers = 1;
  417. desc.pStaticSamplers = &staticSampler;
  418. desc.Flags =
  419. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
  420. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  421. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  422. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
  423. ID3DBlob* blob = NULL;
  424. if (D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, NULL) != S_OK)
  425. return false;
  426. g_pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature));
  427. blob->Release();
  428. }
  429. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  430. // If you would like to use this DX12 sample code but remove this dependency you can:
  431. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  432. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  433. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  434. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
  435. memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
  436. psoDesc.NodeMask = 1;
  437. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  438. psoDesc.pRootSignature = g_pRootSignature;
  439. psoDesc.SampleMask = UINT_MAX;
  440. psoDesc.NumRenderTargets = 1;
  441. psoDesc.RTVFormats[0] = g_RTVFormat;
  442. psoDesc.SampleDesc.Count = 1;
  443. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  444. // Create the vertex shader
  445. {
  446. static const char* vertexShader =
  447. "cbuffer vertexBuffer : register(b0) \
  448. {\
  449. float4x4 ProjectionMatrix; \
  450. };\
  451. struct VS_INPUT\
  452. {\
  453. float2 pos : POSITION;\
  454. float4 col : COLOR0;\
  455. float2 uv : TEXCOORD0;\
  456. };\
  457. \
  458. struct PS_INPUT\
  459. {\
  460. float4 pos : SV_POSITION;\
  461. float4 col : COLOR0;\
  462. float2 uv : TEXCOORD0;\
  463. };\
  464. \
  465. PS_INPUT main(VS_INPUT input)\
  466. {\
  467. PS_INPUT output;\
  468. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  469. output.col = input.col;\
  470. output.uv = input.uv;\
  471. return output;\
  472. }";
  473. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL);
  474. 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!
  475. return false;
  476. psoDesc.VS = { g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize() };
  477. // Create the input layout
  478. static D3D12_INPUT_ELEMENT_DESC local_layout[] = {
  479. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  480. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  481. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
  482. };
  483. psoDesc.InputLayout = { local_layout, 3 };
  484. }
  485. // Create the pixel shader
  486. {
  487. static const char* pixelShader =
  488. "struct PS_INPUT\
  489. {\
  490. float4 pos : SV_POSITION;\
  491. float4 col : COLOR0;\
  492. float2 uv : TEXCOORD0;\
  493. };\
  494. SamplerState sampler0 : register(s0);\
  495. Texture2D texture0 : register(t0);\
  496. \
  497. float4 main(PS_INPUT input) : SV_Target\
  498. {\
  499. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  500. return out_col; \
  501. }";
  502. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL);
  503. 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!
  504. return false;
  505. psoDesc.PS = { g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize() };
  506. }
  507. // Create the blending setup
  508. {
  509. D3D12_BLEND_DESC& desc = psoDesc.BlendState;
  510. desc.AlphaToCoverageEnable = false;
  511. desc.RenderTarget[0].BlendEnable = true;
  512. desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
  513. desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  514. desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
  515. desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
  516. desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO;
  517. desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
  518. desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  519. }
  520. // Create the rasterizer state
  521. {
  522. D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
  523. desc.FillMode = D3D12_FILL_MODE_SOLID;
  524. desc.CullMode = D3D12_CULL_MODE_NONE;
  525. desc.FrontCounterClockwise = FALSE;
  526. desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
  527. desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
  528. desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
  529. desc.DepthClipEnable = true;
  530. desc.MultisampleEnable = FALSE;
  531. desc.AntialiasedLineEnable = FALSE;
  532. desc.ForcedSampleCount = 0;
  533. desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  534. }
  535. // Create depth-stencil State
  536. {
  537. D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
  538. desc.DepthEnable = false;
  539. desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
  540. desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  541. desc.StencilEnable = false;
  542. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
  543. desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  544. desc.BackFace = desc.FrontFace;
  545. }
  546. if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK)
  547. return false;
  548. ImGui_ImplDX12_CreateFontsTexture();
  549. return true;
  550. }
  551. void ImGui_ImplDX12_InvalidateDeviceObjects()
  552. {
  553. if (!g_pd3dDevice)
  554. return;
  555. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  556. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  557. if (g_pRootSignature) { g_pRootSignature->Release(); g_pRootSignature = NULL; }
  558. if (g_pPipelineState) { g_pPipelineState->Release(); g_pPipelineState = NULL; }
  559. 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.
  560. for (UINT i = 0; i < g_numFramesInFlight; ++i)
  561. {
  562. if (g_pFrameResources[i].IB) { g_pFrameResources[i].IB->Release(); g_pFrameResources[i].IB = NULL; }
  563. if (g_pFrameResources[i].VB) { g_pFrameResources[i].VB->Release(); g_pFrameResources[i].VB = NULL; }
  564. }
  565. }
  566. bool ImGui_ImplDX12_Init(void* hwnd, int num_frames_in_flight,
  567. ID3D12Device* device,
  568. DXGI_FORMAT rtv_format,
  569. D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle,
  570. D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
  571. {
  572. g_hWnd = (HWND)hwnd;
  573. g_pd3dDevice = device;
  574. g_RTVFormat = rtv_format;
  575. g_hFontSrvCpuDescHandle = font_srv_cpu_desc_handle;
  576. g_hFontSrvGpuDescHandle = font_srv_gpu_desc_handle;
  577. g_pFrameResources = new FrameResources [num_frames_in_flight];
  578. g_numFramesInFlight = num_frames_in_flight;
  579. g_frameIndex = UINT_MAX;
  580. for (int i = 0; i < num_frames_in_flight; ++i)
  581. {
  582. g_pFrameResources[i].IB = NULL;
  583. g_pFrameResources[i].VB = NULL;
  584. g_pFrameResources[i].VertexBufferSize = 5000;
  585. g_pFrameResources[i].IndexBufferSize = 10000;
  586. }
  587. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  588. return false;
  589. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  590. return false;
  591. ImGuiIO& io = ImGui::GetIO();
  592. io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
  593. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  594. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  595. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  596. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  597. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  598. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  599. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  600. io.KeyMap[ImGuiKey_End] = VK_END;
  601. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  602. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  603. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  604. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  605. io.KeyMap[ImGuiKey_A] = 'A';
  606. io.KeyMap[ImGuiKey_C] = 'C';
  607. io.KeyMap[ImGuiKey_V] = 'V';
  608. io.KeyMap[ImGuiKey_X] = 'X';
  609. io.KeyMap[ImGuiKey_Y] = 'Y';
  610. io.KeyMap[ImGuiKey_Z] = 'Z';
  611. io.RenderDrawListsFn = ImGui_ImplDX12_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  612. io.ImeWindowHandle = g_hWnd;
  613. return true;
  614. }
  615. void ImGui_ImplDX12_Shutdown()
  616. {
  617. ImGui_ImplDX12_InvalidateDeviceObjects();
  618. ImGui::Shutdown();
  619. delete[] g_pFrameResources;
  620. g_pd3dDevice = NULL;
  621. g_hWnd = (HWND)0;
  622. g_pd3dCommandList = NULL;
  623. g_hFontSrvCpuDescHandle.ptr = 0;
  624. g_hFontSrvGpuDescHandle.ptr = 0;
  625. g_pFrameResources = NULL;
  626. g_numFramesInFlight = 0;
  627. g_frameIndex = UINT_MAX;
  628. }
  629. void ImGui_ImplDX12_NewFrame(ID3D12GraphicsCommandList* command_list)
  630. {
  631. if (!g_pPipelineState)
  632. ImGui_ImplDX12_CreateDeviceObjects();
  633. g_pd3dCommandList = command_list;
  634. ImGuiIO& io = ImGui::GetIO();
  635. // Setup display size (every frame to accommodate for window resizing)
  636. RECT rect;
  637. GetClientRect(g_hWnd, &rect);
  638. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  639. // Setup time step
  640. INT64 current_time;
  641. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  642. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  643. g_Time = current_time;
  644. // Read keyboard modifiers inputs
  645. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  646. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  647. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  648. io.KeySuper = false;
  649. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  650. // io.MousePos : filled by WM_MOUSEMOVE events
  651. // io.MouseDown : filled by WM_*BUTTON* events
  652. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  653. // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  654. if (io.WantMoveMouse)
  655. {
  656. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  657. ClientToScreen(g_hWnd, &pos);
  658. SetCursorPos(pos.x, pos.y);
  659. }
  660. // Hide OS mouse cursor if ImGui is drawing it
  661. if (io.MouseDrawCursor)
  662. SetCursor(NULL);
  663. // Start the frame
  664. ImGui::NewFrame();
  665. }