imgui_impl_dx9.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // ImGui Win32 + DirectX9 binding
  2. // You can copy and use unmodified imgui_impl_* files in your project.
  3. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  4. // See main.cpp for an example of using this.
  5. // https://github.com/ocornut/imgui
  6. #include <imgui.h>
  7. #include "imgui_impl_dx9.h"
  8. // DirectX
  9. #include <d3dx9.h>
  10. #define DIRECTINPUT_VERSION 0x0800
  11. #include <dinput.h>
  12. // Data
  13. static HWND g_hWnd = 0;
  14. static INT64 g_Time = 0;
  15. static INT64 g_TicksPerSecond = 0;
  16. static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
  17. static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL;
  18. static LPDIRECT3DINDEXBUFFER9 g_pIB = NULL;
  19. static LPDIRECT3DTEXTURE9 g_FontTexture = NULL;
  20. static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
  21. struct CUSTOMVERTEX
  22. {
  23. D3DXVECTOR3 pos;
  24. D3DCOLOR col;
  25. D3DXVECTOR2 uv;
  26. };
  27. #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
  28. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  29. // If text or lines are blurry when integrating ImGui in your engine:
  30. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  31. void ImGui_ImplDX9_RenderDrawLists(ImDrawData* draw_data)
  32. {
  33. // Create and grow buffers if needed
  34. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  35. {
  36. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  37. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  38. if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  39. return;
  40. }
  41. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  42. {
  43. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  44. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  45. 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)
  46. return;
  47. }
  48. // Copy and convert all vertices into a single contiguous buffer
  49. CUSTOMVERTEX* vtx_dst;
  50. ImDrawIdx* idx_dst;
  51. if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  52. return;
  53. if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
  54. return;
  55. for (int n = 0; n < draw_data->CmdListsCount; n++)
  56. {
  57. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  58. const ImDrawVert* vtx_src = &cmd_list->VtxBuffer[0];
  59. for (int i = 0; i < cmd_list->VtxBuffer.size(); i++)
  60. {
  61. vtx_dst->pos.x = vtx_src->pos.x;
  62. vtx_dst->pos.y = vtx_src->pos.y;
  63. vtx_dst->pos.z = 0.0f;
  64. vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  65. vtx_dst->uv.x = vtx_src->uv.x;
  66. vtx_dst->uv.y = vtx_src->uv.y;
  67. vtx_dst++;
  68. vtx_src++;
  69. }
  70. memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
  71. idx_dst += cmd_list->IdxBuffer.size();
  72. }
  73. g_pVB->Unlock();
  74. g_pIB->Unlock();
  75. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
  76. g_pd3dDevice->SetIndices( g_pIB );
  77. g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
  78. // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing
  79. g_pd3dDevice->SetPixelShader( NULL );
  80. g_pd3dDevice->SetVertexShader( NULL );
  81. g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
  82. g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false );
  83. g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false );
  84. g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
  85. g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
  86. g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false );
  87. g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
  88. g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
  89. g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
  90. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
  91. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE );
  92. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
  93. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
  94. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
  95. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
  96. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
  97. // Setup orthographic projection matrix
  98. D3DXMATRIXA16 mat;
  99. D3DXMatrixIdentity(&mat);
  100. g_pd3dDevice->SetTransform( D3DTS_WORLD, &mat );
  101. g_pd3dDevice->SetTransform( D3DTS_VIEW, &mat );
  102. D3DXMatrixOrthoOffCenterLH( &mat, 0.5f, ImGui::GetIO().DisplaySize.x+0.5f, ImGui::GetIO().DisplaySize.y+0.5f, 0.5f, -1.0f, +1.0f );
  103. g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &mat );
  104. // Render command lists
  105. int vtx_offset = 0;
  106. int idx_offset = 0;
  107. for (int n = 0; n < draw_data->CmdListsCount; n++)
  108. {
  109. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  110. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
  111. {
  112. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  113. if (pcmd->UserCallback)
  114. {
  115. pcmd->UserCallback(cmd_list, pcmd);
  116. }
  117. else
  118. {
  119. const RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  120. g_pd3dDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)pcmd->TextureId );
  121. g_pd3dDevice->SetScissorRect( &r );
  122. g_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.size(), idx_offset, pcmd->ElemCount/3 );
  123. }
  124. idx_offset += pcmd->ElemCount;
  125. }
  126. vtx_offset += cmd_list->VtxBuffer.size();
  127. }
  128. }
  129. IMGUI_API LRESULT ImGui_ImplDX9_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
  130. {
  131. ImGuiIO& io = ImGui::GetIO();
  132. switch (msg)
  133. {
  134. case WM_LBUTTONDOWN:
  135. io.MouseDown[0] = true;
  136. return true;
  137. case WM_LBUTTONUP:
  138. io.MouseDown[0] = false;
  139. return true;
  140. case WM_RBUTTONDOWN:
  141. io.MouseDown[1] = true;
  142. return true;
  143. case WM_RBUTTONUP:
  144. io.MouseDown[1] = false;
  145. return true;
  146. case WM_MBUTTONDOWN:
  147. io.MouseDown[2] = true;
  148. return true;
  149. case WM_MBUTTONUP:
  150. io.MouseDown[2] = false;
  151. return true;
  152. case WM_MOUSEWHEEL:
  153. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  154. return true;
  155. case WM_MOUSEMOVE:
  156. io.MousePos.x = (signed short)(lParam);
  157. io.MousePos.y = (signed short)(lParam >> 16);
  158. return true;
  159. case WM_KEYDOWN:
  160. if (wParam < 256)
  161. io.KeysDown[wParam] = 1;
  162. return true;
  163. case WM_KEYUP:
  164. if (wParam < 256)
  165. io.KeysDown[wParam] = 0;
  166. return true;
  167. case WM_CHAR:
  168. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  169. if (wParam > 0 && wParam < 0x10000)
  170. io.AddInputCharacter((unsigned short)wParam);
  171. return true;
  172. }
  173. return 0;
  174. }
  175. bool ImGui_ImplDX9_Init(void* hwnd, IDirect3DDevice9* device)
  176. {
  177. g_hWnd = (HWND)hwnd;
  178. g_pd3dDevice = device;
  179. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  180. return false;
  181. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  182. return false;
  183. ImGuiIO& io = ImGui::GetIO();
  184. 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.
  185. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  186. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  187. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  188. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  189. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  190. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  191. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  192. io.KeyMap[ImGuiKey_End] = VK_END;
  193. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  194. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  195. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  196. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  197. io.KeyMap[ImGuiKey_A] = 'A';
  198. io.KeyMap[ImGuiKey_C] = 'C';
  199. io.KeyMap[ImGuiKey_V] = 'V';
  200. io.KeyMap[ImGuiKey_X] = 'X';
  201. io.KeyMap[ImGuiKey_Y] = 'Y';
  202. io.KeyMap[ImGuiKey_Z] = 'Z';
  203. 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.
  204. io.ImeWindowHandle = g_hWnd;
  205. return true;
  206. }
  207. void ImGui_ImplDX9_Shutdown()
  208. {
  209. ImGui_ImplDX9_InvalidateDeviceObjects();
  210. ImGui::Shutdown();
  211. g_pd3dDevice = NULL;
  212. g_hWnd = 0;
  213. }
  214. static bool ImGui_ImplDX9_CreateFontsTexture()
  215. {
  216. ImGuiIO& io = ImGui::GetIO();
  217. // Build
  218. unsigned char* pixels;
  219. int width, height, bytes_per_pixel;
  220. io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height, &bytes_per_pixel);
  221. // Create DX9 texture
  222. g_FontTexture = NULL;
  223. if (D3DXCreateTexture(g_pd3dDevice, width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_DEFAULT, &g_FontTexture) < 0)
  224. return false;
  225. D3DLOCKED_RECT tex_locked_rect;
  226. if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
  227. return false;
  228. for (int y = 0; y < height; y++)
  229. memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
  230. g_FontTexture->UnlockRect(0);
  231. // Store our identifier
  232. io.Fonts->TexID = (void *)g_FontTexture;
  233. // Cleanup (don't clear the input data if you want to append new fonts later)
  234. io.Fonts->ClearInputData();
  235. io.Fonts->ClearTexData();
  236. return true;
  237. }
  238. bool ImGui_ImplDX9_CreateDeviceObjects()
  239. {
  240. if (!g_pd3dDevice)
  241. return false;
  242. if (!ImGui_ImplDX9_CreateFontsTexture())
  243. return false;
  244. return true;
  245. }
  246. void ImGui_ImplDX9_InvalidateDeviceObjects()
  247. {
  248. if (!g_pd3dDevice)
  249. return;
  250. if (g_pVB)
  251. {
  252. g_pVB->Release();
  253. g_pVB = NULL;
  254. }
  255. if (g_pIB)
  256. {
  257. g_pIB->Release();
  258. g_pIB = NULL;
  259. }
  260. if (LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)ImGui::GetIO().Fonts->TexID)
  261. {
  262. tex->Release();
  263. ImGui::GetIO().Fonts->TexID = 0;
  264. }
  265. g_FontTexture = NULL;
  266. }
  267. void ImGui_ImplDX9_NewFrame()
  268. {
  269. if (!g_FontTexture)
  270. ImGui_ImplDX9_CreateDeviceObjects();
  271. ImGuiIO& io = ImGui::GetIO();
  272. // Setup display size (every frame to accommodate for window resizing)
  273. RECT rect;
  274. GetClientRect(g_hWnd, &rect);
  275. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  276. // Setup time step
  277. INT64 current_time;
  278. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  279. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  280. g_Time = current_time;
  281. // Read keyboard modifiers inputs
  282. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  283. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  284. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  285. // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
  286. // io.MousePos : filled by WM_MOUSEMOVE events
  287. // io.MouseDown : filled by WM_*BUTTON* events
  288. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  289. // Hide OS mouse cursor if ImGui is drawing it
  290. SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW));
  291. // Start the frame
  292. ImGui::NewFrame();
  293. }