main.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. // Dear ImGui: standalone example application for Windows API + 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_5.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_SwapChainTearingSupport = false;
  86. static bool g_SwapChainOccluded = false;
  87. static HANDLE g_hSwapChainWaitableObject = nullptr;
  88. static ID3D12Resource* g_mainRenderTargetResource[APP_NUM_BACK_BUFFERS] = {};
  89. static D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[APP_NUM_BACK_BUFFERS] = {};
  90. // Forward declarations of helper functions
  91. bool CreateDeviceD3D(HWND hWnd);
  92. void CleanupDeviceD3D();
  93. void CreateRenderTarget();
  94. void CleanupRenderTarget();
  95. void WaitForPendingOperations();
  96. FrameContext* WaitForNextFrameContext();
  97. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  98. // Main code
  99. int main(int, char**)
  100. {
  101. // Make process DPI aware and obtain main monitor scale
  102. ImGui_ImplWin32_EnableDpiAwareness();
  103. float main_scale = ImGui_ImplWin32_GetDpiScaleForMonitor(::MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY));
  104. // Create application window
  105. WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr };
  106. ::RegisterClassExW(&wc);
  107. HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX12 Example", WS_OVERLAPPEDWINDOW, 100, 100, (int)(1280 * main_scale), (int)(800 * main_scale), nullptr, nullptr, wc.hInstance, nullptr);
  108. // Initialize Direct3D
  109. if (!CreateDeviceD3D(hwnd))
  110. {
  111. CleanupDeviceD3D();
  112. ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
  113. return 1;
  114. }
  115. // Show the window
  116. ::ShowWindow(hwnd, SW_SHOWDEFAULT);
  117. ::UpdateWindow(hwnd);
  118. // Setup Dear ImGui context
  119. IMGUI_CHECKVERSION();
  120. ImGui::CreateContext();
  121. ImGuiIO& io = ImGui::GetIO(); (void)io;
  122. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  123. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  124. // Setup Dear ImGui style
  125. ImGui::StyleColorsDark();
  126. //ImGui::StyleColorsLight();
  127. // Setup scaling
  128. ImGuiStyle& style = ImGui::GetStyle();
  129. 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)
  130. 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)
  131. // Setup Platform/Renderer backends
  132. ImGui_ImplWin32_Init(hwnd);
  133. ImGui_ImplDX12_InitInfo init_info = {};
  134. init_info.Device = g_pd3dDevice;
  135. init_info.CommandQueue = g_pd3dCommandQueue;
  136. init_info.NumFramesInFlight = APP_NUM_FRAMES_IN_FLIGHT;
  137. init_info.RTVFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
  138. init_info.DSVFormat = DXGI_FORMAT_UNKNOWN;
  139. // Allocating SRV descriptors (for textures) is up to the application, so we provide callbacks.
  140. // (current version of the backend will only allocate one descriptor, future versions will need to allocate more)
  141. init_info.SrvDescriptorHeap = g_pd3dSrvDescHeap;
  142. 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); };
  143. 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); };
  144. ImGui_ImplDX12_Init(&init_info);
  145. // 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.
  146. //ImGui_ImplDX12_Init(g_pd3dDevice, APP_NUM_FRAMES_IN_FLIGHT, DXGI_FORMAT_R8G8B8A8_UNORM, g_pd3dSrvDescHeap, g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(), g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart());
  147. // Load Fonts
  148. // - If fonts are not explicitly loaded, Dear ImGui will call AddFontDefault() to select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
  149. // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
  150. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
  151. // - 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).
  152. // - Read 'docs/FONTS.md' for more instructions and details.
  153. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
  154. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  155. //style.FontSizeBase = 20.0f;
  156. //io.Fonts->AddFontDefaultVector();
  157. //io.Fonts->AddFontDefaultBitmap();
  158. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
  159. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
  160. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
  161. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
  162. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
  163. //IM_ASSERT(font != nullptr);
  164. // Our state
  165. bool show_demo_window = true;
  166. bool show_another_window = false;
  167. ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  168. // Main loop
  169. bool done = false;
  170. while (!done)
  171. {
  172. // Poll and handle messages (inputs, window resize, etc.)
  173. // See the WndProc() function below for our to dispatch events to the Win32 backend.
  174. MSG msg;
  175. while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
  176. {
  177. ::TranslateMessage(&msg);
  178. ::DispatchMessage(&msg);
  179. if (msg.message == WM_QUIT)
  180. done = true;
  181. }
  182. if (done)
  183. break;
  184. // Handle window screen locked
  185. if ((g_SwapChainOccluded && g_pSwapChain->Present(0, DXGI_PRESENT_TEST) == DXGI_STATUS_OCCLUDED) || ::IsIconic(hwnd))
  186. {
  187. ::Sleep(10);
  188. continue;
  189. }
  190. g_SwapChainOccluded = false;
  191. // Start the Dear ImGui frame
  192. ImGui_ImplDX12_NewFrame();
  193. ImGui_ImplWin32_NewFrame();
  194. ImGui::NewFrame();
  195. // 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!).
  196. if (show_demo_window)
  197. ImGui::ShowDemoWindow(&show_demo_window);
  198. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  199. {
  200. static float f = 0.0f;
  201. static int counter = 0;
  202. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  203. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  204. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  205. ImGui::Checkbox("Another Window", &show_another_window);
  206. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  207. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  208. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  209. counter++;
  210. ImGui::SameLine();
  211. ImGui::Text("counter = %d", counter);
  212. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  213. ImGui::End();
  214. }
  215. // 3. Show another simple window.
  216. if (show_another_window)
  217. {
  218. 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)
  219. ImGui::Text("Hello from another window!");
  220. if (ImGui::Button("Close Me"))
  221. show_another_window = false;
  222. ImGui::End();
  223. }
  224. // Rendering
  225. ImGui::Render();
  226. FrameContext* frameCtx = WaitForNextFrameContext();
  227. UINT backBufferIdx = g_pSwapChain->GetCurrentBackBufferIndex();
  228. frameCtx->CommandAllocator->Reset();
  229. D3D12_RESOURCE_BARRIER barrier = {};
  230. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  231. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  232. barrier.Transition.pResource = g_mainRenderTargetResource[backBufferIdx];
  233. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  234. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  235. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  236. g_pd3dCommandList->Reset(frameCtx->CommandAllocator, nullptr);
  237. g_pd3dCommandList->ResourceBarrier(1, &barrier);
  238. // Render Dear ImGui graphics
  239. 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 };
  240. g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], clear_color_with_alpha, 0, nullptr);
  241. g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, nullptr);
  242. g_pd3dCommandList->SetDescriptorHeaps(1, &g_pd3dSrvDescHeap);
  243. ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), g_pd3dCommandList);
  244. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  245. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  246. g_pd3dCommandList->ResourceBarrier(1, &barrier);
  247. g_pd3dCommandList->Close();
  248. g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&g_pd3dCommandList);
  249. g_pd3dCommandQueue->Signal(g_fence, ++g_fenceLastSignaledValue);
  250. frameCtx->FenceValue = g_fenceLastSignaledValue;
  251. // Present
  252. HRESULT hr = g_pSwapChain->Present(1, 0); // Present with vsync
  253. //HRESULT hr = g_pSwapChain->Present(0, g_SwapChainTearingSupport ? DXGI_PRESENT_ALLOW_TEARING : 0); // Present without vsync
  254. g_SwapChainOccluded = (hr == DXGI_STATUS_OCCLUDED);
  255. g_frameIndex++;
  256. }
  257. WaitForPendingOperations();
  258. // Cleanup
  259. ImGui_ImplDX12_Shutdown();
  260. ImGui_ImplWin32_Shutdown();
  261. ImGui::DestroyContext();
  262. CleanupDeviceD3D();
  263. ::DestroyWindow(hwnd);
  264. ::UnregisterClassW(wc.lpszClassName, wc.hInstance);
  265. return 0;
  266. }
  267. // Helper functions
  268. bool CreateDeviceD3D(HWND hWnd)
  269. {
  270. // Setup swap chain
  271. // This is a basic setup. Optimally could handle fullscreen mode differently. See #8979 for suggestions.
  272. DXGI_SWAP_CHAIN_DESC1 sd;
  273. {
  274. ZeroMemory(&sd, sizeof(sd));
  275. sd.BufferCount = APP_NUM_BACK_BUFFERS;
  276. sd.Width = 0;
  277. sd.Height = 0;
  278. sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  279. sd.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
  280. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  281. sd.SampleDesc.Count = 1;
  282. sd.SampleDesc.Quality = 0;
  283. sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  284. sd.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
  285. sd.Scaling = DXGI_SCALING_STRETCH;
  286. sd.Stereo = FALSE;
  287. }
  288. // [DEBUG] Enable debug interface
  289. #ifdef DX12_ENABLE_DEBUG_LAYER
  290. ID3D12Debug* pdx12Debug = nullptr;
  291. if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&pdx12Debug))))
  292. pdx12Debug->EnableDebugLayer();
  293. #endif
  294. // Create device
  295. D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
  296. if (D3D12CreateDevice(nullptr, featureLevel, IID_PPV_ARGS(&g_pd3dDevice)) != S_OK)
  297. return false;
  298. // [DEBUG] Setup debug interface to break on any warnings/errors
  299. #ifdef DX12_ENABLE_DEBUG_LAYER
  300. if (pdx12Debug != nullptr)
  301. {
  302. ID3D12InfoQueue* pInfoQueue = nullptr;
  303. g_pd3dDevice->QueryInterface(IID_PPV_ARGS(&pInfoQueue));
  304. pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
  305. pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
  306. pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, true);
  307. // Disable breaking on this warning because of a suspected bug in the D3D12 SDK layer, see #9084 for details.
  308. const int D3D12_MESSAGE_ID_FENCE_ZERO_WAIT_ = 1424; // not in all copies of d3d12sdklayers.h
  309. D3D12_MESSAGE_ID disabledMessages[] = { (D3D12_MESSAGE_ID)D3D12_MESSAGE_ID_FENCE_ZERO_WAIT_ };
  310. D3D12_INFO_QUEUE_FILTER filter = {};
  311. filter.DenyList.NumIDs = 1;
  312. filter.DenyList.pIDList = disabledMessages;
  313. pInfoQueue->AddStorageFilterEntries(&filter);
  314. pInfoQueue->Release();
  315. pdx12Debug->Release();
  316. }
  317. #endif
  318. {
  319. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  320. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  321. desc.NumDescriptors = APP_NUM_BACK_BUFFERS;
  322. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  323. desc.NodeMask = 1;
  324. if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dRtvDescHeap)) != S_OK)
  325. return false;
  326. SIZE_T rtvDescriptorSize = g_pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  327. D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_pd3dRtvDescHeap->GetCPUDescriptorHandleForHeapStart();
  328. for (UINT i = 0; i < APP_NUM_BACK_BUFFERS; i++)
  329. {
  330. g_mainRenderTargetDescriptor[i] = rtvHandle;
  331. rtvHandle.ptr += rtvDescriptorSize;
  332. }
  333. }
  334. {
  335. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  336. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  337. desc.NumDescriptors = APP_SRV_HEAP_SIZE;
  338. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  339. if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dSrvDescHeap)) != S_OK)
  340. return false;
  341. g_pd3dSrvDescHeapAlloc.Create(g_pd3dDevice, g_pd3dSrvDescHeap);
  342. }
  343. {
  344. D3D12_COMMAND_QUEUE_DESC desc = {};
  345. desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  346. desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  347. desc.NodeMask = 1;
  348. if (g_pd3dDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(&g_pd3dCommandQueue)) != S_OK)
  349. return false;
  350. }
  351. for (UINT i = 0; i < APP_NUM_FRAMES_IN_FLIGHT; i++)
  352. if (g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_frameContext[i].CommandAllocator)) != S_OK)
  353. return false;
  354. if (g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_frameContext[0].CommandAllocator, nullptr, IID_PPV_ARGS(&g_pd3dCommandList)) != S_OK ||
  355. g_pd3dCommandList->Close() != S_OK)
  356. return false;
  357. if (g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_fence)) != S_OK)
  358. return false;
  359. g_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  360. if (g_fenceEvent == nullptr)
  361. return false;
  362. {
  363. IDXGIFactory5* dxgiFactory = nullptr;
  364. IDXGISwapChain1* swapChain1 = nullptr;
  365. if (CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)) != S_OK)
  366. return false;
  367. BOOL allow_tearing = FALSE;
  368. dxgiFactory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing, sizeof(allow_tearing));
  369. g_SwapChainTearingSupport = (allow_tearing == TRUE);
  370. if (g_SwapChainTearingSupport)
  371. sd.Flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
  372. if (dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, nullptr, nullptr, &swapChain1) != S_OK)
  373. return false;
  374. if (swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)) != S_OK)
  375. return false;
  376. if (g_SwapChainTearingSupport)
  377. dxgiFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER);
  378. swapChain1->Release();
  379. dxgiFactory->Release();
  380. g_pSwapChain->SetMaximumFrameLatency(APP_NUM_BACK_BUFFERS);
  381. g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject();
  382. }
  383. CreateRenderTarget();
  384. return true;
  385. }
  386. void CleanupDeviceD3D()
  387. {
  388. CleanupRenderTarget();
  389. if (g_pSwapChain) { g_pSwapChain->SetFullscreenState(false, nullptr); g_pSwapChain->Release(); g_pSwapChain = nullptr; }
  390. if (g_hSwapChainWaitableObject != nullptr) { CloseHandle(g_hSwapChainWaitableObject); }
  391. for (UINT i = 0; i < APP_NUM_FRAMES_IN_FLIGHT; i++)
  392. if (g_frameContext[i].CommandAllocator) { g_frameContext[i].CommandAllocator->Release(); g_frameContext[i].CommandAllocator = nullptr; }
  393. if (g_pd3dCommandQueue) { g_pd3dCommandQueue->Release(); g_pd3dCommandQueue = nullptr; }
  394. if (g_pd3dCommandList) { g_pd3dCommandList->Release(); g_pd3dCommandList = nullptr; }
  395. if (g_pd3dRtvDescHeap) { g_pd3dRtvDescHeap->Release(); g_pd3dRtvDescHeap = nullptr; }
  396. if (g_pd3dSrvDescHeap) { g_pd3dSrvDescHeap->Release(); g_pd3dSrvDescHeap = nullptr; }
  397. if (g_fence) { g_fence->Release(); g_fence = nullptr; }
  398. if (g_fenceEvent) { CloseHandle(g_fenceEvent); g_fenceEvent = nullptr; }
  399. if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; }
  400. #ifdef DX12_ENABLE_DEBUG_LAYER
  401. IDXGIDebug1* pDebug = nullptr;
  402. if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&pDebug))))
  403. {
  404. pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_SUMMARY);
  405. pDebug->Release();
  406. }
  407. #endif
  408. }
  409. void CreateRenderTarget()
  410. {
  411. for (UINT i = 0; i < APP_NUM_BACK_BUFFERS; i++)
  412. {
  413. ID3D12Resource* pBackBuffer = nullptr;
  414. g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer));
  415. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, g_mainRenderTargetDescriptor[i]);
  416. g_mainRenderTargetResource[i] = pBackBuffer;
  417. }
  418. }
  419. void CleanupRenderTarget()
  420. {
  421. WaitForPendingOperations();
  422. for (UINT i = 0; i < APP_NUM_BACK_BUFFERS; i++)
  423. if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = nullptr; }
  424. }
  425. void WaitForPendingOperations()
  426. {
  427. g_pd3dCommandQueue->Signal(g_fence, ++g_fenceLastSignaledValue);
  428. g_fence->SetEventOnCompletion(g_fenceLastSignaledValue, g_fenceEvent);
  429. ::WaitForSingleObject(g_fenceEvent, INFINITE);
  430. }
  431. FrameContext* WaitForNextFrameContext()
  432. {
  433. FrameContext* frame_context = &g_frameContext[g_frameIndex % APP_NUM_FRAMES_IN_FLIGHT];
  434. if (g_fence->GetCompletedValue() < frame_context->FenceValue)
  435. {
  436. g_fence->SetEventOnCompletion(frame_context->FenceValue, g_fenceEvent);
  437. HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, g_fenceEvent };
  438. ::WaitForMultipleObjects(2, waitableObjects, TRUE, INFINITE);
  439. }
  440. else
  441. ::WaitForSingleObject(g_hSwapChainWaitableObject, INFINITE);
  442. return frame_context;
  443. }
  444. // Forward declare message handler from imgui_impl_win32.cpp
  445. extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  446. // Win32 message handler
  447. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  448. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  449. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  450. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  451. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  452. {
  453. if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
  454. return true;
  455. switch (msg)
  456. {
  457. case WM_SIZE:
  458. if (g_pd3dDevice != nullptr && wParam != SIZE_MINIMIZED)
  459. {
  460. CleanupRenderTarget();
  461. DXGI_SWAP_CHAIN_DESC1 desc = {};
  462. g_pSwapChain->GetDesc1(&desc);
  463. HRESULT result = g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), desc.Format, desc.Flags);
  464. IM_ASSERT(SUCCEEDED(result) && "Failed to resize swapchain.");
  465. CreateRenderTarget();
  466. }
  467. return 0;
  468. case WM_SYSCOMMAND:
  469. if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
  470. return 0;
  471. break;
  472. case WM_DESTROY:
  473. ::PostQuitMessage(0);
  474. return 0;
  475. }
  476. return ::DefWindowProcW(hWnd, msg, wParam, lParam);
  477. }