Algorithmresearch
Delaunay refinement surface meshing
Also called Boissonnat-Oudot surface mesher.
Boissonnat and Oudot's mesher that inserts points of a smooth surface until the restricted Delaunay triangulation is a good, homeomorphic approximation.
- Solves
- Mesh generation
- Time
- O(n^3) worst
- Space
- O(n^2) extra
- Where
- n = the number of output vertices
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jean Daniel Boissonnat, Steve Oudot, 2005
Delaunay refinement surface meshing builds a triangle mesh of a smooth closed surface by choosing points on one at a time. It keeps the 3D Delaunay triangulation of the points chosen so far and reads off the restricted Delaunay triangulation: the triangles whose dual Voronoi edge meets . Each place where such an edge meets is the center of an empty ball that touches the three corners of the triangle. If the ball is larger than a user size at its center, its center is added. Boissonnat and Oudot (2005) proved that the loop stops, and that with below about times the local feature size, the output is homeomorphic to and close to it. The surface is used only through an oracle that intersects segments with it.
In plain words
Scatter a few points on the surface. Build their 3D Delaunay triangulation, then ask, for each triangle, whether the line of points equally far from its three corners crosses the surface between the right limits. Where it does, a ball centered on the surface touches the three corners and contains no other point. A big ball means a big hole in the sample, so put a new point at its center and repeat. When every such ball is smaller than the size you asked for, the triangles you found form the mesh. The proof says that a small enough size gives the right shape. Tests show that much larger sizes still give the right shape, and that too large a size does not.
The problem
The input is a smooth () closed surface and a size function that is positive and 1-Lipschitz. The surface is known through an oracle that, given a segment or a ray, returns the points where it meets . The output is a finite sample and its restricted Delaunay triangulation .
The medial axis of is the closure of the set of points with two or more nearest points on , and is the distance from to it, also called the local feature size. Let be the union of the Voronoi edges of . For a triangle of the Delaunay triangulation whose dual Voronoi edge meets at , the ball through the corners of is a surface Delaunay ball. It contains no point of in its interior. Following Definition 2.2 of the paper, is a loose -sample when
- every has a point of within , that is, every surface Delaunay ball has radius at most at its center, and
- has a vertex on every connected component of .
An -sample in the sense of Amenta and Bern, with every point of within of , is a loose -sample when (Lemma 2.3).
This page makes three kinds of claim.
- Proved bounds, cited. Let be the smallest positive with (Section 2.3 of the paper). For a loose -sample with : is a 2-manifold without boundary (Theorem 4.3); the nearest point map restricted to it is a homeomorphism onto , and the two are ambient isotopic (Theorem 4.4); the Hausdorff distance between them is at most (Theorem 4.5); and , where is the genus and (Theorem 5.1). For the algorithm: it terminates for every positive 1-Lipschitz (Lemma 8.1); if the output is a loose -sample (Lemma 8.2); and if the points inserted by the loop number at most , since the proof of Lemma 8.3 shows they are -sparse and Theorem 5.4 bounds a -sparse sample by . So the topological guarantee needs .
- Proved here. The oracle used by the implementation answers exactly whether a Voronoi edge meets ; the dual Voronoi edge of a triangle is the segment between the circumcenters of its two tetrahedra, or a ray for a hull triangle; recomputing only the triangles of changed tetrahedra keeps correct; the loop stops even though new points are rounded to an integer grid; persistent facets survive. See
proofs/correctness.md. - Measured, no guarantee. On a sphere of radius () and a torus with tube radius and (), the output was a closed surface with the right Euler characteristic, every edge in two triangles, for every tried: from to on the sphere, and from to on the torus, times the proved threshold. On the torus it failed at for each of the five seeds tried. The sizes were well inside the proved bounds: at on the sphere the run gave points, against the lower bound and the upper bound . The proved constants are much worse than the measured ones.
The algorithm
The mesher keeps the 3D Delaunay triangulation of , with a ghost tetrahedron on each face of the convex hull, so that every triangle has two neighbors. For a triangle with neighbors , the dual Voronoi edge is the segment between their circumcenters, or, if is a ghost, the ray from the circumcenter of along the outward normal of . The oracle returns the points of on it.
DELAUNAY-SURFACE-MESHING(S, σ)- 1
E ← for one or more seed points x on each component of S, three points of S near x that form a persistent facet - 2
D ← the Delaunay triangulation of E, with ghost tetrahedra on the hull faces - 3
for each triangle f of D: C(f) ← the points where the Voronoi edge dual to f meets S, found by the oracle - 4
while some triangle f has c in C(f) whose ball has radius r = |c - a| > σ(c), for a corner a of f: - 5
take the pair (f, c) with the largest r / σ(c) - 6
insert c into E and update D by Bowyer-Watson insertion - 7
recompute C(g) for each triangle g of a removed or new tetrahedron, and forget the triangles that are gone - 8
return E and Del|S(E), the triangles f with C(f) not empty
The paper takes the bad balls from a list in any order; picking the worst first is this implementation's choice. Line L1 follows Section 7 of the paper. Around each seed , take a ball of radius below and pick three points of such that the line through their circumcenter, normal to their plane, meets inside . The resulting facet has a surface Delaunay ball of radius at most ; Lemma 7.1 shows such a persistent facet stays in to the end, which gives Condition 2.
The implementation meshes a sphere and a torus, both zero sets of a polynomial with integer coefficients. All points have integer coordinates. A circumcenter is with integer and , so a Voronoi edge is the set of for in or , and is a polynomial in with integer coefficients. A Sturm sequence counts its roots in the interval exactly; bisection then locates each root to within of a unit, and the center is rounded to the grid. Orientation and insphere signs are exact integer computations. Radii and are compared in floating point; this only decides which balls count as bad.
Example
A sphere of radius with and seed 1. Four seeds at the corners of a randomly rotated regular tetrahedron give starting points. Their restricted Delaunay triangulation has triangles: the persistent facets, whose balls have , and triangles with bad balls, the worst at . Each row shows the state before the next insertion.
| insertions | points | triangles of Del|S(E) | bad balls | worst r / σ |
|---|---|---|---|---|
| 0 | 12 | 20 | 16 | 2.256 |
| 4 | 16 | 28 | 24 | 1.793 |
| 10 | 22 | 40 | 27 | 1.233 |
| 22 | 34 | 64 | 11 | 1.051 |
| 28 | 40 | 76 | 1 | 1.000 |
| 29 | 41 | 78 | 0 | none |
At every step the restricted triangulation is a triangulated sphere with triangles. The output has points, triangles and edges, each in exactly two triangles, so its Euler characteristic is , and the persistent facets are still there. Every vertex is within one grid unit of (on a radius of about a million), and the triangles found from the Delaunay triangulation are exactly those found by testing every triple of points against the definition. Here , more than five times the proved threshold, so the topology is correct without a guarantee.
The torus with and behaves the same at : points, triangles, Euler characteristic . At the loop stops after points with triangles, some edges in one, three or four triangles, and Euler characteristic . The surface Delaunay balls are all small enough, yet the output is not a surface: the threshold matters, though the proved one is far too cautious.
Correctness
Termination (Lemma 8.1): a point inserted as the center of a bad ball is at distance from every earlier point, because the ball is empty. So the inserted points are apart, and a compact surface has room for only finitely many of them. In the implementation the rounded point is at distance at least , so the same argument works whenever grid units.
Output quality (Lemma 8.2): when the loop stops, no surface Delaunay ball is bad, so every one has . If this is Condition 1 of a loose -sample. Condition 2 comes from the persistent facets: if a later point fell inside a persistent ball with , then by the Lipschitz condition, while a corner of the facet satisfies , so would lie inside the bad ball centered at , which is empty. With , Theorems 4.3 to 4.5 then give a manifold, homeomorphic and isotopic to , within .
Bookkeeping: inserting a point changes only the tetrahedra of its cavity, and the dual Voronoi edge of a triangle depends only on its two tetrahedra. So only triangles of removed or new tetrahedra need a new oracle call. The proof file gives the details, including why the segment between the two circumcenters is the whole Voronoi edge.
The theorems assume . The implementation's points are within grid units of , so the theorems are not formally applied to it; the tests check the topology directly.
Proof: The oracle is exact, the dual Voronoi edge is the segment or ray between circumcenters, the incremental update is correct, and the loop stops with persistent facets intactfull
Claim. Assume general position: no five points of on a sphere or four on a plane, no Voronoi vertex on . Let , the largest distance that rounding to the integer grid moves a point.
- For a line with integer , the polynomial computed for the sphere is and for the torus , and the Sturm count gives exactly the number of distinct points of on the part of the line with in the given interval.
- Let be a triangle of the Delaunay triangulation . If both its tetrahedra and are real, with circumcenters , its dual Voronoi edge (the points whose nearest points in include ) is the segment . If is a ghost, it is the ray from along the normal of that points away from .
- After an insertion, recomputing the triangles of the removed and the new tetrahedra gives the same restricted triangles and surface balls as computing all of them again.
- If on a neighborhood of , the loop stops.
- If a facet of the initial sample has a surface Delaunay ball with , it is a restricted triangle at the end.
What is cited. Sturm's theorem: for a square-free polynomial with Sturm sequence , the number of distinct real roots in is , where counts sign changes, zeros dropped. The bounds on the output (homeomorphism for , Hausdorff distance, size) are Theorems 4.3 to 4.5, 5.1 and 5.4 and Lemmas 8.2 to 8.4 of Boissonnat and Oudot (2005) and are not repeated.
Step 1: the polynomial and the count (part 1). For the sphere , so , which is what is computed. For the torus ; multiplying by gives with and , which is what is computed. Since , the roots in are the parameters where the line meets . All coefficients are integers, so the Sturm sequence is computed exactly in rationals. If the last element of the sequence is not constant, it is up to a factor, and has the same distinct roots, all simple; the implementation counts with that. A root exactly at the lower end is tested directly by evaluating there, and Sturm's theorem counts the rest in . For a ray, the interval is cut at Cauchy's bound , beyond which there are no roots. The count is exact. Each root is then bracketed by exact bisection to an interval of length at most in , so the computed point is within of the exact point of along the edge, and it lies in the interval.
Step 2: the dual Voronoi edge (part 2). The points equidistant from form a line normal to through its circumcenter. Parametrize it as , affine in . For a point of , set
which is affine in . The point has among its nearest points exactly when for all , so the Voronoi edge is the intersection of half-lines, an interval . A tetrahedron of has an empty circumsphere, centered at , so for all and . By convexity (with after renaming). Now because is on the circumsphere of , and because by general position is not on the circumsphere of , and it is not inside it. An affine function that is positive at and zero at is negative beyond , so ends at ; in the same way ends it at . So , the segment .
If is a ghost, is a face of the convex hull, and every point of is on the side of its plane that contains , or on the plane. Let be the normal of pointing away from , and . The slope of is for every , since points to the inner side or along the plane. So each is nondecreasing, and makes it nonnegative on . The slope for is positive and , so ends at on the other side. Hence is the ray from along . In both cases every computed center lies on , so its ball through contains no point of in its interior.
The ghost test of the insertion uses the same fact: a new point conflicts with a ghost tetrahedron exactly when it is strictly outside the hull face, which is the limit of the insphere test as the fourth vertex goes to infinity on the outer side. With this rule, Bowyer-Watson insertion with ghosts produces the Delaunay triangulation of together with ghosts on the new hull faces, as for points inside the hull.
Step 3: the incremental update (part 3). Inserting removes the tetrahedra (and ghosts) in conflict with and creates new ones joined to ; every other tetrahedron is unchanged. By Step 2 the Voronoi edge of a triangle, and so its surface balls, depends only on the triangle and its two tetrahedra. A triangle that is not a face of a removed or new tetrahedron has the same two tetrahedra before and after, so its result does not change. Every other triangle that still exists is a face of a new tetrahedron and is recomputed; one that no longer exists is removed. The surface balls are computed by the same function either way, so the stored set equals a fresh computation.
Step 4: termination (part 4). When a center of a bad ball is inserted, where is the rounded point that is evaluated, and by Step 2 no point of lies within distance of . The inserted point is within of , so it is at distance at least from every earlier point. So the inserted points are pairwise at least apart, and they lie within of by Step 1. The open balls of radius around them are disjoint and lie in a bounded region, so there are finitely many, and the loop, which inserts one point per round, stops.
Step 5: persistent facets (part 5). Suppose a point , rounded from the center of a bad ball , is the first inserted point inside the open ball ; the ball was bad because . Since and is 1-Lipschitz, . For a corner of the facet,
So lies in the interior of , which is empty by Step 2, a contradiction. Hence no point is ever inserted inside . That ball stays empty, its center stays on and is equidistant from the three corners, so it stays a surface Delaunay ball of the facet, and the facet stays in .
What is not proved. That the output is homeomorphic to is Boissonnat and Oudot's theorem for loose -samples of points on with . The implementation's points are within of , not on it, and the tests use far above , so for them the topology is checked directly: every edge in two triangles, every vertex link one cycle, the Euler characteristic, and orientability. The choice of the worst ball first is not needed by the proofs.
Complexity
For output vertices, the 3D Delaunay triangulation has tetrahedra in the worst case, so each insertion costs and the loop costs in the worst case, with space. The oracle call per triangle costs a constant number of operations on numbers whose size grows with the coordinates. Samples of smooth surfaces behave much better than the worst case: in the runs above there were only a few tetrahedra per point. The scan for the worst ball adds per insertion, which a priority queue would reduce. The sphere with and points took about seconds in Python.
The number of output points is when with (Lemma 8.4 and Theorem 5.1), so it is optimal up to a constant factor. On the sphere, with , the runs gave , , and points for , which is , , and times .
Properties
- The output vertices are points of (in exact arithmetic), so no projection step is needed.
- can vary over . It must be 1-Lipschitz, and must stay below where the guarantee is wanted.
- The algorithm needs only the oracle, not a parametrization, normals or curvature.
- The restricted triangulation contains every persistent facet from the start.
- Triangle shapes are not controlled by the basic loop. Section 9.1 of the paper adds a second pass that also calls a ball bad when its triangle has an angle below , and proves termination for .
Variants and improvements
- Chew's 1993 mesher is the ancestor: it refines surface Delaunay balls by size and shape, without the sampling theory that gives the topological guarantee. The planar version is Chew's second algorithm.
- Cheng, Dey, Ramos and Ray guarantee the topology without knowing , by refining until the restricted Voronoi cells have the topological ball property, which Edelsbrunner and Shah's theorem turns into a homeomorphism.
- Boissonnat and Oudot extended the method to Lipschitz surfaces in 2006, and protecting balls extend Delaunay refinement to surfaces with sharp edges and corners.
- Chapter 14 of Cheng, Dey and Shewchuk adds volume meshing: refine the tetrahedra inside as well, as in tetrahedral Delaunay refinement.
- The CGAL library's former Surface_mesher package, by Laurent Rineau and Mariette Yvinec, states that it is mainly based on this work; it is deprecated since CGAL 6.0 in favor of the 3D Mesh Generation package.
When to use it
Use it when the surface is given implicitly, as a level set, a CAD surface with an intersection routine, or anything else that can answer segment queries, and when a topological guarantee matters. For a fast mesh of a level set on a grid, marching cubes and other isosurface extraction methods are simpler but offer no shape or topology guarantee. For a parametric patch, parametric surface meshing works in the parameter plane. For reconstruction from a fixed point cloud with no oracle, see surface reconstruction.
Pitfalls
- With too large the loop can stop with a non-manifold output, as the torus at shows: every ball is small enough, yet triangles share edges three or four at a time. No check after the fact is built in.
- Without the persistent facets of Section 7, a sample with no restricted triangle on some component has no bad ball there, and the loop never reaches it.
- is rarely known for a real surface. A guessed gives no guarantee; the variant of Cheng, Dey, Ramos and Ray avoids the guess.
- The intersection of a Voronoi edge with is a root of a polynomial or of a general function. Missing a root, or seeing a tangency as a crossing, changes . Exact root counting avoids this for algebraic surfaces.
- The tetrahedra of are scaffolding, not a volume mesh: many are flat. A volume mesh needs its own refinement, and a radius-edge bound would not remove its slivers.
- A Voronoi vertex exactly on , a Voronoi edge tangent to , or five cospherical points are degenerate cases that the paper assumes away. The implementation raises an error when such a case would make a tetrahedron flat.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delaunay-surface-meshing/. The authors are listed in prov/8F2351.jsonl.
"""Boissonnat and Oudot's Delaunay refinement surface mesher (2005).
The surface S is the zero set of a polynomial F with integer coefficients: a
sphere or a torus. It is known to the mesher only through an oracle that, given
a segment or a ray, returns the points where it meets S. The mesher keeps the
3D Delaunay triangulation of the sample E, finds the restricted Delaunay
triangles (those whose dual Voronoi edge meets S), and inserts the center c of
any surface Delaunay ball B(c, r) with r > sigma(c), until there is none.
Coordinates are integers. A new vertex is the exact intersection of a Voronoi
edge with S, located to within a small fraction of a unit and rounded once to
the integer grid, so it lies within one unit of S. All predicates on the
current points are exact: orientation and insphere signs use int arithmetic,
and the question whether a Voronoi edge meets S is answered by an exact Sturm
sequence on a polynomial with integer coefficients. Radii and sigma are
compared in floating point, which only decides which balls count as bad.
"""
import math
import random
from fractions import Fraction
from typing import Callable, Dict, List, Optional, Sequence, Set, Tuple, Union
from mg2geom import cross, dist2, dot, insphere, orient3d, sub
Tet = Tuple[int, int, int, int]
Face = Tuple[int, int, int]
GHOST = -1 # the vertex at infinity; a tetrahedron with it is a hull face
# polynomials in one variable s: lists of coefficients, index = power
def padd(p: Sequence, q: Sequence) -> list:
n = max(len(p), len(q))
return [(p[i] if i < len(p) else 0) + (q[i] if i < len(q) else 0) for i in range(n)]
def pmul(p: Sequence, q: Sequence) -> list:
out = [0] * (len(p) + len(q) - 1)
for i, a in enumerate(p):
for j, b in enumerate(q):
out[i + j] += a * b
return out
def peval(p: Sequence, x):
v = 0
for c in reversed(p):
v = v * x + c
return v
def _trim(p: Sequence) -> list:
p = list(p)
while len(p) > 1 and p[-1] == 0:
p.pop()
return p
def _sign(x) -> int:
return (x > 0) - (x < 0)
def _rem(a: Sequence, b: Sequence) -> list:
a = [Fraction(x) for x in a]
while len(a) >= len(b) and not (len(a) == 1 and a[0] == 0):
c = a[-1] / b[-1]
sh = len(a) - len(b)
for i in range(len(b)):
a[sh + i] -= c * b[i]
a.pop()
a = _trim(a) if a else [Fraction(0)]
return a
def sturm(p: Sequence) -> List[list]:
"""The Sturm sequence p, p', -rem(p, p'), ... of a nonzero polynomial."""
p = _trim(p)
seq = [p]
if len(p) == 1:
return seq
seq.append([i * p[i] for i in range(1, len(p))])
while len(seq[-1]) > 1:
r = _rem(seq[-2], seq[-1])
if len(r) == 1 and r[0] == 0:
break
seq.append([-x for x in r])
return seq
def _variations(seq: List[list], x) -> int:
"""Sign changes of the sequence at x; x = None means +infinity, '-' means -infinity."""
signs = []
for q in seq:
if x is None:
s = _sign(q[-1])
elif x == "-":
s = _sign(q[-1]) * (-1) ** (len(q) - 1)
else:
s = _sign(peval(q, x))
if s:
signs.append(s)
return sum(1 for i in range(1, len(signs)) if signs[i] != signs[i - 1])
def count_roots(seq: List[list], lo, hi) -> int:
"""Number of distinct real roots of seq[0] in (lo, hi] (Sturm's theorem)."""
return _variations(seq, lo) - _variations(seq, hi)
def _quo(a: Sequence, b: Sequence) -> list:
"""The quotient of a by b, for b dividing a exactly."""
a = [Fraction(x) for x in a]
q = [Fraction(0)] * (len(a) - len(b) + 1)
for sh in range(len(a) - len(b), -1, -1):
c = a[sh + len(b) - 1] / b[-1]
q[sh] = c
for i in range(len(b)):
a[sh + i] -= c * b[i]
return _trim(q)
def root_bound(p: Sequence) -> Fraction:
"""Cauchy's bound: every real root has absolute value below it."""
p = _trim(p)
return 1 + max(Fraction(abs(c), abs(p[-1])) for c in p[:-1])
def roots_in(p: Sequence, lo, hi, tol: Fraction) -> List[Fraction]:
"""The distinct real roots of p in [lo, hi], each to within tol.
lo is a Fraction or '-' for minus infinity; hi a Fraction or None for plus
infinity. The number of roots is exact; only their positions are approximate.
A repeated root is first removed by dividing p by gcd(p, p'), so that every
remaining root is simple and Sturm's theorem counts the roots in (a, b]
even when a or b is a root.
"""
p = _trim(p)
if len(p) == 1:
if p[0] == 0:
raise ValueError("the line lies in the surface")
return []
seq = sturm(p)
if len(seq[-1]) > 1: # p has a repeated root: keep its square-free part, same distinct roots
p = _quo(p, seq[-1])
seq = sturm(p)
out = []
if lo == "-":
lo = -root_bound(p)
elif peval(p, lo) == 0:
out.append(Fraction(lo))
if hi is None:
hi = root_bound(p)
stack = [(Fraction(lo), Fraction(hi))]
while stack:
a, b = stack.pop()
n = count_roots(seq, a, b)
if n == 0:
continue
sa, sb = _sign(peval(p, a)), _sign(peval(p, b))
if n == 1 and sb == 0:
out.append(b)
elif n == 1 and sa * sb < 0:
while b - a > tol: # one simple root, where p changes sign
m = (a + b) / 2
sm = _sign(peval(p, m))
if sm == 0:
a = b = m
elif sm == sa:
a = m
else:
b = m
out.append((a + b) / 2)
elif b - a <= tol:
out.append(b if sb == 0 else (a + b) / 2)
else:
m = (a + b) / 2
stack.append((m, b))
stack.append((a, m))
return sorted(out)
def _sq(a, b) -> list:
"""(a + b s)^2."""
return [a * a, 2 * a * b, b * b]
class Sphere:
"""The sphere |x| = R. Its medial axis is the center, so lfs = R everywhere."""
euler = 2
def __init__(self, R: int):
if int(R) != R or R <= 0:
raise ValueError("R must be a positive integer")
self.R = int(R)
def poly(self, A: Sequence[int], B: Sequence[int], W: int) -> list:
"""W^2 F((A + s B) / W) as a polynomial in s with integer coefficients."""
p = [-self.R * self.R * W * W]
for k in range(3):
p = padd(p, _sq(A[k], B[k]))
return p
def distance(self, p: Sequence) -> float:
return abs(math.sqrt(sum(float(x) ** 2 for x in p)) - self.R)
def lfs(self, p: Sequence) -> float:
return float(self.R)
def project(self, p: Sequence[float]) -> tuple:
n = math.sqrt(sum(x * x for x in p))
return tuple(x * self.R / n for x in p)
def normal(self, p: Sequence[float]) -> tuple:
n = math.sqrt(sum(x * x for x in p))
return tuple(x / n for x in p)
def seeds(self, rng: random.Random) -> List[tuple]:
"""Four points of a randomly rotated regular tetrahedron on the sphere."""
q = _random_rotation(rng)
base = [(1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1)]
return [self.project(_apply(q, v)) for v in base]
class Torus:
"""The torus at distance r from the circle of radius R in the plane z = 0.
With R >= 2 r its medial axis is that circle together with the z axis, so
lfs = r everywhere.
"""
euler = 0
def __init__(self, R: int, r: int):
if int(R) != R or int(r) != r or r <= 0 or R < 2 * r:
raise ValueError("need integers R >= 2 r > 0")
self.R, self.r = int(R), int(r)
def poly(self, A: Sequence[int], B: Sequence[int], W: int) -> list:
"""W^4 F((A + s B) / W) with F = (|x|^2 + R^2 - r^2)^2 - 4 R^2 (x^2 + y^2)."""
R2, r2, W2 = self.R * self.R, self.r * self.r, W * W
xy = padd(_sq(A[0], B[0]), _sq(A[1], B[1]))
q = padd(padd(xy, _sq(A[2], B[2])), [(R2 - r2) * W2])
return padd(pmul(q, q), [-4 * R2 * W2 * c for c in xy])
def _core(self, p: Sequence[float]) -> tuple:
rho = math.hypot(p[0], p[1])
return (self.R * p[0] / rho, self.R * p[1] / rho, 0.0)
def distance(self, p: Sequence) -> float:
q = [float(x) for x in p]
return abs(math.hypot(math.hypot(q[0], q[1]) - self.R, q[2]) - self.r)
def lfs(self, p: Sequence) -> float:
return float(self.r)
def normal(self, p: Sequence[float]) -> tuple:
c = self._core(p)
d = sub(p, c)
n = math.sqrt(dot(d, d))
return tuple(x / n for x in d)
def project(self, p: Sequence[float]) -> tuple:
c = self._core(p)
return tuple(c[k] + self.r * v for k, v in enumerate(self.normal(p)))
def seeds(self, rng: random.Random) -> List[tuple]:
"""Four points spread around the torus, at random angles."""
out = []
a0 = rng.uniform(0, 2 * math.pi)
for i in range(4):
a = a0 + i * math.pi / 2
b = rng.uniform(0, 2 * math.pi)
rho = self.R + self.r * math.cos(b)
out.append((rho * math.cos(a), rho * math.sin(a), self.r * math.sin(b)))
return out
def _random_rotation(rng: random.Random) -> list:
q = [rng.gauss(0, 1) for _ in range(4)]
n = math.sqrt(sum(x * x for x in q))
w, x, y, z = (v / n for v in q)
return [
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
]
def _apply(m: list, v: Sequence) -> tuple:
return tuple(sum(m[i][j] * v[j] for j in range(3)) for i in range(3))
def _round(p: Sequence) -> tuple:
return tuple(int(round(x)) for x in p)
def faces_of(t: Tet) -> List[Face]:
return [t[:i] + t[i + 1 :] for i in range(4)]
def circumcenter_hom(a, b, c, d) -> Tuple[tuple, int]:
"""The circumcenter of a tetrahedron as N / W with integer N and W > 0."""
u, v, w = sub(b, a), sub(c, a), sub(d, a)
det = dot(u, cross(v, w))
if det == 0:
raise ValueError("flat tetrahedron")
uu, vv, ww = dot(u, u), dot(v, v), dot(w, w)
cvw, cwu, cuv = cross(v, w), cross(w, u), cross(u, v)
N = tuple(2 * det * a[k] + uu * cvw[k] + vv * cwu[k] + ww * cuv[k] for k in range(3))
W = 2 * det
return (N, W) if W > 0 else (tuple(-x for x in N), -W)
class Mesher:
"""The 3D Delaunay triangulation of the sample, kept with hull (ghost) tetrahedra,
and its restricted Delaunay triangles."""
def __init__(self, surface, sigma: Union[float, Callable], seed: int = 0, max_vertices: int = 2000):
self.S = surface
self.sigma = sigma if callable(sigma) else (lambda p, s=float(sigma): s)
self.max_vertices = max_vertices
self.rng = random.Random(seed)
self.pts: List[tuple] = []
self.tets: Set[Tet] = set()
self.face_tets: Dict[Face, Set[Tet]] = {}
self.cc: Dict[Tet, Tuple[tuple, int]] = {}
self.inside: Optional[tuple] = None
self.balls: Dict[Face, List[tuple]] = {} # restricted face -> [(center, r, sigma(center))]
self.persistent: List[Face] = []
self.log: List[tuple] = [] # (center, r, sigma) of each inserted point
# the oracle: where a Voronoi edge meets S
def voronoi_edge(self, f: Face) -> Tuple[tuple, tuple, int, Optional[int]]:
"""The Voronoi edge dual to face f as (A, B, W, end): the points (A + s B) / W
for s in [0, end], with end = None for a ray."""
t1, t2 = self.face_tets[f]
if t1[0] == GHOST:
t1, t2 = t2, t1
N1, W1 = self.cc[t1]
if t2[0] != GHOST:
N2, W2 = self.cc[t2]
A = tuple(x * W2 for x in N1)
return A, tuple(N2[k] * W1 - A[k] for k in range(3)), W1 * W2, 1
a, b, c = (self.pts[v] for v in f)
d = self.pts[next(v for v in t1 if v not in f)]
n = cross(sub(b, a), sub(c, a))
if dot(n, sub(d, a)) > 0:
n = tuple(-x for x in n)
return N1, tuple(W1 * x for x in n), W1, None
def surface_balls(self, f: Face) -> List[tuple]:
A, B, W, end = self.voronoi_edge(f)
G = self.S.poly(A, B, W) # @line L3
length = math.sqrt(sum(float(x) ** 2 for x in B)) / W
tol = Fraction(1, 8) / max(1, math.ceil(length))
out = []
a = self.pts[f[0]]
for s in roots_in(G, Fraction(0), end, tol):
x = tuple((A[k] + s * B[k]) / W for k in range(3))
c = _round(x)
r = math.sqrt(float(dist2(x, a)))
out.append((c, r, self.sigma(c)))
return out
# Bowyer-Watson insertion with ghost tetrahedra
def conflicts(self, t: Tet, p: tuple) -> bool:
if t[0] == GHOST:
f = [self.pts[v] for v in t[1:]]
o = orient3d(*f, p)
if o == 0:
raise ValueError("degenerate input: a point on the plane of a hull face")
return _sign(o) != _sign(orient3d(*f, self.inside))
return insphere(*[self.pts[v] for v in t], p) > 0
def _add_tet(self, t: Tet) -> None:
t = tuple(sorted(t))
if t[0] != GHOST:
self.cc[t] = circumcenter_hom(*[self.pts[v] for v in t])
self.tets.add(t)
for f in faces_of(t):
self.face_tets.setdefault(f, set()).add(t)
def _remove_tet(self, t: Tet) -> None:
self.tets.discard(t)
self.cc.pop(t, None)
for f in faces_of(t):
s = self.face_tets[f]
s.discard(t)
if not s:
del self.face_tets[f]
def insert(self, p: tuple, hint: Sequence[Tet] = ()) -> int:
if len(self.pts) >= self.max_vertices:
raise RuntimeError("too many vertices")
if p in self.pts:
raise ValueError("repeated point")
start = next((t for t in hint if t in self.tets and self.conflicts(t, p)), None)
if start is None:
start = next(t for t in sorted(self.tets) if self.conflicts(t, p))
cavity = {start}
stack = [start]
while stack:
t = stack.pop()
for f in faces_of(t):
for u in self.face_tets[f]:
if u not in cavity and self.conflicts(u, p):
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)
self.pts.append(p)
v = len(self.pts) - 1
for t in cavity:
self._remove_tet(t)
new = []
for f in boundary:
real = [self.pts[w] for w in f if w != GHOST]
if len(real) == 3 and orient3d(*real, p) == 0:
raise ValueError("degenerate input: cospherical or coplanar points")
self._add_tet(f + (v,))
new.append(tuple(sorted(f + (v,))))
return v
def _start(self, pts: Sequence[tuple]) -> None:
"""The first tetrahedron and its four hull faces, then the other points."""
a, b, c = pts[0], pts[1], pts[2]
i = next(i for i in range(3, len(pts)) if orient3d(a, b, c, pts[i]) != 0)
first = [a, b, c, pts[i]]
self.pts = list(first)
self.inside = tuple(Fraction(sum(q[k] for q in first), 4) for k in range(3))
self._add_tet((0, 1, 2, 3))
for f in faces_of((0, 1, 2, 3)):
self._add_tet((GHOST,) + f)
for q in pts[3:i] + pts[i + 1 :]:
self.insert(q)
# restricted Delaunay triangles
def update_faces(self, faces) -> None:
for f in faces:
if GHOST in f:
continue
if f not in self.face_tets:
self.balls.pop(f, None)
continue
b = self.surface_balls(f)
if b:
self.balls[f] = b
else:
self.balls.pop(f, None)
def restricted(self) -> Set[Face]:
return set(self.balls)
def worst_ball(self) -> Optional[tuple]:
best = None
for f in sorted(self.balls):
for c, r, sg in self.balls[f]:
if r > sg and (best is None or r / sg > best[0]):
best = (r / sg, f, c, r, sg)
return best
def initial_sample(self) -> List[tuple]:
"""Section 7 of the paper: three points of S near each seed, forming a persistent facet."""
seeds = self.S.seeds(self.rng)
out = []
for x in seeds:
d = min(math.dist(x, y) for y in seeds if y is not x)
rad = 0.99 * min(d / 6, self.S.lfs(x), self.sigma(_round(x)) / 6)
for _ in range(50):
tri = self._triangle_near(x, rad)
if tri is not None:
out.extend(tri)
break
else:
raise RuntimeError("no persistent facet found near a seed")
return out
def _triangle_near(self, x: tuple, rad: float) -> Optional[List[tuple]]:
n = self.S.normal(x)
e = (1.0, 0.0, 0.0) if abs(n[0]) < 0.9 else (0.0, 1.0, 0.0)
t1 = cross(n, e)
l1 = math.sqrt(dot(t1, t1))
t1 = tuple(v / l1 for v in t1)
t2 = cross(n, t1)
a0 = self.rng.uniform(0, 2 * math.pi)
tri = []
for i in range(3):
a = a0 + i * 2 * math.pi / 3 + self.rng.uniform(-0.3, 0.3)
q = tuple(x[k] + 0.5 * rad * (math.cos(a) * t1[k] + math.sin(a) * t2[k]) for k in range(3))
tri.append(_round(self.S.project(q)))
if len(set(tri)) < 3:
return None
# the line through the circumcenter, normal to the triangle, must meet S inside B(x, rad)
a, b, c = tri
u, v = sub(b, a), sub(c, a)
nn = cross(u, v)
W = 2 * dot(nn, nn)
if W == 0:
return None
N = tuple(W * a[k] + dot(u, u) * cross(v, nn)[k] + dot(v, v) * cross(nn, u)[k] for k in range(3))
G = self.S.poly(N, tuple(W * k for k in nn), W)
for s in roots_in(G, "-", None, Fraction(1, 1 << 40)):
y = tuple(float((N[k] + s * W * nn[k]) / W) for k in range(3))
if math.dist(y, x) < rad:
return tri
return None
def run(self) -> None:
init = self.initial_sample() # @line L1
self._start(init) # @line L2
self.persistent = [tuple(sorted(self.pts.index(q) for q in init[i : i + 3])) for i in range(0, len(init), 3)]
self.update_faces(list(self.face_tets))
while True:
w = self.worst_ball() # @line L4
if w is None:
break
_, f, c, r, sg = w # @line L5
old = set(self.tets)
self.insert(c, sorted(self.face_tets[f])) # @line L6
self.log.append((c, r, sg))
gone = old - self.tets
born = self.tets - old
touched = {g for t in gone | born for g in faces_of(t)}
self.update_faces(sorted(touched)) # @line L7
def delaunay_surface_mesh(surface, sigma: Union[float, Callable], seed: int = 0, max_vertices: int = 2000) -> Mesher:
"""Mesh the surface until every surface Delaunay ball B(c, r) has r <= sigma(c).
sigma is a number or a function of a point, in the integer units of the
surface, and must be positive and 1-Lipschitz. Returns the Mesher: pts holds
the sample and restricted() the triangles of the restricted Delaunay
triangulation, as triples of indices into pts.
"""
m = Mesher(surface, sigma, seed, max_vertices)
m.run()
return m # @line L8
mg2geom.py 159 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mg2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small exact geometric tools used by the mg2 pages.
Points are tuples of int or fractions.Fraction. Every predicate returns an
exact value when the coordinates are int or Fraction, so its sign is the true
sign. A float converts to a Fraction without rounding (exact()), so the sign
is then exact for the float point as it is stored. The angle functions return
floats and are used only to report or to compare with a stated bound.
"""
import math
from fractions import Fraction
from typing import Sequence, Tuple
Point = Tuple
def exact(p: Point) -> Tuple[Fraction, ...]:
"""The point p with each coordinate converted to Fraction, without rounding."""
return tuple(Fraction(c) for c in p)
def sub(a: Point, b: Point) -> tuple:
return tuple(x - y for x, y in zip(a, b))
def dot(a: Point, b: Point):
return sum(x * y for x, y in zip(a, b))
def cross(a: Point, b: Point) -> tuple:
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def dist2(a: Point, b: Point):
return sum((x - y) * (x - y) for x, y in zip(a, b))
def det3(r0: Sequence, r1: Sequence, r2: Sequence):
return dot(r0, cross(r1, r2))
def det4(m: Sequence[Sequence]):
"""Determinant of a 4 by 4 matrix by cofactor expansion along the first row."""
total = 0
for j in range(4):
minor = [[m[i][k] for k in range(4) if k != j] for i in range(1, 4)]
term = m[0][j] * det3(minor[0], minor[1], minor[2])
total += term if j % 2 == 0 else -term
return total
def orient2d(a: Point, b: Point, c: Point):
"""Twice the signed area of the triangle a, b, c; positive if counterclockwise."""
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def orient3d(a: Point, b: Point, c: Point, d: Point):
"""Six times the signed volume of the tetrahedron a, b, c, d.
It is det[b - a, c - a, d - a]: positive when d lies on the side of the
plane abc from which a, b, c appear clockwise.
"""
return det3(sub(b, a), sub(c, a), sub(d, a))
def insphere(a: Point, b: Point, c: Point, d: Point, e: Point):
"""Positive if e lies inside the sphere through a, b, c, d, zero on it.
The value is det of the rows (p - e, |p - e|^2) for p = a, b, c, d,
divided by nothing, times the sign of orient3d(a, b, c, d), so the result
does not depend on the order of a, b, c, d. The tetrahedron must not be flat.
"""
rows = []
for p in (a, b, c, d):
v = sub(p, e)
rows.append([v[0], v[1], v[2], dot(v, v)])
o = orient3d(a, b, c, d)
if o == 0:
raise ValueError("flat tetrahedron")
val = -det4(rows)
return val if o > 0 else -val
def circumcenter3(a: Point, b: Point, c: Point, d: Point) -> tuple:
"""Exact circumcenter of a tetrahedron, by Cramer's rule on 2 (p - a) . x = |p - a|^2."""
u, v, w = sub(b, a), sub(c, a), sub(d, a)
det = det3(u, v, w)
if det == 0:
raise ValueError("flat tetrahedron")
bu, bv, bw = Fraction(dot(u, u)), Fraction(dot(v, v)), Fraction(dot(w, w))
# x = (bu (v x w) + bv (w x u) + bw (u x v)) / (2 det)
cvw, cwu, cuv = cross(v, w), cross(w, u), cross(u, v)
x = tuple((bu * cvw[k] + bv * cwu[k] + bw * cuv[k]) / (2 * det) for k in range(3))
return tuple(a[k] + x[k] for k in range(3))
def tri_circumcenter3(a: Point, b: Point, c: Point) -> tuple:
"""Exact circumcenter of a triangle in space (the center of its smallest circumscribed sphere)."""
u, v = sub(b, a), sub(c, a)
n = cross(u, v)
nn = Fraction(dot(n, n))
if nn == 0:
raise ValueError("flat triangle")
t1 = cross(n, u)
t2 = cross(v, n)
uu, vv = dot(u, u), dot(v, v)
# x = (|u|^2 (v x n) + |v|^2 (n x u)) / (2 |n|^2)
return tuple(a[k] + (uu * t2[k] + vv * t1[k]) / (2 * nn) for k in range(3))
def radius_edge2(a: Point, b: Point, c: Point, d: Point) -> Fraction:
"""Exact square of the radius-edge ratio R / l_min of a tetrahedron."""
cc = circumcenter3(a, b, c, d)
r2 = dist2(cc, a)
pts = (a, b, c, d)
lmin2 = min(dist2(pts[i], pts[j]) for i in range(4) for j in range(i + 1, 4))
return Fraction(r2) / Fraction(lmin2)
def _angle(u: Sequence[float], v: Sequence[float]) -> float:
nu = math.sqrt(sum(x * x for x in u))
nv = math.sqrt(sum(x * x for x in v))
c = sum(x * y for x, y in zip(u, v)) / (nu * nv)
return math.degrees(math.acos(max(-1.0, min(1.0, c))))
def triangle_angles_deg(a: Point, b: Point, c: Point) -> list:
"""The three plane angles of a triangle in degrees, in 2D or 3D (floats)."""
p = [tuple(float(x) for x in q) for q in (a, b, c)]
out = []
for i in range(3):
o, s, t = p[i], p[(i + 1) % 3], p[(i + 2) % 3]
out.append(_angle(sub(s, o), sub(t, o)))
return out
def dihedral_angles_deg(a: Point, b: Point, c: Point, d: Point) -> list:
"""The six dihedral angles of a tetrahedron in degrees (floats).
The angle at edge pq is the angle between the two faces pqr and pqs,
measured inside the tetrahedron.
"""
p = [tuple(float(x) for x in q) for q in (a, b, c, d)]
out = []
for i in range(4):
for j in range(i + 1, 4):
k, m = [t for t in range(4) if t not in (i, j)]
e = sub(p[j], p[i])
ee = dot(e, e)
# components of p_k - p_i and p_m - p_i orthogonal to the edge
u = sub(p[k], p[i])
v = sub(p[m], p[i])
u = tuple(u[t] - dot(u, e) / ee * e[t] for t in range(3))
v = tuple(v[t] - dot(v, e) / ee * e[t] for t in range(3))
out.append(_angle(u, v))
return out
test_delaunay_surface_meshing.py 338 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delaunay-surface-meshing/. The authors are listed in prov/8F2351.jsonl.
import math
import random
from collections import Counter, defaultdict
from fractions import Fraction as F
from functools import lru_cache
from itertools import combinations
import pytest
from delaunay_surface_meshing import (
GHOST,
Mesher,
Sphere,
Torus,
count_roots,
delaunay_surface_mesh,
faces_of,
peval,
pmul,
roots_in,
sturm,
)
from mg2geom import cross, dist2, dot, insphere, orient3d, sub
R = 1 << 20
SPHERE = Sphere(R)
TORUS = Torus(3 << 18, 1 << 18) # lfs = r = 2^18 everywhere
LFS = {"sphere": R, "torus": 1 << 18}
SURF = {"sphere": SPHERE, "torus": TORUS}
CASES = [("sphere", F(1, 2), 1), ("torus", F(3, 2), 1), ("sphere", F(3, 10), 2)]
ROUND = math.sqrt(3) / 2 # rounding to the grid moves a point at most this far
# a computed center is within 1/8 of the exact point of S on the Voronoi edge, then rounded
@lru_cache(maxsize=None)
def run(kind, eps, seed):
return delaunay_surface_mesh(SURF[kind], float(eps * LFS[kind]), seed=seed)
def edge_count(T):
E = Counter()
for f in T:
for e in combinations(f, 2):
E[e] += 1
return E
def brute_restricted(S, pts):
"""Restricted Delaunay triangles straight from the definition: abc is one if some
point of S has a, b, c among its nearest sample points (an empty ball centered on S)."""
out = set()
n = len(pts)
for i, j, k in combinations(range(n), 3):
a, b, c = pts[i], pts[j], pts[k]
u, v = sub(b, a), sub(c, a)
nn = cross(u, v)
W = 2 * dot(nn, nn)
if W == 0:
continue
# the points equidistant from a, b, c: (N + s W nn) / W
N = tuple(W * a[t] + dot(u, u) * cross(v, nn)[t] + dot(v, v) * cross(nn, u)[t] for t in range(3))
cf = [x / W for x in N]
others = sorted((p for q, p in enumerate(pts) if q not in (i, j, k)), key=lambda p: math.dist(p, cf))
lo, hi, empty = None, None, False # bounds on s as (numerator, positive denominator)
aa = dot(a, a)
for p in others:
# |x - p|^2 >= |x - a|^2 <=> alpha + s beta >= 0
d = sub(a, p)
alpha = 2 * dot(d, N) + W * (dot(p, p) - aa)
beta = 2 * W * dot(d, nn)
if beta == 0:
empty = alpha < 0
elif beta > 0: # s >= -alpha / beta
if lo is None or -alpha * lo[1] > lo[0] * beta:
lo = (-alpha, beta)
else: # s <= alpha / -beta
if hi is None or alpha * hi[1] < hi[0] * -beta:
hi = (alpha, -beta)
if empty or (lo is not None and hi is not None and lo[0] * hi[1] > hi[0] * lo[1]):
empty = True
break
if empty:
continue
G = S.poly(N, tuple(W * x for x in nn), W)
lo = "-" if lo is None else F(*lo)
hi = None if hi is None else F(*hi)
if roots_in(G, lo, hi, F(1, 1 << 30)):
out.add((i, j, k))
return out
# the exact tools
def test_sturm_counts_and_locates_roots():
rng = random.Random(5)
for _ in range(40):
roots = sorted({F(rng.randint(-40, 40), rng.randint(1, 6)) for _ in range(rng.randint(1, 4))})
p = [1]
for x in roots:
p = pmul(p, [-x.numerator, x.denominator])
if rng.random() < 0.3:
p = pmul(p, [1, 0, 1]) # s^2 + 1 adds no real root
if rng.random() < 0.3:
p = pmul(p, [-roots[0].numerator, roots[0].denominator]) # a double root counts once
seq = sturm(p)
lo, hi = F(rng.randint(-50, 0)), F(rng.randint(0, 50))
a, b = lo + F(1, 1000), hi + F(1, 1000) # not roots, so the count is exact even for p
assert count_roots(seq, a, b) == sum(1 for x in roots if a < x <= b)
got = roots_in(p, lo, hi, F(1, 1000))
want = [x for x in roots if lo <= x <= hi]
assert len(got) == len(want)
assert all(abs(g - w) <= F(1, 1000) for g, w in zip(got, want))
assert len(roots_in(p, "-", None, F(1, 1000))) == len(roots)
def test_surface_polynomial_is_the_implicit_function_on_the_line():
rng = random.Random(6)
for S, deg in ((SPHERE, 2), (TORUS, 4)):
for _ in range(20):
A = tuple(rng.randint(-(1 << 30), 1 << 30) for _ in range(3))
B = tuple(rng.randint(-(1 << 30), 1 << 30) for _ in range(3))
W = rng.randint(1, 1 << 10)
s = F(rng.randint(-100, 100), rng.randint(1, 100))
x = [(A[k] + s * B[k]) / W for k in range(3)]
if S is SPHERE:
val = sum(c * c for c in x) - R * R
else:
q = sum(c * c for c in x) + S.R ** 2 - S.r ** 2
val = q * q - 4 * S.R ** 2 * (x[0] ** 2 + x[1] ** 2)
assert peval(S.poly(A, B, W), s) == val * W ** deg
# the output
@pytest.mark.parametrize("case", CASES)
def test_every_vertex_lies_on_the_surface(case):
m = run(*case)
S = SURF[case[0]]
assert max(S.distance(p) for p in m.pts) <= ROUND + 1 / 8
@pytest.mark.parametrize("case", CASES[:2] + [("torus", F(2), 1)])
def test_restricted_triangles_match_brute_force(case):
m = run(*case)
want = brute_restricted(SURF[case[0]], m.pts)
assert m.restricted() == want
@pytest.mark.parametrize("case", CASES[:2] + [("torus", F(2), 1)])
def test_the_triangulation_is_delaunay(case):
m = run(*case)
n = len(m.pts)
real = [t for t in m.tets if t[0] != GHOST]
for t in real:
P = [m.pts[v] for v in t]
assert orient3d(*P) != 0
assert all(insphere(*P, m.pts[q]) < 0 for q in range(n) if q not in t)
for f, ts in m.face_tets.items():
assert len(ts) == 2
hull = [t[1:] for t in m.tets if t[0] == GHOST]
for f in hull: # every point is on the inner side of every hull face
P = [m.pts[v] for v in f]
sides = {(orient3d(*P, m.pts[q]) > 0) for q in range(n) if q not in f}
assert len(sides) == 1
used = {v for t in m.tets for v in t if v != GHOST}
assert used == set(range(n))
@pytest.mark.parametrize("case", CASES)
def test_incremental_update_equals_a_fresh_computation(case):
m = run(*case)
fresh = {}
for f in m.face_tets:
if GHOST not in f:
b = m.surface_balls(f)
if b:
fresh[f] = b
assert fresh == m.balls
@pytest.mark.parametrize("case", CASES)
def test_no_bad_ball_is_left(case):
"""At the end every surface Delaunay ball B(c, r) has r <= sigma(c), which with
sigma = eps lfs is Condition 1 of a loose eps-sample (Lemma 8.2)."""
m = run(*case)
kind, eps, _ = case
assert m.balls
for f, balls in m.balls.items():
for c, r, sg in balls:
assert r <= sg == float(eps * LFS[kind])
assert SURF[kind].distance(c) <= ROUND + 1 / 8
@pytest.mark.parametrize("case", CASES)
def test_output_is_a_closed_two_manifold_of_the_right_genus(case):
m = run(*case)
T = m.restricted()
E = edge_count(T)
assert set(E.values()) == {2}
V = {v for f in T for v in f}
assert V == set(range(len(m.pts)))
link = defaultdict(list)
for f in T:
for v in f:
link[v].append(tuple(x for x in f if x != v))
for v, edges in link.items(): # the link of every vertex is one cycle
adj = defaultdict(list)
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
assert all(len(x) == 2 for x in adj.values())
seen, stack = {edges[0][0]}, [edges[0][0]]
while stack:
for y in adj[stack.pop()]:
if y not in seen:
seen.add(y)
stack.append(y)
assert len(seen) == len(adj)
assert len(V) - len(E) + len(T) == SURF[case[0]].euler
# connected and orientable: orient one triangle and propagate across edges
orient = {}
first = min(T)
orient[first] = first
stack = [first]
by_edge = defaultdict(list)
for f in T:
for e in combinations(f, 2):
by_edge[e].append(f)
while stack:
f = stack.pop()
o = orient[f]
for i in range(3):
a, b = o[i], o[(i + 1) % 3]
for g in by_edge[tuple(sorted((a, b)))]:
if g == f:
continue
c = next(x for x in g if x not in (a, b))
want = (b, a, c)
if g in orient:
assert set(zip(orient[g], orient[g][1:] + orient[g][:1])) >= {(b, a)}
else:
orient[g] = want
stack.append(g)
assert len(orient) == len(T)
@pytest.mark.parametrize("case", CASES)
def test_persistent_facets_stay(case):
"""Section 7: each initial triple has a surface Delaunay ball of radius at most sigma / 3,
and Lemma 7.1: it is still a restricted triangle at the end."""
kind, eps, seed = case
m0 = Mesher(SURF[kind], float(eps * LFS[kind]), seed)
init = m0.initial_sample()
m0._start(init)
m0.update_faces(list(m0.face_tets))
pers = [tuple(sorted(m0.pts.index(q) for q in init[i : i + 3])) for i in range(0, len(init), 3)]
for f in pers:
assert any(r + ROUND <= sg / 3 for c, r, sg in m0.balls[f])
m = run(*case)
assert m.persistent == pers
assert all(f in m.restricted() for f in m.persistent)
@pytest.mark.parametrize("case", CASES)
def test_inserted_points_are_far_apart(case):
"""Lemma 8.1: a point is inserted at distance r > sigma(c) from the sample (less rounding)."""
m = run(*case)
k = len(m.pts) - len(m.log)
for i, (c, r, sg) in enumerate(m.log):
assert m.pts[k + i] == c and r > sg
d = min(math.sqrt(dist2(c, m.pts[j])) for j in range(k + i))
assert d >= r - ROUND
def test_example_sphere():
m = run("sphere", F(1, 2), 1)
assert len(m.pts) == 41 and len(m.log) == 29 and len(m.restricted()) == 78
ratios = [round(r / sg, 3) for c, r, sg in m.log]
assert ratios[0] == 2.256 and ratios[4] == 1.793 and ratios[10] == 1.233 and ratios[-1] == 1.0
assert all(x >= y - 0.01 for x, y in zip(ratios, ratios[1:])) # the worst ratio falls, nearly monotone
m0 = Mesher(SPHERE, R / 2, 1)
m0._start(m0.initial_sample())
m0.update_faces(list(m0.face_tets))
r0 = sorted(round(r / sg, 3) for f in m0.balls for c, r, sg in m0.balls[f])
assert len(m0.pts) == 12 and len(m0.balls) == 20
assert r0[:4] == [0.082] * 4 and r0[4] > 1 and r0[-1] == 2.256
# replay the loop: (points, restricted triangles, bad balls) before each insertion
trace = []
while True:
bad = sum(1 for f in m0.balls for c, r, sg in m0.balls[f] if r > sg)
trace.append((len(m0.pts), len(m0.balls), bad))
w = m0.worst_ball()
if w is None:
break
old = set(m0.tets)
m0.insert(w[2], sorted(m0.face_tets[w[1]]))
m0.update_faces(sorted({g for t in old ^ m0.tets for g in faces_of(t)}))
assert [trace[k] for k in (0, 4, 10, 22, 28, 29)] == [
(12, 20, 16),
(16, 28, 24),
(22, 40, 27),
(34, 64, 11),
(40, 76, 1),
(41, 78, 0),
]
assert all(t == 2 * p - 4 for p, t, _ in trace) # a triangulated sphere at every step
assert m0.pts == m.pts
def test_measured_versus_proved():
"""The guarantee needs sigma < 0.091 lfs. Measured: the torus comes out right at
sigma = 1.5 lfs, 16 times the proved threshold, but not at 2 lfs, and the sizes
stay below mu(S) / eps^2."""
good = run("torus", F(3, 2), 1)
assert len(good.pts) == 40 and set(edge_count(good.restricted()).values()) == {2}
bad = run("torus", F(2), 1)
assert len(bad.pts) == 20
E = edge_count(bad.restricted())
assert set(E.values()) != {2}
V = {v for f in bad.restricted() for v in f}
assert len(V) - len(E) + len(bad.restricted()) == 6
mu = 4 * math.pi # mu(S) = area / lfs^2 for the unit sphere
for eps, seed in ((F(1, 2), 1), (F(3, 10), 2)):
assert len(run("sphere", eps, seed).pts) < mu / float(eps) ** 2
def test_bad_input():
with pytest.raises(ValueError):
Sphere(0)
with pytest.raises(ValueError):
Torus(5, 3)
with pytest.raises(RuntimeError):
delaunay_surface_mesh(SPHERE, R / 5, seed=1, max_vertices=30)
History
Chew (1993) proposed meshing a curved surface by refining surface Delaunay balls. Edelsbrunner and Shah (1994, 1997) defined the restricted Delaunay triangulation and proved that the closed ball property makes it homeomorphic to the surface, and Amenta and Bern (1999) showed that for an -sample with every Voronoi face meets the surface in a topological ball or not at all. Boissonnat and Oudot (2005) introduced loose -samples, which a mesher can check on its own output, and proved that Chew-style refinement produces them with optimal size. Cheng, Dey, Ramos and Ray (2004, 2007) removed the need to know the local feature size, and the book of Cheng, Dey and Shewchuk (2013) gives the whole theory.
References
- Jean-Daniel Boissonnat and Steve Oudot, Provably good sampling and meshing of surfaces, Graphical Models 67(5), 2005, 405 to 451, Section 2 (surface Delaunay balls, Definition 2.2 of a loose epsilon-sample, Lemma 2.3), Section 2.3 (the constant epsilon_0, about 0.091), Theorems 4.3, 4.4 and 4.5 (manifold, homeomorphism and isotopy, Hausdorff distance at most 4.5 epsilon^2 times the largest d_M), Theorem 5.1 and Theorem 5.4 (lower and upper bounds on the size), Section 6 (the algorithm), Section 7 (persistent facets, Lemmas 7.1 and 7.2), Section 8 (Lemmas 8.1 to 8.4), Section 9.1 (removing skinny facets for angles below 30 degrees)
- L. Paul Chew, Guaranteed-quality mesh generation for curved surfaces, Proceedings of the 9th Annual Symposium on Computational Geometry, 1993, 274 to 280, the surface mesher that inserts centers of large surface Delaunay balls (general locator)
- Siu-Wing Cheng, Tamal K. Dey and Jonathan Richard Shewchuk, Delaunay Mesh Generation, CRC Press, 2013, Chapter 13 (restricted Delaunay triangulations of surface samples, pages 287 to 316), Chapter 14 (meshing smooth surfaces and volumes, pages 317 to 348)
- Siu-Wing Cheng, Tamal K. Dey, Edgar A. Ramos and Tathagata Ray, Sampling and meshing a surface with guaranteed topology and geometry, SIAM Journal on Computing 37(4), 2007, 1199 to 1227, refinement driven by the topological ball property instead of the local feature size (general locator)
- Jean-Daniel Boissonnat and Steve Oudot, Provably good sampling and meshing of Lipschitz surfaces, Proceedings of the 22nd Annual Symposium on Computational Geometry, 2006, 337 to 346, the extension to surfaces that are only Lipschitz (general locator)
- Herbert Edelsbrunner and Nimish R. Shah, Triangulating topological spaces, International Journal of Computational Geometry and Applications 7(4), 1997, 365 to 378, the restricted Delaunay triangulation and the closed ball property (general locator)
- Nina Amenta and Marshall Bern, Surface reconstruction by Voronoi filtering, Discrete and Computational Geometry 22(4), 1999, 481 to 504, the local feature size and epsilon-samples; Theorem 2 on Voronoi faces that meet the surface for epsilon below 0.1
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 8F2351 Edit this page History Report an error Markdown