Algorithmadvanced
Offset trimming
Also called offset self-intersection removal.
Removes the loops of an offset curve, where the distance exceeds the radius of curvature or distant parts come close, by cutting it at its self-intersections and keeping the parts at full distance.
- Solves
- Curve offsetting
- Time
- Θ(m log m + K + (I + 1) n) worstΘ(m log m + n) best
- Space
- Θ(m + I) extra
- Where
- I = the number of crossings; K = the number of segment pairs whose x ranges overlap; m = the number of samples of the offset; n = the number of control points
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- In Kwon Lee, Myung Soo Kim, Gershon Elber, 1996
Offset trimming turns the raw offset of a curve, the point set , into the curve that is really at distance from . Where is larger than the radius of curvature on the concave side, the raw offset has cusps and small loops, the swallowtails, and where two distant parts of come closer than , the two offsets cross. In both cases some parts of the raw offset are closer to than . The algorithm samples the raw offset as a polyline, finds all its self-crossings with a sweep and exact orientation tests, cuts it at the crossings, and keeps the pieces whose middle point is at distance from . It is the trimming step of curve offsetting, and the core of tool path computation for pockets.
The model is the real RAM for the geometry. The crossing tests are decided exactly on the floating point samples, in rational arithmetic; the distances are computed in floating point and compared with a tolerance.
In plain words
Roll a coin of radius along the inside of a closed wire, always touching it, and mark where its center goes. Most of the time the center draws a clean curve parallel to the wire. But where the wire bends more sharply than the coin, the coin cannot fit into the corner, and the naive rule "go a distance straight in from the wire" makes the mark run backwards in a little loop. Where the wire pinches into a narrow neck, the marks from the two sides pass each other. In both places, the marks that went too far are closer to the wire than the coin's radius, so the coin could never have been there. The algorithm draws all the naive marks, finds where the drawing crosses itself, cuts it there, and throws away every piece whose middle is too close to the wire.
The problem
The input is a closed planar curve , here a closed uniform cubic B-spline with control points and parameter , a signed distance , a number of samples and a tolerance. This page uses the left unit normal , which points into the interior of a counterclockwise curve, and the signed curvature , positive where the curve turns left. So offsets a counterclockwise curve inward. The mean curvature of surfaces does not appear.
The raw offset is ; see offset curve. It satisfies , so it has a cusp where and runs backwards where . The trimmed offset is the set of points of at distance exactly from :
The output is the pieces of the sampled offset, each marked kept or removed, such that the kept pieces approximate . For a closed curve, is the boundary of the region shrunk or grown by , the boundary of a Minkowski sum or difference with a disc.
The algorithm
OFFSET-TRIM(P_0, ..., P_(n−1), d, m, tol)- 1
q_k ← C(t_k) + d N(t_k) for t_k = k n / m, k = 0, ..., m − 1 ▷ de Boor for C and C' - 2
X ← the pairs of non-adjacent segments of the closed polyline q that meet ▷ sweep in x, exact tests - 3
for each pair (i, j) in X do - 4
add the meeting point as a cut on segment i and as a cut on segment j - 5
sort the cuts along the polyline - 6
for each piece between two consecutive cuts, cyclically, do - 7
u ← the middle parameter of the piece; δ ← dist(γ(u), C) - 8
keep ← (δ ≥ |d| − tol) - 9
output the piece and keep - 10
return the pieces
Sampling (line L1). The de Boor algorithm gives , and is the quadratic B-spline with control points on the same knots. The normal is .
Crossings (line L2). Sort the segments by their least coordinate and sweep from left to right. Keep an active list of the segments whose range reaches the current one, drop the ones that end before it, and test the new segment against the rest. The test is the orientation test: segments and meet if and only if and . Each sign is computed in exact rational arithmetic from the floating point coordinates, because near a crossing of almost parallel branches the cross product is a difference of nearly equal numbers, and a floating point sign can be wrong by catastrophic cancellation. A wrong sign here loses a crossing, and a lost crossing merges a kept piece with a removed one. Two collinear overlapping segments, or two adjacent segments that fold back on each other, are reported as degenerate input; another avoids them.
Cutting (lines L3 to L5). For a crossing of segments and , the exact ratios and of the meeting point along both segments are rationals, and the point is computed once and used for both cuts, so the pieces that meet there share the same end point. Sorting the cuts by (segment, ratio) orders them along the polyline.
Classifying (lines L6 to L8). For each piece, line L7 evaluates the exact offset at the middle parameter, not the polyline, and computes its distance to by dense sampling of and Newton steps on at the local minima. The piece is kept when this distance is up to the tolerance; removed pieces are at a distance clearly less than .
Example
Take the closed uniform cubic B-spline with the eight control points
a counterclockwise dumbbell with two lobes and a neck. At the middle of the neck, , the curve is at , so the neck is wide. The curvature is largest, about , at the four corners of the lobes, where the radius of curvature is about . Offset inward by with samples.
Since , the raw offset has a swallowtail at each of the four corners, with its crossing at . Since is more than half the neck, the offsets of the top and the bottom cross at . The sweep finds these crossings, the same that the brute force test of all pairs finds, and the cuts give pieces:
| pieces | length each | distance of the middle point to | decision |
|---|---|---|---|
| 4 swallowtail loops | removed | ||
| 2 pieces across the neck | removed | ||
| 2 end pieces, at | kept | ||
| 4 side pieces | kept |
The piece across the neck has its middle at : it is the bottom offset, above the bottom at , and it is only below the top. The six kept pieces close up into two loops, one in each lobe, with total length . So the inward offset of the dumbbell at this distance has two components, as the region shrunk by a disc of radius falls apart at the neck.
Correctness
The proof file below has two parts.
Part A is exact and about the polyline. The orientation test with exact signs decides whether two segments meet. The sweep reports exactly the pairs of non-adjacent segments that meet: if two segments meet, their ranges overlap, so the earlier one is still active when the later one starts. After cutting at all reported points, two pieces share a point only at a cut.
Part B is about the exact offset of a simple closed curve, and it is the reason a single test point per piece is enough. Let . Assume that is not the radius of curvature at a vertex of . Then every point where changes from to negative is a self-intersection of . The proof looks at the disc of radius about the point: if it touches twice, both contacts are on the offset side by the Jordan curve theorem, which makes the point a double point of ; if it touches once, the second and third derivatives of the squared distance show that stays nearby. So on each arc between consecutive self-intersections, is identically or negative throughout.
The two parts meet in the sampling: the crossings of the polyline approximate the self-intersections of , and the decision is taken on itself. How fine must be is measured, not proved.
Proof: The sweep finds exactly the meeting segment pairs, and for the exact offset of a closed curve one test point decides each piecefull
We use the pseudocode of the page. There are two parts. Part A is about the polyline that the algorithm computes, and it is exact: the sweep of line L2 reports exactly the pairs of non-adjacent segments that meet, and the cuts of lines L3 to L5 split the polyline into pieces that meet only at cut points. Part B is about the exact offset curve, and it justifies lines L7 and L8: between two consecutive self-intersections, a point of the offset is either everywhere at distance from the curve or everywhere closer. How well the polyline follows the exact offset is a matter of sampling and is measured, not proved, on the page.
Part A: the polyline
Let be the samples of line L1 and let segment join and , indices modulo . Two segments are adjacent if their indices differ by modulo .
Lemma A1 (the predicate). For segments and of positive length that are not contained in one line, the closed segments meet if and only if and , where is the sign of the cross product. The implementation evaluates the signs in exact rational arithmetic on the floating point coordinates, so each sign is the true sign for the sampled points.
Proof. If the segments meet at a point , then lies on the line and on the segment , so and are not strictly on the same side of the line , which is the first condition, and symmetrically the second. Conversely, if and are not parallel, the lines meet in one point , and and are the signs of the values at and of an affine function that vanishes on the line and is linear in along . The second condition says that this function does not have the same strict sign at both ends, so , and the first condition gives in the same way. If they are parallel and on different lines, then and are strictly on the same side of the line and the first condition fails. The rounding claim holds because every float is a rational number and Fraction arithmetic is exact.
Segments of length zero are tested as points against the other segment, and pairs that lie on one line and overlap are reported as degenerate input; these are the remaining cases.
Lemma A2 (the sweep). The list returned in line L2 is exactly the set of pairs of non-adjacent segments that meet.
Proof. Every reported pair passed the test of Lemma A1, so it meets. Conversely, let segments and meet, with before in the order of their least coordinate . They share a point, so their ranges overlap: , where is the greatest coordinate. A segment is dropped from the active list only while some segment with is processed. All segments processed before have , and so does , so is still active when is processed. Their ranges overlap too, so the filter does not skip the pair, and the test of Lemma A1 reports it.
Lemma A3 (the pieces). Cut the closed polyline at every point where one of its segments meets a non-adjacent one, as in lines L3 to L5. If two different pieces, or two non-consecutive parts of one piece, share a point, then this point is a cut point and an end point of the pieces involved.
Proof. Two parts of the polyline that share a point lie on segments and . If and are not adjacent, Lemma A2 reports the pair, and line L4 adds as a cut on segment and as a cut on segment . So is a cut point, and the pieces end there. If or the segments are adjacent, then either is the common vertex, where the polyline passes once, or the two segments fold back onto each other along a line. The implementation checks every vertex for this fold exactly and rejects it as degenerate input.
Part B: the exact offset
Let , in a circle , be a closed curve of class that is regular and simple, and orient it counterclockwise. Let , let be the left unit normal, which points into the interior, and let be the signed curvature, so that and where the curve turns left. The mean curvature of surfaces does not appear. For , the raw offset is , and
Since is at distance from , everywhere. The trimmed offset is .
We use one fact that we do not prove, the local form of the Jordan curve theorem for smooth curves: has two components, the interior and the exterior, and for every the points lie in the interior and in the exterior for all small (do Carmo, Section 1-7).
Assumption (G). There is no with and . That is, is not the radius of curvature at a vertex of on the side of the offset. This holds for all except finitely many values when has finitely many vertices.
Lemma B1. Assume (G). If is a boundary point of the open set , then for some .
Proof. Since is continuous and is a boundary point of an open set, . Let , and let be the open disc of radius about . Then does not meet , and lies on the boundary circle of . Let
Case 1: has a second nearest point , . Then and minimizes , so , and . The open disc is connected and does not meet , so it lies in one component of . It contains and for small . By the fact above, these lie in the same component only if the sign is . So .
Case 2: is the only nearest point of . At we have , so
If , then for near , so , which is false. If , then by (G) . In an arc length parameter, and , so . Then changes sign at , so again , which is false. So . By continuity, there is an interval around with on . For , is strictly convex on with critical point , so for all .
Now take with , and let be a nearest point of , so . A subsequence of converges to some with , so is a nearest point of , and . For large , both and lie in , and , a contradiction. So Case 2 cannot occur.
Theorem B2. Assume (G), and assume that has finitely many self-intersection parameters, that is, parameters with for some . On each open arc between two consecutive such parameters, either on all of or on all of . So the trimmed offset is the union of the closures of the arcs on which vanishes at one point, and one test point per arc decides it.
Proof. The set is open in . By Lemma B1, it has no boundary point inside , so it is also closed in . Since is connected, it is empty or all of .
Lines L3 to L6 cut the sampled offset at the crossing points, which approximate the self-intersections of , line L7 evaluates itself at the middle parameter of each piece, and line L8 keeps the piece when its distance is up to the tolerance. By Theorem B2 this is the right decision for the exact curve, for every piece whose cuts are close to the self-intersections of .
Complexity
Sampling costs , since each de Boor evaluation of a cubic costs . Sorting costs . The sweep tests each pair of segments whose ranges overlap once, pairs, at each, since the rationals come from floats of bounded size. So line L2 costs . For a curve that is long in , is close to , but for a curve with many segments over the same range, can be close to . With crossings there are pieces, or one, and each distance costs for the dense sampling of with a fixed number of samples per span. The total is , with extra space .
The Bentley-Ottmann algorithm finds the crossings in time, independent of , and is the better choice for long polylines with many overlapping ranges. The sweep of this page is simpler and robust with exact tests, and it is fast for the typical offset, which is made of a few monotone runs.
Properties
- Exact topology of the polyline. All crossing decisions are exact for the sampled points, so the cut set is exactly that of the polyline, with no missed or doubled crossings.
- Closed output. For a closed curve, in the generic case two kept and two removed piece ends meet at each crossing, and the kept pieces close up into loops. The number of loops can change with , as in the example.
- Local and global loops alike. The algorithm does not need to know whether a crossing comes from a swallowtail or from two distant parts of .
- Accuracy is the sampling's. The kept pieces are polylines with vertices on , with the chord error of the sampling. A tangential crossing of two branches, or a swallowtail smaller than the sample spacing, can be missed by the polyline.
Variants and improvements
- Exact curve intersection. Instead of a polyline, approximate the offset by Bézier or B-spline pieces and find their self-intersections by curve intersection, for example by subdivision. The cut points are then accurate to the tolerance of that method.
- Local loops first. The swallowtails lie between pairs of cusps, the parameters where . Finding these zeros first and cutting each swallowtail directly removes the local loops cheaply, and only global loops need a sweep.
- Distance maps. Seong, Elber and Kim compute, for the offset, the squared distance to as a function of two parameters and trim the parameter ranges where it is less than . This avoids the sampling of the self-intersections.
- Voronoi diagrams and the medial axis. For lines and arcs, all trimmed offsets of a region can be read off the medial axis, and no trimming is needed.
- Surfaces. The offset surface has self-intersection curves instead of points, and trimming removes regions of the parameter domain; the classification by a distance test is the same.
- Bentley-Ottmann. Replace the sweep by the Bentley-Ottmann algorithm for an output sensitive bound.
When to use it
Use it whenever an offset is computed by moving points along the normal and the distance can exceed a radius of curvature, or the curve has narrow regions: tool paths for pocket machining and contour milling, the shelling of a profile, and the outlines of wide strokes. For an open curve, the same scheme works, but more cuts are needed, because a point of the offset can also come close to the end points of or to the offset on the other side; add the circles around the end points and the opposite offset to the crossing search.
Pitfalls
- Floating point signs. At a nearly tangential crossing, a floating point orientation test can report no crossing, and then a kept and a removed part become one piece, and the test point decides both. Use exact or adaptive signs.
- Classifying by the polyline. The middle point of a chord is not on , and its distance to differs from by the chord error, which can exceed a small tolerance. Evaluate at the middle parameter.
- A local distance search. A Newton step from the foot point of the same parameter always finds the distance , because is at distance from . The distance must be global, over all of .
- Tolerance. With a tolerance that is too large, the end parts of a swallowtail, which are only slightly closer than , are kept. With one that is too small, rounding removes valid pieces.
- Too few samples. A swallowtail or a neck crossing smaller than the sample spacing is invisible. Sample more densely where is near .
- Degenerate sampling. Collinear overlapping segments, which can occur with straight parts of , have no single crossing point. The implementation rejects them; perturbing resolves them.
Implementations
The Python file in this folder has offset_trimming(points, d, m), which returns the sampled offset, the crossing pairs and the pieces with their marks, together with the de Boor evaluation of the curve and its derivative, the exact segment test and the distance to the curve. The tests compare the sweep with a brute force test of all pairs of segments, which solves the two line equations in exact fractions, on random polylines, on integer grids with touching and collinear cases, and on offsets. They check the de Boor evaluation against the basis functions, the worked example, that sampled points of kept pieces are at distance and points of removed pieces closer by a dense brute force distance, that kept pieces do not cross and close up into loops, and two cases where nothing or everything is removed.
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/offset-trimming/. The authors are listed in prov/MJFVD0.jsonl.
"""Trimming the offset of a closed planar cubic B-spline curve.
The curve C is a closed uniform cubic B-spline with control points
P_0, ..., P_(n-1) and parameter t in [0, n). N is the left unit normal, so
for a counterclockwise curve it points inside, and the raw offset is
g(t) = C(t) + d N(t). The algorithm samples g as a closed polyline, finds
the crossings of non-adjacent segments with a sweep in x and exact
orientation tests, splits the polyline at the crossings, and keeps the
pieces whose middle point is at distance |d| from C.
Points are (x, y) tuples of floats. The orientation tests convert the
coordinates to fractions.Fraction, which is exact for floats, so every sign
decision is exact for the sampled points.
"""
from fractions import Fraction
from math import floor, hypot
from typing import NamedTuple
# ---------------------------------------------------------------- the curve
def de_boor(points, t: float, degree: int):
"""Point of the closed uniform B-spline of `degree` with these control points.
The knots are the integers, and span i = floor(t) uses the control
points P_(i - degree), ..., P_i, with indices taken modulo n.
"""
n = len(points)
t = t % n
i = min(int(floor(t)), n - 1)
d = [points[j % n] for j in range(i - degree, i + 1)]
return _de_boor_span(d, i, t, degree)
def _de_boor_span(d, i: int, t: float, degree: int):
"""The de Boor triangle on span [i, i + 1) with the local control points d."""
d = list(d)
for r in range(1, degree + 1):
for k in range(degree, r - 1, -1):
j = i - degree + k # knot index of d[k]
alpha = (t - j) / (degree + 1 - r)
d[k] = ((1 - alpha) * d[k - 1][0] + alpha * d[k][0], (1 - alpha) * d[k - 1][1] + alpha * d[k][1])
return d[degree]
def curve_point(points, t: float):
"""C(t) of the closed uniform cubic B-spline."""
return de_boor(points, t, 3)
def curve_derivative(points, t: float):
"""C'(t): the quadratic B-spline with control points P_j - P_(j-1) on the same knots.
With integer knots the factor 3 / (u_(j+3) - u_j) of the derivative formula is 1,
and span i uses the differences with j = i - 2, i - 1, i.
"""
n = len(points)
t = t % n
i = min(int(floor(t)), n - 1)
diffs = []
for j in range(i - 2, i + 1):
p, q = points[j % n], points[(j - 1) % n]
diffs.append((p[0] - q[0], p[1] - q[1]))
return _de_boor_span(diffs, i, t, 2)
def offset_point(points, t: float, d: float):
"""g(t) = C(t) + d N(t), with N the left unit normal."""
x, y = curve_point(points, t)
dx, dy = curve_derivative(points, t)
s = hypot(dx, dy)
return (x - d * dy / s, y + d * dx / s)
# ------------------------------------------------------- exact predicates
def orient(a, b, c) -> int:
"""Sign of the cross product (b - a) x (c - a), computed exactly."""
ax, ay = Fraction(a[0]), Fraction(a[1])
v = (Fraction(b[0]) - ax) * (Fraction(c[1]) - ay) - (Fraction(b[1]) - ay) * (Fraction(c[0]) - ax)
return (v > 0) - (v < 0)
def segments_cross(a, b, c, e) -> bool:
"""True when the closed segments ab and ce meet. Collinear overlaps raise ValueError."""
if a == b or c == e: # a segment of length zero is a point
p, (s, r) = (a, (c, e)) if a == b else (c, (a, b))
return orient(s, r, p) == 0 and _in_box(p, s, r)
o1, o2, o3, o4 = orient(a, b, c), orient(a, b, e), orient(c, e, a), orient(c, e, b)
if o1 == o2 == o3 == o4 == 0:
if (min(a[0], b[0]) <= max(c[0], e[0]) and min(c[0], e[0]) <= max(a[0], b[0])
and min(a[1], b[1]) <= max(c[1], e[1]) and min(c[1], e[1]) <= max(a[1], b[1])):
raise ValueError("collinear overlapping offset segments; sample with another m")
return False
return o1 * o2 <= 0 and o3 * o4 <= 0
def _dot_sign(a, b, c) -> int:
"""Sign of (b - a) . (c - b), computed exactly."""
a, b, c = [(Fraction(p[0]), Fraction(p[1])) for p in (a, b, c)]
v = (b[0] - a[0]) * (c[0] - b[0]) + (b[1] - a[1]) * (c[1] - b[1])
return (v > 0) - (v < 0)
def _in_box(p, s, r) -> bool:
return min(s[0], r[0]) <= p[0] <= max(s[0], r[0]) and min(s[1], r[1]) <= p[1] <= max(s[1], r[1])
def crossing_ratio(a, b, c, e) -> Fraction:
"""The exact lam in [0, 1] with a + lam (b - a) on the line ce."""
bx, by = Fraction(b[0]) - Fraction(a[0]), Fraction(b[1]) - Fraction(a[1])
ex, ey = Fraction(e[0]) - Fraction(c[0]), Fraction(e[1]) - Fraction(c[1])
cx, cy = Fraction(c[0]) - Fraction(a[0]), Fraction(c[1]) - Fraction(a[1])
return (cx * ey - cy * ex) / (bx * ey - by * ex)
# ---------------------------------------------------- the sweep in x
def polyline_crossings(q) -> list:
"""All pairs (i, j), i < j, of non-adjacent segments of the closed polyline q that meet.
Segment i joins q[i] and q[i + 1], indices modulo m = len(q). Segments
are sorted by their least x and swept from left to right. Each new
segment is tested against the active segments whose x range reaches it.
"""
m = len(q)
seg = [(q[i], q[(i + 1) % m]) for i in range(m)]
lo = [min(s[0][0], s[1][0]) for s in seg]
hi = [max(s[0][0], s[1][0]) for s in seg]
order = sorted(range(m), key=lambda i: lo[i])
active = []
found = []
for i in order:
active = [j for j in active if hi[j] >= lo[i]]
for j in active:
if (i - j) % m in (1, m - 1):
continue # adjacent segments share a vertex
a, b = seg[i]
c, e = seg[j]
if min(a[1], b[1]) > max(c[1], e[1]) or min(c[1], e[1]) > max(a[1], b[1]):
continue
if segments_cross(a, b, c, e):
found.append((min(i, j), max(i, j)))
active.append(i)
return sorted(found)
# ------------------------------------------------ distance to the curve
def distance_to_curve(points, p, samples_per_span: int = 48, refine: int = 3) -> float:
"""Distance from p to C: dense sampling, then Newton steps on (C(s) - p) . C'(s) = 0."""
n = len(points)
total = n * samples_per_span
vals = []
for k in range(total):
s = k * n / total
c = curve_point(points, s)
vals.append((hypot(c[0] - p[0], c[1] - p[1]), s))
best = min(v[0] for v in vals)
# Refine at the local minima of the sampled distance.
cands = [vals[k][1] for k in range(total) if vals[k][0] <= vals[k - 1][0] and vals[k][0] <= vals[(k + 1) % total][0]]
cands.sort(key=lambda s: hypot(curve_point(points, s)[0] - p[0], curve_point(points, s)[1] - p[1]))
h = 1e-6
for s in cands[:refine]:
for _ in range(30):
c = curve_point(points, s)
d1 = curve_derivative(points, s)
f = (c[0] - p[0]) * d1[0] + (c[1] - p[1]) * d1[1]
d1b = curve_derivative(points, s + h)
d1a = curve_derivative(points, s - h)
d2 = ((d1b[0] - d1a[0]) / (2 * h), (d1b[1] - d1a[1]) / (2 * h))
fp = d1[0] ** 2 + d1[1] ** 2 + (c[0] - p[0]) * d2[0] + (c[1] - p[1]) * d2[1]
if fp <= 0:
break
step = f / fp
step = max(-0.5 / samples_per_span, min(0.5 / samples_per_span, step))
s -= step
if abs(step) < 1e-14:
break
c = curve_point(points, s)
best = min(best, hypot(c[0] - p[0], c[1] - p[1]))
return best
# ---------------------------------------------------- the algorithm
class Piece(NamedTuple):
start: tuple # (segment index, exact ratio) where the piece begins
end: tuple # (segment index, exact ratio) where the piece ends
polyline: list # the points of the piece
middle: tuple # the point g(t) at the middle parameter
distance: float # its distance to C
kept: bool
def offset_trimming(points, d: float, m: int, tol: float = 1e-7):
"""Trim the offset at signed distance d of the closed cubic B-spline `points`.
Return (q, crossings, pieces): the sampled raw offset q with m vertices,
the crossing pairs of its segments, and all pieces between consecutive
crossing points, each marked kept or removed.
"""
n = len(points)
ts = [k * n / m for k in range(m)]
q = [offset_point(points, t, d) for t in ts] # @line L1
for k in range(m):
a, b, c = q[k - 1], q[k], q[(k + 1) % m]
if b == c:
raise ValueError("two consecutive offset samples coincide; sample with another m")
if orient(a, b, c) == 0 and _dot_sign(a, b, c) < 0:
raise ValueError("two adjacent offset segments fold back on a line; sample with another m")
crossings = polyline_crossings(q) # @line L2
where = {} # cut (segment, ratio) -> the crossing point, one float point per crossing
for i, j in crossings: # @line L3
a, b, c, e = q[i], q[(i + 1) % m], q[j], q[(j + 1) % m]
lam = crossing_ratio(a, b, c, e)
mu = crossing_ratio(c, e, a, b)
x = _at(q, j, mu) if mu in (0, 1) else _at(q, i, lam) # a touching vertex stays exact
where[_key(i, lam, m)] = x # @line L4
where[_key(j, mu, m)] = x # @line L4
cuts = sorted(where) # @line L5
if not cuts:
start = (0, Fraction(0))
where[start] = q[0]
pairs = [(start, (m, Fraction(0)))]
else:
pairs = [(cuts[k], cuts[k + 1]) for k in range(len(cuts) - 1)]
pairs.append((cuts[-1], (cuts[0][0] + m, cuts[0][1])))
pieces = []
for (i0, l0), (i1, l1) in pairs: # @line L6
first = where[(i0, l0)]
last = where[(i1 % m, l1)]
inner = [q[k % m] for k in range(i0 + 1, i1 + 1)]
if inner and inner[0] == first:
inner = inner[1:]
if inner and inner[-1] == last:
inner = inner[:-1]
poly = [first] + inner + [last]
u0 = (i0 + float(l0)) * n / m
u1 = (i1 + float(l1)) * n / m
mid = offset_point(points, (u0 + u1) / 2, d) # @line L7
dist = distance_to_curve(points, mid) # @line L7
keep = dist >= abs(d) - tol * max(1.0, abs(d)) # @line L8
pieces.append(Piece((i0, l0), (i1 % m, l1), poly, mid, dist, keep)) # @line L9
return q, crossings, pieces # @line L10
def _key(i: int, lam: Fraction, m: int):
"""A cut as (segment, ratio in [0, 1)), so that a vertex has one name."""
return ((i + 1) % m, Fraction(0)) if lam == 1 else (i, lam)
def _at(q, i, lam):
m = len(q)
a, b = q[i % m], q[(i + 1) % m]
if lam == 0:
return a
if lam == 1:
return b
f = float(lam)
return (a[0] + f * (b[0] - a[0]), a[1] + f * (b[1] - a[1]))
def trimmed_offset(points, d: float, m: int, tol: float = 1e-7) -> list:
"""The kept pieces of the trimmed offset, as polylines."""
return [p.polyline for p in offset_trimming(points, d, m, tol)[2] if p.kept]
test_offset_trimming.py 223 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/offset-trimming/. The authors are listed in prov/MJFVD0.jsonl.
import math
import random
from fractions import Fraction
from offset_trimming import (
curve_derivative,
curve_point,
offset_point,
offset_trimming,
polyline_crossings,
)
DUMBBELL = [(-3, -1.5), (-1, -0.4), (1, -0.4), (3, -1.5), (3, 1.5), (1, 0.4), (-1, 0.4), (-3, 1.5)]
def basis_point(points, t):
"""Reference: the uniform cubic B-spline basis functions on span floor(t)."""
n = len(points)
i = int(math.floor(t)) % n
u = t - math.floor(t)
b = ((1 - u) ** 3 / 6, (3 * u**3 - 6 * u**2 + 4) / 6, (-3 * u**3 + 3 * u**2 + 3 * u + 1) / 6, u**3 / 6)
ctrl = [points[(i - 3 + k) % n] for k in range(4)]
return (sum(b[k] * ctrl[k][0] for k in range(4)), sum(b[k] * ctrl[k][1] for k in range(4)))
def brute_meet(a, b, c, e):
"""Independent exact test: solve a + s (b - a) = c + u (e - c) in fractions.
Return True, False, or None for parallel segments that overlap on a line.
"""
a, b, c, e = [(Fraction(p[0]), Fraction(p[1])) for p in (a, b, c, e)]
if a == b or c == e:
p, (s0, s1) = (a, (c, e)) if a == b else (c, (a, b))
if s0 == s1:
return p == s0
on_line = (s1[0] - s0[0]) * (p[1] - s0[1]) == (s1[1] - s0[1]) * (p[0] - s0[0])
return on_line and min(s0[0], s1[0]) <= p[0] <= max(s0[0], s1[0]) and min(s0[1], s1[1]) <= p[1] <= max(s0[1], s1[1])
rx, ry = b[0] - a[0], b[1] - a[1]
sx, sy = e[0] - c[0], e[1] - c[1]
wx, wy = c[0] - a[0], c[1] - a[1]
det = rx * sy - ry * sx
if det == 0:
if rx * wy - ry * wx != 0:
return False # parallel lines
# Collinear: compare projections on the common direction.
k = 0 if (rx != 0 or sx != 0) else 1
lo1, hi1 = sorted((a[k], b[k]))
lo2, hi2 = sorted((c[k], e[k]))
return None if lo1 <= hi2 and lo2 <= hi1 else False
s = (wx * sy - wy * sx) / det
u = (wx * ry - wy * rx) / det
return 0 <= s <= 1 and 0 <= u <= 1
def boxes_meet(a, b, c, e):
return (min(a[0], b[0]) <= max(c[0], e[0]) and min(c[0], e[0]) <= max(a[0], b[0])
and min(a[1], b[1]) <= max(c[1], e[1]) and min(c[1], e[1]) <= max(a[1], b[1]))
def brute_crossings(q):
"""All pairs of non-adjacent segments, each tested; the box test only skips pairs that cannot meet."""
m = len(q)
out, overlap = [], False
for i in range(m):
for j in range(i + 1, m):
if (j - i) % m in (1, m - 1):
continue
if not boxes_meet(q[i], q[(i + 1) % m], q[j], q[(j + 1) % m]):
continue
r = brute_meet(q[i], q[(i + 1) % m], q[j], q[(j + 1) % m])
if r is None:
overlap = True
elif r:
out.append((i, j))
return out, overlap
def dense_curve(points, per_span=300):
n = len(points)
return [curve_point(points, k / per_span) for k in range(n * per_span)]
def dist_point_segment(p, a, b):
vx, vy = b[0] - a[0], b[1] - a[1]
L = vx * vx + vy * vy
s = 0.0 if L == 0 else max(0.0, min(1.0, ((p[0] - a[0]) * vx + (p[1] - a[1]) * vy) / L))
return math.hypot(p[0] - a[0] - s * vx, p[1] - a[1] - s * vy)
def brute_distance(poly, p):
"""Distance from p to the dense closed polyline of C, a lower bound up to the chord error."""
return min(dist_point_segment(p, poly[k], poly[(k + 1) % len(poly)]) for k in range(len(poly)))
def proper(a, b, c, e):
def o(p, q, r):
v = (Fraction(q[0]) - Fraction(p[0])) * (Fraction(r[1]) - Fraction(p[1])) - (Fraction(q[1]) - Fraction(p[1])) * (Fraction(r[0]) - Fraction(p[0]))
return (v > 0) - (v < 0)
return o(a, b, c) * o(a, b, e) < 0 and o(c, e, a) * o(c, e, b) < 0
def test_de_boor_matches_basis_functions_and_derivative():
rng = random.Random(3)
for n in (4, 5, 8, 11):
pts = [(rng.uniform(-5, 5), rng.uniform(-5, 5)) for _ in range(n)]
for _ in range(50):
t = rng.uniform(0, n)
a, b = curve_point(pts, t), basis_point(pts, t)
assert abs(a[0] - b[0]) < 1e-12 and abs(a[1] - b[1]) < 1e-12
h = 1e-6
p, m = curve_point(pts, t + h), curve_point(pts, t - h)
d = curve_derivative(pts, t)
assert abs(d[0] - (p[0] - m[0]) / (2 * h)) < 1e-6 and abs(d[1] - (p[1] - m[1]) / (2 * h)) < 1e-6
def test_sweep_equals_brute_force_on_random_polylines():
rng = random.Random(11)
for _ in range(60):
m = rng.randint(4, 40)
q = [(rng.uniform(-10, 10), rng.uniform(-10, 10)) for _ in range(m)]
expected, overlap = brute_crossings(q)
assert not overlap
assert polyline_crossings(q) == expected
def test_sweep_on_integer_grids_with_touching_and_collinear_cases():
rng = random.Random(12)
raised = equal = 0
for _ in range(300):
m = rng.randint(4, 14)
q = [(float(rng.randint(0, 4)), float(rng.randint(0, 4))) for _ in range(m)]
expected, overlap = brute_crossings(q)
if overlap:
try:
polyline_crossings(q)
except ValueError:
raised += 1
continue
raise AssertionError("a collinear overlap must be reported as degenerate input")
assert polyline_crossings(q) == expected
equal += 1
assert raised > 0 and equal > 0
def test_sweep_equals_brute_force_on_offsets():
for d, m in ((0.5, 400), (0.6, 300), (-0.5, 200), (0.3, 250)):
q = [offset_point(DUMBBELL, k * len(DUMBBELL) / m, d) for k in range(m)]
expected, overlap = brute_crossings(q)
assert not overlap
assert polyline_crossings(q) == expected
def test_dumbbell_example():
q, crossings, pieces = offset_trimming(DUMBBELL, 0.5, 400)
assert len(crossings) == 6
assert len(pieces) == 12
kept = [p for p in pieces if p.kept]
assert len(kept) == 6
for p in pieces:
if p.kept:
assert abs(p.distance - 0.5) < 1e-9
else:
assert p.distance < 0.5 - 1e-3
def test_kept_points_are_at_distance_d_and_removed_points_closer():
poly = dense_curve(DUMBBELL)
for d, m in ((0.5, 400), (0.6, 400)):
q, crossings, pieces = offset_trimming(DUMBBELL, d, m)
cut_points = [p.polyline[0] for p in pieces]
for p in pieces:
for v in p.polyline[1:-1]:
if min(math.dist(v, c) for c in cut_points) < 0.02:
continue
bd = brute_distance(poly, v)
if p.kept:
assert bd >= abs(d) - 1e-4
else:
assert bd < abs(d) - 1e-4
def test_kept_pieces_do_not_cross_and_close_up():
rng = random.Random(5)
shapes = [DUMBBELL]
for _ in range(3):
n = 9
pts = []
for k in range(n):
ang = 2 * math.pi * k / n
r = rng.uniform(1.0, 3.0)
pts.append((r * math.cos(ang), r * math.sin(ang)))
shapes.append(pts)
for pts in shapes:
for d in (0.4, 0.7, -0.4):
_, _, pieces = offset_trimming(pts, d, 300)
kept = [p.polyline for p in pieces if p.kept]
segs = [(pl[k], pl[k + 1]) for pl in kept for k in range(len(pl) - 1)]
for i in range(len(segs)):
for j in range(i + 1, len(segs)):
if boxes_meet(*segs[i], *segs[j]):
assert not proper(*segs[i], *segs[j])
starts = sorted(pl[0] for pl in kept)
ends = sorted(pl[-1] for pl in kept)
assert starts == ends
def test_outward_offset_of_convex_curve_keeps_everything():
n = 8
pts = [(2 * math.cos(2 * math.pi * k / n), 2 * math.sin(2 * math.pi * k / n)) for k in range(n)]
_, crossings, pieces = offset_trimming(pts, -1.0, 200)
assert crossings == [] and len(pieces) == 1 and pieces[0].kept
def test_inward_offset_beyond_every_radius_of_curvature_removes_everything():
n = 8
pts = [(2 * math.cos(2 * math.pi * k / n), 2 * math.sin(2 * math.pi * k / n)) for k in range(n)]
# The curve is close to a circle of radius about 1.80, so d = 2.5 exceeds every radius of curvature.
_, _, pieces = offset_trimming(pts, 2.5, 200)
assert pieces and not any(p.kept for p in pieces)
History
Offsets with loops appeared as soon as offsets were computed for numerically controlled machining. Lee, Kim and Elber approximated planar offsets by polygons and removed their self-intersections with a plane sweep in 1996. Maekawa surveyed offset curves and surfaces, including their self-intersections, in 1999. Seong, Elber and Kim treated local and global self-intersections of curves and surfaces together with distance maps in 2006.
References
- Lee, Kim and Elber 1996, the polygonal approximation of the offset and the removal of its self-intersections by a plane sweep
- Seong, Elber and Kim 2006, the distinction of local and global self-intersections, and the trimming of the parts that are closer than the offset distance
- Maekawa 1999, the survey of offset methods, including the detection and removal of local and global self-intersections
- Mark de Berg, Otfried Cheong, Marc van Kreveld and Mark Overmars, Computational Geometry, Algorithms and Applications, third edition, Springer, 2008, Chapter 2, Line Segment Intersection (the plane sweep and its O((n + I) log n) bound)
- Manfredo P. do Carmo, Differential Geometry of Curves and Surfaces, Prentice-Hall, 1976, Section 1-7, global properties of plane curves (simple closed curves, positive orientation and the interior on the left)
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 MJFVD0 Edit this page History Report an error Markdown