imgui_impl_dx9.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 <d3dx9.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. D3DXVECTOR3 pos;
  25. D3DCOLOR col;
  26. D3DXVECTOR2 uv;
  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. // Create and grow buffers if needed
  35. if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
  36. {
  37. if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
  38. g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
  39. if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  40. return;
  41. }
  42. if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
  43. {
  44. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
  45. g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
  46. 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)
  47. return;
  48. }
  49. // Copy and convert all vertices into a single contiguous buffer
  50. CUSTOMVERTEX* vtx_dst;
  51. ImDrawIdx* idx_dst;
  52. if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  53. return;
  54. if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
  55. return;
  56. for (int n = 0; n < draw_data->CmdListsCount; n++)
  57. {
  58. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  59. const ImDrawVert* vtx_src = &cmd_list->VtxBuffer[0];
  60. for (int i = 0; i < cmd_list->VtxBuffer.size(); i++)
  61. {
  62. vtx_dst->pos.x = vtx_src->pos.x;
  63. vtx_dst->pos.y = vtx_src->pos.y;
  64. vtx_dst->pos.z = 0.0f;
  65. vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  66. vtx_dst->uv.x = vtx_src->uv.x;
  67. vtx_dst->uv.y = vtx_src->uv.y;
  68. vtx_dst++;
  69. vtx_src++;
  70. }
  71. memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
  72. idx_dst += cmd_list->IdxBuffer.size();
  73. }
  74. g_pVB->Unlock();
  75. g_pIB->Unlock();
  76. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
  77. g_pd3dDevice->SetIndices( g_pIB );
  78. g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
  79. // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing
  80. g_pd3dDevice->SetPixelShader( NULL );
  81. g_pd3dDevice->SetVertexShader( NULL );
  82. g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
  83. g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false );
  84. g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false );
  85. g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
  86. g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
  87. g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false );
  88. g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
  89. g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
  90. g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
  91. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
  92. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
  93. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
  94. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
  95. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
  96. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
  97. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
  98. g_pd3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
  99. // Setup orthographic projection matrix
  100. D3DXMATRIXA16 mat;
  101. D3DXMatrixIdentity(&mat);
  102. g_pd3dDevice->SetTransform( D3DTS_WORLD, &mat );
  103. g_pd3dDevice->SetTransform( D3DTS_VIEW, &mat );
  104. D3DXMatrixOrthoOffCenterLH( &mat, 0.5f, ImGui::GetIO().DisplaySize.x+0.5f, ImGui::GetIO().DisplaySize.y+0.5f, 0.5f, -1.0f, +1.0f );
  105. g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &mat );
  106. // Render command lists
  107. int vtx_offset = 0;
  108. int idx_offset = 0;
  109. for (int n = 0; n < draw_data->CmdListsCount; n++)
  110. {
  111. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  112. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
  113. {
  114. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  115. if (pcmd->UserCallback)
  116. {
  117. pcmd->UserCallback(cmd_list, pcmd);
  118. }
  119. else
  120. {
  121. const RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
  122. g_pd3dDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)pcmd->TextureId );
  123. g_pd3dDevice->SetScissorRect( &r );
  124. g_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.size(), idx_offset, pcmd->ElemCount/3 );
  125. }
  126. idx_offset += pcmd->ElemCount;
  127. }
  128. vtx_offset += cmd_list->VtxBuffer.size();
  129. }
  130. }
  131. IMGUI_API LRESULT ImGui_ImplDX9_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
  132. {
  133. ImGuiIO& io = ImGui::GetIO();
  134. switch (msg)
  135. {
  136. case WM_LBUTTONDOWN:
  137. io.MouseDown[0] = true;
  138. return true;
  139. case WM_LBUTTONUP:
  140. io.MouseDown[0] = false;
  141. return true;
  142. case WM_RBUTTONDOWN:
  143. io.MouseDown[1] = true;
  144. return true;
  145. case WM_RBUTTONUP:
  146. io.MouseDown[1] = false;
  147. return true;
  148. case WM_MBUTTONDOWN:
  149. io.MouseDown[2] = true;
  150. return true;
  151. case WM_MBUTTONUP:
  152. io.MouseDown[2] = false;
  153. return true;
  154. case WM_MOUSEWHEEL:
  155. io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
  156. return true;
  157. case WM_MOUSEMOVE:
  158. io.MousePos.x = (signed short)(lParam);
  159. io.MousePos.y = (signed short)(lParam >> 16);
  160. return true;
  161. case WM_KEYDOWN:
  162. if (wParam < 256)
  163. io.KeysDown[wParam] = 1;
  164. return true;
  165. case WM_KEYUP:
  166. if (wParam < 256)
  167. io.KeysDown[wParam] = 0;
  168. return true;
  169. case WM_CHAR:
  170. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  171. if (wParam > 0 && wParam < 0x10000)
  172. io.AddInputCharacter((unsigned short)wParam);
  173. return true;
  174. }
  175. return 0;
  176. }
  177. bool ImGui_ImplDX9_Init(void* hwnd, IDirect3DDevice9* device)
  178. {
  179. g_hWnd = (HWND)hwnd;
  180. g_pd3dDevice = device;
  181. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
  182. return false;
  183. if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
  184. return false;
  185. ImGuiIO& io = ImGui::GetIO();
  186. 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.
  187. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  188. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  189. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  190. io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
  191. io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
  192. io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
  193. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  194. io.KeyMap[ImGuiKey_End] = VK_END;
  195. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  196. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  197. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  198. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  199. io.KeyMap[ImGuiKey_A] = 'A';
  200. io.KeyMap[ImGuiKey_C] = 'C';
  201. io.KeyMap[ImGuiKey_V] = 'V';
  202. io.KeyMap[ImGuiKey_X] = 'X';
  203. io.KeyMap[ImGuiKey_Y] = 'Y';
  204. io.KeyMap[ImGuiKey_Z] = 'Z';
  205. 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.
  206. io.ImeWindowHandle = g_hWnd;
  207. return true;
  208. }
  209. void ImGui_ImplDX9_Shutdown()
  210. {
  211. ImGui_ImplDX9_InvalidateDeviceObjects();
  212. ImGui::Shutdown();
  213. g_pd3dDevice = NULL;
  214. g_hWnd = 0;
  215. }
  216. static bool ImGui_ImplDX9_CreateFontsTexture()
  217. {
  218. // Build texture atlas
  219. ImGuiIO& io = ImGui::GetIO();
  220. unsigned char* pixels;
  221. int width, height, bytes_per_pixel;
  222. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
  223. // Upload texture to graphics system
  224. g_FontTexture = NULL;
  225. if (D3DXCreateTexture(g_pd3dDevice, width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8B8G8R8, D3DPOOL_DEFAULT, &g_FontTexture) < 0)
  226. return false;
  227. D3DLOCKED_RECT tex_locked_rect;
  228. if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
  229. return false;
  230. for (int y = 0; y < height; y++)
  231. memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel));
  232. g_FontTexture->UnlockRect(0);
  233. // Store our identifier
  234. io.Fonts->TexID = (void *)g_FontTexture;
  235. return true;
  236. }
  237. bool ImGui_ImplDX9_CreateDeviceObjects()
  238. {
  239. if (!g_pd3dDevice)
  240. return false;
  241. if (!ImGui_ImplDX9_CreateFontsTexture())
  242. return false;
  243. return true;
  244. }
  245. void ImGui_ImplDX9_InvalidateDeviceObjects()
  246. {
  247. if (!g_pd3dDevice)
  248. return;
  249. if (g_pVB)
  250. {
  251. g_pVB->Release();
  252. g_pVB = NULL;
  253. }
  254. if (g_pIB)
  255. {
  256. g_pIB->Release();
  257. g_pIB = NULL;
  258. }
  259. if (LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)ImGui::GetIO().Fonts->TexID)
  260. {
  261. tex->Release();
  262. ImGui::GetIO().Fonts->TexID = 0;
  263. }
  264. g_FontTexture = NULL;
  265. }
  266. void ImGui_ImplDX9_NewFrame()
  267. {
  268. if (!g_FontTexture)
  269. ImGui_ImplDX9_CreateDeviceObjects();
  270. ImGuiIO& io = ImGui::GetIO();
  271. // Setup display size (every frame to accommodate for window resizing)
  272. RECT rect;
  273. GetClientRect(g_hWnd, &rect);
  274. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  275. // Setup time step
  276. INT64 current_time;
  277. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  278. io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
  279. g_Time = current_time;
  280. // Read keyboard modifiers inputs
  281. io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
  282. io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  283. io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
  284. io.KeySuper = false;
  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. }