Algorithm Search⌘K

Algorithmcore

Direction-parallel toolpath

Also called zigzag toolpath, raster toolpath.

Covers a region with parallel line passes clipped to its boundary and joined end to end, simple and used for pocketing and infill.

Time
O(K n log n + I n^3) worst
Space
O(n + I) extra
Where
I = number of intervals on the pass lines; K = number of pass lines; n = number of edges of the tool-center region
Properties
deterministicexactiterative
Origin
Martin Held, 1991

A direction-parallel toolpath clears a pocket by moving the tool center along parallel straight passes, all in one direction, each clipped to the region where the tool center may go. Neighbouring passes are joined end to end, so the tool runs back and forth in a zigzag, and a last pass runs once around the boundary. This is a manufacturing method of mechanical CAD: placement and routing here mean where a milling tool goes and how it moves, not the placement and routing of a circuit. The same pattern, with the tool replaced by a nozzle, is a common infill pattern of additive manufacturing. The page proves that with a step-over of at most twice the tool radius, the passes and the boundary pass cut everything that the tool can reach. The code builds the path with exact rational geometry for a polygon with holes.

In plain words

Think of mowing a lawn in straight strips. You mow one strip from left to right, step up by a little less than the blade width, and mow the next strip from right to left. The strips cover the lawn if the gap between them is never more than the blade width.

A lawn with a pond or a flower bed in the middle breaks some strips into two pieces. You then cannot mow all the pieces in one long zigzag. You lift the mower, carry it to the next piece and start again. Each lift costs time, so a good plan lifts as few times as it can.

Some grass stays where the fence makes a narrow nook that no strip enters. One last lap along the fence and around every flower bed takes it out.

The problem

The tool is a disk of radius rr in the plane. The region CC is the set of positions of the tool center that keep the tool inside the pocket, which for a pocket PP is the inward offset by rr. The code takes CC as given, a closed polygon with holes under the even-odd rule, as when a CAM system has already computed the offset. A path Γ⊆C\Gamma \subseteq C cuts the set Γ⊕Dr\Gamma \oplus D_r, the Minkowski sum of the path and the disk. No path in CC cuts more than C⊕DrC \oplus D_r, so the goal is to cut all of C⊕DrC \oplus D_r with few retractions and a short path.

The passes lie on the lines yk=ymin⁡+s/2+ksy_k = y_{\min} + s/2 + ks for k=0,1,…k = 0, 1, \dots while yk<ymax⁡y_k < y_{\max}, where ss is the step-over. Each line meets CC in a set of closed intervals, which the code finds with the half-open crossing rule of scanline polygon fill.

The algorithm

  1. DIRECTION-PARALLEL(C, s)
  2. 1for each pass line y_k: I_k ← the intervals of C on y = y_k
  3. 2while some interval is unused do
  4. 3start a stroke at the left end of the lowest unused interval
  5. 4loop
  6. 5cut the current interval to its other end and mark it used
  7. 6J ← unused intervals on the next line whose end on the same side links to here by a segment in C
  8. 7if J is empty then exit the loop ▷ the tool retracts
  9. 8link to the nearest member of J, which becomes the current interval
  10. 9add one stroke around each boundary ring of C
  11. 10return the strokes

Line L6 tests each link with an exact segment-in-region test. The test cuts the segment at every point where it meets an edge of CC, including the ends of collinear overlaps, and checks the midpoint of each piece with a closed point-in-polygon test. A link that would cross a hole or a notch of CC is refused, and the stroke ends there.

The strokes after the first one start with a retraction: the tool lifts, moves fast above the part, and plunges at the start of the next stroke.

Example

Take the U-shaped tool-center region CC with vertices (0,0)(0, 0), (10,0)(10, 0), (10,8)(10, 8), (7,8)(7, 8), (7,4)(7, 4), (3,4)(3, 4), (3,8)(3, 8), (0,8)(0, 8), a tool of radius r=1r = 1 and a step-over s=2s = 2. The pass lines are y=1,3,5,7y = 1, 3, 5, 7. The lines y=1y = 1 and y=3y = 3 meet CC in [0,10][0, 10], and the lines y=5y = 5 and y=7y = 7 meet it in [0,3][0, 3] and [7,10][7, 10].

step stroke moves length
L3 to L8 1 (0,1)→(10,1)→(10,3)→(0,3)→(0,5)→(3,5)→(3,7)→(0,7)(0, 1) \to (10, 1) \to (10, 3) \to (0, 3) \to (0, 5) \to (3, 5) \to (3, 7) \to (0, 7) 32
L7 no unused interval on y=9y = 9: retract
L3 to L8 2 (7,5)→(10,5)→(10,7)→(7,7)(7, 5) \to (10, 5) \to (10, 7) \to (7, 7) 8
L9 3 once around the boundary of CC 44

The tool cuts along 84 units of path, with two retractions. At y=5y = 5 the first stroke ends at (3,5)(3, 5). The interval [7,10][7, 10] on the same line is not on the next line, so the zigzag can reach it only through a retraction. Every point of CC is within s/2=1s/2 = 1 of the path, and the cut region is the U grown by 1 on every side, with its six convex corners rounded to radius 1.

Correctness

Theorem. DIRECTION-PARALLEL stops, it cuts each interval exactly once, and its path lies in CC. If s≤2rs \le 2r, every point of CC is within s/2s/2 of the path, and the path cuts exactly C⊕DrC \oplus D_r.

The intervals lie in CC by the parity of the half-open rule, the links lie in CC by the exact segment test, and the boundary pass lies on ∂C\partial C. For the coverage, take a point pp of CC between two pass lines and walk straight up and straight down from it. Each walk stops at the first point that is on the boundary of CC or on a pass line, and both kinds of points are on the path. The two walks add up to at most the gap ss between the lines, so one of them is at most s/2≤rs/2 \le r. A point outside CC that is within rr of CC is within rr of a boundary point, which is on the path. The full proof is in the proof file.

The boundary pass is needed. A thin tongue of CC that lies between two pass lines and meets neither gets no cut from the zigzag, and the tests show such a case.

Proof: With a step-over of at most twice the tool radius and a last contour pass, the zigzag path cuts exactly the dilated regionfull

Setting. CC is a closed polygon with holes: its boundary ∂C\partial C is the union of the edges of a finite set of rings, and a point not on ∂C\partial C is in CC when a horizontal ray from it crosses ∂C\partial C an odd number of times, counted by the half-open rule below. Let ymin⁡y_{\min} and ymax⁡y_{\max} be the smallest and largest yy of a vertex, s>0s > 0 the step-over, r>0r > 0 the tool radius, and yk=ymin⁡+s/2+ksy_k = y_{\min} + s/2 + ks for k=0,…,K−1k = 0, \dots, K - 1, where KK is the number of values with yk<ymax⁡y_k < y_{\max}. DrD_r is the closed disk of radius rr at the origin. The path Γ\Gamma is the set of points on the strokes that DIRECTION-PARALLEL returns.

Claim. (a) The algorithm stops, and each interval of line L1 is cut exactly once. (b) Γ⊆C\Gamma \subseteq C. (c) If s≤2rs \le 2r, every point of CC is within s/2s/2 of Γ\Gamma, and Γ⊕Dr=C⊕Dr\Gamma \oplus D_r = C \oplus D_r.

The half-open rule. For a line y=cy = c and a vertex vv, let π(v)\pi(v) be true when vy>cv_y > c. An edge uvuv is counted when π(u)≠π(v)\pi(u) \ne \pi(v), and its crossing is the point of the edge at height cc. Around each ring, π\pi changes an even number of times, so the number mm of counted edges is even. For a point pp on the line and not on ∂C\partial C, no crossing has x=pxx = p_x, since that crossing would be a point of an edge equal to pp. The ray test counts the crossings with x>pxx > p_x, and the crossings with x<pxx < p_x number mm minus that, which has the same parity.

Lemma 1 (intervals). Let x0≤x1≤⋯≤xm−1x_0 \le x_1 \le \dots \le x_{m-1} be the sorted crossings on the line LL at height cc. Then each closed interval [x2i,x2i+1][x_{2i}, x_{2i+1}] lies in CC, and C∩L⊆⋃i[x2i,x2i+1]∪∂CC \cap L \subseteq \bigcup_i [x_{2i}, x_{2i+1}] \cup \partial C. Proof. Each xjx_j is a point of an edge, so it is in ∂C⊆C\partial C \subseteq C. Let p∈Lp \in L with p∉∂Cp \notin \partial C. By the half-open rule, p∈Cp \in C if and only if the number of crossings left of pp is odd, that is, if and only if x2i<px<x2i+1x_{2i} < p_x < x_{2i+1} for some ii. So the open intervals hold exactly the points of C∩LC \cap L that are not on ∂C\partial C, and the closed intervals add only points of ∂C\partial C. The code drops the intervals of length zero, whose single point is on ∂C\partial C. □\square

Lemma 2 (segment test). SEGMENT-IN-REGION(a,b)(a, b) returns true if and only if the segment abab lies in CC. Proof. The code collects the parameters t∈[0,1]t \in [0, 1] of all points where abab meets an edge: the crossing point when the two segments are not parallel, and the projections of the edge ends that lie on abab when they are collinear. Parallel edges that are not collinear do not meet abab. So every point of ab∩∂Cab \cap \partial C either has a collected parameter or lies on a collinear edge whose ends are collected. Take two consecutive parameters t0<t1t_0 < t_1 and the open piece between them. If a collinear edge overlaps the piece, the edge ends are outside the open piece, so the edge covers all of it, and the piece lies in ∂C⊆C\partial C \subseteq C; its midpoint is on ∂C\partial C, and the closed point test returns true. Otherwise the open piece does not meet ∂C\partial C. It is connected, so it lies wholly in the interior of CC or wholly outside CC, and its midpoint decides which. The ends aa and bb and all the collected points are tested or are on ∂C\partial C. □\square

Proof of (a). Each run of the body of line L4 marks the current interval as used in line L5. That interval is unused when it becomes current: line L3 takes an unused interval, and line L8 takes one from the unused candidates of line L6. So each interval is cut once, and the loop of line L2 stops when none is unused. There are at most m/2m/2 intervals per line and KK lines, so this takes a finite number of steps.

Proof of (b). The strokes are made of three kinds of segments. Each cut along an interval lies in CC by Lemma 1. Each link was accepted by the segment test, so it lies in CC by Lemma 2. The passes of line L9 run along the edges, which are in ∂C\partial C.

Proof of (c). Every edge is on Γ\Gamma, so ∂C⊆Γ\partial C \subseteq \Gamma. By Lemma 1 and part (a), every point of C∩LkC \cap L_k is on a cut interval or on ∂C\partial C, so C∩Lk⊆ΓC \cap L_k \subseteq \Gamma for each pass line LkL_k.

Let p∈Cp \in C. If p∈∂Cp \in \partial C, its distance to Γ\Gamma is 0. Otherwise pp is an interior point. Put y−1=y0−sy_{-1} = y_0 - s and yK=yK−1+sy_K = y_{K-1} + s, two heights that are not pass lines, with y−1<ymin⁡y_{-1} < y_{\min} and yK≥ymax⁡y_K \ge y_{\max}. Since ymin⁡≤py≤ymax⁡y_{\min} \le p_y \le y_{\max}, there is a kk with −1≤k≤K−1-1 \le k \le K - 1 and yk≤py≤yk+1y_k \le p_y \le y_{k+1}.

Walk up from pp to height yk+1y_{k+1} along the vertical segment σ\sigma. If σ\sigma meets ∂C\partial C, the first such point is on Γ\Gamma at distance at most yk+1−pyy_{k+1} - p_y. If not, σ\sigma is a connected set that starts at an interior point and does not meet ∂C\partial C, so it lies in the interior of CC. Its top end is then an interior point at height yk+1y_{k+1}. All vertices have y≤ymax⁡y \le y_{\max}, so no interior point has y≥ymax⁡y \ge y_{\max}; hence yk+1<ymax⁡y_{k+1} < y_{\max} and k+1≤K−1k + 1 \le K - 1, so the top end lies on the pass line Lk+1L_{k+1} and in CC, which puts it on Γ\Gamma. In both cases Γ\Gamma has a point within yk+1−pyy_{k+1} - p_y of pp. The same walk downward, with y−1<ymin⁡y_{-1} < y_{\min} in place of yK≥ymax⁡y_K \ge y_{\max}, gives a point of Γ\Gamma within py−ykp_y - y_k. The two distances add up to yk+1−yk=sy_{k+1} - y_k = s, so one of them is at most s/2s/2.

Now let s≤2rs \le 2r. By (b), Γ⊕Dr⊆C⊕Dr\Gamma \oplus D_r \subseteq C \oplus D_r. Conversely, let x=c+vx = c + v with c∈Cc \in C and ∣v∣≤r|v| \le r. If x∈Cx \in C, it is within s/2≤rs/2 \le r of Γ\Gamma. If x∉Cx \notin C, the segment from cc to xx is connected and joins a point of CC to a point outside it, so it meets ∂C\partial C at a point bb, and ∣x−b∣≤∣x−c∣≤r|x - b| \le |x - c| \le r with b∈Γb \in \Gamma. So x∈Γ⊕Drx \in \Gamma \oplus D_r. ■\blacksquare

Remark. The contour pass is needed. In the walk above, the first boundary point that σ\sigma meets is on Γ\Gamma only because line L9 runs along every edge. Without it, a thin part of CC that lies between two pass lines and does not meet either of them gets no pass, and the test file gives such a tongue.

Complexity

Line L1 finds the crossings of each of the KK lines with the nn edges and sorts them, in O(Knlog⁡n)O(K n \log n) time. Let II be the number of intervals. Each pass of lines L5 to L8 tests at most nn candidates, and each exact segment test cuts the segment into O(n)O(n) pieces and runs an O(n)O(n) point test on each, so it costs O(n2)O(n^2). The linking takes O(In3)O(I n^3) time in this simple code, and much less in practice, where few candidates exist. A sweep that builds the machining graph of the intervals and their neighbours, as in Held (1991), does the linking in time close to linear in n+In + I. The extra space is O(n+I)O(n + I).

The number of pass lines is about (ymax⁡−ymin⁡)/s(y_{\max} - y_{\min})/s, so halving the step-over doubles the path length.

Properties

  • Straight passes. Most of the path is straight, at a constant feed in one direction, which a machine can run fast.
  • Mixed milling direction. A zigzag alternates between climb milling and conventional milling from one pass to the next. A one-way raster cuts every pass in the same direction and returns over the part between passes, at the cost of more air moves.
  • Each interval once. No interval is cut twice, so the path length is the total length of the intervals plus the links and the boundary pass.
  • Retractions. The number of strokes depends on the shape and on the pass direction. For a pocket with holes, minimizing the number of retractions of a zigzag path is NP-hard (Arkin, Held and Smith, 2000).
  • Exact. With rational vertices and step-over, every crossing, interval end and link test of the code is exact.

Variants and improvements

  • Fewer retractions. Arkin, Held and Smith gave a linear-time method that uses at most 5 OPT+6h5\,\mathrm{OPT} + 6h retractions on a pocket with hh holes, where OPT is the minimum for the given machining graph. Later work gives an optimal linear-time method for pockets without holes.
  • Choice of direction. The direction of the passes changes the number of intervals and retractions. Park and Choi (2000) choose the direction and the links to get few tool paths. A good default runs the passes along the longest side.
  • Cell decomposition. Cutting CC into cells, each of which one zigzag covers, is the boustrophedon cell decomposition of robot coverage path planning.
  • Zigzag with contour. Most CAM systems combine a zigzag for the interior with one or more contour-parallel passes along the walls, as here.
  • Surfaces. On a curved surface, the passes become the cuts of the surface by parallel planes. See iso-planar toolpath.

When to use it

Use a direction-parallel path for wide, open pockets and for roughing, where long straight passes are fast and the milling direction matters less. Use a contour-parallel path when the walls need a good finish, when the pocket has many thin features that would break the passes into many intervals, or when the tool must cut in one milling direction.

Pitfalls

  • No boundary pass. Without the last pass along the walls, thin tongues and the material between the ends of the passes and the wall stay uncut.
  • Step-over above twice the radius. With s>2rs > 2r, the middle strip between two passes is more than rr from both. In a 10×1010 \times 10 square with s=3s = 3 and r=1r = 1, the passes are at y=1.5,4.5,7.5y = 1.5, 4.5, 7.5, and the point (5,3)(5, 3) is 1.51.5 from both neighbouring passes.
  • Links across holes. A link drawn straight from one pass to the next can cross an island or a notch and cut the part. Each link must be tested against the region, or run along the boundary.
  • Vertices on a pass line. A pass line through a vertex counts that vertex once, twice or not at all, depending on the rule. Without the half-open rule, an interval can start at a wrong place or the parity can flip. See scanline polygon fill.
  • Floor finish. For a flat end mill on a flat floor, any s<2rs < 2r leaves a flat floor. For a ball end mill on a curved surface, the step-over leaves ridges between passes. See scallop height.

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.

direction_parallel_toolpath.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direction-parallel-toolpath/. The authors are listed in prov/ZR545D.jsonl.

"""Direction-parallel (zigzag) toolpath with exact rational geometry.

The input is the region C where the tool center may go, a polygon with holes
given as a list of rings. A point is in C by the even-odd rule, and C is closed
(its boundary belongs to it). In a CAM system C is the inward offset of the
pocket by the tool radius r, so the tool cuts C plus a disk of radius r.

The passes lie on the horizontal lines y = ymin + s/2 + k s. Each line meets C
in closed intervals. Greedy linking joins an interval to an unused interval on
the next line by a straight segment, but only if that segment lies in C.
When no link is possible, the tool retracts and a new zigzag starts at the
lowest unused interval. A last pass runs around every ring of C.

All coordinates are int or Fraction, and every test is exact.
"""

from fractions import Fraction

Point = tuple[Fraction, Fraction]


def _norm(rings):
    out = []
    for ring in rings:
        pts = [(Fraction(x), Fraction(y)) for x, y in ring]
        if len(pts) < 3:
            raise ValueError("a ring needs at least 3 vertices")
        out.append(pts)
    if not out:
        raise ValueError("the region needs at least one ring")
    return out


def edges(rings):
    for ring in rings:
        m = len(ring)
        for i in range(m):
            yield ring[i], ring[(i + 1) % m]


def cross(o: Point, a: Point, b: Point) -> Fraction:
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


def on_segment(p: Point, a: Point, b: Point) -> 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 crossings(rings, y) -> list[Fraction]:
    """x of the edges that cross the line at height y, by the half-open rule."""
    xs = []
    for (x0, y0), (x1, y1) in edges(rings):
        if (y0 <= y < y1) or (y1 <= y < y0):
            xs.append(x0 + (y - y0) * (x1 - x0) / (y1 - y0))
    xs.sort()
    return xs


def in_region(rings, p: Point) -> bool:
    """Closed point-in-polygon test: boundary points count as inside."""
    if any(on_segment(p, a, b) for a, b in edges(rings)):
        return True
    return sum(1 for x in crossings(rings, p[1]) if x > p[0]) % 2 == 1


def intervals(rings, y) -> list[tuple[Fraction, Fraction]]:
    """The intervals of the line at height y inside C, without the points of zero length."""
    xs = crossings(rings, y)
    return [(xs[i], xs[i + 1]) for i in range(0, len(xs), 2) if xs[i] < xs[i + 1]]


def segment_in_region(rings, a: Point, b: Point) -> bool:
    """True if the closed segment ab lies in C.

    The segment is cut at every point where it meets an edge, including the
    ends of collinear overlaps. Each open piece then lies wholly inside or
    wholly outside, so the test of its midpoint decides it.
    """
    if not (in_region(rings, a) and in_region(rings, b)):
        return False
    d = (b[0] - a[0], b[1] - a[1])
    dd = d[0] * d[0] + d[1] * d[1]
    if dd == 0:
        return True
    ts = {Fraction(0), Fraction(1)}
    for c, e in edges(rings):
        f = (e[0] - c[0], e[1] - c[1])
        den = d[0] * f[1] - d[1] * f[0]
        w = (c[0] - a[0], c[1] - a[1])
        if den != 0:
            t = (w[0] * f[1] - w[1] * f[0]) / den
            u = (w[0] * d[1] - w[1] * d[0]) / den
            if 0 <= t <= 1 and 0 <= u <= 1:
                ts.add(t)
        elif cross(a, b, c) == 0:
            for q in (c, e):
                t = ((q[0] - a[0]) * d[0] + (q[1] - a[1]) * d[1]) / dd
                if 0 <= t <= 1:
                    ts.add(t)
    ts = sorted(ts)
    for t0, t1 in zip(ts, ts[1:]):
        m = (t0 + t1) / 2
        if not in_region(rings, (a[0] + m * d[0], a[1] + m * d[1])):
            return False
    return True


def scanlines(rings, s):
    """The pass lines y_k = ymin + s/2 + k s below ymax, each with its intervals."""
    ys = [p[1] for ring in rings for p in ring]
    ymin, ymax = min(ys), max(ys)
    lines = []
    y = ymin + s / 2
    while y < ymax:
        lines.append((y, intervals(rings, y)))
        y += s
    return lines


def direction_parallel(rings, s, contour=True) -> list[list[Point]]:
    """The strokes of a zigzag toolpath; the tool retracts between strokes.

    Each stroke is a polyline that the tool center follows without lifting.
    With contour=False the last pass around the rings is left out, which is
    only useful to show what goes wrong without it.
    """
    rings = _norm(rings)
    s = Fraction(s)
    if s <= 0:
        raise ValueError("the step-over must be positive")
    lines = scanlines(rings, s)  # @line L1
    used = [[False] * len(iv) for _, iv in lines]
    strokes = []
    while True:  # @line L2
        start = next(((k, j) for k in range(len(lines)) for j in range(len(lines[k][1]))
                      if not used[k][j]), None)
        if start is None:
            break
        k, j = start  # @line L3
        stroke = [(lines[k][1][j][0], lines[k][0])]
        rightward = True
        while True:  # @line L4
            used[k][j] = True  # @line L5
            lo, hi = lines[k][1][j]
            end = (hi, lines[k][0]) if rightward else (lo, lines[k][0])
            stroke.append(end)
            if k + 1 == len(lines):
                break
            ny, niv = lines[k + 1]
            cands = []
            for jj, (a, b) in enumerate(niv):  # @line L6
                if not used[k + 1][jj]:
                    q = (b, ny) if rightward else (a, ny)
                    cands.append((abs(q[0] - end[0]), jj, q))
            cands.sort()
            nxt = next(((jj, q) for _, jj, q in cands if segment_in_region(rings, end, q)), None)
            if nxt is None:  # @line L7
                break
            jj, q = nxt  # @line L8
            stroke.append(q)
            k, j = k + 1, jj
            rightward = not rightward
        strokes.append(stroke)
    if contour:
        for ring in rings:  # @line L9
            strokes.append(ring + [ring[0]])
    return strokes  # @line L10


def path_segments(strokes) -> list[tuple[Point, Point]]:
    """The segments that the tool center cuts along."""
    return [(st[i], st[i + 1]) for st in strokes for i in range(len(st) - 1)]
test_direction_parallel_toolpath.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direction-parallel-toolpath/. The authors are listed in prov/ZR545D.jsonl.

import math
import random
from collections import Counter
from fractions import Fraction as F

import pytest

from direction_parallel_toolpath import (
    direction_parallel,
    edges,
    in_region,
    path_segments,
    scanlines,
)

U_SHAPE = [[(0, 0), (10, 0), (10, 8), (7, 8), (7, 4), (3, 4), (3, 8), (0, 8)]]


def dist2(p, a, b):
    """Exact squared distance from p to the segment ab."""
    dx, dy = b[0] - a[0], b[1] - a[1]
    dd = dx * dx + dy * dy
    t = 0 if dd == 0 else ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / dd
    t = min(1, max(0, t))
    qx, qy = a[0] + t * dx - p[0], a[1] + t * dy - p[1]
    return qx * qx + qy * qy


def fdist2(p, a, b):
    ax, ay, bx, by = float(a[0]), float(a[1]), float(b[0]), float(b[1])
    px, py = float(p[0]), float(p[1])
    dx, dy = bx - ax, by - ay
    dd = dx * dx + dy * dy
    t = 0.0 if dd == 0 else min(1.0, max(0.0, ((px - ax) * dx + (py - ay) * dy) / dd))
    qx, qy = ax + t * dx - px, ay + t * dy - py
    return qx * qx + qy * qy


def within(p, segs, r2):
    """Is p within distance sqrt(r2) of a segment? Floats first, exact near the threshold."""
    r2f = float(r2)
    for a, b in segs:
        d = fdist2(p, a, b)
        if d < r2f - 1e-9:
            return True
        if d <= r2f + 1e-9 and dist2(p, a, b) <= r2:
            return True
    return False


def in_dilation(rings, p, r2):
    """Brute force for the cut region C + D_r: p is in C or within r of an edge of C."""
    return in_region(rings, p) or within(p, list(edges(rings)), r2)


def star_with_hole(rng):
    k = rng.randrange(6, 11)
    outer = []
    for i in range(k):
        ang = 2 * math.pi * (i + rng.uniform(-0.2, 0.2)) / k
        rad = rng.uniform(4, 10)
        outer.append((F(round(4 * rad * math.cos(ang)), 4), F(round(4 * rad * math.sin(ang)), 4)))
    ox, oy = F(rng.randrange(-2, 3), 4), F(rng.randrange(-2, 3), 4)
    hole = [(ox - 1, oy - 1), (ox + F(3, 2), oy - F(1, 2)), (ox, oy + F(3, 2))]
    return [outer, hole]


def grid(rings, r, m):
    xs = [p[0] for ring in rings for p in ring]
    ys = [p[1] for ring in rings for p in ring]
    x0, x1, y0, y1 = min(xs) - r, max(xs) + r, min(ys) - r, max(ys) + r
    return [(x0 + (x1 - x0) * F(i, m), y0 + (y1 - y0) * F(j, m)) for i in range(m + 1) for j in range(m + 1)]


def test_u_shape_example():
    strokes = direction_parallel(U_SHAPE, 2)
    assert strokes[0] == [(0, 1), (10, 1), (10, 3), (0, 3), (0, 5), (3, 5), (3, 7), (0, 7)]
    assert strokes[1] == [(7, 5), (10, 5), (10, 7), (7, 7)]
    assert len(strokes) == 3 and len(strokes[2]) == 9
    lengths = [sum(math.dist(a, b) for a, b in zip(st, st[1:])) for st in strokes]
    assert lengths == [32, 8, 44]


def test_rasterized_cut_region_is_the_dilation():
    """Every grid point of C + D_r is within r of the path, and no other point is."""
    rng = random.Random(3)
    cases = [(U_SHAPE, F(1), F(2))]
    for _ in range(12):
        r = F(rng.randrange(4, 9), 4)
        cases.append((star_with_hole(rng), r, r * F(rng.randrange(5, 9), 4)))
    for rings, r, s in cases:
        segs = path_segments(direction_parallel(rings, s))
        for p in grid(rings, r, 28):
            assert in_dilation(rings, p, r * r) == within(p, segs, r * r), (p, r, s)


def test_tool_center_stays_in_region():
    rng = random.Random(7)
    for _ in range(12):
        rings = star_with_hole(rng)
        s = F(rng.randrange(4, 13), 4)
        for a, b in path_segments(direction_parallel(rings, s)):
            for i in range(17):
                t = F(i, 16)
                assert in_region(rings, (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])))


def test_each_interval_is_cut_once():
    rng = random.Random(11)
    for _ in range(15):
        rings = star_with_hole(rng)
        s = F(rng.randrange(4, 13), 4)
        lines = scanlines(rings, s)
        want = Counter((y, lo, hi) for y, iv in lines for lo, hi in iv)
        strokes = direction_parallel(rings, s, contour=False)
        got = Counter()
        for a, b in path_segments(strokes):
            if a[1] == b[1]:
                got[(a[1], min(a[0], b[0]), max(a[0], b[0]))] += 1
        assert got == want


def test_without_contour_a_tongue_stays_uncut():
    tongue = [[(0, 0), (4, 0), (4, F(19, 10)), (12, F(19, 10)), (12, F(21, 10)),
               (4, F(21, 10)), (4, 4), (0, 4)]]
    p = (F(25, 2), F(2))
    assert in_dilation(tongue, p, 1)
    assert not within(p, path_segments(direction_parallel(tongue, 2, contour=False)), 1)
    assert within(p, path_segments(direction_parallel(tongue, 2)), 1)


def test_step_over_above_twice_the_radius_leaves_material():
    square = [[(0, 0), (10, 0), (10, 10), (0, 10)]]
    segs = path_segments(direction_parallel(square, 3))
    assert [y for y, _ in scanlines(square, 3)] == [F(3, 2), F(9, 2), F(15, 2)]
    assert in_dilation(square, (5, 3), 1) and not within((5, 3), segs, 1)


def test_bad_input():
    with pytest.raises(ValueError):
        direction_parallel(U_SHAPE, 0)
    with pytest.raises(ValueError):
        direction_parallel([[(0, 0), (1, 0)]], 1)

History

Zigzag paths were among the first pocketing paths of numerical control, because they need only line intersections. Held (1991) treated direction-parallel and contour-parallel pocket machining in one computational geometry framework, with the machining graph of the zigzag intervals. Arkin, Held and Smith (extended abstract 1996, journal 2000) proved that minimizing retractions is NP-hard for pockets with holes, and gave the approximation bound.

References

  1. Martin Held, On the Computational Geometry of Pocket Machining, Lecture Notes in Computer Science 500, Springer, 1991, the chapters on direction-parallel machining, the machining graph of the zigzag intervals and its traversal
  2. Esther M. Arkin, Martin Held and Christopher L. Smith, Optimization problems related to zigzag pocket machining, Algorithmica 26(2), 197-236, 2000, the NP-hardness of minimizing retractions for pockets with holes, and the linear-time method with at most 5 OPT + 6h retractions
  3. Sang C. Park and Byoung K. Choi, Tool-path planning for direction-parallel area milling, Computer-Aided Design 32(1), 17-25, 2000, the choice of the pass direction and the linking of the zigzag passes into few tool paths

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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