imgui_impl_dx10.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. // ImGui Win32 + DirectX10 binding
  2. // In this binding, ImTextureID is used to store a 'ID3D10ShaderResourceView*' 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_dx10.h"
  9. // DirectX
  10. #include <d3d10_1.h>
  11. #include <d3d10.h>
  12. #include <d3dcompiler.h>
  13. #define DIRECTINPUT_VERSION 0x0800
  14. #include <dinput.h>
  15. // Data
  16. static INT64 g_Time = 0;
  17. static INT64 g_TicksPerSecond = 0;
  18. static HWND g_hWnd = 0;
  19. static ID3D10Device* g_pd3dDevice = NULL;
  20. static ID3D10Buffer* g_pVB = NULL;
  21. static ID3D10Buffer* g_pIB = NULL;
  22. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  23. static ID3D10VertexShader* g_pVertexShader = NULL;
  24. static ID3D10InputLayout* g_pInputLayout = NULL;
  25. static ID3D10Buffer* g_pVertexConstantBuffer = NULL;
  26. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  27. static ID3D10PixelShader* g_pPixelShader = NULL;
  28. static ID3D10SamplerState* g_pFontSampler = NULL;
  29. static ID3D10ShaderResourceView*g_pFontTextureView = NULL;
  30. static ID3D10RasterizerState* g_pRasterizerState = NULL;
  31. static ID3D10BlendState* g_pBlendState = NULL;
  32. static ID3D10DepthStencilState* 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_ImplDX10_RenderDrawLists(ImDrawData* draw_data)
  42. {
  43. ID3D10Device* ctx = g_pd3dDevice;
  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. D3D10_BUFFER_DESC desc;
  50. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  51. desc.Usage = D3D10_USAGE_DYNAMIC;
  52. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  53. desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
  54. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  55. desc.MiscFlags = 0;
  56. if (ctx->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. D3D10_BUFFER_DESC desc;
  64. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  65. desc.Usage = D3D10_USAGE_DYNAMIC;
  66. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  67. desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
  68. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  69. if (ctx->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  70. return;
  71. }
  72. // Copy and convert all vertices into a single contiguous buffer
  73. ImDrawVert* vtx_dst = NULL;
  74. ImDrawIdx* idx_dst = NULL;
  75. g_pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
  76. g_pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
  77. for (int n = 0; n < draw_data->CmdListsCount; n++)
  78. {
  79. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  80. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  81. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  82. vtx_dst += cmd_list->VtxBuffer.Size;
  83. idx_dst += cmd_list->IdxBuffer.Size;
  84. }
  85. g_pVB->Unmap();
  86. g_pIB->Unmap();
  87. // Setup orthographic projection matrix into our constant buffer
  88. {
  89. void* mapped_resource;
  90. if (g_pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  91. return;
  92. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource;
  93. const float L = 0.0f;
  94. const float R = ImGui::GetIO().DisplaySize.x;
  95. const float B = ImGui::GetIO().DisplaySize.y;
  96. const float T = 0.0f;
  97. const float mvp[4][4] =
  98. {
  99. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  100. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  101. { 0.0f, 0.0f, 0.5f, 0.0f },
  102. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  103. };
  104. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  105. g_pVertexConstantBuffer->Unmap();
  106. }
  107. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  108. struct BACKUP_DX10_STATE
  109. {
  110. UINT ScissorRectsCount, ViewportsCount;
  111. D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  112. D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  113. ID3D10RasterizerState* RS;
  114. ID3D10BlendState* BlendState;
  115. FLOAT BlendFactor[4];
  116. UINT SampleMask;
  117. UINT StencilRef;
  118. ID3D10DepthStencilState* DepthStencilState;
  119. ID3D10ShaderResourceView* PSShaderResource;
  120. ID3D10SamplerState* PSSampler;
  121. ID3D10PixelShader* PS;
  122. ID3D10VertexShader* VS;
  123. D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  124. ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  125. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  126. DXGI_FORMAT IndexBufferFormat;
  127. ID3D10InputLayout* InputLayout;
  128. };
  129. BACKUP_DX10_STATE old;
  130. old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  131. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  132. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  133. ctx->RSGetState(&old.RS);
  134. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  135. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  136. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  137. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  138. ctx->PSGetShader(&old.PS);
  139. ctx->VSGetShader(&old.VS);
  140. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  141. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  142. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  143. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  144. ctx->IAGetInputLayout(&old.InputLayout);
  145. // Setup viewport
  146. D3D10_VIEWPORT vp;
  147. memset(&vp, 0, sizeof(D3D10_VIEWPORT));
  148. vp.Width = (UINT)ImGui::GetIO().DisplaySize.x;
  149. vp.Height = (UINT)ImGui::GetIO().DisplaySize.y;
  150. vp.MinDepth = 0.0f;
  151. vp.MaxDepth = 1.0f;
  152. vp.TopLeftX = vp.TopLeftY = 0;
  153. ctx->RSSetViewports(1, &vp);
  154. // Bind shader and vertex buffers
  155. unsigned int stride = sizeof(ImDrawVert);
  156. unsigned int offset = 0;
  157. ctx->IASetInputLayout(g_pInputLayout);
  158. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  159. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  160. ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  161. ctx->VSSetShader(g_pVertexShader);
  162. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  163. ctx->PSSetShader(g_pPixelShader);
  164. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  165. // Setup render state
  166. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  167. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  168. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  169. ctx->RSSetState(g_pRasterizerState);
  170. // Render command lists
  171. int vtx_offset = 0;
  172. int idx_offset = 0;
  173. for (int n = 0; n < draw_data->CmdListsCount; n++)
  174. {
  175. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  176. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  177. {
  178. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  179. if (pcmd->UserCallback)
  180. {
  181. pcmd->UserCallback(cmd_list, pcmd);
  182. }
  183. else
  184. {
  185. const D3D10_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  186. ctx->PSSetShaderResources(0, 1, (ID3D10ShaderResourceView**)&pcmd->TextureId);
  187. ctx->RSSetScissorRects(1, &r);
  188. ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  189. }
  190. idx_offset += pcmd->ElemCount;
  191. }
  192. vtx_offset += cmd_list->VtxBuffer.Size;
  193. }
  194. // Restore modified DX state
  195. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  196. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  197. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  198. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  199. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->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); if (old.PS) old.PS->Release();
  203. ctx->VSSetShader(old.VS); if (old.VS) old.VS->Release();
  204. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  205. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  206. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  207. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  208. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  209. }
  210. static bool IsAnyMouseButtonDown()
  211. {
  212. ImGuiIO& io = ImGui::GetIO();
  213. for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
  214. if (io.MouseDown[n])
  215. return true;
  216. return false;
  217. }
  218. // Process Win32 mouse/keyboard inputs.
  219. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  220. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  221. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  222. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  223. // 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.
  224. // 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.
  225. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  226. {
  227. ImGuiIO& io = ImGui::GetIO();
  228. switch (msg)
  229. {
  230. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  231. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  232. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  233. {
  234. int button = 0;
  235. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
  236. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
  237. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
  238. if (!IsAnyMouseButtonDown() && GetCapture() == NULL)
  239. SetCapture(hwnd);
  240. io.MouseDown[button] = true;
  241. return 0;
  242. }
  243. case WM_LBUTTONUP:
  244. case WM_RBUTTONUP:
  245. case WM_MBUTTONUP:
  246. {
  247. int button = 0;
  248. if (msg == WM_LBUTTONUP) button = 0;
  249. if (msg == WM_RBUTTONUP) button = 1;
  250. if (msg == WM_MBUTTONUP) button = 2;
  251. io.MouseDown[button] = false;
  252. if (!IsAnyMouseButtonDown() && GetCapture() == hwnd)
  253. ReleaseCapture();
  254. return 0;
  255. }
  256. case WM_MOUSEWHEEL:
  257. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  258. return 0;
  259. case WM_MOUSEMOVE:
  260. io.MousePos.x = (signed short)(lParam);
  261. io.MousePos.y = (signed short)(lParam >> 16);
  262. return 0;
  263. case WM_KEYDOWN:
  264. case WM_SYSKEYDOWN:
  265. if (wParam < 256)
  266. io.KeysDown[wParam] = 1;
  267. return 0;
  268. case WM_KEYUP:
  269. case WM_SYSKEYUP:
  270. if (wParam < 256)
  271. io.KeysDown[wParam] = 0;
  272. return 0;
  273. case WM_CHAR:
  274. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  275. if (wParam > 0 && wParam < 0x10000)
  276. io.AddInputCharacter((unsigned short)wParam);
  277. return 0;
  278. }
  279. return 0;
  280. }
  281. static void ImGui_ImplDX10_CreateFontsTexture()
  282. {
  283. ImGuiIO& io = ImGui::GetIO();
  284. // Build
  285. unsigned char* pixels;
  286. int width, height;
  287. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  288. // Create DX10 texture
  289. {
  290. D3D10_TEXTURE2D_DESC desc;
  291. ZeroMemory(&desc, sizeof(desc));
  292. desc.Width = width;
  293. desc.Height = height;
  294. desc.MipLevels = 1;
  295. desc.ArraySize = 1;
  296. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  297. desc.SampleDesc.Count = 1;
  298. desc.Usage = D3D10_USAGE_DEFAULT;
  299. desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
  300. desc.CPUAccessFlags = 0;
  301. ID3D10Texture2D *pTexture = NULL;
  302. D3D10_SUBRESOURCE_DATA subResource;
  303. subResource.pSysMem = pixels;
  304. subResource.SysMemPitch = desc.Width * 4;
  305. subResource.SysMemSlicePitch = 0;
  306. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  307. // Create texture view
  308. D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
  309. ZeroMemory(&srv_desc, sizeof(srv_desc));
  310. srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  311. srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
  312. srv_desc.Texture2D.MipLevels = desc.MipLevels;
  313. srv_desc.Texture2D.MostDetailedMip = 0;
  314. g_pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &g_pFontTextureView);
  315. pTexture->Release();
  316. }
  317. // Store our identifier
  318. io.Fonts->TexID = (void *)g_pFontTextureView;
  319. // Create texture sampler
  320. {
  321. D3D10_SAMPLER_DESC desc;
  322. ZeroMemory(&desc, sizeof(desc));
  323. desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
  324. desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP;
  325. desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP;
  326. desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP;
  327. desc.MipLODBias = 0.f;
  328. desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
  329. desc.MinLOD = 0.f;
  330. desc.MaxLOD = 0.f;
  331. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  332. }
  333. // Cleanup (don't clear the input data if you want to append new fonts later)
  334. io.Fonts->ClearInputData();
  335. io.Fonts->ClearTexData();
  336. }
  337. bool ImGui_ImplDX10_CreateDeviceObjects()
  338. {
  339. if (!g_pd3dDevice)
  340. return false;
  341. if (g_pFontSampler)
  342. ImGui_ImplDX10_InvalidateDeviceObjects();
  343. // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
  344. // If you would like to use this DX11 sample code but remove this dependency you can:
  345. // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
  346. // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
  347. // See https://github.com/ocornut/imgui/pull/638 for sources and details.
  348. // Create the vertex shader
  349. {
  350. static const char* vertexShader =
  351. "cbuffer vertexBuffer : register(b0) \
  352. {\
  353. float4x4 ProjectionMatrix; \
  354. };\
  355. struct VS_INPUT\
  356. {\
  357. float2 pos : POSITION;\
  358. float4 col : COLOR0;\
  359. float2 uv : TEXCOORD0;\
  360. };\
  361. \
  362. struct PS_INPUT\
  363. {\
  364. float4 pos : SV_POSITION;\
  365. float4 col : COLOR0;\
  366. float2 uv : TEXCOORD0;\
  367. };\
  368. \
  369. PS_INPUT main(VS_INPUT input)\
  370. {\
  371. PS_INPUT output;\
  372. output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
  373. output.col = input.col;\
  374. output.uv = input.uv;\
  375. return output;\
  376. }";
  377. D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
  378. 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!
  379. return false;
  380. if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pVertexShader) != S_OK)
  381. return false;
  382. // Create the input layout
  383. D3D10_INPUT_ELEMENT_DESC local_layout[] =
  384. {
  385. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  386. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  387. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  388. };
  389. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  390. return false;
  391. // Create the constant buffer
  392. {
  393. D3D10_BUFFER_DESC desc;
  394. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  395. desc.Usage = D3D10_USAGE_DYNAMIC;
  396. desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
  397. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  398. desc.MiscFlags = 0;
  399. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  400. }
  401. }
  402. // Create the pixel shader
  403. {
  404. static const char* pixelShader =
  405. "struct PS_INPUT\
  406. {\
  407. float4 pos : SV_POSITION;\
  408. float4 col : COLOR0;\
  409. float2 uv : TEXCOORD0;\
  410. };\
  411. sampler sampler0;\
  412. Texture2D texture0;\
  413. \
  414. float4 main(PS_INPUT input) : SV_Target\
  415. {\
  416. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  417. return out_col; \
  418. }";
  419. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  420. 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!
  421. return false;
  422. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK)
  423. return false;
  424. }
  425. // Create the blending setup
  426. {
  427. D3D10_BLEND_DESC desc;
  428. ZeroMemory(&desc, sizeof(desc));
  429. desc.AlphaToCoverageEnable = false;
  430. desc.BlendEnable[0] = true;
  431. desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
  432. desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
  433. desc.BlendOp = D3D10_BLEND_OP_ADD;
  434. desc.SrcBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
  435. desc.DestBlendAlpha = D3D10_BLEND_ZERO;
  436. desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
  437. desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
  438. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  439. }
  440. // Create the rasterizer state
  441. {
  442. D3D10_RASTERIZER_DESC desc;
  443. ZeroMemory(&desc, sizeof(desc));
  444. desc.FillMode = D3D10_FILL_SOLID;
  445. desc.CullMode = D3D10_CULL_NONE;
  446. desc.ScissorEnable = true;
  447. desc.DepthClipEnable = true;
  448. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  449. }
  450. // Create depth-stencil State
  451. {
  452. D3D10_DEPTH_STENCIL_DESC desc;
  453. ZeroMemory(&desc, sizeof(desc));
  454. desc.DepthEnable = false;
  455. desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
  456. desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
  457. desc.StencilEnable = false;
  458. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
  459. desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
  460. desc.BackFace = desc.FrontFace;
  461. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  462. }
  463. ImGui_ImplDX10_CreateFontsTexture();
  464. return true;
  465. }
  466. void ImGui_ImplDX10_InvalidateDeviceObjects()
  467. {
  468. if (!g_pd3dDevice)
  469. return;
  470. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  471. 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.
  472. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  473. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  474. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  475. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  476. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  477. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  478. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  479. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  480. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  481. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  482. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  483. }
  484. bool ImGui_ImplDX10_Init(void* hwnd, ID3D10Device* device)
  485. {
  486. g_hWnd = (HWND)hwnd;
  487. g_pd3dDevice = device;
  488. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  489. return false;
  490. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  491. return false;
  492. ImGuiIO& io = ImGui::GetIO();
  493. 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.
  494. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  495. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  496. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  497. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  498. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  499. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  500. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  501. io.KeyMap[ImGuiKey_End] = VK_END;
  502. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  503. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  504. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  505. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  506. io.KeyMap[ImGuiKey_A] = 'A';
  507. io.KeyMap[ImGuiKey_C] = 'C';
  508. io.KeyMap[ImGuiKey_V] = 'V';
  509. io.KeyMap[ImGuiKey_X] = 'X';
  510. io.KeyMap[ImGuiKey_Y] = 'Y';
  511. io.KeyMap[ImGuiKey_Z] = 'Z';
  512. io.RenderDrawListsFn = ImGui_ImplDX10_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  513. io.ImeWindowHandle = g_hWnd;
  514. return true;
  515. }
  516. void ImGui_ImplDX10_Shutdown()
  517. {
  518. ImGui_ImplDX10_InvalidateDeviceObjects();
  519. ImGui::Shutdown();
  520. g_pd3dDevice = NULL;
  521. g_hWnd = (HWND)0;
  522. }
  523. void ImGui_ImplDX10_NewFrame()
  524. {
  525. if (!g_pFontSampler)
  526. ImGui_ImplDX10_CreateDeviceObjects();
  527. ImGuiIO& io = ImGui::GetIO();
  528. // Setup display size (every frame to accommodate for window resizing)
  529. RECT rect;
  530. GetClientRect(g_hWnd, &rect);
  531. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  532. // Setup time step
  533. INT64 current_time;
  534. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  535. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  536. g_Time = current_time;
  537. // Read keyboard modifiers inputs
  538. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  539. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  540. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  541. io.KeySuper = false;
  542. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  543. // io.MousePos : filled by WM_MOUSEMOVE events
  544. // io.MouseDown : filled by WM_*BUTTON* events
  545. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  546. // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  547. if (io.WantMoveMouse)
  548. {
  549. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  550. ClientToScreen(g_hWnd, &pos);
  551. SetCursorPos(pos.x, pos.y);
  552. }
  553. // Hide OS mouse cursor if ImGui is drawing it
  554. if (io.MouseDrawCursor)
  555. SetCursor(NULL);
  556. // 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.
  557. ImGui::NewFrame();
  558. }