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