Data structurecore
Sweep representation of solids
Also called swept solid representation, extrusion and revolution solids.
Represents a solid by a planar profile and a motion, as in extrusions and revolutions, and decides membership as a union over the sweep parameter.
- Time
- O(n) worst
- Space
- Θ(n) extra
- Where
- n = the number of vertices of the profile polygon
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
A sweep representation describes a solid by a set and a motion , : the solid is every point that occupies at some time. The two common cases are the extrusion, where a plane profile moves along a straight vector, and the revolution, where a profile in a half-plane turns a full circle about an axis. A shaft, a washer, a bolt head and a pocket outline are all of this kind, and every mechanical CAD system starts a part from such sweeps. The representation is very small and close to the way people draw, but it is not closed under Boolean operations: the union of two extrusions in different directions is not an extrusion. So a modeler stores a sweep as a primitive of a CSG tree or converts it to a B-rep. This page gives the data structure for extrusions and full revolutions of a simple polygon, and an exact classification of a point as inside, on the boundary of or outside the solid.
In plain words
Draw a shape on paper, then imagine pulling it straight up out of the paper, maybe at a slant. The paper shape leaves a trail, and the trail is a solid. That is an extrusion. Or stand the drawing up next to a pole and spin it once around the pole, like a lathe. The trail is a round solid, such as a ring or a cup. That is a revolution.
To ask if a point is in the trail, ask the reverse question: where was the drawing when it passed through this point? For an extrusion, the height of the point gives the moment, so slide the point back and test it against the drawing. For a revolution, turn the point back into the plane of the drawing and test it there. A point on the pole needs one more look.
The abstract type
A sweep is a pair , where is a bounded set and is a rigid motion or an affine map for each in a parameter interval . Its solid is the union over the parameter:
The general problem of computing this union for any solid and any path is the swept volume problem. This page uses the two cases that Requicha's survey of 1980 calls translational and rotational sweeps:
- Extrusion. is a simple polygon in the plane , is a vector with , and . The solid is a prism, upright if and slanted if not.
- Revolution. is a simple polygon in the half-plane , placed in space as the half-plane , . and turns by about the axis. The solid is the set of points with .
The operations are CLASSIFY(, ), which returns IN, ON or OUT for a point with rational coordinates, VOLUME(), and CHECK(), which tests that the stored data give an r-set.
Representation
An extrusion stores the vertex list of , in either orientation, and the three numbers of . A revolution stores the vertex list of in coordinates. All coordinates are integers or fractions, so that every test below is exact.
The representation is valid, that is the solid is an r-set, under these conditions, which CHECK tests in time:
- is a simple polygon: at least three vertices, nonzero area, and no two edges that meet except neighbours at their common vertex.
- For an extrusion, . If , the profile slides in its own plane and the result is flat, with no volume.
- For a revolution, every vertex has . A profile that crosses the axis sweeps some points twice, and the part on the far side is not a mirror image of the near side, so the stored data do not describe the solid that the user drew.
The representation is unambiguous: a pair or a profile gives one solid. It is not unique: the same prism is the extrusion of its bottom face along or of its top face along , and the same polygon has many vertex lists. In a scheme that also allows curved profiles, a cylinder is the extrusion of a disk and also the revolution of a rectangle.
Operations
The point has rational coordinates. CLASSIFY-PROFILE(, ) is the classification of a point of the plane against a closed polygon as IN, ON or OUT, as on the point in polygon page, with the even-odd crossing rule for IN and OUT and an exact test of whether lies on an edge.
CLASSIFY-EXTRUSION(X, d, p)- 1
t ← p_z / d_z ▷ the only time at which the plane of X passes through p - 2
if t < 0 or t > 1 then return OUT - 3
q ← (p_x − t·d_x, p_y − t·d_y) ▷ p moved back to time 0 - 4
c ← CLASSIFY-PROFILE(X, q) - 5
if c ≠ OUT and (t = 0 or t = 1) then return ON ▷ bottom or top face - 6
return c CLASSIFY-REVOLUTION(X, p)- 7
s ← p_x² + p_y² ▷ the square of the distance to the axis - 8
c ← CLASSIFY-PROFILE(X, (√s, p_z)), comparing √s with each rational number by squares - 9
if s > 0 or c = OUT then return c - 10
if the edges of X on the axis r = 0 contain (0, p_z) and reach above and below it then return IN - 11
return ON
Line L8 never computes . The crossing rule needs only two kinds of test: whether the point is left or right of the crossing of an edge with the line , and whether it lies on a horizontal edge between two rational ends. Both compare with a rational number , and holds exactly when and . So all signs are computed with integers and fractions, as the orientation test page asks for every geometric predicate.
The volumes follow from Cavalieri's principle and from Pappus's centroid theorem:
VOLUME(S)V1 if S is an extrusion then return |area(X)| · |d_z|V2 m ← |Σ_i (r_i + r_{i+1}) (r_i z_{i+1} − r_{i+1} z_i)| / 6 ▷ the first moment of X about the axisV3 return 2π · m
Here are the vertices of in order, with indices taken modulo . Line V2 is the polygon form of ; Pappus's theorem says that the volume of the revolution is times this moment, the area of times the length of the circle traced by its centroid.
Example
Take the square with corners and the slanted vector . The prism has volume .
| L1: | L3: | L4: | result | |
|---|---|---|---|---|
| IN | IN | |||
| ON | ON at L5 | |||
| OUT | OUT | |||
| IN | ON at L5, bottom face | |||
| OUT at L2 |
Now revolve two profiles: the rectangle with , , which gives a ring, and the rectangle with , , which gives a cylinder.
| profile | L7: | L8: | result | |
|---|---|---|---|---|
| IN, since | IN | |||
| ON, on the edge | ON | |||
| OUT | OUT | |||
| ON, on the edge | IN at L10 | |||
| ON, at a corner | ON at L11 | |||
| ON, on the top edge, | ON | |||
| OUT, since | OUT |
The point is on the boundary of the profile but in the interior of the cylinder: the edge on the axis is glued to itself by the full turn. That is why lines L10 and L11 exist. For the volumes, V2 gives for , so the ring has volume , which is . For it gives and the volume . The triangle with corners revolves to a cone of volume .
Correctness
By the definition of the sweep, is in the solid exactly when some parameter value takes back into . For an extrusion, lies in the plane only for , so there is one candidate time, and lines L1 to L4 test it. The map is an affine bijection from onto the solid, and an affine bijection keeps interiors, so is interior exactly when is interior to and . This gives line L5. For a revolution, the turn that brings into the half-plane of brings it to , for any angle if is on the axis. Off the axis, the map from to space is a local diffeomorphism, so interior and boundary points of give interior and boundary points of the solid. On the axis, a small ball around is in the solid exactly when a small half-disk around is in , which is the test of line L10. The full proof is in the proof file.
The tests check CLASSIFY against the definition. The oracle takes a finite sample of the sweep parameter, the times for extrusions and 20 rational rotations from Pythagorean triples and quarter turns for revolutions, and tests whether is in for some sample, with a winding number test that is independent of the crossing rule of the code. The test points are built so that their own parameter is in the sample, so the sampled union gives the exact answer for them. IN and ON are checked by small probes around the point in all lattice directions up to 8, at distance , and by probes along or along the circle. Points with an irrational radius are checked against floating-point classification when they are more than from the profile boundary, and the volumes against a grid count.
Proof: Point classification against extrusions and full revolutions of a simple polygon is exactfull
We use the pseudocode of the page. is a closed region bounded by a simple polygon with rational vertices, and CLASSIFY-PROFILE(, ) returns IN for , ON for and OUT otherwise. This is the correctness of the crossing rule with an exact on-edge test, proved on the point in polygon page; the only new point is that the first coordinate may be , which Lemma 4 handles. Interior and boundary are taken in for and in for the solid.
Lemma 1 (membership is a union over the parameter). For any set , any family of bijections of space and any parameter set , exactly when for some .
Proof. means for some , that is . A point is in a union exactly when it is in one of the sets.
Lemma 2 (extrusion). Let and . Then exactly when and . Further, exactly when and .
Proof. By Lemma 1, exactly when for some . The third coordinate of is , which is only for , and then the first two coordinates are . For the interior, let . It is linear with determinant , so it is a homeomorphism of , and . A homeomorphism of the whole space maps the interior of a set onto the interior of its image, so . Since , the claim follows.
Lemma 3 (revolution). Let and let be the set of points with . This is the union over of the turns of about the axis. Let .
- exactly when .
- If , then exactly when .
- If , then exactly when there is such that the half-disk is in .
Proof. The turn by maps to , whose distance to the axis is . So the union is by Lemma 1, and part 1 is the definition of . For part 2, the map is a local diffeomorphism on , and near the function is continuous, open as a map onto a neighbourhood of in the open half-plane , and . If has a neighbourhood , then is an open neighbourhood of inside . If has a neighbourhood , then is a neighbourhood of inside , since is open there. For part 3, a ball of radius around a point on the axis maps under onto exactly the half-disk of radius around , so exactly when that half-disk is in .
Lemma 4 (exact comparisons with ). For rational and rational , is if , and if .
Proof. If then . If , both and are in , where is strictly increasing, so and compare as and do.
The crossing rule and the on-edge test use the first coordinate of the query point only in comparisons , , with rational : the crossing of an edge with the line is rational, since the edge has rational ends and is rational, and the ends of a horizontal edge are rational. By Lemma 4 every such comparison is exact for , so line L8 computes CLASSIFY-PROFILE(, ) exactly.
Lemma 5 (the axis test). Let be bounded by a simple polygon in and let . The half-disk condition of Lemma 3, part 3, holds exactly when the edges of on the line cover a segment for some .
Proof. Suppose the half-disk of radius is in . Then the points with are in , and they are on , since points with are arbitrarily close and not in . The boundary of is the polygon, so these points lie on edges; a segment of the line covered by finitely many edges is covered by edges that lie on the line, except for finitely many points where an edge crosses it, and closedness of the edges then covers those points too. So the edges on the axis cover the segment, with .
Conversely, suppose edges on cover . Take smaller than the distance from to every edge of the polygon that is not on the axis and does not contain . Any edge that contains and is not on the axis would leave the axis at ; but then three edges, two on the axis above and below and this one, would meet at , or one of the axis edges would cross it in its relative interior, which a simple polygon does not allow, since the axis edges already cover both sides of and a vertex of a simple polygon has exactly two edges. So inside the disk of radius , the polygon boundary is only the axis segment. The open half-disk with is then connected and misses , so it is wholly in or wholly outside . It is not outside: the axis points are in , so each has points of arbitrarily close, and those cannot have . So the half-disk, with its axis diameter, is in .
Theorem. CLASSIFY-EXTRUSION and CLASSIFY-REVOLUTION return IN for points of the interior of the solid, ON for points of its boundary and OUT for points outside it, when the representation is valid. Both stop after exact operations.
Proof. Extrusion: line L1 computes of Lemma 2, line L2 returns OUT when , and lines L3 and L4 classify . If = OUT then by Lemma 2. Otherwise , and by Lemma 2 it is interior exactly when and = IN. Line L5 returns ON when , and line L6 returns , which is IN or ON as required. Since is closed, a point of that is not interior is on its boundary.
Revolution: by the remark after Lemma 4, line L8 gives the class of against . If it is OUT, by Lemma 3, part 1. If , Lemma 3, part 2, says is interior exactly when = IN, so line L9 returns the right answer. If and OUT, then = ON, since has points with arbitrarily close. Then by Lemma 3, part 3, and Lemma 5, is interior exactly when the axis edges cover a neighbourhood of on the axis, which is the test of line L10: an edge on the axis that contains and has an end above covers a segment above it, and likewise below. Otherwise , line L11.
Each line does a constant number of operations, except L4, L8 and L10, which loop once over the edges. So both procedures stop after exact operations on numbers formed from the input coordinates.
Volumes. For an extrusion, every slice with between and is a translate of , so by Cavalieri's principle the volume is , line V1. For a revolution, the volume in cylindrical coordinates is . By Green's theorem with the field , for a counterclockwise boundary, and on the straight edge from to the integral is . Summing over the edges and rearranging gives , the same telescoping identity as in the shoelace formula for the area. Taking the absolute value makes the result independent of the orientation, line V2.
Complexity
- CLASSIFY takes time: one pass over the edges of with a constant number of exact operations per edge. The fractions stay small, since each test uses only the input coordinates and the point.
- VOLUME takes time and gives an exact rational number, times for a revolution.
- CHECK takes time with the plain test of all pairs of edges. A sweep-line test brings it to .
- The representation takes space. The B-rep of the same solid has faces for an extrusion, and for a revolution it has one face of revolution per edge of that is not on the axis.
Variants
- Partial revolution. Turn the profile by an angle less than a full turn. The classification adds a test of whether the direction of lies in the swept sector; with rational end directions this test is an exact cross product. The axis rule of line L10 then no longer applies, since the two end faces of the sector meet on the axis.
- Drafted and tapered extrusions. The profile also shrinks or grows as it moves, so is an affine map with a scale. A slice of the solid is still one scaled copy of , and the classification has the same form.
- Sweeps along a curve. The profile moves along a space curve with a moving frame, which gives a pipe or a spring. The boundary surface is a sweep surface, and self-intersection becomes the main difficulty.
- Sweeps of solids. A solid moves along a path, as a cutting tool does. This is the swept volume problem, solved by envelopes or by sampling. When the solid only translates along a straight segment, the result is the Minkowski sum of the solid and the segment.
- Surfaces of revolution. Revolving only the boundary curve gives a surface of revolution, the boundary of the solid of this page.
When to use it
Use a sweep when the shape comes from a drawing: prismatic parts, turned parts, profiles of pockets and bosses. In a feature-based or history-based modeler, each extrude or revolve step stores exactly this pair of profile and motion, and the system evaluates it to a B-rep and combines it with the rest of the part by Boolean operations. A sweep is also a good representation for direct queries on one primitive: point classification, volume and mass properties are exact and cheap. Do not use sweeps as the only representation of a whole part, since a union of sweeps is not a sweep.
Pitfalls
- Points on the axis. A point on the axis of a revolution is on the boundary of the profile but can be inside the solid. Test the edges on the axis, as lines L10 and L11 do, or the cylinder in the example has a wrong axis line.
- Profiles that cross the axis. If part of has , the revolution does not describe what the drawing shows. Reject such a profile, or cut it at the axis and keep one side.
- Flat extrusions. An extrusion with has no volume. Check before line L1 divides by it.
- Computing the radius. Computing in floating point makes points on cylindrical faces fall in or out at random. Compare squares, as line L8 does.
- Self-intersecting profiles. A profile with crossing edges gives a set that is not the closure of its interior along the crossings, and the even-odd rule gives holes the user did not draw. Run CHECK on input.
- Booleans. The union, intersection or difference of two sweeps is in general not a sweep. Store the result as a CSG tree of sweeps or as a B-rep.
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/sweep-representation/. The authors are listed in prov/QNVPYX.jsonl.
"""Sweep representations of solids: extrusions and full revolutions of a polygon.
An Extrusion holds a simple polygon X in the plane z = 0 and a vector d with
d_z != 0. Its solid is the union of X + t d over t in [0, 1].
A Revolution holds a simple polygon X in the (r, z) half-plane r >= 0. Its
solid is the union over all angles a of the polygon turned by a about the
z axis.
Both classify a point with rational coordinates as IN, ON or OUT with exact
Fraction arithmetic. The revolution never computes the radius sqrt(x^2 + y^2):
it compares its square with the square of a rational number.
"""
from __future__ import annotations
from fractions import Fraction
from typing import Callable, Sequence
IN, ON, OUT = "IN", "ON", "OUT"
Num = Fraction | int
Point2 = tuple[Fraction, Fraction]
Point3 = tuple[Fraction, Fraction, Fraction]
def _sign(v: Num) -> int:
return (v > 0) - (v < 0)
def _cross(o: Point2, a: Point2, b: Point2) -> Fraction:
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def _on_segment(p: Point2, a: Point2, b: Point2) -> bool:
return (_cross(a, b, p) == 0
and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
def _segments_meet(a: Point2, b: Point2, c: Point2, d: Point2) -> bool:
d1, d2 = _sign(_cross(a, b, c)), _sign(_cross(a, b, d))
d3, d4 = _sign(_cross(c, d, a)), _sign(_cross(c, d, b))
if d1 * d2 < 0 and d3 * d4 < 0:
return True
return (_on_segment(c, a, b) or _on_segment(d, a, b)
or _on_segment(a, c, d) or _on_segment(b, c, d))
def area2(poly: Sequence[Point2]) -> Fraction:
"""Twice the signed area of a polygon (positive if counterclockwise)."""
n = len(poly)
return sum((poly[i][0] * poly[(i + 1) % n][1] - poly[(i + 1) % n][0] * poly[i][1]
for i in range(n)), Fraction(0))
def is_simple(poly: Sequence[Point2]) -> bool:
"""True if the closed polygon has at least 3 vertices, nonzero area and no
two edges that meet except adjacent edges at their common vertex. O(n^2)."""
n = len(poly)
if n < 3 or area2(poly) == 0:
return False
for i in range(n):
a, b = poly[i], poly[(i + 1) % n]
if a == b:
return False
for j in range(i + 1, n):
c, d = poly[j], poly[(j + 1) % n]
if j == i + 1 or (i == 0 and j == n - 1):
# adjacent edges: they may share only the common vertex
shared = b if j == i + 1 else a
other = d if j == i + 1 else c
far = a if j == i + 1 else b
if _cross(far, shared, other) == 0 and \
(_on_segment(other, far, shared) or _on_segment(far, shared, other)):
return False
continue
if _segments_meet(a, b, c, d):
return False
return True
def classify_profile(poly: Sequence[Point2], cmp_u: Callable[[Fraction], int],
z: Fraction) -> str:
"""Classify the point (u, z) against the closed polygon, where u is known
only through cmp_u(q) = sign(u - q) for rational q. Crossing number with a
ray towards +u and the half-open rule on vertices. O(n)."""
inside = False
n = len(poly)
for i in range(n):
(ar, az), (br, bz) = poly[i], poly[(i + 1) % n]
if az == bz:
if z == az and cmp_u(min(ar, br)) >= 0 and cmp_u(max(ar, br)) <= 0:
return ON
continue
if min(az, bz) <= z <= max(az, bz):
rc = ar + (z - az) * (br - ar) / (bz - az)
c = cmp_u(rc)
if c == 0:
return ON
if (az > z) != (bz > z) and c < 0:
inside = not inside
return IN if inside else OUT
def cmp_rational(u: Fraction) -> Callable[[Fraction], int]:
return lambda q: _sign(u - q)
def cmp_sqrt(s: Fraction) -> Callable[[Fraction], int]:
"""sign(sqrt(s) - q) for s >= 0, exactly, by comparing s with q^2."""
def cmp(q: Fraction) -> int:
if q < 0:
return 1
return _sign(s - q * q)
return cmp
def _f(v: Num) -> Fraction:
return Fraction(v)
class Extrusion:
"""The translational sweep of a polygon X in z = 0 along the vector d.
Precondition: X is simple and d_z != 0. classify and volume take O(n) time
for n vertices; the representation takes Theta(n) space.
"""
def __init__(self, profile: Sequence[tuple[Num, Num]], d: tuple[Num, Num, Num]):
self.profile: list[Point2] = [(_f(x), _f(y)) for x, y in profile]
self.d: Point3 = (_f(d[0]), _f(d[1]), _f(d[2]))
def check_invariant(self) -> bool:
return self.d[2] != 0 and is_simple(self.profile)
def classify(self, p: tuple[Num, Num, Num]) -> str:
px, py, pz = _f(p[0]), _f(p[1]), _f(p[2])
dx, dy, dz = self.d
t = pz / dz # @line L1
if t < 0 or t > 1: # @line L2
return OUT
q = (px - t * dx, py - t * dy) # @line L3
c = classify_profile(self.profile, cmp_rational(q[0]), q[1]) # @line L4
if c != OUT and (t == 0 or t == 1): # @line L5
return ON
return c # @line L6
def volume(self) -> Fraction:
"""The exact volume: area(X) times |d_z| (Cavalieri)."""
return abs(area2(self.profile)) / 2 * abs(self.d[2])
class Revolution:
"""The full rotational sweep of a polygon X in the half-plane r >= 0 of
the (r, z) plane about the z axis.
Precondition: X is simple and every vertex has r >= 0. classify and
volume take O(n) time; the representation takes Theta(n) space.
"""
def __init__(self, profile: Sequence[tuple[Num, Num]]):
self.profile: list[Point2] = [(_f(r), _f(z)) for r, z in profile]
def check_invariant(self) -> bool:
return all(r >= 0 for r, _ in self.profile) and is_simple(self.profile)
def _axis_covers(self, z: Fraction) -> bool:
"""True if edges of X on the axis r = 0 contain (0, z) and reach both
above and below it."""
up = down = False
n = len(self.profile)
for i in range(n):
(ar, az), (br, bz) = self.profile[i], self.profile[(i + 1) % n]
if ar == 0 and br == 0 and min(az, bz) <= z <= max(az, bz):
up = up or max(az, bz) > z
down = down or min(az, bz) < z
return up and down
def classify(self, p: tuple[Num, Num, Num]) -> str:
px, py, pz = _f(p[0]), _f(p[1]), _f(p[2])
s = px * px + py * py # @line L7
c = classify_profile(self.profile, cmp_sqrt(s), pz) # @line L8
if s > 0 or c == OUT: # @line L9
return c
if self._axis_covers(pz): # @line L10
return IN
return ON # @line L11
def volume_over_pi(self) -> Fraction:
"""The exact volume divided by pi. By Pappus, V = 2 pi times the first
moment of X about the axis, and the moment of a polygon is
(1/6) sum (r_i + r_{i+1}) (r_i z_{i+1} - r_{i+1} z_i)."""
poly, n = self.profile, len(self.profile)
m = sum(((poly[i][0] + poly[(i + 1) % n][0])
* (poly[i][0] * poly[(i + 1) % n][1] - poly[(i + 1) % n][0] * poly[i][1])
for i in range(n)), Fraction(0)) / 6
return 2 * abs(m)
test_sweep_representation.py 316 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sweep-representation/. The authors are listed in prov/QNVPYX.jsonl.
import math
import random
import unittest
from fractions import Fraction as F
from sweep_representation import IN, ON, OUT, Extrusion, Revolution, area2, is_simple
EPS = F(1, 1000)
# ---------------------------------------------------------------------------
# Independent oracles. The profile test is a winding number, not the crossing
# number of the implementation, and the sweep is the plain union of M(t) X
# over a finite sample of the parameter t.
# ---------------------------------------------------------------------------
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def in_closed_polygon(poly, q):
"""Winding number with an exact on-edge test. True for points of the
closed polygon."""
n = len(poly)
w = 0
for i in range(n):
a, b = poly[i], poly[(i + 1) % n]
if cross(a, b, q) == 0 and min(a[0], b[0]) <= q[0] <= max(a[0], b[0]) \
and min(a[1], b[1]) <= q[1] <= max(a[1], b[1]):
return True
if a[1] <= q[1]:
if b[1] > q[1] and cross(a, b, q) > 0:
w += 1
elif b[1] <= q[1] and cross(a, b, q) < 0:
w -= 1
return w != 0
def extrusion_member(profile, d, p, ts):
"""p is in the union of X + t d over the sampled t."""
for t in ts:
if p[2] == t * d[2] and in_closed_polygon(profile, (p[0] - t * d[0], p[1] - t * d[1])):
return True
return False
def rot(c, s, p):
return (c * p[0] - s * p[1], s * p[0] + c * p[1], p[2])
def revolution_member(profile, p, rots):
"""p is in the union of R(a) X over the sampled rotations R(a), where X
sits in the half-plane y = 0, x >= 0."""
for c, s in rots:
x, y, z = rot(c, -s, p) # R(a)^-1 p
if y == 0 and x >= 0 and in_closed_polygon(profile, (x, z)):
return True
return False
def pythagorean_rotations(limit):
"""Rational rotations (cos, sin) = ((a^2 - b^2)/h, 2ab/h), h = a^2 + b^2,
together with their quarter turns and their negatives."""
out = {(F(1), F(0))}
for a in range(1, limit + 1):
for b in range(0, limit + 1):
h = a * a + b * b
c, s = F(a * a - b * b, h), F(2 * a * b, h)
for cc, ss in ((c, s), (-s, c), (-c, -s), (s, -c)):
out.add((cc, ss))
return sorted(out)
ROTS = pythagorean_rotations(3)
def primitive_directions(m):
return [(a, b) for a in range(-m, m + 1) for b in range(-m, m + 1)
if (a, b) != (0, 0) and math.gcd(a, b) == 1]
DIRS = primitive_directions(8)
def random_star_polygon(rng, lo=0, hi=4):
"""A simple lattice polygon: lattice points sorted by angle around a
centre that is on no line through two lattice points of the box."""
while True:
k = rng.randrange(3, 8)
pts = list({(rng.randrange(lo, hi + 1), rng.randrange(lo, hi + 1)) for _ in range(k)})
if len(pts) < 3:
continue
cx, cy = sum(p[0] for p in pts) / len(pts) + 0.0137, sum(p[1] for p in pts) / len(pts) + 0.0071
pts.sort(key=lambda p: math.atan2(p[1] - cy, p[0] - cx))
poly = [(F(x), F(y)) for x, y in pts]
if is_simple(poly):
if area2(poly) < 0:
poly.reverse()
return poly
def random_rational(rng, lo, hi, den=4):
return F(rng.randrange(lo * den, hi * den + 1), den)
class TestHandCases(unittest.TestCase):
def test_oblique_prism(self):
e = Extrusion([(0, 0), (2, 0), (2, 2), (0, 2)], (1, 0, 3))
self.assertTrue(e.check_invariant())
self.assertEqual(e.classify((2, 1, F(3, 2))), IN)
self.assertEqual(e.classify((3, 1, 3)), ON)
self.assertEqual(e.classify((F(1, 5), 1, F(3, 2))), OUT)
self.assertEqual(e.classify((1, 1, 0)), ON)
self.assertEqual(e.classify((1, 1, -1)), OUT)
self.assertEqual(e.volume(), 12)
def test_ring_and_cylinder(self):
ring = Revolution([(1, 0), (2, 0), (2, 1), (1, 1)])
self.assertTrue(ring.check_invariant())
self.assertEqual(ring.classify((1, 1, F(1, 2))), IN) # radius sqrt 2
self.assertEqual(ring.classify((0, 0, F(1, 2))), OUT)
self.assertEqual(ring.classify((F(3, 5), F(4, 5), F(1, 2))), ON) # radius 1
self.assertEqual(ring.volume_over_pi(), 3)
cyl = Revolution([(0, 0), (2, 0), (2, 1), (0, 1)])
self.assertEqual(cyl.classify((0, 0, F(1, 2))), IN) # axis point
self.assertEqual(cyl.classify((0, 0, 1)), ON)
self.assertEqual(cyl.classify((1, 1, 1)), ON) # top face, radius sqrt 2
self.assertEqual(cyl.classify((1, 1, F(1, 2))), IN)
self.assertEqual(cyl.classify((2, 1, F(1, 2))), OUT) # radius sqrt 5
self.assertEqual(cyl.volume_over_pi(), 4)
def test_cone_apex(self):
cone = Revolution([(0, 0), (1, 0), (0, 1)])
self.assertEqual(cone.classify((0, 0, 1)), ON)
self.assertEqual(cone.classify((0, 0, F(1, 2))), IN)
self.assertEqual(cone.volume_over_pi(), F(1, 3))
def test_invalid(self):
self.assertFalse(Extrusion([(0, 0), (1, 0), (0, 1)], (1, 1, 0)).check_invariant())
self.assertFalse(Revolution([(-1, 0), (1, 0), (0, 1)]).check_invariant())
self.assertFalse(Revolution([(0, 0), (2, 2), (2, 0), (0, 2)]).check_invariant())
class TestExtrusionAgainstSampling(unittest.TestCase):
def test_membership(self):
rng = random.Random(11)
n = 20
for _ in range(500):
poly = random_star_polygon(rng)
d = (rng.randrange(-2, 3), rng.randrange(-2, 3), rng.choice([-3, -2, -1, 1, 2, 3]))
d = tuple(F(v) for v in d)
e = Extrusion(poly, d)
ts = [F(k, n) for k in range(-2, n + 3)]
t = rng.choice(ts)
p = (random_rational(rng, -3, 7), random_rational(rng, -3, 7), t * d[2])
want = extrusion_member(poly, d, p, [x for x in ts if 0 <= x <= 1])
self.assertEqual(e.classify(p) != OUT, want, (poly, d, p))
def test_in_and_on_by_probes(self):
rng = random.Random(12)
n = 4
for _ in range(300):
poly = random_star_polygon(rng)
d = (F(rng.randrange(-2, 3)), F(rng.randrange(-2, 3)), F(rng.choice([1, 2, 3])))
e = Extrusion(poly, d)
t = F(rng.randrange(0, n + 1), n)
q = (random_rational(rng, 0, 4), random_rational(rng, 0, 4))
p = (q[0] + t * d[0], q[1] + t * d[1], t * d[2])
got = e.classify(p)
ts = [t, t - EPS, t + EPS]
ts = [x for x in ts if 0 <= x <= 1]
if not extrusion_member(poly, d, p, ts):
self.assertEqual(got, OUT)
continue
probes = [(p[0] + EPS * a, p[1] + EPS * b, p[2]) for a, b in DIRS]
probes += [tuple(p[i] + sg * EPS * d[i] for i in range(3)) for sg in (1, -1)]
inside = all(extrusion_member(poly, d, x, ts) for x in probes)
self.assertEqual(got, IN if inside else ON, (poly, d, p))
def test_sweep_of_profile_points(self):
"""Every point x + t d with x in X and t in [0, 1] is in the solid."""
rng = random.Random(13)
for _ in range(500):
poly = random_star_polygon(rng)
d = (F(rng.randrange(-2, 3)), F(rng.randrange(-2, 3)), F(rng.choice([-2, -1, 1, 2])))
e = Extrusion(poly, d)
x = rng.choice(poly) if rng.random() < 0.3 else \
(random_rational(rng, 0, 4, 7), random_rational(rng, 0, 4, 7))
if not in_closed_polygon(poly, x):
continue
t = F(rng.randrange(0, 1001), 1000)
p = (x[0] + t * d[0], x[1] + t * d[1], t * d[2])
self.assertNotEqual(e.classify(p), OUT)
def test_volume_against_grid(self):
rng = random.Random(14)
for _ in range(3):
poly = random_star_polygon(rng)
d = (F(1), F(0), F(2))
e = Extrusion(poly, d)
m = 8
count = 0
for i in range(m):
for j in range(5 * m):
for k in range(5 * m):
p = (F(2 * j + 1, 2 * m) - 0, F(2 * k + 1, 2 * m), F(2 * i + 1, m))
if e.classify(p) != OUT:
count += 1
est = F(count, m * m * m) * 2
self.assertLess(abs(float(est - e.volume())), 0.6)
class TestRevolutionAgainstSampling(unittest.TestCase):
def profile(self, rng):
poly = random_star_polygon(rng)
if rng.random() < 0.5:
shift = min(r for r, _ in poly)
poly = [(r - shift, z) for r, z in poly]
return poly
def test_membership(self):
rng = random.Random(21)
for _ in range(500):
poly = self.profile(rng)
v = Revolution(poly)
self.assertTrue(v.check_invariant())
c, s = rng.choice(ROTS)
base = (random_rational(rng, 0, 5), F(0), random_rational(rng, -1, 5))
if rng.random() < 0.1:
base = (F(0), F(0), base[2])
p = rot(c, s, base)
want = revolution_member(poly, p, ROTS)
self.assertEqual(v.classify(p) != OUT, want, (poly, p))
def test_in_and_on_by_probes(self):
rng = random.Random(22)
tiny = (F(1000 * 1000 - 1, 1000 * 1000 + 1), F(2 * 1000, 1000 * 1000 + 1))
for _ in range(300):
poly = self.profile(rng)
v = Revolution(poly)
c, s = rng.choice(ROTS)
r = random_rational(rng, 0, 4) if rng.random() < 0.8 else F(0)
z = random_rational(rng, 0, 4)
p = rot(c, s, (r, F(0), z))
got = v.classify(p)
rots = list(ROTS)
# the turns that bring the probes back into the profile half-plane
rots += [(c * tiny[0] - s * tiny[1], s * tiny[0] + c * tiny[1]),
(c * tiny[0] + s * tiny[1], s * tiny[0] - c * tiny[1])]
if not revolution_member(poly, p, rots):
self.assertEqual(got, OUT)
continue
# probes in the half-plane of p, and two small turns of p
probes = [rot(c, s, (r + EPS * a, F(0), z + EPS * b)) for a, b in DIRS]
probes += [rot(tiny[0], tiny[1], p), rot(tiny[0], -tiny[1], p)]
inside = all(revolution_member(poly, x, rots) for x in probes)
self.assertEqual(got, IN if inside else ON, (poly, p))
def test_irrational_radius_against_floats(self):
rng = random.Random(23)
checked = 0
for _ in range(500):
poly = self.profile(rng)
v = Revolution(poly)
p = (random_rational(rng, -4, 4, 3), random_rational(rng, -4, 4, 3),
random_rational(rng, 0, 4, 3))
r = math.hypot(float(p[0]), float(p[1]))
z = float(p[2])
q = (r, z)
fpoly = [(float(a), float(b)) for a, b in poly]
# distance from (r, z) to the profile boundary, in floats
dist = min(seg_dist(q, fpoly[i], fpoly[(i + 1) % len(fpoly)]) for i in range(len(fpoly)))
if dist < 1e-6:
continue
want = IN if in_closed_polygon(fpoly, q) else OUT
self.assertEqual(v.classify(p), want, (poly, p))
checked += 1
self.assertGreater(checked, 400)
def test_volume_against_grid(self):
rng = random.Random(24)
for _ in range(5):
poly = self.profile(rng)
v = Revolution(poly)
m = 40
total = 0.0
for i in range(4 * m):
for j in range(4 * m):
rr, zz = (i + 0.5) / m, (j + 0.5) / m
if in_closed_polygon([(float(a), float(b)) for a, b in poly], (rr, zz)):
total += 2 * math.pi * rr / (m * m)
self.assertLess(abs(total - float(v.volume_over_pi()) * math.pi), 0.5)
def test_rotation_invariance(self):
rng = random.Random(25)
for _ in range(500):
poly = self.profile(rng)
v = Revolution(poly)
p = (random_rational(rng, -4, 4, 2), random_rational(rng, -4, 4, 2),
random_rational(rng, 0, 4, 2))
c, s = rng.choice(ROTS)
self.assertEqual(v.classify(p), v.classify(rot(c, s, p)))
def seg_dist(q, a, b):
ax, ay = b[0] - a[0], b[1] - a[1]
t = ((q[0] - a[0]) * ax + (q[1] - a[1]) * ay) / (ax * ax + ay * ay)
t = max(0.0, min(1.0, t))
return math.hypot(q[0] - a[0] - t * ax, q[1] - a[1] - t * ay)
if __name__ == "__main__":
unittest.main()
History
Solids made by moving a profile are as old as drafting, and the volume rule for revolutions is Pappus's centroid theorem from late antiquity, found again by Guldin in the seventeenth century. In solid modeling, Requicha's survey of 1980 listed translational and rotational sweeps as one of the representation schemes, next to CSG, cell decompositions and boundary representations, and noted that their domain is small. The modelers of the 1980s used extrusions and revolutions as the main way to turn drawings into solids, and kept them as primitives or converted them to B-reps. General sweeps of solids along paths, needed for machining and motion studies, were studied with envelope theory by Wang and Wang in 1986 and by Martin and Stephenson in 1990.
References
- Aristides A. G. Requicha, Representations for rigid solids, theory, methods, and systems, ACM Computing Surveys 12(4), 437 to 464, 1980, the section on sweep representations, translational and rotational sweeps, and their limited domain
- Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, the chapter on representation schemes, the part on sweeping
- Ralph R. Martin and P. C. Stephenson, Sweeping of three-dimensional objects, Computer-Aided Design 22(4), 223 to 234, 1990, the sweep of a solid along a general path, built from the sweeps of its faces and their silhouette curves
- W. P. Wang and K. K. Wang, Geometric modeling for swept volume of moving solids, IEEE Computer Graphics and Applications 6(12), 1986, 8 to 17, the envelope of a moving solid and the self-intersection problems of general sweeps
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 | W4 complete |
|
Tag QNVPYX Edit this page History Report an error Markdown