Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 7 additions & 0 deletions Config/EngineConf.ini
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Docs/agent-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
97 changes: 97 additions & 0 deletions Docs/frame-pipelining.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# 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`, 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
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.

## 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
`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.
3 changes: 2 additions & 1 deletion Docs/time-and-ticks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
14 changes: 14 additions & 0 deletions FlingEngine/Application/src/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down Expand Up @@ -950,6 +957,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)
{
Expand Down
3 changes: 2 additions & 1 deletion FlingEngine/Core/inc/RunSettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
6 changes: 6 additions & 0 deletions FlingEngine/Core/inc/Threading/FrameLimiter.h
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down
11 changes: 10 additions & 1 deletion FlingEngine/Core/src/RunSettings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
{
Expand Down
5 changes: 5 additions & 0 deletions FlingEngine/Core/src/Threading/FrameLimiter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
106 changes: 106 additions & 0 deletions FlingEngine/Graphics/inc/FrameSync.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#pragma once

#include "FlingTypes.h"

#include <utility>
#include <vector>

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<uint32>(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 <typename T>
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 <typename Fn>
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 <typename Fn>
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<std::pair<uint64, T>> m_Items;
};
} // namespace Fling
26 changes: 25 additions & 1 deletion FlingEngine/Graphics/inc/VulkanApp.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,22 @@ 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();

/**
* 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
Expand Down Expand Up @@ -186,7 +202,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,
Expand Down
Loading