Algorithm Search⌘K

Algorithmadvanced

Q-Morph

Also called Owen Q-Morph.

Owen's quadrilateral mesher that converts a triangle mesh by an advancing front of quads that merge triangles and recover edges, giving all-quad meshes.

Time
O(f n) worst
Space
O(n) extra
Where
f = the number of flips in the recovery of the top edge; n = the number of triangles
Properties
deterministicexactiterative
Origin
Steven J. Owen, Matthew L. Staten, Scott A. Canann, Sunil Saigal, 1999

Q-Morph is a method that turns a triangle mesh into a mesh of quadrilaterals. It works like paving: a front moves inward from the boundary, and each step puts a new quad on one front edge. The difference is that Q-Morph does not place new nodes in empty space. It starts from a valid triangle mesh, picks two existing edges as the sides of the new quad, makes the top edge appear in the mesh by flipping triangle edges, and then merges all triangles inside the quad into it. Because the triangle mesh always covers the rest of the region, Q-Morph never has to test whether two fronts cross, which is the hardest part of paving. Steven Owen and his coauthors published it in 1999. It gives quads aligned with the boundary, but there is no proof that it always closes the front and no bound on the quality of the quads. This page implements and proves one core step.

In plain words

Start with a floor that is fully covered by triangular tiles. You want square tiles instead. Begin at a wall. Take one tile edge on the wall, and look for the two tile edges that go away from the wall at its ends, as straight as you can find. Join their far ends with a new line, moving tile edges around until that line is a tile edge too. Now the triangles between the wall and the new line make one four sided tile, so glue them together.

Do this along the whole wall, then along the new line of four sided tiles, and so on. The floor is always fully covered, partly by four sided tiles and partly by triangles, so the work never leaves a gap. At the end, the corners of the new tiles are nudged to make them more even.

The problem

The input is a conforming triangle mesh of a planar region whose boundary has an even number of edges. The output is a conforming mesh of the same region by convex quads, aligned with the boundary. The core step solves a smaller problem: given a conforming triangle mesh with exact coordinates and an edge a→ba \to b with a triangle on its left, return a strictly convex quad (a,b,d,c)(a, b, d, c) and the triangles that remain after the triangles inside the quad are removed, so that the quad and the remaining triangles form a conforming mesh of the same region; or report that the step fails.

The algorithm

The full method keeps a front of edges, starting with the boundary edges of the triangle mesh. Each front edge has a state that records whether the neighbouring front edges at its ends make sharp corners. At a sharp corner, the neighbouring front edge itself becomes a side of the quad. Otherwise, the side is the mesh edge at that end that is closest to the ideal direction, the bisector of the front angle. If no edge is close, Q-Morph swaps an edge or splits one to make a better side. This code uses only the second rule, with the inward normal of abab as the ideal direction, which is the bisector when the front is straight.

  1. QMORPH-STEP(T, a → b)
  2. 1c ← the neighbour of a for which the edge ac is closest in angle to the inward normal of ab
  3. 2d ← the neighbour of b for which the edge bd is closest in angle to the inward normal of ab
  4. 3if c = d then fail
  5. 4if the quad (a, b, d, c) is not strictly convex and counterclockwise then fail
  6. 5if a vertex lies on the segment cd then fail; X ← the edges of T that cross cd
  7. 6while X is not empty: flip an edge of X whose two triangles form a convex quad, first one whose new edge does not cross cd; update X
  8. 7S ← the triangles reached from the triangle left of ab without crossing the four sides of the quad
  9. 8if the area of S is not the area of the quad then fail
  10. 9remove the triangles of S from T, with the vertices inside the quad
  11. 10return the quad (a, b, d, c)

All tests use exact orientation tests. L5 and L6 are the recovery of the top edge by edge flips. The search in L7 is a depth first search over the triangles. After the step, the full method adds the new quad to the front: abab leaves the front, and the sides and the top edge join it where they are not shared with an earlier quad. Between rows, it smooths the nodes, and at the end it closes small loops of the front with fixed patterns.

Example

Take the points a=(0,0)a = (0, 0), b=(2,0)b = (2, 0), c=(−12,2)c = (-\tfrac12, 2), d=(52,2)d = (\tfrac52, 2), p=(1,32)p = (1, \tfrac32) and e=(1,3)e = (1, 3), with the five triangles abpabp, apcapc, bdpbdp, cpecpe and pdepde. The front edge is abab, and its inward normal points up. At aa, the edge to pp is 33.7°33.7° from the normal and the edge to cc is 14.0°14.0°, so the side is acac. At bb, the side is bdbd for the same reason. The quad (a,b,d,c)(a, b, d, c) is a trapezoid with area 5, strictly convex.

The top edge cdcd is not in the mesh: the segment y=2y = 2 crosses the edge pepe. The triangles cpecpe and pdepde form a convex quad, so one flip replaces pepe by cdcd, with the triangles cpdcpd and decdec. The search starts at abpabp and reaches apcapc, bdpbdp and cpdcpd without crossing the quad sides. The four triangles have areas 1.51.5, 1.3751.375, 1.3751.375 and 0.750.75, which add up to 5, the area of the quad. They are removed, together with the inner vertex pp, and the mesh is now the quad (a,b,d,c)(a, b, d, c) and the triangle decdec. The quad has angles of 104.0°104.0° at aa and bb and 76.0°76.0° at cc and dd.

On random meshes of jittered grids, scrambled by 300 random flips, 97 of 128 steps on boundary edges succeeded, and 44 of them needed between 1 and 5 flips to recover the top edge.

Correctness

The proof file shows two results. The first is the parity rule: each quad has 4 edge sides, so 4Q=2Eint+Ebnd4Q = 2E_\text{int} + E_\text{bnd}, and a region can have an all-quad mesh only if its boundary has an even number of edges. Q-Morph needs the same parity on every front loop.

The second is that an accepted step gives a conforming mesh. Each flip keeps a conforming mesh of the same region. The flips touch only edges that cross the open segment cdcd, so the three sides abab, bdbd and caca survive, and after recovery all four sides of the quad are mesh edges. A triangle cannot cross a mesh edge, so each triangle is inside the quad or outside it. The search reaches only triangles inside, and the area check proves that they cover the quad. Replacing them by the quad keeps every other directed edge, so the result is conforming, with the same boundary and the same area. The tests check the area exactly, the conformity, the presence of the top edge, and that the merged triangles are exactly those whose centroid is inside the quad.

Not proved: that a flippable crossing edge always exists during recovery (the code reports a failure if not, and this never happened in the tests), that Q-Morph closes every front, and any bound on the angles of the quads.

Proof: A quad mesh has an even number of boundary edges, and an accepted Q-Morph step gives a conforming mixed mesh with one new quadfull

What is proved and what is not. The proof covers the parity rule for quad meshes and the correctness of one Q-Morph step as implemented here: side edges, top edge recovery by flips, and the merge of the triangles inside the quad. Nothing is proved about Q-Morph as a whole. Owen and his coauthors give no proof that the front always closes and no bound on the angles of the quads; the method relies on side edge swaps and splits, smoothing and closure rules that are tuned by experiment. One fact about recovery is also not proved here: that a crossing edge that can be flipped always exists. The code reports a failure if none exists, and the tests measure that this never happened.

Theorem 1 (parity). In a mesh of a planar region by QQ quads, in which every edge lies in one quad (a boundary edge) or two quads (an interior edge), the number EbE_b of boundary edges is even.

Proof. Count pairs (quad, edge of that quad), the edge sides. Each quad has 4 edges, so there are 4Q4Q pairs. Each interior edge is in two pairs and each boundary edge in one, so 4Q=2Ei+Eb4Q = 2E_i + E_b. Then Eb=4Q−2EiE_b = 4Q - 2E_i is even. □\square

So Q-Morph needs an even number of edges on the boundary of the triangle mesh, and an even number of edges on every front loop, before it can end with quads only. A triangle mesh of a region whose boundary has an odd number of edges cannot become an all-quad mesh by merging alone.

Setting. The input is a conforming triangle mesh TT: counterclockwise triangles with exact coordinates, no directed edge used twice, and no vertex in the interior of an edge. The front edge a→ba \to b has a triangle on its left. The step picks side edges acac and bdbd, which are edges of TT, and accepts them only if c≠dc \ne d and the quad q=(a,b,d,c)q = (a, b, d, c) is strictly convex and counterclockwise (L3, L4).

Lemma 2 (a flip keeps the mesh). Let uvuv be an edge with the triangles (u,v,k)(u, v, k) and (v,u,l)(v, u, l), and let the quad u,l,v,ku, l, v, k be strictly convex. Then replacing the two triangles by (k,u,l)(k, u, l) and (l,v,k)(l, v, k) gives a conforming mesh of the same region, with the same boundary edges and the same total area.

Proof. The code accepts the flip only if orient⁡(k,u,l)>0\operatorname{orient}(k, u, l) > 0 and orient⁡(l,v,k)>0\operatorname{orient}(l, v, k) > 0. Since kk is left of u→vu \to v and ll right of it, these two tests and the two old triangles make the quad strictly convex, and its two diagonals split it into two counterclockwise triangles each. So the new triangles cover the same quad with disjoint interiors, and their areas add up to the same value. The four outer directed edges u→lu \to l, l→vl \to v, v→kv \to k, k→uk \to u are the same as before, so the neighbours see the same edges. The new edge klkl is used once in each direction. No vertex lies inside klkl, because the open diagonal of a strictly convex quad lies in the interior of the quad, which contains no vertex of a conforming mesh. □\square

Lemma 3 (recovery). If RECOVER returns a mesh, it is a conforming mesh of the same region, cdcd is an edge of it, and no edge crosses the open segment cdcd. The quad edges abab, bdbd and caca are never flipped. The number of flips is at least the number of edges of TT that cross cdcd.

Proof. Each step is a flip of Lemma 2, so the mesh stays conforming. The loop stops only when no edge crosses cdcd, and the code then checks that cdcd is an edge. A vertex on the segment cdcd makes the code fail before the loop, so it is not on the path. The code flips only edges that cross the open segment cdcd at a point inside both. The edges caca and bdbd share an end with cdcd, so the orientation of that end against the line cdcd is zero, and they do not cross. The edge abab is the opposite side of cdcd in the strictly convex quad, so it does not meet cdcd. A flip removes one edge and adds one, so the number of crossing edges falls by at most one per flip, which gives the lower bound. □\square

Lemma 4 (each triangle is inside or outside). After recovery, every triangle lies either inside the closed quad qq or outside its interior.

Proof. The four sides of qq are edges of the mesh, by Lemma 3. The interior of a triangle meets no edge of a conforming mesh, so it does not meet the boundary of qq. The interior of a triangle is connected, so it lies in the interior of qq or outside the closed quad. □\square

Theorem 5 (one step). If the step returns a quad qq and a list RR of triangles, then R∪{q}R \cup \{q\} is a conforming mesh of the same region as TT: every cell is strictly convex and counterclockwise, no directed edge is used twice, the boundary edges and the total area are the same, the quad contains abab and the top edge dcdc, and the deleted triangles are exactly the triangles of the recovered mesh that lie inside qq.

Proof. The flood fill (L7) starts at the triangle left of a→ba \to b. That triangle has points near the middle of abab on the left of abab, which are inside qq, so by Lemma 4 it lies inside qq. The fill moves only across edges that are not sides of qq, and a triangle inside qq shares such an edge only with a triangle whose interior meets the interior of qq; by Lemma 4 that triangle is inside too. So every filled triangle is inside qq. The filled triangles have disjoint interiors, and L8 checks that their areas add up to the area of qq. A closed subset of qq with the full area of qq is qq, so the filled triangles cover qq. Then every triangle inside qq is filled, because its interior would overlap the cover otherwise. This is the set that the test compares with the brute force of centroids. Inside qq, no vertex lies on a side other than at a corner: the sides abab, bdbd, caca were mesh edges before recovery and stay mesh edges, and L5 rejects a vertex on cdcd. So the boundary edges of the filled set are exactly a→ba \to b, b→db \to d, d→cd \to c, c→ac \to a, the directed edges of qq. Replacing the filled triangles by qq keeps every directed edge outside qq and puts the same four directed edges back, so no directed edge is used twice, the neighbours across the sides see the same edges, and the area is the same. The vertices strictly inside qq leave the mesh with their triangles. □\square

Termination. Side edge selection looks at the neighbours of two vertices. Recovery does at most a fixed cap of flips, here 1000, and each flip costs O(n)O(n) in this simple code. The flood fill visits each triangle once. So the step always stops. Whether recovery always succeeds without the cap is the open point named above. On 37 random recoveries in meshes of 36 vertices, with up to 15 crossing edges, recovery never failed, and in 23 of them the number of flips equalled the lower bound of Lemma 3.

What is not proved. No bound on the angles or the shape of the quad is proved. The side edges are the mesh edges closest to the ideal direction, but the closest edge can still be far from it, and the quad can be thin; Q-Morph improves the side edges by swaps and splits and smooths the mesh afterwards, and the quality of the result is measured, not proved. The step can fail when the two side edges end at the same vertex or the quad is not convex; Q-Morph then uses other side edges or a split, which are not here.

Complexity

In this simple code, each flip rebuilds the edge map, so recovery costs O(fn)O(f n) for ff flips, and the search costs O(n)O(n). With an adjacency structure, a flip costs O(1)O(1), and the step costs O(f+k)O(f + k) for kk triangles inside the quad, plus the cost to find the crossing edges along cdcd. Each flip removes at most one crossing edge, so ff is at least the number of edges that cross cdcd. Q-Morph as a whole makes about one quad for every two triangles, and the local work per quad is small, so the total cost is close to linear in the number of triangles in practice.

Properties

  • Indirect. Q-Morph needs a triangle mesh first, but any valid triangle mesh will do, often a Delaunay triangulation.
  • Always covered. The region is covered by quads and triangles after every step, so there are no front crossing tests.
  • Boundary aligned. The rows of quads follow the boundary, as in paving.
  • Parity. The boundary must have an even number of edges for an all-quad result.
  • No guarantee. No bound on angles and no proof of success are known; quality depends on side edge choice and smoothing.
  • Step proved. An accepted step is a conforming mesh, with exact checks.

Variants and improvements

  • Side edge swaps and splits. When no mesh edge is close to the ideal direction, Q-Morph swaps an edge or splits one, which this code does not do.
  • Smoothing. Q-Morph smooths the new quad nodes and the nearby triangle nodes as the front moves; see Laplacian smoothing.
  • Blossom-Quad. Pairs the triangles into quads all at once by a minimum cost perfect matching, instead of a front; see Blossom-Quad.
  • Hex meshing. Owen and Saigal extended the idea to hexahedra over a tetrahedral mesh (H-Morph), which is harder to make robust.
  • Constrained recovery. The top edge recovery is the same operation as edge insertion in a constrained Delaunay triangulation.

When to use it

Use Q-Morph when you need an all-quad mesh of a planar region or a CAD face with quads aligned with the boundary, and a good triangle mesher is already available. It is often more robust than direct paving, because the triangle mesh solves the global problem of covering the region. If boundary alignment is less important than speed and global quality, Blossom-Quad is an alternative. For a region that maps to a rectangle, a structured grid is better than both.

Pitfalls

  • Odd boundary count. A front loop with an odd number of edges cannot end with quads only. Fix the count first, or accept one triangle.
  • Lost side edges. Recovery must never flip a side of the quad. Flip only edges that cross the open segment cdcd; the sides share an end with it or lie opposite it.
  • Vertex on the top edge. If a vertex lies on cdcd, no flips can make cdcd an edge. Test for it before the flips.
  • Holes. If the quad covers a hole of the region, the search fills only part of it. Compare the areas, as in L8.
  • Float tests. Crossing tests in floats can miss a touch and leave a crossed edge. Use exact tests.
  • Poor quads. The closest mesh edge can still be far from the ideal direction. Swap or split, and smooth.

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.

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

"""Small exact tools for triangle and tetrahedral meshes, used by the mg3 pages.

Points are tuples of int, fractions.Fraction or float. Every predicate here is
exact when the coordinates are int or Fraction. A float converts to a Fraction
without rounding, so exact() followed by a predicate gives the exact sign for
the float points as they are stored. Nothing here builds a mesh; each page
builds its own.
"""

import math
from fractions import Fraction
from typing import Dict, Iterable, List, 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 to_grid(x: float, bits: int = 20) -> Fraction:
    """The nearest multiple of 2**-bits to x, as a Fraction."""
    return Fraction(round(x * (1 << bits)), 1 << bits)


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 incircle(a: Point, b: Point, c: Point, d: Point):
    """Positive if d is inside the circle through a, b, c (a, b, c counterclockwise),
    zero if on it, negative if outside."""
    rows = []
    for p in (a, b, c):
        dx, dy = p[0] - d[0], p[1] - d[1]
        rows.append((dx, dy, dx * dx + dy * dy))
    (a0, a1, a2), (b0, b1, b2), (c0, c1, c2) = rows
    return a0 * (b1 * c2 - b2 * c1) - a1 * (b0 * c2 - b2 * c0) + a2 * (b0 * c1 - b1 * c0)


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

    Positive if d lies on the side of the plane abc toward which (b - a) x (c - a)
    points, that is, if a, b, c look clockwise from d."""
    u = (b[0] - a[0], b[1] - a[1], b[2] - a[2])
    v = (c[0] - a[0], c[1] - a[1], c[2] - a[2])
    w = (d[0] - a[0], d[1] - a[1], d[2] - a[2])
    return (u[0] * (v[1] * w[2] - v[2] * w[1])
            - u[1] * (v[0] * w[2] - v[2] * w[0])
            + u[2] * (v[0] * w[1] - v[1] * w[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 segments_cross(a: Point, b: Point, c: Point, d: Point) -> bool:
    """True if the open segments ab and cd cross at one point inside both."""
    return (orient2d(a, b, c) * orient2d(a, b, d) < 0
            and orient2d(c, d, a) * orient2d(c, d, b) < 0)


def edge_map(cells: Iterable[Sequence[int]]) -> Dict[Tuple[int, int], int]:
    """Map each directed edge (i, j) of a list of counterclockwise polygons
    (triangles or quads, given by vertex indices) to the index of its cell.
    Raises ValueError if a directed edge is used twice."""
    m: Dict[Tuple[int, int], int] = {}
    for k, cell in enumerate(cells):
        n = len(cell)
        for s in range(n):
            e = (cell[s], cell[(s + 1) % n])
            if e in m:
                raise ValueError("directed edge %r used twice" % (e,))
            m[e] = k
    return m


def boundary_edges(cells: Iterable[Sequence[int]]) -> List[Tuple[int, int]]:
    """The directed edges whose reverse is not an edge of any cell."""
    m = edge_map(cells)
    return [e for e in m if (e[1], e[0]) not in m]


def is_valid_planar_mesh(points: Sequence[Point], cells: Sequence[Sequence[int]]) -> bool:
    """Exact check that every cell is a strictly convex counterclockwise polygon
    and that no directed edge is used twice. With the area sum of the caller,
    this shows a conforming mesh of a simply covered region."""
    try:
        edge_map(cells)
    except ValueError:
        return False
    for cell in cells:
        n = len(cell)
        for s in range(n):
            a, b, c = points[cell[s]], points[cell[(s + 1) % n]], points[cell[(s + 2) % n]]
            if orient2d(a, b, c) <= 0:
                return False
    return True


def mean_ratio(a: Point, b: Point, c: Point) -> float:
    """The mean ratio 4 sqrt(3) A / (sum of squared edge lengths) of a triangle,
    in floats; 1 for the equilateral triangle, 0 for a flat one, negative if the
    triangle is clockwise."""
    s = sum(float((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2) for p, q in ((a, b), (b, c), (c, a)))
    return 2.0 * math.sqrt(3.0) * float(orient2d(a, b, c)) / s
q_morph.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/q-morph/. The authors are listed in prov/D6Y61V.jsonl.

"""The core step of Owen's Q-Morph: turn triangles next to one front edge into a quad.

The input is a conforming triangle mesh, given as counterclockwise index
triples over exact points (int or Fraction), and a front edge a -> b whose left
side is a triangle. The step

1. picks a side edge at a and at b: the existing mesh edge whose direction is
   closest to the ideal direction, here the inward normal of ab;
2. recovers the top edge c d between the far ends of the side edges, by
   flipping triangle edges that cross the segment c d;
3. merges the triangles inside the quad a, b, d, c into one quad.

Every test is exact. The whole of Q-Morph also smooths, swaps or splits edges
to improve the side edges, classifies front edges by the state of their ends,
and closes the front; none of that is here. The step returns None and a reason
when it cannot form a strictly convex quad.
"""

import math
from typing import Dict, List, Optional, Sequence, Tuple

from mg3geom import orient2d, segments_cross

Tri = Tuple[int, int, int]


def directed_owner(tris: Sequence[Tri]) -> Dict[Tuple[int, int], int]:
    m = {}
    for k, (a, b, c) in enumerate(tris):
        for e in ((a, b), (b, c), (c, a)):
            m[e] = k
    return m


def undirected_edges(tris: Sequence[Tri]):
    return {(min(x, y), max(x, y)) for t in tris for x, y in ((t[0], t[1]), (t[1], t[2]), (t[2], t[0]))}


def neighbours(tris: Sequence[Tri], v: int):
    return sorted({w for t in tris if v in t for w in t if w != v})


def angle_between(u, v) -> float:
    return abs(math.atan2(float(u[0] * v[1] - u[1] * v[0]), float(u[0] * v[0] + u[1] * v[1])))


def side_edge(P, tris, a: int, b: int, at: int) -> int:
    """The neighbour w of `at` (not a or b) for which the edge at -> w is closest in
    angle to the inward normal of the front edge a -> b."""
    ideal = (-(P[b][1] - P[a][1]), P[b][0] - P[a][0])
    best = None
    for w in neighbours(tris, at):
        if w in (a, b):
            continue
        d = (P[w][0] - P[at][0], P[w][1] - P[at][1])
        key = (angle_between(ideal, d), w)
        if best is None or key < best:
            best = key
    if best is None:
        raise ValueError("no side edge")
    return best[1]


def flip(P, tris: List[Tri], u: int, v: int) -> Optional[List[Tri]]:
    """Flip the edge uv if its two triangles form a strictly convex quad."""
    own = directed_owner(tris)
    if (u, v) not in own or (v, u) not in own:
        return None
    t1, t2 = own[(u, v)], own[(v, u)]
    k = next(x for x in tris[t1] if x not in (u, v))
    l = next(x for x in tris[t2] if x not in (u, v))
    if orient2d(P[k], P[u], P[l]) <= 0 or orient2d(P[l], P[v], P[k]) <= 0:
        return None
    rest = [t for i, t in enumerate(tris) if i not in (t1, t2)]
    return rest + [(k, u, l), (l, v, k)]


def recover_edge(P, tris: List[Tri], c: int, d: int, cap: int = 1000):
    """Flip edges that cross the open segment cd until cd is an edge.
    Returns (triangles, number of flips) or (None, reason)."""
    for v in range(len(P)):
        if v not in (c, d) and orient2d(P[c], P[d], P[v]) == 0 and \
                min(P[c][0], P[d][0]) <= P[v][0] <= max(P[c][0], P[d][0]) and \
                min(P[c][1], P[d][1]) <= P[v][1] <= max(P[c][1], P[d][1]):
            return None, "a vertex lies on the top edge"
    flips = 0
    while True:
        crossing = [e for e in sorted(undirected_edges(tris)) if segments_cross(P[c], P[d], P[e[0]], P[e[1]])]  # @line L5
        if not crossing:
            break
        if flips >= cap:
            return None, "flip cap reached"
        done = None
        for prefer in (True, False):  # @line L6
            for u, v in crossing:
                new = flip(P, tris, u, v)
                if new is None:
                    continue
                k, l = new[-2][0], new[-2][2]
                if prefer and segments_cross(P[c], P[d], P[k], P[l]):
                    continue
                done = new
                break
            if done is not None:
                break
        if done is None:
            return None, "no crossing edge can be flipped"
        tris = done
        flips += 1
    if (min(c, d), max(c, d)) not in undirected_edges(tris):
        return None, "the top edge is not in the mesh"
    return tris, flips


def triangles_in_quad(tris: Sequence[Tri], a: int, b: int, d: int, c: int) -> List[int]:
    """The triangles reached from the triangle left of a -> b without crossing the
    quad edges ab, bd, dc, ca."""
    own = directed_owner(tris)
    wall = {frozenset(e) for e in ((a, b), (b, d), (d, c), (c, a))}
    start = own[(a, b)]
    seen, stack = {start}, [start]
    while stack:
        t = tris[stack.pop()]
        for x, y in ((t[0], t[1]), (t[1], t[2]), (t[2], t[0])):
            if frozenset((x, y)) in wall:
                continue
            u = own.get((y, x))
            if u is not None and u not in seen:
                seen.add(u)
                stack.append(u)
    return sorted(seen)


def qmorph_step(P, tris: List[Tri], a: int, b: int):
    """One Q-Morph quad on the front edge a -> b. Returns
    (quad, remaining triangles, flips) or (None, reason, 0)."""
    if (a, b) not in directed_owner(tris):
        return None, "a -> b is not an edge with a triangle on its left", 0
    c = side_edge(P, tris, a, b, a)  # @line L1
    d = side_edge(P, tris, a, b, b)  # @line L2
    if c == d:  # @line L3
        return None, "both side edges end at the same vertex", 0
    quad = (a, b, d, c)
    if any(orient2d(P[quad[s]], P[quad[(s + 1) % 4]], P[quad[(s + 2) % 4]]) <= 0 for s in range(4)):  # @line L4
        return None, "the quad a, b, d, c is not strictly convex", 0
    tris, flips = recover_edge(P, list(tris), c, d)
    if tris is None:
        return None, flips, 0
    inside = triangles_in_quad(tris, a, b, d, c)  # @line L7
    covered = sum(orient2d(P[t[0]], P[t[1]], P[t[2]]) for t in (tris[i] for i in inside))
    if covered != orient2d(P[a], P[b], P[d]) + orient2d(P[a], P[d], P[c]):  # @line L8
        return None, "the quad covers a hole of the mesh", 0
    rest = [t for i, t in enumerate(tris) if i not in set(inside)]  # @line L9
    return quad, rest, flips  # @line L10
test_q_morph.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/q-morph/. The authors are listed in prov/D6Y61V.jsonl.

import random
from fractions import Fraction as F

from mg3geom import boundary_edges, is_valid_planar_mesh, orient2d, segments_cross
from q_morph import flip, qmorph_step, recover_edge, undirected_edges


def grid_mesh(rng, W, H, scramble):
    """A triangle mesh of a jittered W x H grid, with the boundary nodes on the
    rectangle, then `scramble` random flips of convex interior edges."""
    P = []
    for j in range(H + 1):
        for i in range(W + 1):
            x, y = F(i), F(j)
            if 0 < i < W:
                x += F(rng.randint(-25, 25), 100)
            if 0 < j < H:
                y += F(rng.randint(-25, 25), 100)
            P.append((x, y))
    v = lambda i, j: j * (W + 1) + i
    tris = []
    for j in range(H):
        for i in range(W):
            a, b, c, d = v(i, j), v(i + 1, j), v(i + 1, j + 1), v(i, j + 1)
            if rng.random() < 0.5:
                tris += [(a, b, c), (a, c, d)]
            else:
                tris += [(a, b, d), (b, c, d)]
    assert is_valid_planar_mesh(P, tris)
    for _ in range(scramble):
        u, w = rng.choice(sorted(undirected_edges(tris)))
        new = flip(P, tris, u, w)
        if new is not None:
            tris = new
    assert is_valid_planar_mesh(P, tris)
    return P, tris


def area(P, cells):
    return sum(sum(orient2d(P[c[0]], P[c[s]], P[c[s + 1]]) for s in range(1, len(c) - 1)) for c in cells)


def inside_quad(P, q, x):
    return all(orient2d(P[q[s]], P[q[(s + 1) % 4]], x) > 0 for s in range(4))


def check_step(P, tris, a, b):
    quad, rest, flips = qmorph_step(P, tris, a, b)
    if quad is None:
        return None
    assert quad[0] == a and quad[1] == b
    c, d = quad[3], quad[2]
    # the top edge is present after recovery, and recovery is deterministic
    recovered, flips2 = recover_edge(P, list(tris), c, d)
    assert flips2 == flips and (min(c, d), max(c, d)) in undirected_edges(recovered)
    # the merged triangles are exactly those whose centroid is inside the quad (brute force)
    merged = sorted(set(recovered) - set(rest))
    brute = sorted(t for t in recovered
                   if inside_quad(P, quad, tuple(sum(P[k][i] for k in t) / 3 for i in range(2))))
    assert merged == brute and len(merged) + len(rest) == len(recovered)
    # exact area: the quad has the area of the merged triangles, and the total is kept
    assert area(P, [quad]) == area(P, merged) > 0
    assert area(P, rest + [quad]) == area(P, tris)
    # conformity: convex cells, no directed edge twice, the same domain boundary
    assert is_valid_planar_mesh(P, rest + [quad])
    assert set(boundary_edges(rest + [quad])) == set(boundary_edges(tris))
    return flips


def test_step_on_jittered_grids():
    rng = random.Random(1)
    done = 0
    for _ in range(6):
        W, H = rng.randint(3, 6), rng.randint(3, 6)
        P, tris = grid_mesh(rng, W, H, 0)
        for i in range(W):
            if check_step(P, tris, i, i + 1) is not None:
                done += 1
    assert done >= 15


def test_step_on_scrambled_meshes_needs_and_does_recovery():
    rng = random.Random(2)
    done = with_flips = 0
    for _ in range(10):
        W, H = rng.randint(4, 6), rng.randint(4, 6)
        P, tris = grid_mesh(rng, W, H, 300)
        for i in range(W):
            flips = check_step(P, tris, i, i + 1)
            if flips is not None:
                done += 1
                with_flips += flips > 0
    assert done >= 20 and with_flips >= 6


def test_edge_recovery_by_flips():
    rng = random.Random(3)
    recovered_count = 0
    for _ in range(20):
        P, tris = grid_mesh(rng, 5, 5, 200)
        c, d = rng.sample(range(len(P)), 2)
        crossing0 = sum(segments_cross(P[c], P[d], P[u], P[w]) for u, w in undirected_edges(tris))
        out, flips = recover_edge(P, list(tris), c, d)
        if out is None:
            assert flips == "a vertex lies on the top edge"
            continue
        recovered_count += 1
        assert (min(c, d), max(c, d)) in undirected_edges(out)
        assert not any(segments_cross(P[c], P[d], P[u], P[w]) for u, w in undirected_edges(out))
        # a flip removes at most one crossing edge, so at least crossing0 flips are needed
        assert flips >= crossing0
        assert is_valid_planar_mesh(P, out) and area(P, out) == area(P, tris)
        assert set(boundary_edges(out)) == set(boundary_edges(tris))
    assert recovered_count >= 10


def test_failures_are_reported():
    P = [(F(0), F(0)), (F(2), F(0)), (F(1), F(2))]
    quad, why, _ = qmorph_step(P, [(0, 1, 2)], 0, 1)
    assert quad is None and "same vertex" in why
    quad, why, _ = qmorph_step(P, [(0, 1, 2)], 1, 0)
    assert quad is None and "not an edge" in why
    # two triangles that already form a convex quad: no flip, the quad is the union
    P = [(F(0), F(0)), (F(2), F(0)), (F(3), F(1)), (F(-1), F(1))]
    quad, rest, flips = qmorph_step(P, [(0, 1, 3), (1, 2, 3)], 0, 1)
    assert quad == (0, 1, 2, 3) and rest == [] and flips == 0
    # the side edge at b leans over the side edge at a: the quad is not convex
    P = [(F(0), F(0)), (F(2), F(0)), (F(1), F(1)), (F(5, 2), F(3))]
    quad, why, _ = qmorph_step(P, [(0, 1, 2), (1, 3, 2)], 0, 1)
    assert quad is None and "not strictly convex" in why

History

Steven Owen, Matthew Staten, Scott Canann and Sunil Saigal published Q-Morph in the International Journal for Numerical Methods in Engineering in 1999. Paving, published in 1991, made good all-quad meshes, but its tests for crossing fronts were slow and fragile. Earlier indirect methods merged pairs of triangles into quads and split the rest, which gave poor alignment with the boundary. Q-Morph joined the two ideas: it moves a paving front over a triangle mesh, so the front never needs to test for crossings. It is still a standard reference method for indirect quad meshing.

References

  1. Steven J. Owen, Matthew L. Staten, Scott A. Canann and Sunil Saigal, Q-Morph, an indirect approach to advancing front quad meshing, International Journal for Numerical Methods in Engineering 44(9), 1999, 1317 to 1340, the front edge states, side edge definition, top edge recovery, quad formation, smoothing and seaming (general locator)

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
  • at least three sources
  • a scene preset for the example