Algorithm Search⌘K

Algorithmcore

Octree mesh generation

Also called Yerry-Shephard octree method.

Yerry and Shephard's tetrahedral meshing that refines an octree to the geometry, cuts boundary cells to the surface and fills inner cells with template elements.

Time
O(D L + k) expected
Space
O(L + k) extra
Where
D = the depth of the finest leaves; L = the number of leaves of the balanced octree; k = the number of output tetrahedra
Properties
deterministicexactiterative
Origin
Mark Yerry, Mark Shephard, 1984

Octree mesh generation builds a tetrahedral mesh of a solid from an octree. It splits the cubes that meet the boundary of the solid until they are small, balances the tree so that cubes that touch differ in size by at most a factor of 2, fills every cube with tetrahedra from a fixed template, and cuts the cubes at the boundary down to the surface. It is the three-dimensional form of quadtree mesh generation. The original method of Yerry and Shephard is an engineering method with no proved guarantee on element shape. Mitchell and Vavasis later proved that an octree method can get bounded aspect ratio and a size within a constant factor of the best, with constants that are not given as numbers.

In plain words

Put the solid in a big cube. Cut a cube into eight whenever the surface of the solid passes through it, until the cubes at the surface are small. Then cut more cubes until no cube touches a cube four or more times smaller. Now fill each cube with tetrahedra: put a point at its center, a point at the center of each square on its sides, and join them to the corners. Cubes that share a square cut it the same way, so the pieces fit. Last, throw away what lies outside the solid and trim the cubes that the surface cuts through. The inner tetrahedra have good shapes. The trimmed ones can be very thin.

The problem

The input is a solid Ω\Omega and a size: the depth DD of the finest cubes. On this page the solid is a ball ∣x−c∣2<r2|x - c|^2 < r^2 inside the root cube [0,S]3[0, S]^3 with S=2D+1S = 2^{D+1}, given by the function f(x)=r2−∣x−c∣2f(x) = r^2 - |x - c|^2, which is positive inside. The output is a set of tetrahedra that meet face to face (a tetrahedralization) and fill a polyhedron close to Ω\Omega. The quality measures are the radius-edge ratio R/ℓmin⁡R/\ell_{\min} and the dihedral angles, two of the mesh quality measures.

This page makes three kinds of claim, and they must be kept apart.

  • Proved bound with its constant, for the inner tetrahedra. Every tetrahedron of the template step has radius-edge ratio at most 5/2≈1.5811\sqrt{5/2} \approx 1.5811 and all six dihedral angles between arctan⁡(1/2)≈35.26°\arctan(1/\sqrt2) \approx 35.26° and 90°+arctan⁡(1/2)≈125.26°90° + \arctan(1/\sqrt2) \approx 125.26°. The proof in proofs/correctness.md lists all 112 template shapes. The bounds are attained, so here proof and measurement agree.
  • Method with no guarantee, for the cut tetrahedra. The cut at the surface, as in Yerry and Shephard, gives no bound. In the example below the smallest dihedral angle after the cut is 1.89°1.89° and the largest radius-edge ratio is 25.725.7, and both get worse as the surface passes closer to a vertex.
  • Proved bounds with unknown constants, cited. Mitchell and Vavasis proved that their octree method gives a triangulation of bounded aspect ratio if the domain has no sharp angles, with a number of tetrahedra at most a factor times that of any mesh with bounded aspect ratio, the factor depending on that mesh's bound. The constants are not given as numbers. Shewchuk (1998, Section 1) notes that they are too weak to give practical reassurance. So the proved constants are much worse than what the method shows in practice.

A radius-edge bound alone would not do here: a sliver has radius-edge ratio as small as 1/21/\sqrt2 and dihedral angles near 0°0° and 180°180°. The inner tetrahedra have no slivers because their dihedral angles are bounded directly, by the list of shapes, not because their radius-edge ratio is bounded.

The algorithm

A box of level kk has side S/2kS/2^k. Two leaves are balanced if they share a face or an edge and differ by at most one level. Leaves that share only a corner may differ more. A boundary square of a leaf bb is one of its faces, or, if the box of the same size across that face is split, one of the four quarters of that face.

  1. OCTREE-MESH(f, c, r², D)
  2. 1T ← the octree whose only leaf is the root cube [0, S]³, S = 2^(D+1)
  3. 2while some leaf b of level < D meets the sphere |x − c|² = r²:
  4. 3split b into its 8 children
  5. 4while some leaf b shares a face or an edge with a leaf two or more levels finer:
  6. 5split b
  7. 6for each leaf b:
  8. 7add the center p of b
  9. 8for each boundary square s of b:
  10. 9add the center m of s; let r₁, …, r_t be the corners of s and the midpoints of its sides that are corners of leaves, in order around s
  11. 10output the tetrahedra (p, m, r_i, r_(i+1)) for i = 1, …, t (indices mod t)
  12. 11compute f(v) at every vertex v
  13. 12for each tetrahedron τ, with j vertices where f > 0:
  14. 13j = 4: keep τ; j = 0: drop τ
  15. 14j = 1: keep the tetrahedron spanned by the positive vertex and the three cut points on its edges
  16. 15j = 2: keep the prism between the positive edge and the four cut points, cut into 3 tetrahedra
  17. 16j = 3: keep the truncated tetrahedron, a prism, cut into 3 tetrahedra
  18. 17return the kept tetrahedra

The cut point on an edge uvuv with f(u)>0>f(v)f(u) > 0 > f(v) is the zero of the linear interpolation, u+f(u)f(u)−f(v)(v−u)u + \frac{f(u)}{f(u) - f(v)} (v - u). All the cut points of one tetrahedron lie on one plane, the zero set of the linear interpolant of ff, so every kept piece is convex. Each piece with j=2j = 2 or j=3j = 3 is a prism: two triangles joined by three edges, with three quadrilateral sides. The quadrilaterals lie on faces of τ\tau or on the cut plane, and two tetrahedra that share a face see the same quadrilateral. Each one is split by the diagonal through its smallest vertex in a fixed global order (here the lexicographic order of the exact coordinates), so neighbors agree. The smallest of the six vertices is the end of two diagonals, so it sees the opposite triangle as one tetrahedron, and the third diagonal splits the pyramid that remains. A prism with the three diagonals in a cycle has no split into tetrahedra; the global order rules that out.

The root side S=2D+1S = 2^{D+1} makes every corner, box center and center of a quarter face an integer point, so L1 to L10 are integer arithmetic. The values f(v)f(v) and the cut points are rational. If f(v)=0f(v) = 0 at a vertex, the program stops with an error, since the paper's snapping of vertices to the surface is not part of this page.

Example

Take the ball with center (8,8,8)(8, 8, 8) and r2=91/3r^2 = 91/3, so r≈5.508r \approx 5.508, and D=3D = 3, so the root is [0,16]3[0, 16]^3. The counts come from the implementation, and the test file checks them.

Step Lines Result
refine to the sphere L2, L3 all 8 boxes of level 1 and 32 of the 64 boxes of level 2 meet the sphere and are split; 256 leaves of side 2 and 32 of side 4 remain
balance L4, L5 no split: the levels already differ by at most one
templates L6 to L10 264 leaves have 6 boundary squares, 24 leaves of side 4 have two faces next to split boxes and so 12; 1777 vertices and 7680 tetrahedra
cut L11 to L16 by the number jj of positive vertices: 4848 tetrahedra with j=0j = 0 dropped, 1344 with j=4j = 4 kept, 576 with j=1j = 1 give 576, 384 with j=2j = 2 give 1152, 528 with j=3j = 3 give 1584
output L17 1395 vertices and 4656 tetrahedra

The template tetrahedra all have dihedral angles in [35.26°,125.26°][35.26°, 125.26°] and radius-edge ratio at most 1.58111.5811. After the cut, the smallest dihedral angle is 1.89°1.89°, the largest is 155.54°155.54°, the largest radius-edge ratio is 25.7225.72, and 312 of the 4656 tetrahedra have a dihedral angle below 5°5°. Moving the center to (7.5,8,8.5)(7.5, 8, 8.5) gives a smallest dihedral angle of 0.32°0.32° and a radius-edge ratio of 747.5747.5. The mesh has volume 673.52673.52, against 699.79699.79 for the ball. It is smaller because ff is concave: on each tetrahedron ff is at least its linear interpolant, so the kept part lies inside the ball.

Correctness

The proof is in proofs/correctness.md. It has four parts.

  1. The loops stop and the tree is balanced. The refinement loop splits only boxes of level below DD. The balance loop never splits a leaf of level DD, since nothing is finer, so it also splits finitely many boxes. When it stops, leaves that share a face or an edge differ by at most one level.
  2. Each boundary square has only its corners and some side midpoints on its boundary, and no tree corner inside. A tree corner inside a square or inside a side, other than the midpoint, would be the corner of a leaf at least two levels finer than the leaf that owns the square, touching it along a face or an edge. Balance forbids that. So both leaves that share a square list the same ring r1,…,rtr_1, \dots, r_t and the same center mm, and they make the same triangles on it.
  3. The template mesh tiles the cube. Every triangle on a boundary square is used once from each side with opposite orientation, or lies on the root boundary. The tetrahedra have positive volume and their volumes add up to S3S^3. A covering count argument, as in the quadtree proof, shows that they tile the root cube face to face.
  4. The shape bound. Up to the symmetries of the cube, a template tetrahedron is (p,m,ri,ri+1)(p, m, r_i, r_{i+1}) for the bottom face of [0,8]3[0, 8]^3 or one of its quarters, with any set of side midpoints on a whole face and none on a quarter (by balance). This gives 112 tetrahedra. Exact arithmetic gives the largest squared radius-edge ratio, 5/25/2, and the dihedral angles, which take only the values 35.26°35.26°, 45°45°, 54.74°54.74°, 60°60°, 90°90° and 125.26°125.26°.

The cut keeps the mesh conforming: two tetrahedra that share a triangle cut it at the same points and split its quadrilateral part by the same diagonal. The test file checks this by cutting with ff and with −f-f: the two parts fill the cube exactly, and their cut triangles are the same triangles with opposite orientation.

Proof: OCTREE-MESH gives a balanced octree and a conforming tetrahedral mesh whose template tetrahedra have radius-edge ratio at most the square root of 5/2 and dihedral angles between 35.26 and 125.26 degreesfull

Claim. Let D≥1D \ge 1, S=2D+1S = 2^{D+1}, and let the ball ∣x−c∣2<r2|x - c|^2 < r^2, with rational cc and r2r^2, lie inside the root cube [0,S]3[0, S]^3, with f(v)≠0f(v) \ne 0 at every vertex of the template mesh. Then:

  1. both loops of OCTREE-MESH stop, and at the end any two leaves that share a face or an edge differ by at most one level;
  2. the tetrahedra of L6 to L10 have positive volume and form a face-to-face tetrahedralization of the root cube;
  3. each of them has radius-edge ratio R/ℓmin⁡≤5/2R/\ell_{\min} \le \sqrt{5/2} and all its dihedral angles in [θ0,90°+θ0][\theta_0, 90° + \theta_0], where θ0=arctan⁡(1/2)≈35.26°\theta_0 = \arctan(1/\sqrt2) \approx 35.26°, and both bounds are attained;
  4. the tetrahedra of L12 to L16 form a face-to-face tetrahedralization of the polyhedron {x:flin(x)>0}\{x : f_{\mathrm{lin}}(x) > 0\}, where flinf_{\mathrm{lin}} is the piecewise linear interpolant of ff on the template mesh, and this polyhedron lies inside the ball.

What is not claimed. No bound is claimed for the tetrahedra made by the cut. The bounds of Mitchell and Vavasis are cited on the page and not proved here.

Notation. A box of level kk has side wk=S/2kw_k = S/2^k. Two closed boxes have contact of dimension dd if their intersection is a point, a segment or a square for d=0,1,2d = 0, 1, 2. The tree corners are the corners of the leaves. Since wD=2w_D = 2, every corner, box center and center of a quarter of a face is an integer point.

Step 1: the loops stop and the tree is balanced. The first loop splits only leaves of level less than DD, and each box is split at most once, so it stops. In the second loop, a leaf is split only if a leaf two or more levels finer touches it, so leaves of level DD are never split, and the number of possible splits is again finite. The second loop stops only when no leaf has a face or edge contact with a leaf two or more levels finer. The test unbalanced looks at the box NN of the same level across each of the 6 faces and 12 edges of the leaf bb; if NN is split, a leaf two levels finer than bb touches bb along a face or an edge exactly when one of the children of NN that touch bb along that face or edge is split. So the loop condition is the balance condition.

Step 2: the vertices on a boundary square. Let bb be a leaf of level kk and FF a face of bb, and let NN be the box of level kk across FF.

First a fact. If qq is a corner of a leaf b′b' and qq lies in the relative interior of an edge or a face of a leaf cc, then b′b' and cc have contact of dimension at least 1. Indeed, one of the three edges of b′b' at qq is parallel to that edge, or lies in that face, and starts into it, so a segment of it lies in cc. By Step 1, b′b' and cc then differ by at most one level.

Case A: NN is not split. The square is s=Fs = F. Take a tree corner q∈Fq \in F that is not a corner of FF. By the fact, qq is a corner of a leaf of level at most k+1k + 1, so qq lies on the lattice wk+1Z3w_{k+1} \mathbb{Z}^3. On the closed face FF this lattice has 9 points: the 4 corners, the 4 side midpoints and the center. The center is not a tree corner: on the side of bb the only leaf there is bb, and on the other side nothing finer than level kk exists, since NN is not split. So the ring of ss is its corners and some side midpoints.

Case B: NN is split. Its four children that touch FF are leaves, since a split child would put leaves of level k+2k + 2 in face contact with bb. So FF is cut into four quarters, each the face of a leaf cc of level k+1k + 1. Let ss be one quarter and qq a tree corner on a side of ss that is not a corner of ss. The side lies in FF, so by the fact applied to bb (when qq is inside a side of FF or inside FF), qq is a corner of a leaf of level at most k+1k + 1, so it lies on wk+1Z3w_{k+1}\mathbb{Z}^3. A side of ss has length wk+1w_{k+1} and contains no such lattice point except its ends. So the ring of ss is its four corners only.

Both sides agree. If the leaf across FF has level kk, it is in Case A for the same face. If the leaves across are the children of NN, each of them sees, across its face, a box of level k+1k + 1 inside the leaf bb, which is not in the tree, so it is in Case A with its whole face, which is one quarter ss. If the leaf across has level k−1k - 1, it is in Case B, and FF is one of its quarters. In every case both leaves cut the common part of their faces into the same squares. They compute the ring of each square from the same global set of tree corners, and the same center mm, so L9 and L10 make the same triangles on every square, from the two sides.

Step 3: the template mesh tiles the cube. Fix a leaf bb with center pp. Its boundary is cut by Step 2 into squares, and each square into the triangles (m,ri,ri+1)(m, r_i, r_{i+1}). These triangles cover the boundary of bb without overlap. The cube bb is convex and pp is an interior point, so it lies on no plane of a face. Hence the cones from pp over these triangles are tetrahedra of positive volume that tile bb, meeting face to face. The leaves tile the root cube, and by Step 2 the triangles on every shared square are the same from both sides. So the tetrahedra of all leaves tile the root cube face to face.

Step 4: the shape bound. Rotations, reflections and scaling preserve both the radius-edge ratio and the dihedral angles. So scale bb to [0,8]3[0, 8]^3, with p=(4,4,4)p = (4, 4, 4), and move the square to the bottom face z=0z = 0. By Step 2 the square is either the whole face, with center (4,4,0)(4, 4, 0), its 4 corners and any set of its 4 side midpoints, or one of the 4 quarters, with center (2,2,0)(2, 2, 0), (6,2,0)(6, 2, 0), (2,6,0)(2, 6, 0) or (6,6,0)(6, 6, 0) and its 4 corners only. The whole face gives ∑M(4+∣M∣)=16⋅4+32=96\sum_{M} (4 + |M|) = 16 \cdot 4 + 32 = 96 tetrahedra over the 16 sets MM of midpoints, and the quarters give 4⋅4=164 \cdot 4 = 16. So every template tetrahedron is similar to one of these 112. Some cases do not occur in a balanced tree; including them only makes the bound safe.

For each of the 112, the squared radius-edge ratio is a rational number, computed exactly from the circumcenter by Cramer's rule. The largest is 5/25/2, attained for instance by (4,4,4),(2,2,0),(0,0,0),(4,0,0)(4,4,4), (2,2,0), (0,0,0), (4,0,0). Each dihedral angle θ\theta has cos⁡θ=−n1⋅n2/(∣n1∣∣n2∣)\cos\theta = -n_1 \cdot n_2 / (|n_1| |n_2|) for the outward normals n1,n2n_1, n_2 of its two faces, which are integer vectors, so cos⁡2θ\cos^2\theta is rational. Over the 112 tetrahedra, the angles that occur are θ0\theta_0, 45°45°, 90°−θ0≈54.74°90° - \theta_0 \approx 54.74°, 60°60°, 90°90° and 90°+θ090° + \theta_0, with cos⁡2θ∈{2/3,1/2,1/3,1/4,0,1/3}\cos^2\theta \in \{2/3, 1/2, 1/3, 1/4, 0, 1/3\}. The smallest is θ0=arctan⁡(1/2)\theta_0 = \arctan(1/\sqrt2) and the largest is 90°+θ090° + \theta_0; the quarter tetrahedron (4,4,4),(2,2,0),(0,0,0),(4,0,0)(4,4,4), (2,2,0), (0,0,0), (4,0,0) has both, at its edges from (4,4,4)(4,4,4) to (4,0,0)(4,0,0) and from (2,2,0)(2,2,0) to (4,0,0)(4,0,0). The tetrahedra on whole faces without midpoints, the standard cut of a cube into 24, have angles 45°45°, 60°60° and 90°90° only. The test file repeats this enumeration.

Step 5: the cut. For a tetrahedron τ\tau with vertices of values f≠0f \ne 0, let gg be the linear function equal to ff at its vertices. The kept part τ∩{g>0}\tau \cap \{g > 0\} is convex, and its new vertices are the zeros of gg on the edges with a sign change, the cut points of L14 to L16.

  • With one positive vertex aa, it is the tetrahedron aa and the three cut points on the edges at aa.
  • With two positive vertices a,ba, b and negative c,dc, d, its facets are the triangles (a,cac,cad)(a, c_{ac}, c_{ad}) and (b,cbc,cbd)(b, c_{bc}, c_{bd}) on the faces acdacd and bcdbcd, the quadrilaterals (a,b,cbc,cac)(a, b, c_{bc}, c_{ac}) and (a,b,cbd,cad)(a, b, c_{bd}, c_{ad}) on the faces abcabc and abdabd, and the quadrilateral (cac,cad,cbd,cbc)(c_{ac}, c_{ad}, c_{bd}, c_{bc}) on the plane g=0g = 0. It is a prism with the edges abab, caccbcc_{ac} c_{bc} and cadcbdc_{ad} c_{bd}.
  • With three positive vertices a,b,ca, b, c and negative dd, it is a prism with the triangles abcabc and cadcbdccdc_{ad} c_{bd} c_{cd}.

Prism lemma. Let a convex prism have bottom b0b1b2b_0 b_1 b_2, top t0t1t2t_0 t_1 t_2 and quadrilaterals Qi=bibi+1ti+1tiQ_i = b_i b_{i+1} t_{i+1} t_i, and let each QiQ_i take the diagonal through its smallest vertex in a total order. Then split_prism returns three tetrahedra of positive volume that tile the prism and induce exactly these diagonals. Proof: let vv be the smallest of the six vertices, say v=b0v = b_0 (the other cases are the same after renaming). It is the smallest vertex of Q0Q_0 and Q2Q_2, so their diagonals are b0t1b_0 t_1 and b0t2b_0 t_2. The cone from b0b_0 over the facets that do not contain b0b_0, which are the top triangle and Q1Q_1, tiles the prism, since the prism is convex. Splitting Q1Q_1 by its chosen diagonal gives the three tetrahedra (b0,t0,t1,t2)(b_0, t_0, t_1, t_2) and two with base on Q1Q_1. Each has positive volume, since b0b_0 is not on the plane of a facet it does not belong to. On Q0Q_0 and Q2Q_2 the cone induces the fan from b0b_0, which is the chosen diagonal. □\square

So the faces of the output inside a face TT of the template mesh are: nothing if all three vertices are negative, TT if all are positive, the triangle at the positive vertex if one is, and the quadrilateral T∩{g>0}T \cap \{g > 0\} split by the diagonal through its smallest vertex if two are. The function gg on TT depends only on the values of ff at the vertices of TT, and the order is global, so the two tetrahedra that share TT produce the same triangles on it. The faces on the planes g=0g = 0 lie on the boundary of {flin>0}\{f_{\mathrm{lin}} > 0\}. With Step 3, this shows that the kept tetrahedra tile {flin>0}\{f_{\mathrm{lin}} > 0\} face to face.

Last, ff is concave, since −∣x−c∣2-|x - c|^2 is. On each tetrahedron, at a point x=∑λivix = \sum \lambda_i v_i with λi≥0\lambda_i \ge 0 and ∑λi=1\sum \lambda_i = 1, we get f(x)≥∑λif(vi)=g(x)f(x) \ge \sum \lambda_i f(v_i) = g(x). So g>0g > 0 implies f>0f > 0, and the kept polyhedron lies in the ball.

Together, Steps 1 to 5 prove the claim. The test file checks Steps 1, 3, 4 and 5 directly: balance by brute force over all pairs of leaves, the tiling by exact volumes and face twins, the 112 shapes and the quality of every template tetrahedron, and the cut by comparing the parts where f>0f > 0 and f<0f < 0, which fill the cube and share their cut triangles with opposite orientation. ■\blacksquare

Complexity

With hashing for the neighbor lookups and a work queue for the balance step, each level is refined once, each split checks a fixed number of neighbors, and each leaf gives at most 6⋅16=966 \cdot 16 = 96 tetrahedra (a whole face gives at most 8 triangles, a split face 4 quarters of 4). The time is then O(DL+k)O(D L + k) expected, and the space is O(L+k)O(L + k). The balance step adds at most a constant factor of leaves: de Berg et al. (Theorem 14.4) prove this for quadtrees, and the same argument works for octrees with a larger constant.

For a smooth surface of area AA and finest side h=S/2Dh = S/2^D, the leaves at the surface number about A/h2A/h^2, so LL and kk grow as 4D4^D, while a uniform grid of the same resolution has 8D8^D cubes. This is the reason to use an octree.

The implementation on this page is simpler: every round of both loops scans all leaves, which is O(L2)O(L^2) in the worst case. It is enough for the test inputs, where D=3D = 3.

Properties

  • Exact. All decisions are signs of integers or fractions.
  • Deterministic. Ties do not arise: the quadrilateral diagonals use a fixed global order.
  • Conforming. The template mesh is face to face across leaves of different sizes, without hanging nodes, because the boundary squares carry their side midpoints.
  • Graded. Balance makes box sizes change by a factor of at most 2 between neighbors, so the mesh coarsens away from the surface.
  • Proved shape bound inside, no bound at the surface. Inner tetrahedra: radius-edge ratio at most 5/2\sqrt{5/2}, dihedral angles in [35.26°,125.26°][35.26°, 125.26°]. Cut tetrahedra: no bound.
  • Axis dependent. A rotated solid gives a different mesh.

Variants and improvements

  • Modified octree of Yerry and Shephard. The 1984 method works from a solid model. It classifies octants as inside, outside or on the boundary, meshes inner octants with templates and meshes boundary octants by special cases cut to the surface. No shape bound is proved.
  • Finite octree. Shephard and Georges (1991) store the boundary geometry in the octree cells and mesh the boundary cells with more general procedures. It is also an engineering method.
  • Provably good octrees. Mitchell and Vavasis (1992, 2000) extend the quadtree method of Bern, Eppstein and Gilbert to three and more dimensions. They warp octree vertices onto the input faces and edges by systematic rules and duplicate boxes for each connected piece of the domain inside them. They prove bounded aspect ratio for domains without sharp angles and size within a factor of optimal, without numeric constants.
  • Isosurface stuffing. Isosurface stuffing replaces the cube templates by the body-centered cubic lattice and snaps or warps vertices near the surface, which gives proved dihedral angle bounds of about 10.78°10.78° and 164.74°164.74° for the whole mesh, including the cut cells.
  • Marching cubes and marching tetrahedra. Marching cubes and marching tetrahedra extract only the surface from a grid. The cut step of this page is marching tetrahedra applied to the volume.
  • Delaunay refinement. Tetrahedral Delaunay refinement gives a proved radius-edge bound for polyhedral input with fewer elements, but does not bound dihedral angles.

When to use it

Use it when the domain is given by a function or a voxel image, when the mesh should be graded by a size field that a tree can represent, or when a quick and robust mesher matters more than element shape near the boundary. It needs only an inside test or a function like ff, not a closed surface mesh. Use isosurface stuffing when you need a dihedral angle bound for every element, and Delaunay refinement or the advancing front method when the boundary is a surface mesh that must be kept.

Pitfalls

  • Bad elements at the surface. Cut tetrahedra can be arbitrarily thin when the surface passes close to a vertex. Snap such vertices to the surface, warp them as isosurface stuffing does, or smooth and untangle after the cut.
  • A radius-edge bound is not enough. It does not exclude slivers. Check the dihedral angles or another measure such as the scaled Jacobian.
  • Face balance only. Balancing across faces alone lets an edge carry two hanging vertices, and the templates then no longer match. Balance across edges as well.
  • Hanging nodes. If a coarse leaf ignores the corners of its finer neighbors, the mesh has cracks. Put the side midpoints into the boundary rings, as L9 does.
  • Inconsistent diagonals. Two prisms that share a quadrilateral must split it the same way. A local rule, such as the shortest diagonal with ties broken by position, can disagree in floating point; a global vertex order cannot.
  • Small features. A feature smaller than the finest cube is lost or meshed with the wrong topology. The depth must follow the smallest feature, or the tree must be refined by a sizing function.

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
octree_mesh_generation.py 299 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/octree-mesh-generation/. The authors are listed in prov/YMYTYF.jsonl.

"""Octree tetrahedral meshing of a ball in the style of Yerry and Shephard.

The root cube is [0, S]^3 with S = 2^(depth + 1), so every box corner, box
center and quarter face center has integer coordinates. A box is a 4-tuple
(k, i, j, l): level k, side w = S / 2^k, lower corner (i, j, l) w.

The domain is the open ball |x - center|^2 < r2, with rational center and r2.
The steps are:

1. refine every leaf that meets the sphere until it reaches level depth;
2. balance the tree: leaves that share a face or an edge differ by at most
   one level;
3. fill every leaf with tetrahedra: one new point at the center of the leaf,
   joined to a fan of triangles on every square of its boundary;
4. cut the tetrahedra by the linear interpolation of
   f(x) = r2 - |x - center|^2 and keep the parts where f > 0.

All arithmetic is exact (int and Fraction). Step 3 gives a conforming mesh of
the root cube whose tetrahedra come from a finite list of shapes. Step 4 cuts
the cells at the boundary and gives no shape guarantee, as in the original
method.
"""

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

from mg2geom import orient3d

Box = Tuple[int, int, int, int]
FACE_DIRS = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
EDGE_DIRS = [
    d
    for a in (1, -1)
    for b in (1, -1)
    for d in ((a, b, 0), (a, 0, b), (0, a, b))
]


class Octree:
    def __init__(self, depth: int):
        if depth < 1:
            raise ValueError("depth must be at least 1")
        self.depth = depth
        self.side = 1 << (depth + 1)
        self.leaves = {(0, 0, 0, 0)}
        self.internal = set()

    def width(self, k: int) -> int:
        return self.side >> k

    def lower(self, b: Box) -> tuple:
        w = self.width(b[0])
        return (b[1] * w, b[2] * w, b[3] * w)

    def split(self, b: Box) -> None:
        k, i, j, l = b
        self.leaves.remove(b)
        self.internal.add(b)
        for a in (0, 1):
            for c in (0, 1):
                for e in (0, 1):
                    self.leaves.add((k + 1, 2 * i + a, 2 * j + c, 2 * l + e))

    def unbalanced(self, b: Box) -> bool:
        """True if a leaf that shares a face or an edge with b is two or more levels finer."""
        k, i, j, l = b
        for d in FACE_DIRS + EDGE_DIRS:
            nb = (k, i + d[0], j + d[1], l + d[2])
            if nb not in self.internal:
                continue
            # children of nb that touch b: fixed along the axes of d, free along the others
            choices = [(0,) if x == 1 else (1,) if x == -1 else (0, 1) for x in d]
            for a in choices[0]:
                for c in choices[1]:
                    for e in choices[2]:
                        if (k + 1, 2 * nb[1] + a, 2 * nb[2] + c, 2 * nb[3] + e) in self.internal:
                            return True
        return False

    def corners(self) -> set:
        out = set()
        for b in self.leaves:
            w = self.width(b[0])
            x, y, z = self.lower(b)
            for a in (0, w):
                for c in (0, w):
                    for e in (0, w):
                        out.add((x + a, y + c, z + e))
        return out


def meets_sphere(lo: tuple, w: int, center: tuple, r2) -> bool:
    """True if the sphere |x - center|^2 = r2 meets the closed box lo + [0, w]^3."""
    near = far = 0
    for x0, c in zip(lo, center):
        x1 = x0 + w
        dn = c - x0 if c < x0 else (c - x1 if c > x1 else 0)
        df = max(abs(c - x0), abs(c - x1))
        near += dn * dn
        far += df * df
    return near <= r2 <= far


def build_tree(center: tuple, r2, depth: int) -> Octree:
    t = Octree(depth)  # @line L1
    while True:  # @line L2
        todo = [b for b in sorted(t.leaves) if b[0] < depth and meets_sphere(t.lower(b), t.width(b[0]), center, r2)]
        if not todo:
            break
        for b in todo:
            t.split(b)  # @line L3
    while True:  # @line L4
        bad = [b for b in sorted(t.leaves) if t.unbalanced(b)]
        if not bad:
            break
        for b in bad:
            if b in t.leaves:
                t.split(b)  # @line L5
    return t


def boundary_squares(t: Octree, b: Box):
    """The squares that make up the boundary of leaf b, as (axis, plane, u0, v0, side).

    A face of b is one square, or four if the box of the same size across it is split.
    """
    k = b[0]
    w = t.width(k)
    lo = t.lower(b)
    out = []
    for d in FACE_DIRS:
        axis = next(a for a in range(3) if d[a])
        plane = lo[axis] + (w if d[axis] == 1 else 0)
        u, v = (axis + 1) % 3, (axis + 2) % 3
        nb = (k, b[1] + d[0], b[2] + d[1], b[3] + d[2])
        if nb in t.internal:
            h = w // 2
            for a in (0, h):
                for c in (0, h):
                    out.append((axis, plane, lo[u] + a, lo[v] + c, h))
        else:
            out.append((axis, plane, lo[u], lo[v], w))
    return out


def point(axis: int, plane, a, c) -> tuple:
    p = [0, 0, 0]
    p[axis] = plane
    p[(axis + 1) % 3] = a
    p[(axis + 2) % 3] = c
    return tuple(p)


def positive(tet: Sequence[int], verts: List[tuple]) -> tuple:
    a, b, c, d = tet
    o = orient3d(verts[a], verts[b], verts[c], verts[d])
    if o == 0:
        raise AssertionError("flat tetrahedron")
    return (a, b, c, d) if o > 0 else (b, a, c, d)


class Mesh:
    def __init__(self):
        self.verts: List[tuple] = []
        self.index: Dict[tuple, int] = {}

    def vid(self, p: tuple) -> int:
        if p not in self.index:
            self.index[p] = len(self.verts)
            self.verts.append(p)
        return self.index[p]


def fill_leaves(t: Octree) -> Tuple[List[tuple], List[tuple]]:
    """Template tetrahedra of every leaf. Returns (vertices, positively oriented tetrahedra)."""
    corners = t.corners()
    m = Mesh()
    tets = []
    for b in sorted(t.leaves):  # @line L6
        w = t.width(b[0])
        lo = t.lower(b)
        cc = m.vid(tuple(x + w // 2 for x in lo))  # @line L7
        for axis, plane, u0, v0, h in boundary_squares(t, b):  # @line L8
            q = h // 2
            ring = []
            for (a, c), (a2, c2) in zip(
                [(u0, v0), (u0 + h, v0), (u0 + h, v0 + h), (u0, v0 + h)],
                [(u0 + h, v0), (u0 + h, v0 + h), (u0, v0 + h), (u0, v0)],
            ):
                ring.append(point(axis, plane, a, c))
                mid = point(axis, plane, (a + a2) // 2, (c + c2) // 2)
                if mid in corners:  # a hanging vertex of a finer neighbor
                    ring.append(mid)
            sc = m.vid(point(axis, plane, u0 + q, v0 + q))  # @line L9
            ids = [m.vid(p) for p in ring]
            for s in range(len(ids)):
                tets.append(positive((cc, sc, ids[s], ids[(s + 1) % len(ids)]), m.verts))  # @line L10
    return m.verts, tets


def split_prism(bottom: Sequence[int], top: Sequence[int], key) -> List[tuple]:
    """Cut a prism into three tetrahedra.

    bottom[i] and top[i] are joined by an edge. Each quadrilateral side gets the
    diagonal through its smallest vertex in the order key, so two prisms that
    share a quadrilateral cut it the same way. The smallest of the six vertices
    is the end of two diagonals; it sees the opposite triangle as one
    tetrahedron, and the remaining pyramid is cut by the third diagonal.
    """
    quads = [(bottom[i], bottom[(i + 1) % 3], top[(i + 1) % 3], top[i]) for i in range(3)]
    diag = []
    for q in quads:
        m = min(q, key=key)
        diag.append(frozenset((q[0], q[2])) if m in (q[0], q[2]) else frozenset((q[1], q[3])))
    v = min(list(bottom) + list(top), key=key)
    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  # the quad that does not contain v
    out = [(v, top[0], top[1], top[2])]
    q = quads[far]
    a, b, c, d = q  # bottom[far], bottom[far + 1], top[far + 1], top[far]
    if diag[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 ball_values(verts: List[tuple], center: tuple, r2) -> List[Fraction]:
    """f(x) = r2 - |x - center|^2 at every vertex: positive inside the ball."""
    return [Fraction(r2) - sum((x - c) ** 2 for x, c in zip(p, center)) for p in verts]


def cut_by_sign(verts: List[tuple], tets: List[tuple], f: Sequence[Fraction]):
    """Keep the part of each tetrahedron where the linear interpolant of the values f is positive.

    Returns (vertices, tetrahedra) of the kept part. Calling it with -f gives
    the other part, cut along the same triangles.
    """
    if any(v == 0 for v in f):
        raise ValueError("the surface passes through a mesh vertex")
    m = Mesh()
    for p in verts:
        m.vid(p)
    cuts: Dict[tuple, int] = {}

    def cut(a: int, b: int) -> int:
        e = (a, b) if a < b else (b, a)
        if e not in cuts:
            pa, pb = verts[e[0]], verts[e[1]]
            s = f[e[0]] / (f[e[0]] - f[e[1]])
            cuts[e] = m.vid(tuple(x + s * (y - x) for x, y in zip(pa, pb)))
        return cuts[e]

    key = lambda i: m.verts[i]  # noqa: E731  (a total order shared by all prisms)
    out = []
    for tet in tets:  # @line L12
        pos = [v for v in tet if f[v] > 0]
        neg = [v for v in tet if f[v] < 0]
        if len(pos) == 4:  # @line L13
            pieces = [tet]
        elif len(pos) == 0:
            pieces = []
        elif len(pos) == 1:  # @line L14
            a = pos[0]
            pieces = [(a, cut(a, neg[0]), cut(a, neg[1]), cut(a, neg[2]))]
        elif len(pos) == 2:  # @line L15
            (a, b), (c, d) = pos, neg
            pieces = split_prism((a, cut(a, c), cut(a, d)), (b, cut(b, c), cut(b, d)), key)
        else:  # @line L16
            d = neg[0]
            pieces = split_prism(tuple(pos), tuple(cut(p, d) for p in pos), key)
        out.extend(positive(p, m.verts) for p in pieces)
    keep = sorted({v for tet in out for v in tet})
    new = {v: i for i, v in enumerate(keep)}
    return [m.verts[v] for v in keep], [tuple(new[v] for v in tet) for tet in out]


def octree_mesh(center: Sequence, r2, depth: int):
    """Mesh the ball |x - center|^2 < r2 inside the root cube [0, 2^(depth+1)]^3.

    Returns (tree, vertices, tetrahedra). Tetrahedra are positively oriented
    4-tuples of vertex indices.
    """
    center = tuple(Fraction(c) for c in center)
    r2 = Fraction(r2)
    t = Octree(depth)
    if r2 <= 0 or not all(0 < c < t.side and c * c > r2 and (t.side - c) ** 2 > r2 for c in center):
        raise ValueError("the ball must lie strictly inside the root cube")
    t = build_tree(center, r2, depth)
    verts, tets = fill_leaves(t)
    f = ball_values(verts, center, r2)  # @line L11
    verts, tets = cut_by_sign(verts, tets, f)
    return t, verts, tets  # @line L17
test_octree_mesh_generation.py 251 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/octree-mesh-generation/. The authors are listed in prov/YMYTYF.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, orient3d, radius_edge2
from octree_mesh_generation import (
    ball_values,
    build_tree,
    cut_by_sign,
    fill_leaves,
    meets_sphere,
    octree_mesh,
    split_prism,
)

DIH_MIN = math.degrees(math.atan(1 / math.sqrt(2)))  # 35.26 degrees
DIH_MAX = 90 + DIH_MIN  # 125.26 degrees


def random_ball(seed):
    r = random.Random(seed)
    center = tuple(F(r.randint(12, 20), 2) for _ in range(3))
    r2 = F(r.randint(6, 80), 3)  # never a quarter-integer, so never zero at a vertex
    return center, r2


CASES = [
    ((8, 8, 8), F(91, 3)),  # the example of the page
    ((F(15, 2), 8, F(17, 2)), F(91, 3)),  # off center
    ((7, 9, 8), F(10, 3)),  # a small ball: the tree is graded
    random_ball(1),
    random_ball(2),
]
DEPTH = 3


@lru_cache(maxsize=None)
def stages(i):
    center, r2 = CASES[i]
    center = tuple(F(c) for c in center)
    t = build_tree(center, r2, DEPTH)
    verts, tets = fill_leaves(t)
    f = ball_values(verts, center, r2)
    inside = cut_by_sign(verts, tets, f)
    outside = cut_by_sign(verts, tets, [-x for x in f])
    return t, verts, tets, inside, outside


def box(t, b):
    w = t.width(b[0])
    return tuple((x, x + w) for x in t.lower(b))


def contact_dim(p, q):
    """Dimension of the intersection of two closed boxes, or -1 if they are apart (brute force)."""
    dim = 0
    for (a0, a1), (b0, b1) in zip(p, q):
        lo, hi = max(a0, b0), min(a1, b1)
        if lo > hi:
            return -1
        dim += lo < hi
    return dim


def faces(tets):
    c = Counter()
    for a, b, cc, d in tets:
        # outward oriented faces of a positive tetrahedron, as sorted triple plus parity
        for tri in ((b, cc, d), (a, d, cc), (a, b, d), (a, cc, b)):
            c[tri_key(tri)] += 1
    return c


def tri_key(tri):
    """A rotation-invariant key that keeps the orientation of the triangle."""
    i = tri.index(min(tri))
    return tri[i:] + tri[:i]


def check_face_pairs(verts, tets, on_boundary):
    c = faces(tets)
    for tri, m in c.items():
        assert m == 1, tri
        twin = (tri[0], tri[2], tri[1])
        if twin not in c:
            assert on_boundary([verts[v] for v in tri]), tri


@pytest.mark.parametrize("i", range(len(CASES)))
def test_tree_is_balanced_by_brute_force(i):
    t = stages(i)[0]
    leaves = sorted(t.leaves)
    boxes = [box(t, b) for b in leaves]
    for a in range(len(leaves)):
        for b in range(a + 1, len(leaves)):
            if contact_dim(boxes[a], boxes[b]) >= 1:
                assert abs(leaves[a][0] - leaves[b][0]) <= 1, (leaves[a], leaves[b])


@pytest.mark.parametrize("i", range(len(CASES)))
def test_leaves_at_the_surface_have_the_finest_size(i):
    t = stages(i)[0]
    center, r2 = CASES[i]
    for b in t.leaves:
        if meets_sphere(t.lower(b), t.width(b[0]), tuple(F(c) for c in center), F(r2)):
            assert b[0] == DEPTH


@pytest.mark.parametrize("i", range(len(CASES)))
def test_template_mesh_is_a_conforming_mesh_of_the_cube(i):
    t, verts, tets = stages(i)[:3]
    vols = [orient3d(*[verts[v] for v in tet]) for tet in tets]
    assert all(v > 0 for v in vols)
    assert sum(vols) == 6 * t.side**3

    def on_cube_face(ps):
        return any(all(p[a] == s for p in ps) for a in range(3) for s in (0, t.side))

    check_face_pairs(verts, tets, on_cube_face)


@pytest.mark.parametrize("i", range(len(CASES)))
def test_template_tetrahedra_have_the_proved_quality(i):
    verts, tets = stages(i)[1:3]
    for tet in tets:
        p = [verts[v] for v in tet]
        assert radius_edge2(*p) <= F(5, 2)
        d = dihedral_angles_deg(*p)
        assert DIH_MIN - 1e-9 <= min(d) and max(d) <= DIH_MAX + 1e-9


def test_template_list_by_enumeration():
    # Every template tetrahedron is (cell center, square center, two ring neighbors).
    # Up to the symmetries of the cube, the square is the bottom face of [0, 8]^3 or a
    # quarter of it; a whole face may carry any of its four edge midpoints; a quarter
    # carries none (balance). This lists all 112 shapes and finds the exact extremes.
    cc = (4, 4, 4)
    shapes = []
    for u0, v0, h in [(0, 0, 8), (0, 0, 4), (4, 0, 4), (0, 4, 4), (4, 4, 4)]:
        cs = [(u0, v0), (u0 + h, v0), (u0 + h, v0 + h), (u0, v0 + h)]
        for mask in range(16 if h == 8 else 1):
            ring = []
            for s in range(4):
                ring.append(cs[s] + (0,))
                if mask >> s & 1:
                    a, b = cs[s], cs[(s + 1) % 4]
                    ring.append(((a[0] + b[0]) // 2, (a[1] + b[1]) // 2, 0))
            sc = (u0 + h // 2, v0 + h // 2, 0)
            shapes += [(cc, sc, ring[s], ring[(s + 1) % len(ring)]) for s in range(len(ring))]
    assert len(shapes) == 112
    assert max(radius_edge2(*s) for s in shapes) == F(5, 2)
    d = [a for s in shapes for a in dihedral_angles_deg(*s)]
    assert min(d) == pytest.approx(DIH_MIN) and max(d) == pytest.approx(DIH_MAX)


@pytest.mark.parametrize("i", range(len(CASES)))
def test_cut_mesh_is_conforming_and_matches_the_outside(i):
    t, verts, tets, inside, outside = stages(i)
    center, r2 = CASES[i]
    center = tuple(F(c) for c in center)
    template = set(verts)
    vi, ti = inside
    vo, to = outside
    vol_in = [orient3d(*[vi[v] for v in tet]) for tet in ti]
    vol_out = [orient3d(*[vo[v] for v in tet]) for tet in to]
    assert all(v > 0 for v in vol_in + vol_out)
    # the two parts fill the cube exactly
    assert sum(vol_in) + sum(vol_out) == 6 * t.side**3
    # every boundary face of the inside lies on the cut surface: its vertices are cut points
    check_face_pairs(vi, ti, lambda ps: not any(p in template for p in ps))
    # the cut triangles of the inside are the cut triangles of the outside, reversed
    cut_in = {tuple(vi[v] for v in tri) for tri in faces(ti) if not any(vi[v] in template for v in tri)}
    cut_out = {tuple(vo[v] for v in tri) for tri in faces(to) if not any(vo[v] in template for v in tri)}
    cut_in = {tri for tri in cut_in if (tri[0], tri[2], tri[1]) not in cut_in}
    rev = set()
    for tri in cut_out:
        r = (tri[0], tri[2], tri[1])
        i0 = r.index(min(r))
        rev.add(r[i0:] + r[:i0])
    norm = set()
    for tri in cut_in:
        i0 = tri.index(min(tri))
        norm.add(tri[i0:] + tri[:i0])
    assert norm == rev
    # every vertex of the inside lies in the closed ball (f is concave, so f >= 0 on the cut points)
    assert all(v >= 0 for v in ball_values(vi, center, r2))
    # A leaf that misses the sphere is kept whole or dropped whole, so the kept volume
    # and the ball differ only inside the leaves that meet the sphere.
    ball = 4 / 3 * math.pi * float(r2) ** 1.5
    band = sum(t.width(b[0]) ** 3 for b in t.leaves if meets_sphere(t.lower(b), t.width(b[0]), center, F(r2)))
    assert abs(sum(vol_in) / 6 - ball) <= band


def test_cutting_gives_no_shape_guarantee():
    # The template bound does not survive the cut: thin pieces appear where the
    # sphere passes close to a vertex.
    vi, ti = stages(1)[3]
    worst = min(min(dihedral_angles_deg(*[vi[v] for v in tet])) for tet in ti)
    assert worst < 1.0


def test_split_prism_gives_three_positive_tetrahedra_and_the_min_vertex_diagonals():
    r = random.Random(7)
    pts = [(0, 0, 0), (4, 0, 0), (0, 4, 0), (1, 1, 5), (5, 1, 5), (1, 5, 5)]  # a slanted prism
    for _ in range(30):
        order = list(range(6))
        r.shuffle(order)
        rank = {v: order[v] for v in range(6)}
        out = split_prism((0, 1, 2), (3, 4, 5), key=lambda v: rank[v])
        vols = []
        for tet in out:
            o = orient3d(*[pts[v] for v in tet])
            assert o != 0
            vols.append(abs(o))
        # the three pieces fill the prism: six times its volume is 6 * area 8 * height 5
        assert sum(vols) == 240
        edges = {frozenset((a, b)) for tet in out for a in tet for b in tet if a != b}
        for q in [(0, 1, 4, 3), (1, 2, 5, 4), (2, 0, 3, 5)]:
            m = min(q, key=lambda v: rank[v])
            j = q.index(m)
            assert frozenset((m, q[(j + 2) % 4])) in edges
            assert frozenset((q[(j + 1) % 4], q[(j + 3) % 4])) not in edges


def test_example_counts():
    t, verts, tets, inside, _ = stages(0)
    assert Counter(b[0] for b in t.leaves) == {3: 256, 2: 32}
    assert (len(verts), len(tets)) == (1777, 7680)
    assert (len(inside[0]), len(inside[1])) == (1395, 4656)
    f = ball_values(verts, (8, 8, 8), F(91, 3))
    assert Counter(sum(1 for v in tet if f[v] > 0) for tet in tets) == {0: 4848, 1: 576, 2: 384, 3: 528, 4: 1344}
    vi, ti = inside
    worst = min(min(dihedral_angles_deg(*[vi[v] for v in tet])) for tet in ti)
    assert worst == pytest.approx(1.8923, abs=1e-4)
    assert sum(orient3d(*[vi[v] for v in tet]) for tet in ti) / 6 == pytest.approx(673.5244, abs=1e-4)


def test_rejects_bad_input():
    with pytest.raises(ValueError):
        octree_mesh((8, 8, 8), 36, 3)  # the sphere passes through the vertex (14, 8, 8)
    with pytest.raises(ValueError):
        octree_mesh((2, 8, 8), F(91, 3), 3)  # the ball leaves the root cube
    with pytest.raises(ValueError):
        octree_mesh((8, 8, 8), 5, 0)

History

Yerry and Shephard published a modified quadtree mesher for finite element analysis in 1983 and the modified octree method for three-dimensional solids in 1984. Shephard and Georges developed it into the finite octree technique in 1991. These were practical methods that worked directly from solid models, and they made fully automatic tetrahedral meshing usable in engineering codes. In 1990 Bern, Eppstein and Gilbert proved bounds for quadtree meshing in the plane, and in 1992 Mitchell and Vavasis carried the proofs to three dimensions, with a journal version for any dimension in 2000. Their QMG code implemented the method. In 2007 Labelle and Shewchuk gave isosurface stuffing, an octree method with explicit dihedral angle bounds.

References

  1. Mark A. Yerry and Mark S. Shephard, Automatic three-dimensional mesh generation by the modified-octree technique, International Journal for Numerical Methods in Engineering 20(11), 1984, 1965 to 1990, the modified octree method for solid models (general locator)
  2. Mark A. Yerry and Mark S. Shephard, A modified quadtree approach to finite element mesh generation, IEEE Computer Graphics and Applications 3(1), 1983, 39 to 46, the two-dimensional method (general locator)
  3. Mark S. Shephard and Marcel K. Georges, Automatic three-dimensional mesh generation by the finite octree technique, International Journal for Numerical Methods in Engineering 32(4), 1991, 709 to 749, the finite octree variant (general locator)
  4. Scott A. Mitchell and Stephen A. Vavasis, Quality mesh generation in three dimensions, Proceedings of the 8th ACM Symposium on Computational Geometry, 1992, 212 to 221, the first octree mesher with bounded aspect ratio and size optimality in three dimensions (general locator)
  5. Scott A. Mitchell and Stephen A. Vavasis, Quality mesh generation in higher dimensions, SIAM Journal on Computing 29(4), 2000, 1334 to 1370, abstract and main theorems (bounded aspect ratio when the domain has no sharp angles, size within a factor of any competing mesh)
  6. Jonathan Richard Shewchuk, Tetrahedral mesh generation by Delaunay refinement, Proceedings of the 14th ACM Symposium on Computational Geometry, 1998, 86 to 95, Section 1, the remark that the bounds of the octree methods are too weak to reassure in practice and are not stated explicitly
  7. Mark de Berg, Otfried Cheong, Marc van Kreveld and Mark Overmars, Computational Geometry, Algorithms and Applications, 3rd edition, Springer, 2008, Chapter 14, Quadtrees (balancing a quadtree and the size of the balanced tree)

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