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.
- Solves
- Solid offsetting
- 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
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jaroslaw R. Rossignac, Aristides A. G. Requicha, 1986
Rossignac and Requicha's method grows a solid by a distance without computing any offset surface. It uses the identity , 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 , 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 . 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 as a CSG tree and a distance . The output is a representation of the grown solid and of the regularized shrunk solid , with , 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: is a CSG tree of closed axis-aligned rectangles with rational corners, the faces of 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 are allowed inputs.
The algorithm
GROW(S, r)- 1
E, V ← the boundary edges and vertices of S ▷ boundary evaluation - 2
T ← the union with the one member S - 3
for each edge e in E do add SLAB(e, r) to T ▷ e swept by r on both sides - 4
for each vertex p in V do add DISK(p, r) to T - 5
return T CLASSIFY(T, x)- 6
if x is in the interior of S or of a swept member then return in - 7
if x is in no member then return out - 8
if the members with x on their boundary cover a neighborhood of x then return in - 9
return on SHRINK-CLASSIFY(S, r, x)- 10
if x is not in S then return out - 11
c ← CLASSIFY of x against the swept members of GROW(S, r) alone - 12
return 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 on both sides; edges give cylinders of radius and vertices give balls of radius . 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 , 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 and 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 on its boundary covers a closed cone of directions at : a half plane on a side, a quadrant at a corner. A disk with on its circle and center covers only the open half plane of directions with ; 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 and of the closure of its complement are the same, since the two sets have the same boundary, so a point of is in the interior of the shrunk solid exactly when it is in no swept member.
Example
Let be the L shape , the union of two rectangles. Line L1 finds six boundary edges, from to , to , to , to , to and to , and six vertices, of which is the reflex corner. For , lines L3 and L4 add six rectangles and six disks; for example the edge from to gives the rectangle .
| query point | members that hold it | result of CLASSIFY |
|---|---|---|
| the boundary of the slab of the right edge | on, at L9: the slab covers only the half plane to the left | |
| the circle of the disk at , since | on, at L9: the rounded convex corner | |
| the boundaries of the slabs and | 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 | |
| the interiors of both slabs and of the disk at | in, at L6 | |
| none: it is from | out, at L7 |
The grown solid has rounded convex corners and one sharp concave corner, at , where the offset lines of the two edges at the reflex corner meet. Shrinking by gives the L shape of arms and , with sharp convex corners and a quarter circle of radius around the reflex corner . SHRINK-CLASSIFY returns on for and , which lie on offset lines, and for , which is at distance exactly from . It returns out for , which is inside the disk at , and in for .
Rounding and filleting by hand. Rounding is . Growing the shrunk L by rounds its five convex corners with quarter circles of radius , and the quarter circle around grows back to the sharp reflex corner. Each convex corner loses , so the area drops by . Filleting is . Growing by makes the sharp concave corner at , and shrinking by turns it into a quarter circle of radius about that meets the edges at and . The convex corners stay sharp, and the area grows by .
Growing does not commute with intersection. For , and , the set is empty, so is empty, but is in both and . 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 of a point of , so . Conversely, if is within of , its nearest point in lies on , on some edge , and the nearest point of to is either inside , so that is in the slab of , or an end of , so that is in a vertex disk. So . For shrinking, the points of in no swept member are those at distance more than from , 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 that lie in no member, and if all are covered, a whole disk around 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 be the regularized set of a CSG tree of closed axis-aligned rectangles, and let . Let and be the edges and vertices computed at line L1, let be the union of the swept members SLAB for and DISK for , and let . A slab is the closed rectangle of points with and , for an edge from to with unit normal .
Lemma 1 (boundary evaluation). is the union of the closed grid cells whose centers are in, and is the union of the edges in .
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 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 . At a grid vertex, going around the four cells, the status changes between two consecutive cells exactly when the vertex is on , and two consecutive cells share an edge that ends at the vertex. So is the union of the separating grid edges, and merging collinear edges into maximal segments does not change their union.
Lemma 2 (decomposition). , and for , if and only if .
Proof. Each point of a slab or a disk is within of a point of , so . Let be within of a closed set with when , and let be a nearest point of to . If , then , since otherwise a point of on the segment from to would be closer. By Lemma 1, lies on an edge from to in , so . The nearest point of to is either a point with , where is normal to and of length at most , so is in the slab of , or an end or , which is in , so is in its disk. This proves and, with , the second claim.
Lemma 3 (the neighborhood test). Let be a point that lies on the boundary of every member of that contains it, and let be these members. Line L8 returns true if and only if .
Proof. Members that do not contain are at positive distance from it and do not matter. For a rectangle , let be its closed tangent cone at ; for smaller than the distance from to the sides of that miss , . For a disk with center and , , a point is in the disk if and only if . The critical directions are , and for each disk. Each is bounded by axis directions, and has a constant sign on each open sector between two consecutive critical directions. Consecutive directions are less than apart, because the four axis directions are among them, so the sum of two consecutive ones lies in the open sector between them.
If the test passes, . Fix an open sector from to with midpoint . If a rectangle has , then , since is a closed cone bounded by critical directions, and all of is covered near . Otherwise a disk has , so on all of . By the germ checks at and , each end of is covered by a rectangle with , which covers the sector, or by a disk with (or ), which by continuity has for some on a closed sub-sector next to that end, and so covers the points there with . The rest of is a closed sub-sector on which , covered for . Each critical direction is covered on its ray by a rectangle with or by a disk with . There are finitely many sectors and directions, so some works for all, and .
If a check fails, . (i) If no member covers the midpoint of a sector, consider for small . It is in no rectangle, since , and in no disk, since for a non-critical , so and . (ii) If the ray of a critical direction is not covered, is in no rectangle, and for each disk , so . (iii) If the germ on the side of at is not covered, let for small . Its direction lies in the open sector between and . A rectangle that holds for arbitrarily small has , hence , since membership in is constant on the open sector, and , since is closed; no such rectangle exists. A disk with misses for small . A disk with holds only if , which fails for small . No disk has , by assumption. In each case points in no member come arbitrarily close to .
Lemma 4 (no positive local minimum). For let . No point with is a local minimum of . Hence .
Proof. Let be a nearest point of to . The points , , are at distance from . The set is open, as is continuous and , and it is contained in the set ; a point with has points with arbitrarily close, so it is not interior.
Theorem. For every point with rational coordinates, CLASSIFY returns in, on or out as is in the interior, on the boundary or outside of , and SHRINK-CLASSIFY does the same for the regularized shrink . Every decision is exact.
Proof. Grow. By Lemma 2, . If , it is interior to , and line L6 returns in. If , it is inside its edge's slab, or it is a vertex and inside its disk, because , so L6 returns in, and it is indeed interior. If , a neighborhood of misses the closed set , so is interior to exactly when it is interior to . 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 lies in exactly when and , because for the distance to the closure of the complement equals . By Lemma 4 and Lemma 2, , so . If , then , and L10 returns out. Let . If , then , so has a neighborhood in and is interior to ; CLASSIFY returns out and L12 returns in. If , a neighborhood of misses , so ; CLASSIFY returns in and L12 returns out. Otherwise is on the boundary of . Since , , so points of come arbitrarily close to and . Each member is the closure of its interior, so points of , which are not in , also come arbitrarily close, and ; CLASSIFY returns on, by Lemma 3, and so does L12.
Exactness. The coordinates, , the corners of the slabs and the centers of the disks are rational; the tests compare coordinates, squared distances with , and signs of dot and cross products of rational vectors.
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 rectangles, the grid has cells, and classifying a cell against the tree costs , so line L1 costs . The boundary has grid edges, so lines L3 and L4 add members, and GROW costs time and space. A query costs to test the members and, when members hold the point on their boundary, to sort the directions and for the sector and germ checks. In three dimensions the number of members is the number of faces, edges and vertices of , 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 .
- 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 , 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 touching two faces; filleting by 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. , 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 shrinks to a segment and a square of side 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 minus with , the point lies on the offset line of the bottom edge and on the circle around the reflex corner . 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 is on the shrunk solid. A test that only looks at sectors calls it out.
- Rounding. The decisions compare a squared distance with ; a point at distance exactly 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.
# 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 and , 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
- 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)
- 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
- 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.
| 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 B7AHTM Edit this page History Report an error Markdown