Algorithmadvanced
Vertex neighborhood classification
Also called Mantyla Boolean algorithm.
Mantyla's B-rep Boolean algorithm that intersects the two boundaries, classifies the neighbourhood of each new vertex by sectors and joins the kept faces with Euler operators.
- Time
- O(n^2 log n) worst
- Space
- O(n^2) extra
- Where
- n = the number of edges of the two boundaries
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Martti Mäntylä, 1986
Vertex neighborhood classification is Mäntylä's algorithm for Boolean operations on two solids given as boundary representations. It cuts the two boundaries along their intersection, so that the new vertices lie on both solids. At each such vertex it looks at the neighborhood: the sectors between the faces of one solid around the vertex, each classified as inside, outside or on the other solid. These local decisions settle every coincident case, such as two faces in one plane or a vertex on a face. The kept faces are then joined with Euler operators into a valid B-rep of the regularized result.
In plain words
Take two solids and their skins. Find every place where the two skins cross and cut both skins there. Now every part of one skin is inside the other solid, outside it, or lies exactly on it.
Most parts are easy: follow a skin from a part you know, and the answer stays the same until you reach a cut. The hard places are the cuts. There, look closely at a tiny ball around the cut point and ask, for each wedge of the ball, whether it is inside the other solid.
Then keep the parts that you need. For a union, keep the outside parts. For an intersection, keep the inside parts. For a difference, keep the first skin outside the second, and the second skin inside the first, turned around. Join the kept parts at the cuts.
The problem
The input is two solids and given by boundary representations of manifold solids and an operation among , and . The output is a boundary representation of , in the sense of the regularized set operations. This is solid Boolean operations with B-rep input. The code on this page solves the planar case: and are simple polygons with rational vertices, given counterclockwise, and the output is the set of boundary loops of the result with the region on the left of every edge.
The algorithm
The planar form has the four steps of Mäntylä's algorithm. In the plane, the neighborhood of a boundary vertex has two sectors, the inside one and the outside one, between its outgoing edge and its incoming edge.
BOOLEAN(A, B, op)- 1
split the edges of A where they meet the boundary of B, and the edges of B likewise - 2
classify every edge of A against B and every edge of B against A: - 3
if the edge is also an edge of the other loop then on-same or on-opposite - 4
else if its tail v is on the other boundary then in or out by the sector of the other polygon at v that holds it - 5
else the class of the previous edge of the loop ▷ a loop that never meets: point in polygon - 6
S ← the edges that the table SELECT keeps for op, the edges of B reversed for a difference - 7
return CONNECT(S) CONNECT(S)- 8
for each edge e of S that is in no loop yet do - 9
start a loop with e - 10
at the head of the current edge, go on with the edge of S that starts there and is first clockwise from the current edge - 11
stop when the loop is back at e
The table SELECT says which classes each operation keeps:
| operation | edges of | edges of |
|---|---|---|
| out, on-same | out | |
| in, on-same | in | |
| out, on-opposite | in, reversed |
An edge that lies on both boundaries is taken from only. When the two solids lie on the same side of a shared edge, it is on-same and stays for a union or an intersection. When they lie on opposite sides, it is on-opposite and stays only for a difference.
Line L4 is the vertex neighborhood test. Let be the direction of the outgoing edge of at and the direction from back along its incoming edge. The inside sector of at is the counterclockwise sweep from to , and the edge of is in when its direction falls in this sweep. The code compares angles with a rational pseudo-angle, so the test is exact.
The solid version. In three dimensions the steps are the same, with sectors between faces in place of sectors between edges:
- Generate. Intersect each edge of with the faces of and each edge of with the faces of . Split the edges at the intersection points, and record each new vertex as a vertex of one solid on a face of the other, or as a vertex of both.
- Classify. At a vertex on a face of the other solid, classify each sector of the vertex neighborhood as above, below or on the plane of that face. At a vertex of both solids, classify the pairs of sectors against each other. Reclassify the on sectors by the operation, with rules like the table above, and insert null edges between the in and out sectors.
- Connect. Join the null edges into loops, which become new null faces along the intersection curve.
- Finish. Cut each solid along its null faces, keep the pieces that the operation selects, and glue them along the null faces with Euler operators.
The planar code covers steps 1 to 3. It does not build the 3D B-rep or use Euler operators.
Example
Let be the square and the square . The boundary of crosses the edges of at and , so line L1 splits both loops there:
- :
- :
At the outgoing edge of points in the direction and its incoming edge goes back in the direction , so the inside sector of is the upper half-plane. The edge of from to points up, so it is in. The next edge, from to , starts at a vertex that is not on , so line L5 gives it the class in as well. At the inside sector of is the right half-plane, and the edge of toward points left, so it is out.
| loop | edges in | edges out |
|---|---|---|
| the other four | ||
| the other four |
For , SELECT keeps the four out edges of and the two in edges of reversed, . CONNECT joins them into one loop with six vertices, , the square with its upper right corner removed. Its area is . The union keeps the eight out edges, area , and the intersection keeps the four in edges, the unit square of area .
Touching squares show the on cases. The squares and share the segment . Each one has it as an edge, in opposite directions, so it is on-opposite: the union drops it and gives one loop around , and the intersection is empty. The squares and touch at the single vertex . Their union has two outgoing edges at that vertex, and line L10 picks the one that keeps each square in its own loop. The result is two loops that share a vertex, which is a non-manifold point of the result.
Correctness
After line L1, an edge of and an edge of are equal or meet only at end points. So the inside of each split edge is all in the other polygon, all out of it, or on it, and the neighborhood test at line L4 reads which sector of the other polygon holds the edge near its tail. A vertex that is not on the other boundary does not change the class, which justifies line L5. Near a point inside an edge, each polygon is a whole disk, an empty disk or a half-disk, and the table SELECT lists exactly the cases where the regularized result is a half-disk. At every vertex the kept edges alternate between incoming and outgoing around the vertex, so CONNECT closes the loops. The full proof shows that the winding number of the output is inside the result and outside.
Proof: Vertex neighborhood classification returns the boundary of the regularized resultfull
The proof is for the planar form of the algorithm on the page. Let and be simple polygons, each given as a counterclockwise loop, so that the polygon is on the left of each edge. Let for op in union, intersection and difference. All coordinates are rational and all signs are exact.
Lemma 1 (generate). After line L1, two edges, one of and one of , are equal as point sets or meet at most in common end points. Every point of is a vertex of both split loops or lies on a pair of equal edges.
Proof. If two original edges cross at one point, that point is a cut of both. If they overlap along a segment, the ends of the overlap are cuts of both. So after the cuts, a split edge of meets a split edge of only at an end of both, or the two edges have the same two ends and lie on one line, which makes them equal.
Lemma 2 (classify). Let be a split edge of with relative interior . Exactly one of these holds, and line L3, L4 or L5 returns it: (in), (out), is an edge of in the same direction (on-same), or in the opposite direction (on-opposite).
Proof. If is not an edge of , then by Lemma 1 the set misses . It is connected, so it lies in or outside . This is the dichotomy. Line L3 detects the two on cases. For line L4, let be on . By Lemma 1, is a vertex of the split loop of , with outgoing direction and the direction toward the previous vertex. Since is on the left of both of its edges at , a small disk around meets exactly in the open sector swept counterclockwise from to . The direction differs from both, since otherwise would overlap an edge of and, by Lemma 1, be equal to it. So the points of near are in exactly when is inside the sector, which is the test of line L4 with the pseudo-angle, a strictly increasing function of the angle. For line L5, the tail is not on , so a small disk around is inside or outside , and the previous edge, which ends at , has the same class. The walk starts at a vertex on , so every edge reached by line L5 follows an edge already classified. If no vertex of the loop is on , then by Lemma 1 the loop misses , so the whole loop is in or outside , and one point in polygon test decides it.
The same lemma holds for the edges of against .
Lemma 3 (select). Call the list of directed edges built at line L6. A point in the relative interior of a split edge lies on if and only if it lies on an edge of . Each such lies on exactly one edge of , and is on the left of that edge near .
Proof. Take for a split edge of , and a small disk around that meets no other split edge, except a copy of in . Then is the closed half-disk on the left of . By Lemma 2, is (in), (out), (on-same) or the closed half-disk on the right (on-opposite). The regularized result in for each case:
| class of | |||
|---|---|---|---|
| in | |||
| out | |||
| on-same | |||
| on-opposite |
For on-opposite, is the segment, whose regularization is empty, and is without the segment, whose regularization is . The point is on exactly in the cells with , and then is on the left of . These cells are the classes that the table SELECT keeps from . Now take for a split edge of that is not an edge of . Then is the half-disk on the left of , and is or . The result is or for the union, or for the intersection, and for the difference it is the closed half-disk on the right of when is in , and when is out of . These are the classes kept from , and for the difference the edge is reversed, which puts the result on its left. The on edges of are equal to edges of and are never kept from , so each boundary point is on one edge of only.
Lemma 4 (connect). At every vertex , the edges of that start at and those that end at alternate in angular order around , and there are as many of each. So the rule of line L10 is a bijection from the edges that end at to the edges that start at , and CONNECT splits into closed loops that use each edge once.
Proof. Let be the indicator of . Walk counterclockwise on a small circle around that meets only the split edges at . By Lemma 3, changes exactly where the circle crosses an edge of , and is on the left of that edge. An edge that starts at has its left side counterclockwise from it, so the walk enters there. An edge that ends at has its left side clockwise from it, so the walk leaves there. Since takes only the values and , entries and exits alternate around the circle, which gives the claim. Rotating clockwise from the direction of an incoming edge, the next edge met is an outgoing one, so line L10 picks the outgoing edge next to it in clockwise order, which is a bijection. A bijection at each vertex makes the successor map a permutation of , so each traced loop returns to its first edge.
Theorem. BOOLEAN returns loops whose union is , with on the left of every edge. For every point not on the loops, the winding number of the loops around is if and otherwise.
Proof. By Lemma 3, every point of in the relative interior of a split edge is on an edge of , and every edge of lies in . The rest of is a finite set of vertices, which are end points of edges of because has no isolated points for a regular closed set. By Lemma 4, the loops use exactly the edges of . For the winding number , both and are far away, both are constant off the edges of and off , and both jump by when a path crosses an edge of from its right to its left at a relative interior point, by Lemma 3. Any two points off the edges can be joined by a path that crosses edges only at such points, since the vertices are finite. So off the loops.
Termination. GENERATE and CLASSIFY loop over finite lists. Each step of CONNECT marks one new edge as used, so it ends after steps.
From the plane to space. In three dimensions, Lemma 2 becomes the classification of the sectors around a vertex: the cones between consecutive faces at that vertex, each in, out, or on a face of the other solid with the same or the opposite normal. Lemma 3 becomes the same table for the face pieces, and Lemma 4 becomes the step that joins the cut edges of the two solids into the new faces. The planar proof does not cover the Euler operator steps of the solid version.
Complexity
The costs are in the real RAM, for the planar code with edges in all.
- Generate. All pairs of edges are tested, , and there are cut points. Sorting the cuts along each edge costs in all.
- Classify. Each of the split edges costs one lookup and one sector test. With the vertices kept in a sorted table, this is .
- Connect. Each kept edge is chosen once, among the edges at its vertex.
So the time is and the space is . With a sweep that reports only the actual crossings, the generate step costs . For solids, generate tests edges against faces, and practical systems cut the work with bounding boxes.
Properties
- Local decisions. Each in, out or on answer comes from the sectors around one vertex, so coincident faces and edges need no global special case.
- Regularized. The table SELECT drops shared faces that the result does not bound, such as the face between two touching solids in a union.
- Exact when the signs are exact. All decisions are signs of orientation tests. With rational input they are exact, and the output is the exact boundary.
- The result may be non-manifold. Two solids that touch along an edge or at a vertex give a result whose boundary is not a 2-manifold there. A B-rep for 2-manifolds must split such a vertex or edge into copies.
Variants and improvements
- Polygon clipping. In the plane the same problem is polygon clipping. Vatti clipping uses a sweep instead of vertex neighborhoods and works on any number of polygons with holes.
- Robust set operations. Hoffmann, Hopcroft and Karasick worked in floating point and kept the topological decisions consistent with each other, so that a sign that cannot be trusted is derived from decisions already made.
- Meshes. For triangle meshes, mesh Boolean operations use the same generate and classify plan, with a winding number or a ray test as the classifier.
- Non-manifold structures. With a radial edge data structure, the result can keep the shared edges and vertices of touching solids instead of splitting them.
When to use it
Use it to combine two solids that are already B-reps, which is the usual case in a modeler that stores B-reps and applies one Boolean at a time. It fits faceted models with exact or filtered predicates. For a solid given as a CSG tree, boundary evaluation builds the B-rep from the whole tree at once. For triangle soups with self-intersections, use a mesh method.
Pitfalls
- Classifying by a sample point only. A test at the midpoint of an edge says on for both on-same and on-opposite. The decision needs the direction, which only the neighborhood gives. With the touching squares, a midpoint test cannot tell that the shared edge goes for a union and stays for a difference.
- Taking an on edge twice. If the shared edges are kept from both polygons, the output has a doubled edge and a loop that runs back along itself.
- The wrong exit at a touching vertex. At a vertex with two outgoing edges, taking the first one counterclockwise instead of clockwise joins the two touching squares into one loop that passes the vertex twice. The area and the winding numbers are still right, but the loop does not match the two faces that a B-rep needs, and a later Euler operator that splits the loop at the vertex is required.
- Inconsistent rounded signs. In floating point, the cut point of two edges may be classified differently from each of the two edges, and the loops then do not close. Compute the cut points and the signs exactly, or derive the uncertain signs from earlier ones as Hoffmann, Hopcroft and Karasick do. See the geometric robustness problem.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertex-neighborhood-classification/. The authors are listed in prov/QA5D08.jsonl.
"""Mantyla's Boolean operation by vertex neighborhood classification, in the plane.
This is the two-dimensional form of the algorithm. A solid is a simple polygon,
a list of points in counterclockwise order. Its boundary is a closed loop of
edges, and the neighborhood of a boundary vertex is a set of two sectors
between the incoming and the outgoing edge: the inside sector and the outside
sector. In three dimensions the sectors lie between the faces around a vertex,
and the same four steps apply: generate, classify, select, connect.
The result of boolean(A, B, op) is the boundary of the regularized set
A op* B, as a list of loops. Each loop is a list of points, the region is on
the left of every edge, so outer loops are counterclockwise and holes are
clockwise. Coordinates are int or Fraction, and every sign is exact.
"""
from fractions import Fraction
from typing import Union
Num = Union[int, Fraction]
Point = tuple
IN, OUT, ON_SAME, ON_OPPOSITE = "in", "out", "on-same", "on-opposite"
# Which edges each operation keeps: (classes kept from A, classes kept from B, B reversed?)
SELECT = {
"union": ({OUT, ON_SAME}, {OUT}, False),
"intersection": ({IN, ON_SAME}, {IN}, False),
"difference": ({OUT, ON_OPPOSITE}, {IN}, True),
}
def cross(o: Point, a: Point, b: Point) -> Num:
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def pseudo_angle(x: Num, y: Num) -> Fraction:
"""A rational number in [0, 4) that increases with the angle of (x, y)."""
if y >= 0 and x > 0 or (x == 0 and y > 0):
return Fraction(y) / (x + y)
if x <= 0 and y >= 0:
return 1 + Fraction(-x) / (-x + y)
if x < 0 or (x == 0 and y < 0):
return 2 + Fraction(-y) / (-x - y)
return 3 + Fraction(x) / (x - y)
def turn(d0: Point, d1: Point) -> Fraction:
"""The counterclockwise rotation from direction d0 to direction d1, in (0, 4] pseudo-angle units."""
r = (pseudo_angle(*d1) - pseudo_angle(*d0)) % 4
return r if r != 0 else Fraction(4)
def _on_segment(p: Point, a: Point, b: Point) -> bool:
return (cross(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 _meet(p: Point, q: Point, r: Point, s: Point) -> list:
"""The points where the segments pq and rs meet: none, one, or the two ends of an overlap."""
d1, d2, d3, d4 = cross(r, s, p), cross(r, s, q), cross(p, q, r), cross(p, q, s)
if d1 == d2 == 0: # collinear: the ends that lie on the other segment
return [x for x in (p, q, r, s) if _on_segment(x, p, q) and _on_segment(x, r, s)]
if (d1 > 0) == (d2 > 0) and d1 != 0 and d2 != 0:
return []
if (d3 > 0) == (d4 > 0) and d3 != 0 and d4 != 0:
return []
t = Fraction(d1) / (d1 - d2)
return [(p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1]))]
def generate(P: list, Q: list) -> list:
"""Split the edges of polygon P at every point where they meet the boundary of Q."""
out = []
n, m = len(P), len(Q)
for i in range(n):
p, q = P[i], P[(i + 1) % n]
cuts = set()
for j in range(m):
cuts.update(_meet(p, q, Q[j], Q[(j + 1) % m]))
d = (q[0] - p[0], q[1] - p[1])
key = lambda x: (x[0] - p[0]) * d[0] + (x[1] - p[1]) * d[1]
inner = sorted((x for x in cuts if x != p and x != q), key=key)
out.append(p)
out.extend(inner)
return out
def point_in_polygon(x: Point, P: list) -> bool:
"""Crossing number test for a point that is not on the boundary of P."""
inside = False
for i in range(len(P)):
a, b = P[i], P[(i + 1) % len(P)]
if (a[1] > x[1]) != (b[1] > x[1]):
if (cross(a, b, x) > 0) == (b[1] > a[1]):
inside = not inside
return inside
def classify(P: list, Q: list) -> list:
"""The class of each edge of the split loop P with respect to the split loop Q."""
n, m = len(P), len(Q)
edges_q = {(Q[j], Q[(j + 1) % m]) for j in range(m)}
where = {Q[j]: j for j in range(m)}
cls = [None] * n
starts = [i for i in range(n) if P[i] in where]
if not starts: # the loops do not meet: one containment test for the whole loop
mid = tuple((P[0][k] + P[1][k]) / Fraction(2) for k in range(2))
return [IN if point_in_polygon(mid, Q) else OUT] * n
for step in range(n):
i = (starts[0] + step) % n
u, w = P[i], P[(i + 1) % n]
if (u, w) in edges_q: # @line L3
cls[i] = ON_SAME
elif (w, u) in edges_q:
cls[i] = ON_OPPOSITE
elif u in where: # @line L4
j = where[u]
nxt, prv = Q[(j + 1) % m], Q[j - 1]
d_out = (nxt[0] - u[0], nxt[1] - u[1])
d_back = (prv[0] - u[0], prv[1] - u[1])
d = (w[0] - u[0], w[1] - u[1])
cls[i] = IN if turn(d_out, d) < turn(d_out, d_back) else OUT # the inside sector of Q at u
else:
cls[i] = cls[i - 1] # @line L5
return cls
def connect(edges: list) -> list:
"""Join directed edges into loops; at a vertex with two exits take the first one clockwise."""
out_of = {}
for e in edges:
out_of.setdefault(e[0], []).append(e)
used = set()
loops = []
for e in edges: # @line L8
if e in used:
continue
loop, cur = [e[0]], e # @line L9
used.add(e)
while True:
v = cur[1]
back = (cur[0][0] - v[0], cur[0][1] - v[1])
nxt = min(out_of[v], key=lambda f: turn((f[1][0] - v[0], f[1][1] - v[1]), back)) # @line L10
if nxt == e: # @line L11
break
if nxt in used:
raise ValueError("the selected edges do not form loops")
loop.append(v)
used.add(nxt)
cur = nxt
loops.append(loop)
return loops
def boolean(A: list, B: list, op: str) -> list:
"""The boundary loops of A op* B for counterclockwise simple polygons A and B."""
SA, SB = generate(A, B), generate(B, A) # @line L1
ca, cb = classify(SA, SB), classify(SB, SA) # @line L2
keep_a, keep_b, reverse_b = SELECT[op]
S = [(SA[i], SA[(i + 1) % len(SA)]) for i in range(len(SA)) if ca[i] in keep_a] # @line L6
for i in range(len(SB)):
if cb[i] in keep_b:
u, w = SB[i], SB[(i + 1) % len(SB)]
S.append((w, u) if reverse_b else (u, w))
return connect(S) # @line L7
def winding_number(x: Point, loops: list) -> int:
"""The winding number of the loops around a point that is on none of them."""
w = 0
for P in loops:
for i in range(len(P)):
a, b = P[i], P[(i + 1) % len(P)]
if a[1] <= x[1] < b[1] and cross(a, b, x) > 0:
w += 1
elif b[1] <= x[1] < a[1] and cross(a, b, x) < 0:
w -= 1
return w
def area(loops: list) -> Fraction:
"""The signed area of the region bounded by the loops (shoelace formula)."""
s = Fraction(0)
for P in loops:
for i in range(len(P)):
a, b = P[i], P[(i + 1) % len(P)]
s += a[0] * b[1] - a[1] * b[0]
return s / 2
test_vertex_neighborhood_classification.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertex-neighborhood-classification/. The authors are listed in prov/QA5D08.jsonl.
import random
import unittest
from fractions import Fraction
from vertex_neighborhood_classification import area, boolean, classify, generate, winding_number
F = Fraction
OPS = {
"union": lambda a, b: a or b,
"intersection": lambda a, b: a and b,
"difference": lambda a, b: a and not b,
}
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def inside(x, P):
"""Even-odd test for a point off the boundary, written apart from the module under test."""
c = 0
for i in range(len(P)):
a, b = P[i], P[(i + 1) % len(P)]
if (a[0] > x[0]) != (b[0] > x[0]):
y = a[1] + F(x[0] - a[0]) * (b[1] - a[1]) / (b[0] - a[0])
c += y > x[1]
return c % 2 == 1
def on_boundary(x, P):
for i in range(len(P)):
a, b = P[i], P[(i + 1) % len(P)]
if cross(a, b, x) == 0 and min(a[0], b[0]) <= x[0] <= max(a[0], b[0]) \
and min(a[1], b[1]) <= x[1] <= max(a[1], b[1]):
return True
return False
def slice_length(x, A, B, op):
"""Length of the vertical line at x inside A op B, by the plain formula at midpoints."""
ys = set()
for P in (A, B):
for i in range(len(P)):
a, b = P[i], P[(i + 1) % len(P)]
if a[0] != b[0] and min(a[0], b[0]) <= x <= max(a[0], b[0]):
ys.add(a[1] + F(x - a[0]) * (b[1] - a[1]) / (b[0] - a[0]))
ys = sorted(ys)
total = F(0)
for y0, y1 in zip(ys, ys[1:]):
m = (x, (y0 + y1) / 2)
if OPS[op](inside(m, A), inside(m, B)):
total += y1 - y0
return total
def brute_area(A, B, op):
"""Area of A op B: the slice length is linear between event abscissas, so midpoints are exact."""
xs = {p[0] for p in A + B}
for i in range(len(A)):
p, q = A[i], A[(i + 1) % len(A)]
for j in range(len(B)):
r, s = B[j], B[(j + 1) % len(B)]
d = (q[0] - p[0]) * (s[1] - r[1]) - (q[1] - p[1]) * (s[0] - r[0])
if d != 0:
t = F((r[0] - p[0]) * (s[1] - r[1]) - (r[1] - p[1]) * (s[0] - r[0])) / d
u = F((r[0] - p[0]) * (q[1] - p[1]) - (r[1] - p[1]) * (q[0] - p[0])) / d
if 0 <= t <= 1 and 0 <= u <= 1:
xs.add(p[0] + t * (q[0] - p[0]))
xs = sorted(xs)
return sum((x1 - x0) * slice_length((x0 + x1) / 2, A, B, op) for x0, x1 in zip(xs, xs[1:]))
DIRS = [(1, 0), (2, 1), (1, 1), (1, 2), (0, 1), (-1, 2), (-1, 1), (-2, 1),
(-1, 0), (-2, -1), (-1, -1), (-1, -2), (0, -1), (1, -2), (1, -1), (2, -1)] # by angle
def random_polygon(rng):
"""A star-shaped simple polygon around an integer center, counterclockwise."""
while True:
idx = sorted(rng.sample(range(16), rng.randint(3, 7)))
dirs = [DIRS[i] for i in idx]
if all(cross((0, 0), dirs[k], dirs[(k + 1) % len(dirs)]) > 0 for k in range(len(dirs))):
break
c = (rng.randint(2, 4), rng.randint(2, 4))
pts = []
for d in dirs:
r = rng.choice([1, 1, 2]) if max(abs(d[0]), abs(d[1])) == 1 else 1
pts.append((c[0] + r * d[0], c[1] + r * d[1]))
return pts
SQ1 = [(0, 0), (2, 0), (2, 2), (0, 2)]
SQ2 = [(1, 1), (3, 1), (3, 3), (1, 3)]
class TestVertexNeighborhoodClassification(unittest.TestCase):
def test_worked_example(self):
SA, SB = generate(SQ1, SQ2), generate(SQ2, SQ1)
self.assertEqual(SA, [(0, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2)])
self.assertEqual(SB, [(1, 1), (2, 1), (3, 1), (3, 3), (1, 3), (1, 2)])
self.assertEqual(classify(SA, SB), ["out", "out", "in", "in", "out", "out"])
self.assertEqual(classify(SB, SA), ["in", "out", "out", "out", "out", "in"])
self.assertEqual(area(boolean(SQ1, SQ2, "union")), 7)
self.assertEqual(area(boolean(SQ1, SQ2, "intersection")), 1)
self.assertEqual(area(boolean(SQ1, SQ2, "difference")), 3)
self.assertEqual(len(boolean(SQ1, SQ2, "difference")[0]), 6)
def test_touching_squares(self):
R = [(2, 0), (4, 0), (4, 2), (2, 2)] # shares the edge x = 2 with SQ1
self.assertEqual(classify(generate(SQ1, R), generate(R, SQ1))[1], "on-opposite")
self.assertEqual(boolean(SQ1, R, "intersection"), [])
self.assertEqual(area(boolean(SQ1, R, "union")), 8)
self.assertEqual(sorted(boolean(SQ1, R, "difference")[0]), sorted(SQ1))
C = [(2, 2), (4, 2), (4, 4), (2, 4)] # touches SQ1 at one corner
loops = boolean(SQ1, C, "union")
self.assertEqual(len(loops), 2)
self.assertEqual(area(loops), 8)
self.assertEqual(boolean(SQ1, C, "intersection"), [])
def test_same_and_nested(self):
self.assertEqual(area(boolean(SQ1, SQ1, "union")), 4)
self.assertEqual(boolean(SQ1, SQ1, "difference"), [])
inner = [(F(1, 2), F(1, 2)), (F(3, 2), F(1, 2)), (F(3, 2), F(3, 2)), (F(1, 2), F(3, 2))]
loops = boolean(SQ1, inner, "difference")
self.assertEqual(len(loops), 2) # an outer loop and a clockwise hole
self.assertEqual(sorted(area([lp]) for lp in loops), [-1, 4])
def test_random_against_point_membership_and_area(self):
rng = random.Random(1986)
grid = [(F(i, 4), F(j, 4)) for i in range(-1, 30, 3) for j in range(-1, 30, 3)]
degenerate = 0
for _ in range(150):
A, B = random_polygon(rng), random_polygon(rng)
degenerate += any(on_boundary(p, B) for p in A)
for op in OPS:
loops = boolean(A, B, op)
self.assertEqual(area(loops), brute_area(A, B, op))
for x in grid:
if on_boundary(x, A) or on_boundary(x, B):
continue
w = winding_number(x, loops)
self.assertEqual(w, int(OPS[op](inside(x, A), inside(x, B))))
self.assertGreater(degenerate, 20)
if __name__ == "__main__":
unittest.main()
History
Mäntylä published vertex neighborhood classification in 1986 for 2-manifold boundary models, and his book of 1988 treats Boolean operations on half-edge models. Requicha and Voelcker's merging algorithms of 1985 combined a B-rep with a new primitive by classification with neighborhoods, and Hoffmann, Hopcroft and Karasick turned to the consistency of the decisions in floating point in 1989.
References
- Martti Mäntylä, Boolean operations of 2-manifolds through vertex neighborhood classification, ACM Transactions on Graphics 5(1), 1 to 29, 1986, the whole paper (the generate, classify and connect steps, the vertex neighborhoods and their sectors, and the reclassification of the on sectors for each operation)
- Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, the chapter on Boolean set operations for the half-edge data structure (chapter number not confirmed)
- Christoph M. Hoffmann, Geometric and Solid Modeling, An Introduction, Morgan Kaufmann, 1989, Chapter 3, Boolean operations on boundary representations
- Christoph M. Hoffmann, John E. Hopcroft and Michael S. Karasick, Robust set operations on polyhedral solids, IEEE Computer Graphics and Applications 9(6), 50 to 59, 1989, the whole paper (set operations on polyhedra in floating point that keep the topological decisions consistent)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QA5D08 Edit this page History Report an error Markdown