imgui_impl_dx11.cpp 23 KB

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