main.cpp 20 KB

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