Drawing

Vertex pulling and mega-buffers

Normally the GPU's fixed-function hardware reads vertices from vertex buffers and hands them to the vertex shader. With vertex pulling, the vertex shader gets only a number, and reads the vertex from memory itself. Together with one big buffer for all meshes, a mega-buffer, this removes all per-mesh bindings, which GPU-driven rendering needs. This page explains both. The last part shows how RASM does it.

In short

  • The classic path: the pipeline describes the vertex layout, the CPU binds vertex buffers, and fixed-function hardware fetches and converts each vertex.
  • Vertex pulling: the pipeline has no vertex input. The shader gets the vertex index and reads a struct from a storage buffer.
  • The index buffer stays. It still decides which vertex each corner uses, and lets the GPU reuse shaded vertices.
  • A mega-buffer holds every mesh. A mesh is a range in it; a draw finds it with firstIndex and vertexOffset.
  • The shader decides the vertex format, so any packing or compression is possible, decoded in a few instructions.
  • Speed is about the same on most desktop GPUs. The real gain is flexibility, and no bindings between draws.

1How the GPU usually gets its vertices

A vertex is a small record: a position, a normal, texture coordinates, maybe more. A mesh stores its vertices in a vertex buffer. In the classic path, the application tells the pipeline what one vertex looks like, with a vertex input layout: how many bytes per vertex (the stride), and for each attribute, its format and its byte offset. Then, before each draw, it binds the vertex buffer.

Index buffer which vertex, per corner Vertex buffer bound by the CPU per mesh Vertex input layout part of the pipeline, fixed at creation Vertex fetch fixed-function hardware: reads and converts Vertex shader in float3 position in float3 normal in float2 uv one vertex in the buffer, as the layout describes it: position normal uv next … 0122432
The layout for this vertex: stride 32 bytes; position at offset 0 and normal at 12, three 32-bit floats each; uv at 24, two floats. The shader declares inputs. It never sees the buffer, the stride or the offsets. Hardware does the reading.

The fetch hardware also converts. An attribute stored as 4 bytes of 0 to 255 can arrive in the shader as a float4 from 0 to 1. The shader does not know how the data was stored.

What the classic path costs you

pipeline 1 shaders pipeline 2 the same

The layout is part of the pipeline

Meshes with different vertex formats need different pipelines, even with the same shaders. Each one splits a draw list (see runs).

bind A draw bind B draw … one indirect call cannot do this

Vertex buffers are bound per draw

Each mesh in its own buffer means a bind between draws. One indirect call over many meshes cannot do that.

formats the hardware converts 3 × f32 2 × f32 4 × u8 … octahedral normal

Only listed formats

The hardware converts a fixed set of formats. Custom packing, such as octahedral normals, needs shader code anyway.

the maximum attributes of one pipeline

Limits on attributes and bindings

A pipeline has a maximum number of attributes and buffer bindings.

2Vertex pulling: the shader reads its own vertex

The idea is simple. Give the pipeline an empty vertex input layout. The vertex shader still runs once per vertex, and it still gets one built-in input: the vertex index, the number of the vertex it must produce. It uses that number to read the vertex from a storage buffer, like any other array.

Index buffer which vertex, per corner vertex index Vertex shader v = vertices[index] a normal buffer read Storage buffer an array of vertex structs vertex input layout: empty fixed-function fetch: not used
The arrow points from the buffer into the shader: the shader pulls its data. In the classic path, the hardware pushes it in.

In Slang or HLSL, a minimal vertex shader looks like this:

struct Vertex
{
    float3 position;
    float3 normal;
    float2 uv;
};

StructuredBuffer<Vertex> vertices;

float4 vertexMain(uint vertexIndex : SV_VertexID) : SV_Position
{
    Vertex v = vertices[vertexIndex];
    return mul(viewProjection, float4(v.position, 1.0));
}

The struct is now a contract between the code that writes the buffer and the shader that reads it. Both sides must agree on every byte: see struct layout rules. The buffer can be a descriptor binding, as here, or a raw GPU address (see buffer device addresses).

3The index buffer still does its job

Vertex pulling replaces the reading of vertex data. It does not replace the index buffer. Indexed drawing works as before: the hardware reads one index per triangle corner, and that index becomes the vertex index the shader receives.

This matters for speed. A vertex is usually shared by several triangles. The GPU keeps the results of recent vertex shader runs in a small cache, keyed by the index. When the same index comes again soon, it reuses the result instead of running the shader again. With pulling, the cache still works, because the hardware still sees the index.

0 1 2 3 triangle A triangle B Index buffer 0 1 2 0 2 3 triangle A triangle B Orange: an index that comes twice. Its shaded vertex can be reused.
The reuse needs the index. That is why vertex pulling keeps indexed draws, and does not read the index buffer itself in the shader.
6corners in the two triangles
4different indices: the vertex shader runs 4 times instead of 6
≈ 6triangles share one vertex in a typical closed mesh

Which number the shader receives

Indexed draws add vertexOffset (also called base vertex) to every index value. Whether the vertex-index built-in includes it depends on the API, and on how the shading language maps its built-in. Check before you index a buffer with it:

API, built-inValue for an indexed draw
Vulkan, VertexIndexindex value + vertexOffset
Direct3D, SV_VertexIDindex value only: the base vertex is not added
A shading language that targets bothpicks one meaning, and may subtract the base vertex on Vulkan to match Direct3D

Non-indexed draws are simpler: the vertex index counts from firstVertex upward, one per vertex.

4One buffer for every mesh

Vertex pulling removes the vertex layout from the pipeline. The second half of the job is to remove the bind between draws. The usual answer is a mega-buffer: one big vertex buffer and one big index buffer for all meshes. Each mesh is a range in each of them. The buffers are bound once, and every draw finds its mesh with two numbers from its draw record.

Vertex buffer A0 … 23 B24 … 27 C28 … 1027 free Index buffer A0 … 35 B36 … 41 C42 … 4841 free Mesh table firstVertex vertexCount firstIndex indexCount A 0 24 0 36 B 24 4 36 6 Draw record for B indexCount 6, firstIndex 36 vertexOffset 24 (= firstVertex) B's indices are 0 … 3, local
The sizes are an example: A is a cube with one quad per face (24 vertices, 36 indices), B a single quad, C a larger mesh. The buffers are not to scale.

Local or global indices

Mesh B's indices can be stored in two ways. Local is the usual choice.

012023 + offset 24 242526242627 vertices read

Local indices + vertexOffset

Stored as the mesh was made, 0 to 3, and the draw adds vertexOffset = 24.

  • Moving a mesh in the buffer: change one number in the table.
  • Index size: a mesh under 65,536 vertices can use 16-bit indices, wherever it sits in the buffer.
  • Uploading: copy the mesh's indices as they are.
242526242627 + offset 0 242526242627 vertices read

Global indices

Already moved, 24 to 27, with vertexOffset = 0.

  • Moving a mesh in the buffer: rewrite every index.
  • Index size: 32-bit as soon as the buffer passes 65,536 vertices.
  • Uploading: add the offset to each index first.

Sharing out the space

A mega-buffer is created once, with a fixed size. Giving a mesh a range of it is sub-allocation, the same problem as a memory allocator:

ABC the next mesh goes here

Bump (linear)

Each mesh goes right after the last one. Nothing is freed.

Good for: content loaded once: a level, a model viewer.
Problem: the buffer only fills up.

new mesh every hole is too small for it

Free list

Freed ranges go into a list; a new mesh takes the first range that fits.

Good for: meshes that come and go.
Problem: holes: the free space splits into pieces too small to use (fragmentation).

1/21/41/81/8 size classes grey: lost to rounding, or free

Buddy or TLSF allocators

Ranges in size classes, merged with their neighbours when freed.

Good for: streaming worlds, map tiles.
Problem: more code. Some space is lost to rounding.

before move on the GPU after

Defragment

Move live meshes together on the GPU, then fix their table rows.

Good for: long sessions.
Problem: every draw record and table row that names a moved range must change in the same frame.

Freeing a range is also a timing problem: the GPU may still be drawing from it in a frame that is in flight. See frames in flight.

5Worked example: one vertex of mesh B

Use the buffers from the picture above, with vertices of 64 bytes. The GPU is drawing mesh B, and it reaches the 6th corner (corner 5).

1. The index

corner 5 of the draw B's 2nd triangle, 3rd corner index buffer[36 + 5] = index buffer[41] value 3 a local index of B B's indices are 0 1 2 0 2 3, stored at 36 … 41. The hardware reads them in order: firstIndex + corner.

The hardware reads the index. The shader is not involved yet.

2. The vertex index

index 3 from the index buffer + vertexOffset 24 from the draw record vertex 27 its place in the vertex buffer On Vulkan the built-in already holds 27. If the language gives the raw index (3), the shader adds the offset itself.

The local index becomes a place in the shared buffer.

3. The address

address = buffer start + 27 × 64 = buffer start + 1728 vertex 25 vertex 26 vertex 27 vertex 28 (C) 1728 1792 Vertex 27 is B's last vertex. Vertex 28 is already mesh C: a wrong offset reads another mesh, with no error.

An array read: element 27 of an array of 64-byte structs.

4. The shader has its vertex

position1728 normal1740 uv, …1752 vertex shader transform, output Index 3 appears once in B's indices, so this vertex is shaded once. Indices 0 and 2 appear twice: their results can be reused.

From here on, the shader is an ordinary vertex shader.

Try it. The picture below shows the part of both buffers around mesh B, and does steps 1 to 3 for the corner you pick.

mesh B's range other meshes the picked index, and the vertices the draw reads reads a vertex of B reads another mesh
Click one of B's six indices to pick a corner of the draw. Then move vertexOffset away from 24: the same indices now read vertices of mesh A or mesh C, and the draw still runs.

6One interleaved struct, or separate streams

With pulling, the shader decides how vertices are laid out in memory. There are two basic choices:

Interleaved (array of structs) pos 0 nrm 0 uv 0 pos 1 nrm 1 uv 1 … One read brings all of a vertex. A pass that needs only positions still loads the rest. Separate streams (struct of arrays) pos 0 pos 1 pos 2 … nrm 0 nrm 1 nrm 2 … uv 0 uv 1 uv 2 … A depth-only or shadow pass reads only the position stream: less memory traffic. A full pass reads 3 places per vertex. Each stream can have its own format.
Many engines use a mix: positions in one stream, everything else interleaved in a second one.

7Smaller vertices

Vertex data is read for every vertex of every draw. Smaller vertices mean less memory, and less memory traffic each frame. With pulling, the shader can decode any packing it likes, so engines often store far less than full 32-bit floats:

AttributeFullPackedHow it is decoded
Position3 × float32 = 12 B3 × 16-bit + 2 B padding = 8 BQuantized inside the mesh's bounding box: p = min + q / 65535 × (max − min). The box is stored once per mesh.
Normal3 × float32 = 12 B2 × 16-bit = 4 BOctahedral encoding: the unit sphere is folded onto a square, so 2 numbers are enough.
Tangent + sign4 × float32 = 16 B2 × 8-bit + sign, 4 BOctahedral too, with the bitangent sign in a spare byte.
Texture coordinate2 × float32 = 8 B2 × 16-bit = 4 BUnsigned normalized 16-bit for UVs in 0 to 1; half floats for UVs that repeat.
a direction: 3 numbers project octahedron, top view fold the lower half out a square: 2 numbers upper half: the diamond lower half: the 4 corners
Octahedral normals spread the error evenly over all directions. 2 × 16 bits give an angle error far below what lighting can show.

Example: 64 bytes down to 20

Full floats · 64 B position 12 normal 12 3 UV sets 24 tangent 16 Packed · 20 B position 8 n 4 uv 4 t 4 packed as in the table above, with one UV set
Scale: 10 px per byte. n is the normal, t the tangent with its sign.
64 B → 20 Bone vertex12 + 12 + 24 + 16 → 8 + 4 + 4 + 4
61.0 → 19.1 MiB1,000,000 vertices64,000,000 B → 20,000,000 B
≈ 0.15 mmposition step, mesh 10 m wide. Full float32: far below 0.01 mm.10 m / 65,535
A trap: half-float UVs

A 16-bit half float has 10 bits of fraction. Between 0.5 and 1.0, its step is 2−11 ≈ 0.00049. On a 4096-texel texture, that is 4096 × 0.00049 = 2 texels: visible as wobbly, swimming textures. Unsigned normalized 16-bit has the same step everywhere, 1 / 65,535, which is 0.06 texels on the same texture.

8Performance notes

16161616 a multiple of 16 bytes: wide loads 444 a float3 at an odd offset: small loads

Alignment

A struct whose size is a multiple of 16 bytes lets the compiler use wide 16-byte loads. A 12-byte float3 at an odd offset may turn into several small loads.

a 64-byte line 64 B vertex 202020 a third each

Cache lines

Memory moves in lines of 64 or 128 bytes. A 64-byte vertex that starts on a line boundary costs one line; a 20-byte vertex costs a third of one.

012023234 green: the vertex cache hits shared vertices come close together

Index order

Reorder the triangles so that shared vertices come close together. The vertex cache then hits more often (Forsyth's algorithm, meshoptimizer).

in the order of first use: forward any order: the reads jump

Vertex order

Reorder the vertices into the order the indices first use them. Reads then walk the buffer forward, line by line.

Fetch hardware vs shader loads

On many desktop GPUs, vertex fetch already runs as ordinary shader loads, so pulling costs about the same. Some GPUs, often mobile ones, still have fast fixed-function fetch. Measure before you depend on either.

Robustness

A wrong vertex index in a pulled read is just a read of the wrong memory: another mesh, or past the end of the buffer. Debug builds can check the index against the mesh's range.

9In RASM

RASM uses vertex pulling for every graphics pipeline: no pipeline has a vertex input layout. All meshes live in one geometry pool: one vertex buffer, one index buffer, one color buffer for the meshes with vertex colors, one skin buffer for the skinned meshes' joints and weights, one morph buffer for the morph targets' deltas, and one table of sub-mesh rows, created at startup and sized by EngineConfig.

GeometryPool, created once Geometry Vertex Pool Vertex = VertexFull, 64 B · STORAGE · read by pointer geometryPoolVertices = 2²¹ vertices = 128 MiB Geometry Index Pool uint32 · INDEX · bound once per scene pass geometryPoolIndices = 2²⁴ indices = 64 MiB Geometry Color Pool uint32 RGBA8 per vertex, only for meshes with colors geometryPoolColors = 2²⁰ colors = 4 MiB Geometry Skin Pool SkinVertex, 16 B, only for skinned meshes · Skin pass geometryPoolSkins = 2²⁰ = 16 MiB Geometry Morph Pool MorphDelta, 24 B per vertex and target · Skin pass geometryPoolMorphs = 2²⁰ = 24 MiB Geometry Table GeometryData, 200 B per sub-mesh · read by pointer geometryPoolSubMeshes = 2¹⁴ rows · meshlets: a pool of their own One sub-mesh in the pool vertices [firstVertex, + vertexCount) LOD 0 indices LOD 1 2 … All LODs index the same vertices. its colors, or none joints, weights, or none target 0 target 1 …, or none each target: one delta per vertex vertexOffset = firstVertex, the same for every LOD boundsCenter, boundsRadius, lodCount, lods[8] colorOffset = firstColor, or -1 without colors skinOffset = firstSkin, or -1 when not skinned morphOffset = firstMorph, or -1; morphTargetCount vertMain: getVertex = vertsPtr[input.vertexID + draw->vertexOffset] skinned or morphed: skinnedVertsPtr[skinnedVertex + input.vertexID], from Skin color: colorsPtr[colorOffset + input.vertexID], or white for -1 SV_VertexID is the raw index value here, so the shader adds the draw's offsets back
Sizes are the EngineConfig defaults. The pool never frees anything: each upload appends after the last one.

One cache line per vertex, and optional streams

The vertex is exactly 64 bytes: one cache line. A vertex that starts on a line ends on it. Adding one more attribute to every vertex, even 4 bytes, would make every vertex span two lines (a 68-byte vertex always holds a line boundary), and every mesh would pay for it, though most glTF files have no vertex colors. So an attribute that only some meshes have is a stream of its own (section 6), and the sub-mesh's row says where its part starts.

68 B68 B68 B cache lines of 64 B color in every vertex: each crosses a line

Color in the vertex

4 more bytes for every vertex of every mesh, and two cache lines for every vertex.

64 B64 B64 B 4 B colors, only where a mesh has them one line per vertex; a mesh without colors pays 0

A color stream

The vertex stays one line. The shader reads a color only when the row's colorOffset is not -1, a branch that is the same for the whole draw.

A color is packed by packVertexColor: R in the low byte, RGB sRGB-encoded so 8 bits keep the dark shades, alpha linear. getVertexColor decodes it to linear in vertMain, before interpolation. The application gives colors to createMesh(vertices, indices, colors); glTF import reads COLOR_0. A skinned glTF mesh's JOINTS_0 / WEIGHTS_0 are a second stream of the same kind: a SkinVertex of 16 bytes (4 joints as 16-bit integers, 4 weights as UNORM16 that add up to 65535), at the row's skinOffset. Only the Skin pass reads it; the views read the posed vertices it writes (skinning). Morph targets are a third stream: a MorphDelta of 24 bytes per vertex and target (the position as floats, the normal and tangent as half floats), at the row's morphOffset, with morphTargetCount targets one after another. The Skin pass reads it too (morph targets).

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Vertex input layoutemptyEmpty for every graphics pipeline (VulkanDevice::createGraphicsPipeline). Core Vulkan, so it also runs where dynamic vertex input is missing, such as MoltenVK.
How the shader reaches the buffera descriptor or an addressA raw address: SceneData::vertsPtr, a VertexFull pointer. No descriptor. See buffer device addresses.
The vertex indexdepends on the API and languageSlang lowers SV_VertexID to VertexIndex − BaseVertex, as in Direct3D. So vertMain gets the local index and adds draw->vertexOffset itself. The hardware adds the offset, Slang removes it, the shader adds it back.
Index bufferkeptKept. One index buffer for all meshes, bound once per scene pass (Renderer::drawSceneView) with bindIndexBuffer, format U32_UINT. The UI pass pulls too, from buffers of its own: Dear ImGui's 20-byte vertices through UiPushConstants::vertices, with U16_UINT indices (shaders/passes/ui.slang).
Indiceslocal + vertexOffsetLocal to the sub-mesh. vertexOffset = firstVertex, set in rebuildDrawList. Always 32-bit, even for small meshes.
Sub-allocationbump, free list, buddy…A free list per stream: GeometryPool::allocate takes the first free range that fits (RangeAllocator), destroyMesh gives the ranges back after the frames in flight (deferred destruction). A mesh that does not fit is not uploaded, and the error names the largest free ranges.
Layoutinterleaved or streamsOne interleaved 64-byte struct: pos, normal, uv[3], tangent. The same bytes as the public Vertex, checked by static_asserts. Vertex colors, skin joints and weights, and morph target deltas are optional streams next to it (above). VertexPosOnly is declared but not used: there is no position-only stream.
Compression16-bit, octahedral…None on the GPU. Full 32-bit floats, and all 3 UV sets are always stored (unused ones are zero). A quantized glTF (KHR_mesh_quantization: positions, normals, tangents and UVs in 8- or 16-bit integers) is decoded to floats on import; the node transform and the texture transform undo the quantization's scale, as the extension intends.
Index and vertex orderoptimize bothOnly the coarser LODs go through meshopt_optimizeVertexCache. LOD 0 keeps the order of the import. No vertex fetch reordering.
LODs—All LODs of a sub-mesh share its vertices and cost only their indices, placed right after LOD 0's. Culling writes the chosen LOD's range into the draw. See mesh simplification and LOD selection.
Upload—Once, when the mesh finishes loading, with fillBuffer at the range's offset. The CPU copy is dropped afterwards (P6). See GPU memory and uploads.

Where it lives in code

WhatWhere
The pool and its buffersGeometryPool::create, GeometryPool::upload, GeometryPool::fits in src/renderer/geometryPool.cpp
Pool sizesgeometryPoolVertices, geometryPoolIndices, geometryPoolColors, geometryPoolSkins, geometryPoolMorphs, geometryPoolSubMeshes in EngineConfig, include/rasm/types.h
Skin joints and weightsSkinVertex in include/rasm/mesh.h; readSkinVertices in src/assets/skinImport.cpp; read by skinMain in shaders/passes/skin.slang
Morph target deltasMorphDelta in include/rasm/mesh.h; readMorphTargets, packMorphDelta in src/assets/morphImport.cpp; read by skinMain
Vertex colorspackVertexColor in src/assets/mesh.cpp; ObjRaw::colors; getVertexColor in shaders/lib/core.slang
The vertex structVertex in include/rasm/mesh.h; gfx::VertexFull in src/renderer/uberMaterialTypes.h; VertexFull in shaders/lib/geometryTypes.slang
A sub-mesh's rangesMeshGeometry in include/rasm/mesh.h; GeometryData, GeometryLod in shaders/lib/geometryTypes.slang
The empty vertex inputVulkanDevice::createGraphicsPipeline in src/rhi/vulkan/vulkanDevice.cpp
The pullvertMain in shaders/passes/rasm.slang, through getVertex in shaders/lib/core.slang
Binding the index buffer, setting vertsPtrRenderer::drawSceneView, Renderer::prepareSceneView in src/renderer/gpuScene.cpp
LOD indicesbuildMeshLods in src/assets/meshLod.cpp
Keep these true
  • Vertex, gfx::VertexFull and the Slang VertexFull have the same 64 bytes. A change to one changes all three and the static_asserts (see struct layout).
  • vertMain adds draw->vertexOffset to SV_VertexID. Removing it makes every mesh read the first mesh's vertices.
  • Every vertex shader of a scene draw reads through getVertex, so a skinned or morphed sub-mesh is drawn posed in every view.
  • Indices are local to their sub-mesh. Every LOD of a sub-mesh uses the same vertexOffset, and its colors are indexed by the same local index.
  • Keep the vertex at 64 bytes. An attribute that not every mesh has is a stream with an offset in GeometryData, not a field in Vertex.
  • The index buffer is bound as U32_UINT. 16-bit indices would need a second index buffer and their own draws.
Not done yet
  • A pool fragments, and nothing moves live ranges to close the holes.
  • No vertex compression and no position-only stream.

Further reading