GPU data

Mesh simplification

A far object covers a few pixels, but its mesh still has all the triangles it has up close. Mesh simplification makes coarser copies of a mesh, its levels of detail (LODs), that look almost the same from far away. This page explains the classic algorithm: edge collapse driven by quadric error metrics. The last part shows how RASM does it. Choosing a level each frame is a separate topic: see LOD selection.

In short

  • An edge collapse merges the two ends of an edge into one vertex. The two triangles on that edge disappear.
  • A quadric is a 4×4 matrix per vertex. It gives the sum of squared distances from any point to the planes of the triangles around that vertex.
  • The algorithm collapses the cheapest edge first, adds the quadrics of the two ends, and repeats until a target count or an error limit.
  • The cost is a distance: how far the surface moved, in the mesh's own units. That is what makes it usable for choosing a level later.
  • Borders and UV seams need extra care, or holes grow and textures tear.
  • If every collapse keeps one of the two old vertices, all levels can share one vertex buffer. Then a level costs only its indices.

1Why fewer triangles

LOD 0 24 triangles · up close LOD 1 12 triangles LOD 2 6 triangles LOD 3 3 triangles · far away further from the camera →
A LOD chain: each level has about half the triangles of the one before. A level is used when the object is so small on screen that the missing detail is smaller than a pixel.

Drawing a far object with all its triangles wastes work in three places:

one pixel, many vertices

Vertex work

Every vertex is fetched and shaded, even when 50 vertices land in one pixel.

1 pixel covered, 4 shaded

Pixel work

GPUs shade pixels in 2 × 2 blocks (quads). A triangle that covers one pixel still runs the pixel shader up to 4 times. Many tiny triangles can cost several times the pixels they cover.

frame 1 frame 2 the detail jumps: flicker

Aliasing

Detail smaller than a pixel flickers as the camera moves. A coarser mesh can even look better.

The LODs are built once, offline or when the mesh loads. Each frame, the renderer only picks one per object (see LOD selection).

2Ways to simplify

Vertex clustering

Lay a grid over the mesh. All vertices in one cell become one vertex. Triangles that end up with two corners in one cell vanish.

Good: very fast, one pass. Reaches any target.

Bad: ignores the shape: merges things that are only close, closes holes, makes ugly results. See section 9.

Vertex removal

Remove one vertex and its triangles, then fill the hole with new triangles.

Good: keeps the original vertices.

Bad: filling a hole in 3D well is hard.

Edge collapse

Merge the two ends of one edge. Repeat, cheapest first.

Good: local, simple, high quality. Keeps the topology when checked.

Bad: slower than clustering. Needs a good cost: that is the quadric.

Edge collapse with quadric error metrics, published by Michael Garland and Paul Heckbert in 1997, is the standard. The rest of this page explains it.

3Edge collapse

Before: 10 triangles u v the edge u–v and its two triangles (orange) collapse v onto u After: 8 triangles v was here u v's triangles now use u: they stretch
One collapse removes one vertex and two triangles (one, if the edge is on a border). Halving a mesh of N triangles takes about N / 4 collapses.

Where does the merged vertex go? There are two choices:

uv a new vertex

Full collapse

Both ends move to a new point, chosen to fit the old surface best (section 5 shows how to compute it). Best quality. But the result has new vertices, so each level needs its own vertex data.

uv stays: an original vertex

Half-edge collapse

One end moves onto the other end, which stays where it is. A little lower quality. But every vertex of every level is one of the original vertices, so all levels can share one vertex buffer (section 10).

Collapses that must be refused

Some collapses break the mesh. Before each one, the algorithm checks:

turned over

Flip

Does any triangle around the moved vertex turn over (its normal points the other way)?

Without it: a fold in the surface: a dark crease or a hole in the silhouette.

glued at one point

Link condition

Do u and v share neighbours other than the two triangles on their edge?

Without it: two surfaces get glued at one point; the mesh is no longer a clean surface (non-manifold).

the border moved

Border and seam rules

Borders and UV seams have their own rules (section 7).

Without them: holes grow, cracks open, textures tear.

4The cost: how far would the surface move?

We need a number for each possible collapse: how much it changes the shape. Measuring the true distance between the old and the new surface is slow. The quadric trick estimates it with a few multiplications.

Start from one triangle. Its plane is 4 numbers p = (a, b, c, d), with a unit normal (a, b, c). Write a point as v = (x, y, z, 1). The distance from the point to the plane is p · v. Its square can be written as a matrix product:

distance²(v) = (p · v)²
             = vᵀ (p pᵀ) v
             = vᵀ K v          K = p pᵀ, a symmetric 4×4 matrix

Now the trick. Each vertex gets the sum of the K of the triangles around it:

Q(vertex) = K1 + K2 + … + Kn      one K per triangle that uses the vertex
cost(v)   = vᵀ Q v                sum of squared distances to them

Q is still one 4×4 symmetric matrix: 10 numbers, no matter how many planes it sums. At the vertex's own position the cost is 0, because the vertex lies on all its planes. Moving it away costs more in some directions than others:

On a flat floor y = 2 y = 1 slide along it: cost 0 cost = y² dashed: points of equal cost At a corner floor wall every move here costs cost = x² + y² along the crease (into the page): free p = (a, b, c, d) K = p pᵀ Q = K1 + K2 + … + Kn cost(v) = vᵀ Q v floor p = (0, 1, 0, 0) → y² wall p = (1, 0, 0, 0) → x² corner: both → x² + y²
The quadric "knows" the local shape. Flat areas and straight creases can be simplified for free; corners and curved parts resist. This is exactly what we want: detail is removed where it is not visible first.

The cost of one collapse

To collapse the edge (u, v), add the two quadrics and evaluate them at the place where the merged vertex will be:

Q      = Q(u) + Q(v)
cost   = targetᵀ Q target
target = u for a half-edge collapse, the best new point for a full one

After the collapse, the merged vertex keeps Q = Q(u) + Q(v). So a vertex's quadric always holds the planes of all the original triangles it replaced. Later costs are measured against the original surface, not against the last simplified one. That is why errors do not quietly add up step after step.

Corner vertex at (0, 0, 0), Q = floor + wallMove it toCost x² + y²As a distance (√cost)
a neighbour along the crease(0, 0, 1)00: free
a neighbour on the floor(1, 0, 0)11: the wall moves by 1
a neighbour on the wall(0, 1, 0)11: the floor moves by 1
somewhere in between(0.3, 0.1, 2)0.09 + 0.01 = 0.10.32

5The algorithm

  1. Quadrics. For every triangle, compute its plane and K. Add K to the quadric of each of its 3 vertices. Many implementations weight K by the triangle's area, so big triangles count more.
  2. Costs. For every edge, compute the cost of collapsing it. Put the edges in a priority queue (a min-heap), cheapest first.
  3. Collapse. Take the cheapest edge. If a check from section 3 refuses it, skip it. Otherwise collapse it and add the two quadrics.
  4. Update. The edges around the merged vertex changed: compute their costs again and fix their place in the queue.
  5. Stop when the triangle count reaches the target, or the next cost is above an error limit, or the queue is empty.

The same idea works in 2D, on a line instead of a surface. There, each point's "planes" are the lines of its two segments. Click through a simplification of 7 points down to 4. The numbers are the cost of each point's cheapest collapse, as a distance (the drawing is 6 units wide).

1. Every point gets a quadric and a cost

P0 · locked P10.10 P20.49 P30.49 P40.46 P50.25 P6 · locked 7 points, target 4

P1 sits almost on the straight line from P0 to P2, so it can go for 0.10. P3 and P4 are the top of the hill: removing either changes the shape a lot.

2. Collapse the cheapest: P1 onto P2

P0 P1 P20.91 (was 0.49) P30.49 P40.46 P50.25 P6 6 points · removed so far: 0.10

P2 now holds the quadric of P1 too, so it "remembers" the original line through P1. Its cost went up: moving it now would also move the part of the line that P1 used to hold.

3. Next: P5 onto P4

P0 P20.91 P30.55 P41.12 P5 P6 5 points · removed so far: 0.10, 0.25

Only the neighbours of the merged point get new costs. Everything else stays in the queue as it was.

4. P3 onto P4, then stop

P0 P2 P4 P6 4 points: the target · collapses 0.10, 0.25, 0.55 error of this level: 0.55

The level's error is the cost of its largest collapse, 0.55. Because the quadrics remember the original line, this number already compares the result with the original, not with the last step.

The best new position

For a full collapse, the best target is where vT Q v is smallest. Split Q into its top-left 3×3 part A, the first three numbers of its last column b, and its bottom-right number c. The cost is xTAx + 2 bTx + c, and its minimum is where A x = −b. That is one 3×3 linear system. When A cannot be inverted, for example on a flat area where every point of the plane costs 0, fall back to the cheapest of the two ends or the midpoint.

6The error, in object units

e original surface simplified surface e: the largest distance between them, in the mesh's units LOD 0 e1 LOD 1 e2 LOD 2 LOD 2 is at most e1 + e2 from LOD 0
The error tells how far a level's surface may be from the original. Seen from far enough, a distance of e is under one pixel. That is how LOD selection picks a level. When each level is made from the one before, its error against LOD 0 is not measured. The sum is a safe upper bound (the triangle inequality).
ChoiceOptionsNote
Absolute or relativeIn the mesh's units (meters, if the mesh is in meters), or divided by the mesh's size (0.01 = 1% of its size)Choosing a level on screen needs absolute units. Relative is handy as a quality setting: "at most 1% deformation".
Each level fromthe original (LOD 0), or the level beforeFrom the original: exact error, more work for coarse levels. From the level before: faster, and the errors add up (e.g. steps of 0.004, 0.006 and 0.011 give levels with 0.004, 0.010 and 0.021).
What the error coversposition only, or also normals and UVsPosition only can hide a big change in shading. See the next section.

A quadric gives the sum of squared distances to many planes, so its square root is an estimate, not an exact distance. In practice it is close to the largest deviation, and it is the number simplifiers usually report.

Try it on a closed outline, 5 units wide. The picture below runs the algorithm of section 5 in 2D, with the same quadrics and half-edge collapses as the 7-point example, and measures the real gap beside the error it reports.

Lower the number of points slowly and watch which ones go first. Find the last count where the spike and the round end are still there. Then switch the order to "every second point" and compare the gap at the same count.

7Borders, seams and attributes

Open borders

A border edge has a triangle on one side only: the edge of a sheet, or the rim of a hole. Here the quadric fails. On a flat sheet, every point of the plane costs 0, so a border vertex can slide into the sheet for free. The border is eaten away.

Plain quadrics: the edge is eaten B was here I cost of B → I: 0 (the sheet is flat) a notch is cut into the border Border planes, or a lock border plane B along the edge: cheap I B → I: costly a plane at right angles to the sheet, along each border edge (seen from above, it is the edge line itself)
Garland and Heckbert's fix: for each border edge, add the quadric of a plane through the edge, at right angles to its triangle, with a large weight. A simpler fix is to lock border vertices: they never move.

Locking matters when one object is split into several meshes that meet along a border, for example a model split into parts by material. If each part is simplified and chosen on its own, an unlocked border can move differently in each part, and a crack opens between them. Locked borders always match, at any mix of levels. The cost: the border keeps all its vertices, so a part with a long border cannot get very coarse.

UV seams and attributes

A vertex is more than a position: it has a normal and UVs. Where a texture is cut open (a UV seam), or a hard edge has two normals, the same position is stored as two vertices with different attributes.

A seam: one position, two vertices UV island 1 UV island 2 u = 1.0 on the left copy, u = 0.0 on the right copy Only one copy moved: a tear moved the two sides differ: a crack, or a jump in the texture
The rule: a seam vertex may only collapse along the seam, and both copies must collapse the same way.
ApproachHowResult
Position-only quadrics, seam rulesFind vertices with equal positions. Treat their edges like borders: they only collapse along the seam, together.No tears. But a collapse inside one island can still bend its normals or stretch its texture.
Attribute quadricsExtend the quadric with the attributes (Garland and Heckbert 1998, Hoppe 1999): the cost also counts how far the normal and UV would change.Better shading and texture. Bigger quadrics, slower, and the weights between position and attributes need tuning.

8Targets and when to stop

A simplifier gets a target: an index count (3 per triangle), an error limit, or both. It stops at whichever comes first. It can also stop early, above the target: when every remaining collapse is refused (locked vertices, seams, the link condition), there is nothing left to do.

RuleTypical choiceWhy
Each level's targethalf the triangles of the level beforeAn object twice as far covers a quarter of the pixels; halving per level gives many levels for little memory.
Minimum sizeno levels for small meshes; stop below a few dozen trianglesA level of a 200-triangle mesh saves almost nothing.
Stallingstop when a step removes less than, say, 10%The simplifier is stuck on constraints; another level would be a near copy.
Maximum levelsa fixed number, e.g. 8Fits a fixed-size table on the GPU.

With halving, the extra indices form a geometric series: ½ + ¼ + ⅛ + … < 1. All the coarser levels together cost less than LOD 0's indices.

LOD 0 all the indices of the full mesh: 1 coarser LOD 1 · ½ LOD 2 · ¼ ⅛ never reached
Every level adds half of what is left. The row of coarser levels never gets as long as LOD 0.

9Sloppy versus topology-preserving

Two parts, a narrow gap dashed: the clustering grid Sloppy (clustering) one blob: the gap is gone reaches any target, very fast changes the topology Topology-preserving the gap and holes stay may stop above the target
"Sloppy" simplifiers (vertex clustering and its variants) ignore which triangles are connected. They are good for the last, coarsest levels, where only the rough outline matters, and as a fallback when topology-preserving simplification gets stuck.
Topology-preserving (edge collapse)Sloppy (clustering)
Speeda priority queue, many updatesone or a few passes
Reaches the targetnot always: stops on constraintsalways
Holes, gaps, separate partskeptmay close or fuse
Many tiny separate parts (leaves, rivets)stuck: each part can only shrink to its smallest shapeparts merge or vanish: good for far levels
Use fornear and middle levelsfar levels, fallback

10Sharing vertices between levels, and the memory cost

With half-edge collapses, every vertex a level uses is an original vertex. So a level is only a new index list into the same vertex buffer.

LOD 0 indices uses every vertex vertices stored once LOD 2 indices 5 vertices, spread out
The coarse level reads few vertices, but they are far apart in memory, so the GPU fetches more cache lines per vertex. Some engines reorder the vertices so coarse levels use the front of the buffer (each level is a prefix), which fixes this.

Worked example: the memory cost

A mesh with 100,000 triangles and 50,000 vertices of 64 bytes, with 32-bit indices. Seven coarser levels, each half the one before:

3.20 MBvertices50,000 × 64 B
1.20 MBLOD 0 indices100,000 × 3 × 4 B
1.19 MBLOD 1 to 7 indices: +27% on the whole mesh99,219 triangles × 12 B
+3.18 MBmore, if each level had its own vertices too: +99% in totalabout 49,600 more × 64 B

Sharing the vertex buffer makes the whole chain cost about a quarter of the mesh instead of doubling it. The price is the quality of half-edge collapses, and the scattered fetches of coarse levels.

After simplifying

Each level's triangles come out in the order the collapses left them. Reorder them for the GPU's vertex cache (so a vertex shared by neighbouring triangles is shaded once), like any other index buffer.

11In RASM

RASM builds LODs for every sub-mesh as it loads, with the meshoptimizer library: buildMeshLods calls meshopt_simplify, which is the quadric edge collapse from this page, with half-edge collapses onto existing vertices.

each step: meshopt_simplify to half of the one before ObjRaw from the importer weldVertices identical ones → one LOD 0 N triangles LOD 1 ≈ N/2 · e1 LOD 2 ≈ N/4 · e1 + e2 … No LODs when the sub-mesh has under 1024 triangles (MIN_LOD_TRIANGLES), or EngineConfig::meshLods is false The chain stops at 8 levels, LOD 0 included (MAX_MESH_LODS), a next target under 64 triangles, or a step that removes under a tenth of the triangles The error adds up the steps' errors, in the mesh's own units, so it never gets smaller Every level is an index list into the same welded vertices (ObjRaw::lods, from fine to coarse).
The OBJ importer gives every face corner its own vertex, and simplification only collapses edges between triangles that share vertices. So weldVertices merges identical vertices first (same position, normal, UVs and tangent, and the same color, the same joints and weights and the same morph target deltas when the mesh has them), with meshopt_generateVertexRemapMulti. It compares at most 16 streams, one per morph target among them, so a mesh with more than 13 morph targets is not welded and gets no levels. A skinned or morphed mesh is simplified in its base shape, and the weights and the deltas do not steer the collapses (D29).

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Algorithmquadric edge collapseThe same, through meshopt_simplify (meshoptimizer, from vcpkg).
Collapse typefull or half-edgeHalf-edge: every level indexes the original vertices. No new positions.
What the cost coversposition, or also attributesPosition only. Seams survive through meshoptimizer's seam rules (vertices with equal positions), but normals and UVs inside an island are not in the cost.
Bordersborder planes, or a lockLocked (meshopt_SimplifyLockBorder). Sub-meshes of one model meet along their borders and pick their levels on their own, so the seam must not crack. tests/meshLodTests.cpp checks that every level keeps every border vertex.
Each level fromthe original, or the level beforeThe level before. A level's error is the sum of its steps' errors: a safe bound against LOD 0, never smaller than the level before's.
Error unitsabsolute or relativeAbsolute, in the mesh's own units (meshopt_SimplifyErrorAbsolute). Stored per level in MeshLod, then GeometryLod; LOD 0 has 0.
Targetshalf per level; stop rulesHalf per level, with no error limit. No levels under 1024 triangles (MIN_LOD_TRIANGLES). Stops at MAX_MESH_LODS = 8 levels with LOD 0, when the next target is under 64 triangles (MIN_LAST_LOD_TRIANGLES), or when a step keeps over 90% of the triangles.
Sloppyfor far levels and as a fallbackNot used. A mesh made of many small separate parts stalls early and gets few levels.
Sharing verticesone vertex buffer, an index list per levelYes. GeometryPool::upload writes the vertices once, then LOD 0's indices followed by each coarser level's. All levels share the sub-mesh's vertexOffset. A level costs only its indices (lodIndexCount, counted by getMeshByteSize).
Vertex order for coarse levelsreorder so each level is a prefixNot done: coarse levels fetch scattered vertices. Each coarser level's triangles are reordered with meshopt_optimizeVertexCache. Then every level of a sub-mesh of 1024 triangles or more (not skinned or morphed) is cut into meshlets, and its indices are written again in meshlet order: the same triangles, in small compact groups.
Speed—meshopt_SimplifySparse: a coarse level only uses a few of the vertices, so the work follows its indices, not the vertex count.
Whenoffline or at loadAt load. loadMesh runs it on the worker (see Streaming assets); createMesh runs it on the main thread. EngineConfig::meshLods (on by default) turns it off.

Where the levels are stored

indices in the pool LOD 0 all N triangles · error 0 LOD 1 ≈ N / 2 LOD 2 ≈ N / 4 3 one after another, from firstIndex vertices in the pool the sub-mesh's vertices, once every level points into them GeometryData row vertexOffset, bounds lodCount = 4 lods[i]: firstIndex, indexCount, error The row has room for MAX_MESH_LODS levels; lodCount says how many are real.
GeometryPool::upload writes this layout and one GeometryData row per sub-mesh. The cull shader reads the row to pick a level and swaps the draw's index range: see LOD selection.

Where it lives in code

WhatWhere
Building the chainbuildMeshLods, weldVertices, MIN_LOD_TRIANGLES, MIN_LAST_LOD_TRIANGLES in src/assets/meshLod.cpp
Where it is calledAssetLoader::loadMesh (worker) and Renderer::createMesh in src/assets/mesh.cpp
CPU resultMeshLod, ObjRaw, MAX_MESH_LODS in include/rasm/mesh.h
The switchEngineConfig::meshLods in include/rasm/types.h
Pool layout and table rowGeometryPool::upload in src/renderer/geometryPool.cpp
GPU structGeometryLod, GeometryData in shaders/lib/core.slang and src/renderer/uberMaterialTypes.h
Tests (no GPU)tests/meshLodTests.cpp: a chain that shares welded vertices with growing errors, locked borders, no levels for a small mesh
Keep these true
  • Every level indexes the sub-mesh's own vertices: they share one vertexOffset. Per-level vertices would need a new field in GeometryLod.
  • Errors never get smaller from one level to the next, and LOD 0's is 0. selectLod assumes that a coarser level never has a smaller error.
  • Borders stay locked, or sub-meshes that meet can crack.
  • MAX_MESH_LODS is the same in include/rasm/mesh.h and core.slang. A change to GeometryData follows the struct contract.
  • buildMeshLods runs on worker threads: it must not touch the engine.
Not done yet

No attribute-aware cost, no sloppy fallback, no vertex reordering for coarse levels (development plan, phase 2). Levels are not streamed in and out of the pool on their own: a mesh's levels come and go with it.

Further reading