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