main.cpp 23 KB

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