Algorithmcore
Boundary evaluation
Also called CSG to B-rep conversion.
Computes the B-rep of a CSG solid by intersecting the faces of the primitives, classifying the pieces against the tree and keeping those on the boundary.
- Time
- O(m^4) worst
- Space
- O(m^3) extra
- Where
- m = the number of faces of all primitives
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Aristides A. G. Requicha, Herbert B. Voelcker, 1985
Boundary evaluation turns a solid given by a CSG tree into a boundary representation. The boundary of the result lies on the faces of the primitives, so the algorithm generates candidates by cutting every face of every primitive along the surfaces of the other primitives, and then classifies each piece against the whole tree. A piece is kept when the solid lies on one side of it and not on the other, and it is oriented so that its normal points away from the solid. Requicha and Voelcker described this generate and classify scheme in 1985, with set membership classification as the classify step.
In plain words
A CSG solid is a recipe of boxes, cylinders and other basic shapes that are added, cut away or intersected. Its skin is made of parts of the skins of the basic shapes. Boundary evaluation finds which parts.
First it cuts each face of each shape into pieces, wherever another shape's surface crosses it. Then it looks at each piece from both sides. Just in front of the piece, is that point in the final solid? And just behind it? If the answers are the same, the piece is inside the solid or outside it, and it is thrown away. If they differ, the piece is part of the skin.
The kept pieces are turned to face out of the solid. Two shapes that share a flat face give the same piece twice, so one copy is dropped. The kept pieces, glued at their edges, form the boundary model.
The problem
The input is a CSG tree whose leaves are primitives and whose inner nodes are , and . The output is a boundary representation of the solid of the tree: a set of oriented faces whose union is , with disjoint relative interiors, each face ordered counterclockwise around the normal that points out of (the right-hand rule). This is solid Boolean operations with CSG input. On this page the primitives are bounded convex polyhedra with nonempty interior, the faces are convex polygons, and the adjacency between faces is left to the B-rep structure.
The algorithm
BOUNDARY-EVALUATION(T)- 1
K ← empty list - 2
for each primitive P_i of T and each face f of P_i, with outward normal n do - 3
Q ← [f] - 4
for each plane π of each primitive P_j with j ≠ i do - 5
replace each polygon of Q that π cuts by its two parts - 6
for each piece g in Q do - 7
c ← the mean of the vertices of g ▷ a point inside g - 8
if c is on the boundary of some P_j with j < i then skip g - 9
front ← T at c + εn, back ← T at c − εn ▷ ε > 0 infinitely small - 10
if back and not front then append g to K - 11
else if front and not back then append g, reversed, to K - 12
return K
Line L9 evaluates the plain Boolean formula of the tree with the truth value of each leaf at the point just in front of or just behind it. A half-space contains for all small when , or when and . The pair (front, back) is the neighborhood of the face point in the sense of Requicha and Voelcker: the two half-balls on the two sides of the face. The classes in, on and out alone cannot decide a piece in the plane of a face of another primitive, and the neighborhood can.
Line L8 removes copies. Two primitives with coplanar faces give the same piece twice, once from each face, and the copy from the primitive of least index is the one that stays. The front and back of both copies agree, up to a swap when the normals are opposite, so either copy gives the same oriented face.
All signs are tests of a point against a plane, which is the orientation test in three dimensions. With integer or rational input, the cut points of line L5 are rational and every sign is exact.
Example
Let and be two cubes that overlap in the unit cube , and let the solid be , a cube of edge with a corner removed. The top face of , with , is cut by the planes and of into four unit squares. The face of , with , is cut by the planes and of into four unit squares. The other planes of the two cubes miss these faces or are parallel to them.
| piece | center | front | back | action |
|---|---|---|---|---|
| top of , | out of : false | in , out of : true | keep | |
| top of , | out of : false | in and : false | drop | |
| of , | in , out of : true | in and : false | keep, reversed | |
| of , | out of : false | out of : false | drop |
The third row is a face of the subtracted cube. Its normal points into the material of , so it is reversed to , which points into the removed corner. In all, gives squares (four on each far face and three on each near face) and gives the squares of that face . The kept squares enclose the volume , computed from them by the divergence theorem. The same pieces with other front and back rules give squares and volume for , and squares and volume for .
Touching cubes show the coplanar case. For and , the face of has front in and back in . For both are true and the face is dropped, which leaves the outer squares of a box of volume . For both are false, and the result is empty: the shared face is not a solid.
Correctness
The boundary of the solid lies on the boundaries of the primitives, so it is covered by the faces and hence by the pieces. After line L5, no plane of another primitive crosses the inside of a piece, so on each side of a piece every primitive is all or nothing, and the regularized solid is all or nothing as well by fact 7 of the regularized set operations. So a piece is on the boundary exactly when front and back differ, and the side where the value is true is the side of the solid. Two pieces in one plane from two primitives are cells of the same arrangement, so they are equal or meet only at their edges, and line L8 keeps one copy. The full proof gives the lemmas and the orientation.
Proof: Generate and classify returns the oriented boundary of the solidfull
Let be a CSG tree with leaves , in the order of the leaves, and inner nodes , and . Each is a bounded convex polyhedron with nonempty interior. Let be the solid of , and let be the finite set of all planes with in some . Write for the plain Boolean formula of , so that is computed from the truth values of the leaves. A piece is a polygon in the list after line L5.
Lemma 1 (pieces are cells). Let be a piece of a face of , in the plane . No plane of meets the relative interior unless it contains . So is the closure of a cell of the arrangement that the planes of cut in , restricted to .
Proof. A plane of some with was used at line L5. After the cut by , every part lies in one closed side of , and later cuts keep this. So either , in which case , or lies in one open side of . A plane of other than supports the convex set , so it meets only on the relative boundary of , and so it misses .
Lemma 2 (the side tests). Let with unit normal of out of , and . There is a ball around cut by into two open half-balls (the side of ) and . Each contains or misses it, and SIDE-MEMBER at line L9 returns which. Hence if of the side tests is true, and otherwise. The same holds with replaced by any point , with the same answers.
Proof. By Lemma 1, the only planes of through are copies of . Take so small that it meets no other plane of . For a half-space with or , the sign holds on all of . For a half-space with , the plane is , so is a nonzero multiple of and . This is negative on exactly when . These are the tests of SIDE-MEMBER, and on every inequality of holds strictly or one fails everywhere. So or . On the open set each leaf is all or nothing, so the plain formula is all or nothing with the value of . By fact 7 of the regularized set operations, and the plain set differ only on the union of the boundaries of the , which misses , and is closed, so the claim holds. For another point , the signs are the same as at : they are nonzero and constant on the connected set for the planes that miss it, and zero for the copies of .
So each piece has two values: front on and back on , the same at every point of .
Lemma 3 (boundary points). A point lies on if and only if front back. If back is true and front is false, lies on the side of near , and if front is true and back is false, it lies on the side of .
Proof. Near , by Lemma 2, is the closure of , , both or neither, intersected with . These four cases give the whole ball, the empty set, or a closed half-ball. Only a half-ball has on its boundary.
Lemma 4 (copies). Let be a piece of a face of with on the boundary of , . Then the face of through lies in the plane of , and among the pieces of there is one with the same point set as .
Proof. The point lies on a plane of , which by Lemma 1 is . So is in the face of in . By Lemma 1 applied to both faces, the pieces of and of are the closures of the cells of one arrangement, the trace of on : the planes of do not cut , and those of do not cut . The cell through is in both lists.
Theorem. The polygons returned at line L12 have pairwise disjoint relative interiors, their union is , and each one is ordered counterclockwise around the normal that points out of .
Proof. Cover. The boundary of lies in the union of the boundaries of the (fact 7 again: off that union, is locally all or nothing). Each boundary point of is in a face , which is the union of its pieces. So lies in the union of all pieces. Let be in the relative interior of a piece . By Lemma 3, has front back. If is skipped at line L8, its center lies on the boundary of some with . Take the least such . By Lemma 4, has a copy of , whose center is the same point and lies on no boundary of with , so the copy is not skipped. It has the same front and back, or both swapped when the normals are opposite. So the point set is kept at line L10 or L11. It remains to cover the points of on the set , the union of the relative boundaries of all pieces, which is a finite union of segments. Let and let be a ball around . Then is connected, because a finite union of segments does not separate a ball. It meets , because and has no interior, and it meets the open complement of for the same reason. So meets . Hence is a limit of points of , which lie in kept polygons, and the union of the kept polygons is closed, so it contains .
Only boundary. A kept polygon has front back, so by Lemma 3 its relative interior lies in , and so does its closure.
Disjoint. Two pieces of the same face are distinct cells of one arrangement. Two pieces in different planes: one of them, say , was cut by the plane of the other, or both lie in faces of one convex , which meet only along edges. In both cases misses the other piece. Two pieces in one plane from different primitives are equal or have disjoint relative interiors by Lemma 4, and line L8 keeps one copy of each point set.
Orientation. The faces of are counterclockwise around their outward normal . Line L10 keeps when is on the side of , so points out of . Line L11 keeps the reversed list when is on the side of , and the reversed order is counterclockwise around , which points out of .
Termination. Each loop runs over finite lists. Line L5 replaces a polygon by at most two polygons, and the number of planes is finite.
Degenerate input. Coplanar faces, touching primitives and faces that meet along edges are part of the input. They need no special case: Lemma 1 holds for them, the side tests use only signs computed exactly, and line L8 removes the copies of coplanar pieces. The proof needs the signs to be exact. With rounded arithmetic, Lemma 1 can fail for a piece that a plane only nearly misses.
Complexity
The costs are in the real RAM, with exact arithmetic on rational coordinates.
- Generate. The planes cut a face as an arrangement of at most lines in the plane of the face (line arrangement), which has cells of total size . Cutting all current pieces by one more plane costs their total size, so one face costs and all faces cost .
- Classify. There are pieces, and lines L8 and L9 test the center of each against all half-spaces, for .
- Space. One face holds pieces at a time, and the output can have pieces.
The bound is far from tight for real models, where most planes miss most faces. A practical version cuts a face only by the primitives whose bounding boxes meet it (axis-aligned bounding box) and merges coplanar kept pieces into one face.
Properties
- Exact. With rational input, every vertex is a rational point and every decision is an exact sign, so the output is the exact boundary.
- Degenerate input needs no special case. Coplanar faces, touching primitives and faces that meet along an edge are handled by the side tests and by line L8.
- Not merged. The output is a set of convex polygons. Neighboring coplanar pieces are not joined, and the faces may meet edge to edge or at T-junctions.
- Local. Each piece is classified on its own, so the pieces can be processed in parallel.
Variants and improvements
- Active zones. Rossignac and Voelcker defined the active zone of a primitive: the region where a change of the primitive changes the solid. A face piece outside the active zone of its primitive cannot be on the boundary, so it needs no classification, and the zone also detects redundant primitives.
- Merging. Instead of evaluating the whole tree at once, the B-rep is built incrementally: the B-rep of the left subtree is combined with the next primitive by one Boolean operation on B-reps. That operation is vertex neighborhood classification or another B-rep Boolean algorithm.
- Curved primitives. With quadrics or spline surfaces, line L5 cuts a face along an intersection curve, which needs surface surface intersection, and the side tests use the surface normal.
- Meshes. For triangle meshes the same generate and classify idea works on the arrangement of the triangles (mesh arrangements, mesh Boolean operations), with a winding number as the classifier.
When to use it
Use boundary evaluation when a CSG model must be shown or used as faces and edges: for machining, meshing, drawing many times, or computing mass properties by surface integrals. For one picture, a volume estimate or a point test, CSG ray casting and set membership classification need no boundary at all. When the input is already two B-reps, a B-rep Boolean algorithm works on them directly.
Pitfalls
- Classifying the center only. A piece in the plane of a face of another primitive is on that primitive for its center, so in, on and out cannot say whether it stays. In the touching cubes the shared face is on both primitives, and only the front and back values show that it is inside the union and outside the intersection.
- Keeping both coplanar copies. Without line L8, the faces of for contain the face twice, once from each box. The volume by the divergence theorem is then wrong, and a B-rep built from the list is not a manifold.
- Forgetting to reverse. Faces that come from a subtracted primitive must be reversed at line L11. Without this, every cut face of a difference has its normal into the solid.
- Rounded cut points. In floating point, a cut point of line L5 is rounded, and a later plane may then cut a piece that it only touches. The pieces of two faces no longer match along their common edge, and the side test of a thin piece can give the wrong sign. Use exact or filtered predicates; see the geometric robustness problem and exact geometric computation.
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/boundary-evaluation/. The authors are listed in prov/G7ANN6.jsonl.
"""Boundary evaluation of a CSG solid by generate and classify, with exact arithmetic.
A primitive is a bounded convex polyhedron with nonempty interior, given as a
list of half-spaces (a, b) that mean a . x <= b. An inner node of the tree is
a tuple (op, left, right) with op in "union", "intersection" and "difference",
and the operations are the regularized ones. Coordinates are int or Fraction.
The result is a list of planar convex polygons, each a list of 3D points in
counterclockwise order seen from outside the solid (the right-hand rule gives
the outward normal). The polygons cover the boundary of the solid, and their
relative interiors are disjoint. Coplanar neighbors are not merged into one
face, and no adjacency is built: that is the job of a B-rep structure.
"""
from fractions import Fraction
from functools import cmp_to_key
from typing import Union
Num = Union[int, Fraction]
Vec = tuple
HalfSpace = tuple
Polygon = list
OPS = {
"union": lambda a, b: a or b,
"intersection": lambda a, b: a and b,
"difference": lambda a, b: a and not b,
}
def dot(a: Vec, b: Vec) -> Num:
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 sub(a: Vec, b: Vec) -> Vec:
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def is_node(tree) -> bool:
return isinstance(tree, tuple) and len(tree) == 3 and isinstance(tree[0], str)
def primitives(tree) -> list:
"""The leaves of the tree, left to right. Their positions are the primitive indices."""
return primitives(tree[1]) + primitives(tree[2]) if is_node(tree) else [tree]
def _solve3(p: HalfSpace, q: HalfSpace, r: HalfSpace):
"""The common point of three planes, or None if they do not meet in one point (Cramer)."""
(a1, b1), (a2, b2), (a3, b3) = p, q, r
c23 = cross(a2, a3)
det = dot(a1, c23)
if det == 0:
return None
c31, c12 = cross(a3, a1), cross(a1, a2)
return tuple(Fraction(b1 * c23[k] + b2 * c31[k] + b3 * c12[k]) / det for k in range(3))
def _same_plane(p: HalfSpace, q: HalfSpace) -> bool:
(a, b), (c, e) = p, q
return cross(a, c) == (0, 0, 0) and dot(a, c) > 0 and b * dot(c, c) == e * dot(a, c)
def convex_faces(prim: list) -> list:
"""The faces of a convex polyhedron as (polygon, outward normal), counterclockwise from outside."""
faces = []
for i, (a, b) in enumerate(prim):
if any(_same_plane((a, b), prim[j]) for j in range(i)):
continue
pts = set()
others = [h for j, h in enumerate(prim) if j != i]
for j in range(len(others)):
for k in range(j + 1, len(others)):
x = _solve3((a, b), others[j], others[k])
if x is not None and all(dot(c, x) <= e for c, e in prim):
pts.add(x)
if len(pts) < 3:
continue
poly = _sort_ccw(list(pts), a)
if _area_vector(poly) != (0, 0, 0):
faces.append((poly, a))
return faces
def _sort_ccw(pts: list, n: Vec) -> list:
"""Sort coplanar points of a convex polygon counterclockwise around the normal n."""
m = len(pts)
c = tuple(sum(p[k] for p in pts) / Fraction(m) for k in range(3))
u = sub(pts[0], c)
v = cross(n, u)
def half(p):
w = sub(p, c)
y, x = dot(w, v), dot(w, u)
return 0 if (y > 0 or (y == 0 and x > 0)) else 1
def cmp(p, q):
hp, hq = half(p), half(q)
if hp != hq:
return hp - hq
s = dot(cross(sub(p, c), sub(q, c)), n)
return -1 if s > 0 else (1 if s < 0 else 0)
return sorted(pts, key=cmp_to_key(cmp))
def _area_vector(poly: Polygon) -> Vec:
"""Twice the vector area of a planar polygon (Newell)."""
s = (0, 0, 0)
for k in range(len(poly)):
p, q = poly[k], poly[(k + 1) % len(poly)]
s = tuple(s[t] + w for t, w in enumerate(cross(p, q)))
return s
def split(poly: Polygon, a: Vec, b: Num) -> list:
"""Cut a convex polygon by the plane a . x = b. Returns the parts of positive area (one or two)."""
vals = [dot(a, p) - b for p in poly]
if all(v >= 0 for v in vals) or all(v <= 0 for v in vals):
return [poly]
lo, hi = [], []
for k in range(len(poly)):
p, q = poly[k], poly[(k + 1) % len(poly)]
vp, vq = vals[k], vals[(k + 1) % len(poly)]
if vp <= 0:
lo.append(p)
if vp >= 0:
hi.append(p)
if (vp < 0 < vq) or (vq < 0 < vp):
t = Fraction(vp) / (vp - vq)
x = tuple(p[i] + t * (q[i] - p[i]) for i in range(3))
lo.append(x)
hi.append(x)
return [part for part in (lo, hi) if len(part) >= 3]
def side_member(prim: list, c: Vec, n: Vec, s: int) -> bool:
"""Is c + s*eps*n inside the primitive, for every small enough eps > 0?"""
for a, b in prim:
v = dot(a, c) - b
if v > 0 or (v == 0 and s * dot(a, n) >= 0):
return False
return True
def on_boundary(prim: list, c: Vec) -> bool:
vals = [dot(a, c) - b for a, b in prim]
return all(v <= 0 for v in vals) and any(v == 0 for v in vals)
def evaluate(tree, leaf_value) -> bool:
"""The Boolean formula of the tree, with leaf_value(k) for the k-th primitive."""
counter = [0]
def go(t):
if not is_node(t):
counter[0] += 1
return leaf_value(counter[0] - 1)
op, l, r = t
x = go(l)
y = go(r)
return OPS[op](x, y)
return go(tree)
def boundary_evaluation(tree) -> list:
"""The oriented boundary polygons of the regularized solid of a CSG tree."""
prims = primitives(tree)
K = [] # @line L1
for i, P in enumerate(prims): # @line L2
for f, n in convex_faces(P):
Q = [f] # @line L3
for j, Pj in enumerate(prims): # @line L4
if j == i:
continue
for a, b in Pj:
Q = [part for g in Q for part in split(g, a, b)] # @line L5
for g in Q: # @line L6
c = tuple(sum(p[k] for p in g) / Fraction(len(g)) for k in range(3)) # @line L7
if any(on_boundary(prims[j], c) for j in range(i)): # @line L8
continue # a coplanar copy, kept from the primitive of least index
front = evaluate(tree, lambda k: side_member(prims[k], c, n, +1)) # @line L9
back = evaluate(tree, lambda k: side_member(prims[k], c, n, -1))
if back and not front: # @line L10
K.append(g)
elif front and not back: # @line L11
K.append(g[::-1])
return K # @line L12
def volume(faces: list) -> Fraction:
"""The volume enclosed by closed oriented polygons, by the divergence theorem."""
six_v = Fraction(0)
for poly in faces:
for k in range(1, len(poly) - 1):
six_v += dot(poly[0], cross(poly[k], poly[k + 1]))
return six_v / 6
def box(x0: Num, y0: Num, z0: Num, x1: Num, y1: Num, z1: Num) -> list:
"""The box [x0, x1] x [y0, y1] x [z0, z1] as six half-spaces."""
return [((1, 0, 0), x1), ((-1, 0, 0), -x0), ((0, 1, 0), y1), ((0, -1, 0), -y0),
((0, 0, 1), z1), ((0, 0, -1), -z0)]
test_boundary_evaluation.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-evaluation/. The authors are listed in prov/G7ANN6.jsonl.
import random
import unittest
from collections import Counter
from fractions import Fraction
from boundary_evaluation import box, boundary_evaluation, volume
F = Fraction
def dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def cross(a, b):
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 is_node(t):
return isinstance(t, tuple) and len(t) == 3 and isinstance(t[0], str)
# ---- brute force: inclusion and exclusion over convex intersections ----
def clip(poly, a, b):
"""Keep the part of a convex polygon with a . x <= b (Sutherland and Hodgman)."""
out = []
for k in range(len(poly)):
p, q = poly[k], poly[(k + 1) % len(poly)]
vp, vq = dot(a, p) - b, dot(a, q) - b
if vp <= 0:
out.append(p)
if (vp < 0 < vq) or (vq < 0 < vp):
t = F(vp) / (vp - vq)
out.append(tuple(p[i] + t * (q[i] - p[i]) for i in range(3)))
return out
def convex_volume(halfspaces, R=1000):
"""Volume of {x : a . x <= b for all (a, b)}: clip a large square in each plane, then sum tetrahedra."""
six_v = F(0)
for i, (a, b) in enumerate(halfspaces):
e = (1, 0, 0) if a[1] != 0 or a[2] != 0 else (0, 1, 0)
u = cross(a, e)
v = cross(a, u)
p0 = tuple(F(b * a[k], dot(a, a)) for k in range(3))
poly = [tuple(p0[k] + sx * R * u[k] + sy * R * v[k] for k in range(3))
for sx, sy in ((1, 1), (-1, 1), (-1, -1), (1, -1))]
if dot(cross(u, v), a) < 0:
poly.reverse()
for j, (c, d) in enumerate(halfspaces):
if j != i and poly:
# a plane met twice is kept once: drop the copy with the larger index
if cross(a, c) == (0, 0, 0) and dot(a, c) > 0 and b * dot(c, c) == d * dot(a, c):
if j < i:
poly = []
continue
poly = clip(poly, c, d)
for k in range(1, len(poly) - 1):
six_v += dot(poly[0], cross(poly[k], poly[k + 1]))
return six_v / 6
def indicator(tree, counter):
"""The indicator of the plain formula as a polynomial: {frozenset of leaves: coefficient}."""
if not is_node(tree):
counter[0] += 1
return {frozenset([counter[0] - 1]): 1}
op, l, r = tree
p, q = indicator(l, counter), indicator(r, counter)
pq = Counter()
for s, x in p.items():
for t, y in q.items():
pq[s | t] += x * y
res = Counter()
if op == "union":
res.update(p), res.update(q), res.subtract(pq)
elif op == "intersection":
res.update(pq)
else:
res.update(p), res.subtract(pq)
return {s: x for s, x in res.items() if x}
def leaves(tree):
return leaves(tree[1]) + leaves(tree[2]) if is_node(tree) else [tree]
def brute_volume(tree):
prims = leaves(tree)
poly = indicator(tree, [0])
return sum(x * convex_volume([h for k in s for h in prims[k]]) for s, x in poly.items())
# ---- checks on the output surface ----
def area_vector_sum(faces):
s = [0, 0, 0]
for poly in faces:
for k in range(len(poly)):
c = cross(poly[k], poly[(k + 1) % len(poly)])
for t in range(3):
s[t] += c[t]
return tuple(s)
def edges_cancel(faces):
"""Every directed edge, cut at the output vertices on it, has an opposite copy."""
verts = {p for poly in faces for p in poly}
count = Counter()
for poly in faces:
for k in range(len(poly)):
p, q = poly[k], poly[(k + 1) % len(poly)]
d = tuple(q[i] - p[i] for i in range(3))
dd = dot(d, d)
inner = []
for w in verts:
e = tuple(w[i] - p[i] for i in range(3))
if cross(d, e) == (0, 0, 0):
t = F(dot(d, e)) / dd
if 0 < t < 1:
inner.append((t, w))
chain = [p] + [w for _, w in sorted(inner)] + [q]
for x, y in zip(chain, chain[1:]):
count[(x, y)] += 1
return all(count[(x, y)] == count[(y, x)] for (x, y) in count)
def random_primitive(rng):
lo = [rng.randint(0, 2) for _ in range(3)]
hi = [x + rng.randint(1, 3) for x in lo]
prim = box(*lo, *hi)
center = [F(lo[i] + hi[i], 2) for i in range(3)]
if rng.random() < 0.5:
a = tuple(rng.choice([-1, 1]) * rng.randint(0, 1) for _ in range(2)) + (rng.choice([-1, 1]),)
prim.append((a, dot(a, center) + rng.randint(0, 1))) # a cut that keeps the center
return prim
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.3:
return random_primitive(rng)
op = rng.choice(["union", "intersection", "difference"])
return (op, random_tree(rng, depth - 1), random_tree(rng, depth - 1))
A = box(0, 0, 0, 2, 2, 2)
B = box(1, 1, 1, 3, 3, 3)
class TestBoundaryEvaluation(unittest.TestCase):
def test_worked_example(self):
for op, vol, nfaces in (("union", 15, 42), ("intersection", 1, 6), ("difference", 7, 24)):
faces = boundary_evaluation((op, A, B))
self.assertEqual(volume(faces), vol)
self.assertEqual(len(faces), nfaces)
self.assertEqual(area_vector_sum(faces), (0, 0, 0))
self.assertTrue(edges_cancel(faces))
def test_touching_and_coplanar(self):
C = box(1, 0, 0, 2, 1, 1)
D = box(0, 0, 0, 1, 1, 1)
self.assertEqual(boundary_evaluation(("intersection", D, C)), [])
self.assertEqual(volume(boundary_evaluation(("union", D, C))), 2)
self.assertEqual(len(boundary_evaluation(("union", D, C))), 10)
E = box(1, 0, 0, 2, 2, 2) # shares three faces with A, same orientation
self.assertEqual(volume(boundary_evaluation(("difference", A, E))), 4)
self.assertEqual(volume(boundary_evaluation(("union", A, E))), 8)
self.assertEqual(boundary_evaluation(("difference", E, A)), [])
def test_random_against_inclusion_exclusion(self):
rng = random.Random(1985)
nonempty = 0
for _ in range(70):
tree = random_tree(rng, 2)
faces = boundary_evaluation(tree)
self.assertEqual(volume(faces), brute_volume(tree))
self.assertEqual(area_vector_sum(faces), (0, 0, 0))
self.assertTrue(edges_cancel(faces))
nonempty += bool(faces)
self.assertGreater(nonempty, 35)
if __name__ == "__main__":
unittest.main()
History
Requicha's survey of 1980 described the conversion from a CSG representation to a boundary representation as one of the basic algorithms of a solid modeler. Tilove's set membership classification of the same year gave the classify step. Requicha and Voelcker published the generate and classify algorithms for boundary evaluation and merging in 1985, and Rossignac and Voelcker's active zones of 1989 cut the number of classifications.
References
- Aristides A. G. Requicha and Herbert B. Voelcker, Boolean operations in solid modeling, boundary evaluation and merging algorithms, Proceedings of the IEEE 73(1), 30 to 44, 1985, the whole paper (the generate and classify scheme, the candidate faces, the classification with neighborhoods, and the merging of a new primitive into a B-rep)
- Robert B. Tilove, Set membership classification, a unified approach to geometric intersection problems, IEEE Transactions on Computers C-29(10), 874 to 883, 1980, the classification of a face against a CSG tree, which is the classify step
- Jaroslaw R. Rossignac and Herbert B. Voelcker, Active zones in CSG for accelerating boundary evaluation, redundancy elimination, interference detection, and shading algorithms, ACM Transactions on Graphics 8(1), 51 to 87, 1989, the definition of the active zone of a primitive and its use to skip classifications in boundary evaluation
- Aristides A. G. Requicha, Representations for rigid solids, theory, methods, and systems, ACM Computing Surveys 12(4), 437 to 464, 1980, the sections on the conversion between representations, where boundary evaluation turns a CSG representation into a boundary representation
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 G7ANN6 Edit this page History Report an error Markdown