imgui_impl_dx11.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. // ImGui Renderer for: DirectX11
  2. // This needs to be used along with a Platform Binding (e.g. Win32)
  3. // Implemented features:
  4. // [X] 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 use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  7. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  8. // https://github.com/ocornut/imgui
  9. // CHANGELOG
  10. // (minor and older changes stripped away, please see git history for details)
  11. // 2018-XX-XX: Platform: Added support for multiple windows via the ImGuiRendererInterface.
  12. // 2018-XX-XX: DirectX11: Offset projection matrix and clipping rectangle by draw_data->DisplayPos (which will be non-zero for multi-viewport applications).
  13. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
  14. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  15. // 2016-05-07: DirectX11: Disabling depth-write.
  16. #include "imgui.h"
  17. #include "imgui_impl_dx11.h"
  18. // DirectX
  19. #include <d3d11.h>
  20. #include <d3dcompiler.h>
  21. // DirectX data
  22. static ID3D11Device* g_pd3dDevice = NULL;
  23. static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
  24. static IDXGIFactory1* g_pFactory = NULL;
  25. static ID3D11Buffer* g_pVB = NULL;
  26. static ID3D11Buffer* g_pIB = NULL;
  27. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  28. static ID3D11VertexShader* g_pVertexShader = NULL;
  29. static ID3D11InputLayout* g_pInputLayout = NULL;
  30. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  31. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  32. static ID3D11PixelShader* g_pPixelShader = NULL;
  33. static ID3D11SamplerState* g_pFontSampler = NULL;
  34. static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
  35. static ID3D11RasterizerState* g_pRasterizerState = NULL;
  36. static ID3D11BlendState* g_pBlendState = NULL;
  37. static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
  38. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  39. struct VERTEX_CONSTANT_BUFFER
  40. {
  41. float mvp[4][4];
  42. };
  43. // Forward Declarations
  44. static void ImGui_ImplDX11_InitPlatformInterface();
  45. static void ImGui_ImplDX11_ShutdownPlatformInterface();
  46. // Render function
  47. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
  48. void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
  49. {
  50. ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
  51. // Create and grow vertex/index buffers if needed
  52. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  53. {
  54. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  55. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  56. D3D11_BUFFER_DESC desc;
  57. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  58. desc.Usage = D3D11_USAGE_DYNAMIC;
  59. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  60. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  61. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  62. desc.MiscFlags = 0;
  63. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  64. return;
  65. }
  66. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  67. {
  68. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  69. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  70. D3D11_BUFFER_DESC desc;
  71. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  72. desc.Usage = D3D11_USAGE_DYNAMIC;
  73. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  74. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  75. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  76. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  77. return;
  78. }
  79. // Copy and convert all vertices into a single contiguous buffer
  80. D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
  81. if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
  82. return;
  83. if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
  84. return;
  85. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
  86. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
  87. for (int n = 0; n < draw_data->CmdListsCount; n++)
  88. {
  89. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  90. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  91. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  92. vtx_dst += cmd_list->VtxBuffer.Size;
  93. idx_dst += cmd_list->IdxBuffer.Size;
  94. }
  95. ctx->Unmap(g_pVB, 0);
  96. ctx->Unmap(g_pIB, 0);
  97. // Setup orthographic projection matrix into our constant buffer
  98. // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
  99. {
  100. D3D11_MAPPED_SUBRESOURCE mapped_resource;
  101. if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  102. return;
  103. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
  104. float L = draw_data->DisplayPos.x;
  105. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  106. float T = draw_data->DisplayPos.y;
  107. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  108. float mvp[4][4] =
  109. {
  110. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  111. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  112. { 0.0f, 0.0f, 0.5f, 0.0f },
  113. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  114. };
  115. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  116. ctx->Unmap(g_pVertexConstantBuffer, 0);
  117. }
  118. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  119. struct BACKUP_DX11_STATE
  120. {
  121. UINT ScissorRectsCount, ViewportsCount;
  122. D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  123. D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  124. ID3D11RasterizerState* RS;
  125. ID3D11BlendState* BlendState;
  126. FLOAT BlendFactor[4];
  127. UINT SampleMask;
  128. UINT StencilRef;
  129. ID3D11DepthStencilState* DepthStencilState;
  130. ID3D11ShaderResourceView* PSShaderResource;
  131. ID3D11SamplerState* PSSampler;
  132. ID3D11PixelShader* PS;
  133. ID3D11VertexShader* VS;
  134. UINT PSInstancesCount, VSInstancesCount;
  135. ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
  136. D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  137. ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  138. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  139. DXGI_FORMAT IndexBufferFormat;
  140. ID3D11InputLayout* InputLayout;
  141. };
  142. BACKUP_DX11_STATE old;
  143. old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  144. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  145. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  146. ctx->RSGetState(&old.RS);
  147. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  148. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  149. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  150. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  151. old.PSInstancesCount = old.VSInstancesCount = 256;
  152. ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
  153. ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
  154. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  155. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  156. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  157. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  158. ctx->IAGetInputLayout(&old.InputLayout);
  159. // Setup viewport
  160. D3D11_VIEWPORT vp;
  161. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  162. vp.Width = draw_data->DisplaySize.x;
  163. vp.Height = draw_data->DisplaySize.y;
  164. vp.MinDepth = 0.0f;
  165. vp.MaxDepth = 1.0f;
  166. vp.TopLeftX = vp.TopLeftY = 0;
  167. ctx->RSSetViewports(1, &vp);
  168. // Bind shader and vertex buffers
  169. unsigned int stride = sizeof(ImDrawVert);
  170. unsigned int offset = 0;
  171. ctx->IASetInputLayout(g_pInputLayout);
  172. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  173. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  174. ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  175. ctx->VSSetShader(g_pVertexShader, NULL, 0);
  176. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  177. ctx->PSSetShader(g_pPixelShader, NULL, 0);
  178. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  179. // Setup render state
  180. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  181. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  182. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  183. ctx->RSSetState(g_pRasterizerState);
  184. // Render command lists
  185. int vtx_offset = 0;
  186. int idx_offset = 0;
  187. ImVec2 display_pos = draw_data->DisplayPos;
  188. for (int n = 0; n < draw_data->CmdListsCount; n++)
  189. {
  190. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  191. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  192. {
  193. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  194. if (pcmd->UserCallback)
  195. {
  196. // User callback (registered via ImDrawList::AddCallback)
  197. pcmd->UserCallback(cmd_list, pcmd);
  198. }
  199. else
  200. {
  201. // Apply scissor/clipping rectangle
  202. const ImVec4 clip_rect = ImVec4(pcmd->ClipRect.x - display_pos.x, pcmd->ClipRect.y - display_pos.y, pcmd->ClipRect.z - display_pos.x, pcmd->ClipRect.w - display_pos.y);
  203. const D3D11_RECT clip_rect_dx = { (LONG)clip_rect.x, (LONG)clip_rect.y, (LONG)clip_rect.z, (LONG)clip_rect.w };
  204. ctx->RSSetScissorRects(1, &clip_rect_dx);
  205. // Bind texture, Draw
  206. ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
  207. ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  208. }
  209. idx_offset += pcmd->ElemCount;
  210. }
  211. vtx_offset += cmd_list->VtxBuffer.Size;
  212. }
  213. // Restore modified DX state
  214. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  215. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  216. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  217. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  218. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  219. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  220. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  221. ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
  222. for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
  223. ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
  224. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  225. for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
  226. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  227. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  228. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  229. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  230. }
  231. static void ImGui_ImplDX11_CreateFontsTexture()
  232. {
  233. // Build texture atlas
  234. ImGuiIO& io = ImGui::GetIO();
  235. unsigned char* pixels;
  236. int width, height;
  237. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  238. // Upload texture to graphics system
  239. {
  240. D3D11_TEXTURE2D_DESC desc;
  241. ZeroMemory(&desc, sizeof(desc));
  242. desc.Width = width;
  243. desc.Height = height;
  244. desc.MipLevels = 1;
  245. desc.ArraySize = 1;
  246. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  247. desc.SampleDesc.Count = 1;
  248. desc.Usage = D3D11_USAGE_DEFAULT;
  249. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  250. desc.CPUAccessFlags = 0;
  251. ID3D11Texture2D *pTexture = NULL;
  252. D3D11_SUBRESOURCE_DATA subResource;
  253. subResource.pSysMem = pixels;
  254. subResource.SysMemPitch = desc.Width * 4;
  255. subResource.SysMemSlicePitch = 0;
  256. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  257. // Create texture view
  258. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  259. ZeroMemory(&srvDesc, sizeof(srvDesc));
  260. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  261. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  262. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  263. srvDesc.Texture2D.MostDetailedMip = 0;
  264. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
  265. pTexture->Release();
  266. }
  267. // Store our identifier
  268. io.Fonts->TexID = (void *)g_pFontTextureView;
  269. // Create texture sampler
  270. {
  271. D3D11_SAMPLER_DESC desc;
  272. ZeroMemory(&desc, sizeof(desc));
  273. desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  274. desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  275. desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  276. desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  277. desc.MipLODBias = 0.f;
  278. desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  279. desc.MinLOD = 0.f;
  280. desc.MaxLOD = 0.f;
  281. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  282. }
  283. }
  284. bool ImGui_ImplDX11_CreateDeviceObjects()
  285. {
  286. if (!g_pd3dDevice)
  287. return false;
  288. if (g_pFontSampler)
  289. ImGui_ImplDX11_InvalidateDeviceObjects();
  290. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  291. // If you would like to use this DX11 sample code but remove this dependency you can:
  292. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  293. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  294. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  295. // Create the vertex shader
  296. {
  297. static const char* vertexShader =
  298. "cbuffer vertexBuffer : register(b0) \
  299. {\
  300. float4x4 ProjectionMatrix; \
  301. };\
  302. struct VS_INPUT\
  303. {\
  304. float2 pos : POSITION;\
  305. float4 col : COLOR0;\
  306. float2 uv : TEXCOORD0;\
  307. };\
  308. \
  309. struct PS_INPUT\
  310. {\
  311. float4 pos : SV_POSITION;\
  312. float4 col : COLOR0;\
  313. float2 uv : TEXCOORD0;\
  314. };\
  315. \
  316. PS_INPUT main(VS_INPUT input)\
  317. {\
  318. PS_INPUT output;\
  319. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  320. output.col = input.col;\
  321. output.uv = input.uv;\
  322. return output;\
  323. }";
  324. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  325. 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!
  326. return false;
  327. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  328. return false;
  329. // Create the input layout
  330. D3D11_INPUT_ELEMENT_DESC local_layout[] =
  331. {
  332. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  333. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  334. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  335. };
  336. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  337. return false;
  338. // Create the constant buffer
  339. {
  340. D3D11_BUFFER_DESC desc;
  341. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  342. desc.Usage = D3D11_USAGE_DYNAMIC;
  343. desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  344. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  345. desc.MiscFlags = 0;
  346. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  347. }
  348. }
  349. // Create the pixel shader
  350. {
  351. static const char* pixelShader =
  352. "struct PS_INPUT\
  353. {\
  354. float4 pos : SV_POSITION;\
  355. float4 col : COLOR0;\
  356. float2 uv : TEXCOORD0;\
  357. };\
  358. sampler sampler0;\
  359. Texture2D texture0;\
  360. \
  361. float4 main(PS_INPUT input) : SV_Target\
  362. {\
  363. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  364. return out_col; \
  365. }";
  366. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  367. 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!
  368. return false;
  369. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  370. return false;
  371. }
  372. // Create the blending setup
  373. {
  374. D3D11_BLEND_DESC desc;
  375. ZeroMemory(&desc, sizeof(desc));
  376. desc.AlphaToCoverageEnable = false;
  377. desc.RenderTarget[0].BlendEnable = true;
  378. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  379. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  380. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  381. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  382. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  383. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  384. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  385. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  386. }
  387. // Create the rasterizer state
  388. {
  389. D3D11_RASTERIZER_DESC desc;
  390. ZeroMemory(&desc, sizeof(desc));
  391. desc.FillMode = D3D11_FILL_SOLID;
  392. desc.CullMode = D3D11_CULL_NONE;
  393. desc.ScissorEnable = true;
  394. desc.DepthClipEnable = true;
  395. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  396. }
  397. // Create depth-stencil State
  398. {
  399. D3D11_DEPTH_STENCIL_DESC desc;
  400. ZeroMemory(&desc, sizeof(desc));
  401. desc.DepthEnable = false;
  402. desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
  403. desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
  404. desc.StencilEnable = false;
  405. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  406. desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  407. desc.BackFace = desc.FrontFace;
  408. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  409. }
  410. ImGui_ImplDX11_CreateFontsTexture();
  411. return true;
  412. }
  413. void ImGui_ImplDX11_InvalidateDeviceObjects()
  414. {
  415. if (!g_pd3dDevice)
  416. return;
  417. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  418. 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.
  419. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  420. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  421. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  422. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  423. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  424. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  425. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  426. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  427. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  428. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  429. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  430. }
  431. bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
  432. {
  433. // Get factory from device
  434. IDXGIDevice* pDXGIDevice = NULL;
  435. IDXGIAdapter* pDXGIAdapter = NULL;
  436. IDXGIFactory1* pFactory = NULL;
  437. if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) != S_OK)
  438. return false;
  439. if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) != S_OK)
  440. return false;
  441. if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) != S_OK)
  442. return false;
  443. ImGuiIO& io = ImGui::GetIO();
  444. g_pd3dDevice = device;
  445. g_pd3dDeviceContext = device_context;
  446. g_pFactory = pFactory;
  447. io.ConfigFlags |= ImGuiConfigFlags_RendererHasViewports;
  448. if (io.ConfigFlags & ImGuiConfigFlags_EnableViewports)
  449. ImGui_ImplDX11_InitPlatformInterface();
  450. return true;
  451. }
  452. void ImGui_ImplDX11_Shutdown()
  453. {
  454. ImGui_ImplDX11_ShutdownPlatformInterface();
  455. ImGui_ImplDX11_InvalidateDeviceObjects();
  456. g_pd3dDevice = NULL;
  457. g_pd3dDeviceContext = NULL;
  458. }
  459. void ImGui_ImplDX11_NewFrame()
  460. {
  461. if (!g_pFontSampler)
  462. ImGui_ImplDX11_CreateDeviceObjects();
  463. }
  464. // --------------------------------------------------------------------------------------------------------
  465. // Platform Windows
  466. // --------------------------------------------------------------------------------------------------------
  467. #include "imgui_internal.h" // ImGuiViewport
  468. struct ImGuiPlatformDataDx11
  469. {
  470. IDXGISwapChain* SwapChain;
  471. ID3D11RenderTargetView* RTView;
  472. ImGuiPlatformDataDx11() { SwapChain = NULL; RTView = NULL; }
  473. ~ImGuiPlatformDataDx11() { IM_ASSERT(SwapChain == NULL && RTView == NULL); }
  474. };
  475. static void ImGui_ImplDX11_CreateViewport(ImGuiViewport* viewport)
  476. {
  477. ImGuiPlatformDataDx11* data = IM_NEW(ImGuiPlatformDataDx11)();
  478. viewport->RendererUserData = data;
  479. // FIXME-PLATFORM
  480. HWND hwnd = (HWND)viewport->PlatformHandle;
  481. IM_ASSERT(hwnd != 0);
  482. // Create swap chain
  483. DXGI_SWAP_CHAIN_DESC sd;
  484. ZeroMemory(&sd, sizeof(sd));
  485. sd.BufferDesc.Width = (UINT)viewport->Size.x;
  486. sd.BufferDesc.Height = (UINT)viewport->Size.y;
  487. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  488. sd.SampleDesc.Count = 1;
  489. sd.SampleDesc.Quality = 0;
  490. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  491. sd.BufferCount = 1;
  492. sd.OutputWindow = hwnd;
  493. sd.Windowed = TRUE;
  494. sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  495. sd.Flags = 0;
  496. IM_ASSERT(data->SwapChain == NULL && data->RTView == NULL);
  497. g_pFactory->CreateSwapChain(g_pd3dDevice, &sd, &data->SwapChain);
  498. // Create the render target
  499. if (data->SwapChain)
  500. {
  501. ID3D11Texture2D* pBackBuffer;
  502. data->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  503. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &data->RTView);
  504. pBackBuffer->Release();
  505. }
  506. }
  507. static void ImGui_ImplDX11_DestroyViewport(ImGuiViewport* viewport)
  508. {
  509. if (ImGuiPlatformDataDx11* data = (ImGuiPlatformDataDx11*)viewport->RendererUserData)
  510. {
  511. if (data->SwapChain)
  512. data->SwapChain->Release();
  513. data->SwapChain = NULL;
  514. if (data->RTView)
  515. data->RTView->Release();
  516. data->RTView = NULL;
  517. IM_DELETE(data);
  518. }
  519. viewport->RendererUserData = NULL;
  520. }
  521. static void ImGui_ImplDX11_ResizeViewport(ImGuiViewport* viewport, ImVec2 size)
  522. {
  523. ImGuiPlatformDataDx11* data = (ImGuiPlatformDataDx11*)viewport->RendererUserData;
  524. if (data->RTView)
  525. {
  526. data->RTView->Release();
  527. data->RTView = NULL;
  528. }
  529. if (data->SwapChain)
  530. {
  531. ID3D11Texture2D* pBackBuffer = NULL;
  532. data->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
  533. data->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
  534. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &data->RTView);
  535. pBackBuffer->Release();
  536. }
  537. }
  538. static void ImGui_ImplDX11_RenderViewport(ImGuiViewport* viewport)
  539. {
  540. ImGuiPlatformDataDx11* data = (ImGuiPlatformDataDx11*)viewport->RendererUserData;
  541. ImVec4 clear_color = ImGui::GetStyle().Colors[ImGuiCol_WindowBg]; // FIXME-PLATFORM
  542. clear_color.w = 1.0f;
  543. g_pd3dDeviceContext->OMSetRenderTargets(1, &data->RTView, NULL);
  544. g_pd3dDeviceContext->ClearRenderTargetView(data->RTView, (float*)&clear_color);
  545. ImGui_ImplDX11_RenderDrawData(&viewport->DrawData);
  546. }
  547. static void ImGui_ImplDX11_SwapBuffers(ImGuiViewport* viewport)
  548. {
  549. ImGuiPlatformDataDx11* data = (ImGuiPlatformDataDx11*)viewport->RendererUserData;
  550. data->SwapChain->Present(0, 0); // Present without vsync
  551. }
  552. void ImGui_ImplDX11_InitPlatformInterface()
  553. {
  554. ImGuiIO& io = ImGui::GetIO();
  555. io.RendererInterface.CreateViewport = ImGui_ImplDX11_CreateViewport;
  556. io.RendererInterface.DestroyViewport = ImGui_ImplDX11_DestroyViewport;
  557. io.RendererInterface.ResizeViewport = ImGui_ImplDX11_ResizeViewport;
  558. io.RendererInterface.RenderViewport = ImGui_ImplDX11_RenderViewport;
  559. io.RendererInterface.SwapBuffers = ImGui_ImplDX11_SwapBuffers;
  560. }
  561. void ImGui_ImplDX11_ShutdownPlatformInterface()
  562. {
  563. ImGui::DestroyViewportsRendererData(ImGui::GetCurrentContext());
  564. ImGuiIO& io = ImGui::GetIO();
  565. memset(&io.RendererInterface, 0, sizeof(io.RendererInterface));
  566. }