2
0

main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. #include <windows.h>
  2. #include <mmsystem.h>
  3. #include <d3dx9.h>
  4. #define DIRECTINPUT_VERSION 0x0800
  5. #include <dinput.h>
  6. #include "../../imgui.h"
  7. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strdup
  8. static HWND hWnd;
  9. static LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice
  10. static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device
  11. static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices
  12. static LPDIRECT3DTEXTURE9 g_pTexture = NULL; // Our texture
  13. struct CUSTOMVERTEX
  14. {
  15. D3DXVECTOR3 position;
  16. D3DCOLOR color;
  17. float tu, tv;
  18. };
  19. #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
  20. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  21. {
  22. size_t total_vtx_count = 0;
  23. for (int n = 0; n < cmd_lists_count; n++)
  24. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  25. if (total_vtx_count == 0)
  26. return;
  27. ImVector<ImVec4> clip_rect_stack;
  28. clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999));
  29. // Setup orthographic projection
  30. // Set up world matrix
  31. D3DXMATRIXA16 mat;
  32. D3DXMatrixIdentity(&mat);
  33. g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat);
  34. g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat);
  35. D3DXMatrixOrthoOffCenterLH(&mat, 0.0f, ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y, 0.0f, -1.0f, +1.0f);
  36. g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat);
  37. D3DSURFACE_DESC texture_desc;
  38. g_pTexture->GetLevelDesc(0, &texture_desc);
  39. // Fill the vertex buffer
  40. CUSTOMVERTEX* vtx_dst;
  41. if (g_pVB->Lock(0, total_vtx_count, (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
  42. return;
  43. for (int n = 0; n < cmd_lists_count; n++)
  44. {
  45. const ImDrawList* cmd_list = cmd_lists[n];
  46. if (cmd_list->commands.empty() || cmd_list->vtx_buffer.empty())
  47. continue;
  48. const ImDrawVert* vtx_src = &cmd_list->vtx_buffer[0];
  49. for (size_t i = 0; i < cmd_list->vtx_buffer.size(); i++)
  50. {
  51. vtx_dst->position.x = vtx_src->pos.x;
  52. vtx_dst->position.y = vtx_src->pos.y;
  53. vtx_dst->position.z = 0.0f;
  54. vtx_dst->color = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000)>>16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9
  55. vtx_dst->tu = vtx_src->uv.x;
  56. vtx_dst->tv = vtx_src->uv.y;
  57. vtx_dst++;
  58. vtx_src++;
  59. }
  60. }
  61. g_pVB->Unlock();
  62. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
  63. g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
  64. // Setup render state: alpha-blending enabled, no face culling, no depth testing
  65. g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
  66. g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, false );
  67. g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, false );
  68. g_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true );
  69. g_pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD );
  70. g_pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, false );
  71. g_pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
  72. g_pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
  73. g_pd3dDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, true );
  74. // Setup texture
  75. g_pd3dDevice->SetTexture( 0, g_pTexture );
  76. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
  77. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
  78. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
  79. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
  80. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
  81. g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
  82. int vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those
  83. bool clip_rect_dirty = true;
  84. for (int n = 0; n < cmd_lists_count; n++)
  85. {
  86. const ImDrawList* cmd_list = cmd_lists[n];
  87. if (cmd_list->commands.empty() || cmd_list->vtx_buffer.empty())
  88. continue;
  89. const ImDrawCmd* pcmd = &cmd_list->commands.front();
  90. const ImDrawCmd* pcmd_end = &cmd_list->commands.back();
  91. int clip_rect_buf_consumed = 0; // offset in cmd_list->clip_rect_buffer. each PushClipRect command consume 1 of those.
  92. while (pcmd <= pcmd_end)
  93. {
  94. const ImDrawCmd& cmd = *pcmd++;
  95. switch (cmd.cmd_type)
  96. {
  97. case ImDrawCmdType_DrawTriangleList:
  98. if (clip_rect_dirty)
  99. {
  100. const ImVec4& clip_rect = clip_rect_stack.back();
  101. const RECT r = { (LONG)clip_rect.x, (LONG)clip_rect.y, (LONG)clip_rect.z, (LONG)clip_rect.w };
  102. g_pd3dDevice->SetScissorRect(&r);
  103. clip_rect_dirty = false;
  104. }
  105. g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vtx_consumed, cmd.vtx_count/3);
  106. vtx_consumed += cmd.vtx_count;
  107. break;
  108. case ImDrawCmdType_PushClipRect:
  109. clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_consumed++]);
  110. clip_rect_dirty = true;
  111. break;
  112. case ImDrawCmdType_PopClipRect:
  113. clip_rect_stack.pop_back();
  114. clip_rect_dirty = true;
  115. break;
  116. }
  117. }
  118. }
  119. }
  120. // Get text data in Win32 clipboard
  121. static const char* ImImpl_GetClipboardTextFn()
  122. {
  123. static char* buf_local = NULL;
  124. if (buf_local)
  125. {
  126. free(buf_local);
  127. buf_local = NULL;
  128. }
  129. if (!OpenClipboard(NULL))
  130. return NULL;
  131. HANDLE buf_handle = GetClipboardData(CF_TEXT);
  132. if (buf_handle == NULL)
  133. return NULL;
  134. if (char* buf_global = (char*)GlobalLock(buf_handle))
  135. buf_local = strdup(buf_global);
  136. GlobalUnlock(buf_handle);
  137. CloseClipboard();
  138. return buf_local;
  139. }
  140. // Set text data in Win32 clipboard
  141. static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end)
  142. {
  143. if (!OpenClipboard(NULL))
  144. return;
  145. if (!text_end)
  146. text_end = text + strlen(text);
  147. const int buf_length = (text_end - text) + 1;
  148. HGLOBAL buf_handle = GlobalAlloc(GMEM_MOVEABLE, buf_length * sizeof(char));
  149. if (buf_handle == NULL)
  150. return;
  151. char* buf_global = (char *)GlobalLock(buf_handle);
  152. memcpy(buf_global, text, text_end - text);
  153. buf_global[text_end - text] = 0;
  154. GlobalUnlock(buf_handle);
  155. EmptyClipboard();
  156. SetClipboardData(CF_TEXT, buf_handle);
  157. CloseClipboard();
  158. }
  159. HRESULT InitD3D(HWND hWnd)
  160. {
  161. if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
  162. return E_FAIL;
  163. D3DPRESENT_PARAMETERS d3dpp;
  164. ZeroMemory(&d3dpp, sizeof(d3dpp));
  165. d3dpp.Windowed = TRUE;
  166. d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  167. d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
  168. d3dpp.EnableAutoDepthStencil = TRUE;
  169. d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  170. d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  171. // Create the D3DDevice
  172. if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice) < 0)
  173. return E_FAIL;
  174. // Create the vertex buffer.
  175. if (g_pd3dDevice->CreateVertexBuffer(10000 * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0)
  176. return E_FAIL;
  177. // Load font texture
  178. const void* png_data;
  179. unsigned int png_size;
  180. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  181. if (D3DXCreateTextureFromFileInMemory(g_pd3dDevice, png_data, png_size, &g_pTexture) < 0)
  182. return E_FAIL;
  183. return S_OK;
  184. }
  185. void Cleanup()
  186. {
  187. if (g_pTexture != NULL)
  188. g_pTexture->Release();
  189. if (g_pd3dDevice != NULL)
  190. g_pd3dDevice->Release();
  191. if (g_pD3D != NULL)
  192. g_pD3D->Release();
  193. }
  194. LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  195. {
  196. ImGuiIO& io = ImGui::GetIO();
  197. switch (msg)
  198. {
  199. case WM_LBUTTONDOWN:
  200. io.MouseDown[0] = true;
  201. return true;
  202. case WM_LBUTTONUP:
  203. io.MouseDown[0] = false;
  204. return true;
  205. case WM_RBUTTONDOWN:
  206. io.MouseDown[1] = true;
  207. return true;
  208. case WM_RBUTTONUP:
  209. io.MouseDown[1] = false;
  210. return true;
  211. case WM_MOUSEWHEEL:
  212. io.MouseWheel = GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1 : -1;
  213. return true;
  214. case WM_MOUSEMOVE:
  215. io.MousePos.x = (signed short)(lParam);
  216. io.MousePos.y = (signed short)(lParam >> 16);
  217. return true;
  218. case WM_CHAR:
  219. // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
  220. if (wParam > 1 && wParam < 256)
  221. io.AddInputCharacter((char)wParam);
  222. return true;
  223. case WM_DESTROY:
  224. {
  225. Cleanup();
  226. PostQuitMessage(0);
  227. return 0;
  228. }
  229. }
  230. return DefWindowProc(hWnd, msg, wParam, lParam);
  231. }
  232. void InitImGui()
  233. {
  234. RECT rect;
  235. GetClientRect(hWnd, &rect);
  236. ImGuiIO& io = ImGui::GetIO();
  237. io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
  238. io.DeltaTime = 1.0f/60.0f;
  239. io.KeyMap[ImGuiKey_Tab] = VK_TAB;
  240. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
  241. io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
  242. io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
  243. io.KeyMap[ImGuiKey_DownArrow] = VK_UP;
  244. io.KeyMap[ImGuiKey_Home] = VK_HOME;
  245. io.KeyMap[ImGuiKey_End] = VK_END;
  246. io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
  247. io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
  248. io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
  249. io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
  250. io.KeyMap[ImGuiKey_A] = 'A';
  251. io.KeyMap[ImGuiKey_C] = 'C';
  252. io.KeyMap[ImGuiKey_V] = 'V';
  253. io.KeyMap[ImGuiKey_X] = 'X';
  254. io.KeyMap[ImGuiKey_Y] = 'Y';
  255. io.KeyMap[ImGuiKey_Z] = 'Z';
  256. io.PixelCenterOffset = 0.0f;
  257. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  258. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  259. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  260. }
  261. int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, LPWSTR, int)
  262. {
  263. // Register the window class
  264. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, L"ImGui Example", NULL };
  265. RegisterClassEx(&wc);
  266. // Create the application's window
  267. hWnd = CreateWindow(L"ImGui Example", L"ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
  268. INT64 ticks_per_second, time;
  269. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  270. return 1;
  271. if (!QueryPerformanceCounter((LARGE_INTEGER *)&time))
  272. return 1;
  273. // Initialize Direct3D
  274. if (InitD3D(hWnd) >= 0)
  275. {
  276. // Show the window
  277. ShowWindow(hWnd, SW_SHOWDEFAULT);
  278. UpdateWindow(hWnd);
  279. InitImGui();
  280. // Enter the message loop
  281. MSG msg;
  282. ZeroMemory(&msg, sizeof(msg));
  283. while (msg.message != WM_QUIT)
  284. {
  285. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
  286. {
  287. TranslateMessage(&msg);
  288. DispatchMessage(&msg);
  289. continue;
  290. }
  291. // 1) ImGui start frame, setup time delta & inputs
  292. ImGuiIO& io = ImGui::GetIO();
  293. INT64 current_time;
  294. QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
  295. io.DeltaTime = (float)(current_time - time) / ticks_per_second;
  296. time = current_time;
  297. BYTE keystate[256];
  298. GetKeyboardState(keystate);
  299. for (int i = 0; i < 256; i++)
  300. io.KeysDown[i] = (keystate[i] & 0x80) != 0;
  301. io.KeyCtrl = (keystate[VK_CONTROL] & 0x80) != 0;
  302. io.KeyShift = (keystate[VK_SHIFT] & 0x80) != 0;
  303. // io.MousePos : filled by WM_MOUSEMOVE event
  304. // io.MouseDown : filled by WM_*BUTTON* events
  305. // io.MouseWheel : filled by WM_MOUSEWHEEL events
  306. ImGui::NewFrame();
  307. // 2) ImGui usage
  308. static bool show_test_window = true;
  309. static bool show_another_window = false;
  310. static float f;
  311. ImGui::Text("Hello, world!");
  312. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  313. show_test_window ^= ImGui::Button("Test Window");
  314. show_another_window ^= ImGui::Button("Another Window");
  315. // Calculate and show framerate
  316. static float ms_per_frame[120] = { 0 };
  317. static int ms_per_frame_idx = 0;
  318. static float ms_per_frame_accum = 0.0f;
  319. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  320. ms_per_frame[ms_per_frame_idx] = io.DeltaTime * 1000.0f;
  321. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  322. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  323. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  324. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  325. if (show_test_window)
  326. {
  327. // More example code in ShowTestWindow()
  328. ImGui::SetNewWindowDefaultPos(ImVec2(650, 20)); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
  329. ImGui::ShowTestWindow(&show_test_window);
  330. }
  331. if (show_another_window)
  332. {
  333. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  334. ImGui::Text("Hello");
  335. ImGui::End();
  336. }
  337. // 3) Render
  338. g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
  339. g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
  340. g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
  341. g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(204, 153, 153), 1.0f, 0); // Clear the backbuffer and the zbuffer
  342. if (g_pd3dDevice->BeginScene() >= 0)
  343. {
  344. ImGui::Render();
  345. g_pd3dDevice->EndScene();
  346. }
  347. g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
  348. }
  349. ImGui::Shutdown();
  350. }
  351. if (g_pVB)
  352. g_pVB->Release();
  353. UnregisterClass(L"ImGui Example", wc.hInstance);
  354. return 0;
  355. }