Algorithm Search⌘K

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.

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
Properties
deterministicnot exactiterative
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 ff, 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 10.7843°10.7843° and 164.7373°164.7373° 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 f:R3→Rf : \mathbb{R}^3 \to \mathbb{R} that is positive inside the domain and negative outside, a way to find the point where f=0f = 0 on a segment, and a lattice spacing hh. The output is a set of tetrahedra that meet face to face (a tetrahedralization), whose boundary vertices lie on the surface f=0f = 0. On this page f(x)=r2−∣x−c∣2f(x) = r^2 - |x - c|^2, 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 αlong=0.28511\alpha_{\text{long}} = 0.28511 and αshort=0.39882\alpha_{\text{short}} = 0.39882, every dihedral angle of every output tetrahedron lies in [10.7843°,164.7373°][10.7843°, 164.7373°], and every plane angle in [9.0454°,154.9845°][9.0454°, 154.9845°]. 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 0.0001°0.0001°: some cut functions produce these angles. This page does not repeat that proof.
  • Proved here. The BCC tetrahedron has dihedral angles 60°60° (four times) and 90°90° (twice), volume h3/12h^3/12, circumradius 5/16 h\sqrt{5/16}\,h and radius-edge ratio 5/12≈0.6455\sqrt{5/12} \approx 0.6455. 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 [19.08°,135.68°][19.08°, 135.68°], and over 25 random balls with r/hr/h between 1.61.6 and 6.26.2 the worst were 18.48°18.48° and 149.78°149.78°. Labelle and Shewchuk show meshes of real models with all angles in [14°,158°][14°, 158°]. 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 0.1°0.1° 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 1/21/\sqrt2 while its dihedral angles approach 0°0° and 180°180°. 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 2.212.21.

The algorithm

A lattice point has doubled coordinates (i,j,k)(i, j, k), all even or all odd, at position h2(i,j,k)\frac{h}{2}(i, j, k). The even points form the cubic lattice and the odd points the shifted lattice. Black edges join neighbors at distance hh along an axis; red edges join a cube corner to a cube center, length 32h\frac{\sqrt3}{2} h. Each BCC tetrahedron has two opposite black edges and four red edges. A lattice point qq is violated if a cut point on one of its edges lies at less than α\alpha times the edge length from qq, with α=αlong\alpha = \alpha_{\text{long}} on black edges and αshort\alpha_{\text{short}} on red edges.

  1. ISOSURFACE-STUFFING(f, h)
  2. 1compute f(q) at every lattice point q in a box around the domain
  3. 2for each edge pq with f(p) f(q) < 0, find its cut point, the zero of f on pq
  4. 3for each lattice point q, in a fixed order:
  5. 4if q is violated by a cut point on one of its edges that still has one:
  6. 5move q to the nearest such cut point; set f(q) ← 0, which removes the cut points on its edges
  7. 6for each BCC tetrahedron τ, by the signs of f at its vertices:
  8. 7no positive vertex: drop τ (also when all four are zero)
  9. 8no negative vertex: output τ
  10. 9one positive vertex a: output the tetrahedron of a, the zero vertices and the cut points on the edges from a
  11. 10two positive, one zero, one negative: output the pyramid over the quadrilateral of the face ab with the negative vertex, split into 2
  12. 11two positive, two negative: output the prism between edge ab and the four cut points, split into 3
  13. 12three positive, one negative: output the truncated tetrahedron, a prism, split into 3
  14. 13output the pieces, with the moved positions of the moved points
  15. 14return the output tetrahedra

Each quadrilateral on a face of τ\tau has corners a,ba, b (positive) and the cut points cc on bxbx and dd on axax, where xx is the negative vertex of the face. It is split by one of the diagonals acac or bdbd:

  • if axax or bxbx is black, the diagonal that ends at the cut point on that black edge;
  • otherwise abab is black and the Parity Rule applies: if aa and bb are on the cubic lattice, take acac when an odd number of the coordinates of aa are greater than those of cc, and bdbd otherwise; on the shifted lattice the choice is reversed.

The quadrilateral of a two-positive prism that lies on the surface is inside τ\tau, 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 qq 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 (0.03,−0.02,0.01)(0.03, -0.02, 0.01) and r=1r = 1, and h=1/4h = 1/4. 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 [19.08°,135.68°][19.08°, 135.68°], inside the proved range [10.78°,164.74°][10.78°, 164.74°]. The mesh has volume 4.12224.1222, against 4.18884.1888 for the ball, and every boundary vertex lies on the sphere up to rounding: ∣f∣<3⋅10−16|f| < 3 \cdot 10^{-16} there. The radius-edge ratio reaches 2.212.21. Without step 3, that is with α=0\alpha = 0, the same input gives 6628 tetrahedra with a smallest dihedral angle of 0.17°0.17° and a largest of 169.62°169.62°: 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 h3/12h^3/12 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 τ\tau 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 abxabx and for baxbax. 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 α\alpha 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 ωh\omega h from the surface is classified correctly for a constant ω\omega given in Theorem 2, and that for a smooth surface with distance dMd_M to the medial axis the mesh boundary is within ωh\omega h of the surface in both directions when dM>ωhd_M > \omega h, and is ambient isotopic to it when h/dMh / d_M 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 Λ={(i,j,k)∈Z3:i≡j≡k(mod2)}\Lambda = \{(i, j, k) \in \mathbb{Z}^3 : i \equiv j \equiv k \pmod 2\} and h=2h = 2. Then:

  1. the BCC tetrahedron T0=(p0,p1,p2,p3)=((0,0,0),(2,0,0),(1,1,1),(1,−1,1))T_0 = (p_0, p_1, p_2, p_3) = ((0,0,0), (2,0,0), (1,1,1), (1,-1,1)) has dihedral angles 90°90° at its two black edges and 60°60° at its four red edges, volume 2/32/3 (that is h3/12h^3/12), circumradius 5/2\sqrt{5}/2 (that is 5/16 h\sqrt{5/16}\,h) and radius-edge ratio 5/12\sqrt{5/12};
  2. its circumsphere has no other point of Λ\Lambda inside or on it, and the BCC tetrahedra tile R3\mathbb{R}^3 face to face;
  3. 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 [10.7843°,164.7373°][10.7843°, 164.7373°] 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 p0p1p_0 p_1 and p2p3p_2 p_3 have squared length 4, and the four red edges, such as p2−p0=(1,1,1)p_2 - p_0 = (1,1,1), have squared length 3. The volume is 16det⁡[(2,0,0),(1,1,1),(1,−1,1)]=16⋅2⋅2=23\frac16 \det[(2,0,0), (1,1,1), (1,-1,1)] = \frac16 \cdot 2 \cdot 2 = \frac23, and 12⋅23=812 \cdot \frac23 = 8 is the volume of a cell of the cubic lattice 2Z32\mathbb{Z}^3. The point o=(1,0,12)o = (1, 0, \frac12) has ∣o−p∣2=1+14=54|o - p|^2 = 1 + \frac14 = \frac54 for all four vertices, so it is the circumcenter, R=5/2R = \sqrt5/2 and R2/ℓmin⁡2=5/43=512R^2/\ell_{\min}^2 = \frac{5/4}{3} = \frac{5}{12}.

For the dihedral angles, take the outward normals n0=(1,0,1)n_0 = (1, 0, 1), n1=(−1,0,1)n_1 = (-1, 0, 1), n2=(0,−1,−1)n_2 = (0, -1, -1) and n3=(0,1,−1)n_3 = (0, 1, -1) of the faces opposite p0,…,p3p_0, \dots, p_3. Each is orthogonal to the edges of its face, and nk⋅(pk−q)<0n_k \cdot (p_k - q) < 0 for a vertex qq of that face, so it points away from pkp_k. The dihedral angle at the edge pipjp_i p_j has cos⁡θ=−nk⋅nl/(∣nk∣∣nl∣)\cos\theta = -n_k \cdot n_l / (|n_k||n_l|), where k,lk, l are the other two indices, and ∣nk∣2=2|n_k|^2 = 2 for all kk. At p0p1p_0 p_1: −n2⋅n3/2=−(−1+1)/2=0-n_2 \cdot n_3 / 2 = -(-1 + 1)/2 = 0. At p2p3p_2 p_3: −n0⋅n1/2=−(−1+1)/2=0-n_0 \cdot n_1 / 2 = -(-1 + 1)/2 = 0. At p0p2p_0 p_2: −n1⋅n3/2=−(−1)/2=12-n_1 \cdot n_3 / 2 = -(-1)/2 = \frac12. At p0p3p_0 p_3: −n1⋅n2/2=−(−1)/2=12-n_1 \cdot n_2 / 2 = -(-1)/2 = \frac12. At p1p2p_1 p_2: −n0⋅n3/2=−(−1)/2=12-n_0 \cdot n_3 / 2 = -(-1)/2 = \frac12. At p1p3p_1 p_3: −n0⋅n2/2=−(−1)/2=12-n_0 \cdot n_2 / 2 = -(-1)/2 = \frac12. So the black edges have 90°90° and the red edges 60°60°.

Step 2: emptiness and tiling. Let q∈Λq \in \Lambda with ∣q−o∣2≤54|q - o|^2 \le \frac54, that is (q1−1)2+q22+(q3−12)2≤54(q_1 - 1)^2 + q_2^2 + (q_3 - \frac12)^2 \le \frac54. Then ∣q3−12∣≤52<32|q_3 - \frac12| \le \frac{\sqrt5}{2} < \frac32, so q3∈{0,1}q_3 \in \{0, 1\} and (q3−12)2=14(q_3 - \frac12)^2 = \frac14, which leaves (q1−1)2+q22≤1(q_1 - 1)^2 + q_2^2 \le 1. If qq is even, q1−1q_1 - 1 is odd, so (q1−1)2=1(q_1 - 1)^2 = 1 and q2=0q_2 = 0, q3=0q_3 = 0: these are p0p_0 and p1p_1. If qq is odd, q1−1q_1 - 1 is even, so q1=1q_1 = 1, and q2=±1q_2 = \pm 1, q3=1q_3 = 1: these are p2p_2 and p3p_3. So no other lattice point lies inside or on the circumsphere. The nearest ones, such as (0,0,2)(0, 0, 2), are at squared distance 134\frac{13}{4} from oo.

Every BCC tetrahedron (p,p+2ei,c,c′)(p, p + 2e_i, c, c') listed by bcc_tetrahedra is the image of T0T_0 under a symmetry of Λ\Lambda: 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 Λ\Lambda, and each is a cell of the Delaunay subdivision of Λ\Lambda. 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, 12⋅23=812 \cdot \frac23 = 8, is the volume of one cell of 2Z32\mathbb{Z}^3. A periodic family of interior-disjoint tetrahedra whose volume per period equals the volume of a period covers space. So the BCC tetrahedra tile R3\mathbb{R}^3 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 a,ba, b be positive and xx negative on the face, with cut points cc on bxbx and dd on axax; the diagonals are acac and bdbd. If axax is black the rule takes bdbd, the diagonal at the cut point on axax, whichever of a,ba, b is named first, and likewise if bxbx is black. Otherwise abab is black, along an axis ii, and xx lies on the other lattice with xi=ai+bi2x_i = \frac{a_i + b_i}{2} and xk=ak±1x_k = a_k \pm 1 for k≠ik \ne i. Since cc lies strictly inside the segment bxbx, ak>cka_k > c_k holds exactly when 2ak>bk+xk2 a_k > b_k + x_k. For k=ik = i this reads ai>bia_i > b_i; for k≠ik \ne i it reads ak>xka_k > x_k, because bk=akb_k = a_k. Exchanging aa and bb (and so cc and dd) changes the test for k=ik = i into bi>aib_i > a_i and leaves the others unchanged. Exactly one of ai>bia_i > b_i and bi>aib_i > a_i holds, so the two counts have opposite parity. On the cubic lattice, the rule for (a,b)(a, b) takes acac if its count is odd and bdbd if it is even, and the rule for (b,a)(b, a) takes bdbd if its count is odd and acac 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 FF 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 FF has a positive vertex, inspection of L8 to L12 shows that the output of a tetrahedron τ⊃F\tau \supset F meets FF in: all of FF if FF has no negative vertex; the triangle of the positive vertex and the zero vertices or cut points on its other two edges if FF has one positive and some negative vertex; and the quadrilateral a,b,c,da, b, c, d of Step 3a, split by the rule, if FF has two positive vertices and one negative. (In L10, for instance, the face abdabd carries the split quadrilateral, the faces azdazd and bzdbzd the triangles azd′a z d' with d′d' the cut point, and the face abzabz is whole.) These triangles depend only on FF and its values, so both tetrahedra produce the same ones. If FF has no positive vertex, the output of τ\tau meets FF in a set of dimension at most one, except when all three vertices of FF are zero and the fourth vertex of τ\tau is positive: then FF is a face of the output. So either both sides output FF as a face, or one side does and FF is a boundary face with its three vertices on the surface.

Step 3c: the prisms split. A prism with bottom b0b1b2b_0 b_1 b_2, top t0t1t2t_0 t_1 t_2 and a diagonal on each quadrilateral bibi+1ti+1tib_i b_{i+1} t_{i+1} t_i splits into three tetrahedra with these diagonals if some vertex vv is the end of two of them: take the tetrahedron from vv to the opposite triangle and the pyramid from vv 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 a,b,ca, b, c positive and dd negative, dd lies on one black edge dydy of τ\tau with y∈{a,b,c}y \in \{a, b, c\}. Both faces of τ\tau that contain dydy take the diagonal at the cut point on dydy, which is then the end of two diagonals.

In L11, with a,ba, b positive and c,dc, d negative, the faces abcabc and abdabd carry two of the diagonals. If abab is red, the black edges of τ\tau are ac,bdac, bd or ad,bcad, bc; say acac and bdbd. Then abcabc takes bb to the cut point on acac, and abdabd takes aa to the cut point on bdbd: no common end. If abab is black along axis ii, so is cdcd, along an axis m≠im \ne i, with cm=am±1c_m = a_m \pm 1, dm=am∓1d_m = a_m \mp 1 and ck=dkc_k = d_k for k≠mk \ne m. By Step 3a, the counts of aa for the faces abcabc and abdabd differ only at the coordinate mm, where exactly one of am>cma_m > c_m and am>dma_m > d_m holds. So the counts have opposite parity, one face takes the diagonal from aa and the other the diagonal from bb, and again there is no common end. In both cases the third quadrilateral lies on the surface inside τ\tau, 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. ■\blacksquare

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 O(N)O(N) evaluations and root findings, with hashing for the lattice, and the space is O(N+k)O(N + k). With a uniform lattice NN grows as h−3h^{-3}. The graded version uses an octree, so the count grows as h−2h^{-2} 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. [10.7843°,164.7373°][10.7843°, 164.7373°] for the parameters on this page, by a computer-assisted proof, tight to within 0.0001°0.0001°.
  • Boundary fit. Every vertex on the mesh boundary lies on the surface f=0f = 0.
  • 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 60°60° or 90°90°.

Variants and improvements

  • Other parameters. Table 1 of the paper gives several choices of (αlong,αshort)(\alpha_{\text{long}}, \alpha_{\text{short}}). Optimizing the largest angle instead gives [8.9716°,158.7403°][8.9716°, 158.7403°] with α=(0.26649,0.36918)\alpha = (0.26649, 0.36918). Safe variants, in which no BCC tetrahedron can invert during warping, give [9.3171°,161.6432°][9.3171°, 161.6432°] or [9.0551°,160.5331°][9.0551°, 160.5331°], and ordered warping gives [9.7766°,163.5685°][9.7766°, 163.5685°].
  • Both sides. The double-sided rows of Table 1 mesh the inside and the outside with compatible tetrahedra, with weaker bounds: [6.4917°,164.1013°][6.4917°, 164.1013°] and [7.6872°,168.0481°][7.6872°, 168.0481°].
  • 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 1.66°1.66°.
  • Linear cut points. Placing each cut point by linear interpolation of ff 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 30°30° and 135°135° 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 (0.17°0.17° 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 hh are lost or meshed with the wrong topology. Theorem 3 needs hh small against the distance dMd_M 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.

isosurface_stuffing.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example