1 // Dear ImGui: standalone example application for DirectX 11
2 // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
3 // Read online: https://github.com/ocornut/imgui/tree/master/docs
4
5 #include "imgui.h"
6 #include "imgui_impl_win32.h"
7 #include "imgui_impl_dx11.h"
8 #include <d3d11.h>
9 #include <tchar.h>
10
11 // Data
12 static ID3D11Device* g_pd3dDevice = NULL;
13 static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
14 static IDXGISwapChain* g_pSwapChain = NULL;
15 static ID3D11RenderTargetView* g_mainRenderTargetView = NULL;
16
17 // Forward declarations of helper functions
18 bool CreateDeviceD3D(HWND hWnd);
19 void CleanupDeviceD3D();
20 void CreateRenderTarget();
21 void CleanupRenderTarget();
22 LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
23
24 // Main code
main(int,char **)25 int main(int, char**)
26 {
27 // Create application window
28 //ImGui_ImplWin32_EnableDpiAwareness();
29 WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
30 ::RegisterClassEx(&wc);
31 HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
32
33 // Initialize Direct3D
34 if (!CreateDeviceD3D(hwnd))
35 {
36 CleanupDeviceD3D();
37 ::UnregisterClass(wc.lpszClassName, wc.hInstance);
38 return 1;
39 }
40
41 // Show the window
42 ::ShowWindow(hwnd, SW_SHOWDEFAULT);
43 ::UpdateWindow(hwnd);
44
45 // Setup Dear ImGui context
46 IMGUI_CHECKVERSION();
47 ImGui::CreateContext();
48 ImGuiIO& io = ImGui::GetIO(); (void)io;
49 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
50 //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
51 io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
52 io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
53 //io.ConfigViewportsNoAutoMerge = true;
54 //io.ConfigViewportsNoTaskBarIcon = true;
55 //io.ConfigViewportsNoDefaultParent = true;
56 //io.ConfigDockingAlwaysTabBar = true;
57 //io.ConfigDockingTransparentPayload = true;
58 //io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleFonts; // FIXME-DPI: Experimental. THIS CURRENTLY DOESN'T WORK AS EXPECTED. DON'T USE IN USER APP!
59 //io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleViewports; // FIXME-DPI: Experimental.
60
61 // Setup Dear ImGui style
62 ImGui::StyleColorsDark();
63 //ImGui::StyleColorsClassic();
64
65 // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
66 ImGuiStyle& style = ImGui::GetStyle();
67 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
68 {
69 style.WindowRounding = 0.0f;
70 style.Colors[ImGuiCol_WindowBg].w = 1.0f;
71 }
72
73 // Setup Platform/Renderer backends
74 ImGui_ImplWin32_Init(hwnd);
75 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
76
77 // Load Fonts
78 // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
79 // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
80 // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
81 // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
82 // - Read 'docs/FONTS.md' for more instructions and details.
83 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
84 //io.Fonts->AddFontDefault();
85 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
86 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
87 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
88 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
89 //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
90 //IM_ASSERT(font != NULL);
91
92 // Our state
93 bool show_demo_window = true;
94 bool show_another_window = false;
95 ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
96
97 // Main loop
98 bool done = false;
99 while (!done)
100 {
101 // Poll and handle messages (inputs, window resize, etc.)
102 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
103 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
104 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
105 // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
106 MSG msg;
107 while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
108 {
109 ::TranslateMessage(&msg);
110 ::DispatchMessage(&msg);
111 if (msg.message == WM_QUIT)
112 done = true;
113 }
114 if (done)
115 break;
116
117 // Start the Dear ImGui frame
118 ImGui_ImplDX11_NewFrame();
119 ImGui_ImplWin32_NewFrame();
120 ImGui::NewFrame();
121
122 // 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!).
123 if (show_demo_window)
124 ImGui::ShowDemoWindow(&show_demo_window);
125
126 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
127 {
128 static float f = 0.0f;
129 static int counter = 0;
130
131 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
132
133 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
134 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
135 ImGui::Checkbox("Another Window", &show_another_window);
136
137 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
138 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
139
140 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
141 counter++;
142 ImGui::SameLine();
143 ImGui::Text("counter = %d", counter);
144
145 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
146 ImGui::End();
147 }
148
149 // 3. Show another simple window.
150 if (show_another_window)
151 {
152 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)
153 ImGui::Text("Hello from another window!");
154 if (ImGui::Button("Close Me"))
155 show_another_window = false;
156 ImGui::End();
157 }
158
159 // Rendering
160 ImGui::Render();
161 const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
162 g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
163 g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha);
164 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
165
166 // Update and Render additional Platform Windows
167 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
168 {
169 ImGui::UpdatePlatformWindows();
170 ImGui::RenderPlatformWindowsDefault();
171 }
172
173 g_pSwapChain->Present(1, 0); // Present with vsync
174 //g_pSwapChain->Present(0, 0); // Present without vsync
175 }
176
177 // Cleanup
178 ImGui_ImplDX11_Shutdown();
179 ImGui_ImplWin32_Shutdown();
180 ImGui::DestroyContext();
181
182 CleanupDeviceD3D();
183 ::DestroyWindow(hwnd);
184 ::UnregisterClass(wc.lpszClassName, wc.hInstance);
185
186 return 0;
187 }
188
189 // Helper functions
190
CreateDeviceD3D(HWND hWnd)191 bool CreateDeviceD3D(HWND hWnd)
192 {
193 // Setup swap chain
194 DXGI_SWAP_CHAIN_DESC sd;
195 ZeroMemory(&sd, sizeof(sd));
196 sd.BufferCount = 2;
197 sd.BufferDesc.Width = 0;
198 sd.BufferDesc.Height = 0;
199 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
200 sd.BufferDesc.RefreshRate.Numerator = 60;
201 sd.BufferDesc.RefreshRate.Denominator = 1;
202 sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
203 sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
204 sd.OutputWindow = hWnd;
205 sd.SampleDesc.Count = 1;
206 sd.SampleDesc.Quality = 0;
207 sd.Windowed = TRUE;
208 sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
209
210 UINT createDeviceFlags = 0;
211 //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
212 D3D_FEATURE_LEVEL featureLevel;
213 const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, };
214 if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
215 return false;
216
217 CreateRenderTarget();
218 return true;
219 }
220
CleanupDeviceD3D()221 void CleanupDeviceD3D()
222 {
223 CleanupRenderTarget();
224 if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
225 if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; }
226 if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
227 }
228
CreateRenderTarget()229 void CreateRenderTarget()
230 {
231 ID3D11Texture2D* pBackBuffer;
232 g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
233 g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView);
234 pBackBuffer->Release();
235 }
236
CleanupRenderTarget()237 void CleanupRenderTarget()
238 {
239 if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; }
240 }
241
242 #ifndef WM_DPICHANGED
243 #define WM_DPICHANGED 0x02E0 // From Windows SDK 8.1+ headers
244 #endif
245
246 // Forward declare message handler from imgui_impl_win32.cpp
247 extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
248
249 // Win32 message handler
WndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)250 LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
251 {
252 if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
253 return true;
254
255 switch (msg)
256 {
257 case WM_SIZE:
258 if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
259 {
260 CleanupRenderTarget();
261 g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
262 CreateRenderTarget();
263 }
264 return 0;
265 case WM_SYSCOMMAND:
266 if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
267 return 0;
268 break;
269 case WM_DESTROY:
270 ::PostQuitMessage(0);
271 return 0;
272 case WM_DPICHANGED:
273 if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
274 {
275 //const int dpi = HIWORD(wParam);
276 //printf("WM_DPICHANGED to %d (%.0f%%)\n", dpi, (float)dpi / 96.0f * 100.0f);
277 const RECT* suggested_rect = (RECT*)lParam;
278 ::SetWindowPos(hWnd, NULL, suggested_rect->left, suggested_rect->top, suggested_rect->right - suggested_rect->left, suggested_rect->bottom - suggested_rect->top, SWP_NOZORDER | SWP_NOACTIVATE);
279 }
280 break;
281 }
282 return ::DefWindowProc(hWnd, msg, wParam, lParam);
283 }
284