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