2
0

imgui_impl_dx10.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. // CHANGELOG
  9. // (minor and older changes stripped away, please see git history for details)
  10. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
  11. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
  12. // 2018-02-06: Inputs: Honoring the io.WantMoveMouse by repositioning the mouse by using navigation and ImGuiNavFlags_MoveMouse is set.
  13. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
  14. // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert.
  15. // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag.
  16. // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read.
  17. // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
  18. // 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set.
  19. // 2016-05-07: DirectX10: Disabling depth-write.
  20. #include "imgui.h"
  21. #include "imgui_impl_dx10.h"
  22. // DirectX
  23. #include <d3d10_1.h>
  24. #include <d3d10.h>
  25. #include <d3dcompiler.h>
  26. #define DIRECTINPUT_VERSION 0x0800
  27. #include <dinput.h>
  28. // Data
  29. static INT64 g_Time = 0;
  30. static INT64 g_TicksPerSecond = 0;
  31. static HWND g_hWnd = 0;
  32. static ID3D10Device* g_pd3dDevice = NULL;
  33. static ID3D10Buffer* g_pVB = NULL;
  34. static ID3D10Buffer* g_pIB = NULL;
  35. static ID3D10Blob * g_pVertexShaderBlob = NULL;
  36. static ID3D10VertexShader* g_pVertexShader = NULL;
  37. static ID3D10InputLayout* g_pInputLayout = NULL;
  38. static ID3D10Buffer* g_pVertexConstantBuffer = NULL;
  39. static ID3D10Blob * g_pPixelShaderBlob = NULL;
  40. static ID3D10PixelShader* g_pPixelShader = NULL;
  41. static ID3D10SamplerState* g_pFontSampler = NULL;
  42. static ID3D10ShaderResourceView*g_pFontTextureView = NULL;
  43. static ID3D10RasterizerState* g_pRasterizerState = NULL;
  44. static ID3D10BlendState* g_pBlendState = NULL;
  45. static ID3D10DepthStencilState* g_pDepthStencilState = NULL;
  46. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  47. struct VERTEX_CONSTANT_BUFFER
  48. {
  49. float mvp[4][4];
  50. };
  51. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  52. // If text or lines are blurry when integrating ImGui in your engine:
  53. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  54. void ImGui_ImplDX10_RenderDrawLists(ImDrawData* draw_data)
  55. {
  56. ID3D10Device* ctx = g_pd3dDevice;
  57. // Create and grow vertex/index buffers if needed
  58. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  59. {
  60. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  61. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  62. D3D10_BUFFER_DESC desc;
  63. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  64. desc.Usage = D3D10_USAGE_DYNAMIC;
  65. desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
  66. desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
  67. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  68. desc.MiscFlags = 0;
  69. if (ctx->CreateBuffer(&desc, NULL, &g_pVB) < 0)
  70. return;
  71. }
  72. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  73. {
  74. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  75. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  76. D3D10_BUFFER_DESC desc;
  77. memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
  78. desc.Usage = D3D10_USAGE_DYNAMIC;
  79. desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
  80. desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
  81. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  82. if (ctx->CreateBuffer(&desc, NULL, &g_pIB) < 0)
  83. return;
  84. }
  85. // Copy and convert all vertices into a single contiguous buffer
  86. ImDrawVert* vtx_dst = NULL;
  87. ImDrawIdx* idx_dst = NULL;
  88. g_pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
  89. g_pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
  90. for (int n = 0; n < draw_data->CmdListsCount; n++)
  91. {
  92. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  93. memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
  94. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  95. vtx_dst += cmd_list->VtxBuffer.Size;
  96. idx_dst += cmd_list->IdxBuffer.Size;
  97. }
  98. g_pVB->Unmap();
  99. g_pIB->Unmap();
  100. // Setup orthographic projection matrix into our constant buffer
  101. {
  102. void* mapped_resource;
  103. if (g_pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
  104. return;
  105. VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource;
  106. const float L = 0.0f;
  107. const float R = ImGui::GetIO().DisplaySize.x;
  108. const float B = ImGui::GetIO().DisplaySize.y;
  109. const float T = 0.0f;
  110. const float mvp[4][4] =
  111. {
  112. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  113. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  114. { 0.0f, 0.0f, 0.5f, 0.0f },
  115. { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
  116. };
  117. memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
  118. g_pVertexConstantBuffer->Unmap();
  119. }
  120. // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
  121. struct BACKUP_DX10_STATE
  122. {
  123. UINT ScissorRectsCount, ViewportsCount;
  124. D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  125. D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
  126. ID3D10RasterizerState* RS;
  127. ID3D10BlendState* BlendState;
  128. FLOAT BlendFactor[4];
  129. UINT SampleMask;
  130. UINT StencilRef;
  131. ID3D10DepthStencilState* DepthStencilState;
  132. ID3D10ShaderResourceView* PSShaderResource;
  133. ID3D10SamplerState* PSSampler;
  134. ID3D10PixelShader* PS;
  135. ID3D10VertexShader* VS;
  136. D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
  137. ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
  138. UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
  139. DXGI_FORMAT IndexBufferFormat;
  140. ID3D10InputLayout* InputLayout;
  141. };
  142. BACKUP_DX10_STATE old;
  143. old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
  144. ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
  145. ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
  146. ctx->RSGetState(&old.RS);
  147. ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
  148. ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
  149. ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
  150. ctx->PSGetSamplers(0, 1, &old.PSSampler);
  151. ctx->PSGetShader(&old.PS);
  152. ctx->VSGetShader(&old.VS);
  153. ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
  154. ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
  155. ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
  156. ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
  157. ctx->IAGetInputLayout(&old.InputLayout);
  158. // Setup viewport
  159. D3D10_VIEWPORT vp;
  160. memset(&vp, 0, sizeof(D3D10_VIEWPORT));
  161. vp.Width = (UINT)ImGui::GetIO().DisplaySize.x;
  162. vp.Height = (UINT)ImGui::GetIO().DisplaySize.y;
  163. vp.MinDepth = 0.0f;
  164. vp.MaxDepth = 1.0f;
  165. vp.TopLeftX = vp.TopLeftY = 0;
  166. ctx->RSSetViewports(1, &vp);
  167. // Bind shader and vertex buffers
  168. unsigned int stride = sizeof(ImDrawVert);
  169. unsigned int offset = 0;
  170. ctx->IASetInputLayout(g_pInputLayout);
  171. ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
  172. ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  173. ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  174. ctx->VSSetShader(g_pVertexShader);
  175. ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
  176. ctx->PSSetShader(g_pPixelShader);
  177. ctx->PSSetSamplers(0, 1, &g_pFontSampler);
  178. // Setup render state
  179. const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
  180. ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
  181. ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
  182. ctx->RSSetState(g_pRasterizerState);
  183. // Render command lists
  184. int vtx_offset = 0;
  185. int idx_offset = 0;
  186. for (int n = 0; n < draw_data->CmdListsCount; n++)
  187. {
  188. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  189. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  190. {
  191. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  192. if (pcmd->UserCallback)
  193. {
  194. pcmd->UserCallback(cmd_list, pcmd);
  195. }
  196. else
  197. {
  198. const D3D10_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  199. ctx->PSSetShaderResources(0, 1, (ID3D10ShaderResourceView**)&pcmd->TextureId);
  200. ctx->RSSetScissorRects(1, &r);
  201. ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
  202. }
  203. idx_offset += pcmd->ElemCount;
  204. }
  205. vtx_offset += cmd_list->VtxBuffer.Size;
  206. }
  207. // Restore modified DX state
  208. ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
  209. ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
  210. ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
  211. ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
  212. ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
  213. ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
  214. ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
  215. ctx->PSSetShader(old.PS); if (old.PS) old.PS->Release();
  216. ctx->VSSetShader(old.VS); if (old.VS) old.VS->Release();
  217. ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
  218. ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
  219. ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
  220. ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
  221. ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
  222. }
  223. // Process Win32 mouse/keyboard inputs.
  224. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  225. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  226. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  227. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  228. // 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.
  229. // 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.
  230. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  231. {
  232. if (ImGui::GetCurrentContext() == NULL)
  233. return 0;
  234. ImGuiIO& io = ImGui::GetIO();
  235. switch (msg)
  236. {
  237. case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
  238. case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
  239. case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
  240. {
  241. int button = 0;
  242. if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
  243. if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
  244. if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
  245. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
  246. ::SetCapture(hwnd);
  247. io.MouseDown[button] = true;
  248. return 0;
  249. }
  250. case WM_LBUTTONUP:
  251. case WM_RBUTTONUP:
  252. case WM_MBUTTONUP:
  253. {
  254. int button = 0;
  255. if (msg == WM_LBUTTONUP) button = 0;
  256. if (msg == WM_RBUTTONUP) button = 1;
  257. if (msg == WM_MBUTTONUP) button = 2;
  258. io.MouseDown[button] = false;
  259. if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
  260. ::ReleaseCapture();
  261. return 0;
  262. }
  263. case WM_MOUSEWHEEL:
  264. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  265. return 0;
  266. case WM_MOUSEHWHEEL:
  267. io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  268. return 0;
  269. case WM_MOUSEMOVE:
  270. io.MousePos.x = (signed short)(lParam);
  271. io.MousePos.y = (signed short)(lParam >> 16);
  272. return 0;
  273. case WM_KEYDOWN:
  274. case WM_SYSKEYDOWN:
  275. if (wParam < 256)
  276. io.KeysDown[wParam] = 1;
  277. return 0;
  278. case WM_KEYUP:
  279. case WM_SYSKEYUP:
  280. if (wParam < 256)
  281. io.KeysDown[wParam] = 0;
  282. return 0;
  283. case WM_CHAR:
  284. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  285. if (wParam > 0 && wParam < 0x10000)
  286. io.AddInputCharacter((unsigned short)wParam);
  287. return 0;
  288. }
  289. return 0;
  290. }
  291. static void ImGui_ImplDX10_CreateFontsTexture()
  292. {
  293. ImGuiIO& io = ImGui::GetIO();
  294. // Build
  295. unsigned char* pixels;
  296. int width, height;
  297. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  298. // Create DX10 texture
  299. {
  300. D3D10_TEXTURE2D_DESC desc;
  301. ZeroMemory(&desc, sizeof(desc));
  302. desc.Width = width;
  303. desc.Height = height;
  304. desc.MipLevels = 1;
  305. desc.ArraySize = 1;
  306. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  307. desc.SampleDesc.Count = 1;
  308. desc.Usage = D3D10_USAGE_DEFAULT;
  309. desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
  310. desc.CPUAccessFlags = 0;
  311. ID3D10Texture2D *pTexture = NULL;
  312. D3D10_SUBRESOURCE_DATA subResource;
  313. subResource.pSysMem = pixels;
  314. subResource.SysMemPitch = desc.Width * 4;
  315. subResource.SysMemSlicePitch = 0;
  316. g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
  317. // Create texture view
  318. D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
  319. ZeroMemory(&srv_desc, sizeof(srv_desc));
  320. srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  321. srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
  322. srv_desc.Texture2D.MipLevels = desc.MipLevels;
  323. srv_desc.Texture2D.MostDetailedMip = 0;
  324. g_pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &g_pFontTextureView);
  325. pTexture->Release();
  326. }
  327. // Store our identifier
  328. io.Fonts->TexID = (void *)g_pFontTextureView;
  329. // Create texture sampler
  330. {
  331. D3D10_SAMPLER_DESC desc;
  332. ZeroMemory(&desc, sizeof(desc));
  333. desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
  334. desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP;
  335. desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP;
  336. desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP;
  337. desc.MipLODBias = 0.f;
  338. desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
  339. desc.MinLOD = 0.f;
  340. desc.MaxLOD = 0.f;
  341. g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
  342. }
  343. // Cleanup (don't clear the input data if you want to append new fonts later)
  344. io.Fonts->ClearInputData();
  345. io.Fonts->ClearTexData();
  346. }
  347. bool ImGui_ImplDX10_CreateDeviceObjects()
  348. {
  349. if (!g_pd3dDevice)
  350. return false;
  351. if (g_pFontSampler)
  352. ImGui_ImplDX10_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(), &g_pVertexShader) != S_OK)
  391. return false;
  392. // Create the input layout
  393. D3D10_INPUT_ELEMENT_DESC local_layout[] =
  394. {
  395. { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  396. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  397. { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
  398. };
  399. if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
  400. return false;
  401. // Create the constant buffer
  402. {
  403. D3D10_BUFFER_DESC desc;
  404. desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
  405. desc.Usage = D3D10_USAGE_DYNAMIC;
  406. desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
  407. desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
  408. desc.MiscFlags = 0;
  409. g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
  410. }
  411. }
  412. // Create the pixel shader
  413. {
  414. static const char* pixelShader =
  415. "struct PS_INPUT\
  416. {\
  417. float4 pos : SV_POSITION;\
  418. float4 col : COLOR0;\
  419. float2 uv : TEXCOORD0;\
  420. };\
  421. sampler sampler0;\
  422. Texture2D texture0;\
  423. \
  424. float4 main(PS_INPUT input) : SV_Target\
  425. {\
  426. float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
  427. return out_col; \
  428. }";
  429. D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
  430. 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!
  431. return false;
  432. if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK)
  433. return false;
  434. }
  435. // Create the blending setup
  436. {
  437. D3D10_BLEND_DESC desc;
  438. ZeroMemory(&desc, sizeof(desc));
  439. desc.AlphaToCoverageEnable = false;
  440. desc.BlendEnable[0] = true;
  441. desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
  442. desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
  443. desc.BlendOp = D3D10_BLEND_OP_ADD;
  444. desc.SrcBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
  445. desc.DestBlendAlpha = D3D10_BLEND_ZERO;
  446. desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
  447. desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
  448. g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
  449. }
  450. // Create the rasterizer state
  451. {
  452. D3D10_RASTERIZER_DESC desc;
  453. ZeroMemory(&desc, sizeof(desc));
  454. desc.FillMode = D3D10_FILL_SOLID;
  455. desc.CullMode = D3D10_CULL_NONE;
  456. desc.ScissorEnable = true;
  457. desc.DepthClipEnable = true;
  458. g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
  459. }
  460. // Create depth-stencil State
  461. {
  462. D3D10_DEPTH_STENCIL_DESC desc;
  463. ZeroMemory(&desc, sizeof(desc));
  464. desc.DepthEnable = false;
  465. desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
  466. desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
  467. desc.StencilEnable = false;
  468. desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
  469. desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
  470. desc.BackFace = desc.FrontFace;
  471. g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
  472. }
  473. ImGui_ImplDX10_CreateFontsTexture();
  474. return true;
  475. }
  476. void ImGui_ImplDX10_InvalidateDeviceObjects()
  477. {
  478. if (!g_pd3dDevice)
  479. return;
  480. if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
  481. 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.
  482. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  483. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  484. if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
  485. if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
  486. if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
  487. if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
  488. if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
  489. if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
  490. if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
  491. if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
  492. if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
  493. }
  494. bool ImGui_ImplDX10_Init(void* hwnd, ID3D10Device* device)
  495. {
  496. g_hWnd = (HWND)hwnd;
  497. g_pd3dDevice = device;
  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_Space] = VK_SPACE;
  516. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  517. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  518. io.KeyMap[ImGuiKey_A] = 'A';
  519. io.KeyMap[ImGuiKey_C] = 'C';
  520. io.KeyMap[ImGuiKey_V] = 'V';
  521. io.KeyMap[ImGuiKey_X] = 'X';
  522. io.KeyMap[ImGuiKey_Y] = 'Y';
  523. io.KeyMap[ImGuiKey_Z] = 'Z';
  524. 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.
  525. io.ImeWindowHandle = g_hWnd;
  526. return true;
  527. }
  528. void ImGui_ImplDX10_Shutdown()
  529. {
  530. ImGui_ImplDX10_InvalidateDeviceObjects();
  531. g_pd3dDevice = NULL;
  532. g_hWnd = (HWND)0;
  533. }
  534. void ImGui_ImplDX10_NewFrame()
  535. {
  536. if (!g_pFontSampler)
  537. ImGui_ImplDX10_CreateDeviceObjects();
  538. ImGuiIO& io = ImGui::GetIO();
  539. // Setup display size (every frame to accommodate for window resizing)
  540. RECT rect;
  541. GetClientRect(g_hWnd, &rect);
  542. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  543. // Setup time step
  544. INT64 current_time;
  545. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  546. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  547. g_Time = current_time;
  548. // Read keyboard modifiers inputs
  549. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  550. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  551. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  552. io.KeySuper = false;
  553. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  554. // io.MousePos : filled by WM_MOUSEMOVE events
  555. // io.MouseDown : filled by WM_*BUTTON* events
  556. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  557. // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  558. if (io.WantMoveMouse)
  559. {
  560. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  561. ClientToScreen(g_hWnd, &pos);
  562. SetCursorPos(pos.x, pos.y);
  563. }
  564. // Hide OS mouse cursor if ImGui is drawing it
  565. if (io.MouseDrawCursor)
  566. SetCursor(NULL);
  567. // 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.
  568. ImGui::NewFrame();
  569. }