Algorithmcore
Advancing front mesh generation
Also called advancing front method, moving front method.
Builds a triangle or tetrahedral mesh from the boundary inward, adding one element at a time at an ideal point on the current front, after Lo, Peraire and Löhner.
- Solves
- Mesh generation
- Time
- O(n^3) worst
- Space
- O(n) extra
- Where
- n = the number of vertices of the output mesh
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- S. H. Lo, Jaime Peraire, Rainald Löhner, Paresh Parikh, 1985
Advancing front mesh generation fills a domain with triangles, or with tetrahedra in 3D, starting from its boundary. The boundary edges form the front. The method repeatedly takes one front edge, places an ideal new point inside at the distance that the mesh sizing function asks for, or uses a nearby existing front point instead, and adds the triangle if it does not overlap anything. The front then moves inward until it closes up. The result has well shaped triangles near the boundary and sizes that follow the sizing function, but the method has no quality guarantee: the quality of its triangles is only measured, never proved.
In plain words
Think of tiling a floor from the walls inward. You lay a row of tiles along each wall. The inner edge of the tiles you have laid is the front. You pick a short piece of the front, cut a new tile to fit against it, and lay it down if it does not overlap any tile already there. Then the front has moved a little.
When two parts of the front come close, you use a corner that is already there instead of a new one, so the gaps close. In the end the front shrinks to nothing and the floor is covered.
The tiles near the walls are neat. Where the fronts meet in the middle, a tile can come out thin, and nothing in the method prevents it. A program measures the tiles at the end.
The problem
This page solves the planar case of mesh generation, which asks for a triangulation of a domain whose triangles have bounded angles and sizes. Here the input is a simple polygon with rational corners in counterclockwise order and a target edge length . The output is a set of counterclockwise triangles that cover the polygon, have disjoint interiors, and meet edge to edge. Edge lengths should be close to and angles should be large, but these two wishes are goals, not guarantees.
The algorithm
ORIENT2D is the orientation test. A front edge is directed so that the unmeshed region lies to its left. Coordinates are Fractions, so every test below is exact; floats are used only in L5 and L6 to propose candidates.
ADVANCING-FRONT(P, h)- 1
F ← sides of P, each cut into ⌈|side| / h⌉ equal edges, directed counterclockwise - 2
V ← vertices of F; h_min ← min(h, shortest edge of F) / 2; T ← ∅ - 3
while F ≠ ∅ do - 4
ab ← a shortest edge of F - 5
δ ← min(max(h, 0.55 |ab|), 2 |ab|); p ← the point left of ab with |pa| = |pb| = δ, rounded to the grid of step h/64 - 6
C ← front vertices c left of ab with |c − p| < 0.8 δ, nearest to p first; then p - 7
append to C all front vertices strictly left of ab, nearest to the midpoint of ab first - 8
c ← the first c in C with VALID(a, b, c) ▷ the part added in L7 always has one - 9
T ← T ∪ {abc}; if c = p then V ← V ∪ {p} - 10
remove ab from F; if bc ∈ F then remove it else add cb; if ca ∈ F then remove it else add ac - 11
return T VALID(a, b, c)- 12
if ORIENT2D(a, b, c) ≤ 0 then return false - 13
if c is new and |c − v| < h_min for some v ∈ V then return false - 14
if a front vertex other than a, b, c lies in the closed triangle abc then return false - 15
if bc or ca shares with a front edge, other than itself, a point that is not a common endpoint then return false - 16
return true
L5 places the ideal point. For an edge of length it is the apex of an equilateral triangle. For a short edge it is higher, to grow the size toward , and for a long edge it is lower. L6 prefers an existing front vertex near the ideal point, which is how two parts of the front close up without thin gaps. L13 keeps new points away from old ones, which is what makes the method stop. L14 and L15 are the overlap tests, by the segment intersection test in exact arithmetic. L10 updates the front: a side of the new triangle that was a front edge is closed, and any other side becomes a new front edge, reversed so that the unmeshed region is on its left.
Example
Take the square , , , and . L1 cuts each side in two, so the front has 8 edges of length 2.
| step | edge | ideal point | chosen | triangle |
|---|---|---|---|---|
| 1 | front vertex , at distance about 1.04 from | |||
| 2 to 4 | the next shortest edges | the corner neighbours | the other three corner triangles | |
| 5 | , length | the new point | ||
| 6 to 8 | the rest of the diamond | existing front vertices | three more triangles |
In step 1, and the apex of the equilateral triangle is , which L5 rounds to . The vertex is within of it, so L6 tries it first, and it passes VALID. After step 4 the front is the diamond with edges of length , so in step 5, , the height is , and the ideal point is exactly the center . No front vertex is near it, so the new point is used. The result is 8 right isosceles triangles, each with ORIENT2D equal to 4. They add up to 32, twice the area of the square, and the smallest angle is .
No quality guarantee. On a random convex polygon with 7 integer corners in , all of whose angles are at least , and , the method makes 123 valid triangles. One of them, inside the polygon where two parts of the front closed up, has angles of about , and . On the ten random convex polygons of the tests, with from 5 to 10, the smallest angles were between and . These numbers are measurements. Nothing in the method bounds them.
Correctness
The proof keeps four facts true before each step: front edges meet only at common endpoints; the front is the boundary of the unmeshed region, which lies to the left of each front edge; the triangles made so far are counterclockwise, inside the polygon and interior-disjoint from each other and from the unmeshed region; and no vertex lies on a triangle except at its corners. VALID implies that no front edge enters the new triangle, so the triangle lies in the unmeshed region, and the update of L10 keeps the four facts.
A valid choice always exists. The front edges form a planar straight line graph, and its constrained Delaunay triangulation has a triangle on the left of every front edge . That triangle contains no other front vertex and crosses no front edge, so VALID accepts , and L7 puts every such into the candidate list. The same fact, that every polygonal region can be triangulated with its own vertices, is the existence theorem of polygon triangulation.
The method stops. New points are at least apart and from all older vertices, so by a packing argument only finitely many are made. The triangles never contain a vertex except at their corners, so they are faces of one triangulation of the final vertex set, which has at most triangles. Each iteration adds one triangle, so the loop runs at most that many times, and it stops only when the front is empty, when the triangles cover the polygon. The full proof is below.
Nothing in this argument concerns angles. Validity is proved; quality is not.
Proof: The planar advancing front with exact tests and a fallback always finishes with a conforming triangulation of the polygonfull
Claim. Let be a closed region bounded by a simple polygon with rational corners in counterclockwise order, and let be rational. Then ADVANCING-FRONT stops, and its output is a set of counterclockwise triangles that have pairwise disjoint interiors, whose union is , and in which no vertex lies on a triangle other than at its corners. All tests are exact. Nothing is claimed about the angles.
What the proof does not give. The proof gives validity, not quality. The smallest angle depends on the order of the front, the ideal point and the meeting of fronts, and nothing in the method bounds it. In the tests, a random convex polygon with all corners above gets a triangle with angles of about , and where two parts of the front close up. In three dimensions Step 3 fails: a polyhedral region such as the Schönhardt polyhedron has no tetrahedralization without new vertices, so the 3D method can stall.
Notation. At any moment, is the front, a set of directed segments, the set of vertices made so far, and the set of triangles. Let be the closure of , the unmeshed region. A front vertex is an endpoint of a front edge.
Invariant. Before each test of L3:
- (I1) two front edges meet at most in a common endpoint;
- (I2) is a finite union of closed polygonal regions whose boundary is the union of the front edges, and for each front edge the points just to the left of are in and the points just to the right are not;
- (I3) the triangles of are counterclockwise, have disjoint interiors, lie in , and their interiors do not meet ;
- (I4) every vertex of that is not a front vertex lies outside , and no vertex of lies on a triangle of other than at its corners.
At the start, is the boundary of , cut into pieces at points on the sides, and . (I1) holds because the polygon is simple, (I2) because it is counterclockwise, and (I3) and (I4) hold trivially.
Step 1 (VALID means that the triangle lies in ). Let and let pass VALID: ORIENT2D (L12), no front vertex other than lies in the closed triangle (L14), and no front edge other than or themselves shares with or a point that is not a common endpoint (L15). We show that no front edge meets the interior of .
Suppose it does, at a point . Follow from in both directions until it leaves the closed triangle or ends. An end of inside the closed triangle is a front vertex, so by L14 it is , or , which lie on the boundary of . So in both directions reaches a point of the boundary of , say and , with strictly between them. They are distinct. They are not both corners of , because the segment between two corners is a side of and does not pass through its interior. So one of them, say , lies inside a side of , not at a corner.
- If is inside the side , then and share a point that is not an endpoint of , against (I1).
- If is inside the side or , then shares with that side a point that is not an endpoint of the side, which L15 rejects. The exception of L15 does not apply, because passes through the interior of and so is not the side itself.
Both cases are impossible, so no front edge meets the interior of .
The interior of is connected and does not meet the boundary of , which by (I2) is the union of the front edges. Points of just to the left of are in by (I2). So the interior of lies in the interior of , and .
Step 2 (the update keeps the invariant). L10 removes , and for each of the new sides and either removes the front edge with the same direction, whose left side was the interior of , or adds the reversed side, whose left side is the rest of . The new front is therefore the boundary of with on the left, which is (I2). By L15, the added edges and meet old front edges at most in common endpoints, and they meet each other only at , which is (I1). The new triangle is counterclockwise, lies in with its interior in the interior of , so its interior misses the old triangles and , which is (I3). For (I4): a vertex that stops being a front vertex has all of its neighbourhood in the union of triangles, so it is not in . A vertex of on other than would be a front vertex by (I4), and L14 excludes it; a vertex of inside or is excluded the same way. A new point is in the interior of , so it lies on no old triangle.
Step 3 (a valid choice always exists). Let . The front edges form a planar straight line graph by (I1). Every such graph has a triangulation of the convex hull of its vertices that contains all its edges, for example its constrained Delaunay triangulation, and every triangle of it contains no vertex of the graph except its corners. Let be the triangle of this triangulation on the left of . It exists, because by (I2) the points just left of are in , which lies in the convex hull. Its corner is a front vertex strictly left of . No front vertex other than lies in it, and its sides do not cross front edges, because the front edges are edges of the triangulation. So VALID holds, and L7 puts every front vertex strictly left of into the candidate list, so L8 finds a valid candidate.
Step 4 (termination). A new point is accepted only if it is at distance at least from every vertex of (L13), and it lies in by Step 1. So the new points are pairwise at distance at least , and the open disks of radius around them are disjoint and lie in the set of points within of . That set has finite area , so at most new points are ever made, and , where is the number of boundary points.
Each iteration adds one triangle. By (I3) and (I4) the triangles have disjoint interiors, corners in , and no vertex of on them except their corners. Their sides form a planar straight line graph on , which extends to a triangulation of , and each of our triangles is then a face of it, since it contains no other vertex and its sides are edges. A triangulation of points, not all on a line, has at most triangles. So the number of iterations is at most , which is bounded, and the loop stops.
Step 5 (the output). The loop stops only when , because Step 3 shows that each iteration with adds a triangle. Then by (I2) has no boundary, and as a bounded closed polygonal region it has no interior, so the triangles cover up to a set of zero area, and since they are closed and is the closure of its interior, they cover . With (I3) and (I4) this is the claim. Every test in L12 to L15 uses ORIENT2D, comparisons of squared distances, and set membership on Fraction coordinates, so every decision is exact. Floats are used only in L5 and L6, to propose candidates, and a bad proposal fails VALID.
Complexity
Each iteration scans the front to find the shortest edge, and each VALID test scans the front once, in time for a front of edges. Usually one of the first few candidates is valid, so an iteration costs , and the whole run , which is for a front of about edges on a fat domain. In the worst case L8 tests all fallback candidates, each in time, so the time is with . Production codes keep the front in a heap by length and the points and edges in a quadtree or an alternating digital tree, so that each search looks only at nearby entries. With such structures the run time is close to in practice, but this is not a proved bound. The space is .
Properties
- Valid output, proved. The triangles tile the polygon edge to edge. With exact predicates this holds for every simple polygon.
- No quality guarantee. Angles are good near the boundary and can be poor where fronts meet. Unlike Delaunay refinement, which inserts circumcenters of bad triangles until a proved angle bound holds, as in Ruppert's algorithm and Chew's second algorithm, the advancing front proves nothing about angles.
- Boundary first. The boundary edges are used as given, so the mesh conforms to the boundary without the boundary recovery that Delaunay methods need.
- Follows a sizing function. The ideal point uses the local size, so graded and stretched meshes are natural.
- Not Delaunay. The output is not in general a Delaunay triangulation of its vertices.
Variants and improvements
- Background mesh. Peraire and coauthors read the size and a stretching direction from a coarse background mesh, which gives meshes adapted to a flow solution.
- Advancing front Delaunay. Points are placed by the advancing front rule but connected by Delaunay insertion, which combines good point placement with a Delaunay structure.
- Three dimensions. Löhner and Parikh advance a front of triangles with tetrahedra. The existence step of the proof fails in 3D, because a region such as the Schönhardt polyhedron cannot be split into tetrahedra without new points, so the 3D method can stall and needs repair steps, such as removing nearby elements and trying again.
- Quadrilaterals. Paving advances rows of quadrilaterals from the boundary in the same way.
- Smoothing after. Most codes follow the method with Laplacian smoothing and edge swaps to improve the measured quality, as measured by the mesh quality measures.
When to use it
Use it when the boundary must be kept exactly as given, when the element size must follow a sizing function closely, or when stretched elements are needed near walls, as in flow simulation with the finite element method. It is also a good choice for surfaces, where the front can advance in the parameter plane or directly on the surface. Use a Delaunay refinement method instead when a proved lower bound on the angles is needed, or a structured grid when the domain splits into four-sided blocks.
Pitfalls
- Inexact predicates. With float orientation tests, a near-collinear case can accept an overlapping triangle and corrupt the front. Use exact or robust predicates for every validity test.
- Expecting quality. The method does not guarantee angles. Measure the mesh and repair it.
- Front collisions. Without the fallback of L7, two fronts that meet at a bad angle can leave a gap with no acceptable ideal point, and the method stalls.
- Size jumps. A boundary with very different edge lengths in one place gives triangles of very different sizes next to each other. Limit the gradation of the sizing function first.
- 3D failure. In 3D the method can stall on regions that have no tetrahedralization without new points; a robust code needs a fallback such as local remeshing.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/advancing-front-mesh-generation/. The authors are listed in prov/NKGVJD.jsonl.
"""Advancing front triangulation of a simple polygon in the plane.
All points are tuples of Fraction, and every decision that affects validity
(orientation, containment, crossing, the minimum distance of a new point) is
made with exact rational arithmetic. Floats are used only to propose the ideal
point, which is then rounded to a rational grid; a bad proposal is rejected by
the exact tests, never accepted.
The method has no quality guarantee. The triangles are valid and tile the
polygon, but their angles are only measured, see min_angle_degrees().
"""
import math
from fractions import Fraction
from typing import Dict, List, Sequence, Tuple
from mg1geom import in_closed_triangle, orient2d, segments_cross, twice_area
Point = Tuple[Fraction, Fraction]
Triangle = Tuple[Point, Point, Point]
def _d2(p: Point, q: Point) -> Fraction:
return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2
def _split_side(a: Point, b: Point, h: Fraction) -> List[Point]:
"""Points a = q_0, ..., q_k (b excluded) cutting ab into k equal parts, k the least with k h >= |ab|."""
k = max(1, math.ceil(math.sqrt(float(_d2(a, b))) / float(h)))
while k > 1 and (k - 1) ** 2 * h * h >= _d2(a, b):
k -= 1
while k * k * h * h < _d2(a, b):
k += 1
return [(a[0] + (b[0] - a[0]) * Fraction(t, k), a[1] + (b[1] - a[1]) * Fraction(t, k)) for t in range(k)]
def _ideal_point(a: Point, b: Point, h: Fraction) -> Tuple[Point, float]:
"""The point left of ab at distance delta from a and b, rounded to the grid of step h / 64."""
ab = math.sqrt(float(_d2(a, b)))
delta = min(max(float(h), 0.55 * ab), 2.0 * ab)
height = math.sqrt(max(delta * delta - ab * ab / 4, 0.0))
mx, my = float(a[0] + b[0]) / 2, float(a[1] + b[1]) / 2
nx, ny = -float(b[1] - a[1]) / ab, float(b[0] - a[0]) / ab
g = Fraction(h) / 64
gf = float(g)
return (Fraction(round((mx + height * nx) / gf)) * g, Fraction(round((my + height * ny) / gf)) * g), delta
def advancing_front(polygon: Sequence[Point], h) -> Tuple[List[Triangle], List[Point]]:
"""Triangulate a simple counterclockwise polygon with target edge length h.
Precondition: polygon is a list of at least 3 distinct points with int or
Fraction coordinates, simple and counterclockwise; h > 0 (int or Fraction).
Returns (triangles, vertices); each triangle is counterclockwise.
Cost: O(n^3) exact operations in the worst case for n vertices of the
output, from the fallback search; usually O(n f) for a front of size f.
"""
pts = [(Fraction(p[0]), Fraction(p[1])) for p in polygon]
h = Fraction(h)
if len(pts) < 3 or h <= 0 or twice_area(pts) <= 0:
raise ValueError("need a counterclockwise polygon with at least 3 vertices and h > 0")
loop: List[Point] = []
for i in range(len(pts)):
loop += _split_side(pts[i], pts[(i + 1) % len(pts)], h)
front: Dict[Tuple[Point, Point], None] = {}
for i in range(len(loop)): # @line L1
front[(loop[i], loop[(i + 1) % len(loop)])] = None
vertices: List[Point] = list(loop) # @line L2
hmin2 = min([h * h] + [_d2(a, b) for a, b in front]) / 4
triangles: List[Triangle] = []
def valid(a: Point, b: Point, c: Point, new: bool, fverts) -> bool:
if orient2d(a, b, c) <= 0: # @line L12
return False
if new and any(_d2(c, v) < hmin2 for v in vertices): # @line L13
return False
if any(v not in (a, b, c) and in_closed_triangle(v, a, b, c) for v in fverts): # @line L14
return False
for e in front: # @line L15
s = set(e)
if s != {b, c} and segments_cross(b, c, e[0], e[1]):
return False
if s != {c, a} and segments_cross(c, a, e[0], e[1]):
return False
return True # @line L16
while front: # @line L3
a, b = min(front, key=lambda e: _d2(e[0], e[1])) # @line L4
p, delta = _ideal_point(a, b, h) # @line L5
fverts = {v for e in front for v in e}
left = [v for v in fverts if orient2d(a, b, v) > 0]
r2 = (0.8 * delta) ** 2
near = sorted((v for v in left if float(_d2(v, p)) < r2), key=lambda v: (_d2(v, p), v)) # @line L6
mid = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
candidates = [(v, False) for v in near] + [(p, p not in fverts)]
candidates += [(v, False) for v in sorted(left, key=lambda v: (_d2(v, mid), v))] # @line L7
c = None
for v, new in candidates: # @line L8
if v in (a, b):
continue
if valid(a, b, v, new, fverts):
c = v
break
if c is None:
raise RuntimeError("no valid triangle on a front edge; the input is not a simple polygon")
triangles.append((a, b, c)) # @line L9
if c not in fverts and c not in vertices:
vertices.append(c)
del front[(a, b)] # @line L10
if (b, c) in front:
del front[(b, c)]
else:
front[(c, b)] = None
if (c, a) in front:
del front[(c, a)]
else:
front[(a, c)] = None
return triangles, vertices # @line L11
def min_angle_degrees(triangles: Sequence[Triangle]) -> float:
"""The smallest angle over all triangles, in degrees (a float measurement)."""
best = 180.0
for t in triangles:
for k in range(3):
p, q, r = [tuple(map(float, x)) for x in (t[k], t[(k + 1) % 3], t[(k + 2) % 3])]
u = (q[0] - p[0], q[1] - p[1])
v = (r[0] - p[0], r[1] - p[1])
ang = math.degrees(math.atan2(abs(u[0] * v[1] - u[1] * v[0]), u[0] * v[0] + u[1] * v[1]))
best = min(best, ang)
return best
mg1geom.py 77 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mg1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small exact tools for planar grids and triangulations, used by the mg1 pages.
Points are tuples of int, fractions.Fraction or float. Every predicate here is
exact when the coordinates are int or Fraction. A float coordinate converts to
a Fraction without rounding, so exact() followed by a predicate gives the exact
sign for the float points as they are stored.
"""
from fractions import Fraction
from typing import Iterable, 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 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 twice_area(poly: Sequence[Point]):
"""Twice the signed area of a polygon by the shoelace formula."""
n = len(poly)
return sum(poly[i][0] * poly[(i + 1) % n][1] - poly[(i + 1) % n][0] * poly[i][1] for i in range(n))
def quad_corner_values(q: Sequence[Point]) -> list:
"""The four values ORIENT2D(q[k-1], q[k], q[k+1]) of a quadrilateral q[0..3].
They are the Jacobian determinants of the bilinear map of the cell at its
corners. All four are positive exactly when the quadrilateral is strictly
convex and counterclockwise.
"""
return [orient2d(q[k - 1], q[k], q[(k + 1) % 4]) for k in range(4)]
def grid_cells(grid: Sequence[Sequence[Point]]) -> Iterable:
"""Yield ((i, j), corners) for each cell of a grid x[i][j], corners counterclockwise for u right, v up."""
for i in range(len(grid) - 1):
for j in range(len(grid[0]) - 1):
yield (i, j), (grid[i][j], grid[i + 1][j], grid[i + 1][j + 1], grid[i][j + 1])
def in_closed_triangle(p: Point, a: Point, b: Point, c: Point) -> bool:
"""True if p lies in the closed counterclockwise triangle a, b, c."""
return orient2d(a, b, p) >= 0 and orient2d(b, c, p) >= 0 and orient2d(c, a, p) >= 0
def segments_cross(a: Point, b: Point, c: Point, d: Point) -> bool:
"""True if the closed segments ab and cd share a point other than a common endpoint.
Segments that share exactly one endpoint and are not collinear return False.
Cost O(1); exact for int and Fraction.
"""
shared = {a, b} & {c, d}
o1, o2 = orient2d(a, b, c), orient2d(a, b, d)
o3, o4 = orient2d(c, d, a), orient2d(c, d, b)
if o1 == 0 and o2 == 0:
# collinear: overlap in more than a shared endpoint?
k = 0 if a[0] != b[0] else 1
lo1, hi1 = sorted((a[k], b[k]))
lo2, hi2 = sorted((c[k], d[k]))
lo, hi = max(lo1, lo2), min(hi1, hi2)
if lo < hi:
return True
return lo == hi and not shared
if shared:
# two segments that are not collinear meet in at most one point
return False
return o1 * o2 <= 0 and o3 * o4 <= 0
test_advancing_front_mesh_generation.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/advancing-front-mesh-generation/. The authors are listed in prov/NKGVJD.jsonl.
import random
from collections import Counter
from fractions import Fraction as F
import pytest
from advancing_front_mesh_generation import advancing_front, min_angle_degrees
from mg1geom import orient2d, twice_area
def convex_hull(points):
"""Counterclockwise convex hull by the monotone chain, collinear points dropped."""
pts = sorted(set(points))
def half(seq):
h = []
for p in seq:
while len(h) >= 2 and orient2d(h[-2], h[-1], p) <= 0:
h.pop()
h.append(p)
return h
return half(pts)[:-1] + half(list(reversed(pts)))[:-1]
def shoelace_exact(poly):
"""Twice the area by the shoelace formula, written out with Fractions (the oracle)."""
n = len(poly)
return sum(F(poly[i][0]) * F(poly[(i + 1) % n][1]) - F(poly[(i + 1) % n][0]) * F(poly[i][1]) for i in range(n))
def on_segment(p, a, b):
return orient2d(a, b, p) == 0 and min(a[0], b[0]) <= p[0] <= max(a[0], b[0]) and min(a[1], b[1]) <= p[1] <= max(a[1], b[1])
def interiors_disjoint(t, s):
"""Two counterclockwise triangles have disjoint interiors iff an edge of one separates them."""
for p, q in ((t, s), (s, t)):
for k in range(3):
a, b = p[k], p[(k + 1) % 3]
if all(orient2d(a, b, v) <= 0 for v in q):
return True
return False
def check_mesh(poly, tris, convex):
poly = [(F(x), F(y)) for x, y in poly]
n = len(poly)
# every triangle is counterclockwise
assert all(orient2d(*t) > 0 for t in tris)
# every vertex is inside the closed polygon
if convex:
for t in tris:
for v in t:
assert all(orient2d(poly[i], poly[(i + 1) % n], v) >= 0 for i in range(n))
# exact area sum
assert sum(orient2d(*t) for t in tris) == shoelace_exact(poly)
# conformity: each directed edge once; an edge without its twin lies on the boundary
directed = Counter((t[k], t[(k + 1) % 3]) for t in tris for k in range(3))
assert max(directed.values()) == 1
for (a, b) in directed:
if (b, a) not in directed:
assert any(on_segment(a, poly[i], poly[(i + 1) % n]) and on_segment(b, poly[i], poly[(i + 1) % n]) for i in range(n))
# no vertex lies inside another triangle or in the middle of its edge
verts = {v for t in tris for v in t}
for t in tris:
for v in verts:
if v not in t:
assert not (orient2d(t[0], t[1], v) >= 0 and orient2d(t[1], t[2], v) >= 0 and orient2d(t[2], t[0], v) >= 0)
def test_example_of_the_page() -> None:
tris, verts = advancing_front([(0, 0), (4, 0), (4, 4), (0, 4)], 2)
assert len(tris) == 8 and len(verts) == 9
assert tris[0] == ((0, 0), (2, 0), (0, 2))
assert tris[4] == ((0, 2), (2, 0), (2, 2))
assert (F(2), F(2)) in verts
assert all(orient2d(*t) == 4 for t in tris)
check_mesh([(0, 0), (4, 0), (4, 4), (0, 4)], tris, True)
assert abs(min_angle_degrees(tris) - 45.0) < 1e-9
def test_random_convex_polygons() -> None:
rng = random.Random(1)
for _ in range(10):
poly = convex_hull([(rng.randint(0, 40), rng.randint(0, 40)) for _ in range(12)])
h = rng.randint(5, 10)
tris, verts = advancing_front(poly, h)
check_mesh(poly, tris, True)
# Euler: V - E + F = 1 for a triangulated disk
edges = {frozenset((t[k], t[(k + 1) % 3])) for t in tris for k in range(3)}
assert len(verts) - len(edges) + len(tris) == 1
assert len(tris) <= 2 * len(verts) - 5
def test_interiors_pairwise_disjoint() -> None:
rng = random.Random(3)
for _ in range(3):
poly = convex_hull([(rng.randint(0, 30), rng.randint(0, 30)) for _ in range(10)])
tris, _ = advancing_front(poly, 7)
for i in range(len(tris)):
for j in range(i + 1, len(tris)):
assert interiors_disjoint(tris[i], tris[j])
def test_nonconvex_polygon_and_rational_size() -> None:
poly = [(0, 0), (8, 0), (8, 3), (3, 3), (3, 8), (0, 8)]
tris, _ = advancing_front(poly, F(3, 2))
check_mesh(poly, tris, False)
comb = [(0, 0), (9, 0), (9, 4), (7, 4), (7, 1), (6, 1), (6, 4), (3, 4), (3, 1), (2, 1), (2, 4), (0, 4)]
tris, _ = advancing_front(comb, 2)
check_mesh(comb, tris, False)
def test_quality_is_only_measured() -> None:
rng = random.Random(1)
poly = convex_hull([(rng.randint(0, 40), rng.randint(0, 40)) for _ in range(12)])
tris, _ = advancing_front(poly, 4)
check_mesh(poly, tris, True)
assert 0 < min_angle_degrees(tris) < 10 # valid, but with a small angle
def test_bad_input() -> None:
with pytest.raises(ValueError):
advancing_front([(0, 0), (0, 4), (4, 0)], 1) # clockwise
with pytest.raises(ValueError):
advancing_front([(0, 0), (4, 0), (0, 4)], 0)
History
S. H. Lo published a method in 1985 that builds triangles from the boundary of a planar domain inward. Peraire, Vahdati, Morgan and Zienkiewicz developed the advancing front generator with a background mesh for adaptive compressible flow computations in 1987, and Löhner and Parikh extended it to tetrahedra in 1988. The method became the main unstructured mesh generator in computational fluid dynamics in the following years, next to Delaunay methods, and the two families were later combined.
References
- S. H. Lo, A new mesh generation scheme for arbitrary planar domains, International Journal for Numerical Methods in Engineering 21(8), 1985, 1403 to 1426, the generation of triangles from the boundary inward with a front of directed edges and the choice of the new node (general locator)
- J. Peraire, M. Vahdati, K. Morgan and O. C. Zienkiewicz, Adaptive remeshing for compressible flow computations, Journal of Computational Physics 72(2), 1987, 449 to 466, the advancing front generator driven by element sizes and stretching from a background mesh, used for adaptive remeshing (general locator)
- Rainald Löhner and Paresh Parikh, Generation of three-dimensional unstructured grids by the advancing-front method, International Journal for Numerical Methods in Fluids 8(10), 1988, 1135 to 1149, the extension to tetrahedra, with the front made of triangles, and the data structures for the search of close points and faces (general locator)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 NKGVJD Edit this page History Report an error Markdown