13.2 KB、324行 生 Blame 履歴
1// Dear ImGui: standalone example application for Windows API + OpenGL
2
3// Learn about Dear ImGui:
4// - FAQ https://dearimgui.com/faq
5// - Getting Started https://dearimgui.com/getting-started
6// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
7// - Introduction, links and more at the top of imgui.cpp
8
9// This is provided for completeness, however it is strongly recommended you use OpenGL with SDL or GLFW.
10
11#include "imgui.h"
12#include "imgui_impl_opengl3.h"
13#include "imgui_impl_win32.h"
14#ifndef WIN32_LEAN_AND_MEAN
15#define WIN32_LEAN_AND_MEAN
16#endif
17#include <windows.h>
18#include <GL/gl.h>
19#include <tchar.h>
20
21// Data stored per platform window
22struct WGL_WindowData { HDC hDC; };
23
24// Data
25static HGLRC g_hRC;
26static WGL_WindowData g_MainWindow;
27static int g_Width;
28static int g_Height;
29
30// Forward declarations of helper functions
31bool CreateDeviceWGL(HWND hWnd, WGL_WindowData* data);
32void CleanupDeviceWGL(HWND hWnd, WGL_WindowData* data);
33void ResetDeviceWGL();
34LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
35
36// Support function for multi-viewports
37// Unlike most other backend combination, we need specific hooks to combine Win32+OpenGL.
38// We could in theory decide to support Win32-specific code in OpenGL backend via e.g. an hypothetical ImGui_ImplOpenGL3_InitForRawWin32().
39static void Hook_Renderer_CreateWindow(ImGuiViewport* viewport)
40{
41 assert(viewport->RendererUserData == NULL);
42
43 WGL_WindowData* data = IM_NEW(WGL_WindowData);
44 CreateDeviceWGL((HWND)viewport->PlatformHandle, data);
45 viewport->RendererUserData = data;
46}
47
48static void Hook_Renderer_DestroyWindow(ImGuiViewport* viewport)
49{
50 if (viewport->RendererUserData != NULL)
51 {
52 WGL_WindowData* data = (WGL_WindowData*)viewport->RendererUserData;
53 CleanupDeviceWGL((HWND)viewport->PlatformHandle, data);
54 IM_DELETE(data);
55 viewport->RendererUserData = NULL;
56 }
57}
58
59static void Hook_Platform_RenderWindow(ImGuiViewport* viewport, void*)
60{
61 // Activate the platform window DC in the OpenGL rendering context
62 if (WGL_WindowData* data = (WGL_WindowData*)viewport->RendererUserData)
63 wglMakeCurrent(data->hDC, g_hRC);
64}
65
66static void Hook_Renderer_SwapBuffers(ImGuiViewport* viewport, void*)
67{
68 if (WGL_WindowData* data = (WGL_WindowData*)viewport->RendererUserData)
69 ::SwapBuffers(data->hDC);
70}
71
72// Main code
73int main(int, char**)
74{
75 // Make process DPI aware and obtain main monitor scale
76 ImGui_ImplWin32_EnableDpiAwareness();
77 float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY));
78
79 // Create application window
80 WNDCLASSEXW wc = { sizeof(wc), CS_OWNDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr };
81 ::RegisterClassExW(&wc);
82 HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+OpenGL3 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr);
83
84 // Initialize OpenGL
85 if (!CreateDeviceWGL(hwnd, &g_MainWindow))
86 {
87 CleanupDeviceWGL(hwnd, &g_MainWindow);
88 ::DestroyWindow(hwnd);
89 ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
90 return 1;
91 }
92 wglMakeCurrent(g_MainWindow.hDC, g_hRC);
93
94 // Show the window
95 ::ShowWindow(hwnd, SW_SHOWDEFAULT);
96 ::UpdateWindow(hwnd);
97
98 // Setup Dear ImGui context
99 IMGUI_CHECKVERSION();
100 ImGui::CreateContext();
101 ImGuiIO& io = ImGui::GetIO(); (void)io;
102 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
103 io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
104 io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
105 io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
106
107 // Setup Dear ImGui style
108 ImGui::StyleColorsDark();
109 //ImGui::StyleColorsClassic();
110
111 // Setup scaling
112 ImGuiStyle& style = ImGui::GetStyle();
113 style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
114 style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor)
115 io.ConfigDpiScaleFonts = true; // [Experimental] Automatically overwrite style.FontScaleDpi in Begin() when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now.
116 io.ConfigDpiScaleViewports = true; // [Experimental] Scale Dear ImGui and Platform Windows when Monitor DPI changes.
117
118 // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
119 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
120 {
121 style.WindowRounding = 0.0f;
122 style.Colors[ImGuiCol_WindowBg].w = 1.0f;
123 }
124
125 // Setup Platform/Renderer backends
126 ImGui_ImplWin32_InitForOpenGL(hwnd);
127 ImGui_ImplOpenGL3_Init();
128
129 // Win32+GL needs specific hooks for viewport, as there are specific things needed to tie Win32 and GL api.
130 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
131 {
132 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
133 IM_ASSERT(platform_io.Renderer_CreateWindow == NULL);
134 IM_ASSERT(platform_io.Renderer_DestroyWindow == NULL);
135 IM_ASSERT(platform_io.Renderer_SwapBuffers == NULL);
136 IM_ASSERT(platform_io.Platform_RenderWindow == NULL);
137 platform_io.Renderer_CreateWindow = Hook_Renderer_CreateWindow;
138 platform_io.Renderer_DestroyWindow = Hook_Renderer_DestroyWindow;
139 platform_io.Renderer_SwapBuffers = Hook_Renderer_SwapBuffers;
140 platform_io.Platform_RenderWindow = Hook_Platform_RenderWindow;
141 }
142
143 // Load Fonts
144 // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
145 // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
146 // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
147 // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
148 // - Read 'docs/FONTS.md' for more instructions and details.
149 // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
150 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
151 //style.FontSizeBase = 20.0f;
152 //io.Fonts->AddFontDefaultVector();
153 //io.Fonts->AddFontDefaultBitmap();
154 //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
155 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
156 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
157 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
158 //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
159 //IM_ASSERT(font != nullptr);
160
161 // Our state
162 bool show_demo_window = true;
163 bool show_another_window = false;
164 ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
165
166 // Main loop
167 bool done = false;
168 while (!done)
169 {
170 // Poll and handle messages (inputs, window resize, etc.)
171 // See the WndProc() function below for our to dispatch events to the Win32 backend.
172 MSG msg;
173 while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
174 {
175 ::TranslateMessage(&msg);
176 ::DispatchMessage(&msg);
177 if (msg.message == WM_QUIT)
178 done = true;
179 }
180 if (done)
181 break;
182 if (::IsIconic(hwnd))
183 {
184 ::Sleep(10);
185 continue;
186 }
187
188 // Start the Dear ImGui frame
189 ImGui_ImplOpenGL3_NewFrame();
190 ImGui_ImplWin32_NewFrame();
191 ImGui::NewFrame();
192
193 // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
194 if (show_demo_window)
195 ImGui::ShowDemoWindow(&show_demo_window);
196
197 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
198 {
199 static float f = 0.0f;
200 static int counter = 0;
201
202 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
203
204 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
205 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
206 ImGui::Checkbox("Another Window", &show_another_window);
207
208 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
209 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
210
211 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
212 counter++;
213 ImGui::SameLine();
214 ImGui::Text("counter = %d", counter);
215
216 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
217 ImGui::End();
218 }
219
220 // 3. Show another simple window.
221 if (show_another_window)
222 {
223 ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
224 ImGui::Text("Hello from another window!");
225 if (ImGui::Button("Close Me"))
226 show_another_window = false;
227 ImGui::End();
228 }
229
230 // Rendering
231 ImGui::Render();
232 glViewport(0, 0, g_Width, g_Height);
233 glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
234 glClear(GL_COLOR_BUFFER_BIT);
235 ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
236
237 // Update and Render additional Platform Windows
238 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
239 {
240 ImGui::UpdatePlatformWindows();
241 ImGui::RenderPlatformWindowsDefault();
242
243 // Restore the OpenGL rendering context to the main window DC, since platform windows might have changed it.
244 wglMakeCurrent(g_MainWindow.hDC, g_hRC);
245 }
246
247 // Present
248 ::SwapBuffers(g_MainWindow.hDC);
249 }
250
251 ImGui_ImplOpenGL3_Shutdown();
252 ImGui_ImplWin32_Shutdown();
253 ImGui::DestroyContext();
254
255 CleanupDeviceWGL(hwnd, &g_MainWindow);
256 wglDeleteContext(g_hRC);
257 ::DestroyWindow(hwnd);
258 ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
259
260 return 0;
261}
262
263// Helper functions
264bool CreateDeviceWGL(HWND hWnd, WGL_WindowData* data)
265{
266 HDC hDc = ::GetDC(hWnd);
267 PIXELFORMATDESCRIPTOR pfd = { 0 };
268 pfd.nSize = sizeof(pfd);
269 pfd.nVersion = 1;
270 pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
271 pfd.iPixelType = PFD_TYPE_RGBA;
272 pfd.cColorBits = 32;
273
274 const int pf = ::ChoosePixelFormat(hDc, &pfd);
275 if (pf == 0)
276 return false;
277 if (::SetPixelFormat(hDc, pf, &pfd) == FALSE)
278 return false;
279 ::ReleaseDC(hWnd, hDc);
280
281 data->hDC = ::GetDC(hWnd);
282 if (!g_hRC)
283 g_hRC = wglCreateContext(data->hDC);
284 return true;
285}
286
287void CleanupDeviceWGL(HWND hWnd, WGL_WindowData* data)
288{
289 wglMakeCurrent(nullptr, nullptr);
290 ::ReleaseDC(hWnd, data->hDC);
291}
292
293// Forward declare message handler from imgui_impl_win32.cpp
294extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
295
296// Win32 message handler
297// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
298// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
299// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
300// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
301LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
302{
303 if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
304 return true;
305
306 switch (msg)
307 {
308 case WM_SIZE:
309 if (wParam != SIZE_MINIMIZED)
310 {
311 g_Width = LOWORD(lParam);
312 g_Height = HIWORD(lParam);
313 }
314 return 0;
315 case WM_SYSCOMMAND:
316 if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
317 return 0;
318 break;
319 case WM_DESTROY:
320 ::PostQuitMessage(0);
321 return 0;
322 }
323 return ::DefWindowProcW(hWnd, msg, wParam, lParam);
324}