Culling and the frame

Multiple render targets

Often one pass must produce several images for the same pixels: a color, a normal, a material, a mask. Multiple render targets (MRT) let one draw write all of them at once. The fragment shader returns several values, and each one goes to its own texture. This page explains how that works, what it costs, and where it goes wrong. The last part shows how RASM does it.

In short

  • A pass can have N color attachments. The fragment shader returns N values; output i goes to attachment i.
  • The geometry is drawn once: vertex work, rasterization and the depth test happen one time for all N images.
  • All attachments have the same size. Each one has its own format, and can have its own blend state and write mask. There is one depth attachment for all of them.
  • The pipeline is built for the exact list of formats, in order. A pass with other formats cannot use it.
  • APIs allow 4 to 8 color attachments. The real limit is bytes per pixel: every byte is written and later read, for every pixel, every frame.
  • The classic use is deferred shading: a G-buffer pass writes surface data, a lighting pass reads it.

1The problem: several images per pixel

Many techniques need more than one value per pixel:

color normal material

Deferred shading

Needs the surface color, the normal and the material of every pixel.

one velocity per pixel

Motion blur, temporal anti-aliasing

Need a velocity per pixel.

7 12 31 one object ID per pixel

Object picking

Needs an object ID per pixel.

1 0 color mask

Post effects

Often need a mask that says which pixels belong to what.

A pass with one output can only write one of these images. To get three, you draw the scene three times, with three shaders. Every draw reads the vertices again, runs the vertex shader again, builds the triangles again and runs the depth test again. Only the last step, the fragment shader, does different work.

One output per pass: the mesh is drawn 3 times Mesh read 3 times pass 1 · vertex · raster · depth · fragment pass 2 · vertex · raster · depth · fragment pass 3 · vertex · raster · depth · fragment albedo normal material vertex work × 3 depth test × 3 Three outputs in one pass: the mesh is drawn once Mesh read once one pass vertex · raster · depth: once fragment shader: 3 outputs albedo normal material vertex work × 1 depth test × 1
The same three images, two ways. With many triangles, the top way costs about three times the geometry work.

There is a second problem with the top way. The three passes must agree exactly on which surface is in front at each pixel. With the same depth test and the same vertices they usually do, but it is easy to break:

albedo, pass 1 normal, pass 2 the two images show different surfaces at the edges

Three passes can disagree

A shader that moves vertices a little differently, or a different depth state, and the normal image shows a different surface than the albedo image.

albedo, output 0 normal, output 1 the same surface at every pixel

One pass cannot

The surface is found once per pixel, and every image gets its value from it (section 2).

2The idea: one pass, N outputs

A render pass does not have to draw into one image. It can have a list of color attachments: textures numbered 0, 1, 2 and so on. The fragment shader then returns one value per attachment. The GPU writes output 0 to attachment 0, output 1 to attachment 1, and so on, all for the same pixel.

One pixel fragment at (x, y) Fragment shader runs once, returns out 0 = albedo out 1 = normal out 2 = material attachment 0 · albedo 4 bytes, sRGB color attachment 1 · normal 4 bytes, 10 + 10 + 10 + 2 bits attachment 2 · material 4 bytes, linear data depth attachment: one, shared · tested once, for all outputs
Output i goes to attachment i. The orange square is the same pixel position in every texture.

In the shader, each output is marked with its attachment number. In Slang and HLSL the fragment shader returns a struct, and each field has a semantic with the number. (In Slang, fragMain also gets the [shader("fragment")] attribute; it is left out here.)

struct GBufferOutput
{
    float4 albedo : SV_TARGET0;
    float4 normal : SV_TARGET1;
    float4 material : SV_TARGET2;
};

GBufferOutput fragMain(VSOutput input)
{
    GBufferOutput output;
    output.albedo = float4(baseColor, ambientOcclusion);
    output.normal = float4(normalize(input.normal) * 0.5 + 0.5, 0.0);
    output.material = float4(metallic, roughness, 0.0, 0.0);
    return output;
}

Other shading languages spell the number differently, but the idea is the same:

LanguageOutput 1 is written as
Slang, HLSLfloat4 normal : SV_Target1; (the case of the semantic does not matter)
GLSLlayout(location = 1) out vec4 normal;
Metal (MSL)float4 normal [[color(1)]];
WGSL@location(1) normal: vec4f

Everything before the fragment shader is shared. The rasterizer finds the pixels once. The depth test runs once, and if it fails, none of the outputs are written. If it passes, all of them are. So the images can never disagree about which surface is visible.

Here is one such pass on a small scene. Each pixel finds its surface once and writes three outputs. There is no lighting: the images hold raw surface data.

Move the front ball over the other balls: all four images change together, at the same pixels. Move the probe: the three values always belong to the same surface. In the material image, red is metallic and green is roughness.

3The rules

The attachments of one pass are not fully free. They share some things and keep others apart:

shared by all: one size, one sample count attachment 0 attachment 1 attachment 2 depth a color a normal an ID (and stencil) format blend state write mask load, store, clear 8-bit sRGB 10-bit 32-bit integer blend on blend off blend off R G B A R G B R clear, store clear, store keep, store one for the pass: visibility is decided once per pixel
Above the sheets: what every attachment of a pass has in common. Under each sheet: what it can choose for itself. The values are examples.
PropertyPer attachment, or shared?Why
Size (width, height)shared: all the sameOne pixel position (x, y) must mean the same place in every texture.
Sample count (MSAA)sharedThe rasterizer makes one set of samples for all of them.
Formatper attachmentA color can be 8-bit sRGB, a normal 10-bit, a velocity 16-bit float, an ID a 32-bit integer.
Blend stateper attachment, if the GPU supports independent blendWithout it, all attachments must use the same blend state (Vulkan: the independentBlend feature; D3D12: IndependentBlendEnable). Desktop GPUs all support it.
Write maskper attachment (also under independent blend)Turns off writes to some channels, or to the whole attachment.
Load and store, clear valueper attachmentOne attachment can be cleared and another kept; see Load and store ops.
Depth (and stencil)one for the passVisibility is decided once per pixel, for all outputs.

The pipeline is built for exact formats

A graphics pipeline is compiled for a fixed list of attachment formats: how many there are, in which order, and which format each one has. The driver bakes the conversion from the shader's output (a float4) to each format into the pipeline. So a pipeline can only draw in a pass whose attachments have exactly those formats.

Same list → draw pipeline expects pass has 0 · RGBA8 sRGB 1 · RGB10A2 2 · RGBA8 depth · D32 0 · RGBA8 sRGB 1 · RGB10A2 2 · RGBA8 depth · D32 = = = = count, order and formats all match Other list → invalid pipeline expects pass has 0 · RGBA8 sRGB 1 · RGB10A2 2 · RGBA8 depth · D32 0 · RGBA8 sRGB 1 · RGBA8 missing depth · D32 = ≠ ≠ = validation error, or wrong output
The check is per slot. Older APIs used a "render pass" object to describe the list; with dynamic rendering (Vulkan 1.3) the pipeline lists the formats directly.

So one shader often needs several pipelines: one per list of formats it draws into. A material shader that draws both into a G-buffer and into a forward HDR target is two pipelines.

Limits

APIColor attachments per passNotes
VulkanmaxColorAttachments: at least 4, 8 on almost every GPUQuery it on the device. Some mobile GPUs report only 4.
Direct3D 128Fixed by the API.
Metal84 on the oldest Apple GPUs.
WebGPU8 by defaultAlso limits the total size: by default at most 32 bytes per sample over all attachments.

In practice the count is rarely the limit. The bytes are.

4The cost: bytes per pixel

Every attachment is written for every pixel the pass covers, and some later pass reads it back. So the cost of MRT is simple to estimate: add up the bytes per pixel of all attachments, and multiply by the number of pixels.

Bytes per pixel, one box = one attachment (15 px per byte) fat position · RGBA32F · 16 normal · RGBA16F · 8 albedo material depth 36 B packed albedo normal material velocity depth 20 B
The same surface data, two layouts. The difference is almost 2× in memory and bandwidth. The packed version drops the position (the lighting pass rebuilds it from depth), stores the normal in 2 × 16 bits, and still has room for a velocity. Every byte here is paid once to write and once to read, at every pixel.

Worked example: a G-buffer at 1080p

A 1920 × 1080 image has 2,073,600 pixels. Take the packed layout: four 4-byte color attachments and a 4-byte depth, 20 bytes per pixel.

memory      20 B × 2,073,600 px = 41,472,000 B ≈ 39.6 MiB
write       41.5 MB per frame   × 60 frames/s ≈ 2.5 GB/s
write+read  83 MB per frame     × 60 frames/s ≈ 5.0 GB/s
LayoutB/pixelMemory at 1080pWrite + read, 60 fps, 1080pMemory at 4KWrite + read, 60 fps, 4K
packed2039.6 MiB5.0 GB/s158.2 MiB19.9 GB/s
fat3671.2 MiB9.0 GB/s284.8 MiB35.8 GB/s

These are lower bounds. A pixel covered by several triangles is written several times (overdraw), the depth test also reads depth, and later passes may read the images more than once. A mid-range GPU has a few hundred GB/s in total, so a fat G-buffer at 4K takes a real part of the frame.

Build a layout yourself. The bar starts as the fat layout from the picture above.

Click the three boxes to change a format, and try to reach 20 bytes per pixel with a velocity. Then change the screen size: the cost grows with the number of pixels.

Packing: fewer bytes for the same data

camera pixel (x, y) depth position

Position

Naive: RGBA32F, 16 B. Packed: 0 B.

Do not store it. Rebuild it from the depth and the pixel position with the inverse view-projection matrix.

fold sphere: 3 numbers square: 2 numbers

Normal

Naive: RGBA16F, 8 B. Packed: RG16, 4 B, or RGB10A2, 4 B.

Octahedral encoding: fold the unit sphere onto a square, and store 2 numbers instead of 3. Or store 3 numbers in 10 bits each.

R G B A metallic roughness AO flags one RGBA8 texel: 4 bytes

Metallic, roughness, AO, flags

Naive: one attachment each. Packed: one RGBA8, 4 B.

Put small values that are used together into the channels of one attachment.

x y empty empty 8 B x y 4 B screen-space motion has 2 parts

Velocity

Naive: RGBA16F, 8 B. Packed: RG16F, 4 B.

Screen-space motion has 2 parts; the other channels were empty.

Tile-based GPUs

Most mobile GPUs, Apple's included, draw the screen in small tiles and keep the tile's attachments in fast on-chip memory. Writing many attachments is cheap there, as long as they fit in that memory and the pass does not store the ones nobody reads later. If all attachments together are too big for a tile, the GPU uses smaller tiles, which costs more. See Load and store ops.

5The classic use: deferred shading

Where the lighting runs is the difference between forward and deferred shading:

pixel lit 5 times, 4 of them hidden

Forward shading

Every triangle computes its lighting while it is drawn. A pixel that is covered five times is lit five times, and every object's shader must loop over every light.

pixel lit once: the visible surface

Deferred shading

Splits the work in two passes. Lighting is computed only for the surface that is really visible.

The first pass, the geometry pass, uses MRT to store what is needed for lighting: the G-buffer (geometry buffer). The second pass, the lighting pass, runs once per pixel and reads the G-buffer as textures.

Mesh all objects Geometry pass draws every object MRT: 4 outputs no lighting G-buffer 0 · albedo 1 · normal 2 · material 3 · velocity depth read Lighting pass full screen once per pixel loops over lights light list HDR color
Pass 1 writes several images with MRT. Pass 2 reads them as ordinary textures. The lighting cost no longer depends on overdraw.

What it gives

  • Lighting runs once per visible pixel, not once per covered triangle.
  • Many lights are cheap: each light only touches the pixels it reaches.
  • Other screen effects (ambient occlusion, reflections, decals) can read the same normals and depth.

What it costs

  • The G-buffer memory and bandwidth from section 4, every frame.
  • One surface per pixel: transparent objects need a forward pass after.
  • MSAA is hard: every attachment would need all its samples.
  • All materials must fit the same G-buffer layout.

MRT is not only for deferred shading. A forward pass can also write a velocity image for temporal effects (see History buffers), an object ID for picking, or a mask for a later post effect, next to its color.

6Variants

shader slot 0 empty: dropped slot 2

Unused slots

Some APIs allow an empty attachment in the middle of the list (a null view in Vulkan dynamic rendering, a null target in D3D12). The shader output for that slot is dropped.

Use: one shader for several passes that use different subsets of the outputs.

output mask 0 R G B A old values stay

Write mask 0

The attachment is bound, but its write mask turns all channels off.

Use: a pass that leaves one image untouched while it writes the others.

1 write 2 read the same pixel, in tile memory

Subpasses, input attachments, local read

A later step of the same pass reads the value an earlier step wrote at the same pixel, without a round trip to memory (Vulkan subpasses and dynamic rendering local read, Metal tile memory).

Use: deferred shading on tile-based GPUs: the G-buffer never leaves the chip.

shader

Storage images

The shader writes images directly, with no attachment: any pixel, any number of images.

Use: compute passes, or writes to other pixels than the current one. There is no blending and no depth test, and the shader must handle ordering itself.

17 18 19 triangle ID per pixel later pass

Visibility buffer

The geometry pass writes only a triangle ID and an instance ID (one 32- or 64-bit attachment). A later pass fetches the triangle and computes the rest.

Use: very dense geometry, where even a packed G-buffer is too big.

shader blend into 1 image 2 outputs, 1 image

Dual-source blending

Two shader outputs feed the blend of one attachment. Not MRT; see below.

Use: per-channel alpha, for example subpixel text.

MRT: 2 outputs → 2 images shader out 0 out 1 image 0 image 1 Dual source: 2 outputs → 1 image shader color factor blend into image 0 c·f + old·(1 − f) usually allowed with one attachment only
Both have a second shader output, but they do different things. Dual-source blending is a blend feature, not a way to write more images.

7Pitfalls

Normals show up in the color image, or masks in the albedo
The output number and the attachment order differ. Nothing crashes: all are float4. Keep one list of the attachments and build both the pass and the shader struct from it.
Garbage in one image at some pixels
An output is not written on some path. A missing output (or a missing channel) is undefined, not 0. Write every output in every branch. Use a write mask if the image should keep its old value.
Normals and masks come back bent
Data in an sRGB format: the GPU applied the sRGB curve on write. Use UNORM or float formats for data. Only colors get sRGB. See Color spaces.
Validation error, or the pipeline fails
Blending on a format that cannot blend. Integer formats never blend, and 32-bit float often cannot. Turn blending off for that attachment (needs independent blend), or pick another format.
A mask or roughness stored in alpha also changes how the color mixes
Blending is on with data in alpha. Keep blending off on data attachments, or move the data out of alpha.
At edges a mask is 0.3 or 0.7, not 0 or 1
The mask is read with a linear filter, and the reader's size or position differs. Compare against 0.5, or sample with a nearest filter.
The pass is bandwidth-bound; on tile-based GPUs it is slower than expected
Too many bytes. Pack (section 4), and do not store attachments that no later pass reads.

8In RASM

A RASM render target has up to MAX_COLOR_ATTACHMENTS (4) color textures and one depth texture. Its formats are listed in RenderTargetDesc::colorFormats. A pipeline that draws into it takes its formats from the target, and every color is a bindless texture that later passes can sample. examples/01_render_graph uses two colors.

trail_rt from the Trail pass Background pass color : SV_TARGET0 mask : SV_TARGET1 composite_rt color 0 · trail color swapchain format color 1 · mask, 0 or 1 R8G8B8A8_UNORM depth · D32_SFLOAT needed, not used Present mask 0 → green else the color reads attachments 0 and 1 with getRenderTargetTexture The mask is 1 where the trail's alpha is at least 0.5: the bunny writes alpha 1 over the clear color's alpha 0.
One full-screen draw writes both colors. The next pass reads them as two bindless textures.

The fragment shader of the Background pass, as in the example (where fragMain also has the [shader("fragment")] attribute):

struct Targets
{
    float4 color : SV_TARGET0;
    float4 mask : SV_TARGET1;
};

Targets fragMain(VSOutput input)
{
    Targets targets;
    targets.color = gTextures[pc.indices[0]].Sample(input.UV);
    targets.mask = float4(targets.color.a < 0.5 ? 0.0 : 1.0);
    return targets;
}

The target lists the two formats in the same order, and the pipeline is made from the target, so the formats always match:

compositeHandle = builder.createRenderTarget({
    .name = "composite_rt",
    .swapchainScale = 1.0f,
    .colorFormats = {colorFormat, rasm::Format::R8G8B8A8_UNORM},
    .depthFormat = rasm::Format::D32_SFLOAT,
});

// later: a pipeline with the target's formats
auto pipeline = engine.createPipeline("background", source, compositeHandle);

What happens to the formats

CPU · create the target RenderTargetDesc colorFormats = {A, B} checkRenderTargetDesc no gap · a depth (storage: none) createAttachments A, B, depth · colors bindless CPU · create the pipeline Renderer::createPipeline (name, source, target) PipelineDesc colorAttachmentFormats = {A, B} Vulkan pipeline every color: blend off, RGBA written Each frame · record the pass beginPass A, B → attachments one clear, one load op bindPipeline pipeline formats = the pass's? yes: bind, draw no: error, draws skipped endPass A, B → SAMPLED later passes read A and B stand for the two formats of the example: the swapchain format and R8G8B8A8_UNORM.
The target is the one source of the format list. The pipeline copies it, and bindPipeline checks it again for every pass.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Number of colors4 to 8, from the deviceMAX_COLOR_ATTACHMENTS = 4, the minimum Vulkan guarantees, so no device query is needed.
The list of formatssome APIs allow empty slotsNo gaps. The list ends at the first Format::UNKNOWN (colorAttachmentCount). checkRenderTargetDesc rejects a desc with a gap, or without a depth format. A depth-only target (a shadow map) has no color.
DepthoptionalNeeded by every render target that passes draw into, even when no pass tests depth, as in the example. Only a storage target, which compute passes write, has none.
Blend state, write maskper attachment, with independent blendThe same for every color: one BlendMode per pipeline, all four channels written (VulkanDevice::createGraphicsPipeline). So no independent blend is needed. A pipeline from Renderer::createPipeline has blending off; only pipelines the engine makes itself blend, such as the transparent scene draws.
Clear valueper attachmentOne RenderTargetDesc::clearColor for all colors.
Load and storeper attachmentOne load op for all colors (AttachmentOps::loadColor, set per pass by the render graph); colors are always stored. See Load and store ops.
Pipeline formatsexact list, in orderRenderer::createPipeline with a target copies its color and depth formats. RenderContext::bindPipeline compares all of them with the pass's; a mismatch logs an error and skips the pass's draws.
Reading the resultsample as texturesEvery color is bindless with LINEAR_CLAMP. endPass moves each to SAMPLED; getRenderTargetTexture with the attachment index returns it.
Formats for packingRG16, RGB10A2, RG16FOnly RG16F is in Format: R16G16_SFLOAT, the scene's MOTION_FORMAT. The other 4-byte color formats are R8G8B8A8_UNORM, R8G8B8A8_SRGB, B8G8R8A8_SRGB and B8G8R8A8_UNORM; the example's 1-bit mask takes 4 bytes.
G-buffer from the scenesection 5None. addScenePasses needs a target with a SCENE_COLOR_FORMAT color and D32_SFLOAT depth; it logs an error and adds no passes otherwise. The scene writes a second color only for TAA: a MOTION_FORMAT color, with one sample, gets each pixel's motion (RASM_MOTION_VECTORS, TAA). Its passes shade as they draw, so this is forward shading with two outputs, not a G-buffer.
Subpasses, local readsection 6None. Each pass is its own dynamic rendering scope; a later pass reads the colors as textures.
Memorysection 4All colors and the depth of a transient target share heaps with other transient targets (D9). See Transient memory and aliasing. A history target has two copies of every color (History buffers). A history or readable target has memory of its own.

Where it lives in code

WhatWhere
The limitMAX_COLOR_ATTACHMENTS in include/rasm/types.h
The format listRenderTargetDesc::colorFormats in include/rasm/render/resource.h; colorAttachmentCount in src/rhi/resource.cpp
The target's dataRenderTarget, RenderTargetAttachments in include/rasm/types.h
Desc checkscheckRenderTargetDesc in src/rhi/renderContext.cpp
One texture per colorcreateAttachments in src/rhi/renderContext.cpp
Pipeline formats from a targetRenderer::createPipeline in src/renderer/renderer.cpp, into PipelineDesc::colorAttachmentFormats
Blend state for every colorVulkanDevice::createGraphicsPipeline in src/rhi/vulkan/vulkanDevice.cpp
Starting the passRenderer::beginPass in src/renderer/renderer.cpp; RenderContext::beginRendering; VulkanCommandBuffer::beginRendering in src/rhi/vulkan/vulkanCommandBuffer.cpp
The format checkRenderContext::bindPipeline in src/rhi/renderContext.cpp
Reading color iRenderer::endPass, Renderer::getRenderTargetTexture in src/renderer/renderer.cpp
The scene's colors: color, and motionRenderer::addScenePasses in src/renderer/gpuScene.cpp; RASM_MOTION_VECTORS in shaders/passes/rasm.slang
The examplethe Background and Present passes in examples/01_render_graph/main.cpp
Keep these true
  • The shader's SV_TARGET0, SV_TARGET1, … follow the order of the target's colorFormats. Make the pipeline with createPipeline(name, source, renderTarget), so its formats come from the target.
  • A render target desc has no gap in colorFormats, and a depth format; a storage one has colors and no depth. checkRenderTargetDesc rejects anything else.
  • Data attachments (masks, normals, IDs) use a UNORM or float format, never sRGB.
  • Write every output on every path. Blending is off, so an output the shader skips leaves undefined values.
  • addScenePasses draws only into a target with a SCENE_COLOR_FORMAT color (and, with one sample, an optional second MOTION_FORMAT color) and D32_SFLOAT depth, or a depth-only one.
  • A pipeline that draws into a render target comes from createPipeline(name, source, renderTarget), even for one color: the two-argument overload is for the swapchain, which has no depth.
  • A new per-attachment field in PipelineDesc (a blend state, a write mask) must also go into its hash in src/rhi/resource.cpp, or two different pipelines are merged.

Further reading