Algorithm Search⌘K

Algorithmadvanced

Approximate convex decomposition

Also called ACD.

Split a nonconvex mesh into a few nearly convex parts whose concavity is below a tolerance, so that convex collision tests apply to each part.

Time
O((r + 1) (n + r) log(n + r)) worstO(r) cuts
Space
O(n + r) extra
Where
n = the number of vertices of the polygon; r = the number of reflex vertices
Properties
deterministicexactofflineiterative
Origin
Jyh Ming Lien, Nancy M. Amato, 2004

Approximate convex decomposition splits a nonconvex shape into a small number of pieces that are each nearly convex. The concavity of a piece measures how far its boundary goes into its convex hull. The method cuts only the parts that are more concave than a tolerance τ\tau, and leaves small dents in place. Then the convex hulls of the pieces replace the shape in collision detection, so that fast tests for convex shapes, such as GJK, apply to each piece. An exact convex decomposition is the case τ=0\tau = 0. It can need many more pieces, and in 3D the number can grow with the square of the number of reflex edges. This page uses a 2D polygon, where the ideas are the same as for meshes and every step can be checked.

In plain words

A collision test is fast for shapes with no dents, such as a box or a ball. Real objects, such as a chair or a cup, have dents and holes.

You can cut the object into pieces with no dents at all, but you can need very many pieces. Most of the dents are small, and a small dent hardly changes where two objects touch.

So measure each dent by how deep it goes. Cut only at the deepest dent. Check the two new pieces again, and cut them only if they still have a dent deeper than your limit. A larger limit gives fewer pieces that are a little less exact.

The problem

The input is a simple polygon PP with nn vertices and a tolerance τ≥0\tau \ge 0. The output is a set of simple polygons with disjoint interiors whose union is PP, each with a concavity of at most τ\tau, and with few pieces. Let HH be the convex hull of a polygon XX. The parts of HH outside XX are the pockets, and the edge of HH that closes a pocket is its bridge. The concavity of a vertex of XX is 00 on the hull, and otherwise its distance to the bridge of its pocket. The concavity of XX is the largest concavity of its vertices. This is the straight-line concavity of Lien and Amato. Their paper also uses a measure by shortest paths inside the pocket, and newer 3D methods use other measures. The measure and τ\tau are choices, and the answer depends on them.

The algorithm

  1. ACD(P, τ)
  2. 1Q ← [P]
  3. 2while Q is not empty
  4. 3take a piece X from Q
  5. 4compute the convex hull of X and the concavity of each vertex of X
  6. 5if the concavity of X is at most τ then add X to the output and continue
  7. 6v ← the reflex vertex of X with the largest concavity
  8. 7extend each edge at v beyond v to its first hit q on the boundary of X, and keep the shorter cut vq
  9. 8split X along vq into two pieces, and add both to Q
  10. 9return the output

Line L4 uses Andrew's monotone chain for the hull. The hull vertices appear in the order of XX, so the vertices between two consecutive hull vertices form a pocket, with the bridge between those two hull vertices. Line L7 is a choice of this page. An edge extension starts into the interior at a reflex vertex, so the cut is always valid, and each piece gets an angle of at most π\pi at vv. Lien and Amato resolve a notch by a cut that they choose with a score. The code uses exact rational arithmetic, so the hit points, the areas and the comparisons with τ\tau have no rounding. It compares squared distances with τ2\tau^2.

Example

Take a rectangle from (0,0)(0, 0) to (8,6)(8, 6) with two dents: the polygon (0,0),(3,0),(4,1),(5,0),(8,0),(8,6),(6,6),(5,2),(3,6),(0,6)(0,0), (3,0), (4,1), (5,0), (8,0), (8,6), (6,6), (5,2), (3,6), (0,6), with the area 41. Its hull is the rectangle. There are two pockets. The reflex vertex (4,1)(4, 1) has the bridge from (0,0)(0, 0) to (8,0)(8, 0) and the concavity 1. The reflex vertex (5,2)(5, 2) has the bridge from (8,6)(8, 6) to (0,6)(0, 6) and the concavity 4. The other vertices have the concavity 0.

τ\tau pieces what happens
4 or more 1 no cut
from about 0.728 up to 4 2 one cut at (5,2)(5, 2)
less than about 0.728 3 a second cut at (4,1)(4, 1), and all pieces are convex

With τ=1\tau = 1, the loop cuts at (5,2)(5, 2). The extension of the edge from (6,6)(6, 6) to (5,2)(5, 2) hits the edge from (4,1)(4, 1) to (5,0)(5, 0) at (23/5,2/5)(23/5, 2/5), with the length 1.6491.649. The extension of the edge from (3,6)(3, 6) to (5,2)(5, 2) hits (6,0)(6, 0), with the length 2.2362.236. Line L7 keeps the first cut. The right piece (23/5,2/5),(5,0),(8,0),(8,6),(6,6)(23/5, 2/5), (5, 0), (8, 0), (8, 6), (6, 6) is convex, with the area 82/582/5. The left piece, with the area 123/5123/5, still holds the dent at (4,1)(4, 1). Its bridge is now the segment from (3,0)(3, 0) to (23/5,2/5)(23/5, 2/5), because the cut took (5,0)(5, 0) out of this piece, so the concavity of the dent is now 3/17≈0.7283/\sqrt{17} \approx 0.728. This is at most 1, so the loop stops with two pieces. With τ=0.5\tau = 0.5, the loop also cuts at (4,1)(4, 1), along the extension of the edge from (3,0)(3, 0), which hits the vertex (5,2)(5, 2). This gives a triangle with the area 3/53/5 and a convex pentagon with the area 24. The areas always add up to 41.

Correctness

The proof is in proofs/correctness.md. A reflex vertex is never on the hull, so it has a positive concavity, and a polygon with the concavity 0 is convex. At a reflex vertex, both edge extensions start into the interior, so the cut to the first boundary hit is a chord, and it splits the piece into two simple polygons with the same union. The cut gives the vertex an angle of at most π\pi in both pieces and makes no new reflex vertex. So each cut lowers the total number of reflex vertices by at least one. The loop stops after at most rr cuts with at most r+1r + 1 pieces, and it outputs a piece only when its concavity is at most τ\tau. The proof does not depend on which reflex vertex or which extension the code picks.

Proof: The cut loop partitions the polygon into at most r + 1 pieces of concavity at most the tolerancefull

Let PP be a simple polygon with nn vertices and RR reflex vertices, and let τ≥0\tau \ge 0. We work in the real RAM, and the code is exact because it uses rational arithmetic. A polygon here is a simple polygon listed counterclockwise with no vertex of a straight angle. The code removes straight angles after each cut, and this changes neither the region nor the reflex vertices. For a polygon XX with the hull HH, the concavity of a vertex vv is 00 if vv is a vertex of HH. Otherwise it is the distance of vv to the bridge of vv, the segment between the nearest vertices of HH before and after vv along XX. The concavity of XX is the largest concavity of its vertices.

Lemma 1 (concavity 0 means convex). A reflex vertex of XX has a positive concavity. If XX has no reflex vertex, the concavity of XX is 00.

Proof. Let vv be a vertex of XX on the boundary of HH. There is a closed half-plane that holds HH with vv on its boundary line. XX is in HH, so near vv the interior of XX is in the half-plane, and the interior angle at vv is at most π\pi. So a reflex vertex is not on the boundary of HH. A bridge is an edge of HH, so it is on the boundary of HH, and the distance of a reflex vertex to its bridge is positive. If XX has no reflex vertex, then all its angles are less than π\pi, so XX is convex, X=HX = H, every vertex of XX is a vertex of HH, and every concavity is 00. □\square

Lemma 2 (the cut is a chord). Let rr be a reflex vertex of XX with the neighbors pp before and mm after it, let dd be r−pr - p or r−mr - m, and let qq be the first point of the boundary of XX, other than rr, on the ray r+s dr + s\,d with s>0s > 0. Then qq exists, the open segment from rr to qq is in the interior of XX, and the code finds qq.

Proof. The interior of XX is to the left of each edge. So the interior angle θ∈(π,2π)\theta \in (\pi, 2\pi) at rr is swept counterclockwise from the direction m−rm - r to the direction p−rp - r. The direction r−pr - p is at the angle θ−π\theta - \pi from m−rm - r in this sweep, and r−mr - m is at the angle π\pi. Both values are strictly between 00 and θ\theta, so the ray starts into the interior. XX is bounded, so the ray meets its boundary, and qq exists. The points of the ray just after rr are interior, the open segment from rr to qq is connected, and it does not meet the boundary, so it stays in the interior. The ray meets the edge prpr only at rr, because it is on the line of that edge and goes away from pp. It meets the edge rmrm only at rr, because θ≠π\theta \neq \pi. So the code can skip these two edges. For each other edge it computes the exact intersection, or the ends of the edge if the edge is on the line of the ray, and it keeps the smallest s>0s > 0. □\square

Lemma 3 (a cut removes a reflex vertex). Cut XX along the segment rqrq of Lemma 2, with qq added as a vertex if it is inside an edge. The result is two polygons AA and BB with disjoint interiors and A∪B=XA \cup B = X, so area⁡(A)+area⁡(B)=area⁡(X)\operatorname{area}(A) + \operatorname{area}(B) = \operatorname{area}(X), and AA and BB have together at most RX−1R_X - 1 reflex vertices, where RXR_X is the number of reflex vertices of XX.

Proof. By Lemma 2, rqrq is a chord of XX: its ends are on the boundary and the rest is in the interior. A chord splits a simple polygon into two simple polygons. Their boundaries are the two chains of the boundary of XX from rr to qq, each closed by rqrq, and both are counterclockwise. The angles at the vertices other than rr and qq do not change. At rr the angle θ\theta splits into θ−π\theta - \pi and π\pi, or into π\pi and θ−π\theta - \pi, and both are at most π\pi, so rr is not reflex in AA or BB. If qq is inside an edge, the angle π\pi at qq splits into two positive parts, because the segment does not run along the edge, so both parts are less than π\pi. If qq is a vertex of angle φ\varphi, the angle splits into two positive parts with the sum φ<2π\varphi < 2\pi, so at most one part is more than π\pi, and none is more than π\pi if φ<π\varphi < \pi. So rr stops being reflex, and no vertex becomes reflex. □\square

Theorem. The loop terminates after at most RR cuts. It returns at most R+1R + 1 polygons with disjoint interiors whose union is PP, and each has a concavity of at most τ\tau. If τ=0\tau = 0, each returned polygon is convex.

Proof. The invariant is: the polygons in the queue and the output together have disjoint interiors and the union PP. It holds at the start, when the queue holds only PP. Moving a polygon to the output keeps it. When the loop takes a polygon XX with a concavity above τ≥0\tau \ge 0, Lemma 1 gives a reflex vertex of XX, so line L6 has a choice, and Lemma 3 replaces XX by two polygons with the same union and disjoint interiors, so the invariant holds again. Let Φ\Phi be the total number of reflex vertices in the queue. At the start Φ=R\Phi = R, a cut lowers Φ\Phi by at least 1 by Lemma 3, and moving a polygon to the output does not raise it. So there are at most RR cuts. Each cut adds one polygon, so the output has at most R+1R + 1 polygons, and the loop runs at most 2R+12R + 1 times. When the queue is empty, the invariant says that the output is a partition of PP, and line L5 adds a polygon to the output only if its concavity is at most τ\tau. If τ=0\tau = 0, Lemma 1 says that a polygon with a reflex vertex has a positive concavity, so each output polygon has no reflex vertex and is convex. ■\blacksquare

Remarks. The theorem does not depend on the choice of the reflex vertex at line L6 or on the choice of the edge at line L7. Any reflex vertex and either extension give a correct result. These choices change only the number and the shape of the pieces. With τ=0\tau = 0 the bound of R+1R + 1 pieces is the usual bound for removing the reflex vertices of a polygon one at a time. In 3D there is no such linear bound: Chazelle (1984) gives polyhedra with rr reflex edges for which every convex decomposition has Ω(r2)\Omega(r^2) pieces.

Complexity

There are at most rr cuts, so the loop runs at most 2r+12r + 1 times. A cut adds at most one vertex, so a piece has at most n+rn + r vertices. Each round costs O(mlog⁡m)O(m \log m) for the hull of a piece with mm vertices and O(m)O(m) for the concavities and the cut. The total is O((r+1)(n+r)log⁡(n+r))O((r + 1)(n + r)\log(n + r)) in the real RAM. The code uses Fractions, and the size of the numbers grows with the depth of the cuts, which this bound does not count. In practice the cost is in the number of pieces, because every collision query then runs on each pair of pieces.

Properties

  • A valid partition for any choice. Any reflex vertex and any edge extension give a correct partition. The rule changes only the number and the shape of the pieces.
  • At most r + 1 pieces. For τ=0\tau = 0 the output is a convex partition with at most r+1r + 1 pieces. Hertel and Mehlhorn give a partition within four times the optimum, and the optimum can be found in polynomial time for a polygon without holes.
  • Fewer pieces for a larger tolerance. On 100 random star-shaped polygons with 16 integer vertices and a mean of 6.36 reflex vertices, the mean number of pieces was 7.33 for τ=0\tau = 0, 6.4 for τ=1\tau = 1, 4.92 for τ=4\tau = 4 and 3.58 for τ=8\tau = 8. The mean concavity of the input was 15.2. These are measured values for this cut rule. For a greedy rule like this one, a larger τ\tau does not give fewer pieces for every input.
  • Not optimal. The method is greedy and does not minimize the number of pieces for a given τ\tau.

Variants and improvements

  • Shortest-path concavity. Lien and Amato also measure the concavity by the shortest path from the vertex to the bridge inside the pocket. This is larger for pockets that curl, and costs more to compute.
  • Polyhedra. Lien and Amato (2007) extend the concavity measure and the cuts to polyhedra.
  • Hierarchical clustering. Mamou and Ghorbel (2009) build the pieces of a mesh from the bottom up. They merge adjacent parts in the dual graph of the triangles while the merged part stays nearly convex.
  • Collision-aware concavity. Wei, Liu, Ling and Su (2022) measure the concavity by the distance between the shape and its hull from both the boundary and the interior. They cut the mesh with planes and choose the planes by a tree search, not by one greedy step.
  • Use the hulls. A physics engine stores the convex hull of each piece, not the piece itself. The hulls fill the dents that the method left, and with this measure each pocket vertex is at most τ\tau from its bridge.

When to use it

Use approximate convex decomposition to make collision shapes for a nonconvex rigid body before the simulation starts. The convex hulls of the pieces go into a bounding volume hierarchy, and each pair of pieces that overlap goes to a convex collision test. Choose τ\tau from the size of the smallest gap or dent that must stay visible in contacts. Use an exact convex decomposition when the pieces must match the shape exactly, for example for a Minkowski sum.

Pitfalls

  • Units. The concavity is a length. A fixed τ\tau gives very different results on a small object and on a large one, so scale τ\tau to the size of the object.
  • Too many pieces for small τ\tau. Each piece costs time in every collision query. Very small values of τ\tau give a large number of pieces with little gain.
  • The hulls can overlap other parts. The hull of a piece covers its dents, so a thin gap between two parts of the object can close. A slot or a handle can become solid.
  • Rounding. In floating point the hit point of a cut can fall just outside the polygon or make a tiny sliver piece. Exact arithmetic, or snapping the hit to a nearby vertex, avoids this.
  • Simple input. The 2D method needs a simple polygon. A mesh for the 3D methods must be closed and without self-intersections, or the concavity is not well defined.

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.

approximate_convex_decomposition.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approximate-convex-decomposition/. The authors are listed in prov/1SYCDG.jsonl.

"""Approximate convex decomposition of a simple polygon, in exact rational arithmetic.

The concavity of a vertex is its distance to the bridge of its pocket: the convex hull edge that
spans the chain of the polygon that holds the vertex. Hull vertices have concavity 0. The
concavity of a polygon is the largest concavity of its vertices.

While a piece has a concavity above the tolerance tau, the code cuts its reflex vertex of
largest concavity. The cut extends one of the two edges at that vertex beyond it, to the first
point where it meets the boundary, and the code keeps the shorter of the two cuts. This cut
rule is a choice of this page. The paper of Lien and Amato picks the cut by a score.

All coordinates are Fractions, so the areas, the hulls, the cuts and the comparisons with tau are
exact. Distances are compared as squares.
"""

from __future__ import annotations

import math
from fractions import Fraction

Point = tuple


def _pt(p) -> Point:
    return (Fraction(p[0]), Fraction(p[1]))


def cross(o: Point, a: Point, b: Point):
    """The z part of (a - o) x (b - o): positive for a left turn o, a, b."""
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


def area2(P: list) -> Fraction:
    """Twice the signed area of the polygon P, positive if P is counterclockwise."""
    n = len(P)
    return sum((P[i][0] * P[(i + 1) % n][1] - P[(i + 1) % n][0] * P[i][1] for i in range(n)), Fraction(0))


def convex_hull(points: list) -> list:
    """Andrew's monotone chain: the hull vertices in counterclockwise order, without collinear points."""
    pts = sorted(set(points))
    if len(pts) <= 2:
        return pts
    lower: list = []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    upper: list = []
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    return lower[:-1] + upper[:-1]


def is_reflex(P: list, i: int) -> bool:
    n = len(P)
    return cross(P[i - 1], P[i], P[(i + 1) % n]) < 0


def reflex_count(P: list) -> int:
    return sum(is_reflex(P, i) for i in range(len(P)))


def seg_dist2(p: Point, a: Point, b: Point) -> Fraction:
    """The squared distance of p to the segment ab."""
    ab = (b[0] - a[0], b[1] - a[1])
    ap = (p[0] - a[0], p[1] - a[1])
    L = ab[0] * ab[0] + ab[1] * ab[1]
    t = (ap[0] * ab[0] + ap[1] * ab[1]) / L if L else Fraction(0)
    t = min(max(t, Fraction(0)), Fraction(1))
    dx, dy = ap[0] - t * ab[0], ap[1] - t * ab[1]
    return dx * dx + dy * dy


def vertex_concavities(P: list) -> list:
    """The squared concavity of each vertex of the counterclockwise simple polygon P."""
    n = len(P)
    hull = set(convex_hull(P))
    idx = [i for i in range(n) if P[i] in hull]
    conc = [Fraction(0)] * n
    for k, a in enumerate(idx):
        b = idx[(k + 1) % len(idx)]
        j = (a + 1) % n
        while j != b:  # the pocket between the hull vertices a and b, with the bridge P[a] P[b]
            conc[j] = seg_dist2(P[j], P[a], P[b])
            j = (j + 1) % n
    return conc


def concavity(P: list) -> float:
    """The concavity of the polygon P (a float, the square root of the exact square)."""
    P = normalize(P)
    return math.sqrt(max(vertex_concavities(P)))


def normalize(P: list) -> list:
    """Fractions, counterclockwise, and no vertex with a straight angle."""
    P = [_pt(p) for p in P]
    if area2(P) < 0:
        P.reverse()
    changed = True
    while changed and len(P) > 3:
        changed = False
        for i in range(len(P)):
            if cross(P[i - 1], P[i], P[(i + 1) % len(P)]) == 0:
                del P[i]
                changed = True
                break
    return P


def first_hit(P: list, i: int, d: Point):
    """The first point where the ray from P[i] in the direction d meets an edge not at P[i].

    Returns (q, j, u): the point, the index j of the edge P[j] P[j+1], and the parameter u of q on it.
    """
    n = len(P)
    r = P[i]
    best = None
    for j in range(n):
        if j == i or (j + 1) % n == i:
            continue
        a, b = P[j], P[(j + 1) % n]
        e = (b[0] - a[0], b[1] - a[1])
        ar = (a[0] - r[0], a[1] - r[1])
        den = d[0] * e[1] - d[1] * e[0]
        cands = []
        if den != 0:
            s = (ar[0] * e[1] - ar[1] * e[0]) / den
            u = (ar[0] * d[1] - ar[1] * d[0]) / den
            if s > 0 and 0 <= u <= 1:
                cands.append((s, u))
        elif ar[0] * d[1] - ar[1] * d[0] == 0:  # the edge is on the line of the ray
            dd = d[0] * d[0] + d[1] * d[1]
            for u, x in ((Fraction(0), a), (Fraction(1), b)):
                s = ((x[0] - r[0]) * d[0] + (x[1] - r[1]) * d[1]) / dd
                if s > 0:
                    cands.append((s, u))
        for s, u in cands:
            if best is None or s < best[0]:
                best = (s, j, u)
    s, j, u = best
    q = (r[0] + s * d[0], r[1] + s * d[1])
    return q, j, u


def _chain(V: list, a: int, b: int) -> list:
    out = [V[a]]
    k = a
    while k != b:
        k = (k + 1) % len(V)
        out.append(V[k])
    return out


def split(P: list, i: int, q: Point, j: int, u: Fraction):
    """Split P along the segment from P[i] to q, where q is on the edge P[j] P[j+1] at the parameter u."""
    n = len(P)
    V = list(P)
    if u == 0:
        k = j
    elif u == 1:
        k = (j + 1) % n
    else:
        V.insert(j + 1, q)
        k = j + 1
        if k <= i:
            i += 1
    return normalize(_chain(V, i, k)), normalize(_chain(V, k, i))


def best_cut(P: list, i: int):
    """The shorter of the two cuts that extend an edge at the reflex vertex P[i] beyond it."""
    n = len(P)
    r, prev, nxt = P[i], P[i - 1], P[(i + 1) % n]
    best = None
    for d in ((r[0] - prev[0], r[1] - prev[1]), (r[0] - nxt[0], r[1] - nxt[1])):
        q, j, u = first_hit(P, i, d)
        L = (q[0] - r[0]) ** 2 + (q[1] - r[1]) ** 2
        if best is None or L < best[0]:
            best = (L, q, j, u)
    return best[1:]


def approximate_convex_decomposition(P: list, tau) -> list:
    """Pieces of the simple polygon P, each with a concavity of at most tau.

    The pieces are counterclockwise lists of Fraction points. Their interiors are disjoint and
    their union is P. With tau = 0 the pieces are convex.
    """
    tau2 = Fraction(tau) ** 2
    queue = [normalize(P)]  # @line L1
    done: list = []
    while queue:  # @line L2
        X = queue.pop()  # @line L3
        conc = vertex_concavities(X)  # @line L4
        if max(conc) <= tau2:  # @line L5
            done.append(X)
            continue
        i = max((k for k in range(len(X)) if is_reflex(X, k)), key=lambda k: (conc[k], -k))  # @line L6
        q, j, u = best_cut(X, i)  # @line L7
        A, B = split(X, i, q, j, u)  # @line L8
        assert reflex_count(A) + reflex_count(B) < reflex_count(X)
        queue += [B, A]
    return done  # @line L9
test_approximate_convex_decomposition.py 191 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approximate-convex-decomposition/. The authors are listed in prov/1SYCDG.jsonl.

import math
import random
from fractions import Fraction

import pytest

from approximate_convex_decomposition import (
    approximate_convex_decomposition,
    area2,
    concavity,
    cross,
    normalize,
    reflex_count,
    seg_dist2,
    vertex_concavities,
)

EXAMPLE = [(0, 0), (3, 0), (4, 1), (5, 0), (8, 0), (8, 6), (6, 6), (5, 2), (3, 6), (0, 6)]


def F(*xs):
    return tuple(Fraction(x) for x in xs)


def _orient(a, b, c):
    v = cross(a, b, c)
    return (v > 0) - (v < 0)


def _on_segment(p, a, b):
    return _orient(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 _segments_meet(a, b, c, d):
    o1, o2, o3, o4 = _orient(a, b, c), _orient(a, b, d), _orient(c, d, a), _orient(c, d, b)
    if o1 != o2 and o3 != o4 and 0 not in (o1, o2, o3, o4):
        return True
    return _on_segment(c, a, b) or _on_segment(d, a, b) or _on_segment(a, c, d) or _on_segment(b, c, d)


def is_simple(P):
    n = len(P)
    if len(set(P)) != n or n < 3:
        return False
    for i in range(n):
        a, b = P[i], P[(i + 1) % n]
        for j in range(i + 1, n):
            c, d = P[j], P[(j + 1) % n]
            if j == i + 1 or (i == 0 and j == n - 1):
                far_end = d if j == i + 1 else c  # the end of the edge cd that is not shared with ab
                near_end = a if j == i + 1 else b
                if _on_segment(far_end, a, b) or _on_segment(near_end, c, d):
                    return False  # adjacent edges that overlap
                continue
            if _segments_meet(a, b, c, d):
                return False
    return True


def on_boundary(p, P):
    return any(_on_segment(p, P[i], P[(i + 1) % len(P)]) for i in range(len(P)))


def strictly_inside(p, P):
    if on_boundary(p, P):
        return False
    inside = False
    n = len(P)
    for i in range(n):
        a, b = P[i], P[(i + 1) % n]
        if (a[1] > p[1]) != (b[1] > p[1]):
            x = a[0] + (p[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1])
            if x > p[0]:
                inside = not inside
    return inside


def random_polygon(rng, n):
    """A random simple star-shaped polygon with integer vertices, counterclockwise."""
    while True:
        angles = sorted(rng.uniform(0, 2 * math.pi) for _ in range(n))
        P = []
        for a in angles:
            R = rng.uniform(4, 30)
            P.append(F(round(R * math.cos(a)), round(R * math.sin(a))))
        if is_simple(P) and area2(P) > 0:
            return P


def brute_concavities(P):
    """The squared concavities with the hull by brute force: ab is a hull edge if no point is right of it."""
    n = len(P)
    pairs = [(i, j) for i in range(n) for j in range(n) if i != j and all(cross(P[i], P[j], P[k]) >= 0 for k in range(n))]
    on_hull = {i for pair in pairs for i in pair}
    # keep the corners only: drop a point in the middle of a hull edge, as the monotone chain does
    hull = {i for i in on_hull if not any(i not in (a, b) and _on_segment(P[i], P[a], P[b]) for a, b in pairs)}
    out = []
    for v in range(n):
        if v in hull:
            out.append(Fraction(0))
            continue
        a = v
        while a not in hull:
            a = (a - 1) % n
        b = v
        while b not in hull:
            b = (b + 1) % n
        out.append(seg_dist2(P[v], P[a], P[b]))
    return out


def test_page_example():
    P = normalize(EXAMPLE)
    assert area2(P) == 82
    conc = vertex_concavities(P)
    assert conc[P.index(F(5, 2))] == 16 and conc[P.index(F(4, 1))] == 1
    assert sum(1 for x in conc if x) == 2
    assert len(approximate_convex_decomposition(EXAMPLE, 4)) == 1
    two = approximate_convex_decomposition(EXAMPLE, 1)
    assert len(two) == 2
    assert sorted(area2(X) / 2 for X in two) == [Fraction(82, 5), Fraction(123, 5)]
    left = next(X for X in two if F(0, 0) in X)
    assert F(Fraction(23, 5), Fraction(2, 5)) in left
    assert max(vertex_concavities(left)) == Fraction(9, 17)  # 3 / sqrt(17) for the vertex (4, 1)
    three = approximate_convex_decomposition(EXAMPLE, Fraction(1, 2))
    assert len(three) == 3 and all(reflex_count(X) == 0 for X in three)
    assert sorted(area2(X) / 2 for X in three) == [Fraction(3, 5), Fraction(82, 5), 24]


def test_convex_input_is_one_piece():
    sq = [(0, 0), (2, 0), (2, 2), (1, 2), (0, 2)]
    D = approximate_convex_decomposition(sq, 0)
    assert len(D) == 1 and area2(D[0]) == 8 and len(D[0]) == 4
    assert concavity(sq) == 0
    assert len(approximate_convex_decomposition(list(reversed(sq)), 0)) == 1


def test_concavity_against_brute_force():
    rng = random.Random(5)
    for _ in range(60):
        P = random_polygon(rng, rng.randint(5, 12))
        P = normalize(P)
        assert vertex_concavities(P) == brute_concavities(P)


def test_a_reflex_vertex_has_positive_concavity():
    rng = random.Random(6)
    for _ in range(60):
        P = normalize(random_polygon(rng, rng.randint(5, 12)))
        conc = vertex_concavities(P)
        for i in range(len(P)):
            if cross(P[i - 1], P[i], P[(i + 1) % len(P)]) < 0:
                assert conc[i] > 0


@pytest.mark.parametrize("tau", [0, 1, 3])
def test_random_polygons_are_partitioned(tau):
    rng = random.Random(100 + tau)
    for _ in range(25):
        P = normalize(random_polygon(rng, rng.randint(6, 12)))
        r = reflex_count(P)
        D = approximate_convex_decomposition(P, tau)
        assert 1 <= len(D) <= r + 1
        assert sum(area2(X) for X in D) == area2(P)
        for X in D:
            assert area2(X) > 0 and is_simple(X)
            assert max(vertex_concavities(X)) <= Fraction(tau) ** 2
            assert all(strictly_inside(v, P) or on_boundary(v, P) for v in X)
            if tau == 0:
                assert reflex_count(X) == 0
        xs = [p[0] for p in P]
        ys = [p[1] for p in P]
        for _ in range(40):
            p = (Fraction(rng.randint(int(min(xs)) * 16, int(max(xs)) * 16), 16) + Fraction(1, 97),
                 Fraction(rng.randint(int(min(ys)) * 16, int(max(ys)) * 16), 16) + Fraction(1, 89))
            if any(on_boundary(p, X) for X in D):
                continue
            count = sum(strictly_inside(p, X) for X in D)
            assert count == (1 if strictly_inside(p, P) else 0)


def test_a_smaller_tolerance_never_leaves_a_concave_piece():
    rng = random.Random(9)
    for _ in range(20):
        P = random_polygon(rng, 10)
        for tau in (Fraction(1, 2), 2, 5):
            for X in approximate_convex_decomposition(P, tau):
                assert concavity(X) <= tau + 1e-12

History

Exact convex decomposition was studied first. Chazelle (1984) showed that some polyhedra with rr reflex edges need Ω(r2)\Omega(r^2) convex pieces, so an exact decomposition of a detailed mesh can be very large. Lien and Amato proposed approximate convex decomposition for polygons in 2004, with the journal version in 2006, and extended it to polyhedra in 2007. Mamou and Ghorbel (2009) gave a hierarchical method for meshes, and Wei, Liu, Ling and Su (2022) gave a method with a collision-aware concavity and a tree search over the cuts.

References

  1. Jyh-Ming Lien and Nancy M. Amato, Approximate convex decomposition of polygons, Computational Geometry 35(1-2), 2006, 100 to 123, the pockets and bridges of the convex hull, the concavity measures, and the resolution of the most concave notch
  2. Jyh-Ming Lien and Nancy M. Amato, Approximate convex decomposition of polyhedra, Proceedings of the 2007 ACM Symposium on Solid and Physical Modeling, 121 to 131, the extension of the method to polyhedra
  3. Bernard Chazelle, Convex partitions of polyhedra, a lower bound and worst-case optimal algorithm, SIAM Journal on Computing 13(3), 1984, 488 to 507, the quadratic lower bound on the number of convex pieces of a polyhedron
  4. Khaled Mamou and Faouzi Ghorbel, A simple and efficient approach for 3D mesh approximate convex decomposition, IEEE International Conference on Image Processing (ICIP 2009), 3501 to 3504, the hierarchical approximate convex decomposition of a mesh by the decimation of its dual graph
  5. Xinyue Wei, Minghua Liu, Zhan Ling and Hao Su, Approximate convex decomposition for 3D meshes with collision-aware concavity and tree search, ACM Transactions on Graphics 41(4), 2022, article 42, the collision-aware concavity, the cuts by planes, and the tree search over the cuts

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.cuts
  • 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