Engine tour
One frame, step by step
A frame is beginFrame, some passes, and endFrame. By default all passes go into one command buffer, and the frame has one submit. With async compute on, the frame is a few batches on two queues, each with its own command buffer and submit. The CPU records the next frame while the GPU still runs the last one, so there are two frame slots. A timeline fence per queue tells the CPU when a slot is free again.
This is stop 2 of the engine tour, after the big picture. It walks one frame of RASM and shows where each job runs. The ideas under it have their own guides: frames in flight, the swapchain, barriers and layouts, and indirect draws.
In short
Renderer::renderruns a render graph (ViewGraph::render):beginFrame, the scene passes fromaddScenePassesinto a 16-bit float target, theTone Mappass fromaddToneMapPassinto the swapchain, withEngineConfig::uitheUIpass fromaddUiPassover it,endFrame. With a list of views, each view has its own target and tone map (Many views of one scene).- The scene passes are
Cull 1,Scene 1,Hi-Z,Cull 2,Scene 2(onlyCullandScenewithout occlusion culling), thenTransparent, which draws the see-through materials back to front. The graph puts the barriers between them. frameCountis the slot (0 or 1), not a frame counter.MAX_FRAMES_IN_FLIGHT= 2.- Each graphics submit signals the next value of
frameFence, and each compute submit the next value ofcomputeFence. Before a slot is reused,beginFramewaits for the values its last submits signaled. - With
EngineConfig::asyncCompute,Cull 1,Hi-ZandCull 2run on the compute queue, and the frame is four batches, submitted together at the end (below). It is off by default. - Everything that rewrites a slot's buffers runs right after that wait: frame stats, the overlay text or the UI (
buildUi, which also runs the application's UI callback),syncGpuScene. beginFramereturns false to skip a frame (minimized, swapchain out of date). Then record nothing and do not callendFrame.
1Three ways to run a frame
render keeps one graph and builds it again only when a view (scene, camera, output, settings) or a view's size in pixels changes; before that it polls the events and recreates a resized swapchain, so the views take the new size in the same frame. The stepper below walks that frame. Only graph passes draw the scene: an app with its own graph calls addScenePasses and addToneMapPass itself (render graphs).2One frame, step by step
This is frame 7 of an app that calls render(scene, camera) with occlusion culling on and async compute off (the defaults). Frame 7 uses slot 0. Click through the steps (or use the arrow keys). The strip at the top of each picture shows where we are.
1. Input and finished loads
F1 shows the stats (showStats: the RASM window with the UI, else the overlay), and F2 steps forcedLod through the LODs and back to the automatic choice (-1). Loads that end together spread over several frames. finishLoads runs before anything binds the bindless set or the geometry pool. A load is drawn once its copies are done, a frame or two after its fill, so no frame waits for copies in flight. See Streaming assets in the background and transfer queues.
2. Skip checks and resize
The events come from the SDL platform and from the application's Renderer::addInputEvent, all through one path (The platform layer): quit, Esc (SDL only), F1–F3, resize, minimize, and the camera's input. While every SDL window is minimized, pollEvents waits up to 100 ms for an event (SDL_WaitEventTimeout), so skipped frames do not spin the CPU; a NATIVE application skips frames with a size of 0 (setWindowSize) and waits in its own loop. Each window is checked on its own (Renderer::updateSwapchain): a minimized one sits the frame out, and the frame is skipped only when no window can show. A failed recreation keeps the window's WindowFrame::outOfDate set, so the next frame tries again.
3. Wait until the slot is free
beginFrame waits for frameResources[frameCount].fenceValue, and with async compute also for computeFenceValue on computeFence. Then the GPU is done with everything slot 0 used: its command buffers, its per-slot buffers, its timestamp queries. At start both slots hold 0 and the fence starts at 0, so the first waits return at once. How a timeline fence works is in Frames in flight.
4. Rewrite the slot: stats, overlay, scene
A change made after beginFrame (for example updateTransform during the passes) reaches the GPU in the next frame. See the GPU scene tables (stop 3), GPU timing for the stats and bitmap text for the overlay, immediate-mode UI for the UI. The UI is built before syncGpuScene, so what its callback changes reaches the GPU in this frame.
5. Acquire a swapchain image
Acquire comes after the scene sync, so a skip here wastes nothing: the uploads it queued go out with the next submit. The swapchain picks its own acquire semaphore; see The swapchain and presenting.
6. Start recording, then Cull 1
history · bake: clearNewHistory clears new copies of history render targets (none in this app). Then recordEnvironmentBakes records the compute work that prepares image-based lighting, before any pass: the BRDF LUT in the engine's first frame, and an environment whose image has just loaded (Image-based lighting). Most frames have none.
barrier G|C→C: from the graph (G = graphics, C = compute). Last frame's Scene 2 read what Cull 1 writes.
ts: a GPU timestamp, only while frame stats are measured. Every pass gets a pair, named after the pass.
beginFrame acquires an image from every window that can show (WindowFrame::acquired, rendered false) and opens the graphics batch (Renderer::useQueue), which begins the slot's command buffer. Each command buffer has its own pool, and begin resets it. That is safe because of the wait in step 3. Then RenderGraph::execute runs the passes in its order. Before each pass it records the barriers that the pass's declared reads and writes need, outside any render pass. With async compute, Cull 1 records into a compute batch instead, and the graph adds waits between the queues (below).
Cull 1 is a compute pass, so its dispatches sit between render passes, in the same command buffer. countMain tests each draw against the frustum and last frame's visibility flags, and writeMain packs the visible ones into the view's visible-draw list. The COMPUTE → COMPUTE barrier between them is inside the pass. What they do is in Frustum culling, LOD selection and Stream compaction. Then, since this scene has a point light with a range, recordLightClusters sorts it into the view's clusters: three dispatches under a GPU timer of their own, Light Clusters (Clustered lighting).
7. Scene 1: the early draws
barrier C→G: from the graph. Cull 1 wrote the visible draws and counts these draws read.
image and depth of scene_hdr, the 16-bit float target ViewGraph makes, start from UNKNOWN (discard): Scene 1 is the target's first pass, so it clears both.
A barrier call names only the new usage: RenderContext remembers the layout each texture is in (TextureStates). With discard set, as here, the old contents are dropped and the barrier starts from UNKNOWN. acquireNextImage marks the acquired swapchain image UNKNOWN too, and its barrier, in the Tone Map pass, waits at color output, after the acquire. Barriers must be recorded outside a render pass. See GPU synchronization.
The draw lists and runs drawSceneView uses are in stop 3. The ideas: indirect draws, device addresses for the push constant, vertex pulling and the uber shader for what each draw runs.
8. Hi-Z, Cull 2, Scene 2: occlusion culling
depth → SAMPLED: Hi-Z declares readDepth of the target, so the graph makes Scene 1 store its depth.
hizMain builds one level per dispatch: level 0 from the depth of the early draws, each next one from the one before.
late countMain: seen = in the frustum and not occluded. It writes the visibility flags and keeps what Scene 1 missed.
Scene 2 loads color and depth (no discard), and draws the sky last. Hi-Z, Cull 2 and Scene 2 dispatch and draw nothing when the view has no Hi-Z.
When the scene has see-through (BLEND) materials, Cull 2 also sorts them back to front after writeMain (sorting on the GPU), and a Transparent pass after Scene 2 draws them with blending on and depth writes off (transparency). This app has none, so Transparent only begins and ends its rendering.
Each step is a pass of its own, so no dispatch ever sits inside a render pass. The late culling rewrites the same visible-draw list and counts that Scene 1 read, so the graph's barrier before Cull 2 waits for the early draws. Cull 1 reads the visibility flags that this pass wrote last frame (readPrevious). Without occlusionCulling, addScenePasses adds only Cull and Scene, and this step is not there. Why two passes, and how a Hi-Z works, is in Occlusion culling with Hi-Z.
9. Tone Map, then endFrame closes the command buffer
Tone Map: the graph's last pass. The graph moves scene_hdr's color to SAMPLED; the pass draws one triangle over the swapchain image (UNKNOWN → COLOR_ATTACHMENT) that multiplies by the camera's exposure and applies AgX. See Tone mapping.
UI / overlay: with EngineConfig::ui, the graph's UI pass draws ImGui's windows over the image, through the swapchain's UNORM view where the device has one (Immediate-mode UI); a graph without it gets the pass from endFrame. Without the UI, the stats overlay, only when it is shown (F1). Both draw after the tone map, so their colors are not mapped, and both load the image's color.
readbacks: the copies asked for with readFrame or readTexture since the last frame (recordReadbacks), after everything that draws, into host-readable buffers (Headless rendering and readback).
barrier → PRESENT_SRC: once per frame, the swapchain image goes COLOR_ATTACHMENT → PRESENT_SRC. A headless engine's offscreen image skips it: nothing presents it.
barrier C→H: COMPUTE → HOST. The CPU reads the cull stats after this slot's next fence wait. With a compute queue the culling runs there, and the barrier goes in its last batch instead.
No pass drew to the swapchain? endFrame first records an empty pass named "Clear", so present still works.
Present needs the image in PRESENT_SRC. A frame that only draws into render targets gets the empty "Clear" pass, so it presents the clear color. A headless engine (PlatformType::HEADLESS) does the same into its offscreen image, whose "present" does nothing. A render target pass instead leaves its color textures SAMPLED in endPass, for later passes.
10. Submit and present
submitBatches ends the command buffer, then submits it. The upload copies go out first on the same queue, so the frame sees their data (GPU memory and uploads). A slot takes the new fence value only after a successful submit: waiting for a value that nothing signals would block forever.
11. Move to the other slot
Frame 8 can start at once if the GPU already reached 6. Otherwise the CPU waits in step 3 of frame 8.
With async compute: a frame of batches
With EngineConfig::asyncCompute, on a GPU with a compute queue, the steps are the same, but recording moves between two queues. A batch is one command buffer and one submit on one queue.
Async compute off (the default)
One batch. Every pass is recorded into it.
Async compute on
Recording moves between the queues. Each move closes a batch.
- Each queue has one open batch (
Renderer::useQueue), andFrameResources::commandBuffernames the one being recorded. - A batch is closed when the other queue needs what it did (
Renderer::waitForQueue, called by the graph) or at the end of the frame. endFramesubmits all batches together, in the order they were closed (Renderer::submitBatches), so every wait is on a submit that already went out.- Their command buffers end only there, so the frame's last compute batch, closed long before the end, still takes the cull stats barrier.
If a batch's command buffer can't be made or begun, useQueue returns false and the frame is dropped: the graph stops, and submitBatches ends every batch and submits none.
Cull 1 uses this slot's visible draws, which frame N-2 used last, so it waits only for that frame, which the fence wait in step 3 already covers. It can run next to the previous frame's Scene 2. The last graphics submit waits for all of the frame's compute work, so fenceValue covers the whole frame. Only the first graphics submit waits for the image (the swapchain). The idea: Async compute and multiple queues; how the graph picks the waits: render graphs.Pending uploads still go out first, on the graphics queue. Their copies wait for the last compute submit, the copies flushed while recording too, and a compute submit waits for them, so a frame with uploads loses the overlap. With async compute off, or on a GPU without a compute family that has no graphics, there is one batch, as in the steps above. Async compute costs a little more than it saves on the scene passes today, so it is off by default (P11).
3Two slots over time
With two slots, the CPU can record frame N+1 while the GPU runs frame N. It cannot get further ahead: frame N+2 uses the same slot as frame N, so step 3 waits for frame N's fence value. Frames in flight draws this on a timeline and explains why one timeline fence per queue is enough. The picture is for one graphics submit per frame; with async compute, a frame signals two graphics values and two compute values.
Nothing is reset: the fence values only grow. A skipped frame needs no cleanup, because it signaled nothing and changed no slot value.
Play both sides to see the rule work. You are the CPU and the GPU. It starts where step 3 above did: frame 7 wants slot 0, which last signaled 5, and the GPU has reached 4.
beginFrame blocks. Then let the GPU finish a frame. Try to make the CPU write a slot that the GPU still uses: the fence wait never lets it.What has one copy per slot
| Per slot | Where |
|---|---|
| depth texture, fence values, the command buffer being recorded | FrameResources in Renderer::frameResources |
| command buffers per queue, one per batch | Renderer::batchCommandBuffers |
SceneData (a slot per scene view), cull stats | GpuScene |
| visible draws with their draw counts, Hi-Z buffer | SceneView, one per scene view in GpuScene::views |
| instance and material table buffers, draw list buffers | GpuTable, SceneDrawList::buffers |
| GPU timestamp query pool | FrameStatsSlot |
| stats overlay text buffer | StatsOverlaySlot |
color and depth textures of a render target with history | RenderTarget::attachments |
All of them are indexed by frameCount. A history render target's texture changes every frame, so fetch it with getRenderTargetTexture each frame. A render target without history has one pair of textures that both slots share: the GPU runs the frames in order, and each frame's first use waits for the frame before. The visibility flags of occlusion culling (SceneView::visibility) have one buffer per scene view, shared by both slots: only the compute passes use them, those run on one queue in frame order, and each frame reads what the one before wrote.
4Swapchain results and skipped frames
| Call | OK | SUBOPTIMAL | OUT_OF_DATE | FAILURE |
|---|---|---|---|---|
acquireNextImage | go on | go on, recreate next frame | skip, recreate next frame | skip |
present | — | recreate next frame | recreate next frame | logged |
recreateSwapchain | go on | — | 0 × 0 surface: keep the old swapchain, skip | skip, try again next frame |
"Recreate next frame" means the window's WindowFrame::outOfDate is set, and step 2 of the next frame recreates that window's swapchain. What these results mean in Vulkan is in The swapchain and presenting.
A skipped frame (beginFrame returns false)
Nothing is recorded or submitted. frameCount does not move, and there is no Tracy frame mark. What ran before the skip still counts: input, finished loads, and (when acquire skips) the scene sync, whose uploads go out with the next submit.
A frame that fails to submit
It was recorded, but the slot keeps its old fence value, so the next wait on it passes at once. frameCount still moves. The image stays acquired, and the next acquire returns it again. Its timestamps are not read, because the slot's value did not change.
submitBatches calls discardRecording, so the textures it moved go back to the layouts they still have on the GPU. With several batches, a failed submit ends the frame there, since later ones may wait for it; the textures go back only to the layouts the batches that went out left them in. An environment bake in a dropped frame is recorded again in the next one: finishEnvironmentBakes sees that its textures went back.
5Resize
- The window reports a new pixel size. With SDL,
SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGEDsetsresizedand the newpixelWidthandpixelHeightinpollEvents; aNATIVEor headless application callsRenderer::setWindowSize, which does the same. - The next
beginFramerecreates. It callsRenderer::recreateSwapchain, which callsRenderContext::recreateSwapchain. - The swapchain is rebuilt. A 0 × 0 surface returns
OUT_OF_DATEand keeps the old swapchain. Otherwise it releases pending semaphores, waits until the device is idle, and builds the new swapchain. - Image handles change. The old swapchain image handles are dropped and new ones are registered. Handles from an earlier
getSwapchainImagesare no longer valid. - Sizes follow.
createSwapchainResourcescallsRenderContext::resizeRenderTargets, which rebuilds every target with aswapchainScaleat the new size, andupdateCameraAspectRatio. The device is idle, so the old textures can be destroyed at once. A rebuilt target keeps its bindless slots, so theHi-Zpass still finds its depth. The swapchain itself has no depth.
Everything swapchain-sized uses the swapchain extent in pixels. Window::width and height are the logical size, used only for the mouse. They differ on HiDPI screens.
6Where each job runs in the frame
| Job | When | Why there |
|---|---|---|
finishLoads | start of beginFrame | before anything binds the bindless set or the geometry pool |
updateFrameStats | after the fence wait | reads what the slot's last frame measured, then resets the slot |
updateStatsOverlay | after updateFrameStats, without the UI | writes the slot's text buffer, which the GPU no longer reads |
buildUi | after updateFrameStats, with EngineConfig::ui | builds the RASM window and runs the UI callback before syncGpuScene, so what the UI changes reaches this frame; the UI pass draws it |
syncGpuScene | after the fence wait, before acquire | writes the slot's tables and draw lists |
| graph barriers and queue waits | RenderGraph::execute, before each pass begins | barriers are not allowed inside a render pass, and a wait closes the other queue's batch |
prepareSceneView | start of the Cull pass, on the CPU | writes the view's SceneData slot, which the GPU reads after the whole frame is recorded |
recordSceneCulling, recordHiz | the Cull and Hi-Z compute passes | dispatches are not allowed inside a render pass |
drawSceneView | the Scene graphics passes | records draws; needs a rendering scope |
| tone map | the Tone Map pass, the graph's last | reads the finished HDR image; the overlay draws after it, in endFrame, so the overlay is not tone mapped |
| cull stats barrier | endFrame, after the last pass; with a compute queue, submitBatches, at the end of the last compute batch | COMPUTE → HOST, so the CPU can read the counters after the fences |
| submits | submitBatches, at the end of endFrame | the GPU starts the frame once it is recorded, and every wait is on a submit already made |
| upload flush | inside RenderContext::submit | the copies must run before the frame that reads them |
tagReleases | endFrame, after submitBatches, also for a dropped frame | what was destroyed since the last frame waits for the values the queues and the uploads signaled last (deferred destruction) |
collectReleases | beginFrame: at its start (after a tagReleases, so skipped frames still free), and after the fence wait | frees the destroyed objects and bindless slots whose values the fences reached, by reading the fences, never waiting; nothing to do when nothing was destroyed |
D7: one window: the engine draws one main window, and its own camera input covers all of it.
B21: the swapchain always uses VK_PRESENT_MODE_FIFO_KHR, so the frame rate is capped at the display refresh rate.
P11: async compute does not pay off for the scene passes yet, so it is off by default.
7Where it lives in code
| What | Where |
|---|---|
| Frame functions | Renderer::render, Renderer::beginFrame, Renderer::endFrame, Renderer::beginPass, Renderer::endPass in src/renderer/renderer.cpp |
The graph behind render | ViewGraph::render in src/renderer/viewGraph.cpp |
| Tone map | Renderer::addToneMapPass in src/renderer/toneMap.cpp; the shader in shaders/passes/toneMap.slang |
| Load budget | AssetLoader::Impl::finishLoads, LOAD_BUDGET in src/renderer/renderer.cpp |
| Frame slot state | FrameResources in include/rasm/types.h; frameFence, frameFenceValue, computeFence, computeFenceValue, frameCount in include/rasm/renderer.h |
| Batches | Renderer::useQueue, Renderer::waitForQueue, Renderer::waitForQueueWork, Renderer::closeBatch, Renderer::submitBatches in src/renderer/renderer.cpp |
| Resize | Renderer::recreateSwapchain, Renderer::createSwapchainResources in src/renderer/renderer.cpp; RenderContext::recreateSwapchain in src/rhi/renderContext.cpp |
| Events and minimize | Renderer::pollEvents, addInputEvent, setWindowSize in src/renderer/renderer.cpp, the input state in src/platform/input.cpp and src/platform/cameraInput.cpp, the SDL events in src/platform/sdlPlatform.cpp |
| Scene sync, scene passes | Renderer::syncGpuScene, Renderer::addScenePasses, Renderer::prepareSceneView, Renderer::recordSceneCulling, Renderer::recordHiz, Renderer::drawSceneView in src/renderer/gpuScene.cpp |
| Stats | Renderer::updateFrameStats in src/renderer/frameStats.cpp |
| Acquire, submit, present | VulkanSwapchain in src/rhi/vulkan/vulkanSwapchain.cpp, VulkanQueue::submit in src/rhi/vulkan/vulkanQueue.cpp |
| Graph frame | RenderGraph::execute, RenderGraph::bufferBarrier in src/renderer/renderGraph.cpp |
| Texture layouts | RenderContext::transitionImageLayout, RenderContext::discardRecording in src/rhi/renderContext.cpp; TextureStates in src/rhi/textureStates.cpp |
8Rules when you change it
frameCountis the frame-in-flight slot (0 or 1). Per-frame mutable buffers are indexed by it.- A slot's buffers are written only after that slot's fence wait. GPU scene tables are written only in
syncGpuScene. - A slot takes a new fence value only when a submit that signals it succeeded.
- Without async compute the frame has one command buffer and one submit; with it, a few batches. GPU work goes in as a graph pass that declares every buffer and target it uses: the graph records barriers and queue waits only for what is declared.
- Record through
FrameResources::commandBuffer, read inside the pass: it names the batch being recorded, which changes between queues. - When
beginFramereturns false, record nothing and do not callendFrame. - Every swapchain call handles
SUBOPTIMALandOUT_OF_DATEexplicitly. - Swapchain-sized resources use the swapchain extent in pixels, not the window's logical size.
- Run the examples with
enableValidationon after a frame-loop change. A change that adds validation messages is not done.