imgui_impl_dx11.cpp 28 KB

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