imgui_impl_dx11.cpp 24 KB

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