main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. // ImGui - standalone example application for DirectX 12
  2. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  3. // FIXME: 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*))
  4. #include "imgui.h"
  5. #include "imgui_impl_dx12.h"
  6. #include <d3d12.h>
  7. #include <dxgi1_4.h>
  8. #include <tchar.h>
  9. #define DX12_ENABLE_DEBUG_LAYER 0
  10. struct FrameContext
  11. {
  12. ID3D12CommandAllocator* CommandAllocator;
  13. UINT64 FenceValue;
  14. };
  15. // Data
  16. static int const NUM_FRAMES_IN_FLIGHT = 3;
  17. static FrameContext g_frameContext[NUM_FRAMES_IN_FLIGHT] = {};
  18. static UINT g_frameIndex = 0;
  19. static int const NUM_BACK_BUFFERS = 3;
  20. static ID3D12Device* g_pd3dDevice = NULL;
  21. static ID3D12DescriptorHeap* g_pd3dRtvDescHeap = NULL;
  22. static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL;
  23. static ID3D12CommandQueue* g_pd3dCommandQueue = NULL;
  24. static ID3D12GraphicsCommandList* g_pd3dCommandList = NULL;
  25. static ID3D12Fence* g_fence = NULL;
  26. static HANDLE g_fenceEvent = NULL;
  27. static UINT64 g_fenceLastSignaledValue = 0;
  28. static IDXGISwapChain3* g_pSwapChain = NULL;
  29. static HANDLE g_hSwapChainWaitableObject = NULL;
  30. static ID3D12Resource* g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {};
  31. static D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {};
  32. void CreateRenderTarget()
  33. {
  34. ID3D12Resource* pBackBuffer;
  35. for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
  36. {
  37. g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer));
  38. g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, g_mainRenderTargetDescriptor[i]);
  39. g_mainRenderTargetResource[i] = pBackBuffer;
  40. }
  41. }
  42. void WaitForLastSubmittedFrame()
  43. {
  44. FrameContext* frameCtxt = &g_frameContext[g_frameIndex % NUM_FRAMES_IN_FLIGHT];
  45. UINT64 fenceValue = frameCtxt->FenceValue;
  46. if (fenceValue == 0)
  47. return; // No fence was signaled
  48. frameCtxt->FenceValue = 0;
  49. if (g_fence->GetCompletedValue() >= fenceValue)
  50. return;
  51. g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent);
  52. WaitForSingleObject(g_fenceEvent, INFINITE);
  53. }
  54. FrameContext* WaitForNextFrameResources()
  55. {
  56. UINT nextFrameIndex = g_frameIndex + 1;
  57. g_frameIndex = nextFrameIndex;
  58. HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, NULL };
  59. DWORD numWaitableObjects = 1;
  60. FrameContext* frameCtxt = &g_frameContext[nextFrameIndex % NUM_FRAMES_IN_FLIGHT];
  61. UINT64 fenceValue = frameCtxt->FenceValue;
  62. if (fenceValue != 0) // means no fence was signaled
  63. {
  64. frameCtxt->FenceValue = 0;
  65. g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent);
  66. waitableObjects[1] = g_fenceEvent;
  67. numWaitableObjects = 2;
  68. }
  69. WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE);
  70. return frameCtxt;
  71. }
  72. void ResizeSwapChain(HWND hWnd, int width, int height)
  73. {
  74. DXGI_SWAP_CHAIN_DESC1 sd;
  75. g_pSwapChain->GetDesc1(&sd);
  76. sd.Width = width;
  77. sd.Height = height;
  78. IDXGIFactory4* dxgiFactory = nullptr;
  79. g_pSwapChain->GetParent(IID_PPV_ARGS(&dxgiFactory));
  80. g_pSwapChain->Release();
  81. CloseHandle(g_hSwapChainWaitableObject);
  82. IDXGISwapChain1* swapChain1 = NULL;
  83. dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1);
  84. swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain));
  85. swapChain1->Release();
  86. dxgiFactory->Release();
  87. g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS);
  88. g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject();
  89. assert(g_hSwapChainWaitableObject != NULL);
  90. }
  91. void CleanupRenderTarget()
  92. {
  93. WaitForLastSubmittedFrame();
  94. for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
  95. if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = NULL; }
  96. }
  97. HRESULT CreateDeviceD3D(HWND hWnd)
  98. {
  99. // Setup swap chain
  100. DXGI_SWAP_CHAIN_DESC1 sd;
  101. {
  102. ZeroMemory(&sd, sizeof(sd));
  103. sd.BufferCount = NUM_BACK_BUFFERS;
  104. sd.Width = 0;
  105. sd.Height = 0;
  106. sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  107. sd.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
  108. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  109. sd.SampleDesc.Count = 1;
  110. sd.SampleDesc.Quality = 0;
  111. sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  112. sd.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
  113. sd.Scaling = DXGI_SCALING_STRETCH;
  114. sd.Stereo = FALSE;
  115. }
  116. if (DX12_ENABLE_DEBUG_LAYER)
  117. {
  118. ID3D12Debug* dx12Debug = NULL;
  119. if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&dx12Debug))))
  120. {
  121. dx12Debug->EnableDebugLayer();
  122. dx12Debug->Release();
  123. }
  124. }
  125. D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
  126. if (D3D12CreateDevice(NULL, featureLevel, IID_PPV_ARGS(&g_pd3dDevice)) != S_OK)
  127. return E_FAIL;
  128. {
  129. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  130. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  131. desc.NumDescriptors = NUM_BACK_BUFFERS;
  132. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  133. desc.NodeMask = 1;
  134. if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dRtvDescHeap)) != S_OK)
  135. return E_FAIL;
  136. SIZE_T rtvDescriptorSize = g_pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  137. D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_pd3dRtvDescHeap->GetCPUDescriptorHandleForHeapStart();
  138. for (UINT i = 0; i < NUM_BACK_BUFFERS; i++)
  139. {
  140. g_mainRenderTargetDescriptor[i] = rtvHandle;
  141. rtvHandle.ptr += rtvDescriptorSize;
  142. }
  143. }
  144. {
  145. D3D12_DESCRIPTOR_HEAP_DESC desc = {};
  146. desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  147. desc.NumDescriptors = 1;
  148. desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  149. if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dSrvDescHeap)) != S_OK)
  150. return E_FAIL;
  151. }
  152. {
  153. D3D12_COMMAND_QUEUE_DESC desc = {};
  154. desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  155. desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  156. desc.NodeMask = 1;
  157. if (g_pd3dDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(&g_pd3dCommandQueue)) != S_OK)
  158. return E_FAIL;
  159. }
  160. for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++)
  161. if (g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_frameContext[i].CommandAllocator)) != S_OK)
  162. return E_FAIL;
  163. if (g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_frameContext[0].CommandAllocator, NULL, IID_PPV_ARGS(&g_pd3dCommandList)) != S_OK ||
  164. g_pd3dCommandList->Close() != S_OK)
  165. return E_FAIL;
  166. if (g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_fence)) != S_OK)
  167. return E_FAIL;
  168. g_fenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  169. if (g_fenceEvent == NULL)
  170. return E_FAIL;
  171. {
  172. IDXGIFactory4* dxgiFactory = NULL;
  173. IDXGISwapChain1* swapChain1 = NULL;
  174. if (CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)) != S_OK ||
  175. dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1) != S_OK ||
  176. swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)) != S_OK)
  177. return E_FAIL;
  178. swapChain1->Release();
  179. dxgiFactory->Release();
  180. g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS);
  181. g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject();
  182. }
  183. CreateRenderTarget();
  184. return S_OK;
  185. }
  186. void CleanupDeviceD3D()
  187. {
  188. CleanupRenderTarget();
  189. if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
  190. if (g_hSwapChainWaitableObject != NULL) { CloseHandle(g_hSwapChainWaitableObject); }
  191. for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++)
  192. if (g_frameContext[i].CommandAllocator) { g_frameContext[i].CommandAllocator->Release(); g_frameContext[i].CommandAllocator = NULL; }
  193. if (g_pd3dCommandQueue) { g_pd3dCommandQueue->Release(); g_pd3dCommandQueue = NULL; }
  194. if (g_pd3dCommandList) { g_pd3dCommandList->Release(); g_pd3dCommandList = NULL; }
  195. if (g_pd3dRtvDescHeap) { g_pd3dRtvDescHeap->Release(); g_pd3dRtvDescHeap = NULL; }
  196. if (g_pd3dSrvDescHeap) { g_pd3dSrvDescHeap->Release(); g_pd3dSrvDescHeap = NULL; }
  197. if (g_fence) { g_fence->Release(); g_fence = NULL; }
  198. if (g_fenceEvent) { CloseHandle(g_fenceEvent); g_fenceEvent = NULL; }
  199. if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
  200. }
  201. extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
  202. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  203. {
  204. if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
  205. return true;
  206. switch (msg)
  207. {
  208. case WM_SIZE:
  209. if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
  210. {
  211. ImGui_ImplDX12_InvalidateDeviceObjects();
  212. CleanupRenderTarget();
  213. ResizeSwapChain(hWnd, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam));
  214. CreateRenderTarget();
  215. ImGui_ImplDX12_CreateDeviceObjects();
  216. }
  217. return 0;
  218. case WM_SYSCOMMAND:
  219. if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
  220. return 0;
  221. break;
  222. case WM_DESTROY:
  223. PostQuitMessage(0);
  224. return 0;
  225. }
  226. return DefWindowProc(hWnd, msg, wParam, lParam);
  227. }
  228. int main(int, char**)
  229. {
  230. // Create application window
  231. WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
  232. RegisterClassEx(&wc);
  233. HWND hwnd = CreateWindow(_T("ImGui Example"), _T("ImGui DirectX12 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
  234. // Initialize Direct3D
  235. if (CreateDeviceD3D(hwnd) < 0)
  236. {
  237. CleanupDeviceD3D();
  238. UnregisterClass(_T("ImGui Example"), wc.hInstance);
  239. return 1;
  240. }
  241. // Show the window
  242. ShowWindow(hwnd, SW_SHOWDEFAULT);
  243. UpdateWindow(hwnd);
  244. // Setup ImGui binding
  245. ImGui::CreateContext();
  246. ImGuiIO& io = ImGui::GetIO(); (void)io;
  247. //io.NavFlags |= ImGuiNavFlags_EnableKeyboard; // Enable Keyboard Controls
  248. ImGui_ImplDX12_Init(hwnd, NUM_FRAMES_IN_FLIGHT, g_pd3dDevice,
  249. DXGI_FORMAT_R8G8B8A8_UNORM,
  250. g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(),
  251. g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart());
  252. // Setup style
  253. ImGui::StyleColorsDark();
  254. //ImGui::StyleColorsClassic();
  255. // Load Fonts
  256. // - 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.
  257. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  258. // - 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).
  259. // - 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.
  260. // - Read 'misc/fonts/README.txt' for more instructions and details.
  261. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  262. //io.Fonts->AddFontDefault();
  263. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
  264. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
  265. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
  266. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
  267. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
  268. //IM_ASSERT(font != NULL);
  269. bool show_demo_window = true;
  270. bool show_another_window = false;
  271. ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  272. // Main loop
  273. MSG msg;
  274. ZeroMemory(&msg, sizeof(msg));
  275. while (msg.message != WM_QUIT)
  276. {
  277. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  278. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
  279. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
  280. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  281. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
  282. {
  283. TranslateMessage(&msg);
  284. DispatchMessage(&msg);
  285. continue;
  286. }
  287. ImGui_ImplDX12_NewFrame(g_pd3dCommandList);
  288. // 1. Show a simple window.
  289. // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
  290. {
  291. static float f = 0.0f;
  292. static int counter = 0;
  293. ImGui::Text("Hello, world!"); // Display some text (you can use a format string too)
  294. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  295. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  296. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our windows open/close state
  297. ImGui::Checkbox("Another Window", &show_another_window);
  298. if (ImGui::Button("Button")) // Buttons return true when clicked (NB: most widgets return true when edited/activated)
  299. counter++;
  300. ImGui::SameLine();
  301. ImGui::Text("counter = %d", counter);
  302. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  303. }
  304. // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name your windows.
  305. if (show_another_window)
  306. {
  307. ImGui::Begin("Another Window", &show_another_window);
  308. ImGui::Text("Hello from another window!");
  309. if (ImGui::Button("Close Me"))
  310. show_another_window = false;
  311. ImGui::End();
  312. }
  313. // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow(). Read its code to learn more about Dear ImGui!
  314. if (show_demo_window)
  315. {
  316. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
  317. ImGui::ShowDemoWindow(&show_demo_window);
  318. }
  319. // Rendering
  320. FrameContext* frameCtxt = WaitForNextFrameResources();
  321. UINT backBufferIdx = g_pSwapChain->GetCurrentBackBufferIndex();
  322. frameCtxt->CommandAllocator->Reset();
  323. D3D12_RESOURCE_BARRIER barrier = {};
  324. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  325. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  326. barrier.Transition.pResource = g_mainRenderTargetResource[backBufferIdx];
  327. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  328. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  329. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  330. g_pd3dCommandList->Reset(frameCtxt->CommandAllocator, NULL);
  331. g_pd3dCommandList->ResourceBarrier(1, &barrier);
  332. g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], (float*)&clear_color, 0, NULL);
  333. g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, NULL);
  334. g_pd3dCommandList->SetDescriptorHeaps(1, &g_pd3dSrvDescHeap);
  335. ImGui::Render();
  336. ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData());
  337. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  338. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  339. g_pd3dCommandList->ResourceBarrier(1, &barrier);
  340. g_pd3dCommandList->Close();
  341. g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*) &g_pd3dCommandList);
  342. g_pSwapChain->Present(1, 0); // Present with vsync
  343. //g_pSwapChain->Present(0, 0); // Present without vsync
  344. UINT64 fenceValue = g_fenceLastSignaledValue + 1;
  345. g_pd3dCommandQueue->Signal(g_fence, fenceValue);
  346. g_fenceLastSignaledValue = fenceValue;
  347. frameCtxt->FenceValue = fenceValue;
  348. }
  349. ImGui_ImplDX12_Shutdown();
  350. ImGui::DestroyContext();
  351. CleanupDeviceD3D();
  352. UnregisterClass(_T("ImGui Example"), wc.hInstance);
  353. return 0;
  354. }