Algorithmadvanced
Quadtree mesh generation
Also called Bern-Eppstein-Gilbert meshing.
Bern, Eppstein and Gilbert's triangulation of a planar point set from a balanced quadtree, with aspect ratio at most 4 and a size within a constant factor of the optimum.
- Solves
- Mesh generation
- Time
- O(n log n + k) worst
- Space
- O(k) extra
- Where
- k = the number of output triangles; n = the number of input points
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Marshall Bern, David Eppstein, John Gilbert, 1990
Quadtree mesh generation, in the form of Bern, Eppstein and Gilbert, triangulates a set of points in the plane. It refines a quadtree until each input point sits in a small box of its own with eight equal neighbors. It balances the tree so that boxes that share a side differ in size by at most a factor of 2. It moves the box corner nearest to each point onto the point and cuts every box into triangles by a fixed template. The result has every input point as a vertex, every triangle has aspect ratio at most 4, which gives every angle at least , and the number of triangles is within a constant factor of the least number that any triangulation with that aspect ratio can have. Both the shape bound and the size bound are proved results.
In plain words
Put a big square around the points. Cut a square into four whenever it holds two points, or a point that has another point too near, or a point that has a cut square close by. Then cut more squares until no square has a much smaller square next to it. Now every point is alone in a small square. Pull the nearest square corner onto the point. Last, cut each square into triangles. A square that did not move gets a center point and becomes right isosceles triangles. A square with a moved corner gets one diagonal, the one that gives the better triangles. Small squares appear only near points that are close together, so the mesh is fine where it must be and coarse elsewhere.
The problem
The input is a set of distinct points in the plane. The output is a triangulation of a square that contains , in which every point of is a vertex. The quality measure of the paper is the aspect ratio of a triangle: its longest side divided by the altitude onto that side. It is the measure of mesh quality that the size proofs use, in the normalization of Bern, Eppstein and Gilbert, , without the factor that the aspect ratio of that page has, and it controls the smallest angle through
The goal has two parts. Every triangle must have . The number of triangles must be at most a constant times the size of any triangulation of with the same aspect ratio bound. This page builds triangles in the root square only, so the points must be the only constraints. Polygons and segments need the variant of Section 5 of the paper.
The page makes two kinds of claim, and the reader must keep them apart.
- Proved bound. Every triangle has , so every angle is at least . This page proves it for its own templates (in
proofs/correctness.md), following Lemma 1 of the paper. - Proved bound with an unknown constant. The size is within a constant factor of the optimum (Theorem 1 and Corollary 1 of the paper). The paper proves that the constant exists but does not give its value. This page cites that result and does not prove it.
The algorithm
A box of the tree is a square. Its extended neighbors are the boxes of the same size that share a side or a corner with it. A leaf of side is crowded if it holds at least one point and one of these holds:
- C1. holds two or more points.
- C2. holds one point , and the nearest other point is closer than to .
- C3. A box of the same size near is split. The paper takes the 3 by 3 block of boxes around (the extended neighbors). This page takes the 5 by 5 block; the reason is below.
The tree is balanced if no side of a leaf has two or more box corners strictly inside it. Then two leaves that share part of a side differ in size by a factor of at most 2.
QUADTREE-MESH(X)- 1
R ← the square of side 4L concentric with the bounding square of X (L = its side) - 2
T ← the quadtree whose only leaf is R - 3
repeat - 4
if some leaf b is crowded (C1, C2 or C3) then - 5
split b; split each extended neighbor of b, after first splitting coarser leaves so that it exists - 6
else if a leaf b that holds a point lacks an extended neighbor of its own size then - 7
split the coarser leaf that covers that neighbor - 8
else if a side of some leaf b has two or more box corners inside it then - 9
split b - 10
else stop - 11
for each x ∈ X: replace the corner of x's leaf nearest to x (ties: smallest x, then smallest y) by x - 12
for each leaf b: - 13
if no corner of b moved: add the center c of b and join c to every corner and side midpoint of b - 14
else: cut the moved quadrilateral by the diagonal whose two triangles have the smaller largest A - 15
return the triangles
The paper takes a root of twice the size of the bounding square and says that any root works if its side is a constant times the diameter of and its sides are far from the points. A root of side keeps every point at distance from the boundary, so every leaf that holds a point has all eight extended neighbors inside the root.
Why the 5 by 5 block. The paper states that only boxes with unsplit sides get a moved corner, so the diagonal template of L14 always applies. With the 3 by 3 block of C3, this is not always true. For the three points , and , the point moves the corner , and two of the four boxes at that corner have a split side, because the split comes from a box two places away. The test file checks this case. With the 5 by 5 block, every box that touches the moved corner has all its side neighbors inside the 5 by 5 block of the point's box, so none of them is split, and the diagonal template always applies. The size argument of the paper uses C3 only through a fixed neighborhood of each box, so a larger fixed block should change only its constant. This page does not redo that argument.
All tests are exact. Box corners are dyadic fractions of the root, and the only predicates are comparisons of squared distances and the sign of ORIENT2D. The aspect ratio is a rational number, , so L14 compares fractions. With floating point, a point very close to a box side can be filed in the wrong box, and the tie in L11 can break two ways. Then two boxes can disagree about a moved corner and the mesh gets a hole. Exact arithmetic, as here, or a floating-point filter in the style of Shewchuk 1997 that falls back to exact arithmetic, removes the problem.
Example
Take . The bounding square has side , so the root has side 16 and its lower left corner is . The squared nearest neighbor distances are 10 for and and 16 for . Each round of the loop does all the splits of one rule. The numbers come from the implementation and the test file checks them.
| Round | Rule | Boxes | Width | Why |
|---|---|---|---|---|
| 1 | C1 | root | 16 | it holds all three points |
| 2 | C2 | 1, and its 3 extended neighbors | 8 | |
| 3 | C2 | 3, with their neighbors | 4 | and |
| 4 | C2 | 3, with their neighbors | 2 | and |
| 5 | L6 | the box at is made | 1 | the leaf of needs a neighbor there |
| 6 | L6 | the box at is made | 1 | the same |
| 7 | balance | 3 boxes | 4 | each touches boxes of width 1 |
At width 1 the points stop: and , and no box in the 5 by 5 blocks is split. The tree has 109 leaves: 68 of width 1, 39 of width 2 and 2 of width 4. In L11, each point sits at the middle of the left side of its unit box, so two corners tie, and the rule picks the lower one: moves to , moves to , and moves to .
| Triangles | Count | Aspect ratio | Smallest angle |
|---|---|---|---|
| unmoved boxes, center fan | 410 | 2 | 45° |
| moved boxes, diagonal away from the point | 6 | 2 | 45° |
| moved boxes, at the point | 6 | 5/4 | 53.13° |
| moved boxes, at the point | 6 | 3/2 | 45° |
| moved boxes, at the point | 6 | 5/2 | 26.57° |
The output has 232 vertices and 434 triangles, and the smallest angle is , in the triangle . Most of the triangles are far from the points. The root of side and the 5 by 5 block both add boxes; the paper notes that simple heuristics remove many of them afterwards without losing the bound.
Correctness
The proof is in proofs/correctness.md. It has five parts.
- The loop stops. Let be the smallest distance between two input points. The first box of the smallest size that is ever split was split by C1 or C2, because C3, L5, L6 and L9 all need an earlier split of a box of that size or smaller. C1 and C2 need side more than . So all split boxes are at least that large, and there are finitely many of them.
- Balance and the neighbor property hold. The loop stops only when L4, L6 and L8 find nothing. So the tree is balanced, every leaf with a point holds one point, has eight leaf neighbors of its size, and has no split box in its 5 by 5 block.
- The moves are consistent. The moved corner of is within of . Two points cannot move the same corner, and no box gets two moved corners, because C2 keeps the other points at least away. The tie rule removes the one equality case.
- Every triangle has . The center fan gives right isosceles triangles with . For a moved box, scale it to with the moved corner at the origin. The point lies in . If it lies in , the diagonal through the point gives . Otherwise the other diagonal gives . L14 takes the better of the two.
- The triangles tile . All are counterclockwise, every inner edge is used once in each direction, and the other edges lie on the boundary of . A covering count argument then shows that each point of lies in exactly one triangle.
Size optimality is not proved here. Theorem 1 of the paper shows for every triangulation that contains , and Corollary 1 turns this into a constant factor of the optimum for any fixed aspect ratio bound . Those results are for the 3 by 3 block of the paper; for the 5 by 5 block of this page they should hold with a larger constant, but this page does not prove it.
Proof: QUADTREE-MESH stops with a balanced tree and a triangulation of the root square whose triangles all have aspect ratio at most 4full
Claim. Let be a set of distinct points with rational coordinates. Then QUADTREE-MESH, with C3 over the 5 by 5 block, stops. At the end the quadtree is balanced, and every leaf that holds a point holds exactly one and is surrounded by eight leaves of its own size. The output is a triangulation of the root square that has every point of as a vertex, and every triangle has aspect ratio . So every angle is at least .
What is not claimed. The size bound of Bern, Eppstein and Gilbert (Theorem 1 and Corollary 1 of their paper) is cited, not proved here.
Notation. For a triangle, , where is the longest side and the altitude onto it. Since , we have . If is the smallest angle and a side next to it other than the longest, then , so . Thus gives . A box is internal if it has been split. The block of radius of a box of level is the set of level boxes whose column and row differ from those of by at most .
Step 1: the loop stops. Let be the smallest distance between two points of . Every split in the run is of one of these kinds: a crowded box (L5, first part), a neighbor of a crowded box or a coarser box split to create it (L5, second part), a coarser box that covers a missing neighbor (L7), or an unbalanced leaf (L9). Suppose some box is split, and let be the smallest side of a box that is ever split. Look at the first split, in time order, of a box of side .
- If it was crowded by C3, a box of side in its block was already internal, so an earlier split of a box of side exists. Contradiction.
- If it was split in the second part of L5, the crowded box was split just before it, and that box has side at most . By the choice of it has side , and it was split earlier. Contradiction.
- If it was split in L7, it covers a missing neighbor of a leaf of side that holds a point, so , and that leaf exists because its parent, of side , was split before. Again an earlier split of a box of side at most exists. Contradiction.
- If it was split in L9, one of its sides has two corners inside, so a box of side was split earlier. Contradiction with the choice of .
So the first split of side was by C1 or C2. With C1 the box holds two points, so its diagonal is at least and . With C2 the box holds a point whose nearest neighbor is closer than , so . Every split box therefore has side more than . The root holds finitely many boxes of that size or larger, and each is split at most once. Each round of the loop splits at least one box, so the loop stops.
Step 2: the state at the end. The loop stops only when no leaf is crowded, no leaf with a point lacks a neighbor of its size, and no leaf is unbalanced. So the tree is balanced. Let be a leaf of side that holds a point . C1 fails, so is the only point in . C2 fails, so every other point is at distance at least from . L6 fails, so all eight extended neighbors of exist, and C3 fails, so no box of the 5 by 5 block is internal. In particular the eight extended neighbors are leaves. They lie in the root. The root has side and its boundary is at distance at least from , so a box that holds a point and touches the boundary has side at least , which means side or . Such a box is crowded by C1 or C2, because any two points are at most apart. So a final leaf with a point does not touch the boundary, and its eight neighbors, which are boxes of the same grid, lie inside the root.
Step 3: the moves. Let lie in leaf of side and let be its chosen corner. Since is a nearest corner, lies in the closed quarter of at , so . The four boxes with corner are and three of its extended neighbors, all leaves of side .
(a) Two points never move the same corner. If and both chose , then lies in one of these four boxes, of side , so . This contradicts Step 2.
(b) No box has two moved corners. Let a box of side have moved corners and , moved by and . The leaves of and both touch , so they are extended neighbors of and all have side . If and are adjacent corners, . If they are opposite corners, , and Step 2 forces equality. Equality needs , so is the center of its box, and lie on one diagonal line. At the center all four corners tie, and the tie rule picks the lower left corner, so is the lower left corner of the box of . The points lie on one line in the order , and is the corner of opposite to , so lies below and to the left of , and is the upper right corner of . The same argument with in place of shows that is the upper right corner of as well. So , a contradiction.
(c) A box with a moved corner has no split side. Let have the moved corner of , where lies in . The box lies in the 3 by 3 block of , so each box across a side of , at the level of , lies in the 5 by 5 block of . By Step 2 none of them is internal. A side of a leaf has a corner inside it only if the box of the same level across that side is internal. So the sides of hold no corner inside.
By (a), (b) and (c), every leaf with a moved corner is a quadrilateral with exactly one moved corner and no other boundary vertex, which is the case L14 handles.
Step 4: the unmoved boxes. By balance, the vertices on a side of an unmoved leaf of side are its two corners and, if the box across is internal, the midpoint. The fan from the center gives two kinds of triangles. A triangle , corner, corner has a right angle at and legs . A triangle , corner, midpoint has a right angle at the midpoint and legs . Both are right isosceles, with .
Step 5: the moved boxes. Scale, rotate and reflect so that the box is and its moved corner is the origin. These maps do not change . The other corners are , and . By Step 3, lies in the quarter at the origin of a box with corner , so . L14 takes, among the diagonals whose two triangles are both counterclockwise, the one with the smaller largest . So it suffices to show one valid diagonal with both triangles at most 4.
Case 1: and . Take the diagonal , with triangles and . Twice the area of is . Put . The squared sides are , and . So
because is at most on . The triangle is the mirror case with and swapped, so too.
Case 2: or . Take the diagonal , with triangles and . The triangle is right isosceles, . Twice the area of is . Let . One coordinate is negative and the other is at most , so and . The squared sides are , and . First, because . Second,
On the region of Case 2 this is negative. The function grows with and with on , so on the part with it is below its value at , which is , and on the part with it is below its value at , which is . By symmetry the same holds for . So and .
In both cases a valid diagonal with exists, so the triangles of L14 have .
Step 6: the triangles tile the root. All triangles are counterclockwise: the fans by construction, and the moved boxes because L14 accepts only counterclockwise pairs, and Step 5 shows that one exists. Now look at the directed edges.
- Inside a leaf, the fan edges and the diagonal of L14 are used once in each direction.
- Two leaves of the same size that share a side see the same vertices on it: the same corners, moved or not, since both boxes have the corner and a moved corner is moved for all four boxes at it, and no midpoint, since a midpoint would need an internal box across, and both are leaves. So the edge is used once in each direction.
- A leaf of side and two leaves of side that share its side: the big leaf has the midpoint , because the box across is internal, and its edges are and . The small leaves have the sides and with no midpoint. The point and the corners and are not moved, because a moved corner has four leaves of one size around it.
- Edges on the boundary of the root are used once, with the root on their left.
Let be the number of triangles that contain a point that lies on no edge. When crosses an inner edge, it leaves the triangle on one side and enters the triangle on the other side, because the edge is used once in each direction, so does not change. When crosses the boundary of from outside, grows by one. Far from , . So outside and inside. The triangles have disjoint interiors and cover , and since no vertex lies inside an edge used in the other direction, they meet face to face. Every point of is a moved corner, so it is a vertex.
Together, Steps 1 to 6 prove the claim. The test file checks Steps 2, 5 and 6 directly: balance by brute force over all pairs of leaves, in exact arithmetic, and the tiling by orientation, edge twins and total area.
Complexity
The paper's implementation runs in time, where is the output size, and this is optimal: sorting reduces to it, and the output must be written. Corollary 2 bounds the output: , where is the worst aspect ratio in the Delaunay triangulation of . The paper shows that this is tight: the points and for need triangles for any constant aspect ratio bound.
The implementation on this page is simpler and slower. Each round of the loop scans every leaf, and there are rounds in the worst case, so it takes exact operations with the reach of C3. That is enough for the small inputs of the tests. A fast version keeps a queue of leaves to check and finds neighbors by walking the tree.
Properties
- Exact. Every decision is a comparison of rational numbers.
- Deterministic. Each round scans the leaves in a fixed order, and ties in L11 have a fixed rule.
- Graded. Box sizes follow the distance to the nearest other point, so the mesh is fine only where points are close.
- Proved shape bound. and angles of at least . The largest angle is below , but the method does not try to bound it further.
- Proved size bound with an unknown constant. The constant of Theorem 1 is not given as a number.
The proved constants are much worse than the measured ones. Over 60 random sets of 2 to 12 integer points in , the worst aspect ratio was , against the proved 4, and the smallest angle was , against the proved . The largest angle was . The size constant is the larger gap: the proof gives no number, and in practice most of the triangles come from the root and the balance step, so a cleanup pass that merges boxes far from the points removes a large part of them.
Variants and improvements
- No obtuse angles. Section 3 of the paper changes the templates near the points and gets a triangulation with no obtuse angle and aspect ratio at most 2, still within a constant of (Theorem 2). A non-obtuse triangulation is a Delaunay triangulation of its vertices. Theorem 3 drops the aspect ratio bound and gets size.
- Only acute angles. Section 4 uses a strongly balanced quadtree and gets aspect ratio at most 5/3 with no obtuse angles (Theorem 4).
- Segments and polygons. Section 5 warps corners onto input segments. Lemma 7 gives and every new angle at least , which is . Theorem 8 handles polygons whose interior angles are at least , with angles at least .
- Higher dimensions. Section 6 uses a balanced -tree and gets bounded aspect ratio with size (Theorem 9). In 3D this is the starting point of octree mesh generation.
- Delaunay refinement. Ruppert's algorithm and Chew's second algorithm get better angle bounds (about and ) with fewer triangles in practice, at the cost of a less local construction.
When to use it
Use it when a proof of both quality and size matters more than the triangle count, or when the mesh must line up with an axis aligned grid, for example to couple with a finite difference solver or an adaptive quadtree solver. Use Delaunay refinement when you want fewer, better shaped triangles for the same input, and the advancing front method when the boundary layer of the mesh must be smooth.
Pitfalls
- Rotation dependence. The mesh depends on the axes. A rotated input gives a different mesh with a different size.
- Many triangles away from the points. The root and the balance step make a ring of boxes far from the data. Count the triangles before you compare with other methods.
- Unsplit sides are not automatic. With the 3 by 3 block of C3, a box with a moved corner can have a split side, and then the two-triangle template does not apply. This page uses a 5 by 5 block for that reason.
- Ties. A point at the center of its box, or on a midline, is equally close to two or four corners. Without a fixed tie rule, two neighboring boxes may choose different corners.
- Floating point. A point on a box side can be assigned to two boxes by rounding. Use exact or filtered predicates.
- Aspect ratio is not the angle. gives angles of at least , but a triangle with may have its smallest angle far above that bound, since also holds.
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
# 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
quadtree_mesh_generation.py 248 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quadtree-mesh-generation/. The authors are listed in prov/C1TYAG.jsonl.
"""Quadtree triangulation of a planar point set after Bern, Eppstein and Gilbert.
The input is a list of at least two distinct points with int or Fraction
coordinates. All arithmetic is exact. A box is a triple (k, i, j): level k,
column i and row j, so its side is S / 2^k and its lower left corner is
origin + (i, j) S / 2^k. The parameter reach is the half width of the block
of boxes that condition C3 looks at: reach=1 is the 3 by 3 block of the
paper, reach=2 (the default) is the 5 by 5 block that this page uses so that
no warped box has a split side.
"""
import math
from fractions import Fraction
from typing import Dict, List, Sequence, Tuple
from mg2geom import dist2, orient2d
Box = Tuple[int, int, int]
SIDES = ((0, -1), (1, 0), (0, 1), (-1, 0)) # bottom, right, top, left
class Quadtree:
def __init__(self, points: Sequence, reach: int = 2):
pts = [tuple(Fraction(c) for c in p) for p in points]
if len(set(pts)) != len(pts) or len(pts) < 2:
raise ValueError("need at least two distinct points")
self.points = pts
self.reach = reach
xs, ys = [p[0] for p in pts], [p[1] for p in pts]
ext = max(max(xs) - min(xs), max(ys) - min(ys))
cx, cy = (max(xs) + min(xs)) / 2, (max(ys) + min(ys)) / 2
self.side = 4 * ext # root side 4L: points stay in the middle quarter
self.origin = (cx - 2 * ext, cy - 2 * ext) # @line L1
self.leaves = {(0, 0, 0)} # @line L2
self.internal = set()
self._at_level: Dict[int, Dict[Box, list]] = {}
self.nn2 = {p: min(dist2(p, q) for q in pts if q != p) for p in pts}
# geometry of boxes
def width(self, k: int) -> Fraction:
return self.side / (1 << k)
def corner(self, k: int, i: int, j: int) -> tuple:
w = self.width(k)
return (self.origin[0] + i * w, self.origin[1] + j * w)
def inside_root(self, k: int, i: int, j: int) -> bool:
return 0 <= i < (1 << k) and 0 <= j < (1 << k)
def index_of(self, p, k: int) -> tuple:
w = self.width(k)
return (math.floor((p[0] - self.origin[0]) / w), math.floor((p[1] - self.origin[1]) / w))
def points_in(self, b: Box) -> list:
k = b[0]
if k not in self._at_level: # map box -> points, one map per level
m: Dict[Box, list] = {}
for p in self.points:
m.setdefault((k,) + self.index_of(p, k), []).append(p)
self._at_level[k] = m
return self._at_level[k].get(b, [])
# tree edits
def exists(self, b: Box) -> bool:
return b in self.leaves or b in self.internal
def split(self, b: Box) -> None:
k, i, j = b
self.leaves.remove(b)
self.internal.add(b)
for a in (0, 1):
for c in (0, 1):
self.leaves.add((k + 1, 2 * i + a, 2 * j + c))
def make_exist(self, b: Box) -> None:
"""Split the leaf that covers box b until b is a node of the tree."""
k, i, j = b
while not self.exists(b):
for up in range(1, k + 1):
anc = (k - up, i >> up, j >> up)
if anc in self.leaves:
self.split(anc)
break
def block(self, b: Box, reach: int):
k, i, j = b
for di in range(-reach, reach + 1):
for dj in range(-reach, reach + 1):
nb = (k, i + di, j + dj)
if (di or dj) and self.inside_root(*nb):
yield nb
# conditions
def crowded(self, b: Box) -> bool:
pts = self.points_in(b)
if not pts:
return False
if len(pts) >= 2: # C1
return True
w = self.width(b[0])
if self.nn2[pts[0]] < 8 * w * w: # C2: nearest neighbor closer than 2 sqrt(2) w
return True
return any(nb in self.internal for nb in self.block(b, self.reach)) # C3
def missing_neighbor(self, b: Box):
if not self.points_in(b):
return None
for nb in self.block(b, 1):
if not self.exists(nb):
return nb
return None
def unbalanced(self, b: Box) -> bool:
"""True if a side of leaf b has two or more quadtree corners inside it."""
k, i, j = b
for di, dj in SIDES:
nb = (k, i + di, j + dj)
if nb not in self.internal:
continue
for a in (0, 1):
ci = 2 * nb[1] + (a if di == 0 else (0 if di == 1 else 1))
cj = 2 * nb[2] + (a if dj == 0 else (0 if dj == 1 else 1))
if (k + 1, ci, cj) in self.internal:
return True
return False
def build(self, trace=None) -> None:
"""Split until no leaf is crowded, every leaf with a point has its 8 neighbors, and the tree is balanced.
If trace is a list, each round appends (rule, list of boxes).
"""
while True: # @line L3
todo = [b for b in sorted(self.leaves) if self.crowded(b)] # @line L4
if todo:
done = []
for b in todo:
if b in self.leaves and self.crowded(b):
self.split(b) # @line L5
done.append(b)
for nb in self.block(b, 1):
self.make_exist(nb)
if nb in self.leaves:
self.split(nb)
if trace is not None:
trace.append(("crowded", done))
continue
gaps = [nb for b in sorted(self.leaves) for nb in [self.missing_neighbor(b)] if nb] # @line L6
if gaps:
for nb in gaps:
self.make_exist(nb) # @line L7
if trace is not None:
trace.append(("neighbor", gaps))
continue
bad = [b for b in sorted(self.leaves) if self.unbalanced(b)] # @line L8
if bad:
for b in bad:
if b in self.leaves:
self.split(b) # @line L9
if trace is not None:
trace.append(("balance", bad))
continue
return # @line L10
# boundary vertices of a leaf, counterclockwise from the lower left corner
def boundary(self, b: Box) -> list:
k, i, j = b
w = self.width(k)
x0, y0 = self.corner(k, i, j)
corners = [(x0, y0), (x0 + w, y0), (x0 + w, y0 + w), (x0, y0 + w)]
out = []
for s, (di, dj) in enumerate(SIDES):
out.append(("corner", corners[s]))
if (k, i + di, j + dj) in self.internal:
p, q = corners[s], corners[(s + 1) % 4]
out.append(("mid", ((p[0] + q[0]) / 2, (p[1] + q[1]) / 2)))
return out
def aspect(a, b, c) -> Fraction:
"""Exact aspect ratio of Bern, Eppstein and Gilbert: longest side over the altitude to it.
It equals longest^2 / (2 area) = longest^2 / |orient2d|.
"""
t = orient2d(a, b, c)
if t == 0:
raise ValueError("flat triangle")
longest2 = max(dist2(a, b), dist2(b, c), dist2(c, a))
return Fraction(longest2) / abs(t)
def quadtree_mesh(points: Sequence, reach: int = 2):
"""Return (tree, vertices, triangles). Triangles are counterclockwise triples of vertex indices."""
t = Quadtree(points, reach)
t.build()
warp: Dict[tuple, tuple] = {}
for p in t.points: # @line L11
k = max(b[0] for b in t.leaves)
while True: # find the leaf that holds p
i, j = t.index_of(p, k)
if (k, i, j) in t.leaves:
break
k -= 1
x0, y0 = t.corner(k, i, j)
w = t.width(k)
cs = [(x0, y0), (x0, y0 + w), (x0 + w, y0), (x0 + w, y0 + w)]
y = min(cs, key=lambda c: (dist2(c, p), c)) # nearest corner, ties to the smallest
if y in warp:
raise AssertionError("two points warp one corner")
warp[y] = p
index: Dict[tuple, int] = {}
verts: List[tuple] = []
def vid(p) -> int:
if p not in index:
index[p] = len(verts)
verts.append(p)
return index[p]
tris: List[tuple] = []
for b in sorted(t.leaves): # @line L12
bd = t.boundary(b)
warped = [p for kind, p in bd if kind == "corner" and p in warp]
if not warped: # @line L13
k, i, j = b
w = t.width(k)
x0, y0 = t.corner(k, i, j)
c = (x0 + w / 2, y0 + w / 2)
ring = [p for _, p in bd]
for s in range(len(ring)):
tris.append((vid(c), vid(ring[s]), vid(ring[(s + 1) % len(ring)])))
continue
if len(warped) != 1 or len(bd) != 4:
raise AssertionError("warped box with a split side or two warped corners")
q = [warp.get(p, p) for _, p in bd] # @line L14
best = None
for d in (0, 1): # diagonal q[d] q[d + 2]
pair = [(q[d], q[d + 1], q[(d + 2) % 4]), (q[d], q[(d + 2) % 4], q[(d + 3) % 4])]
if any(orient2d(*tri) <= 0 for tri in pair):
continue
score = max(aspect(*tri) for tri in pair)
if best is None or score < best[0]:
best = (score, pair)
for tri in best[1]:
tris.append(tuple(vid(p) for p in tri))
return t, verts, tris # @line L15
test_quadtree_mesh_generation.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quadtree-mesh-generation/. The authors are listed in prov/C1TYAG.jsonl.
import math
import random
from collections import Counter
from fractions import Fraction as F
import pytest
from mg2geom import orient2d, triangle_angles_deg
from quadtree_mesh_generation import Quadtree, aspect, quadtree_mesh
def random_points(seed, n, size=40):
r = random.Random(seed)
pts = set()
while len(pts) < n:
pts.add((r.randint(0, size), r.randint(0, size)))
return sorted(pts)
def leaf_square(t, b):
k, i, j = b
x0, y0 = t.corner(k, i, j)
return x0, y0, t.width(k)
def side_contact(s, u):
"""Length of the common boundary of two closed squares with disjoint interiors (brute force)."""
ax, ay, aw = s
bx, by, bw = u
if ax + aw == bx or bx + bw == ax: # vertical contact
return max(0, min(ay + aw, by + bw) - max(ay, by))
if ay + aw == by or by + bw == ay: # horizontal contact
return max(0, min(ax + aw, bx + bw) - max(ax, bx))
return 0
CASES = [random_points(seed, n) for seed, n in [(1, 2), (2, 3), (3, 5), (4, 8), (5, 11), (6, 12), (7, 4)]]
CASES.append([(0, 0), (8, 0), (8, 1)]) # a close pair far from a third point
CASES.append([(F(1, 3), F(2, 7)), (F(5, 2), F(-1, 9)), (F(3, 4), F(9, 5))]) # rational input
@pytest.mark.parametrize("pts", CASES)
def test_tree_is_balanced_by_brute_force(pts):
t, _, _ = quadtree_mesh(pts)
sq = [leaf_square(t, b) for b in t.leaves]
for a in range(len(sq)):
for b in range(a + 1, len(sq)):
if side_contact(sq[a], sq[b]) > 0:
ratio = sq[a][2] / sq[b][2]
assert ratio in (F(1, 2), 1, 2), (sq[a], sq[b])
@pytest.mark.parametrize("pts", CASES)
def test_point_leaves_are_surrounded_by_eight_equal_leaves(pts):
t, _, _ = quadtree_mesh(pts)
sq = {leaf_square(t, b) for b in t.leaves}
for p in t.points:
holders = [s for s in sq if s[0] <= p[0] < s[0] + s[2] and s[1] <= p[1] < s[1] + s[2]]
assert len(holders) == 1
x0, y0, w = holders[0]
assert sum(1 for s in sq if s[0] <= p[0] < s[0] + s[2] and s[1] <= p[1] < s[1] + s[2]) == 1
for di in (-1, 0, 1):
for dj in (-1, 0, 1):
if di or dj:
assert (x0 + di * w, y0 + dj * w, w) in sq
others = [q for q in t.points if q != p]
assert min((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2 for q in others) >= 8 * w * w
@pytest.mark.parametrize("pts", CASES)
def test_triangles_tile_the_root_square(pts):
t, v, tris = quadtree_mesh(pts)
assert all(orient2d(v[a], v[b], v[c]) > 0 for a, b, c in tris)
assert sum(orient2d(v[a], v[b], v[c]) for a, b, c in tris) == 2 * t.side ** 2
edges = Counter()
for a, b, c in tris:
for e in ((a, b), (b, c), (c, a)):
edges[e] += 1
x0, y0, s = t.origin[0], t.origin[1], t.side
for (a, b), m in edges.items():
assert m == 1
if (b, a) not in edges: # a boundary edge lies on the root boundary
pa, pb = v[a], v[b]
assert (pa[0] == pb[0] and pa[0] in (x0, x0 + s)) or (pa[1] == pb[1] and pa[1] in (y0, y0 + s))
# Every inner edge has its twin, so no vertex hangs in the middle of an edge,
# and with positive areas that sum to the square this is a triangulation.
assert set(t.points) <= set(v)
@pytest.mark.parametrize("pts", CASES)
def test_aspect_ratio_at_most_4_and_angle_bound(pts):
_, v, tris = quadtree_mesh(pts)
bound = math.degrees(math.asin(0.25)) # 14.4775..., from A <= 4 and 1/sin(theta) <= A
for a, b, c in tris:
assert aspect(v[a], v[b], v[c]) <= 4
assert min(triangle_angles_deg(v[a], v[b], v[c])) >= bound - 1e-9
def test_many_random_inputs_keep_the_bound():
worst = 0
for seed in range(100, 115):
_, v, tris = quadtree_mesh(random_points(seed, 2 + seed % 9, 60))
worst = max(worst, max(aspect(v[a], v[b], v[c]) for a, b, c in tris))
assert worst <= 4
def test_three_by_three_block_lets_a_warped_box_have_a_split_side():
# With the 3 by 3 block of the paper, a box that shares the warped corner can
# have a split side. The 5 by 5 block of this page rules it out.
pts = [(11, 19), (12, 9), (19, 5)]
with pytest.raises(AssertionError):
quadtree_mesh(pts, reach=1)
quadtree_mesh(pts, reach=2)
def test_trace_of_the_three_point_example():
t = Quadtree([(0, 0), (4, 0), (1, 3)])
trace = []
t.build(trace)
assert [r for r, _ in trace] == ["crowded"] * 4 + ["neighbor"] * 2 + ["balance"]
assert Counter(t.width(b[0]) for b in t.leaves) == {1: 68, 2: 39, 4: 2}
_, v, tris = quadtree_mesh([(0, 0), (4, 0), (1, 3)])
assert (len(v), len(tris)) == (232, 434)
assert max(aspect(v[a], v[b], v[c]) for a, b, c in tris) == F(5, 2)
def test_rejects_bad_input():
with pytest.raises(ValueError):
quadtree_mesh([(1, 1)])
with pytest.raises(ValueError):
quadtree_mesh([(1, 1), (1, 1)])
History
Bern, Eppstein and Gilbert presented the method at FOCS 1990 and published the journal version in 1994. Earlier quadtree meshers, such as the one of Yerry and Shephard from 1983, were engineering methods with no guarantee. The paper gave the first proof that one method gets both bounded aspect ratio and a size within a constant factor of the optimum, and it ran in optimal time. Its warping idea, its balance condition and its size argument by charging boxes to triangles of an optimal mesh became standard tools. Mitchell and Vavasis carried the approach to three dimensions in 1992, and Ruppert's Delaunay refinement of 1993 to 1995 gave the same kind of size guarantee with better angles.
References
- Marshall Bern, David Eppstein and John Gilbert, Provably good mesh generation, Journal of Computer and System Sciences 48(3), 1994, 384 to 409, Section 2 (crowded boxes C1 to C3, warping, Lemma 1 with aspect ratio at most 4, Theorem 1, Corollaries 1 and 2), Section 3 (Theorem 2, no obtuse angles), Section 5 (Lemma 7, aspect ratio at most 5 and angles of at least 18.4 degrees for segments and polygons)
- Marshall Bern, David Eppstein and John Gilbert, Provably good mesh generation, Proceedings of the 31st Annual Symposium on Foundations of Computer Science (FOCS), 1990, 231 to 241, the conference version of the quadtree method (general locator)
- Mark de Berg, Otfried Cheong, Marc van Kreveld and Mark Overmars, Computational Geometry, Algorithms and Applications, 3rd edition, Springer, 2008, Chapter 14, Quadtrees, Non-Uniform Mesh Generation (balanced quadtrees and the balancing step)
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 C1TYAG Edit this page History Report an error Markdown