1 // dear imgui: Renderer Backend for DirectX12
2 // This needs to be used along with a Platform Backend (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!
6 // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
7
8 // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
9 // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
10 // To build this on 32-bit systems:
11 // - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file)
12 // - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like.
13 // - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!)
14 // - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file)
15
16 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
17 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
18 // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
19 // Read online: https://github.com/ocornut/imgui/tree/master/docs
20
21 // CHANGELOG
22 // (minor and older changes stripped away, please see git history for details)
23 // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
24 // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
25 // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
26 // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
27 // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
28 // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
29 // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
30 // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
31 // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
32 // 2019-03-29: Misc: Various minor tidying up.
33 // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
34 // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
35 // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
36 // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
37 // 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).
38 // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
39
40 #include "imgui.h"
41 #include "imgui_impl_dx12.h"
42
43 // DirectX
44 #include <d3d12.h>
45 #include <dxgi1_4.h>
46 #include <d3dcompiler.h>
47 #ifdef _MSC_VER
48 #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
49 #endif
50
51 // DirectX data
52 struct ImGui_ImplDX12_RenderBuffers
53 {
54 ID3D12Resource* IndexBuffer;
55 ID3D12Resource* VertexBuffer;
56 int IndexBufferSize;
57 int VertexBufferSize;
58 };
59
60 struct ImGui_ImplDX12_Data
61 {
62 ID3D12Device* pd3dDevice;
63 ID3D12RootSignature* pRootSignature;
64 ID3D12PipelineState* pPipelineState;
65 DXGI_FORMAT RTVFormat;
66 ID3D12Resource* pFontTextureResource;
67 D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
68 D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
69
70 ImGui_ImplDX12_RenderBuffers* pFrameResources;
71 UINT numFramesInFlight;
72 UINT frameIndex;
73
ImGui_ImplDX12_DataImGui_ImplDX12_Data74 ImGui_ImplDX12_Data() { memset(this, 0, sizeof(*this)); frameIndex = UINT_MAX; }
75 };
76
77 struct VERTEX_CONSTANT_BUFFER
78 {
79 float mvp[4][4];
80 };
81
82 // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
83 // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
ImGui_ImplDX12_GetBackendData()84 static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
85 {
86 return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : NULL;
87 }
88
89 // Functions
ImGui_ImplDX12_SetupRenderState(ImDrawData * draw_data,ID3D12GraphicsCommandList * ctx,ImGui_ImplDX12_RenderBuffers * fr)90 static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr)
91 {
92 ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
93
94 // Setup orthographic projection matrix into our constant buffer
95 // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
96 VERTEX_CONSTANT_BUFFER vertex_constant_buffer;
97 {
98 float L = draw_data->DisplayPos.x;
99 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
100 float T = draw_data->DisplayPos.y;
101 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
102 float mvp[4][4] =
103 {
104 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
105 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
106 { 0.0f, 0.0f, 0.5f, 0.0f },
107 { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
108 };
109 memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
110 }
111
112 // Setup viewport
113 D3D12_VIEWPORT vp;
114 memset(&vp, 0, sizeof(D3D12_VIEWPORT));
115 vp.Width = draw_data->DisplaySize.x;
116 vp.Height = draw_data->DisplaySize.y;
117 vp.MinDepth = 0.0f;
118 vp.MaxDepth = 1.0f;
119 vp.TopLeftX = vp.TopLeftY = 0.0f;
120 ctx->RSSetViewports(1, &vp);
121
122 // Bind shader and vertex buffers
123 unsigned int stride = sizeof(ImDrawVert);
124 unsigned int offset = 0;
125 D3D12_VERTEX_BUFFER_VIEW vbv;
126 memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
127 vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
128 vbv.SizeInBytes = fr->VertexBufferSize * stride;
129 vbv.StrideInBytes = stride;
130 ctx->IASetVertexBuffers(0, 1, &vbv);
131 D3D12_INDEX_BUFFER_VIEW ibv;
132 memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
133 ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
134 ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
135 ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
136 ctx->IASetIndexBuffer(&ibv);
137 ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
138 ctx->SetPipelineState(bd->pPipelineState);
139 ctx->SetGraphicsRootSignature(bd->pRootSignature);
140 ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
141
142 // Setup blend factor
143 const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
144 ctx->OMSetBlendFactor(blend_factor);
145 }
146
147 template<typename T>
SafeRelease(T * & res)148 static inline void SafeRelease(T*& res)
149 {
150 if (res)
151 res->Release();
152 res = NULL;
153 }
154
155 // Render function
ImGui_ImplDX12_RenderDrawData(ImDrawData * draw_data,ID3D12GraphicsCommandList * ctx)156 void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx)
157 {
158 // Avoid rendering when minimized
159 if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
160 return;
161
162 // FIXME: I'm assuming that this only gets called once per frame!
163 // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
164 ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
165 bd->frameIndex = bd->frameIndex + 1;
166 ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
167
168 // Create and grow vertex/index buffers if needed
169 if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount)
170 {
171 SafeRelease(fr->VertexBuffer);
172 fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
173 D3D12_HEAP_PROPERTIES props;
174 memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
175 props.Type = D3D12_HEAP_TYPE_UPLOAD;
176 props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
177 props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
178 D3D12_RESOURCE_DESC desc;
179 memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
180 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
181 desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
182 desc.Height = 1;
183 desc.DepthOrArraySize = 1;
184 desc.MipLevels = 1;
185 desc.Format = DXGI_FORMAT_UNKNOWN;
186 desc.SampleDesc.Count = 1;
187 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
188 desc.Flags = D3D12_RESOURCE_FLAG_NONE;
189 if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
190 return;
191 }
192 if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount)
193 {
194 SafeRelease(fr->IndexBuffer);
195 fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
196 D3D12_HEAP_PROPERTIES props;
197 memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
198 props.Type = D3D12_HEAP_TYPE_UPLOAD;
199 props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
200 props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
201 D3D12_RESOURCE_DESC desc;
202 memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
203 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
204 desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
205 desc.Height = 1;
206 desc.DepthOrArraySize = 1;
207 desc.MipLevels = 1;
208 desc.Format = DXGI_FORMAT_UNKNOWN;
209 desc.SampleDesc.Count = 1;
210 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
211 desc.Flags = D3D12_RESOURCE_FLAG_NONE;
212 if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
213 return;
214 }
215
216 // Upload vertex/index data into a single contiguous GPU buffer
217 void* vtx_resource, *idx_resource;
218 D3D12_RANGE range;
219 memset(&range, 0, sizeof(D3D12_RANGE));
220 if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
221 return;
222 if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
223 return;
224 ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
225 ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
226 for (int n = 0; n < draw_data->CmdListsCount; n++)
227 {
228 const ImDrawList* cmd_list = draw_data->CmdLists[n];
229 memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
230 memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
231 vtx_dst += cmd_list->VtxBuffer.Size;
232 idx_dst += cmd_list->IdxBuffer.Size;
233 }
234 fr->VertexBuffer->Unmap(0, &range);
235 fr->IndexBuffer->Unmap(0, &range);
236
237 // Setup desired DX state
238 ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
239
240 // Render command lists
241 // (Because we merged all buffers into a single one, we maintain our own offset into them)
242 int global_vtx_offset = 0;
243 int global_idx_offset = 0;
244 ImVec2 clip_off = draw_data->DisplayPos;
245 for (int n = 0; n < draw_data->CmdListsCount; n++)
246 {
247 const ImDrawList* cmd_list = draw_data->CmdLists[n];
248 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
249 {
250 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
251 if (pcmd->UserCallback != NULL)
252 {
253 // User callback, registered via ImDrawList::AddCallback()
254 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
255 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
256 ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
257 else
258 pcmd->UserCallback(cmd_list, pcmd);
259 }
260 else
261 {
262 // Project scissor/clipping rectangles into framebuffer space
263 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
264 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
265 if (clip_max.x < clip_min.x || clip_max.y < clip_min.y)
266 continue;
267
268 // Apply Scissor/clipping rectangle, Bind texture, Draw
269 const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
270 D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
271 texture_handle.ptr = (UINT64)pcmd->GetTexID();
272 ctx->SetGraphicsRootDescriptorTable(1, texture_handle);
273 ctx->RSSetScissorRects(1, &r);
274 ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
275 }
276 }
277 global_idx_offset += cmd_list->IdxBuffer.Size;
278 global_vtx_offset += cmd_list->VtxBuffer.Size;
279 }
280 }
281
ImGui_ImplDX12_CreateFontsTexture()282 static void ImGui_ImplDX12_CreateFontsTexture()
283 {
284 // Build texture atlas
285 ImGuiIO& io = ImGui::GetIO();
286 ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
287 unsigned char* pixels;
288 int width, height;
289 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
290
291 // Upload texture to graphics system
292 {
293 D3D12_HEAP_PROPERTIES props;
294 memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
295 props.Type = D3D12_HEAP_TYPE_DEFAULT;
296 props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
297 props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
298
299 D3D12_RESOURCE_DESC desc;
300 ZeroMemory(&desc, sizeof(desc));
301 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
302 desc.Alignment = 0;
303 desc.Width = width;
304 desc.Height = height;
305 desc.DepthOrArraySize = 1;
306 desc.MipLevels = 1;
307 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
308 desc.SampleDesc.Count = 1;
309 desc.SampleDesc.Quality = 0;
310 desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
311 desc.Flags = D3D12_RESOURCE_FLAG_NONE;
312
313 ID3D12Resource* pTexture = NULL;
314 bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
315 D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture));
316
317 UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
318 UINT uploadSize = height * uploadPitch;
319 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
320 desc.Alignment = 0;
321 desc.Width = uploadSize;
322 desc.Height = 1;
323 desc.DepthOrArraySize = 1;
324 desc.MipLevels = 1;
325 desc.Format = DXGI_FORMAT_UNKNOWN;
326 desc.SampleDesc.Count = 1;
327 desc.SampleDesc.Quality = 0;
328 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
329 desc.Flags = D3D12_RESOURCE_FLAG_NONE;
330
331 props.Type = D3D12_HEAP_TYPE_UPLOAD;
332 props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
333 props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
334
335 ID3D12Resource* uploadBuffer = NULL;
336 HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
337 D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer));
338 IM_ASSERT(SUCCEEDED(hr));
339
340 void* mapped = NULL;
341 D3D12_RANGE range = { 0, uploadSize };
342 hr = uploadBuffer->Map(0, &range, &mapped);
343 IM_ASSERT(SUCCEEDED(hr));
344 for (int y = 0; y < height; y++)
345 memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4);
346 uploadBuffer->Unmap(0, &range);
347
348 D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
349 srcLocation.pResource = uploadBuffer;
350 srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
351 srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
352 srcLocation.PlacedFootprint.Footprint.Width = width;
353 srcLocation.PlacedFootprint.Footprint.Height = height;
354 srcLocation.PlacedFootprint.Footprint.Depth = 1;
355 srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
356
357 D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
358 dstLocation.pResource = pTexture;
359 dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
360 dstLocation.SubresourceIndex = 0;
361
362 D3D12_RESOURCE_BARRIER barrier = {};
363 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
364 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
365 barrier.Transition.pResource = pTexture;
366 barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
367 barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
368 barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
369
370 ID3D12Fence* fence = NULL;
371 hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
372 IM_ASSERT(SUCCEEDED(hr));
373
374 HANDLE event = CreateEvent(0, 0, 0, 0);
375 IM_ASSERT(event != NULL);
376
377 D3D12_COMMAND_QUEUE_DESC queueDesc = {};
378 queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
379 queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
380 queueDesc.NodeMask = 1;
381
382 ID3D12CommandQueue* cmdQueue = NULL;
383 hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
384 IM_ASSERT(SUCCEEDED(hr));
385
386 ID3D12CommandAllocator* cmdAlloc = NULL;
387 hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
388 IM_ASSERT(SUCCEEDED(hr));
389
390 ID3D12GraphicsCommandList* cmdList = NULL;
391 hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList));
392 IM_ASSERT(SUCCEEDED(hr));
393
394 cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL);
395 cmdList->ResourceBarrier(1, &barrier);
396
397 hr = cmdList->Close();
398 IM_ASSERT(SUCCEEDED(hr));
399
400 cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
401 hr = cmdQueue->Signal(fence, 1);
402 IM_ASSERT(SUCCEEDED(hr));
403
404 fence->SetEventOnCompletion(1, event);
405 WaitForSingleObject(event, INFINITE);
406
407 cmdList->Release();
408 cmdAlloc->Release();
409 cmdQueue->Release();
410 CloseHandle(event);
411 fence->Release();
412 uploadBuffer->Release();
413
414 // Create texture view
415 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
416 ZeroMemory(&srvDesc, sizeof(srvDesc));
417 srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
418 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
419 srvDesc.Texture2D.MipLevels = desc.MipLevels;
420 srvDesc.Texture2D.MostDetailedMip = 0;
421 srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
422 bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle);
423 SafeRelease(bd->pFontTextureResource);
424 bd->pFontTextureResource = pTexture;
425 }
426
427 // Store our identifier
428 // READ THIS IF THE STATIC_ASSERT() TRIGGERS:
429 // - Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'.
430 // - This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
431 // [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file)
432 // [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like.
433 // [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!)
434 // [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file)
435 static_assert(sizeof(ImTextureID) >= sizeof(bd->hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
436 io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr);
437 }
438
ImGui_ImplDX12_CreateDeviceObjects()439 bool ImGui_ImplDX12_CreateDeviceObjects()
440 {
441 ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
442 if (!bd || !bd->pd3dDevice)
443 return false;
444 if (bd->pPipelineState)
445 ImGui_ImplDX12_InvalidateDeviceObjects();
446
447 // Create the root signature
448 {
449 D3D12_DESCRIPTOR_RANGE descRange = {};
450 descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
451 descRange.NumDescriptors = 1;
452 descRange.BaseShaderRegister = 0;
453 descRange.RegisterSpace = 0;
454 descRange.OffsetInDescriptorsFromTableStart = 0;
455
456 D3D12_ROOT_PARAMETER param[2] = {};
457
458 param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
459 param[0].Constants.ShaderRegister = 0;
460 param[0].Constants.RegisterSpace = 0;
461 param[0].Constants.Num32BitValues = 16;
462 param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
463
464 param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
465 param[1].DescriptorTable.NumDescriptorRanges = 1;
466 param[1].DescriptorTable.pDescriptorRanges = &descRange;
467 param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
468
469 D3D12_STATIC_SAMPLER_DESC staticSampler = {};
470 staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
471 staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
472 staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
473 staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
474 staticSampler.MipLODBias = 0.f;
475 staticSampler.MaxAnisotropy = 0;
476 staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
477 staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
478 staticSampler.MinLOD = 0.f;
479 staticSampler.MaxLOD = 0.f;
480 staticSampler.ShaderRegister = 0;
481 staticSampler.RegisterSpace = 0;
482 staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
483
484 D3D12_ROOT_SIGNATURE_DESC desc = {};
485 desc.NumParameters = _countof(param);
486 desc.pParameters = param;
487 desc.NumStaticSamplers = 1;
488 desc.pStaticSamplers = &staticSampler;
489 desc.Flags =
490 D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
491 D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
492 D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
493 D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
494
495 // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
496 // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
497 static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
498 if (d3d12_dll == NULL)
499 {
500 // Attempt to load d3d12.dll from local directories. This will only succeed if
501 // (1) the current OS is Windows 7, and
502 // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
503 // See https://github.com/ocornut/imgui/pull/3696 for details.
504 const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample
505 for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
506 if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != NULL)
507 break;
508
509 // If failed, we are on Windows >= 10.
510 if (d3d12_dll == NULL)
511 d3d12_dll = ::LoadLibraryA("d3d12.dll");
512
513 if (d3d12_dll == NULL)
514 return false;
515 }
516
517 PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
518 if (D3D12SerializeRootSignatureFn == NULL)
519 return false;
520
521 ID3DBlob* blob = NULL;
522 if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, NULL) != S_OK)
523 return false;
524
525 bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
526 blob->Release();
527 }
528
529 // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
530 // If you would like to use this DX12 sample code but remove this dependency you can:
531 // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
532 // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
533 // See https://github.com/ocornut/imgui/pull/638 for sources and details.
534
535 D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
536 memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
537 psoDesc.NodeMask = 1;
538 psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
539 psoDesc.pRootSignature = bd->pRootSignature;
540 psoDesc.SampleMask = UINT_MAX;
541 psoDesc.NumRenderTargets = 1;
542 psoDesc.RTVFormats[0] = bd->RTVFormat;
543 psoDesc.SampleDesc.Count = 1;
544 psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
545
546 ID3DBlob* vertexShaderBlob;
547 ID3DBlob* pixelShaderBlob;
548
549 // Create the vertex shader
550 {
551 static const char* vertexShader =
552 "cbuffer vertexBuffer : register(b0) \
553 {\
554 float4x4 ProjectionMatrix; \
555 };\
556 struct VS_INPUT\
557 {\
558 float2 pos : POSITION;\
559 float4 col : COLOR0;\
560 float2 uv : TEXCOORD0;\
561 };\
562 \
563 struct PS_INPUT\
564 {\
565 float4 pos : SV_POSITION;\
566 float4 col : COLOR0;\
567 float2 uv : TEXCOORD0;\
568 };\
569 \
570 PS_INPUT main(VS_INPUT input)\
571 {\
572 PS_INPUT output;\
573 output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
574 output.col = input.col;\
575 output.uv = input.uv;\
576 return output;\
577 }";
578
579 if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &vertexShaderBlob, NULL)))
580 return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
581 psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
582
583 // Create the input layout
584 static D3D12_INPUT_ELEMENT_DESC local_layout[] =
585 {
586 { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
587 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
588 { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
589 };
590 psoDesc.InputLayout = { local_layout, 3 };
591 }
592
593 // Create the pixel shader
594 {
595 static const char* pixelShader =
596 "struct PS_INPUT\
597 {\
598 float4 pos : SV_POSITION;\
599 float4 col : COLOR0;\
600 float2 uv : TEXCOORD0;\
601 };\
602 SamplerState sampler0 : register(s0);\
603 Texture2D texture0 : register(t0);\
604 \
605 float4 main(PS_INPUT input) : SV_Target\
606 {\
607 float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
608 return out_col; \
609 }";
610
611 if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &pixelShaderBlob, NULL)))
612 {
613 vertexShaderBlob->Release();
614 return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
615 }
616 psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
617 }
618
619 // Create the blending setup
620 {
621 D3D12_BLEND_DESC& desc = psoDesc.BlendState;
622 desc.AlphaToCoverageEnable = false;
623 desc.RenderTarget[0].BlendEnable = true;
624 desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
625 desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
626 desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
627 desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
628 desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
629 desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
630 desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
631 }
632
633 // Create the rasterizer state
634 {
635 D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
636 desc.FillMode = D3D12_FILL_MODE_SOLID;
637 desc.CullMode = D3D12_CULL_MODE_NONE;
638 desc.FrontCounterClockwise = FALSE;
639 desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
640 desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
641 desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
642 desc.DepthClipEnable = true;
643 desc.MultisampleEnable = FALSE;
644 desc.AntialiasedLineEnable = FALSE;
645 desc.ForcedSampleCount = 0;
646 desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
647 }
648
649 // Create depth-stencil State
650 {
651 D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
652 desc.DepthEnable = false;
653 desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
654 desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
655 desc.StencilEnable = false;
656 desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
657 desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
658 desc.BackFace = desc.FrontFace;
659 }
660
661 HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
662 vertexShaderBlob->Release();
663 pixelShaderBlob->Release();
664 if (result_pipeline_state != S_OK)
665 return false;
666
667 ImGui_ImplDX12_CreateFontsTexture();
668
669 return true;
670 }
671
ImGui_ImplDX12_InvalidateDeviceObjects()672 void ImGui_ImplDX12_InvalidateDeviceObjects()
673 {
674 ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
675 if (!bd || !bd->pd3dDevice)
676 return;
677 ImGuiIO& io = ImGui::GetIO();
678
679 SafeRelease(bd->pRootSignature);
680 SafeRelease(bd->pPipelineState);
681 SafeRelease(bd->pFontTextureResource);
682 io.Fonts->SetTexID(NULL); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
683
684 for (UINT i = 0; i < bd->numFramesInFlight; i++)
685 {
686 ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
687 SafeRelease(fr->IndexBuffer);
688 SafeRelease(fr->VertexBuffer);
689 }
690 }
691
ImGui_ImplDX12_Init(ID3D12Device * device,int num_frames_in_flight,DXGI_FORMAT rtv_format,ID3D12DescriptorHeap * cbv_srv_heap,D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle,D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)692 bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap,
693 D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
694 {
695 ImGuiIO& io = ImGui::GetIO();
696 IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!");
697
698 // Setup backend capabilities flags
699 ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
700 io.BackendRendererUserData = (void*)bd;
701 io.BackendRendererName = "imgui_impl_dx12";
702 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
703
704 bd->pd3dDevice = device;
705 bd->RTVFormat = rtv_format;
706 bd->hFontSrvCpuDescHandle = font_srv_cpu_desc_handle;
707 bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle;
708 bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[num_frames_in_flight];
709 bd->numFramesInFlight = num_frames_in_flight;
710 bd->frameIndex = UINT_MAX;
711 IM_UNUSED(cbv_srv_heap); // Unused in master branch (will be used by multi-viewports)
712
713 // Create buffers with a default size (they will later be grown as needed)
714 for (int i = 0; i < num_frames_in_flight; i++)
715 {
716 ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i];
717 fr->IndexBuffer = NULL;
718 fr->VertexBuffer = NULL;
719 fr->IndexBufferSize = 10000;
720 fr->VertexBufferSize = 5000;
721 }
722
723 return true;
724 }
725
ImGui_ImplDX12_Shutdown()726 void ImGui_ImplDX12_Shutdown()
727 {
728 ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
729 IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?");
730 ImGuiIO& io = ImGui::GetIO();
731
732 ImGui_ImplDX12_InvalidateDeviceObjects();
733 delete[] bd->pFrameResources;
734 io.BackendRendererName = NULL;
735 io.BackendRendererUserData = NULL;
736 IM_DELETE(bd);
737 }
738
ImGui_ImplDX12_NewFrame()739 void ImGui_ImplDX12_NewFrame()
740 {
741 ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
742 IM_ASSERT(bd != NULL && "Did you call ImGui_ImplDX12_Init()?");
743
744 if (!bd->pPipelineState)
745 ImGui_ImplDX12_CreateDeviceObjects();
746 }
747