1 // dear imgui: Renderer for DirectX11
2 // This needs to be used along with a Platform Binding (e.g. Win32)
3 
4 // Implemented features:
5 //  [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp.
6 
7 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
8 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp
9 // https://github.com/ocornut/imgui
10 
11 // CHANGELOG
12 // (minor and older changes stripped away, please see git history for details)
13 //  2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
14 //  2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
15 //  2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility.
16 //  2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions.
17 //  2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
18 //  2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
19 //  2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
20 //  2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
21 //  2016-05-07: DirectX11: Disabling depth-write.
22 
23 #include "imgui.h"
24 #include "imgui_impl_dx11.h"
25 
26 // DirectX
27 #include <stdio.h>
28 #include <d3d11.h>
29 #include <d3dcompiler.h>
30 #ifdef _MSC_VER
31 #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
32 #endif
33 
34 // DirectX data
35 static ID3D11Device*            g_pd3dDevice = NULL;
36 static ID3D11DeviceContext*     g_pd3dDeviceContext = NULL;
37 static IDXGIFactory*            g_pFactory = NULL;
38 static ID3D11Buffer*            g_pVB = NULL;
39 static ID3D11Buffer*            g_pIB = NULL;
40 static ID3D10Blob*              g_pVertexShaderBlob = NULL;
41 static ID3D11VertexShader*      g_pVertexShader = NULL;
42 static ID3D11InputLayout*       g_pInputLayout = NULL;
43 static ID3D11Buffer*            g_pVertexConstantBuffer = NULL;
44 static ID3D10Blob*              g_pPixelShaderBlob = NULL;
45 static ID3D11PixelShader*       g_pPixelShader = NULL;
46 static ID3D11SamplerState*      g_pFontSampler = NULL;
47 static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
48 static ID3D11RasterizerState*   g_pRasterizerState = NULL;
49 static ID3D11BlendState*        g_pBlendState = NULL;
50 static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
51 static int                      g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
52 
53 struct VERTEX_CONSTANT_BUFFER
54 {
55     float   mvp[4][4];
56 };
57 
58 // Render function
59 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
ImGui_ImplDX11_RenderDrawData(ImDrawData * draw_data)60 void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
61 {
62     ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
63 
64     // Create and grow vertex/index buffers if needed
65     if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
66     {
67         if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
68         g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
69         D3D11_BUFFER_DESC desc;
70         memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
71         desc.Usage = D3D11_USAGE_DYNAMIC;
72         desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
73         desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
74         desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
75         desc.MiscFlags = 0;
76         if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
77             return;
78     }
79     if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
80     {
81         if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
82         g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
83         D3D11_BUFFER_DESC desc;
84         memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
85         desc.Usage = D3D11_USAGE_DYNAMIC;
86         desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
87         desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
88         desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
89         if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
90             return;
91     }
92 
93     // Copy and convert all vertices into a single contiguous buffer
94     D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
95     if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
96         return;
97     if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
98         return;
99     ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
100     ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
101     for (int n = 0; n < draw_data->CmdListsCount; n++)
102     {
103         const ImDrawList* cmd_list = draw_data->CmdLists[n];
104         memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
105         memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
106         vtx_dst += cmd_list->VtxBuffer.Size;
107         idx_dst += cmd_list->IdxBuffer.Size;
108     }
109     ctx->Unmap(g_pVB, 0);
110     ctx->Unmap(g_pIB, 0);
111 
112     // Setup orthographic projection matrix into our constant buffer
113     // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
114     {
115         D3D11_MAPPED_SUBRESOURCE mapped_resource;
116         if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
117             return;
118         VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
119         float L = draw_data->DisplayPos.x;
120         float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
121         float T = draw_data->DisplayPos.y;
122         float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
123         float mvp[4][4] =
124         {
125             { 2.0f/(R-L),   0.0f,           0.0f,       0.0f },
126             { 0.0f,         2.0f/(T-B),     0.0f,       0.0f },
127             { 0.0f,         0.0f,           0.5f,       0.0f },
128             { (R+L)/(L-R),  (T+B)/(B-T),    0.5f,       1.0f },
129         };
130         memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
131         ctx->Unmap(g_pVertexConstantBuffer, 0);
132     }
133 
134     // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
135     struct BACKUP_DX11_STATE
136     {
137         UINT                        ScissorRectsCount, ViewportsCount;
138         D3D11_RECT                  ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
139         D3D11_VIEWPORT              Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
140         ID3D11RasterizerState*      RS;
141         ID3D11BlendState*           BlendState;
142         FLOAT                       BlendFactor[4];
143         UINT                        SampleMask;
144         UINT                        StencilRef;
145         ID3D11DepthStencilState*    DepthStencilState;
146         ID3D11ShaderResourceView*   PSShaderResource;
147         ID3D11SamplerState*         PSSampler;
148         ID3D11PixelShader*          PS;
149         ID3D11VertexShader*         VS;
150         UINT                        PSInstancesCount, VSInstancesCount;
151         ID3D11ClassInstance*        PSInstances[256], *VSInstances[256];   // 256 is max according to PSSetShader documentation
152         D3D11_PRIMITIVE_TOPOLOGY    PrimitiveTopology;
153         ID3D11Buffer*               IndexBuffer, *VertexBuffer, *VSConstantBuffer;
154         UINT                        IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
155         DXGI_FORMAT                 IndexBufferFormat;
156         ID3D11InputLayout*          InputLayout;
157     };
158     BACKUP_DX11_STATE old;
159     old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
160     ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
161     ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
162     ctx->RSGetState(&old.RS);
163     ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
164     ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
165     ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
166     ctx->PSGetSamplers(0, 1, &old.PSSampler);
167     old.PSInstancesCount = old.VSInstancesCount = 256;
168     ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
169     ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
170     ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
171     ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
172     ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
173     ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
174     ctx->IAGetInputLayout(&old.InputLayout);
175 
176     // Setup viewport
177     D3D11_VIEWPORT vp;
178     memset(&vp, 0, sizeof(D3D11_VIEWPORT));
179     vp.Width =  draw_data->DisplaySize.x;
180     vp.Height = draw_data->DisplaySize.y;
181     vp.MinDepth = 0.0f;
182     vp.MaxDepth = 1.0f;
183     vp.TopLeftX = vp.TopLeftY = 0;
184     ctx->RSSetViewports(1, &vp);
185 
186     // Bind shader and vertex buffers
187     unsigned int stride = sizeof(ImDrawVert);
188     unsigned int offset = 0;
189     ctx->IASetInputLayout(g_pInputLayout);
190     ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
191     ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
192     ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
193     ctx->VSSetShader(g_pVertexShader, NULL, 0);
194     ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
195     ctx->PSSetShader(g_pPixelShader, NULL, 0);
196     ctx->PSSetSamplers(0, 1, &g_pFontSampler);
197 
198     // Setup render state
199     const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
200     ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
201     ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
202     ctx->RSSetState(g_pRasterizerState);
203 
204     // Render command lists
205     int vtx_offset = 0;
206     int idx_offset = 0;
207     ImVec2 pos = draw_data->DisplayPos;
208     for (int n = 0; n < draw_data->CmdListsCount; n++)
209     {
210         const ImDrawList* cmd_list = draw_data->CmdLists[n];
211         for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
212         {
213             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
214             if (pcmd->UserCallback)
215             {
216                 // User callback (registered via ImDrawList::AddCallback)
217                 pcmd->UserCallback(cmd_list, pcmd);
218             }
219             else
220             {
221                 // Apply scissor/clipping rectangle
222                 const D3D11_RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) };
223                 ctx->RSSetScissorRects(1, &r);
224 
225                 // Bind texture, Draw
226                 ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->TextureId;
227                 ctx->PSSetShaderResources(0, 1, &texture_srv);
228                 ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
229             }
230             idx_offset += pcmd->ElemCount;
231         }
232         vtx_offset += cmd_list->VtxBuffer.Size;
233     }
234 
235     // Restore modified DX state
236     ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
237     ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
238     ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
239     ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
240     ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
241     ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
242     ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
243     ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
244     for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
245     ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
246     ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
247     for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
248     ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
249     ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
250     ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
251     ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
252 }
253 
ImGui_ImplDX11_CreateFontsTexture()254 static void ImGui_ImplDX11_CreateFontsTexture()
255 {
256     // Build texture atlas
257     ImGuiIO& io = ImGui::GetIO();
258     unsigned char* pixels;
259     int width, height;
260     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
261 
262     // Upload texture to graphics system
263     {
264         D3D11_TEXTURE2D_DESC desc;
265         ZeroMemory(&desc, sizeof(desc));
266         desc.Width = width;
267         desc.Height = height;
268         desc.MipLevels = 1;
269         desc.ArraySize = 1;
270         desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
271         desc.SampleDesc.Count = 1;
272         desc.Usage = D3D11_USAGE_DEFAULT;
273         desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
274         desc.CPUAccessFlags = 0;
275 
276         ID3D11Texture2D *pTexture = NULL;
277         D3D11_SUBRESOURCE_DATA subResource;
278         subResource.pSysMem = pixels;
279         subResource.SysMemPitch = desc.Width * 4;
280         subResource.SysMemSlicePitch = 0;
281         g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
282 
283         // Create texture view
284         D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
285         ZeroMemory(&srvDesc, sizeof(srvDesc));
286         srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
287         srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
288         srvDesc.Texture2D.MipLevels = desc.MipLevels;
289         srvDesc.Texture2D.MostDetailedMip = 0;
290         g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
291         pTexture->Release();
292     }
293 
294     // Store our identifier
295     io.Fonts->TexID = (ImTextureID)g_pFontTextureView;
296 
297     // Create texture sampler
298     {
299         D3D11_SAMPLER_DESC desc;
300         ZeroMemory(&desc, sizeof(desc));
301         desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
302         desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
303         desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
304         desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
305         desc.MipLODBias = 0.f;
306         desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
307         desc.MinLOD = 0.f;
308         desc.MaxLOD = 0.f;
309         g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
310     }
311 }
312 
ImGui_ImplDX11_CreateDeviceObjects()313 bool    ImGui_ImplDX11_CreateDeviceObjects()
314 {
315     if (!g_pd3dDevice)
316         return false;
317     if (g_pFontSampler)
318         ImGui_ImplDX11_InvalidateDeviceObjects();
319 
320     // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
321     // If you would like to use this DX11 sample code but remove this dependency you can:
322     //  1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
323     //  2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
324     // See https://github.com/ocornut/imgui/pull/638 for sources and details.
325 
326     // Create the vertex shader
327     {
328         static const char* vertexShader =
329             "cbuffer vertexBuffer : register(b0) \
330             {\
331             float4x4 ProjectionMatrix; \
332             };\
333             struct VS_INPUT\
334             {\
335             float2 pos : POSITION;\
336             float4 col : COLOR0;\
337             float2 uv  : TEXCOORD0;\
338             };\
339             \
340             struct PS_INPUT\
341             {\
342             float4 pos : SV_POSITION;\
343             float4 col : COLOR0;\
344             float2 uv  : TEXCOORD0;\
345             };\
346             \
347             PS_INPUT main(VS_INPUT input)\
348             {\
349             PS_INPUT output;\
350             output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
351             output.col = input.col;\
352             output.uv  = input.uv;\
353             return output;\
354             }";
355 
356         D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
357         if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
358             return false;
359         if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
360             return false;
361 
362         // Create the input layout
363         D3D11_INPUT_ELEMENT_DESC local_layout[] =
364         {
365             { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT,   0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
366             { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,   0, (size_t)(&((ImDrawVert*)0)->uv),  D3D11_INPUT_PER_VERTEX_DATA, 0 },
367             { "COLOR",    0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
368         };
369         if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
370             return false;
371 
372         // Create the constant buffer
373         {
374             D3D11_BUFFER_DESC desc;
375             desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
376             desc.Usage = D3D11_USAGE_DYNAMIC;
377             desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
378             desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
379             desc.MiscFlags = 0;
380             g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
381         }
382     }
383 
384     // Create the pixel shader
385     {
386         static const char* pixelShader =
387             "struct PS_INPUT\
388             {\
389             float4 pos : SV_POSITION;\
390             float4 col : COLOR0;\
391             float2 uv  : TEXCOORD0;\
392             };\
393             sampler sampler0;\
394             Texture2D texture0;\
395             \
396             float4 main(PS_INPUT input) : SV_Target\
397             {\
398             float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
399             return out_col; \
400             }";
401 
402         D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
403         if (g_pPixelShaderBlob == NULL)  // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
404             return false;
405         if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
406             return false;
407     }
408 
409     // Create the blending setup
410     {
411         D3D11_BLEND_DESC desc;
412         ZeroMemory(&desc, sizeof(desc));
413         desc.AlphaToCoverageEnable = false;
414         desc.RenderTarget[0].BlendEnable = true;
415         desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
416         desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
417         desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
418         desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
419         desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
420         desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
421         desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
422         g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
423     }
424 
425     // Create the rasterizer state
426     {
427         D3D11_RASTERIZER_DESC desc;
428         ZeroMemory(&desc, sizeof(desc));
429         desc.FillMode = D3D11_FILL_SOLID;
430         desc.CullMode = D3D11_CULL_NONE;
431         desc.ScissorEnable = true;
432         desc.DepthClipEnable = true;
433         g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
434     }
435 
436     // Create depth-stencil State
437     {
438         D3D11_DEPTH_STENCIL_DESC desc;
439         ZeroMemory(&desc, sizeof(desc));
440         desc.DepthEnable = false;
441         desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
442         desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
443         desc.StencilEnable = false;
444         desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
445         desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
446         desc.BackFace = desc.FrontFace;
447         g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
448     }
449 
450     ImGui_ImplDX11_CreateFontsTexture();
451 
452     return true;
453 }
454 
ImGui_ImplDX11_InvalidateDeviceObjects()455 void    ImGui_ImplDX11_InvalidateDeviceObjects()
456 {
457     if (!g_pd3dDevice)
458         return;
459 
460     if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
461     if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
462     if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
463     if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
464 
465     if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
466     if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
467     if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
468     if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
469     if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
470     if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
471     if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
472     if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
473     if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
474 }
475 
ImGui_ImplDX11_Init(ID3D11Device * device,ID3D11DeviceContext * device_context)476 bool    ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
477 {
478     ImGuiIO& io = ImGui::GetIO();
479     io.BackendRendererName = "imgui_impl_dx11";
480 
481     // Get factory from device
482     IDXGIDevice* pDXGIDevice = NULL;
483     IDXGIAdapter* pDXGIAdapter = NULL;
484     IDXGIFactory* pFactory = NULL;
485 
486     if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
487         if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
488             if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
489             {
490                 g_pd3dDevice = device;
491                 g_pd3dDeviceContext = device_context;
492                 g_pFactory = pFactory;
493             }
494     if (pDXGIDevice) pDXGIDevice->Release();
495     if (pDXGIAdapter) pDXGIAdapter->Release();
496 
497     return true;
498 }
499 
ImGui_ImplDX11_Shutdown()500 void ImGui_ImplDX11_Shutdown()
501 {
502     ImGui_ImplDX11_InvalidateDeviceObjects();
503     if (g_pFactory) { g_pFactory->Release(); g_pFactory = NULL; }
504     g_pd3dDevice = NULL;
505     g_pd3dDeviceContext = NULL;
506 }
507 
ImGui_ImplDX11_NewFrame()508 void ImGui_ImplDX11_NewFrame()
509 {
510     if (!g_pFontSampler)
511         ImGui_ImplDX11_CreateDeviceObjects();
512 }
513