1// dear imgui: Renderer Backend for DirectX11
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 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
6// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
7// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
8
9// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
10// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
11// Learn about Dear ImGui:
12// - FAQ https://dearimgui.com/faq
13// - Getting Started https://dearimgui.com/getting-started
14// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
15// - Introduction, links and more at the top of imgui.cpp
16
17// CHANGELOG
18// (minor and older changes stripped away, please see git history for details)
19// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
20// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
21// 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).
22// 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
23// 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer.
24// 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled).
25// 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore.
26// 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
27// 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
28// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
29// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
30// 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility.
31// 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions.
32// 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
33// 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
34// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
35// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
36// 2016-05-07: DirectX11: Disabling depth-write.
37
38#include "imgui.h"
39#ifndef IMGUI_DISABLE
40#include "imgui_impl_dx11.h"
41
42// DirectX
43#include <stdio.h>
44#include <d3d11.h>
45#include <d3dcompiler.h>
46#ifdef _MSC_VER
47#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
48#endif
49
50// DirectX11 data
51struct ImGui_ImplDX11_Data
52{
53 ID3D11Device* pd3dDevice;
54 ID3D11DeviceContext* pd3dDeviceContext;
55 IDXGIFactory* pFactory;
56 ID3D11Buffer* pVB;
57 ID3D11Buffer* pIB;
58 ID3D11VertexShader* pVertexShader;
59 ID3D11InputLayout* pInputLayout;
60 ID3D11Buffer* pVertexConstantBuffer;
61 ID3D11PixelShader* pPixelShader;
62 ID3D11SamplerState* pFontSampler;
63 ID3D11ShaderResourceView* pFontTextureView;
64 ID3D11RasterizerState* pRasterizerState;
65 ID3D11BlendState* pBlendState;
66 ID3D11DepthStencilState* pDepthStencilState;
67 int VertexBufferSize;
68 int IndexBufferSize;
69
70 ImGui_ImplDX11_Data() { memset(s: (void*)this, c: 0, n: sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
71};
72
73struct VERTEX_CONSTANT_BUFFER_DX11
74{
75 float mvp[4][4];
76};
77
78// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
79// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
80static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData()
81{
82 return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
83}
84
85// Forward Declarations
86static void ImGui_ImplDX11_InitPlatformInterface();
87static void ImGui_ImplDX11_ShutdownPlatformInterface();
88
89// Functions
90static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* ctx)
91{
92 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
93
94 // Setup viewport
95 D3D11_VIEWPORT vp;
96 memset(s: &vp, c: 0, n: sizeof(D3D11_VIEWPORT));
97 vp.Width = draw_data->DisplaySize.x;
98 vp.Height = draw_data->DisplaySize.y;
99 vp.MinDepth = 0.0f;
100 vp.MaxDepth = 1.0f;
101 vp.TopLeftX = vp.TopLeftY = 0;
102 ctx->RSSetViewports(1, &vp);
103
104 // Setup shader and vertex buffers
105 unsigned int stride = sizeof(ImDrawVert);
106 unsigned int offset = 0;
107 ctx->IASetInputLayout(bd->pInputLayout);
108 ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
109 ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
110 ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
111 ctx->VSSetShader(bd->pVertexShader, nullptr, 0);
112 ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
113 ctx->PSSetShader(bd->pPixelShader, nullptr, 0);
114 ctx->PSSetSamplers(0, 1, &bd->pFontSampler);
115 ctx->GSSetShader(nullptr, nullptr, 0);
116 ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
117 ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
118 ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
119
120 // Setup blend state
121 const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
122 ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
123 ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0);
124 ctx->RSSetState(bd->pRasterizerState);
125}
126
127// Render function
128void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
129{
130 // Avoid rendering when minimized
131 if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
132 return;
133
134 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
135 ID3D11DeviceContext* ctx = bd->pd3dDeviceContext;
136
137 // Create and grow vertex/index buffers if needed
138 if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
139 {
140 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
141 bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
142 D3D11_BUFFER_DESC desc;
143 memset(s: &desc, c: 0, n: sizeof(D3D11_BUFFER_DESC));
144 desc.Usage = D3D11_USAGE_DYNAMIC;
145 desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert);
146 desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
147 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
148 desc.MiscFlags = 0;
149 if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
150 return;
151 }
152 if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
153 {
154 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
155 bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
156 D3D11_BUFFER_DESC desc;
157 memset(s: &desc, c: 0, n: sizeof(D3D11_BUFFER_DESC));
158 desc.Usage = D3D11_USAGE_DYNAMIC;
159 desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
160 desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
161 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
162 if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
163 return;
164 }
165
166 // Upload vertex/index data into a single contiguous GPU buffer
167 D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
168 if (ctx->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
169 return;
170 if (ctx->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
171 return;
172 ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
173 ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
174 for (int n = 0; n < draw_data->CmdListsCount; n++)
175 {
176 const ImDrawList* cmd_list = draw_data->CmdLists[n];
177 memcpy(dest: vtx_dst, src: cmd_list->VtxBuffer.Data, n: cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
178 memcpy(dest: idx_dst, src: cmd_list->IdxBuffer.Data, n: cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
179 vtx_dst += cmd_list->VtxBuffer.Size;
180 idx_dst += cmd_list->IdxBuffer.Size;
181 }
182 ctx->Unmap(bd->pVB, 0);
183 ctx->Unmap(bd->pIB, 0);
184
185 // Setup orthographic projection matrix into our constant buffer
186 // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
187 {
188 D3D11_MAPPED_SUBRESOURCE mapped_resource;
189 if (ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
190 return;
191 VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData;
192 float L = draw_data->DisplayPos.x;
193 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
194 float T = draw_data->DisplayPos.y;
195 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
196 float mvp[4][4] =
197 {
198 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
199 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
200 { 0.0f, 0.0f, 0.5f, 0.0f },
201 { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
202 };
203 memcpy(dest: &constant_buffer->mvp, src: mvp, n: sizeof(mvp));
204 ctx->Unmap(bd->pVertexConstantBuffer, 0);
205 }
206
207 // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
208 struct BACKUP_DX11_STATE
209 {
210 UINT ScissorRectsCount, ViewportsCount;
211 D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
212 D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
213 ID3D11RasterizerState* RS;
214 ID3D11BlendState* BlendState;
215 FLOAT BlendFactor[4];
216 UINT SampleMask;
217 UINT StencilRef;
218 ID3D11DepthStencilState* DepthStencilState;
219 ID3D11ShaderResourceView* PSShaderResource;
220 ID3D11SamplerState* PSSampler;
221 ID3D11PixelShader* PS;
222 ID3D11VertexShader* VS;
223 ID3D11GeometryShader* GS;
224 UINT PSInstancesCount, VSInstancesCount, GSInstancesCount;
225 ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation
226 D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
227 ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
228 UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
229 DXGI_FORMAT IndexBufferFormat;
230 ID3D11InputLayout* InputLayout;
231 };
232 BACKUP_DX11_STATE old = {};
233 old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
234 ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
235 ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
236 ctx->RSGetState(&old.RS);
237 ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
238 ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
239 ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
240 ctx->PSGetSamplers(0, 1, &old.PSSampler);
241 old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256;
242 ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
243 ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
244 ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
245 ctx->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount);
246
247 ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
248 ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
249 ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
250 ctx->IAGetInputLayout(&old.InputLayout);
251
252 // Setup desired DX state
253 ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
254
255 // Render command lists
256 // (Because we merged all buffers into a single one, we maintain our own offset into them)
257 int global_idx_offset = 0;
258 int global_vtx_offset = 0;
259 ImVec2 clip_off = draw_data->DisplayPos;
260 for (int n = 0; n < draw_data->CmdListsCount; n++)
261 {
262 const ImDrawList* cmd_list = draw_data->CmdLists[n];
263 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
264 {
265 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
266 if (pcmd->UserCallback != nullptr)
267 {
268 // User callback, registered via ImDrawList::AddCallback()
269 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
270 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
271 ImGui_ImplDX11_SetupRenderState(draw_data, ctx);
272 else
273 pcmd->UserCallback(cmd_list, pcmd);
274 }
275 else
276 {
277 // Project scissor/clipping rectangles into framebuffer space
278 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
279 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
280 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
281 continue;
282
283 // Apply scissor/clipping rectangle
284 const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
285 ctx->RSSetScissorRects(1, &r);
286
287 // Bind texture, Draw
288 ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID();
289 ctx->PSSetShaderResources(0, 1, &texture_srv);
290 ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
291 }
292 }
293 global_idx_offset += cmd_list->IdxBuffer.Size;
294 global_vtx_offset += cmd_list->VtxBuffer.Size;
295 }
296
297 // Restore modified DX state
298 ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
299 ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
300 ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
301 ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
302 ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
303 ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
304 ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
305 ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
306 for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
307 ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
308 ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
309 ctx->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release();
310 for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
311 ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
312 ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
313 ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
314 ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
315}
316
317static void ImGui_ImplDX11_CreateFontsTexture()
318{
319 // Build texture atlas
320 ImGuiIO& io = ImGui::GetIO();
321 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
322 unsigned char* pixels;
323 int width, height;
324 io.Fonts->GetTexDataAsRGBA32(out_pixels: &pixels, out_width: &width, out_height: &height);
325
326 // Upload texture to graphics system
327 {
328 D3D11_TEXTURE2D_DESC desc;
329 ZeroMemory(&desc, sizeof(desc));
330 desc.Width = width;
331 desc.Height = height;
332 desc.MipLevels = 1;
333 desc.ArraySize = 1;
334 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
335 desc.SampleDesc.Count = 1;
336 desc.Usage = D3D11_USAGE_DEFAULT;
337 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
338 desc.CPUAccessFlags = 0;
339
340 ID3D11Texture2D* pTexture = nullptr;
341 D3D11_SUBRESOURCE_DATA subResource;
342 subResource.pSysMem = pixels;
343 subResource.SysMemPitch = desc.Width * 4;
344 subResource.SysMemSlicePitch = 0;
345 bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
346 IM_ASSERT(pTexture != nullptr);
347
348 // Create texture view
349 D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
350 ZeroMemory(&srvDesc, sizeof(srvDesc));
351 srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
352 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
353 srvDesc.Texture2D.MipLevels = desc.MipLevels;
354 srvDesc.Texture2D.MostDetailedMip = 0;
355 bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &bd->pFontTextureView);
356 pTexture->Release();
357 }
358
359 // Store our identifier
360 io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView);
361
362 // Create texture sampler
363 // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
364 {
365 D3D11_SAMPLER_DESC desc;
366 ZeroMemory(&desc, sizeof(desc));
367 desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
368 desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
369 desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
370 desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
371 desc.MipLODBias = 0.f;
372 desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
373 desc.MinLOD = 0.f;
374 desc.MaxLOD = 0.f;
375 bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
376 }
377}
378
379bool ImGui_ImplDX11_CreateDeviceObjects()
380{
381 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
382 if (!bd->pd3dDevice)
383 return false;
384 if (bd->pFontSampler)
385 ImGui_ImplDX11_InvalidateDeviceObjects();
386
387 // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
388 // If you would like to use this DX11 sample code but remove this dependency you can:
389 // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
390 // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
391 // See https://github.com/ocornut/imgui/pull/638 for sources and details.
392
393 // Create the vertex shader
394 {
395 static const char* vertexShader =
396 "cbuffer vertexBuffer : register(b0) \
397 {\
398 float4x4 ProjectionMatrix; \
399 };\
400 struct VS_INPUT\
401 {\
402 float2 pos : POSITION;\
403 float4 col : COLOR0;\
404 float2 uv : TEXCOORD0;\
405 };\
406 \
407 struct PS_INPUT\
408 {\
409 float4 pos : SV_POSITION;\
410 float4 col : COLOR0;\
411 float2 uv : TEXCOORD0;\
412 };\
413 \
414 PS_INPUT main(VS_INPUT input)\
415 {\
416 PS_INPUT output;\
417 output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
418 output.col = input.col;\
419 output.uv = input.uv;\
420 return output;\
421 }";
422
423 ID3DBlob* vertexShaderBlob;
424 if (FAILED(D3DCompile(vertexShader, strlen(s: vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
425 return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
426 if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK)
427 {
428 vertexShaderBlob->Release();
429 return false;
430 }
431
432 // Create the input layout
433 D3D11_INPUT_ELEMENT_DESC local_layout[] =
434 {
435 { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
436 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
437 { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
438 };
439 if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
440 {
441 vertexShaderBlob->Release();
442 return false;
443 }
444 vertexShaderBlob->Release();
445
446 // Create the constant buffer
447 {
448 D3D11_BUFFER_DESC desc;
449 desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11);
450 desc.Usage = D3D11_USAGE_DYNAMIC;
451 desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
452 desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
453 desc.MiscFlags = 0;
454 bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
455 }
456 }
457
458 // Create the pixel shader
459 {
460 static const char* pixelShader =
461 "struct PS_INPUT\
462 {\
463 float4 pos : SV_POSITION;\
464 float4 col : COLOR0;\
465 float2 uv : TEXCOORD0;\
466 };\
467 sampler sampler0;\
468 Texture2D texture0;\
469 \
470 float4 main(PS_INPUT input) : SV_Target\
471 {\
472 float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
473 return out_col; \
474 }";
475
476 ID3DBlob* pixelShaderBlob;
477 if (FAILED(D3DCompile(pixelShader, strlen(s: pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
478 return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
479 if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK)
480 {
481 pixelShaderBlob->Release();
482 return false;
483 }
484 pixelShaderBlob->Release();
485 }
486
487 // Create the blending setup
488 {
489 D3D11_BLEND_DESC desc;
490 ZeroMemory(&desc, sizeof(desc));
491 desc.AlphaToCoverageEnable = false;
492 desc.RenderTarget[0].BlendEnable = true;
493 desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
494 desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
495 desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
496 desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
497 desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
498 desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
499 desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
500 bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
501 }
502
503 // Create the rasterizer state
504 {
505 D3D11_RASTERIZER_DESC desc;
506 ZeroMemory(&desc, sizeof(desc));
507 desc.FillMode = D3D11_FILL_SOLID;
508 desc.CullMode = D3D11_CULL_NONE;
509 desc.ScissorEnable = true;
510 desc.DepthClipEnable = true;
511 bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
512 }
513
514 // Create depth-stencil State
515 {
516 D3D11_DEPTH_STENCIL_DESC desc;
517 ZeroMemory(&desc, sizeof(desc));
518 desc.DepthEnable = false;
519 desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
520 desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
521 desc.StencilEnable = false;
522 desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
523 desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
524 desc.BackFace = desc.FrontFace;
525 bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
526 }
527
528 ImGui_ImplDX11_CreateFontsTexture();
529
530 return true;
531}
532
533void ImGui_ImplDX11_InvalidateDeviceObjects()
534{
535 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
536 if (!bd->pd3dDevice)
537 return;
538
539 if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
540 if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well.
541 if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
542 if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
543 if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
544 if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
545 if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
546 if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
547 if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
548 if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
549 if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
550}
551
552bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
553{
554 ImGuiIO& io = ImGui::GetIO();
555 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
556
557 // Setup backend capabilities flags
558 ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)();
559 io.BackendRendererUserData = (void*)bd;
560 io.BackendRendererName = "imgui_impl_dx11";
561 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
562 io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
563
564 // Get factory from device
565 IDXGIDevice* pDXGIDevice = nullptr;
566 IDXGIAdapter* pDXGIAdapter = nullptr;
567 IDXGIFactory* pFactory = nullptr;
568
569 if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
570 if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
571 if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
572 {
573 bd->pd3dDevice = device;
574 bd->pd3dDeviceContext = device_context;
575 bd->pFactory = pFactory;
576 }
577 if (pDXGIDevice) pDXGIDevice->Release();
578 if (pDXGIAdapter) pDXGIAdapter->Release();
579 bd->pd3dDevice->AddRef();
580 bd->pd3dDeviceContext->AddRef();
581
582 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
583 ImGui_ImplDX11_InitPlatformInterface();
584
585 return true;
586}
587
588void ImGui_ImplDX11_Shutdown()
589{
590 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
591 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
592 ImGuiIO& io = ImGui::GetIO();
593
594 ImGui_ImplDX11_ShutdownPlatformInterface();
595 ImGui_ImplDX11_InvalidateDeviceObjects();
596 if (bd->pFactory) { bd->pFactory->Release(); }
597 if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
598 if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); }
599 io.BackendRendererName = nullptr;
600 io.BackendRendererUserData = nullptr;
601 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
602 IM_DELETE(p: bd);
603}
604
605void ImGui_ImplDX11_NewFrame()
606{
607 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
608 IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX11_Init()?");
609
610 if (!bd->pFontSampler)
611 ImGui_ImplDX11_CreateDeviceObjects();
612}
613
614//--------------------------------------------------------------------------------------------------------
615// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
616// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
617// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
618//--------------------------------------------------------------------------------------------------------
619
620// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
621struct ImGui_ImplDX11_ViewportData
622{
623 IDXGISwapChain* SwapChain;
624 ID3D11RenderTargetView* RTView;
625
626 ImGui_ImplDX11_ViewportData() { SwapChain = nullptr; RTView = nullptr; }
627 ~ImGui_ImplDX11_ViewportData() { IM_ASSERT(SwapChain == nullptr && RTView == nullptr); }
628};
629
630static void ImGui_ImplDX11_CreateWindow(ImGuiViewport* viewport)
631{
632 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
633 ImGui_ImplDX11_ViewportData* vd = IM_NEW(ImGui_ImplDX11_ViewportData)();
634 viewport->RendererUserData = vd;
635
636 // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
637 // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
638 HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
639 IM_ASSERT(hwnd != 0);
640
641 // Create swap chain
642 DXGI_SWAP_CHAIN_DESC sd;
643 ZeroMemory(&sd, sizeof(sd));
644 sd.BufferDesc.Width = (UINT)viewport->Size.x;
645 sd.BufferDesc.Height = (UINT)viewport->Size.y;
646 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
647 sd.SampleDesc.Count = 1;
648 sd.SampleDesc.Quality = 0;
649 sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
650 sd.BufferCount = 1;
651 sd.OutputWindow = hwnd;
652 sd.Windowed = TRUE;
653 sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
654 sd.Flags = 0;
655
656 IM_ASSERT(vd->SwapChain == nullptr && vd->RTView == nullptr);
657 bd->pFactory->CreateSwapChain(bd->pd3dDevice, &sd, &vd->SwapChain);
658
659 // Create the render target
660 if (vd->SwapChain)
661 {
662 ID3D11Texture2D* pBackBuffer;
663 vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
664 bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
665 pBackBuffer->Release();
666 }
667}
668
669static void ImGui_ImplDX11_DestroyWindow(ImGuiViewport* viewport)
670{
671 // The main viewport (owned by the application) will always have RendererUserData == nullptr since we didn't create the data for it.
672 if (ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData)
673 {
674 if (vd->SwapChain)
675 vd->SwapChain->Release();
676 vd->SwapChain = nullptr;
677 if (vd->RTView)
678 vd->RTView->Release();
679 vd->RTView = nullptr;
680 IM_DELETE(p: vd);
681 }
682 viewport->RendererUserData = nullptr;
683}
684
685static void ImGui_ImplDX11_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
686{
687 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
688 ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
689 if (vd->RTView)
690 {
691 vd->RTView->Release();
692 vd->RTView = nullptr;
693 }
694 if (vd->SwapChain)
695 {
696 ID3D11Texture2D* pBackBuffer = nullptr;
697 vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
698 vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
699 if (pBackBuffer == nullptr) { fprintf(stderr, format: "ImGui_ImplDX11_SetWindowSize() failed creating buffers.\n"); return; }
700 bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
701 pBackBuffer->Release();
702 }
703}
704
705static void ImGui_ImplDX11_RenderWindow(ImGuiViewport* viewport, void*)
706{
707 ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
708 ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
709 ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
710 bd->pd3dDeviceContext->OMSetRenderTargets(1, &vd->RTView, nullptr);
711 if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
712 bd->pd3dDeviceContext->ClearRenderTargetView(vd->RTView, (float*)&clear_color);
713 ImGui_ImplDX11_RenderDrawData(draw_data: viewport->DrawData);
714}
715
716static void ImGui_ImplDX11_SwapBuffers(ImGuiViewport* viewport, void*)
717{
718 ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
719 vd->SwapChain->Present(0, 0); // Present without vsync
720}
721
722static void ImGui_ImplDX11_InitPlatformInterface()
723{
724 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
725 platform_io.Renderer_CreateWindow = ImGui_ImplDX11_CreateWindow;
726 platform_io.Renderer_DestroyWindow = ImGui_ImplDX11_DestroyWindow;
727 platform_io.Renderer_SetWindowSize = ImGui_ImplDX11_SetWindowSize;
728 platform_io.Renderer_RenderWindow = ImGui_ImplDX11_RenderWindow;
729 platform_io.Renderer_SwapBuffers = ImGui_ImplDX11_SwapBuffers;
730}
731
732static void ImGui_ImplDX11_ShutdownPlatformInterface()
733{
734 ImGui::DestroyPlatformWindows();
735}
736
737//-----------------------------------------------------------------------------
738
739#endif // #ifndef IMGUI_DISABLE
740

source code of imgui/backends/imgui_impl_dx11.cpp