imgui_impl_dx10.cpp 29 KB

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