imgui_impl_dx11.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // ImGui Win32 + DirectX11 binding
  2. // In this binding, ImTextureID is used to store a 'ID3D11ShaderResourceView*' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
  3. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  4. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  5. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  6. // https://github.com/ocornut/imgui
  7. #include <imgui.h>
  8. #include "imgui_impl_dx11.h"
  9. // DirectX
  10. #include <d3d11.h>
  11. #include <d3dcompiler.h>
  12. #define DIRECTINPUT_VERSION 0x0800
  13. #include <dinput.h>
  14. // Data
  15. static INT64 g_Time = 0;
  16. static INT64 g_TicksPerSecond = 0;
  17. static HWND g_hWnd = 0;
  18. static ID3D11Device* g_pd3dDevice = NULL;
  19. static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
  20. static ID3D11Buffer* g_pVB = NULL;
  21. static ID3D11Buffer* g_pIB = NULL;
  22. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  23. static ID3D11VertexShader* g_pVertexShader = NULL;
  24. static ID3D11InputLayout* g_pInputLayout = NULL;
  25. static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
  26. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  27. static ID3D11PixelShader* g_pPixelShader = NULL;
  28. static ID3D11SamplerState* g_pFontSampler = NULL;
  29. static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
  30. static ID3D11RasterizerState* g_pRasterizerState = NULL;
  31. static ID3D11BlendState* g_pBlendState = NULL;
  32. static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
  33. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  34. struct VERTEX_CONSTANT_BUFFER
  35. {
  36. float mvp[4][4];
  37. };
  38. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  39. // If text or lines are blurry when integrating ImGui in your engine:
  40. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  41. void ImGui_ImplDX11_RenderDrawLists(ImDrawData* draw_data)
  42. {
  43. ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
  44. // Create and grow vertex/index buffers if needed
  45. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  46. {
  47. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  48. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  49. D3D11_BUFFER_DESC desc;
  50. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  51. desc.Usage = D3D11_USAGE_DYNAMIC;
  52. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  53. desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
  54. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  55. desc.MiscFlags = 0;
  56. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  57. return;
  58. }
  59. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  60. {
  61. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  62. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  63. D3D11_BUFFER_DESC desc;
  64. memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
  65. desc.Usage = D3D11_USAGE_DYNAMIC;
  66. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  67. desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
  68. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  69. if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  70. return;
  71. }
  72. // Copy and convert all vertices into a single contiguous buffer
  73. D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
  74. if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
  75. return;
  76. if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
  77. return;
  78. ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
  79. ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
  80. for (int n = 0; n < draw_data->CmdListsCount; n++)
  81. {
  82. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  83. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  84. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  85. vtx_dst += cmd_list->VtxBuffer.Size;
  86. idx_dst += cmd_list->IdxBuffer.Size;
  87. }
  88. ctx->Unmap(g_pVB, 0);
  89. ctx->Unmap(g_pIB, 0);
  90. // Setup orthographic projection matrix into our constant buffer
  91. {
  92. D3D11_MAPPED_SUBRESOURCE mapped_resource;
  93. if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  94. return;
  95. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
  96. float L = 0.0f;
  97. float R = ImGui::GetIO().DisplaySize.x;
  98. float B = ImGui::GetIO().DisplaySize.y;
  99. float T = 0.0f;
  100. float mvp[4][4] =
  101. {
  102. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  103. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  104. { 0.0f, 0.0f, 0.5f, 0.0f },
  105. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  106. };
  107. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  108. ctx->Unmap(g_pVertexConstantBuffer, 0);
  109. }
  110. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  111. struct BACKUP_DX11_STATE
  112. {
  113. UINT ScissorRectsCount, ViewportsCount;
  114. D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  115. D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  116. ID3D11RasterizerState* RS;
  117. ID3D11BlendState* BlendState;
  118. FLOAT BlendFactor[4];
  119. UINT SampleMask;
  120. UINT StencilRef;
  121. ID3D11DepthStencilState* DepthStencilState;
  122. ID3D11ShaderResourceView* PSShaderResource;
  123. ID3D11SamplerState* PSSampler;
  124. ID3D11PixelShader* PS;
  125. ID3D11VertexShader* VS;
  126. UINT PSInstancesCount, VSInstancesCount;
  127. ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
  128. D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  129. ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  130. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  131. DXGI_FORMAT IndexBufferFormat;
  132. ID3D11InputLayout* InputLayout;
  133. };
  134. BACKUP_DX11_STATE old;
  135. old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  136. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  137. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  138. ctx->RSGetState(&old.RS);
  139. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  140. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  141. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  142. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  143. old.PSInstancesCount = old.VSInstancesCount = 256;
  144. ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
  145. ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
  146. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  147. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  148. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  149. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  150. ctx->IAGetInputLayout(&old.InputLayout);
  151. // Setup viewport
  152. D3D11_VIEWPORT vp;
  153. memset(&vp, 0, sizeof(D3D11_VIEWPORT));
  154. vp.Width = ImGui::GetIO().DisplaySize.x;
  155. vp.Height = ImGui::GetIO().DisplaySize.y;
  156. vp.MinDepth = 0.0f;
  157. vp.MaxDepth = 1.0f;
  158. vp.TopLeftX = vp.TopLeftY = 0.0f;
  159. ctx->RSSetViewports(1, &vp);
  160. // Bind shader and vertex buffers
  161. unsigned int stride = sizeof(ImDrawVert);
  162. unsigned int offset = 0;
  163. ctx->IASetInputLayout(g_pInputLayout);
  164. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  165. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  166. ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  167. ctx->VSSetShader(g_pVertexShader, NULL, 0);
  168. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  169. ctx->PSSetShader(g_pPixelShader, NULL, 0);
  170. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  171. // Setup render state
  172. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  173. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  174. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  175. ctx->RSSetState(g_pRasterizerState);
  176. // Render command lists
  177. int vtx_offset = 0;
  178. int idx_offset = 0;
  179. for (int n = 0; n < draw_data->CmdListsCount; n++)
  180. {
  181. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  182. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  183. {
  184. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  185. if (pcmd->UserCallback)
  186. {
  187. pcmd->UserCallback(cmd_list, pcmd);
  188. }
  189. else
  190. {
  191. const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  192. ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
  193. ctx->RSSetScissorRects(1, &r);
  194. ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  195. }
  196. idx_offset += pcmd->ElemCount;
  197. }
  198. vtx_offset += cmd_list->VtxBuffer.Size;
  199. }
  200. // Restore modified DX state
  201. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  202. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  203. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  204. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  205. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  206. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  207. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  208. ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
  209. for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
  210. ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
  211. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  212. for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
  213. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  214. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  215. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  216. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  217. }
  218. IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
  219. {
  220. ImGuiIO& io = ImGui::GetIO();
  221. switch (msg)
  222. {
  223. case WM_LBUTTONDOWN:
  224. io.MouseDown[0] = true;
  225. return true;
  226. case WM_LBUTTONUP:
  227. io.MouseDown[0] = false;
  228. return true;
  229. case WM_RBUTTONDOWN:
  230. io.MouseDown[1] = true;
  231. return true;
  232. case WM_RBUTTONUP:
  233. io.MouseDown[1] = false;
  234. return true;
  235. case WM_MBUTTONDOWN:
  236. io.MouseDown[2] = true;
  237. return true;
  238. case WM_MBUTTONUP:
  239. io.MouseDown[2] = false;
  240. return true;
  241. case WM_MOUSEWHEEL:
  242. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  243. return true;
  244. case WM_MOUSEMOVE:
  245. io.MousePos.x = (signed short)(lParam);
  246. io.MousePos.y = (signed short)(lParam >> 16);
  247. return true;
  248. case WM_KEYDOWN:
  249. if (wParam < 256)
  250. io.KeysDown[wParam] = 1;
  251. return true;
  252. case WM_KEYUP:
  253. if (wParam < 256)
  254. io.KeysDown[wParam] = 0;
  255. return true;
  256. case WM_CHAR:
  257. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  258. if (wParam > 0 && wParam < 0x10000)
  259. io.AddInputCharacter((unsigned short)wParam);
  260. return true;
  261. }
  262. return 0;
  263. }
  264. static void ImGui_ImplDX11_CreateFontsTexture()
  265. {
  266. // Build texture atlas
  267. ImGuiIO& io = ImGui::GetIO();
  268. unsigned char* pixels;
  269. int width, height;
  270. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  271. // Upload texture to graphics system
  272. {
  273. D3D11_TEXTURE2D_DESC desc;
  274. ZeroMemory(&desc, sizeof(desc));
  275. desc.Width = width;
  276. desc.Height = height;
  277. desc.MipLevels = 1;
  278. desc.ArraySize = 1;
  279. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  280. desc.SampleDesc.Count = 1;
  281. desc.Usage = D3D11_USAGE_DEFAULT;
  282. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  283. desc.CPUAccessFlags = 0;
  284. ID3D11Texture2D *pTexture = NULL;
  285. D3D11_SUBRESOURCE_DATA subResource;
  286. subResource.pSysMem = pixels;
  287. subResource.SysMemPitch = desc.Width * 4;
  288. subResource.SysMemSlicePitch = 0;
  289. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  290. // Create texture view
  291. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  292. ZeroMemory(&srvDesc, sizeof(srvDesc));
  293. srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  294. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  295. srvDesc.Texture2D.MipLevels = desc.MipLevels;
  296. srvDesc.Texture2D.MostDetailedMip = 0;
  297. g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
  298. pTexture->Release();
  299. }
  300. // Store our identifier
  301. io.Fonts->TexID = (void *)g_pFontTextureView;
  302. // Create texture sampler
  303. {
  304. D3D11_SAMPLER_DESC desc;
  305. ZeroMemory(&desc, sizeof(desc));
  306. desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  307. desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  308. desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  309. desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  310. desc.MipLODBias = 0.f;
  311. desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
  312. desc.MinLOD = 0.f;
  313. desc.MaxLOD = 0.f;
  314. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  315. }
  316. }
  317. bool ImGui_ImplDX11_CreateDeviceObjects()
  318. {
  319. if (!g_pd3dDevice)
  320. return false;
  321. if (g_pFontSampler)
  322. ImGui_ImplDX11_InvalidateDeviceObjects();
  323. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  324. // If you would like to use this DX11 sample code but remove this dependency you can:
  325. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  326. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  327. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  328. // Create the vertex shader
  329. {
  330. static const char* vertexShader =
  331. "cbuffer vertexBuffer : register(b0) \
  332. {\
  333. float4x4 ProjectionMatrix; \
  334. };\
  335. struct VS_INPUT\
  336. {\
  337. float2 pos : POSITION;\
  338. float4 col : COLOR0;\
  339. float2 uv : TEXCOORD0;\
  340. };\
  341. \
  342. struct PS_INPUT\
  343. {\
  344. float4 pos : SV_POSITION;\
  345. float4 col : COLOR0;\
  346. float2 uv : TEXCOORD0;\
  347. };\
  348. \
  349. PS_INPUT main(VS_INPUT input)\
  350. {\
  351. PS_INPUT output;\
  352. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  353. output.col = input.col;\
  354. output.uv = input.uv;\
  355. return output;\
  356. }";
  357. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  358. 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!
  359. return false;
  360. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
  361. return false;
  362. // Create the input layout
  363. D3D11_INPUT_ELEMENT_DESC local_layout[] = {
  364. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  365. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  366. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
  367. };
  368. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  369. return false;
  370. // Create the constant buffer
  371. {
  372. D3D11_BUFFER_DESC desc;
  373. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  374. desc.Usage = D3D11_USAGE_DYNAMIC;
  375. desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  376. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  377. desc.MiscFlags = 0;
  378. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  379. }
  380. }
  381. // Create the pixel shader
  382. {
  383. static const char* pixelShader =
  384. "struct PS_INPUT\
  385. {\
  386. float4 pos : SV_POSITION;\
  387. float4 col : COLOR0;\
  388. float2 uv : TEXCOORD0;\
  389. };\
  390. sampler sampler0;\
  391. Texture2D texture0;\
  392. \
  393. float4 main(PS_INPUT input) : SV_Target\
  394. {\
  395. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  396. return out_col; \
  397. }";
  398. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  399. 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!
  400. return false;
  401. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
  402. return false;
  403. }
  404. // Create the blending setup
  405. {
  406. D3D11_BLEND_DESC desc;
  407. ZeroMemory(&desc, sizeof(desc));
  408. desc.AlphaToCoverageEnable = false;
  409. desc.RenderTarget[0].BlendEnable = true;
  410. desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
  411. desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
  412. desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
  413. desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
  414. desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
  415. desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  416. desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  417. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  418. }
  419. // Create the rasterizer state
  420. {
  421. D3D11_RASTERIZER_DESC desc;
  422. ZeroMemory(&desc, sizeof(desc));
  423. desc.FillMode = D3D11_FILL_SOLID;
  424. desc.CullMode = D3D11_CULL_NONE;
  425. desc.ScissorEnable = true;
  426. desc.DepthClipEnable = true;
  427. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  428. }
  429. // Create depth-stencil State
  430. {
  431. D3D11_DEPTH_STENCIL_DESC desc;
  432. ZeroMemory(&desc, sizeof(desc));
  433. desc.DepthEnable = false;
  434. desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
  435. desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
  436. desc.StencilEnable = false;
  437. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
  438. desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
  439. desc.BackFace = desc.FrontFace;
  440. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  441. }
  442. ImGui_ImplDX11_CreateFontsTexture();
  443. return true;
  444. }
  445. void ImGui_ImplDX11_InvalidateDeviceObjects()
  446. {
  447. if (!g_pd3dDevice)
  448. return;
  449. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  450. 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.
  451. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  452. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  453. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  454. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  455. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  456. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  457. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  458. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  459. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  460. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  461. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  462. }
  463. bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context)
  464. {
  465. g_hWnd = (HWND)hwnd;
  466. g_pd3dDevice = device;
  467. g_pd3dDeviceContext = device_context;
  468. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  469. return false;
  470. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  471. return false;
  472. ImGuiIO& io = ImGui::GetIO();
  473. io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
  474. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  475. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  476. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  477. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  478. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  479. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  480. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  481. io.KeyMap[ImGuiKey_End] = VK_END;
  482. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  483. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  484. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  485. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  486. io.KeyMap[ImGuiKey_A] = 'A';
  487. io.KeyMap[ImGuiKey_C] = 'C';
  488. io.KeyMap[ImGuiKey_V] = 'V';
  489. io.KeyMap[ImGuiKey_X] = 'X';
  490. io.KeyMap[ImGuiKey_Y] = 'Y';
  491. io.KeyMap[ImGuiKey_Z] = 'Z';
  492. io.RenderDrawListsFn = ImGui_ImplDX11_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  493. io.ImeWindowHandle = g_hWnd;
  494. return true;
  495. }
  496. void ImGui_ImplDX11_Shutdown()
  497. {
  498. ImGui_ImplDX11_InvalidateDeviceObjects();
  499. ImGui::Shutdown();
  500. g_pd3dDevice = NULL;
  501. g_pd3dDeviceContext = NULL;
  502. g_hWnd = (HWND)0;
  503. }
  504. void ImGui_ImplDX11_NewFrame()
  505. {
  506. if (!g_pFontSampler)
  507. ImGui_ImplDX11_CreateDeviceObjects();
  508. ImGuiIO& io = ImGui::GetIO();
  509. // Setup display size (every frame to accommodate for window resizing)
  510. RECT rect;
  511. GetClientRect(g_hWnd, &rect);
  512. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  513. // Setup time step
  514. INT64 current_time;
  515. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  516. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  517. g_Time = current_time;
  518. // Read keyboard modifiers inputs
  519. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  520. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  521. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  522. io.KeySuper = false;
  523. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  524. // io.MousePos : filled by WM_MOUSEMOVE events
  525. // io.MouseDown : filled by WM_*BUTTON* events
  526. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  527. // Hide OS mouse cursor if ImGui is drawing it
  528. if (io.MouseDrawCursor)
  529. SetCursor(NULL);
  530. // Start the frame
  531. ImGui::NewFrame();
  532. }