main.cpp 20 KB

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