1 // Dear ImGui: standalone example application for DirectX 12
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 // Important: to compile on 32-bit systems, the DirectX12 backend requires code to be compiled with '#define ImTextureID ImU64'.
6 // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
7 // This define is set in the example .vcxproj file and need to be replicated in your app or by adding it to your imconfig.h file.
8 
9 #include "imgui.h"
10 #include "imgui_impl_win32.h"
11 #include "imgui_impl_dx12.h"
12 #include <d3d12.h>
13 #include <dxgi1_4.h>
14 #include <tchar.h>
15 
16 #ifdef _DEBUG
17 #define DX12_ENABLE_DEBUG_LAYER
18 #endif
19 
20 #ifdef DX12_ENABLE_DEBUG_LAYER
21 #include <dxgidebug.h>
22 #pragma comment(lib, "dxguid.lib")
23 #endif
24 
25 struct FrameContext
26 {
27     ID3D12CommandAllocator* CommandAllocator;
28     UINT64                  FenceValue;
29 };
30 
31 // Data
32 static int const                    NUM_FRAMES_IN_FLIGHT = 3;
33 static FrameContext                 g_frameContext[NUM_FRAMES_IN_FLIGHT] = {};
34 static UINT                         g_frameIndex = 0;
35 
36 static int const                    NUM_BACK_BUFFERS = 3;
37 static ID3D12Device*                g_pd3dDevice = NULL;
38 static ID3D12DescriptorHeap*        g_pd3dRtvDescHeap = NULL;
39 static ID3D12DescriptorHeap*        g_pd3dSrvDescHeap = NULL;
40 static ID3D12CommandQueue*          g_pd3dCommandQueue = NULL;
41 static ID3D12GraphicsCommandList*   g_pd3dCommandList = NULL;
42 static ID3D12Fence*                 g_fence = NULL;
43 static HANDLE                       g_fenceEvent = NULL;
44 static UINT64                       g_fenceLastSignaledValue = 0;
45 static IDXGISwapChain3*             g_pSwapChain = NULL;
46 static HANDLE                       g_hSwapChainWaitableObject = NULL;
47 static ID3D12Resource*              g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {};
48 static D3D12_CPU_DESCRIPTOR_HANDLE  g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {};
49 
50 // Forward declarations of helper functions
51 bool CreateDeviceD3D(HWND hWnd);
52 void CleanupDeviceD3D();
53 void CreateRenderTarget();
54 void CleanupRenderTarget();
55 void WaitForLastSubmittedFrame();
56 FrameContext* WaitForNextFrameResources();
57 LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
58 
59 // Main code
main(int,char **)60 int main(int, char**)
61 {
62     // Create application window
63     //ImGui_ImplWin32_EnableDpiAwareness();
64     WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
65     ::RegisterClassEx(&wc);
66     HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX12 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
67 
68     // Initialize Direct3D
69     if (!CreateDeviceD3D(hwnd))
70     {
71         CleanupDeviceD3D();
72         ::UnregisterClass(wc.lpszClassName, wc.hInstance);
73         return 1;
74     }
75 
76     // Show the window
77     ::ShowWindow(hwnd, SW_SHOWDEFAULT);
78     ::UpdateWindow(hwnd);
79 
80     // Setup Dear ImGui context
81     IMGUI_CHECKVERSION();
82     ImGui::CreateContext();
83     ImGuiIO& io = ImGui::GetIO(); (void)io;
84     io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;       // Enable Keyboard Controls
85     //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls
86     io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;           // Enable Docking
87     io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;         // Enable Multi-Viewport / Platform Windows
88     //io.ConfigViewportsNoAutoMerge = true;
89     //io.ConfigViewportsNoTaskBarIcon = true;
90 
91     // Setup Dear ImGui style
92     ImGui::StyleColorsDark();
93     //ImGui::StyleColorsClassic();
94 
95     // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
96     ImGuiStyle& style = ImGui::GetStyle();
97     if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
98     {
99         style.WindowRounding = 0.0f;
100         style.Colors[ImGuiCol_WindowBg].w = 1.0f;
101     }
102 
103     // Setup Platform/Renderer backends
104     ImGui_ImplWin32_Init(hwnd);
105     ImGui_ImplDX12_Init(g_pd3dDevice, NUM_FRAMES_IN_FLIGHT,
106         DXGI_FORMAT_R8G8B8A8_UNORM, g_pd3dSrvDescHeap,
107         g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(),
108         g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart());
109 
110     // Load Fonts
111     // - 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.
112     // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
113     // - 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).
114     // - 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.
115     // - Read 'docs/FONTS.md' for more instructions and details.
116     // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
117     //io.Fonts->AddFontDefault();
118     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
119     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
120     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
121     //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
122     //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
123     //IM_ASSERT(font != NULL);
124 
125     // Our state
126     bool show_demo_window = true;
127     bool show_another_window = false;
128     ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
129 
130     // Main loop
131     bool done = false;
132     while (!done)
133     {
134         // Poll and handle messages (inputs, window resize, etc.)
135         // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
136         // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
137         // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
138         // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
139         MSG msg;
140         while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
141         {
142             ::TranslateMessage(&msg);
143             ::DispatchMessage(&msg);
144             if (msg.message == WM_QUIT)
145                 done = true;
146         }
147         if (done)
148             break;
149 
150         // Start the Dear ImGui frame
151         ImGui_ImplDX12_NewFrame();
152         ImGui_ImplWin32_NewFrame();
153         ImGui::NewFrame();
154 
155         // 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!).
156         if (show_demo_window)
157             ImGui::ShowDemoWindow(&show_demo_window);
158 
159         // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
160         {
161             static float f = 0.0f;
162             static int counter = 0;
163 
164             ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.
165 
166             ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
167             ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
168             ImGui::Checkbox("Another Window", &show_another_window);
169 
170             ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
171             ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
172 
173             if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
174                 counter++;
175             ImGui::SameLine();
176             ImGui::Text("counter = %d", counter);
177 
178             ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
179             ImGui::End();
180         }
181 
182         // 3. Show another simple window.
183         if (show_another_window)
184         {
185             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)
186             ImGui::Text("Hello from another window!");
187             if (ImGui::Button("Close Me"))
188                 show_another_window = false;
189             ImGui::End();
190         }
191 
192         // Rendering
193         ImGui::Render();
194 
195         FrameContext* frameCtx = WaitForNextFrameResources();
196         UINT backBufferIdx = g_pSwapChain->GetCurrentBackBufferIndex();
197         frameCtx->CommandAllocator->Reset();
198 
199         D3D12_RESOURCE_BARRIER barrier = {};
200         barrier.Type                   = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
201         barrier.Flags                  = D3D12_RESOURCE_BARRIER_FLAG_NONE;
202         barrier.Transition.pResource   = g_mainRenderTargetResource[backBufferIdx];
203         barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
204         barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
205         barrier.Transition.StateAfter  = D3D12_RESOURCE_STATE_RENDER_TARGET;
206         g_pd3dCommandList->Reset(frameCtx->CommandAllocator, NULL);
207         g_pd3dCommandList->ResourceBarrier(1, &barrier);
208 
209         // Render Dear ImGui graphics
210         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 };
211         g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], clear_color_with_alpha, 0, NULL);
212         g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, NULL);
213         g_pd3dCommandList->SetDescriptorHeaps(1, &g_pd3dSrvDescHeap);
214         ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), g_pd3dCommandList);
215         barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
216         barrier.Transition.StateAfter  = D3D12_RESOURCE_STATE_PRESENT;
217         g_pd3dCommandList->ResourceBarrier(1, &barrier);
218         g_pd3dCommandList->Close();
219 
220         g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&g_pd3dCommandList);
221 
222         // Update and Render additional Platform Windows
223         if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
224         {
225             ImGui::UpdatePlatformWindows();
226             ImGui::RenderPlatformWindowsDefault(NULL, (void*)g_pd3dCommandList);
227         }
228 
229         g_pSwapChain->Present(1, 0); // Present with vsync
230         //g_pSwapChain->Present(0, 0); // Present without vsync
231 
232         UINT64 fenceValue = g_fenceLastSignaledValue + 1;
233         g_pd3dCommandQueue->Signal(g_fence, fenceValue);
234         g_fenceLastSignaledValue = fenceValue;
235         frameCtx->FenceValue = fenceValue;
236     }
237 
238     WaitForLastSubmittedFrame();
239 
240     // Cleanup
241     ImGui_ImplDX12_Shutdown();
242     ImGui_ImplWin32_Shutdown();
243     ImGui::DestroyContext();
244 
245     CleanupDeviceD3D();
246     ::DestroyWindow(hwnd);
247     ::UnregisterClass(wc.lpszClassName, wc.hInstance);
248 
249     return 0;
250 }
251 
252 // Helper functions
253 
CreateDeviceD3D(HWND hWnd)254 bool CreateDeviceD3D(HWND hWnd)
255 {
256     // Setup swap chain
257     DXGI_SWAP_CHAIN_DESC1 sd;
258     {
259         ZeroMemory(&sd, sizeof(sd));
260         sd.BufferCount = NUM_BACK_BUFFERS;
261         sd.Width = 0;
262         sd.Height = 0;
263         sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
264         sd.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
265         sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
266         sd.SampleDesc.Count = 1;
267         sd.SampleDesc.Quality = 0;
268         sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
269         sd.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
270         sd.Scaling = DXGI_SCALING_STRETCH;
271         sd.Stereo = FALSE;
272     }
273 
274     // [DEBUG] Enable debug interface
275 #ifdef DX12_ENABLE_DEBUG_LAYER
276     ID3D12Debug* pdx12Debug = NULL;
277     if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&pdx12Debug))))
278         pdx12Debug->EnableDebugLayer();
279 #endif
280 
281     // Create device
282     D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
283     if (D3D12CreateDevice(NULL, featureLevel, IID_PPV_ARGS(&g_pd3dDevice)) != S_OK)
284         return false;
285 
286     // [DEBUG] Setup debug interface to break on any warnings/errors
287 #ifdef DX12_ENABLE_DEBUG_LAYER
288     if (pdx12Debug != NULL)
289     {
290         ID3D12InfoQueue* pInfoQueue = NULL;
291         g_pd3dDevice->QueryInterface(IID_PPV_ARGS(&pInfoQueue));
292         pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
293         pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
294         pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, true);
295         pInfoQueue->Release();
296         pdx12Debug->Release();
297     }
298 #endif
299 
300     {
301         D3D12_DESCRIPTOR_HEAP_DESC desc = {};
302         desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
303         desc.NumDescriptors = NUM_BACK_BUFFERS;
304         desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
305         desc.NodeMask = 1;
306         if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dRtvDescHeap)) != S_OK)
307             return false;
308 
309         SIZE_T rtvDescriptorSize = g_pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
310         D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_pd3dRtvDescHeap->GetCPUDescriptorHandleForHeapStart();
311         for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
312         {
313             g_mainRenderTargetDescriptor[i] = rtvHandle;
314             rtvHandle.ptr += rtvDescriptorSize;
315         }
316     }
317 
318     {
319         D3D12_DESCRIPTOR_HEAP_DESC desc = {};
320         desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
321         desc.NumDescriptors = 1;
322         desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
323         if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dSrvDescHeap)) != S_OK)
324             return false;
325     }
326 
327     {
328         D3D12_COMMAND_QUEUE_DESC desc = {};
329         desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
330         desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
331         desc.NodeMask = 1;
332         if (g_pd3dDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(&g_pd3dCommandQueue)) != S_OK)
333             return false;
334     }
335 
336     for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++)
337         if (g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_frameContext[i].CommandAllocator)) != S_OK)
338             return false;
339 
340     if (g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_frameContext[0].CommandAllocator, NULL, IID_PPV_ARGS(&g_pd3dCommandList)) != S_OK ||
341         g_pd3dCommandList->Close() != S_OK)
342         return false;
343 
344     if (g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_fence)) != S_OK)
345         return false;
346 
347     g_fenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
348     if (g_fenceEvent == NULL)
349         return false;
350 
351     {
352         IDXGIFactory4* dxgiFactory = NULL;
353         IDXGISwapChain1* swapChain1 = NULL;
354         if (CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)) != S_OK)
355             return false;
356         if (dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1) != S_OK)
357             return false;
358         if (swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)) != S_OK)
359             return false;
360         swapChain1->Release();
361         dxgiFactory->Release();
362         g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS);
363         g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject();
364     }
365 
366     CreateRenderTarget();
367     return true;
368 }
369 
CleanupDeviceD3D()370 void CleanupDeviceD3D()
371 {
372     CleanupRenderTarget();
373     if (g_pSwapChain) { g_pSwapChain->SetFullscreenState(false, NULL); g_pSwapChain->Release(); g_pSwapChain = NULL; }
374     if (g_hSwapChainWaitableObject != NULL) { CloseHandle(g_hSwapChainWaitableObject); }
375     for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++)
376         if (g_frameContext[i].CommandAllocator) { g_frameContext[i].CommandAllocator->Release(); g_frameContext[i].CommandAllocator = NULL; }
377     if (g_pd3dCommandQueue) { g_pd3dCommandQueue->Release(); g_pd3dCommandQueue = NULL; }
378     if (g_pd3dCommandList) { g_pd3dCommandList->Release(); g_pd3dCommandList = NULL; }
379     if (g_pd3dRtvDescHeap) { g_pd3dRtvDescHeap->Release(); g_pd3dRtvDescHeap = NULL; }
380     if (g_pd3dSrvDescHeap) { g_pd3dSrvDescHeap->Release(); g_pd3dSrvDescHeap = NULL; }
381     if (g_fence) { g_fence->Release(); g_fence = NULL; }
382     if (g_fenceEvent) { CloseHandle(g_fenceEvent); g_fenceEvent = NULL; }
383     if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
384 
385 #ifdef DX12_ENABLE_DEBUG_LAYER
386     IDXGIDebug1* pDebug = NULL;
387     if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&pDebug))))
388     {
389         pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_SUMMARY);
390         pDebug->Release();
391     }
392 #endif
393 }
394 
CreateRenderTarget()395 void CreateRenderTarget()
396 {
397     for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
398     {
399         ID3D12Resource* pBackBuffer = NULL;
400         g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer));
401         g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, g_mainRenderTargetDescriptor[i]);
402         g_mainRenderTargetResource[i] = pBackBuffer;
403     }
404 }
405 
CleanupRenderTarget()406 void CleanupRenderTarget()
407 {
408     WaitForLastSubmittedFrame();
409 
410     for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
411         if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = NULL; }
412 }
413 
WaitForLastSubmittedFrame()414 void WaitForLastSubmittedFrame()
415 {
416     FrameContext* frameCtx = &g_frameContext[g_frameIndex % NUM_FRAMES_IN_FLIGHT];
417 
418     UINT64 fenceValue = frameCtx->FenceValue;
419     if (fenceValue == 0)
420         return; // No fence was signaled
421 
422     frameCtx->FenceValue = 0;
423     if (g_fence->GetCompletedValue() >= fenceValue)
424         return;
425 
426     g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent);
427     WaitForSingleObject(g_fenceEvent, INFINITE);
428 }
429 
WaitForNextFrameResources()430 FrameContext* WaitForNextFrameResources()
431 {
432     UINT nextFrameIndex = g_frameIndex + 1;
433     g_frameIndex = nextFrameIndex;
434 
435     HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, NULL };
436     DWORD numWaitableObjects = 1;
437 
438     FrameContext* frameCtx = &g_frameContext[nextFrameIndex % NUM_FRAMES_IN_FLIGHT];
439     UINT64 fenceValue = frameCtx->FenceValue;
440     if (fenceValue != 0) // means no fence was signaled
441     {
442         frameCtx->FenceValue = 0;
443         g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent);
444         waitableObjects[1] = g_fenceEvent;
445         numWaitableObjects = 2;
446     }
447 
448     WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE);
449 
450     return frameCtx;
451 }
452 
453 // Forward declare message handler from imgui_impl_win32.cpp
454 extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
455 
456 // Win32 message handler
WndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)457 LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
458 {
459     if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
460         return true;
461 
462     switch (msg)
463     {
464     case WM_SIZE:
465         if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
466         {
467             WaitForLastSubmittedFrame();
468             CleanupRenderTarget();
469             HRESULT result = g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT);
470             assert(SUCCEEDED(result) && "Failed to resize swapchain.");
471             CreateRenderTarget();
472         }
473         return 0;
474     case WM_SYSCOMMAND:
475         if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
476             return 0;
477         break;
478     case WM_DESTROY:
479         ::PostQuitMessage(0);
480         return 0;
481     }
482     return ::DefWindowProc(hWnd, msg, wParam, lParam);
483 }
484