Algorithm Search⌘K

Algorithmadvanced

Rossignac-Requicha offsetting

Also called constant radius offsetting of CSG.

Grows a solid by r as the union of the solid with its faces, edges and vertices swept by r, shrinks it by the dual rule, and rounds or fillets by composing the two.

Time
O(m^3) worst
Space
O(m^2) extra
Where
m = the number of boxes in the CSG tree of the planar version; t = the number of swept primitives that hold a query point on their boundary
Properties
deterministicexactiterative
Origin
Jaroslaw R. Rossignac, Aristides A. G. Requicha, 1986

Rossignac and Requicha's method grows a solid SS by a distance rr without computing any offset surface. It uses the identity S↑r=S∪(∂S)↑rS \uparrow r = S \cup (\partial S) \uparrow r, and splits the boundary into its faces, edges and vertices, whose offsets are simple solids: a slab for a planar face, a cylinder for a straight edge and a ball for a vertex. The grown solid is therefore a union of known primitives, a CSG tree that a modeler can classify and display at once. Shrinking is growing the complement, and rounding and filleting are a shrink followed by a grow and the reverse. Rossignac and Requicha gave the method in 1986, as part of their definition of solid offsetting.

In plain words

To coat a solid with a layer of thickness rr, you do not need to move every face and then repair the gaps and overlaps. Instead, take the solid, and add to it a thick plate around every face, a round rod around every edge and a ball around every corner, all of thickness rr. Where these pieces overlap does not matter: the coated solid is simply everything they cover together.

Shrinking works the other way round. A point stays in the shrunk solid when it is inside the solid and not inside any plate, rod or ball.

The only hard question is at the edge of the result, where you must decide whether a point is inside or exactly on the skin. There the method looks at all the pieces that touch the point and checks whether they close up around it.

The problem

The input is a solid SS as a CSG tree and a distance r>0r > 0. The output is a representation of the grown solid S↑r={x:dist⁡(x,S)≤r}S \uparrow r = \{x : \operatorname{dist}(x, S) \le r\} and of the regularized shrunk solid cl⁡(int⁡(S↓r))\operatorname{cl}(\operatorname{int}(S \downarrow r)), with S↓r={x:x+Br⊆S}S \downarrow r = \{x : x + B_r \subseteq S\}, as defined on the solid offsetting page. Here the output is a point membership classification, a function that returns in, on or out for each query point, which is the form a CSG system uses to render, to compute mass properties and to evaluate a boundary. The implementation treats the planar case: SS is a CSG tree of closed axis-aligned rectangles with rational corners, the faces of SS are its boundary segments, and the edge and vertex offsets are rectangles and disks. Touching parts, holes that close exactly and walls of width exactly 2r2r are allowed inputs.

The algorithm

  1. GROW(S, r)
  2. 1E, V ← the boundary edges and vertices of S ▷ boundary evaluation
  3. 2T ← the union with the one member S
  4. 3for each edge e in E do add SLAB(e, r) to T ▷ e swept by r on both sides
  5. 4for each vertex p in V do add DISK(p, r) to T
  6. 5return T
  7. CLASSIFY(T, x)
  8. 6if x is in the interior of S or of a swept member then return in
  9. 7if x is in no member then return out
  10. 8if the members with x on their boundary cover a neighborhood of x then return in
  11. 9return on
  12. SHRINK-CLASSIFY(S, r, x)
  13. 10if x is not in S then return out
  14. 11c ← CLASSIFY of x against the swept members of GROW(S, r) alone
  15. 12return in, on or out when c is out, on or in

In three dimensions, line L3 adds the offset of each face, which for a planar face is the prism swept by the face along its normal by rr on both sides; edges give cylinders of radius rr and vertices give balls of radius rr. The faces of a B-rep are oriented by the right-hand rule so that their normals point out of the solid, but the swept members are symmetric, so the method needs no orientation. For curved faces the face offset is the region between the two offset surfaces at ±r\pm r, which is no longer a primitive of a simple CSG system; this is the main limit of the method.

Line L1 is a boundary evaluation. For a tree of rectangles it is exact and short: the distinct xx and yy coordinates of the rectangles cut the plane into a grid, the center of each cell is classified against the tree with the regularized set operations, and the boundary is the set of grid edges between a cell inside and a cell outside, merged into maximal segments. The vertices are the ends of these segments.

Line L8 is a neighborhood classification, as in vertex neighborhood classification. A rectangle with xx on its boundary covers a closed cone of directions at xx: a half plane on a side, a quadrant at a corner. A disk with xx on its circle and center cc covers only the open half plane of directions vv with v⋅(c−x)>0v \cdot (c - x) > 0; along its tangent it misses a thin cusp. The test sorts the axis directions and the tangent directions of the disks by angle, and checks every open sector between two of them, every one of these directions, and the two thin germs on either side of each direction. A germ on the side of a tangent is covered only by a rectangle whose cone holds the whole germ, or by another disk that holds the tangent direction strictly.

Lines L10 to L12 use the dual rule. The swept members of SS and of the closure of its complement are the same, since the two sets have the same boundary, so a point of SS is in the interior of the shrunk solid exactly when it is in no swept member.

Example

Let SS be the L shape [0,2]×[0,1]∪[0,1]×[0,2][0, 2] \times [0, 1] \cup [0, 1] \times [0, 2], the union of two rectangles. Line L1 finds six boundary edges, from (0,0)(0, 0) to (2,0)(2, 0), (2,0)(2, 0) to (2,1)(2, 1), (1,1)(1, 1) to (2,1)(2, 1), (1,1)(1, 1) to (1,2)(1, 2), (0,2)(0, 2) to (1,2)(1, 2) and (0,0)(0, 0) to (0,2)(0, 2), and six vertices, of which (1,1)(1, 1) is the reflex corner. For r=1/2r = 1/2, lines L3 and L4 add six rectangles and six disks; for example the edge from (1,1)(1, 1) to (2,1)(2, 1) gives the rectangle [1,2]×[1/2,3/2][1, 2] \times [1/2, 3/2].

query point members that hold it result of CLASSIFY
(5/2,1/2)(5/2, 1/2) the boundary of the slab [3/2,5/2]×[0,1][3/2, 5/2] \times [0, 1] of the right edge on, at L9: the slab covers only the half plane to the left
(23/10,−2/5)(23/10, -2/5) the circle of the disk at (2,0)(2, 0), since (3/10)2+(4/10)2=1/4(3/10)^2 + (4/10)^2 = 1/4 on, at L9: the rounded convex corner
(3/2,3/2)(3/2, 3/2) the boundaries of the slabs [1,2]×[1/2,3/2][1, 2] \times [1/2, 3/2] and [1/2,3/2]×[1,2][1/2, 3/2] \times [1, 2] on, at L9: the two cones leave the open quadrant up and to the right uncovered; this is the sharp concave corner of the grown solid
(5/4,5/4)(5/4, 5/4) the interiors of both slabs and of the disk at (1,1)(1, 1) in, at L6
(8/5,8/5)(8/5, 8/5) none: it is 0.72>1/2\sqrt{0.72} > 1/2 from (1,1)(1, 1) out, at L7

The grown solid has rounded convex corners and one sharp concave corner, at (3/2,3/2)(3/2, 3/2), where the offset lines of the two edges at the reflex corner meet. Shrinking SS by r=1/4r = 1/4 gives the L shape of arms [1/4,7/4]×[1/4,3/4][1/4, 7/4] \times [1/4, 3/4] and [1/4,3/4]×[1/4,7/4][1/4, 3/4] \times [1/4, 7/4], with sharp convex corners and a quarter circle of radius 1/41/4 around the reflex corner (1,1)(1, 1). SHRINK-CLASSIFY returns on for (1/4,1/2)(1/4, 1/2) and (3/2,3/4)(3/2, 3/4), which lie on offset lines, and for (17/20,4/5)(17/20, 4/5), which is at distance exactly 1/41/4 from (1,1)(1, 1). It returns out for (9/10,9/10)(9/10, 9/10), which is inside the disk at (1,1)(1, 1), and in for (1/2,1/2)(1/2, 1/2).

Rounding and filleting by hand. Rounding is (S↓r)↑r(S \downarrow r) \uparrow r. Growing the shrunk L by 1/41/4 rounds its five convex corners with quarter circles of radius 1/41/4, and the quarter circle around (1,1)(1, 1) grows back to the sharp reflex corner. Each convex corner loses r2−πr2/4r^2 - \pi r^2 / 4, so the area drops by 5(1−π/4)/165(1 - \pi/4)/16. Filleting is (S↑r)↓r(S \uparrow r) \downarrow r. Growing by 1/41/4 makes the sharp concave corner at (5/4,5/4)(5/4, 5/4), and shrinking by 1/41/4 turns it into a quarter circle of radius 1/41/4 about (5/4,5/4)(5/4, 5/4) that meets the edges at (5/4,1)(5/4, 1) and (1,5/4)(1, 5/4). The convex corners stay sharp, and the area grows by 1/16−π/641/16 - \pi/64.

Growing does not commute with intersection. For A=[0,1]2A = [0, 1]^2, B=[2,3]×[0,1]B = [2, 3] \times [0, 1] and r=3/4r = 3/4, the set A∩BA \cap B is empty, so (A∩B)↑r(A \cap B) \uparrow r is empty, but (3/2,1/2)(3/2, 1/2) is in both A↑rA \uparrow r and B↑rB \uparrow r. So the method must grow the solid as a whole, from its boundary, and cannot grow the primitives of a tree with intersections or differences.

Correctness

Every point of a swept member is within rr of a point of ∂S⊆S\partial S \subseteq S, so T⊆S↑rT \subseteq S \uparrow r. Conversely, if x∉Sx \notin S is within rr of SS, its nearest point yy in SS lies on ∂S\partial S, on some edge ee, and the nearest point of ee to xx is either inside ee, so that xx is in the slab of ee, or an end of ee, so that xx is in a vertex disk. So T=S↑rT = S \uparrow r. For shrinking, the points of SS in no swept member are those at distance more than rr from ∂S\partial S, and the regularized shrink is the closure of that set, because the distance to the boundary has no local minimum at a positive value. The neighborhood test of line L8 is exact: if a sector, a direction or a germ is not covered, the proof constructs points arbitrarily close to xx that lie in no member, and if all are covered, a whole disk around xx is. The full proof gives the details. All tests compare rational numbers, so every decision is exact.

What is proved is the planar method on rectangle trees. The three-dimensional method rests on the same identity, with prisms, cylinders and balls as members, but the neighborhood test of line L8 for those members is not proved here.

Proof: The swept members give the grown solid, and the classification of grow and shrink is exactfull

Let S⊂R2S \subset \mathbb{R}^2 be the regularized set of a CSG tree of closed axis-aligned rectangles, and let r>0r > 0. Let EE and VV be the edges and vertices computed at line L1, let UU be the union of the swept members SLAB(e,r)(e, r) for e∈Ee \in E and DISK(p,r)(p, r) for p∈Vp \in V, and let T=S∪UT = S \cup U. A slab is the closed rectangle of points a+s(b−a)+τνa + s(b - a) + \tau \nu with s∈[0,1]s \in [0, 1] and ∣τ∣≤r|\tau| \le r, for an edge from aa to bb with unit normal ν\nu.

Lemma 1 (boundary evaluation). SS is the union of the closed grid cells whose centers are in, and ∂S\partial S is the union of the edges in EE.

Proof. Every rectangle boundary lies on grid lines, so each open cell lies inside or outside each open rectangle, and the Boolean expression of the tree on the open rectangles is constant on each open cell. The regularized operations take the closure of the interior of the result, so SS is the closure of the union of the open cells that are in, which is the union of the closed cells that are in. A point inside a cell, or on a grid edge between two cells of the same status, has a neighborhood of one status. A point on a grid edge between an in cell and an out cell is on ∂S\partial S. At a grid vertex, going around the four cells, the status changes between two consecutive cells exactly when the vertex is on ∂S\partial S, and two consecutive cells share an edge that ends at the vertex. So ∂S\partial S is the union of the separating grid edges, and merging collinear edges into maximal segments does not change their union. □\square

Lemma 2 (decomposition). S↑r=TS \uparrow r = T, and for x∈Sx \in S, x∈Ux \in U if and only if dist⁡(x,∂S)≤r\operatorname{dist}(x, \partial S) \le r.

Proof. Each point of a slab or a disk is within rr of a point of ∂S⊆S\partial S \subseteq S, so T⊆S↑rT \subseteq S \uparrow r. Let xx be within rr of a closed set Z∈{S,∂S}Z \in \{S, \partial S\} with x∉Sx \notin S when Z=SZ = S, and let yy be a nearest point of ZZ to xx. If Z=SZ = S, then y∈∂Sy \in \partial S, since otherwise a point of SS on the segment from xx to yy would be closer. By Lemma 1, yy lies on an edge ee from aa to bb in EE, so dist⁡(x,e)≤r\operatorname{dist}(x, e) \le r. The nearest point of ee to xx is either a point a+s(b−a)a + s(b - a) with 0<s<10 < s < 1, where x−a−s(b−a)x - a - s(b - a) is normal to ee and of length at most rr, so xx is in the slab of ee, or an end aa or bb, which is in VV, so xx is in its disk. This proves S↑r⊆TS \uparrow r \subseteq T and, with Z=∂SZ = \partial S, the second claim. □\square

Lemma 3 (the neighborhood test). Let xx be a point that lies on the boundary of every member of UU that contains it, and let MM be these members. Line L8 returns true if and only if x∈int⁡Ux \in \operatorname{int} U.

Proof. Members that do not contain xx are at positive distance from it and do not matter. For a rectangle R∈MR \in M, let KRK_R be its closed tangent cone at xx; for ρ\rho smaller than the distance from xx to the sides of RR that miss xx, R∩B(x,ρ)=(x+KR)∩B(x,ρ)R \cap B(x, \rho) = (x + K_R) \cap B(x, \rho). For a disk with center cc and w=c−xw = c - x, ∣w∣=r|w| = r, a point x+yx + y is in the disk if and only if ∣y∣2≤2y⋅w|y|^2 \le 2 y \cdot w. The critical directions are ±e1\pm e_1, ±e2\pm e_2 and ±w⊥\pm w^\perp for each disk. Each KRK_R is bounded by axis directions, and v⋅wv \cdot w has a constant sign on each open sector between two consecutive critical directions. Consecutive directions are less than π\pi apart, because the four axis directions are among them, so the sum mm of two consecutive ones lies in the open sector between them.

If the test passes, x∈int⁡Ux \in \operatorname{int} U. Fix an open sector σ\sigma from vv to v′v' with midpoint mm. If a rectangle has m∈KRm \in K_R, then KR⊇σˉK_R \supseteq \bar\sigma, since KRK_R is a closed cone bounded by critical directions, and all of σˉ\bar\sigma is covered near xx. Otherwise a disk has m⋅w>0m \cdot w > 0, so v⋅w>0v \cdot w > 0 on all of σ\sigma. By the germ checks at vv and v′v', each end of σ\sigma is covered by a rectangle with KR⊇σˉK_R \supseteq \bar\sigma, which covers the sector, or by a disk with v⋅w′>0v \cdot w' > 0 (or v′⋅w′>0v' \cdot w' > 0), which by continuity has u⋅w′≥c∣u∣u \cdot w' \ge c|u| for some c>0c > 0 on a closed sub-sector next to that end, and so covers the points x+yx + y there with ∣y∣≤2c|y| \le 2c. The rest of σ\sigma is a closed sub-sector on which u⋅w≥c′∣u∣u \cdot w \ge c' |u|, covered for ∣y∣≤2c′|y| \le 2c'. Each critical direction vv is covered on its ray by a rectangle with v∈KRv \in K_R or by a disk with v⋅w>0v \cdot w > 0. There are finitely many sectors and directions, so some ρ0>0\rho_0 > 0 works for all, and B(x,ρ0)⊆UB(x, \rho_0) \subseteq U.

If a check fails, x∉int⁡Ux \notin \operatorname{int} U. (i) If no member covers the midpoint mm of a sector, consider x+tmx + t m for small t>0t > 0. It is in no rectangle, since m∉KRm \notin K_R, and in no disk, since m⋅w≠0m \cdot w \ne 0 for a non-critical mm, so m⋅w<0m \cdot w < 0 and t2∣m∣2>2tm⋅wt^2 |m|^2 > 2 t m \cdot w. (ii) If the ray of a critical direction vv is not covered, x+tvx + t v is in no rectangle, and for each disk v⋅w≤0v \cdot w \le 0, so t2∣v∣2>2tv⋅wt^2 |v|^2 > 2 t v \cdot w. (iii) If the germ on the side of mm at vv is not covered, let yt=x+tv+t3my_t = x + t v + t^3 m for small t>0t > 0. Its direction v+t2mv + t^2 m lies in the open sector between vv and mm. A rectangle that holds yty_t for arbitrarily small tt has v+t2m∈KRv + t^2 m \in K_R, hence m∈KRm \in K_R, since membership in KRK_R is constant on the open sector, and v∈KRv \in K_R, since KRK_R is closed; no such rectangle exists. A disk with v⋅w<0v \cdot w < 0 misses yty_t for small tt. A disk with v⋅w=0v \cdot w = 0 holds yty_t only if t2∣v∣2+O(t4)≤2t3m⋅wt^2|v|^2 + O(t^4) \le 2 t^3 m \cdot w, which fails for small tt. No disk has v⋅w>0v \cdot w > 0, by assumption. In each case points in no member come arbitrarily close to xx. □\square

Lemma 4 (no positive local minimum). For x∈Sx \in S let d(x)=dist⁡(x,∂S)d(x) = \operatorname{dist}(x, \partial S). No point xx with d(x)>0d(x) > 0 is a local minimum of dd. Hence int⁡{x∈S:d(x)≥r}={x∈S:d(x)>r}\operatorname{int}\{x \in S : d(x) \ge r\} = \{x \in S : d(x) > r\}.

Proof. Let yy be a nearest point of ∂S\partial S to xx. The points x+t(y−x)x + t(y - x), 0<t<10 < t < 1, are at distance (1−t)d(x)<d(x)(1 - t) d(x) < d(x) from yy. The set {d>r}\{d > r\} is open, as dd is continuous and ∂S∩{d>r}=∅\partial S \cap \{d > r\} = \emptyset, and it is contained in the set {d≥r}\{d \ge r\}; a point with d=rd = r has points with d<rd < r arbitrarily close, so it is not interior. □\square

Theorem. For every point xx with rational coordinates, CLASSIFY(T,x)(T, x) returns in, on or out as xx is in the interior, on the boundary or outside of S↑rS \uparrow r, and SHRINK-CLASSIFY(S,r,x)(S, r, x) does the same for the regularized shrink R=cl⁡(int⁡(S↓r))R = \operatorname{cl}(\operatorname{int}(S \downarrow r)). Every decision is exact.

Proof. Grow. By Lemma 2, T=S↑rT = S \uparrow r. If x∈int⁡Sx \in \operatorname{int} S, it is interior to TT, and line L6 returns in. If x∈∂Sx \in \partial S, it is inside its edge's slab, or it is a vertex and inside its disk, because r>0r > 0, so L6 returns in, and it is indeed interior. If x∉Sx \notin S, a neighborhood of xx misses the closed set SS, so xx is interior to TT exactly when it is interior to UU. Line L6 handles a point inside a member, line L7 a point in no member, and lines L8 and L9 are correct by Lemma 3.

Shrink. A closed ball x+Brx + B_r lies in SS exactly when x∈Sx \in S and d(x)≥rd(x) \ge r, because for x∈Sx \in S the distance to the closure of the complement equals d(x)d(x). By Lemma 4 and Lemma 2, int⁡(S↓r)={x∈S:d(x)>r}=S∖U\operatorname{int}(S \downarrow r) = \{x \in S : d(x) > r\} = S \setminus U, so R=cl⁡(S∖U)R = \operatorname{cl}(S \setminus U). If x∉Sx \notin S, then x∉R⊆Sx \notin R \subseteq S, and L10 returns out. Let x∈Sx \in S. If x∉Ux \notin U, then x∉∂S⊆Ux \notin \partial S \subseteq U, so xx has a neighborhood in S∖US \setminus U and is interior to RR; CLASSIFY returns out and L12 returns in. If x∈int⁡Ux \in \operatorname{int} U, a neighborhood of xx misses S∖US \setminus U, so x∉Rx \notin R; CLASSIFY returns in and L12 returns out. Otherwise xx is on the boundary of UU. Since ∂S⊆int⁡U\partial S \subseteq \operatorname{int} U, x∈int⁡Sx \in \operatorname{int} S, so points of S∖US \setminus U come arbitrarily close to xx and x∈Rx \in R. Each member is the closure of its interior, so points of int⁡U\operatorname{int} U, which are not in RR, also come arbitrarily close, and x∈∂Rx \in \partial R; CLASSIFY returns on, by Lemma 3, and so does L12.

Exactness. The coordinates, rr, the corners of the slabs and the centers of the disks are rational; the tests compare coordinates, squared distances with r2r^2, and signs of dot and cross products of rational vectors. ■\blacksquare

What is not claimed. The proof covers the planar method on trees of axis-aligned rectangles. In three dimensions the decomposition of Lemma 2 holds with face prisms, edge cylinders and vertex balls by the same argument, but the neighborhood test of Lemma 3 for cylinders and balls, whose tangent cones have curved germs in more directions, is not proved here.

Complexity

The costs are in the real RAM, and with rational input every operation is exact. For a tree of mm rectangles, the grid has O(m2)O(m^2) cells, and classifying a cell against the tree costs O(m)O(m), so line L1 costs O(m3)O(m^3). The boundary has O(m2)O(m^2) grid edges, so lines L3 and L4 add O(m2)O(m^2) members, and GROW costs O(m3)O(m^3) time and O(m2)O(m^2) space. A query costs O(m2)O(m^2) to test the members and, when tt members hold the point on their boundary, O(tlog⁡t)O(t \log t) to sort the directions and O(t2)O(t^2) for the sector and germ checks. In three dimensions the number of members is the number of faces, edges and vertices of SS, and the classification of a point costs time linear in that number, plus the cost of the neighborhood test at boundary points.

Properties

  • No offset surfaces are intersected. The grown solid is a union, so the trimming of offset faces that defeats B-rep offsetting does not arise; its boundary is evaluated only when needed.
  • Topology changes are automatic. Parts that merge, holes that close and walls that vanish need no special case, because membership is decided point by point.
  • Exact. With rational input and squared distances, every decision is a comparison of rational numbers, including the decisions at distance exactly rr.
  • Grow and shrink together. Both use the same members, so rounding and filleting cost two applications of the same machinery.
  • Not a boundary. The output is a classification, not a B-rep. A B-rep of the result needs a boundary evaluation of the union, which brings back the intersections of the member surfaces.

Variants and improvements

  • Curved faces. For a face on a sphere, a cylinder or a torus, the face offset is bounded by offset surfaces of the same kind, so a CSG system with these primitives can still represent it. General curved faces need offset surfaces and approximation.
  • Pruning members. A face, edge or vertex whose offset lies inside the union of the others can be dropped; for example, at a straight run of collinear edges the interior vertices add nothing. Spatial sorting of the members makes a query cheaper.
  • Distance fields. A sampled signed distance function gives the same sets approximately, by thresholding the distance at ±r\pm r, and is the usual choice for meshes and for 3D printing.
  • Rolling-ball blends. A fillet of a single edge, not of the whole solid, is built by the rolling-ball method, which traces the path of a ball of radius rr touching two faces; filleting by (S↑r)↓r(S \uparrow r) \downarrow r gives the same surface on that edge but changes all concave edges at once.
  • Minkowski sums. Replacing the ball by another convex body gives the general Minkowski sum, where the edge and vertex members become swept copies of that body.

When to use it

Use the method when the solid is a CSG tree and the result is needed for classification: for clearance and interference checks, for display by ray casting, for tolerance zones and for mass properties of grown or shrunk parts. Use B-rep offsetting when a boundary representation of the offset is needed for further modeling, and accept its harder intersection and trimming steps. For one rounded edge, use a blend; for whole-solid rounding and filleting, use the compositions on this page.

Pitfalls

  • Growing the leaves of the tree. (A∪B)↑r=A↑r∪B↑r(A \cup B) \uparrow r = A \uparrow r \cup B \uparrow r, but no such identity holds for intersection or difference, as the example shows. Only a union tree can be grown by growing its leaves.
  • Missing the regularization. A wall of width exactly 2r2r shrinks to a segment and a square of side 2r2r to a point; without regularization these lower-dimensional pieces stay in the result. Lines L10 to L12 remove them, because such points are covered by members on all sides.
  • Treating a disk like a half plane. A disk covers the directions along its tangent only outside a thin cusp. In the L shape [−2,2]×[0,3][-2, 2] \times [0, 3] minus [0,2]×[1,3][0, 2] \times [1, 3] with r=1/2r = 1/2, the point (0,1/2)(0, 1/2) lies on the offset line y=1/2y = 1/2 of the bottom edge and on the circle around the reflex corner (0,1)(0, 1). The two members leave no open sector uncovered, but points just above the line and to the left of the circle are in neither, so (0,1/2)(0, 1/2) is on the shrunk solid. A test that only looks at sectors calls it out.
  • Rounding. The decisions compare a squared distance with r2r^2; a point at distance exactly rr is a degenerate input, not a rare one, since tolerances and design rules put features at exact distances. Branching on the sign of a rounded difference of nearly equal numbers is an orientation-test style decision and can fail by catastrophic cancellation. The fix is exact rational arithmetic, as here, or a filter that falls back to exact arithmetic near zero.
  • Curved faces in a simple CSG system. The offset of a curved face is not a slab, and replacing it by a slab of its tangent plane is wrong away from the point of tangency.

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.

rossignac_requicha_offsetting.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rossignac-requicha-offsetting/. The authors are listed in prov/B7AHTM.jsonl.

"""Growing and shrinking a planar CSG solid by the method of Rossignac and Requicha, exactly.

A solid is a CSG tree of closed axis-aligned boxes with rational corners and
the regularized operations union, intersection and difference. Growing by r
replaces the solid S by the union of S with the boundary edges of S swept by
r along their normals (closed rectangles, the "slabs") and the boundary
vertices swept by r (closed disks). Shrinking uses the same primitives: a
point of S is in the regularized shrink when it is not inside their union,
which is the complement of the grown complement.

Membership is exact in rational arithmetic. A point is classified as "in",
"on" or "out" of a union of primitives with a neighborhood test: the
primitives that hold the point on their boundary must cover every direction
around it, and a disk only covers the open half plane on its side of its
tangent.
"""

from fractions import Fraction
from functools import cmp_to_key

# --- CSG of boxes -----------------------------------------------------------


def box(x0, x1, y0, y1):
    return ("box", (Fraction(x0), Fraction(x1), Fraction(y0), Fraction(y1)))


def union(a, b):
    return ("union", a, b)


def inter(a, b):
    return ("inter", a, b)


def diff(a, b):
    return ("diff", a, b)


def boxes_of(t):
    if t[0] == "box":
        return [t[1]]
    return boxes_of(t[1]) + boxes_of(t[2])


def open_member(t, p) -> bool:
    """Membership of a point that lies on no box boundary, so no rule for ties is needed."""
    if t[0] == "box":
        x0, x1, y0, y1 = t[1]
        return x0 < p[0] < x1 and y0 < p[1] < y1
    a, b = open_member(t[1], p), open_member(t[2], p)
    if t[0] == "union":
        return a or b
    if t[0] == "inter":
        return a and b
    return a and not b


class Solid:
    """The regularized set of a CSG tree, as the closed cells of the grid of its box coordinates."""

    def __init__(self, tree):
        bs = boxes_of(tree)
        self.xs = sorted({b[0] for b in bs} | {b[1] for b in bs})
        self.ys = sorted({b[2] for b in bs} | {b[3] for b in bs})
        nx, ny = len(self.xs) - 1, len(self.ys) - 1
        self.cell = [[open_member(tree, ((self.xs[i] + self.xs[i + 1]) / 2, (self.ys[j] + self.ys[j + 1]) / 2)) for j in range(ny)] for i in range(nx)]
        self.cells = [(self.xs[i], self.xs[i + 1], self.ys[j], self.ys[j + 1]) for i in range(nx) for j in range(ny) if self.cell[i][j]]
        self.edges = self._boundary()
        self.vertices = sorted({p for e in self.edges for p in e})

    def _in(self, i, j) -> bool:
        return 0 <= i < len(self.cell) and 0 <= j < len(self.cell[0]) and self.cell[i][j]

    def _boundary(self):
        """Maximal boundary segments: grid edges between an inside cell and an outside cell, merged."""
        nx, ny = len(self.xs) - 1, len(self.ys) - 1
        edges = []
        for j in range(ny + 1):  # horizontal edges at y = ys[j]
            run = None
            for i in range(nx):
                if self._in(i, j - 1) != self._in(i, j):
                    run = (self.xs[i] if run is None else run[0], self.xs[i + 1])
                else:
                    if run:
                        edges.append(((run[0], self.ys[j]), (run[1], self.ys[j])))
                    run = None
            if run:
                edges.append(((run[0], self.ys[j]), (run[1], self.ys[j])))
        for i in range(nx + 1):  # vertical edges at x = xs[i]
            run = None
            for j in range(ny):
                if self._in(i - 1, j) != self._in(i, j):
                    run = (self.ys[j] if run is None else run[0], self.ys[j + 1])
                else:
                    if run:
                        edges.append(((self.xs[i], run[0]), (self.xs[i], run[1])))
                    run = None
            if run:
                edges.append(((self.xs[i], run[0]), (self.xs[i], run[1])))
        return edges

    def contains(self, p) -> bool:
        return any(c[0] <= p[0] <= c[1] and c[2] <= p[1] <= c[3] for c in self.cells)

    def on_boundary(self, p) -> bool:
        for (a, b) in self.edges:
            if 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]):
                return True
        return False


# --- the swept primitives ---------------------------------------------------


def slab(edge, r):
    """An axis-parallel edge swept by r on both sides along its normal: a closed box."""
    (a, b) = edge
    if a[1] == b[1]:
        return ("rect", (min(a[0], b[0]), max(a[0], b[0]), a[1] - r, a[1] + r))
    return ("rect", (a[0] - r, a[0] + r, min(a[1], b[1]), max(a[1], b[1])))


def disk(p, r):
    return ("disk", (p, r))


def where(prim, x):
    """-1 inside, 0 on the boundary, +1 outside the closed primitive."""
    kind, d = prim
    if kind == "rect":
        x0, x1, y0, y1 = d
        if x0 < x[0] < x1 and y0 < x[1] < y1:
            return -1
        return 0 if (x0 <= x[0] <= x1 and y0 <= x[1] <= y1) else 1
    (c, r) = d
    s = (x[0] - c[0]) ** 2 + (x[1] - c[1]) ** 2 - r * r
    return (s > 0) - (s < 0)


# --- neighborhood classification --------------------------------------------


def half(v) -> int:
    return 0 if (v[1] > 0 or (v[1] == 0 and v[0] > 0)) else 1


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


def sort_by_angle(vs):
    def cmp(a, b):
        ha, hb = half(a), half(b)
        if ha != hb:
            return ha - hb
        c = cross(a, b)
        return -1 if c > 0 else (1 if c < 0 else 0)

    out = []
    for v in sorted(vs, key=cmp_to_key(cmp)):
        if not out or cmp(out[-1], v) != 0:
            out.append(v)
    return out


def in_cone(prim, x, v) -> bool:
    """For a rectangle with x on its boundary: is direction v in its closed tangent cone at x?"""
    x0, x1, y0, y1 = prim[1]
    return (x[0] != x0 or v[0] >= 0) and (x[0] != x1 or v[0] <= 0) and (x[1] != y0 or v[1] >= 0) and (x[1] != y1 or v[1] <= 0)


def disk_covers(prim, x, v) -> bool:
    """A disk with x on its circle covers the directions in the open half plane towards its center."""
    (c, _) = prim[1]
    return v[0] * (c[0] - x[0]) + v[1] * (c[1] - x[1]) > 0


def covers_neighborhood(touching, x) -> bool:
    """Do the primitives that hold x on their boundary cover a whole neighborhood of x?"""
    rays = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    for prim in touching:
        if prim[0] == "disk":
            (c, _) = prim[1]
            w = (c[0] - x[0], c[1] - x[1])
            rays += [(-w[1], w[0]), (w[1], -w[0])]
    rays = sort_by_angle(rays)
    rects = [p for p in touching if p[0] == "rect"]
    disks = [p for p in touching if p[0] == "disk"]

    def generic(m):
        return any(in_cone(p, x, m) for p in rects) or any(disk_covers(p, x, m) for p in disks)

    n = len(rays)
    for k in range(n):
        v, nxt, prv = rays[k], rays[(k + 1) % n], rays[k - 1]
        m_after = (v[0] + nxt[0], v[1] + nxt[1])
        m_before = (v[0] + prv[0], v[1] + prv[1])
        if not generic(m_after):  # the open sector after v
            return False
        if not generic(v):  # the ray v itself
            return False
        for m in (m_before, m_after):  # the thin germs on each side of v
            if not (any(in_cone(p, x, v) and in_cone(p, x, m) for p in rects) or any(disk_covers(p, x, v) for p in disks)):
                return False
    return True


# --- the method -------------------------------------------------------------


class Grown:
    """S grown by r, as the union of S with its swept boundary edges and vertices."""

    def __init__(self, S: Solid, r):
        self.S, self.r, self.prims = S, Fraction(r), []

    def classify_primitives(self, x) -> str:
        """in, on or out of the union of the swept primitives alone."""
        w = [where(p, x) for p in self.prims]
        if any(s < 0 for s in w):  # @line L6
            return "in"
        touching = [p for p, s in zip(self.prims, w) if s == 0]
        if not touching:  # @line L7
            return "out"
        if covers_neighborhood(touching, x):  # @line L8
            return "in"
        return "on"  # @line L9

    def classify(self, x) -> str:
        """in, on or out of the grown solid."""
        x = (Fraction(x[0]), Fraction(x[1]))
        if self.S.contains(x) and not self.S.on_boundary(x):
            return "in"
        return self.classify_primitives(x)

    def contains(self, x) -> bool:
        return self.classify(x) != "out"


def grow(tree, r) -> Grown:
    if Fraction(r) <= 0:
        raise ValueError("the distance must be positive")
    S = Solid(tree)  # @line L1
    T = Grown(S, r)  # @line L2
    T.prims += [slab(e, T.r) for e in S.edges]  # @line L3
    T.prims += [disk(p, T.r) for p in S.vertices]  # @line L4
    return T  # @line L5


def shrink_classify(tree_or_grown, r, x) -> str:
    """in, on or out of the regularized shrink of S by r."""
    G = tree_or_grown if isinstance(tree_or_grown, Grown) else grow(tree_or_grown, r)
    x = (Fraction(x[0]), Fraction(x[1]))
    if not G.S.contains(x):  # @line L10
        return "out"
    c = G.classify_primitives(x)  # @line L11
    return {"out": "in", "on": "on", "in": "out"}[c]  # @line L12
test_rossignac_requicha_offsetting.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rossignac-requicha-offsetting/. The authors are listed in prov/B7AHTM.jsonl.

import random
import unittest
from fractions import Fraction as F

from rossignac_requicha_offsetting import Solid, box, diff, grow, inter, shrink_classify, union


def d2_rect(c, x):
    dx = max(c[0] - x[0], F(0), x[0] - c[1])
    dy = max(c[2] - x[1], F(0), x[1] - c[3])
    return dx * dx + dy * dy


def d2_to_solid(S: Solid, x):
    """Brute force: the squared distance to the union of the closed inside cells."""
    return min((d2_rect(c, x) for c in S.cells), default=None)


def d2_to_complement(S: Solid, x):
    """Brute force: the squared distance to the closure of the complement, for x in the grid."""
    xs, ys = S.xs, S.ys
    best = min(x[0] - xs[0], xs[-1] - x[0], x[1] - ys[0], ys[-1] - x[1]) ** 2
    for i in range(len(xs) - 1):
        for j in range(len(ys) - 1):
            if not S.cell[i][j]:
                best = min(best, d2_rect((xs[i], xs[i + 1], ys[j], ys[j + 1]), x))
    return best


def random_tree(rng, n):
    def rb():
        x0, y0 = rng.randint(0, 5), rng.randint(0, 5)
        return box(x0, x0 + rng.randint(1, 3), y0, y0 + rng.randint(1, 3))

    t = rb()
    for _ in range(n - 1):
        t = rng.choice([union, union, inter, diff])(t, rb())
    return t


def points(rng, k, lo=-2, hi=10, den=4):
    return [(F(rng.randint(lo * den, hi * den), den), F(rng.randint(lo * den, hi * den), den)) for _ in range(k)]


def near(rng, S: Solid, k, den=4):
    """Random points of the grid of step 1/den in the box of S, widened by 1."""
    if not S.cells:
        return points(rng, k)
    x0, x1 = min(c[0] for c in S.cells) - 1, max(c[1] for c in S.cells) + 1
    y0, y1 = min(c[2] for c in S.cells) - 1, max(c[3] for c in S.cells) + 1
    return [(F(rng.randint(int(x0 * den), int(x1 * den)), den), F(rng.randint(int(y0 * den), int(y1 * den)), den)) for _ in range(k)]


def ring(x, K=40, N=1000):
    """The points x + (i, j) / N with max(|i|, |j|) = K."""
    out = []
    for i in range(-K, K + 1):
        out += [(x[0] + F(i, N), x[1] + F(K, N)), (x[0] + F(i, N), x[1] - F(K, N))]
        out += [(x[0] + F(K, N), x[1] + F(i, N)), (x[0] - F(K, N), x[1] + F(i, N))]
    return out


class TestGrow(unittest.TestCase):
    def test_box_grows_to_a_rounded_box(self):
        r = F(1, 2)
        G = grow(box(0, 3, 0, 2), r)
        rng = random.Random(1)
        pts = points(rng, 600, -1, 4, 10) + [(F(3) + F(3, 10), F(2) + F(4, 10)), (F(-1, 2), F(1)), (F(1), F(5, 2))]
        for x in pts:
            d2 = d2_rect((F(0), F(3), F(0), F(2)), x)
            expect = "in" if d2 < r * r else ("on" if d2 == r * r else "out")
            self.assertEqual(G.classify(x), expect, x)

    def test_random_trees_against_brute_force(self):
        rng = random.Random(2)
        for _ in range(25):
            tree = random_tree(rng, rng.randint(1, 4))
            r = rng.choice([F(1, 2), F(3, 4), F(1, 3)])
            G = grow(tree, r)
            for x in near(rng, G.S, 60):
                d2 = d2_to_solid(G.S, x)
                if d2 is None:
                    self.assertEqual(G.classify(x), "out")
                    continue
                self.assertEqual(G.contains(x), d2 <= r * r)
                if d2 != r * r:
                    self.assertEqual(G.classify(x), "in" if d2 < r * r else "out")
                else:
                    # At distance exactly r, x is on the boundary when points nearby are farther.
                    outside = any(d2_to_solid(G.S, y) > r * r for y in ring(x))
                    self.assertEqual(G.classify(x), "on" if outside else "in", x)

    def test_union_identity_and_intersection_inclusion(self):
        rng = random.Random(3)
        for _ in range(12):
            A, B = random_tree(rng, 2), random_tree(rng, 2)
            r = F(1, 2)
            GA, GB, GU, GI = grow(A, r), grow(B, r), grow(union(A, B), r), grow(inter(A, B), r)
            for x in points(rng, 50):
                self.assertEqual(GU.contains(x), GA.contains(x) or GB.contains(x))
                if GI.contains(x):
                    self.assertTrue(GA.contains(x) and GB.contains(x))
        # The inclusion is strict: two disjoint squares at distance 1.
        A, B, r = box(0, 1, 0, 1), box(2, 3, 0, 1), F(3, 4)
        x = (F(3, 2), F(1, 2))
        self.assertTrue(grow(A, r).contains(x) and grow(B, r).contains(x))
        self.assertFalse(grow(inter(A, B), r).contains(x))

    def test_degenerate_contacts(self):
        r = F(1, 2)
        # A square hole of half side r closes exactly: its center is an interior point.
        G = grow(diff(box(0, 3, 0, 3), box(1, 2, 1, 2)), r)
        self.assertEqual(G.classify((F(3, 2), F(3, 2))), "in")
        # Two squares at distance 2r merge along a segment, which is interior except at its ends.
        G = grow(union(box(0, 1, 0, 1), box(2, 3, 0, 1)), r)
        self.assertEqual(G.classify((F(3, 2), F(1, 2))), "in")
        self.assertEqual(G.classify((F(3, 2), F(0))), "on")
        self.assertEqual(G.classify((F(3, 2), F(-1, 100))), "out")


class TestShrink(unittest.TestCase):
    def test_box_shrinks_to_a_box(self):
        r = F(1, 2)
        G = grow(box(0, 4, 0, 2), r)
        rng = random.Random(4)
        for x in points(rng, 500, -1, 5, 8):
            inner = (F(1, 2), F(7, 2), F(1, 2), F(3, 2))
            inside = inner[0] < x[0] < inner[1] and inner[2] < x[1] < inner[3]
            closed = inner[0] <= x[0] <= inner[1] and inner[2] <= x[1] <= inner[3]
            self.assertEqual(shrink_classify(G, r, x), "in" if inside else ("on" if closed else "out"), x)

    def test_random_trees_against_brute_force(self):
        rng = random.Random(5)
        for _ in range(25):
            tree = random_tree(rng, rng.randint(1, 4))
            r = rng.choice([F(1, 2), F(1, 3)])
            G = grow(tree, r)
            for x in near(rng, G.S, 60):
                if not G.S.contains(x):
                    self.assertEqual(shrink_classify(G, r, x), "out")
                    continue
                d2 = d2_to_complement(G.S, x)
                if d2 != r * r:
                    self.assertEqual(shrink_classify(G, r, x), "in" if d2 > r * r else "out")
                else:
                    deeper = any(G.S.contains(y) and d2_to_complement(G.S, y) > r * r for y in ring(x))
                    self.assertEqual(shrink_classify(G, r, x), "on" if deeper else "out", x)

    def test_regularization(self):
        r = F(1, 2)
        # A slab of width exactly 2r shrinks to a segment, which regularization removes.
        self.assertEqual(shrink_classify(box(0, 1, 0, 3), r, (F(1, 2), F(1))), "out")
        # A square of side 2r shrinks to its center, which regularization removes.
        self.assertEqual(shrink_classify(box(0, 1, 0, 1), r, (F(1, 2), F(1, 2))), "out")
        # In an L shape the shrunk left arm touches the line y = r at a point below the reflex corner.
        L = diff(box(-2, 2, 0, 3), box(0, 2, 1, 3))
        self.assertEqual(shrink_classify(L, r, (F(0), F(1, 2))), "on")
        self.assertEqual(shrink_classify(L, r, (F(-1), F(1, 2))), "on")
        self.assertEqual(shrink_classify(L, r, (F(1), F(1, 2))), "out")
        self.assertEqual(shrink_classify(L, r, (F(-1, 5), F(51, 100))), "in")
        self.assertEqual(shrink_classify(L, r, (F(-1, 20), F(51, 100))), "out")

    def test_nonpositive_distance_is_rejected(self):
        with self.assertRaises(ValueError):
            grow(box(0, 1, 0, 1), 0)


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

History

Rossignac and Requicha's paper of 1986 defined growing and shrinking of r-sets, proved their main properties, wrote the grown solid as the union of the solid with offsets of its faces, edges and vertices, and showed how to evaluate it in a CSG modeler. It also defined rounding and filleting of a whole solid as (S↓r)↑r(S \downarrow r) \uparrow r and (S↑r)↓r(S \uparrow r) \downarrow r, the opening and closing of mathematical morphology. The classification machinery it relies on comes from Requicha's theory of representations and Tilove's set membership classification, both of 1980.

References

  1. Jaroslaw R. Rossignac and Aristides A. G. Requicha, Offsetting operations in solid modelling, Computer Aided Geometric Design 3(2), 129 to 148, 1986, the whole paper (the definitions of growing and shrinking, the decomposition of the grown solid into offsets of faces, edges and vertices, the evaluation for CSG solids, and rounding and filleting)
  2. Aristides A. G. Requicha, Representations for rigid solids, theory, methods, and systems, ACM Computing Surveys 12(4), 437 to 464, 1980, the r-sets, the regularized operations and the CSG representation that the method builds on
  3. 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 points and sets against a CSG tree, including the neighborhoods needed at boundary points

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