Foundations
The swapchain and presenting
A program never draws straight onto the screen. It draws into an image, and hands the image to the system, which shows it at the next refresh. The swapchain is the small set of images that goes round between the two. This page explains the loop (acquire, render, present), the sync it needs, the present modes behind "vsync", and what to do when the window changes size. The last part shows how RASM does it.
In short
- A swapchain is a ring of 2 to 4 images owned by the presentation engine (the OS compositor or display).
- Each frame: acquire an image, render into it, present it.
- Acquire returns before the image is really free. An acquire semaphore makes the GPU wait; a present semaphore makes the present wait for the rendering.
- The present mode decides what happens at the refresh: wait for it (FIFO, vsync), replace the waiting image (MAILBOX), or show at once and tear (IMMEDIATE).
- When the window changes, the swapchain becomes out of date or suboptimal. The program then builds a new one, and everything sized like it.
- A minimized window has size 0 × 0: no swapchain can exist for it, so frames are skipped.
1Why not draw onto the screen
The display reads its picture from memory, line by line, about 60 to 240 times per second. What happens when the program draws into that same memory?
One image
The program draws into the memory the display reads. The display shows half-drawn frames.
Several images
The display shows one, while the program draws into another. When the new one is done, they swap.
That is the old idea of double buffering, and a swapchain is its modern, explicit form.
The images belong to the presentation engine, not to the program. The program asks for one, may draw into it until it gives it back, and must not touch it after that. The engine decides which image comes next, and when.
2The loop: acquire, render, present
- 1. AcquireAsk the swapchain for the next image. The answer is an index into its images. It may block when every image is in use.
- 2. RenderRecord commands that draw into that image, and submit them.
- 3. PresentGive the image back, with a request to show it.
There is a catch in step 1. Acquire returns as soon as the swapchain knows which image comes next, which can be before the display has stopped reading it. So the index alone does not make it safe to draw. The image becomes free at some later moment, and only the GPU timeline knows when.
Two semaphores handle this. A semaphore is a GPU-side signal: one submission signals it, and another one waits for it. The CPU never waits on it.
| Semaphore | Signaled by | Waited on by | Wait where |
|---|---|---|---|
| Acquire ("image available") | the presentation engine, when the image is free | the submission that draws into the image | the color output stage, so earlier work is not held back |
| Present ("render finished") | that submission, when it is done | the present call | the presentation engine, before it reads the image |
Before present, the image must also be in the layout the display can read (in Vulkan: PRESENT_SRC). Its old contents do not matter at acquire, so the first barrier of the frame can discard them. See GPU synchronization for layouts and barriers.
When may a semaphore be used again?
A binary semaphore must be waited on once before it is signaled again. That makes reuse the most common swapchain bug:
| Semaphore | Free again when | So keep |
|---|---|---|
| Acquire | the submission that waited on it has finished, which a fence tells the CPU | one per frame in flight, reused after that frame's fence wait |
| Present | the present has waited on it. The program cannot observe that directly (without an extension that gives present a fence). | one per swapchain image. An image is acquired again only after its last present finished, so by then its semaphore is free. |
One present semaphore per frame in flight
It looks right and works on many machines, but the present of frame n may still hold it when frame n + 2 signals it again. Validation layers now report this.
One per swapchain image
An image is acquired again only after its last present finished. By then its semaphore is free.
3Present modes and vsync
The display refreshes at fixed times, the vertical blank (vblank). The present mode says what happens to a presented image between two of them.
The four modes, by their Vulkan names:
FIFO
At a refresh, shows the oldest queued image. A full queue makes acquire or present block.
"vsync on". Always supported. Saves power: the GPU does not render frames nobody sees.
Tearing: no · Latency: higher
FIFO_RELAXED
Like FIFO, but an image that arrives late is shown at once.
Avoids a whole lost refresh when a frame is a little late.
Tearing: only when late · Latency: higher
MAILBOX
At a refresh, shows the newest image. A new present replaces the queued one.
"Triple buffering" in the classic sense. The GPU runs flat out; frames are wasted.
Tearing: no · Latency: low
IMMEDIATE
Does not wait for a refresh.
"vsync off". Liked by competitive games.
Tearing: yes · Latency: lowest
Worked example: when the GPU is too slow for FIFO
A 60 Hz display refreshes every 16.7 ms. With FIFO, a frame can only appear at a refresh. These numbers come from stepping the rules above with a fixed GPU time per frame:
With 2 images and 20 ms frames, the GPU loses the rest of each refresh, so it drops all the way to 30. A third image lets the GPU start the next frame during the wait. The average is close to the GPU's own 50, but the timing is uneven, which the eye notices as judder.
Step the same rules yourself, for any GPU time. The display stays at 60 Hz.
4When the swapchain no longer fits
A swapchain is built for one window size and one surface. When the window changes, acquire and present report it:
Suboptimal
The image was acquired or presented, but the swapchain no longer matches the surface exactly (for example, its size).
Do: finish and present this frame. Rebuild before the next one.
Out of date
The swapchain cannot be used any more. From acquire: no image was acquired.
Do: skip this frame. Rebuild.
Surface size 0 × 0
The window is minimized. No swapchain can be built for it.
Do: skip frames, ideally sleeping until a window event, until the size is back.
Most programs also listen to the window system's own resize event, because not every platform reports out of date in time. Rebuilding works like this:
- Wait for the GPU. The old images may still be in use by frames in flight. The simple way is to wait until the device is idle; resize is rare, so the stall does not matter.
- Build the new swapchain with the new size, passing the old one as "old swapchain". That lets the system hand over smoothly, and retires the old one even if the build fails.
- Destroy the old swapchain and its image views.
- Rebuild what has the screen's size: depth buffers, full-screen render targets, the viewport, and the camera's aspect ratio.
- Use the swapchain's size, not the window's. The surface picks the final size, and on high-DPI screens it is in pixels, while the window size may be in points.
A rebuild can happen between acquire and present. Then an acquire semaphore may be signaled and never waited on, and a binary semaphore in that state cannot be signaled again. A robust rebuild first makes sure every signaled semaphore is waited on (for example, with an empty submission that only waits), or destroys and recreates the semaphores.
5Format and color space
The swapchain also fixes the pixel format and the color space the display expects. A common choice is an 8-bit BGRA or RGBA format with an sRGB encoding.
- Shaderoutputs linear color
- sRGB formatthe hardware converts linear to sRGB when it writes
- Displaygets the sRGB it expects
HDR displays need other color spaces and wider formats. See color spaces: sRGB and linear.
6Pitfalls
- Drawing as soon as acquire returns, with no semaphore wait
- The display may still read the image: flicker or garbage, on some machines only.
- Present semaphores per frame in flight
- A semaphore is signaled while a present still waits on it (section 2).
- Treating the image index as the frame slot
- The order of images is up to the swapchain, and their count is not the number of frames in flight. Index frame resources by the slot (see frames in flight).
- Ignoring suboptimal or out of date
- A stretched picture after resize, or errors on every frame.
- Forgetting the layout change to "present"
- The display reads an image in a layout it does not understand.
- Not presenting an acquired image
- The image stays out of the ring. After a few such frames, acquire has no image left to give.
7In RASM
VulkanSwapchain builds the swapchain with vk-bootstrap and owns all of its sync objects. No semaphore crosses the RHI: a submit only names the swapchains, to wait for their images (SubmitDesc::acquireSwapchains) or to present them (SubmitDesc::presentSwapchains), and each swapchain fills in its waits and signals. Each window has its own swapchain (Renderer::addWindow): the main window's uses the surface the device was chosen for, another makes a surface of its own, and the device checks that its graphics queue can present to it (vkGetPhysicalDeviceSurfaceSupportKHR). A frame is one submit, or with async compute a few (the frame loop): the first graphics submit waits for every window's image, and the last one presents them all; each window is then presented with its own vkQueuePresentKHR. The engine's frame loop handles skipped frames and resize.
A headless engine (PlatformType::HEADLESS) has no surface. RenderContext then makes an OffscreenSwapchain instead: two readable R8G8B8A8_SRGB images on the device, handed out in turn, each after the frame fence of the last submit that drew into it. Submits name no swapchain, and present does nothing. The window's images also get copy-source usage when the surface allows it, so readFrame can read either. See Headless rendering and readback.
acquireNextImage when an acquire semaphore is free again, without depending on how the engine paces its frames.| Sync object | Kind | How many | Free again when |
|---|---|---|---|
acquireSemaphores | binary | MAX_FRAMES_IN_FLIGHT (2), used in turn by nextAcquireSlot | releaseTimeline reaches the value in acquireReleaseValues for that slot: the submit that waited on it is done |
presentSemaphores | binary | one per swapchain image | the image is acquired again. They survive a resize; a swapchain with more images only adds more. |
releaseTimeline | timeline | 1 | — (values only grow; releaseValue is the last one signaled) |
The order is enforced
acquireWaited (onAcquireWaited), so later submits of the frame skip the wait; present clears it. A call in the wrong state logs an error and fails: a submit that waits for or presents the image while Idle, an acquire while Submitted (FAILURE), a present that does not follow a successful submit. "Acquire again" happens after a failed submit: the image is still acquired and its semaphore still signaled, so it is handed out again.The frame loop around it
WindowFrame::outOfDate carries the news to the next beginFrame, for that window only. The window sets resized on SDL's pixel-size event, or when a NATIVE application calls setWindowSize, so the swapchain follows the size in pixels (B17).Resize, step by step
- Ask the surface.
VulkanSwapchain::resizereads the surface size. A 0 × 0 surface returnsOUT_OF_DATEand keeps the old swapchain (B5). A failed query returnsFAILUREand keeps it too. - Consume pending signals.
releasePendingSemaphoressubmits a wait-only batch for an image that was acquired but not submitted, and for one submitted but not presented. - Go idle and rebuild. The device waits idle, the old image views go, and the new swapchain is built with the old one as
oldSwapchain. The old one is destroyed either way. If the build fails, there is no swapchain, and acquire reportsOUT_OF_DATEuntil a rebuild works. - New handles.
RenderContext::recreateSwapchainregisters the new images under new texture handles. - Screen-sized resources.
Renderer::createSwapchainResourcesrebuilds the render targets sized from the swapchain (RenderContext::resizeRenderTargets), which keep their bindless slots, and sets the camera aspect ratio from the swapchain's extent.
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Present mode | a choice: FIFO, MAILBOX, IMMEDIATE | Always VK_PRESENT_MODE_FIFO_KHR, so the frame rate is capped at the refresh rate. Other modes crashed vkDestroyDevice on NVIDIA (B21). There is no vsync option. |
| Image count | 2 to 4 | vk-bootstrap's default; RASM does not ask for a count. |
| Format | sRGB or HDR | Asks for VK_FORMAT_B8G8R8A8_SRGB with VK_COLOR_SPACE_SRGB_NONLINEAR_KHR. No HDR. |
| Acquire semaphores | one per frame in flight, freed by the frame fence | One per frame in flight, but the swapchain tracks their reuse with its own releaseTimeline, so it does not rely on the engine's frame fence. |
| Present semaphores | one per image | The same (presentSemaphores), kept across resizes. |
| Wait stage | color output | Color attachment output. The barrier that moves the image out of UNKNOWN waits at the same stage, so the layout change comes after the acquire. |
| Layout | discard at acquire, "present" before present | RenderContext::acquireNextImage sets the image's state to UNKNOWN; beginPass moves it to COLOR_ATTACHMENT, discarding; endFrame moves it to PRESENT_SRC. |
| Every acquired image is presented | yes | Yes. A frame that only drew into render targets gets a "Clear" pass in endFrame. A failed submit keeps the image acquired for the next frame. |
| Suboptimal | finish the frame, rebuild | The same, through the window's WindowFrame::outOfDate. |
| Minimized window | skip frames, sleep | The same: beginFrame skips, and with SDL pollEvents waits up to 100 ms for an event while minimized. A NATIVE application reports a size of 0 with setWindowSize and sleeps in its own loop. |
| Rebuild | wait idle, old swapchain, release signals | All three. |
| Present queue | any queue that can present | The graphics queue. Compute queue submits never wait for the image or present it. |
| Submits per frame | one | One, or a few with EngineConfig::asyncCompute: the first graphics submit waits for the image, the last one presents. |
Where it lives in code
| What | Where |
|---|---|
| Building, acquire, present, resize | VulkanSwapchain in src/rhi/vulkan/vulkanSwapchain.cpp |
| The image wait, the present signals | getAcquireWait, onAcquireWaited, getPresentSignals, onSubmitted; used by VulkanQueue::submit in src/rhi/vulkan/vulkanQueue.cpp |
| Result codes | SwapchainStatus in include/rasm/types.h |
| Image handles, layout at acquire | RenderContext::acquireNextImage, recreateSwapchain in src/rhi/renderContext.cpp |
| Skips, resize, present | Renderer::beginFrame, endFrame, submitBatches, recreateSwapchain, createSwapchainResources in src/renderer/renderer.cpp |
| Resize and minimize events | pollEvents in src/platform/sdlPlatform.cpp src/platform/platform.h |
- Swapchain calls handle
VK_SUBOPTIMAL_KHRandVK_ERROR_OUT_OF_DATE_KHRexplicitly, and return aSwapchainStatusthe engine acts on. - No semaphore crosses the RHI. The acquire → submit → present order lives inside
VulkanSwapchain. - Everything sized like the screen comes from the swapchain's extent in pixels, not from the window's logical size.
- Swapchain images belong to the swapchain:
RenderContext::destroyTexturerefuses them.
Further reading
- The Khronos Group, Vulkan Specification: the chapter "Window System Integration (WSI)", and the extension VK_EXT_swapchain_maintenance1 (fences for present).
- Alexander Overvoorde, Vulkan Tutorial: the chapters "Swap chain" and "Swap chain recreation".
- Microsoft, DXGI flip model documentation, for the same ideas on Windows and Direct3D.