Algorithm Search⌘K

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.

Time
O(n log n + k) worst
Space
O(k) extra
Where
k = the number of output triangles; n = the number of input points
Properties
deterministicexactiterative
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 arcsin⁡(1/4)≈14.48°\arcsin(1/4) \approx 14.48°, 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 XX of n≥2n \ge 2 distinct points in the plane. The output is a triangulation of a square RR that contains XX, in which every point of XX is a vertex. The quality measure of the paper is the aspect ratio A(abc)A(abc) 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, A(abc)=ℓmax⁡2/(2 area)A(abc) = \ell_{\max}^2 / (2\,\mathrm{area}), without the factor 3/2\sqrt{3}/2 that the aspect ratio of that page has, and it controls the smallest angle θ\theta through

1sin⁡θ≤A(abc)≤2sin⁡θ.\frac{1}{\sin \theta} \le A(abc) \le \frac{2}{\sin\theta}.

The goal has two parts. Every triangle must have A≤4A \le 4. The number of triangles must be at most a constant times the size of any triangulation of XX 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 A≤4A \le 4, so every angle is at least arcsin⁡(1/4)≈14.4775°\arcsin(1/4) \approx 14.4775°. 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 bb of side ℓ\ell is crowded if it holds at least one point and one of these holds:

  • C1. bb holds two or more points.
  • C2. bb holds one point xx, and the nearest other point is closer than 22 ℓ2\sqrt2\,\ell to xx.
  • C3. A box of the same size near bb is split. The paper takes the 3 by 3 block of boxes around bb (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.

  1. QUADTREE-MESH(X)
  2. 1R ← the square of side 4L concentric with the bounding square of X (L = its side)
  3. 2T ← the quadtree whose only leaf is R
  4. 3repeat
  5. 4if some leaf b is crowded (C1, C2 or C3) then
  6. 5split b; split each extended neighbor of b, after first splitting coarser leaves so that it exists
  7. 6else if a leaf b that holds a point lacks an extended neighbor of its own size then
  8. 7split the coarser leaf that covers that neighbor
  9. 8else if a side of some leaf b has two or more box corners inside it then
  10. 9split b
  11. 10else stop
  12. 11for each x ∈ X: replace the corner of x's leaf nearest to x (ties: smallest x, then smallest y) by x
  13. 12for each leaf b:
  14. 13if no corner of b moved: add the center c of b and join c to every corner and side midpoint of b
  15. 14else: cut the moved quadrilateral by the diagonal whose two triangles have the smaller largest A
  16. 15return 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 XX and its sides are far from the points. A root of side 4L4L keeps every point at distance 1.5L1.5L 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 (11,19)(11, 19), (12,9)(12, 9) and (19,5)(19, 5), the point (11,19)(11, 19) moves the corner (11.5,19)(11.5, 19), 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, A(abc)=ℓmax⁡2/(2 area)A(abc) = \ell_{\max}^2 / (2\,\mathrm{area}), 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 X={(0,0),(4,0),(1,3)}X = \{(0,0), (4,0), (1,3)\}. The bounding square has side L=4L = 4, so the root has side 16 and its lower left corner is (−6,−6.5)(-6, -6.5). The squared nearest neighbor distances are 10 for (0,0)(0,0) and (1,3)(1,3) and 16 for (4,0)(4,0). 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 10<8⋅82=51210 < 8 \cdot 8^2 = 512
3 C2 3, with their neighbors 4 10<12810 < 128 and 16<12816 < 128
4 C2 3, with their neighbors 2 10<3210 < 32 and 16<3216 < 32
5 L6 the box at (0,3.5)(0, 3.5) is made 1 the leaf of (1,3)(1,3) needs a neighbor there
6 L6 the box at (2,3.5)(2, 3.5) is made 1 the same
7 balance 3 boxes 4 each touches boxes of width 1

At width 1 the points stop: 10≥8⋅1210 \ge 8 \cdot 1^2 and 16≥816 \ge 8, 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: (0,−0.5)(0, -0.5) moves to (0,0)(0, 0), (4,−0.5)(4, -0.5) moves to (4,0)(4, 0), and (1,2.5)(1, 2.5) moves to (1,3)(1, 3).

Triangles Count Aspect ratio AA 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 arctan⁡(1/2)≈26.57°\arctan(1/2) \approx 26.57°, in the triangle (0,0),(0,0.5),(−1,0.5)(0,0), (0, 0.5), (-1, 0.5). Most of the triangles are far from the points. The root of side 4L4L 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.

  1. The loop stops. Let δ\delta 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 δ/(22)\delta / (2\sqrt2). So all split boxes are at least that large, and there are finitely many of them.
  2. 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.
  3. The moves are consistent. The moved corner yy of xx is within ℓ/2\ell/\sqrt2 of xx. Two points cannot move the same corner, and no box gets two moved corners, because C2 keeps the other points at least 22 ℓ2\sqrt2\,\ell away. The tie rule removes the one equality case.
  4. Every triangle has A≤4A \le 4. The center fan gives right isosceles triangles with A=2A = 2. For a moved box, scale it to [0,1]2[0,1]^2 with the moved corner at the origin. The point lies in [−12,12]2[-\tfrac12, \tfrac12]^2. If it lies in [0,12]2[0, \tfrac12]^2, the diagonal through the point gives A≤5/2A \le 5/2. Otherwise the other diagonal gives A<4A < 4. L14 takes the better of the two.
  5. The triangles tile RR. All are counterclockwise, every inner edge is used once in each direction, and the other edges lie on the boundary of RR. A covering count argument then shows that each point of RR lies in exactly one triangle.

Size optimality is not proved here. Theorem 1 of the paper shows ∣QT(X)∣≤c′′⋅∣T∣log⁡A(T)|QT(X)| \le c'' \cdot |T| \log A(T) for every triangulation TT that contains XX, and Corollary 1 turns this into a constant factor of the optimum for any fixed aspect ratio bound α≥4\alpha \ge 4. 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 XX be a set of n≥2n \ge 2 distinct points with rational coordinates. Then QUADTREE-MESH(X)(X), 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 RR that has every point of XX as a vertex, and every triangle abcabc has aspect ratio A(abc)≤4A(abc) \le 4. So every angle is at least arcsin⁡(1/4)≈14.4775°\arcsin(1/4) \approx 14.4775°.

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, A(abc)=ℓmax⁡/hA(abc) = \ell_{\max} / h, where ℓmax⁡\ell_{\max} is the longest side and hh the altitude onto it. Since h=2 area/ℓmax⁡h = 2\,\mathrm{area}/\ell_{\max}, we have A=ℓmax⁡2/(2 area)A = \ell_{\max}^2 / (2\,\mathrm{area}). If θ\theta is the smallest angle and bb a side next to it other than the longest, then h=bsin⁡θ≤ℓmax⁡sin⁡θh = b \sin\theta \le \ell_{\max} \sin\theta, so A≥1/sin⁡θA \ge 1/\sin\theta. Thus A≤4A \le 4 gives sin⁡θ≥1/4\sin\theta \ge 1/4. A box is internal if it has been split. The block of radius rr of a box bb of level kk is the set of level kk boxes whose column and row differ from those of bb by at most rr.

Step 1: the loop stops. Let δ\delta be the smallest distance between two points of XX. 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 ss be the smallest side of a box that is ever split. Look at the first split, in time order, of a box of side ss.

  • If it was crowded by C3, a box of side ss in its block was already internal, so an earlier split of a box of side ss 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 ss. By the choice of ss it has side ss, and it was split earlier. Contradiction.
  • If it was split in L7, it covers a missing neighbor of a leaf of side tt that holds a point, so s≥2ts \ge 2t, and that leaf exists because its parent, of side 2t≤s2t \le s, was split before. Again an earlier split of a box of side at most ss exists. Contradiction.
  • If it was split in L9, one of its sides has two corners inside, so a box of side s/2s/2 was split earlier. Contradiction with the choice of ss.

So the first split of side ss was by C1 or C2. With C1 the box holds two points, so its diagonal is at least δ\delta and s≥δ/2s \ge \delta/\sqrt2. With C2 the box holds a point whose nearest neighbor is closer than 22 s2\sqrt2\,s, so s>δ/(22)s > \delta / (2\sqrt2). Every split box therefore has side more than δ/(22)\delta / (2\sqrt2). 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 bb be a leaf of side ℓ\ell that holds a point xx. C1 fails, so xx is the only point in bb. C2 fails, so every other point is at distance at least 22 ℓ2\sqrt2\,\ell from xx. L6 fails, so all eight extended neighbors of bb 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 4L4L and its boundary is at distance at least 1.5L1.5L from XX, so a box that holds a point and touches the boundary has side at least 1.5L1.5L, which means side 2L2L or 4L4L. Such a box is crowded by C1 or C2, because any two points are at most 2L<22⋅2L\sqrt2 L < 2\sqrt2 \cdot 2L 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 xx lie in leaf bb of side ℓ\ell and let yy be its chosen corner. Since yy is a nearest corner, xx lies in the closed quarter of bb at yy, so ∣x−y∣≤ℓ/2|x - y| \le \ell/\sqrt2. The four boxes with corner yy are bb and three of its extended neighbors, all leaves of side ℓ\ell.

(a) Two points never move the same corner. If xx and x′x' both chose yy, then x′x' lies in one of these four boxes, of side ℓ\ell, so ∣x−x′∣≤2 ℓ<22 ℓ|x - x'| \le \sqrt2\,\ell < 2\sqrt2\,\ell. This contradicts Step 2.

(b) No box has two moved corners. Let a box qq of side ℓ\ell have moved corners yy and y′y', moved by xx and x′x'. The leaves of xx and x′x' both touch qq, so they are extended neighbors of qq and all have side ℓ\ell. If yy and y′y' are adjacent corners, ∣x−x′∣≤ℓ/2+ℓ+ℓ/2=(1+2)ℓ<22 ℓ|x - x'| \le \ell/\sqrt2 + \ell + \ell/\sqrt2 = (1 + \sqrt2)\ell < 2\sqrt2\,\ell. If they are opposite corners, ∣x−x′∣≤22 ℓ|x - x'| \le 2\sqrt2\,\ell, and Step 2 forces equality. Equality needs ∣x−y∣=ℓ/2|x - y| = \ell/\sqrt2, so xx is the center of its box, and x,y,y′,x′x, y, y', x' lie on one diagonal line. At the center all four corners tie, and the tie rule picks the lower left corner, so yy is the lower left corner of the box of xx. The points lie on one line in the order x,y,y′,x′x, y, y', x', and y′y' is the corner of qq opposite to yy, so qq lies below and to the left of yy, and yy is the upper right corner of qq. The same argument with x′x' in place of xx shows that y′y' is the upper right corner of qq as well. So y=y′y = y', a contradiction.

(c) A box with a moved corner has no split side. Let qq have the moved corner yy of xx, where xx lies in bb. The box qq lies in the 3 by 3 block of bb, so each box across a side of qq, at the level of qq, lies in the 5 by 5 block of bb. 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 qq 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 ℓ\ell are its two corners and, if the box across is internal, the midpoint. The fan from the center cc gives two kinds of triangles. A triangle cc, corner, corner has a right angle at cc and legs ℓ/2\ell/\sqrt2. A triangle cc, corner, midpoint has a right angle at the midpoint and legs ℓ/2\ell/2. Both are right isosceles, with A=ℓmax⁡2/(2 area)=2A = \ell_{\max}^2/(2\,\mathrm{area}) = 2.

Step 5: the moved boxes. Scale, rotate and reflect so that the box qq is [0,1]2[0,1]^2 and its moved corner is the origin. These maps do not change AA. The other corners are p=(1,0)p = (1,0), r=(1,1)r = (1,1) and u=(0,1)u = (0,1). By Step 3, xx lies in the quarter at the origin of a box with corner 00, so x=(x1,x2)∈[−12,12]2x = (x_1, x_2) \in [-\tfrac12, \tfrac12]^2. L14 takes, among the diagonals whose two triangles are both counterclockwise, the one with the smaller largest AA. So it suffices to show one valid diagonal with both triangles at most 4.

Case 1: x1≥0x_1 \ge 0 and x2≥0x_2 \ge 0. Take the diagonal xrxr, with triangles xprxpr and xruxru. Twice the area of xprxpr is ORIENT2D(x,p,r)=1−x1≥12>0\mathrm{ORIENT2D}(x, p, r) = 1 - x_1 \ge \tfrac12 > 0. Put t=1−x1∈[12,1]t = 1 - x_1 \in [\tfrac12, 1]. The squared sides are ∣pr∣2=1|pr|^2 = 1, ∣xp∣2=t2+x22≤t2+14|xp|^2 = t^2 + x_2^2 \le t^2 + \tfrac14 and ∣xr∣2=t2+(1−x2)2≤t2+1|xr|^2 = t^2 + (1 - x_2)^2 \le t^2 + 1. So

A(xpr)≤t2+1t=t+1t≤52,A(xpr) \le \frac{t^2 + 1}{t} = t + \frac1t \le \frac52,

because t+1/tt + 1/t is at most 5/25/2 on [12,1][\tfrac12, 1]. The triangle xruxru is the mirror case with x1x_1 and x2x_2 swapped, so A(xru)≤5/2A(xru) \le 5/2 too.

Case 2: x1<0x_1 < 0 or x2<0x_2 < 0. Take the diagonal pupu, with triangles xpuxpu and prupru. The triangle prupru is right isosceles, A=2A = 2. Twice the area of xpuxpu is ORIENT2D(x,p,u)=1−x1−x2\mathrm{ORIENT2D}(x, p, u) = 1 - x_1 - x_2. Let σ=x1+x2\sigma = x_1 + x_2. One coordinate is negative and the other is at most 12\tfrac12, so σ<12\sigma < \tfrac12 and 1−σ>12>01 - \sigma > \tfrac12 > 0. The squared sides are ∣pu∣2=2|pu|^2 = 2, ∣xp∣2=(1−x1)2+x22|xp|^2 = (1 - x_1)^2 + x_2^2 and ∣xu∣2=x12+(1−x2)2|xu|^2 = x_1^2 + (1 - x_2)^2. First, 2<4(1−σ)2 < 4(1 - \sigma) because σ<12\sigma < \tfrac12. Second,

∣xp∣2−4(1−σ)=(x1+1)2+(x2+2)2−8.|xp|^2 - 4(1 - \sigma) = (x_1 + 1)^2 + (x_2 + 2)^2 - 8.

On the region of Case 2 this is negative. The function grows with x1x_1 and with x2x_2 on [−12,12]2[-\tfrac12, \tfrac12]^2, so on the part with x2<0x_2 < 0 it is below its value at (12,0)(\tfrac12, 0), which is 94+4−8<0\tfrac94 + 4 - 8 < 0, and on the part with x1<0x_1 < 0 it is below its value at (0,12)(0, \tfrac12), which is 1+254−8<01 + \tfrac{25}{4} - 8 < 0. By symmetry the same holds for ∣xu∣2|xu|^2. So ℓmax⁡2<4(1−σ)\ell_{\max}^2 < 4 (1 - \sigma) and A(xpu)<4A(xpu) < 4.

In both cases a valid diagonal with A≤4A \le 4 exists, so the triangles of L14 have A≤4A \le 4.

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 cvc v 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 2ℓ2\ell and two leaves of side ℓ\ell that share its side: the big leaf has the midpoint mm, because the box across is internal, and its edges are ama m and mbm b. The small leaves have the sides mam a and bmb m with no midpoint. The point mm and the corners aa and bb 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 w(z)w(z) be the number of triangles that contain a point zz that lies on no edge. When zz 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 ww does not change. When zz crosses the boundary of RR from outside, ww grows by one. Far from RR, w=0w = 0. So w=0w = 0 outside RR and w=1w = 1 inside. The triangles have disjoint interiors and cover RR, and since no vertex lies inside an edge used in the other direction, they meet face to face. Every point of XX 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, A≤4A \le 4 in exact arithmetic, and the tiling by orientation, edge twins and total area. ■\blacksquare

Complexity

The paper's implementation runs in O(nlog⁡n+k)O(n \log n + k) time, where kk is the output size, and this is optimal: sorting reduces to it, and the output must be written. Corollary 2 bounds the output: k=O(nlog⁡A(DT(X)))k = O(n \log A(DT(X))), where A(DT(X))A(DT(X)) is the worst aspect ratio in the Delaunay triangulation of XX. The paper shows that this is tight: the points (0,kα)(0, k\alpha) and (1,kα)(1, k\alpha) for k=1,…,n/2k = 1, \dots, n/2 need Ω(nlog⁡A(DT(X)))\Omega(n \log A(DT(X))) 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 O(k)O(k) rounds in the worst case, so it takes O(k2(n+r2))O(k^2 (n + r^2)) exact operations with r=2r = 2 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. A≤4A \le 4 and angles of at least 14.48°14.48°. The largest angle is below 180°−2⋅14.48°180° - 2 \cdot 14.48°, but the method does not try to bound it further.
  • Proved size bound with an unknown constant. The constant c′′c'' 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 [0,40]2[0, 40]^2, the worst aspect ratio was 74/25=2.9674/25 = 2.96, against the proved 4, and the smallest angle was 22.29°22.29°, against the proved 14.48°14.48°. The largest angle was 104.0°104.0°. 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 ∣QT(X)∣|QT(X)| (Theorem 2). A non-obtuse triangulation is a Delaunay triangulation of its vertices. Theorem 3 drops the aspect ratio bound and gets O(n)O(n) 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 A≤5A \le 5 and every new angle at least 18.4°18.4°, which is arctan⁡(1/3)\arctan(1/3). Theorem 8 handles polygons whose interior angles are at least β\beta, with angles at least min⁡(18.4°,β)\min(18.4°, \beta).
  • Higher dimensions. Section 6 uses a balanced 2d2^d-tree and gets bounded aspect ratio with size O(∣T∣log⁡A(T))O(|T| \log A(T)) (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 20.7°20.7° and 26.57°26.57°) 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. A≤4A \le 4 gives angles of at least 14.48°14.48°, but a triangle with A=4A = 4 may have its smallest angle far above that bound, since A≤2/sin⁡θA \le 2/\sin\theta 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.

mg2geom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the mg2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small exact geometric tools used by the mg2 pages.

Points are tuples of int or fractions.Fraction. Every predicate returns an
exact value when the coordinates are int or Fraction, so its sign is the true
sign. A float converts to a Fraction without rounding (exact()), so the sign
is then exact for the float point as it is stored. The angle functions return
floats and are used only to report or to compare with a stated bound.
"""

import math
from fractions import Fraction
from typing import Sequence, Tuple

Point = Tuple


def exact(p: Point) -> Tuple[Fraction, ...]:
    """The point p with each coordinate converted to Fraction, without rounding."""
    return tuple(Fraction(c) for c in p)


def sub(a: Point, b: Point) -> tuple:
    return tuple(x - y for x, y in zip(a, b))


def dot(a: Point, b: Point):
    return sum(x * y for x, y in zip(a, b))


def cross(a: Point, b: Point) -> tuple:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def dist2(a: Point, b: Point):
    return sum((x - y) * (x - y) for x, y in zip(a, b))


def det3(r0: Sequence, r1: Sequence, r2: Sequence):
    return dot(r0, cross(r1, r2))


def det4(m: Sequence[Sequence]):
    """Determinant of a 4 by 4 matrix by cofactor expansion along the first row."""
    total = 0
    for j in range(4):
        minor = [[m[i][k] for k in range(4) if k != j] for i in range(1, 4)]
        term = m[0][j] * det3(minor[0], minor[1], minor[2])
        total += term if j % 2 == 0 else -term
    return total


def orient2d(a: Point, b: Point, c: Point):
    """Twice the signed area of the triangle a, b, c; positive if counterclockwise."""
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def orient3d(a: Point, b: Point, c: Point, d: Point):
    """Six times the signed volume of the tetrahedron a, b, c, d.

    It is det[b - a, c - a, d - a]: positive when d lies on the side of the
    plane abc from which a, b, c appear clockwise.
    """
    return det3(sub(b, a), sub(c, a), sub(d, a))


def insphere(a: Point, b: Point, c: Point, d: Point, e: Point):
    """Positive if e lies inside the sphere through a, b, c, d, zero on it.

    The value is det of the rows (p - e, |p - e|^2) for p = a, b, c, d,
    divided by nothing, times the sign of orient3d(a, b, c, d), so the result
    does not depend on the order of a, b, c, d. The tetrahedron must not be flat.
    """
    rows = []
    for p in (a, b, c, d):
        v = sub(p, e)
        rows.append([v[0], v[1], v[2], dot(v, v)])
    o = orient3d(a, b, c, d)
    if o == 0:
        raise ValueError("flat tetrahedron")
    val = -det4(rows)
    return val if o > 0 else -val


def circumcenter3(a: Point, b: Point, c: Point, d: Point) -> tuple:
    """Exact circumcenter of a tetrahedron, by Cramer's rule on 2 (p - a) . x = |p - a|^2."""
    u, v, w = sub(b, a), sub(c, a), sub(d, a)
    det = det3(u, v, w)
    if det == 0:
        raise ValueError("flat tetrahedron")
    bu, bv, bw = Fraction(dot(u, u)), Fraction(dot(v, v)), Fraction(dot(w, w))
    # x = (bu (v x w) + bv (w x u) + bw (u x v)) / (2 det)
    cvw, cwu, cuv = cross(v, w), cross(w, u), cross(u, v)
    x = tuple((bu * cvw[k] + bv * cwu[k] + bw * cuv[k]) / (2 * det) for k in range(3))
    return tuple(a[k] + x[k] for k in range(3))


def tri_circumcenter3(a: Point, b: Point, c: Point) -> tuple:
    """Exact circumcenter of a triangle in space (the center of its smallest circumscribed sphere)."""
    u, v = sub(b, a), sub(c, a)
    n = cross(u, v)
    nn = Fraction(dot(n, n))
    if nn == 0:
        raise ValueError("flat triangle")
    t1 = cross(n, u)
    t2 = cross(v, n)
    uu, vv = dot(u, u), dot(v, v)
    # x = (|u|^2 (v x n) + |v|^2 (n x u)) / (2 |n|^2)
    return tuple(a[k] + (uu * t2[k] + vv * t1[k]) / (2 * nn) for k in range(3))


def radius_edge2(a: Point, b: Point, c: Point, d: Point) -> Fraction:
    """Exact square of the radius-edge ratio R / l_min of a tetrahedron."""
    cc = circumcenter3(a, b, c, d)
    r2 = dist2(cc, a)
    pts = (a, b, c, d)
    lmin2 = min(dist2(pts[i], pts[j]) for i in range(4) for j in range(i + 1, 4))
    return Fraction(r2) / Fraction(lmin2)


def _angle(u: Sequence[float], v: Sequence[float]) -> float:
    nu = math.sqrt(sum(x * x for x in u))
    nv = math.sqrt(sum(x * x for x in v))
    c = sum(x * y for x, y in zip(u, v)) / (nu * nv)
    return math.degrees(math.acos(max(-1.0, min(1.0, c))))


def triangle_angles_deg(a: Point, b: Point, c: Point) -> list:
    """The three plane angles of a triangle in degrees, in 2D or 3D (floats)."""
    p = [tuple(float(x) for x in q) for q in (a, b, c)]
    out = []
    for i in range(3):
        o, s, t = p[i], p[(i + 1) % 3], p[(i + 2) % 3]
        out.append(_angle(sub(s, o), sub(t, o)))
    return out


def dihedral_angles_deg(a: Point, b: Point, c: Point, d: Point) -> list:
    """The six dihedral angles of a tetrahedron in degrees (floats).

    The angle at edge pq is the angle between the two faces pqr and pqs,
    measured inside the tetrahedron.
    """
    p = [tuple(float(x) for x in q) for q in (a, b, c, d)]
    out = []
    for i in range(4):
        for j in range(i + 1, 4):
            k, m = [t for t in range(4) if t not in (i, j)]
            e = sub(p[j], p[i])
            ee = dot(e, e)
            # components of p_k - p_i and p_m - p_i orthogonal to the edge
            u = sub(p[k], p[i])
            v = sub(p[m], p[i])
            u = tuple(u[t] - dot(u, e) / ee * e[t] for t in range(3))
            v = tuple(v[t] - dot(v, e) / ee * e[t] for t in range(3))
            out.append(_angle(u, v))
    return out
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

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

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