Algorithm Search⌘K

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
Properties
deterministicofflineiterative
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 P0,…,PL−1P_0, \ldots, P_{L-1} are primitives and whose inner nodes are ∪∗\cup^*, ∩∗\cap^* and −∗-^*. The output is a boundary representation of the solid XX of the tree: a set of oriented faces whose union is ∂X\partial X, with disjoint relative interiors, each face ordered counterclockwise around the normal that points out of XX (the right-hand rule). This is solid Boolean operations with CSG input. On this page the primitives are bounded convex polyhedra Pi={x:a⋅x≤b for (a,b)∈Hi}P_i = \{x : a \cdot x \le b \text{ for } (a, b) \in H_i\} with nonempty interior, the faces are convex polygons, and the adjacency between faces is left to the B-rep structure.

The algorithm

  1. BOUNDARY-EVALUATION(T)
  2. 1K ← empty list
  3. 2for each primitive P_i of T and each face f of P_i, with outward normal n do
  4. 3Q ← [f]
  5. 4for each plane π of each primitive P_j with j ≠ i do
  6. 5replace each polygon of Q that π cuts by its two parts
  7. 6for each piece g in Q do
  8. 7c ← the mean of the vertices of g ▷ a point inside g
  9. 8if c is on the boundary of some P_j with j < i then skip g
  10. 9front ← T at c + εn, back ← T at c − εn ▷ ε > 0 infinitely small
  11. 10if back and not front then append g to K
  12. 11else if front and not back then append g, reversed, to K
  13. 12return 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 cc or just behind it. A half-space a⋅x≤ba \cdot x \le b contains c+sεnc + s \varepsilon n for all small ε>0\varepsilon > 0 when a⋅c<ba \cdot c < b, or when a⋅c=ba \cdot c = b and s (a⋅n)<0s \, (a \cdot n) < 0. The pair (front, back) is the neighborhood of the face point cc 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 A=[0,2]3A = [0, 2]^3 and B=[1,3]3B = [1, 3]^3 be two cubes that overlap in the unit cube [1,2]3[1, 2]^3, and let the solid be A−∗BA -^* B, a cube of edge 22 with a corner removed. The top face z=2z = 2 of AA, with n=(0,0,1)n = (0, 0, 1), is cut by the planes x=1x = 1 and y=1y = 1 of BB into four unit squares. The face x=1x = 1 of BB, with n=(−1,0,0)n = (-1, 0, 0), is cut by the planes y=2y = 2 and z=2z = 2 of AA into four unit squares. The other planes of the two cubes miss these faces or are parallel to them.

piece center cc front back action
top of AA, [0,1]×[0,1][0, 1] \times [0, 1] (1/2,1/2,2)(1/2, 1/2, 2) out of AA: false in AA, out of BB: true keep
top of AA, [1,2]×[1,2][1, 2] \times [1, 2] (3/2,3/2,2)(3/2, 3/2, 2) out of AA: false in AA and BB: false drop
x=1x = 1 of BB, y,z∈[1,2]y, z \in [1, 2] (1,3/2,3/2)(1, 3/2, 3/2) in AA, out of BB: true in AA and BB: false keep, reversed
x=1x = 1 of BB, y,z∈[2,3]y, z \in [2, 3] (1,5/2,5/2)(1, 5/2, 5/2) out of AA: false out of AA: false drop

The third row is a face of the subtracted cube. Its normal (−1,0,0)(-1, 0, 0) points into the material of A−∗BA -^* B, so it is reversed to (1,0,0)(1, 0, 0), which points into the removed corner. In all, AA gives 2121 squares (four on each far face and three on each near face) and BB gives the 33 squares of [1,2]3[1, 2]^3 that face AA. The 2424 kept squares enclose the volume 8−1=78 - 1 = 7, computed from them by the divergence theorem. The same pieces with other front and back rules give 4242 squares and volume 1515 for A∪∗BA \cup^* B, and 66 squares and volume 11 for A∩∗BA \cap^* B.

Touching cubes show the coplanar case. For D=[0,1]3D = [0, 1]^3 and C=[1,2]×[0,1]2C = [1, 2] \times [0, 1]^2, the face x=1x = 1 of DD has front in CC and back in DD. For D∪∗CD \cup^* C both are true and the face is dropped, which leaves the 1010 outer squares of a box of volume 22. For D∩∗CD \cap^* C 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 TT be a CSG tree with leaves P0,…,PL−1P_0, \ldots, P_{L-1}, in the order of the leaves, and inner nodes ∪∗\cup^*, ∩∗\cap^* and −∗-^*. Each Pi={x:a⋅x≤b for (a,b)∈Hi}P_i = \{x : a \cdot x \le b \text{ for } (a, b) \in H_i\} is a bounded convex polyhedron with nonempty interior. Let XX be the solid of TT, and let Π\Pi be the finite set of all planes a⋅x=ba \cdot x = b with (a,b)(a, b) in some HiH_i. Write Φ\Phi for the plain Boolean formula of TT, so that Φ(χ0,…,χL−1)\Phi(\chi_0, \ldots, \chi_{L-1}) is computed from the truth values of the leaves. A piece is a polygon in the list QQ after line L5.

Lemma 1 (pieces are cells). Let gg be a piece of a face ff of PiP_i, in the plane πf\pi_f. No plane of Π\Pi meets the relative interior ri⁡g\operatorname{ri} g unless it contains πf\pi_f. So gg is the closure of a cell of the arrangement that the planes of Π\Pi cut in πf\pi_f, restricted to ff.

Proof. A plane σ\sigma of some PjP_j with j≠ij \ne i was used at line L5. After the cut by σ\sigma, every part lies in one closed side of σ\sigma, and later cuts keep this. So either g⊆σg \subseteq \sigma, in which case σ=πf\sigma = \pi_f, or ri⁡g\operatorname{ri} g lies in one open side of σ\sigma. A plane σ\sigma of PiP_i other than πf\pi_f supports the convex set PiP_i, so it meets f⊆Pif \subseteq P_i only on the relative boundary of ff, and so it misses ri⁡g\operatorname{ri} g. □\square

Lemma 2 (the side tests). Let c∈ri⁡gc \in \operatorname{ri} g with unit normal nn of πf\pi_f out of PiP_i, and s=±1s = \pm 1. There is a ball UU around cc cut by πf\pi_f into two open half-balls U+U^+ (the side of nn) and U−U^-. Each PjP_j contains UsU^s or misses it, and SIDE-MEMBER(Pj,c,n,s)(P_j, c, n, s) at line L9 returns which. Hence X⊇UsX \supseteq U^s if Φ\Phi of the side tests is true, and X∩Us=∅X \cap U^s = \emptyset otherwise. The same holds with cc replaced by any point q∈ri⁡gq \in \operatorname{ri} g, with the same answers.

Proof. By Lemma 1, the only planes of Π\Pi through cc are copies of πf\pi_f. Take UU so small that it meets no other plane of Π\Pi. For a half-space with a⋅c<ba \cdot c < b or a⋅c>ba \cdot c > b, the sign holds on all of UU. For a half-space with a⋅c=ba \cdot c = b, the plane is πf\pi_f, so aa is a nonzero multiple of nn and a⋅(c+tn)−b=t (a⋅n)a \cdot (c + t n) - b = t \, (a \cdot n). This is negative on UsU^s exactly when s (a⋅n)<0s \, (a \cdot n) < 0. These are the tests of SIDE-MEMBER, and on UsU^s every inequality of PjP_j holds strictly or one fails everywhere. So Pj⊇UsP_j \supseteq U^s or Pj∩Us=∅P_j \cap U^s = \emptyset. On the open set UsU^s each leaf is all or nothing, so the plain formula is all or nothing with the value of Φ\Phi. By fact 7 of the regularized set operations, XX and the plain set differ only on the union of the boundaries of the PjP_j, which misses UsU^s, and XX is closed, so the claim holds. For another point q∈ri⁡gq \in \operatorname{ri} g, the signs a⋅q−ba \cdot q - b are the same as at cc: they are nonzero and constant on the connected set ri⁡g\operatorname{ri} g for the planes that miss it, and zero for the copies of πf\pi_f. □\square

So each piece gg has two values: front =Φ= \Phi on U+U^+ and back =Φ= \Phi on U−U^-, the same at every point of ri⁡g\operatorname{ri} g.

Lemma 3 (boundary points). A point q∈ri⁡gq \in \operatorname{ri} g lies on ∂X\partial X if and only if front ≠\ne back. If back is true and front is false, XX lies on the side of −n-n near qq, and if front is true and back is false, it lies on the side of nn.

Proof. Near qq, by Lemma 2, XX is the closure of U+U^+, U−U^-, both or neither, intersected with UU. These four cases give the whole ball, the empty set, or a closed half-ball. Only a half-ball has qq on its boundary. □\square

Lemma 4 (copies). Let gg be a piece of a face of PiP_i with c∈ri⁡gc \in \operatorname{ri} g on the boundary of PjP_j, j≠ij \ne i. Then the face f′f' of PjP_j through cc lies in the plane of gg, and among the pieces of f′f' there is one with the same point set as gg.

Proof. The point cc lies on a plane of PjP_j, which by Lemma 1 is πf\pi_f. So cc is in the face f′f' of PjP_j in πf\pi_f. By Lemma 1 applied to both faces, the pieces of ff and of f′f' are the closures of the cells of one arrangement, the trace of Π\Pi on πf\pi_f: the planes of PiP_i do not cut ri⁡f\operatorname{ri} f, and those of PjP_j do not cut ri⁡f′\operatorname{ri} f'. The cell through cc is in both lists. □\square

Theorem. The polygons returned at line L12 have pairwise disjoint relative interiors, their union is ∂X\partial X, and each one is ordered counterclockwise around the normal that points out of XX.

Proof. Cover. The boundary of XX lies in the union of the boundaries of the PjP_j (fact 7 again: off that union, XX is locally all or nothing). Each boundary point of PiP_i is in a face ff, which is the union of its pieces. So ∂X\partial X lies in the union of all pieces. Let q∈∂Xq \in \partial X be in the relative interior of a piece gg. By Lemma 3, gg has front ≠\ne back. If gg is skipped at line L8, its center lies on the boundary of some PjP_j with j<ij < i. Take the least such jj. By Lemma 4, PjP_j has a copy of gg, whose center is the same point and lies on no boundary of PkP_k with k<jk < j, 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 ∂X\partial X on the set SS, the union of the relative boundaries of all pieces, which is a finite union of segments. Let p∈∂Xp \in \partial X and let UU be a ball around pp. Then U∖SU \setminus S is connected, because a finite union of segments does not separate a ball. It meets int⁡X\operatorname{int} X, because p∈cl⁡(int⁡X)p \in \operatorname{cl}(\operatorname{int} X) and SS has no interior, and it meets the open complement of XX for the same reason. So U∖SU \setminus S meets ∂X\partial X. Hence pp is a limit of points of ∂X∖S\partial X \setminus S, which lie in kept polygons, and the union of the kept polygons is closed, so it contains pp.

Only boundary. A kept polygon has front ≠\ne back, so by Lemma 3 its relative interior lies in ∂X\partial X, 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 gg, was cut by the plane of the other, or both lie in faces of one convex PiP_i, which meet only along edges. In both cases ri⁡g\operatorname{ri} g 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 PiP_i are counterclockwise around their outward normal nn. Line L10 keeps gg when XX is on the side of −n-n, so nn points out of XX. Line L11 keeps the reversed list when XX is on the side of nn, and the reversed order is counterclockwise around −n-n, which points out of XX. ■\blacksquare

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 mm planes cut a face as an arrangement of at most mm lines in the plane of the face (line arrangement), which has O(m2)O(m^2) cells of total size O(m2)O(m^2). Cutting all current pieces by one more plane costs their total size, so one face costs O(m3)O(m^3) and all faces cost O(m4)O(m^4).
  • Classify. There are O(m3)O(m^3) pieces, and lines L8 and L9 test the center of each against all mm half-spaces, for O(m4)O(m^4).
  • Space. One face holds O(m2)O(m^2) pieces at a time, and the output can have O(m3)O(m^3) 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 A∪∗EA \cup^* E for E=[1,2]×[0,2]2E = [1, 2] \times [0, 2]^2 contain the face x=2x = 2 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.

boundary_evaluation.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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
  4. 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.

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