From 495bbea0f2b62cff37712f655129d7af2d7a75b7 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Tue, 17 Nov 2026 13:52:20 -0500 Subject: [PATCH 1/5] No frame cap when the monitor's refresh rate is unknown and VSync is on On Wayland the refresh rate is not known, so the cap fell back to 60 and held a 240 Hz monitor at 60 fps. With VSync on the display paces the frames, so there is no cap then. With VSync off the fallback of 60 stays. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017NN37Q2jpV81xZaX3ocojK --- Docs/agent-guide.md | 2 +- Docs/time-and-ticks.md | 3 ++- FlingEngine/Core/inc/RunSettings.h | 3 ++- FlingEngine/Core/src/RunSettings.cpp | 11 ++++++++++- FlingTests/Core/RunSettingsTests.cpp | 15 +++++++++++---- 5 files changed, 26 insertions(+), 8 deletions(-) diff --git a/Docs/agent-guide.md b/Docs/agent-guide.md index 8c0837ab..e1feb255 100644 --- a/Docs/agent-guide.md +++ b/Docs/agent-guide.md @@ -765,7 +765,7 @@ flag or key. The startup line `Run settings: ...` names each value and its sourc | --- | --- | --- | --- | --- | | Exec mode | `--exec direct\|inline\|threaded` | `Exec` | threaded | no | | Tick rate | `--sim-hz N` (1 to 1000) | `SimHz` | 30 | GPU Options, at a tick boundary | -| Frame cap | `--max-fps N` (0: none, max 1000) | `MaxFps` | monitor refresh rate, else 60 (`FallbackMaxFps`); none with `--null-render` | GPU Options | +| Frame cap | `--max-fps N` (0: none, max 1000) | `MaxFps` | monitor refresh rate, else none with VSync on, else 60 (`FallbackMaxFps`); none with `--null-render` | GPU Options | | VSync | `--vsync on\|off` | `VSync` | on | GPU Options (swap chain rebuilt) | | Interpolation | `--interpolation on\|off` | `Interpolation` | on | GPU Options | | Frustum culling | `--frustum-culling on\|off` | `FrustumCulling` | on | GPU Options | diff --git a/Docs/time-and-ticks.md b/Docs/time-and-ticks.md index 20a81b06..59f68497 100644 --- a/Docs/time-and-ticks.md +++ b/Docs/time-and-ticks.md @@ -155,7 +155,8 @@ refuses it". The main thread's frames are variable rate, with a cap (`FrameLimiter`, `Core/inc/Threading/FrameLimiter.h`): `--max-fps N`, else `[Engine] MaxFps`, else the refresh rate of the monitor the window is on (the GLFW video mode), -else 60 when that is 0 or not known. 0 means no cap. A cap that came from the +else, when that is 0 or not known (Wayland), no cap with VSync on (the display paces +the frames) and 60 with VSync off. 0 means no cap. A cap that came from the monitor follows the window to another monitor: the engine reads the refresh rate again once a second (`RunControls::SetMonitorHz`). GLFW gives the refresh rate as a whole number, so a 59.94 Hz display reports 59. A `--null-render` diff --git a/FlingEngine/Core/inc/RunSettings.h b/FlingEngine/Core/inc/RunSettings.h index 1217bda7..4e45d21f 100644 --- a/FlingEngine/Core/inc/RunSettings.h +++ b/FlingEngine/Core/inc/RunSettings.h @@ -189,7 +189,8 @@ namespace Fling /** * The default frame cap, when neither the command line nor the config file set one: * none for a headless run (so headless runs and tests stay as fast as before), else - * MonitorMaxFps(t_MonitorHz), else FallbackMaxFps when the refresh rate is missing or 0. + * MonitorMaxFps(t_MonitorHz), else none when the refresh rate is missing or 0 and VSync is on (the display + * paces the frames), else FallbackMaxFps. * * @param t_MonitorHz The refresh rate of the window's monitor. Empty when it is not known */ diff --git a/FlingEngine/Core/src/RunSettings.cpp b/FlingEngine/Core/src/RunSettings.cpp index 19afcdcd..1e2e2102 100644 --- a/FlingEngine/Core/src/RunSettings.cpp +++ b/FlingEngine/Core/src/RunSettings.cpp @@ -260,6 +260,13 @@ namespace Fling MaxFps = MonitorMaxFps(*MonitorHz); MaxFpsSource = SettingSource::Monitor; } + else if (VSync) + { + // The refresh rate is not known (Wayland), but VSync on makes the display pace the + // frames. A cap of 60 here would hold a faster monitor at 60. + MaxFps = 0; + MaxFpsSource = SettingSource::Default; + } else { MaxFps = FallbackMaxFps; @@ -274,7 +281,9 @@ namespace Fling if (MaxFpsSource == SettingSource::Default) { CapSource = - Headless ? String("default for ") + HeadlessFlag : "default: the monitor refresh rate is not known"; + Headless ? String("default for ") + HeadlessFlag : + VSync ? String("default: the monitor refresh rate is not known, so the display paces the frames") : + String("default: the monitor refresh rate is not known"); } else if (MaxFpsSource == SettingSource::Monitor) { diff --git a/FlingTests/Core/RunSettingsTests.cpp b/FlingTests/Core/RunSettingsTests.cpp index 9217327a..4f47c7bb 100644 --- a/FlingTests/Core/RunSettingsTests.cpp +++ b/FlingTests/Core/RunSettingsTests.cpp @@ -63,16 +63,23 @@ TEST_CASE("Run settings: the frame cap is the monitor's refresh rate, else 60", Settings.ResolveFrameCap(2000u); REQUIRE(Settings.MaxFps == RunSettings::MaxMaxFps); } - SECTION("A monitor that reports 0") + SECTION("A monitor that reports 0, with VSync on: the display paces the frames") { Settings.ResolveFrameCap(0u); - REQUIRE(Settings.MaxFps == 60); + REQUIRE(Settings.MaxFps == 0); + REQUIRE(Settings.MaxFpsSource == SettingSource::Default); + } + SECTION("No monitor, with VSync on: no cap") + { + Settings.ResolveFrameCap(std::nullopt); + REQUIRE(Settings.MaxFps == 0); REQUIRE(Settings.MaxFpsSource == SettingSource::Default); } - SECTION("No monitor") + SECTION("No monitor, with VSync off: the fallback cap") { + REQUIRE(Resolve({"--vsync", "off"}, {}, Settings, Error)); Settings.ResolveFrameCap(std::nullopt); - REQUIRE(Settings.MaxFps == 60); + REQUIRE(Settings.MaxFps == RunSettings::FallbackMaxFps); REQUIRE(Settings.MaxFpsSource == SettingSource::Default); } SECTION("Headless runs have no cap unless they ask for one, so tests stay fast") From 8418532f2327ea31f7d35820a2c3606131d45a76 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Tue, 17 Nov 2026 14:21:02 -0500 Subject: [PATCH 2/5] Profile the acquire, submit and present calls separately Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017NN37Q2jpV81xZaX3ocojK --- FlingEngine/Graphics/src/VulkanApp.cpp | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 6688a867..832b7e23 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -672,7 +672,11 @@ namespace Fling const bool bPresentSync = !m_SwapChain->IsOffscreen(); // Aquire the active image index - VkResult iResult = m_SwapChain->AquireNextImage(m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]); + VkResult iResult = VK_SUCCESS; + { + FLING_PROFILE_SCOPE("Vk.Acquire"); + iResult = m_SwapChain->AquireNextImage(m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]); + } uint32 ImageIndex = m_SwapChain->GetActiveImageIndex(); if (iResult == VK_ERROR_OUT_OF_DATE_KHR) @@ -821,10 +825,13 @@ namespace Fling FinalScreenSubmitInfo.signalSemaphoreCount = bPresentSync ? 1 : 0; FinalScreenSubmitInfo.pSignalSemaphores = &m_State->m_RenderFinishedSemaphores[ImageIndex]; - VK_CHECK_RESULT(vkQueueSubmit(m_LogicalDevice->GetGraphicsQueue(), - 1, - &FinalScreenSubmitInfo, - m_State->m_InFlightFences[CurrentFrameIndex])); + { + FLING_PROFILE_SCOPE("Vk.Submit"); + VK_CHECK_RESULT(vkQueueSubmit(m_LogicalDevice->GetGraphicsQueue(), + 1, + &FinalScreenSubmitInfo, + m_State->m_InFlightFences[CurrentFrameIndex])); + } // Finish up the frame by setting the in flight fences to wait ----- { @@ -841,8 +848,12 @@ namespace Fling m_Capturer->OnFrameDone(); // Present the swap chain with the renderer finished semaphore - iResult = m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), - m_State->m_RenderFinishedSemaphores[ImageIndex]); + { + // On the NVIDIA Wayland driver this call blocks until the GPU has finished the frame + FLING_PROFILE_SCOPE("Vk.QueuePresent"); + iResult = m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), + m_State->m_RenderFinishedSemaphores[ImageIndex]); + } // Check if the swap chain is out of date and needs to be rebuilt if (iResult == VK_ERROR_OUT_OF_DATE_KHR || iResult == VK_SUBOPTIMAL_KHR || bSwapchainOutOfDate) From fd0e2910fac6c76881ded5900b6d38d0619ab0ef Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Tue, 17 Nov 2026 15:29:58 -0500 Subject: [PATCH 3/5] Pipeline the frames: the CPU records a frame while the GPU draws the one before The renderer waited for each frame's fence right after the submit, and vkQueuePresentKHR blocks until the GPU is done on the NVIDIA Wayland driver, so the CPU and the GPU took turns (2.7 ms a frame: 0.8 CPU plus 1.9 GPU). Now two frames are in flight: - The fence wait moved to the start of the frame (the frame slot's last frame). - A present thread presents and acquires on a second queue, so the render thread does not wait in the driver. It owns the swap chain's two blocking calls (a swap chain is externally synchronized). - FrameUploader copies the data that the CPU makes each frame (camera, world matrices, draw commands, occlusion slots and parameters) from per frame staging memory into GPU buffers. The counters come back through per frame readback buffers. - FrameSync and RetireList free what a frame used only when the GPU is done with it. - ImGui and the debug pass keep a buffer pair for each frame slot. - The GPU runs one frame at a time: a semaphore chain and a barrier order the frames, because they share the G-buffer, depth and pyramid images. - The final pass waits for the G-buffer at every stage (it sampled it from the fragment shader after waiting at the color output stage only). Lighting test level, RelWithDebInfo, 1080p, RTX 3090, VSync off, no cap: 366 to 538 fps. Validation layers report nothing, also with the swap chain made again every 40 frames. Docs/frame-pipelining.md has the design and the rules for a pass. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017NN37Q2jpV81xZaX3ocojK --- AGENTS.md | 3 + Docs/frame-pipelining.md | 83 ++++++ FlingEngine/Application/src/Engine.cpp | 7 + FlingEngine/Graphics/inc/FrameSync.h | 106 +++++++ FlingEngine/Graphics/inc/VulkanApp.h | 17 +- FlingEngine/Graphics/src/DebugSubpass.cpp | 100 ++++--- FlingEngine/Graphics/src/DebugSubpass.h | 25 +- FlingEngine/Graphics/src/FrameCapture.h | 3 + FlingEngine/Graphics/src/FrameUploader.cpp | 231 +++++++++++++++ FlingEngine/Graphics/src/FrameUploader.h | 100 +++++++ FlingEngine/Graphics/src/ImGuiSubpass.cpp | 46 +-- FlingEngine/Graphics/src/ImGuiSubpass.h | 12 +- FlingEngine/Graphics/src/LogicalDevice.cpp | 26 +- FlingEngine/Graphics/src/LogicalDevice.h | 21 +- FlingEngine/Graphics/src/OcclusionCuller.cpp | 94 ++++-- FlingEngine/Graphics/src/OcclusionCuller.h | 26 +- FlingEngine/Graphics/src/OffscreenSubpass.cpp | 112 ++++--- FlingEngine/Graphics/src/OffscreenSubpass.h | 38 ++- FlingEngine/Graphics/src/PresentThread.cpp | 139 +++++++++ FlingEngine/Graphics/src/PresentThread.h | 106 +++++++ FlingEngine/Graphics/src/Subpass.h | 4 + FlingEngine/Graphics/src/SwapChain.cpp | 37 ++- FlingEngine/Graphics/src/SwapChain.h | 12 + FlingEngine/Graphics/src/VulkanApp.cpp | 277 +++++++++++++++--- FlingEngine/Graphics/src/VulkanAppState.h | 24 ++ FlingTests/Graphics/FrameSyncTests.cpp | 82 ++++++ Plans/gpu-blend.md | 4 + 27 files changed, 1524 insertions(+), 211 deletions(-) create mode 100644 Docs/frame-pipelining.md create mode 100644 FlingEngine/Graphics/inc/FrameSync.h create mode 100644 FlingEngine/Graphics/src/FrameUploader.cpp create mode 100644 FlingEngine/Graphics/src/FrameUploader.h create mode 100644 FlingEngine/Graphics/src/PresentThread.cpp create mode 100644 FlingEngine/Graphics/src/PresentThread.h create mode 100644 FlingTests/Graphics/FrameSyncTests.cpp diff --git a/AGENTS.md b/AGENTS.md index 0aa871e7..e7f89204 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,6 +123,9 @@ platform setup (Vulkan SDK, GLFW, etc.). [`Docs/threading-model.md`](Docs/threading-model.md). - Occlusion culling in the G-buffer pass (a two phase Hi-Z pass on the GPU, its CPU twin and tests): [`Docs/occlusion-culling.md`](Docs/occlusion-culling.md). +- Frame pipelining (the CPU records a frame while the GPU draws the one before: the fence at the start of the + frame, the present thread, `FrameUploader`, `FrameSync` and `RetireList`, and the rules for a render pass that + writes data each frame): [`Docs/frame-pipelining.md`](Docs/frame-pipelining.md). - One self-contained guide to all of the above, written to be loaded as context by an AI coding agent: [`Docs/agent-guide.md`](Docs/agent-guide.md). The handoff for the original Fling authors (what changed since the first commit, diff --git a/Docs/frame-pipelining.md b/Docs/frame-pipelining.md new file mode 100644 index 00000000..f98ef9af --- /dev/null +++ b/Docs/frame-pipelining.md @@ -0,0 +1,83 @@ +# Frame pipelining: the CPU records a frame while the GPU draws the one before + +The renderer keeps two frames in flight (`VkConfig::MAX_FRAMES_IN_FLIGHT`, `FrameSync::FramesInFlight`). +The main thread records frame N while the GPU still draws frame N-1. Before this, each frame waited for +its own fence right after the submit, so the CPU and the GPU took turns: the frame time was the CPU time +plus the GPU time. Now it is the larger of the two. + +Measured on the lighting test level (RelWithDebInfo, 1080p window, RTX 3090, VSync off, no frame cap, +30 Hz sim, 900 ticks, three runs each): + +| | Before | After | +|---|---|---| +| Spheres turning | 2.70 to 2.73 ms (366 to 370 fps) | 1.85 to 1.87 ms (536 to 541 fps) | +| Spheres still | 2.76 to 2.77 ms (361 to 363 fps) | 1.82 to 1.88 ms (533 to 549 fps) | + +The frame is now GPU bound. `Vk.Acquire` (the render thread waits for an image) is the largest scope. + +## The parts + +1. **The fence moved to the start of the frame.** `VulkanApp::Update` waits for the fence of the frame + slot (`frame number % FramesInFlight`) before it records. That frame was submitted two frames ago, so it + is done. The frame before it may still run on the GPU. `FrameSync::Begin` then tells the passes which + frames are finished. + +2. **The present thread** (`PresentThread`). On some drivers (NVIDIA on Wayland) `vkQueuePresentKHR` + does not return until the GPU has finished the frame. Called on the render thread, that brings the wait + back. So a thread of its own makes the present call, on a second queue of the graphics family + (`LogicalDevice::HasSeparatePresentQueue`). A swap chain must not be used by two threads at once, so the + same thread also acquires the images, one after each present, and the render thread takes them + (`TakeAcquired`). Without a second queue, or offscreen, the render thread presents and acquires itself: + the picture is the same, and there is no overlap. + +3. **Data for the GPU goes through `FrameUploader`.** A buffer that the CPU wrote each frame and the GPU + read (the camera, the world matrices, the draw commands, the occlusion slot data and parameters) was a + host visible buffer that the CPU overwrote. With two frames in flight that races with the GPU. Now the + CPU writes into a staging buffer of its own frame slot (`Stage`), and the frame's first command buffer + (`FrameUploader::Record`) copies it into a buffer in GPU memory. Only the GPU writes those buffers, in + the order of the submissions. They are also faster to read than host memory. + +4. **The GPU runs one frame at a time.** The frames share the G-buffer images, the depth buffers, the depth + pyramid and the visibility flags. The first submission of a frame waits for the last one of the frame + before (`VulkanApp::State::m_FrameChain`), and the upload command buffer starts with a full memory + barrier. The CPU records ahead; the GPU frames do not overlap each other. + +## Rules for a pass + +- A buffer that the CPU writes while recording and that a command buffer reads: put the data through + `FrameUploader::Stage`, or keep one copy for each frame slot (`FrameSync::Slot()`): the ImGui pass and the + debug pass do this. A swap chain image index is not a frame slot, but the buffers that are indexed by + image (the lighting UBOs) are safe too: two frames in a row never get the same image. +- Free a resource that a frame used (a descriptor set, a buffer) with `RetireList`: `Add` tags it with the + current frame, `Release` frees it when `FrameSync::IsDone` says the frames that could use it are finished. +- Writing a descriptor set that a frame in flight uses is not allowed. The few places that must do it (a + larger world matrix buffer, new occlusion buffers) call `LogicalDevice::WaitForIdle()` first. This is + rare: the buffers grow by doubling. +- Before the engine frees a model or a texture that a frame may use, call `VulkanApp::WaitForGpuIdle()` + (`Engine` does this at shutdown). +- A screenshot copy is recorded in one frame, and the capturer takes it when that frame is done + (`VulkanApp::State::m_CaptureFrame`). One copy is in flight at a time. + +## Checking it + +- `--profile`: `Vk.WaitForGpu` (the fence at the start of the frame), `Vk.Acquire`, `Vk.Submit`, + `Vk.QueuePresent` (handing the present over), `Present.Thread` and `Present.Acquire` (on the present thread), + `Upload.Record`. +- The validation layers (`EnableValidationLayers=true` in `Config/EngineConf.ini`) report nothing in a run, + also when the swap chain is made again every 40 frames. +- The synchronization validation (`VK_LAYER_ENABLES=VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT`) + reports `SYNC-HAZARD-*-RACING-*` between the submissions of two frames. The frames are ordered by a + semaphore chain and by the barrier at the start of the upload, and the layer does not follow that chain + between batches of one queue. It reports nothing between frames when each submit is followed by a fence wait. + It also reports the depth attachment of the final render pass (`WRITE_AFTER_WRITE vs. layout transition`), + which has nothing to do with the pipelining. +- With `--exec threaded` and `--frames-per-tick N`, the frame that a `--screenshot-ticks` capture shows can + differ from run to run when frames are fast: the game thread and the frames are not locked step by step. + Compare pictures of runs with the same mode in one build, or use `--frustum-culling off`. + +## Not done + +- The CPU still waits for an image in `Vk.Acquire` when the GPU is the slower side. That is the limit now: + reducing the GPU time (it is about 1.8 ms for the lighting test level) is the next gain. +- Three frames in flight, and overlapping two GPU frames, need a copy of the G-buffer images and the depth + pyramid for each frame slot. diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index 3ede446c..70a6fd7a 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -950,6 +950,13 @@ namespace Fling // The world still holds the game until the world is destroyed below m_GameImpl.reset(); + // The renderer records a frame while the GPU draws the one before: let the GPU finish before the models + // and textures that the frames use are freed + if (m_SystemsStarted && !m_Options.NullRender && m_World) + { + VulkanApp::Get().WaitForGpuIdle(); + } + // Cleanup any resources if (m_SystemsStarted) { diff --git a/FlingEngine/Graphics/inc/FrameSync.h b/FlingEngine/Graphics/inc/FrameSync.h new file mode 100644 index 00000000..e1f8f03f --- /dev/null +++ b/FlingEngine/Graphics/inc/FrameSync.h @@ -0,0 +1,106 @@ +#pragma once + +#include "FlingTypes.h" + +#include +#include + +namespace Fling +{ + /** + * Which frame the renderer records now, and which frames the GPU has finished. + * + * The renderer keeps VkConfig::MAX_FRAMES_IN_FLIGHT frames in flight: the CPU records frame N while + * the GPU still draws frame N-1. VulkanApp::Update calls Begin after it waited for the fence of the + * frame slot, so every frame up to N - FramesInFlight has finished on the GPU, and the frame N - 1 may + * still run. A resource that a recorded frame used can go only when IsDone says so. + * + * Main (render) thread only. + */ + class FrameSync + { + public: + /** How many frames the CPU can record ahead of the GPU. VulkanApp.cpp checks that it equals + * VkConfig::MAX_FRAMES_IN_FLIGHT. */ + static constexpr uint32 FramesInFlight = 2; + + /** Start frame t_Frame. Call it after the fence of the frame slot is done. */ + static void Begin(const uint64 t_Frame) { s_Frame = t_Frame; } + + /** The number of the frame that is recorded now */ + static uint64 Frame() { return s_Frame; } + + /** The frame slot: the index of the resources that only one frame in flight uses */ + static uint32 Slot() { return static_cast(s_Frame % FramesInFlight); } + + /** True if frame t_Frame and all before it are finished on the GPU, so what they used can go */ + static bool IsDone(const uint64 t_Frame) + { + return t_Frame + FramesInFlight <= s_Frame || t_Frame < s_IdleBefore; + } + + /** The device was idle just now: every frame before the current one is done. */ + static void MarkIdle() { s_IdleBefore = s_Frame; } + + /** Start again at frame 0 (a new renderer, a test) */ + static void Reset() + { + s_Frame = 0; + s_IdleBefore = 0; + } + + private: + static inline uint64 s_Frame = 0; + static inline uint64 s_IdleBefore = 0; + }; + + /** + * Things that were used by a frame in flight and can be freed only when the GPU is done with that + * frame. Add tags the item with the current frame; Release gives back the ones that are done. + */ + template + class RetireList + { + public: + void Add(T t_Item) { m_Items.emplace_back(FrameSync::Frame(), std::move(t_Item)); } + + /** Call t_Free for each item whose frame is done, and forget it */ + template + void Release(Fn&& t_Free) + { + size_t Kept = 0; + for (size_t i = 0; i < m_Items.size(); ++i) + { + if (FrameSync::IsDone(m_Items[i].first)) + { + t_Free(m_Items[i].second); + } + else + { + if (Kept != i) + { + m_Items[Kept] = std::move(m_Items[i]); + } + ++Kept; + } + } + m_Items.resize(Kept); + } + + /** Call t_Free for every item, done or not. The device is idle. */ + template + void ReleaseAll(Fn&& t_Free) + { + for (auto& Item : m_Items) + { + t_Free(Item.second); + } + m_Items.clear(); + } + + bool Empty() const { return m_Items.empty(); } + + private: + std::vector> m_Items; + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index 0a879a8c..cde9c218 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -77,6 +77,13 @@ namespace Fling /** Wait for the GPU, then free the render pipelines, the device, and the window. */ void ShutdownRenderer(); + /** + * Wait until the GPU has finished every frame that was recorded. The renderer records the next frame + * while the GPU still draws the last one, so call this before freeing a model, texture or other + * resource that a frame may have used. Main thread. + */ + void WaitForGpuIdle(); + /** * Wait for the screenshots that are being written (Screenshot::Request) and call their * callbacks. A frame copies a screenshot; a writer thread saves it later, so a run that @@ -186,7 +193,15 @@ namespace Fling /** Make the swap chain and what depends on it again (a resize, an out-of-date swap chain, a present mode * change). */ - void RecreateSwapchain(); + /** @return False when the swap chain stays (the window closed while it was minimized) */ + bool RecreateSwapchain(); + + /** Start the thread that presents and acquires, when the device has a queue for it. Not offscreen. */ + void StartPresentThread(); + + /** Make (again) the semaphores that the acquires of the present thread signal */ + void MakeAcquireSemaphores(); + void DestroyAcquireSemaphores(); /** Builds any render pipelines with their specific set of sub passes and shaders */ void BuildRenderPipelines(PipelineFlags t_Conf, diff --git a/FlingEngine/Graphics/src/DebugSubpass.cpp b/FlingEngine/Graphics/src/DebugSubpass.cpp index 3dd376bf..96823095 100644 --- a/FlingEngine/Graphics/src/DebugSubpass.cpp +++ b/FlingEngine/Graphics/src/DebugSubpass.cpp @@ -48,22 +48,25 @@ namespace Fling for (size_t i = 0; i < t_Snapshot.Meshes.size() && i < m_ItemSlots.size(); ++i) { - const GpuMesh& Mesh = m_GpuMeshes[m_ItemSlots[i]]; + const uint32 ItemSlot = m_ItemSlots[i]; + const GpuMesh& Mesh = m_GpuMeshes[ItemSlot]; if (!Mesh.Drawn || Mesh.MeshModel == nullptr) { continue; } + const FrameResources& Frame = m_FrameResources[ItemSlot]; + const uint32 FrameSlot = FrameSync::Slot(); Fling::Model* Model = Mesh.MeshModel; m_Ubo.Model = t_Snapshot.Meshes[i].ResolveWorld(t_Snapshot.BlendAlpha); - memcpy(Mesh.Ubo->m_MappedMem, &m_Ubo, sizeof(m_Ubo)); + memcpy(Frame.Ubos[FrameSlot]->m_MappedMem, &m_Ubo, sizeof(m_Ubo)); vkCmdBindDescriptorSets(t_CmdBuf.GetHandle(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_GraphicsPipeline->GetPipelineLayout(), 0, 1, - &Mesh.Set, + &Frame.Sets[FrameSlot], 0, nullptr); @@ -83,16 +86,17 @@ namespace Fling MeshProxyTable::SyncResult Result = m_Proxies.Sync(t_Snapshot.Meshes); m_ItemSlots = std::move(Result.ItemSlots); m_GpuMeshes.resize(m_Proxies.Capacity()); + m_FrameResources.resize(m_Proxies.Capacity()); for (const uint32 Slot : Result.Removed) { - RetireGpuMesh(m_GpuMeshes[Slot]); + RetireGpuMesh(Slot); } auto Prepare = [&](const uint32 Slot) { + RetireGpuMesh(Slot); GpuMesh& Mesh = m_GpuMeshes[Slot]; - RetireGpuMesh(Mesh); const bool bHasAssets = ResolveMeshAssets(m_Proxies.At(Slot), Mesh); Mesh.Drawn = bHasAssets && Mesh.MeshMaterial->GetType() == Material::Type::Debug; if (!Mesh.Drawn) @@ -102,11 +106,18 @@ namespace Fling } const VkDeviceSize BufferSize = sizeof(DebugUBO); - Mesh.Ubo = new Buffer(BufferSize, - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - Mesh.Ubo->MapMemory(BufferSize); - CreateMeshDescriptorSet(Mesh); + FrameResources& Frame = m_FrameResources[Slot]; + for (uint32 f = 0; f < FrameSync::FramesInFlight; ++f) + { + Frame.Ubos[f] = new Buffer(BufferSize, + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + Frame.Ubos[f]->MapMemory(BufferSize); + CreateMeshDescriptorSet(Frame.Sets[f], Frame.Ubos[f]); + } + // The first frame's resources stand for the mesh in the checks of the other code + Mesh.Ubo = Frame.Ubos[0]; + Mesh.Set = Frame.Sets[0]; }; for (const uint32 Slot : Result.Added) @@ -119,44 +130,56 @@ namespace Fling } } - void DebugSubpass::RetireGpuMesh(GpuMesh& t_Mesh) + void DebugSubpass::RetireGpuMesh(const uint32 t_Slot) { - if (t_Mesh.Set != VK_NULL_HANDLE) - { - m_RetiredDescriptorSets.emplace_back(t_Mesh.Set); - } - if (t_Mesh.Ubo != nullptr) + FrameResources& Frame = m_FrameResources[t_Slot]; + for (uint32 f = 0; f < FrameSync::FramesInFlight; ++f) { - m_RetiredUniformBuffers.emplace_back(t_Mesh.Ubo); + if (Frame.Sets[f] != VK_NULL_HANDLE) + { + m_RetiredDescriptorSets.Add(Frame.Sets[f]); + } + if (Frame.Ubos[f] != nullptr) + { + m_RetiredUniformBuffers.Add(Frame.Ubos[f]); + } } - t_Mesh = GpuMesh{}; + Frame = FrameResources{}; + m_GpuMeshes[t_Slot] = GpuMesh{}; } - void DebugSubpass::ReleaseRetiredMeshResources() + void DebugSubpass::ReleaseRetiredMeshResources(const bool t_All) { - if (!m_RetiredDescriptorSets.empty() && m_DescriptorPool != VK_NULL_HANDLE) + auto FreeSet = [this](const VkDescriptorSet t_Set) { - VK_CHECK_RESULT(vkFreeDescriptorSets(m_Device->GetVkDevice(), - m_DescriptorPool, - static_cast(m_RetiredDescriptorSets.size()), - m_RetiredDescriptorSets.data())); + if (m_DescriptorPool != VK_NULL_HANDLE) + { + VK_CHECK_RESULT(vkFreeDescriptorSets(m_Device->GetVkDevice(), m_DescriptorPool, 1, &t_Set)); + } + }; + auto FreeBuffer = [](Buffer* t_Buffer) + { + delete t_Buffer; + }; + if (t_All) + { + m_RetiredDescriptorSets.ReleaseAll(FreeSet); + m_RetiredUniformBuffers.ReleaseAll(FreeBuffer); } - m_RetiredDescriptorSets.clear(); - - for (Buffer* Ubo : m_RetiredUniformBuffers) + else { - delete Ubo; + m_RetiredDescriptorSets.Release(FreeSet); + m_RetiredUniformBuffers.Release(FreeBuffer); } - m_RetiredUniformBuffers.clear(); } void DebugSubpass::CreateDescriptorSets(VkDescriptorPool t_Pool) { } - void DebugSubpass::CreateMeshDescriptorSet(GpuMesh& t_Mesh) + void DebugSubpass::CreateMeshDescriptorSet(VkDescriptorSet& t_Set, Buffer* t_Ubo) { - if (t_Mesh.Set == VK_NULL_HANDLE) + if (t_Set == VK_NULL_HANDLE) { VkDescriptorSetLayout layout = m_GraphicsPipeline->GetDescriptorSetLayout(); VkDescriptorSetAllocateInfo allocInfo = {}; @@ -166,12 +189,12 @@ namespace Fling allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &layout; - VK_CHECK_RESULT(vkAllocateDescriptorSets(m_Device->GetVkDevice(), &allocInfo, &t_Mesh.Set)); + VK_CHECK_RESULT(vkAllocateDescriptorSets(m_Device->GetVkDevice(), &allocInfo, &t_Set)); } std::vector writeDescriptorSets = { // 0: UBO - Initializers::WriteDescriptorSetUniform(t_Mesh.Ubo, t_Mesh.Set, 0), + Initializers::WriteDescriptorSetUniform(t_Ubo, t_Set, 0), }; vkUpdateDescriptorSets(m_Device->GetVkDevice(), @@ -184,7 +207,7 @@ namespace Fling void DebugSubpass::PrepareAttachments() { // Create the descriptor pool for off screen things - uint32 DescriptorCount = 100 * m_SwapChain->GetImageViewCount(); + const uint32 DescriptorCount = 100 * m_SwapChain->GetImageViewCount() * FrameSync::FramesInFlight; std::vector poolSizes = { Initializers::DescriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, DescriptorCount), @@ -196,7 +219,7 @@ namespace Fling poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; poolInfo.poolSizeCount = static_cast(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); - poolInfo.maxSets = to_u32(100 * m_SwapChain->GetImageViewCount()); + poolInfo.maxSets = DescriptorCount; if (vkCreateDescriptorPool(m_Device->GetVkDevice(), &poolInfo, nullptr, &m_DescriptorPool) != VK_SUCCESS) { @@ -217,14 +240,15 @@ namespace Fling void DebugSubpass::CleanUp() { // Called after the device is idle - for (GpuMesh& Mesh : m_GpuMeshes) + for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) { - RetireGpuMesh(Mesh); + RetireGpuMesh(Slot); } m_GpuMeshes.clear(); + m_FrameResources.clear(); m_Proxies.Clear(); m_ItemSlots.clear(); - ReleaseRetiredMeshResources(); + ReleaseRetiredMeshResources(true); if (m_DescriptorPool != VK_NULL_HANDLE) { diff --git a/FlingEngine/Graphics/src/DebugSubpass.h b/FlingEngine/Graphics/src/DebugSubpass.h index 666a5282..a31ad7d4 100644 --- a/FlingEngine/Graphics/src/DebugSubpass.h +++ b/FlingEngine/Graphics/src/DebugSubpass.h @@ -1,10 +1,12 @@ #pragma once #include "FlingMath.h" +#include "FrameSync.h" #include "GpuMesh.h" #include "MeshProxyTable.h" #include "Subpass.h" +#include #include #include @@ -48,12 +50,12 @@ namespace Fling /** Match the proxies to the snapshot, and make resources for meshes with a debug material */ void SyncProxies(const RenderSnapshot& t_Snapshot); - void RetireGpuMesh(GpuMesh& t_Mesh); + void RetireGpuMesh(uint32 t_Slot); - /** Free retired sets and UBOs. The previous frame has finished on the GPU when Draw starts. */ - void ReleaseRetiredMeshResources(); + /** Free retired sets and UBOs whose frames are finished on the GPU (t_All: all of them, the device is idle) */ + void ReleaseRetiredMeshResources(bool t_All = false); - void CreateMeshDescriptorSet(GpuMesh& t_Mesh); + void CreateMeshDescriptorSet(VkDescriptorSet& t_Set, Buffer* t_Ubo); VkRenderPass m_GlobalRenderPass = VK_NULL_HANDLE; @@ -75,8 +77,19 @@ namespace Fling std::vector m_ItemSlots; - std::vector m_RetiredDescriptorSets; + /** + * The UBO and the descriptor set of a mesh for each frame slot: the CPU writes the UBO of the slot that it + * records while the GPU may still read the one of the frame before. Indexed by slot like m_GpuMeshes. + */ + struct FrameResources + { + std::array Ubos{}; + std::array Sets{}; + }; + std::vector m_FrameResources; + + RetireList m_RetiredDescriptorSets; - std::vector m_RetiredUniformBuffers; + RetireList m_RetiredUniformBuffers; }; } // namespace Fling \ No newline at end of file diff --git a/FlingEngine/Graphics/src/FrameCapture.h b/FlingEngine/Graphics/src/FrameCapture.h index 01a08744..5b388b78 100644 --- a/FlingEngine/Graphics/src/FrameCapture.h +++ b/FlingEngine/Graphics/src/FrameCapture.h @@ -69,6 +69,9 @@ namespace Fling /** The fence of the frame that RecordCopy recorded into has signaled: start the writes. Main thread. */ void OnFrameDone(); + /** True if RecordCopy recorded a copy whose frame OnFrameDone has not seen yet */ + bool HasRecorded() const { return m_Recorded != nullptr; } + /** Call the callbacks of the captures that the writer finished. Main thread. */ void DeliverResults(); diff --git a/FlingEngine/Graphics/src/FrameUploader.cpp b/FlingEngine/Graphics/src/FrameUploader.cpp new file mode 100644 index 00000000..0f4963bf --- /dev/null +++ b/FlingEngine/Graphics/src/FrameUploader.cpp @@ -0,0 +1,231 @@ +#include "Buffer.h" +#include "CommandBuffer.h" +#include "FrameSync.h" +#include "FrameUploader.h" +#include "GraphicsHelpers.h" +#include "LogicalDevice.h" +#include "Profiler.h" + +#include +#include + +namespace Fling +{ + namespace + { + constexpr VkDeviceSize MinChunkSize = 256 * 1024; + constexpr VkDeviceSize Alignment = 16; + } // namespace + + FrameUploader::FrameUploader(const LogicalDevice* t_Device) : m_Device(t_Device) + { + GraphicsHelpers::CreateCommandPool(&m_Pool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); + m_Slots.resize(FrameSync::FramesInFlight); + for (Slot& Each : m_Slots) + { + Each.Cmd = std::make_unique(m_Device, m_Pool); + } + } + + FrameUploader::~FrameUploader() + { + // The device is idle when the renderer shuts down + for (Slot& Each : m_Slots) + { + Each.Chunks.clear(); + Each.Cmd.reset(); + } + vkDestroyCommandPool(m_Device->GetVkDevice(), m_Pool, nullptr); + } + + void FrameUploader::Begin() + { + m_Current = &m_Slots[FrameSync::Slot()]; + Slot& S = *m_Current; + VkDeviceSize Used = 0; + for (const Chunk& Each : S.Chunks) + { + Used += Each.Used; + } + S.LastUsed = Used; + if (S.Chunks.size() > 1) + { + // The last frame needed more than one chunk: one larger chunk serves a frame of that size + S.Chunks.clear(); + } + for (Chunk& Each : S.Chunks) + { + Each.Used = 0; + } + S.Ops.clear(); + } + + void* FrameUploader::Stage(const Buffer& t_Dst, const VkDeviceSize t_DstOffset, const VkDeviceSize t_Size) + { + assert(m_Current != nullptr); + Slot& S = *m_Current; + const VkDeviceSize Size = (t_Size + Alignment - 1) & ~(Alignment - 1); + + Chunk* Target = nullptr; + if (!S.Chunks.empty() && S.Chunks.back().Capacity - S.Chunks.back().Used >= Size) + { + Target = &S.Chunks.back(); + } + else + { + Chunk Fresh; + // Twice what the last frame used, so a steady load needs one chunk + Fresh.Capacity = std::max({Size, MinChunkSize, S.LastUsed * 2}); + Fresh.Staging = + std::make_unique(Fresh.Capacity, + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + Fresh.Staging->MapMemory(Fresh.Capacity); + S.Chunks.push_back(std::move(Fresh)); + Target = &S.Chunks.back(); + } + + Op Queued; + Queued.Type = Op::Kind::Stage; + Queued.Src = Target->Staging->GetVkBuffer(); + Queued.Dst = t_Dst.GetVkBuffer(); + Queued.SrcOffset = Target->Used; + Queued.DstOffset = t_DstOffset; + Queued.Size = t_Size; + S.Ops.push_back(Queued); + + void* Out = static_cast(Target->Staging->m_MappedMem) + Target->Used; + Target->Used += Size; + return Out; + } + + void FrameUploader::Fill(const Buffer& t_Dst, + const VkDeviceSize t_DstOffset, + const VkDeviceSize t_Size, + const uint32 t_Value) + { + assert(m_Current != nullptr); + Op Queued; + Queued.Type = Op::Kind::Fill; + Queued.Dst = t_Dst.GetVkBuffer(); + Queued.DstOffset = t_DstOffset; + Queued.Size = t_Size; + Queued.Value = t_Value; + m_Current->Ops.push_back(Queued); + } + + void FrameUploader::Copy(const Buffer& t_Src, const Buffer& t_Dst, const VkDeviceSize t_Size) + { + assert(m_Current != nullptr); + Op Queued; + Queued.Type = Op::Kind::Copy; + Queued.Src = t_Src.GetVkBuffer(); + Queued.Dst = t_Dst.GetVkBuffer(); + Queued.Size = t_Size; + m_Current->Ops.push_back(Queued); + } + + CommandBuffer* FrameUploader::Record() + { + assert(m_Current != nullptr); + FLING_PROFILE_SCOPE("Upload.Record"); + Slot& S = *m_Current; + CommandBuffer& Cmd = *S.Cmd; + Cmd.Begin(); + Cmd.BeginLabel("Upload"); + + // The frame before this one is finished on the GPU before anything below runs + VkMemoryBarrier Head = {}; + Head.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; + Head.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + Head.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + vkCmdPipelineBarrier(Cmd.GetHandle(), + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + 0, + 1, + &Head, + 0, + nullptr, + 0, + nullptr); + + std::vector Regions; + // The buffers that an earlier copy or fill of this command buffer wrote: using one again needs a barrier + std::vector Written; + auto IsWritten = [&Written](const VkBuffer t_Buffer) + { + return std::find(Written.begin(), Written.end(), t_Buffer) != Written.end(); + }; + auto TransferBarrier = [&]() + { + VkMemoryBarrier Between = {}; + Between.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; + Between.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + Between.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + vkCmdPipelineBarrier(Cmd.GetHandle(), + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, + 1, + &Between, + 0, + nullptr, + 0, + nullptr); + Written.clear(); + }; + size_t i = 0; + while (i < S.Ops.size()) + { + const Op& First = S.Ops[i]; + if (First.Type == Op::Kind::Fill) + { + if (IsWritten(First.Dst)) + { + TransferBarrier(); + } + vkCmdFillBuffer(Cmd.GetHandle(), First.Dst, First.DstOffset, First.Size, First.Value); + Written.push_back(First.Dst); + ++i; + continue; + } + if (IsWritten(First.Dst) || (First.Type == Op::Kind::Copy && IsWritten(First.Src))) + { + TransferBarrier(); + } + // Neighbors with the same source and target go in one call + Regions.clear(); + size_t j = i; + while (j < S.Ops.size() && S.Ops[j].Type != Op::Kind::Fill && S.Ops[j].Src == First.Src && + S.Ops[j].Dst == First.Dst) + { + Regions.push_back({S.Ops[j].SrcOffset, S.Ops[j].DstOffset, S.Ops[j].Size}); + ++j; + } + vkCmdCopyBuffer(Cmd.GetHandle(), First.Src, First.Dst, static_cast(Regions.size()), Regions.data()); + Written.push_back(First.Dst); + i = j; + } + + // The copies are visible to everything that follows in this frame (and to the host, for the readback buffers) + VkMemoryBarrier Tail = {}; + Tail.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; + Tail.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + Tail.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + vkCmdPipelineBarrier(Cmd.GetHandle(), + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + 0, + 1, + &Tail, + 0, + nullptr, + 0, + nullptr); + + Cmd.EndLabel(); + Cmd.End(); + return &Cmd; + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/FrameUploader.h b/FlingEngine/Graphics/src/FrameUploader.h new file mode 100644 index 00000000..d8b971ed --- /dev/null +++ b/FlingEngine/Graphics/src/FrameUploader.h @@ -0,0 +1,100 @@ +#pragma once + +#include "FlingTypes.h" +#include "FlingVulkan.h" + +#include +#include + +namespace Fling +{ + class Buffer; + class CommandBuffer; + class LogicalDevice; + + /** + * Sends the data that the CPU makes each frame to GPU buffers, without the CPU writing to memory + * that a frame in flight still reads. + * + * The CPU writes into a staging buffer that only this frame slot uses (Stage), and the GPU copies it + * to the real buffer when it runs this frame (Record makes a command buffer, which goes first in the + * frame's submission). The real buffers are in GPU memory and only the GPU writes them, in submission + * order, so a frame that records while the one before it still draws never races with it. + * + * The command buffer starts with a memory barrier that waits for the whole frame before it. The + * frames on the GPU therefore run one after the other, which is what the passes assume (the + * G-buffer images, the depth pyramid and the visibility flags are shared by every frame). + * The CPU and the GPU overlap, the GPU frames do not. + * + * Main (render) thread only. Begin, then Stage, Fill and Copy any number of times, then Record. + */ + class FrameUploader + { + public: + explicit FrameUploader(const LogicalDevice* t_Device); + ~FrameUploader(); + + FrameUploader(const FrameUploader&) = delete; + FrameUploader& operator=(const FrameUploader&) = delete; + + /** Start this frame's uploads. The frame slot's last frame is finished (VulkanApp waited for its fence). */ + void Begin(); + + /** + * Queue a copy of t_Size bytes into t_Dst at t_DstOffset, and give the memory to write them to. + * The pointer is valid until Record. The buffer needs VK_BUFFER_USAGE_TRANSFER_DST_BIT. + */ + void* Stage(const Buffer& t_Dst, VkDeviceSize t_DstOffset, VkDeviceSize t_Size); + + /** Queue a fill of a range of t_Dst with t_Value (a multiple of 4 bytes) */ + void Fill(const Buffer& t_Dst, VkDeviceSize t_DstOffset, VkDeviceSize t_Size, uint32 t_Value); + + /** + * Queue a copy on the GPU, from the start of t_Src to the start of t_Dst. It runs after the barrier at + * the start of the frame, so it sees the writes of the frame before. + */ + void Copy(const Buffer& t_Src, const Buffer& t_Dst, VkDeviceSize t_Size); + + /** Record the frame's copies. The command buffer goes first in this frame's submission. */ + CommandBuffer* Record(); + + private: + struct Chunk + { + std::unique_ptr Staging; + VkDeviceSize Capacity = 0; + VkDeviceSize Used = 0; + }; + + struct Op + { + enum class Kind : uint8 + { + Stage, + Fill, + Copy + }; + Kind Type = Kind::Stage; + VkBuffer Src = VK_NULL_HANDLE; + VkBuffer Dst = VK_NULL_HANDLE; + VkDeviceSize SrcOffset = 0; + VkDeviceSize DstOffset = 0; + VkDeviceSize Size = 0; + uint32 Value = 0; + }; + + /** What one frame slot holds: its staging memory, its queued copies and its command buffer */ + struct Slot + { + std::vector Chunks; + std::vector Ops; + std::unique_ptr Cmd; + VkDeviceSize LastUsed = 0; + }; + + const LogicalDevice* m_Device; + VkCommandPool m_Pool = VK_NULL_HANDLE; + std::vector m_Slots; + Slot* m_Current = nullptr; + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/src/ImGuiSubpass.cpp b/FlingEngine/Graphics/src/ImGuiSubpass.cpp index 0c38095a..015eccc1 100644 --- a/FlingEngine/Graphics/src/ImGuiSubpass.cpp +++ b/FlingEngine/Graphics/src/ImGuiSubpass.cpp @@ -138,9 +138,10 @@ namespace Fling if (imDrawData->CmdListsCount > 0) { VkDeviceSize offsets[1] = {0}; - vkCmdBindVertexBuffers(t_commandBuffer, 0, 1, &m_vertexBuffer->GetVkBuffer(), offsets); + vkCmdBindVertexBuffers(t_commandBuffer, 0, 1, &m_vertexBuffer[FrameSync::Slot()]->GetVkBuffer(), offsets); - vkCmdBindIndexBuffer(t_commandBuffer, m_indexBuffer->GetVkBuffer(), 0, VK_INDEX_TYPE_UINT16); + vkCmdBindIndexBuffer( + t_commandBuffer, m_indexBuffer[FrameSync::Slot()]->GetVkBuffer(), 0, VK_INDEX_TYPE_UINT16); for (int32 i = 0; i < imDrawData->CmdListsCount; ++i) { @@ -462,13 +463,17 @@ namespace Fling void ImGuiSubpass::PrepareResources() { // Create vert and index buffers for use with imgui geometry - m_indexBuffer = std::make_unique(); - m_vertexBuffer = std::make_unique(); + for (uint32 f = 0; f < FrameSync::FramesInFlight; ++f) + { + m_indexBuffer[f] = std::make_unique(); + m_vertexBuffer[f] = std::make_unique(); + } } void ImGuiSubpass::UpdateUniforms() { ImDrawData* imDrawData = ImGui::GetDrawData(); + const uint32 Slot = FrameSync::Slot(); VkDeviceSize vertexBufferSize = imDrawData->TotalVtxCount * sizeof(ImDrawVert); VkDeviceSize indexBufferSize = imDrawData->TotalIdxCount * sizeof(ImDrawIdx); @@ -478,30 +483,31 @@ namespace Fling return; } - if ((m_vertexBuffer->GetVkBuffer() == VK_NULL_HANDLE) || (m_vertexCount != imDrawData->TotalVtxCount)) + if ((m_vertexBuffer[Slot]->GetVkBuffer() == VK_NULL_HANDLE) || + (m_vertexCount[Slot] != imDrawData->TotalVtxCount)) { - m_vertexBuffer->UnmapMemory(); - m_vertexBuffer->Release(); + m_vertexBuffer[Slot]->UnmapMemory(); + m_vertexBuffer[Slot]->Release(); - m_vertexBuffer->CreateBuffer( + m_vertexBuffer[Slot]->CreateBuffer( vertexBufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, true); - m_vertexCount = imDrawData->TotalVtxCount; - m_vertexBuffer->MapMemory(); + m_vertexCount[Slot] = imDrawData->TotalVtxCount; + m_vertexBuffer[Slot]->MapMemory(); } - if ((m_indexBuffer->GetVkBuffer() == VK_NULL_HANDLE) || (m_indexCount < imDrawData->TotalIdxCount)) + if ((m_indexBuffer[Slot]->GetVkBuffer() == VK_NULL_HANDLE) || (m_indexCount[Slot] < imDrawData->TotalIdxCount)) { - m_indexBuffer->UnmapMemory(); - m_indexBuffer->Release(); + m_indexBuffer[Slot]->UnmapMemory(); + m_indexBuffer[Slot]->Release(); - m_indexBuffer->CreateBuffer( + m_indexBuffer[Slot]->CreateBuffer( indexBufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, true); - m_indexCount = imDrawData->TotalIdxCount; - m_indexBuffer->MapMemory(); + m_indexCount[Slot] = imDrawData->TotalIdxCount; + m_indexBuffer[Slot]->MapMemory(); } - ImDrawVert* vtxDst = (ImDrawVert*)m_vertexBuffer->m_MappedMem; - ImDrawIdx* idxDst = (ImDrawIdx*)m_indexBuffer->m_MappedMem; + ImDrawVert* vtxDst = (ImDrawVert*)m_vertexBuffer[Slot]->m_MappedMem; + ImDrawIdx* idxDst = (ImDrawIdx*)m_indexBuffer[Slot]->m_MappedMem; for (int n = 0; n < imDrawData->CmdListsCount; ++n) { @@ -512,8 +518,8 @@ namespace Fling idxDst += cmd_list->IdxBuffer.Size; } - m_vertexBuffer->Flush(VK_WHOLE_SIZE, 0); - m_indexBuffer->Flush(VK_WHOLE_SIZE, 0); + m_vertexBuffer[Slot]->Flush(VK_WHOLE_SIZE, 0); + m_indexBuffer[Slot]->Flush(VK_WHOLE_SIZE, 0); } } // namespace Fling diff --git a/FlingEngine/Graphics/src/ImGuiSubpass.h b/FlingEngine/Graphics/src/ImGuiSubpass.h index bf0ac3c4..fa6973c6 100644 --- a/FlingEngine/Graphics/src/ImGuiSubpass.h +++ b/FlingEngine/Graphics/src/ImGuiSubpass.h @@ -2,8 +2,10 @@ #include "Ecs/EntityStorage.h" #include "FlingMath.h" +#include "FrameSync.h" #include "Subpass.h" +#include #include namespace Fling @@ -65,8 +67,10 @@ namespace Fling glm::vec2 translate; } pushConstBlock; - std::unique_ptr m_vertexBuffer; - std::unique_ptr m_indexBuffer; + /** The geometry of the UI: one pair of buffers for each frame slot, because the CPU writes the pair of the + * frame it records */ + std::array, FrameSync::FramesInFlight> m_vertexBuffer; + std::array, FrameSync::FramesInFlight> m_indexBuffer; VkDescriptorPool m_descriptorPool = VK_NULL_HANDLE; VkDescriptorSetLayout m_descriptorSetLayout = VK_NULL_HANDLE; @@ -86,8 +90,8 @@ namespace Fling /** Instance of the editor that we will get what commands to build from */ std::shared_ptr m_DebugUI; - int32 m_vertexCount = 0; - int32 m_indexCount = 0; + std::array m_vertexCount{}; + std::array m_indexCount{}; VkRenderPass m_GlobalRenderPass = VK_NULL_HANDLE; }; diff --git a/FlingEngine/Graphics/src/LogicalDevice.cpp b/FlingEngine/Graphics/src/LogicalDevice.cpp index 172cba99..fd91d2a4 100644 --- a/FlingEngine/Graphics/src/LogicalDevice.cpp +++ b/FlingEngine/Graphics/src/LogicalDevice.cpp @@ -1,4 +1,5 @@ #include "FlingIntegers.h" +#include "FrameSync.h" #include "Instance.h" #include "Logger.h" #include "LogicalDevice.h" @@ -25,6 +26,11 @@ namespace Fling vkGetPhysicalDeviceQueueFamilyProperties(PhysDevice, &QueueFamilyCount, nullptr); std::vector QueueFamilies(QueueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(PhysDevice, &QueueFamilyCount, QueueFamilies.data()); + m_FamilyQueueCounts.resize(QueueFamilyCount); + for (uint32 i = 0; i < QueueFamilyCount; ++i) + { + m_FamilyQueueCounts[i] = QueueFamilies[i].queueCount; + } std::optional graphicsFamily; std::optional presentFamily; @@ -95,14 +101,18 @@ namespace Fling // Generate the CreatinInfo for each queue family std::vector QueueCreateInfos; - float Priority = 1.0f; + float Priority[2] = {1.0f, 1.0f}; + // A second queue of the graphics family, for presenting from its own thread (a queue is externally + // synchronized, and vkQueuePresentKHR can block until the GPU has finished the frame) + m_SeparatePresentQueue = m_GraphicsFamily == m_PresentFamily && m_Surface != VK_NULL_HANDLE && + m_FamilyQueueCounts[m_GraphicsFamily] >= 2; for (const uint32 fam : UniqueQueueFamilies) { VkDeviceQueueCreateInfo QueueCreateInfo = {}; QueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; QueueCreateInfo.queueFamilyIndex = fam; - QueueCreateInfo.queueCount = 1; - QueueCreateInfo.pQueuePriorities = &Priority; + QueueCreateInfo.queueCount = (fam == m_GraphicsFamily && m_SeparatePresentQueue) ? 2 : 1; + QueueCreateInfo.pQueuePriorities = Priority; QueueCreateInfos.push_back(QueueCreateInfo); } @@ -139,12 +149,18 @@ namespace Fling VulkanLoader::LoadDevice(m_Device); vkGetDeviceQueue(m_Device, m_GraphicsFamily, 0, &m_GraphicsQueue); - vkGetDeviceQueue(m_Device, m_PresentFamily, 0, &m_PresentQueue); + vkGetDeviceQueue(m_Device, m_PresentFamily, m_SeparatePresentQueue ? 1 : 0, &m_PresentQueue); } - void LogicalDevice::WaitForIdle() + void LogicalDevice::WaitForIdle() const { + // A thread that presents holds its queue, which the wait needs to be free + if (m_BeforeIdle) + { + m_BeforeIdle(); + } vkDeviceWaitIdle(m_Device); + FrameSync::MarkIdle(); } LogicalDevice::~LogicalDevice() diff --git a/FlingEngine/Graphics/src/LogicalDevice.h b/FlingEngine/Graphics/src/LogicalDevice.h index 8c0f2989..0a686c73 100644 --- a/FlingEngine/Graphics/src/LogicalDevice.h +++ b/FlingEngine/Graphics/src/LogicalDevice.h @@ -3,6 +3,9 @@ #include "FlingTypes.h" #include "FlingVulkan.h" +#include +#include + namespace Fling { class PhysicalDevice; @@ -33,7 +36,20 @@ namespace Fling uint32 GetGraphicsFamily() const { return m_GraphicsFamily; } uint32 GetPresentFamily() const { return m_PresentFamily; } - void WaitForIdle(); + /** + * True if the present queue is a queue of its own (the graphics family has two), so another thread can + * present while this one submits. vkQueuePresentKHR can block until the GPU has finished the frame. + */ + bool HasSeparatePresentQueue() const { return m_SeparatePresentQueue; } + + /** + * A function that WaitForIdle calls before it waits: the thread that presents makes its queue free there. + * Main (render) thread only. + */ + void SetBeforeIdle(std::function t_Function) { m_BeforeIdle = std::move(t_Function); } + + /** Wait until the GPU is idle. Every frame before the current one is finished then (FrameSync). */ + void WaitForIdle() const; private: /** The vulkan logical device */ @@ -51,6 +67,9 @@ namespace Fling /** Queue families */ VkQueueFlags m_SupportedQueues{}; + bool m_SeparatePresentQueue = false; + std::vector m_FamilyQueueCounts; + std::function m_BeforeIdle; uint32 m_GraphicsFamily = 0; uint32 m_PresentFamily = 0; uint32 m_ComputeFamily = 0; diff --git a/FlingEngine/Graphics/src/OcclusionCuller.cpp b/FlingEngine/Graphics/src/OcclusionCuller.cpp index 10a22360..1661edcc 100644 --- a/FlingEngine/Graphics/src/OcclusionCuller.cpp +++ b/FlingEngine/Graphics/src/OcclusionCuller.cpp @@ -1,4 +1,5 @@ #include "Buffer.h" +#include "FrameUploader.h" #include "GraphicsHelpers.h" #include "Logger.h" #include "LogicalDevice.h" @@ -21,6 +22,8 @@ namespace Fling constexpr uint32 DownsampleGroupSize = 8; constexpr VkMemoryPropertyFlags HostVisible = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + /** The buffers that the CPU fills each frame are in GPU memory: the frame's upload copies into them */ + constexpr VkMemoryPropertyFlags DeviceLocal = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; /** The std140 block Params of cull.comp */ struct alignas(16) CullParams @@ -65,9 +68,10 @@ namespace Fling } // namespace OcclusionCuller::OcclusionCuller(const LogicalDevice* t_Device, + FrameUploader* t_Uploader, std::shared_ptr t_Downsample, std::shared_ptr t_Cull) - : m_Device(t_Device) + : m_Device(t_Device), m_Uploader(t_Uploader) { assert(m_Device); if (!t_Downsample || !t_Cull || t_Downsample->GetShaderModule() == VK_NULL_HANDLE || @@ -110,12 +114,18 @@ namespace Fling Alloc.pSetLayouts = &m_CullSetLayout; VK_CHECK_RESULT(vkAllocateDescriptorSets(Dev, &Alloc, &m_CullSet)); - m_Params = new Buffer(sizeof(CullParams), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, HostVisible); - m_Params->MapMemory(sizeof(CullParams)); - m_Stats = new Buffer( - sizeof(uint32) * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, HostVisible); - m_Stats->MapMemory(sizeof(uint32) * 4); - std::memset(m_Stats->m_MappedMem, 0, sizeof(uint32) * 4); + m_Params = new Buffer( + sizeof(CullParams), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, DeviceLocal); + m_Stats = new Buffer(sizeof(uint32) * 4, + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + DeviceLocal); + for (Buffer*& Each : m_Readback) + { + Each = new Buffer(sizeof(uint32) * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, HostVisible); + Each->MapMemory(sizeof(uint32) * 4); + std::memset(Each->m_MappedMem, 0, sizeof(uint32) * 4); + } m_Supported = true; } @@ -124,9 +134,10 @@ namespace Fling { const VkDevice Dev = m_Device->GetVkDevice(); DestroyPyramid(); - for (Buffer* B : m_Retired) + m_Retired.ReleaseAll([](Buffer* t_Buffer) { delete t_Buffer; }); + for (Buffer* Each : m_Readback) { - delete B; + delete Each; } delete m_Params; delete m_Slots; @@ -361,27 +372,38 @@ namespace Fling if (m_Capacity < t_Slots || m_Slots == nullptr) { const size_t Capacity = std::max(t_Slots, 64); + const bool bReplace = m_Slots != nullptr; + if (bReplace) + { + // The sets of the frames in flight point at the old buffers: let those frames finish first + m_Device->WaitForIdle(); + } for (Buffer* Old : {m_Slots, m_Draw2, m_Visible}) { if (Old != nullptr) { - m_Retired.push_back(Old); + m_Retired.Add(Old); } } - m_Slots = new Buffer(sizeof(OcclusionSlot) * Capacity, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, HostVisible); - m_Slots->MapMemory(sizeof(OcclusionSlot) * Capacity); - std::memset(m_Slots->m_MappedMem, 0, sizeof(OcclusionSlot) * Capacity); + m_Slots = new Buffer(sizeof(OcclusionSlot) * Capacity, + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + DeviceLocal); m_Draw2 = new Buffer(sizeof(VkDrawIndexedIndirectCommand) * Capacity, - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, - HostVisible); - m_Draw2->MapMemory(sizeof(VkDrawIndexedIndirectCommand) * Capacity); - std::memset(m_Draw2->m_MappedMem, 0, sizeof(VkDrawIndexedIndirectCommand) * Capacity); + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | + VK_BUFFER_USAGE_TRANSFER_DST_BIT, + DeviceLocal); + m_Uploader->Fill(*m_Draw2, 0, sizeof(VkDrawIndexedIndirectCommand) * Capacity, 0); // Nothing was visible yet, so the first frame draws everything in the second pass - m_Visible = new Buffer(sizeof(uint32) * Capacity, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, HostVisible); - m_Visible->MapMemory(sizeof(uint32) * Capacity); - std::memset(m_Visible->m_MappedMem, 0, sizeof(uint32) * Capacity); + m_Visible = new Buffer(sizeof(uint32) * Capacity, + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + DeviceLocal); + m_Uploader->Fill(*m_Visible, 0, sizeof(uint32) * Capacity, 0); m_Capacity = Capacity; } + if (m_Draw1 != t_Draw1 && m_Draw1 != nullptr) + { + m_Device->WaitForIdle(); + } m_Draw1 = t_Draw1; WriteCullDescriptors(); return true; @@ -389,11 +411,7 @@ namespace Fling void OcclusionCuller::ReleaseRetired() { - for (Buffer* B : m_Retired) - { - delete B; - } - m_Retired.clear(); + m_Retired.Release([](Buffer* t_Buffer) { delete t_Buffer; }); } void OcclusionCuller::WriteCullDescriptors() const @@ -436,19 +454,35 @@ namespace Fling vkUpdateDescriptorSets(m_Device->GetVkDevice(), static_cast(Writes.size()), Writes.data(), 0, nullptr); } - OcclusionSlot* OcclusionCuller::MappedSlots() const + OcclusionSlot* OcclusionCuller::StageSlots(const size_t t_Count) { - return m_Slots != nullptr ? static_cast(m_Slots->m_MappedMem) : nullptr; + assert(m_Slots != nullptr && t_Count <= m_Capacity); + return static_cast(m_Uploader->Stage(*m_Slots, 0, sizeof(OcclusionSlot) * t_Count)); + } + + void OcclusionCuller::QueueStatsReadback() + { + if (!m_Supported) + { + return; + } + if (!m_StatsReady) + { + // Device memory starts with whatever was there + m_Uploader->Fill(*m_Stats, 0, sizeof(uint32) * 4, 0); + m_StatsReady = true; + } + m_Uploader->Copy(*m_Stats, *m_Readback[FrameSync::Slot()], sizeof(uint32) * 4); } uint32 OcclusionCuller::ReadOccludedCount() const { - return m_Stats != nullptr ? *static_cast(m_Stats->m_MappedMem) : 0; + return *static_cast(m_Readback[FrameSync::Slot()]->m_MappedMem); } uint32 OcclusionCuller::ReadFrustumCulledCount() const { - return m_Stats != nullptr ? static_cast(m_Stats->m_MappedMem)[1] : 0; + return static_cast(m_Readback[FrameSync::Slot()]->m_MappedMem)[1]; } void OcclusionCuller::SetWorlds(Buffer* t_Worlds) @@ -474,7 +508,7 @@ namespace Fling { Params.Planes[i] = t_View.Planes[i]; } - std::memcpy(m_Params->m_MappedMem, &Params, sizeof(Params)); + std::memcpy(m_Uploader->Stage(*m_Params, 0, sizeof(Params)), &Params, sizeof(Params)); } void OcclusionCuller::Dispatch(VkCommandBuffer t_Cmd, const uint32 t_Phase) const diff --git a/FlingEngine/Graphics/src/OcclusionCuller.h b/FlingEngine/Graphics/src/OcclusionCuller.h index 7781b3fc..95ba8f36 100644 --- a/FlingEngine/Graphics/src/OcclusionCuller.h +++ b/FlingEngine/Graphics/src/OcclusionCuller.h @@ -3,6 +3,7 @@ #include "FlingMath.h" #include "FlingTypes.h" #include "FlingVulkan.h" +#include "FrameSync.h" #include "Frustum.h" #include @@ -11,6 +12,7 @@ namespace Fling { class Buffer; + class FrameUploader; class LogicalDevice; class Shader; @@ -70,6 +72,7 @@ namespace Fling { public: OcclusionCuller(const LogicalDevice* t_Device, + FrameUploader* t_Uploader, std::shared_ptr t_Downsample, std::shared_ptr t_Cull); ~OcclusionCuller(); @@ -93,16 +96,25 @@ namespace Fling */ bool EnsureCapacity(size_t t_Slots, Buffer* t_Draw1); - /** Delete the buffers that EnsureCapacity replaced. The GPU is done with the frame that used them. */ + /** Delete the buffers that EnsureCapacity replaced, when the GPU is done with the frames that used them. */ void ReleaseRetired(); - /** The slot data, one per slot, for the CPU to fill. Valid after EnsureCapacity. */ - OcclusionSlot* MappedSlots() const; + /** + * Memory for the slot data of t_Count slots, for the CPU to fill (every field of every slot): the + * frame's upload copies it to the GPU. Valid after EnsureCapacity, until the frame's upload is recorded. + */ + OcclusionSlot* StageSlots(size_t t_Count); + + /** + * Queue the copy of the counters that the last frame made to this frame slot's readback buffer. Call it + * once a frame, before the frame's other work is recorded. + */ + void QueueStatsReadback(); /** The second draw commands, one per slot: the draws that the second render pass reads */ const Buffer* Draw2() const { return m_Draw2; } - /** The meshes the previous frame found hidden, read from the GPU's counter */ + /** The meshes found hidden by the frame that the readback buffer of this frame slot holds (a few frames old) */ uint32 ReadOccludedCount() const; /** The slots with TestFrustum that the previous frame found outside the view */ @@ -168,6 +180,10 @@ namespace Fling Buffer* m_Worlds = nullptr; size_t m_Capacity = 0; uint32 m_SlotCount = 0; - std::vector m_Retired; + RetireList m_Retired; + FrameUploader* m_Uploader; + /** The counters, copied to the host after each frame: one buffer for each frame slot */ + Buffer* m_Readback[FrameSync::FramesInFlight] = {}; + bool m_StatsReady = false; }; } // namespace Fling diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.cpp b/FlingEngine/Graphics/src/OffscreenSubpass.cpp index 4ebb223c..bedfc124 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.cpp +++ b/FlingEngine/Graphics/src/OffscreenSubpass.cpp @@ -61,20 +61,21 @@ namespace Fling } m_RecordedDrawListVersions.resize(m_OffscreenCmdBufs.size(), 0); - // One camera UBO is enough because each frame waits for the GPU to finish - // before the next frame writes it again + m_Uploader = std::make_unique(m_Device); + + // One camera UBO is enough: it is in GPU memory, and each frame's upload writes it after the + // frame before has finished on the GPU VkDeviceSize CameraBufferSize = sizeof(OffscreenCameraUBO); m_CameraUboBuffer = new Buffer(CameraBufferSize, - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - m_CameraUboBuffer->MapMemory(CameraBufferSize); + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); // Tell the Vulkan app that the draw command buffers need to WAIT on this offscreen semaphore PrepareAttachments(); if (t_HizDownsample && t_HizCull) { - m_Occlusion = std::make_unique(m_Device, t_HizDownsample, t_HizCull); + m_Occlusion = std::make_unique(m_Device, m_Uploader.get(), t_HizDownsample, t_HizCull); SetOcclusionDepth(); } } @@ -121,8 +122,9 @@ namespace Fling CommandBuffer* OffscreenCmdBuf = m_OffscreenCmdBufs[t_ActiveSwapImage]; assert(OffscreenCmdBuf); - // The previous frame is done on the GPU, so the resources of destroyed meshes can go FLING_PROFILE_SCOPE("Offscreen.Draw"); + m_Uploader->Begin(); + // The resources of destroyed meshes go when the frames that used them are done ReleaseRetiredMeshResources(); const bool bOcclusion = OcclusionActive(); @@ -130,9 +132,13 @@ namespace Fling { m_Occlusion->ReleaseRetired(); } - // The GPU counted the hidden meshes of the previous frame + // The GPU counted the hidden meshes of a frame that finished (a few frames ago) m_OccludedCount = bOcclusion ? m_Occlusion->ReadOccludedCount() : 0; m_GpuFrustumCulled = bOcclusion ? m_Occlusion->ReadFrustumCulledCount() : 0; + if (m_Occlusion) + { + m_Occlusion->QueueStatsReadback(); + } const bool bGpuBlend = GpuBlendActive(); // The culler leaves the meshes that the GPU blends to the GPU (it has no matrix for them) m_Culler.SetDeferBlended(bGpuBlend); @@ -155,7 +161,7 @@ namespace Fling CameraUBO.Projection = m_Camera->GetProjectionMatrix(); CameraUBO.Projection[1][1] *= -1.0f; CameraUBO.View = m_Camera->GetViewMatrix(); - memcpy(m_CameraUboBuffer->m_MappedMem, &CameraUBO, sizeof(CameraUBO)); + memcpy(m_Uploader->Stage(*m_CameraUboBuffer, 0, sizeof(CameraUBO)), &CameraUBO, sizeof(CameraUBO)); // The view volume of exactly the matrices the shader uses this frame m_CameraViewProjection = CameraUBO.Projection * CameraUBO.View; @@ -199,6 +205,8 @@ namespace Fling BuildOffscreenCommandBuffer(*OffscreenCmdBuf); m_RecordedDrawListVersions[t_ActiveSwapImage] = m_DrawListVersion; } + + m_UploadCmd = m_Uploader->Record(); } void OffscreenSubpass::SyncProxies(const RenderSnapshot& t_Snapshot) @@ -268,11 +276,11 @@ namespace Fling { if (t_Mesh.Set != VK_NULL_HANDLE) { - m_RetiredDescriptorSets.emplace_back(t_Mesh.Set); + m_RetiredDescriptorSets.Add(t_Mesh.Set); } if (t_Mesh.Ubo != nullptr) { - m_RetiredUniformBuffers.emplace_back(t_Mesh.Ubo); + m_RetiredUniformBuffers.Add(t_Mesh.Ubo); } t_Mesh = GpuMesh{}; } @@ -306,12 +314,15 @@ namespace Fling void OffscreenSubpass::WriteOcclusionSlots(const RenderSnapshot& t_Snapshot) { - OcclusionSlot* Slots = m_Occlusion->MappedSlots(); + OcclusionSlot* Slots = m_Occlusion->StageSlots(m_GpuMeshes.size()); const bool bGpuBlend = GpuBlendActive(); for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) { const GpuMesh& Mesh = m_GpuMeshes[Slot]; - Slots[Slot].Info = glm::uvec4(IsDrawable(Mesh) ? Mesh.MeshModel->GetIndexCount() : 0u, 0u, 0u, 0u); + // The staging memory holds an old frame's data: every field is written + OcclusionSlot Empty; + Empty.Info = glm::uvec4(IsDrawable(Mesh) ? Mesh.MeshModel->GetIndexCount() : 0u, 0u, 0u, 0u); + Slots[Slot] = Empty; } for (size_t i = 0; i < t_Snapshot.Meshes.size() && i < m_ItemSlots.size(); ++i) { @@ -376,22 +387,24 @@ namespace Fling } if (m_DrawCommands != nullptr) { - m_RetiredUniformBuffers.emplace_back(m_DrawCommands); + m_RetiredUniformBuffers.Add(m_DrawCommands); } const VkDeviceSize Size = sizeof(VkDrawIndexedIndirectCommand) * Capacity; m_DrawCommands = new Buffer(Size, - VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - m_DrawCommands->MapMemory(Size); + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + m_Uploader->Fill(*m_DrawCommands, 0, Size, 0); m_DrawCommandCapacity = Capacity; InvalidateCommandBuffers(); } void OffscreenSubpass::WriteDrawCommands() { - // One buffer is enough: each frame waits for the GPU to finish before the next frame - // writes it (as with the camera UBO) - auto* Commands = static_cast(m_DrawCommands->m_MappedMem); + // One buffer is enough: it is in GPU memory, and the frame's upload writes it after the frame + // before has finished on the GPU (as with the camera UBO) + auto* Commands = static_cast( + m_Uploader->Stage(*m_DrawCommands, 0, sizeof(VkDrawIndexedIndirectCommand) * m_GpuMeshes.size())); for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) { const GpuMesh& Mesh = m_GpuMeshes[Slot]; @@ -407,7 +420,6 @@ namespace Fling void OffscreenSubpass::UpdateMeshUniformBuffers(const RenderSnapshot& t_Snapshot) { - glm::mat4* Worlds = static_cast(m_WorldBuffer->m_MappedMem); const bool bGpuBlend = GpuBlendActive(); for (size_t i = 0; i < t_Snapshot.Meshes.size() && i < m_ItemSlots.size(); ++i) { @@ -431,7 +443,9 @@ namespace Fling continue; } - Worlds[Slot] = m_Worlds[i]; + std::memcpy(m_Uploader->Stage(*m_WorldBuffer, sizeof(glm::mat4) * Slot, sizeof(glm::mat4)), + &m_Worlds[i], + sizeof(glm::mat4)); Mesh.UploadedVersion = Item.WorldVersion; } } @@ -448,16 +462,21 @@ namespace Fling Capacity *= 2; } const VkDeviceSize Size = sizeof(glm::mat4) * Capacity; + // The descriptor sets of the meshes are written again below, and the frames in flight use them + if (m_WorldBuffer != nullptr) + { + m_Device->WaitForIdle(); + } Buffer* Bigger = new Buffer(Size, - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - Bigger->MapMemory(Size); - std::memset(Bigger->m_MappedMem, 0, Size); + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + m_Uploader->Fill(*Bigger, 0, Size, 0); if (m_WorldBuffer != nullptr) { - std::memcpy(Bigger->m_MappedMem, m_WorldBuffer->m_MappedMem, sizeof(glm::mat4) * m_WorldCapacity); - // The GPU is done with the last frame, but it is freed with the other retired buffers - m_RetiredUniformBuffers.emplace_back(m_WorldBuffer); + // The GPU copies the matrices over: it is freed with the other retired buffers + m_Uploader->Copy(*m_WorldBuffer, *Bigger, sizeof(glm::mat4) * m_WorldCapacity); + m_RetiredUniformBuffers.Add(m_WorldBuffer); } m_WorldBuffer = Bigger; m_WorldCapacity = Capacity; @@ -745,6 +764,8 @@ namespace Fling uint32 t_ActiveFrameIndex, uint32 t_CurrentFrameInFlight) { + // The upload goes first: it copies this frame's data, after the frame before has finished + t_CmdBuffs.emplace_back(m_UploadCmd); t_CmdBuffs.emplace_back(m_OffscreenCmdBufs[t_ActiveFrameIndex]); t_Deps.emplace_back(m_OffscreenSemaphores[t_CurrentFrameInFlight]); } @@ -763,7 +784,7 @@ namespace Fling m_Occlusion.reset(); m_Proxies.Clear(); m_ItemSlots.clear(); - ReleaseRetiredMeshResources(); + ReleaseRetiredMeshResources(true); if (m_DescriptorPool != VK_NULL_HANDLE) { @@ -791,21 +812,28 @@ namespace Fling InvalidateCommandBuffers(); } - void OffscreenSubpass::ReleaseRetiredMeshResources() + void OffscreenSubpass::ReleaseRetiredMeshResources(const bool t_All) { - if (!m_RetiredDescriptorSets.empty() && m_DescriptorPool != VK_NULL_HANDLE) + auto FreeSet = [this](const VkDescriptorSet t_Set) { - VK_CHECK_RESULT(vkFreeDescriptorSets(m_Device->GetVkDevice(), - m_DescriptorPool, - static_cast(m_RetiredDescriptorSets.size()), - m_RetiredDescriptorSets.data())); + if (m_DescriptorPool != VK_NULL_HANDLE) + { + VK_CHECK_RESULT(vkFreeDescriptorSets(m_Device->GetVkDevice(), m_DescriptorPool, 1, &t_Set)); + } + }; + auto FreeBuffer = [](Buffer* t_Buffer) + { + delete t_Buffer; + }; + if (t_All) + { + m_RetiredDescriptorSets.ReleaseAll(FreeSet); + m_RetiredUniformBuffers.ReleaseAll(FreeBuffer); } - m_RetiredDescriptorSets.clear(); - - for (Buffer* Ubo : m_RetiredUniformBuffers) + else { - delete Ubo; + m_RetiredDescriptorSets.Release(FreeSet); + m_RetiredUniformBuffers.Release(FreeBuffer); } - m_RetiredUniformBuffers.clear(); } -} // namespace Fling \ No newline at end of file +} // namespace Fling diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.h b/FlingEngine/Graphics/src/OffscreenSubpass.h index 5c6b2a86..739e1bbe 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.h +++ b/FlingEngine/Graphics/src/OffscreenSubpass.h @@ -1,6 +1,8 @@ #pragma once #include "FlingMath.h" +#include "FrameSync.h" +#include "FrameUploader.h" #include "Frustum.h" #include "GpuMesh.h" #include "MeshCuller.h" @@ -116,11 +118,15 @@ namespace Fling */ void SyncProxies(const RenderSnapshot& t_Snapshot); - /** Retire the resources of one proxy. ReleaseRetiredMeshResources frees them on the next Draw. */ + /** Retire the resources of one proxy. ReleaseRetiredMeshResources frees them when the frames that used them are + * done. */ void RetireGpuMesh(GpuMesh& t_Mesh); - /** Free the descriptor sets and UBOs of destroyed meshes */ - void ReleaseRetiredMeshResources(); + /** + * Free the descriptor sets and UBOs of destroyed meshes whose frames are finished on the GPU + * (t_All: free all of them, the device is idle) + */ + void ReleaseRetiredMeshResources(bool t_All = false); void CreateMeshDescriptorSet(GpuMesh& t_Mesh); @@ -176,6 +182,12 @@ namespace Fling /** Make each offscreen command buffer record again on its next use */ inline void InvalidateCommandBuffers() { ++m_DrawListVersion; } + /** Sends the data that the CPU makes each frame to the GPU buffers of this pass and of the occlusion passes */ + std::unique_ptr m_Uploader; + + /** The upload command buffer of the current frame, which goes first in the submission. Set by Draw. */ + CommandBuffer* m_UploadCmd = nullptr; + // We need an offscreen semaphore for each possible frame in flight because the swap chain // presentation will depend on this command buffer being complete std::vector m_OffscreenSemaphores; @@ -191,7 +203,7 @@ namespace Fling VkDescriptorPool m_DescriptorPool = VK_NULL_HANDLE; - /** Camera UBO that every mesh descriptor set points to */ + /** Camera UBO that every mesh descriptor set points to. In GPU memory: m_Uploader writes it each frame. */ Buffer* m_CameraUboBuffer = nullptr; /** Projection * view of this frame's camera UBO, for culling */ @@ -238,7 +250,10 @@ namespace Fling /** The view volume of the last CullMeshes */ Frustum m_View; - /** The world matrix of every slot (a mat4 each), read by the vertex shader and the cull shader */ + /** + * The world matrix of every slot (a mat4 each), read by the vertex shader and the cull shader. In GPU + * memory: the cull shader writes the matrices of the meshes that move, and m_Uploader the others. + */ Buffer* m_WorldBuffer = nullptr; size_t m_WorldCapacity = 0; @@ -258,16 +273,15 @@ namespace Fling uint32 m_GpuFrustumCulled = 0; /** - * Descriptor sets of meshes that are gone. They are freed at the start of the next - * Draw. The previous frame has finished on the GPU then, and every command buffer - * records again. + * Descriptor sets of meshes that are gone. A frame in flight can still use them, so they are + * freed when the frames up to the one that retired them are done. */ - std::vector m_RetiredDescriptorSets; + RetireList m_RetiredDescriptorSets; /** - * UBOs of destroyed meshes, and draw command buffers that were replaced by a larger one. - * Deleted at the same time as m_RetiredDescriptorSets. + * UBOs of destroyed meshes, and buffers that were replaced by a larger one. Freed at the + * same time as m_RetiredDescriptorSets. */ - std::vector m_RetiredUniformBuffers; + RetireList m_RetiredUniformBuffers; }; } // namespace Fling \ No newline at end of file diff --git a/FlingEngine/Graphics/src/PresentThread.cpp b/FlingEngine/Graphics/src/PresentThread.cpp new file mode 100644 index 00000000..af324314 --- /dev/null +++ b/FlingEngine/Graphics/src/PresentThread.cpp @@ -0,0 +1,139 @@ +#include "Logger.h" +#include "PresentThread.h" +#include "Profiler.h" +#include "Threading/CommandRunnable.h" +#include "Threading/Thread.h" + +#include +#include + +namespace Fling +{ + PresentThread::PresentThread(std::function t_Acquire, + const std::vector* t_Semaphores) + : m_Acquire(std::move(t_Acquire)), m_Semaphores(t_Semaphores) + { + m_Runnable = std::make_shared(); + m_Thread = Thread::Create(m_Runnable, {.Name = "Present", .Priority = ThreadPriority::Normal}); + if (m_Thread == nullptr) + { + F_LOG_WARN("Cannot start the present thread; the render thread presents"); + m_Runnable.reset(); + } + } + + PresentThread::~PresentThread() + { + if (m_Thread != nullptr) + { + Drain(); + m_Thread->Kill(); + m_Thread.reset(); + } + m_Runnable.reset(); + } + + void PresentThread::AcquireOne() + { + FLING_PROFILE_SCOPE("Present.Acquire"); + Acquired Image; + Image.Semaphore = (*m_Semaphores)[m_AcquireCount % m_Semaphores->size()]; + ++m_AcquireCount; + Image.Result = m_Acquire(Image.Semaphore, Image.Index); + // With every image busy the driver can say NOT_READY though the wait has no time limit: ask again + while (Image.Result == VK_NOT_READY || Image.Result == VK_TIMEOUT) + { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + Image.Result = m_Acquire(Image.Semaphore, Image.Index); + } + { + ScopedLock Lock(m_Mutex); + m_Acquired.push_back(Image); + } + m_Ready.NotifyAll(); + } + + void PresentThread::Prime(const uint32 t_Count) + { + for (uint32 i = 0; i < t_Count; ++i) + { + m_Pending.fetch_add(1, std::memory_order_acq_rel); + m_Runnable->Enqueue( + [this]() + { + AcquireOne(); + m_Pending.fetch_sub(1, std::memory_order_acq_rel); + }); + } + } + + void PresentThread::SubmitPresent(std::function t_Present) + { + m_Pending.fetch_add(1, std::memory_order_acq_rel); + m_Runnable->Enqueue( + [this, Present = std::move(t_Present)]() + { + VkResult Result = VK_SUCCESS; + { + FLING_PROFILE_SCOPE("Present.Thread"); + Result = Present(); + } + // An out of date swap chain matters more than a suboptimal one, and any error more than both + int32 Seen = m_Result.load(std::memory_order_acquire); + auto Rank = [](const int32 t_Value) + { + return t_Value == VK_SUCCESS ? 0 : (t_Value == VK_SUBOPTIMAL_KHR ? 1 : 2); + }; + while (Rank(static_cast(Result)) > Rank(Seen) && + !m_Result.compare_exchange_weak(Seen, static_cast(Result), std::memory_order_acq_rel)) + { + } + // The image of the frame that comes after the ones in flight + if (Result == VK_SUCCESS || Result == VK_SUBOPTIMAL_KHR) + { + AcquireOne(); + } + else + { + // The render thread waits for an image: tell it that the swap chain is no good + Acquired Failed; + Failed.Result = Result; + { + ScopedLock Lock(m_Mutex); + m_Acquired.push_back(Failed); + } + m_Ready.NotifyAll(); + } + m_Pending.fetch_sub(1, std::memory_order_acq_rel); + }); + } + + PresentThread::Acquired PresentThread::TakeAcquired() + { + ScopedLock Lock(m_Mutex); + m_Ready.Wait(Lock, [this]() { return !m_Acquired.empty(); }); + const Acquired Image = m_Acquired.front(); + m_Acquired.pop_front(); + return Image; + } + + void PresentThread::Drain() + { + while (m_Pending.load(std::memory_order_acquire) != 0) + { + std::this_thread::sleep_for(std::chrono::microseconds(50)); + } + } + + void PresentThread::Reset() + { + ScopedLock Lock(m_Mutex); + m_Acquired.clear(); + m_AcquireCount = 0; + } + + VkResult PresentThread::TakeResult() + { + return static_cast(m_Result.exchange(VK_SUCCESS, std::memory_order_acq_rel)); + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/PresentThread.h b/FlingEngine/Graphics/src/PresentThread.h new file mode 100644 index 00000000..d40a0b02 --- /dev/null +++ b/FlingEngine/Graphics/src/PresentThread.h @@ -0,0 +1,106 @@ +#pragma once + +#include "FlingTypes.h" +#include "FlingVulkan.h" +#include "Threading/ConditionVariable.h" +#include "Threading/Mutex.h" +#include "Threading/ThreadSafety.h" + +#include +#include +#include +#include +#include + +namespace Fling +{ + class CommandRunnable; + class Thread; + + /** + * A thread that owns the swap chain's two blocking calls: it presents the frames and it acquires the images. + * + * On some drivers (NVIDIA on Wayland) vkQueuePresentKHR blocks until the GPU has finished the frame. + * Called on the render thread, that makes the CPU wait for the GPU every frame, and the two never work at the + * same time. Here the render thread hands the present over and goes on with the next frame. + * + * A swap chain is externally synchronized: it must not be used by two threads at once. So this thread also + * makes the acquire calls, one after each present, and the render thread takes the images that it got + * (TakeAcquired). The render thread never calls the swap chain between Drain and the next Submit. + * + * Order of the work: the presents and the acquires run in the order they were given. + */ + class PresentThread + { + public: + /** An image that the thread acquired, and the semaphore that its acquire signals */ + struct Acquired + { + uint32 Index = 0; + VkSemaphore Semaphore = VK_NULL_HANDLE; + VkResult Result = VK_SUCCESS; + }; + + /** + * @param t_Acquire Acquires the next image of the swap chain: signals the semaphore, gives the image index. + * @param t_Semaphores The semaphores that the acquires signal, used in turn. At least FramesInFlight + 2: an + * acquire reuses the semaphore of the one that was this many acquires earlier, whose + * frame is finished by then. The vector must not change while the thread runs. + */ + PresentThread(std::function t_Acquire, + const std::vector* t_Semaphores); + ~PresentThread(); + + PresentThread(const PresentThread&) = delete; + PresentThread& operator=(const PresentThread&) = delete; + + /** False when the OS cannot start the thread. Present nothing then. */ + bool IsRunning() const { return m_Thread != nullptr; } + + /** Acquire t_Count images ahead of the frames: call it after the swap chain is made, and after a Reset */ + void Prime(uint32 t_Count); + + /** + * Run t_Present on the thread, then acquire the next image (for the frame that is FramesInFlight frames + * later). The present's result is kept for TakeResult. + */ + void SubmitPresent(std::function t_Present); + + /** The next acquired image. Waits for the thread when it is not there yet. */ + Acquired TakeAcquired(); + + /** Wait until every submitted present and acquire has returned. */ + void Drain(); + + /** + * Forget the images that were acquired and not taken, and start the semaphores again. Call it after Drain, + * when the swap chain and the semaphores are made again. + */ + void Reset(); + + /** + * The worst result of the presents since the last call (an out of date swap chain wins over a + * suboptimal one), or VK_SUCCESS. + */ + VkResult TakeResult(); + + private: + /** On the thread: acquire one image and queue it */ + void AcquireOne(); + + const std::function m_Acquire; + const std::vector* const m_Semaphores; + + std::shared_ptr m_Runnable; + std::shared_ptr m_Thread; + std::atomic m_Pending{0}; + std::atomic m_Result{VK_SUCCESS}; + + /** The number of acquires made. The thread only. */ + uint64 m_AcquireCount = 0; + + Mutex m_Mutex; + ConditionVariable m_Ready; + std::deque m_Acquired FLING_GUARDED_BY(m_Mutex); + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/src/Subpass.h b/FlingEngine/Graphics/src/Subpass.h index ae35896d..66d35f8f 100644 --- a/FlingEngine/Graphics/src/Subpass.h +++ b/FlingEngine/Graphics/src/Subpass.h @@ -46,6 +46,10 @@ namespace Fling /** * Record this pass for one frame. A pass reads only the snapshot, never the * world, so the world can change while the frame is drawn. + * + * The GPU may still draw the frame before this one (Docs/frame-pipelining.md): do not write memory that + * a recorded frame reads. Send per frame data through a FrameUploader, or keep a copy for each + * FrameSync::Slot(), and free what a frame used with a RetireList. */ virtual void Draw(CommandBuffer& t_CmdBuf, uint32 t_ActiveFrameInFlight, diff --git a/FlingEngine/Graphics/src/SwapChain.cpp b/FlingEngine/Graphics/src/SwapChain.cpp index 7d91264c..08134186 100644 --- a/FlingEngine/Graphics/src/SwapChain.cpp +++ b/FlingEngine/Graphics/src/SwapChain.cpp @@ -35,11 +35,7 @@ namespace Fling PhysicalDevice* t_PhysDev, VkSurfaceKHR t_Surface, const bool t_VSync) - : m_VSync(t_VSync), - m_Extents{t_Extent}, - m_Device(t_Dev), - m_PhysicalDevice(t_PhysDev), - m_Surface(t_Surface) + : m_VSync(t_VSync), m_Extents{t_Extent}, m_Device(t_Dev), m_PhysicalDevice(t_PhysDev), m_Surface(t_Surface) { assert(m_Device && m_PhysicalDevice && m_Surface); Recreate(m_Extents); @@ -313,6 +309,17 @@ namespace Fling return t_AvailableFormats[0]; } + VkResult Swapchain::AcquireImage(const VkSemaphore t_Semaphore, uint32& t_OutIndex) const + { + assert(m_Device && !m_Offscreen); + return vkAcquireNextImageKHR(m_Device->GetVkDevice(), + m_SwapChain, + std::numeric_limits::max(), + t_Semaphore, + VK_NULL_HANDLE, + &t_OutIndex); + } + VkResult Swapchain::AquireNextImage(const VkSemaphore& t_CompletedSemaphore) { assert(m_Device); @@ -335,6 +342,26 @@ namespace Fling return iRes; } + VkResult Swapchain::QueuePresent(const VkQueue& t_PresentQueue, + const VkSemaphore& t_WaitSemaphore, + const uint32 t_ImageIndex) const + { + if (m_Offscreen) + { + return VK_SUCCESS; + } + + VkPresentInfoKHR presentInfo = {}; + presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + presentInfo.waitSemaphoreCount = 1; + presentInfo.pWaitSemaphores = &t_WaitSemaphore; + VkSwapchainKHR swapChains[] = {m_SwapChain}; + presentInfo.swapchainCount = 1; + presentInfo.pSwapchains = swapChains; + presentInfo.pImageIndices = &t_ImageIndex; + return vkQueuePresentKHR(t_PresentQueue, &presentInfo); + } + VkResult Swapchain::QueuePresent(const VkQueue& t_PresentQueue, const VkSemaphore& t_WaitSemaphore) { if (m_Offscreen) diff --git a/FlingEngine/Graphics/src/SwapChain.h b/FlingEngine/Graphics/src/SwapChain.h index f5d759b8..4695e6ad 100644 --- a/FlingEngine/Graphics/src/SwapChain.h +++ b/FlingEngine/Graphics/src/SwapChain.h @@ -41,8 +41,20 @@ namespace Fling VkResult AquireNextImage(const VkSemaphore& t_CompletedSemaphore); + /** + * Acquire the next image of a window's swap chain: signals t_Semaphore and gives the image index. Does not + * change the active image, so the present thread can call it (the swap chain is used by one thread at a time). + */ + VkResult AcquireImage(VkSemaphore t_Semaphore, uint32& t_OutIndex) const; + VkResult QueuePresent(const VkQueue& t_PresentQueue, const VkSemaphore& t_WaitSemaphore); + /** + * Present image t_ImageIndex. Reads nothing that a later AquireNextImage changes, so another thread can call + * it while this one records the next frame (the swap chain must not be recreated meanwhile). + */ + VkResult QueuePresent(const VkQueue& t_PresentQueue, const VkSemaphore& t_WaitSemaphore, uint32 t_ImageIndex) const; + /** * Recreate this swap chain including image views, render passes, and command buffers. * DOES NOT Clean up any resources. diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 832b7e23..a6300308 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -9,6 +9,7 @@ #include "FlingIntegers.h" #include "FlingWindow.h" #include "FrameCapture.h" +#include "FrameSync.h" #include "GeometrySubpass.h" #include "GitVersion.h" #include "GraphicsHelpers.h" @@ -30,7 +31,9 @@ #include "VulkanAppState.h" #include "VulkanLoader.h" +#include #include +#include namespace { @@ -89,6 +92,9 @@ namespace namespace Fling { + static_assert(FrameSync::FramesInFlight == VkConfig::MAX_FRAMES_IN_FLIGHT, + "FrameSync and the swap chain resources must agree on the frames in flight"); + VulkanApp::VulkanApp() : m_State(std::make_unique()) { } @@ -216,6 +222,56 @@ namespace Fling m_Camera = new FirstPersonCamera(Aspect, CamMoveSpeed, CamRotSpeed); BuildSwapChainResources(); + + StartPresentThread(); + } + + void VulkanApp::StartPresentThread() + { + if (m_SwapChain->IsOffscreen() || !m_LogicalDevice->HasSeparatePresentQueue()) + { + return; + } + MakeAcquireSemaphores(); + auto Thread = std::make_unique([this](const VkSemaphore t_Semaphore, uint32& t_OutIndex) + { return m_SwapChain->AcquireImage(t_Semaphore, t_OutIndex); }, + &m_State->m_AcquireSemaphores); + if (!Thread->IsRunning()) + { + DestroyAcquireSemaphores(); + return; + } + m_State->m_PresentThread = std::move(Thread); + // WaitForIdle needs the present queue free: let the presents that wait on the GPU return first + m_LogicalDevice->SetBeforeIdle( + [this]() + { + if (m_State->m_PresentThread) + { + m_State->m_PresentThread->Drain(); + } + }); + // The images of the first frames + m_State->m_PresentThread->Prime(FrameSync::FramesInFlight); + } + + void VulkanApp::MakeAcquireSemaphores() + { + DestroyAcquireSemaphores(); + m_State->m_AcquireSemaphores.resize(FrameSync::FramesInFlight + 2); + for (VkSemaphore& Each : m_State->m_AcquireSemaphores) + { + Each = GraphicsHelpers::CreateSemaphore(m_LogicalDevice->GetVkDevice()); + } + } + + void VulkanApp::DestroyAcquireSemaphores() + { + for (const VkSemaphore Each : m_State->m_AcquireSemaphores) + { + vkDestroySemaphore(m_LogicalDevice->GetVkDevice(), Each, nullptr); + } + m_State->m_AcquireSemaphores.clear(); } void VulkanApp::BuildSwapChainResources() @@ -360,6 +416,8 @@ namespace Fling m_State->m_PresentCompleteSemaphores.resize(VkConfig::MAX_FRAMES_IN_FLIGHT); m_State->m_InFlightFences.resize(VkConfig::MAX_FRAMES_IN_FLIGHT); + m_State->m_FrameChain = GraphicsHelpers::CreateSemaphore(m_LogicalDevice->GetVkDevice()); + VkFenceCreateInfo fenceInfo = {}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; @@ -477,18 +535,25 @@ namespace Fling { if (m_Capturer) { + // The last copy may still be on the GPU: wait for it, then the writer takes it + if (m_State->m_CaptureFrame >= 0 && m_LogicalDevice != nullptr) + { + m_LogicalDevice->WaitForIdle(); + m_Capturer->OnFrameDone(); + m_State->m_CaptureFrame = -1; + } m_Capturer->Flush(); } } - void VulkanApp::RecreateSwapchain() + bool VulkanApp::RecreateSwapchain() { F_LOG_TRACE("Making the swap chain again"); // Offscreen images keep their size (there is no window) if (m_CurrentWindow != nullptr && !m_CurrentWindow->WaitForNewWindowSize()) { // The window was closed while minimized. ShouldTick sees the close next. - return; + return false; } m_LogicalDevice->WaitForIdle(); @@ -504,6 +569,15 @@ namespace Fling { Pipeline->OnSwapchainResized(); } + + if (m_State->m_PresentThread) + { + // The images that were acquired belong to the old swap chain, and their semaphores may be signaled + m_State->m_PresentThread->Reset(); + MakeAcquireSemaphores(); + m_State->m_PresentThread->Prime(FrameSync::FramesInFlight); + } + return true; } void VulkanApp::CleanupSwapChainResources() @@ -671,26 +745,85 @@ namespace Fling // Offscreen there is no present engine: no semaphores between the acquire, the frame and the present const bool bPresentSync = !m_SwapChain->IsOffscreen(); - // Aquire the active image index + // What the presents on the present thread found out about the swap chain (a resize, a new surface size) + if (m_State->m_PresentThread) + { + const VkResult Presented = m_State->m_PresentThread->TakeResult(); + if (Presented == VK_ERROR_OUT_OF_DATE_KHR || Presented == VK_SUBOPTIMAL_KHR) + { + bSwapchainOutOfDate = true; + } + else if (Presented != VK_SUCCESS) + { + F_LOG_FATAL("Failed to present swap chain image!"); + } + } + if (bSwapchainOutOfDate) + { + bSwapchainOutOfDate = false; + RecreateSwapchain(); + } + + // The frame slot: the frame that used it last (FramesInFlight frames ago) must be done before this one + // writes what that frame read. The frame before it may still be on the GPU: that is the overlap. + const uint64 Frame = m_State->m_FrameNumber; + CurrentFrameIndex = static_cast(Frame % FrameSync::FramesInFlight); + { + // The CPU waits here for the GPU: a long wait means the frame is GPU bound + FLING_PROFILE_SCOPE("Vk.WaitForGpu"); + vkWaitForFences(m_LogicalDevice->GetVkDevice(), + 1, + &m_State->m_InFlightFences[CurrentFrameIndex], + VK_TRUE, + std::numeric_limits::max()); + } + FrameSync::Begin(Frame); + + // A screenshot's copy was in the frame of this slot: it is done, so the writer thread takes it + if (m_State->m_CaptureFrame >= 0 && FrameSync::IsDone(static_cast(m_State->m_CaptureFrame))) + { + m_Capturer->OnFrameDone(); + m_State->m_CaptureFrame = -1; + } + + // Aquire the active image index. With the present thread the image was acquired ahead of the frame VkResult iResult = VK_SUCCESS; + uint32 ImageIndex = 0; + VkSemaphore AcquireSemaphore = m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]; { FLING_PROFILE_SCOPE("Vk.Acquire"); - iResult = m_SwapChain->AquireNextImage(m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]); + if (m_State->m_PresentThread) + { + const PresentThread::Acquired Image = m_State->m_PresentThread->TakeAcquired(); + iResult = Image.Result; + ImageIndex = Image.Index; + AcquireSemaphore = Image.Semaphore; + } + else + { + iResult = m_SwapChain->AquireNextImage(AcquireSemaphore); + ImageIndex = m_SwapChain->GetActiveImageIndex(); + } } - uint32 ImageIndex = m_SwapChain->GetActiveImageIndex(); if (iResult == VK_ERROR_OUT_OF_DATE_KHR) { F_LOG_WARN("Swap chain out of date! "); bSwapchainOutOfDate = false; - RecreateSwapchain(); + if (!RecreateSwapchain() && m_State->m_PresentThread) + { + // The swap chain stays (the window is closing): the next frame still needs an image + m_State->m_PresentThread->Prime(1); + } return; } vkResetFences(m_LogicalDevice->GetVkDevice(), 1, &m_State->m_InFlightFences[CurrentFrameIndex]); + ++m_State->m_FrameNumber; if (iResult != VK_SUCCESS && iResult != VK_SUBOPTIMAL_KHR) { + F_LOG_ERROR("Acquire result {}", static_cast(iResult)); F_LOG_FATAL("Failed to acquire swap chain image!"); } @@ -747,8 +880,16 @@ namespace Fling CmdBuf->EndRenderPass(); // A screenshot waits: the GPU copies this frame out in the same command buffer - // (nothing is recorded when none waits) - m_Capturer->RecordCopy(CmdBuf->GetHandle(), *m_SwapChain, ImageIndex); + // (nothing is recorded when none waits). One copy at a time: the capturer holds one until its frame is + // done. + if (m_State->m_CaptureFrame < 0) + { + m_Capturer->RecordCopy(CmdBuf->GetHandle(), *m_SwapChain, ImageIndex); + if (m_Capturer->HasRecorded()) + { + m_State->m_CaptureFrame = static_cast(Frame); + } + } // End command buffer recording CmdBuf->End(); @@ -765,6 +906,24 @@ namespace Fling // Wait for the color attachment to be done VkPipelineStageFlags waitStages[] = {m_State->m_WaitStages}; + // What the first submission of the frame waits for: the swap chain image, and the frame before this one + // (it shares the G-buffer images, the depth and the occlusion buffers with this one) + std::vector FirstWaits; + std::vector FirstWaitStages; + if (bPresentSync) + { + FirstWaits.push_back(AcquireSemaphore); + FirstWaitStages.push_back(m_State->m_WaitStages); + } + if (m_State->m_FrameChainSignaled) + { + FirstWaits.push_back(m_State->m_FrameChain); + FirstWaitStages.push_back(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + m_State->m_FrameChainSignaled = false; + } + + std::vector FinalWaitStages; + // Submit any PIPELINE command buffers for work VkSubmitInfo FinalScreenSubmitInfo = {}; FinalScreenSubmitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; @@ -777,10 +936,10 @@ namespace Fling // Submit sub pass command buffers with their waits VkSubmitInfo OffscreenSubmission = {}; OffscreenSubmission.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - OffscreenSubmission.pWaitDstStageMask = waitStages; - // Wait on Present complete - OffscreenSubmission.pWaitSemaphores = &m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]; - OffscreenSubmission.waitSemaphoreCount = bPresentSync ? 1 : 0; + // Wait on Present complete, and on the frame before + OffscreenSubmission.pWaitDstStageMask = FirstWaitStages.data(); + OffscreenSubmission.pWaitSemaphores = FirstWaits.data(); + OffscreenSubmission.waitSemaphoreCount = static_cast(FirstWaits.size()); // Signal that the dependent semaphores are done when this is complete OffscreenSubmission.pSignalSemaphores = SemaphoresToWaitOn.data(); @@ -800,15 +959,19 @@ namespace Fling VK_CHECK_RESULT( vkQueueSubmit(m_LogicalDevice->GetGraphicsQueue(), 1, &OffscreenSubmission, VK_NULL_HANDLE)); - // Wait for dependent semaphores + // Wait for dependent semaphores. The pass samples the G-buffer in its fragment shaders, and its depth + // tests start before the color output: the wait covers every stage + FinalWaitStages.assign(SemaphoresToWaitOn.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + FinalScreenSubmitInfo.pWaitDstStageMask = FinalWaitStages.data(); FinalScreenSubmitInfo.waitSemaphoreCount = (uint32)SemaphoresToWaitOn.size(); FinalScreenSubmitInfo.pWaitSemaphores = SemaphoresToWaitOn.data(); } else { // Track any semaphores that we may need to wait on for the render pipeline - FinalScreenSubmitInfo.waitSemaphoreCount = bPresentSync ? 1 : 0; - FinalScreenSubmitInfo.pWaitSemaphores = &m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]; + FinalScreenSubmitInfo.pWaitDstStageMask = FirstWaitStages.data(); + FinalScreenSubmitInfo.waitSemaphoreCount = static_cast(FirstWaits.size()); + FinalScreenSubmitInfo.pWaitSemaphores = FirstWaits.data(); } // Collect any addition command buffers that we want to submit, but are not dependent on offscreen @@ -821,9 +984,22 @@ namespace Fling FinalScreenSubmitInfo.pCommandBuffers = submitCommandBuffers.data(); FinalScreenSubmitInfo.commandBufferCount = (uint32)submitCommandBuffers.size(); - // Actually present the swap chain queue. This is always going to be the signal for the final semaphore - FinalScreenSubmitInfo.signalSemaphoreCount = bPresentSync ? 1 : 0; - FinalScreenSubmitInfo.pSignalSemaphores = &m_State->m_RenderFinishedSemaphores[ImageIndex]; + // Actually present the swap chain queue. This is always going to be the signal for the final semaphore. + // The next frame waits for the other one. + VkSemaphore FinalSignals[2] = {VK_NULL_HANDLE, m_State->m_FrameChain}; + uint32 FinalSignalCount = 1; + if (bPresentSync) + { + FinalSignals[0] = m_State->m_RenderFinishedSemaphores[ImageIndex]; + FinalSignalCount = 2; + } + else + { + FinalSignals[0] = m_State->m_FrameChain; + } + FinalScreenSubmitInfo.signalSemaphoreCount = FinalSignalCount; + FinalScreenSubmitInfo.pSignalSemaphores = FinalSignals; + m_State->m_FrameChainSignaled = true; { FLING_PROFILE_SCOPE("Vk.Submit"); @@ -833,45 +1009,60 @@ namespace Fling m_State->m_InFlightFences[CurrentFrameIndex])); } - // Finish up the frame by setting the in flight fences to wait ----- + // The frame is on its way. The next Update waits for its fence (the frame slot) before it reuses what it read. + // Present: on the present thread when there is one, so that a driver that blocks the call until the GPU has + // finished the frame does not make this thread wait + if (m_State->m_PresentThread && bPresentSync) { - // The CPU waits here for the GPU: a long wait means the frame is GPU bound - FLING_PROFILE_SCOPE("Vk.WaitForGpu"); - vkWaitForFences(m_LogicalDevice->GetVkDevice(), - 1, - &m_State->m_InFlightFences[CurrentFrameIndex], - VK_TRUE, - std::numeric_limits::max()); + const VkSemaphore Finished = m_State->m_RenderFinishedSemaphores[ImageIndex]; + FLING_PROFILE_SCOPE("Vk.QueuePresent"); + m_State->m_PresentThread->SubmitPresent( + [this, Finished, ImageIndex]() + { return m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), Finished, ImageIndex); }); } - - // The frame is drawn, and so is a screenshot's copy: the writer thread takes it from here - m_Capturer->OnFrameDone(); - - // Present the swap chain with the renderer finished semaphore + else { // On the NVIDIA Wayland driver this call blocks until the GPU has finished the frame FLING_PROFILE_SCOPE("Vk.QueuePresent"); iResult = m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), m_State->m_RenderFinishedSemaphores[ImageIndex]); - } - // Check if the swap chain is out of date and needs to be rebuilt - if (iResult == VK_ERROR_OUT_OF_DATE_KHR || iResult == VK_SUBOPTIMAL_KHR || bSwapchainOutOfDate) - { - bSwapchainOutOfDate = false; - RecreateSwapchain(); + // Check if the swap chain is out of date and needs to be rebuilt + if (iResult == VK_ERROR_OUT_OF_DATE_KHR || iResult == VK_SUBOPTIMAL_KHR) + { + bSwapchainOutOfDate = true; + } + else if (iResult != VK_SUCCESS) + { + F_LOG_FATAL("Failed to present swap chain image!"); + } } - else if (iResult != VK_SUCCESS) + } + + void VulkanApp::WaitForGpuIdle() + { + if (m_LogicalDevice != nullptr) { - F_LOG_FATAL("Failed to present swap chain image!"); + m_LogicalDevice->WaitForIdle(); } - - // Update the current in flight frame index! - CurrentFrameIndex = (CurrentFrameIndex + 1) % VkConfig::MAX_FRAMES_IN_FLIGHT; } void VulkanApp::ShutdownRenderer() { + // The last frames still run, and the present thread uses the swap chain + if (m_LogicalDevice != nullptr) + { + m_LogicalDevice->WaitForIdle(); + m_LogicalDevice->SetBeforeIdle(nullptr); + } + m_State->m_PresentThread.reset(); + DestroyAcquireSemaphores(); + if (m_State->m_CaptureFrame >= 0 && m_Capturer) + { + m_Capturer->OnFrameDone(); + m_State->m_CaptureFrame = -1; + } + Singleton::Shutdown(); // Wait for the device to be ready before shutting down @@ -925,6 +1116,8 @@ namespace Fling } m_State->m_RenderFinishedSemaphores.clear(); + vkDestroySemaphore(m_LogicalDevice->GetVkDevice(), m_State->m_FrameChain, nullptr); + m_State->m_FrameChain = VK_NULL_HANDLE; for (size_t i = 0; i < VkConfig::MAX_FRAMES_IN_FLIGHT; i++) { vkDestroySemaphore(m_LogicalDevice->GetVkDevice(), m_State->m_PresentCompleteSemaphores[i], nullptr); diff --git a/FlingEngine/Graphics/src/VulkanAppState.h b/FlingEngine/Graphics/src/VulkanAppState.h index 467b536e..a4f8fa8a 100644 --- a/FlingEngine/Graphics/src/VulkanAppState.h +++ b/FlingEngine/Graphics/src/VulkanAppState.h @@ -1,8 +1,10 @@ #pragma once #include "FlingVulkan.h" +#include "PresentThread.h" #include "VulkanApp.h" +#include #include namespace Fling @@ -16,7 +18,29 @@ namespace Fling std::vector m_PresentCompleteSemaphores; std::vector m_RenderFinishedSemaphores; std::vector m_InFlightFences; + + /** + * Signaled by the last submission of each frame, and waited on by the first submission of the next frame. + * The frames share the G-buffer images, the depth buffers and the occlusion buffers, so the GPU runs them one + * after the other: the CPU records ahead, the GPU does not overlap two frames. + */ + VkSemaphore m_FrameChain = VK_NULL_HANDLE; + bool m_FrameChainSignaled = false; VkSurfaceKHR m_Surface = VK_NULL_HANDLE; VkCommandPool m_CommandPool = VK_NULL_HANDLE; + + /** Presents the frames on a queue of its own. Null when the device has no second queue, offscreen, or when it + * does not start. */ + std::unique_ptr m_PresentThread; + + /** What the acquires of the present thread signal, used in turn (FramesInFlight + 2 of them) */ + std::vector m_AcquireSemaphores; + + /** The number of the next frame that Update records. Its frame slot is the number modulo the frames in flight. + */ + uint64 m_FrameNumber = 0; + + /** The frame that a screenshot copy was recorded in, whose fence has not been seen yet. -1: none. */ + int64 m_CaptureFrame = -1; }; } // namespace Fling diff --git a/FlingTests/Graphics/FrameSyncTests.cpp b/FlingTests/Graphics/FrameSyncTests.cpp new file mode 100644 index 00000000..a30ecced --- /dev/null +++ b/FlingTests/Graphics/FrameSyncTests.cpp @@ -0,0 +1,82 @@ +#include "FrameSync.h" + +#include +#include + +using namespace Fling; + +TEST_CASE("Frame sync: the slot goes round, and a frame is done FramesInFlight frames later", "[FrameSync]") +{ + FrameSync::Reset(); + for (uint64 Frame = 0; Frame < 8; ++Frame) + { + FrameSync::Begin(Frame); + REQUIRE(FrameSync::Frame() == Frame); + REQUIRE(FrameSync::Slot() == Frame % FrameSync::FramesInFlight); + } + + FrameSync::Begin(5); + // The frame before the slot's last frame is done, the one in flight is not + REQUIRE(FrameSync::IsDone(5 - FrameSync::FramesInFlight)); + REQUIRE_FALSE(FrameSync::IsDone(5 - FrameSync::FramesInFlight + 1)); + REQUIRE_FALSE(FrameSync::IsDone(5)); + FrameSync::Reset(); +} + +TEST_CASE("Frame sync: an idle device finishes every frame before the current one", "[FrameSync]") +{ + FrameSync::Reset(); + FrameSync::Begin(10); + REQUIRE_FALSE(FrameSync::IsDone(9)); + FrameSync::MarkIdle(); + REQUIRE(FrameSync::IsDone(9)); + // The frame that is recorded now is not submitted yet, so it is not done + REQUIRE_FALSE(FrameSync::IsDone(10)); + FrameSync::Reset(); +} + +TEST_CASE("Retire list: an item goes when the frames up to its own are done", "[FrameSync]") +{ + FrameSync::Reset(); + RetireList Retired; + std::vector Freed; + auto Free = [&Freed](const int t_Item) + { + Freed.push_back(t_Item); + }; + + FrameSync::Begin(3); + Retired.Add(30); + FrameSync::Begin(4); + Retired.Add(40); + Retired.Add(41); + + // Frame 3 may still be on the GPU while frame 4 is recorded + Retired.Release(Free); + REQUIRE(Freed.empty()); + + FrameSync::Begin(3 + FrameSync::FramesInFlight); + Retired.Release(Free); + REQUIRE(Freed == std::vector{30}); + + FrameSync::Begin(4 + FrameSync::FramesInFlight); + Retired.Release(Free); + REQUIRE(Freed == std::vector{30, 40, 41}); + REQUIRE(Retired.Empty()); + FrameSync::Reset(); +} + +TEST_CASE("Retire list: ReleaseAll frees what is left, done or not", "[FrameSync]") +{ + FrameSync::Reset(); + RetireList Retired; + FrameSync::Begin(7); + Retired.Add(1); + Retired.Add(2); + + std::vector Freed; + Retired.ReleaseAll([&Freed](const int t_Item) { Freed.push_back(t_Item); }); + REQUIRE(Freed == std::vector{1, 2}); + REQUIRE(Retired.Empty()); + FrameSync::Reset(); +} diff --git a/Plans/gpu-blend.md b/Plans/gpu-blend.md index a5b4b32b..4289b84b 100644 --- a/Plans/gpu-blend.md +++ b/Plans/gpu-blend.md @@ -82,3 +82,7 @@ test the blend. No validation layer messages, with and without occlusion culling 0..1. A screenshot with `--gpu-blend on` and `off` at the same tick must match (within float rounding). - `--profile`: `Graphics.PublishSnapshot` and `Offscreen.*` before and after. + +Real window, 1080p, RTX 3090, VSync off, no frame cap, 30 Hz sim (RelWithDebInfo, `Docs/frame-pipelining.md`): +the frame was 2.7 ms with the CPU and the GPU taking turns. With the frames pipelined it is 1.85 ms (536 to 541 fps +with the spheres turning, 533 to 549 still), GPU bound. The world matrix buffer is now in GPU memory. From fa1a1d6fa2e0755096d980e2a4649bd8ec2ed942 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Tue, 17 Nov 2026 16:23:33 -0500 Subject: [PATCH 4/5] Make the present thread optional: [Graphics] PresentThread, on by default Off, the main thread presents a frame after it has submitted the next one, so the CPU and the GPU still overlap (460 fps against 560 with the thread and 368 before the pipelining on the lighting level). The held frame is shown at once when the frame limiter will sleep anyway (FrameLimiter::WillWait), so a capped run pays no extra frame of delay. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017NN37Q2jpV81xZaX3ocojK --- Config/EngineConf.ini | 7 +++ Docs/frame-pipelining.md | 16 ++++- FlingEngine/Application/src/Engine.cpp | 7 +++ FlingEngine/Core/inc/Threading/FrameLimiter.h | 6 ++ .../Core/src/Threading/FrameLimiter.cpp | 5 ++ FlingEngine/Graphics/inc/VulkanApp.h | 9 +++ FlingEngine/Graphics/src/VulkanApp.cpp | 59 ++++++++++++++----- FlingEngine/Graphics/src/VulkanAppState.h | 10 ++++ FlingTests/Core/FrameLimiterTests.cpp | 21 +++++++ 9 files changed, 125 insertions(+), 15 deletions(-) diff --git a/Config/EngineConf.ini b/Config/EngineConf.ini index 84a16741..78a31823 100644 --- a/Config/EngineConf.ini +++ b/Config/EngineConf.ini @@ -52,6 +52,13 @@ EnableValidationLayers=false #EnableValidationLayers=true [Graphics] +; PresentThread: true (default) presents and acquires the swap chain images on a thread of its own, so +; the render thread records the next frame while a driver that blocks vkQueuePresentKHR until the GPU is +; done (NVIDIA on Wayland) waits. false: the render thread does both, and presents a frame after it has +; submitted the next one, so the CPU and the GPU still overlap. false is the setting for a driver that +; does not block; it adds one frame of delay before a frame is shown when the frame limiter does not sleep. +; Needs a second queue in the graphics family, else the render thread presents. Docs/frame-pipelining.md +PresentThread=true ; Cube map folder for the skybox, relative to the Assets directory. Leave empty for no skybox. ; @see Cubemap.h for the face file names Skybox=Textures/Skybox/Garden diff --git a/Docs/frame-pipelining.md b/Docs/frame-pipelining.md index f98ef9af..c8a591d7 100644 --- a/Docs/frame-pipelining.md +++ b/Docs/frame-pipelining.md @@ -22,7 +22,7 @@ The frame is now GPU bound. `Vk.Acquire` (the render thread waits for an image) is done. The frame before it may still run on the GPU. `FrameSync::Begin` then tells the passes which frames are finished. -2. **The present thread** (`PresentThread`). On some drivers (NVIDIA on Wayland) `vkQueuePresentKHR` +2. **The present thread** (`PresentThread`, optional, see below). On some drivers (NVIDIA on Wayland) `vkQueuePresentKHR` does not return until the GPU has finished the frame. Called on the render thread, that brings the wait back. So a thread of its own makes the present call, on a second queue of the graphics family (`LogicalDevice::HasSeparatePresentQueue`). A swap chain must not be used by two threads at once, so the @@ -42,6 +42,20 @@ The frame is now GPU bound. `Vk.Acquire` (the render thread waits for an image) before (`VulkanApp::State::m_FrameChain`), and the upload command buffer starts with a full memory barrier. The CPU records ahead; the GPU frames do not overlap each other. +## The present thread is optional + +`[Graphics] PresentThread` in `Config/EngineConf.ini` (default `true`) turns the present thread on or off. The +engine itself has two threads, the game thread and the main thread, and the present thread is an extra one for a +driver that blocks. Off (or when the device has no second queue), the main thread does the swap chain calls +itself and gets the same overlap another way: it presents a frame after it has submitted the next one, so the GPU +has that frame queued while the present call waits. The cost is that a frame is shown one frame later than it could +be. When the frame limiter is going to sleep anyway (`FrameLimiter::WillWait`), the engine presents the held frame +first (`VulkanApp::PresentPendingFrame`), so a capped run does not pay it. A driver whose present call does not +block gains nothing from the thread, and can switch it off. + +Same scene (uncapped, VSync off): about 560 fps with the thread, about 460 fps without it, 368 fps before the +pipelining. + ## Rules for a pass - A buffer that the CPU writes while recording and that a command buffer reads: put the data through diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index 70a6fd7a..f063d10f 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -740,6 +740,13 @@ namespace Fling UpdateFrameLimiter(); } + // Without a present thread the renderer holds the last frame back, to record the next one while the GPU + // draws it. When the limiter sleeps anyway, nothing is gained by holding it: show it now + if (!m_Options.NullRender && m_FrameLimiter.WillWait()) + { + VulkanApp::Get().PresentPendingFrame(); + } + // The game ticks on its own clock, so it runs at the same speed, only shown less often m_FrameLimiter.WaitForNextFrame(); } diff --git a/FlingEngine/Core/inc/Threading/FrameLimiter.h b/FlingEngine/Core/inc/Threading/FrameLimiter.h index f9e0ba0d..e7a37813 100644 --- a/FlingEngine/Core/inc/Threading/FrameLimiter.h +++ b/FlingEngine/Core/inc/Threading/FrameLimiter.h @@ -74,6 +74,12 @@ namespace Fling */ CORE_API void WaitForNextFrame(); + /** + * True if WaitForNextFrame would wait now: the frame is faster than the cap. The render thread uses it to + * present a frame before it sleeps, instead of after the next frame. + */ + CORE_API bool WillWait() const; + /** The number of times the schedule started again because a frame was too late. */ uint64 GetRestarts() const { return m_Restarts; } diff --git a/FlingEngine/Core/src/Threading/FrameLimiter.cpp b/FlingEngine/Core/src/Threading/FrameLimiter.cpp index 1551a88d..f8eb594d 100644 --- a/FlingEngine/Core/src/Threading/FrameLimiter.cpp +++ b/FlingEngine/Core/src/Threading/FrameLimiter.cpp @@ -51,6 +51,11 @@ namespace Fling return Math::Min(m_SpinNs, m_PeriodNs / 2); } + bool FrameLimiter::WillWait() const + { + return m_PeriodNs > 0 && m_Started && m_Now() < m_NextNs; + } + void FrameLimiter::WaitForNextFrame() { if (m_PeriodNs <= 0) diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index cde9c218..5c12b93f 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -84,6 +84,15 @@ namespace Fling */ void WaitForGpuIdle(); + /** + * Show the frame that is held back. Without a present thread ([Graphics] PresentThread=false) Update + * presents the frame before the one it just submitted, because the present call can wait for the GPU and + * the GPU should have the next frame queued by then. Call this when the thread would wait anyway (the frame + * limiter sleeps), so the frame is not shown later than it needs to be. Does nothing when no frame is held + * back. Main thread. + */ + void PresentPendingFrame(); + /** * Wait for the screenshots that are being written (Screenshot::Request) and call their * callbacks. A frame copies a screenshot; a writer thread saves it later, so a run that diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index a6300308..9fc9e999 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -228,10 +228,18 @@ namespace Fling void VulkanApp::StartPresentThread() { - if (m_SwapChain->IsOffscreen() || !m_LogicalDevice->HasSeparatePresentQueue()) + if (m_SwapChain->IsOffscreen()) { return; } + // [Graphics] PresentThread: on by default. Off, or without a second queue, the render thread presents + const bool bWanted = FlingConfig::GetBool("Graphics", "PresentThread", true); + if (!bWanted || !m_LogicalDevice->HasSeparatePresentQueue()) + { + F_LOG_TRACE("Present thread: off ({}); the render thread presents the frame before the one it submits", + bWanted ? "the device has no second queue" : "[Graphics] PresentThread is false"); + return; + } MakeAcquireSemaphores(); auto Thread = std::make_unique([this](const VkSemaphore t_Semaphore, uint32& t_OutIndex) { return m_SwapChain->AcquireImage(t_Semaphore, t_OutIndex); }, @@ -242,6 +250,7 @@ namespace Fling return; } m_State->m_PresentThread = std::move(Thread); + F_LOG_TRACE("Present thread: on"); // WaitForIdle needs the present queue free: let the presents that wait on the GPU return first m_LogicalDevice->SetBeforeIdle( [this]() @@ -555,6 +564,8 @@ namespace Fling // The window was closed while minimized. ShouldTick sees the close next. return false; } + // The frame that is held back belongs to the old swap chain: show it first + PresentPendingFrame(); m_LogicalDevice->WaitForIdle(); CleanupSwapChainResources(); @@ -1022,25 +1033,44 @@ namespace Fling } else { - // On the NVIDIA Wayland driver this call blocks until the GPU has finished the frame - FLING_PROFILE_SCOPE("Vk.QueuePresent"); - iResult = m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), - m_State->m_RenderFinishedSemaphores[ImageIndex]); + // No present thread. The present call can wait for the GPU (on the NVIDIA Wayland driver it does until the + // frame is done), so it is made after the next frame is submitted, not right after this one: the GPU then + // has that frame queued while the call waits. This frame is held until then + // (PresentPendingFrame also runs when the frame limiter sleeps, so a capped run shows it at once). + PresentPendingFrame(); + m_State->m_HeldFrame.Valid = true; + m_State->m_HeldFrame.Finished = + bPresentSync ? m_State->m_RenderFinishedSemaphores[ImageIndex] : VK_NULL_HANDLE; + m_State->m_HeldFrame.ImageIndex = ImageIndex; + } + } - // Check if the swap chain is out of date and needs to be rebuilt - if (iResult == VK_ERROR_OUT_OF_DATE_KHR || iResult == VK_SUBOPTIMAL_KHR) - { - bSwapchainOutOfDate = true; - } - else if (iResult != VK_SUCCESS) - { - F_LOG_FATAL("Failed to present swap chain image!"); - } + void VulkanApp::PresentPendingFrame() + { + VulkanApp::State::HeldFrame Held = m_State->m_HeldFrame; + if (!Held.Valid) + { + return; + } + m_State->m_HeldFrame.Valid = false; + + FLING_PROFILE_SCOPE("Vk.QueuePresent"); + const VkResult Result = + m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), Held.Finished, Held.ImageIndex); + // Check if the swap chain is out of date and needs to be rebuilt + if (Result == VK_ERROR_OUT_OF_DATE_KHR || Result == VK_SUBOPTIMAL_KHR) + { + bSwapchainOutOfDate = true; + } + else if (Result != VK_SUCCESS) + { + F_LOG_FATAL("Failed to present swap chain image!"); } } void VulkanApp::WaitForGpuIdle() { + PresentPendingFrame(); if (m_LogicalDevice != nullptr) { m_LogicalDevice->WaitForIdle(); @@ -1050,6 +1080,7 @@ namespace Fling void VulkanApp::ShutdownRenderer() { // The last frames still run, and the present thread uses the swap chain + PresentPendingFrame(); if (m_LogicalDevice != nullptr) { m_LogicalDevice->WaitForIdle(); diff --git a/FlingEngine/Graphics/src/VulkanAppState.h b/FlingEngine/Graphics/src/VulkanAppState.h index a4f8fa8a..854a4026 100644 --- a/FlingEngine/Graphics/src/VulkanAppState.h +++ b/FlingEngine/Graphics/src/VulkanAppState.h @@ -33,6 +33,16 @@ namespace Fling * does not start. */ std::unique_ptr m_PresentThread; + /** A frame that was submitted and is not presented yet (no present thread). Update presents it after the next + * submit. */ + struct HeldFrame + { + bool Valid = false; + VkSemaphore Finished = VK_NULL_HANDLE; + uint32 ImageIndex = 0; + }; + HeldFrame m_HeldFrame; + /** What the acquires of the present thread signal, used in turn (FramesInFlight + 2 of them) */ std::vector m_AcquireSemaphores; diff --git a/FlingTests/Core/FrameLimiterTests.cpp b/FlingTests/Core/FrameLimiterTests.cpp index 777ec58d..baa0a09c 100644 --- a/FlingTests/Core/FrameLimiterTests.cpp +++ b/FlingTests/Core/FrameLimiterTests.cpp @@ -210,3 +210,24 @@ TEST_CASE("Sleep timer: it never wakes before the deadline", "[FrameLimiter]") // A deadline in the past returns at once Timer.SleepUntil(Clock::now() - std::chrono::seconds(1)); } + +TEST_CASE("Frame limiter: WillWait says if the next wait would sleep", "[FrameLimiter]") +{ + VirtualFrames Clock; + FrameLimiter Limiter = Clock.Make(1 * Ms); + + // No cap: never + REQUIRE_FALSE(Limiter.WillWait()); + + Limiter.SetMaxFps(100); + const int64 Period = Limiter.GetPeriodNs(); + // The schedule has not started: the first wait does not sleep + REQUIRE_FALSE(Limiter.WillWait()); + Clock.Frame(Limiter, 0); + + // A frame that is faster than the period will wait, a slower one will not + Clock.Now += Period / 2; + REQUIRE(Limiter.WillWait()); + Clock.Now += Period; + REQUIRE_FALSE(Limiter.WillWait()); +} From a9cd52f7124719f9bda0ad6b284efc65074906e4 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Tue, 17 Nov 2026 21:37:42 +0000 Subject: [PATCH 5/5] Annotate PresentThread wait predicate for clang thread-safety analysis Co-Authored-By: Claude Sonnet 5.5 --- FlingEngine/Graphics/src/PresentThread.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FlingEngine/Graphics/src/PresentThread.cpp b/FlingEngine/Graphics/src/PresentThread.cpp index af324314..5e036f5a 100644 --- a/FlingEngine/Graphics/src/PresentThread.cpp +++ b/FlingEngine/Graphics/src/PresentThread.cpp @@ -111,7 +111,7 @@ namespace Fling PresentThread::Acquired PresentThread::TakeAcquired() { ScopedLock Lock(m_Mutex); - m_Ready.Wait(Lock, [this]() { return !m_Acquired.empty(); }); + m_Ready.Wait(Lock, [this]() FLING_REQUIRES(m_Mutex) { return !m_Acquired.empty(); }); const Acquired Image = m_Acquired.front(); m_Acquired.pop_front(); return Image;