Algorithm Search⌘K

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.

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
Properties
deterministicofflineiterative
Origin
In Kwon Lee, Myung Soo Kim, Gershon Elber, 1996

Offset trimming turns the raw offset of a curve, the point set C+dNC + dN, into the curve that is really at distance ∣d∣|d| from CC. Where dd 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 CC come closer than 2∣d∣2|d|, the two offsets cross. In both cases some parts of the raw offset are closer to CC than ∣d∣|d|. 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 ∣d∣|d| from CC. 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 ∣d∣|d| 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 ∣d∣|d| 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 CC, here a closed uniform cubic B-spline with control points P0,…,Pn−1P_0, \dots, P_{n-1} and parameter t∈[0,n)t \in [0, n), a signed distance d≠0d \ne 0, a number of samples mm and a tolerance. This page uses the left unit normal NN, which points into the interior of a counterclockwise curve, and the signed curvature κ\kappa, positive where the curve turns left. So d>0d > 0 offsets a counterclockwise curve inward. The mean curvature HH of surfaces does not appear.

The raw offset is γ(t)=C(t)+dN(t)\gamma(t) = C(t) + d N(t); see offset curve. It satisfies γ′=(1−dκ)C′\gamma' = (1 - d\kappa) C', so it has a cusp where dκ=1d \kappa = 1 and runs backwards where dκ>1d \kappa > 1. The trimmed offset is the set of points of γ\gamma at distance exactly ∣d∣|d| from CC:

Od={γ(t):dist⁡(γ(t),C)=∣d∣}.O_d = \{\gamma(t) : \operatorname{dist}(\gamma(t), C) = |d|\}.

The output is the pieces of the sampled offset, each marked kept or removed, such that the kept pieces approximate OdO_d. For a closed curve, OdO_d is the boundary of the region shrunk or grown by ∣d∣|d|, the boundary of a Minkowski sum or difference with a disc.

The algorithm

  1. OFFSET-TRIM(P_0, ..., P_(n−1), d, m, tol)
  2. 1q_k ← C(t_k) + d N(t_k) for t_k = k n / m, k = 0, ..., m − 1 ▷ de Boor for C and C'
  3. 2X ← the pairs of non-adjacent segments of the closed polyline q that meet ▷ sweep in x, exact tests
  4. 3for each pair (i, j) in X do
  5. 4add the meeting point as a cut on segment i and as a cut on segment j
  6. 5sort the cuts along the polyline
  7. 6for each piece between two consecutive cuts, cyclically, do
  8. 7u ← the middle parameter of the piece; δ ← dist(γ(u), C)
  9. 8keep ← (δ ≥ |d| − tol)
  10. 9output the piece and keep
  11. 10return the pieces

Sampling (line L1). The de Boor algorithm gives C(t)C(t), and C′(t)C'(t) is the quadratic B-spline with control points Pj−Pj−1P_j - P_{j-1} on the same knots. The normal is N=(−y′,x′)/∣C′∣N = (-y', x')/|C'|.

Crossings (line L2). Sort the mm segments by their least xx coordinate and sweep from left to right. Keep an active list of the segments whose xx 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 abab and cece meet if and only if orient⁡(a,b,c)orient⁡(a,b,e)≤0\operatorname{orient}(a, b, c)\operatorname{orient}(a, b, e) \le 0 and orient⁡(c,e,a)orient⁡(c,e,b)≤0\operatorname{orient}(c, e, a)\operatorname{orient}(c, e, b) \le 0. 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 mm avoids them.

Cutting (lines L3 to L5). For a crossing of segments ii and jj, the exact ratios λ\lambda and μ\mu 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 γ\gamma at the middle parameter, not the polyline, and computes its distance to CC by dense sampling of CC and Newton steps on (C(s)−p)⋅C′(s)=0(C(s) - p) \cdot C'(s) = 0 at the local minima. The piece is kept when this distance is ∣d∣|d| up to the tolerance; removed pieces are at a distance clearly less than ∣d∣|d|.

Example

Take the closed uniform cubic B-spline with the eight control points

(−3,−1.5), (−1,−0.4), (1,−0.4), (3,−1.5), (3,1.5), (1,0.4), (−1,0.4), (−3,1.5),(-3, -1.5),\ (-1, -0.4),\ (1, -0.4),\ (3, -1.5),\ (3, 1.5),\ (1, 0.4),\ (-1, 0.4),\ (-3, 1.5),

a counterclockwise dumbbell with two lobes and a neck. At the middle of the neck, x=0x = 0, the curve is at y=±107/240≈±0.4458y = \pm 107/240 \approx \pm 0.4458, so the neck is 0.89170.8917 wide. The curvature is largest, about 2.39752.3975, at the four corners of the lobes, where the radius of curvature is about 0.41710.4171. Offset inward by d=0.5d = 0.5 with m=400m = 400 samples.

Since 0.5>0.41710.5 > 0.4171, the raw offset has a swallowtail at each of the four corners, with its crossing at (±2.3308,±0.4404)(\pm 2.3308, \pm 0.4404). Since 0.50.5 is more than half the neck, the offsets of the top and the bottom cross at (±0.6688,0)(\pm 0.6688, 0). The sweep finds these 66 crossings, the same 66 that the brute force test of all pairs finds, and the cuts give 1212 pieces:

pieces length each distance of the middle point to CC decision
4 swallowtail loops 0.06980.0698 0.49380.4938 removed
2 pieces across the neck 1.34351.3435 0.39170.3917 removed
2 end pieces, at (±2.4167,0)(\pm 2.4167, 0) 0.90550.9055 0.50000.5000 kept
4 side pieces 1.72381.7238 0.50000.5000 kept

The piece across the neck has its middle at (0,0.0542)(0, 0.0542): it is the bottom offset, 0.50.5 above the bottom at y=−0.4458y = -0.4458, and it is only 0.4458−0.0542=0.39170.4458 - 0.0542 = 0.3917 below the top. The six kept pieces close up into two loops, one in each lobe, with total length 8.70628.7062. So the inward offset of the dumbbell at this distance has two components, as the region shrunk by a disc of radius 0.50.5 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 xx 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 γ\gamma of a simple closed C3C^3 curve, and it is the reason a single test point per piece is enough. Let f(t)=dist⁡(γ(t),C)−∣d∣≤0f(t) = \operatorname{dist}(\gamma(t), C) - |d| \le 0. Assume that ∣d∣|d| is not the radius of curvature at a vertex of CC. Then every point where ff changes from 00 to negative is a self-intersection of γ\gamma. The proof looks at the disc of radius ∣d∣|d| about the point: if it touches CC twice, both contacts are on the offset side by the Jordan curve theorem, which makes the point a double point of γ\gamma; if it touches once, the second and third derivatives of the squared distance show that ff stays 00 nearby. So on each arc between consecutive self-intersections, ff is identically 00 or negative throughout.

The two parts meet in the sampling: the crossings of the polyline approximate the self-intersections of γ\gamma, and the decision is taken on γ\gamma itself. How fine mm 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 ∣d∣|d| 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 q0,…,qm−1q_0, \dots, q_{m-1} be the samples of line L1 and let segment kk join qkq_k and qk+1q_{k+1}, indices modulo mm. Two segments are adjacent if their indices differ by 11 modulo mm.

Lemma A1 (the predicate). For segments abab and cece of positive length that are not contained in one line, the closed segments meet if and only if orient⁡(a,b,c)orient⁡(a,b,e)≤0\operatorname{orient}(a, b, c)\operatorname{orient}(a, b, e) \le 0 and orient⁡(c,e,a)orient⁡(c,e,b)≤0\operatorname{orient}(c, e, a)\operatorname{orient}(c, e, b) \le 0, where orient⁡\operatorname{orient} 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 xx, then xx lies on the line abab and on the segment cece, so cc and ee are not strictly on the same side of the line abab, which is the first condition, and symmetrically the second. Conversely, if abab and cece are not parallel, the lines meet in one point x=a+λ(b−a)=c+μ(e−c)x = a + \lambda (b - a) = c + \mu (e - c), and orient⁡(c,e,a)\operatorname{orient}(c, e, a) and orient⁡(c,e,b)\operatorname{orient}(c, e, b) are the signs of the values at aa and bb of an affine function that vanishes on the line cece and is linear in λ\lambda along abab. The second condition says that this function does not have the same strict sign at both ends, so 0≤λ≤10 \le \lambda \le 1, and the first condition gives 0≤μ≤10 \le \mu \le 1 in the same way. If they are parallel and on different lines, then cc and ee are strictly on the same side of the line abab and the first condition fails. The rounding claim holds because every float is a rational number and Fraction arithmetic is exact. □\square

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 ii and jj meet, with jj before ii in the order of their least xx coordinate ℓ\ell. They share a point, so their xx ranges overlap: ℓi≤hj\ell_i \le h_j, where hh is the greatest xx coordinate. A segment is dropped from the active list only while some segment kk with ℓk>hj\ell_k > h_j is processed. All segments processed before ii have ℓk≤ℓi≤hj\ell_k \le \ell_i \le h_j, and so does ii, so jj is still active when ii is processed. Their yy ranges overlap too, so the yy filter does not skip the pair, and the test of Lemma A1 reports it. □\square

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 xx lie on segments ii and jj. If ii and jj are not adjacent, Lemma A2 reports the pair, and line L4 adds xx as a cut on segment ii and as a cut on segment jj. So xx is a cut point, and the pieces end there. If i=ji = j or the segments are adjacent, then either xx 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. □\square

Part B: the exact offset

Let C(t)C(t), tt in a circle R/LZ\mathbb{R}/L\mathbb{Z}, be a closed curve of class C3C^3 that is regular and simple, and orient it counterclockwise. Let T=C′/∣C′∣T = C'/|C'|, let NN be the left unit normal, which points into the interior, and let κ\kappa be the signed curvature, so that T′=∣C′∣κNT' = |C'| \kappa N and κ>0\kappa > 0 where the curve turns left. The mean curvature HH of surfaces does not appear. For d≠0d \ne 0, the raw offset is γ(t)=C(t)+dN(t)\gamma(t) = C(t) + d N(t), and

f(t)=dist⁡(γ(t),C)−∣d∣.f(t) = \operatorname{dist}(\gamma(t), C) - |d|.

Since C(t)C(t) is at distance ∣d∣|d| from γ(t)\gamma(t), f≤0f \le 0 everywhere. The trimmed offset is {γ(t):f(t)=0}\{\gamma(t) : f(t) = 0\}.

We use one fact that we do not prove, the local form of the Jordan curve theorem for smooth curves: R2∖C\mathbb{R}^2 \setminus C has two components, the interior and the exterior, and for every tt the points C(t)+εN(t)C(t) + \varepsilon N(t) lie in the interior and C(t)−εN(t)C(t) - \varepsilon N(t) in the exterior for all small ε>0\varepsilon > 0 (do Carmo, Section 1-7).

Assumption (G). There is no tt with dκ(t)=1d \kappa(t) = 1 and κ′(t)=0\kappa'(t) = 0. That is, ∣d∣|d| is not the radius of curvature at a vertex of CC on the side of the offset. This holds for all dd except finitely many values when CC has finitely many vertices.

Lemma B1. Assume (G). If t0t_0 is a boundary point of the open set {t:f(t)<0}\{t : f(t) < 0\}, then γ(t0)=γ(s)\gamma(t_0) = \gamma(s) for some s≠t0s \ne t_0.

Proof. Since ff is continuous and t0t_0 is a boundary point of an open set, f(t0)=0f(t_0) = 0. Let P=γ(t0)P = \gamma(t_0), and let DD be the open disc of radius ∣d∣|d| about PP. Then DD does not meet CC, and C(t0)C(t_0) lies on the boundary circle of DD. Let

F(t,s)=12∣γ(t)−C(s)∣2.F(t, s) = \tfrac{1}{2} |\gamma(t) - C(s)|^2.

Case 1: PP has a second nearest point C(s)C(s), s≠t0s \ne t_0. Then ∣P−C(s)∣=∣d∣|P - C(s)| = |d| and ss minimizes F(t0,⋅)F(t_0, \cdot), so ∂sF=−(P−C(s))⋅C′(s)=0\partial_s F = -(P - C(s)) \cdot C'(s) = 0, and P−C(s)=±dN(s)P - C(s) = \pm d N(s). The open disc DD is connected and does not meet CC, so it lies in one component of R2∖C\mathbb{R}^2 \setminus C. It contains C(t0)+εdN(t0)C(t_0) + \varepsilon d N(t_0) and C(s)+ε(P−C(s))=C(s)±εdN(s)C(s) + \varepsilon (P - C(s)) = C(s) \pm \varepsilon d N(s) for small ε>0\varepsilon > 0. By the fact above, these lie in the same component only if the sign is ++. So P=C(s)+dN(s)=γ(s)P = C(s) + d N(s) = \gamma(s).

Case 2: C(t0)C(t_0) is the only nearest point of PP. At s=ts = t we have γ(t)−C(t)=dN(t)\gamma(t) - C(t) = d N(t), so

∂sF(t,t)=0,∂s2F(t,t)=∣C′∣2−dN⋅C′′=∣C′(t)∣2(1−dκ(t)).\partial_s F(t, t) = 0, \qquad \partial_s^2 F(t, t) = |C'|^2 - d N \cdot C'' = |C'(t)|^2 \left(1 - d \kappa(t)\right).

If 1−dκ(t0)<01 - d \kappa(t_0) < 0, then F(t0,s)<d2/2F(t_0, s) < d^2/2 for s≠t0s \ne t_0 near t0t_0, so f(t0)<0f(t_0) < 0, which is false. If 1−dκ(t0)=01 - d \kappa(t_0) = 0, then by (G) κ′(t0)≠0\kappa'(t_0) \ne 0. In an arc length parameter, C′′=κNC'' = \kappa N and C′′′=κ′N−κ2TC''' = \kappa' N - \kappa^2 T, so ∂s3F(t0,t0)=3C′⋅C′′−dN⋅C′′′=−dκ′(t0)≠0\partial_s^3 F(t_0, t_0) = 3 C' \cdot C'' - d N \cdot C''' = -d \kappa'(t_0) \ne 0. Then F(t0,⋅)−d2/2F(t_0, \cdot) - d^2/2 changes sign at t0t_0, so again f(t0)<0f(t_0) < 0, which is false. So 1−dκ(t0)>01 - d \kappa(t_0) > 0. By continuity, there is an interval UU around t0t_0 with ∂s2F>0\partial_s^2 F > 0 on U×UU \times U. For t∈Ut \in U, F(t,⋅)F(t, \cdot) is strictly convex on UU with critical point s=ts = t, so ∣γ(t)−C(s)∣≥∣d∣|\gamma(t) - C(s)| \ge |d| for all s∈Us \in U.

Now take tk→t0t_k \to t_0 with f(tk)<0f(t_k) < 0, and let C(sk)C(s_k) be a nearest point of γ(tk)\gamma(t_k), so ∣γ(tk)−C(sk)∣<∣d∣|\gamma(t_k) - C(s_k)| < |d|. A subsequence of sks_k converges to some s∗s^* with ∣P−C(s∗)∣≤∣d∣|P - C(s^*)| \le |d|, so C(s∗)C(s^*) is a nearest point of PP, and s∗=t0s^* = t_0. For large kk, both tkt_k and sks_k lie in UU, and ∣γ(tk)−C(sk)∣≥∣d∣|\gamma(t_k) - C(s_k)| \ge |d|, a contradiction. So Case 2 cannot occur. □\square

Theorem B2. Assume (G), and assume that γ\gamma has finitely many self-intersection parameters, that is, parameters tt with γ(t)=γ(s)\gamma(t) = \gamma(s) for some s≠ts \ne t. On each open arc II between two consecutive such parameters, either f=0f = 0 on all of II or f<0f < 0 on all of II. So the trimmed offset is the union of the closures of the arcs on which ff vanishes at one point, and one test point per arc decides it.

Proof. The set {f<0}∩I\{f < 0\} \cap I is open in II. By Lemma B1, it has no boundary point inside II, so it is also closed in II. Since II is connected, it is empty or all of II. □\square

Lines L3 to L6 cut the sampled offset at the crossing points, which approximate the self-intersections of γ\gamma, line L7 evaluates γ\gamma itself at the middle parameter of each piece, and line L8 keeps the piece when its distance is ∣d∣|d| 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 γ\gamma.

Complexity

Sampling costs Θ(m)\Theta(m), since each de Boor evaluation of a cubic costs O(1)O(1). Sorting costs Θ(mlog⁡m)\Theta(m \log m). The sweep tests each pair of segments whose xx ranges overlap once, KK pairs, at O(1)O(1) each, since the rationals come from floats of bounded size. So line L2 costs Θ(mlog⁡m+K)\Theta(m \log m + K). For a curve that is long in xx, KK is close to mm, but for a curve with many segments over the same xx range, KK can be close to m2/2m^2/2. With II crossings there are 2I2I pieces, or one, and each distance costs Θ(n)\Theta(n) for the dense sampling of CC with a fixed number of samples per span. The total is Θ(mlog⁡m+K+(I+1)n)\Theta(m \log m + K + (I + 1) n), with extra space Θ(m+I)\Theta(m + I).

The Bentley-Ottmann algorithm finds the II crossings in O((m+I)log⁡m)O((m + I) \log m) time, independent of KK, and is the better choice for long polylines with many overlapping xx ranges. The xx 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 dd, 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 CC.
  • Accuracy is the sampling's. The kept pieces are polylines with vertices on γ\gamma, 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 dκ=1d\kappa = 1. 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 CC as a function of two parameters and trim the parameter ranges where it is less than d2d^2. 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 xx 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 CC 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 γ\gamma, and its distance to CC differs from ∣d∣|d| by the chord error, which can exceed a small tolerance. Evaluate γ\gamma at the middle parameter.
  • A local distance search. A Newton step from the foot point of the same parameter always finds the distance ∣d∣|d|, because C(u)C(u) is at distance ∣d∣|d| from γ(u)\gamma(u). The distance must be global, over all of CC.
  • Tolerance. With a tolerance that is too large, the end parts of a swallowtail, which are only slightly closer than ∣d∣|d|, 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 dκd\kappa is near 11.
  • Degenerate sampling. Collinear overlapping segments, which can occur with straight parts of CC, have no single crossing point. The implementation rejects them; perturbing mm 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 ∣d∣|d| 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.

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

  1. Lee, Kim and Elber 1996, the polygonal approximation of the offset and the removal of its self-intersections by a plane sweep
  2. 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
  3. Maekawa 1999, the survey of offset methods, including the detection and removal of local and global self-intersections
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example