imgui_impl_dx11.cpp 41 KB

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