Algorithm Search⌘K

Algorithmadvanced

Shewchuk's tetrahedral Delaunay refinement

Also called 3D Delaunay refinement.

Refines a Delaunay tetrahedral mesh of a polyhedral domain by inserting circumcenters of bad tetrahedra and splitting encroached faces, bounding the radius-edge ratio.

Time
O(n^2) worst
Space
O(n^2) extra
Where
n = the number of output vertices
Properties
deterministicexactiterative
Origin
Jonathan Richard Shewchuk, 1998

Shewchuk's tetrahedral Delaunay refinement builds a tetrahedral mesh of a polyhedral domain by keeping a Delaunay tetrahedralization and adding vertices to it. It splits boundary edges and boundary faces that are too close to other vertices, and it inserts the circumcenter of every tetrahedron whose radius-edge ratio exceeds a bound BB. Shewchuk (1998) proved that it stops, with every ratio at most BB, for every B≥2B \ge 2 on inputs whose angles between incident edges and faces are at least 90°90°, and that the mesh is graded when B>2B > 2. It is the three-dimensional form of Ruppert's algorithm, and mesh generators such as TetGen use refinement of this kind. A ratio bound does not exclude slivers, so the output may still contain nearly flat tetrahedra.

In plain words

Start with the Delaunay tetrahedralization of the corners of the domain. Then repeat three rules, in order of priority. If a boundary edge has a vertex inside or on the sphere that has the edge as a diameter, add the edge's midpoint. If a boundary triangle has a vertex inside or on its smallest sphere, add the triangle's circumcenter, unless that point would crowd a boundary edge; then split the edge instead. If a tetrahedron has a large circumsphere compared with its shortest edge, add the center of that sphere, unless it would crowd the boundary. Each new vertex lands in empty space, far from the others, so the edges cannot get shorter without limit, and the loop stops. Slivers can pass every one of these tests.

The problem

The input is a piecewise linear complex (PLC) XX: a set of vertices, segments and polygonal facets in R3\mathbb{R}^3, closed under intersection, that bounds the domain. The output is a Delaunay tetrahedralization of a point set that contains the vertices of XX, that conforms to XX (each segment is a union of mesh edges, the subsegments, and each facet a union of mesh triangles, the subfacets), and in which every tetrahedron has circumradius RR and shortest edge ℓ\ell with R/ℓ≤BR / \ell \le B.

The local feature size lfs(p)\mathrm{lfs}(p) of a point pp is the radius of the smallest ball centered at pp that meets two features of XX (vertices, segments or facets) that do not intersect each other. It is 11-Lipschitz and positive on the domain; the mesh sizing function page uses it as a target size. The insertion radius rvr_v of a vertex vv is the distance from vv to the nearest other vertex at the moment vv is inserted, which is the length of the shortest edge at vv just after a Delaunay insertion.

This page makes three kinds of claim.

  • Proved bound, cited. If no two incident segments or facets meet at an angle below 90°90° (Shewchuk's projection condition: the orthogonal projection of one of two intersecting constraints onto the other does not meet the interior of the other), then for every B≥2B \ge 2 the algorithm stops, and every tetrahedron has radius-edge ratio at most BB. For B>2B > 2, Theorems 5 and 6 bound every insertion radius from below by lfs\mathrm{lfs} divided by DT=B+1+2B−2D_T = \frac{B + 1 + \sqrt2}{B - 2} for a tetrahedron circumcenter, DF=(1+2)B+2B−2D_F = \frac{(1 + \sqrt2) B + \sqrt2}{B - 2} for a subfacet circumcenter and DS=(3+2)BB−2D_S = \frac{(3 + \sqrt2) B}{B - 2} for a subsegment midpoint, and every vertex is at distance at least lfs(v)/(DS+1)\mathrm{lfs}(v) / (D_S + 1) from its nearest neighbor. For B=2.5B = 2.5 these are DT≈9.83D_T \approx 9.83, DF≈14.90D_F \approx 14.90 and DS≈22.07D_S \approx 22.07, so the spacing can be about 23 times below the local feature size.
  • Proved here. For B=2B = 2, a sketch of termination by insertion radius, with every edge at least lfsmin⁡/2\mathrm{lfs}_{\min}/2 long, where lfsmin⁡\mathrm{lfs}_{\min} is the smallest local feature size in the domain. See proofs/correctness.md. It rests on Shewchuk's Lemma 3, which is cited.
  • Measured, no guarantee. The constants are far worse than what happens. In the example below the shortest edge is 0.560.56 against a proved 0.1250.125. On the example of Shewchuk's Figure 13 the spacing with B=2.5B = 2.5 is 9 times below the local feature size, not 23, and the program terminates down to B=1.05B = 1.05, where no proof applies, though it fails to terminate at B=1.04B = 1.04. Inputs with angles below 90°90° also usually work in practice.

A radius-edge bound does not remove slivers. A sliver has four vertices near a great circle of its circumsphere, so its radius-edge ratio can be as small as 1/2≈0.711/\sqrt2 \approx 0.71 while its dihedral angles approach 0°0° and 180°180°. Every rule above is blind to it. Shewchuk's Section 8 says the only proved guarantee for sliver removal at that time, Chew's, was too weak to give any practical assurance, and that there was no guarantee that slivers can be removed. Sliver exudation proves a dihedral angle bound, with a tiny constant.

The algorithm

A vertex encroaches a subsegment if it lies inside or on its diametral sphere, the smallest sphere through its two ends. A vertex off the plane of a subfacet encroaches it if it lies inside or on its equatorial sphere, the smallest sphere through its three corners. A tetrahedron is skinny if R/ℓ>BR / \ell > B.

  1. DELAUNAY-REFINE(X, B)
  2. 1T ← the Delaunay tetrahedralization of the vertices of X; queue every skinny tetrahedron
  3. 2repeat while one of the rules below applies, in this order:
  4. 3if some subsegment s is encroached: insert the midpoint of s
  5. 4else if some subfacet f is encroached:
  6. 5c ← the circumcenter of f
  7. 6if c encroaches a subsegment s: reject c and split s as in L3
  8. 7else insert c
  9. 8else if some tetrahedron t is skinny:
  10. 9c ← the circumcenter of t
  11. 10if c encroaches a subsegment or subfacet: reject c, keep t queued, and split that feature as in L3 or L4 to L7
  12. 11else insert c
  13. 12return T
  14. 13insert v: remove every tetrahedron whose circumsphere has v strictly inside, and join v to each face of the hole (Bowyer-Watson)

Insertion (L13) is the Bowyer-Watson algorithm, so the mesh stays Delaunay. Inserting a vertex on a subsegment or subfacet replaces it by two subsegments or three or more subfacets. A rejected circumcenter is never inserted. When it encroaches several subfacets, Shewchuk's analysis splits one that contains its orthogonal projection, and the implementation does the same.

The implementation takes a box [0,a]×[0,b]×[0,c][0, a] \times [0, b] \times [0, c] with integer sides, its 8 corners, 12 edges and 6 faces, plus optional input vertices strictly inside. All input angles are 90°90°, so the projection condition holds. The domain is convex, so the subfacets are the faces of the mesh on the box, and an empty equatorial sphere makes them a Delaunay triangulation of each facet. Coordinates are integers in units of 2−202^{-20}. Each midpoint or circumcenter is computed exactly and rounded once to this grid, and every test (orientation, insphere, encroachment, ratio) is exact integer or rational arithmetic. Rounding keeps a point on its box edge or face, since those coordinates are integers already. The implementation keeps a set of features found encroached and tests each new vertex against every feature and each new feature against every vertex, which makes each step O(n)O(n).

Example

Take the box [0,4]×[0,3]×[0,2][0, 4] \times [0, 3] \times [0, 2] with two input vertices inside, at (1,1,12)(1, 1, \frac12) and (52,2,1)(\frac52, 2, 1), and B=2B = 2. The steps come from the implementation, and the test file checks the totals.

Steps Rule What happens
start L1 10 vertices and 18 tetrahedra; 4 box edges and 12 box triangles are encroached by the inner vertices
1 to 5 L3 5 box edges split at their midpoints, such as (0,32,0)(0, \frac32, 0)
6 to 14 L4 to L6 9 subfacet circumcenters rejected, because each encroaches a subsegment; that subsegment is split instead
15 to 21 L7 7 subfacet circumcenters inserted, such as (2516,32,0)(\frac{25}{16}, \frac32, 0) with insertion radius 0.900.90
22, 23 L4 to L6 2 more rejections and subsegment splits
end L12 33 vertices (10 input, 16 on edges, 7 on faces) and 66 tetrahedra; no skinny tetrahedron was left to split

The largest radius-edge ratio is 1.981.98. The shortest edge is 0.55990.5599. Here the nearest pair of non-intersecting features is the vertex (1,1,12)(1, 1, \frac12) and the face z=0z = 0, at distance 12\frac12, so lfsmin⁡≥14\mathrm{lfs}_{\min} \ge \frac14 and the proof guarantees edges of at least 18\frac18: the measured spacing is 4.5 times better. The dihedral angles range from 6.32°6.32° to 166.55°166.55°. The worst tetrahedron, with vertices (1,1,12)(1, 1, \frac12), (52,2,1)(\frac52, 2, 1), (2516,32,0)(\frac{25}{16}, \frac32, 0) and (2516,32,2)(\frac{25}{16}, \frac32, 2), has radius-edge ratio 1.151.15 and dihedral angles 6.3°6.3° and 166.5°166.5°: a sliver that passes the test. With B=6/5B = 6/5, below the proved threshold, the same input stops at 63 vertices and 167 tetrahedra, with 4 tetrahedron circumcenters inserted, ratio at most 1.21.2, and still a 4.98°4.98° dihedral angle.

Correctness

The output is what it should be when the loop stops. Bowyer-Watson insertion keeps the tetrahedralization Delaunay. When L2 finds nothing to do, no subsegment is encroached, so each one has an empty diametral sphere and is an edge of the Delaunay tetrahedralization; likewise each subfacet has an empty equatorial sphere and is a Delaunay face. So the mesh conforms to XX, and no tetrahedron is skinny. A circumcenter that lies outside the domain is separated from its tetrahedron by a subfacet, and it encroaches that subfacet (Chapter 8 of Cheng, Dey and Shewchuk), so a circumcenter that passes L10 lies in the domain. The implementation also checks that every inserted point lies in the box.

The loop stops. This is where B≥2B \ge 2 and the 90°90° condition enter. Shewchuk's Lemma 3 says that each new vertex vv either has rv≥lfs(v)r_v \ge \mathrm{lfs}(v) or has a parent pp, the vertex that caused it to be inserted, with rv≥C rpr_v \ge C\, r_p, where C=BC = B if vv is a tetrahedron circumcenter and C=1/2C = 1/\sqrt2 if vv is a subsegment midpoint or subfacet circumcenter. In the dataflow graph of Figure 12 the cycles are tetrahedron to tetrahedron (factor BB), through a subfacet or a subsegment (factor B/2B/\sqrt2), and through a subfacet and then a subsegment (factor B/2B/2). With B≥2B \ge 2 no cycle shrinks the radius, so by induction every tetrahedron circumcenter has rv≥lfsmin⁡r_v \ge \mathrm{lfs}_{\min}, every subfacet circumcenter rv≥lfsmin⁡/2r_v \ge \mathrm{lfs}_{\min}/\sqrt2 and every midpoint rv≥lfsmin⁡/2r_v \ge \mathrm{lfs}_{\min}/2. Every edge is then at least lfsmin⁡/2\mathrm{lfs}_{\min}/2, so disjoint balls of radius lfsmin⁡/4\mathrm{lfs}_{\min}/4 fit around the vertices, and a bounded domain holds only finitely many. The sketch is in proofs/correctness.md; the full proof, with the case analysis of Lemma 3 and the grading bound, is in Shewchuk (1998) and in Chapter 8 of Cheng, Dey and Shewchuk.

Why slivers survive. The analysis only bounds R/ℓR/\ell. A sliver has R/ℓR/\ell near 1/21/\sqrt2, so it is never skinny, and none of the rules ever looks at it. The insertion radius argument needs the new vertex to be far from all others, which a circumcenter is; the circumcenter of a sliver is also far from all others, but nothing asks for it.

The test file checks, on 8 inputs, that every tetrahedron has an empty circumsphere by the exact insphere test against all vertices, that every ratio is at most BB (compared exactly as squares), that the volumes are positive and add up to the box, that faces match in pairs with the unmatched ones on the box, that the subsegments are mesh edges and cover the 12 box edges, that nothing is encroached at the end, and, for B=2B = 2, that every insertion radius and every edge is at least the proved lfsmin⁡/2\mathrm{lfs}_{\min}/2.

Proof: With B = 2 and input angles of at least 90 degrees, DELAUNAY-REFINE stops with a conforming Delaunay mesh of radius-edge ratio at most 2 and every edge at least half the smallest local feature sizefull

Claim. Let XX be a piecewise linear complex that satisfies Shewchuk's projection condition (no two incident segments or facets meet at an angle below 90°90°), let B=2B = 2, and assume exact arithmetic. Let lfsmin⁡\mathrm{lfs}_{\min} be the infimum of the local feature size over the domain. Then:

  1. lfsmin⁡≥dmin⁡/2>0\mathrm{lfs}_{\min} \ge d_{\min}/2 > 0, where dmin⁡d_{\min} is the smallest distance between two features of XX that do not intersect;
  2. every vertex that DELAUNAY-REFINE inserts or rejects has insertion radius at least lfsmin⁡/2\mathrm{lfs}_{\min}/2, and every edge of every intermediate mesh has length at least lfsmin⁡/2\mathrm{lfs}_{\min}/2;
  3. the loop of L2 stops, and the output is a Delaunay tetrahedralization that conforms to XX and has radius-edge ratio at most 22 for every tetrahedron.

What is cited. Part 2 uses Lemma 3 of Shewchuk (1998) for the subsegment and subfacet cases. Its case analysis, which is where the projection condition is used, is not repeated here; we prove the tetrahedron case and show where the factor 1/21/\sqrt2 comes from. The full proof is in Shewchuk (1998), Sections 5 and 6, and in Chapter 8 of Cheng, Dey and Shewchuk, Delaunay Mesh Generation. The proof also says nothing about dihedral angles, and slivers survive; see the last step.

Step 1: the local feature size is bounded below. A ball that meets two disjoint closed sets has diameter at least their distance. So every ball centered anywhere that meets two non-intersecting features has radius at least dmin⁡/2d_{\min}/2, and lfs(x)≥dmin⁡/2\mathrm{lfs}(x) \ge d_{\min}/2 for every xx. Since XX has finitely many features, all closed, dmin⁡>0d_{\min} > 0. For the box [0,a]×[0,b]×[0,c][0, a] \times [0, b] \times [0, c] with inner input vertices, the pairs that do not intersect are opposite faces, a face and an edge or corner it misses, two edges that do not meet, an inner vertex and any face, edge or corner, and two inner vertices; the smallest of their distances is min⁡(a,b,c)\min(a, b, c) or the distance from an inner vertex to a face or to another inner vertex.

Step 2: the insertion radius of a circumcenter. Let tt be a skinny tetrahedron of the current Delaunay mesh, with circumcenter vv, circumradius RR and shortest edge pqpq of length ℓ\ell, so R>BℓR > B \ell. The circumsphere of tt has no vertex strictly inside, and the four vertices of tt lie on it, so the nearest vertex to vv is at distance exactly RR: rv=Rr_v = R, whether vv is then inserted or rejected. Say qq was inserted after pp. When qq was inserted, pp was already there, so ℓ≥rq\ell \ge r_q, and rv=R>Brqr_v = R > B r_q. If pp and qq are both input vertices, they are two features that do not intersect, so ℓ≥dmin⁡≥lfsmin⁡\ell \ge d_{\min} \ge \mathrm{lfs}_{\min}, hence rv>B lfsmin⁡r_v > B\, \mathrm{lfs}_{\min}. This is the case C=BC = B of Lemma 3.

Step 3: where 1/21/\sqrt2 comes from. Let a rejected circumcenter pp encroach a subsegment abab with midpoint vv and half-length ρ\rho, and suppose for this illustration that no vertex lies in the closed diametral ball of abab, so that rv=ρr_v = \rho. The angle apbapb is at least 90°90°, so ∣pa∣2+∣pb∣2≤∣ab∣2=4ρ2|pa|^2 + |pb|^2 \le |ab|^2 = 4\rho^2, and the nearer of a,ba, b is within 2 ρ\sqrt2\,\rho of pp. Then rp≤2 ρr_p \le \sqrt2\,\rho and rv≥rp/2r_v \ge r_p/\sqrt2.

Let pp instead encroach a subfacet ff with circumcenter vv and circumradius ρ\rho, where ff contains the orthogonal projection p′p' of pp onto its plane. Every point of a triangle is within its circumradius of the nearest corner: the largest distance to the nearest corner over the triangle is attained at the circumcenter if it lies in the triangle, and otherwise at the midpoint of a side, at most half that side away. So ∣p′−x∣≤ρ|p' - x| \le \rho for some corner xx. And ∣p−p′∣2+∣p′−v∣2=∣p−v∣2≤ρ2|p - p'|^2 + |p' - v|^2 = |p - v|^2 \le \rho^2, so ∣p−p′∣≤ρ|p - p'| \le \rho, and ∣p−x∣2=∣p−p′∣2+∣p′−x∣2≤2ρ2|p - x|^2 = |p - p'|^2 + |p' - x|^2 \le 2\rho^2. Again rp≤2 ρ=2 rvr_p \le \sqrt2\,\rho = \sqrt2\, r_v when the equatorial ball holds no other vertex.

Shewchuk's Lemma 3 handles the general case: every inserted vertex vv has rv≥lfs(v)r_v \ge \mathrm{lfs}(v), or it has a parent pp (the vertex that caused its insertion) with rv≥Crpr_v \ge C r_p, where C=BC = B if vv is a tetrahedron circumcenter and C=1/2C = 1/\sqrt2 if vv is a subfacet circumcenter or a subsegment midpoint. The parent of a subfacet circumcenter is a rejected tetrahedron circumcenter, and the parent of a subsegment midpoint is a rejected tetrahedron or subfacet circumcenter. The projection condition is what rules out the other cases, such as a vertex on one facet encroaching a subsegment of an incident facet.

Step 4: induction. Order all vertices, inserted and rejected, by the time they are created, and give an input vertex the insertion radius lfsmin⁡\mathrm{lfs}_{\min}, a lower bound for its distance to every other input vertex by Step 1. We show:

  • a tetrahedron circumcenter has rv≥lfsmin⁡r_v \ge \mathrm{lfs}_{\min};
  • a subfacet circumcenter has rv≥lfsmin⁡/2r_v \ge \mathrm{lfs}_{\min}/\sqrt2;
  • a subsegment midpoint has rv≥lfsmin⁡/2r_v \ge \mathrm{lfs}_{\min}/2.

All three bounds are at least lfsmin⁡/2\mathrm{lfs}_{\min}/2, and the input vertices satisfy it. Take a new vertex vv and assume the bounds for all earlier ones. If rv≥lfs(v)r_v \ge \mathrm{lfs}(v), then rv≥lfsmin⁡r_v \ge \mathrm{lfs}_{\min} and all three hold. Otherwise:

  • vv is a tetrahedron circumcenter: rv≥2rp≥2⋅lfsmin⁡/2=lfsmin⁡r_v \ge 2 r_p \ge 2 \cdot \mathrm{lfs}_{\min}/2 = \mathrm{lfs}_{\min}, by Step 2 and the weakest bound for the parent;
  • vv is a subfacet circumcenter with a rejected tetrahedron circumcenter as parent: rv≥rp/2≥lfsmin⁡/2r_v \ge r_p/\sqrt2 \ge \mathrm{lfs}_{\min}/\sqrt2;
  • vv is a subsegment midpoint with a rejected tetrahedron circumcenter as parent: rv≥lfsmin⁡/2≥lfsmin⁡/2r_v \ge \mathrm{lfs}_{\min}/\sqrt2 \ge \mathrm{lfs}_{\min}/2; with a rejected subfacet circumcenter as parent: rv≥12⋅lfsmin⁡2=lfsmin⁡/2r_v \ge \frac{1}{\sqrt2} \cdot \frac{\mathrm{lfs}_{\min}}{\sqrt2} = \mathrm{lfs}_{\min}/2.

This is the dataflow graph of Shewchuk's Figure 12: every cycle passes through a tetrahedron circumcenter, and the products along the cycles are BB, B/2B/\sqrt2 and B/2B/2, all at least 11 when B≥2B \ge 2. With B<2B < 2 the last cycle can shrink the radii, and the argument fails.

Step 5: edges and termination. An edge uvuv of any intermediate mesh, with vv inserted after uu, has ∣uv∣≥rv≥lfsmin⁡/2|uv| \ge r_v \ge \mathrm{lfs}_{\min}/2. An edge between two input vertices has length at least dmin⁡≥lfsmin⁡d_{\min} \ge \mathrm{lfs}_{\min}. So the open balls of radius lfsmin⁡/4\mathrm{lfs}_{\min}/4 around the vertices are disjoint, and they lie in the domain grown by lfsmin⁡/4\mathrm{lfs}_{\min}/4, a bounded set of volume VV. Hence there are at most V/(43π(lfsmin⁡/4)3)V / (\frac43 \pi (\mathrm{lfs}_{\min}/4)^3) vertices. Each pass of L2 inserts exactly one vertex: L3, L7 and L11 insert one, and a rejection in L6 or L10 is followed in the same pass by the insertion of a midpoint or a subfacet circumcenter. So the loop stops.

Step 6: the output. Bowyer-Watson insertion (L13) keeps the tetrahedralization Delaunay. When the loop stops, no subsegment is encroached, so each has a diametral ball with no vertex inside or on it except its ends; such a segment is an edge of the Delaunay tetrahedralization. No subfacet is encroached, so each has an equatorial ball free of vertices off its plane, and the vertices in its plane lie outside its circumcircle because the facet triangulation is Delaunay; such a triangle is a Delaunay face. So every subsegment and subfacet is in the mesh, and the mesh conforms to XX. No tetrahedron is skinny, so every radius-edge ratio is at most 22.

Step 7: what is not proved. Nothing above mentions dihedral angles. A sliver with vertices near a great circle of its circumsphere has R/ℓR/\ell close to 1/2<21/\sqrt2 < 2, so it is never skinny and L8 never looks at it, and it can be in the output. The implementation's example contains one, with ratio 1.151.15 and dihedral angles of 6.3°6.3° and 166.5°166.5°.

Remark on rounding. The implementation rounds each new vertex to a grid of spacing 2−202^{-20}, which moves it by at most 322−20\frac{\sqrt3}{2} 2^{-20} and changes no step of the argument by more than that amount. The tests check the bound of Step 5 with a slack of two grid units. ■\blacksquare

Complexity

Shewchuk reports that with good point location each insertion takes constant time in practice. In the worst case a Delaunay tetrahedralization of nn points has Θ(n2)\Theta(n^2) tetrahedra, so an insertion can take O(n)O(n) time and the whole refinement O(n2)O(n^2); the space is O(n2)O(n^2) in the worst case and O(n)O(n) for a mesh of bounded ratio, whose vertices have bounded degree by a result of Miller, Talmor, Teng and Walkington. The grading bound of Theorem 6 and a packing argument give n=O(∫Ωlfs(x)−3 dx)n = O\left(\int_\Omega \mathrm{lfs}(x)^{-3}\, dx\right) for B>2B > 2. The implementation is simpler: it tests each new vertex against every subsegment and subfacet and finds a tetrahedron in conflict by a scan when it has none, so each step costs O(n)O(n) and a run O(n2)O(n^2), enough for the few hundred vertices of the tests.

Properties

  • Proved quality. Radius-edge ratio at most BB for every B≥2B \ge 2, under the 90°90° input angle condition.
  • Proved grading for B>2B > 2. Edges at least lfs(v)/(DS+1)\mathrm{lfs}(v)/(D_S + 1) long, with the constants above.
  • No dihedral angle bound. Slivers can remain.
  • Conforming, with Steiner points. Segments and facets appear as unions of mesh edges and triangles; extra vertices are added on them.
  • Exact here. All predicates are exact; the only rounding is of new vertices to the grid.
  • Deterministic. The order of the queues fixes the output.

Variants and improvements

  • Small input angles. Shewchuk's thesis and Chapter 9 of Cheng, Dey and Shewchuk handle inputs with angles below 90°90° by protecting the region near sharp edges, at the cost of leaving some skinny tetrahedra near them. Protecting balls do this with weighted vertices.
  • Constrained Delaunay version. TetGen refines a constrained Delaunay tetrahedralization instead of a conforming one, which needs fewer Steiner points on the boundary; the input faces are first recovered by boundary recovery.
  • Sliver removal. Sliver exudation assigns weights to the vertices and proves a dihedral angle bound; Chew's 1997 method inserts a random point near the circumcenter of a sliver instead of the circumcenter itself.
  • Other insertion points. Inserting a point on the segment from the middle of the shortest edge to the circumcenter, instead of the circumcenter, gives fewer vertices in practice.
  • Smooth boundaries. Delaunay surface meshing refines a restricted Delaunay triangulation of a curved surface first, then this algorithm fills the volume.
  • Lattice methods. Isosurface stuffing proves dihedral angle bounds of about 10.78°10.78° but cannot keep sharp features.

When to use it

Use it when the domain is a polyhedron given as a PLC, the mesh must contain its segments and facets, and the sizes should grade from small near small features to large in the interior. Follow it by sliver removal or mesh improvement, such as topological mesh improvement or optimization-based smoothing, when the solver needs good dihedral angles. Do not use the plain algorithm with B<2B < 2 and expect a guarantee: it often works but nothing proves it.

Pitfalls

  • Taking the ratio bound for a quality guarantee. Slivers have small radius-edge ratios; check the dihedral angles too.
  • Small input angles. With incident faces at angles below 90°90°, splitting one feature can encroach the other forever. Either protect the sharp regions or accept skinny tetrahedra near them.
  • Wrong priorities. Inserting a tetrahedron circumcenter that encroaches the boundary puts a vertex too close to it; the proof needs it rejected and the feature split instead.
  • Inexact predicates. An insphere test with floating point can make the cavity of Bowyer-Watson not star-shaped and the mesh invalid. Use exact or adaptive predicates.
  • Circumcenters outside the domain. Without the encroachment rules, a circumcenter may lie outside a nonconvex domain.
  • BB too small. Shewchuk's example stops at B=1.05B = 1.05 and runs forever at B=1.04B = 1.04; set a vertex limit, as the implementation does.

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.

mg2geom.pyI0RawGitHub
# 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
tetrahedral_delaunay_refinement.py 307 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tetrahedral-delaunay-refinement/. The authors are listed in prov/VNAEW7.jsonl.

"""Shewchuk's tetrahedral Delaunay refinement (1998) for a box domain.

The input piecewise linear complex (PLC) is an axis-aligned box [0, a] x [0, b]
x [0, c] with integer sides, its 8 corners, 12 edges (segments) and 6 faces
(facets), plus optional input vertices inside the box. All its input angles are
90 degrees, so it satisfies Shewchuk's projection condition, and the refinement
terminates for every bound B >= 2 on the radius-edge ratio.

Coordinates are integers in units of 1/SCALE. A new vertex (a midpoint or a
circumcenter) is computed exactly and rounded once to this grid. Rounding keeps
a point on its box edge or face, since those coordinates are integers already.
Every predicate (orientation, insphere, encroachment, radius-edge test) is exact.

The domain is convex, so the faces of the tetrahedralization that lie on the box
are the subfacets: a face on the hull of a Delaunay tetrahedralization has an
empty circumcircle within its plane, so these faces form a 2D Delaunay
triangulation of each facet, as Shewchuk's algorithm keeps.
"""

from fractions import Fraction
from typing import Dict, List, Optional, Sequence, Set, Tuple

from mg2geom import circumcenter3, dist2, dot, insphere, orient3d, radius_edge2, sub, tri_circumcenter3

SCALE = 1 << 20

Tet = Tuple[int, int, int, int]
Face = Tuple[int, int, int]
Seg = Tuple[int, int]


def _round(p: Sequence[Fraction]) -> tuple:
    return tuple(int(round(x)) for x in p)


class Refiner:
    def __init__(self, sides: Sequence[int], inner: Sequence[Sequence] = (), B=2, max_vertices: int = 5000):
        if len(sides) != 3 or min(sides) <= 0 or any(int(s) != s for s in sides):
            raise ValueError("need three positive integer sides")
        self.L = tuple(int(s) * SCALE for s in sides)
        self.B2 = Fraction(B) ** 2
        if self.B2 < 1:
            raise ValueError("B must be at least 1")
        self.max_vertices = max_vertices
        self.pts: List[tuple] = []
        self.kind: List[str] = []
        self.r2: List[Optional[int]] = []  # squared insertion radius, None for input vertices
        self.tets: Set[Tet] = set()
        self.face_tets: Dict[Face, Set[Tet]] = {}
        self.subsegs: Set[Seg] = set()
        self.subfacets: Dict[Face, tuple] = {}  # face -> (circumcenter, R^2, (axis, value))
        self.enc_segs: Set[Seg] = set()  # subsegments found encroached (a superset; checked again on use)
        self.enc_facets: Set[Face] = set()
        self.skinny: List[Tet] = []
        self.rejected = 0
        corners = [(x, y, z) for x in (0, self.L[0]) for y in (0, self.L[1]) for z in (0, self.L[2])]
        for p in corners:
            self._add_point(p, "input", None)
        # the 8 corners are cospherical, so any triangulation of the box is Delaunay:
        # take the 6 tetrahedra around the diagonal from corner 0 to corner 7
        for path in ((1, 3), (1, 5), (2, 3), (2, 6), (4, 5), (4, 6)):
            self._add_tet((0, path[0], path[1], 7))
        for i in range(3):  # the 12 box edges are the first subsegments
            for p in range(8):
                q = p | (4 >> i)
                if q != p:
                    self._add_subseg((p, q))
        for p in inner:
            q = tuple(Fraction(x) * SCALE for x in p)
            if len(q) != 3 or any(x.denominator != 1 for x in q) or not all(0 < q[k] < self.L[k] for k in range(3)):
                raise ValueError("inner vertices must lie strictly inside the box, on the 1/SCALE grid")
            q = tuple(int(x) for x in q)
            if q in self.pts:
                raise ValueError("repeated inner vertex")
            self.insert(q, "input")

    # bookkeeping
    def _add_point(self, p: tuple, kind: str, r2) -> int:
        self.pts.append(p)
        self.kind.append(kind)
        self.r2.append(r2)
        return len(self.pts) - 1

    def plane(self, f: Face) -> Optional[Tuple[int, int]]:
        """The box face (axis, value) that contains the triangle f, if any."""
        P = [self.pts[v] for v in f]
        for k in range(3):
            for s in (0, self.L[k]):
                if all(p[k] == s for p in P):
                    return (k, s)
        return None

    def _add_subseg(self, s: Seg) -> None:
        s = tuple(sorted(s))
        self.subsegs.add(s)
        if any(self.seg_encroached_by(s, p) for p in self.pts):
            self.enc_segs.add(s)

    def _add_tet(self, t: Tet) -> None:
        P = [self.pts[v] for v in t]
        if orient3d(*P) < 0:
            t = (t[1], t[0], t[2], t[3])
        self.tets.add(t)
        for f in faces_of(t):
            self.face_tets.setdefault(f, set()).add(t)
            if f not in self.subfacets:
                pl = self.plane(f)
                if pl is not None:
                    cc = tri_circumcenter3(*[self.pts[v] for v in f])
                    self.subfacets[f] = (cc, dist2(cc, self.pts[f[0]]), pl)
                    if any(self.facet_encroached_by(f, p) for p in self.pts):
                        self.enc_facets.add(f)
        if radius_edge2(*[self.pts[v] for v in t]) > self.B2:
            self.skinny.append(t)

    def _remove_tet(self, t: Tet) -> None:
        self.tets.discard(t)
        for f in faces_of(t):
            s = self.face_tets[f]
            s.discard(t)
            if not s:
                del self.face_tets[f]
                self.subfacets.pop(f, None)

    # encroachment: a vertex inside or on the diametral sphere of a subsegment,
    # or inside or on the equatorial sphere of a subfacet and off its plane
    def seg_encroached_by(self, s: Seg, p: tuple) -> bool:
        a, b = self.pts[s[0]], self.pts[s[1]]
        return p != a and p != b and dot(sub(p, a), sub(p, b)) <= 0

    def facet_encroached_by(self, f: Face, p: tuple) -> bool:
        cc, R2, (k, s) = self.subfacets[f]
        return p[k] != s and dist2(p, cc) <= R2

    def encroached_subseg(self) -> Optional[Seg]:
        while self.enc_segs:
            s = min(self.enc_segs)
            if s in self.subsegs and any(self.seg_encroached_by(s, p) for p in self.pts):
                return s
            self.enc_segs.discard(s)
        return None

    def encroached_subfacet(self) -> Optional[Face]:
        while self.enc_facets:
            f = min(self.enc_facets)
            if f in self.subfacets and any(self.facet_encroached_by(f, p) for p in self.pts):
                return f
            self.enc_facets.discard(f)
        return None

    # Bowyer-Watson insertion
    def locate_conflict(self, p: tuple) -> Tet:
        for t in self.tets:
            if insphere(*[self.pts[v] for v in t], p) > 0:
                return t
        raise AssertionError("no tetrahedron in conflict")

    def insert(self, p: tuple, kind: str, start: Optional[Tet] = None) -> int:
        if not all(0 <= p[k] <= self.L[k] for k in range(3)):
            raise AssertionError("point outside the domain")
        r2 = min(dist2(p, q) for q in self.pts)
        if r2 == 0:
            raise AssertionError("duplicate point")
        if len(self.pts) >= self.max_vertices:
            raise RuntimeError("too many vertices")
        if start is None or start not in self.tets or insphere(*[self.pts[v] for v in start], p) <= 0:
            start = self.locate_conflict(p)
        cavity = {start}
        stack = [start]
        while stack:  # @line L13
            t = stack.pop()
            for f in faces_of(t):
                for u in self.face_tets[f]:
                    if u not in cavity and insphere(*[self.pts[v] for v in u], p) > 0:
                        cavity.add(u)
                        stack.append(u)
        boundary = []
        for t in cavity:
            for f in faces_of(t):
                if not any(u in cavity for u in self.face_tets[f] if u != t):
                    boundary.append(f)
        v = self._add_point(p, kind, None if kind == "input" else r2)
        for t in cavity:
            self._remove_tet(t)
        for f in boundary:
            if orient3d(*[self.pts[w] for w in f], p) == 0:
                # p lies in the plane of this face; it can only be a face on the box boundary
                if self.plane(f) is None:
                    raise AssertionError("cavity is not star-shaped")
                continue
            self._add_tet(f + (v,))
        # subsegments that contain the new vertex are split in two
        for s in [s for s in self.subsegs if between(self.pts[s[0]], p, self.pts[s[1]])]:
            self.subsegs.discard(s)
            self._add_subseg((s[0], v))
            self._add_subseg((v, s[1]))
        # the new vertex may encroach old subsegments and subfacets
        for s in self.subsegs:
            if self.seg_encroached_by(s, p):
                self.enc_segs.add(s)
        for f in self.subfacets:
            if self.facet_encroached_by(f, p):
                self.enc_facets.add(f)
        return v

    def tet_with_edge(self, s: Seg) -> Optional[Tet]:
        for t in self.tets:
            if s[0] in t and s[1] in t:
                return t
        return None

    # the refinement loop
    def split_subseg(self, s: Seg) -> None:
        a, b = self.pts[s[0]], self.pts[s[1]]
        m = _round(tuple(Fraction(x + y, 2) for x, y in zip(a, b)))
        self.insert(m, "segment", self.tet_with_edge(s))  # @line L3

    def split_subfacet(self, f: Face) -> None:
        c = _round(self.subfacets[f][0])  # @line L5
        enc = [s for s in sorted(self.subsegs) if self.seg_encroached_by(s, c)]
        if enc:  # @line L6
            self.rejected += 1
            self.split_subseg(enc[0])
            return
        self.insert(c, "facet", next(iter(self.face_tets[f])))  # @line L7

    def step(self) -> bool:
        s = self.encroached_subseg()
        if s is not None:
            self.split_subseg(s)
            return True
        f = self.encroached_subfacet()  # @line L4
        if f is not None:
            self.split_subfacet(f)
            return True
        while self.skinny:  # @line L8
            t = self.skinny.pop(0)
            if t not in self.tets:
                continue
            c = _round(circumcenter3(*[self.pts[v] for v in t]))  # @line L9
            enc = [s for s in sorted(self.subsegs) if self.seg_encroached_by(s, c)]
            encf = [g for g in sorted(self.subfacets) if self.facet_encroached_by(g, c)]
            if enc or encf:  # @line L10
                self.rejected += 1
                self.skinny.append(t)
                if enc:
                    self.split_subseg(enc[0])
                else:
                    self.split_subfacet(self.pick_subfacet(encf, c))
                return True
            self.insert(c, "tet", t)  # @line L11
            return True
        return False  # @line L12

    def pick_subfacet(self, encf: List[Face], c: tuple) -> Face:
        """Prefer an encroached subfacet that contains the projection of c, as in Shewchuk's analysis."""
        for g in encf:
            k, _ = self.subfacets[g][2]
            P = [self.pts[v] for v in g]
            q = list(c)
            q[k] = P[0][k]
            i, j = [x for x in range(3) if x != k]
            o = [orient2(P[a], P[(a + 1) % 3], q, i, j) for a in range(3)]
            if all(x >= 0 for x in o) or all(x <= 0 for x in o):
                return g
        return encf[0]

    def run(self) -> None:
        while self.step():  # @line L2
            pass

    # results in the original units
    def points(self) -> List[Tuple[Fraction, ...]]:
        return [tuple(Fraction(x, SCALE) for x in p) for p in self.pts]


def orient2(a, b, c, i, j):
    return (b[i] - a[i]) * (c[j] - a[j]) - (b[j] - a[j]) * (c[i] - a[i])


def between(a, p, b) -> bool:
    """True if p lies strictly between a and b on the segment ab."""
    d = sub(b, a)
    e = sub(p, a)
    cr = (d[1] * e[2] - d[2] * e[1], d[2] * e[0] - d[0] * e[2], d[0] * e[1] - d[1] * e[0])
    if cr != (0, 0, 0):
        return False
    t = dot(e, d)
    return 0 < t < dot(d, d)


def faces_of(t: Tet) -> List[Face]:
    return [tuple(sorted(t[:i] + t[i + 1 :])) for i in range(4)]


def delaunay_refine(sides: Sequence[int], inner: Sequence[Sequence] = (), B=2, max_vertices: int = 5000) -> Refiner:
    """Refine the box with the given integer sides until no subsegment or subfacet is
    encroached and every tetrahedron has radius-edge ratio at most B.

    Returns the Refiner; its fields pts (in units of 1/SCALE) and tets hold the mesh.
    """
    r = Refiner(sides, inner, B, max_vertices)  # @line L1
    r.run()
    return r
test_tetrahedral_delaunay_refinement.py 192 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tetrahedral-delaunay-refinement/. The authors are listed in prov/VNAEW7.jsonl.

import math
import random
from collections import Counter
from fractions import Fraction as F
from functools import lru_cache

import pytest

from mg2geom import dihedral_angles_deg, dist2, dot, insphere, orient3d, radius_edge2, sub, tri_circumcenter3
from tetrahedral_delaunay_refinement import SCALE, delaunay_refine

SIDES = (4, 3, 2)
EXAMPLE = ((1, 1, F(1, 2)), (F(5, 2), 2, 1))


def random_inner(seed, n):
    r = random.Random(seed)
    pts = set()
    while len(pts) < n:
        pts.add(tuple(F(r.randint(1, 4 * s - 1), 4) for s in SIDES))
    return tuple(sorted(pts))


CASES = [
    (SIDES, (), 2),
    (SIDES, EXAMPLE[:1], 2),
    ((3, 3, 3), ((1, 1, 1),), 2),
    (SIDES, EXAMPLE, 2),
    (SIDES, EXAMPLE, F(6, 5)),  # below the proved threshold: no guarantee, but it stops here
    (SIDES, random_inner(1, 4), 2),
    (SIDES, random_inner(2, 4), 2),
    (SIDES, random_inner(3, 3), 2),
]


@lru_cache(maxsize=None)
def run(i):
    sides, inner, B = CASES[i]
    return delaunay_refine(sides, inner, B)


def edges(tets):
    return {tuple(sorted((t[i], t[j]))) for t in tets for i in range(4) for j in range(i + 1, 4)}


def face_count(tets):
    return Counter(tuple(sorted(t[:k] + t[k + 1 :])) for t in tets for k in range(4))


def on_box(P, f, L):
    return any(all(P[v][k] == s for v in f) for k in range(3) for s in (0, L[k]))


def d_min(sides, inner):
    """The smallest distance between two input features that do not meet.

    For the box these are opposite faces (distance = side), an inner vertex and a
    face, or two inner vertices. Any ball that meets two such features has diameter
    at least this distance, so the local feature size is at least d_min / 2 everywhere.
    """
    d = [float(s) for s in sides]
    for p in inner:
        d += [float(min(F(p[k]), sides[k] - F(p[k]))) for k in range(3)]
        d += [math.sqrt(dist2(p, q)) for q in inner if q != p]
    return min(d)


@pytest.mark.parametrize("i", range(len(CASES)))
def test_delaunay_by_brute_force_and_radius_edge_bound(i):
    R = run(i)
    P = R.pts
    for t in R.tets:
        T = [P[v] for v in t]
        # empty circumsphere: no vertex of the mesh lies strictly inside, by the exact insphere test
        assert all(insphere(*T, p) <= 0 for p in P)
        # the quality goal: radius-edge ratio at most B, compared exactly as squares
        assert radius_edge2(*T) <= R.B2


@pytest.mark.parametrize("i", range(len(CASES)))
def test_conforming_mesh_of_the_box(i):
    R = run(i)
    P, L = R.pts, R.L
    vols = [orient3d(*[P[v] for v in t]) for t in R.tets]
    assert all(v > 0 for v in vols)
    assert sum(vols) == 6 * L[0] * L[1] * L[2]
    # face to face: an interior face lies in two tetrahedra, a boundary face in one, on the box
    for f, m in face_count(R.tets).items():
        assert m in (1, 2)
        assert (m == 1) == on_box(P, f, L)
    # every input vertex is a mesh vertex
    sides, inner, _ = CASES[i]
    for p in inner:
        assert tuple(int(F(x) * SCALE) for x in p) in P
    # the subsegments are mesh edges and cover the 12 box edges exactly
    E = edges(R.tets)
    assert set(R.subsegs) <= E
    length = Counter()
    for a, b in R.subsegs:
        d = sub(P[b], P[a])
        k = [j for j in range(3) if d[j] != 0]
        assert len(k) == 1
        length[k[0]] += abs(d[k[0]])
    assert [length[k] for k in range(3)] == [4 * L[k] for k in range(3)]


@pytest.mark.parametrize("i", range(len(CASES)))
def test_nothing_is_encroached_at_the_end(i):
    R = run(i)
    P, L = R.pts, R.L
    for a, b in R.subsegs:
        # closed diametral sphere: (p - a).(p - b) <= 0 means p is inside or on it
        assert all(dot(sub(p, P[a]), sub(p, P[b])) > 0 for p in P if p not in (P[a], P[b]))
    for f, m in face_count(R.tets).items():
        if m != 1:
            continue
        cc = tri_circumcenter3(*[P[v] for v in f])
        R2 = dist2(cc, P[f[0]])
        k = [k for k in range(3) if P[f[0]][k] == P[f[1]][k] == P[f[2]][k]][0]
        # closed equatorial sphere; vertices in the facet plane do not count
        assert all(dist2(p, cc) > R2 for p in P if p[k] != P[f[0]][k])


@pytest.mark.parametrize("i", [k for k in range(len(CASES)) if CASES[k][2] >= 2])
def test_edges_are_not_shorter_than_the_proved_bound(i):
    # For B = 2 every insertion radius is at least lfs_min / 2 >= d_min / 4.
    # Rounding to the 1/SCALE grid can cost at most a few grid units.
    R = run(i)
    sides, inner, _ = CASES[i]
    bound = d_min(sides, inner) / 4 * SCALE - 2
    for v, r2 in enumerate(R.r2):
        if r2 is not None:
            assert math.sqrt(r2) >= bound
    shortest = min(math.sqrt(dist2(R.pts[a], R.pts[b])) for a, b in edges(R.tets))
    assert shortest >= bound


def test_measured_spacing_is_far_better_than_the_bound():
    R = run(3)
    shortest = min(math.sqrt(dist2(R.pts[a], R.pts[b])) for a, b in edges(R.tets)) / SCALE
    bound = d_min(*CASES[3][:2]) / 4
    assert bound == 0.125
    assert shortest == pytest.approx(0.5599, abs=1e-4)
    assert shortest > 4 * bound


def test_a_sliver_has_a_small_radius_edge_ratio():
    # four points near the equator of the unit sphere: nearly flat, ratio near 1/sqrt(2)
    eps = F(1, 20)
    t = ((1, 0, 0), (-1, 0, 0), (0, 1, eps), (0, -1, eps))
    assert orient3d(*t) != 0
    assert radius_edge2(*t) < F(4, 7) < 4  # ratio below 0.76, far below B = 2
    d = dihedral_angles_deg(*t)
    assert min(d) < 6 and max(d) > 174


def test_slivers_survive_refinement():
    for i in (3, 4):
        R = run(i)
        P = R.pts
        worst = min(R.tets, key=lambda t: min(dihedral_angles_deg(*[P[v] for v in t])))
        W = [P[v] for v in worst]
        # it passes the radius-edge test, yet it is nearly flat
        assert radius_edge2(*W) <= R.B2
        assert min(dihedral_angles_deg(*W)) < 7
        assert max(dihedral_angles_deg(*W)) > 165


def test_example_counts():
    R = run(3)
    assert len(R.pts) == 33 and len(R.tets) == 66
    assert Counter(R.kind) == {"input": 10, "segment": 16, "facet": 7}
    d = [a for t in R.tets for a in dihedral_angles_deg(*[R.pts[v] for v in t])]
    assert min(d) == pytest.approx(6.3185, abs=1e-3)
    assert max(d) == pytest.approx(166.5462, abs=1e-3)
    R = run(4)
    assert len(R.pts) == 63 and len(R.tets) == 167
    assert Counter(R.kind)["tet"] == 4


def test_rejects_bad_input():
    with pytest.raises(ValueError):
        delaunay_refine((4, 3, 0))
    with pytest.raises(ValueError):
        delaunay_refine(SIDES, B=F(1, 2))
    with pytest.raises(ValueError):
        delaunay_refine(SIDES, ((0, 1, 1),))  # on the boundary, not strictly inside
    with pytest.raises(RuntimeError):
        delaunay_refine(SIDES, EXAMPLE, F(6, 5), max_vertices=40)

History

Chew gave the first provably good Delaunay refinement algorithm in the plane in 1989, and Ruppert (1995) proved a graded and size-optimal planar version. Dey, Bajaj and Sugihara (1992) and Chew (1997) generalized Delaunay refinement to three dimensions for point sets, with uniform meshes. Shewchuk, in his 1997 thesis and his 1998 paper, extended Ruppert's insertion radius analysis to tetrahedra and to PLC inputs, with the radius-edge bound of 2, graded meshes for B>2B > 2, and the condition that input angles be at least 90°90°. Cheng, Dey, Edelsbrunner, Facello and Teng then proved that sliver exudation removes slivers, and later work relaxed the angle condition. Si's TetGen refines a constrained Delaunay tetrahedralization in the same way.

References

  1. Jonathan Richard Shewchuk, Tetrahedral mesh generation by Delaunay refinement, Proceedings of the 14th Annual Symposium on Computational Geometry, 1998, 86 to 95, Section 4 (the algorithm, encroachment and its priorities), Section 5 (the projection condition), Lemma 3 and Figure 12 (insertion radii and the dataflow graph), Theorems 5 and 6 (grading constants), Section 8 (slivers and the measured results of Figure 13)
  2. Siu-Wing Cheng, Tamal K. Dey and Jonathan Richard Shewchuk, Delaunay Mesh Generation, CRC Press, 2013, Chapter 8, Tetrahedral meshing of PLCs (pages 185 to 204), the full termination and grading proofs; Chapter 9 for PLCs with small angles
  3. Jim Ruppert, A Delaunay refinement algorithm for quality 2-dimensional mesh generation, Journal of Algorithms 18(3), 1995, 548 to 585, the local feature size and the insertion radius argument in the plane (general locator)
  4. Tamal K. Dey, Chanderjit L. Bajaj and Kokichi Sugihara, On good triangulations in three dimensions, International Journal of Computational Geometry and Applications 2(1), 1992, 75 to 95, uniform Delaunay refinement of point sets in three dimensions (general locator)
  5. L. Paul Chew, Guaranteed-quality Delaunay meshing in 3D (short version), Proceedings of the 13th Annual Symposium on Computational Geometry, 1997, 391 to 393, uniform 3D Delaunay refinement with sliver removal by random choice of the new vertex (general locator)

Where this leads

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.worst
  • 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