Foundations

Frames in flight

The CPU and the GPU are two processors. If each waits for the other, each sits idle half the time. With frames in flight, the CPU prepares the next frame while the GPU still draws the last one. That needs a few copies of the data that changes every frame, and a fence that says when a copy is free again. The last part shows how RASM does it.

In short

  • The CPU records a frame, the GPU runs it later. They can work on different frames at the same time.
  • Data the CPU writes every frame gets one copy per frame slot. Frame n uses slot n mod N.
  • Before the CPU reuses a slot, it waits on a fence until the GPU has finished the last frame that used it.
  • A timeline fence is one growing counter. Each submit signals the next value; each slot remembers its value.
  • More slots hide more spikes, but add latency. When the GPU is the slow side, a third slot adds latency and no speed.
  • Data that never changes, or that only the GPU writes and reads within a frame, needs no copies.

1Two workers, one frame at a time

The CPU builds a frame: it reads input, moves objects, and records commands. Then it submits them, and the GPU runs them. If the CPU then waits for the GPU before it starts the next frame, the two never work at the same time:

One slot: take turns CPU GPU F0 waits F1 waits F2 waits F3 idle F0 idle F1 idle F2 idle F3 a frame every 16 ms Two slots: overlap CPU GPU F0 F1 F2 F3 F4 F5 idle F0 F1 F2 F3 F4 F5 F2 waits for F0 a frame every 10 ms 0 10 20 30 40 50 60 ms
The CPU needs 6 ms per frame and the GPU 10 ms. With two slots, the CPU may run one frame ahead. Frame 2 must wait until the GPU finishes frame 0, because they share slot 0 (dashed boxes: the CPU waits).

With overlap, the slower side alone sets the frame time: max(CPU, GPU) instead of CPU + GPU. The work itself does not change.

16 msper frame with one slot: 62.5 frames per secondCPU + GPU = 6 + 10
10 msper frame with two slots: 100 frames per secondmax(CPU, GPU) = max(6, 10)

2The problem: shared data

Overlap has a price. A frame's commands do not run when they are recorded; they read their data later, while the GPU runs them. Take the camera matrix. The CPU writes it into a buffer, and the GPU reads it during the frame.

CPU writes camera of F1 GPU reads camera of F0 the camera buffer F1 F1 F0 F0 at the same time: F0 may see half of F1's camera

One buffer: a race

The CPU writes frame 1's camera while the GPU still draws frame 0 with it.

CPU writes camera of F1 GPU reads camera of F0 camera, slot 1 F1 F1 camera, slot 0 F0 F0 no shared bytes, no race

One buffer per slot

The CPU writes slot 1 while the GPU reads slot 0. F2 writes slot 0 again, after the GPU is done with F0.

Nothing stops the race

The GPU does not notice a CPU write to mapped memory. Nothing in the API stops the race; the program has to avoid it.

There are only two ways out: wait until the GPU is done before writing (the "one slot" picture, slow), or write somewhere else. Frames in flight do the second, and wait only when the other place is still in use.

3Frame slots

Pick a number N, usually 2 or 3. Give every per-frame resource N copies, and call copy i slot i. Frame n uses slot n mod N. So with N = 2, frames 0, 2, 4 use slot 0 and frames 1, 3, 5 use slot 1.

frame 0 frame 1 frame 2 frame 3 frame 4 frame 5 slot 0 slot 1 slot 0 slot 1 slot 0 slot 1 slot 0 command buffer frame buffers fence value of its last submit slot 1 command buffer frame buffers fence value of its last submit
A slot is a set of resources, not a frame. The frame number keeps growing; the slot number goes round.

With N slots, the CPU can be at most N − 1 frames ahead of the GPU: frame n must wait for frame n − N, which used the same slot. That wait is the only one the CPU needs.

4Fences: how the CPU knows

A fence is a sync object the GPU signals and the CPU can wait on. The submit names it; when the GPU has finished everything in that submit, it signals the fence. There are two kinds.

fence 0signaled fence 1not signaled submit signaled CPU waits reset

Binary: one per slot

Submit with the slot's fence. The GPU finishes and signals it. The CPU waits for it, then resets it before the next submit. Each fence answers one question: "is that one submit done?"

wait(6) blocks until here the GPU has reached 5 3 4 5 6 7 8 slot 0: last signal 6 slot 1: last signal 7

Timeline: one counter

Every submit signals the next value. Values only grow, and nothing is reset. One object answers "how far has the GPU come?" for every submit. Reading the counter never blocks.

A timeline needs one object for all slots. It also serves uploads, readbacks and deferred deletes: each just stores the value it waits for.

APIBinary fenceTimeline (counter)
VulkanVkFence: wait, then resettimeline semaphore (core since 1.2): signal a value, wait for a value
Direct3D 12—ID3D12Fence is always a counter
Metala completion handler per command bufferMTLSharedEvent, a 64-bit value
WebGPUonSubmittedWorkDone, a promise—

Do not confuse a fence with a semaphore in the binary sense. A binary semaphore orders work between GPU submissions (for example, "draw only after the swapchain image is free"); the CPU cannot wait on it. See the swapchain and GPU synchronization.

5Worked example: the fence, frame by frame

Two slots and one timeline fence that starts at 0. Each slot starts with the value 0, so the first wait on each slot returns at once. Click through the steps (or use the arrow keys).

1. Frame 0, slot 0

Counter: GPU has reached 0 0 1 2 3 4 slot 0 0 → 1 slot 1 0 wait(0): returns at once write slot 0's buffers, record submit, signal 1 slot 0 remembers 1 GPU: starts frame 0

The submit names the value it will signal. The slot stores it, so the next frame that uses slot 0 knows what to wait for.

2. Frame 1, slot 1

Counter: GPU has reached 0 0 1 2 3 4 slot 0 1 slot 1 0 → 2 wait(0): returns at once write slot 1's buffers, record submit, signal 2 slot 1 remembers 2 GPU: still on frame 0 frame 1 is queued behind it

The CPU is now one frame ahead. Slot 0 is still in use by the GPU, but the CPU did not touch it.

3. Frame 2, slot 0: the CPU waits

Counter: GPU reaches 1 0 1 2 3 4 slot 0 1 → 3 slot 1 2 wait(1): blocks until frame 0 is done now slot 0 is free: rewrite it, record submit, signal 3 slot 0 remembers 3 GPU: finished frame 0, runs frame 1

This is the wait that keeps the race away. It sits at the start of the frame, right before the slot is touched, so the CPU did as much work as possible before it.

4. Frame 3, slot 1

Counter: GPU reaches 2 0 1 2 3 4 slot 0 3 slot 1 2 → 4 wait(2): blocks until frame 1 is done rewrite slot 1, record submit, signal 4 The rule: frame n signals n + 1, and waits for n + 1 − N, the value of frame n − N.

With a timeline, the bookkeeping is one number per slot and one counter. Nothing is ever reset.

6What gets a copy per slot, and what does not

The rule is simple: a resource needs one copy per slot when the CPU changes it every frame (or the CPU reads it back), and the GPU may still be using the old contents.

One copy per slot

slot 0 slot 1

Command buffers and their memory (pools, allocators)

Re-recording resets their memory, which the GPU reads while it runs them.

camera, time, lights slot 0 camera, time, lights slot 1

Per-frame constants: camera, time, lights

The CPU rewrites them every frame.

slot 0 slot 1

Per-object data the CPU updates (transforms)

The same reason. A change must reach every copy, each in its own frame.

CPU reads, after its fence slot 0 GPU writes now slot 1

Readback buffers, timer queries

The GPU writes them, the CPU reads them after the fence. A second frame must not overwrite them first.

One copy is enough

frame 0 frame 1

Meshes, textures, pipelines, samplers

Written once, then only read. If they change, write new data elsewhere, or wait.

frame 0 frame 1 depth, culling list in order

GPU-only scratch: a depth buffer, a culling list made and used in one frame

Usually one copy. The queue runs frames in order, and a barrier covers earlier submissions.

Unless frames may overlap on the GPU, or the data must survive to the next frame.

the swapchain owns them 0 1 2

Swapchain images

The swapchain owns them. Their count is not N. See the swapchain.

Changing a resource that has one copy

It is still possible. Either write only to parts no running frame reads (a new row, a new descriptor slot), or defer the change: remember the fence value of the current frame, and apply the change once the counter has passed it. Deleting works the same way: a destroyed object is put in a queue with the current value, and really freed later.

the GPU has reached 5 destroy is called: remember value 6 4 5 6 7 8 delete queue: the object, value 6 counter reaches 6: really freed
A deferred delete is a wait that nobody blocks on: the object stays alive until the counter has passed its value.

7How many slots: throughput against latency

Latency here means the time from the start of a frame on the CPU (when input is read) to the end of its GPU work. A simple model, with fixed costs per frame, shows the trade-off. The numbers come from stepping the rule "frame n may start when the CPU is free and frame n − N is done on the GPU":

Two slots CPU GPU F0 F1 F2 F3 F4 F5 F0 F1 F2 F3 F4 F5 latency of F4: 20 ms Three slots CPU GPU F0 F1 F2 F3 F4 F5 F6 F0 F1 F2 F3 F4 F5 latency of F4: 30 ms 0 10 20 30 40 50 60 ms
The CPU needs 6 ms per frame and the GPU 10 ms. With three slots the CPU starts frame 4 earlier, but the GPU finishes it at the same moment. The frame only waits longer in the queue.
CPU, GPU per frameSlots NTime per frameFrames per secondLatency
6 ms, 10 ms (GPU-bound)116 ms62.516 ms
210 ms10020 ms
310 ms10030 ms
10 ms, 6 ms (CPU-bound)116 ms62.516 ms
210 ms10016 ms
310 ms10016 ms

The same rule, stepped live for any costs. The middle row shows the frames that are recorded but not yet on the GPU.

the CPU records a frame a recorded frame waits for the GPU; the latency of one frame the GPU runs a frame dashed: the CPU waits for its slot, or the GPU is idle
Go from 2 slots to 3 and 4: the time per frame stays, the latency grows. Then make the CPU slower than the GPU, and change the slots again.
CPU queue GPU waits at the fence F5 waits runs F4 each extra slot: one more frame waits here

GPU-bound

The CPU runs ahead until it hits the fence. Each extra slot is one more finished frame waiting in the queue, so latency grows by one GPU frame, and speed does not change.

CPU queue GPU records F5 empty idle, waits more slots change nothing

CPU-bound

The GPU waits for the CPU, never the other way. The queue stays empty, so more slots change nothing. They do help when costs vary: a slow CPU frame can then hide behind a fast one.

That is why 2 is the common default, and 3 is used when frame costs jump around. Games that care about input lag go further: they limit how far the CPU may run ahead, or delay the start of the CPU frame so it finishes just in time.

8Where to wait, and other pitfalls

Waiting right after submit
Back to "one slot": no overlap. Instead: wait at the start of the frame that reuses the slot.
Writing the slot before the wait
The race from section 2 comes back, but only sometimes. Instead: everything that writes a slot's resources runs after its wait.
Remembering a value nothing signals
A submit failed, but the slot stored its value anyway. The next wait on that slot never returns. Instead: store the value only after the submit succeeded.
Mixing up frame number and slot
Two frames in flight share one slot. Instead: keep both, and index per-frame resources by the slot.
Readback "now"
The CPU reads a result the GPU has not written yet. Instead: read a slot's results after its wait: they are N frames old, and that is fine for statistics.
Waiting forever
A GPU hang (device lost) freezes the program. Instead: a timeout, or at least an error on a failed wait.
Resize or shutdown with frames in flight
Resources are freed while the GPU still uses them. Instead: wait for the device to go idle first; it is rare, so the cost does not matter.

9In RASM

RASM uses two slots (MAX_FRAMES_IN_FLIGHT = 2) and one timeline fence per queue: Renderer::frameFence for the graphics queue, and Renderer::computeFence for the compute queue when async compute is on. A slot remembers the last value of each (FrameResources::fenceValue, FrameResources::computeFenceValue), and beginFrame waits for both. frameCount is the slot, 0 or 1, not a frame counter. Everything that writes a slot's resources runs right after the wait in beginFrame.

beginFrame waitForFence the slot's fenceValue, and computeFenceValue updateFrameStats, updateStatsOverlay or buildUi, syncGpuScene write only this slot's buffers acquireNextImage open the graphics batch passes record into their queue's batch (one batch without async compute) endFrame submitBatches() each signals v = last value + 1 ok frameFenceValue = v frameResources[frameCount] .fenceValue = v compute: computeFenceValue, the same way failed discardRecording its values stay as they were frameCount = (frameCount + 1) % 2 The slot flips after every frame that reached endFrame, submitted or not. A frame that beginFrame skipped (minimized window, failed acquire) does not flip it.
The present after a successful submit is left out here; see the swapchain. For the whole frame and its batches, see one frame, step by step. The frame's last graphics submit waits for all of its compute work, so the graphics value alone already covers the whole frame; beginFrame still waits for both.

What has one copy per slot

Per slotWhereWritten by
Fence valuesFrameResources in Renderer::frameResourcessubmitBatches; beginFrame waits for them
Command buffers, one per batch and queueRenderer::batchCommandBuffersthe passes; FrameResources::commandBuffer names the one being recorded
GPU tables: instances, materials, lights, animated entities, morph weight overridesGpuTable::bufferssyncGpuScene, through GpuTable::upload
Draw lists, one per sceneSceneDrawList::bufferssyncGpuScene, through uploadDrawList
Scene data, one per scene viewGpuScene::sceneData (host-visible)prepareSceneView, at the start of the view's Cull pass
Culling: visible lists with their counts, Hi-Z, cull statscullStats in GpuScene; visibleDraws, hiz in each SceneViewthe culling and Hi-Z passes; the CPU reads cullStats back
Light clusters of a shaded viewViewClusters::buffersthe Light Clusters pass (clustered lighting)
Posed transforms, joint matrices, morph weights, skinned verticestransforms, joints, weights, skinnedVertices in GpuAnimationthe Animate and Skin passes; motion vectors read the other slot's skinned vertices, the frame before's (skinning)
Attachments of a render target with historyRenderTarget::attachmentspasses that draw into the target; the next frame reads the copy
Timestamp queriesFrameStatsSlot::timestampsthe GPU timers; read in updateFrameStats
Stats overlay textStatsOverlaySlot::textupdateStatsOverlay, with the UI off
Dear ImGui's vertices and indicesUiSlot in Ui::slotsbuildUi, with EngineConfig::ui (immediate-mode UI)
The Inspect pass's parametersInspector::paramsrecordInspect (inspecting GPU resources)
A change reaches both slots

A changed table row is marked dirty in every slot (GpuTable::setRow). Each slot then uploads it once, in its own frame, after its own wait. That is why EngineConfig::maxInstances costs its memory twice.

What has one copy

last frame:culling writes this frame:Cull 1 reads visibility

The visibility buffer

One GPU-only buffer per scene view is shared on purpose: SceneView::visibility, what the last frame's occlusion culling saw. The next frame reads it, so it must survive the frame.

Only compute passes use it, and they run on one queue in frame order, and the Cull 1 pass declares it with readPrevious, so the graph puts a compute-to-compute barrier before it: one copy is safe (see occlusion culling).

this frame:draw, then read next frame:draw, then read render target

A render target without history

It has one copy that both slots share. Each frame draws it before it reads it, and the queue runs the frames in order, so the next frame's draw waits behind the barriers of this one (see temporal history).

A use on the other queue waits for it instead (render graphs).

in use: never changed + + new: only added

Geometry, textures, pipelines, the bindless set

The geometry pool, textures, pipelines and the one bindless descriptor set have a single copy. They are only added to: new ranges, new textures, new bindless slots, never a change to something a running frame reads.

The bindless set's layout uses update-after-bind, which allows writing new slots while earlier frames still run.

The visible-draw lists and the Hi-Z have one copy per slot for a second reason: with async compute, Cull 1 of the next frame then does not wait for this frame's draws, and can run next to them.

A destroyed object is freed once the frames in flight that may use it are done, through a release queue tied to these fences (deferred destruction). Resize waits for the device to go idle instead, then rebuilds the render targets sized from the window (RenderContext::resizeRenderTargets).

Where RASM follows the textbook, and where it differs

PartThis pageRASM
SlotsN = 2 or 32, fixed at compile time (MAX_FRAMES_IN_FLIGHT in include/rasm/types.h).
Slot indexframe number mod NframeCount holds only the slot; there is no frame number. It flips in endFrame.
Fencebinary per slot, or one timelineOne timeline per queue: frameFence, a Vulkan timeline semaphore. frameFenceValue is the last value signaled; FrameResources::fenceValue is the slot's. With async compute, computeFence, computeFenceValue and FrameResources::computeFenceValue do the same for the compute queue. A frame may signal several values of each, one per batch.
Where to waitstart of the frameIn beginFrame, after input, finished loads and swapchain recreation, before anything writes the slot.
Value only on successstore it after the submitThe same: a failed submit leaves both values, and calls discardRecording.
Wait timeouta timeoutNone: waitForFence waits with UINT64_MAX. A failed wait skips the frame.
ReadbackN frames lateThe cull stats and GPU timers of a slot are read after its wait, so the overlay and the RASM window show the frame from two frames ago. FrameStatsSlot::readFenceValue skips a slot whose frame was never submitted. An image copy (Renderer::readFrame, Renderer::readTexture) rides in a frame's last graphics batch and keeps that frame's fence value, so isReadbackReady turns true about two frames later, and nothing waits (readback).
Other users of the timeline ideauploads, deletesUploadManager has its own timeline, "Upload Fence" (and the loads' "Load Upload Fence" on the transfer queue), to free staging space. The release queue waits for the frame, compute and both upload fences before it frees a destroyed object (deferred destruction).
Swapchain imagesseparate from slotsSeparate. The swapchain also keeps its own acquire semaphores and its own release timeline, so it does not depend on the frame fence. See the swapchain.

Where it lives in code

WhatWhere
The slot countMAX_FRAMES_IN_FLIGHT in include/rasm/types.h
Slot stateFrameResources in include/rasm/types.h; frameResources, frameFence, frameFenceValue, computeFence, computeFenceValue, batchCommandBuffers in include/rasm/renderer.h
The wait, the submits, the flipRenderer::beginFrame, Renderer::endFrame and Renderer::submitBatches in src/renderer/renderer.cpp
Per-slot tablesGpuTable in src/renderer/gpuTable.cpp
Timeline fenceVulkanDevice::createFence, waitForFence, getFenceValue in src/rhi/vulkan/vulkanDevice.cpp; signaled in VulkanQueue::submit
Keep these true
  • Per-frame mutable buffers are indexed by frameCount, and written only after beginFrame's wait for that slot.
  • GPU scene tables are written only in syncGpuScene. Change rows through GpuTable::setRow, never by writing a slot's buffer.
  • A slot takes a fence value only after a submit that signals it succeeded.
  • beginFrame waits for both of the slot's fences before anything reuses its command buffers or writes its buffers.
  • A resource with one copy is freed or reused only through the release queue, after the frames that may use it (deferred destruction).

Further reading