imgui_impl_dx9.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. // ImGui Win32 + DirectX9 binding
  2. // In this binding, ImTextureID is used to store a 'LPDIRECT3DTEXTURE9' 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_dx9.h"
  9. // DirectX
  10. #include <d3d9.h>
  11. #define DIRECTINPUT_VERSION 0x0800
  12. #include <dinput.h>
  13. // Data
  14. static HWND g_hWnd = 0;
  15. static INT64 g_Time = 0;
  16. static INT64 g_TicksPerSecond = 0;
  17. static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
  18. static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL;
  19. static LPDIRECT3DINDEXBUFFER9 g_pIB = NULL;
  20. static LPDIRECT3DTEXTURE9 g_FontTexture = NULL;
  21. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  22. struct CUSTOMVERTEX
  23. {
  24. float pos[3];
  25. D3DCOLOR col;
  26. float uv[2];
  27. };
  28. #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
  29. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  30. // If text or lines are blurry when integrating ImGui in your engine:
  31. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  32. void ImGui_ImplDX9_RenderDrawLists(ImDrawData* draw_data)
  33. {
  34. // Avoid rendering when minimized
  35. ImGuiIO& io = ImGui::GetIO();
  36. if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f)
  37. return;
  38. // Create and grow buffers if needed
  39. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  40. {
  41. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  42. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  43. if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  44. return;
  45. }
  46. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  47. {
  48. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  49. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  50. if (g_pd3dDevice->CreateIndexBuffer(g_IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0)
  51. return;
  52. }
  53. // Backup the DX9 state
  54. IDirect3DStateBlock9* d3d9_state_block = NULL;
  55. if (g_pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0)
  56. return;
  57. // Copy and convert all vertices into a single contiguous buffer
  58. CUSTOMVERTEX* vtx_dst;
  59. ImDrawIdx* idx_dst;
  60. if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  61. return;
  62. if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
  63. return;
  64. for (int n = 0; n < draw_data->CmdListsCount; n++)
  65. {
  66. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  67. const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data;
  68. for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
  69. {
  70. vtx_dst->pos[0] = vtx_src->pos.x;
  71. vtx_dst->pos[1] = vtx_src->pos.y;
  72. vtx_dst->pos[2] = 0.0f;
  73. vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  74. vtx_dst->uv[0] = vtx_src->uv.x;
  75. vtx_dst->uv[1] = vtx_src->uv.y;
  76. vtx_dst++;
  77. vtx_src++;
  78. }
  79. memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  80. idx_dst += cmd_list->IdxBuffer.Size;
  81. }
  82. g_pVB->Unlock();
  83. g_pIB->Unlock();
  84. g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));
  85. g_pd3dDevice->SetIndices(g_pIB);
  86. g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
  87. // Setup viewport
  88. D3DVIEWPORT9 vp;
  89. vp.X = vp.Y = 0;
  90. vp.Width = (DWORD)io.DisplaySize.x;
  91. vp.Height = (DWORD)io.DisplaySize.y;
  92. vp.MinZ = 0.0f;
  93. vp.MaxZ = 1.0f;
  94. g_pd3dDevice->SetViewport(&vp);
  95. // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing
  96. g_pd3dDevice->SetPixelShader(NULL);
  97. g_pd3dDevice->SetVertexShader(NULL);
  98. g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
  99. g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, false);
  100. g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
  101. g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
  102. g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false);
  103. g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
  104. g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
  105. g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
  106. g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, true);
  107. g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
  108. g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
  109. g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
  110. g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
  111. g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
  112. g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
  113. g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
  114. g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
  115. // Setup orthographic projection matrix
  116. // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
  117. {
  118. const float L = 0.5f, R = io.DisplaySize.x+0.5f, T = 0.5f, B = io.DisplaySize.y+0.5f;
  119. D3DMATRIX mat_identity = { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } };
  120. D3DMATRIX mat_projection =
  121. {
  122. 2.0f/(R-L), 0.0f, 0.0f, 0.0f,
  123. 0.0f, 2.0f/(T-B), 0.0f, 0.0f,
  124. 0.0f, 0.0f, 0.5f, 0.0f,
  125. (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f,
  126. };
  127. g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity);
  128. g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity);
  129. g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection);
  130. }
  131. // Render command lists
  132. int vtx_offset = 0;
  133. int idx_offset = 0;
  134. for (int n = 0; n < draw_data->CmdListsCount; n++)
  135. {
  136. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  137. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  138. {
  139. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  140. if (pcmd->UserCallback)
  141. {
  142. pcmd->UserCallback(cmd_list, pcmd);
  143. }
  144. else
  145. {
  146. const RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  147. g_pd3dDevice->SetTexture(0, (LPDIRECT3DTEXTURE9)pcmd->TextureId);
  148. g_pd3dDevice->SetScissorRect(&r);
  149. g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, idx_offset, pcmd->ElemCount/3);
  150. }
  151. idx_offset += pcmd->ElemCount;
  152. }
  153. vtx_offset += cmd_list->VtxBuffer.Size;
  154. }
  155. // Restore the DX9 state
  156. d3d9_state_block->Apply();
  157. d3d9_state_block->Release();
  158. }
  159. static bool IsAnyMouseButtonDown()
  160. {
  161. ImGuiIO& io = ImGui::GetIO();
  162. for (int n = 0; n < ARRAYSIZE(io.MouseDown); n++)
  163. if (io.MouseDown[n])
  164. return true;
  165. return false;
  166. }
  167. // We use Win32 SetCapture/ReleaseCapture() API to enable reading the mouse outside our Windows bounds.
  168. IMGUI_API LRESULT ImGui_ImplDX9_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  169. {
  170. ImGuiIO& io = ImGui::GetIO();
  171. switch (msg)
  172. {
  173. case WM_LBUTTONDOWN:
  174. if (!IsAnyMouseButtonDown()) ::SetCapture(hwnd);
  175. io.MouseDown[0] = true;
  176. return true;
  177. case WM_RBUTTONDOWN:
  178. if (!IsAnyMouseButtonDown()) ::SetCapture(hwnd);
  179. io.MouseDown[1] = true;
  180. return true;
  181. case WM_MBUTTONDOWN:
  182. if (!IsAnyMouseButtonDown()) ::SetCapture(hwnd);
  183. io.MouseDown[2] = true;
  184. return true;
  185. case WM_LBUTTONUP:
  186. io.MouseDown[0] = false;
  187. if (!IsAnyMouseButtonDown()) ::ReleaseCapture();
  188. return true;
  189. case WM_RBUTTONUP:
  190. io.MouseDown[1] = false;
  191. if (!IsAnyMouseButtonDown()) ::ReleaseCapture();
  192. return true;
  193. case WM_MBUTTONUP:
  194. io.MouseDown[2] = false;
  195. if (!IsAnyMouseButtonDown()) ::ReleaseCapture();
  196. return true;
  197. case WM_MOUSEWHEEL:
  198. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  199. return true;
  200. case WM_MOUSEMOVE:
  201. io.MousePos.x = (signed short)(lParam);
  202. io.MousePos.y = (signed short)(lParam >> 16);
  203. return true;
  204. case WM_KEYDOWN:
  205. if (wParam < 256)
  206. io.KeysDown[wParam] = 1;
  207. return true;
  208. case WM_KEYUP:
  209. if (wParam < 256)
  210. io.KeysDown[wParam] = 0;
  211. return true;
  212. case WM_CHAR:
  213. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  214. if (wParam > 0 && wParam < 0x10000)
  215. io.AddInputCharacter((unsigned short)wParam);
  216. return true;
  217. }
  218. return 0;
  219. }
  220. bool ImGui_ImplDX9_Init(void* hwnd, IDirect3DDevice9* device)
  221. {
  222. g_hWnd = (HWND)hwnd;
  223. g_pd3dDevice = device;
  224. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  225. return false;
  226. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  227. return false;
  228. ImGuiIO& io = ImGui::GetIO();
  229. 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.
  230. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  231. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  232. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  233. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  234. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  235. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  236. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  237. io.KeyMap[ImGuiKey_End] = VK_END;
  238. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  239. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  240. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  241. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  242. io.KeyMap[ImGuiKey_A] = 'A';
  243. io.KeyMap[ImGuiKey_C] = 'C';
  244. io.KeyMap[ImGuiKey_V] = 'V';
  245. io.KeyMap[ImGuiKey_X] = 'X';
  246. io.KeyMap[ImGuiKey_Y] = 'Y';
  247. io.KeyMap[ImGuiKey_Z] = 'Z';
  248. io.RenderDrawListsFn = ImGui_ImplDX9_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  249. io.ImeWindowHandle = g_hWnd;
  250. return true;
  251. }
  252. void ImGui_ImplDX9_Shutdown()
  253. {
  254. ImGui_ImplDX9_InvalidateDeviceObjects();
  255. ImGui::Shutdown();
  256. g_pd3dDevice = NULL;
  257. g_hWnd = 0;
  258. }
  259. static bool ImGui_ImplDX9_CreateFontsTexture()
  260. {
  261. // Build texture atlas
  262. ImGuiIO& io = ImGui::GetIO();
  263. unsigned char* pixels;
  264. int width, height, bytes_per_pixel;
  265. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
  266. // Upload texture to graphics system
  267. g_FontTexture = NULL;
  268. if (g_pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_FontTexture, NULL) < 0)
  269. return false;
  270. D3DLOCKED_RECT tex_locked_rect;
  271. if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
  272. return false;
  273. for (int y = 0; y < height; y++)
  274. memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
  275. g_FontTexture->UnlockRect(0);
  276. // Store our identifier
  277. io.Fonts->TexID = (void *)g_FontTexture;
  278. return true;
  279. }
  280. bool ImGui_ImplDX9_CreateDeviceObjects()
  281. {
  282. if (!g_pd3dDevice)
  283. return false;
  284. if (!ImGui_ImplDX9_CreateFontsTexture())
  285. return false;
  286. return true;
  287. }
  288. void ImGui_ImplDX9_InvalidateDeviceObjects()
  289. {
  290. if (!g_pd3dDevice)
  291. return;
  292. if (g_pVB)
  293. {
  294. g_pVB->Release();
  295. g_pVB = NULL;
  296. }
  297. if (g_pIB)
  298. {
  299. g_pIB->Release();
  300. g_pIB = NULL;
  301. }
  302. // At this point note that we set ImGui::GetIO().Fonts->TexID to be == g_FontTexture, so clear both.
  303. ImGuiIO& io = ImGui::GetIO();
  304. IM_ASSERT(g_FontTexture == io.Fonts->TexID);
  305. if (g_FontTexture)
  306. g_FontTexture->Release();
  307. g_FontTexture = NULL;
  308. io.Fonts->TexID = NULL;
  309. }
  310. void ImGui_ImplDX9_NewFrame()
  311. {
  312. if (!g_FontTexture)
  313. ImGui_ImplDX9_CreateDeviceObjects();
  314. ImGuiIO& io = ImGui::GetIO();
  315. // Setup display size (every frame to accommodate for window resizing)
  316. RECT rect;
  317. GetClientRect(g_hWnd, &rect);
  318. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  319. // Setup time step
  320. INT64 current_time;
  321. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  322. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  323. g_Time = current_time;
  324. // Read keyboard modifiers inputs
  325. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  326. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  327. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  328. io.KeySuper = false;
  329. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  330. // io.MousePos : filled by WM_MOUSEMOVE events
  331. // io.MouseDown : filled by WM_*BUTTON* events
  332. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  333. // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  334. if (io.WantMoveMouse)
  335. {
  336. POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
  337. ClientToScreen(g_hWnd, &pos);
  338. SetCursorPos(pos.x, pos.y);
  339. }
  340. // Hide OS mouse cursor if ImGui is drawing it
  341. if (io.MouseDrawCursor)
  342. SetCursor(NULL);
  343. // Start the frame
  344. ImGui::NewFrame();
  345. }