CodeRigor

LESSON

Surfaces from a scalar field

Turn a grid of field values into a watertight triangle mesh with marching tetrahedra, then check it by edge counts, Euler characteristic and enclosed volume.

A scalar field gives one number at every point of space: a distance, a density, a height. The surface you see or collide with is where the field equals a chosen level. This lesson is about turning field values sampled on a grid into a triangle mesh of that surface. It pairs with Coding Adventure: Marching Cubes by Sebastian Lague, linked under Watch & read. You build the tetrahedron form of the same idea, with polygonize, interpolate and signed_volume, and check the mesh by counting its edges and measuring the volume it encloses. The second video listed there, Terraforming, revisits the method for editable terrain on a planet; watch it afterwards.

Samples sit at the grid points, and a cell is the cube between eight neighbouring samples. Call a sample inside when its value is below the level and outside otherwise. The surface passes through any cube whose corners are not all alike. Marching cubes reads the pattern of eight corners as a number from 0 to 255 and looks up the triangles in a table of 256 entries. Marching tetrahedra avoids the table. It cuts each cube into six tetrahedra, and a tetrahedron has only four corners and sixteen patterns.

The cut is the same for every cube: the six tetrahedra share the diagonal from corner 0 to corner 7, and each is a walk from 0 to 7 that adds one axis at a time. Because every cube is cut alike, two neighbouring cubes cut their shared face along the same diagonal, and the surfaces meet there.

Python
from itertools import permutations, product

print([(0, a, a | b, 7) for a, b, c in permutations((1, 2, 4))])
counts = [0, 0, 0]
for signs in product((0, 1), repeat=4):
    k = sum(signs)
    counts[0 if k in (0, 4) else 1 if k in (1, 3) else 2] += 1
print(counts)

The second line shows the three cases of a tetrahedron. Two of the sixteen patterns have no surface. Eight have one corner alone, giving a triangle. Six split two against two, giving a quadrilateral that you cut into two triangles. Inside a tetrahedron the field is linear, so the level set is flat, and that is why a triangle or a quadrilateral is exact.

A vertex goes on every edge that joins an inside corner to an outside one. If the field is a at p and b at q, the crossing is at p + t (q - p) with t = (level - a) / (b - a). Take a unit tetrahedron with values 0.2, 1.0, 0.8 and 1.4 at its corners and level 0.5. Only corner 0 is inside, so the triangle sits on its three edges, at t = 0.375, 0.5 and 0.25.

Python
import numpy as np

P = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1.0]])
v, level = [0.2, 1.0, 0.8, 1.4], 0.5
q = np.array([P[0] + (level - v[0]) / (v[j] - v[0]) * (P[j] - P[0]) for j in (1, 2, 3)])
print(q.round(3).tolist())
print(np.cross(q[1] - q[0], q[2] - q[0]).round(5).tolist())

The cross product is the triangle's normal, and the order of the vertices decides which way it points. You want it to face toward larger field values, away from the inside. Do not hard-code that per case. Compare the first triangle's normal with the vector from the inside centroid to the outside centroid, and reverse every triangle of that tetrahedron if they disagree. In the example the normal is (0.125, 0.094, 0.188), pointing away from corner 0 as it should.

From samples to a mesh
start / 5
polygonize visits every cell and tetrahedron. A vertex is created the first time a grid edge is crossed and reused after that.
From samples to a mesh
polygonize visits every cell and tetrahedron. A vertex is created the first time a grid edge is crossed and reused after that.

Several mistakes are common. Measuring the fraction from the wrong end, (b - level) / (b - a), puts every vertex at the mirror image of its place on the edge. It looks right whenever the level is halfway, so a symmetric test field does not expose it. Building the second triangle of a quadrilateral in the opposite direction to the first leaves half of it facing inward. Merging vertices afterwards by distance, instead of keying them by the grid edge, joins points that should be apart and misses ones that should merge. Treating a sample equal to the level inconsistently, inside in one place and outside in another, makes neighbours disagree about a shared edge, so fix one rule.

To verify the mesh, do not look at it; count. On a closed surface every edge belongs to exactly two triangles and is walked once in each direction. The vertices, edges and faces of a sphere satisfy V - E + F = 2. For a closed mesh the volume is the sum of v₀ · (v₁ × v₂) / 6 over the triangles, positive when they face outward.

Python
import numpy as np

V = np.array([[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1.0]])
F = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
edges = {tuple(sorted(e)) for a, b, c in F for e in ((a, b), (b, c), (c, a))}
print(len(V), len(edges), len(F), len(V) - len(edges) + len(F))
print(round(sum(V[a] @ np.cross(V[b], V[c]) for a, b, c in F) / 6, 4))

An octahedron has 6 vertices, 12 edges and 8 faces, and encloses 4/3. The hidden tests apply the same counts to a sphere meshed from a distance field, then compare the volume with 4/3 π r³. The mesh is inscribed in the field, so the volume is a little low, and the error falls roughly fourfold each time the spacing is halved.

Volume error of a meshed unit sphere
Measured with the reference solution on a grid spanning 3.2 units. The error is 14.42, 3.59 and 0.89 per cent at spacings 0.533, 0.267 and 0.133. The dashed curve is 50 times the spacing squared.
Volume error of a meshed unit sphere
Measured with the reference solution on a grid spanning 3.2 units. The error is 14.42, 3.59 and 0.89 per cent at spacings 0.533, 0.267 and 0.133. The dashed curve is 50 times the spacing squared.

Know what these checks do not show. A closed, outward, correctly sized mesh can still miss a feature thinner than the spacing, round off a sharp edge, or follow the field between samples only as well as a straight line can. The edge counts hold for any closed surface without handles, a cube as much as a sphere, so they test connectivity and orientation, not shape. Marching tetrahedra also tends to produce more, smaller triangles than marching cubes for the same grid, which is the price of having no table.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

A short video on marching cubes: how a grid of density values becomes a mesh, then editable and procedural terrain and an underwater scene. Watch it for the picture; here you build the tetrahedron variant of the same idea.

A longer video that revisits the marching cubes algorithm and uses it for a planet whose terrain can be edited. Useful afterwards to see how chunks of a field are meshed separately and what goes wrong at their borders.