Foundations

Headless rendering and readback

Not every frame is for a screen. A test compares a frame with a stored image, a tool makes thumbnails, a server renders a map tile. Such a program renders headless, with no window, and then reads the pixels back from the GPU to the CPU. This page explains both: what takes the place of the window, how a copy reaches the CPU without stopping the GPU, how to turn the GPU's formats into plain pixels, and how to get the same pixels on every run. The last part shows how RASM does it.

In short

  • Headless: no window, no surface, no swapchain. The frame renders into images the program owns, which play the swapchain's role.
  • The GPU's images live in its own memory, in a layout only it knows. A copy moves them, row by row, into a buffer the CPU can read.
  • The copy is done only when the GPU has finished that frame. Wait on that frame's fence, a few frames later, and the CPU never stalls.
  • The bytes come in the image's format: BGRA order, sRGB numbers, half floats, depth. Convert them to what a PNG or an HDR file needs.
  • For a test, the same frame must give the same pixels on every run: wait for all loads, use a fixed time, and keep the GPU work in a fixed order.

1Why render without a window

A window is one place a frame can go. Many programs want the pixels themselves:

= this run golden image

Image tests

A test renders a scene and compares it with an approved image. A shader change that breaks the picture fails the test.

Thumbnails and screenshots

An asset browser renders each model once into a small image and saves it. A game saves the frame on a key press.

no screen map tiles

Servers and CI machines

A build machine or a tile server has no display at all. A window can't even be opened there.

0123 1/60 s per frame, not real time

Offline video

Frames for a video are rendered as slowly as they need to be, each at its exact time, and written to files.

2What takes the place of the window

With a window, the frame's last pass draws into a swapchain image, and present hands it to the screen (The swapchain). Without one, there is no surface, so there can be no swapchain. The program makes its own images instead, and the last pass draws into them:

passes swapchainimage present screen the system owns the images

Window

Surface, swapchain, acquire and present. The system decides which image comes next.

passes image 0 image 1 copy CPU the program owns the images

Headless

No surface, no swapchain extension. The program takes its images in turn, and "present" does nothing.

Keep the same shape as a swapchain: a few images, one per frame in flight, handed out in turn. Then the rest of the renderer does not change: the tone map still writes "the output image", and only the end of the frame differs. An image is handed out again only once the GPU has finished the last frame that drew into it, as the presentation engine would do.

Headless is a first step to "bring your own window"

Once the renderer no longer assumes a window, the window becomes one choice among several: a window the engine opens, a window the application owns, or none. The engine only needs to know where the frame goes and where the input comes from.

3The copy to the CPU

A rendered image sits in GPU memory, and the GPU stores it in its own tiled order: small blocks of pixels together, often compressed. The CPU can't read that. A copy command rewrites the image into a buffer as plain rows, in memory the CPU can map:

image, in GPU memory tiled: 2 × 2 blocks together 0123 4567 891011 12131415 copy image → buffer buffer the CPU can read rows, one after another row 0: px 0 1 4 5 row 1: px 2 3 6 7 row 2: px 8 9 12 13 row 3: px 10 11 14 15 byte 0 byte 16 byte 32 byte 48 row pitch = width × bytes per pixel = 4 × 4 = 16 bytes (some APIs pad it, D3D12 to 256)
The copy also undoes compression and tiling. The CPU then reads the buffer like any array: pixel (x, y) starts at byte y · pitch + x · bytes per pixel.
  1. 1. BarrierThe image waits for its last writer, and moves to the copy-source layout.
  2. 2. CopyImage → buffer, one layer and one mip at a time.
  3. 3. BarrierThe image goes back to its layout; the buffer's bytes are made visible to the host.
  4. 4. ReadAfter the fence: map the buffer and read the rows.

The image must allow the copy: it is created with copy-source usage. That flag is not free on every GPU: some drivers keep less compression for an image that may be copied, so engines ask for it only on the images they will read.

4When are the pixels there?

The copy is only recorded in the frame's commands. It runs when the GPU reaches it, which is after the CPU has moved on (Frames in flight). The simple way, to wait for the GPU to be idle right after the submit, works but stops the whole pipeline. The better way is to wait for the fence of the frame that made the copy, later:

CPU GPU F waits F+1 F idle nothing overlaps

Wait at once

The CPU waits for frame F, then the GPU waits for the CPU. Fine for one screenshot, bad for every frame.

CPU GPU F F+1 F+2: read F + copy F+1 F's fence: the copy is done

Wait on F's fence, later

With N frames in flight the CPU waits for frame F at the start of frame F + N anyway. Reading the copy then costs nothing.

So a readback is a small state machine: asked, then recorded into a frame, then done when that frame's fence value is reached, then taken. The program polls "is it done?" each frame and keeps rendering. Try it: the lab computes the same rule as the frame loop, with the CPU waiting for its frame slot at the start of each frame.

The copy rides in frame 2 (amber). Move "take in frame" to the frame where the program reads it, and look for the red wait on the CPU row. Then change the frames in flight and the GPU time.

5Converting the pixels

The buffer holds the image's own format. A PNG wants 8-bit RGBA in sRGB; an HDR file or a test of light values wants linear floats. Each source needs its own small rule:

B G R A R G B A

Byte order

Window images are often BGRA. Swap red and blue; the bytes stay exact.

linear 0.5 sRGB 188

sRGB curve

Linear light gets the sRGB curve for a PNG; an sRGB image is decoded for floats (Color spaces).

16 bit 32 bit, the same value

Half floats

HDR images hold 16-bit floats. Widen them to 32 bits; values above 1 stay, for HDR.

Two more rules. A depth image gives one float per pixel, so it reads as floats only. And an HDR value has no 8-bit form of its own: turning 25.0 into a byte means clamping it to 1 (or tone mapping it first), so a screenshot reads the tone-mapped frame, not the HDR target.

sRGB(c) = 12.92 · c, when c ≤ 0.0031308

sRGB(c) = 1.055 · c1/2.4 − 0.055, otherwise

c
a linear value, clamped to 0..1
sRGB(c)
the stored number, times 255 and rounded for 8 bits

6The same pixels on every run

An image test compares frame N of one run with frame N of another. Everything that decides what frame N shows must then be the same, not only the scene:

run 1, frame 60 run 2: still loading

Background loads

A file that loads in the background shows from the frame its load ends, which depends on the clock. Wait for every load before frame 1.

frame 60 is at 0.93 s, 1.07 s 1.00 s, fixed

Time

Animation and anything else driven by the wall clock moves by a different amount each run. Step time by a fixed amount per frame.

A B B A run 1run 2 blend order changes the color

Order on the GPU

Threads that append with atomics land in any order. Where order changes pixels (blending, ties), use a fixed order: prefix sums, a stable sort.

History counts too. Temporal effects (TAA, occlusion culling from the last frame) make frame N depend on the frames before it, so a test renders the same number of frames, with the same inputs, every run. And the GPU and its driver are part of the result: two GPUs round some math differently, so stored images belong to one driver, and tests compare with a small tolerance.

7Pitfalls

The frame rate drops while screenshots are taken
The program waits for the copy in the frame that asked for it. Poll the fence and take the pixels a few frames later.
The image is all black or random
The copy ran before the frame's passes wrote the image, or the bytes were read before the fence. The copy goes after the last pass, and the read after the fence.
Red and blue are swapped
The image is BGRA and was written to a file as RGBA.
The PNG is too dark or washed out
The sRGB curve is applied twice, or not at all: an sRGB image's bytes are already encoded, a linear image's are not.
Rows are shifted or slanted
The row pitch is wider than width × bytes per pixel (padding), and the reader assumed none.
The copy of a temporary target shows another image
Its memory was shared with a later target (Memory aliasing), which overwrote it before the copy at the end of the frame. A target that is read back needs memory of its own.
A multisampled image can't be copied
Copy commands take one sample per pixel. Read the resolved image.

8In RASM

RASM chooses the platform in EngineConfig::platform. PlatformType::SDL opens a window, PlatformType::NATIVE draws into the application's (The platform layer); PlatformType::HEADLESS opens none, starts no SDL and creates a Vulkan device without a surface. The frames then render into an OffscreenSwapchain: two readable R8G8B8A8_SRGB images on the device, which the rest of the engine sees as the swapchain. A readback is asked for with Renderer::readFrame or Renderer::readTexture and recorded at the end of the next frame. Each window has its own swapchain, offscreen when headless (Renderer::addWindow), and readFrame(window) copies that window's image; a window with no image that frame (minimized) is copied in the next frame that has one.

Larger than the window readFrame copies the window's image. For a still larger than the window or than the device's largest image, with no seams and averaged samples, use exportView (Tiled offscreen export).
EngineConfig::platform SdlPlatform HeadlessPlatform surface +VulkanSwapchain no surface,OffscreenSwapchain swapchain image tone map, UIwrite the image recordReadbackscopy, endFrame takeReadbackafter the fence or a readable targetRenderTargetDesc::readable writePng
The engine after the platform does not know whether a window exists: it acquires, draws and "presents" the same way. Only endFrame skips the move to the present layout for an offscreen image.
This pageRASM
Images of your own instead of a swapchainOffscreenSwapchain, an rhi::Swapchain on rhi::Device textures, so every backend gets it. MAX_FRAMES_IN_FLIGHT images, each handed out again after the frame fence of its last present submit (submitted).
Copy-source usage only where neededTextureDesc::readable, RenderTargetDesc::readable (off by default). A window's swapchain images get it when the surface's supportedUsageFlags has TRANSFER_SRC; else readFrame returns invalid.
Barrier, copy, barrierrhi::CommandBuffer::copyFromTexture: the image goes to the copy layout and back to its tracked state, then a copy → host barrier. Rows are tightly packed.
Wait on the frame's fence, laterEach readback keeps the frame fence value of the frame that copied it. isReadbackReady compares it with the fence; takeReadback waits only when called too early.
Read back only what you needA pick copies only the rect it drew, through the same frame fence: isPickReady, takePick (Picking).
A temporary target needs memory of its ownA graph makes a readable target outside the shared transient memory, as it does a history target.
Convert on the CPUconvertReadback, when the image is taken: ReadbackFormat::RGBA8_SRGB or RGBA32_FLOAT.
Wait for all loadsRenderer::waitForLoads; the examples call it with --wait-for-loads (C16), which verify-change passes.
A fixed time stepEngineConfig::fixedDeltaTime: the cameras' easing, Dear ImGui and the stats' refresh step by it instead of the measured frame time (C15). The examples set 1/60 s with --fixed-step.
The UI without a windowDear ImGui runs with no SDL: the display is the window's size (newUiPlatformFrame), its input is whatever the application sends with Renderer::addInputEvent (none by default), and the UI draws through the offscreen images' R8G8B8A8_UNORM view (TextureDesc::encodedView), so it looks as on a window.
Compare with a stored image, with a tolerancereadPng reads a stored PNG back as an RGBA8_SRGB image, the format writePng writes. The golden-image tests compare frames this way (Image tests).
A fixed GPU orderCulling compacts draws with prefix sums, the light clusters use integer atomics whose result does not depend on order, and the blend sort is a fixed bitonic network, so a frame does not depend on thread timing.
Bring your own windowPlatformType::NATIVE draws into the application's window, and the application sends the input (The platform layer). A native window's frames are read the same way when its surface allows copies: 19_embedding --headless renders into a hidden window and writes frame N.

Every example runs headless

Each example takes --headless --frames N --out file.png (examples/exampleArgs.h). applyExampleArgs sets PlatformType::HEADLESS, and the frame loop runs on exampleRunning instead of Renderer::running: it asks for the copy right before frame N, takes it after frame N, writes the PNG and ends the loop. main returns exampleExit, which is 1 with an error when the frame was not written (the copy or the write failed, or the loop ended before frame N). So a run opens no window, and verify-change checks every example this way.

frames 1 2 … N − 1 N + copy readFrame() before frame N takeReadback waits for N's fence writePng(--out) exampleRunning returns false: the example exits The UI is drawn too, with no input: the RASM window and an example's own windows are in the PNG.
Frame N is the same frame a windowed capture of frame N shows (the N-th present). With --fixed-step, EngineConfig::fixedDeltaTime is 1/60 s, so the cameras, the UI and the stats step the same way in every run.

Code map

WhatWhere
The platform choice, eventsPlatform in src/platform/platform.h; src/platform/sdlPlatform.cpp, src/platform/headlessPlatform.cpp, src/platform/nativePlatform.cpp; Renderer::pollEvents in src/renderer/renderer.cpp
A device without a surfaceVulkanDevice::initialize in src/rhi/vulkan/vulkanDevice.cpp
The offscreen imagessrc/rhi/offscreenSwapchain.cpp; made in RenderContext::initialize (src/rhi/renderContext.cpp)
The copyVulkanCommandBuffer::copyFromTexture, RenderContext::copyTextureToBuffer
Readbacks and conversionsrc/renderer/readback.cpp: Renderer::readFrame, readTexture, isReadbackReady, takeReadback, recordReadbacks, convertReadback, writePng, readPng
The exampleexamples/16_headless/main.cpp: a PNG of the frame and the HDR target's brightest and mean values
Every example's flagsparseExampleArgs, applyExampleArgs, exampleRunning, exampleExit in examples/exampleArgs.h
The UI without a windowsrc/platform/uiPlatform.cpp
Teststests/readbackTests.cpp: every conversion, and a PNG written with writePng and read again with readPng
Rules to keep

A readback is recorded after every pass and the UI, before the image moves to the present layout. Never wait for a readback in the frame that asked for it. A render target that is read back is made readable; do not add copy-source usage to images nobody reads.

Further reading