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