Drawing

Uber shaders and shader permutations

Materials differ: one has a normal map, one does not; one is lit, one is unlit. A renderer can compile a separate shader for every combination, or write one big shader, an uber shader, that handles all of them with branches at run time. This page explains both ways, what a branch really costs on a GPU, and why GPU-driven renderers lean towards one shader. The last part shows how RASM does it.

In short

  • Every on/off feature doubles the number of shader combinations, the permutations. A few features give hundreds of shaders.
  • Compile-time variants (#if) give the fastest code per combination, but cost compile time, memory, pipeline-creation stalls and draw-call splits.
  • An uber shader branches at run time on material data. One shader, one pipeline, slightly slower code.
  • A branch that is the same for all threads of a wave is cheap. A branch that differs inside a wave (divergence) runs both sides.
  • The real cost of an uber shader is often registers: the worst path decides how many waves fit on the GPU.
  • Specialization constants sit in between: one compiled shader, with constants fixed when the pipeline is made.

1The permutation explosion

Take a typical material model, like glTF's. A texture can be there or not. The surface can be opaque, cut out, or blended. It can be lit or unlit, single- or double-sided. Each choice changes the shader code, so each combination of choices is, in the simplest design, its own shader.

base colortexture× 2 metal-roughtexture× 2 normalmap× 2 occlusionmap× 2 emissivemap× 2 alphamode× 3 double-sided× 2 shadingmodel× 2 2 × 2 × 2 × 2 × 2 × 3 × 2 × 2 = 384 combinations per pass Each cell is one shader. × 3 passes (depth only, shadow, color) = 1,152 shaders Add skinning (× 2) or vertex colors (× 2), and it doubles again.
The count multiplies: each new on/off feature doubles it. This is the permutation explosion.

Try it. Build the material model one feature at a time and watch the count. The single orange cell is the other answer, an uber shader (section 3).

Switch every feature off, then put them back one by one. Each feature multiplies the number of shaders to compile. The uber shader stays one shader: it only gets one more test.

Not every combination is used by a real scene, so engines only compile the ones they meet. But they do not know which ones until the content is loaded, and the set changes with every new asset.

2Way 1: compile-time variants

The classic answer writes the shader once, with preprocessor switches, and compiles it once per combination with different #defines:

float3 n = input.normal;
#if HAS_NORMAL_MAP
    n = sampleNormalMap(material.normalTexture, input.uv, n);
#endif
// compiled twice: with HAS_NORMAL_MAP = 1, and with HAS_NORMAL_MAP = 0
one source with #if switches compile × N one per combination normal map, lit no normal map, lit … N binaries pipeline 1 pipeline 2 pipeline N Every draw must bind the pipeline of its combination, so draws are grouped and split by pipeline.
Each binary contains only the code its combination needs: no dead branches, no wasted registers.
normal map, lit no normal map, lit

Good

  • The fastest code for each combination. Unused features cost nothing.
  • Each binary uses only the registers its own path needs.
  • Simple to reason about: one shader does one thing.
a new pipeline: one long frame frame time, frame after frame

Bad

  • Compile time grows with the number of combinations.
  • Each binary needs a pipeline. Creating a pipeline the first time it is needed causes a visible stall: the well-known shader stutter.
  • More pipelines mean more state changes, and more splits of a GPU-driven draw list.

3Way 2: one uber shader with runtime branches

The other answer compiles one shader that contains every feature, and decides at run time, from the material's data, which parts to run. The material stores flags, or uses a special value such as "no texture" for a missing texture index:

float3 n = input.normal;
if (material.normalTexture != NO_TEXTURE)
    n = sampleNormalMap(material.normalTexture, input.uv, n);
// compiled once; the branch is decided per material, at run time
one source with if (material…) compile × 1 one binary if normal map: … if emissive map: … if unlit: … else: … … 1 pipeline for all draws
The material becomes data: a row in a table, read by the shader. Changing a material never needs a new pipeline.
the material table: one row per material material 0 normalTexture = 7 unlit = 0 material 1 NO_TEXTURE unlit = 0 material 2 NO_TEXTURE unlit = 1 read the one shader row 0: runs the normal-map code row 1: skips it row 2: takes the unlit path
Three materials, three behaviours, one binary. The shader reads the row of the draw's material and branches on it.

Whether this is fast depends on how GPUs run branches. That is the next section.

4How a GPU runs a branch

A GPU does not run each pixel's shader on its own. It runs them in groups of 32 or 64 threads, called a wave (or warp). All threads of a wave share one instruction stream: at each step, they all run the same instruction, each on its own data. Each thread is a lane of the wave.

So what happens at an if? If all lanes agree, the wave simply runs the side they chose. If they disagree, the wave runs both sides, one after the other, and switches off the lanes that did not choose the side being run. This is called divergence.

a wave of 8 lanes (real waves have 32 or 64), time from left to right all lanes: A uniform A 100 steps all lanes: B uniform B 300 steps 3 lanes A, 5 lanes B divergent A, 5 lanes off B, 3 lanes off 400 steps both sides, for every lane
A divergent branch costs the sum of both sides. Lanes that are switched off wait; they do no useful work.

Try it with the same wave: side A costs 100 steps, side B 300.

Press "All lanes: A", then click one lane. One lane that disagrees is enough: the wave runs both sides, and the other seven lanes wait for it.

So the question is not "does the shader branch?" but "is the branch the same for all lanes of a wave?". There are three kinds of values a branch can test:

side B: not in the binary every lane: A, and no test

Known when compiling

A #define, a specialization constant.

Cost: none: the compiler removes the side not taken

wave 1: all A wave 2: all B. Each wave runs one side.

The same for the whole draw (uniform)

A material flag, when the draw has one material.

Cost: small: every wave takes one side; only the test itself costs

one wave runs A, then B

Different per pixel or vertex (varying)

A texture value, the light's distance.

Cost: can be both sides, when neighbouring pixels disagree

A material branch is the good, middle case: all pixels of one draw share one material. Whether one wave can hold pixels of two draws depends on the GPU. When it can, the branch may diverge in that wave, at draw edges only. In Vulkan, the specification treats each draw of a multi-draw as its own group for this purpose, so a value that is the same for the whole draw still counts as uniform.

5The hidden cost: registers

Divergence is easy to see. A bigger cost of uber shaders is easy to miss. A GPU keeps many waves in flight on each compute unit at once. When one wave waits for memory, for example for a texture, the unit switches to another one. More waves in flight hide more waiting. The number of waves that fit is called occupancy.

Waves share the unit's register file. A shader that needs more registers per thread leaves room for fewer waves. And the compiler must give the shader enough registers for its worst path, even if most materials never take it. One rare, heavy feature in an uber shader can lower the occupancy of every material.

the registers of one wave the register file of one SIMD (example: AMD GCN)
registers per thread 256 vector registers per lane waves per SIMD up to 24 10 waves 40 6 waves 64 4 waves 84 3 waves 128 2 waves waves = min(10, ⌊256 / registers⌋). 10 is the maximum.
More registers per thread, fewer waves in flight. Other GPUs have other numbers, but the same shape.

A branch that raises the count from 40 to 64 turns 6 waves into 4, for every pixel the shader runs, taken or not.

Keep the heavy path small

Do not copy big structs or arrays into local variables at the top of an uber shader "just in case": the compiler may keep them in registers for the whole shader. Read data when a path needs it, through a pointer or an index.

6Way 3: specialization constants

Vulkan offers a middle way. A specialization constant is a constant in the compiled shader (SPIR-V) whose value is given only when a pipeline is created. The driver then compiles the pipeline with that value, and removes the branches it decides. Metal has the same idea as function constants.

// Slang
[SpecializationConstant] const bool hasNormalMap = false;

// GLSL
layout(constant_id = 0) const bool HAS_NORMAL_MAP = false;
one source compiled once one SPIR-V binary hasNormalMap: decided later true false pipeline A driver compiles it with the normal-map code pipeline B driver compiles it without: the branch is gone
The front-end compile happens once. Each value still needs its own pipeline, and its own driver compile.
Compile-time variantsUber shaderSpecialization constants
Source compilesone per combinationoneone
Pipelinesone per combinationoneone per combination
Code speedbestbranch tests, worst-case registersbest
Draw-list splitsone per combinationnoneone per combination
Can change per draw for freenoyes: it is datano
Available onevery APIevery APIVulkan (and Metal's function constants); not in Direct3D 12

7The material type switch

Some differences are not small features but whole shading models: lit and unlit, skin, hair, cloth, clear coat. An uber shader handles them with a small integer per material, the material type (or shading model id), and a switch at the top of the pixel shader:

switch (material.type)
{
case UNLIT:      return shadeUnlit(material, input);
case CLEAR_COAT: return shadeClearCoat(material, input);
default:         return shadeStandard(material, input);
}

The type is uniform per material, so this is the cheap kind of branch. The register cost from section 5 still applies: the heaviest model sets the register count for all.

Deferred renderers use the same idea one step later: they write the shading model id into the G-buffer, and the lighting pass switches on it per pixel.

one draw: every pixel has the same type

Switch per draw

All lanes of a wave agree. The switch costs only its test.

these waves hold two ids: both sides run

Switch per pixel (deferred)

Neighbouring pixels can have different ids, so divergence is real at the edges between materials.

8Why GPU-driven renderers want one pipeline

In a GPU-driven renderer, one indirect call draws many objects, but with one pipeline. Every extra pipeline splits the draw list into another run: another range to cull and pack, another count, another call.

A pipeline per material type type 1 type 2 type 3 type 4 type 5 bind 1draw bind 2draw bind 3draw bind 4draw bind 5draw 5 runs: 5 ranges to cull and pack, 5 counts, 5 pipeline binds and 5 indirect calls. One uber pipeline all types, one run bind once one indirect draw The type is a field in the material row. The shader switches on it, per draw.
The more pipelines, the more the CPU and the culling pass work per frame. An uber shader keeps it at one.

This is why GPU-driven renderers usually combine three ideas:

material row if … if … else …

An uber shader

For the shading.

012345 textures[3] all textures bound once, as one array

Bindless textures

Picked by index from the material row.

mesh A mesh B mesh C one mega-buffer offset

Vertex pulling

From one mega-buffer.

Together they remove every reason to bind anything between draws.

9Choosing: what goes where

Real engines mix the three ways. A common split:

DifferenceUsually handled byWhy
Blending, depth writes, the render passseparate pipelinesIt is fixed-function state, and transparent objects need their own sorted pass anyway.
Face culling, viewportdynamic stateSet in the command buffer; it splits runs but not pipelines.
Vertex formatvertex pullingThe format becomes shader code reading a buffer.
Which textures a material hasruntime branchesCheap, uniform per draw, and changes nothing else.
Shading modelmaterial type switchUniform per draw; one pipeline.
A rare, very heavy featurea variant or a specialization constantKeeps its registers out of every other material.
Debug views, quality levelsspecialization constants or variantsSet for the whole frame, not per draw.

10In RASM

RASM draws every scene object with one uber shader, shaders/passes/rasm.slang: one vertMain, one fragMain. Materials are rows in the material table, and fragMain branches on them at run time. Variants, each a #define, exist only for what changes the pipeline or the shader's outputs, never for a material feature: the alpha mode, which changes fixed state (blending, depth writes) and whether the shader may discard, so fragMain is compiled once per mode (transparency); alpha-to-coverage for cut-outs on a multisampled target (MSAA); a second output for motion vectors (TAA); and the debug views (debug views).

push constant 16 B: scene, firstDraw SceneData camera, lights, tables DrawInfo getDrawIndex() InstanceData row firstInstance MaterialData row materialIndex vertMain follows the first four; it passes materialIndex to fragMain (nointerpolation) materialId, factors, texture slots fragMain per pixel UNLIT PBR shadeUnlit base color factor × texture × vertex color; reads only the base color part of the row shadePBR fragMain first copies the whole material into a PBRInfo (P9) 5 runtime texture checks, hasTexture: base color, metallic-roughness, emissive, occlusion, normal (a missing one is INVALID_TEXTURE_INDEX) selectUV per texture, then one branch for the texture transforms backFace from isFrontFace and the mirroring sign
Every branch on the material is uniform per draw: one draw is one instance with one material. The light loops run the view's shadowed lights, the global lights and the lights of the pixel's cluster (clustered lighting), which differ between pixels.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Variants#defines, specialization constantsFor the alpha mode: fragMain plain, with RASM_ALPHA_MASK and with RASM_ALPHA_BLEND, which Renderer::createScenePipeline puts before the source. Then for the target and the view, not the material: RASM_ALPHA_TO_COVERAGE with RASM_ALPHA_MASK on a multisampled target, RASM_MOTION_VECTORS on a target with a MOTION_FORMAT color (getMotionDefine), and RASM_DEBUG_VIEW for a debug view, made the first time one is chosen. Everything else is a runtime branch. No specialization constants.
Texture transformsa branch, or a variantA runtime branch on MATERIAL_TEXTURE_TRANSFORM in the row's flags, one for all five textures. A branch per texture made the opaque draws of 05_city about 6% slower, though no material there has a transform: the transform code raised the register count of the whole shader.
Texture featuresruntime branchesRuntime. Each of the 5 textures is used only when its index is not INVALID_TEXTURE_INDEX (hasTexture). selectUV picks the UV set per texture at run time too.
Shading modelsa type switchSix: MaterialId PBR, UNLIT, TERRAIN, VECTOR, POINTS and GLYPHS, stored in MaterialData. POINTS draws in a pipeline of its own (Point clouds), and GLYPHS in rasm.slang compiled with RASM_GLYPHS, whose vertex stage places each glyph (Instanced glyphs). The vertex stage tests TERRAIN (it lifts the vertex by the tile's heights, Terrain from height maps) and VECTOR (it spreads the vertex by the style's width, Vector lines, polygons and points), uniform per draw. fragMain tests VECTOR and UNLIT, each with one if, and shades TERRAIN and GLYPHS as PBR. getGfxMaterialId maps the public MaterialType to it; glTF's KHR_materials_unlit gives UNLIT. The PBR model itself is in PBR shading.
Uniformityuniform per drawYes: instanceCount is always 1, so each draw has one material. The texture index is used without a non-uniform marker, which relies on this.
Double-sided, mirroredoften a variantNot variants. The cull mode is dynamic state, so double-sided and mirrored draws only change the run (see face culling). The shader works out the mirroring sign from the world matrix's determinant, per vertex.
Pipelinesas few as possibleOne graphics pipeline per alpha mode for the scene draws, each made only once a scene has such draws; the alpha mode is part of the run, so it costs a run, not a draw. A view's set of them (ShadedPipelines) depends on its target: one set per sample count, and one for a target with motion vectors, so views of each kind can share a frame. The debug views have sets of their own. The others are the depth-only pipelines of shadow maps, the sky, the tone map, the UI, the stats overlay, the compute pipelines of animation, culling, Hi-Z, the blend sort, the light clusters, the MSAA resolve, TAA and bloom, and any pipeline an application makes with Renderer::createPipeline.
Alpha modesa pipeline per blend modeYes: the opaque variant never discards and keeps the early depth test; the mask variant discards (compiled as a demote to a helper, so the texture samples after it keep their derivatives, B33); the blend variant has premultiplied blending and no depth write.
Shared shading codea functionThe variants share fragMain itself, not a function that takes the varyings: such a function made Slang read every varying up front, about 5% slower on the opaque draws of 05_city.
Registersread data when neededThe unlit path reads its part of the row through a pointer. The PBR path copies the whole material into PBRInfo first (P9), and reads each light through lightsPtr when it shades it.
Compile costcache pipelinesMade the first time a scene is drawn (Renderer::prepareSceneView), from shaders the shader workers compiled at startup (Shader warm-up). Each variant is compiled once and then read from the shader cache on later starts; the driver's compile goes through the pipeline cache. A failed compile is retried every frame, so a shader fixed on disk is picked up while the application runs.

How to add a shading path

  1. The public type. Add a value to MaterialType in include/rasm/material.h, before COUNT, and a case for it in the switch in Renderer::createMaterial (src/assets/material.cpp).
  2. The GPU id. Add the same value to gfx::MaterialId in src/renderer/uberMaterialTypes.h and to MaterialId in shaders/lib/core.slang, in the same order.
  3. The mapping. Return it from getGfxMaterialId in src/renderer/gpuScene.cpp.
  4. The shading. Write a shade function in a new file in shaders/lib/, include it in rasm.slang, and branch to it in fragMain before the PBR path, like the unlit path. Read only the fields you need through the MaterialData pointer.
  5. New material data. If the path needs any: new fields in Material on both sides, filled in convertToGfxMaterial. That is a CPU↔GPU struct change: follow the struct rules.
  6. Check. Run the examples with enableValidation on. A shader-only change needs no rebuild; the enum changes do.

Where it lives in code

WhatWhere
The uber shadervertMain, fragMain, VSOutput in shaders/passes/rasm.slang
Shading pathsshadePBR, PBRInfo in shaders/lib/pbr.slang; shadeUnlit in shaders/lib/unlit.slang
Shared helpershasTexture, selectUV, applyTextureTransform, getTextureUV, sampleBaseColor, getBaseAlpha, MaterialId in shaders/lib/core.slang
The material rowgfx::MaterialData, gfx::MaterialId in src/renderer/uberMaterialTypes.h; convertToGfxMaterial, toMaterialData, getGfxMaterialId, Renderer::writeMaterialRow in src/renderer/gpuScene.cpp
Making the pipelinesRenderer::createScenePipeline in src/renderer/renderer.cpp; called from Renderer::prepareSceneView, with getMotionDefine; the sets in ShadedPipelines (src/renderer/gpuScene.h)
Fixed and dynamic stateVulkanDevice::createGraphicsPipeline in src/rhi/vulkan/vulkanDevice.cpp
The public material typesMaterialType in include/rasm/material.h
Keep these true
  • Every scene draw goes through the pipeline of its alpha mode, from its view's set. A material feature is a field and a branch, not a new pipeline: a new pipeline would split every draw list.
  • A branch on a material flag that guards several reads goes around all of them at once, so the code it guards does not add registers in every place.
  • MaterialId has the same values in the same order in C++ and Slang.
  • The material branch must stay uniform per draw. If one draw ever covers several materials (real instancing), the texture indices need a non-uniform marker.
  • Shaders output linear color; the swapchain encodes it (see color spaces).
Not done yet
  • P9: the PBR path copies the material and all lights into registers up front.
  • D12: the shader uses pointers and spirv_asm, so it is Vulkan-only today.

Further reading