Algorithmresearch
Isosurface stuffing
Also called Labelle-Shewchuk stuffing.
Labelle and Shewchuk's tetrahedral mesher for smooth domains that warps a body-centred cubic lattice to the surface, with proven dihedral angle bounds.
- Solves
- Mesh generation
- Time
- O(N) expected
- Space
- O(N + k) extra
- Where
- N = the number of lattice points in a box around the domain; k = the number of output tetrahedra
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- François Labelle, Jonathan Richard Shewchuk, 2007
Isosurface stuffing is a tetrahedral mesher for a domain with a smooth boundary given by a function , positive inside. It lays a body-centred cubic (BCC) lattice over the domain, moves the lattice points that lie too close to the surface onto it, and fills each lattice tetrahedron near the surface from a short table of stencils. Labelle and Shewchuk (2007) proved, with a computer-assisted search, that every dihedral angle of the output lies between and for a uniform lattice. Few tetrahedral meshers have a proved dihedral angle bound with a useful constant and also fit the boundary. It is also fast, because it does no point location and no geometric search.
In plain words
Fill space with a lattice: the corners of all unit cubes plus their centers. Join them into identical tetrahedra whose angles are only 60° and 90°. These are very good shapes. Now look at the boundary of the domain. Each lattice edge that crosses it gets a cut point where it crosses. If a cut point lies very close to one end of its edge, cutting there would make a thin tetrahedron, so move that lattice point onto the surface instead. After all such moves, cut each lattice tetrahedron at the surface by a fixed rule. The moves keep every piece fat, and a computer-checked proof gives the exact limits.
The problem
The input is a function that is positive inside the domain and negative outside, a way to find the point where on a segment, and a lattice spacing . The output is a set of tetrahedra that meet face to face (a tetrahedralization), whose boundary vertices lie on the surface . On this page , so the domain is a ball, and the zero on a segment is the root of a quadratic.
This page makes three kinds of claim, and they must be kept apart.
- Proved bound with its constant, cited. Theorem 1 of Labelle and Shewchuk: with the parameters and , every dihedral angle of every output tetrahedron lies in , and every plane angle in . The proof is computer assisted: interval arithmetic over a quadtree subdivision of the parameter space of each stencil case. It holds for every cut function, smooth or not, since the search covers every position of the cut points. The bounds are rounded outward and are tight to within : some cut functions produce these angles. This page does not repeat that proof.
- Proved here. The BCC tetrahedron has dihedral angles (four times) and (twice), volume , circumradius and radius-edge ratio . The BCC tetrahedra tile space and are Delaunay. The stencils fit face to face: the Parity Rule gives the same diagonal from both sides of a face, and every prism has a split. See
proofs/correctness.md. - Measured, no guarantee. On balls the angles are far better than the bound. In the example below they lie in , and over 25 random balls with between and the worst were and . Labelle and Shewchuk show meshes of real models with all angles in . The proved bound is tight over all inputs, but the inputs that reach it are rare. Against Delaunay methods the gap is the other way round: Labelle and Shewchuk note that the provable dihedral angle bounds of Delaunay refinement with sliver removal are below and probably below a millionth of a degree, while these methods give much better angles in practice.
A radius-edge ratio bound would not be enough. A sliver has radius-edge ratio as small as while its dihedral angles approach and . Isosurface stuffing bounds the dihedral angles directly, so it has no slivers. Its radius-edge ratio is not what it controls: in the example it reaches .
The algorithm
A lattice point has doubled coordinates , all even or all odd, at position . The even points form the cubic lattice and the odd points the shifted lattice. Black edges join neighbors at distance along an axis; red edges join a cube corner to a cube center, length . Each BCC tetrahedron has two opposite black edges and four red edges. A lattice point is violated if a cut point on one of its edges lies at less than times the edge length from , with on black edges and on red edges.
ISOSURFACE-STUFFING(f, h)- 1
compute f(q) at every lattice point q in a box around the domain - 2
for each edge pq with f(p) f(q) < 0, find its cut point, the zero of f on pq - 3
for each lattice point q, in a fixed order: - 4
if q is violated by a cut point on one of its edges that still has one: - 5
move q to the nearest such cut point; set f(q) ← 0, which removes the cut points on its edges - 6
for each BCC tetrahedron τ, by the signs of f at its vertices: - 7
no positive vertex: drop τ (also when all four are zero) - 8
no negative vertex: output τ - 9
one positive vertex a: output the tetrahedron of a, the zero vertices and the cut points on the edges from a - 10
two positive, one zero, one negative: output the pyramid over the quadrilateral of the face ab with the negative vertex, split into 2 - 11
two positive, two negative: output the prism between edge ab and the four cut points, split into 3 - 12
three positive, one negative: output the truncated tetrahedron, a prism, split into 3 - 13
output the pieces, with the moved positions of the moved points - 14
return the output tetrahedra
Each quadrilateral on a face of has corners (positive) and the cut points on and on , where is the negative vertex of the face. It is split by one of the diagonals or :
- if or is black, the diagonal that ends at the cut point on that black edge;
- otherwise is black and the Parity Rule applies: if and are on the cubic lattice, take when an odd number of the coordinates of are greater than those of , and otherwise; on the shifted lattice the choice is reversed.
The quadrilateral of a two-positive prism that lies on the surface is inside , so its diagonal is free; the implementation takes the one for which the prism splits. A prism can be cut into three tetrahedra with given diagonals on its three quadrilaterals exactly when the diagonals do not form a cycle, which is when some vertex is the end of two of them.
L5 moves to the cut point that violates it and lies nearest to it, as the paper suggests. Ties go to the smaller neighbor. The order of L3 matters only when two neighbors are both violated by their shared cut point; the first one moved removes it.
The implementation stores the lattice in doubled integer coordinates. It finds each cut point as the float root of the quadratic and then keeps it as an exact fraction, so all orientation tests on the output are exact. It orients every piece by the unmoved positions, where it is a part of the BCC tetrahedron, and the tests then check that every output tetrahedron has positive volume after the moves.
Example
Take the ball with center and , and . The counts come from the implementation, and the test file checks them.
| Step | Lines | Result |
|---|---|---|
| values | L1 | 3456 lattice points in the box, 544 inside the ball |
| cut points | L2 | 1288 lattice edges cross the sphere |
| warp | L3 to L5 | 242 lattice points move onto the sphere, 84 of them along black edges; 172 cut points remain |
| stencils | L6 to L12 | 16698 BCC tetrahedra: 1721 with four positive vertices and 1181 with positive and zero vertices only are kept whole, 464 with one positive vertex and some negative give one piece each, 69 pyramids give 2, 9 two-positive prisms and 5 three-positive prisms give 3; the other 13249 are dropped |
| output | L13, L14 | 834 vertices and 3546 tetrahedra |
The dihedral angles lie in , inside the proved range . The mesh has volume , against for the ball, and every boundary vertex lies on the sphere up to rounding: there. The radius-edge ratio reaches . Without step 3, that is with , the same input gives 6628 tetrahedra with a smallest dihedral angle of and a largest of : the warping is what removes the slivers.
Correctness
Correctness has two parts with different status.
The mesh is a tetrahedralization of a region bounded by the surface. This is proved in proofs/correctness.md. The BCC tetrahedra are Delaunay with strictly empty circumspheres, so they tile space without overlap, and a volume count (12 tetrahedra of volume per cubic cell) shows they also leave no gap. Each output piece lies in one BCC tetrahedron. What a stencil puts on a face of depends only on the signs at the three vertices of the face and on the quadrilateral rule, and the rule gives the same diagonal for the face and for . So two neighbors put the same triangles on their common face. The prisms always split: in the three-positive case the cut point on the black edge at the negative vertex is the end of two diagonals, and in the two-positive case the two face diagonals have no common end, so exactly one of the two diagonals of the surface quadrilateral avoids a cycle.
The angles are bounded. This is Theorem 1 of the paper, proved by computer. Its key facts are that a moved lattice point has value zero and lies within the part of one of its edges (its asterisk), that a lattice point labelled positive or negative was not moved, and that no edge at a moved point carries a cut point. Each stencil piece then has each vertex fixed or on a segment, and the extremes of a dihedral angle occur with the two vertices off the edge at ends of their segments. This reduces each case to at most two parameters, which a quadtree with interval arithmetic covers.
The paper also proves that every boundary vertex lies on the surface, that a point farther than from the surface is classified correctly for a constant given in Theorem 2, and that for a smooth surface with distance to the medial axis the mesh boundary is within of the surface in both directions when , and is ambient isotopic to it when is small enough (Theorem 3).
Proof: The BCC tetrahedra tile space and are Delaunay, and the stencils of ISOSURFACE-STUFFING fit face to face; the dihedral angle bounds are those of Theorem 1 of Labelle and Shewchukfull
Claim. Work in doubled coordinates, so the lattice is and . Then:
- the BCC tetrahedron has dihedral angles at its two black edges and at its four red edges, volume (that is ), circumradius (that is ) and radius-edge ratio ;
- its circumsphere has no other point of inside or on it, and the BCC tetrahedra tile face to face;
- the stencils of L7 to L12 match on every common face of two BCC tetrahedra, every prism of L11 and L12 splits into three tetrahedra with the prescribed diagonals, and so the pieces form a face-to-face tetrahedralization of the region they cover, provided they keep positive volume after warping.
What is not claimed. That the warped pieces keep positive volume and have dihedral angles in is Theorem 1 of Labelle and Shewchuk (2007), proved there by a computer search with interval arithmetic. It is cited, not proved here. The test file checks it on balls, with exact orientation tests.
Step 1: the BCC tetrahedron. The black edges and have squared length 4, and the four red edges, such as , have squared length 3. The volume is , and is the volume of a cell of the cubic lattice . The point has for all four vertices, so it is the circumcenter, and .
For the dihedral angles, take the outward normals , , and of the faces opposite . Each is orthogonal to the edges of its face, and for a vertex of that face, so it points away from . The dihedral angle at the edge has , where are the other two indices, and for all . At : . At : . At : . At : . At : . At : . So the black edges have and the red edges .
Step 2: emptiness and tiling. Let with , that is . Then , so and , which leaves . If is even, is odd, so and , : these are and . If is odd, is even, so , and , : these are and . So no other lattice point lies inside or on the circumsphere. The nearest ones, such as , are at squared distance from .
Every BCC tetrahedron listed by bcc_tetrahedra is the image of under a symmetry of : a translation by an even vector composed with a permutation of the axes and sign changes. So each has a strictly empty circumsphere among the points of , and each is a cell of the Delaunay subdivision of . Distinct Delaunay cells have disjoint interiors and meet face to face. For coverage, each even point starts 3 black edges, each with 4 tetrahedra, so there are 12 tetrahedra per even point. Their total volume, , is the volume of one cell of . A periodic family of interior-disjoint tetrahedra whose volume per period equals the volume of a period covers space. So the BCC tetrahedra tile face to face. (The test file also locates random points and finds each in exactly one tetrahedron.)
Step 3a: the quadrilateral rule depends only on the face. A face of a BCC tetrahedron omits one vertex, so it contains the black edge that avoids that vertex and two red edges. Let be positive and negative on the face, with cut points on and on ; the diagonals are and . If is black the rule takes , the diagonal at the cut point on , whichever of is named first, and likewise if is black. Otherwise is black, along an axis , and lies on the other lattice with and for . Since lies strictly inside the segment , holds exactly when . For this reads ; for it reads , because . Exchanging and (and so and ) changes the test for into and leaves the others unchanged. Exactly one of and holds, so the two counts have opposite parity. On the cubic lattice, the rule for takes if its count is odd and if it is even, and the rule for takes if its count is odd and if it is even; with opposite parities they agree. On the shifted lattice both choices are reversed, and they still agree.
Step 3b: the stencils agree on every face. Let be a common face of two BCC tetrahedra, with the values after warping. A zero vertex is a vertex of the output, and an edge with a zero end has no cut point. If has a positive vertex, inspection of L8 to L12 shows that the output of a tetrahedron meets in: all of if has no negative vertex; the triangle of the positive vertex and the zero vertices or cut points on its other two edges if has one positive and some negative vertex; and the quadrilateral of Step 3a, split by the rule, if has two positive vertices and one negative. (In L10, for instance, the face carries the split quadrilateral, the faces and the triangles with the cut point, and the face is whole.) These triangles depend only on and its values, so both tetrahedra produce the same ones. If has no positive vertex, the output of meets in a set of dimension at most one, except when all three vertices of are zero and the fourth vertex of is positive: then is a face of the output. So either both sides output as a face, or one side does and is a boundary face with its three vertices on the surface.
Step 3c: the prisms split. A prism with bottom , top and a diagonal on each quadrilateral splits into three tetrahedra with these diagonals if some vertex is the end of two of them: take the tetrahedron from to the opposite triangle and the pyramid from over the third quadrilateral, split by its diagonal. If no vertex is the end of two diagonals, each of the six vertices is the end of exactly one, the diagonals form a cycle around the prism, and no split exists, as in Schönhardt's twisted prism.
In L12, with positive and negative, lies on one black edge of with . Both faces of that contain take the diagonal at the cut point on , which is then the end of two diagonals.
In L11, with positive and negative, the faces and carry two of the diagonals. If is red, the black edges of are or ; say and . Then takes to the cut point on , and takes to the cut point on : no common end. If is black along axis , so is , along an axis , with , and for . By Step 3a, the counts of for the faces and differ only at the coordinate , where exactly one of and holds. So the counts have opposite parity, one face takes the diagonal from and the other the diagonal from , and again there is no common end. In both cases the third quadrilateral lies on the surface inside , so its diagonal appears in no other tetrahedron. Its corners are the four cut points. Of its two diagonals, one joins the two cut points that end the face diagonals, and the other joins the two cut points that end neither; the first makes a vertex the end of two diagonals, the second leaves a cycle. L11 tries both and takes the first, so the prism splits.
Step 3d: conclusion. Before warping, each piece lies in its BCC tetrahedron, and the pieces of one tetrahedron tile the part of it that the stencil keeps. By Step 2 the BCC tetrahedra tile space face to face, and by Steps 3b and 3c the pieces of neighbors match on every common face. Warping moves only lattice points whose value becomes zero, and moves each to a single position shared by all pieces that contain it, so the combinatorial structure does not change, and the pieces still meet face to face as long as each keeps positive volume. Theorem 1 of Labelle and Shewchuk gives the positive volumes and the angle bounds. Every boundary face of the output has only zero vertices and cut points as vertices, and all of these lie on the surface.
Complexity
Each lattice point is evaluated once, each edge gets at most one cut point, and each BCC tetrahedron gives at most three pieces, so the time is evaluations and root findings, with hashing for the lattice, and the space is . With a uniform lattice grows as . The graded version uses an octree, so the count grows as near the surface plus a coarse interior. On a dense domain, Labelle and Shewchuk report about 510 tetrahedra per millisecond for their prototype, against about 157 for Pyramid, their Delaunay mesher, because stuffing does far fewer numerical calculations and needs simpler data structures.
Properties
- Proved dihedral angle bound with explicit constant. for the parameters on this page, by a computer-assisted proof, tight to within .
- Boundary fit. Every vertex on the mesh boundary lies on the surface .
- Deterministic. The result depends on the warping order only through ties of the kind described above.
- Not exact. The cut points are float roots, kept exactly afterwards. With exact roots the method would need algebraic numbers.
- No sharp features. Edges and corners of the domain are rounded off.
- Lattice aligned. Most tetrahedra are exact BCC tetrahedra, so more than half of the dihedral angles are or .
Variants and improvements
- Other parameters. Table 1 of the paper gives several choices of . Optimizing the largest angle instead gives with . Safe variants, in which no BCC tetrahedron can invert during warping, give or , and ordered warping gives .
- Both sides. The double-sided rows of Table 1 mesh the inside and the outside with compatible tetrahedra, with weaker bounds: and .
- Graded interior. A BCC-like octree coarsens the mesh away from the surface while the tetrahedra at the surface stay of one size. The dihedral bounds of Table 1 still hold. If the surface tetrahedra vary in size too, the authors cannot guarantee better than .
- Linear cut points. Placing each cut point by linear interpolation of instead of on the surface keeps the angle bound but gives up the boundary guarantees.
- Lattice refinement without a fitted boundary. Labelle (2006) gives a lattice method with all dihedral angles between and for meshes that do not conform to the boundary.
- Other boundary-fitted methods. Octree mesh generation cuts cubes without moving vertices and has no bound at the surface. Tetrahedral Delaunay refinement bounds the radius-edge ratio, and sliver exudation removes slivers with a far weaker proved angle.
When to use it
Use it for domains with smooth boundaries given by a level set, a signed distance function or a voxel image, when every tetrahedron must have good dihedral angles and the mesh is needed fast or often, as in simulations that remesh a moving liquid or soft tissue. It is a poor choice when the domain has sharp edges or corners that must be kept, or when the boundary is a given triangle mesh that must appear in the output; use Delaunay surface meshing followed by Delaunay refinement there.
Pitfalls
- Skipping the warp. Cutting the lattice where the surface crosses it, without moving vertices, gives slivers ( in the example).
- Inconsistent diagonals. A diagonal rule that depends on the tetrahedron, not on the face, makes neighbors disagree and leaves a crack. The Parity Rule and the black-edge rule depend only on the face.
- Quadruple-zero tetrahedra. A BCC tetrahedron whose four vertices all moved onto the surface may be very flat. Dropping it keeps the bounds of Table 1. A well-shaped one is a sign that the lattice is too coarse for the surface.
- Expecting the radius-edge ratio to be small. The method bounds dihedral angles, not the radius-edge ratio, which is a different measure and does not exclude slivers by itself.
- Too coarse a lattice. Features smaller than about are lost or meshed with the wrong topology. Theorem 3 needs small against the distance to the medial axis.
- Floating-point cut points. Rounding can put a cut point exactly at an end of its edge. Clamp it and test orientations exactly, as here.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isosurface-stuffing/. The authors are listed in prov/B7WM22.jsonl.
"""Isosurface stuffing of Labelle and Shewchuk (2007), uniform version, for a ball.
The background grid is the body-centred cubic (BCC) lattice of spacing h. A
lattice point is stored by its doubled coordinates (i, j, k): all even for the
cubic lattice Z^3 and all odd for the shifted lattice Z^3 + (1/2, 1/2, 1/2).
Its position is (h/2)(i, j, k). An edge is *black* (long, axis aligned, length
h) or *red* (short, length h sqrt(3)/2).
The domain is the ball f(x) = r2 - |x - center|^2 > 0. The four steps are those
of the paper: values at the lattice points, cut points on the edges with a sign
change, warping of violated lattice points onto the surface, and stencils.
Cut points are the exact zeros of f on the edge, rounded once to a float and
then kept as exact fractions. Every predicate on positions is exact.
"""
import math
from fractions import Fraction
from typing import Dict, List, Sequence, Tuple
from mg2geom import orient3d
# The row "minimum dihedral angle, unsafe" of Table 1 of the paper.
ALPHA_LONG = Fraction("0.28511")
ALPHA_SHORT = Fraction("0.39882")
DIHEDRAL_MIN = 10.7843
DIHEDRAL_MAX = 164.7373
BLACK_STEPS = [tuple(2 * s if a == i else 0 for a in range(3)) for i in range(3) for s in (1, -1)]
RED_STEPS = [(a, b, c) for a in (1, -1) for b in (1, -1) for c in (1, -1)]
Key = Tuple[int, int, int]
def is_black(p: Key, q: Key) -> bool:
return sum(1 for a, b in zip(p, q) if a != b) == 1
def bcc_tetrahedra(points: set):
"""All BCC grid tetrahedra with the four vertices in points.
Each one has exactly one black edge of the cubic lattice, so it is listed
once: for the black edge p, p + 2e_i, the four centers around the edge give
four tetrahedra.
"""
out = []
for p in sorted(points):
if p[0] % 2:
continue
for i in range(3):
q = tuple(p[a] + (2 if a == i else 0) for a in range(3))
if q not in points:
continue
j, k = [a for a in range(3) if a != i]
ring = []
for sj, sk in ((1, 1), (-1, 1), (-1, -1), (1, -1)):
c = [0, 0, 0]
c[i], c[j], c[k] = p[i] + 1, p[j] + sj, p[k] + sk
ring.append(tuple(c))
for s in range(4):
c1, c2 = ring[s], ring[(s + 1) % 4]
if c1 in points and c2 in points:
out.append((p, q, c1, c2))
return out
class Stuffing:
def __init__(self, center: Sequence, r2, h, alpha_long=ALPHA_LONG, alpha_short=ALPHA_SHORT):
self.center = tuple(Fraction(c) for c in center)
self.r2 = Fraction(r2)
self.h = Fraction(h)
if self.r2 <= 0 or self.h <= 0:
raise ValueError("need r2 > 0 and h > 0")
self.alpha = {True: Fraction(alpha_long), False: Fraction(alpha_short)}
half = self.h / 2
r = math.sqrt(self.r2)
lo = [math.floor((float(c) - r) / float(half)) - 3 for c in self.center]
hi = [math.ceil((float(c) + r) / float(half)) + 3 for c in self.center]
self.points = {
(i, j, k)
for i in range(lo[0], hi[0] + 1)
for j in range(lo[1], hi[1] + 1)
for k in range(lo[2], hi[2] + 1)
if i % 2 == j % 2 == k % 2
}
self.orig = {p: tuple(half * x for x in p) for p in self.points}
self.pos = dict(self.orig)
self.value = {p: self.f(self.orig[p]) for p in self.points} # @line L1
self.cut_t: Dict[tuple, Fraction] = {}
self.warped: Dict[Key, Key] = {}
def f(self, x) -> Fraction:
return self.r2 - sum((a - c) ** 2 for a, c in zip(x, self.center))
def neighbors(self, p: Key):
for d in BLACK_STEPS + RED_STEPS:
q = (p[0] + d[0], p[1] + d[1], p[2] + d[2])
if q in self.points:
yield q
# cut points
def has_cut(self, p: Key, q: Key) -> bool:
return self.value[p] * self.value[q] < 0
def cut_param(self, p: Key, q: Key) -> Fraction:
"""The position of the cut point on edge pq, as a fraction of the way from p to q."""
e = (p, q) if p < q else (q, p)
if e not in self.cut_t:
a, b = self.orig[e[0]], self.orig[e[1]]
d = [y - x for x, y in zip(a, b)]
w = [x - c for x, c in zip(a, self.center)]
# f(a + t d) = C0 - 2 t B - t^2 A with C0 = f(a), B = d . w, A = |d|^2.
# If a is inside, the roots have opposite signs and we want the positive one.
# If a is outside and b inside, we want the smaller root, where the edge enters.
A = float(sum(x * x for x in d))
B = float(sum(x * y for x, y in zip(d, w)))
C0 = float(self.f(a))
root = math.sqrt(max(0.0, B * B + A * C0))
t = (-B + root) / A if C0 > 0 else (-B - root) / A
self.cut_t[e] = min(max(Fraction(t), Fraction(0)), Fraction(1)) # @line L2
t = self.cut_t[e]
return t if e[0] == p else 1 - t
def cut_point(self, p: Key, q: Key) -> tuple:
s = self.cut_param(p, q)
a, b = self.orig[p], self.orig[q]
return tuple(x + s * (y - x) for x, y in zip(a, b))
# step 3
def warp(self) -> None:
for q in sorted(self.points): # @line L3
if self.value[q] == 0:
continue
best = None
for r in self.neighbors(q):
if not self.has_cut(q, r):
continue
s = self.cut_param(q, r)
if s < self.alpha[is_black(q, r)]: # @line L4
d2 = s * s * sum((x - y) ** 2 for x, y in zip(self.orig[q], self.orig[r]))
if best is None or (d2, r) < best[:2]:
best = (d2, r)
if best is not None:
r = best[1]
self.pos[q] = self.cut_point(q, r) # @line L5
self.value[q] = Fraction(0) # its cut points disappear with its sign
self.warped[q] = r
# step 4
def quad_diagonal(self, a: Key, b: Key, x: Key) -> frozenset:
"""Diagonal of the quadrilateral that face abx leaves, with a, b positive and x negative.
Its corners are a, b, cut(b, x), cut(a, x). A truncated black edge
gives the diagonal at its cut point; a whole black edge ab uses the
Parity Rule.
"""
ca, cb = ("c",) + edge(a, x), ("c",) + edge(b, x)
A, B = ("v", a), ("v", b)
if is_black(a, x):
return frozenset((B, ca))
if is_black(b, x):
return frozenset((A, cb))
# Parity Rule: diagonals are a-c and b-d with c = cut(b, x), d = cut(a, x).
# A coordinate of a is greater than that of c exactly when 2 a > b + x
# coordinatewise, since c lies strictly inside the red edge bx.
odd = sum(1 for i in range(3) if 2 * a[i] > b[i] + x[i]) % 2 == 1
on_cubic = a[0] % 2 == 0
return frozenset((A, cb)) if odd == on_cubic else frozenset((B, ca))
def stencil(self, tet: Sequence[Key]) -> List[tuple]:
pos = [v for v in tet if self.value[v] > 0]
zero = [v for v in tet if self.value[v] == 0]
neg = [v for v in tet if self.value[v] < 0]
V = lambda v: ("v", v) # noqa: E731
C = lambda p, q: ("c",) + edge(p, q) # noqa: E731
if not pos:
return [] # @line L7
if not neg:
return [tuple(V(v) for v in tet)] # @line L8
if len(pos) == 1: # @line L9
a = pos[0]
return [(V(a),) + tuple(V(z) for z in zero) + tuple(C(a, x) for x in neg)]
if len(pos) == 2 and len(zero) == 1: # @line L10
(a, b), z, d = pos, zero[0], neg[0]
g = self.quad_diagonal(a, b, d)
if g == frozenset((V(a), C(b, d))):
return [(V(z), V(a), V(b), C(b, d)), (V(z), V(a), C(b, d), C(a, d))]
return [(V(z), V(a), V(b), C(a, d)), (V(z), V(b), C(b, d), C(a, d))]
if len(pos) == 2: # @line L11
(a, b), (c, d) = pos, neg
bottom = (V(a), C(a, c), C(a, d))
top = (V(b), C(b, c), C(b, d))
q0 = self.quad_diagonal(a, b, c)
q2 = self.quad_diagonal(a, b, d)
for q1 in (frozenset((C(a, c), C(b, d))), frozenset((C(a, d), C(b, c)))):
try:
return split_prism(bottom, top, [q0, q1, q2])
except ValueError:
continue
raise AssertionError("no prism split")
a, b, c = pos # @line L12
d = neg[0]
bottom = (V(a), V(b), V(c))
top = (C(a, d), C(b, d), C(c, d))
diags = [self.quad_diagonal(a, b, d), self.quad_diagonal(b, c, d), self.quad_diagonal(c, a, d)]
return split_prism(bottom, top, diags)
def position(self, key, warped=True) -> tuple:
if key[0] == "v":
return (self.pos if warped else self.orig)[key[1]]
return self.cut_point(key[1], key[2])
def mesh(self):
"""Run the four steps. Returns (vertices, tetrahedra) with positive orientation."""
self.warp()
index: Dict[tuple, int] = {}
verts: List[tuple] = []
tets: List[tuple] = []
for tet in bcc_tetrahedra(self.points): # @line L6
for piece in self.stencil(tet):
# orient by the unwarped positions, where the piece is a part of the BCC tetrahedron
o = orient3d(*[self.position(k, warped=False) for k in piece])
if o == 0:
raise AssertionError("flat stencil piece")
if o < 0:
piece = (piece[1], piece[0]) + tuple(piece[2:])
ids = []
for k in piece:
p = self.position(k)
if p not in index:
index[p] = len(verts)
verts.append(p)
ids.append(index[p])
tets.append(tuple(ids)) # @line L13
return verts, tets
def edge(p: Key, q: Key) -> tuple:
return (p, q) if p < q else (q, p)
def split_prism(bottom: Sequence, top: Sequence, diags: Sequence[frozenset]) -> List[tuple]:
"""Cut a prism into three tetrahedra with the given diagonals of its quadrilaterals.
bottom[i] and top[i] are joined by an edge, and diags[i] is the diagonal of
the quadrilateral bottom[i], bottom[i+1], top[i+1], top[i]. A split exists
if and only if some vertex is the end of two diagonals; otherwise
ValueError is raised.
"""
six = list(bottom) + list(top)
deg = {v: sum(1 for g in diags if v in g) for v in six}
twice = [v for v in six if deg[v] == 2]
if not twice:
raise ValueError("the three diagonals form a cycle")
v = twice[0]
quads = [(bottom[i], bottom[(i + 1) % 3], top[(i + 1) % 3], top[i]) for i in range(3)]
if v in top:
bottom, top = top, bottom
quads = [(q[3], q[2], q[1], q[0]) for q in quads]
i = list(bottom).index(v)
far = (i + 1) % 3
out = [(v, top[0], top[1], top[2])]
a, b, c, d = quads[far]
if diags[far] == frozenset((a, c)):
out += [(v, a, b, c), (v, a, c, d)]
else:
out += [(v, a, b, d), (v, b, c, d)]
return out
def isosurface_stuffing(center: Sequence, r2, h, **kw):
"""Mesh the ball |x - center|^2 < r2 with a BCC lattice of spacing h.
Returns (stuffing state, vertices, tetrahedra).
"""
s = Stuffing(center, r2, h, **kw)
verts, tets = s.mesh()
return s, verts, tets # @line L14
mg2geom.py 159 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mg2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small exact geometric tools used by the mg2 pages.
Points are tuples of int or fractions.Fraction. Every predicate returns an
exact value when the coordinates are int or Fraction, so its sign is the true
sign. A float converts to a Fraction without rounding (exact()), so the sign
is then exact for the float point as it is stored. The angle functions return
floats and are used only to report or to compare with a stated bound.
"""
import math
from fractions import Fraction
from typing import Sequence, Tuple
Point = Tuple
def exact(p: Point) -> Tuple[Fraction, ...]:
"""The point p with each coordinate converted to Fraction, without rounding."""
return tuple(Fraction(c) for c in p)
def sub(a: Point, b: Point) -> tuple:
return tuple(x - y for x, y in zip(a, b))
def dot(a: Point, b: Point):
return sum(x * y for x, y in zip(a, b))
def cross(a: Point, b: Point) -> tuple:
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def dist2(a: Point, b: Point):
return sum((x - y) * (x - y) for x, y in zip(a, b))
def det3(r0: Sequence, r1: Sequence, r2: Sequence):
return dot(r0, cross(r1, r2))
def det4(m: Sequence[Sequence]):
"""Determinant of a 4 by 4 matrix by cofactor expansion along the first row."""
total = 0
for j in range(4):
minor = [[m[i][k] for k in range(4) if k != j] for i in range(1, 4)]
term = m[0][j] * det3(minor[0], minor[1], minor[2])
total += term if j % 2 == 0 else -term
return total
def orient2d(a: Point, b: Point, c: Point):
"""Twice the signed area of the triangle a, b, c; positive if counterclockwise."""
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def orient3d(a: Point, b: Point, c: Point, d: Point):
"""Six times the signed volume of the tetrahedron a, b, c, d.
It is det[b - a, c - a, d - a]: positive when d lies on the side of the
plane abc from which a, b, c appear clockwise.
"""
return det3(sub(b, a), sub(c, a), sub(d, a))
def insphere(a: Point, b: Point, c: Point, d: Point, e: Point):
"""Positive if e lies inside the sphere through a, b, c, d, zero on it.
The value is det of the rows (p - e, |p - e|^2) for p = a, b, c, d,
divided by nothing, times the sign of orient3d(a, b, c, d), so the result
does not depend on the order of a, b, c, d. The tetrahedron must not be flat.
"""
rows = []
for p in (a, b, c, d):
v = sub(p, e)
rows.append([v[0], v[1], v[2], dot(v, v)])
o = orient3d(a, b, c, d)
if o == 0:
raise ValueError("flat tetrahedron")
val = -det4(rows)
return val if o > 0 else -val
def circumcenter3(a: Point, b: Point, c: Point, d: Point) -> tuple:
"""Exact circumcenter of a tetrahedron, by Cramer's rule on 2 (p - a) . x = |p - a|^2."""
u, v, w = sub(b, a), sub(c, a), sub(d, a)
det = det3(u, v, w)
if det == 0:
raise ValueError("flat tetrahedron")
bu, bv, bw = Fraction(dot(u, u)), Fraction(dot(v, v)), Fraction(dot(w, w))
# x = (bu (v x w) + bv (w x u) + bw (u x v)) / (2 det)
cvw, cwu, cuv = cross(v, w), cross(w, u), cross(u, v)
x = tuple((bu * cvw[k] + bv * cwu[k] + bw * cuv[k]) / (2 * det) for k in range(3))
return tuple(a[k] + x[k] for k in range(3))
def tri_circumcenter3(a: Point, b: Point, c: Point) -> tuple:
"""Exact circumcenter of a triangle in space (the center of its smallest circumscribed sphere)."""
u, v = sub(b, a), sub(c, a)
n = cross(u, v)
nn = Fraction(dot(n, n))
if nn == 0:
raise ValueError("flat triangle")
t1 = cross(n, u)
t2 = cross(v, n)
uu, vv = dot(u, u), dot(v, v)
# x = (|u|^2 (v x n) + |v|^2 (n x u)) / (2 |n|^2)
return tuple(a[k] + (uu * t2[k] + vv * t1[k]) / (2 * nn) for k in range(3))
def radius_edge2(a: Point, b: Point, c: Point, d: Point) -> Fraction:
"""Exact square of the radius-edge ratio R / l_min of a tetrahedron."""
cc = circumcenter3(a, b, c, d)
r2 = dist2(cc, a)
pts = (a, b, c, d)
lmin2 = min(dist2(pts[i], pts[j]) for i in range(4) for j in range(i + 1, 4))
return Fraction(r2) / Fraction(lmin2)
def _angle(u: Sequence[float], v: Sequence[float]) -> float:
nu = math.sqrt(sum(x * x for x in u))
nv = math.sqrt(sum(x * x for x in v))
c = sum(x * y for x, y in zip(u, v)) / (nu * nv)
return math.degrees(math.acos(max(-1.0, min(1.0, c))))
def triangle_angles_deg(a: Point, b: Point, c: Point) -> list:
"""The three plane angles of a triangle in degrees, in 2D or 3D (floats)."""
p = [tuple(float(x) for x in q) for q in (a, b, c)]
out = []
for i in range(3):
o, s, t = p[i], p[(i + 1) % 3], p[(i + 2) % 3]
out.append(_angle(sub(s, o), sub(t, o)))
return out
def dihedral_angles_deg(a: Point, b: Point, c: Point, d: Point) -> list:
"""The six dihedral angles of a tetrahedron in degrees (floats).
The angle at edge pq is the angle between the two faces pqr and pqs,
measured inside the tetrahedron.
"""
p = [tuple(float(x) for x in q) for q in (a, b, c, d)]
out = []
for i in range(4):
for j in range(i + 1, 4):
k, m = [t for t in range(4) if t not in (i, j)]
e = sub(p[j], p[i])
ee = dot(e, e)
# components of p_k - p_i and p_m - p_i orthogonal to the edge
u = sub(p[k], p[i])
v = sub(p[m], p[i])
u = tuple(u[t] - dot(u, e) / ee * e[t] for t in range(3))
v = tuple(v[t] - dot(v, e) / ee * e[t] for t in range(3))
out.append(_angle(u, v))
return out
test_isosurface_stuffing.py 221 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isosurface-stuffing/. The authors are listed in prov/B7WM22.jsonl.
import math
import random
from collections import Counter
from fractions import Fraction as F
from functools import lru_cache
import pytest
from isosurface_stuffing import (
DIHEDRAL_MAX,
DIHEDRAL_MIN,
Stuffing,
bcc_tetrahedra,
is_black,
isosurface_stuffing,
split_prism,
)
from mg2geom import circumcenter3, dihedral_angles_deg, dist2, insphere, orient3d, radius_edge2
def random_ball(seed):
r = random.Random(seed)
center = tuple(F(r.randint(-500, 500), 1000) for _ in range(3))
r2 = F(r.randint(300, 1500), 1000)
h = F(1, r.randint(3, 5))
return center, r2, h
CASES = [
((F(3, 100), F(-2, 100), F(1, 100)), F(1), F(1, 4)), # the example of the page
((0, 0, 0), F(1), F(1, 4)), # lattice points lie exactly on the sphere
random_ball(1),
random_ball(2),
]
@lru_cache(maxsize=None)
def run(i):
center, r2, h = CASES[i]
return isosurface_stuffing(center, r2, h)
def lattice(lo, hi):
return {(i, j, k) for i in range(lo, hi + 1) for j in range(lo, hi + 1) for k in range(lo, hi + 1) if i % 2 == j % 2 == k % 2}
# The BCC tetrahedron, in doubled coordinates: black edges (0,0,0)-(2,0,0) and (1,1,1)-(1,-1,1).
BCC = ((0, 0, 0), (2, 0, 0), (1, 1, 1), (1, -1, 1))
def test_bcc_tetrahedron_shape():
d = dihedral_angles_deg(*BCC)
# pairs in the order 01, 02, 03, 12, 13, 23; the black edges are 01 and 23
assert d[0] == pytest.approx(90) and d[5] == pytest.approx(90)
assert all(x == pytest.approx(60) for x in d[1:5])
# six times the volume is 4 in doubled units, so the volume is 4 / 6 / 8 = 1/12 of h^3
assert orient3d(*BCC) == 4
assert F(orient3d(*BCC), 6 * 8) == F(1, 12)
# circumcenter (1/2, 0, 1/4) h, R^2 = 5/16 h^2, shortest edge sqrt(3)/2 h
cc = circumcenter3(*BCC)
assert tuple(x / 2 for x in cc) == (F(1, 2), 0, F(1, 4))
assert dist2(cc, BCC[0]) / 4 == F(5, 16)
assert radius_edge2(*BCC) == F(5, 12)
def test_bcc_circumsphere_is_strictly_empty():
others = lattice(-6, 8) - set(BCC)
worst = max(insphere(*BCC, p) for p in others)
assert worst < 0 # no other lattice point is inside or on the sphere
assert worst == -8 # -1/4 for h = 1; doubling the coordinates multiplies it by 2^5
# the same fact as a margin: the nearest other lattice point is at squared distance
# 13/16 h^2 from the circumcenter, against R^2 = 5/16 h^2
cc = circumcenter3(*BCC)
assert min(dist2(p, cc) for p in others) / 4 == F(13, 16)
def test_bcc_tetrahedra_tile_space():
pts = lattice(-2, 10)
tets = bcc_tetrahedra(pts)
# every cubic lattice point away from the border starts 3 black edges with 4 tetrahedra each
per_point = Counter(t[0] for t in tets)
assert all(per_point[p] == 12 for p in lattice(0, 6) if p[0] % 2 == 0)
# 12 tetrahedra of volume 1/12 per unit cell: the volume is right; now check no overlap
# and no gap by locating random points (brute force over all tetrahedra)
r = random.Random(3)
boxes = []
for t in tets:
lo = tuple(min(p[a] for p in t) for a in range(3))
hi = tuple(max(p[a] for p in t) for a in range(3))
boxes.append((lo, hi, t if orient3d(*t) > 0 else (t[1], t[0], t[2], t[3])))
for _ in range(150):
x = tuple(F(r.randint(3000, 5000), 1000) + F(1, 7919) for _ in range(3))
hits = 0
for lo, hi, (a, b, c, d) in boxes:
if all(lo[k] <= x[k] <= hi[k] for k in range(3)):
if orient3d(x, b, c, d) > 0 and orient3d(a, x, c, d) > 0 and orient3d(a, b, x, d) > 0 and orient3d(a, b, c, x) > 0:
hits += 1
assert hits == 1, x
def test_parity_rule_is_the_same_from_both_sides():
s = Stuffing((0, 0, 0), 1, 1)
pts = lattice(-2, 4)
n = 0
for a in pts:
for b in pts:
if not (a < b and dist2(a, b) in (3, 4)):
continue
for x in pts:
if dist2(a, x) in (3, 4) and dist2(b, x) in (3, 4) and x not in (a, b):
# a BCC triangle: one black edge and two red edges
assert sum(is_black(p, q) for p, q in ((a, b), (a, x), (b, x))) == 1
assert s.quad_diagonal(a, b, x) == s.quad_diagonal(b, a, x)
n += 1
assert n > 1000
def test_split_prism():
pts = {"b0": (0, 0, 0), "b1": (6, 0, 0), "b2": (0, 6, 0), "t0": (1, 1, 5), "t1": (7, 1, 5), "t2": (1, 7, 5)}
bottom, top = ("b0", "b1", "b2"), ("t0", "t1", "t2")
quads = [(bottom[i], bottom[(i + 1) % 3], top[(i + 1) % 3], top[i]) for i in range(3)]
for mask in range(8):
diags = [frozenset((q[0], q[2])) if mask >> i & 1 else frozenset((q[1], q[3])) for i, q in enumerate(quads)]
deg = Counter(v for g in diags for v in g)
if max(deg.values()) < 2:
with pytest.raises(ValueError):
split_prism(bottom, top, diags)
continue
out = split_prism(bottom, top, diags)
assert sum(abs(orient3d(*[pts[v] for v in t])) for t in out) == 6 * 18 * 5
edges = {frozenset((a, b)) for t in out for a in t for b in t if a != b}
for g, q in zip(diags, quads):
assert g in edges and frozenset(set(q) - g) not in edges
def faces(tets):
c = Counter()
for a, b, cc, d in tets:
for tri in ((b, cc, d), (a, d, cc), (a, b, d), (a, cc, b)):
i = tri.index(min(tri))
c[tri[i:] + tri[:i]] += 1
return c
@pytest.mark.parametrize("i", range(len(CASES)))
def test_mesh_of_a_ball(i):
state, verts, tets = run(i)
center, r2, h = CASES[i]
f = state.f
# every tetrahedron has positive volume in the warped (final) geometry, by an exact test
vols = [orient3d(*[verts[v] for v in t]) for t in tets]
assert all(v > 0 for v in vols)
# the stated dihedral bounds of Table 1 hold on every tetrahedron
for t in tets:
d = dihedral_angles_deg(*[verts[v] for v in t])
assert DIHEDRAL_MIN <= min(d) and max(d) <= DIHEDRAL_MAX
# face to face: every face is used once in each orientation, or once on the boundary
c = faces(tets)
tol = 1e-12 * float(r2)
for tri, m in c.items():
assert m == 1
if (tri[0], tri[2], tri[1]) not in c:
assert all(abs(float(f(verts[v]))) <= tol for v in tri)
# no vertex leaves the closed ball, so no tetrahedron does
assert all(float(f(p)) >= -tol for p in verts)
# a lattice point deeper than the largest warp distance stays where it is, and the
# BCC tetrahedra of such points are kept whole, so the mesh contains the ball of
# radius r - 1.5 h; it lies in the ball of radius r
r = math.sqrt(r2)
vol = sum(vols) / 6
assert 4 / 3 * math.pi * (r - 1.5 * float(h)) ** 3 < vol < 4 / 3 * math.pi * r**3
@pytest.mark.parametrize("i", range(len(CASES)))
def test_no_violation_is_left_after_warping(i):
state = run(i)[0]
for q in state.points:
if q in state.warped:
assert state.value[q] == 0
assert abs(float(state.f(state.pos[q]))) <= 1e-12
# it moved to a cut point on one of its own edges, within the alpha fraction
r = state.warped[q]
assert state.cut_param(q, r) < state.alpha[is_black(q, r)]
continue
assert state.pos[q] == state.orig[q]
for r in state.neighbors(q):
if state.has_cut(q, r):
assert state.cut_param(q, r) >= state.alpha[is_black(q, r)]
def test_warping_is_what_removes_the_slivers():
center, r2, h = CASES[0]
_, verts, tets = isosurface_stuffing(center, r2, h, alpha_long=0, alpha_short=0)
worst = min(min(dihedral_angles_deg(*[verts[v] for v in t])) for t in tets)
assert worst < 1 # cutting the lattice without warping leaves a 0.17 degree sliver
def test_example_counts():
state, verts, tets = run(0)
assert len(state.points) == 3456
assert sum(1 for p in state.points if state.f(state.orig[p]) > 0) == 544
assert len(state.warped) == 242
assert sum(is_black(q, r) for q, r in state.warped.items()) == 84
assert (len(verts), len(tets)) == (834, 3546)
d = [a for t in tets for a in dihedral_angles_deg(*[verts[v] for v in t])]
assert min(d) == pytest.approx(19.0757, abs=1e-4)
assert max(d) == pytest.approx(135.6767, abs=1e-4)
vol = sum(orient3d(*[verts[v] for v in t]) for t in tets) / 6
assert float(vol) == pytest.approx(4.1222, abs=1e-4)
# the radius-edge ratio is not what the method bounds; it reaches about 2.2 here
assert max(radius_edge2(*[verts[v] for v in t]) for t in tets) == pytest.approx(4.8936, abs=1e-4)
def test_rejects_bad_input():
with pytest.raises(ValueError):
isosurface_stuffing((0, 0, 0), 0, F(1, 4))
with pytest.raises(ValueError):
isosurface_stuffing((0, 0, 0), 1, 0)
History
Body-centred cubic tetrahedra were listed by Sommerville among the tetrahedra that tile space, and Fuchs and Naylor proposed the BCC lattice for meshing. Bern, Eppstein and Gilbert introduced the warping of a background grid onto a boundary in their quadtree mesher of 1990. Labelle and Shewchuk combined the BCC lattice, warping and a table of stencils in isosurface stuffing, presented at SIGGRAPH 2007, and proved its dihedral angle bounds by an interval arithmetic search. Earlier provable tetrahedral meshers either bounded only the radius-edge ratio or had dihedral angle bounds far below one degree.
References
- François Labelle and Jonathan Richard Shewchuk, Isosurface stuffing, fast tetrahedral meshes with good dihedral angles, ACM Transactions on Graphics 26(3), 2007, article 57 (SIGGRAPH 2007), Section 3 (the four steps, the stencils and the Parity Rule), Section 4.1 (Theorem 1 and Table 1, the dihedral angle bounds and the parameters alpha), Section 4.2 (Theorems 2 and 3), Section 5 (graded meshes), Section 2 (the comparison with other methods)
- François Labelle, Sliver removal by lattice refinement, Proceedings of the 22nd ACM Symposium on Computational Geometry, 2006, 347 to 356, the lattice mesher with dihedral angles between 30 and 135 degrees that does not conform to the boundary (general locator; the numbers are quoted from Section 2 of Labelle and Shewchuk)
- Marshall Bern, David Eppstein and John Gilbert, Provably good mesh generation, Journal of Computer and System Sciences 48(3), 1994, 384 to 409, the warping of a background grid onto the boundary (general locator), which Labelle and Shewchuk adopt
- D. M. Y. Sommerville, Space-filling tetrahedra in Euclidean space, Proceedings of the Edinburgh Mathematical Society 41, 49 to 57, the tetrahedra that tile space, among them the BCC tetrahedron (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag B7WM22 Edit this page History Report an error Markdown