imgui_impl_dx11.cpp 31 KB

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