Algorithm Search⌘K

Algorithmadvanced

Minkowski sum of polyhedra

Also called polyhedral Minkowski sum.

Computes the Minkowski sum of two polyhedra; convex polytopes add face by face through support functions, and general polyhedra go through convex pieces, with up to O(n^3 m^3) output.

Time
O(n m (n + m)) worst
Space
O(n m) extra
Where
m = the number of vertices of Q; n = the number of vertices of P
Properties
deterministicexactiterative
Origin
Efi Fogel, Dan Halperin, 2007

The Minkowski sum of two solids PP and QQ is P⊕Q={p+q:p∈P,q∈Q}P \oplus Q = \{p + q : p \in P, q \in Q\}: the region that QQ covers when its reference point moves over all of PP. In solid modeling it grows a part by a tool shape, as in offsetting with a ball, gives the region a translating tool sweeps along a segment, and gives the configuration space obstacles for a robot that translates. The plane version is on the Minkowski sum page, with the merge for convex polygons. In three dimensions the convex case is still easy: the support functions add, so each face of the sum is the sum of a face of PP and a face of QQ with the same outer normal, and the sum of two convex polytopes has O(nm)O(nm) faces. The general case goes through a convex decomposition of both solids, the pairwise sums of the pieces and a union of up to quadratically many convex polytopes, and the result can have Θ(n3m3)\Theta(n^3 m^3) faces. This page gives the convex step exactly, with integer arithmetic.

In plain words

Take a box and a little pyramid. Put a copy of the pyramid at every point of the box. The result is a bigger convex shape.

Look at the result from any side. The part of it that sticks out furthest toward you is the part of the box that sticks out furthest that way, plus the part of the pyramid that sticks out furthest that way. Those parts can be a corner, an edge or a flat face. Two corners give a corner, a corner and a face give a copy of the face, and two edges that are not parallel give a flat four-sided face.

So the flat faces of the result come from three places: the faces of the box, the faces of the pyramid, and pairs of edges, one from each. The method lists all these candidates and keeps the ones that give a flat face.

The problem

Input. Two finite point sets PP and QQ in R3\mathbb{R}^3 with integer coordinates, each with a three-dimensional convex hull. We write PP and QQ also for the hulls, the convex polytopes. PP has nn points, QQ has mm.

Output. The facets of P⊕QP \oplus Q: for each facet, its outer normal uu as a primitive integer vector and the cycle of its vertices in counterclockwise order seen from outside.

Notation. For a direction u≠0u \neq 0, hK(u)=max⁡x∈Ku⋅xh_K(u) = \max_{x \in K} u \cdot x is the support function and F(K,u)={x∈K:u⋅x=hK(u)}F(K, u) = \{x \in K : u \cdot x = h_K(u)\} is the face of KK in direction uu. For a finite set, FF is the set of points that attain the maximum. A face is a facet if it spans a plane and an edge if it spans a line. The normal cone of a face GG is the set of uu with F(K,u)⊇GF(K, u) \supseteq G.

The key fact is the additivity of support functions and faces:

hP⊕Q(u)=hP(u)+hQ(u),F(P⊕Q,u)=F(P,u)⊕F(Q,u).h_{P \oplus Q}(u) = h_P(u) + h_Q(u), \qquad F(P \oplus Q, u) = F(P, u) \oplus F(Q, u).

The first equation is item 4 on the support function page. The second follows: u⋅(p+q)=hP(u)+hQ(u)u \cdot (p + q) = h_P(u) + h_Q(u) with u⋅p≤hP(u)u \cdot p \le h_P(u) and u⋅q≤hQ(u)u \cdot q \le h_Q(u) holds only if both are equalities. So the faces of the sum are sums of faces of the summands with a common normal, and a facet of the sum with normal uu comes from one of three cases: a facet of PP plus a face of QQ, a face of PP plus a facet of QQ, or an edge ee of PP plus an edge ff of QQ that are not parallel, with uu perpendicular to both, that is u=± e×fu = \pm\, e \times f.

The algorithm

  1. MINKOWSKI-SUM-CONVEX(P, Q)
  2. 1N ← the outer facet normals of P and of Q
  3. 2for each edge direction e of P and each edge direction f of Q do
  4. 3if e × f ≠ 0 then add e × f and −(e × f) to N, as primitive integer vectors
  5. 4S ← an empty map from normals to facets
  6. 5for each u in N do
  7. 6A ← F(P, u); B ← F(Q, u) ▷ two support queries
  8. 7if the points a + b, a ∈ A, b ∈ B, span a plane then
  9. 8S[u] ← the convex polygon of these points, counterclockwise seen from u
  10. 9return S

Line L1 needs the facets of PP and QQ. A B-rep gives them; for point sets, the code finds them by brute force over triples of points. The edges of line L2 come from the facets: if u1u_1 and u2u_2 are the normals of two adjacent facets, then F(P,u1+u2)F(P, u_1 + u_2) is their common edge. Line L3 adds both signs, since the cross product does not tell which side the facet is on; line L7 rejects the wrong sign and every pair whose Gauss arcs do not cross. The vertices of the sum are the vertices of its facets.

Fogel and Halperin do lines L2 to L7 in one pass: the Gaussian map of a convex polytope puts each facet normal as a point on the unit sphere, each edge as a great arc between the normals of its two facets, and each vertex as the spherical region of its normal cone. The Gaussian map of P⊕QP \oplus Q is the overlay of the two maps, so the edge pairs that give facets are exactly the pairs of arcs that cross, and a sweep over the sphere finds them without testing all EPEQE_P E_Q pairs.

Example

Let TT be the tetrahedron with corners (0,0,0),(1,0,0),(0,1,0),(0,0,1)(0,0,0), (1,0,0), (0,1,0), (0,0,1) and CC the unit cube [0,1]3[0,1]^3. Line L1 gives the 4 normals of TT and the 6 of CC. The three normals (−1,0,0)(-1,0,0), (0,−1,0)(0,-1,0) and (0,0,−1)(0,0,-1) are shared, so NN has 7 vectors so far. TT has 6 edge directions and CC has 3, which give 15 non-parallel pairs, and line L3 brings NN to 13 vectors. Lines L5 to L8 then do this:

uu F(T,u)F(T, u) F(C,u)F(C, u) sum spans result
(1,1,1)(1,1,1) facet x+y+z=1x + y + z = 1 vertex (1,1,1)(1,1,1) plane triangle
(−1,0,0)(-1,0,0), (0,−1,0)(0,-1,0), (0,0,−1)(0,0,-1) facet facet plane pentagon, 5 vertices each
(1,0,0)(1,0,0), (0,1,0)(0,1,0), (0,0,1)(0,0,1) vertex facet plane unit square, 4 vertices each
(1,1,0)(1,1,0), (1,0,1)(1,0,1), (0,1,1)(0,1,1) edge, such as (1,0,0)(0,1,0)(1,0,0)(0,1,0) edge, such as (1,1,0)(1,1,1)(1,1,0)(1,1,1) plane parallelogram
(−1,−1,0)(-1,-1,0), (−1,0,−1)(-1,0,-1), (0,−1,−1)(0,-1,-1) edge, such as (0,0,0)(0,0,1)(0,0,0)(0,0,1) the parallel edge (0,0,0)(0,0,1)(0,0,0)(0,0,1) line rejected

The sum has 1+3+3+3=101 + 3 + 3 + 3 = 10 facets and 13 vertices, so it has 21 edges, and 13−21+10=213 - 21 + 10 = 2 as Euler's formula requires. The pentagon on the plane x=0x = 0 has the vertices (0,0,0),(0,2,0),(0,2,1),(0,1,2),(0,0,2)(0,0,0), (0,2,0), (0,2,1), (0,1,2), (0,0,2). In the three rejected rows, an edge of TT is parallel to an edge of CC, and their sum is a longer edge of P⊕QP \oplus Q, not a facet.

Two more sums that the tests check: the tetrahedron TT plus its reflection −T-T gives a cuboctahedron, with 8 triangles, 6 squares and 12 vertices. The cube plus the octahedron with vertices ±ei\pm e_i gives 6 squares, 8 triangles and 12 rectangles, 26 facets and 24 vertices.

Correctness

The face identity above says that F(P⊕Q,u)=A⊕BF(P \oplus Q, u) = A \oplus B for the sets of line L6, so a candidate uu that passes line L7 is the normal of a facet of the sum, and line L8 records that facet. Conversely, let uu be the outer normal of a facet of the sum. The facet is A⊕BA \oplus B, whose span is the sum of the spans of AA and BB. If AA spans a plane, uu is the normal of a facet of PP, which is in NN by line L1; the same holds for BB. Otherwise each of AA and BB is a vertex or an edge, and their spans add up to a plane only if both are edges with directions ee and ff that are not parallel. Then uu is perpendicular to ee and ff, so it is a positive multiple of e×fe \times f or of −(e×f)-(e \times f), and line L3 added both. Every edge of PP is the intersection of two facets, so the edge directions of line L2 cover all edges. So SS is exactly the set of facets of the sum. The full proof is in the proof file.

The tests check that the vertices of the output attain hP(w)+hQ(w)h_P(w) + h_Q(w) for all 124 integer directions ww with entries in {−2,…,2}\{-2, \ldots, 2\} on 500 random pairs, and for all 728 directions with entries in {−4,…,4}\{-4, \ldots, 4\} on 60 larger pairs. They check that each facet is a supporting plane that touches exactly its listed vertices, in counterclockwise order, that V−E+F=2V - E + F = 2, and on 80 small pairs that the facets and vertices equal those of the convex hull of all nmnm vertex sums, found by brute force over triples.

Proof: The candidate normals and support faces give exactly the facets of the Minkowski sum of two convex polytopesfull

We use the pseudocode of the page. PP and QQ are convex polytopes in R3\mathbb{R}^3 with nonempty interior, given by finite point sets with integer coordinates. For u≠0u \neq 0, hK(u)=max⁡x∈Ku⋅xh_K(u) = \max_{x \in K} u \cdot x and F(K,u)={x∈K:u⋅x=hK(u)}F(K, u) = \{x \in K : u \cdot x = h_K(u)\}. Every face of a polytope is F(K,u)F(K, u) for some uu, and its dimension is the dimension of its affine hull. For a finite set SS we write F(S,u)F(S, u) for the points of SS that attain the maximum; then conv⁡F(S,u)=F(conv⁡S,u)\operatorname{conv} F(S, u) = F(\operatorname{conv} S, u), since a linear function attains its maximum over a polytope on the hull of the points of SS where it is maximal.

Lemma 1 (support functions and faces add). For nonempty compact convex sets KK and LL and every u≠0u \neq 0: hK⊕L(u)=hK(u)+hL(u)h_{K \oplus L}(u) = h_K(u) + h_L(u) and F(K⊕L,u)=F(K,u)⊕F(L,u)F(K \oplus L, u) = F(K, u) \oplus F(L, u).

Proof. For x∈Kx \in K and y∈Ly \in L, u⋅(x+y)=u⋅x+u⋅y≤hK(u)+hL(u)u \cdot (x + y) = u \cdot x + u \cdot y \le h_K(u) + h_L(u), with equality when xx and yy attain their maxima, so hK⊕L(u)=hK(u)+hL(u)h_{K \oplus L}(u) = h_K(u) + h_L(u). A point z∈K⊕Lz \in K \oplus L attains this value exactly when some, and then every, decomposition z=x+yz = x + y with x∈K,y∈Lx \in K, y \in L has u⋅x+u⋅y=hK(u)+hL(u)u \cdot x + u \cdot y = h_K(u) + h_L(u). Since each term is at most its maximum, both are equal to their maxima, so x∈F(K,u)x \in F(K, u) and y∈F(L,u)y \in F(L, u). Conversely, the sum of two such points attains the maximum. □\square

Lemma 2 (the dimension of a sum). For nonempty convex sets AA and BB, dim⁡(A⊕B)=dim⁡(lin⁡(A−A)+lin⁡(B−B))\dim (A \oplus B) = \dim(\operatorname{lin}(A - A) + \operatorname{lin}(B - B)), where lin⁡(A−A)\operatorname{lin}(A - A) is the linear space parallel to the affine hull of AA.

Proof. The affine hull of A⊕BA \oplus B is aff⁡A+aff⁡B\operatorname{aff} A + \operatorname{aff} B, a translate of lin⁡(A−A)+lin⁡(B−B)\operatorname{lin}(A - A) + \operatorname{lin}(B - B). □\square

Lemma 3 (edges from adjacent facets). Let u1u_1 and u2u_2 be the outer normals of two facets G1G_1 and G2G_2 of PP that share an edge gg. Then F(P,u1+u2)=gF(P, u_1 + u_2) = g. Every edge of PP arises this way from some pair of facet normals.

Proof. For x∈Px \in P, (u1+u2)⋅x≤hP(u1)+hP(u2)(u_1 + u_2) \cdot x \le h_P(u_1) + h_P(u_2), with equality exactly when x∈G1∩G2x \in G_1 \cap G_2. The bound is attained, since g⊆G1∩G2g \subseteq G_1 \cap G_2 is not empty, so F(P,u1+u2)=G1∩G2F(P, u_1 + u_2) = G_1 \cap G_2. Two distinct facets of a 3-polytope meet in a face of dimension at most 1, and here it contains gg, so it is gg. Every edge of a 3-polytope lies in exactly two facets. □\square

So the edge directions of line L2, found as the faces F(P,u1+u2)F(P, u_1 + u_2) of dimension 1 over all pairs of facet normals, are exactly the directions of the edges of PP, and likewise for QQ. A pair of facets that are not adjacent gives a vertex or nothing new, since its face F(P,u1+u2)F(P, u_1 + u_2) is a vertex or an edge in that case, and an edge found this way is still an edge of PP.

Lemma 4 (the normal of a facet). A facet GG of a polytope KK with nonempty interior has exactly one outer normal up to a positive factor: the uu with F(K,u)=GF(K, u) = G form the open ray of the outer normal of the plane of GG.

Proof. If F(K,u)=GF(K, u) = G, then uu is perpendicular to the plane of GG, since u⋅xu \cdot x is constant on GG and GG spans the plane, and uu points away from KK, since KK lies in {u⋅x≤hK(u)}\{u \cdot x \le h_K(u)\} and has points off the plane. □\square

Theorem. MINKOWSKI-SUM-CONVEX returns a map whose keys are exactly the primitive outer normals of the facets of P⊕QP \oplus Q, and whose value at uu is the vertex cycle of the facet F(P⊕Q,u)F(P \oplus Q, u).

Proof. (Soundness.) Let u∈Nu \in N pass line L7. By Lemma 1, applied to the hulls, and the remark on finite sets, conv⁡{a+b:a∈A,b∈B}=F(P,u)⊕F(Q,u)=F(P⊕Q,u)\operatorname{conv}\{a + b : a \in A, b \in B\} = F(P, u) \oplus F(Q, u) = F(P \oplus Q, u). This face spans a plane, so it is a facet, and line L8 stores the plane hull of the points, which is the facet. By Lemma 4 the facet has only the normal uu up to scaling, so no facet is stored twice under two keys.

(Completeness.) Let GG be a facet of P⊕QP \oplus Q with primitive outer normal uu, and let A′=F(P,u)A' = F(P, u) and B′=F(Q,u)B' = F(Q, u), so G=A′⊕B′G = A' \oplus B' by Lemma 1. By Lemma 2 the spaces of A′A' and B′B' add to a plane. If A′A' is a facet of PP, then by Lemma 4 uu is its primitive outer normal, which line L1 put in NN. The same holds if B′B' is a facet of QQ. Otherwise dim⁡A′≤1\dim A' \le 1 and dim⁡B′≤1\dim B' \le 1, and their spaces add to dimension 2 only if both are edges, with directions ee and ff that are not parallel. By Lemma 3 these directions are found in line L2. The vector uu is perpendicular to ee and to ff, since u⋅xu \cdot x is constant on each face, so uu is a nonzero multiple of e×fe \times f. Both primitive vectors on that line are added in line L3, so u∈Nu \in N. Line L7 accepts uu, since A⊕BA \oplus B spans the plane of GG by the soundness part.

(The cycle.) The plane hull in line L8 projects the points onto the coordinate plane that drops the coordinate where ∣uk∣|u_k| is largest. This projection is a bijection on the plane of the facet, since uk≠0u_k \neq 0, and it keeps or reverses orientation by the sign of uku_k, reversed once more for the middle axis since (x,z)(x, z) is a left-handed pair. The monotone chain gives the vertices of the projected hull in counterclockwise order, and the code reverses the list when the orientation is reversed, so the cycle is counterclockwise seen from the side uu points to.

(Termination.) NN is finite, at most FP+FQ+2EPEQF_P + F_Q + 2 E_P E_Q vectors, and each step of lines L5 to L8 does finitely many integer operations. □\square

Corollary (the vertices). The vertices of P⊕QP \oplus Q are the points that occur in the facet cycles. Each vertex vv of the sum is F(P⊕Q,u)F(P \oplus Q, u) for some uu, and a face of a 3-polytope that is a vertex lies in at least three facets, so it occurs in their cycles; conversely every point of a facet cycle is a vertex of that facet, so a vertex of the sum.

Corollary (the size). The sum has at most FP+FQ+2EPEQF_P + F_Q + 2 E_P E_Q facets, which is O(nm)O(nm) for summands with nn and mm vertices, since a 3-polytope with nn vertices has at most 3n−63n - 6 edges and 2n−42n - 4 facets. By Euler's formula, the numbers of vertices and edges of the sum are also O(nm)O(nm).

Complexity

  • The set NN has at most FP+FQ+2EPEQF_P + F_Q + 2 E_P E_Q vectors, where FF and EE count facets and edges. By Euler's formula a convex polytope with nn vertices has at most 3n−63n - 6 edges and 2n−42n - 4 facets, so ∣N∣=O(nm)|N| = O(nm).
  • Each candidate needs two support queries in O(n+m)O(n + m) time and a plane hull of ∣A∣⋅∣B∣|A| \cdot |B| points, so the total time is O((n+m)⋅nm)O((n + m) \cdot nm) in the worst case. The code adds the brute-force facet search on point sets, O(n4+m4)O(n^4 + m^4); a B-rep input avoids it.
  • The output has O(nm)O(nm) facets, and this is tight: for two prisms over regular kk-gons, one turned by a right angle, the arcs of the top and bottom edges of each prism cross Θ(k2)\Theta(k^2) arcs of the other. Fogel, Halperin and Weibel found the exact maximum number of facets of the sum of two convex polytopes; the conference version of their paper states it as 4mn−9m−9n+264mn - 9m - 9n + 26 for summands with mm and nn facets, and the tests check this bound on 300 random pairs.
  • With the Gaussian map overlay, the time is the time of a map overlay on the sphere, O((n+m+k)log⁡(n+m))O((n + m + k) \log (n + m)) for kk crossings by a plane sweep, which is near linear in the output.
  • For nonconvex polyhedra the output can have Θ(n3m3)\Theta(n^3 m^3) faces, so no method is better than that in the worst case.

Properties

  • Exact. Every quantity is an integer: the normals are cross products of integer vectors, and the faces are found by comparing integer dot products. No tolerance is needed, and degenerate inputs, such as parallel edges or coplanar faces, are handled by line L7 and not by special cases.
  • Output sensitive with the overlay. The plain version tests Θ(EPEQ)\Theta(E_P E_Q) pairs even when few of them cross; the Gaussian map overlay pays only for the crossings.
  • Symmetric. The output does not depend on the order of PP and QQ.
  • The sum of a polytope and a segment. If QQ is a segment, the sum is the region a translating PP sweeps, the extrusion case of the sweep representation for a convex profile.

Variants and improvements

  • Convex hull of vertex sums. The sum of two convex polytopes is the convex hull of the nmnm sums of vertices, which a 3D convex hull algorithm computes in O(nmlog⁡(nm))O(nm \log(nm)) time. It is short to code but does Θ(nm)\Theta(nm) work even when the sum has few faces.
  • Gaussian map overlay. Fogel and Halperin's method, with exact arithmetic in CGAL. They also used the sum P⊕(−Q)P \oplus (-Q) for collision detection and penetration depth.
  • Nonconvex polyhedra by decomposition. Decompose both polyhedra into convex pieces, add each pair of pieces with the convex method, and take the union of all pairwise sums. Hachenberger made this exact, with a decomposition into O(r2)O(r^2) pieces for rr reflex edges and the union computed with Nef polyhedra; this is the method of CGAL's 3D Minkowski sum. The union is the expensive step.
  • Convolution. As in the plane, a candidate surface is formed from facet and vertex pairs and from edge and edge pairs whose normals match, and the sum is the part of space where this surface has a positive winding number. It avoids the decomposition, but the arrangement of the candidate surface is hard to compute robustly in three dimensions.
  • Approximation. Voxel grids and distance fields give approximate sums with a bounded error, used when the inputs are meshes with many faces.
  • Minkowski difference. For convex PP and QQ, the set {x:x+Q⊆P}\{x : x + Q \subseteq P\} is the polytope cut out by the facet planes of PP, each moved inward by hQh_Q of its normal: x+Q⊆Px + Q \subseteq P exactly when u⋅x+hQ(u)≤hP(u)u \cdot x + h_Q(u) \le h_P(u) for every facet normal uu of PP.

When to use it

Use the convex method whenever both solids are convex, or when one is convex and the other is a union of a few convex pieces: tool shapes in machining, convex hulls of robot links, bounding shapes in collision tests. For questions that need only one direction at a time, such as distance and intersection tests between convex shapes, do not build the sum at all; GJK uses the support function of P⊕(−Q)P \oplus (-Q) directly. For offsets of a solid by a ball, the sum has spherical and cylindrical faces, and the dedicated offsetting methods are simpler. Use the decomposition method for general polyhedra only when an exact result matters, as in assembly planning, since its output and time can be very large.

Pitfalls

  • Only one sign of e×fe \times f. The cross product of two edge directions gives the line of the normal, not its side. Test both signs, as line L3 does.
  • Parallel edges. If e×f=0e \times f = 0, the edges add to a longer edge, not a facet. Skip the pair, or the code divides by zero when it normalizes the vector.
  • Floating-point normals. With floating-point coordinates, two nearly parallel facets of the sum can come out as two facets with a sliver between them, or a face can appear that does not exist. Use integer or rational coordinates and exact dot products, or merge normals with a tolerance and accept that the result is approximate.
  • Points that are not vertices. A face found by support queries can contain points of the input that are not vertices, for example the middle of an edge. Take the plane hull of the face, as line L8 does, instead of all points.
  • Nonconvex inputs. The face rule holds only for convex sets. For a nonconvex solid, the support face in a direction says nothing about the dents, so the convex method gives the convex hull of the sum, not the sum.

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.

minkowski_sum_of_polyhedra.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minkowski-sum-of-polyhedra/. The authors are listed in prov/EBNP81.jsonl.

"""The Minkowski sum of two convex polytopes in R^3, by support faces.

The facets of P + Q have the outer normals of the facets of P, the outer
normals of the facets of Q, and the normals e x f of pairs of non-parallel
edges e of P and f of Q whose Gauss arcs cross. For each candidate normal u
the face of the sum in direction u is F(P, u) + F(Q, u), so a candidate is
a facet exactly when that sum spans a plane. This is the step that the
Gaussian map overlay of Fogel and Halperin does in one sweep; here every
candidate is tested with the support function.

All arithmetic is on Python integers, so every sign is exact. The polytopes
are given as finite point sets with integer coordinates whose convex hull is
three-dimensional; points that are not vertices are allowed.

Cost: O(F_P + F_Q + E_P E_Q) candidates, each tested in O(n + m) time, where
n and m are the input sizes. Finding the facets and edges of the inputs from
point sets takes O(n^4) and O(m^4) time by brute force; a B-rep would give
them directly.
"""

from __future__ import annotations

from math import gcd
from typing import Iterable, Sequence

Vec = tuple[int, int, int]


def sub(a: Vec, b: Vec) -> Vec:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def add(a: Vec, b: Vec) -> Vec:
    return (a[0] + b[0], a[1] + b[1], a[2] + b[2])


def dot(a: Vec, b: Vec) -> int:
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


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


def primitive(u: Vec) -> Vec:
    g = gcd(gcd(abs(u[0]), abs(u[1])), abs(u[2]))
    return (u[0] // g, u[1] // g, u[2] // g)


def support(points: Sequence[Vec], u: Vec) -> int:
    """h(u) = max of u . x over the points."""
    return max(dot(u, p) for p in points)


def face(points: Sequence[Vec], u: Vec) -> list[Vec]:
    """F(P, u): the points of P that attain h_P(u)."""
    h = support(points, u)
    return [p for p in points if dot(u, p) == h]


def affine_dim(points: Sequence[Vec]) -> int:
    """The dimension of the affine hull of a nonempty point set."""
    o = points[0]
    vs = [sub(p, o) for p in points[1:] if p != o]
    if not vs:
        return 0
    a = vs[0]
    b = next((v for v in vs if cross(a, v) != (0, 0, 0)), None)
    if b is None:
        return 1
    n = cross(a, b)
    return 3 if any(dot(n, v) != 0 for v in vs) else 2


def facet_normals(points: Sequence[Vec]) -> set[Vec]:
    """The primitive outer normals of the facets of conv(points). O(n^4)."""
    pts = list(dict.fromkeys(points))
    out: set[Vec] = set()
    k = len(pts)
    for i in range(k):
        for j in range(i + 1, k):
            for l in range(j + 1, k):
                n = cross(sub(pts[j], pts[i]), sub(pts[l], pts[i]))
                if n == (0, 0, 0):
                    continue
                n = primitive(n)
                c = dot(n, pts[i])
                s = [dot(n, p) - c for p in pts]
                if all(v <= 0 for v in s):
                    out.add(n)
                elif all(v >= 0 for v in s):
                    out.add((-n[0], -n[1], -n[2]))
    return out


def edge_directions(points: Sequence[Vec], normals: Iterable[Vec]) -> list[Vec]:
    """The directions of the edges of conv(points): for two facet normals
    u1, u2 the face F(P, u1 + u2) is the common edge when the facets are
    adjacent. O(F^2 n)."""
    ns = list(normals)
    out: set[Vec] = set()
    for i in range(len(ns)):
        for j in range(i + 1, len(ns)):
            w = add(ns[i], ns[j])
            if w == (0, 0, 0):
                continue
            f = face(points, w)
            if affine_dim(f) == 1:
                a = min(f)
                b = max(f)
                out.add(primitive(sub(b, a)))
    return sorted(out)


def hull_2d_in_plane(points: Sequence[Vec], u: Vec) -> list[Vec]:
    """The vertices of the convex polygon conv(points), which lie in a plane
    with normal u, in counterclockwise order seen from the side u points to."""
    pts = sorted(set(points))
    # drop the coordinate where u is largest, project, take the hull
    k = max(range(3), key=lambda i: abs(u[i]))
    ax = [i for i in range(3) if i != k]

    def pr(p: Vec) -> tuple[int, int]:
        return (p[ax[0]], p[ax[1]])

    def turn(o: Vec, a: Vec, b: Vec) -> int:
        oo, aa, bb = pr(o), pr(a), pr(b)
        return (aa[0] - oo[0]) * (bb[1] - oo[1]) - (aa[1] - oo[1]) * (bb[0] - oo[0])

    pts.sort(key=pr)
    if len(pts) <= 2:
        return pts
    lower: list[Vec] = []
    for p in pts:
        while len(lower) >= 2 and turn(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    upper: list[Vec] = []
    for p in reversed(pts):
        while len(upper) >= 2 and turn(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    hull = lower[:-1] + upper[:-1]
    # the projection keeps orientation when u[k] > 0 for the cyclic axes
    sign = u[k] if k != 1 else -u[k]
    if sign < 0:
        hull.reverse()
    return hull


def minkowski_sum_convex(P: Sequence[Vec], Q: Sequence[Vec]) -> dict[Vec, list[Vec]]:
    """The facets of conv(P) + conv(Q): a map from each primitive outer
    normal to the vertex cycle of the facet. Precondition: both hulls are
    three-dimensional and all coordinates are integers."""
    fp, fq = facet_normals(P), facet_normals(Q)
    cand: set[Vec] = set(fp) | set(fq)  # @line L1
    for e in edge_directions(P, fp):  # @line L2
        for f in edge_directions(Q, fq):
            c = cross(e, f)
            if c != (0, 0, 0):
                c = primitive(c)  # @line L3
                cand.add(c)
                cand.add((-c[0], -c[1], -c[2]))
    facets: dict[Vec, list[Vec]] = {}  # @line L4
    for u in sorted(cand):  # @line L5
        a, b = face(P, u), face(Q, u)  # @line L6
        s = [add(x, y) for x in a for y in b]
        if affine_dim(s) == 2:  # @line L7
            facets[u] = hull_2d_in_plane(s, u)  # @line L8
    return facets  # @line L9


def vertices_of(facets: dict[Vec, list[Vec]]) -> set[Vec]:
    return {v for cyc in facets.values() for v in cyc}


def euler_characteristic(facets: dict[Vec, list[Vec]]) -> int:
    """V - E + F of the boundary given by the facet cycles."""
    edges = set()
    for cyc in facets.values():
        for i in range(len(cyc)):
            a, b = cyc[i], cyc[(i + 1) % len(cyc)]
            edges.add((min(a, b), max(a, b)))
    return len(vertices_of(facets)) - len(edges) + len(facets)
test_minkowski_sum_of_polyhedra.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minkowski-sum-of-polyhedra/. The authors are listed in prov/EBNP81.jsonl.

import itertools
import random
import unittest

from minkowski_sum_of_polyhedra import (affine_dim, cross, dot, euler_characteristic, facet_normals,
                                         minkowski_sum_convex, sub, support, vertices_of)

DIRS2 = [w for w in itertools.product(range(-2, 3), repeat=3) if w != (0, 0, 0)]
DIRS4 = [w for w in itertools.product(range(-4, 5), repeat=3) if w != (0, 0, 0)]


def random_body(rng, k_lo=4, k_hi=8, r=3):
    while True:
        k = rng.randrange(k_lo, k_hi + 1)
        pts = list({tuple(rng.randrange(-r, r + 1) for _ in range(3)) for _ in range(k)})
        if len(pts) >= 4 and affine_dim(pts) == 3:
            return pts


def rank(vs):
    vs = [v for v in vs if v != (0, 0, 0)]
    if not vs:
        return 0
    a = vs[0]
    b = next((v for v in vs if cross(a, v) != (0, 0, 0)), None)
    if b is None:
        return 1
    n = cross(a, b)
    return 3 if any(dot(n, v) != 0 for v in vs) else 2


class TestHandCases(unittest.TestCase):
    def test_tetrahedron_plus_its_reflection(self):
        t = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]
        s = minkowski_sum_convex(t, [(-a, -b, -c) for a, b, c in t])
        self.assertEqual(len(s), 14)                       # cuboctahedron
        self.assertEqual(sorted(len(c) for c in s.values()), [3] * 8 + [4] * 6)
        self.assertEqual(len(vertices_of(s)), 12)

    def test_cube_plus_octahedron(self):
        c = [(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)]
        o = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
        s = minkowski_sum_convex(c, o)
        self.assertEqual(len(s), 26)
        self.assertEqual(len(vertices_of(s)), 24)
        self.assertEqual(euler_characteristic(s), 2)

    def test_cube_plus_cube(self):
        c = [(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)]
        s = minkowski_sum_convex(c, c)
        self.assertEqual(len(s), 6)
        self.assertEqual(vertices_of(s), {(x, y, z) for x in (0, 2) for y in (0, 2) for z in (0, 2)})


class TestRandom(unittest.TestCase):
    def check_facets(self, P, Q, s):
        verts = vertices_of(s)
        for u, cyc in s.items():
            h = support(P, u) + support(Q, u)
            on = {v for v in verts if dot(u, v) == h}
            self.assertTrue(all(dot(u, v) <= h for v in verts))
            self.assertEqual(on, set(cyc))
            self.assertGreaterEqual(len(cyc), 3)
            for i in range(len(cyc)):
                a, b, c = cyc[i], cyc[(i + 1) % len(cyc)], cyc[(i + 2) % len(cyc)]
                n = cross(sub(b, a), sub(c, b))
                # a strict left turn seen from outside: n is a positive multiple of u
                self.assertEqual(cross(n, u), (0, 0, 0))
                self.assertGreater(dot(n, u), 0)

    def test_support_function_adds(self):
        rng = random.Random(1)
        for _ in range(500):
            P, Q = random_body(rng), random_body(rng)
            s = minkowski_sum_convex(P, Q)
            verts = vertices_of(s)
            for w in DIRS2:
                self.assertEqual(max(dot(w, v) for v in verts), support(P, w) + support(Q, w))
            self.check_facets(P, Q, s)
            self.assertEqual(euler_characteristic(s), 2)

    def test_support_function_many_directions(self):
        rng = random.Random(2)
        for _ in range(60):
            P, Q = random_body(rng, 6, 10, 5), random_body(rng, 6, 10, 5)
            s = minkowski_sum_convex(P, Q)
            verts = vertices_of(s)
            for w in DIRS4:
                self.assertEqual(max(dot(w, v) for v in verts), support(P, w) + support(Q, w))

    def test_against_hull_of_vertex_sums(self):
        """Brute force: the facets of the hull of all n m sums, by triples."""
        rng = random.Random(3)
        for _ in range(80):
            P, Q = random_body(rng, 4, 5), random_body(rng, 4, 5)
            s = minkowski_sum_convex(P, Q)
            sums = list({(p[0] + q[0], p[1] + q[1], p[2] + q[2]) for p in P for q in Q})
            normals = facet_normals(sums)
            self.assertEqual(set(s), normals)
            hs = {u: support(sums, u) for u in normals}
            want = {x for x in sums if rank([u for u in normals if dot(u, x) == hs[u]]) == 3}
            self.assertEqual(vertices_of(s), want)

    def test_facet_count_bound(self):
        """The facet bound 4 m n - 9 m - 9 n + 26 of Fogel, Halperin and
        Weibel for summands with m and n facets."""
        rng = random.Random(4)
        for _ in range(300):
            P, Q = random_body(rng), random_body(rng)
            m, n = len(facet_normals(P)), len(facet_normals(Q))
            self.assertLessEqual(len(minkowski_sum_convex(P, Q)), 4 * m * n - 9 * m - 9 * n + 26)


if __name__ == "__main__":
    unittest.main()

History

Minkowski defined the sum of convex bodies around 1900 in his work on convex bodies and mixed volumes, and the additivity of support functions was part of that theory. In robotics, Lozano-Pérez used sums of convex polygons and polyhedra for configuration space obstacles in the late 1970s and early 1980s, and in solid modeling, Rossignac and Requicha used sums with a ball to define offsets in 1986. Fogel and Halperin gave an exact and fast construction of the sum of convex polyhedra through Gaussian maps in 2007. Fogel, Halperin and Weibel settled the exact maximum number of facets of the sum of two convex polytopes in 2007 and 2009, and Hachenberger gave the first exact implementation for nonconvex polyhedra by decomposition and Nef polyhedra in 2007, published in 2009.

References

  1. Efi Fogel and Dan Halperin, Exact and efficient construction of Minkowski sums of convex polyhedra with applications, Computer-Aided Design 39(11), 929 to 940, 2007, the Gaussian map of a convex polyhedron, the overlay of two Gaussian maps as the Gaussian map of the sum, and the exact implementation
  2. Efi Fogel, Dan Halperin and Christophe Weibel, On the exact maximum complexity of Minkowski sums of polytopes, Discrete and Computational Geometry 42(4), 654 to 669, 2009, the tight bound on the number of facets of the sum of two convex polytopes in three dimensions (the conference version, SoCG 2007, states it as 4mn - 9m - 9n + 26 for summands with m and n facets)
  3. Peter Hachenberger, Exact Minkowksi sums of polyhedra and exact and efficient decomposition of polyhedra into convex pieces, Algorithmica 55(2), 329 to 345, 2009, the decomposition of nonconvex polyhedra into O(r^2) convex pieces, the pairwise sums and their union with Nef polyhedra (the word Minkowksi is spelled this way in the printed title)
  4. Rolf Schneider, Convex Bodies, The Brunn-Minkowski Theory, second edition, Cambridge University Press, 2014, Section 1.7 on support functions and their additivity, and Chapter 2 on faces and normal cones of convex bodies

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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