imgui_impl_dx10.cpp 26 KB

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