13.2 KB、295行 生 Blame 履歴
1// Dear ImGui: standalone example application for SDL2 + DirectX 11
2// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
3
4// Learn about Dear ImGui:
5// - FAQ https://dearimgui.com/faq
6// - Getting Started https://dearimgui.com/getting-started
7// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
8// - Introduction, links and more at the top of imgui.cpp
9
10#include "imgui.h"
11#include "imgui_impl_sdl2.h"
12#include "imgui_impl_dx11.h"
13#include <d3d11.h>
14#include <stdio.h>
15#include <SDL.h>
16#include <SDL_syswm.h>
17
18// Data
19static ID3D11Device* g_pd3dDevice = nullptr;
20static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr;
21static IDXGISwapChain* g_pSwapChain = nullptr;
22static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr;
23
24// Forward declarations of helper functions
25bool CreateDeviceD3D(HWND hWnd);
26void CleanupDeviceD3D();
27void CreateRenderTarget();
28void CleanupRenderTarget();
29
30// Main code
31int main(int, char**)
32{
33 // Setup SDL
34 // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems,
35 // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to the latest version of SDL is recommended!)
36#ifdef _WIN32
37 ::SetProcessDPIAware();
38#endif
39 if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0)
40 {
41 printf("Error: %s\n", SDL_GetError());
42 return 1;
43 }
44
45 // From 2.0.18: Enable native IME.
46#ifdef SDL_HINT_IME_SHOW_UI
47 SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
48#endif
49
50 // Setup window
51 float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0);
52 SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
53 SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int)(1280 * main_scale), (int)(800 * main_scale), window_flags);
54 if (window == nullptr)
55 {
56 printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
57 return 1;
58 }
59
60 SDL_SysWMinfo wmInfo;
61 SDL_VERSION(&wmInfo.version);
62 SDL_GetWindowWMInfo(window, &wmInfo);
63 HWND hwnd = (HWND)wmInfo.info.win.window;
64
65 // Initialize Direct3D
66 if (!CreateDeviceD3D(hwnd))
67 {
68 CleanupDeviceD3D();
69 return 1;
70 }
71
72 // Setup Dear ImGui context
73 IMGUI_CHECKVERSION();
74 ImGui::CreateContext();
75 ImGuiIO& io = ImGui::GetIO(); (void)io;
76 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
77 io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
78 io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
79 io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
80 //io.ConfigViewportsNoAutoMerge = true;
81 //io.ConfigViewportsNoTaskBarIcon = true;
82
83 // Setup Dear ImGui style
84 ImGui::StyleColorsDark();
85 //ImGui::StyleColorsLight();
86
87 // Setup scaling
88 ImGuiStyle& style = ImGui::GetStyle();
89 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)
90 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)
91 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.
92 io.ConfigDpiScaleViewports = true; // [Experimental] Scale Dear ImGui and Platform Windows when Monitor DPI changes.
93
94 // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
95 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
96 {
97 style.WindowRounding = 0.0f;
98 style.Colors[ImGuiCol_WindowBg].w = 1.0f;
99 }
100
101 // Setup Platform/Renderer backends
102 ImGui_ImplSDL2_InitForD3D(window);
103 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
104
105 // Load Fonts
106 // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
107 // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
108 // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
109 // - 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).
110 // - Read 'docs/FONTS.md' for more instructions and details.
111 // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
112 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
113 //style.FontSizeBase = 20.0f;
114 //io.Fonts->AddFontDefaultVector();
115 //io.Fonts->AddFontDefaultBitmap();
116 //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
117 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
118 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
119 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
120 //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
121 //IM_ASSERT(font != nullptr);
122
123 // Our state
124 bool show_demo_window = true;
125 bool show_another_window = false;
126 ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
127
128 // Main loop
129 bool done = false;
130 while (!done)
131 {
132 // Poll and handle events (inputs, window resize, etc.)
133 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
134 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
135 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
136 // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
137 SDL_Event event;
138 while (SDL_PollEvent(&event))
139 {
140 ImGui_ImplSDL2_ProcessEvent(&event);
141 if (event.type == SDL_QUIT)
142 done = true;
143 if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
144 done = true;
145 if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window))
146 {
147 // Release all outstanding references to the swap chain's buffers before resizing.
148 CleanupRenderTarget();
149 g_pSwapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
150 CreateRenderTarget();
151 }
152 }
153 if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
154 {
155 SDL_Delay(10);
156 continue;
157 }
158
159 // Start the Dear ImGui frame
160 ImGui_ImplDX11_NewFrame();
161 ImGui_ImplSDL2_NewFrame();
162 ImGui::NewFrame();
163
164 // 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!).
165 if (show_demo_window)
166 ImGui::ShowDemoWindow(&show_demo_window);
167
168 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
169 {
170 static float f = 0.0f;
171 static int counter = 0;
172
173 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
174
175 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
176 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
177 ImGui::Checkbox("Another Window", &show_another_window);
178
179 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
180 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
181
182 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
183 counter++;
184 ImGui::SameLine();
185 ImGui::Text("counter = %d", counter);
186
187 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
188 ImGui::End();
189 }
190
191 // 3. Show another simple window.
192 if (show_another_window)
193 {
194 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)
195 ImGui::Text("Hello from another window!");
196 if (ImGui::Button("Close Me"))
197 show_another_window = false;
198 ImGui::End();
199 }
200
201 // Rendering
202 ImGui::Render();
203 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 };
204 g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr);
205 g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha);
206 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
207
208 // Update and Render additional Platform Windows
209 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
210 {
211 ImGui::UpdatePlatformWindows();
212 ImGui::RenderPlatformWindowsDefault();
213 }
214
215 g_pSwapChain->Present(1, 0); // Present with vsync
216 //g_pSwapChain->Present(0, 0); // Present without vsync
217 }
218
219 // Cleanup
220 ImGui_ImplDX11_Shutdown();
221 ImGui_ImplSDL2_Shutdown();
222 ImGui::DestroyContext();
223
224 CleanupDeviceD3D();
225 SDL_DestroyWindow(window);
226 SDL_Quit();
227
228 return 0;
229}
230
231// Helper functions to use DirectX11
232bool CreateDeviceD3D(HWND hWnd)
233{
234 // Setup swap chain
235 // This is a basic setup. Optimally could use e.g. DXGI_SWAP_EFFECT_FLIP_DISCARD and handle fullscreen mode differently. See #8979 for suggestions.
236 DXGI_SWAP_CHAIN_DESC sd;
237 ZeroMemory(&sd, sizeof(sd));
238 sd.BufferCount = 2;
239 sd.BufferDesc.Width = 0;
240 sd.BufferDesc.Height = 0;
241 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
242 sd.BufferDesc.RefreshRate.Numerator = 60;
243 sd.BufferDesc.RefreshRate.Denominator = 1;
244 sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
245 sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
246 sd.OutputWindow = hWnd;
247 sd.SampleDesc.Count = 1;
248 sd.SampleDesc.Quality = 0;
249 sd.Windowed = TRUE;
250 sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
251
252 UINT createDeviceFlags = 0;
253 //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
254 D3D_FEATURE_LEVEL featureLevel;
255 const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, };
256 HRESULT res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext);
257 if (res == DXGI_ERROR_UNSUPPORTED) // Try high-performance WARP software driver if hardware is not available.
258 res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext);
259 if (res != S_OK)
260 return false;
261
262 // Disable DXGI's default Alt+Enter fullscreen behavior.
263 // - You are free to leave this enabled, but it will not work properly with multiple viewports.
264 // - This must be done for all windows associated to the device. Our DX11 backend does this automatically for secondary viewports that it creates.
265 IDXGIFactory* pSwapChainFactory;
266 if (SUCCEEDED(g_pSwapChain->GetParent(IID_PPV_ARGS(&pSwapChainFactory))))
267 {
268 pSwapChainFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER);
269 pSwapChainFactory->Release();
270 }
271
272 CreateRenderTarget();
273 return true;
274}
275
276void CleanupDeviceD3D()
277{
278 CleanupRenderTarget();
279 if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = nullptr; }
280 if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = nullptr; }
281 if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; }
282}
283
284void CreateRenderTarget()
285{
286 ID3D11Texture2D* pBackBuffer;
287 g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
288 g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &g_mainRenderTargetView);
289 pBackBuffer->Release();
290}
291
292void CleanupRenderTarget()
293{
294 if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; }
295}