imgui_impl_dx11.cpp 34 KB

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