imgui_impl_dx9.cpp 10 KB

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