Skip to main content

sim_components/
path.rs

1//! Paths of straight lines, circular arcs and smooth curves through via points in tool coordinates, and the
2//! planning of the timing along them.
3//! Both planners give poses at times, one per profile cycle, which `Command::Trajectory` runs.
4//!
5//! A path file has one piece per line. The path starts where the machine stands.
6//!
7//! ```text
8//! line,0.5,0.35              straight to this point: one position per axis
9//! arc,0.6,0.25,0.5,0.25,cw   on a circle to the point (0.6, 0.25) around the centre (0.5, 0.25)
10//! spline,0.7,0.2             on a smooth curve through this point
11//! ```
12//!
13//! `cw` and `ccw` are seen with the first axis to the right and the second upwards. An arc that ends on the end
14//! of the piece before it is a full turn. As the first piece an arc has to end at least 1 mm from where the
15//! machine stands (see `FIRST_ARC`). Spline pieces that follow one another form one curve through all their points (see
16//! `spline`); it leaves the line or arc before it in that piece's direction and ends in the direction the
17//! line or arc after it starts with. Lines work on any number of axes; arcs and splines on two and on three (see
18//! below). Empty lines and lines starting with `#` are skipped.
19//!
20//! On a machine with three axes (x, y, z) a line has three positions (`line,0.1,0.0,-0.8`), and so does a spline
21//! point. An arc gives its end and its centre with three positions each, `arc,x,y,z,cx,cy,cz,cw`: it lies in the
22//! plane through where it starts, its end and its centre, and `cw`/`ccw` is seen from the side of that plane its
23//! normal points to when the normal is taken upwards (+z); for a vertical plane, towards the viewer (-y), as the
24//! scene looks at the machine; for the y-z plane, from +x. So an arc in the x-z plane is seen as on a two-axis
25//! machine with x and z. What three axes do not have: a full turn (start and end the same). A half turn (start, centre
26//! and end on one line) leaves the plane open: a program states it (`Piece::Arc::plane`, G17, G18, G19, the three points
27//! of a MoveC), else it is laid in the first of the x-y, x-z and y-z planes that holds the line; one that no such plane
28//! holds, or that the stated plane does not hold, is refused. Transition curves on three axes are laid in the plane of the arc
29//! they meet (`blend3`); where two arcs in different planes meet, the path passes as given.
30//!
31//! Where the axes are x, y, z and an orientation as a rotation vector rx, ry, rz (an arm in tool space), a line moves
32//! the place straight and turns the orientation by slerp (`Geo::Slerp`): about one fixed axis at a steady rate, not
33//! along the straight line between the two rotation vectors, which is not the same turn where they are not parallel.
34
35use crate::control::CommandError;
36use crate::drive::DriveParams;
37use sim_core::{AxisInfo, Machine};
38use std::sync::Arc;
39
40#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
41pub enum Piece {
42    /// Straight to this point.
43    Line(Vec<f64>),
44    /// On a circle around `centre` to the point `to`. `plane` is the normal of the circle's plane where the program
45    /// states it (G17, G18, G19, or the three points of a MoveC): on three axes or more it tells the plane of a half turn,
46    /// which start, end and centre on one line leave open. `None`: the first of the x-y, x-z and y-z planes that holds the
47    /// start's radius (see `arc3`).
48    Arc {
49        to: Vec<f64>,
50        centre: Vec<f64>,
51        clockwise: bool,
52        #[serde(default, skip_serializing_if = "Option::is_none")]
53        plane: Option<[f64; 3]>,
54    },
55    /// On a smooth curve through this point; consecutive ones form one curve.
56    Spline(Vec<f64>),
57}
58
59/// Reads a path file (format: see the top of this file). The error is the line that cannot be read.
60pub fn parse(text: &str) -> Result<Vec<Piece>, String> {
61    let mut pieces = Vec::new();
62    for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
63        let fields: Vec<&str> = line.split(',').map(str::trim).collect();
64        let numbers = |fields: &[&str]| {
65            fields.iter().map(|v| v.parse().ok().filter(|n: &f64| n.is_finite())).collect::<Option<Vec<f64>>>()
66        };
67        let turn = fields[fields.len() - 1];
68        let piece = match fields[0] {
69            "line" if fields.len() > 1 => numbers(&fields[1..]).map(Piece::Line),
70            "spline" if fields.len() > 1 => numbers(&fields[1..]).map(Piece::Spline),
71            // The end and the centre: two positions each, three each, or on more axes the end's and three.
72            "arc" if fields.len() >= 6 && fields.len() != 7 && (turn == "cw" || turn == "ccw") => {
73                let count = fields.len() - 2;
74                let split = match count {
75                    4 => 2,
76                    6 => 3,
77                    _ => count - 3,
78                };
79                numbers(&fields[1..fields.len() - 1]).map(|n| Piece::Arc {
80                    to: n[..split].to_vec(),
81                    centre: n[split..].to_vec(),
82                    clockwise: turn == "cw",
83                    plane: None,
84                })
85            }
86            _ => None,
87        };
88        pieces.push(piece.ok_or(line.to_string())?);
89    }
90    Ok(pieces)
91}
92
93/// Reads a path given as poses at times: per line the time in seconds and one position per axis. Lines that
94/// do not start with a number (a header, comments) are skipped. The error is the line that cannot be read.
95pub fn parse_trajectory(text: &str) -> Result<Vec<(f64, Vec<f64>)>, String> {
96    let mut points = Vec::new();
97    for line in text.lines() {
98        let mut fields = line.split(',').map(|f| f.trim().parse::<f64>());
99        let Some(Ok(time)) = fields.next() else { continue };
100        let pose: Vec<f64> = fields.collect::<Result<_, _>>().map_err(|_| line.to_string())?;
101        if !time.is_finite() || pose.iter().any(|v| !v.is_finite()) {
102            return Err(line.to_string());
103        }
104        points.push((time, pose));
105    }
106    Ok(points)
107}
108
109/// A piece with its start and its length worked out.
110#[derive(Clone)]
111enum Geo {
112    Line {
113        from: Vec<f64>,
114        dir: Vec<f64>,
115        length: f64,
116    },
117    /// A line of a tool whose axes are x, y, z and a rotation vector rx, ry, rz: the place on the straight line from
118    /// `from` to `to`, the orientation by slerp between theirs, both at the share s / `length` of the way; `length` the
119    /// straight distance between the two poses, as a `Line` has it. `at`: the index of rx (3; 4 on an arm on a track, whose
120    /// track axis comes first).
121    Slerp {
122        from: Vec<f64>,
123        to: Vec<f64>,
124        length: f64,
125        at: usize,
126    },
127    /// `turn` is 1 counter-clockwise and -1 clockwise.
128    Arc {
129        centre: [f64; 2],
130        radius: f64,
131        from_angle: f64,
132        turn: f64,
133        length: f64,
134    },
135    /// An arc in space: at the angle phi = s / radius from its start the point centre + radius (cos phi u + sin phi w),
136    /// u from the centre to its start, w at right angles to it in its plane, in the direction it turns.
137    Arc3 {
138        centre: [f64; 3],
139        u: [f64; 3],
140        w: [f64; 3],
141        radius: f64,
142        length: f64,
143    },
144    /// A transition curve (clothoid): from the point `from` in the direction `heading`, the curvature goes
145    /// evenly with the distance from `k0` to `k1`. Curvature is 1 / radius, positive counter-clockwise. On three axes
146    /// `plane` is where the curve lies: a point (the origin of `from`) and the two directions of its first and second
147    /// coordinate; `None` on two axes.
148    Clothoid {
149        from: [f64; 2],
150        heading: f64,
151        k0: f64,
152        k1: f64,
153        length: f64,
154        plane: Option<[[f64; 3]; 3]>,
155    },
156    /// One span of a spline, from one via point to the next, or a part of one: the polynomial c0 + c1 u + ... +
157    /// c5 u^5 for u from 0 to `h` (a cubic, c4 = c5 = 0, but where a spline is eased into a line or an arc,
158    /// `ease`). `travelled` is the distance along it at `SPLINE_PARTS` + 1 evenly spaced u, the last being the
159    /// length; `tightest` and `rate` are the most its curvature and the change of curvature per distance get, and
160    /// `binormal` the most kappa tau (curvature times torsion) gets: the jerk at the speed v along the binormal is
161    /// `binormal` v^3, which is 0 on two axes. `dims` is the number of axes it runs in, two to `WIDEST` (the coefficients of the axes beyond are zero).
162    Spline {
163        c: Box<Poly>,
164        h: f64,
165        travelled: Vec<f64>,
166        tightest: f64,
167        rate: f64,
168        binormal: f64,
169        dims: usize,
170    },
171    /// An arc on a machine with more than three axes (`arc_on`): `arc` (an `Arc3`) on the first three, and the others
172    /// going from `from` by `by`, evenly with the distance along the arc. The distance along this piece counts all
173    /// axes, as a line's does: the piece is `length` = sqrt(L^2 + |by|^2) long for the arc's L, and at the distance s it
174    /// is at s L / length on the arc and at from + by s / length on the other axes. `turn`: the index in `from` of rx
175    /// where the other axes end in an orientation as a rotation vector (`shape` sets it on an arm in tool space): the
176    /// orientation then goes by slerp from `from` to `from + by`, as `Slerp` has it, and not evenly per component.
177    Carried {
178        arc: Box<Geo>,
179        from: Vec<f64>,
180        by: Vec<f64>,
181        length: f64,
182        turn: Option<usize>,
183    },
184}
185
186/// The most axes a spline (and a rounded corner, `round_corners`) runs in: the six of an arm in tool space.
187const WIDEST: usize = 6;
188
189/// A vector on up to `WIDEST` axes, zeros after the axes it has.
190type Wide = [f64; WIDEST];
191
192/// The coefficients of a spline span's polynomial in u, per power, for up to `WIDEST` axes.
193type Poly = [Wide; 6];
194
195fn norm3(a: [f64; 3]) -> f64 {
196    (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt()
197}
198
199fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
200    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
201}
202
203fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
204    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
205}
206
207/// `dot3` and `norm3` on any number of axes (the sums of a three-axis vector with zeros after it are the same).
208fn dot(a: &[f64], b: &[f64]) -> f64 {
209    a.iter().zip(b).map(|(a, b)| a * b).sum()
210}
211
212fn norm(a: &[f64]) -> f64 {
213    dot(a, a).sqrt()
214}
215
216/// The first three of a spline's rates, for the cross products of a span on up to three axes.
217fn first3(a: &Wide) -> [f64; 3] {
218    [a[0], a[1], a[2]]
219}
220
221/// A vector as a `Wide` one: zeros after its axes. `None` with more axes than `WIDEST`.
222fn wide(v: &[f64]) -> Option<Wide> {
223    (v.len() <= WIDEST).then(|| std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0)))
224}
225
226/// A spline span's table of distance travelled has this many parts.
227const SPLINE_PARTS: usize = 64;
228/// The curvature of a spline span and its rate of change are looked at at 4 * `SPLINE_PARTS` + 1 places; what
229/// they reach in between is covered by raising the largest found by this factor.
230const SPLINE_MARGIN: f64 = 1.05;
231
232/// Derivatives of a spline span's polynomial by u: first, second, third.
233fn poly_rates(c: &Poly, u: f64) -> [Wide; 3] {
234    // The k-th derivative: sum over m of m! / (m - k)! c_m u^(m - k).
235    let rate = |k: usize, i: usize| {
236        (k..6).rev().fold(0.0, |sum, m| sum * u + c[m][i] * ((m - k + 1)..=m).map(|f| f as f64).product::<f64>())
237    };
238    [1, 2, 3].map(|k| std::array::from_fn(|i| rate(k, i)))
239}
240
241/// The same polynomial with u counted from `from`: its coefficients around that point.
242fn poly_shift(c: &Poly, from: f64) -> Poly {
243    let mut out = [[0.0; WIDEST]; 6];
244    for (m, cm) in c.iter().enumerate() {
245        // (u + from)^m = sum over k of m! / (k! (m - k)!) u^k from^(m - k)
246        let mut binomial = 1.0;
247        for (k, o) in out.iter_mut().enumerate().take(m + 1) {
248            for i in 0..WIDEST {
249                o[i] += cm[i] * binomial * from.powi((m - k) as i32);
250            }
251            binomial *= (m - k) as f64 / (k + 1) as f64;
252        }
253    }
254    out
255}
256
257/// Distance travelled on a spline span between two values of u: five-point Gauss-Legendre, exact to rounding
258/// for a part of a 64th of a span.
259fn poly_distance(c: &Poly, from: f64, to: f64) -> f64 {
260    const NODES: [(f64, f64); 5] = [
261        (0.0, 0.568_888_888_888_888_9),
262        (0.538_469_310_105_683_1, 0.478_628_670_499_366_5),
263        (-0.538_469_310_105_683_1, 0.478_628_670_499_366_5),
264        (0.906_179_845_938_664, 0.236_926_885_056_189_1),
265        (-0.906_179_845_938_664, 0.236_926_885_056_189_1),
266    ];
267    let (mid, half) = (0.5 * (from + to), 0.5 * (to - from));
268    half * NODES
269        .iter()
270        .map(|(x, w)| {
271            let [d, ..] = poly_rates(c, mid + half * x);
272            w * norm(&d)
273        })
274        .sum::<f64>()
275}
276
277/// A spline span of the polynomial `c` for u from 0 to `h`, with its table of distance travelled and the most its
278/// curvature and the change of curvature per distance get. `None` for a curve that nearly stops and turns on the
279/// spot somewhere (its speed by u, 1 on average, falls below 0.05).
280fn span(c: Poly, h: f64, dims: usize) -> Option<Geo> {
281    let part = h / SPLINE_PARTS as f64;
282    let mut travelled = vec![0.0];
283    for k in 0..SPLINE_PARTS {
284        travelled.push(travelled[k] + poly_distance(&c, k as f64 * part, (k + 1) as f64 * part));
285    }
286    let (mut tightest, mut rate, mut binormal) = (0f64, 0f64, 0f64);
287    for k in 0..=4 * SPLINE_PARTS {
288        let [d, d2, d3] = poly_rates(&c, k as f64 * part / 4.0);
289        let speed = norm(&d);
290        if speed < 0.05 {
291            return None;
292        }
293        // Curvature k = |d x d2| / speed^3, and its derivative by u over the speed: d|n|/du = n . (d x d3) / |n| with
294        // n = d x d2 (on two axes n has a z part only, and this is the size of the signed formula). On more than three
295        // axes by Lagrange's identity: |n|^2 = |d|^2 |d2|^2 - (d . d2)^2 and n . (d x d3) = |d|^2 (d2 . d3) - (d . d2)
296        // (d . d3).
297        let (size, along) = if dims <= 3 {
298            let (n, turn) = (cross3(first3(&d), first3(&d2)), cross3(first3(&d), first3(&d3)));
299            let size = norm3(n);
300            (size, if size > 0.0 { dot3(n, turn) / size } else { norm3(turn) })
301        } else {
302            let (dd2, dd3) = (dot(&d, &d2), dot(&d, &d3));
303            let size = (speed * speed * dot(&d2, &d2) - dd2 * dd2).max(0.0).sqrt();
304            let turn = (speed * speed * dot(&d3, &d3) - dd3 * dd3).max(0.0).sqrt();
305            (size, if size > 0.0 { (speed * speed * dot(&d2, &d3) - dd2 * dd3) / size } else { turn })
306        };
307        let curvature = size / speed.powi(3);
308        let by_u = along / speed.powi(3) - 3.0 * curvature * dot(&d, &d2) / (speed * speed);
309        (tightest, rate) = (tightest.max(curvature), rate.max((by_u / speed).abs()));
310        // The jerk's binormal part kappa tau v^3: the part of d3 at right angles to d and d2 (the rest of d3 is along
311        // them, which `tightest` and `rate` cover), per speed^3; on three axes that is |d3 . n| / (|n| speed^3) =
312        // kappa |tau|. Nil on two axes and where d2 is along d (a straight stretch, an inflection: no binormal there).
313        if dims >= 3 {
314            let p2: Wide = std::array::from_fn(|i| d2[i] - dot(&d2, &d) / (speed * speed) * d[i]);
315            let size = norm(&p2);
316            if size > 1e-6 * norm(&d2) {
317                let (a1, a2) = (dot(&d3, &d) / (speed * speed), dot(&d3, &p2) / (size * size));
318                let rest: Wide = std::array::from_fn(|i| d3[i] - a1 * d[i] - a2 * p2[i]);
319                binormal = binormal.max(norm(&rest) / speed.powi(3));
320            }
321        }
322    }
323    Some(Geo::Spline {
324        c: Box::new(c),
325        h,
326        travelled,
327        tightest: SPLINE_MARGIN * tightest,
328        rate: SPLINE_MARGIN * rate,
329        binormal: SPLINE_MARGIN * binormal,
330        dims,
331    })
332}
333
334impl Geo {
335    fn length(&self) -> f64 {
336        match self {
337            Geo::Line { length, .. }
338            | Geo::Slerp { length, .. }
339            | Geo::Arc { length, .. }
340            | Geo::Arc3 { length, .. }
341            | Geo::Clothoid { length, .. }
342            | Geo::Carried { length, .. } => *length,
343            Geo::Spline { travelled, .. } => travelled[SPLINE_PARTS],
344        }
345    }
346
347    /// Pose, direction and curvature at the distance s from the start of the piece: the pose and its first
348    /// and second derivative by the distance travelled.
349    fn at(&self, s: f64) -> [Vec<f64>; 3] {
350        match self {
351            Geo::Line { from, dir, .. } => {
352                [from.iter().zip(dir).map(|(p, d)| p + d * s).collect(), dir.clone(), vec![0.0; dir.len()]]
353            }
354            Geo::Slerp { from, to, length, at } => {
355                let (at, n) = (*at, from.len());
356                let turns = |i: usize| (at..at + 3).contains(&i);
357                let dir: Vec<f64> = from.iter().zip(to).map(|(f, t)| (t - f) / length).collect();
358                // Both orientations about one axis, on its same side: the turn goes along that axis, and its rotation
359                // vector along the straight line between them, with no bend. By the differences below its rounding
360                // (2e-8 rad/m^2 on a turn of 0.2 rad) marked it as bending, and the time-optimal plan gave its ramps
361                // 0.4 of those axes' jerk.
362                let (a, b) = ([from[at], from[at + 1], from[at + 2]], [to[at], to[at + 1], to[at + 2]]);
363                if one_axis(a, b) {
364                    return [from.iter().zip(&dir).map(|(p, d)| p + d * s).collect(), dir.clone(), vec![0.0; n]];
365                }
366                let pose = |s: f64| -> Vec<f64> {
367                    let turned = crate::rigid::slerp(
368                        [from[at], from[at + 1], from[at + 2]],
369                        [to[at], to[at + 1], to[at + 2]],
370                        s / length,
371                    );
372                    (0..n).map(|i| if turns(i) { turned[i - at] } else { from[i] + s * dir[i] }).collect()
373                };
374                // The orientation's rates in closed form (`rigid::slerp_rates`, past the ends too). The place's are exact
375                // as well: by differences they were bends of rounding noise on every axis, which `piece_limits` cannot
376                // pass.
377                let here = pose(s);
378                let [_, turn, bend] = crate::rigid::slerp_rates(
379                    [from[at], from[at + 1], from[at + 2]],
380                    [to[at], to[at + 1], to[at + 2]],
381                    s / length,
382                );
383                let first = (0..n).map(|i| if turns(i) { turn[i - at] / length } else { dir[i] }).collect();
384                let second = (0..n).map(|i| if turns(i) { bend[i - at] / (length * length) } else { 0.0 }).collect();
385                [here, first, second]
386            }
387            Geo::Arc { centre, radius, from_angle, turn, .. } => {
388                let (sin, cos) = (from_angle + turn * s / radius).sin_cos();
389                [
390                    vec![centre[0] + radius * cos, centre[1] + radius * sin],
391                    vec![-turn * sin, turn * cos],
392                    vec![-cos / radius, -sin / radius],
393                ]
394            }
395            Geo::Arc3 { centre, u, w, radius, .. } => {
396                let (sin, cos) = (s / radius).sin_cos();
397                [
398                    (0..3).map(|i| centre[i] + radius * (cos * u[i] + sin * w[i])).collect(),
399                    (0..3).map(|i| -sin * u[i] + cos * w[i]).collect(),
400                    (0..3).map(|i| -(cos * u[i] + sin * w[i]) / radius).collect(),
401                ]
402            }
403            Geo::Clothoid { from, heading, k0, k1, length, plane } => {
404                let angle = |u: f64| heading + k0 * u + 0.5 * (k1 - k0) * u * u / length;
405                // The pose is the direction added up along the curve, which has no closed form: Simpson's
406                // rule over 64 intervals, exact to far below a nanometre for the turns a blend makes.
407                let (n, h) = (64, s / 64.0);
408                let (mut x, mut y) = (0.0, 0.0);
409                for i in 0..=n {
410                    let weight = if i == 0 || i == n {
411                        1.0
412                    } else if i % 2 == 1 {
413                        4.0
414                    } else {
415                        2.0
416                    };
417                    let (sin, cos) = angle(i as f64 * h).sin_cos();
418                    (x, y) = (x + weight * cos, y + weight * sin);
419                }
420                let ((sin, cos), k) = (angle(s).sin_cos(), k0 + (k1 - k0) * s / length);
421                let flat = [[from[0] + x * h / 3.0, from[1] + y * h / 3.0], [cos, sin], [-k * sin, k * cos]];
422                match plane {
423                    None => flat.map(|v| v.to_vec()),
424                    // In space: the pose from the plane's point, direction and curvature along its two directions.
425                    Some([o, e1, e2]) => {
426                        let lift = |v: [f64; 2], point: f64| {
427                            (0..3).map(|i| point * o[i] + v[0] * e1[i] + v[1] * e2[i]).collect()
428                        };
429                        [lift(flat[0], 1.0), lift(flat[1], 0.0), lift(flat[2], 0.0)]
430                    }
431                }
432            }
433            Geo::Spline { c, h, travelled, dims, .. } => {
434                let u = spline_u(c, *h, travelled, s);
435                let [d, d2, _] = poly_rates(c, u);
436                let speed = norm(&d);
437                let (dir, along) = (d.map(|x| x / speed), dot(&d, &d2) / speed);
438                let pose = (0..*dims).map(|i| c.iter().rev().fold(0.0, |sum, cm| sum * u + cm[i])).collect();
439                // The second derivative by distance: what of the second derivative by u is across the direction.
440                [pose, dir[..*dims].to_vec(), (0..*dims).map(|i| (d2[i] - along * dir[i]) / (speed * speed)).collect()]
441            }
442            Geo::Carried { arc, from, by, length, turn } => {
443                let share = arc.length() / length;
444                let [mut pose, mut dir, mut curve] = arc.at(s * share);
445                dir.iter_mut().for_each(|d| *d *= share);
446                curve.iter_mut().for_each(|c| *c *= share * share);
447                pose.extend(carried_tail(from, by, *length, *turn, s));
448                dir.extend(by.iter().map(|b| b / length));
449                curve.extend(by.iter().map(|_| 0.0));
450                if let Some(k) = turn.filter(|k| slerps(from, by, *k)) {
451                    // The orientation's rates in closed form, as `Slerp` has them.
452                    let end = |i: usize| from[i] + by[i];
453                    let [_, turned, bent] = crate::rigid::slerp_rates(
454                        [from[k], from[k + 1], from[k + 2]],
455                        [end(k), end(k + 1), end(k + 2)],
456                        s / length,
457                    );
458                    for i in 0..3 {
459                        let at = pose.len() - by.len() + k + i;
460                        dir[at] = turned[i] / length;
461                        curve[at] = bent[i] / (length * length);
462                    }
463                }
464                [pose, dir, curve]
465            }
466        }
467    }
468}
469
470/// Both orientations (rotation vectors) about one axis, on its same side: the turn goes along that axis and its rotation
471/// vector along the straight line between them, with no bend. To the rounding of the turns' sizes: a turn that ends a
472/// piece is the next one's start only to it (a level pose as 1e-17 rad about some axis), and the next turn bent by it.
473fn one_axis(a: [f64; 3], b: [f64; 3]) -> bool {
474    let size = |v: [f64; 3]| crate::rigid::dot(v, v).sqrt();
475    let scale = (size(a) + size(b)).powi(2);
476    size(crate::rigid::cross(a, b)) <= 1e-12 * scale
477        && crate::rigid::dot(a, b) >= -1e-12 * scale
478        && size(a).max(size(b)) < std::f64::consts::PI
479}
480
481/// Whether the orientation of a `Geo::Carried` (rx at `k` in `from`, going `by`) turns by a slerp that bends its rotation
482/// vector (`one_axis`: it does not).
483fn slerps(from: &[f64], by: &[f64], k: usize) -> bool {
484    let (a, b) =
485        ([from[k], from[k + 1], from[k + 2]], [from[k] + by[k], from[k + 1] + by[k + 1], from[k + 2] + by[k + 2]]);
486    !one_axis(a, b)
487}
488
489/// The other axes of a `Geo::Carried` at the distance s: evenly with it, but the orientation at `turn` by slerp.
490fn carried_tail(from: &[f64], by: &[f64], length: f64, turn: Option<usize>, s: f64) -> Vec<f64> {
491    let mut tail: Vec<f64> = from.iter().zip(by).map(|(f, b)| f + b * s / length).collect();
492    if let Some(k) = turn.filter(|k| slerps(from, by, *k)) {
493        let end = |i: usize| from[i] + by[i];
494        let turned =
495            crate::rigid::slerp([from[k], from[k + 1], from[k + 2]], [end(k), end(k + 1), end(k + 2)], s / length);
496        tail[k..k + 3].copy_from_slice(&turned);
497    }
498    tail
499}
500
501/// The u at which a spline span has run the distance s: from its table of distance travelled, then Newton's method on
502/// the distance itself, which converges to rounding in two or three steps.
503fn spline_u(c: &Poly, h: f64, travelled: &[f64], s: f64) -> f64 {
504    let part = travelled.partition_point(|t| *t <= s).clamp(1, SPLINE_PARTS) - 1;
505    let (u0, du) = (part as f64 * h / SPLINE_PARTS as f64, h / SPLINE_PARTS as f64);
506    let mut u = u0 + du * (s - travelled[part]) / (travelled[part + 1] - travelled[part]);
507    for _ in 0..4 {
508        let [d, ..] = poly_rates(c, u);
509        u -= (travelled[part] + poly_distance(c, u0, u) - s) / norm(&d);
510    }
511    u
512}
513
514/// A smooth curve from `points[0]` through all of `points`: a cubic spline, one `Geo::Spline` per span.
515///
516/// The parameter u runs with the straight distance between the via points, and on each span the curve is a
517/// cubic in u. The cubics are chosen so that the curve has no step in position, in direction or in curvature
518/// at a via point (the first and second derivative by u agree there). At an end the curve takes the given
519/// direction (`before` at the start, `after` at the end: that of the line or arc it joins); where there is
520/// none it ends without curvature. That leaves one curve, found by solving for the derivatives at the
521/// points (a system with three entries per row).
522///
523/// What it does not promise: the curvature at an end with a given direction is whatever the points ask for,
524/// so where the spline joins a line or an arc the curvature steps, and the path passes that junction as
525/// slowly as a line into an arc (`junction_speed`), unless a tolerance lets `ease` bend the spline's end to the
526/// curvature of its neighbour.
527///
528/// `None` for a curve that nearly stops and turns on the spot somewhere (its speed by u, 1 on average, falls
529/// below 0.05): via points and end directions that fight each other.
530fn spline(points: &[Vec<f64>], before: Option<Wide>, after: Option<Wide>) -> Option<Vec<Geo>> {
531    let (n, dims) = (points.len() - 1, points[0].len());
532    let h: Vec<f64> = points.windows(2).map(|w| distance(&w[0], &w[1])).collect();
533    // A two-axis point has no third position: its chord there is zero.
534    let chord = |i: usize, axis: usize| if axis < dims { (points[i + 1][axis] - points[i][axis]) / h[i] } else { 0.0 };
535    // Rows (below, diagonal, above, right side) of the system for the derivatives at the points.
536    let mut rows: Vec<[f64; 3]> = Vec::new();
537    let mut right: Vec<Wide> = Vec::new();
538    for i in 0..=n {
539        let (row, side) = match (i, before, after) {
540            (0, Some(dir), _) => ([0.0, 1.0, 0.0], dir),
541            (0, None, _) => ([0.0, 2.0, 1.0], std::array::from_fn(|axis| 3.0 * chord(0, axis))),
542            (i, _, Some(dir)) if i == n => ([0.0, 1.0, 0.0], dir),
543            (i, _, None) if i == n => ([1.0, 2.0, 0.0], std::array::from_fn(|axis| 3.0 * chord(n - 1, axis))),
544            _ => (
545                [h[i], 2.0 * (h[i - 1] + h[i]), h[i - 1]],
546                std::array::from_fn(|axis| 3.0 * (h[i] * chord(i - 1, axis) + h[i - 1] * chord(i, axis))),
547            ),
548        };
549        rows.push(row);
550        right.push(side);
551    }
552    // Elimination downwards, then substitution upwards.
553    for i in 1..=n {
554        let factor = rows[i][0] / rows[i - 1][1];
555        rows[i][1] -= factor * rows[i - 1][2];
556        right[i] = std::array::from_fn(|axis| right[i][axis] - factor * right[i - 1][axis]);
557    }
558    let mut d = vec![[0.0; WIDEST]; n + 1];
559    for i in (0..=n).rev() {
560        let above = if i < n { d[i + 1] } else { [0.0; WIDEST] };
561        d[i] = std::array::from_fn(|axis| (right[i][axis] - rows[i][2] * above[axis]) / rows[i][1]);
562    }
563    (0..n)
564        .map(|i| {
565            let c = [
566                std::array::from_fn(|axis| if axis < dims { points[i][axis] } else { 0.0 }),
567                d[i],
568                std::array::from_fn(|axis| (3.0 * chord(i, axis) - 2.0 * d[i][axis] - d[i + 1][axis]) / h[i]),
569                std::array::from_fn(|axis| (d[i][axis] + d[i + 1][axis] - 2.0 * chord(i, axis)) / (h[i] * h[i])),
570                [0.0; WIDEST],
571                [0.0; WIDEST],
572            ];
573            span(c, h[i], dims)
574        })
575        .collect()
576}
577
578fn distance(a: &[f64], b: &[f64]) -> f64 {
579    a.iter().zip(b).map(|(a, b)| (a - b) * (a - b)).sum::<f64>().sqrt()
580}
581
582/// The path the planners time: the pieces laid end to end from `start`, with transition curves where the
583/// tolerance allows them (`blend` between lines and arcs, `ease` where a spline meets a line or an arc), and how
584/// far that path is from the given one at most. `speed` is the highest speed along a piece that the planner will
585/// allow, which sets how long a transition has to be. On three axes the curves between lines and arcs are laid in the
586/// arcs' planes (`blend3`); paths on other numbers of axes have only lines and run as given. Corners are rounded first,
587/// within the corner tolerance (`round_corners`).
588fn geometry(
589    axes: &[AxisInfo],
590    start: &[f64],
591    pieces: &[Piece],
592    tolerance: impl Into<Tolerance>,
593    speed: &dyn Fn(&Geo) -> f64,
594    slack: f64,
595) -> Result<(Vec<Geo>, f64), CommandError> {
596    geometry_fed(axes, start, pieces, &[], tolerance, speed, slack).map(|(geo, off, _)| (geo, off))
597}
598
599/// `geometry` for pieces with a speed cap each (`feeds`, see `given_fed`): and per piece of the path its cap. Each stretch
600/// of pieces at one cap is shaped on its own, with the cap as a bound on its `speed`, so that no corner is rounded and no
601/// transition curve laid across a change of the cap (at the junction the path passes at the lower cap, as `timed` has it).
602fn geometry_fed(
603    axes: &[AxisInfo],
604    start: &[f64],
605    pieces: &[Piece],
606    feeds: &[f64],
607    tolerance: impl Into<Tolerance>,
608    speed: &dyn Fn(&Geo) -> f64,
609    slack: f64,
610) -> Result<(Vec<Geo>, f64, Vec<f64>), CommandError> {
611    let tolerance = tolerance.into();
612    let (geo, off, caps) = given_fed(start, pieces, feeds, slack)?;
613    let (mut out, mut shaped, mut moved, mut at) = (Vec::new(), Vec::new(), 0.0f64, 0);
614    while at < geo.len() {
615        let cap = caps[at];
616        let end = at + caps[at..].iter().take_while(|c| **c == cap).count();
617        let (part, deviation) = shape(axes, start.len(), geo[at..end].to_vec(), tolerance, &|g| speed(g).min(cap));
618        shaped.extend(part.iter().map(|_| cap));
619        out.extend(part);
620        moved = moved.max(deviation);
621        at = end;
622    }
623    Ok((out, off + moved, shaped))
624}
625
626/// The pieces as given, `geo`, shaped (see `geometry`) and how far that moves them at most.
627fn shape(
628    axes: &[AxisInfo],
629    dims: usize,
630    mut geo: Vec<Geo>,
631    tolerance: Tolerance,
632    speed: &dyn Fn(&Geo) -> f64,
633) -> (Vec<Geo>, f64) {
634    let Tolerance { path: tolerance, corner } = tolerance;
635    let n = axes.len();
636    let tool_space = (6..=7).contains(&n) && axes[n - 3..].iter().map(|a| a.id).eq(["rx", "ry", "rz"]);
637    // An arc's tail (the axes after x, y, z) ends in rx, ry, rz: its orientation turns by slerp (`arc_on`), also where a
638    // corner next to it is rounded (`trimmed` cuts the slerp).
639    if tool_space {
640        for g in &mut geo {
641            if let Geo::Carried { turn, .. } = g {
642                *turn = Some(n - 6);
643            }
644        }
645    }
646    let (mut geo, rounded) = round_corners(geo, corner);
647    // An orientation as a rotation vector turns by slerp along a line (what is left of it after its corners are
648    // rounded: the rounding curves pass the rotation vector as any other axis, within the corner tolerance).
649    // x, y, z, rx, ry, rz, or with an axis before them (an arm on a track).
650    if tool_space {
651        for g in &mut geo {
652            if let Geo::Line { from, dir, length } = g {
653                let to = from.iter().zip(dir.iter()).map(|(f, d)| f + *length * d).collect();
654                *g = Geo::Slerp { from: from.clone(), to, length: *length, at: n - 3 };
655            }
656        }
657    }
658    if tolerance <= 0.0 {
659        return (geo, rounded);
660    }
661    // The speeds of the pieces as given, in space: `blend3` hands `blend` the pieces in a plane's coordinates.
662    let speeds: Vec<f64> = geo.iter().map(speed).collect();
663    let (geo, moved) = match dims {
664        2 => blend(geo, &speeds, axes, tolerance),
665        3 => blend3(geo, &speeds, axes, tolerance),
666        _ => (geo, 0.0),
667    };
668    let (geo, eased) = ease(geo, axes, tolerance, speed);
669    // The three change different places of the path, so the largest of them counts.
670    (geo, moved.max(eased).max(rounded))
671}
672
673/// How far a planned path may leave the pieces as given: `path` for the transition curves where pieces meet in their
674/// direction (`profile.path_tolerance_m`), `corner` for rounding the corners (`round_corners`,
675/// `profile.corner_tolerance_m`). A tolerance alone is a path tolerance, with corners stopped at.
676#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)]
677pub struct Tolerance {
678    pub path: f64,
679    pub corner: f64,
680}
681
682impl From<f64> for Tolerance {
683    fn from(path: f64) -> Self {
684        Self { path, corner: 0.0 }
685    }
686}
687
688/// The highest speed along a piece within the axis limits, as `plan` times it.
689fn axis_speed(axes: &[AxisInfo]) -> impl Fn(&Geo) -> f64 {
690    let bounds = axis_bounds(axes);
691    move |geo| limits(geo, &bounds)[0]
692}
693
694/// How far the path that is planned for these pieces is from the pieces as given, at most: the deviation
695/// the transition curves make, plus how far an arc ends off its stated end (`given`). Zero with a tolerance of
696/// zero and arcs that end on their circles. For the plan within the axis limits. A program's run with a feed per piece
697/// (`plan_feeds`) is shaped per stretch of one feed, with no curve across a change of feed and shorter curves at a lower
698/// feed: this reads it as without the feeds, so it may read higher than that run's own path, never lower, and never
699/// more than the larger of the two tolerances plus how far an arc ends off its stated end.
700pub fn deviation(
701    axes: &[AxisInfo],
702    start: &[f64],
703    pieces: &[Piece],
704    tolerance: impl Into<Tolerance>,
705    slack: f64,
706) -> Result<f64, CommandError> {
707    Ok(geometry(axes, start, pieces, tolerance, &axis_speed(axes), slack)?.1)
708}
709
710/// For an arc that is the first piece: how far its end may be off the circle through its start (the planners'
711/// `slack`). A path starts at the setpoint of the machine at rest, which is where the motors stand: under belt
712/// stretch and gear twist that far from the pose the file was written for. The controller passes
713/// `Machine::setpoint_slack` (12 and 46 um on a gantry holding its Z axis against gravity, within this default of
714/// 0.1 mm; more on the delta, whose gearboxes sag under the platform); this is for a path from a stated point.
715pub const ARC_SLACK: f64 = 1e-4;
716/// A first arc has to end at least this far from where the machine stands, and at least ten times the slack.
717/// Nearer, a full turn (whose end is up to the slack from there) cannot be told from a short arc (a 130 um arc ran
718/// as a full turn), so neither is guessed: the path is refused, and the file states the start with a `line` to it
719/// first, after which the arc is no longer the first piece. The margin of ten over the slack keeps a first arc that
720/// is run at most a tenth longer or shorter than the one the file means.
721const FIRST_ARC: f64 = 1e-3;
722/// For every later arc: how far the stated end may be off the circle through the stated end before it.
723const ARC_TOLERANCE: f64 = 1e-5;
724
725fn piece_end(piece: &Piece) -> &Vec<f64> {
726    let (Piece::Line(to) | Piece::Arc { to, .. } | Piece::Spline(to)) = piece;
727    to
728}
729
730/// The pieces laid end to end from `start`, and how far a piece ends off its stated end at most: an arc is
731/// laid on the circle through where the path stands, which its stated end may miss by the tolerances above.
732/// Pieces without length are left out.
733#[cfg(test)]
734fn given(start: &[f64], pieces: &[Piece], slack: f64) -> Result<(Vec<Geo>, f64), CommandError> {
735    given_fed(start, pieces, &[], slack).map(|(geo, off, _)| (geo, off))
736}
737
738/// `given` and per piece it returns the speed cap along the path of the piece it came from (`feeds`: one per piece,
739/// none or too few: no cap, infinite), the lowest of a run of spline pieces, which is one curve.
740fn given_fed<'a>(
741    start: &[f64],
742    pieces: &'a [Piece],
743    feeds: &[f64],
744    slack: f64,
745) -> Result<(Vec<Geo>, f64, Vec<f64>), CommandError> {
746    let bad = Err(CommandError { key: "error-path" });
747    let (mut here, mut out): (Vec<f64>, Vec<Geo>) = (start.to_vec(), Vec::new());
748    let mut caps: Vec<f64> = Vec::new();
749    let feed = |from: usize, to: usize| {
750        (from..to).map(|i| feeds.get(i).copied().unwrap_or(f64::INFINITY)).fold(f64::INFINITY, f64::min)
751    };
752    // The end the file stated last; none before the first piece, where the path stands on the machine's setpoint.
753    let (mut stated, mut off): (Option<&'a Vec<f64>>, f64) = (None, 0.0);
754    let mut rest = pieces;
755    while let Some((piece, after)) = rest.split_first() {
756        rest = after;
757        let index = pieces.len() - rest.len() - 1;
758        let geo = match piece {
759            Piece::Spline(_) if (2..=WIDEST).contains(&here.len()) => {
760                // The whole run of spline pieces is one curve; a via point given twice counts once.
761                let run = 1 + rest.iter().take_while(|p| matches!(p, Piece::Spline(_))).count();
762                let mut points = vec![here.clone()];
763                for to in std::iter::once(piece)
764                    .chain(&rest[..run - 1])
765                    .filter_map(|p| if let Piece::Spline(to) = p { Some(to) } else { None })
766                {
767                    if to.len() != here.len() {
768                        return bad;
769                    }
770                    if distance(to, &points[points.len() - 1]) > 1e-9 {
771                        points.push(to.clone());
772                    }
773                }
774                rest = &rest[run - 1..];
775                stated = Some(piece_end(&pieces[pieces.len() - rest.len() - 1]));
776                if points.len() < 2 {
777                    continue;
778                }
779                let end = &points[points.len() - 1];
780                // The direction the piece before ends with, and the one the line or arc after starts with.
781                let before = out.last().and_then(|g| wide(&g.at(g.length())[1]));
782                let after = match rest.first() {
783                    Some(Piece::Line(to)) if to.len() == end.len() && distance(to, end) > 1e-9 => {
784                        wide(&to.iter().zip(end).map(|(t, e)| (t - e) / distance(to, end)).collect::<Vec<_>>())
785                    }
786                    Some(Piece::Arc { centre, clockwise, .. })
787                        if centre.len() == 2 && end.len() == 2 && distance(end, centre) > 1e-6 =>
788                    {
789                        let (turn, radius) = (if *clockwise { -1.0 } else { 1.0 }, distance(end, centre));
790                        wide(&[-turn * (end[1] - centre[1]) / radius, turn * (end[0] - centre[0]) / radius])
791                    }
792                    Some(Piece::Arc { to, centre, clockwise, plane })
793                        if end.len() >= 3
794                            && to.len() == end.len()
795                            && (centre.len() == 3 || centre.len() == end.len()) =>
796                    {
797                        arc_on(end, to, centre, *clockwise, *plane).and_then(|g| wide(&g.at(0.0)[1]))
798                    }
799                    _ => None,
800                };
801                let Some(spans) = spline(&points, before, after) else { return bad };
802                here = end.clone();
803                caps.extend(spans.iter().map(|_| feed(index, index + run)));
804                out.extend(spans);
805                continue;
806            }
807            Piece::Line(to) if to.len() == here.len() => {
808                let length = distance(to, &here);
809                Geo::Line {
810                    dir: to.iter().zip(&here).map(|(t, h)| (t - h) / length).collect(),
811                    from: here.clone(),
812                    length,
813                }
814            }
815            Piece::Arc { to, centre, clockwise, .. } if here.len() == 2 && to.len() == 2 && centre.len() == 2 => {
816                let radius = distance(&here, centre);
817                // The arc starts where the path stands and takes its radius from there. What it is, a full turn
818                // or by which angle it turns, is told from the points the file states: the end stated before
819                // it and its own. Only a first piece has none before it and is told from where the machine
820                // stands, with the slack that needs; too near to there it is not told at all (`FIRST_ARC`).
821                let (from, slack) = match stated {
822                    Some(p) => (&p[..], ARC_TOLERANCE),
823                    None => (&here[..], slack),
824                };
825                if !(radius > 1e-6 && (distance(to, centre) - distance(from, centre)).abs() < slack) {
826                    return bad;
827                }
828                if stated.is_none() && distance(to, from) < FIRST_ARC.max(10.0 * slack) {
829                    return Err(CommandError { key: "error-path-first-arc" });
830                }
831                let angle = |p: &[f64]| (p[1] - centre[1]).atan2(p[0] - centre[0]);
832                let turn = if *clockwise { -1.0 } else { 1.0 };
833                let full = distance(to, from) < 1e-9;
834                let sweep = if full {
835                    std::f64::consts::TAU
836                } else {
837                    (turn * (angle(to) - angle(from))).rem_euclid(std::f64::consts::TAU)
838                };
839                Geo::Arc {
840                    centre: [centre[0], centre[1]],
841                    radius,
842                    from_angle: angle(&here),
843                    turn,
844                    length: sweep * radius,
845                }
846            }
847            // The centre may carry the machine's other axes too (a program's), of which the arc takes the first three.
848            Piece::Arc { to, centre, clockwise, plane }
849                if here.len() >= 3 && to.len() == here.len() && (centre.len() == 3 || centre.len() == here.len()) =>
850            {
851                let centre = &centre[..3];
852                // Its end is told from the end stated before it, as on two axes. An arc in space is never a full turn,
853                // so a first arc needs no distance from where the machine stands. On more than three axes the arc is
854                // on the first three, and the others go along with it (`arc_on`).
855                let (from, slack) = match stated {
856                    Some(p) => (&p[..], ARC_TOLERANCE),
857                    None => (&here[..], slack),
858                };
859                if (distance(&to[..3], centre) - distance(&from[..3], centre)).abs() >= slack {
860                    return bad;
861                }
862                let Some(geo) = arc_on(&here, to, centre, *clockwise, *plane) else { return bad };
863                geo
864            }
865            _ => return bad,
866        };
867        if geo.length() > 1e-9 {
868            // The next piece starts where this one really ends, so the path has no jump.
869            here = geo.at(geo.length())[0].clone();
870            out.push(geo);
871            caps.push(feed(index, index + 1));
872        }
873        stated = Some(piece_end(piece));
874        off = off.max(distance(&here, piece_end(piece)));
875    }
876    // Below a nanometre it is rounding.
877    if out.is_empty() { bad } else { Ok((out, if off > 1e-9 { off } else { 0.0 }, caps)) }
878}
879
880/// An arc in space from `from` around `centre` towards `to`, in the plane of the three points, turning clockwise or
881/// counter-clockwise as seen from the side its normal points to: the normal taken upwards (+z), for a vertical plane
882/// towards the viewer (-y), for the y-z plane along +x (see the top of the file). `None` where the three points leave
883/// the plane open (on one line: a half or a full turn) or the radius is nil.
884fn arc3(from: &[f64], to: &[f64], centre: &[f64], clockwise: bool, plane: Option<[f64; 3]>) -> Option<Geo> {
885    let at = |p: &[f64]| [p[0] - centre[0], p[1] - centre[1], p[2] - centre[2]];
886    let (a, b) = (at(from), at(to));
887    let radius = norm3(a);
888    let mut normal = cross3(a, b);
889    let mut size = norm3(normal);
890    if radius < 1e-6 {
891        return None;
892    }
893    if size < 1e-9 * radius * norm3(b) {
894        // A half turn (end opposite the start) leaves the plane open: the one the program states (`plane`, which the
895        // start's radius has to lie in), else the first of the x-y, x-z and y-z planes that holds the start's radius, as
896        // G17 before G18 before G19 would. A full turn has no end to tell it from.
897        if dot3(a, b) >= 0.0 {
898            return None;
899        }
900        let flat = |i: usize| a[i].abs() < 1e-9 * radius;
901        normal = match plane {
902            Some(n) if norm3(n) > 0.0 && dot3(a, n).abs() <= 1e-9 * radius * norm3(n) => n,
903            Some(_) => return None,
904            None if flat(2) => [0.0, 0.0, 1.0],
905            None if flat(1) => [0.0, 1.0, 0.0],
906            None if flat(0) => [1.0, 0.0, 0.0],
907            None => return None,
908        };
909        size = norm3(normal);
910    }
911    normal = normal.map(|x| x / size);
912    let view = if normal[2].abs() > 1e-9 {
913        [0.0, 0.0, 1.0]
914    } else if normal[1].abs() > 1e-9 {
915        [0.0, -1.0, 0.0]
916    } else {
917        [1.0, 0.0, 0.0]
918    };
919    if dot3(normal, view) < 0.0 {
920        normal = normal.map(|x| -x);
921    }
922    // Counter-clockwise seen from the normal's side turns from u towards normal x u.
923    let u = a.map(|x| x / radius);
924    let w = cross3(normal, u).map(|x| if clockwise { -x } else { x });
925    let angle = dot3(b, w).atan2(dot3(b, u)).rem_euclid(std::f64::consts::TAU);
926    Some(Geo::Arc3 { centre: [centre[0], centre[1], centre[2]], u, w, radius, length: angle * radius })
927}
928
929/// `arc3` on three axes or more: the arc on the first three (the centre has three positions), and on a machine with more
930/// axes the others carried along from where the arc starts to its end, each evenly with the distance (`Geo::Carried`):
931/// a SCARA's or a delta's turn, an arm's orientation in tool space.
932///
933/// An arm's orientation (rx, ry, rz) goes along by the quaternion slerp between its two ends, as a line's does
934/// (`shape` marks the piece, `Geo::Carried::turn`): the tool turns at an even rate about one axis, which per component
935/// of the rotation vector it would not.
936fn arc_on(from: &[f64], to: &[f64], centre: &[f64], clockwise: bool, plane: Option<[f64; 3]>) -> Option<Geo> {
937    let arc = arc3(&from[..3], &to[..3], centre, clockwise, plane)?;
938    if from.len() == 3 {
939        return Some(arc);
940    }
941    let by: Vec<f64> = to[3..].iter().zip(&from[3..]).map(|(t, f)| t - f).collect();
942    let length = (arc.length().powi(2) + by.iter().map(|b| b * b).sum::<f64>()).sqrt();
943    Some(Geo::Carried { arc: Box::new(arc), from: from[3..].to_vec(), by, length, turn: None })
944}
945
946/// A planned pose with what rounding has put outside an axis's range back on its end. A path that ends on the
947/// end of a stroke, or runs along it, comes out of the sines and sums a few 1e-17 m beyond it, and would be
948/// refused as leaving the travel range.
949fn within(axes: &[AxisInfo], mut pose: Vec<f64>) -> Vec<f64> {
950    for (p, axis) in pose.iter_mut().zip(axes) {
951        let inside = p.clamp(axis.min, axis.max);
952        if (*p - inside).abs() < 1e-9 {
953            *p = inside;
954        }
955    }
956    pose
957}
958
959/// A corner: the direction turns by more than 1 mrad from one piece to the next. The path stops there, unless
960/// `round_corners` has rounded it.
961fn corner(a: &Geo, b: &Geo) -> bool {
962    distance(&a.at(a.length())[1], &b.at(0.0)[1]) > 1e-3
963}
964
965/// The distance from the point `p` to the straight piece from `a` to `b`.
966fn to_segment(p: &[f64], a: &[f64], b: &[f64]) -> f64 {
967    let ab: Vec<f64> = b.iter().zip(a).map(|(b, a)| b - a).collect();
968    let ap: Vec<f64> = p.iter().zip(a).map(|(p, a)| p - a).collect();
969    let along = (dot(&ap, &ab) / dot(&ab, &ab)).clamp(0.0, 1.0);
970    ap.iter().zip(&ab).map(|(p, d)| (p - along * d).powi(2)).sum::<f64>().sqrt()
971}
972
973/// The curve that rounds a corner between two lines (`round_corners`): from the point `d` before the corner `at` on the
974/// line coming in (direction `ta`) to the point `d` after it on the line going out (`tb`), a polynomial in u from 0 to
975/// 2 d that leaves and arrives in the lines' directions at a speed by u of 1, with no curvature at either end:
976///
977/// ```text
978/// p(u) = at - d ta + ta u + (tb - ta) (u^3 / (4 d^2) - u^4 / (16 d^3))
979/// ```
980///
981/// (the quintic through both ends with those first and zero second derivatives, whose fifth power drops out). So the
982/// path keeps its direction and its curvature (zero) at both ends: no step in the axes' accelerations. Its middle, u = d,
983/// is 3 d / 16 (tb - ta) from the corner, which is 3 d sin(theta) / 16 off each line for the turn theta, and there it
984/// moves at (ta + tb) / 2 by u and turns at 3 (tb - ta) / (4 d), at right angles: a curvature of
985/// 3 |tb - ta| / (d |ta + tb|^2), for a right angle 3 sqrt(2) / (2 d), a radius of sqrt(2) d / 3.
986/// `None` where it nearly stops (`span`): a turn of nearly half a circle.
987fn corner_curve(at: &[f64], ta: &[f64], tb: &[f64], d: f64) -> Option<Geo> {
988    let (dims, change) = (at.len(), wide(&tb.iter().zip(ta).map(|(b, a)| b - a).collect::<Vec<_>>())?);
989    let (ta, start) = (wide(ta)?, wide(&at.iter().zip(ta).map(|(p, t)| p - d * t).collect::<Vec<_>>())?);
990    let zero = [0.0; WIDEST];
991    let c = [start, ta, zero, change.map(|x| x / (4.0 * d * d)), change.map(|x| -x / (16.0 * d * d * d)), zero];
992    span(c, 2.0 * d, dims)
993}
994
995/// The curve that rounds a corner next to an arc or a spline (`round_corners`): the quintic in u from 0 to `h` that leaves
996/// `p0` in the unit direction `t0` with the curvature vector `k0` and arrives at `p1` in `t1` with `k1`, at a speed by u of
997/// 1 at both ends (quintic Hermite interpolation, in tau = u / h with the derivatives h t and h^2 k):
998///
999/// ```text
1000/// p = p0 + h t0 tau + h^2 k0 / 2 tau^2
1001///   + (10 (p1 - p0) - h (6 t0 + 4 t1) - h^2 (3 k0 - k1) / 2) tau^3
1002///   + (15 (p0 - p1) + h (8 t0 + 7 t1) + h^2 (3 k0 / 2 - k1)) tau^4
1003///   + (6 (p1 - p0) - 3 h (t0 + t1) - h^2 (k0 - k1) / 2) tau^5
1004/// ```
1005///
1006/// So the path keeps its place, direction and curvature at both ends (G2). Between two lines (k = 0, h = 2 d, p0 and p1
1007/// `d` either side of the corner) it is `corner_curve`'s curve. `None` where it nearly stops (`span`).
1008fn hermite_curve(start: [&[f64]; 3], end: [&[f64]; 3], h: f64) -> Option<Geo> {
1009    let dims = start[0].len();
1010    let ([p0, t0, k0], [p1, t1, k1]) = (start.map(wide), end.map(wide));
1011    let (p0, t0, k0, p1, t1, k1) = (p0?, t0?, k0?, p1?, t1?, k1?);
1012    let tau: [Wide; 6] = [
1013        p0,
1014        std::array::from_fn(|i| h * t0[i]),
1015        std::array::from_fn(|i| h * h * k0[i] / 2.0),
1016        std::array::from_fn(|i| {
1017            10.0 * (p1[i] - p0[i]) - h * (6.0 * t0[i] + 4.0 * t1[i]) - h * h * (3.0 * k0[i] - k1[i]) / 2.0
1018        }),
1019        std::array::from_fn(|i| {
1020            15.0 * (p0[i] - p1[i]) + h * (8.0 * t0[i] + 7.0 * t1[i]) + h * h * (1.5 * k0[i] - k1[i])
1021        }),
1022        std::array::from_fn(|i| 6.0 * (p1[i] - p0[i]) - 3.0 * h * (t0[i] + t1[i]) - h * h * (k0[i] - k1[i]) / 2.0),
1023    ];
1024    let c: Poly = std::array::from_fn(|m| tau[m].map(|x| x / h.powi(m as i32)));
1025    span(c, h, dims)
1026}
1027
1028/// The piece with `from` cut off its start and `to` off its end (both along it), for a corner rounded beside it. Lines,
1029/// arcs and spline spans; `None` for the others, and where nothing is left.
1030fn trimmed(geo: &Geo, from: f64, to: f64) -> Option<Geo> {
1031    let length = geo.length() - from - to;
1032    if length <= 1e-12 {
1033        return None;
1034    }
1035    Some(match geo {
1036        Geo::Line { from: start, dir, .. } => {
1037            Geo::Line { from: start.iter().zip(dir).map(|(p, d)| p + from * d).collect(), dir: dir.clone(), length }
1038        }
1039        Geo::Arc { centre, radius, from_angle, turn, .. } => Geo::Arc {
1040            centre: *centre,
1041            radius: *radius,
1042            from_angle: from_angle + turn * from / radius,
1043            turn: *turn,
1044            length,
1045        },
1046        Geo::Arc3 { centre, u, w, radius, .. } => {
1047            let (sin, cos) = (from / radius).sin_cos();
1048            Geo::Arc3 {
1049                centre: *centre,
1050                u: std::array::from_fn(|i| cos * u[i] + sin * w[i]),
1051                w: std::array::from_fn(|i| -sin * u[i] + cos * w[i]),
1052                radius: *radius,
1053                length,
1054            }
1055        }
1056        Geo::Carried { arc, from: start, by, length: whole, turn } => {
1057            let share = arc.length() / whole;
1058            let arc = trimmed(arc, from * share, to * share)?;
1059            // The orientation's slerp between the new ends is the same slerp, cut.
1060            let (new_from, new_by) = if turn.is_some() {
1061                let (a, b) = (
1062                    carried_tail(start, by, *whole, *turn, from),
1063                    carried_tail(start, by, *whole, *turn, from + length),
1064                );
1065                let by = b.iter().zip(&a).map(|(b, a)| b - a).collect();
1066                (a, by)
1067            } else {
1068                (
1069                    start.iter().zip(by).map(|(f, b)| f + b * from / whole).collect(),
1070                    by.iter().map(|b| b * length / whole).collect(),
1071                )
1072            };
1073            Geo::Carried { arc: Box::new(arc), from: new_from, by: new_by, length, turn: *turn }
1074        }
1075        Geo::Spline { c, h, travelled, dims, .. } => {
1076            let (u0, u1) = (spline_u(c, *h, travelled, from), spline_u(c, *h, travelled, geo.length() - to));
1077            span(poly_shift(c, u0), u1 - u0, *dims)?
1078        }
1079        Geo::Slerp { .. } | Geo::Clothoid { .. } => return None,
1080    })
1081}
1082
1083/// How far the points of `curve` are from the path it replaces, at most: the last `back` of `a` and the first `ahead` of
1084/// `b`, each looked at at 65 places (as two broken lines, which lie within (d / 64)^2 / (8 r) of an arc of radius r).
1085fn off_corner(curve: &Geo, a: &Geo, back: f64, b: &Geo, ahead: f64) -> f64 {
1086    let la = a.length();
1087    let line: Vec<Vec<f64>> = (0..=64)
1088        .map(|k| a.at(la - back + back * k as f64 / 64.0)[0].clone())
1089        .chain((1..=64).map(|k| b.at(ahead * k as f64 / 64.0)[0].clone()))
1090        .collect();
1091    let off = |u: f64| {
1092        let p = &curve.at(curve.length() * u)[0];
1093        line.windows(2).map(|w| to_segment(p, &w[0], &w[1])).fold(f64::INFINITY, f64::min)
1094    };
1095    let (best, _) = (0..=64).map(|k| (k, off(k as f64 / 64.0))).fold((0, 0.0), |m, c| if c.1 > m.1 { c } else { m });
1096    // The peak can lie between samples (the cusp next to an arc): golden-section it between the neighbours of the best.
1097    let (mut lo, mut hi) = ((best as f64 - 1.0).max(0.0) / 64.0, (best as f64 + 1.0).min(64.0) / 64.0);
1098    let phi = 0.5 * (5f64.sqrt() - 1.0);
1099    let mut peak = off(best as f64 / 64.0);
1100    for _ in 0..30 {
1101        let (x1, x2) = (hi - phi * (hi - lo), lo + phi * (hi - lo));
1102        let (f1, f2) = (off(x1), off(x2));
1103        peak = peak.max(f1).max(f2);
1104        if f1 < f2 { lo = x1 } else { hi = x2 }
1105    }
1106    peak
1107}
1108
1109/// The curve that rounds the corner between `a` and `b`, either of them an arc or a spline (`hermite_curve`), from `d`
1110/// before the corner on `a` to `d` after it on `b`, with `d` as large as keeps it within `tolerance` of them, at most
1111/// `most`; with d and its deviation. The deviation grows about as d (3 d sin(theta) / 16 for the turn theta where the
1112/// curvature is small against 1 / d, as between lines), so d is scaled by the tolerance over the deviation until the
1113/// deviation is within 2 % below the tolerance, at most 30 times.
1114fn round_corner(a: &Geo, b: &Geo, tolerance: f64, most: f64) -> Option<(f64, Geo, f64)> {
1115    let curve_at = |d: f64| {
1116        let ([p0, t0, k0], [p1, t1, k1]) = (a.at(a.length() - d), b.at(d));
1117        let curve = hermite_curve([&p0, &t0, &k0], [&p1, &t1, &k1], 2.0 * d)?;
1118        let off = off_corner(&curve, a, d, b, d);
1119        Some((d, curve, off))
1120    };
1121    let mut best: Option<(f64, Geo, f64)> = None;
1122    let mut d = most;
1123    for _ in 0..30 {
1124        let Some(found) = curve_at(d) else {
1125            d *= 0.5;
1126            continue;
1127        };
1128        let off = found.2;
1129        if off <= tolerance {
1130            let done = off >= 0.98 * tolerance || d >= most;
1131            if best.as_ref().is_none_or(|b| found.0 > b.0) {
1132                best = Some(found);
1133            }
1134            if done {
1135                break;
1136            }
1137        }
1138        d = (d * 0.99 * tolerance / off.max(1e-300)).min(most);
1139    }
1140    best
1141}
1142
1143/// Rounds each corner (`corner`) by a curve as far from the corner as `tolerance` allows, as a CNC rounds a corner within
1144/// a tolerance (Siemens' G642) or a robot passes a point in a zone: the path no longer stops there. Between two lines the
1145/// curve is `corner_curve`'s: it starts and ends `d` from the corner on the lines, d such that the curve is nowhere
1146/// further from the two lines than the tolerance (for a right angle d = 16 tolerance / 3); the deviation is measured on
1147/// the curve at 65 places against the two pieces of line it replaces, and it scales with d. Where an arc or a spline
1148/// meets the corner the curve is `hermite_curve`'s, from `d` back along the piece before to `d` on along the one after,
1149/// with their directions and curvatures there (G2), d found by `round_corner`. Either way d is no more than half of either
1150/// piece, so that two rounded corners never overlap. A turn of nearly half a circle (where the curve would nearly stop,
1151/// `span`) and a corner on more than `WIDEST` axes stay corners.
1152fn round_corners(geo: Vec<Geo>, tolerance: f64) -> (Vec<Geo>, f64) {
1153    let n = geo.len();
1154    if tolerance <= 0.0 || n < 2 {
1155        return (geo, 0.0);
1156    }
1157    // Per piece how much of it its corners take at its start and its end, and the curve at each junction.
1158    let (mut cut, mut curves, mut off) = (vec![[0.0f64; 2]; n], vec![None; n + 1], 0f64);
1159    let roundable = |g: &Geo| !matches!(g, Geo::Slerp { .. } | Geo::Clothoid { .. });
1160    for j in 1..n {
1161        if !corner(&geo[j - 1], &geo[j]) || !roundable(&geo[j - 1]) || !roundable(&geo[j]) {
1162            continue;
1163        }
1164        let most = 0.5 * geo[j - 1].length().min(geo[j].length());
1165        let (d, curve, by) = match (&geo[j - 1], &geo[j]) {
1166            (Geo::Line { dir: ta, .. }, Geo::Line { from: at, dir: tb, .. }) => {
1167                // The deviation for d = 1, against the corner's two lines as far as the curve reaches.
1168                let Some(unit) = corner_curve(at, ta, tb, 1.0) else { continue };
1169                let (before, after): (Vec<f64>, Vec<f64>) =
1170                    (at.iter().zip(ta).map(|(p, t)| p - t).collect(), at.iter().zip(tb).map(|(p, t)| p + t).collect());
1171                let per_d = (0..=64)
1172                    .map(|k| {
1173                        let p = &unit.at(unit.length() * k as f64 / 64.0)[0];
1174                        to_segment(p, &before, at).min(to_segment(p, at, &after))
1175                    })
1176                    .fold(0.0, f64::max);
1177                let d = (tolerance / per_d).min(most);
1178                let Some(curve) = corner_curve(at, ta, tb, d) else { continue };
1179                (d, curve, per_d * d)
1180            }
1181            (a, b) => {
1182                let Some(found) = round_corner(a, b, tolerance, most) else { continue };
1183                found
1184            }
1185        };
1186        (cut[j - 1][1], cut[j][0], curves[j]) = (d, d, Some(curve));
1187        off = off.max(by);
1188    }
1189    let mut out = Vec::new();
1190    for (i, piece) in geo.into_iter().enumerate() {
1191        out.extend(curves[i].take());
1192        if cut[i] == [0.0; 2] {
1193            out.push(piece);
1194        } else {
1195            // Two corners that each take half of a piece leave nothing of it.
1196            out.extend(trimmed(&piece, cut[i][0], cut[i][1]));
1197        }
1198    }
1199    (out, off)
1200}
1201
1202// ---------------------------------------------------------------------------------------------
1203// Transition curves.
1204
1205/// What a transition curve joins: a straight line through a point, or a circle with its curvature.
1206#[derive(Clone, Copy)]
1207enum Side {
1208    Line { point: [f64; 2], dir: [f64; 2] },
1209    Circle { centre: [f64; 2], curvature: f64 },
1210}
1211
1212/// The transition curve from `a` to `b`, which are apart by `gap` where they are nearest: a line and a
1213/// circle that the line misses by the gap, a circle inside a wider one, or two circles side by side that
1214/// turn opposite ways. A curve whose curvature goes evenly from that of `a` to that of `b` joins two such
1215/// with no step in position, direction or curvature for exactly one length, found here by halving.
1216fn transition(a: Side, b: Side, gap: f64) -> Option<Geo> {
1217    // The curve laid from the origin along +x: the centre of the circle that fits it at its end.
1218    let centre_at_end = |k0: f64, k1: f64, length: f64| {
1219        let [end, dir, _] = Geo::Clothoid { from: [0.0, 0.0], heading: 0.0, k0, k1, length, plane: None }.at(length);
1220        [end[0] - dir[1] / k1, end[1] + dir[0] / k1]
1221    };
1222    // To first order the gap is the change of curvature times length squared / 24.
1223    let longest = |change: f64| 2.0 * (24.0 * gap / change.abs()).sqrt();
1224    match (a, b) {
1225        (Side::Line { point, dir }, Side::Circle { centre, curvature: k }) => {
1226            let to_centre = [centre[0] - point[0], centre[1] - point[1]];
1227            // The centre is this far beside the line; the curve's own circle has to end up as far beside +x.
1228            let beside = (dir[0] * to_centre[1] - dir[1] * to_centre[0]).abs();
1229            let length =
1230                largest(0.0, longest(k), |length| length == 0.0 || centre_at_end(0.0, k, length)[1].abs() <= beside);
1231            let along = dir[0] * to_centre[0] + dir[1] * to_centre[1] - centre_at_end(0.0, k, length)[0];
1232            let from = [point[0] + along * dir[0], point[1] + along * dir[1]];
1233            (length > 0.0 && length < longest(k)).then(|| Geo::Clothoid {
1234                from,
1235                heading: dir[1].atan2(dir[0]),
1236                k0: 0.0,
1237                k1: k,
1238                length,
1239                plane: None,
1240            })
1241        }
1242        // The same curve run backwards: every direction and every turn is the other way round.
1243        (Side::Circle { centre, curvature }, Side::Line { point, dir }) => {
1244            let back = transition(
1245                Side::Line { point, dir: [-dir[0], -dir[1]] },
1246                Side::Circle { centre, curvature: -curvature },
1247                gap,
1248            )?;
1249            let [end, dir, _] = back.at(back.length());
1250            Some(Geo::Clothoid {
1251                from: [end[0], end[1]],
1252                heading: (-dir[1]).atan2(-dir[0]),
1253                k0: curvature,
1254                k1: 0.0,
1255                length: back.length(),
1256                plane: None,
1257            })
1258        }
1259        (Side::Circle { centre: ca, curvature: k0 }, Side::Circle { centre: cb, curvature: k1 }) => {
1260            // The two circles of the curve start out touching and move apart (or into each other) as it
1261            // gets longer; it fits when their centres are as far apart as the real ones.
1262            let apart = |length: f64| {
1263                if length == 0.0 {
1264                    (1.0 / k1 - 1.0 / k0).abs()
1265                } else {
1266                    distance(&centre_at_end(k0, k1, length), &[0.0, 1.0 / k0])
1267                }
1268            };
1269            let moved = (distance(&ca, &cb) - apart(0.0)).abs();
1270            let length = largest(0.0, longest(k1 - k0), |length| (apart(length) - apart(0.0)).abs() <= moved);
1271            // Turned so that the line between the curve's centres lies on the line between the real ones.
1272            let end = centre_at_end(k0, k1, length);
1273            let heading = (cb[1] - ca[1]).atan2(cb[0] - ca[0]) - (end[1] - 1.0 / k0).atan2(end[0]);
1274            let from = [ca[0] + heading.sin() / k0, ca[1] - heading.cos() / k0];
1275            (length > 0.0 && length < longest(k1 - k0)).then_some(Geo::Clothoid {
1276                from,
1277                heading,
1278                k0,
1279                k1,
1280                length,
1281                plane: None,
1282            })
1283        }
1284        _ => None,
1285    }
1286}
1287
1288/// Puts transition curves where a line and an arc, or two arcs, meet in the same direction. There the
1289/// curvature steps, and with it the acceleration towards the centre, which is why `junction_speed` lets the
1290/// path pass such a place only at a crawl. A transition curve changes the curvature evenly over its length
1291/// L instead, so at the speed v the acceleration towards the centre changes at the rate v^3 dk / L (dk: the
1292/// step of the curvature, 1 / r for a line into an arc of radius r).
1293///
1294/// Such a curve does not fit between a line and a circle that touch: it needs the circle moved in by
1295///
1296/// ```text
1297/// e = L^2 / (24 r)        (first term; the code solves the exact length)
1298/// ```
1299///
1300/// So every blended arc keeps its centre and gets a radius smaller by its e, and the transition curves
1301/// replace about L / 2 of the pieces on either side of each junction. The planned path is then nowhere
1302/// further from the given one than the largest e, which is what is reported. Each arc gets its own L: the
1303/// length the faster of its junctions needs to be passed at the speed of its slower piece with 0.4 of the jerk
1304/// limit, L = v^3 dk / (0.4 j), but no longer than the tolerance allows on it, L = sqrt(24 e_max r). The speed v
1305/// is that of the plan: the axis limits for `plan`, the motors for `plan_time_optimal`. Where L is shorter than
1306/// needed, `limits` lowers the speed on the curve. A junction of a line and an arc so gets the curve its own speed
1307/// asks for, not the one the fastest junction of the path asks for.
1308///
1309/// With an arc moved in by e = L^2 / (24 r), a line beside it is apart from it by e and the curve there comes out
1310/// L long. Two arcs turning opposite ways are apart by the sum of their e, which fits whatever their L. Two arcs
1311/// turning the same way are apart by the difference of their e, which is positive for one L only: arcs that hand
1312/// over to one another turning the same way share one L (the longest any of them needs, the shortest any allows).
1313/// An arc whose one end has to stay where it is given (at a corner, at an end of the path, or where a
1314/// spline joins it, see `ease`) and whose other end meets a line or an arc in its direction is moved another way:
1315/// its circle shrinks by s and moves towards the fixed end by s, so that it still passes through that end in the
1316/// same direction, and is then inside its old circle by s (1 - cos phi) at its other end, phi being the angle the arc
1317/// turns through. That gap is made e, so s = e / (1 - cos phi), for arcs whose radius stays above half of what it
1318/// was; next to an arc the gap is taken as e as well, and `transition` fits the curve to where the circles really
1319/// are. Halfway round, phi = pi, the new circle is 2 s inside the old one; so an arc that turns more than half a
1320/// circle gets s no larger than half the tolerance, e = (tolerance / 2) (1 - cos phi) at its free end and a shorter
1321/// L. The exact distance of the two circles on the arc is reported. A whole turn has no free end to move and stays
1322/// as it is. An arc with both ends fixed meets nothing in its direction and needs no curve. Where a curve would not
1323/// fit (a wider arc moved in beside a tighter one that was not) both arcs stay as given. Two arcs of the same
1324/// curvature (to 1e-9 relative: one circle) get no curve between them. Pieces too short for their curves halve
1325/// every L of the path, up to eight times; then the path stays as given. So does a blend in which a curve would
1326/// take more of an arc than it can reach, or whose length differs from the given one's by more than the curves'
1327/// lengths and the moved arcs' shrink times their angles (a whole turn gained or lost).
1328fn blend(geo: Vec<Geo>, speed: &[f64], axes: &[AxisInfo], tolerance: f64) -> (Vec<Geo>, f64) {
1329    let n = geo.len();
1330    let k: Vec<f64> =
1331        geo.iter().map(|g| if let Geo::Arc { radius, turn, .. } = g { turn / radius } else { 0.0 }).collect();
1332    // Junction j is where piece j - 1 hands over to piece j; it gets a curve where both are lines or arcs that
1333    // meet in the same direction.
1334    let spline = |i: usize| matches!(geo[i], Geo::Spline { .. });
1335    let tangent: Vec<bool> =
1336        (0..=n).map(|j| j > 0 && j < n && !corner(&geo[j - 1], &geo[j]) && !spline(j - 1) && !spline(j)).collect();
1337    let free: Vec<bool> = (0..n).map(|i| k[i] != 0.0 && tangent[i] && tangent[i + 1]).collect();
1338    // The angle an arc turns through.
1339    let sweep = |i: usize| geo[i].length() * k[i].abs();
1340    // An arc fixed at one end: Some(true) at its start, Some(false) at its end. Not a whole turn, whose far end is
1341    // its fixed one (1 - cos phi = 0).
1342    let fixed: Vec<Option<bool>> = (0..n)
1343        .map(|i| match (k[i] != 0.0 && 1.0 - sweep(i).cos() > 1e-9, tangent[i], tangent[i + 1]) {
1344            (true, true, false) => Some(false),
1345            (true, false, true) => Some(true),
1346            _ => None,
1347        })
1348        .collect();
1349    let blended = |i: usize| free[i] || fixed[i].is_some();
1350    if !(0..n).any(blended) {
1351        return (geo, 0.0);
1352    }
1353    let jerk = axes.iter().map(|a| a.max_jerk).fold(f64::INFINITY, f64::min);
1354    let needed = |j: usize| speed[j - 1].min(speed[j]).powi(3) * (k[j] - k[j - 1]).abs() / (0.4 * jerk);
1355    // Per arc: the longest L its junctions need, and the longest the tolerance allows on it (for an arc fixed at one
1356    // end that turns more than half a circle, s = e / (1 - cos phi) up to half the tolerance).
1357    let mut want: Vec<[f64; 2]> = (0..n)
1358        .map(|i| {
1359            if !blended(i) {
1360                return [0.0; 2];
1361            }
1362            let room = if fixed[i].is_some() && sweep(i) > std::f64::consts::PI {
1363                0.5 * tolerance * (1.0 - sweep(i).cos())
1364            } else {
1365                tolerance
1366            };
1367            [
1368                [i, i + 1].into_iter().filter(|&j| tangent[j]).map(needed).fold(0.0, f64::max),
1369                (24.0 * room / k[i].abs()).sqrt(),
1370            ]
1371        })
1372        .collect();
1373    // Arcs that hand over to one another turning the same way share one L, along the whole chain of them.
1374    for _ in 0..n {
1375        for j in (1..n).filter(|&j| tangent[j] && k[j] * k[j - 1] > 0.0 && blended(j) && blended(j - 1)) {
1376            let shared = [want[j][0].max(want[j - 1][0]), want[j][1].min(want[j - 1][1])];
1377            (want[j - 1], want[j]) = (shared, shared);
1378        }
1379    }
1380    let mut length: Vec<f64> = want.iter().map(|[need, most]| need.min(*most)).collect();
1381    for _ in 0..8 {
1382        if let Some(blended) = blend_with(&geo, &k, &free, &fixed, &tangent, &length) {
1383            return blended;
1384        }
1385        length.iter_mut().for_each(|l| *l /= 2.0);
1386    }
1387    (geo, 0.0)
1388}
1389
1390/// `blend` for one length of the transition curves per arc; `None` if a piece is too short for its curves.
1391fn blend_with(
1392    geo: &[Geo],
1393    k: &[f64],
1394    free: &[bool],
1395    fixed: &[Option<bool>],
1396    tangent: &[bool],
1397    length: &[f64],
1398) -> Option<(Vec<Geo>, f64)> {
1399    let n = geo.len();
1400    // The gap each arc leaves to a line beside it: moved in by it, or (fixed at one end) shrunk and moved.
1401    let mut inset: Vec<f64> = (0..n)
1402        .map(|i| if free[i] || fixed[i].is_some() { k[i].abs() * length[i] * length[i] / 24.0 } else { 0.0 })
1403        .collect();
1404    // The circle each arc is laid on: centre and radius. A fixed arc's circle moves towards its fixed end.
1405    let circle = |inset: &[f64], i: usize| match &geo[i] {
1406        Geo::Arc { centre, radius, from_angle, turn, length } => Some(match fixed[i] {
1407            None => (*centre, radius - inset[i]),
1408            Some(at_start) => {
1409                let sweep = length / radius;
1410                let shrink = inset[i] / (1.0 - sweep.cos());
1411                let (sin, cos) = if at_start { from_angle.sin_cos() } else { (from_angle + turn * sweep).sin_cos() };
1412                ([centre[0] + shrink * cos, centre[1] + shrink * sin], radius - shrink)
1413            }
1414        }),
1415        _ => None,
1416    };
1417    for i in 0..n {
1418        if let (Some(_), Some((_, moved)), Geo::Arc { radius, .. }) = (fixed[i], circle(&inset, i), &geo[i])
1419            && moved < 0.5 * radius
1420        {
1421            inset[i] = 0.0;
1422        }
1423    }
1424    // Curvatures this close are one (two arcs on one circle come out with radii apart by rounding), and pieces this
1425    // close touch: a curve between them would be built from rounding, and may take any angle of the arcs.
1426    let same = |j: usize| (k[j] - k[j - 1]).abs() <= 1e-9 * k[j].abs().max(k[j - 1].abs());
1427    // How far apart the two pieces of junction j are once the arcs are moved in.
1428    let gap = |inset: &[f64], j: usize| {
1429        let (tighter, wider) = if k[j].abs() > k[j - 1].abs() { (j, j - 1) } else { (j - 1, j) };
1430        let gap = if k[j] * k[j - 1] < 0.0 { inset[j] + inset[j - 1] } else { inset[tighter] - inset[wider] };
1431        if gap.abs() < 1e-12 { 0.0 } else { gap }
1432    };
1433    let fits = |inset: &[f64], j: usize| gap(inset, j) >= 0.0 && (gap(inset, j) == 0.0 || !same(j));
1434    while let Some(j) = (1..n).find(|&j| tangent[j] && !fits(&inset, j)) {
1435        (inset[j - 1], inset[j]) = (0.0, 0.0);
1436    }
1437    let side = |i: usize| match &geo[i] {
1438        Geo::Arc { turn, .. } => {
1439            circle(&inset, i).map(|(centre, radius)| Side::Circle { centre, curvature: turn / radius })
1440        }
1441        Geo::Line { from, dir, .. } => Some(Side::Line { point: [from[0], from[1]], dir: [dir[0], dir[1]] }),
1442        Geo::Clothoid { .. } | Geo::Spline { .. } | Geo::Arc3 { .. } | Geo::Slerp { .. } | Geo::Carried { .. } => None,
1443    };
1444    let mut curves: Vec<Option<Geo>> = vec![None];
1445    for j in 1..n {
1446        let gap = gap(&inset, j);
1447        curves.push(if tangent[j] && gap > 0.0 { Some(transition(side(j - 1)?, side(j)?, gap)?) } else { None });
1448        // A curve that turns half a circle is no blend, and what it takes of an arc could no longer be told
1449        // from a whole turn more.
1450        if matches!(curves[j], Some(Geo::Clothoid { k0, k1, length, .. }) if 0.5 * (k0.abs() + k1.abs()) * length >= std::f64::consts::PI)
1451        {
1452            return None;
1453        }
1454    }
1455    curves.push(None);
1456    // The most a curve can take of an arc beside it: it replaces about half its length there, so less than its length
1457    // times its larger curvature, as an angle.
1458    let reach = |c: &Option<Geo>| match c {
1459        Some(Geo::Clothoid { k0, k1, length, .. }) => length * k0.abs().max(k1.abs()) + 1e-9,
1460        _ => 0.0,
1461    };
1462    let (mut out, mut off, mut cut) = (Vec::new(), 0f64, 0f64);
1463    for (i, piece) in geo.iter().enumerate() {
1464        // Where the curves before and after the piece leave of it.
1465        let start = curves[i].as_ref().map(|c| c.at(c.length())[0].clone());
1466        let end = curves[i + 1].as_ref().map(|c| c.at(0.0)[0].clone());
1467        let reaches = (reach(&curves[i]), reach(&curves[i + 1]));
1468        cut += curves[i].as_ref().map_or(0.0, Geo::length);
1469        out.extend(curves[i].take());
1470        out.push(match piece {
1471            Geo::Line { from, dir, length } => {
1472                let from = start.unwrap_or(from.clone());
1473                let to = end.unwrap_or_else(|| piece.at(*length)[0].clone());
1474                let length = from.iter().zip(&to).zip(dir).map(|((f, t), d)| (t - f) * d).sum::<f64>();
1475                Geo::Line { from, dir: dir.clone(), length }
1476            }
1477            // On two axes only: a slerp is a line of six.
1478            Geo::Slerp { .. } => piece.clone(),
1479            Geo::Arc { radius, from_angle, turn, length, .. } => {
1480                let (centre, moved) = circle(&inset, i)?;
1481                if moved <= 0.0 {
1482                    return None;
1483                }
1484                // The ends' angles seen from the new centre are those seen from the old one: a fixed end's centre
1485                // moves along the line to that end, and a free end is where the circle is nearest the line, in the
1486                // direction the old end had from the old centre.
1487                let angle = |p: &[f64]| (p[1] - centre[1]).atan2(p[0] - centre[0]);
1488                let sweep = length / radius;
1489                // What each curve takes of the arc, as the angle from the arc's own end to where the curve
1490                // meets it. (The angle between the two curves alone does not tell curves that overlap from
1491                // an arc: overlapping by more than the rest of the circle, they read as a short arc again,
1492                // and the path went round once more than the given one.)
1493                let taken = |by: &Option<Vec<f64>>, arc_end: f64, sign: f64| {
1494                    by.as_ref().map_or(0.0, |p| (sign * turn * (angle(p) - arc_end)).rem_euclid(std::f64::consts::TAU))
1495                };
1496                let (before, after) = (taken(&start, *from_angle, 1.0), taken(&end, from_angle + turn * sweep, -1.0));
1497                // More than a curve can take is a wrapped angle, a whole turn off: refused.
1498                if before > reaches.0 || after > reaches.1 {
1499                    return None;
1500                }
1501                let left = sweep - before - after;
1502                // How far the new circle is from the old one on the arc: the gap where it meets the line, and for a
1503                // fixed arc r - |s u + (r - s) v|, with u and v at the angle theta apart, which grows with theta up to
1504                // half a turn (2 s there): at its free end, or halfway round for an arc that turns further.
1505                let shrink = radius - moved;
1506                // On its smaller circle the arc is shorter by up to the shrink times its angle.
1507                cut += shrink.abs() * sweep;
1508                let swing = if fixed[i].is_some() {
1509                    radius
1510                        - (radius * radius - 2.0 * shrink * moved * (1.0 - sweep.min(std::f64::consts::PI).cos()))
1511                            .sqrt()
1512                } else {
1513                    0.0
1514                };
1515                off = off.max(inset[i]).max(swing);
1516                // Curves that overlap leave less than nothing: a length below zero, refused below.
1517                Geo::Arc {
1518                    centre,
1519                    radius: moved,
1520                    from_angle: start.as_deref().map_or(*from_angle, angle),
1521                    turn: *turn,
1522                    length: left * moved,
1523                }
1524            }
1525            Geo::Spline { .. } | Geo::Arc3 { .. } | Geo::Carried { .. } => piece.clone(),
1526            Geo::Clothoid { .. } => return None,
1527        });
1528        if out[out.len() - 1].length() <= 0.0 {
1529            return None;
1530        }
1531    }
1532    // The last check: the blended path is as long as the given one but for what the curves and the moved arcs may
1533    // change. A whole turn gained or lost (2 pi r) is far more.
1534    let length = |path: &[Geo]| path.iter().map(Geo::length).sum::<f64>();
1535    if (length(&out) - length(geo)).abs() > cut + 1e-9 {
1536        return None;
1537    }
1538    Some((out, off))
1539}
1540
1541/// A plane: a point on it, two directions in it at right angles, and its normal.
1542type Plane = [[f64; 3]; 4];
1543
1544/// `blend` on three axes. A line that meets an arc in its direction lies in the arc's plane, and so does a line or an
1545/// arc that meets that line in its direction and lies in the plane (to 1 nm). Such a run of pieces is blended in its
1546/// plane, on the coordinates along the first arc's start and its direction there (`blend` as on two axes, with the
1547/// speeds of the pieces in space), and laid back into space: lines and arcs as such, the curves with their plane.
1548/// The deviation is the one in the plane, as the plane's coordinates keep distances. A line between two arcs in
1549/// different planes lies in both; it is cut in half, and each half goes with its arc.
1550///
1551/// Where pieces do not share a plane, the junction is rounded in space, not here: a turn of more than 1 mrad between
1552/// two pieces (also between two arcs in different planes) is a corner, which `round_corners` rounds before this runs
1553/// (`Tolerance::corner`) by the G2 quintic of `hermite_curve`. The two tangents span a plane and the curve starts and
1554/// ends on it; where the arcs' curvature vectors leave it the curve takes their out-of-plane part (a torsion) so
1555/// that curvature stays continuous, and its distance to the given pieces is added to the reported deviation as for any
1556/// corner. Two tangents that are parallel (a turn below 1 mrad) need no rounding: the piece off the run's plane
1557/// (more than 1 nm) ends the run and the path passes the junction at the speed `junction_speed` allows, a step of
1558/// curvature only. A helix or any piece with torsion keeps its own geometry.
1559fn blend3(geo: Vec<Geo>, speed: &[f64], axes: &[AxisInfo], tolerance: f64) -> (Vec<Geo>, f64) {
1560    let plane_of =
1561        |g: &Geo| if let Geo::Arc3 { centre, u, w, .. } = g { Some([*centre, *u, *w, cross3(*u, *w)]) } else { None };
1562    let near =
1563        |p: &[f64], [o, _, _, normal]: &Plane| dot3([p[0] - o[0], p[1] - o[1], p[2] - o[2]], *normal).abs() < 1e-9;
1564    let lies_in = |g: &Geo, plane: &Plane| match g {
1565        Geo::Line { .. } => near(&g.at(0.0)[0], plane) && near(&g.at(g.length())[0], plane),
1566        Geo::Arc3 { centre, u, w, .. } => near(centre, plane) && norm3(cross3(cross3(*u, *w), plane[3])) < 1e-9,
1567        _ => false,
1568    };
1569    let (mut out, mut off) = (Vec::new(), 0f64);
1570    // The run being gathered, with the speeds of its pieces, and its plane once an arc has set it.
1571    let (mut run, mut plane): (Vec<(Geo, f64)>, Option<Plane>) = (Vec::new(), None);
1572    let mut flush = |run: Vec<(Geo, f64)>, plane: Option<Plane>| {
1573        let (blended, moved) = blend_in_plane(run, plane, axes, tolerance);
1574        out.extend(blended);
1575        off = off.max(moved);
1576    };
1577    for (g, v) in geo.into_iter().zip(speed.iter().copied()) {
1578        let joins = run.last().is_some_and(|(last, _)| {
1579            matches!(last, Geo::Line { .. } | Geo::Arc3 { .. })
1580                && matches!(g, Geo::Line { .. } | Geo::Arc3 { .. })
1581                && !corner(last, &g)
1582        });
1583        let own = plane_of(&g);
1584        match (joins, plane, own) {
1585            (true, Some(p), _) if lies_in(&g, &p) => run.push((g, v)),
1586            // An arc in another plane: a line before it that lies in both is shared out between the two runs.
1587            (true, Some(_), Some(q)) => {
1588                let shared = match run.last() {
1589                    Some((line @ Geo::Line { from, dir, length }, _)) if lies_in(line, &q) => {
1590                        let middle: Vec<f64> = from.iter().zip(dir).map(|(f, d)| f + 0.5 * length * d).collect();
1591                        Some((
1592                            Geo::Line { from: from.clone(), dir: dir.clone(), length: 0.5 * length },
1593                            Geo::Line { from: middle, dir: dir.clone(), length: 0.5 * length },
1594                        ))
1595                    }
1596                    _ => None,
1597                };
1598                let mut next = Vec::new();
1599                if let Some((first, second)) = shared {
1600                    let (_, speed) = run.pop().unwrap();
1601                    run.push((first, speed));
1602                    next.push((second, speed));
1603                }
1604                flush(std::mem::replace(&mut run, next), plane);
1605                (run, plane) = ([run, vec![(g, v)]].concat(), own);
1606            }
1607            // The first arc of a run of lines sets its plane; lines before it that do not lie in it stay as given.
1608            (true, None, Some(q)) => {
1609                let keep = run.len() - run.iter().rev().take_while(|(line, _)| lies_in(line, &q)).count();
1610                let rest = run.split_off(keep);
1611                flush(std::mem::replace(&mut run, rest), None);
1612                run.push((g, v));
1613                plane = own;
1614            }
1615            (true, None, None) => run.push((g, v)),
1616            _ => {
1617                flush(std::mem::replace(&mut run, vec![(g, v)]), plane);
1618                plane = own;
1619            }
1620        }
1621    }
1622    flush(run, plane);
1623    (out, off)
1624}
1625
1626/// A run of lines and arcs in one plane (`blend3`) blended there and laid back into space.
1627fn blend_in_plane(run: Vec<(Geo, f64)>, plane: Option<Plane>, axes: &[AxisInfo], tolerance: f64) -> (Vec<Geo>, f64) {
1628    let Some([o, e1, e2, normal]) = plane.filter(|_| run.len() > 1) else {
1629        return (run.into_iter().map(|(g, _)| g).collect(), 0.0);
1630    };
1631    let along = |d: &[f64]| vec![dot3([d[0], d[1], d[2]], e1), dot3([d[0], d[1], d[2]], e2)];
1632    let flat = |p: &[f64]| along(&[p[0] - o[0], p[1] - o[1], p[2] - o[2]]);
1633    let (pieces, speeds): (Vec<Geo>, Vec<f64>) = run
1634        .into_iter()
1635        .map(|(g, v)| {
1636            let g = match g {
1637                Geo::Line { from, dir, length } => Geo::Line { from: flat(&from), dir: along(&dir), length },
1638                Geo::Arc3 { centre, u, w, radius, length } => {
1639                    let c = flat(&centre);
1640                    Geo::Arc {
1641                        centre: [c[0], c[1]],
1642                        radius,
1643                        from_angle: dot3(u, e2).atan2(dot3(u, e1)),
1644                        turn: dot3(cross3(u, w), normal).signum(),
1645                        length,
1646                    }
1647                }
1648                other => other,
1649            };
1650            (g, v)
1651        })
1652        .unzip();
1653    let (blended, moved) = blend(pieces, &speeds, axes, tolerance);
1654    let up = |v: &[f64], point: f64| [0, 1, 2].map(|i| point * o[i] + v[0] * e1[i] + v[1] * e2[i]);
1655    let lifted = blended
1656        .into_iter()
1657        .map(|g| match g {
1658            Geo::Line { from, dir, length } => {
1659                Geo::Line { from: up(&from, 1.0).to_vec(), dir: up(&dir, 0.0).to_vec(), length }
1660            }
1661            Geo::Arc { centre, radius, from_angle, turn, length } => {
1662                let (sin, cos) = from_angle.sin_cos();
1663                Geo::Arc3 {
1664                    centre: up(&centre, 1.0),
1665                    u: up(&[cos, sin], 0.0),
1666                    w: up(&[-turn * sin, turn * cos], 0.0),
1667                    radius,
1668                    length,
1669                }
1670            }
1671            Geo::Clothoid { from, heading, k0, k1, length, .. } => {
1672                Geo::Clothoid { from, heading, k0, k1, length, plane: Some([o, e1, e2]) }
1673            }
1674            other => other,
1675        })
1676        .collect();
1677    (lifted, moved)
1678}
1679
1680/// How far the easing of a spline's end (`ease`) moves it at most, per change of curvature and square of the
1681/// length eased: the largest value of w^2 (1 - w)^3 / 2 for w from 0 to 1, at w = 0.4.
1682const EASE_PEAK: f64 = 0.01728;
1683/// The change of curvature per distance at the eased end is this many times the change of curvature over the
1684/// length eased: the third derivative of w^2 (1 - w)^3 / 2 at w = 0 is -9, and nowhere else is it larger.
1685const EASE_RATE: f64 = 9.0;
1686
1687/// Eases a spline into the line or arc it meets: where the curvature steps at such a junction, the spline's end
1688/// is bent so that its curvature there is that of its neighbour, and the junction is passed at speed instead of
1689/// at the crawl `junction_speed` allows for the step.
1690///
1691/// The spline leaves the junction in the neighbour's direction at a speed by u of 1 (`spline`), so the step of its
1692/// second derivative by u across the direction is the step of the curvature, dk. Over the length l of the span
1693/// next to the junction (u from 0 to l, counted from the junction) the polynomial gets
1694///
1695/// ```text
1696/// delta(u) = D l^2 w^2 (1 - w)^3 / 2,   w = u / l
1697/// ```
1698///
1699/// added, D the change of the second derivative that makes the curvature that of the neighbour (across the
1700/// direction, of size dk). It has no position, direction or second derivative at w = 1, and none but D at w = 0:
1701/// the junction keeps its place and direction, the rest of the spline stays as it was, and the eased piece is a
1702/// polynomial of the fifth degree. It moves the spline by at most `EASE_PEAK` dk l^2 (at w = 0.4), which the
1703/// tolerance bounds:
1704///
1705/// ```text
1706/// l = sqrt(e / (0.01728 dk))
1707/// ```
1708///
1709/// but no longer than half the span, so that a via point never moves, and no longer than needed: at the
1710/// junction the curvature changes by `EASE_RATE` dk / l per distance, so the speed v of the slower of the two
1711/// pieces asks for l = 9 dk v^3 / (0.4 j) (with the margin of `SPLINE_MARGIN`). Each junction gets its own l.
1712/// Only junctions where the direction does not turn (no corner) are eased. The spline's shape between its via
1713/// points away from the junctions, and the via points themselves, stay as they are.
1714fn ease(mut geo: Vec<Geo>, axes: &[AxisInfo], tolerance: f64, speed: &dyn Fn(&Geo) -> f64) -> (Vec<Geo>, f64) {
1715    let jerk = axes.iter().map(|a| a.max_jerk).fold(f64::INFINITY, f64::min);
1716    let mut moved = 0f64;
1717    let mut j = 1;
1718    while j < geo.len() {
1719        let spline = |g: &Geo| matches!(g, Geo::Spline { .. });
1720        let (into, out_of) = (spline(&geo[j]) && !spline(&geo[j - 1]), spline(&geo[j - 1]) && !spline(&geo[j]));
1721        if (into || out_of) && !corner(&geo[j - 1], &geo[j]) {
1722            let (at, other) = if into { (j, j - 1) } else { (j - 1, j) };
1723            let Geo::Spline { c, h, dims, .. } = &geo[at] else { unreachable!() };
1724            let (c, h, dims) = (**c, *h, *dims);
1725            // The neighbour's curvature where it meets the spline, and the spline's own there.
1726            let target = &geo[other].at(if into { geo[other].length() } else { 0.0 })[2];
1727            let [d, d2, _] = poly_rates(&c, if into { 0.0 } else { h });
1728            let along = dot(&d, &d2);
1729            let change: Wide = std::array::from_fn(|i| target.get(i).copied().unwrap_or(0.0) - (d2[i] - along * d[i]));
1730            let dk = norm(&change);
1731            let v = speed(&geo[other]).min(speed(&geo[at]));
1732            let needed = EASE_RATE * SPLINE_MARGIN * dk * v.powi(3) / (0.4 * jerk);
1733            let l = (tolerance / (EASE_PEAK * dk)).sqrt().min(needed).min(0.5 * h);
1734            if dk > 1e-9 && l > 0.0 {
1735                // The eased part and the rest, each a polynomial of its own with u from 0.
1736                let (mut eased, rest) = if into { (c, poly_shift(&c, l)) } else { (poly_shift(&c, h - l), c) };
1737                // delta expanded in powers of u: from the junction at u = 0, or towards it at u = l.
1738                let powers = if into {
1739                    [0.5, -1.5 / l, 1.5 / (l * l), -0.5 / (l * l * l)]
1740                } else {
1741                    [0.0, 0.5 / l, -1.0 / (l * l), 0.5 / (l * l * l)]
1742                };
1743                for (m, p) in powers.iter().enumerate() {
1744                    for i in 0..WIDEST {
1745                        eased[m + 2][i] += p * change[i];
1746                    }
1747                }
1748                if let (Some(eased), Some(rest)) = (span(eased, l, dims), span(rest, h - l, dims)) {
1749                    let pieces = if into { [eased, rest] } else { [rest, eased] };
1750                    geo.splice(at..=at, pieces);
1751                    moved = moved.max(EASE_PEAK * dk * l * l);
1752                    j += 1;
1753                }
1754            }
1755        }
1756        j += 1;
1757    }
1758    (geo, moved)
1759}
1760
1761// ---------------------------------------------------------------------------------------------
1762// Timing within the axis limits.
1763
1764/// A change of speed by `dv` under an acceleration and a jerk limit, with no acceleration before and after:
1765/// the time of each of the two jerk phases and the time at constant acceleration between them.
1766fn ramp(dv: f64, a: f64, j: f64) -> (f64, f64) {
1767    let dv = dv.abs();
1768    if dv * j < a * a { ((dv / j).sqrt(), 0.0) } else { (a / j, dv / a - a / j) }
1769}
1770
1771/// The distance such a ramp covers: its time at the mean of the two speeds, because it is symmetric.
1772fn ramp_distance(v0: f64, v1: f64, a: f64, j: f64) -> f64 {
1773    let (tj, ta) = ramp(v1 - v0, a, j);
1774    0.5 * (v0 + v1) * (2.0 * tj + ta)
1775}
1776
1777/// The largest value from `low`, which passes, to `high` that passes `ok`, found by halving.
1778fn largest(mut low: f64, mut high: f64, ok: impl Fn(f64) -> bool) -> f64 {
1779    if ok(high) {
1780        return high;
1781    }
1782    for _ in 0..60 {
1783        let mid = 0.5 * (low + high);
1784        if ok(mid) { low = mid } else { high = mid }
1785    }
1786    low
1787}
1788
1789/// `largest` to a share of 1e-9 of `high`: for the time-optimal plan's top speeds, where each try runs a piece.
1790fn highest_fitting(mut low: f64, mut high: f64, ok: impl Fn(f64) -> bool) -> f64 {
1791    if ok(high) {
1792        return high;
1793    }
1794    while high - low > 1e-9 * high {
1795        let mid = 0.5 * (low + high);
1796        // From a low of 0 where nothing above fits, high halves down to the smallest number and the middle rounds to
1797        // low: before 15 November that looped for ever (a delta's line planned time-optimal hung the cycle).
1798        if mid <= low || mid >= high {
1799            break;
1800        }
1801        if ok(mid) { low = mid } else { high = mid }
1802    }
1803    low
1804}
1805
1806/// `highest_fitting` where the values that pass `ok` need not be one range from `low` (which passes): the highest of
1807/// `TOPS_GRID` + 1 evenly spaced values that passes is found from the top down, and the halving runs between it and the
1808/// next one up, where the highest passing interval ends. A range narrower than a grid step (1 / `TOPS_GRID` of the
1809/// span) that lies between two grid values is not seen.
1810fn highest_fitting_scan(low: f64, high: f64, ok: impl Fn(f64) -> bool) -> f64 {
1811    if ok(high) {
1812        return high;
1813    }
1814    let at = |k: usize| low + (high - low) * k as f64 / TOPS_GRID as f64;
1815    let k = (1..TOPS_GRID).rev().find(|&k| ok(at(k))).unwrap_or(0);
1816    highest_fitting(at(k), at(k + 1), ok)
1817}
1818
1819/// The grid steps of `highest_fitting_scan`.
1820const TOPS_GRID: usize = 32;
1821
1822/// What bounds the tool's speed, its acceleration or its jerk: per row a direction in axis space and the most
1823/// the rate may be along it. An axis limit is a row along its axis; a motor's rated speed is a row along the
1824/// tool movement that turns the motor.
1825type Bounds = Vec<(Vec<f64>, f64)>;
1826
1827/// The velocity, acceleration and jerk limits of the axes as bounds.
1828fn axis_bounds(axes: &[AxisInfo]) -> [Bounds; 3] {
1829    let rows = |limit: fn(&AxisInfo) -> f64| {
1830        axes.iter()
1831            .enumerate()
1832            .map(|(i, a)| ((0..axes.len()).map(|k| (k == i) as u8 as f64).collect(), limit(a)))
1833            .collect()
1834    };
1835    [rows(|a| a.max_vel), rows(|a| a.max_acc), rows(|a| a.max_jerk)]
1836}
1837
1838/// Speed, acceleration and jerk along a piece that keep the tool within its bounds wherever on the piece.
1839fn limits(geo: &Geo, bounds: &[Bounds; 3]) -> [f64; 3] {
1840    let tightest = |per_row: &dyn Fn(&[f64]) -> f64| {
1841        bounds.each_ref().map(|rows| rows.iter().map(|(row, most)| most / per_row(row)).fold(f64::INFINITY, f64::min))
1842    };
1843    // The direction turns through the axes on a curve, so there a bound holds for the length of the vector.
1844    let any = || tightest(&|row| row.iter().map(|w| w * w).sum::<f64>().sqrt());
1845    match geo {
1846        Geo::Line { dir, .. } => tightest(&|row| row.iter().zip(dir).map(|(w, d)| w * d).sum::<f64>().abs()),
1847        Geo::Slerp { .. } => sampled(geo, bounds),
1848        Geo::Carried { from, by, turn: Some(k), .. } if slerps(from, by, *k) => sampled(geo, bounds),
1849        Geo::Arc { radius, .. } | Geo::Arc3 { radius, .. } => curved(*radius, *radius * *radius, 0.0, 0.0, any()),
1850        // A transition curve counts as an arc of its tightest radius.
1851        Geo::Clothoid { k0, k1, length, .. } => {
1852            let r = 1.0 / k0.abs().max(k1.abs());
1853            curved(r, r * r, (k1 - k0).abs() / length, 0.0, any())
1854        }
1855        // So does a spline span, with the fastest its curvature changes anywhere on it.
1856        // On three axes or more it also has the jerk v^3 kappa tau along the binormal (`binormal`).
1857        Geo::Spline { tightest, rate, binormal, .. } => {
1858            let r = 1.0 / tightest;
1859            curved(r, r * r, *rate, *binormal, any())
1860        }
1861        // An arc with other axes carried along is a helix: with the share of the distance that is on the arc, its
1862        // curvature is the arc's times share^2 and its |p'''| is share^3 / R^2 (the jerk's radius squared R^2 / share^3).
1863        Geo::Carried { arc, length, .. } => {
1864            let Geo::Arc3 { radius, length: on_arc, .. } = **arc else { unreachable!("a carried piece is an arc") };
1865            let share = on_arc / length;
1866            curved(radius / share.powi(2), radius * radius / share.powi(3), 0.0, 0.0, any())
1867        }
1868    }
1869}
1870
1871/// `limits` on a curve of radius `r` whose curvature changes by `dk` per distance (0 on an arc), whose jerk term
1872/// v^3 |p'''| is v^3 / sqrt(`r_jerk2`) (r^2 unless other axes are carried along) and whose kappa tau, curvature times
1873/// torsion, reaches `binormal` (0 on a plane curve), from the speed, acceleration and jerk the tool may have in any
1874/// direction.
1875///
1876/// Along the path (t), towards the centre (n) and along the binormal (b), at the speed v:
1877///
1878/// ```text
1879/// acceleration = t dv/dt + n v^2 / r
1880/// jerk         = t (d2v/dt2 - v^3 / r^2) + n (3 v dv/dt / r + v^3 dk) + b v^3 kappa tau
1881/// ```
1882///
1883/// The limits are shared out 3 : 4 : 5. Acceleration: 0.6 along, 0.8 towards the centre. Jerk: 0.4 for the
1884/// ramps and 0.4 for v^3 / r^2, together 0.8 along, and 0.6 towards the centre: all of it for 3 v dv/dt / r
1885/// on an arc, and on a transition curve 0.4 for v^3 dk and 0.2 for 3 v dv/dt / r. The binormal takes the share g of the
1886/// jerk limit that v^3 kappa tau needs (at most `BINORMAL_SHARE`) and the other two take sqrt(1 - g^2) of their
1887/// shares, so the three together stay within the limit (no torsion: g = 0, as without it).
1888fn curved(r: f64, r_jerk2: f64, dk: f64, binormal: f64, [v, a, j]: [f64; 3]) -> [f64; 3] {
1889    // The highest speed with `j_tn` the jerk for the other two shares; the binormal's own cap is on the full limit.
1890    let top = |j_tn: f64| {
1891        let v = v.min((0.8 * a * r).sqrt()).min((0.4 * j_tn * r_jerk2).cbrt());
1892        let v = if dk > 0.0 { v.min((0.4 * j_tn / dk).cbrt()) } else { v };
1893        if binormal > 0.0 { v.min((BINORMAL_SHARE * j / binormal).cbrt()) } else { v }
1894    };
1895    // The share the binormal needs at the speed the full limit would allow; the lower speed with the smaller limit needs less.
1896    let g = (binormal * top(j).powi(3) / j).min(BINORMAL_SHARE);
1897    let j_tn = j * (1.0 - g * g).sqrt();
1898    let (v, share) = (top(j_tn), if dk > 0.0 { 0.2 / 3.0 } else { 0.2 });
1899    [v, (0.6 * a).min(share * j_tn * r / v), 0.4 * j_tn]
1900}
1901
1902/// `limits` on a piece whose derivatives by distance p', p'', p''' are read along it, not given in closed form: a slerp
1903/// (whose rotation vector's rates are not the chord's and which bends, by up to 0.2 per rad on a quarter turn about a
1904/// tilted axis) and an arc whose orientation turns by slerp. A row w's rate is w . p' v, its acceleration
1905/// w . (p' v' + p'' v^2) and its jerk w . (p' v'' + 3 p'' v v' + p''' v^3); with P1, P2, P3 the most of |w . p'|,
1906/// |w . p''|, |w . p'''| over the piece, each stays within its row's limit where P1 v, P1 a + P2 v^2 and P1 j + 3 P2 v a +
1907/// P3 v^3 do. The speed keeps P2 v^2 within half the acceleration limit and P3 v^3 within a quarter of the jerk's, the
1908/// acceleration 3 P2 v a within another quarter of it; the ramps take what is left. On a piece that does not bend (P2 =
1909/// P3 = 0) that is v, a, j = the limits over P1.
1910///
1911/// P1 is read at `SLERP_SAMPLES` + 1 places with the best place's parabola's top (error of the order h^4 of the share h
1912/// = 1 / `SLERP_SAMPLES`); P2 at the same places; P3 by the third differences of the pose at 33 places, a twentieth
1913/// of the piece apart (on a short piece finer steps would read the rounding of the pose).
1914fn sampled(geo: &Geo, bounds: &[Bounds; 3]) -> [f64; 3] {
1915    let length = geo.length();
1916    let at: Vec<[Vec<f64>; 3]> =
1917        (0..=SLERP_SAMPLES).map(|k| geo.at(length * k as f64 / SLERP_SAMPLES as f64)).collect();
1918    let pose = |t: f64| geo.at(length * t)[0].clone();
1919    let d = 0.05;
1920    // A straight piece (a turn about one axis, `one_axis`) has none: its differences would be the rounding alone.
1921    let straight = at.iter().all(|[_, _, p2]| p2.iter().all(|x| *x == 0.0));
1922    let third: Vec<Vec<f64>> = (0..=32)
1923        .filter(|_| !straight)
1924        .map(|k| {
1925            let t = k as f64 / 32.0;
1926            let (a, b, c, e) = (pose(t + 2.0 * d), pose(t + d), pose(t - d), pose(t - 2.0 * d));
1927            (0..a.len()).map(|i| (a[i] - 2.0 * b[i] + 2.0 * c[i] - e[i]) / (2.0 * (d * length).powi(3))).collect()
1928        })
1929        .collect();
1930    let dot = |row: &[f64], v: &[f64]| row.iter().zip(v).map(|(w, x)| w * x).sum::<f64>();
1931    let most = |row: &[f64], of: &mut dyn Iterator<Item = &Vec<f64>>| of.map(|v| dot(row, v).abs()).fold(0.0, f64::max);
1932    let first = |row: &[f64]| {
1933        let along: Vec<f64> = at.iter().map(|[_, p1, _]| dot(row, p1)).collect();
1934        let k = (0..along.len()).fold(0, |m, k| if along[k].abs() > along[m].abs() { k } else { m });
1935        let mut top = along[k].abs();
1936        if (1..SLERP_SAMPLES).contains(&k) {
1937            // The parabola through the best place and its neighbours has its vertex at -b / 2a from it.
1938            let (a, b) = ((along[k - 1] + along[k + 1] - 2.0 * along[k]) / 2.0, (along[k + 1] - along[k - 1]) / 2.0);
1939            if a * along[k] < 0.0 {
1940                top = (along[k] - b * b / (4.0 * a)).abs();
1941            }
1942        }
1943        top
1944    };
1945    // Per bound and row: its limit, P1, P2, P3.
1946    let rows = bounds.each_ref().map(|rows| {
1947        rows.iter()
1948            .map(|(row, limit)| {
1949                (*limit, first(row), most(row, &mut at.iter().map(|[_, _, p2]| p2)), most(row, &mut third.iter()))
1950            })
1951            .collect::<Vec<_>>()
1952    });
1953    let fold =
1954        |of: &dyn Fn(&(f64, f64, f64, f64)) -> f64, k: usize| rows[k].iter().map(of).fold(f64::INFINITY, f64::min);
1955    let v = fold(&|&(l, p1, ..)| l / p1, 0)
1956        .min(fold(&|&(l, _, p2, _)| (0.5 * l / p2).sqrt(), 1))
1957        .min(fold(&|&(l, .., p3)| (0.25 * l / p3).cbrt(), 2));
1958    // A part that is 0 stays 0 at any speed (no 0 * inf).
1959    let times = |p: f64, x: f64| if p == 0.0 { 0.0 } else { p * x };
1960    let a = fold(&|&(l, p1, p2, _)| (l - times(p2, v * v)) / p1, 1)
1961        .min(fold(&|&(l, _, p2, _)| 0.25 * l / times(3.0 * p2, v), 2));
1962    let j = fold(&|&(l, p1, p2, p3)| (l - times(3.0 * p2, v * a) - times(p3, v.powi(3))) / p1, 2);
1963    [v, a, j]
1964}
1965
1966/// The places along a slerp at which `limits` reads its rates, 256 intervals.
1967const SLERP_SAMPLES: usize = 256;
1968
1969/// The most of the jerk limit that the binormal part v^3 kappa tau of a spline's jerk may use (`curved`).
1970const BINORMAL_SHARE: f64 = 0.3;
1971
1972/// How fast the path may pass from one piece into the next. At a corner not at all. Elsewhere the direction
1973/// may turn a little and the curvature may jump (line into arc), which steps the axis speeds and
1974/// accelerations. Taken over one profile cycle, each of the two steps may use half an axis's jerk limit.
1975fn junction_speed(a: &Geo, b: &Geo, axes: &[AxisInfo], cycle: f64) -> f64 {
1976    if corner(a, b) {
1977        return 0.0;
1978    }
1979    let ([_, dir0, curve0], [_, dir1, curve1]) = (a.at(a.length()), b.at(0.0));
1980    let per_axis = |i: usize, axis: &AxisInfo| {
1981        let half = 0.5 * axis.max_jerk;
1982        (half * cycle * cycle / (dir1[i] - dir0[i]).abs()).min((half * cycle / (curve1[i] - curve0[i]).abs()).sqrt())
1983    };
1984    axes.iter().enumerate().map(|(i, axis)| per_axis(i, axis)).fold(f64::INFINITY, f64::min)
1985}
1986
1987/// Plans the timing of a path within the velocity, acceleration and jerk limits of every axis, from rest to rest.
1988///
1989/// Each piece gets one speed, acceleration and jerk limit along the path that hold on all of it (`limits`),
1990/// and each junction a highest speed (`junction_speed`). Look-ahead then lowers the junction speeds until
1991/// every piece is long enough to change from the speed at its start to the speed at its end; a tight arc or
1992/// a corner far ahead so slows the pieces before it. On each piece the speed goes by a jerk-limited ramp to
1993/// the highest speed the piece has room for, stays there, and goes by a second ramp to the speed at its end.
1994///
1995/// With a `tolerance` above zero the path gets transition curves first (`blend`), which let it pass from a
1996/// line into an arc at speed, and is off the given pieces by up to the tolerance (`deviation` says by how much).
1997pub fn plan(
1998    axes: &[AxisInfo],
1999    start: &[f64],
2000    pieces: &[Piece],
2001    cycle: f64,
2002    tolerance: impl Into<Tolerance>,
2003    slack: f64,
2004) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
2005    plan_at(axes, start, pieces, cycle, tolerance, slack, f64::INFINITY)
2006}
2007
2008/// `plan` with the speed along the path no higher than `feed` (in the axes' units per second, the length of the speed
2009/// vector over all axes): a program's feed (G-code F, a robot's v or $VEL.CP), which is the speed along the path, not
2010/// along each axis. Infinite: the axes' limits alone.
2011pub fn plan_at(
2012    axes: &[AxisInfo],
2013    start: &[f64],
2014    pieces: &[Piece],
2015    cycle: f64,
2016    tolerance: impl Into<Tolerance>,
2017    slack: f64,
2018    feed: f64,
2019) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
2020    plan_feeds(axes, start, pieces, &vec![feed; pieces.len()], cycle, tolerance, slack)
2021}
2022
2023/// `plan_at` with a feed per piece (`feeds[i]` for `pieces[i]`; none or too few: no cap): a program's blocks at their own
2024/// feeds, planned as one path, no stop between them. Each piece's speed is bound by its own feed and the path passes
2025/// from one piece into the next at the lower of the two feeds at most, with the junction's own limit (`timed`). The
2026/// stretches at one feed are shaped on their own (`geometry_fed`).
2027pub fn plan_feeds(
2028    axes: &[AxisInfo],
2029    start: &[f64],
2030    pieces: &[Piece],
2031    feeds: &[f64],
2032    cycle: f64,
2033    tolerance: impl Into<Tolerance>,
2034    slack: f64,
2035) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
2036    plan_within(axes, None, start, pieces, feeds, cycle, tolerance, slack)
2037}
2038
2039/// `plan_feeds` with the flange's angular speed and acceleration limits `spin` (rad/s, rad/s^2; `MotionLaw::spin`, an
2040/// arm in tool space) kept on the pieces that turn by slerp: about one axis, so the flange turns at the angle between
2041/// their orientations over their length times the speed along the path, and accelerates as much times the path's
2042/// acceleration (no other part, the axis fixed). The axes' limits bound the rotation vector's rates only, which spin
2043/// the flange faster away from no turn.
2044#[allow(clippy::too_many_arguments)]
2045pub fn plan_within(
2046    axes: &[AxisInfo],
2047    spin: Option<[f64; 2]>,
2048    start: &[f64],
2049    pieces: &[Piece],
2050    feeds: &[f64],
2051    cycle: f64,
2052    tolerance: impl Into<Tolerance>,
2053    slack: f64,
2054) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
2055    let (speed, bounds) = (axis_speed(axes), axis_bounds(axes));
2056    let (geo, _, caps) = geometry_fed(axes, start, pieces, feeds, tolerance, &speed, slack)?;
2057    let limits: Vec<[f64; 3]> = geo
2058        .iter()
2059        .zip(&caps)
2060        .map(|(g, cap)| {
2061            let [v, a, j] = limits(g, &bounds);
2062            let per_length = match (spin, g) {
2063                (Some(_), Geo::Slerp { from, to, length, at }) => {
2064                    use crate::rigid::{exp, log, matmul, transpose};
2065                    let rotation = |p: &[f64]| exp([p[*at], p[at + 1], p[at + 2]]);
2066                    let turn = log(&matmul(&rotation(to), &transpose(&rotation(from))));
2067                    norm(&turn) / length
2068                }
2069                _ => 0.0,
2070            };
2071            let [most_w, most_a] = spin.unwrap_or([f64::INFINITY; 2]);
2072            if per_length > 0.0 {
2073                [v.min(*cap).min(most_w / per_length), a.min(most_a / per_length), j]
2074            } else {
2075                [v.min(*cap), a, j]
2076            }
2077        })
2078        .collect();
2079    timed(axes, &geo, &limits, cycle)
2080}
2081
2082/// The timing of `plan` for pieces with their speed, acceleration and jerk limits along the path; refused where it would
2083/// take more than `PLAN_POINTS_MOST` poses (a feed of 0.000001 mm/min).
2084fn timed(
2085    axes: &[AxisInfo],
2086    geo: &[Geo],
2087    limits: &[[f64; 3]],
2088    cycle: f64,
2089) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
2090    let n = geo.len();
2091    // Two cycles at steady speed on either side of a junction, so that the jerk of a ramp and the steps of
2092    // the junction never fall into the same three cycles.
2093    let hold = 2.0 * cycle;
2094    // The length piece i needs to change between two speeds.
2095    let need = |i: usize, v0: f64, v1: f64| hold * (v0 + v1) + ramp_distance(v0, v1, limits[i][1], limits[i][2]);
2096
2097    // Speed at the start of each piece and at the end of the last; at rest at both ends of the path.
2098    let mut speed = vec![0.0; n + 1];
2099    for i in 1..n {
2100        // A piece too short for the steady cycles at both of its ends is passed slowly enough to have them.
2101        let short = geo[i - 1].length().min(geo[i].length()) / (2.0 * hold);
2102        speed[i] = junction_speed(&geo[i - 1], &geo[i], axes, cycle).min(limits[i - 1][0]).min(limits[i][0]).min(short);
2103    }
2104    // Look-ahead: no junction faster than the piece after it can brake from, or than the piece before it can reach.
2105    for i in (0..n).rev() {
2106        let after = speed[i + 1];
2107        speed[i] = largest(after.min(speed[i]), speed[i], |v| need(i, v, after) <= geo[i].length());
2108    }
2109    for i in 0..n {
2110        let before = speed[i];
2111        speed[i + 1] = largest(before.min(speed[i + 1]), speed[i + 1], |v| need(i, before, v) <= geo[i].length());
2112    }
2113
2114    // Per piece the phases of constant jerk as (duration, jerk): steady, up to the top speed, cruise, down, steady.
2115    let mut phases = Vec::new();
2116    for i in 0..n {
2117        let ([v_max, a, j], v0, v1, length) = (limits[i], speed[i], speed[i + 1], geo[i].length());
2118        let covered = |top: f64| hold * (v0 + v1) + ramp_distance(v0, top, a, j) + ramp_distance(top, v1, a, j);
2119        let top = largest(v0.max(v1), v_max, |top| covered(top) <= length);
2120        let (up, down, cruise) = (ramp(top - v0, a, j), ramp(top - v1, a, j), ((length - covered(top)) / top).max(0.0));
2121        let steady = |v: f64| if v > 0.0 { hold } else { 0.0 };
2122        phases.push([
2123            (steady(v0), 0.0),
2124            (up.0, j),
2125            (up.1, 0.0),
2126            (up.0, -j),
2127            (cruise, 0.0),
2128            (down.0, -j),
2129            (down.1, 0.0),
2130            (down.0, j),
2131            (steady(v1), 0.0),
2132        ]);
2133    }
2134
2135    let duration = |i: usize| phases[i].iter().map(|p| p.0).sum::<f64>();
2136    let total: f64 = (0..n).map(duration).sum();
2137    if !(total / cycle <= PLAN_POINTS_MOST) {
2138        return Err(CommandError { key: "error-path-long" });
2139    }
2140    let mut points = Vec::new();
2141    for k in 0..=(total / cycle - 1e-9).ceil() as usize {
2142        // The piece this moment falls into, and the time since its start.
2143        let (mut i, mut t) = (0, k as f64 * cycle);
2144        while i + 1 < n && t >= duration(i) {
2145            t -= duration(i);
2146            i += 1;
2147        }
2148        let (mut s, mut v, mut a) = (0.0, speed[i], 0.0);
2149        for (time, jerk) in phases[i] {
2150            let h = t.min(time);
2151            s += v * h + a * h * h / 2.0 + jerk * h * h * h / 6.0;
2152            v += a * h + jerk * h * h / 2.0;
2153            a += jerk * h;
2154            t -= h;
2155        }
2156        points.push((k as f64 * cycle, within(axes, geo[i].at(s.min(geo[i].length()))[0].clone())));
2157    }
2158    Ok(points)
2159}
2160
2161// ---------------------------------------------------------------------------------------------
2162// Timing as fast as the motors allow.
2163
2164/// What a time-optimal plan keeps within beside each motor's torque-speed curve, its rated speed and the axes' jerk
2165/// limits (see `plan_time_optimal`).
2166#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
2167pub struct PlanLimits {
2168    /// The share of each torque limit the plan may use (`profile.torque_reserve`): of the motor's torque-speed curve, of
2169    /// the torque of the drive's maximum current, and of the gearbox's and the pulley's torque rating.
2170    pub reserve: f64,
2171    /// The lowest and the highest tension a belt section may have and the share of the room to them the plan may use.
2172    pub tension: [f64; 3],
2173    /// Per motor (in the order of `Machine::motors`) its gearbox: the ratio, the inertia that turns at its input (rotor
2174    /// and gearbox, kg m^2), the most torque at its output (N m), `ratings.gearbox_max_torque_nm` (M2max) or
2175    /// `pulley_max_torque_nm` where that is lower (infinite where the config rates neither), and its efficiency
2176    /// (`gearbox.efficiency` with effects.gearbox_efficiency, else 1). `None` (or no entry) where the machine reports no
2177    /// gearbox output torque, or the gearbox is neither rated nor lossy.
2178    pub gearbox: Vec<Option<[f64; 4]>>,
2179    /// The most load a guide may carry, `ratings.guide_max_load_n` (N); infinite without. The plan keeps `reserve` of it.
2180    pub guide: f64,
2181    /// Per motor (in the order of `Machine::motors`) the friction on its shaft as the motor and its gearbox have it:
2182    /// [Coulomb level, viscous, smoothing speed, gearbox drag at its reference speed, that speed] in N m and rad/s
2183    /// (`mech::ShaftFriction`, `mech::GearDrag`), all 0 with effects.motor_friction and gearbox_drag off. No entry: none.
2184    #[serde(default)]
2185    pub friction: Vec<[f64; 5]>,
2186    /// Per motor (in the order of `Machine::motors`) the drive's and the gearbox's ratings that bound the plan beside the
2187    /// motor: [the drive's maximum current `ratings.drive_max_current_a` (A, whether or not effects.drive_current_limit
2188    /// holds the drive to it), the gearbox's maximum input speed `ratings.gearbox_max_input_speed_rpm` (rad/s), the
2189    /// most power the braking resistor takes `ratings.braking_resistor_peak_w` (W, shared out evenly over the motors of
2190    /// a line-up that brakes through one module)], each infinite without. No entry: none.
2191    #[serde(default)]
2192    pub ratings: Vec<[f64; 3]>,
2193    /// `profile.time_optimal_margin`: the share of every limit the plan may use, on top of the reserves (1: all).
2194    #[serde(default = "one")]
2195    pub margin: f64,
2196    /// The controller interpolates the plan's points with the Hermite cubic (`profile.trajectory_spline = "hermite"`);
2197    /// false: with the C2 spline, as shipped. It sets what `piece_limits` keeps back for the cubics' overshoot.
2198    #[serde(default)]
2199    pub hermite: bool,
2200    /// The share of every speed rating the plan keeps back for the velocity loops' following (`speed_kept_of`, the
2201    /// largest over the motors); at least `SPEED_KEPT`.
2202    #[serde(default = "speed_kept")]
2203    pub speed_kept: f64,
2204    /// Per motor (in the order of `Machine::motors`) what the keep-back at a place takes from the motor's loop and drive
2205    /// (`LoopKeep`, `PlanLimits::kept_at`): with it the share kept back is that of the place's own pose (its drive
2206    /// trains, rigid inertias and jerks) and `speed_kept` is the least of them. No entry: `speed_kept` everywhere.
2207    #[serde(default)]
2208    pub loops: Vec<LoopKeep>,
2209}
2210
2211/// What `speed_kept_of` takes of one motor's loop and drive: the loop's integral gain (N m per rad), the share of the
2212/// torque J a its precontrol gives, the drive's peak torque (N m) and the top speed (rad/s) the share is taken over.
2213#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
2214pub struct LoopKeep {
2215    pub ki: f64,
2216    pub torque_ff: f64,
2217    pub peak_torque: f64,
2218    pub max_speed: f64,
2219}
2220
2221fn one() -> f64 {
2222    1.0
2223}
2224
2225fn speed_kept() -> f64 {
2226    SPEED_KEPT
2227}
2228
2229/// The share of its top speed `top` (rad/s) that a motor's velocity loop follows a ramp of acceleration `acc` (rad/s^2)
2230/// off by, at most, from the loop's integral gain `ki` (N m per rad), the inertia `inertia` (kg m^2) it is tuned for
2231/// and the share `feedforward` of the torque J a that the precontrol gives. The speed error e of the PI loop on a ramp
2232/// a t, with the loop's torque (1 - feedforward) J a to find, obeys J e'' + kp e' + ki e = 0 with e'(0) = (1 -
2233/// feedforward) a, whose peak is at most (1 - feedforward) a / w_n for the natural frequency w_n = sqrt(ki / J)
2234/// (the underdamped peak a/w_n exp(-z acos(z) / sqrt(1 - z^2)) is below it, as is the critical a/(e w_n)). The share is
2235/// that over `top`, at least `SPEED_KEPT`: a loop that follows a ramp closely keeps the least. On top of it the speed
2236/// `train` (rad/s) that an elastic drive train adds (`train_speed`); at most `SPEED_KEPT_MOST` in all.
2237pub fn speed_kept_of(ki: f64, inertia: f64, feedforward: f64, acc: f64, top: f64, train: f64) -> f64 {
2238    let peak = (1.0 - feedforward).max(0.0) * acc * (inertia / ki).sqrt();
2239    let share = peak / top;
2240    let share = if share.is_finite() { share.max(SPEED_KEPT) } else { SPEED_KEPT };
2241    let train = train / top;
2242    (share + if train.is_finite() { train.max(0.0) } else { 0.0 }).min(SPEED_KEPT_MOST)
2243}
2244
2245/// How much faster than the plan's rigid motion a motor runs with an elastic drive train (`Machine::trains`) while its
2246/// acceleration changes at the jerk `jerk` (rad/s^3), rad/s. Two masses on a spring k, the rotor's side J_m and the
2247/// load's J_L (s = J_L / (J_m + J_L), w^2 = k / J_L the load's frequency against the motor held), the motor's torque the
2248/// rigid (J_m + J_L) a(t): the twist x = theta_m - theta_L obeys x'' + k (1/J_m + 1/J_L) x = (J_m + J_L) / J_m a, so at
2249/// a steady a it holds x = a / w^2, and while a changes at j it grows at x' = j / w^2 (to which the free swing
2250/// (j / w^2) (1 - cos) settles about its mean). The motor runs ahead of the masses' common speed by s x', so by
2251/// s j / w^2; the swing's peak is twice that, which the velocity loop damps. A ramp quicker than the train's swing is
2252/// a step of the acceleration `acc` (rad/s^2, the most the motor has): x = acc / w^2 (1 - cos W t) at the swing's own
2253/// frequency W = sqrt(k (1/J_m + 1/J_L)) = w / sqrt(1 - s), so x' peaks at acc W / w^2 however high the jerk limit;
2254/// the lower of the two.
2255pub fn train_speed(train: sim_core::Train, jerk: f64, acc: f64) -> f64 {
2256    let w = std::f64::consts::TAU * train.hz;
2257    let swing = w / (1.0 - train.load_share).sqrt();
2258    train.load_share * jerk.abs().min(acc.abs() * swing) / (w * w)
2259}
2260
2261impl PlanLimits {
2262    /// The torque share and the belt only, with no gearbox or guide rating and no friction.
2263    pub fn new(reserve: f64, tension: [f64; 3]) -> Self {
2264        Self {
2265            reserve,
2266            tension,
2267            gearbox: Vec::new(),
2268            guide: f64::INFINITY,
2269            friction: Vec::new(),
2270            ratings: Vec::new(),
2271            margin: 1.0,
2272            hermite: false,
2273            speed_kept: SPEED_KEPT,
2274            loops: Vec::new(),
2275        }
2276    }
2277
2278    /// The share of every speed rating kept back at the tool pose `pose`, `speed_kept_of` of each motor with the train,
2279    /// the rigid inertia and the jerk it has there (the most over the motors, at least `SPEED_KEPT`); `speed_kept`
2280    /// where no `loops` are given.
2281    pub fn kept_at(&self, machine: &dyn Machine, pose: &[f64]) -> f64 {
2282        self.kept_at_reserve(machine, pose, self.reserve)
2283    }
2284
2285    /// `kept_at` with the torque reserve `reserve` the motors' acceleration comes from (`reserve` of these limits, which
2286    /// the plan holds times the margin).
2287    fn kept_at_reserve(&self, machine: &dyn Machine, pose: &[f64], reserve: f64) -> f64 {
2288        if self.loops.is_empty() {
2289            return self.speed_kept;
2290        }
2291        let trains = machine.trains(pose);
2292        let jerks = crate::control::motor_jerks(machine, pose);
2293        crate::control::rigid_inertias(machine, pose)
2294            .iter()
2295            .zip(&self.loops)
2296            .enumerate()
2297            .filter(|(_, (inertia, _))| **inertia > 0.0)
2298            .map(|(k, (&inertia, p))| {
2299                let acc = reserve * p.peak_torque / inertia;
2300                let train = trains.get(k).copied().flatten().map_or(0.0, |t| train_speed(t, jerks[k], acc));
2301                speed_kept_of(p.ki, inertia, p.torque_ff, acc, p.max_speed, train)
2302            })
2303            .fold(SPEED_KEPT, f64::max)
2304    }
2305
2306    /// The share the motors' curves are built with: where each place keeps back its own share (`kept_at`) the least
2307    /// there is, which each place's speed ceiling then lowers (`Place::scale`).
2308    fn curve_kept(&self) -> f64 {
2309        if self.loops.is_empty() { self.speed_kept } else { SPEED_KEPT }
2310    }
2311
2312    /// These limits with the margin taken into the reserves: the torque share and the share of the belt's room.
2313    fn with_margin(&self) -> Self {
2314        let mut out = self.clone();
2315        out.reserve *= self.margin;
2316        out.tension[2] *= self.margin;
2317        out
2318    }
2319
2320    /// Each motor's drive as the plan holds it: its maximum current no more than the drive's rating, and its maximum
2321    /// speed no more than the gearbox's input speed rating, times the margin, less `speed_kept`.
2322    fn rated(&self, drives: &[&DriveParams]) -> Vec<DriveParams> {
2323        self.rated_keeping(drives, self.speed_kept)
2324    }
2325
2326    /// `rated` with the share `kept` kept back of the speed ratings.
2327    fn rated_keeping(&self, drives: &[&DriveParams], kept: f64) -> Vec<DriveParams> {
2328        drives
2329            .iter()
2330            .enumerate()
2331            .map(|(m, drive)| {
2332                let [current, speed, _] = self.ratings.get(m).copied().unwrap_or([f64::INFINITY; 3]);
2333                let mut drive = (*drive).clone();
2334                drive.drive_max_current = drive.drive_max_current.min(current);
2335                drive.max_speed = drive.max_speed.min(speed) * self.margin * (1.0 - kept);
2336                drive
2337            })
2338            .collect()
2339    }
2340
2341    /// The most power motor `m`'s braking may feed back (W), times the margin; infinite without a rating.
2342    fn braking(&self, m: usize) -> f64 {
2343        self.ratings.get(m).map_or(f64::INFINITY, |r| r[2] * self.margin)
2344    }
2345
2346    /// The steady friction on motor `m`'s shaft at the speed `speed` (rad/s, at least 0): c tanh(w / smoothing) + b w +
2347    /// T0 (w / n0)^(2/3), as `mech::ShaftFriction::torque` has it at the reference temperature, without the breakaway's
2348    /// Stribeck rise near a standstill.
2349    pub fn shaft_friction(&self, m: usize, speed: f64) -> f64 {
2350        let Some(&[coulomb, viscous, smoothing, drag, drag_speed]) = self.friction.get(m) else { return 0.0 };
2351        let drag = if drag > 0.0 { drag * (speed / drag_speed).powf(crate::mech::DRAG_EXPONENT) } else { 0.0 };
2352        coulomb * (speed / smoothing).tanh() + viscous * speed + drag
2353    }
2354}
2355
2356/// The most torque a motor gives the time-optimal plan at the speed `speed`, before the reserve: its torque-speed curve
2357/// at that speed or the rated speed where that is higher (level up to it) or, with effects.drive_current_limit, the torque of the drive's maximum current where that is lower.
2358fn motor_torque(drive: &DriveParams, speed: f64) -> f64 {
2359    let curve = drive.torque_curve(speed.max(drive.rated_speed)).1;
2360    if drive.drive_max_current.is_finite() { curve.min(drive.torque_of(drive.drive_max_current)) } else { curve }
2361}
2362
2363/// Speeds at which a motor's torque-speed curve is read for the time-optimal plan (`MotorCurve`), evenly from zero to
2364/// its maximum speed.
2365const CURVE_SAMPLES: usize = 256;
2366
2367/// What one motor gives the time-optimal plan by its speed: its torque-speed curve (`DriveParams::torque_curve`, which
2368/// falls above the rated speed: linearly to the no-load speed, or with effects.field_weakening as the d-q model has it),
2369/// or the torque of the drive's maximum current where that is lower, as it drives (`motoring`, torque in the direction
2370/// it turns) and as it brakes, less what the reserve keeps at a standstill ((1 - reserve) times the torque there: for
2371/// friction and elasticity, which do not shrink with the speed), read at `CURVE_SAMPLES` + 1 speeds `step` apart from
2372/// zero to its maximum speed (`DriveParams::max_speed`) and lowered so that neither rises with the speed. Up to the
2373/// rated speed that is `reserve` times the curve, as before; above it the room falls faster than the curve. The motor's
2374/// own shaft friction and its gearbox's drag at each speed (`PlanLimits::shaft_friction`) come off as it drives; as it
2375/// brakes they would help, which is not counted (at a standstill there is none).
2376#[derive(Debug)]
2377struct MotorCurve {
2378    step: f64,
2379    motoring: Vec<f64>,
2380    braking: Vec<f64>,
2381    /// The most power its braking may feed back to the DC link (`PlanLimits::braking`): as it brakes at the speed w its
2382    /// torque is held to power / |w| as well, the mechanical power, which while braking exceeds the electrical by the losses, so the bound is on the safe side.
2383    power: f64,
2384}
2385
2386impl MotorCurve {
2387    fn new(drive: &DriveParams, reserve: f64, power: f64, friction: impl Fn(f64) -> f64) -> Self {
2388        let step = drive.max_speed / CURVE_SAMPLES as f64;
2389        let most =
2390            if drive.drive_max_current.is_finite() { drive.torque_of(drive.drive_max_current) } else { f64::INFINITY };
2391        let at = |speed: f64| {
2392            let (low, high) = drive.torque_curve(speed);
2393            [high.min(most), (-low).min(most)]
2394        };
2395        // What friction and elasticity keep of the torque at a standstill, they keep at every speed: where the curve has
2396        // less than that left, the rigid torque has to stay as far on the other side (below zero here).
2397        let kept = at(0.0).map(|t| (1.0 - reserve) * t);
2398        let (mut motoring, mut braking) = (Vec::new(), Vec::new());
2399        let (mut drives, mut brakes) = (f64::INFINITY, f64::INFINITY);
2400        for i in 0..=CURVE_SAMPLES {
2401            let [high, low] = at(i as f64 * step);
2402            drives = drives.min((1.0 - KEPT_BACK) * (high - kept[0] - friction(i as f64 * step)));
2403            brakes = brakes.min((1.0 - KEPT_BACK) * (low - kept[1]));
2404            motoring.push(drives);
2405            braking.push(brakes);
2406        }
2407        Self { step, motoring, braking, power: (1.0 - KEPT_BACK) * power }
2408    }
2409
2410    /// The highest speed the motor may turn at.
2411    fn max_speed(&self) -> f64 {
2412        self.step * CURVE_SAMPLES as f64
2413    }
2414
2415    /// The lowest and the highest torque at the (signed) motor speed `speed` and at every speed of its sign below it: the
2416    /// curve as read at the next speed up, which is no higher, as the curve does not rise. Beyond the maximum speed an
2417    /// empty range.
2418    fn range(&self, speed: f64) -> (f64, f64) {
2419        // The rounding of a speed at the maximum is not beyond it.
2420        let i = (speed.abs() / self.step * (1.0 - 1e-12)).ceil() as usize;
2421        let (Some(drives), Some(brakes)) = (self.motoring.get(i), self.braking.get(i)) else {
2422            return (f64::INFINITY, f64::NEG_INFINITY);
2423        };
2424        // The braking power's bound is the tightest at the speed itself, among the speeds of its sign up to it.
2425        let brakes = brakes.min(self.power / speed.abs());
2426        if speed >= 0.0 { (-brakes, *drives) } else { (-drives, brakes) }
2427    }
2428}
2429
2430/// Plans the timing of a path as fast as the motors allow, within the jerk limits of the axes, point by point.
2431///
2432/// The path is the one `plan` times (transition curves included, their lengths for the speeds the motors allow per
2433/// piece, `motor_limits`), with its look-ahead over the junctions, the speed at a junction and the stop at a corner.
2434/// Within a piece the limits are read at places about 2 mm apart (`piece_limits`): at each the rigid model gives how
2435/// fast each motor turns per speed along the path, and its torque as c a + d v^2 + e for the acceleration a and the
2436/// speed v along the path (with the centripetal and Coriolis torque of the speed, `Machine::feedforward_torque_moving`,
2437/// and e the torque that holds the tool there). Each motor is judged by its own drive and motor (`drives`, in the order
2438/// of `Machine::motors`): it may turn up to its maximum speed (`DriveParams::max_speed`) and give `reserve` times its
2439/// torque-speed curve at the speed it turns (level up to the rated speed, falling above it: `MotorCurve`), or of the
2440/// torque of the drive's maximum current where that is lower (effects.drive_current_limit), each way as gravity pushes
2441/// and as it drives or brakes. The rest is for friction and elasticity, which the
2442/// rigid model leaves out. Each axis keeps its jerk limit: on a line the ramps use it in full, on a curve 0.4 of it,
2443/// and the rest is for the jerk that speed and acceleration make on the curve.
2444///
2445/// A gearbox (`PlanLimits::gearbox`) keeps `reserve` times its output torque rating: the output torque is the ratio
2446/// times the motor's torque less what turns the inertia at the input, again of the form c a + d v^2 + e. A guide keeps
2447/// its load rating (`PlanLimits::guide`): the machine gives each guide's load as a load at rest plus the size of a part
2448/// linear in the acceleration (`Machine::rigid_guide_loads`).
2449///
2450/// Each piece then follows the highest speed its places allow (`smoothed`: the places' top speeds, lowered where the
2451/// speed could not come down in time or would bend too sharply for the jerk) from below, as fast as the jerk and the
2452/// acceleration there allow, from its start and from its end (`follow`), and the two runs meet at a top speed at which
2453/// both have no acceleration (`piece_timing`): the highest that fits. The velocity and acceleration limits of the axes
2454/// play no part.
2455///
2456/// The belt is a limit of the plan too: `tension` is the lowest and the highest tension a belt section may have
2457/// (`ratings.belt_min_tension_n` and `belt_max_tension_n`, each less `profile.tension_margin_n`; -inf and inf where the
2458/// config has none) and the share of the room to them the plan may use (`profile.tension_reserve`). The rigid model gives
2459/// each section's tension at each place as c + g . acceleration (`Machine::rigid_tensions_moving`: c a + b v + d v^2 along the path, as the checks' fit),
2460/// so each section and place is one more bound: |g . acceleration| <= share * min(highest - c, c - lowest), the same
2461/// room both ways. The rest of the room is for what the rigid model leaves out: the margin for the guide friction the
2462/// belt pulls, the share (0.5 in the shipped configs) for the belt's vibration, which after a quick ramp of acceleration
2463/// overshoots by up to the rigid model's change of tension, either way.
2464pub fn plan_time_optimal(
2465    machine: &dyn Machine,
2466    drives: &[&DriveParams],
2467    limits: &PlanLimits,
2468    start: &[f64],
2469    pieces: &[Piece],
2470    cycle: f64,
2471    tolerance: impl Into<Tolerance>,
2472    slack: f64,
2473) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
2474    let (rated, wide) = (limits.rated(drives), limits.rated_keeping(drives, limits.curve_kept()));
2475    let (limits, wide) = (&limits.with_margin(), wide.iter().collect::<Vec<&DriveParams>>());
2476    let drives: Vec<&DriveParams> = rated.iter().collect();
2477    let ((geo, _), _) = time_optimal_geometry(machine, &drives, limits, start, pieces, tolerance, slack)?;
2478    // The curves reach as far as the least share kept back goes; each place's speed ceiling lowers them (`Place::scale`).
2479    let curves: Arc<[MotorCurve]> = wide
2480        .iter()
2481        .enumerate()
2482        .map(|(m, drive)| MotorCurve::new(drive, limits.reserve, limits.braking(m), |w| limits.shaft_friction(m, w)))
2483        .collect();
2484    let places =
2485        geo.iter().map(|piece| piece_limits(machine, &curves, limits, piece, cycle)).collect::<Result<Vec<_>, _>>()?;
2486    timed_by_motors(machine.axes(), &geo, &places, cycle)
2487}
2488
2489/// The same path as `plan` times, transition curves included, their lengths for the speeds the motors allow, with
2490/// the deviation and the motors' limits per piece; refused where a piece has no torque left beyond holding the tool
2491/// or turns no motor, or where the belt holding the tool there is already beyond its tension limits.
2492fn time_optimal_geometry(
2493    machine: &dyn Machine,
2494    drives: &[&DriveParams],
2495    limits: &PlanLimits,
2496    start: &[f64],
2497    pieces: &[Piece],
2498    tolerance: impl Into<Tolerance>,
2499    slack: f64,
2500) -> Result<((Vec<Geo>, f64), Vec<[f64; 3]>), CommandError> {
2501    let (plan, piece_limits) = (limits, motor_limits(machine, drives, limits, limits.tension));
2502    let path = geometry(machine.axes(), start, pieces, tolerance, &|piece| piece_limits(piece)[0], slack)?;
2503    let mut limited = Vec::new();
2504    let usable = |limits: &[f64; 3]| limits.iter().all(|l| l.is_finite() && *l > 0.0);
2505    for piece in &path.0 {
2506        let limits = piece_limits(piece);
2507        if !usable(&limits) {
2508            // Said by what is short: the torque, or the belt alone.
2509            let torque_alone =
2510                usable(&motor_limits(machine, drives, plan, [f64::NEG_INFINITY, f64::INFINITY, 1.0])(piece));
2511            return Err(CommandError { key: if torque_alone { "error-path-tension" } else { "error-path-torque" } });
2512        }
2513        limited.push(limits);
2514    }
2515    Ok((path, limited))
2516}
2517
2518/// `deviation` for the path `plan_time_optimal` plans: its transition curves are as long as the speeds the
2519/// motors allow need them to be, not the speeds of the axis limits. Refused as that plan is.
2520pub fn deviation_time_optimal(
2521    machine: &dyn Machine,
2522    drives: &[&DriveParams],
2523    limits: &PlanLimits,
2524    start: &[f64],
2525    pieces: &[Piece],
2526    tolerance: impl Into<Tolerance>,
2527    slack: f64,
2528) -> Result<f64, CommandError> {
2529    let (rated, limits) = (limits.rated(drives), &limits.with_margin());
2530    let drives: Vec<&DriveParams> = rated.iter().collect();
2531    Ok(time_optimal_geometry(machine, &drives, limits, start, pieces, tolerance, slack)?.0.1)
2532}
2533
2534/// The speed, acceleration and jerk limits along a piece that `plan_time_optimal` uses: speed and acceleration
2535/// from the motors and the belt's tension limits, jerk from the axes.
2536fn motor_limits<'a>(
2537    machine: &'a dyn Machine,
2538    drives: &'a [&'a DriveParams],
2539    plan: &'a PlanLimits,
2540    [lowest, highest, share]: [f64; 3],
2541) -> impl Fn(&Geo) -> [f64; 3] + 'a {
2542    let reserve = plan.reserve;
2543    let axes = machine.axes();
2544    let [_, _, jerk] = axis_bounds(axes);
2545    let h = 1e-3;
2546    // Each motor's torque at the speed it turns at, along its whole curve (`MotorCurve`; level up to the rated speed),
2547    // less the shaft's friction there (at the rated speed below it).
2548    let torque = move |m: usize, speed: f64| {
2549        let speed = speed.max(drives[m].rated_speed);
2550        reserve * motor_torque(drives[m], speed) - plan.shaft_friction(m, speed)
2551    };
2552    move |piece| {
2553        let per_motor = |f: &dyn Fn(&mut [f64])| {
2554            let mut out = vec![0.0; machine.motors().len()];
2555            f(&mut out);
2556            out
2557        };
2558        // Per place and motor: the acceleration row with the torque that holds the tool, and how fast the motor turns
2559        // per unit of speed along the path (`fast` its most over the piece); `vel` and `fixed` do not depend on the speed.
2560        let (mut vel, mut fixed, mut rows) = (Vec::new(), Vec::new(), Vec::new());
2561        let mut fast = vec![0.0f64; machine.motors().len()];
2562        for i in 0..=8 {
2563            let pose = &piece.at(piece.length() * i as f64 / 8.0)[0];
2564            let unit = |axis: usize, size: f64| -> Vec<f64> {
2565                (0..axes.len()).map(|k| if k == axis { size } else { 0.0 }).collect()
2566            };
2567            let hold = per_motor(&|out| machine.feedforward_torque(pose, &unit(0, 0.0), out));
2568            // Per axis and motor: the torque for an acceleration of 1 m/s^2, and the angle per metre.
2569            let per_acc: Vec<Vec<f64>> = (0..axes.len())
2570                .map(|a| per_motor(&|out| machine.feedforward_torque(pose, &unit(a, 1.0), out)))
2571                .collect();
2572            let angle = |a: usize, sign: f64| {
2573                per_motor(&|out| {
2574                    machine.inverse(&pose.iter().zip(unit(a, sign * h)).map(|(p, d)| p + d).collect::<Vec<_>>(), out)
2575                })
2576            };
2577            let turn: Vec<Vec<f64>> = (0..axes.len())
2578                .map(|a| {
2579                    angle(a, 1.0)
2580                        .iter()
2581                        .zip(angle(a, -1.0))
2582                        .map(|(ahead, behind)| (ahead - behind) / (2.0 * h))
2583                        .collect()
2584                })
2585                .collect();
2586            let dir = &piece.at(piece.length() * i as f64 / 8.0)[1];
2587            for m in 0..hold.len() {
2588                vel.push((turn.iter().map(|per_axis| per_axis[m]).collect(), drives[m].max_speed));
2589                rows.push((
2590                    per_acc.iter().map(|per_axis| per_axis[m] - hold[m]).collect::<Vec<f64>>(),
2591                    hold[m].abs(),
2592                    m,
2593                ));
2594                fast[m] = fast[m].max(turn.iter().zip(dir).map(|(per_axis, d)| per_axis[m] * d).sum::<f64>().abs());
2595            }
2596            if lowest.is_finite() || highest.is_finite() {
2597                let tensions = |acc: &[f64]| {
2598                    let mut out = Vec::new();
2599                    machine.rigid_tensions(pose, acc, &mut out);
2600                    out
2601                };
2602                let still = tensions(&unit(0, 0.0));
2603                let per_acc: Vec<Vec<f64>> = (0..axes.len()).map(|a| tensions(&unit(a, 1.0))).collect();
2604                for (k, c) in still.iter().enumerate() {
2605                    fixed.push((
2606                        per_acc.iter().map(|per_axis| per_axis[k] - c).collect(),
2607                        share * (highest - c).min(c - lowest),
2608                    ));
2609                }
2610            }
2611        }
2612        // The limits for a plan that runs the piece at the speed `v`: the torque of each motor at the speed it then turns at.
2613        let at_speed = |v: f64| {
2614            let acc = rows
2615                .iter()
2616                .map(|(row, hold, m)| (row.clone(), torque(*m, fast[*m] * v) - hold))
2617                .chain(fixed.iter().cloned())
2618                .collect();
2619            limits(piece, &[vel.clone(), acc, jerk.clone()])
2620        };
2621        // The speed the piece is run at is the one its own limit allows at that speed (the torque falls with the speed, so
2622        // the limit does not rise): between 0, where the torque is the most, and that limit, the fixed point by halving.
2623        let top = at_speed(0.0);
2624        if !top[0].is_finite() || top[0] <= 0.0 || at_speed(top[0])[0] >= top[0] * (1.0 - 1e-12) {
2625            return top;
2626        }
2627        let (mut low, mut high) = (0.0, top[0]);
2628        for _ in 0..40 {
2629            let mid = 0.5 * (low + high);
2630            if at_speed(mid)[0] >= mid { low = mid } else { high = mid }
2631        }
2632        // Where the limit steps down at the fixed point (a step in a curve), the speed is held below that step.
2633        let mut out = at_speed(low);
2634        out[0] = out[0].min(high);
2635        out
2636    }
2637}
2638
2639// ---------------------------------------------------------------------------------------------
2640// Timing as fast as the motors allow, point by point.
2641
2642/// Whether a piece of `length` under `limits` can be timed from the speed `v0` at its start to `v1` at its end: by
2643/// `piece_timing` with its top at the higher of the two, or (`joins`) by `curve_join`.
2644fn piece_fits(limits: &PieceLimits, length: f64, [v0, v1]: [f64; 2], cycle: f64, joins: bool) -> bool {
2645    let (hold, step) = (2.0 * cycle, cycle / STEPS_PER_CYCLE);
2646    piece_timing(limits, length, [v0, v1, v0.max(v1)], hold, step, 0.0).is_some()
2647        || joins && curve_join(limits, length, [v0, v1], hold, step).is_some()
2648}
2649
2650/// The quickest timing of a piece from `v0` to `v1` (`piece_fits`): `piece_timing` at the highest top that fits, or
2651/// (`joins`) `curve_join` where that is quicker or the only one.
2652fn piece_knots(
2653    limits: &PieceLimits,
2654    length: f64,
2655    [v0, v1]: [f64; 2],
2656    cycle: f64,
2657    joins: bool,
2658) -> Result<Vec<[f64; 4]>, CommandError> {
2659    let (hold, step) = (2.0 * cycle, cycle / STEPS_PER_CYCLE);
2660    let timing = |top: f64, slack: f64| piece_timing(limits, length, [v0, v1, top], hold, step, slack);
2661
2662    // The top speed: the highest that fits, up to the curve's highest. The runs are the same whatever the top until
2663    // they brake for it, so the higher top is the quicker; it fits while the runs reach it before they meet.
2664    // The tops that fit need not be one range from `low` (a speed curve with two humps and a dip between them: a top
2665    // between the dip and the lower hump does not fit). `highest_fitting_scan` looks at every range, on a grid.
2666    let low = v0.max(v1);
2667    let peak = timing(low, 0.0).map(|_| {
2668        let highest = limits.curve[0].iter().fold(low * low, |a: f64, b| a.max(*b)).sqrt();
2669        let top = highest_fitting_scan(low, highest, |top| timing(top, 0.0).is_some());
2670        // The look-ahead has made every piece fit; the slack is for a difference in the last bit.
2671        timing(top, 1e-9 * length)
2672    });
2673    let joined = if joins { curve_join(limits, length, [v0, v1], hold, step) } else { None };
2674    let duration = |knots: &Option<Vec<[f64; 4]>>| knots.as_ref().map_or(f64::INFINITY, |k| k[k.len() - 1][0]);
2675    let peak = peak.flatten();
2676    let quicker = if duration(&joined) < duration(&peak) { joined } else { peak };
2677    quicker.ok_or(CommandError { key: "error-path" })
2678}
2679
2680/// The speed at the start of each piece and at the end of the last, at rest at both ends of the path, as fast as each
2681/// junction and the pieces beside it allow: `junction_speed` (the step of the axes' rates), what the speed curve of each
2682/// piece allows at the junction (its first or its last place, from where it can still slow down along the curve), and
2683/// the look-ahead of `timed` with `piece_fits`. A run from the junction into either piece has to keep below that piece's
2684/// speed curve (`follow` with no top), which caps the junction before the look-ahead. The look-ahead takes each speed as
2685/// fitting from the lower of a junction's speed and the next one's on, which holds where both are no faster than the
2686/// slowest place of their pieces; where the speeds that come out leave a piece that does not fit, the two junctions of
2687/// that piece are lowered to what they are with `joins` off and the look-ahead runs again, piece by piece, as long as
2688/// pieces are left that do not fit (at most once per piece; then the whole path as with `joins` off). With `joins` off,
2689/// `curve_join` is left out and a junction is passed no faster than the slowest place of either piece, as before 14
2690/// November (also for the comparison in the tests).
2691fn junction_speeds(axes: &[AxisInfo], geo: &[Geo], limits: &[PieceLimits], cycle: f64, joins: bool) -> Vec<f64> {
2692    let n = geo.len();
2693    let (hold, step) = (2.0 * cycle, cycle / STEPS_PER_CYCLE);
2694    let fits = |i: usize, v0: f64, v1: f64| piece_fits(&limits[i], geo[i].length(), [v0, v1], cycle, joins);
2695    let curve_end = |l: &PieceLimits, end: bool| l.curve[0][if end { l.curve[0].len() - 1 } else { 0 }].sqrt();
2696    // A run from the speed `v` at piece i's start (`backward`: its end) that follows its curve all along.
2697    let enters = |i: usize, v: f64, backward: bool| {
2698        follow(&limits[i], v, f64::INFINITY, [hold * v, geo[i].length()], backward, step)
2699    };
2700    let mut speed = vec![0.0; n + 1];
2701    for i in 1..n {
2702        // A piece too short for the steady cycles at both of its ends is passed slowly enough to have them.
2703        let short = geo[i - 1].length().min(geo[i].length()) / (2.0 * hold);
2704        let (before, after) = if joins {
2705            (curve_end(&limits[i - 1], true), curve_end(&limits[i], false))
2706        } else {
2707            (limits[i - 1].lowest, limits[i].lowest)
2708        };
2709        speed[i] = junction_speed(&geo[i - 1], &geo[i], axes, cycle).min(before).min(after).min(short);
2710        let slowest = limits[i - 1].lowest.min(limits[i].lowest);
2711        if joins && speed[i] > slowest {
2712            let ok = |v: f64| enters(i, v, false).is_some() && enters(i - 1, v, true).is_some();
2713            speed[i] = highest_fitting(slowest.min(speed[i]), speed[i], ok);
2714        }
2715    }
2716    let look_ahead = |speed: &mut Vec<f64>| {
2717        for i in (0..n).rev() {
2718            let after = speed[i + 1];
2719            speed[i] = largest(after.min(speed[i]), speed[i], |v| fits(i, v, after));
2720        }
2721        for i in 0..n {
2722            let before = speed[i];
2723            speed[i + 1] = largest(before.min(speed[i + 1]), speed[i + 1], |v| fits(i, before, v));
2724        }
2725    };
2726    look_ahead(&mut speed);
2727    if !joins {
2728        return speed;
2729    }
2730    // Per piece that does not fit, its two junctions as without the joins, where that is slower.
2731    let mut without: Option<Vec<f64>> = None;
2732    for _ in 0..n {
2733        let misfits: Vec<usize> = (0..n).filter(|&i| !fits(i, speed[i], speed[i + 1])).collect();
2734        if misfits.is_empty() {
2735            return speed;
2736        }
2737        let without = without.get_or_insert_with(|| junction_speeds(axes, geo, limits, cycle, false));
2738        for i in misfits {
2739            (speed[i], speed[i + 1]) = (speed[i].min(without[i]), speed[i + 1].min(without[i + 1]));
2740        }
2741        look_ahead(&mut speed);
2742    }
2743    junction_speeds(axes, geo, limits, cycle, false)
2744}
2745
2746/// The places at which the time-optimal plan reads the rigid model are about this far apart along a piece (m), and on
2747/// a curve no more than `PLACE_TURN` of its turning (rad), at least `PLACES_LEAST` and at most `PLACES_MOST` of them
2748/// per piece. Between two places the bounds are taken as straight; where the direction turns by 0.02 rad they bend
2749/// away from that by about 0.02^2 / 8 = 5e-5 of themselves, within what the plan keeps back (`KEPT_BACK`).
2750const PLACE_SPACING: f64 = 2e-3;
2751const PLACE_TURN: f64 = 0.02;
2752const PLACES_LEAST: usize = 32;
2753const PLACES_MOST: usize = 1000;
2754/// The share of each torque and tension limit that the time-optimal plan keeps back, for what falls between its
2755/// places and the rounding of its steps.
2756const KEPT_BACK: f64 = 2e-4;
2757/// The share of each speed rating (a motor's maximum speed, a gearbox's input speed, a screw's speed) that the
2758/// time-optimal plan keeps back for the following of the loops: a plan at the motors' 420 rad/s ran them up to 420.66
2759/// rad/s (0.157 % over) on a belt gantry's cycle. This is the least `PlanLimits::speed_kept` has; `speed_kept_of`
2760/// raises it for a loop that follows less closely.
2761const SPEED_KEPT: f64 = 0.01;
2762/// The most `speed_kept_of` keeps back.
2763const SPEED_KEPT_MOST: f64 = 0.5;
2764/// Steps of the time-optimal plan's ramps per profile cycle.
2765const STEPS_PER_CYCLE: f64 = 4.0;
2766/// The step of the central differences by which the plan reads the motors' speed per speed along the path (m).
2767const TURN_STEP: f64 = 1e-6;
2768/// The most a motor may turn per distance along the path (rad per m, or per rad in joint space) before it is at a
2769/// singularity: a gearbox of 100 on an arm of 0.1 m turns 1e3, so this is far beyond any machine that moves. It is
2770/// the cap of `singular_turn`, which takes the motor's own bound.
2771const SINGULAR_TURN: f64 = 1e6;
2772
2773/// The most a motor of top speed `top` (rad/s) may turn per distance along a piece of `length`: a plan takes at most
2774/// `PLAN_LONGEST` over the piece, so it crawls no slower than length / `PLAN_LONGEST`, and at that speed the motor,
2775/// held to `top`, turns at most top / (length / `PLAN_LONGEST`) per unit of distance; more is a singularity (the plan
2776/// would have to crawl below that). No more than `SINGULAR_TURN`.
2777fn singular_turn(top: f64, length: f64) -> f64 {
2778    SINGULAR_TURN.min(top * PLAN_LONGEST / length)
2779}
2780/// The longest a time-optimal plan may take (s): a path that crawls this slowly passes a singularity, or a pose where
2781/// the motors nearly cannot move the tool, and its poses (one per profile cycle, a million at 1 ms) would be unbounded.
2782const PLAN_LONGEST: f64 = 1000.0;
2783/// The step of the second differences by which the plan reads how the motors' speed per speed along the path changes
2784/// along it, for the torque that turns a gearbox's input (m, or rad on a path in joint space).
2785const BEND_STEP: f64 = 1e-4;
2786/// The share of the ceilings of acceleration that the speed curve a piece follows may use (`smoothed`), and the share of
2787/// the ramps' jerk its own jerk may use: the rest lets a run catch up with the curve and follow its bends.
2788const CURVE_ACCELERATION: f64 = 0.9;
2789const CURVE_JERK: f64 = 0.5;
2790/// How far a run with no top may get above the speed curve it follows (`follow`, for `curve_join`), as a share of the
2791/// curve's speed: a run that comes onto the curve at its ceiling of acceleration passes it by some 1e-4 before it
2792/// settles on it; one that starts faster than the curve lets it slow down passes it by far more. The plans' tests allow
2793/// the motors 0.1 % over their rated speed for the same rounding.
2794const CURVE_OVERSHOOT: f64 = 1e-3;
2795/// The most sweeps that lower the speed curve until its acceleration and jerk hold.
2796const CURVE_SWEEPS: usize = 300;
2797/// The speeds, evenly from zero to the curve's highest, at which the ceilings of acceleration are worked out
2798/// (`PieceLimits::most`): a run takes the ceilings of the lowest level at or above the speed it can reach.
2799const LEVELS: usize = 32;
2800/// The most steps of a run along a piece (`follow`): one that takes longer is held back by a ceiling near zero and
2801/// refused. 2^18 steps are 65 s at a profile cycle of 1 ms.
2802const RUN_STEPS: usize = 1 << 18;
2803/// The most points a plan may have: ten million, 2.8 hours at a planning cycle of 1 ms (160 MB of
2804/// six-axis poses).
2805const PLAN_POINTS_MOST: f64 = 1e7;
2806
2807/// What bounds the speed v and the acceleration a along the path at one place of a piece (p', p'', p''': the pose's
2808/// derivatives by the distance along the path).
2809struct Place {
2810    /// low <= c a + d v^2 + e <= high, as [c, d, e, low, high]: per motor its torque (c per acceleration, d per speed
2811    /// squared: the centripetal and Coriolis part, e the torque that holds the tool), per belt section its change of
2812    /// tension (e = 0).
2813    rows: Vec<[f64; 5]>,
2814    /// Per motor behind a lossy gearbox (the first rows; empty where no motor has one): the row [c, d, e] with eta of the
2815    /// load's torque (the load drives the motor) beside the 1 / eta of `rows` (the motor drives the load); `Place::against`
2816    /// says which holds against which bound.
2817    low: Vec<[f64; 3]>,
2818    /// Per motor (the first rows), how fast it turns per speed along the path (rad/m, signed): its row's low and high
2819    /// are then those of its curve (`curves`) at that speed, not the row's own (which are those at a standstill).
2820    turn: Vec<f64>,
2821    curves: Arc<[MotorCurve]>,
2822    /// Per motor the friction of the guides it drives (`Machine::rigid_friction`, `rigid_friction_rise`); empty where the
2823    /// machine tells none.
2824    guide: Vec<Friction>,
2825    /// Per row (after the motors' rows; none where empty) a part b v of its value that grows with the speed v along the
2826    /// path alone (a screw's speed): its value is then c a + b v + d v^2 + e (`Machine::rigid_checks`).
2827    speed: Vec<f64>,
2828    /// Per axis, 3 |p''| v |a| + |p'''| v^3 <= room as [3 |p''|, |p'''|, room]: the part of the axis jerk that speed and
2829    /// acceleration take on a curve. The rest of the jerk limit is for the ramps.
2830    bends: Vec<[f64; 3]>,
2831    /// The share of the curves' top speed the motors may turn at here: the place's own share kept back for the loops'
2832    /// following (`PlanLimits::kept_at`) against the one the curves are built with.
2833    scale: f64,
2834    /// The highest speed at which the place holds every row and bend without acceleration.
2835    top: f64,
2836}
2837/// A motor's friction against the guides it drives at the speed w along the path,
2838/// f(w) = c + sum level exp(-(w / speed)^2) + b w, a [level, speed] per guide (`Machine::rigid_friction`,
2839/// `rigid_friction_rise`), and the speeds of its interior extremes, f'(w) = b - sum 2 level w / speed^2 exp(-(w / speed)^2) = 0.
2840/// interior extremes, f'(w) = b - sum 2 level w / speed^2 exp(-(w / speed)^2) = 0.
2841#[derive(Clone, Debug, Default)]
2842struct Friction {
2843    c: f64,
2844    b: f64,
2845    rises: Vec<[f64; 2]>,
2846    turns: Vec<f64>,
2847}
2848
2849impl Friction {
2850    /// The stationary speeds by bisection of every change of sign of f' on a grid 2 % apart from a thousandth of the
2851    /// least Stribeck speed to 6 times the largest (and from 0, where f' = b). Beyond that the rises' slopes are below
2852    /// e^-36 of theirs: f' is b there. Between grid points f' changes its sign at most once unless two extremes lie
2853    /// within 2 % of a speed, where f differs between them by a part in 10^5 of the rise.
2854    fn new(c: f64, b: f64, rises: Vec<[f64; 2]>) -> Self {
2855        let rises: Vec<[f64; 2]> = rises.into_iter().filter(|[level, speed]| *level != 0.0 && *speed > 0.0).collect();
2856        let slope = |w: f64| {
2857            b - rises
2858                .iter()
2859                .map(|[level, speed]| 2.0 * level * w / (speed * speed) * (-(w / speed).powi(2)).exp())
2860                .sum::<f64>()
2861        };
2862        let (least, most) = rises.iter().fold((f64::INFINITY, 0.0f64), |(lo, hi), r| (lo.min(r[1]), hi.max(r[1])));
2863        let mut grid = vec![0.0];
2864        let mut w = 1e-3 * least;
2865        while w < 6.0 * most {
2866            grid.push(w);
2867            w *= 1.02;
2868        }
2869        grid.push(6.0 * most);
2870        let mut turns = Vec::new();
2871        for pair in grid.windows(2).filter(|_| !rises.is_empty()) {
2872            let (mut lo, mut hi) = (pair[0], pair[1]);
2873            let (at_lo, at_hi) = (slope(lo), slope(hi));
2874            if at_hi == 0.0 {
2875                turns.push(hi);
2876            } else if at_lo * at_hi < 0.0 {
2877                for _ in 0..100 {
2878                    let mid = 0.5 * (lo + hi);
2879                    if (slope(mid) > 0.0) == (at_lo > 0.0) { lo = mid } else { hi = mid }
2880                }
2881                turns.push(0.5 * (lo + hi));
2882            }
2883        }
2884        Self { c, b, rises, turns }
2885    }
2886
2887    fn at(&self, w: f64) -> f64 {
2888        self.c + self.b * w + self.rises.iter().map(|[level, speed]| level * (-(w / speed).powi(2)).exp()).sum::<f64>()
2889    }
2890
2891    /// The least and the most of f over the speeds from 0 to `v`, and of 0 (the torque it gives at a standstill): at the
2892    /// ends or at a stationary speed below v.
2893    fn range(&self, v: f64) -> (f64, f64) {
2894        let inner = self.turns.iter().filter(|&&w| w < v).map(|&w| self.at(w));
2895        let all: Vec<f64> = [0.0, self.at(0.0), self.at(v)].into_iter().chain(inner).collect();
2896        (all.iter().copied().fold(f64::INFINITY, f64::min), all.iter().copied().fold(f64::NEG_INFINITY, f64::max))
2897    }
2898}
2899
2900#[cfg(test)]
2901mod friction_range_tests {
2902    use super::Friction;
2903
2904    fn range([c, b, level, speed]: [f64; 4], v: f64) -> (f64, f64) {
2905        Friction::new(c, b, vec![[level, speed]]).range(v)
2906    }
2907
2908    /// Without a rise [c, b] give the ends and 0: c = 1, b = -2 at v = 0.3: f runs from 1 to 0.4, with 0 below: (0, 1).
2909    /// With a rise 0.5 over speed 0.1 and b = 0: the friction at a standstill is 1.5 and falls to 1 + 0.5 e^-9 at 0.3.
2910    /// With level 1, speed 1, b = 0.5 the friction first rises (f' = b > 0 at 0) to a maximum where t e^(-t^2) = 0.25, the
2911    /// smaller root t = 0.2685 (found by Newton below), which beats the standstill value: f = 0 + e^(-t^2) + 0.5 t.
2912    #[test]
2913    fn the_friction_range_has_its_ends_and_its_interior_extremes() {
2914        assert_eq!(range([1.0, -2.0, 0.0, 1.0], 0.3), (0.0, 1.0));
2915        let (least, most) = range([1.0, 0.0, 0.5, 0.1], 0.3);
2916        assert!((most - 1.5).abs() < 1e-12 && least == 0.0, "{least} {most}");
2917        let mut t: f64 = 0.27;
2918        for _ in 0..20 {
2919            let (g, dg) = (t * (-t * t).exp() - 0.25, (1.0 - 2.0 * t * t) * (-t * t).exp());
2920            t -= g / dg;
2921        }
2922        let top = (-t * t).exp() + 0.5 * t;
2923        assert!(top > 1.0 && (t - 0.2685).abs() < 1e-3, "{t} {top}");
2924        // (At v = 2 the end, e^-4 + 1, is below that maximum; the second root, t = 1.28, is a minimum.)
2925        let (_, most) = range([0.0, 0.5, 1.0, 1.0], 2.0);
2926        assert!((most - top).abs() < 1e-9, "{most} against {top}");
2927        // Not reached below the speed: v = 0.1 stops before t = 0.2685.
2928        let (_, most) = range([0.0, 0.5, 1.0, 1.0], 0.1);
2929        assert!((most - (1.0_f64.max((-0.01_f64).exp() + 0.05))).abs() < 1e-12, "{most}");
2930    }
2931
2932    /// Two guides on one motor with Stribeck speeds 10 apart and rises of opposite sign (a motor driving two axes that
2933    /// turn against each other): c = 0.2, b = 0.3, rises 1 over 0.01 and -0.6 over 0.1. Against the extremes of f sampled
2934    /// at a million speeds up to v = 0.5 (each within its sampling step's |f'| dw < 1e-9 of the true one).
2935    #[test]
2936    fn two_rises_have_the_extremes_of_their_sum() {
2937        let friction = Friction::new(0.2, 0.3, vec![[1.0, 0.01], [-0.6, 0.1]]);
2938        let v = 0.5;
2939        let samples = 1_000_000;
2940        let (mut lo, mut hi) = (0.0f64, f64::NEG_INFINITY);
2941        for k in 0..=samples {
2942            let f = friction.at(v * k as f64 / samples as f64);
2943            (lo, hi) = (lo.min(f), hi.max(f));
2944        }
2945        let (least, most) = friction.range(v);
2946        assert!((least - lo).abs() < 1e-9 && (most - hi).abs() < 1e-9, "({least}, {most}) against ({lo}, {hi})");
2947        // The minimum lies inside, below both ends.
2948        assert!(friction.turns.iter().any(|&w| friction.at(w) < friction.at(v).min(friction.at(0.0)) - 1e-3), "{lo}");
2949    }
2950}
2951
2952impl Place {
2953    /// The low and high of row `i` at the speed `v` along the path, and at every speed below it.
2954    fn bounds(&self, i: usize, v: f64) -> (f64, f64) {
2955        match self.turn.get(i) {
2956            Some(turn) => {
2957                // Beyond the place's own ceiling no room (the curve's own end is where its table ends).
2958                if (turn * v).abs() > self.scale * self.curves[i].max_speed() * (1.0 - 1e-12) {
2959                    return (f64::INFINITY, f64::NEG_INFINITY);
2960                }
2961                let (low, high) = self.curves[i].range(turn * v);
2962                // The guides' friction takes its torque off the room on its side, at its most over the speeds up to v
2963                // (from none at a standstill).
2964                let (least, most) = self.guide.get(i).map_or((0.0, 0.0), |g| g.range(v));
2965                (low - least, high - most)
2966            }
2967            None => {
2968                // The part b v takes its room off its side, at its most over the speeds up to v, as the friction above.
2969                let b = self.speed.get(i).copied().unwrap_or(0.0) * v;
2970                (self.rows[i][3] - b.min(0.0), self.rows[i][4] - b.max(0.0))
2971            }
2972        }
2973    }
2974
2975    /// Row `i`'s forms [c, d, e], each with whether it holds against the high and the low bound. Behind a lossy gearbox the
2976    /// motor gives I alpha + (T - I alpha) / eta where the load's torque T - I alpha turns the way the motor turns (it
2977    /// drives the load), I alpha + eta (T - I alpha) where against it (the load drives the motor): for a motor that turns
2978    /// forwards along the path that is the larger of the two forms, for one that turns backwards the smaller. So the eta
2979    /// form holds against both bounds, and the 1 / eta form against the high bound where the motor turns forwards, the low
2980    /// where backwards (both where it stands), whichever sign the load's torque has, the rotor's I alpha too.
2981    fn against(&self, i: usize) -> [([f64; 3], bool, bool); 2] {
2982        let [c, d, e, ..] = self.rows[i];
2983        match self.low.get(i) {
2984            Some(&eta) => {
2985                let turn = self.turn.get(i).copied().unwrap_or(0.0);
2986                [([c, d, e], turn >= 0.0, turn <= 0.0), (eta, true, true)]
2987            }
2988            None => [([c, d, e], true, true), ([c, d, e], false, false)],
2989        }
2990    }
2991
2992    /// Whether row `i` holds at the speed `v` along the path without acceleration, each of its forms against its bounds.
2993    fn holds(&self, i: usize, v: f64) -> bool {
2994        let (low, high) = self.bounds(i, v);
2995        self.against(i).iter().all(|([_, d, e], vs_high, vs_low)| {
2996            (!vs_high || d * v * v + e <= high) && (!vs_low || d * v * v + e >= low)
2997        })
2998    }
2999
3000    /// The most acceleration (`sign` 1) or deceleration (-1) along the path that holds every row and bend here at
3001    /// every speed from zero to `top`. Rows are linear in v^2, so the two ends of that range are the worst, against
3002    /// bounds that do not widen with the speed (a motor's curve), so those at `top`; the bends get tighter with the
3003    /// speed, so `top` is. A row's form that grows with the acceleration meets its high bound, one that falls its low
3004    /// bound (`against`).
3005    fn most(&self, top: f64, sign: f64) -> f64 {
3006        let x = top * top;
3007        let rows = (0..self.rows.len()).flat_map(|i| {
3008            let (low, high) = self.bounds(i, top);
3009            self.against(i).into_iter().flat_map(move |([c, d, e], vs_high, vs_low)| {
3010                let up = (vs_high && c * sign > 0.0).then(|| (high - e).min(high - (d * x + e)) / c.abs());
3011                let down = (vs_low && c * sign < 0.0).then(|| (e - low).min(d * x + e - low) / c.abs());
3012                [up, down]
3013            })
3014        });
3015        let rows = rows.flatten();
3016        let bends = self
3017            .bends
3018            .iter()
3019            .filter(|b| b[0] > 0.0 && top > 0.0)
3020            .map(|[p2, p3, room]| (room - p3 * top.powi(3)) / (p2 * top));
3021        rows.chain(bends).fold(f64::INFINITY, f64::min).max(0.0)
3022    }
3023}
3024
3025/// A piece as the time-optimal plan sees it: its places, evenly spaced by `spacing` from its start to its end, the
3026/// jerk along the path its ramps may use, the lowest of the places' speeds without acceleration, and for a run from
3027/// the start ([0]) and one from the end ([1]), each by the distance from where it starts: the speed curve it follows
3028/// (`smoothed`, as squared speeds at the places) and, per speed level (`level` apart, `LEVELS` of them), the most
3029/// acceleration and deceleration of the run at each place at speeds up to that level (`ceiling`), as
3030/// most[run][acceleration or deceleration][level][place].
3031struct PieceLimits {
3032    places: Vec<Place>,
3033    spacing: f64,
3034    jerk: f64,
3035    lowest: f64,
3036    curve: [Vec<f64>; 2],
3037    /// Per run, the lowest of the curve over 2^i places from each place on, as lowest_ahead[run][i][place].
3038    lowest_ahead: [Vec<Vec<f64>>; 2],
3039    level: f64,
3040    most: [[Vec<Vec<f64>>; 2]; 2],
3041}
3042
3043impl PieceLimits {
3044    /// The speed level whose ceilings hold up to the speed `v`.
3045    fn level_of(&self, v: f64) -> usize {
3046        ((v / self.level).ceil() as usize).clamp(1, LEVELS) - 1
3047    }
3048
3049    /// The lowest squared speed of a run's curve between the distances `from` and `to` (by the places around them).
3050    fn lowest_between(&self, backward: bool, from: f64, to: f64) -> f64 {
3051        let table = &self.lowest_ahead[backward as usize];
3052        let last = table[0].len() - 1;
3053        let (i, j) = (((from / self.spacing) as usize).min(last), ((to / self.spacing).ceil() as usize).min(last));
3054        let (i, j) = (i.min(j), i.max(j));
3055        let size = (usize::BITS - 1 - (j - i + 1).leading_zeros()) as usize;
3056        table[size][i].min(table[size][j + 1 - (1 << size)])
3057    }
3058}
3059
3060/// The lowest of `values` over 2^i entries from each entry on, for i from 0 while 2^i fits: a range's lowest is then the
3061/// lower of two overlapping such spans.
3062fn lowest_ahead(values: &[f64]) -> Vec<Vec<f64>> {
3063    let mut table = vec![values.to_vec()];
3064    while 2 << (table.len() - 1) <= values.len() {
3065        let (half, last) = (1 << (table.len() - 1), &table[table.len() - 1]);
3066        let next = (0..=values.len() - 2 * half).map(|k| last[k].min(last[k + half])).collect();
3067        table.push(next);
3068    }
3069    table
3070}
3071
3072/// The speed curve a piece follows from below, as squared speeds x at its places: no place's top exceeded, the
3073/// acceleration along it (x' / 2) within `CURVE_ACCELERATION` of the places' ceilings (`Place::most`, at speeds up to
3074/// the curve's), and its jerk (v times the change of that acceleration per distance, so |x''| <= 2 j / v) within
3075/// `CURVE_JERK` of the ramps' jerk. It starts at the places' tops (infinite ones at the highest finite) and is only ever
3076/// lowered, in sweeps forwards and backwards: a rise or a fall too steep lowers its upper end; a peak too sharp is
3077/// lowered onto the bound; at a dip too sharp the higher of its two sides is lowered, then both. So it never falls below
3078/// its lowest place's top, which is also why the end speeds a piece is planned with (no more than that,
3079/// `timed_by_motors`) are always below it.
3080///
3081/// shortcut: the sweeps stop once one changes the curve by no more than 1e-7 of its highest, or after `CURVE_SWEEPS`
3082/// (a sharp dip converges slowly, by about 1 % a sweep); what is left of a bend too sharp is far within the jerk the runs
3083/// keep beside the curve's. Solve the bends directly (a parabola in x around each dip) if a machine's dips need more.
3084fn smoothed(places: &[Place], spacing: f64, jerk: f64, highest: f64) -> Vec<f64> {
3085    let n = places.len();
3086    let mut x: Vec<f64> = places.iter().map(|p| p.top.min(highest).powi(2)).collect();
3087    let most = |k: usize, x: f64, sign: f64| CURVE_ACCELERATION * places[k].most(x.sqrt(), sign);
3088    let bend = 2.0 * CURVE_JERK * jerk * spacing * spacing;
3089    let bend_at = |x: &mut Vec<f64>, k: usize| {
3090        let (c, d2) = (bend / x[k].sqrt(), x[k - 1] + x[k + 1] - 2.0 * x[k]);
3091        if d2 < -c {
3092            x[k] = 0.5 * (x[k - 1] + x[k + 1] + c);
3093        } else if d2 > c {
3094            let (high, low) = if x[k - 1] > x[k + 1] { (k - 1, k + 1) } else { (k + 1, k - 1) };
3095            let mut excess = d2 - c;
3096            let first = excess.min(x[high] - x[low]);
3097            (x[high], excess) = (x[high] - first, excess - first);
3098            x[k - 1] -= 0.5 * excess;
3099            x[k + 1] -= 0.5 * excess;
3100        }
3101    };
3102    for _ in 0..CURVE_SWEEPS {
3103        let before = x.clone();
3104        for k in 0..n - 1 {
3105            let rise = most(k, x[k + 1], 1.0).min(most(k + 1, x[k + 1], 1.0));
3106            x[k + 1] = x[k + 1].min(x[k] + 2.0 * spacing * rise);
3107            if k > 0 {
3108                bend_at(&mut x, k);
3109            }
3110        }
3111        for k in (0..n - 1).rev() {
3112            let fall = most(k, x[k], -1.0).min(most(k + 1, x[k], -1.0));
3113            x[k] = x[k].min(x[k + 1] + 2.0 * spacing * fall);
3114            if k + 2 < n {
3115                bend_at(&mut x, k + 1);
3116            }
3117        }
3118        let top = x.iter().fold(0.0, |a: f64, b| a.max(*b));
3119        if x.iter().zip(&before).all(|(now, then)| then - now <= 1e-7 * top) {
3120            break;
3121        }
3122    }
3123    x
3124}
3125
3126/// The most acceleration of a run (`sign` 1 for a run from the start: forwards; -1 from the end: the deceleration
3127/// forwards) or the most it slows down (the other sign) at each place, by the distance from where the run starts
3128/// (`backward` from the end), at speeds up to the run's `curve` there and up to `cap`, lowered ahead of where it falls by
3129/// the jerk times the least time between two places (their spacing over that speed), so that the acceleration can
3130/// follow it. Between places it is taken as straight (`ceiling_at`), within what the plan keeps back (`KEPT_BACK`).
3131fn ceiling(places: &[Place], curve: &[f64], spacing: f64, jerk: f64, sign: f64, backward: bool, cap: f64) -> Vec<f64> {
3132    let n = places.len();
3133    let at = |k: usize| if backward { n - 1 - k } else { k };
3134    let speed: Vec<f64> = curve.iter().map(|x| x.sqrt().min(cap)).collect();
3135    let mut most: Vec<f64> = (0..n).map(|k| places[at(k)].most(speed[k], sign)).collect();
3136    for k in (0..n - 1).rev() {
3137        most[k] = most[k].min(most[k + 1] + jerk * spacing / speed[k].max(speed[k + 1]));
3138    }
3139    most
3140}
3141
3142/// The share of its axes' jerk a curved piece's ramps may use: what the bends 3 |p''| v a + |p'''| v^3 leave of an axis's
3143/// limit at the piece's own ceilings of speed and acceleration (the axes' limits along the path), at least 0.4 (as `curved`
3144/// shares it out), so a slight curve keeps nearly all of it. `derivatives`: the pose and its three derivatives per place.
3145fn ramp_share(axes: &[AxisInfo], derivatives: &[[Vec<f64>; 4]]) -> f64 {
3146    let ceiling = |most: fn(&AxisInfo) -> f64| {
3147        derivatives
3148            .iter()
3149            .flat_map(|[_, d1, ..]| axes.iter().zip(d1).map(move |(a, d)| most(a) / d.abs()))
3150            .fold(f64::INFINITY, f64::min)
3151    };
3152    let (v, a) = (ceiling(|a| a.max_vel), ceiling(|a| a.max_acc));
3153    let used = derivatives
3154        .iter()
3155        .flat_map(|[_, _, d2, d3]| {
3156            axes.iter()
3157                .enumerate()
3158                .map(move |(i, ax)| (3.0 * d2[i].abs() * v * a + d3[i].abs() * v.powi(3)) / ax.max_jerk)
3159        })
3160        .fold(0.0, f64::max);
3161    if used.is_finite() { (1.0 - used).clamp(0.4, 1.0) } else { 0.4 }
3162}
3163
3164/// The places of a piece and what bounds the time-optimal plan at each (see `plan_time_optimal`). Refused where the
3165/// torque that holds the tool (at a motor or a gearbox), the belt's holding tension or a guide's load at rest leaves no
3166/// room, or where the piece turns no motor.
3167fn piece_limits(
3168    machine: &dyn Machine,
3169    curves: &Arc<[MotorCurve]>,
3170    limits: &PlanLimits,
3171    geo: &Geo,
3172    cycle: f64,
3173) -> Result<PieceLimits, CommandError> {
3174    let (reserve, [lowest, highest, share]) = (limits.reserve, limits.tension);
3175    let gearbox = |m: usize| limits.gearbox.get(m).copied().flatten();
3176    let (axes, motors, length) = (machine.axes(), machine.motors().len(), geo.length());
3177    // The tightest curvature, so that on a tight curve the places are no more than `PLACE_TURN` of its turning apart.
3178    let tightest = match geo {
3179        Geo::Line { .. } | Geo::Slerp { .. } => 0.0,
3180        Geo::Arc { radius, .. } | Geo::Arc3 { radius, .. } => 1.0 / radius,
3181        Geo::Clothoid { k0, k1, .. } => k0.abs().max(k1.abs()),
3182        Geo::Spline { tightest, .. } => *tightest,
3183        Geo::Carried { arc, length, .. } => {
3184            let Geo::Arc3 { radius, length: on_arc, .. } = **arc else { unreachable!("a carried piece is an arc") };
3185            (on_arc / length).powi(2) / radius
3186        }
3187    };
3188    let count =
3189        ((length / PLACE_SPACING).max(tightest * length / PLACE_TURN).ceil() as usize).clamp(PLACES_LEAST, PLACES_MOST);
3190    let spacing = length / count as f64;
3191    // The pose and its derivatives by distance; the third from the second by central differences within the piece.
3192    let h = spacing / 4.0;
3193    let derivatives: Vec<[Vec<f64>; 4]> = (0..=count)
3194        .map(|k| {
3195            let s = if k == count { length } else { k as f64 * spacing };
3196            let [pose, d1, d2] = geo.at(s);
3197            let (behind, ahead) = ((s - h).max(0.0), (s + h).min(length));
3198            let d3 = geo.at(ahead)[2].iter().zip(&geo.at(behind)[2]).map(|(a, b)| (a - b) / (ahead - behind)).collect();
3199            [pose, d1, d2, d3]
3200        })
3201        .collect();
3202    // The ramps' jerk along the path: on a line all of the axes' jerk limits; on a curve what its bends leave, 0.4 at least, as `curved` shares
3203    // it out, and the bends get the rest. A turning slerp bends its rotation vector a little (and its differences
3204    // add rounding): an axis of it that bends keeps 0.6 of its jerk limit for that, or the bend would stop the piece.
3205    let slerp = matches!(geo, Geo::Slerp { .. });
3206    let bends = |i: usize| slerp && derivatives.iter().any(|[_, _, d2, _]| d2[i] != 0.0);
3207    let along = derivatives
3208        .iter()
3209        .flat_map(|[_, d1, ..]| {
3210            axes.iter().zip(d1).enumerate().map(|(i, (a, d))| if bends(i) { 0.4 } else { 1.0 } * a.max_jerk / d.abs())
3211        })
3212        .fold(f64::INFINITY, f64::min);
3213    // A curve's ramps get what its bends leave (`ramp_share`); the bends' rows below take the rest of each axis's limit
3214    // whatever the share, so the limits hold with any share.
3215    let ramps = if matches!(geo, Geo::Line { .. } | Geo::Slerp { .. }) { 1.0 } else { ramp_share(axes, &derivatives) };
3216    let jerk = ramps * along;
3217    // What each motor gives at a standstill, either way: the bounds of its row, and what holds the tool.
3218    let torque: Vec<f64> = curves.iter().map(|c| c.motoring[0].min(c.braking[0])).collect();
3219    let zero = vec![0.0; axes.len()];
3220    let checks = machine.rating_checks();
3221    let mut places = Vec::new();
3222    for [pose, d1, d2, d3] in &derivatives {
3223        // The share of the speed ratings kept back here, and what the speed ceiling is of the curves' (`PlanLimits::kept_at`).
3224        let kept = limits.kept_at_reserve(machine, pose, limits.reserve / limits.margin);
3225        let scale = (1.0 - kept) / (1.0 - limits.curve_kept());
3226        let torques = |vel: &[f64], acc: &[f64]| {
3227            let mut out = vec![0.0; motors];
3228            machine.feedforward_torque_moving(pose, vel, acc, &mut out);
3229            out
3230        };
3231        // At the speed v and the acceleration a along the path the tool moves at v p' and accelerates at a p' + v^2 p''.
3232        let (hold, per_acc, per_speed) = (torques(&zero, &zero), torques(&zero, d1), torques(d1, d2));
3233        // The motors' angles a distance h along the path, to second order: pose + h p' + h^2 / 2 p''.
3234        let angles = |h: f64| {
3235            let mut out = vec![0.0; motors];
3236            let moved: Vec<f64> =
3237                pose.iter().zip(d1).zip(d2).map(|((p, d1), d2)| p + h * d1 + 0.5 * h * h * d2).collect();
3238            machine.inverse(&moved, &mut out);
3239            out
3240        };
3241        let (ahead, behind) = (angles(TURN_STEP), angles(-TURN_STEP));
3242        // Near a singularity (or where the inverse finds no pose) a motor turns without bound per distance along the
3243        // path, and the plan would crawl or, with the rows not finite, run unbounded: refused.
3244        let bounded = |v: &[f64]| v.iter().all(|x| x.is_finite());
3245        if ![&hold, &per_acc, &per_speed, &ahead, &behind].iter().all(|v| bounded(v))
3246            || ahead
3247                .iter()
3248                .zip(&behind)
3249                .zip(curves.iter())
3250                .any(|((a, b), curve)| (a - b).abs() > 2.0 * TURN_STEP * singular_turn(curve.max_speed(), length))
3251        {
3252            return Err(CommandError { key: "error-path-singular" });
3253        }
3254        if hold.iter().zip(&torque).any(|(t, most)| t.abs() >= *most) {
3255            return Err(CommandError { key: "error-path-torque" });
3256        }
3257        let mut rows: Vec<[f64; 5]> = (0..motors)
3258            .map(|m| [per_acc[m] - hold[m], per_speed[m] - hold[m], hold[m], -torque[m], torque[m]])
3259            .collect();
3260        // The speeds 1 and 2 along the path: the tool at v p' and p'' v^2 (and the same twice over, four times the second).
3261        let (twice, four): (Vec<f64>, Vec<f64>) =
3262            (d1.iter().map(|x| 2.0 * x).collect(), d2.iter().map(|x| 4.0 * x).collect());
3263        // Per row after the motors' rows, the part b v of its value that grows with the speed alone (see `Place::speed`).
3264        let mut speed = vec![0.0; motors];
3265        if lowest.is_finite() || highest.is_finite() {
3266            // The tension at the speed too (a delta's carriages accelerate with the speed): c a + b v + d v^2 as the
3267            // checks below, read at rest, at the acceleration 1 and at the speeds 1 and 2 along the path.
3268            let tensions = |vel: &[f64], acc: &[f64]| {
3269                let mut out = Vec::new();
3270                machine.rigid_tensions_moving(pose, vel, acc, &mut out);
3271                out
3272            };
3273            let (still, per_acc, once, fast) =
3274                (tensions(&zero, &zero), tensions(&zero, d1), tensions(d1, d2), tensions(&twice, &four));
3275            for k in 0..still.len() {
3276                let room = (1.0 - KEPT_BACK) * share * (highest - still[k]).min(still[k] - lowest);
3277                if !(room > 0.0) {
3278                    return Err(CommandError { key: "error-path-tension" });
3279                }
3280                let d = 0.5 * (fast[k] - 2.0 * once[k] + still[k]);
3281                // The same room on both sides: the belt's vibration after a change of tension swings as far the
3282                // other way (see `plan_time_optimal`).
3283                rows.push([per_acc[k] - still[k], d, 0.0, -room, room]);
3284                speed.push(once[k] - still[k] - d);
3285            }
3286        }
3287        // Per motor its row with eta of the load's torque (`Place::low`): the same as its row but behind a lossy gearbox.
3288        let mut low: Vec<[f64; 3]> = rows[..motors].iter().map(|[c, d, e, ..]| [*c, *d, *e]).collect();
3289        if (0..motors).any(|m| gearbox(m).is_some()) {
3290            // The output torque ratio (T - I alpha), alpha = theta' a + theta'' v^2 the input's angular acceleration: the
3291            // torque the load takes, whatever the gearbox loses. What it loses the motor gives on top: the rigid model's
3292            // motor torque is I alpha + (T - I alpha), and with the efficiency eta the motor gives I alpha + (T - I alpha)
3293            // / eta while it drives the load, I alpha + (T - I alpha) eta while the load drives it (`Place::against` says
3294            // which form holds against which bound): a motor that brakes the load gives eta of what the load's
3295            // deceleration asks, not 1 / eta of it.
3296            let (far, here, back) = (angles(BEND_STEP), angles(0.0), angles(-BEND_STEP));
3297            for m in (0..motors).filter_map(|m| Some((m, gearbox(m)?))).collect::<Vec<_>>() {
3298                let (m, [ratio, inertia, rated, efficiency]) = m;
3299                let turn = (ahead[m] - behind[m]) / (2.0 * TURN_STEP);
3300                let bend = (far[m] - 2.0 * here[m] + back[m]) / (BEND_STEP * BEND_STEP);
3301                let [c, d, e, ..] = rows[m];
3302                let (c_load, d_load) = (c - inertia * turn, d - inertia * bend);
3303                (rows[m][0], rows[m][1], rows[m][2]) =
3304                    (inertia * turn + c_load / efficiency, inertia * bend + d_load / efficiency, e / efficiency);
3305                low[m] = [inertia * turn + c_load * efficiency, inertia * bend + d_load * efficiency, e * efficiency];
3306                // Holding while it starts to turn: the load's torque drives the motor where it turns the other way.
3307                if (if e * turn >= 0.0 { e / efficiency } else { e * efficiency }).abs() >= torque[m] {
3308                    return Err(CommandError { key: "error-path-torque" });
3309                }
3310                if rated.is_finite() {
3311                    let room = (1.0 - KEPT_BACK) * reserve * rated;
3312                    if (ratio * e).abs() >= room {
3313                        return Err(CommandError { key: "error-path-torque" });
3314                    }
3315                    rows.push([ratio * c_load, ratio * d_load, ratio * e, -room, room]);
3316                }
3317            }
3318        }
3319        if limits.guide.is_finite() {
3320            // Each guide's load is its load at rest plus the size of a part linear in the tool's acceleration, within
3321            // `reserve` of the rating, as the motors' torques are within `reserve` of theirs: the rest is for what the
3322            // rigid model leaves out (the frame's and the belt's vibration, the friction the rows do not see).
3323            let loads = |acc: &[f64]| {
3324                let mut out = Vec::new();
3325                machine.rigid_guide_loads(pose, acc, &mut out);
3326                out
3327            };
3328            let (still, per_acc, per_speed) = (loads(&zero), loads(d1), loads(d2));
3329            for k in 0..still.len() {
3330                let room = (1.0 - KEPT_BACK) * reserve * limits.guide - still[k][0];
3331                if !(room > 0.0) {
3332                    return Err(CommandError { key: "error-path-guide" });
3333                }
3334                rows.push([per_acc[k][1] - still[k][1], per_speed[k][1] - still[k][1], 0.0, -room, room]);
3335            }
3336        }
3337        // The machine's own parts (`Machine::rigid_checks`), each within its check's limit: a value read at rest, at the
3338        // acceleration 1 and at the speeds 1 and 2 along the path gives c a + b v + d v^2 + e. One that grows with the
3339        // acceleration keeps `reserve` of its limit, as the torques do; a speed alone, the margin's share less
3340        // `speed_kept`; a limit of the plan itself, the margin's share.
3341        speed.resize(rows.len(), 0.0);
3342        if !checks.is_empty() {
3343            let values = |vel: &[f64], acc: &[f64]| {
3344                let mut out = Vec::new();
3345                machine.rigid_checks(pose, vel, acc, &mut out);
3346                out
3347            };
3348            let (still, per_acc, once, fast) =
3349                (values(&zero, &zero), values(&zero, d1), values(d1, d2), values(&twice, &four));
3350            for (k, check) in checks.iter().enumerate().take(still.len()) {
3351                let e = still[k];
3352                if !e.is_finite() {
3353                    continue;
3354                }
3355                let (c, d) = (per_acc[k] - e, 0.5 * (fast[k] - 2.0 * once[k] + e));
3356                // A limit of the plan itself (`plan.` signals: the flange's spin) is judged on the planned motion, which the
3357                // rigid model gives exactly: the margin's share, no reserve for what the model leaves out. Less, where it
3358                // grows with the acceleration, what the controller's cubics between the plan's points add above the most
3359                // acceleration of the motion they pass through: where a ramp of jerk J ends in a plateau, the C2 spline
3360                // overshoots it by up to 0.0850 J h (h the cycle), the Hermite cubic by 0.138 J h with the five-point
3361                // slopes and 2/3 J h with the neighbours' (which it takes next to the trajectory's ends), worked out over
3362                // every phase of the points against the ramp's end; at a peak of acceleration less. The
3363                // axes' jerk is the ramps' along p' and the bends' (each axis's limit less the ramps' share, where the
3364                // piece bends that axis).
3365                let plan = check.signal.starts_with("plan.");
3366                let share = if plan {
3367                    limits.margin
3368                } else if c != 0.0 {
3369                    reserve
3370                } else {
3371                    limits.margin * (1.0 - kept)
3372                };
3373                let cubics = if plan && c != 0.0 {
3374                    let bent: f64 = (0..axes.len())
3375                        .filter(|&i| d2[i] != 0.0 || d3[i] != 0.0)
3376                        .map(|i| {
3377                            let unit: Vec<f64> = (0..axes.len()).map(|k| if k == i { 1.0 } else { 0.0 }).collect();
3378                            (values(&zero, &unit)[k] - e).abs() * (axes[i].max_jerk - jerk * d1[i].abs()).max(0.0)
3379                        })
3380                        .sum();
3381                    let overshoot = if limits.hermite { 2.0 / 3.0 } else { 0.0851 };
3382                    overshoot * cycle * (c.abs() * jerk + bent)
3383                } else {
3384                    0.0
3385                };
3386                let room = (1.0 - KEPT_BACK) * share * check.limit - cubics;
3387                if !(e.abs() < room) {
3388                    return Err(CommandError { key: "error-path-rating" });
3389                }
3390                rows.push([c, d, e, -room, room]);
3391                speed.push(once[k] - e - d);
3392            }
3393        }
3394        let bends: Vec<[f64; 3]> = axes
3395            .iter()
3396            .enumerate()
3397            .map(|(i, a)| [3.0 * d2[i].abs(), d3[i].abs(), a.max_jerk - jerk * d1[i].abs()])
3398            .collect();
3399        // The highest speed squared: each motor at its maximum speed, each row and bend without acceleration; the rows
3400        // of fixed bounds and the bends directly, then the motors' rows against their curves, which do not widen with
3401        // the speed, by halving.
3402        let turn: Vec<f64> = (0..motors).map(|m| (ahead[m] - behind[m]) / (2.0 * TURN_STEP)).collect();
3403        let mut x =
3404            (0..motors).map(|m| (scale * curves[m].max_speed() / turn[m].abs()).powi(2)).fold(f64::INFINITY, f64::min);
3405        for [_, d, e, low, high] in rows[motors..].iter().filter(|r| r[1] != 0.0) {
3406            x = x.min(if *d > 0.0 { (high - e) / d } else { (e - low) / -d });
3407        }
3408        for [_, p3, room] in bends.iter().filter(|b| b[1] > 0.0) {
3409            x = x.min((room / p3).max(0.0).powf(2.0 / 3.0));
3410        }
3411        let (mut plain, mut rise) = (Vec::new(), Vec::new());
3412        machine.rigid_friction(pose, d1, &mut plain);
3413        machine.rigid_friction_rise(pose, d1, &mut rise);
3414        // Behind a lossy gearbox the motor gives the friction's torque over the efficiency (as the load's, above). Friction
3415        // does help a motor that brakes, but not at a standstill, and the bounds hold at every speed up to v (`Place::bounds`).
3416        let guide: Vec<Friction> = plain
3417            .iter()
3418            .enumerate()
3419            .map(|(m, [c, b])| {
3420                let over = gearbox(m).map_or(1.0, |[.., efficiency]| 1.0 / efficiency);
3421                let rises = rise.get(m).map_or(Vec::new(), |r| r.iter().map(|[l, s]| [l * over, *s]).collect());
3422                Friction::new(c * over, b * over, rises)
3423            })
3424            .collect();
3425        let mut place = Place { rows, low, turn, curves: curves.clone(), guide, speed, bends, top: x.sqrt(), scale };
3426        // A motor that turns here and has to hold the tool against more than its curve less its friction leaves no room.
3427        if (0..motors).any(|m| place.turn[m] != 0.0 && !place.holds(m, 0.0)) {
3428            return Err(CommandError { key: "error-path-torque" });
3429        }
3430        // The motors' rows and the rows with a part that grows with the speed (whose top the formula above overestimates).
3431        let holds = |place: &Place, v: f64| {
3432            (0..place.rows.len()).filter(|&i| i < motors || place.speed[i] != 0.0).all(|i| place.holds(i, v))
3433        };
3434        if place.top.is_finite() && !holds(&place, place.top) {
3435            let (mut slow, mut fast) = (0.0, place.top);
3436            for _ in 0..60 {
3437                let v = 0.5 * (slow + fast);
3438                if holds(&place, v) { slow = v } else { fast = v }
3439            }
3440            place.top = slow;
3441        }
3442        places.push(place);
3443    }
3444    piece_limits_of(places, spacing, jerk)
3445}
3446
3447/// A piece's `PieceLimits` from its places, `spacing` apart, and the jerk along the path its ramps may use.
3448fn piece_limits_of(places: Vec<Place>, spacing: f64, jerk: f64) -> Result<PieceLimits, CommandError> {
3449    let lowest = places.iter().map(|p| p.top).fold(f64::INFINITY, f64::min);
3450    // A piece that turns no motor has no speed limit: refused as the per-piece limits refuse it.
3451    if !(lowest.is_finite() && lowest > 0.0 && jerk.is_finite() && jerk > 0.0) {
3452        return Err(CommandError { key: "error-path-torque" });
3453    }
3454    let highest = places.iter().map(|p| p.top).filter(|t| t.is_finite()).fold(lowest, f64::max);
3455    let forward = smoothed(&places, spacing, jerk, highest);
3456    let backward: Vec<f64> = forward.iter().rev().copied().collect();
3457    let level = forward.iter().fold(0.0, |a: f64, b| a.max(*b)).sqrt() / LEVELS as f64;
3458    let tables = |curve: &[f64], sign: f64, backward: bool| -> Vec<Vec<f64>> {
3459        (1..=LEVELS).map(|l| ceiling(&places, curve, spacing, jerk, sign, backward, l as f64 * level)).collect()
3460    };
3461    let most = [
3462        [tables(&forward, 1.0, false), tables(&forward, -1.0, false)],
3463        [tables(&backward, -1.0, true), tables(&backward, 1.0, true)],
3464    ];
3465    let lowest_ahead = [lowest_ahead(&forward), lowest_ahead(&backward)];
3466    Ok(PieceLimits { places, spacing, jerk, lowest, curve: [forward, backward], lowest_ahead, level, most })
3467}
3468
3469/// A table of `ceiling` at the distance `s`, between its places by straight lines.
3470fn ceiling_at(most: &[f64], spacing: f64, s: f64) -> f64 {
3471    let x = (s / spacing).clamp(0.0, (most.len() - 1) as f64);
3472    let k = (x as usize).min(most.len() - 2);
3473    most[k] + (x - k as f64) * (most[k + 1] - most[k])
3474}
3475
3476/// The speed curve of a run (`PieceLimits::curve`) at the distance `s`: its speed, its acceleration v dv/ds (straight
3477/// between the middles of the places' gaps) and its jerk, v times the change of that acceleration per distance.
3478fn along_curve(curve: &[f64], spacing: f64, s: f64) -> [f64; 3] {
3479    let n = curve.len();
3480    let x = (s / spacing).clamp(0.0, (n - 1) as f64);
3481    let k = (x as usize).min(n - 2);
3482    let speed = (curve[k] + (x - k as f64) * (curve[k + 1] - curve[k])).max(0.0).sqrt();
3483    let acc = |i: usize| (curve[i + 1] - curve[i]) / (2.0 * spacing);
3484    let m = (x - 0.5).clamp(0.0, (n - 2) as f64);
3485    let i = (m as usize).min(n - 3);
3486    let (a0, a1) = (acc(i), acc(i + 1));
3487    [speed, a0 + (m - i as f64) * (a1 - a0), speed * (a1 - a0) / spacing]
3488}
3489
3490/// A jerk-limited run along a piece from the speed `from`, with no acceleration, at the distance `start` from where it
3491/// starts (the piece's start, or its end with `backward`, by `PieceLimits::curve` and `most` [1]), until the speed
3492/// reaches `top` with no acceleration, no further than `end`. Its knots (time, distance, speed, acceleration) with the
3493/// jerk constant between them, at steps of `step`. `None` where it does not reach top by `end`, or stops. With no top
3494/// (infinite) the run follows the curve as far as `end` and its knots end there; `None` where it gets above the curve
3495/// (by more than `CURVE_OVERSHOOT` of it): it started faster than the curve lets it slow down (`curve_join`).
3496///
3497/// Each step the acceleration rises by as much as the jerk allows, but no more than three things allow: the ceiling of
3498/// acceleration ahead; that it can still fall to zero at the jerk limit by the time the speed reaches top; and that it
3499/// can still come down onto the speed curve the run follows, at the jerk left beside the curve's own (at least
3500/// `1 - CURVE_JERK` of it), by the time the speed reaches the curve. The last is left out while the acceleration can
3501/// fall to zero at the jerk limit with the speed below the curve all the way, and the curve keeps room there for its own
3502/// slowing down. It falls at most to the ceiling of slowing down. So the run rises along the ceiling, comes onto the
3503/// speed curve and follows it, up and down, and on to top; and it is the same run, whatever the top, until it brakes
3504/// for it, so that a higher top that fits is the quicker.
3505fn follow(
3506    limits: &PieceLimits,
3507    from: f64,
3508    top: f64,
3509    [start, end]: [f64; 2],
3510    backward: bool,
3511    step: f64,
3512) -> Option<Vec<[f64; 4]>> {
3513    let (curve, [up, down]) = (&limits.curve[backward as usize], &limits.most[backward as usize]);
3514    let (jerk, spacing) = (limits.jerk, limits.spacing);
3515    let rise = jerk * step;
3516    let mut knots = vec![[0.0, start, from, 0.0]];
3517    while knots.len() < RUN_STEPS {
3518        let [t, s, v, a] = knots[knots.len() - 1];
3519        if v >= top {
3520            return Some(knots);
3521        }
3522        // The largest change du of the acceleration in this step after which it can still fall to zero at the jerk
3523        // limit by the time the speed reaches top: (a + du)^2 <= 2 jerk (top - v - a step - du step / 2).
3524        let b = 2.0 * a + rise;
3525        let disc = b * b - 4.0 * (a * a + 2.0 * jerk * (v + a * step - top));
3526        let brake = if disc >= 0.0 { 0.5 * (disc.sqrt() - b) } else { f64::NEG_INFINITY };
3527        if brake <= -a && a > 0.0 {
3528            // Within this step the acceleration has to reach zero: at the constant jerk -a / h that takes it there
3529            // over the time h in which the speed reaches top, h = 2 (top - v) / a. On the brake curve that is the
3530            // jerk limit; below it, less.
3531            let h = (2.0 * (top - v) / a).max(0.0);
3532            let s = s + v * h + a * h * h / 3.0;
3533            knots.push([t + h, s, top, 0.0]);
3534            return (s <= end).then_some(knots);
3535        }
3536        let ahead = s + v * step + (a / 2.0 + rise / 6.0) * step * step;
3537        // Onto the curve: with y the acceleration above the curve's after this step and g the gap to the curve's speed
3538        // then, at the jerk k beside the curve's own the gap closes as y falls to zero where y^2 <= 2 k g, and
3539        // g = gap - y step / 2, gap = curve - v - (a + curve's a) step / 2 at an acceleration rising evenly to it.
3540        let [speed, acc, own] = along_curve(curve, spacing, ahead);
3541        let k = (jerk - own.abs()).max((1.0 - CURVE_JERK) * jerk);
3542        let gap = speed - v - 0.5 * (a + acc) * step;
3543        let y =
3544            if gap >= 0.0 { 0.5 * ((k * k * step * step + 8.0 * k * gap).sqrt() - k * step) } else { 2.0 * gap / step };
3545        // The ceilings for the most speed the run can reach if its acceleration falls to zero from after this step.
3546        let high = (a + rise).max(0.0);
3547        let level = limits.level_of(v + (a + rise / 2.0) * step + high * high / (2.0 * jerk));
3548        let floor = (-ceiling_at(&down[level], spacing, ahead) - a).clamp(-rise, rise);
3549        let du = brake.min(ceiling_at(&up[level], spacing, ahead) - a).min(rise).max(floor);
3550        // Below the curve all the way if the acceleration falls to zero from after this step: the speed rises to
3551        // `reach` over the time a / jerk; there the curve's own slowing down has to have room (y >= 0 at no gap).
3552        let after = a + du;
3553        let reach = v + (a + du / 2.0) * step + after.max(0.0).powi(2) / (2.0 * jerk);
3554        let there = ahead + reach * after.max(0.0) / jerk;
3555        let [end_speed, end_acc, end_own] = along_curve(curve, spacing, there);
3556        let room = (jerk - end_own.abs()).max((1.0 - CURVE_JERK) * jerk);
3557        // (To the rounding of a run that ends on the curve's speed.)
3558        let reach = reach * (1.0 - 1e-9);
3559        // Below the lowest of the curve all the rest of the way, the run never has to follow its slowing down: a curve
3560        // that falls faster than the jerk can follow but stays above the run (a turn about z alone, whose motors' speed
3561        // limit falls by a fifth over the turn) held the run at rest and refused the piece as a crawl.
3562        let below_rest = reach * reach <= limits.lowest_between(backward, ahead, (curve.len() - 1) as f64 * spacing);
3563        let clear = reach * reach <= limits.lowest_between(backward, ahead, there)
3564            && (below_rest || end_acc.min(0.0).powi(2) <= 2.0 * room * (end_speed - reach).max(0.0));
3565        let du = if clear { du } else { du.min(y + acc - a).max(floor) };
3566        let next = [t + step, s + v * step + (a / 2.0 + du / 6.0) * step * step, v + (a + du / 2.0) * step, a + du];
3567        if top.is_infinite() {
3568            if next[1] > end {
3569                return Some(knots);
3570            }
3571            if next[2] > (1.0 + CURVE_OVERSHOOT) * along_curve(curve, spacing, next[1])[0] {
3572                return None;
3573            }
3574        }
3575        // Past the end, or held at rest by a ceiling of zero.
3576        if next[1] > end || (next[2] <= 0.0 && next[3] <= 0.0) {
3577            return None;
3578        }
3579        knots.push(next);
3580    }
3581    None
3582}
3583
3584/// The timing of one piece of the length `length` from the speed `v0` at its start to `v1` at its end, with `top` the
3585/// highest speed on it: steady for `hold` at each end that is not at rest, a run from v0 that follows the speed curve
3586/// up to top, cruise at top, and a run down to v1 (planned from the end backwards the same way). As knots (time from
3587/// the start, distance, speed, acceleration) with the jerk constant between them. `None` where that does not fit into
3588/// the piece or the cruise passes a place faster than it holds; `slack` is how much more than the piece's length it
3589/// may take, for rounding. Where the runs would meet while the speed curve still rises or falls, `curve_join` joins them
3590/// on the curve instead, with no cruise.
3591fn piece_timing(
3592    limits: &PieceLimits,
3593    length: f64,
3594    [v0, v1, top]: [f64; 3],
3595    hold: f64,
3596    step: f64,
3597    slack: f64,
3598) -> Option<Vec<[f64; 4]>> {
3599    let (start, end) = (hold * v0, length + slack - hold * v1);
3600    let rise = follow(limits, v0, top, [start, end], false, step)?;
3601    let reached = rise[rise.len() - 1][1];
3602    let fall = follow(limits, v1, top, [hold * v1, length + slack - reached], true, step)?;
3603    let (braking, took) = ((length - fall[fall.len() - 1][1]).max(reached), fall[fall.len() - 1][0]);
3604    // The cruise between the climbs holds at top at every place it passes.
3605    let (first, last) = (
3606        (reached / limits.spacing).floor() as usize,
3607        ((braking / limits.spacing).ceil() as usize).min(limits.places.len() - 1),
3608    );
3609    // (To the rounding of the places' tops, read by differences: a top on the curve is on the places' tops.)
3610    if limits.places[first.min(last)..=last].iter().any(|p| p.top < top * (1.0 - 1e-8)) {
3611        return None;
3612    }
3613    let mut knots = vec![[0.0, 0.0, v0, 0.0]];
3614    if v0 > 0.0 {
3615        knots.push([hold, start, v0, 0.0]);
3616    }
3617    let t0 = knots[knots.len() - 1][0];
3618    knots.extend(rise[1..].iter().map(|[t, s, v, a]| [t0 + t, *s, *v, *a]));
3619    let [t, s, ..] = knots[knots.len() - 1];
3620    if braking > s {
3621        knots.push([t + (braking - s) / top, braking, top, 0.0]);
3622    }
3623    let t1 = knots[knots.len() - 1][0];
3624    knots.extend(fall.iter().rev().skip(1).map(|[t, s, v, a]| [t1 + took - t, length - s, *v, -a]));
3625    if v1 > 0.0 {
3626        let t = knots[knots.len() - 1][0];
3627        knots.push([t + hold, length, v1, 0.0]);
3628    }
3629    knots.last_mut().unwrap()[1] = length;
3630    Some(knots)
3631}
3632
3633/// The state [distance, speed, acceleration] of a run (`follow`'s knots, the jerk constant between them) at the time `t`
3634/// from its start, on its cubic between the knots around `t`; at its last knot beyond that.
3635fn run_at(knots: &[[f64; 4]], t: f64) -> [f64; 3] {
3636    let k = knots.partition_point(|knot| knot[0] <= t).clamp(1, knots.len().max(2) - 1);
3637    let Some(&[t1, .., a1]) = knots.get(k) else {
3638        let [_, s, v, a] = knots[knots.len() - 1];
3639        return [s, v, a];
3640    };
3641    let [t0, s, v, a] = knots[k - 1];
3642    let h = t1 - t0;
3643    let jerk = if h > 0.0 { (a1 - a) / h } else { 0.0 };
3644    let tau = (t - t0).clamp(0.0, h.max(0.0));
3645    [s + v * tau + a * tau * tau / 2.0 + jerk * tau.powi(3) / 6.0, v + a * tau + jerk * tau * tau / 2.0, a + jerk * tau]
3646}
3647
3648/// The two runs of a piece (`follow`, from `v0` at its start and from `v1` at its end, each after its steady cycles),
3649/// with no top: each follows the speed curve as far as the piece goes, and the plan takes the run from the start up to
3650/// where it meets the run from the end, and that one from there. Where they meet both are on the speed curve, at its
3651/// speed and its acceleration, so the plan switches from one to the other directly, without the cruise at no
3652/// acceleration that `piece_timing` joins them on: the plan when the runs meet while the curve rises or falls, and the
3653/// only one where the piece has to slow down below both its end speeds somewhere. Knots as `piece_timing`'s; `None`
3654/// where a run starts faster than the curve lets it slow down, or the runs meet off the curve (at a peak of speed,
3655/// where `piece_timing` joins them; with a jerk so high that a few steps' worth of it spans any step of acceleration,
3656/// a peak passes as on the curve, which holds as the switch keeps the place and the speed).
3657fn curve_join(limits: &PieceLimits, length: f64, [v0, v1]: [f64; 2], hold: f64, step: f64) -> Option<Vec<[f64; 4]>> {
3658    let rise = follow(limits, v0, f64::INFINITY, [hold * v0, length - hold * v1], false, step)?;
3659    let fall = follow(limits, v1, f64::INFINITY, [hold * v1, length - hold * v0], true, step)?;
3660    // A fall of its start knot alone has no span to meet the rise on: the cruise join (`piece_timing`) times the piece.
3661    if fall.len() < 2 {
3662        return None;
3663    }
3664    // The fall's state at the distance `s` from the start, on its own cubic between its knots (its time there found by
3665    // halving, the distance rising with it): its time, speed and acceleration forwards (its own acceleration the other
3666    // way round).
3667    let fall_at = |s: f64| {
3668        let back = length - s;
3669        let k = fall.partition_point(|knot| knot[1] <= back).clamp(1, fall.len() - 1);
3670        let (mut early, mut late) = (fall[k - 1][0], fall[k][0]);
3671        for _ in 0..60 {
3672            let mid = 0.5 * (early + late);
3673            if run_at(&fall, mid)[0] < back { early = mid } else { late = mid }
3674        }
3675        let t = 0.5 * (early + late);
3676        let [_, v, a] = run_at(&fall, t);
3677        [t, v, -a]
3678    };
3679    // The rise meets the fall where it is first as fast as the fall at the same place: within the rise's step up to its
3680    // first knot that is (`meet`), found by halving on the rise's own cubic. The plan switches there from the one run to
3681    // the other at the same place and speed; only the acceleration steps. (Switching at the knot itself, with the cubic
3682    // from the rise's acceleration to the fall's next knot in between, left the speed short of the fall's by the step of
3683    // the acceleration times half that span: 1.05e-3 m/s where a rise at 2.02 m/s^2 met a fall braking at 5.14 m/s^2 on
3684    // an axis behind a lossy gearbox, which the profile cycle's differences read as 0.46 % more braking torque
3685    // than the plan held.) Both are on the curve if their accelerations agree to the jerk of a few steps.
3686    let reach = length - fall[fall.len() - 1][1];
3687    let ahead = |t: f64| {
3688        let [s, v, _] = run_at(&rise, t);
3689        s >= reach && v >= fall_at(s)[1]
3690    };
3691    let meet = rise.iter().position(|&[_, s, v, _]| s >= reach && v >= fall_at(s)[1])?;
3692    let t_meet = if meet == 0 {
3693        rise[0][0]
3694    } else {
3695        let (mut early, mut late) = (rise[meet - 1][0], rise[meet][0]);
3696        for _ in 0..60 {
3697            let mid = 0.5 * (early + late);
3698            if ahead(mid) { late = mid } else { early = mid }
3699        }
3700        late
3701    };
3702    let [s_meet, v_meet, a_meet] = run_at(&rise, t_meet);
3703    let [took, v_fall, a_fall] = fall_at(s_meet);
3704    if (v_meet - v_fall).abs() > KEPT_BACK * v_meet.max(1e-9) || (a_meet - a_fall).abs() > 4.0 * limits.jerk * step {
3705        return None;
3706    }
3707    // The switch keeps the jerk limit over the profile cycle up to it: from the rise's acceleration a cycle before the meet
3708    // to the fall's at its first knot after it. (A rise still ramping at the full jerk met a fall a cycle's jerk further
3709    // on, 4 steps' worth, and the plan stepped its acceleration on the same way: 1.23 times the jerk over that cycle.)
3710    let after = fall.iter().rev().find(|knot| knot[1] < length - s_meet);
3711    let [t_back, _, _, a_back] = rise[meet.saturating_sub(STEPS_PER_CYCLE as usize)];
3712    if after.is_some_and(|&[t, _, _, a]| (a + a_back).abs() > limits.jerk * (t_meet - t_back + took - t) * (1.0 + 1e-9))
3713    {
3714        return None;
3715    }
3716    let mut knots = vec![[0.0, 0.0, v0, 0.0]];
3717    if v0 > 0.0 {
3718        knots.push([hold, hold * v0, v0, 0.0]);
3719    }
3720    let t0 = knots[knots.len() - 1][0];
3721    knots.extend(rise[1..meet.max(1)].iter().map(|[t, s, v, a]| [t0 + t, *s, *v, *a]));
3722    // The rise's state where they meet, then the fall's at the same time and place.
3723    if meet > 0 {
3724        knots.push([t0 + t_meet, s_meet, v_meet, a_meet]);
3725    }
3726    knots.push([t0 + t_meet, s_meet, v_fall, a_fall]);
3727    let t1 = t0 + t_meet + took;
3728    knots.extend(
3729        fall.iter().rev().filter(|knot| knot[1] < length - s_meet).map(|[t, s, v, a]| [t1 - t, length - s, *v, -a]),
3730    );
3731    if v1 > 0.0 {
3732        let t = knots[knots.len() - 1][0];
3733        knots.push([t + hold, length, v1, 0.0]);
3734    }
3735    knots.last_mut().unwrap()[1] = length;
3736    Some(knots)
3737}
3738
3739/// The timing of `plan_time_optimal`: the look-ahead of `timed` over the junction speeds (`junction_speeds`), with each
3740/// piece timed point by point under its `PieceLimits`: by `piece_timing` at the highest top that fits, or by
3741/// `curve_join`, whichever is the quicker.
3742fn timed_by_motors(
3743    axes: &[AxisInfo],
3744    geo: &[Geo],
3745    limits: &[PieceLimits],
3746    cycle: f64,
3747) -> Result<Vec<(f64, Vec<f64>)>, CommandError> {
3748    let n = geo.len();
3749    let speed = junction_speeds(axes, geo, limits, cycle, true);
3750    let mut knots = Vec::new();
3751    for i in 0..n {
3752        knots.push(piece_knots(&limits[i], geo[i].length(), [speed[i], speed[i + 1]], cycle, true)?);
3753    }
3754
3755    let duration = |i: usize| knots[i][knots[i].len() - 1][0];
3756    let total: f64 = (0..n).map(duration).sum();
3757    // A crawl near a singularity, or where the motors' limits slow the path to one, would ask for a pose per cycle
3758    // without bound and fill the memory: refused beyond `PLAN_LONGEST`, and beyond `PLAN_POINTS_MOST` poses where a
3759    // cycle below 0.1 ms makes that the tighter bound.
3760    if !(total <= PLAN_LONGEST && total / cycle <= PLAN_POINTS_MOST) {
3761        return Err(CommandError { key: "error-path-singular" });
3762    }
3763    let mut points = Vec::new();
3764    for k in 0..=(total / cycle - 1e-9).ceil() as usize {
3765        let (mut i, mut t) = (0, k as f64 * cycle);
3766        while i + 1 < n && t >= duration(i) {
3767            t -= duration(i);
3768            i += 1;
3769        }
3770        let piece = &knots[i];
3771        let next = piece.partition_point(|knot| knot[0] <= t);
3772        let s = if next >= piece.len() {
3773            piece[piece.len() - 1][1]
3774        } else {
3775            let ([t0, s, v, a], [t1, .., a1]) = (piece[next - 1], piece[next]);
3776            let (h, tau) = (t1 - t0, t - t0);
3777            let jerk = if h > 0.0 { (a1 - a) / h } else { 0.0 };
3778            s + v * tau + a * tau * tau / 2.0 + jerk * tau.powi(3) / 6.0
3779        };
3780        points.push((k as f64 * cycle, within(axes, geo[i].at(s.clamp(0.0, geo[i].length()))[0].clone())));
3781    }
3782    Ok(points)
3783}
3784
3785#[cfg(test)]
3786mod tests {
3787    use super::*;
3788
3789    fn axes() -> [AxisInfo; 2] {
3790        let axis = |max_vel: f64, max_acc: f64| AxisInfo {
3791            id: "",
3792            key: "",
3793            unit: "m",
3794            min: 0.0,
3795            max: 1.0,
3796            max_vel,
3797            max_acc,
3798            max_jerk: 100.0,
3799        };
3800        [axis(0.8, 8.0), axis(0.4, 6.0)]
3801    }
3802
3803    fn axes3() -> [AxisInfo; 3] {
3804        let axis = |min: f64, max: f64| AxisInfo {
3805            id: "",
3806            key: "",
3807            unit: "m",
3808            min,
3809            max,
3810            max_vel: 3.0,
3811            max_acc: 50.0,
3812            max_jerk: 2500.0,
3813        };
3814        [axis(-0.6, 0.6), axis(-0.6, 0.6), axis(-1.1, -0.6)]
3815    }
3816
3817    /// On three axes: a line and a spline point have three positions, an arc its end and its centre with three each.
3818    /// A quarter circle of 0.1 m in the x-z plane, from +x to +z around its centre, is counter-clockwise seen from the
3819    /// viewer (-y, x to the right and z up, as on a two-axis machine with x and z): 0.1 pi / 2 long, through
3820    /// (0.1 cos 45, 0, 0.1 sin 45) about the centre halfway; clockwise it goes the other way round, three quarters.
3821    /// In the x-y plane, seen from +z, from +x to +y is counter-clockwise too. An arc whose start, end and centre lie on
3822    /// one line (a half turn) leaves its plane open and is laid in the x-y, else x-z, else y-z plane; where none holds
3823    /// it, it is refused. A centre with the machine's other axes too (a program's, four axes) works as one with three.
3824    #[test]
3825    fn arcs_on_three_axes_lie_in_the_plane_of_their_points() {
3826        let pieces = parse(
3827            "line,0.1,0.0,-0.8
3828arc,0.0,0.0,-0.7,0.0,0.0,-0.8,ccw
3829arc,-0.1,0.0,-0.8,0.0,0.0,-0.8,ccw",
3830        )
3831        .unwrap();
3832        assert_eq!(
3833            pieces[1],
3834            Piece::Arc { to: vec![0.0, 0.0, -0.7], centre: vec![0.0, 0.0, -0.8], clockwise: false, plane: None }
3835        );
3836        let geo = given(&[0.1, 0.0, -0.9], &pieces, ARC_SLACK).unwrap().0;
3837        assert_eq!(geo.len(), 3);
3838        let quarter = std::f64::consts::FRAC_PI_2 * 0.1;
3839        assert!((geo[1].length() - quarter).abs() < 1e-12 && (geo[2].length() - quarter).abs() < 1e-12);
3840        let half = 0.1 * std::f64::consts::FRAC_1_SQRT_2;
3841        let [mid, dir, curve] = geo[1].at(0.5 * quarter);
3842        assert!(
3843            distance(&mid, &[half, 0.0, -0.8 + half]) < 1e-12
3844                && distance(&dir, &[-std::f64::consts::FRAC_1_SQRT_2, 0.0, std::f64::consts::FRAC_1_SQRT_2]) < 1e-12
3845        );
3846        // Its curvature points at the centre, 1 / r long.
3847        assert!(
3848            distance(&curve, &[-10.0 * std::f64::consts::FRAC_1_SQRT_2, 0.0, -10.0 * std::f64::consts::FRAC_1_SQRT_2])
3849                < 1e-9
3850        );
3851        let cw = given(&[0.1, 0.0, -0.8], &parse("arc,0.0,0.0,-0.7,0.0,0.0,-0.8,cw").unwrap(), ARC_SLACK).unwrap().0;
3852        assert!((cw[0].length() - 3.0 * quarter).abs() < 1e-12 && cw[0].at(cw[0].length() / 3.0)[0][2] < -0.8);
3853        let flat = given(&[0.1, 0.0, -0.8], &parse("arc,0.0,0.1,-0.8,0.0,0.0,-0.8,ccw").unwrap(), ARC_SLACK).unwrap().0;
3854        assert!((flat[0].length() - quarter).abs() < 1e-12 && flat[0].at(0.5 * quarter)[0][1] > 0.0);
3855        // A half turn is laid in the x-y plane (the first plane that holds the start's radius): ccw from +x passes +y;
3856        // one whose radius lies in no coordinate plane stays refused.
3857        let half =
3858            given(&[0.1, 0.0, -0.8], &parse("arc,-0.1,0.0,-0.8,0.0,0.0,-0.8,ccw").unwrap(), ARC_SLACK).unwrap().0;
3859        assert!(
3860            (half[0].length() - 2.0 * quarter).abs() < 1e-12
3861                && distance(&half[0].at(quarter)[0], &[0.0, 0.1, -0.8]) < 1e-12
3862        );
3863        let tilted = parse("arc,-0.1,-0.1,-0.9,0.0,0.0,-0.8,ccw").unwrap();
3864        assert_eq!(given(&[0.1, 0.1, -0.7], &tilted, ARC_SLACK).err().unwrap().key, "error-path");
3865        // Planned within the axis limits, the path ends where it was told.
3866        let points = plan(&axes3(), &[0.1, 0.0, -0.9], &pieces, 1e-3, 0.0, ARC_SLACK).unwrap();
3867        assert!(distance(&points[points.len() - 1].1, &[-0.1, 0.0, -0.8]) < 1e-9);
3868    }
3869
3870    /// A program's arc on four axes has its centre with four positions too (the other axis at its start value): a quarter
3871    /// of 0.1 m radius is 0.1 pi / 2 long, and a half turn there is laid in the x-y plane, 0.1 pi long.
3872    #[test]
3873    fn arcs_on_four_axes_take_a_centre_with_four_positions() {
3874        let arc = |to: [f64; 4]| Piece::Arc {
3875            to: to.to_vec(),
3876            centre: vec![0.0, 0.0, -0.8, 0.0],
3877            clockwise: false,
3878            plane: None,
3879        };
3880        let start = [0.1, 0.0, -0.8, 0.0];
3881        let quarter = given(&start, &[arc([0.0, 0.1, -0.8, 0.0])], ARC_SLACK).unwrap().0;
3882        assert!((quarter[0].length() - 0.1 * std::f64::consts::FRAC_PI_2).abs() < 1e-12);
3883        let half = given(&start, &[arc([-0.1, 0.0, -0.8, 0.0])], ARC_SLACK).unwrap().0;
3884        assert!((half[0].length() - 0.1 * std::f64::consts::PI).abs() < 1e-12);
3885    }
3886
3887    /// A helix: an arc of radius R = 10 mm with a fourth axis carried along, the arc a share s = 0.45 of the distance. The
3888    /// acceleration is v^2 s^2 / R and the jerk v^3 s^3 / R^2 (not s^4), so with the limits 5 / 100 / 100 the jerk bound is
3889    /// v <= cbrt(0.4 * 100 * R^2 / s^3) = cbrt(0.04 * 1e-4 / 0.091125) = 0.35272 m/s, the acceleration's
3890    /// sqrt(0.8 * 100 * R / s^2) = 1.987 m/s.
3891    #[test]
3892    fn a_helix_keeps_its_jerk_with_the_carried_axes() {
3893        let (r, share) = (0.01_f64, 0.45_f64);
3894        let on_arc = std::f64::consts::TAU / 3.0 * r;
3895        let arc = Geo::Arc3 { centre: [0.0; 3], u: [1.0, 0.0, 0.0], w: [0.0, 1.0, 0.0], radius: r, length: on_arc };
3896        let helix =
3897            Geo::Carried { arc: Box::new(arc), from: vec![0.0], by: vec![0.1], length: on_arc / share, turn: None };
3898        let bounds: [Bounds; 3] = [
3899            vec![(vec![1.0, 0.0, 0.0, 0.0], 5.0)],
3900            vec![(vec![1.0, 0.0, 0.0, 0.0], 100.0)],
3901            vec![(vec![1.0, 0.0, 0.0, 0.0], 100.0)],
3902        ];
3903        let [v, ..] = limits(&helix, &bounds);
3904        assert!(
3905            (v - (0.4_f64 * 100.0 * r * r / share.powi(3)).cbrt()).abs() < 1e-9 && (v - 0.35272).abs() < 1e-4,
3906            "{v}"
3907        );
3908        assert!(v.powi(3) * share.powi(3) / (r * r) <= 0.4 * 100.0 * (1.0 + 1e-9));
3909    }
3910
3911    /// The deviation of a curve from the corner it replaces is read between the samples too: a line from (0.9, 0) to
3912    /// (1.0, 0.2) beside the corner (0.9, 0), (1, 0), (1, 0.2) (the last 0.1 of the first piece, the first 0.2 of the
3913    /// second) is as far from it as the nearer leg: 0.2 u from the first and 0.1 (1 - u) from the second, equal at u = 1/3,
3914    /// where the peak is 1/15 = 0.066667 (the samples at 21 / 64 and 22 / 64 give 0.065625).
3915    #[test]
3916    fn the_deviation_of_a_corner_curve_is_found_between_the_samples() {
3917        let line =
3918            |from: [f64; 2], dir: [f64; 2], length: f64| Geo::Line { dir: dir.to_vec(), from: from.to_vec(), length };
3919        let (a, b) = (line([0.0, 0.0], [1.0, 0.0], 1.0), line([1.0, 0.0], [0.0, 1.0], 1.0));
3920        let size = 0.05_f64.sqrt();
3921        let curve = line([0.9, 0.0], [0.1 / size, 0.2 / size], size);
3922        let off = off_corner(&curve, &a, 0.1, &b, 0.2);
3923        assert!((off - 1.0 / 15.0).abs() < 1e-6, "{off}");
3924    }
3925
3926    /// `deviation` reads a run with a feed per piece as without the feeds: a line into an arc (tangent), a line out of it
3927    /// (tangent) and a right-angled corner, at 10, 20, 20 and 10 mm/s, with 1 mm for the transition curves and the corner.
3928    /// Without the feeds the line-arc junction gets a curve, with them (a change of feed there) it does not, and the
3929    /// curves at the lower feed are shorter: the feeds' path deviates less, the reading is never below it, and never
3930    /// above the tolerance.
3931    #[test]
3932    fn the_deviation_without_the_feeds_bounds_that_of_a_run_with_them() {
3933        let axes = axes();
3934        let pieces = parse("line,0.1,0.0\narc,0.2,0.1,0.1,0.1,ccw\nline,0.2,0.2\nline,0.3,0.2").unwrap();
3935        let tolerance = Tolerance { path: 1e-3, corner: 1e-3 };
3936        let fed =
3937            geometry_fed(&axes, &[0.0; 2], &pieces, &[0.01, 0.02, 0.02, 0.01], tolerance, &axis_speed(&axes), 0.0)
3938                .unwrap()
3939                .1;
3940        let read = deviation(&axes, &[0.0; 2], &pieces, tolerance, 0.0).unwrap();
3941        assert!(fed <= read && read <= 1e-3 * (1.0 + 1e-9) && read > 0.0, "with the feeds {fed} m, read {read} m");
3942    }
3943
3944    /// The ramps of a piece of radius 100 m keep nearly all of the jerk: at the start (tangent along x) with the limits
3945    /// 0.8 m/s, 8 m/s^2 and 100 m/s^3 on x, p'' = 0.01 and p''' = -1e-4 along the axes, the bends use (3 * 0.01 * 0.8 * 8 +
3946    /// 1e-4 * 0.8^3) / 100 = 1.9205e-3 of x's jerk, the ramps 0.998; at a radius of 10 mm the bends use more than all and
3947    /// the ramps keep the 0.4 floor.
3948    #[test]
3949    fn a_slight_curve_gives_its_ramps_nearly_all_the_jerk() {
3950        let axes = axes();
3951        let at = |r: f64| [[vec![0.0, 0.0], vec![1.0, 0.0], vec![0.0, 1.0 / r], vec![-1.0 / (r * r), 0.0]]];
3952        let share = ramp_share(&axes, &at(100.0));
3953        assert!((share - (1.0 - 1.9205e-3)).abs() < 1e-6, "{share}");
3954        assert_eq!(ramp_share(&axes, &at(0.01)), 0.4);
3955    }
3956
3957    /// A spline on three axes passes through its via points, leaves the line before it in that line's direction, and its
3958    /// plan keeps every axis within its speed, acceleration and jerk (to the 0.1 % of differencing the planned poses).
3959    #[test]
3960    fn a_spline_on_three_axes_passes_through_its_points_within_the_limits() {
3961        let pieces = parse(
3962            "line,0.0,0.0,-0.8
3963spline,0.1,0.1,-0.75
3964spline,0.2,0.0,-0.8
3965line,0.2,0.0,-0.9",
3966        )
3967        .unwrap();
3968        let geo = given(&[0.0, 0.0, -0.9], &pieces, ARC_SLACK).unwrap().0;
3969        let ends: Vec<Vec<f64>> = geo.iter().map(|g| g.at(g.length())[0].clone()).collect();
3970        assert!(distance(&ends[1], &[0.1, 0.1, -0.75]) < 1e-9 && distance(&ends[2], &[0.2, 0.0, -0.8]) < 1e-9);
3971        // Out of the vertical line upwards, into the last line downwards: no corner at either junction.
3972        assert!(
3973            distance(&geo[1].at(0.0)[1], &[0.0, 0.0, 1.0]) < 1e-9
3974                && distance(&geo[2].at(geo[2].length())[1], &[0.0, 0.0, -1.0]) < 1e-9
3975        );
3976        let (axes, cycle) = (axes3(), 1e-3);
3977        let points = plan(&axes, &[0.0, 0.0, -0.9], &pieces, cycle, 0.0, ARC_SLACK).unwrap();
3978        for w in points.windows(4) {
3979            for (i, axis) in axes.iter().enumerate() {
3980                let p = [w[0].1[i], w[1].1[i], w[2].1[i], w[3].1[i]];
3981                assert!(
3982                    ((p[1] - p[0]) / cycle).abs() <= 1.001 * axis.max_vel
3983                        && ((p[2] - 2.0 * p[1] + p[0]) / cycle.powi(2)).abs() <= 1.001 * axis.max_acc
3984                );
3985                assert!(((p[3] - 3.0 * p[2] + 3.0 * p[1] - p[0]) / cycle.powi(3)).abs() <= 1.001 * axis.max_jerk);
3986            }
3987        }
3988        assert!(distance(&points[points.len() - 1].1, &[0.2, 0.0, -0.9]) < 1e-9);
3989        // With a tolerance its junctions with the lines are eased as on two axes, within the tolerance.
3990        let eased = deviation(&axes, &[0.0, 0.0, -0.9], &pieces, 1e-3, ARC_SLACK).unwrap();
3991        assert!(eased > 0.0 && eased <= 1e-3, "{eased} m");
3992    }
3993
3994    /// A corner between a line and an arc is rounded within the corner tolerance, no longer stopped at. The line runs
3995    /// along +x to (0.1, 0); the arc of radius 1 m around (-0.9, 0) leaves there along +y, counter-clockwise: a right
3996    /// angle. Between two lines a right angle is rounded from d = 16 tolerance / 3 before the corner to d after it, its
3997    /// deviation 3 d / 16 at the middle; the arc bends away from its tangent by d^2 / (2 R) = 1.4e-7 m over d, 0.1 % of
3998    /// the tolerance, so with 0.1 mm the curve starts 16e-4 / 3 = 0.533 mm before the corner within the 2 % the search
3999    /// leaves (`round_corner`), and its deviation is the tolerance within those 2 %. At its ends the curve has the
4000    /// pieces' curvature: none on the line, 1 / R = 1 / m on the arc (G2). Before, the corner stayed a stop.
4001    #[test]
4002    fn a_line_arc_corner_is_rounded_within_the_corner_tolerance() {
4003        let axes = axes();
4004        let pieces = parse("line,0.1,0.0\narc,0.0950041652780258,0.0998334166468282,-0.9,0.0,ccw").unwrap();
4005        let tolerance = Tolerance { path: 0.0, corner: 1e-4 };
4006        let (geo, off) = geometry(&axes, &[0.0, 0.0], &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
4007        assert_eq!(geo.len(), 3, "line, curve, arc");
4008        let d = 0.1 - geo[0].length();
4009        assert!((d / (16e-4 / 3.0) - 1.0).abs() < 0.025, "{d} m");
4010        assert!((0.97e-4..=1e-4).contains(&off), "{off} m");
4011        let size = |v: &[f64]| v.iter().map(|x| x * x).sum::<f64>().sqrt();
4012        let curve = &geo[1];
4013        assert!(size(&curve.at(0.0)[2]) < 1e-6 && (size(&curve.at(curve.length())[2]) - 1.0).abs() < 1e-3);
4014        assert!(!corner(&geo[0], &geo[1]) && !corner(&geo[1], &geo[2]));
4015        // The plan passes the junctions at speed and ends on the arc's end.
4016        let points = plan(&axes, &[0.0, 0.0], &pieces, 1e-3, tolerance, ARC_SLACK).unwrap();
4017        let at = |p: &(f64, Vec<f64>)| (p.1[0] - 0.1).abs() + p.1[1].abs();
4018        let near = points.windows(2).min_by(|a, b| at(&a[0]).total_cmp(&at(&b[0]))).unwrap();
4019        assert!(distance(&near[0].1, &near[1].1) > 1e-5, "stops at the corner");
4020        assert!(distance(&points[points.len() - 1].1, &[0.0950041652780258, 0.0998334166468282]) < 1e-9);
4021        // Without a corner tolerance it stays a corner.
4022        let (stopped, _) = geometry(&axes, &[0.0, 0.0], &pieces, 0.0, &axis_speed(&axes), ARC_SLACK).unwrap();
4023        assert!(stopped.len() == 2 && corner(&stopped[0], &stopped[1]));
4024    }
4025
4026    #[test]
4027    fn a_path_file_is_read_line_by_line() {
4028        let pieces =
4029            parse("# a corner rounded off\nline, 0.5, 0.35\n\narc,0.6,0.25,0.5,0.25,cw\nline,0.6,0.05\n").unwrap();
4030        assert_eq!(pieces.len(), 3);
4031        assert_eq!(pieces[0], Piece::Line(vec![0.5, 0.35]));
4032        assert_eq!(
4033            pieces[1],
4034            Piece::Arc { to: vec![0.6, 0.25], centre: vec![0.5, 0.25], clockwise: true, plane: None }
4035        );
4036        assert_eq!(parse("spline, 0.7,0.2").unwrap(), [Piece::Spline(vec![0.7, 0.2])]);
4037        for bad in [
4038            "circle,1,2",
4039            "line",
4040            "line,a",
4041            "arc,0.6,0.25,0.5,0.25",
4042            "arc,0.6,0.25,0.5,0.25,left",
4043            "line,inf",
4044            "spline",
4045            "spline,0.5,nan",
4046        ] {
4047            assert_eq!(parse(&format!("line,0.5\n{bad}")), Err(bad.to_string()));
4048        }
4049        // An arc whose end is not on the circle through the start, an arc on one axis and a point with the
4050        // wrong number of positions cannot be laid out.
4051        let refused = |start: &[f64], text: &str| {
4052            plan(&axes()[..start.len()], start, &parse(text).unwrap(), 1e-3, 0.0, ARC_SLACK).unwrap_err().key
4053        };
4054        assert_eq!(refused(&[0.5, 0.35], "arc,0.6,0.26,0.5,0.25,cw"), "error-path");
4055        // A start up to 0.1 mm off the circle (the setpoint of a machine at rest) is run; one a millimetre off
4056        // is not.
4057        let geo = given(&[0.0999876, 0.3500458], &parse("arc,0.3,0.35,0.2,0.35,cw").unwrap(), ARC_SLACK).unwrap().0;
4058        assert!((geo[0].length() - std::f64::consts::PI * 0.1).abs() < 1e-4, "{} m", geo[0].length());
4059        assert_eq!(refused(&[0.101, 0.35], "arc,0.3,0.35,0.2,0.35,cw"), "error-path");
4060        assert_eq!(refused(&[0.5], "arc,0.6,0.25,0.5,0.25,cw"), "error-path");
4061        assert_eq!(refused(&[0.5, 0.35], "line,0.6"), "error-path");
4062        assert_eq!(refused(&[0.5, 0.35], ""), "error-path");
4063        // A spline needs two axes too, and a point with two positions.
4064        assert_eq!(refused(&[0.5], "spline,0.6"), "error-path");
4065        assert_eq!(refused(&[0.5, 0.35], "spline,0.6,0.3,0.1"), "error-path");
4066    }
4067
4068    /// An arc with a chord below 0.1 mm ran as a full circle: "ends where it starts" was judged with the slack
4069    /// that only the machine's rest setpoint needs. Around (0.3, 0.25) with r = 0.1 m, from the top:
4070    /// (a) after a line, an arc of 0.8 mrad (chord 80 um) is 80 um long and the path stays above z = 0.3499
4071    /// (it went down to 0.15); an arc back to the line's end is still a full turn, 0.6283 m.
4072    /// (b) As the first piece an arc that ends within 1 mm of where the machine stands is refused, because a
4073    /// full turn cannot be told from a short arc there: a 130 um arc written from the start pose (0.1, 0.35)
4074    /// ran as a full turn from the rest setpoint 47 um off it. So are the full turn and an arc of 0.5 mrad; a
4075    /// first arc of 2 mm is run as that. With its start stated by a line first, each is what the file says:
4076    /// the arc of 130 um or 50 um, also from a setpoint 47 um off, and the full turn.
4077    /// (c) A later arc whose end is 90 um off its circle is refused (it ended 90 um short, unsaid); one 8 um
4078    /// off is run and the 8 um are reported, on their own and on top of what transition curves take. Four
4079    /// quarter turns around one centre, each stated 9 um further out than the one before, end 36 um off: every
4080    /// arc keeps the radius the path has, so the offsets add up, and the sum is what is reported.
4081    #[test]
4082    fn a_short_arc_is_not_a_full_turn_and_an_arc_off_its_end_is_reported() {
4083        let (axes, top) = (axes(), vec![0.3, 0.35]);
4084        let arc = |by: f64, r: f64| Piece::Arc {
4085            to: vec![0.3 + r * by.sin(), 0.25 + r * by.cos()],
4086            centre: vec![0.3, 0.25],
4087            clockwise: true,
4088            plane: None,
4089        };
4090        let lengths = |start: &[f64], pieces: &[Piece]| {
4091            given(start, pieces, ARC_SLACK).unwrap().0.iter().map(Geo::length).collect::<Vec<f64>>()
4092        };
4093        let short = [Piece::Line(top.clone()), arc(8e-4, 0.1), Piece::Line(vec![0.5, 0.35])];
4094        assert!((lengths(&[0.1, 0.35], &short)[1] - 8e-5).abs() < 1e-12, "{:?}", lengths(&[0.1, 0.35], &short));
4095        let lowest = plan(&axes, &[0.1, 0.35], &short, 1e-3, 0.0, ARC_SLACK)
4096            .unwrap()
4097            .iter()
4098            .map(|p| p.1[1])
4099            .fold(f64::INFINITY, f64::min);
4100        assert!(lowest > 0.3499, "the path goes down to z = {lowest}");
4101        assert_eq!(deviation(&axes, &[0.1, 0.35], &short, 0.0, ARC_SLACK).unwrap(), 0.0);
4102        assert!(
4103            (lengths(&[0.1, 0.35], &[Piece::Line(top.clone()), arc(0.0, 0.1)])[1] - std::f64::consts::TAU * 0.1).abs()
4104                < 1e-12
4105        );
4106
4107        let (pose, rest) = (vec![0.1, 0.35], [0.0999876, 0.3500458]);
4108        let up = |by: f64| Piece::Arc {
4109            to: vec![0.2 - 0.1 * by.cos(), 0.35 + 0.1 * by.sin()],
4110            centre: vec![0.2, 0.35],
4111            clockwise: true,
4112            plane: None,
4113        };
4114        for (start, first) in [
4115            (&rest[..], up(1.3e-3)),
4116            (&rest[..], up(0.0)),
4117            (&pose[..], up(0.0)),
4118            (&top[..], arc(5e-4, 0.1)),
4119            (&top[..], arc(9.9e-3, 0.1)),
4120        ] {
4121            assert_eq!(
4122                deviation(&axes, start, std::slice::from_ref(&first), 0.0, ARC_SLACK).unwrap_err().key,
4123                "error-path-first-arc",
4124                "{first:?} from {start:?}"
4125            );
4126        }
4127        assert!((lengths(&rest, &[up(0.02)])[0] - 2e-3).abs() < 1e-4);
4128        for (by, length) in [(1.3e-3, 1.3e-4), (0.0, std::f64::consts::TAU * 0.1)] {
4129            let stated = lengths(&rest, &[Piece::Line(pose.clone()), up(by)]);
4130            assert!(stated.len() == 2 && (stated[1] - length).abs() < 1e-7, "{stated:?}");
4131        }
4132        assert!((lengths(&top, &[Piece::Line(top.clone()), arc(5e-4, 0.1)])[0] - 5e-5).abs() < 1e-12);
4133        let sagged = lengths(&[0.300012, 0.350046], &[Piece::Line(top.clone()), arc(5e-4, 0.1)]);
4134        assert!(sagged.len() == 2 && (sagged[1] - 5e-5).abs() < 1e-12, "{sagged:?}");
4135
4136        let off_by = |by: f64| {
4137            [Piece::Line(top.clone()), arc(std::f64::consts::FRAC_PI_2, 0.1 + by), Piece::Line(vec![0.4, 0.05])]
4138        };
4139        assert_eq!(deviation(&axes, &[0.1, 0.35], &off_by(-9e-5), 0.0, ARC_SLACK).unwrap_err().key, "error-path");
4140        let reported = deviation(&axes, &[0.1, 0.35], &off_by(8e-6), 0.0, ARC_SLACK).unwrap();
4141        assert!((reported - 8e-6).abs() < 1e-12, "{reported} m reported");
4142        let spiral: Vec<Piece> = std::iter::once(Piece::Line(top.clone()))
4143            .chain((1..=4).map(|k| arc(k as f64 * std::f64::consts::FRAC_PI_2, 0.1 + 9e-6 * k as f64)))
4144            .collect();
4145        let added = deviation(&axes, &[0.1, 0.35], &spiral, 0.0, ARC_SLACK).unwrap();
4146        assert!((added - 3.6e-5).abs() < 1e-12, "{added} m reported");
4147        let blended = deviation(&axes, &[0.1, 0.35], &off_by(8e-6), 1e-4, ARC_SLACK).unwrap();
4148        assert!((blended - 1.08e-4).abs() < 1e-6, "{blended} m reported with transition curves");
4149    }
4150
4151    /// Splines: smooth curves through via points.
4152    /// (a) By hand: one spline piece between two points at rest has no direction to keep and no curvature at
4153    /// its ends, so it is the straight line between them, and u is the distance along it.
4154    /// (b) Geometry of four paths (between two lines; alone, from rest to rest; out of an arc and into an arc;
4155    /// a tight S of via points 20 mm apart): every via point is where one span hands over to the next, the
4156    /// path has no step in position or direction anywhere, none in curvature from span to span, and the curve
4157    /// leaves and meets its neighbours in their direction.
4158    /// (c) Timing by both the limits: speed, acceleration and jerk of both axes, by differences over one cycle
4159    /// as for arcs, stay within the axis limits (margin 0.1 %), from the start to the end of the path, and the
4160    /// planned poses pass every via point within half of what the tool travels in a cycle.
4161    #[test]
4162    fn a_spline_passes_through_its_via_points_within_the_axis_limits() {
4163        let (axes, cycle) = (axes(), 1e-3);
4164        let straight = plan(&axes, &[0.1, 0.1], &parse("spline,0.5,0.4").unwrap(), cycle, 0.0, ARC_SLACK).unwrap();
4165        // On the line through (0.1, 0.1) and (0.5, 0.4): 3 (x - 0.1) = 4 (z - 0.1).
4166        assert!(
4167            straight.iter().all(|(_, p)| (3.0 * (p[0] - 0.1) - 4.0 * (p[1] - 0.1)).abs() < 1e-12)
4168                && distance(&straight[straight.len() - 1].1, &[0.5, 0.4]) < 1e-12
4169        );
4170        let [Geo::Spline { travelled, .. }] =
4171            &given(&[0.1, 0.1], &parse("spline,0.5,0.4").unwrap(), ARC_SLACK).unwrap().0[..]
4172        else {
4173            panic!("one span")
4174        };
4175        assert!((travelled[SPLINE_PARTS] - 0.5).abs() < 1e-14 && (travelled[16] - 0.125).abs() < 1e-14);
4176
4177        let paths = [
4178            ([0.1, 0.35], "line,0.3,0.35\nspline,0.4,0.3\nspline,0.5,0.32\nspline,0.6,0.2\nline,0.6,0.05"),
4179            ([0.2, 0.1], "spline,0.3,0.2\nspline,0.5,0.25\nspline,0.7,0.1"),
4180            (
4181                [0.1, 0.5],
4182                "line,0.3,0.5\narc,0.4,0.4,0.3,0.4,cw\nspline,0.45,0.3\nspline,0.55,0.25\narc,0.65,0.15,0.55,0.15,cw\nline,0.65,0.05",
4183            ),
4184            (
4185                [0.3, 0.2],
4186                "line,0.4,0.2\nspline,0.42,0.21\nspline,0.44,0.19\nspline,0.46,0.21\nspline,0.48,0.2\nline,0.6,0.2",
4187            ),
4188        ];
4189        for (start, text) in paths {
4190            let pieces = parse(text).unwrap();
4191            let geo = given(&start, &pieces, ARC_SLACK).unwrap().0;
4192            let via: Vec<&Vec<f64>> =
4193                pieces.iter().filter_map(|p| if let Piece::Spline(to) = p { Some(to) } else { None }).collect();
4194            let ends: Vec<Vec<f64>> =
4195                geo.iter().filter(|g| matches!(g, Geo::Spline { .. })).map(|g| g.at(g.length())[0].clone()).collect();
4196            assert_eq!(ends.len(), via.len(), "{text}");
4197            for (end, via) in ends.iter().zip(&via) {
4198                assert!(distance(end, via) < 1e-12, "{text}: span ends at {end:?}, via point {via:?}");
4199            }
4200            for pair in geo.windows(2) {
4201                let (before, after) = (pair[0].at(pair[0].length()), pair[1].at(0.0));
4202                let steps =
4203                    [distance(&before[0], &after[0]), distance(&before[1], &after[1]), distance(&before[2], &after[2])];
4204                let both = matches!(pair, [Geo::Spline { .. }, Geo::Spline { .. }]);
4205                assert!(steps[0] < 1e-12 && steps[1] < 1e-9 && (!both || steps[2] < 1e-6), "{text}: steps {steps:?}");
4206            }
4207            // With a tolerance of 0.1 mm the spline is eased into the lines and arcs it meets (`ease`), and an arc beside
4208            // it gets its transition curve towards the line at its other end (`blend`): no step in position, direction
4209            // or curvature at any junction, every planned pose within the reported deviation of the path as given, the
4210            // reported deviation within the tolerance, the axis limits kept, the via points still passed, and faster.
4211            let (eased, reported) = geometry(&axes, &start, &pieces, 1e-4, &axis_speed(&axes), ARC_SLACK).unwrap();
4212            assert!(
4213                reported <= 1e-4 + 1e-12 && (reported > 0.0) == (eased.len() > geo.len()),
4214                "{text}: {reported} m reported, {} pieces from {}",
4215                eased.len(),
4216                geo.len()
4217            );
4218            for pair in eased.windows(2) {
4219                let (before, after) = (pair[0].at(pair[0].length()), pair[1].at(0.0));
4220                let steps =
4221                    [distance(&before[0], &after[0]), distance(&before[1], &after[1]), distance(&before[2], &after[2])];
4222                assert!(steps[0] < 1e-11 && steps[1] < 1e-9 && steps[2] < 1e-6, "{text}, eased: steps {steps:?}");
4223            }
4224            let (smooth, given_plan) = (
4225                plan(&axes, &start, &pieces, cycle, 1e-4, ARC_SLACK).unwrap(),
4226                plan(&axes, &start, &pieces, cycle, 0.0, ARC_SLACK).unwrap(),
4227            );
4228            let peak = peak_rates(&smooth, cycle);
4229            for (i, axis) in axes.iter().enumerate() {
4230                assert!(
4231                    peak[0][i] <= 1.001 * axis.max_vel
4232                        && peak[1][i] <= 1.001 * axis.max_acc
4233                        && peak[2][i] <= 1.001 * axis.max_jerk,
4234                    "{text}, eased, axis {i}: {peak:?}"
4235                );
4236            }
4237            let line = polyline(&geo);
4238            let furthest = smooth.iter().map(|p| off_line(&line, &p.1)).fold(0.0, f64::max);
4239            assert!(furthest <= reported + 1e-7, "{text}: {furthest} m off the given path, {reported} m reported");
4240            for via in &via {
4241                let nearest = smooth.iter().map(|p| distance(&p.1, via)).fold(f64::INFINITY, f64::min);
4242                assert!(nearest <= 0.5 * 0.8 * cycle * 1.01, "{text}, eased: {nearest} m past the via point {via:?}");
4243            }
4244            let (eased_time, given_time) = (smooth[smooth.len() - 1].0, given_plan[given_plan.len() - 1].0);
4245            assert!(reported == 0.0 || eased_time < given_time, "{text}: {eased_time} s eased against {given_time} s");
4246            println!("eased: {eased_time} s against {given_time} s, off by {furthest} m of {reported} m reported");
4247
4248            let points = plan(&axes, &start, &pieces, cycle, 0.0, ARC_SLACK).unwrap();
4249            let peak = peak_rates(&points, cycle);
4250            for (i, axis) in axes.iter().enumerate() {
4251                assert!(
4252                    peak[0][i] <= 1.001 * axis.max_vel
4253                        && peak[1][i] <= 1.001 * axis.max_acc
4254                        && peak[2][i] <= 1.001 * axis.max_jerk,
4255                    "{text}, axis {i}: {peak:?}"
4256                );
4257            }
4258            let last = points.len() - 1;
4259            let end = geo[geo.len() - 1].at(geo[geo.len() - 1].length())[0].clone();
4260            assert!(
4261                points[0].1 == start
4262                    && distance(&points[last].1, &end) < 1e-9
4263                    && distance(&points[last].1, &points[last - 1].1) < 1e-6,
4264                "{text}"
4265            );
4266            for via in &via {
4267                let nearest = points.iter().map(|p| distance(&p.1, via)).fold(f64::INFINITY, f64::min);
4268                assert!(nearest <= 0.5 * 0.8 * cycle * 1.01, "{text}: {nearest} m past the via point {via:?}");
4269            }
4270            println!("{} s, peak rates {peak:?}: {}", points[last].0, text.replace('\n', " | "));
4271        }
4272
4273        // A via point straight back along the line before it: the curve would have to turn on the spot.
4274        assert_eq!(
4275            plan(&axes, &[0.1, 0.35], &parse("line,0.5,0.35\nspline,0.3,0.35").unwrap(), cycle, 0.0, ARC_SLACK)
4276                .unwrap_err()
4277                .key,
4278            "error-path"
4279        );
4280        // A via point given twice counts once, and a spline of nothing but where the path stands is no piece.
4281        let twice = given(&[0.2, 0.1], &parse("spline,0.3,0.2\nspline,0.3,0.2\nspline,0.5,0.25").unwrap(), ARC_SLACK)
4282            .unwrap()
4283            .0;
4284        assert_eq!(twice.len(), 2);
4285        assert_eq!(
4286            plan(&axes, &[0.2, 0.1], &parse("spline,0.2,0.1").unwrap(), cycle, 0.0, ARC_SLACK).unwrap_err().key,
4287            "error-path"
4288        );
4289    }
4290
4291    /// Rates of the planned poses by differences over one cycle: the largest speed, acceleration and jerk
4292    /// of each axis.
4293    fn peak_rates(points: &[(f64, Vec<f64>)], cycle: f64) -> [[f64; 2]; 3] {
4294        let mut peak = [[0f64; 2]; 3];
4295        for w in points.windows(4) {
4296            for i in 0..2 {
4297                let p = [w[0].1[i], w[1].1[i], w[2].1[i], w[3].1[i]];
4298                let rates = [
4299                    (p[1] - p[0]) / cycle,
4300                    (p[2] - 2.0 * p[1] + p[0]) / cycle.powi(2),
4301                    (p[3] - 3.0 * p[2] + 3.0 * p[1] - p[0]) / cycle.powi(3),
4302                ];
4303                for (peak, rate) in peak.iter_mut().zip(rates) {
4304                    peak[i] = peak[i].max(rate.abs());
4305                }
4306            }
4307        }
4308        peak
4309    }
4310
4311    /// A path as points 0.05 mm apart along it, whose straight pieces cut a curve of 5 mm radius by 0.06 um at most.
4312    fn polyline(geo: &[Geo]) -> Vec<Vec<f64>> {
4313        let mut out = vec![geo[0].at(0.0)[0].clone()];
4314        for g in geo {
4315            let parts = (g.length() / 5e-5).ceil().max(1.0) as usize;
4316            out.extend((1..=parts).map(|k| g.at(g.length() * k as f64 / parts as f64)[0].clone()));
4317        }
4318        out
4319    }
4320
4321    /// How far a point is from a path given as `polyline`: from the nearest of its straight pieces. Any number of axes.
4322    fn off_line(line: &[Vec<f64>], p: &[f64]) -> f64 {
4323        let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(a, b)| a * b).sum::<f64>();
4324        line.windows(2)
4325            .map(|w| {
4326                let ab: Vec<f64> = w[1].iter().zip(&w[0]).map(|(b, a)| b - a).collect();
4327                let ap: Vec<f64> = p.iter().zip(&w[0]).map(|(p, a)| p - a).collect();
4328                let t = (dot(&ab, &ap) / dot(&ab, &ab).max(1e-300)).clamp(0.0, 1.0);
4329                ap.iter().zip(&ab).map(|(p, b)| (p - t * b) * (p - t * b)).sum::<f64>().sqrt()
4330            })
4331            .fold(f64::INFINITY, f64::min)
4332    }
4333
4334    /// A line, an arc that leaves it tangentially, and a line that leaves the arc tangentially.
4335    /// (a) Speed, acceleration and jerk of both axes, taken from the planned poses by differences over one
4336    /// cycle, stay within the axis limits. Margin 0.1 %, for taking differences instead of derivatives. (b) Every planned pose lies on the path. And the
4337    /// hand calculations: on the arc of radius 0.1 m the speed is at most sqrt(a r) with the smaller
4338    /// acceleration limit, 6 m/s^2, so 0.775 m/s; the planner keeps 0.8 of that limit for the centripetal
4339    /// acceleration and the axis speed limit of 0.4 m/s is lower still, so the arc runs at 0.4 m/s. Into
4340    /// and out of the arc the acceleration towards the centre steps by v^2 / r, and that step within one
4341    /// cycle may use half the jerk limit: v = sqrt(0.5 * 100 * 0.001 * 0.1) = 0.0707 m/s.
4342    #[test]
4343    fn a_planned_path_stays_within_the_axis_limits_and_on_its_pieces() {
4344        let (axes, cycle) = (axes(), 1e-3);
4345        let pieces = parse("line,0.5,0.35\narc,0.6,0.25,0.5,0.25,cw\nline,0.6,0.05").unwrap();
4346        let points = plan(&axes, &[0.1, 0.35], &pieces, cycle, 0.0, ARC_SLACK).unwrap();
4347        let peak = peak_rates(&points, cycle);
4348        for (i, axis) in axes.iter().enumerate() {
4349            assert!(
4350                peak[0][i] <= 1.001 * axis.max_vel
4351                    && peak[1][i] <= 1.001 * axis.max_acc
4352                    && peak[2][i] <= 1.001 * axis.max_jerk,
4353                "axis {i}: {peak:?}"
4354            );
4355        }
4356        // The limits are used: full speed and acceleration on the first line, most of the jerk limit.
4357        assert!(peak[0][0] > 0.999 * 0.8 && peak[1][0] > 0.99 * 8.0 && peak[2][0] > 0.95 * 100.0, "{peak:?}");
4358
4359        let on_arc = |p: &[f64]| p[0] > 0.5 + 1e-9 && p[1] > 0.25 + 1e-9;
4360        let (mut off_path, mut arc_speed, mut junction_speed) = (0f64, 0f64, f64::INFINITY);
4361        for w in points.windows(2) {
4362            let p = &w[1].1;
4363            let off = if on_arc(p) {
4364                (distance(p, &[0.5, 0.25]) - 0.1).abs()
4365            } else {
4366                (p[1] - 0.35).abs().min((p[0] - 0.6).abs())
4367            };
4368            off_path = off_path.max(off);
4369            let speed = distance(&w[0].1, p) / cycle;
4370            if on_arc(p) && on_arc(&w[0].1) {
4371                arc_speed = arc_speed.max(speed);
4372            } else if on_arc(p) != on_arc(&w[0].1) {
4373                junction_speed = junction_speed.min(speed);
4374            }
4375        }
4376        assert!(off_path < 1e-12, "{off_path} m off the path");
4377        assert!(arc_speed <= (6.0f64 * 0.1).sqrt() && (arc_speed - 0.4).abs() < 1e-3, "{arc_speed} m/s on the arc");
4378        assert!((junction_speed - 0.0707).abs() < 1e-3, "{junction_speed} m/s into the arc");
4379        // Rest to rest, from the start to the end of the path.
4380        let last = points.len() - 1;
4381        assert!(points[0].1 == [0.1, 0.35] && distance(&points[last].1, &[0.6, 0.05]) < 1e-12);
4382        assert!(distance(&points[1].1, &points[0].1) < 1e-6 && distance(&points[last].1, &points[last - 1].1) < 1e-6);
4383        println!(
4384            "duration {} s, peak rates {peak:?}, arc {arc_speed} m/s, junction {junction_speed} m/s",
4385            points[last].0
4386        );
4387    }
4388
4389    /// Transition curves on the same line, arc, line. Without them the path crawls into and out of the arc at
4390    /// 0.0707 m/s (the test above). With a tolerance of 0.1 mm:
4391    /// (a) The curve may be L = sqrt(24 e r) = sqrt(24 * 0.0001 * 0.1) = 15.49 mm long. To enter the arc at its
4392    /// 0.4 m/s with 0.4 of the jerk limit it would need v^3 / (0.4 j r) = 0.064 / (0.4 * 100 * 0.1) = 16 mm, so
4393    /// the tolerance decides: the arc moves in by the full 0.1 mm, and the speed on the curve is
4394    /// (0.4 j r L)^(1/3) = (40 * 0.1 * 0.01549)^(1/3) = 0.3957 m/s, five and a half times the crawl.
4395    /// (b) With a tolerance of 1 mm the curve is the 16 mm it needs and no longer, and the path is off by
4396    /// e = L^2 / (24 r) = 0.016^2 / 2.4 = 0.1067 mm.
4397    /// (c) Speed, acceleration and jerk of both axes stay within the limits, by differences as above; every
4398    /// planned pose is within the reported deviation of the given path, and reaches it on the arc; the path
4399    /// still ends on its target; and it takes clearly less time.
4400    #[test]
4401    fn transition_curves_let_the_path_enter_an_arc_at_speed() {
4402        let (axes, cycle, start) = (axes(), 1e-3, [0.1, 0.35]);
4403        let pieces = parse(
4404            "line,0.5,0.35
4405arc,0.6,0.25,0.5,0.25,cw
4406line,0.6,0.05",
4407        )
4408        .unwrap();
4409        let given = plan(&axes, &start, &pieces, cycle, 0.0, ARC_SLACK).unwrap();
4410        assert_eq!(deviation(&axes, &start, &pieces, 0.0, ARC_SLACK).unwrap(), 0.0);
4411        // How far a pose is from the given path: from the first line, the arc or the second line.
4412        let off = |p: &[f64]| {
4413            if p[0] <= 0.5 {
4414                (p[1] - 0.35).abs()
4415            } else if p[1] <= 0.25 {
4416                (p[0] - 0.6).abs()
4417            } else {
4418                (distance(p, &[0.5, 0.25]) - 0.1).abs()
4419            }
4420        };
4421        let curves = |tolerance: f64| -> Vec<f64> {
4422            let geo = geometry(&axes, &start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap().0;
4423            geo.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).map(Geo::length).collect()
4424        };
4425        for (tolerance, by_hand, length, speed) in [(1e-4, 1e-4, 0.01549, 0.3957), (1e-3, 0.1067e-3, 0.016, 0.4)] {
4426            let reported = deviation(&axes, &start, &pieces, tolerance, ARC_SLACK).unwrap();
4427            assert!(
4428                (reported / by_hand - 1.0).abs() < 2e-3 && reported <= tolerance,
4429                "{reported} m reported, {by_hand} m by hand"
4430            );
4431            let lengths = curves(tolerance);
4432            assert!(
4433                lengths.len() == 2 && lengths.iter().all(|l| (l / length - 1.0).abs() < 5e-3),
4434                "{lengths:?} against {length}"
4435            );
4436
4437            let points = plan(&axes, &start, &pieces, cycle, tolerance, ARC_SLACK).unwrap();
4438            let peak = peak_rates(&points, cycle);
4439            for (i, axis) in axes.iter().enumerate() {
4440                assert!(
4441                    peak[0][i] <= 1.001 * axis.max_vel
4442                        && peak[1][i] <= 1.001 * axis.max_acc
4443                        && peak[2][i] <= 1.001 * axis.max_jerk,
4444                    "axis {i}: {peak:?}"
4445                );
4446            }
4447            let furthest = points.iter().map(|p| off(&p.1)).fold(0.0, f64::max);
4448            assert!(
4449                furthest <= reported + 1e-9 && furthest > 0.999 * reported,
4450                "{furthest} m off the path, {reported} m reported"
4451            );
4452            // The slowest the path gets between leaving the first line and being back on the second.
4453            let blended = |p: &[f64]| off(p) > 1e-9;
4454            let slowest = points
4455                .windows(2)
4456                .filter(|w| blended(&w[0].1) && blended(&w[1].1))
4457                .map(|w| distance(&w[0].1, &w[1].1) / cycle)
4458                .fold(f64::INFINITY, f64::min);
4459            assert!((slowest - speed).abs() < 2e-3, "{slowest} m/s through the blend, {speed} m/s by hand");
4460            let (last, before) = (points.len() - 1, given[given.len() - 1].0);
4461            assert!(
4462                points[0].1 == start
4463                    && distance(&points[last].1, &[0.6, 0.05]) < 1e-9
4464                    && distance(&points[last].1, &points[last - 1].1) < 1e-6
4465            );
4466            assert!(points[last].0 < 0.9 * before, "{} s with transition curves, {before} s without", points[last].0);
4467            println!(
4468                "tolerance {tolerance} m: {} s against {before} s, off by {furthest} m, curves {lengths:?} m, slowest {slowest} m/s, peak rates {peak:?}",
4469                points[last].0
4470            );
4471        }
4472    }
4473
4474    /// Two arcs: an S of a 0.1 m and a 0.05 m arc turning opposite ways, and the same two turning the same way,
4475    /// each between two lines. Every junction gets its curve, and the blended path has no step in position,
4476    /// direction or curvature anywhere; it ends on its target, stays within the axis limits and is faster.
4477    /// (An arc at an end of the path: `an_arc_at_an_end_or_a_corner_gets_its_transition_curve`.)
4478    #[test]
4479    fn transition_curves_join_two_arcs() {
4480        let (axes, cycle, start, tolerance) = (axes(), 1e-3, [0.1, 0.5], 1e-4);
4481        let s_curve = "line,0.3,0.5
4482arc,0.4,0.4,0.3,0.4,cw
4483arc,0.45,0.35,0.45,0.4,ccw
4484line,0.7,0.35";
4485        let same_way = "line,0.3,0.5
4486arc,0.4,0.4,0.3,0.4,cw
4487arc,0.35,0.35,0.35,0.4,cw
4488line,0.1,0.35";
4489        for (text, end) in [(s_curve, [0.7, 0.35]), (same_way, [0.1, 0.35])] {
4490            let pieces = parse(text).unwrap();
4491            let (geo, reported) = geometry(&axes, &start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
4492            assert_eq!(geo.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).count(), 3, "{text}");
4493            // The tighter arc is the one that moves in by the whole tolerance.
4494            assert!((reported - tolerance).abs() < 1e-12, "{reported}");
4495            for pair in geo.windows(2) {
4496                let (before, after) = (pair[0].at(pair[0].length()), pair[1].at(0.0));
4497                let steps =
4498                    [distance(&before[0], &after[0]), distance(&before[1], &after[1]), distance(&before[2], &after[2])];
4499                assert!(steps[0] < 1e-11 && steps[1] < 1e-9 && steps[2] < 1e-7, "{text}: steps {steps:?}");
4500            }
4501            let (points, given) = (
4502                plan(&axes, &start, &pieces, cycle, tolerance, ARC_SLACK).unwrap(),
4503                plan(&axes, &start, &pieces, cycle, 0.0, ARC_SLACK).unwrap(),
4504            );
4505            let peak = peak_rates(&points, cycle);
4506            for (i, axis) in axes.iter().enumerate() {
4507                assert!(
4508                    peak[0][i] <= 1.001 * axis.max_vel
4509                        && peak[1][i] <= 1.001 * axis.max_acc
4510                        && peak[2][i] <= 1.001 * axis.max_jerk,
4511                    "{text}, axis {i}: {peak:?}"
4512                );
4513            }
4514            let (last, before) = (points.len() - 1, given[given.len() - 1].0);
4515            assert!(
4516                distance(&points[last].1, &end) < 1e-9 && points[last].0 < 0.9 * before,
4517                "{text}: {} s against {before} s",
4518                points[last].0
4519            );
4520            println!("{} s against {before} s", points[last].0);
4521        }
4522    }
4523
4524    /// A wide arc (0.25 m, 0.35 rad of it) that hands over to a tight one (1.72 mm, 1 rad) turning the same
4525    /// way, between two lines, with a tolerance of 1 mm. The curves on the tight arc turned by more than the
4526    /// whole circle between them; what they left of the arc was taken as the angle between
4527    /// them, which read as a short arc again, and the planned path went round once more than the given one
4528    /// (turning by 7.63 rad for 1.35 rad). Now what each curve takes is counted from the arc's own end, such
4529    /// curves are refused and shorter ones tried: the planned path turns as far as the given one.
4530    #[test]
4531    fn curves_too_long_for_a_tight_arc_do_not_add_a_turn() {
4532        let (axes, start, tolerance) = (axes(), [0.2, 0.02], 1e-3);
4533        let (wide, tight, a, b) = (0.25, 0.00172, 0.35, 1.0);
4534        // Clockwise from heading +z: after turning by t, the point is at the angle t above the centre's left.
4535        let on = |centre: [f64; 2], r: f64, t: f64| [centre[0] - r * t.cos(), centre[1] + r * t.sin()];
4536        let c1 = [0.2 + wide, 0.2];
4537        let p1 = on(c1, wide, a);
4538        let c2 = [p1[0] + (c1[0] - p1[0]) * tight / wide, p1[1] + (c1[1] - p1[1]) * tight / wide];
4539        let p2 = on(c2, tight, a + b);
4540        let end = [p2[0] + 0.02 * (a + b).sin(), p2[1] + 0.02 * (a + b).cos()];
4541        let arc = |to: [f64; 2], centre: [f64; 2]| Piece::Arc {
4542            to: to.to_vec(),
4543            centre: centre.to_vec(),
4544            clockwise: true,
4545            plane: None,
4546        };
4547        let pieces = [Piece::Line(vec![0.2, 0.2]), arc(p1, c1), arc(p2, c2), Piece::Line(end.to_vec())];
4548        let (geo, reported) = geometry(&axes, &start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
4549        let turned: f64 = geo
4550            .iter()
4551            .map(|g| match g {
4552                Geo::Arc { radius, turn, length, .. } => turn * length / radius,
4553                Geo::Clothoid { k0, k1, length, .. } => 0.5 * (k0 + k1) * length,
4554                Geo::Line { .. } | Geo::Slerp { .. } | Geo::Spline { .. } | Geo::Arc3 { .. } | Geo::Carried { .. } => {
4555                    0.0
4556                }
4557            })
4558            .sum();
4559        assert!((turned + a + b).abs() < 1e-9, "the planned path turns by {turned} rad, the given one by {}", -a - b);
4560        // It is blended all the same, with shorter curves, and the tight arc moves in by less than its radius.
4561        assert!(
4562            geo.iter().any(|g| matches!(g, Geo::Clothoid { .. })) && reported > 0.0 && reported < tight,
4563            "{reported} m reported"
4564        );
4565        let points = plan(&axes, &start, &pieces, 1e-3, tolerance, ARC_SLACK).unwrap();
4566        assert!(distance(&points[points.len() - 1].1, &end) < 1e-9);
4567        println!("turned {turned} rad, off by {reported} m, {} pieces", geo.len());
4568    }
4569
4570    /// A line that ends on the end of a stroke, at z = 0: its last pose came out at z = -2.8e-17, outside the
4571    /// range, and the controller refused the whole path. Planned poses stay within the ranges of the axes.
4572    #[test]
4573    fn a_path_onto_the_end_of_a_stroke_stays_within_the_range() {
4574        let axes = axes();
4575        let points = plan(&axes, &[0.278, 0.231], &[Piece::Line(vec![0.525, 0.0])], 1e-3, 0.0, ARC_SLACK).unwrap();
4576        assert!(points.iter().all(|p| p.1[1] >= 0.0), "ends at z = {:e}", points[points.len() - 1].1[1]);
4577        assert_eq!(points[points.len() - 1].1, [0.525, 0.0]);
4578        // A path that leaves the range for good is left as it is, for the controller to refuse.
4579        let beyond = plan(&axes, &[0.278, 0.231], &[Piece::Line(vec![0.525, -0.001])], 1e-3, 0.0, ARC_SLACK).unwrap();
4580        assert!(beyond[beyond.len() - 1].1[1] < -0.000_999);
4581    }
4582
4583    /// A corner is stopped at: the speed at the corner of two lines at right angles is zero, and each line
4584    /// is the S-curve of a single move, whose time the profile test calculates by hand.
4585    #[test]
4586    fn a_corner_is_stopped_at() {
4587        let (axes, cycle) = (axes(), 1e-3);
4588        let points = plan(
4589            &axes,
4590            &[0.1, 0.1],
4591            &[Piece::Line(vec![0.5, 0.1]), Piece::Line(vec![0.5, 0.3])],
4592            cycle,
4593            0.0,
4594            ARC_SLACK,
4595        )
4596        .unwrap();
4597        let moves = [
4598            crate::profile::Move::new(&[0.1, 0.1], &[0.5, 0.1], &axes),
4599            crate::profile::Move::new(&[0.5, 0.1], &[0.5, 0.3], &axes),
4600        ];
4601        let duration = points[points.len() - 1].0;
4602        assert!((duration - moves[0].duration() - moves[1].duration()).abs() <= cycle, "{duration} s");
4603        let corner = (moves[0].duration() / cycle).round() as usize;
4604        assert!(
4605            distance(&points[corner].1, &[0.5, 0.1]) < 1e-6
4606                && distance(&points[corner + 1].1, &points[corner].1) < 1e-6
4607        );
4608        let peak = peak_rates(&points, cycle);
4609        assert!(
4610            peak[1][0] <= 8.0 * 1.001 && peak[1][1] <= 6.0 * 1.001 && peak[2][0] <= 100.1 && peak[2][1] <= 100.1,
4611            "{peak:?}"
4612        );
4613    }
4614
4615    /// An arc that touches an end of the path or a corner: a line into a quarter arc of 0.1 m that ends the path,
4616    /// and the same with a corner after the arc (a line at right angles). The arc's end has to stay where it is
4617    /// given, so its circle shrinks by s and moves towards that end by s; after a quarter turn it is then apart
4618    /// from the line by s (1 - cos 90 degrees) = s, which is made e = L^2 / (24 r). With 0.1 mm these are the
4619    /// numbers of `transition_curves_let_the_path_enter_an_arc_at_speed`: L = sqrt(24 e r) = 15.49 mm, and the
4620    /// path enters the arc at (0.4 j r L)^(1/3) = 0.3957 m/s instead of 0.0707 m/s. The arc still ends exactly
4621    /// where it is given (the end of the path, or the corner, where the path stops), every planned pose is within
4622    /// the reported 0.1 mm of the given path, and the axis limits hold.
4623    #[test]
4624    fn an_arc_at_an_end_or_a_corner_gets_its_transition_curve() {
4625        let (axes, cycle, start, tolerance) = (axes(), 1e-3, [0.1, 0.35], 1e-4);
4626        // How far a pose is from the given path: the first line, the arc, or the line after the corner.
4627        let off = |p: &[f64]| {
4628            if p[0] <= 0.5 {
4629                (p[1] - 0.35).abs()
4630            } else if p[0] <= 0.6 {
4631                (distance(p, &[0.5, 0.25]) - 0.1).abs()
4632            } else {
4633                (p[1] - 0.25).abs()
4634            }
4635        };
4636        for (text, end) in [
4637            ("line,0.5,0.35\narc,0.6,0.25,0.5,0.25,cw", [0.6, 0.25]),
4638            ("line,0.5,0.35\narc,0.6,0.25,0.5,0.25,cw\nline,0.7,0.25", [0.7, 0.25]),
4639        ] {
4640            let pieces = parse(text).unwrap();
4641            let (geo, reported) = geometry(&axes, &start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
4642            let curves: Vec<f64> = geo.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).map(Geo::length).collect();
4643            assert!(curves.len() == 1 && (curves[0] / 0.01549 - 1.0).abs() < 5e-3, "{text}: curves {curves:?}");
4644            assert!(
4645                (reported / tolerance - 1.0).abs() < 2e-3 && reported <= tolerance,
4646                "{text}: {reported} m reported"
4647            );
4648            let arc = geo.iter().find(|g| matches!(g, Geo::Arc { .. })).unwrap();
4649            assert!(
4650                distance(&arc.at(arc.length())[0], &[0.6, 0.25]) < 1e-12
4651                    && distance(&arc.at(arc.length())[1], &[0.0, -1.0]) < 1e-12,
4652                "{text}: the arc ends elsewhere"
4653            );
4654            for pair in geo.windows(2).filter(|pair| !corner(&pair[0], &pair[1])) {
4655                let (before, after) = (pair[0].at(pair[0].length()), pair[1].at(0.0));
4656                let steps =
4657                    [distance(&before[0], &after[0]), distance(&before[1], &after[1]), distance(&before[2], &after[2])];
4658                assert!(steps[0] < 1e-11 && steps[1] < 1e-9 && steps[2] < 1e-7, "{text}: steps {steps:?}");
4659            }
4660            for tolerance in [0.0, tolerance] {
4661                let points = plan(&axes, &start, &pieces, cycle, tolerance, ARC_SLACK).unwrap();
4662                let peak = peak_rates(&points, cycle);
4663                for (i, axis) in axes.iter().enumerate() {
4664                    assert!(
4665                        peak[0][i] <= 1.001 * axis.max_vel
4666                            && peak[1][i] <= 1.001 * axis.max_acc
4667                            && peak[2][i] <= 1.001 * axis.max_jerk,
4668                        "{text}, axis {i}: {peak:?}"
4669                    );
4670                }
4671                let furthest = points.iter().map(|p| off(&p.1)).fold(0.0, f64::max);
4672                assert!(
4673                    furthest <= reported + 1e-9 && (tolerance == 0.0 || furthest > 0.5 * reported),
4674                    "{text}: {furthest} m off the path"
4675                );
4676                // The arc's end is passed exactly (the path stops there), and the path ends on its target.
4677                assert!(
4678                    points.iter().any(|p| distance(&p.1, &[0.6, 0.25]) < 1e-6)
4679                        && distance(&points[points.len() - 1].1, &end) < 1e-9,
4680                    "{text}"
4681                );
4682                // The speed where the path leaves the first line.
4683                let leaves = points.iter().position(|p| off(&p.1) > 1e-9 || p.1[0] > 0.5).unwrap();
4684                let speed = distance(&points[leaves].1, &points[leaves - 1].1) / cycle;
4685                let by_hand = if tolerance > 0.0 { 0.3957 } else { 0.0707 };
4686                assert!(
4687                    (speed - by_hand).abs() < 2e-3,
4688                    "{text}, tolerance {tolerance}: {speed} m/s into the arc, {by_hand} by hand"
4689                );
4690                println!(
4691                    "{text:?}, tolerance {tolerance}: {} s, {speed} m/s into the arc, off by {furthest} m",
4692                    points[points.len() - 1].0
4693                );
4694            }
4695        }
4696    }
4697
4698    /// A line into a spline: along x to (0.3, 0.2), then one span to (0.39, 0.23), where the path ends. By hand
4699    /// (`spline`): the span leaves in the line's direction, d0 = (1, 0), and ends without curvature, so
4700    /// d1 = (3 chord - d0) / 2 with chord = (0.09, 0.03) / h, h = sqrt(0.009) = 94.87 mm, and its curvature at the
4701    /// junction is 3 dz / h^2 = 3 * 0.03 / 0.009 = 10 1/m.
4702    /// (a) Without a tolerance the curvature steps by 10 1/m there and the path passes at
4703    /// sqrt(0.5 j T / 10) = sqrt(0.5 * 100 * 0.001 / 10) = 0.0707 m/s.
4704    /// (b) With 0.1 mm the span is eased over l = sqrt(e / (0.01728 dk)) = sqrt(1e-4 / 0.1728) = 24.06 mm (half
4705    /// the span is 47.4 mm; the length needed at 0.4 m/s, 9 * 1.05 * 10 * 0.4^3 / (0.4 * 100) = 151 mm, is more),
4706    /// which moves it by 0.01728 * 10 * l^2 = 0.1 mm. At the junction its curvature is 0 and changes per distance
4707    /// by 9 * 10 / l = 3740.6 1/m^2 from the easing, plus the span's own change there, d0 x 6 c3 with
4708    /// c3 = (d0 + d1 - 2 chord) / h^2: (0.4743 - 0.6325) / 0.009 * 6 = -105.4 1/m^2, together 3635.2 1/m^2. With
4709    /// the margin of 1.05 the speed on the eased part is cbrt(0.4 j / (1.05 * 3635.2)) = 0.2189 m/s, three times
4710    /// the crawl. The planned poses stay within the reported 0.1 mm of the spline as given and within the axis
4711    /// limits, and the path still ends on the via point.
4712    #[test]
4713    fn a_spline_eased_into_a_line_is_entered_at_the_hand_calculated_speed() {
4714        let (axes, cycle, start) = (axes(), 1e-3, [0.1, 0.2]);
4715        let pieces = parse("line,0.3,0.2\nspline,0.39,0.23").unwrap();
4716        let geo = given(&start, &pieces, ARC_SLACK).unwrap().0;
4717        let Geo::Spline { c, .. } = &geo[1] else { panic!("a spline span") };
4718        let [d, d2, _] = poly_rates(c, 0.0);
4719        assert!((d[0] - 1.0).abs() < 1e-12 && d[1].abs() < 1e-12 && (d2[1] - 10.0).abs() < 1e-9, "{d:?} {d2:?}");
4720        let (eased, reported) = geometry(&axes, &start, &pieces, 1e-4, &axis_speed(&axes), ARC_SLACK).unwrap();
4721        let Geo::Spline { h: l, .. } = &eased[1] else { panic!("the eased part") };
4722        assert!(
4723            eased.len() == 3 && (l - 0.024056).abs() < 1e-5 && (reported - 1e-4).abs() < 1e-12,
4724            "{l} m eased, {reported} m reported"
4725        );
4726        for (tolerance, by_hand) in [(0.0, 0.0707), (1e-4, 0.2189)] {
4727            let points = plan(&axes, &start, &pieces, cycle, tolerance, ARC_SLACK).unwrap();
4728            let peak = peak_rates(&points, cycle);
4729            for (i, axis) in axes.iter().enumerate() {
4730                assert!(
4731                    peak[0][i] <= 1.001 * axis.max_vel
4732                        && peak[1][i] <= 1.001 * axis.max_acc
4733                        && peak[2][i] <= 1.001 * axis.max_jerk,
4734                    "tolerance {tolerance}, axis {i}: {peak:?}"
4735                );
4736            }
4737            let past = points.iter().position(|p| p.1[0] > 0.3).unwrap();
4738            let speed = distance(&points[past].1, &points[past - 1].1) / cycle;
4739            assert!(
4740                (speed / by_hand - 1.0).abs() < 0.01,
4741                "tolerance {tolerance}: {speed} m/s at the junction, {by_hand} by hand"
4742            );
4743            let line = polyline(&geo);
4744            let furthest = points.iter().map(|p| off_line(&line, &p.1)).fold(0.0, f64::max);
4745            assert!(
4746                furthest <= reported * (tolerance > 0.0) as u8 as f64 + 1e-7
4747                    && (tolerance == 0.0 || furthest > 0.9 * reported),
4748                "tolerance {tolerance}: {furthest} m off"
4749            );
4750            assert!(distance(&points[points.len() - 1].1, &[0.39, 0.23]) < 1e-9);
4751            println!(
4752                "tolerance {tolerance}: {} s, {speed} m/s at the junction, off by {furthest} m",
4753                points[points.len() - 1].0
4754            );
4755        }
4756    }
4757
4758    /// Total length and total turning of a path.
4759    fn length_and_turning(geo: &[Geo]) -> (f64, f64) {
4760        let turned = |g: &Geo| match g {
4761            Geo::Arc { radius, turn, length, .. } => turn * length / radius,
4762            Geo::Clothoid { k0, k1, length, .. } => 0.5 * (k0 + k1) * length,
4763            Geo::Line { .. } | Geo::Slerp { .. } | Geo::Spline { .. } | Geo::Arc3 { .. } | Geo::Carried { .. } => 0.0,
4764        };
4765        (geo.iter().map(Geo::length).sum(), geo.iter().map(turned).sum())
4766    }
4767
4768    /// The blended path is as long as the given one, but for what the transitions change: each curve replaces about
4769    /// its own length of the pieces beside it, and each arc moved in by at most the reported deviation is shorter by
4770    /// at most that times the angle it turns. And it turns by as much (a lost or added turn shows here).
4771    fn assert_blend_keeps_the_path(start: &[f64], pieces: &[Piece], tolerance: f64, what: &str) {
4772        let axes = axes();
4773        let (given, _) = geometry(&axes, start, pieces, 0.0, &axis_speed(&axes), ARC_SLACK).unwrap();
4774        let (planned, reported) = geometry(&axes, start, pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
4775        let ((given_length, given_turn), (planned_length, planned_turn)) =
4776            (length_and_turning(&given), length_and_turning(&planned));
4777        let curves: f64 = planned.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).map(Geo::length).sum();
4778        let allowance = curves + reported * given_turn.abs().max(planned_turn.abs()) + 1e-12;
4779        assert!(
4780            (planned_length - given_length).abs() <= allowance,
4781            "{what}: given {given_length} m, planned {planned_length} m, allowance {allowance} m"
4782        );
4783        assert!(
4784            (planned_turn - given_turn).abs() < 1e-6,
4785            "{what}: given turns {given_turn} rad, planned {planned_turn} rad"
4786        );
4787    }
4788
4789    /// Two arcs on the same circle that together turn more than a whole turn (4 rad, then pi + 0.05 rad, radius
4790    /// 0.05 m), between two lines: their radii differ by rounding, so a transition curve was built between them,
4791    /// and what it took of the arcs wrapped by a whole turn: the planned path was 0.1953 m long for 0.5096 m given.
4792    /// Equal curvatures get no curve, and the path keeps its length and its turning.
4793    #[test]
4794    fn two_arcs_on_one_circle_keep_their_whole_turn() {
4795        let (centre, r) = ([0.5, 0.5], 0.05);
4796        let at = |angle: f64| vec![centre[0] + r * angle.cos(), centre[1] + r * angle.sin()];
4797        let (a1, a2) =
4798            (std::f64::consts::FRAC_PI_2 - 4.0, std::f64::consts::FRAC_PI_2 - 4.0 - std::f64::consts::PI - 0.05);
4799        let end = at(a2);
4800        let arc = |to: Vec<f64>| Piece::Arc { to, centre: centre.to_vec(), clockwise: true, plane: None };
4801        let pieces = [
4802            Piece::Line(vec![0.5, 0.55]),
4803            arc(at(a1)),
4804            arc(end.clone()),
4805            Piece::Line(vec![end[0] + 0.1 * a2.sin(), end[1] - 0.1 * a2.cos()]),
4806        ];
4807        let axes = axes();
4808        let given =
4809            length_and_turning(&geometry(&axes, &[0.45, 0.55], &pieces, 0.0, &axis_speed(&axes), ARC_SLACK).unwrap().0)
4810                .0;
4811        assert!((given - (0.05 + 0.05 * (4.0 + std::f64::consts::PI + 0.05) + 0.1)).abs() < 1e-9, "{given} m");
4812        assert_blend_keeps_the_path(&[0.45, 0.55], &pieces, 1e-4, "two arcs on one circle");
4813    }
4814
4815    /// Random paths of lines and arcs that join in the same direction (arcs of 2 mm to 0.2 m, turning 0.05 to 6 rad
4816    /// either way, some continuing on the circle before them), blended with tolerances of 0.01 to 1 mm: every one
4817    /// keeps its length within what its transitions may change, and its turning.
4818    #[test]
4819    fn blended_random_paths_keep_their_length_and_turning() {
4820        let mut seed = 0x2545_F491_4F6C_DD1Du64;
4821        let mut random = move || {
4822            seed ^= seed << 13;
4823            seed ^= seed >> 7;
4824            seed ^= seed << 17;
4825            (seed >> 11) as f64 / (1u64 << 53) as f64
4826        };
4827        for case in 0..400 {
4828            let (mut here, start_heading) = ([0.5, 0.5], random() * std::f64::consts::TAU);
4829            let mut heading = start_heading;
4830            let mut pieces = Vec::new();
4831            let mut last_arc: Option<([f64; 2], bool)> = None;
4832            for _ in 0..2 + (random() * 6.0) as usize {
4833                if random() < 0.35 {
4834                    let length = 0.001 + 0.1 * random();
4835                    here = [here[0] + length * heading.cos(), here[1] + length * heading.sin()];
4836                    pieces.push(Piece::Line(here.to_vec()));
4837                    last_arc = None;
4838                } else {
4839                    // On the circle before it half the time, else a new one turning either way.
4840                    let (centre, clockwise) = match last_arc {
4841                        Some(same) if random() < 0.5 => same,
4842                        _ => {
4843                            let (r, clockwise) = (0.002 + 0.2 * random(), random() < 0.5);
4844                            let side = if clockwise { -1.0 } else { 1.0 };
4845                            ([here[0] - side * r * heading.sin(), here[1] + side * r * heading.cos()], clockwise)
4846                        }
4847                    };
4848                    let (r, side) = (distance(&here, &centre), if clockwise { -1.0 } else { 1.0 });
4849                    let sweep = 0.05 + 5.95 * random();
4850                    let angle = (here[1] - centre[1]).atan2(here[0] - centre[0]) + side * sweep;
4851                    here = [centre[0] + r * angle.cos(), centre[1] + r * angle.sin()];
4852                    heading += side * sweep;
4853                    pieces.push(Piece::Arc { to: here.to_vec(), centre: centre.to_vec(), clockwise, plane: None });
4854                    last_arc = Some((centre, clockwise));
4855                }
4856            }
4857            pieces.push(Piece::Line(vec![here[0] + 0.05 * heading.cos(), here[1] + 0.05 * heading.sin()]));
4858            // A lead-in line onto the first piece, in its direction.
4859            let lead = [0.5 - 0.01 * start_heading.cos(), 0.5 - 0.01 * start_heading.sin()];
4860            let pieces = [&[Piece::Line(vec![0.5, 0.5])][..], &pieces].concat();
4861            for tolerance in [1e-5, 1e-4, 1e-3] {
4862                assert_blend_keeps_the_path(
4863                    &lead,
4864                    &pieces,
4865                    tolerance,
4866                    &format!("case {case}, tolerance {tolerance}: {pieces:?}"),
4867                );
4868            }
4869        }
4870    }
4871
4872    /// No step in position, direction or curvature between two pieces that meet in their direction.
4873    fn assert_no_steps(geo: &[Geo], what: &str) {
4874        for pair in geo.windows(2).filter(|pair| !corner(&pair[0], &pair[1])) {
4875            let (before, after) = (pair[0].at(pair[0].length()), pair[1].at(0.0));
4876            let steps =
4877                [distance(&before[0], &after[0]), distance(&before[1], &after[1]), distance(&before[2], &after[2])];
4878            assert!(steps[0] < 1e-11 && steps[1] < 1e-9 && steps[2] < 1e-7, "{what}: steps {steps:?}");
4879        }
4880    }
4881
4882    /// Every planned pose is within the reported deviation of the given path (and a part of it gets there), the axis
4883    /// limits hold (by differences, as above), the path ends on `end`, and it takes less time than as given (the gain
4884    /// is that of the junctions only: 5 % on a path that is mostly one arc at full speed). The planned poses.
4885    fn assert_blend_runs_within(
4886        axes: &[AxisInfo],
4887        start: &[f64],
4888        pieces: &[Piece],
4889        tolerance: f64,
4890        end: &[f64],
4891        what: &str,
4892    ) -> Vec<(f64, Vec<f64>)> {
4893        let (cycle, given) = (1e-3, geometry(axes, start, pieces, 0.0, &axis_speed(axes), ARC_SLACK).unwrap().0);
4894        let reported = deviation(axes, start, pieces, tolerance, ARC_SLACK).unwrap();
4895        assert!(reported > 0.0 && reported <= tolerance * (1.0 + 1e-9), "{what}: {reported} m reported");
4896        let (points, before) = (
4897            plan(axes, start, pieces, cycle, tolerance, ARC_SLACK).unwrap(),
4898            plan(axes, start, pieces, cycle, 0.0, ARC_SLACK).unwrap(),
4899        );
4900        let line = polyline(&given);
4901        let furthest = points.iter().map(|p| off_line(&line, &p.1)).fold(0.0, f64::max);
4902        assert!(
4903            furthest <= reported + 1e-7 && furthest > 0.5 * reported,
4904            "{what}: {furthest} m off, {reported} m reported"
4905        );
4906        for w in points.windows(4) {
4907            for (i, axis) in axes.iter().enumerate() {
4908                let p = [w[0].1[i], w[1].1[i], w[2].1[i], w[3].1[i]];
4909                assert!(
4910                    ((p[1] - p[0]) / cycle).abs() <= 1.001 * axis.max_vel
4911                        && ((p[2] - 2.0 * p[1] + p[0]) / cycle.powi(2)).abs() <= 1.001 * axis.max_acc,
4912                    "{what}, axis {i}"
4913                );
4914                assert!(
4915                    ((p[3] - 3.0 * p[2] + 3.0 * p[1] - p[0]) / cycle.powi(3)).abs() <= 1.001 * axis.max_jerk,
4916                    "{what}, axis {i}"
4917                );
4918            }
4919        }
4920        let (last, slower) = (points.len() - 1, before[before.len() - 1].0);
4921        assert!(
4922            distance(&points[last].1, end) < 1e-9 && points[last].0 < slower - 0.01,
4923            "{what}: {} s against {slower} s",
4924            points[last].0
4925        );
4926        println!("{what}: {} s against {slower} s, off by {furthest} m, {reported} m reported", points[last].0);
4927        points
4928    }
4929
4930    /// The pieces of a line, an arc and a line on three axes, in the plane through (0, 0, -0.85) along x and along
4931    /// (0, cos 30, sin 30) (tilted by 30 degrees about x, in no plane of two axes): along x onto the circle of 0.1 m
4932    /// around that point, a quarter of it counter-clockwise, then 0.15 m on in its direction. The start, the plane's
4933    /// point and its two directions.
4934    fn tilted_path() -> (Vec<f64>, Vec<Piece>, [[f64; 3]; 3]) {
4935        let (c, e1, e2, r) =
4936            ([0.0, 0.0, -0.85], [1.0, 0.0, 0.0], [0.0, 30f64.to_radians().cos(), 30f64.to_radians().sin()], 0.1);
4937        let at = |a: f64, b: f64| (0..3).map(|i| c[i] + a * e1[i] + b * e2[i]).collect::<Vec<f64>>();
4938        let pieces = vec![
4939            Piece::Line(at(0.0, -r)),
4940            Piece::Arc { to: at(r, 0.0), centre: c.to_vec(), clockwise: false, plane: None },
4941            Piece::Line(at(r, 0.15)),
4942        ];
4943        (at(-0.2, -r), pieces, [c, e1, e2])
4944    }
4945
4946    /// Transition curves on three axes, on `tilted_path` with a tolerance of 0.1 mm (the delta's limits: 3 m/s,
4947    /// 50 m/s^2, 2500 m/s^3). By hand: on the arc the speed is sqrt(0.8 a r) = sqrt(0.8 * 50 * 0.1) = 2 m/s, whose
4948    /// entry would need a curve of v^3 dk / (0.4 j) = 8 * 10 / 1000 = 80 mm; the tolerance allows
4949    /// L = sqrt(24 e r) = sqrt(24 * 1e-4 * 0.1) = 15.49 mm, so the arc moves in by e = L^2 / (24 r) = 0.1 mm to a radius
4950    /// of 99.9 mm. Both curves are 15.49 mm, every piece and every planned pose lies in the tilted plane, there is no
4951    /// step in position, direction or curvature, every pose is within the reported 0.1 mm of the given path and the
4952    /// path is faster than as given. Then a second arc of 0.05 m in another plane (x = 0.1, through the last line)
4953    /// and a line out of it: the line between the arcs lies in both planes and is shared out, so all four junctions get
4954    /// their curve (the second arc's in its own plane), with the same checks.
4955    #[test]
4956    fn transition_curves_on_three_axes_lie_in_the_plane_of_the_arc() {
4957        let (axes, tolerance) = (axes3(), 1e-4);
4958        let (start, pieces, [c, e1, e2]) = tilted_path();
4959        let normal = cross3(e1, e2);
4960        let (geo, reported) = geometry(&axes, &start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
4961        assert!((reported - 1e-4).abs() < 1e-12, "{reported} m reported, 0.1 mm by hand");
4962        let curves: Vec<f64> = geo.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).map(Geo::length).collect();
4963        assert!(
4964            curves.len() == 2 && curves.iter().all(|l| (l / 0.01549 - 1.0).abs() < 5e-3),
4965            "curves {curves:?}, 15.49 mm by hand"
4966        );
4967        assert!(
4968            geo.iter().any(|g| matches!(g, Geo::Arc3 { radius, .. } if (radius - 0.0999).abs() < 1e-12)),
4969            "the arc moved in by 0.1 mm"
4970        );
4971        assert_no_steps(&geo, "tilted");
4972        let in_plane = |p: &[f64]| dot3([p[0] - c[0], p[1] - c[1], p[2] - c[2]], normal).abs();
4973        let points = assert_blend_runs_within(
4974            &axes,
4975            &start,
4976            &pieces,
4977            tolerance,
4978            &[0.1, 0.15 * e2[1], -0.85 + 0.15 * e2[2]],
4979            "tilted",
4980        );
4981        let off_plane = points.iter().map(|p| in_plane(&p.1)).fold(0.0, f64::max);
4982        assert!(off_plane < 1e-12, "{off_plane} m off the plane");
4983
4984        // On out of the last line into an arc in the plane x = 0.1: its centre 0.05 m along the first plane's normal
4985        // (0, -sin 30, cos 30), a quarter turn towards e2, and 0.1 m on along that normal.
4986        let q = [0.1, 0.15 * e2[1], -0.85 + 0.15 * e2[2]];
4987        let centre: Vec<f64> = (0..3).map(|i| q[i] + 0.05 * normal[i]).collect();
4988        let end: Vec<f64> = (0..3).map(|i| centre[i] + 0.05 * e2[i] + 0.1 * normal[i]).collect();
4989        let more = [
4990            pieces,
4991            vec![
4992                Piece::Arc {
4993                    to: (0..3).map(|i| centre[i] + 0.05 * e2[i]).collect(),
4994                    centre,
4995                    clockwise: false,
4996                    plane: None,
4997                },
4998                Piece::Line(end.clone()),
4999            ],
5000        ]
5001        .concat();
5002        let (geo, _) = geometry(&axes, &start, &more, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
5003        assert_eq!(geo.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).count(), 4);
5004        assert_no_steps(&geo, "two planes");
5005        assert_blend_runs_within(&axes, &start, &more, tolerance, &end, "two planes");
5006    }
5007
5008    /// One curve length per arc: a line, a quarter arc of 0.1 m, a line, a quarter arc of 20 mm, a line, with 1 mm.
5009    /// By hand (axes as above, 100 m/s^3): on the wide arc 0.4 m/s (the axis limit), its curves
5010    /// L = v^3 dk / (0.4 j) = 0.064 * 10 / 40 = 16 mm (the tolerance allows sqrt(24 * 1e-3 * 0.1) = 49 mm); on the
5011    /// tight arc the jerk decides, v = (0.4 j r^2)^(1/3) = (40 * 0.0004)^(1/3) = 0.252 m/s, and
5012    /// L = 0.016 * 50 / 40 = 20 mm (allowed: sqrt(24 * 1e-3 * 0.02) = 21.9 mm). One length for the whole path made
5013    /// both 20 mm. The tight arc moves in by e = L^2 / (24 r) = 0.0004 / 0.48 = 0.833 mm, the wide one by
5014    /// 0.000256 / 2.4 = 0.107 mm; the larger is reported.
5015    #[test]
5016    fn each_arc_gets_the_curve_its_own_junctions_need() {
5017        let (axes, start, tolerance) = (axes(), [0.1, 0.35], 1e-3);
5018        let pieces = parse(
5019            "line,0.5,0.35
5020arc,0.6,0.25,0.5,0.25,cw
5021line,0.6,0.15
5022arc,0.58,0.13,0.58,0.15,cw
5023line,0.3,0.13",
5024        )
5025        .unwrap();
5026        let (geo, reported) = geometry(&axes, &start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
5027        let curves: Vec<f64> = geo.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).map(Geo::length).collect();
5028        assert_eq!(curves.len(), 4);
5029        println!("curves {curves:?} m");
5030        assert!(curves[..2].iter().all(|l| (l / 0.016 - 1.0).abs() < 5e-3), "{curves:?}: the wide arc's 16 mm by hand");
5031        // Fitted exactly, 19.67 mm: e = L^2 / (24 r) is the first term, and a curve as long as the radius turns 0.5 rad.
5032        assert!(
5033            curves[2..].iter().all(|l| (l / 0.020 - 1.0).abs() < 0.02),
5034            "{curves:?}: the tight arc's 20 mm by hand"
5035        );
5036        assert!((reported / 0.833e-3 - 1.0).abs() < 2e-3, "{reported} m reported, 0.833 mm by hand");
5037        assert_no_steps(&geo, "two arcs");
5038        assert_blend_runs_within(&axes, &start, &pieces, tolerance, &[0.3, 0.13], "two arcs");
5039    }
5040
5041    /// An arc fixed at one end with an arc at its other end: the path starts on a quarter arc of 0.1 m (its start, where
5042    /// the machine stands, stays), which hands over to a quarter arc of 50 mm turning the other way (an S), or the same
5043    /// way, and then to a line. The first arc shrinks by s and moves towards its start, s (1 - cos 90 degrees) = e:
5044    /// both junctions get their curve, the first arc still leaves the start along +x, no step anywhere, every pose
5045    /// within the reported deviation (at most 0.1 mm), faster than as given.
5046    #[test]
5047    fn an_arc_fixed_at_one_end_gets_its_curve_towards_an_arc() {
5048        let (axes, start, tolerance) = (axes(), [0.3, 0.5], 1e-4);
5049        for (text, end) in [
5050            ("arc,0.4,0.4,0.3,0.4,cw\narc,0.45,0.35,0.45,0.4,ccw\nline,0.7,0.35", [0.7, 0.35]),
5051            ("arc,0.4,0.4,0.3,0.4,cw\narc,0.35,0.35,0.35,0.4,cw\nline,0.1,0.35", [0.1, 0.35]),
5052        ] {
5053            let pieces = parse(text).unwrap();
5054            let (geo, _) = geometry(&axes, &start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
5055            assert_eq!(geo.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).count(), 2, "{text}");
5056            let [from, dir, _] = geo[0].at(0.0);
5057            assert!(distance(&from, &start) < 1e-12 && distance(&dir, &[1.0, 0.0]) < 1e-12, "{text}: {from:?} {dir:?}");
5058            assert_no_steps(&geo, text);
5059            assert_blend_runs_within(&axes, &start, &pieces, tolerance, &end, text);
5060        }
5061    }
5062
5063    /// An arc fixed at one end that turns three quarters: a line into a 0.1 m arc that ends the path after 270 degrees.
5064    /// Halfway round its smaller circle is 2 s inside the old one, so s is at most half the tolerance: with 0.1 mm,
5065    /// s = 0.05 mm, the gap at the free end e = s (1 - cos 270 degrees) = 0.05 mm, the curve
5066    /// L = sqrt(24 e r) = sqrt(24 * 5e-5 * 0.1) = 10.95 mm (shorter than the 16 mm the speed asks for), and the reported
5067    /// deviation is 2 s = 0.1 mm. The arc still ends on (0.4, 0.25) heading +y, and the path runs as above.
5068    #[test]
5069    fn an_arc_fixed_at_one_end_that_turns_three_quarters_gets_its_curve() {
5070        let (axes, start, tolerance) = (axes(), [0.1, 0.35], 1e-4);
5071        let pieces = parse("line,0.5,0.35\narc,0.4,0.25,0.5,0.25,cw").unwrap();
5072        let (geo, reported) = geometry(&axes, &start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
5073        let curves: Vec<f64> = geo.iter().filter(|g| matches!(g, Geo::Clothoid { .. })).map(Geo::length).collect();
5074        assert!(curves.len() == 1 && (curves[0] / 0.010954 - 1.0).abs() < 5e-3, "{curves:?}, 10.95 mm by hand");
5075        assert!((reported / 1e-4 - 1.0).abs() < 1e-3 && reported <= tolerance, "{reported} m reported, 0.1 mm by hand");
5076        let [end, dir, _] = geo[geo.len() - 1].at(geo[geo.len() - 1].length());
5077        assert!(distance(&end, &[0.4, 0.25]) < 1e-12 && distance(&dir, &[0.0, 1.0]) < 1e-12, "{end:?} {dir:?}");
5078        assert_no_steps(&geo, "three quarters");
5079        assert_blend_runs_within(&axes, &start, &pieces, tolerance, &[0.4, 0.25], "three quarters");
5080    }
5081
5082    /// The halving for a piece's top speed ends where nothing above a low of 0 fits: before 15 November it halved the
5083    /// high down to the smallest number, whose middle with 0 rounds to 0, and looped for ever (a line of the four-arm
5084    /// delta hung its time-optimal cycle). It ends with the low; and finds a top that fits as before.
5085    #[test]
5086    fn the_search_for_a_top_speed_ends_where_nothing_above_zero_fits() {
5087        assert_eq!(highest_fitting(0.0, 1.0, |top| top == 0.0), 0.0);
5088        let found = highest_fitting(0.0, 1.0, |top| top <= 0.3);
5089        assert!((found - 0.3).abs() < 1e-9, "{found}");
5090    }
5091
5092    /// Places with the same acceleration bound A = 10 m/s^2 both ways at any speed and a top of 1 m/s, except one of
5093    /// 0.5 m/s in the middle, 10 mm apart.
5094    fn dip(jerk: f64) -> (Vec<Place>, Vec<f64>) {
5095        let places: Vec<Place> = (0..41)
5096            .map(|k| Place {
5097                rows: vec![[1.0, 0.0, 0.0, -10.0, 10.0]],
5098                low: Vec::new(),
5099                turn: Vec::new(),
5100                curves: Arc::from([]),
5101                guide: Vec::new(),
5102                speed: Vec::new(),
5103                bends: Vec::new(),
5104                top: if k == 20 { 0.5 } else { 1.0 },
5105                scale: 1.0,
5106            })
5107            .collect();
5108        let x = smoothed(&places, 0.01, jerk, 1.0);
5109        (places, x)
5110    }
5111
5112    /// A piece whose speed curve falls faster than the jerk could follow, but stays far above what the piece reaches:
5113    /// tops from 4 to 2 m/s over 0.4 m (the curve slows at (16 - 4) / (2 * 0.4) = 15 m/s^2, which 20 m/s^3 cannot
5114    /// follow from rest), accelerations within 50 m/s^2. Rest to rest the jerk alone bounds it: four phases of
5115    /// T = (d / (2 j))^(1/3) = (0.4 / 40)^(1/3) = 0.215443 s, 4.31 m/s^2 and 0.928 m/s at most, 0.861774 s in all. Before
5116    /// 15 November the run counted on the curve's slowing at its speed and stayed at rest: the piece was refused as a
5117    /// crawl (a turn about z alone on the six-axis platform on cranks, whose motors' speed limit falls over the turn).
5118    #[test]
5119    fn a_piece_under_a_steeply_falling_speed_curve_takes_the_hand_calculated_time() {
5120        let places: Vec<Place> = (0..41)
5121            .map(|k| Place {
5122                rows: vec![[1.0, 0.0, 0.0, -50.0, 50.0]],
5123                low: Vec::new(),
5124                turn: Vec::new(),
5125                curves: Arc::from([]),
5126                guide: Vec::new(),
5127                speed: Vec::new(),
5128                bends: Vec::new(),
5129                top: 4.0 - 2.0 * k as f64 / 40.0,
5130                scale: 1.0,
5131            })
5132            .collect();
5133        let limits = piece_limits_of(places, 0.01, 20.0).unwrap();
5134        let knots = piece_knots(&limits, 0.4, [0.0, 0.0], 1e-3, true).unwrap();
5135        let [t, s, v, _] = knots[knots.len() - 1];
5136        assert!((t - 0.861774).abs() < 2e-3 && s == 0.4 && v.abs() < 1e-9, "{t} s, {s} m, {v} m/s");
5137        let fastest = knots.iter().map(|k| k[2]).fold(0.0, f64::max);
5138        assert!((fastest - 0.928318).abs() < 5e-3, "{fastest} m/s");
5139    }
5140
5141    /// A turn about one axis (from no turn to (0.075, 0.075, 0.1) rad, or on along that axis) does not bend its rotation
5142    /// vector: turns about one axis add, so it runs along the straight line, at the line's rate, with no second
5143    /// derivative. Its differences had a bend of rounding (2e-8 rad/m^2), and the time-optimal plan gave such a piece
5144    /// 0.4 of its axes' jerk; a turn that changes its axis still bends.
5145    #[test]
5146    fn a_turn_about_one_axis_does_not_bend_its_rotation_vector() {
5147        let to = [0.04, 0.04, 0.43, 0.075, 0.075, 0.1];
5148        let length = to.iter().map(|v| v * v).sum::<f64>().sqrt();
5149        // From no turn, from a level pose to the rounding (as a previous piece ends at it), and from along the axis.
5150        for from in [vec![0.0; 6], vec![0.0, 0.0, 0.0, 1e-17, -2e-17, 0.0], vec![0.0, 0.0, 0.0, 0.03, 0.03, 0.04]] {
5151            let piece = Geo::Slerp { from: from.clone(), to: to.to_vec(), length, at: 3 };
5152            for s in [0.0, 0.3 * length, length] {
5153                let [pose, d1, d2] = piece.at(s);
5154                for i in 3..6 {
5155                    let line = from[i] + (to[i] - from[i]) * s / length;
5156                    assert!((pose[i] - line).abs() < 1e-15 && d2[i] == 0.0, "{s}: {pose:?} {d2:?}");
5157                    assert!((d1[i] - (to[i] - from[i]) / length).abs() < 1e-15, "{d1:?}");
5158                }
5159            }
5160        }
5161        let turning = Geo::Slerp { from: vec![0.0, 0.0, 0.0, 0.3, 0.0, 0.0], to: to.to_vec(), length, at: 3 };
5162        assert!(turning.at(0.5 * length)[2][3..].iter().any(|v| v.abs() > 1e-3));
5163    }
5164
5165    /// The angle (rad) between two orientations given as rotation vectors: 2 acos |q . q'| for their quaternions.
5166    fn angle_between(a: &[f64], b: &[f64]) -> f64 {
5167        let (qa, qb) = (crate::rigid::quaternion([a[0], a[1], a[2]]), crate::rigid::quaternion([b[0], b[1], b[2]]));
5168        2.0 * qa.iter().zip(qb).map(|(x, y)| x * y).sum::<f64>().abs().clamp(0.0, 1.0).acos()
5169    }
5170
5171    /// An arc in tool space whose orientation turns from (1.2, 0, 0) to (0, 1.0, 0.8) rad, about an axis that changes
5172    /// per component of the rotation vector: by slerp the tool turns about one fixed axis at an even rate, so the angle
5173    /// between its orientations at equal distances along the arc is the same all along it (a quarter circle of radius
5174    /// 0.1 m, 10 steps). Evenly per component of the rotation vector it would differ between the steps (by 1e-6 of a
5175    /// step for small turns such as (0.3, 0, 0) to (0, 0.8, 0.5); more for these).
5176    #[test]
5177    fn a_tool_space_arc_turns_the_tool_at_an_even_rate() {
5178        let (from, to) = ([0.1, 0.0, 0.0, 1.2, 0.0, 0.0], [0.0, 0.1, 0.0, 0.0, 1.0, 0.8]);
5179        let Some(Geo::Carried { arc, from: tail, by, length, .. }) = arc_on(&from, &to, &[0.0; 3], false, None) else {
5180            panic!("an arc")
5181        };
5182        let arm = Geo::Carried { arc, from: tail, by, length, turn: Some(0) };
5183        let steps: Vec<f64> = (0..10)
5184            .map(|k| {
5185                angle_between(
5186                    &arm.at(length * k as f64 / 10.0)[0][3..],
5187                    &arm.at(length * (k + 1) as f64 / 10.0)[0][3..],
5188                )
5189            })
5190            .collect();
5191        let whole = angle_between(&from[3..], &to[3..]);
5192        for step in &steps {
5193            assert!((step - whole / 10.0).abs() < 1e-9, "{steps:?} against {}", whole / 10.0);
5194        }
5195        // Per component it is not even.
5196        let mut line = arm.clone();
5197        if let Geo::Carried { turn, .. } = &mut line {
5198            *turn = None;
5199        }
5200        let uneven: Vec<f64> = (0..10)
5201            .map(|k| {
5202                angle_between(
5203                    &line.at(length * k as f64 / 10.0)[0][3..],
5204                    &line.at(length * (k + 1) as f64 / 10.0)[0][3..],
5205                )
5206            })
5207            .collect();
5208        assert!(uneven.iter().any(|s| (s - whole / 10.0).abs() > 1e-4), "{uneven:?}");
5209    }
5210
5211    /// The axis-rate rows of a slerp take its real rates: from the rotation vector (0.5, 0, 0) to (0, 0.9, 0.3), the
5212    /// largest rate of each component per distance along the piece is found by 20 001 central differences of the slerp
5213    /// (`rigid::slerp`, the quaternion formula of Shoemake), and `limits` gives the limit 1 over it for a row along that
5214    /// component, within 1e-4.
5215    #[test]
5216    fn a_slerps_axis_rate_rows_take_the_largest_rate_along_it() {
5217        let (from, to) = ([0.0, 0.0, 0.0, 0.5, 0.0, 0.0], [0.1, 0.0, 0.0, 0.0, 0.9, 0.3]);
5218        let length = from.iter().zip(&to).map(|(f, t)| (t - f) * (t - f)).sum::<f64>().sqrt();
5219        let piece = Geo::Slerp { from: from.to_vec(), to: to.to_vec(), length, at: 3 };
5220        for axis in 3..6 {
5221            let row: Vec<f64> = (0..6).map(|k| (k == axis) as u8 as f64).collect();
5222            // The speed row alone: the bend's own caps (`sampled`) out of the way.
5223            let bounds: [Bounds; 3] = [vec![(row.clone(), 1.0)], vec![(row.clone(), 1e9)], vec![(row, 1e9)]];
5224            let h = 1e-6;
5225            let rate = |t: f64| {
5226                let at = |t: f64| crate::rigid::slerp([0.5, 0.0, 0.0], [0.0, 0.9, 0.3], t)[axis - 3];
5227                (at(t + h) - at(t - h)) / (2.0 * h) / length
5228            };
5229            let most = (0..=20_000).map(|k| rate(k as f64 / 20_000.0).abs()).fold(0.0, f64::max);
5230            let [v, ..] = limits(&piece, &bounds);
5231            assert!((v * most - 1.0).abs() < 1e-4, "axis {axis}: {v} against {}", 1.0 / most);
5232        }
5233    }
5234
5235    /// The orientation's rates on a turning slerp are the closed form's: for three pairs of rotation vectors (one of 2.8
5236    /// rad turns, one of 0.03 rad where the series of the closed form takes over, one of 0.7 rad), at the
5237    /// ends and past them, `Geo::at`'s rates agree within 1e-9 (relative to the larger of 1 and the rate) with seven-point
5238    /// central differences of its own pose over 2 % of the piece. The place's axes keep their even rate and no bend.
5239    #[test]
5240    fn a_slerps_orientation_rates_are_the_closed_forms() {
5241        let cases = [
5242            ([0.0, 0.0, 0.0, 2.0, 0.5, -0.4], [0.1, 0.0, 0.0, -1.0, 0.8, 1.3]),
5243            ([0.0, 0.0, 0.0, 0.01, 0.02, 0.0], [0.1, 0.0, 0.0, 0.0, 0.01, 0.03]),
5244            ([0.0, 0.0, 0.0, 0.3, -0.2, 0.1], [0.1, 0.0, 0.0, -0.2, 0.3, 0.5]),
5245        ];
5246        for (from, to) in cases {
5247            let length = from.iter().zip(&to).map(|(f, t)| (t - f) * (t - f)).sum::<f64>().sqrt();
5248            let piece = Geo::Slerp { from: from.to_vec(), to: to.to_vec(), length, at: 3 };
5249            let h = 0.02;
5250            for share in [0.0, 0.3, 1.0, -0.05, 1.04] {
5251                let pose = |k: f64| piece.at((share + k * h) * length).into_iter().next().unwrap();
5252                let p: Vec<Vec<f64>> = (-3..=3).map(|k| pose(k as f64)).collect();
5253                let [_, first, second] = piece.at(share * length);
5254                let by_1 = [-1.0 / 60.0, 3.0 / 20.0, -0.75, 0.0, 0.75, -3.0 / 20.0, 1.0 / 60.0];
5255                let by_2 = [1.0 / 90.0, -3.0 / 20.0, 1.5, -49.0 / 18.0, 1.5, -3.0 / 20.0, 1.0 / 90.0];
5256                let rate = |i: usize| (0..7).map(|k| by_1[k] * p[k][i]).sum::<f64>() / (h * length);
5257                let bend = |i: usize| (0..7).map(|k| by_2[k] * p[k][i]).sum::<f64>() / (h * h * length * length);
5258                // The vector's own size is the scale: a small component of a large rate has the vector's absolute error.
5259                let size = |f: &dyn Fn(usize) -> f64| (3..6).map(|i| f(i).abs()).fold(1.0, f64::max);
5260                let (big_rate, big_bend) = (size(&rate), size(&bend));
5261                for i in 3..6 {
5262                    assert!(
5263                        (first[i] - rate(i)).abs() < 1e-9 * big_rate,
5264                        "rate {i} at {share}: {} to {}",
5265                        first[i],
5266                        rate(i)
5267                    );
5268                    assert!(
5269                        (second[i] - bend(i)).abs() < 1e-9 * big_bend,
5270                        "bend {i} at {share}: {} to {}",
5271                        second[i],
5272                        bend(i)
5273                    );
5274                }
5275                for i in 0..3 {
5276                    assert_eq!((first[i], second[i]), ((to[i] - from[i]) / length, 0.0));
5277                }
5278            }
5279        }
5280    }
5281
5282    /// A tool-space line from the orientation (3, 0, 0) to (0, 0, 1) rad (and 10 mm), planned within the axis limits
5283    /// (rotation axes 3 rad/s, 5 rad/s^2, 1e4 rad/s^3): its slerp bends its rotation vector by up to 0.375 per rad, which
5284    /// at 2.5 rad/s along it is 2.3 rad/s^2 beside the ramps'. Read from the plan's poses (second differences over 1 ms,
5285    /// independent of `limits`), no rotation axis goes beyond its 5 rad/s^2 (measured 4.68); with the bend left out (P2
5286    /// = P3 = 0 in `sampled`, the chord's rule) the plan reached 5.27 rad/s^2.
5287    #[test]
5288    fn a_slerp_planned_within_the_axis_limits_keeps_its_axes_accelerations() {
5289        let axis = |id: &'static str, rotation: bool| AxisInfo {
5290            id,
5291            key: "",
5292            unit: "",
5293            min: -10.0,
5294            max: 10.0,
5295            max_vel: if rotation { 3.0 } else { 10.0 },
5296            max_acc: if rotation { 5.0 } else { 1e3 },
5297            max_jerk: if rotation { 1e4 } else { 1e6 },
5298        };
5299        let axes = [
5300            axis("x", false),
5301            axis("y", false),
5302            axis("z", false),
5303            axis("rx", true),
5304            axis("ry", true),
5305            axis("rz", true),
5306        ];
5307        let start = [0.0, 0.0, 0.0, 3.0, 0.0, 0.0];
5308        let points =
5309            plan(&axes, &start, &[Piece::Line(vec![0.01, 0.0, 0.0, 0.0, 0.0, 1.0])], 1e-3, 0.0, ARC_SLACK).unwrap();
5310        let worst = points
5311            .windows(3)
5312            .map(|w| (3..6).map(|i| (w[2].1[i] - 2.0 * w[1].1[i] + w[0].1[i]).abs() / 1e-6).fold(0.0, f64::max))
5313            .fold(0.0, f64::max);
5314        assert!(worst <= 5.0 * (1.0 + 1e-6), "{worst} rad/s^2");
5315    }
5316
5317    /// A table of 1 kg on two linear axes, each driven by a motor through a pinion of 10 mm (100 rad per m): the motor's
5318    /// torque per acceleration is 0.01 N m per m/s^2.
5319    struct Table {
5320        axes: [AxisInfo; 2],
5321        motors: [sim_core::MotorInfo; 2],
5322        /// The load's frequency of the drive trains (Hz) at x < 0 and at x >= 0; 0: rigid.
5323        train_hz: [f64; 2],
5324    }
5325
5326    impl Machine for Table {
5327        fn axes(&self) -> &[AxisInfo] {
5328            &self.axes
5329        }
5330        fn motors(&self) -> &[sim_core::MotorInfo] {
5331            &self.motors
5332        }
5333        fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
5334            (motors[0], motors[1]) = (tool[0] / 0.01, tool[1] / 0.01);
5335        }
5336        fn forward(&self, motors: &[f64], tool: &mut [f64]) {
5337            (tool[0], tool[1]) = (motors[0] * 0.01, motors[1] * 0.01);
5338        }
5339        fn state_len(&self) -> usize {
5340            4
5341        }
5342        fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
5343            *state = vec![tool[0], tool[1], 0.0, 0.0];
5344            torque.fill(0.0);
5345        }
5346        fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
5347            out.copy_from_slice(&[s[2], s[3], torque[0] / 0.01, torque[1] / 0.01]);
5348        }
5349        fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
5350            pos.copy_from_slice(&s[..2]);
5351            vel.copy_from_slice(&s[2..]);
5352        }
5353        fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
5354            s[2..].copy_from_slice(vel);
5355        }
5356        fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
5357            (pos[0], pos[1], vel[0], vel[1]) = (s[0] / 0.01, s[1] / 0.01, s[2] / 0.01, s[3] / 0.01);
5358        }
5359        fn feedforward_torque(&self, _: &[f64], acc: &[f64], out: &mut [f64]) {
5360            (out[0], out[1]) = (acc[0] * 0.01, acc[1] * 0.01);
5361        }
5362        fn energy(&self, s: &[f64]) -> f64 {
5363            0.5 * (s[2] * s[2] + s[3] * s[3])
5364        }
5365        fn trains(&self, pose: &[f64]) -> Vec<Option<sim_core::Train>> {
5366            let hz = self.train_hz[(pose[0] >= 0.0) as usize];
5367            vec![(hz > 0.0).then_some(sim_core::Train { hz, load_share: 0.5 }); 2]
5368        }
5369        fn set_payload_attached(&mut self, _: bool) {}
5370        fn signal_infos(&self) -> Vec<sim_core::SignalInfo> {
5371            Vec::new()
5372        }
5373        fn base_signals(&self, _: &[f64], _: &[f64], _: &mut Vec<f64>) {}
5374        fn scene(&self, _: &[f64], _: &mut sim_core::Scene) {}
5375    }
5376
5377    /// The share kept back of the speed ratings is the one of the place's own pose (`PlanLimits::kept_at`), not the
5378    /// start's. On the `Table` the motors' inertia is J = 1e-4 kg m^2 (0.01 N m per m/s^2 over 100 rad per m, twice),
5379    /// their peak torque 3.8 N m, so a = 3.8 / 1e-4 = 38000 rad/s^2; the loops' precontrol is full (the loop's own share
5380    /// is the least, 0.01), the jerk limit far quicker than the trains' swing, so each adds the swing after a step of a:
5381    /// s a / (w sqrt(1 - s)) with s = 0.5, w = 2 pi f, over the top speed 400 rad/s. A train of 30 Hz on the left and
5382    /// 60 Hz on the right: 142.56 rad/s, 0.3564 and so 0.3664 kept back on the left; 71.28 rad/s, 0.1782 and 0.1882 on
5383    /// the right (with the start pose's share, taken at x = 0.1 on the right, the left would keep 0.1882 back).
5384    #[test]
5385    fn the_share_kept_back_is_taken_at_the_place_not_the_start() {
5386        let axis =
5387            |id| AxisInfo { id, key: "", unit: "m", min: -1.0, max: 1.0, max_vel: 10.0, max_acc: 1e4, max_jerk: 1e12 };
5388        let motor = |id| sim_core::MotorInfo { id, key: "" };
5389        let table = Table { axes: [axis("x"), axis("y")], motors: [motor("a"), motor("b")], train_hz: [30.0, 60.0] };
5390        let mut plan = PlanLimits::new(1.0, [0.0; 3]);
5391        plan.loops = vec![LoopKeep { ki: 100.0, torque_ff: 1.0, peak_torque: 3.8, max_speed: 400.0 }; 2];
5392        let by_hand = |hz: f64| {
5393            let w = std::f64::consts::TAU * hz;
5394            SPEED_KEPT + 0.5 * 38000.0 / (w * 0.5_f64.sqrt()) / 400.0
5395        };
5396        for (x, hz) in [(-0.1, 30.0), (0.1, 60.0)] {
5397            let kept = plan.kept_at(&table, &[x, 0.0]);
5398            assert!((kept / by_hand(hz) - 1.0).abs() < 1e-4, "x = {x}: {kept} against {} by hand", by_hand(hz));
5399        }
5400        assert!((by_hand(30.0) - 0.3664).abs() < 1e-4 && (by_hand(60.0) - 0.1882).abs() < 1e-4);
5401    }
5402
5403    /// The transition curves are sized with the motors' torque at the speed the piece runs at (`motor_limits`). On the
5404    /// `Table` a half circle of r = 0.05 m from the bottom, ccw, turns each motor at up to 100 v; the arc's speed is
5405    /// sqrt(0.8 a r) (`curved`) with a = T(100 v) / 0.01 for the motor's torque T, 3.8 N m up to 314 rad/s and falling
5406    /// to 0 at 420 (the test drive). With the whole torque that is sqrt(0.8 * 0.05 * 380) = 3.899 m/s, 390 rad/s, on the
5407    /// falling part: there 106 v^2 = 15.2 (420 - 100 v), v = 3.3958 m/s (340 rad/s). Without the fall (no-load speed
5408    /// far up) it is 3.899.
5409    #[test]
5410    fn the_transition_speed_takes_the_motors_torque_at_the_speed_it_runs_at() {
5411        let axis =
5412            |id| AxisInfo { id, key: "", unit: "m", min: -1.0, max: 1.0, max_vel: 10.0, max_acc: 1e4, max_jerk: 1e12 };
5413        let motor = |id| sim_core::MotorInfo { id, key: "" };
5414        let table = Table { axes: [axis("x"), axis("y")], motors: [motor("a"), motor("b")], train_hz: [0.0, 0.0] };
5415        let r = 0.05;
5416        let arc = Geo::Arc {
5417            centre: [0.0, 0.0],
5418            radius: r,
5419            from_angle: -std::f64::consts::FRAC_PI_2,
5420            turn: 1.0,
5421            length: std::f64::consts::PI * r,
5422        };
5423        let plan = PlanLimits::new(1.0, [0.0; 3]);
5424        let speed = |drive: &DriveParams| {
5425            let drives = [drive, drive];
5426            motor_limits(&table, &drives, &plan, [f64::NEG_INFINITY, f64::INFINITY, 1.0])(&arc)[0]
5427        };
5428        let falling = crate::drive::tests::params();
5429        let hand = (-1520.0 + (1520.0_f64.powi(2) + 4.0 * 106.0 * 6384.0).sqrt()) / 212.0;
5430        assert!((speed(&falling) - hand).abs() < 1e-9, "{} against {hand} m/s", speed(&falling));
5431        let level = DriveParams { rated_speed: 1e4, no_load_speed: 2e4, max_speed: 1e4, ..falling.clone() };
5432        assert!((speed(&level) - 15.2_f64.sqrt()).abs() < 1e-9, "{} m/s", speed(&level));
5433    }
5434
5435    /// Tops that fit in two ranges, [0, 1] and [4, 5] (a speed curve with two humps and a dip between them), are found in
5436    /// the higher range: 5, where the halving from 0 alone settles at 1 (its first try, 3, does not fit); with one range
5437    /// the result is the same as the halving's.
5438    #[test]
5439    fn the_highest_fitting_top_is_searched_in_every_range() {
5440        let two = |x: f64| x <= 1.0 || (4.0..=5.0).contains(&x);
5441        assert!((highest_fitting_scan(0.0, 6.0, two) - 5.0).abs() < 1e-8);
5442        assert!((highest_fitting(0.0, 6.0, two) - 1.0).abs() < 1e-8);
5443        let one = |x: f64| x <= 2.5;
5444        assert!((highest_fitting_scan(0.0, 6.0, one) - highest_fitting(0.0, 6.0, one)).abs() < 1e-8);
5445        assert_eq!(highest_fitting_scan(0.0, 2.0, one), 2.0);
5446    }
5447
5448    /// The speed curve a piece follows around a slow place. With a jerk too high to matter, the squared speed may change
5449    /// by 2 * 0.01 m * 0.9 * 10 m/s^2 = 0.18 m^2/s^2 from place to place, so from the dip's 0.25 it rises 0.43, 0.61,
5450    /// 0.79, 0.97 to the tops' 1 on either side. With 50 m/s^3 the bends hold too: |x'' spacing^2| <= 2 * 0.5 * 50 *
5451    /// 0.01^2 / v, never above a top, never below the dip.
5452    #[test]
5453    fn the_speed_curve_comes_down_to_a_slow_place_within_its_acceleration_and_jerk() {
5454        let (_, x) = dip(1e9);
5455        for (i, want) in [0.25, 0.43, 0.61, 0.79, 0.97, 1.0, 1.0].iter().enumerate() {
5456            assert!((x[20 + i] - want).abs() < 1e-12 && (x[20 - i] - want).abs() < 1e-12, "{i}: {x:?}");
5457        }
5458        let (places, x) = dip(50.0);
5459        let lowest = x.iter().fold(f64::INFINITY, |a: f64, b| a.min(*b));
5460        assert!((lowest - 0.25).abs() < 1e-12 && x.iter().zip(&places).all(|(x, p)| *x <= p.top * p.top), "{x:?}");
5461        for k in 1..40 {
5462            let bend = (x[k - 1] + x[k + 1] - 2.0 * x[k]).abs() * x[k].sqrt() / (2.0 * 0.5 * 50.0 * 1e-4);
5463            let slope = (x[k + 1] - x[k]).abs() / (2.0 * 0.01 * 0.9 * 10.0);
5464            assert!(bend <= 1.0 + 1e-4 && slope <= 1.0 + 1e-9, "at {k}: bend {bend}, slope {slope}, {x:?}");
5465        }
5466        // The jerk makes the dip wider than the acceleration alone: the curve is lower beside it.
5467        assert!(x[21] < 0.43 - 0.01 && x[24] < 0.97, "{x:?}");
5468    }
5469
5470    /// A right-angled corner rounded within a tolerance e of 1 mm (`round_corners`): the curve's middle is 3 d sin(90°) /
5471    /// 16 = 3 d / 16 off each line, so d = 16 e / 3 = 5.333 mm, and there it turns at a radius of sqrt(2) d / 3 = 16
5472    /// sqrt(2) e / 9 = 2.514 mm (`corner_curve`: moving at (ta + tb) / 2, |.| = 1 / sqrt(2), turning at 3 (tb - ta) /
5473    /// (4 d), |.| = 3 sqrt(2) / (4 d), at right angles: k = 3 sqrt(2) / (2 d)). The lines are cut back by d, the planned
5474    /// path keeps within the tolerance of the two lines and no longer stops at the corner.
5475    #[test]
5476    fn a_right_angled_corner_is_rounded_within_the_tolerance_at_the_hand_calculated_radius() {
5477        let (axes, start, e) = (axes(), [0.1, 0.1], 1e-3);
5478        let pieces = parse("line,0.5,0.1\nline,0.5,0.5").unwrap();
5479        let rounded = Tolerance { path: 0.0, corner: e };
5480        let (geo, reported) = geometry(&axes, &start, &pieces, rounded, &axis_speed(&axes), ARC_SLACK).unwrap();
5481        let (d, radius) = (16.0 * e / 3.0, 16.0 * 2f64.sqrt() * e / 9.0);
5482        assert!((d - 5.3333e-3).abs() < 1e-7 && (radius - 2.5142e-3).abs() < 1e-7);
5483        assert!((reported - e).abs() < 1e-12, "{reported} m reported");
5484        let [Geo::Line { length: first, .. }, curve @ Geo::Spline { .. }, Geo::Line { from, length: last, .. }] =
5485            &geo[..]
5486        else {
5487            panic!("a line, the corner's curve and a line");
5488        };
5489        assert!((first - (0.4 - d)).abs() < 1e-12 && (last - (0.4 - d)).abs() < 1e-12, "{first} m, {last} m");
5490        let ([begin, ..], [end, ..]) = (curve.at(0.0), curve.at(curve.length()));
5491        assert!(distance(&begin, &[0.5 - d, 0.1]) < 1e-12 && distance(&end, from) < 1e-12, "{begin:?} {end:?}");
5492        let [middle, _, turning] = curve.at(0.5 * curve.length());
5493        let off = (0.5 - middle[0]).min(middle[1] - 0.1);
5494        assert!((off - e).abs() < 1e-12 && (1.0 / norm(&turning) - radius).abs() < 1e-9, "{off} m, {turning:?}");
5495        // Planned within the axis limits: never off the two lines by more than the tolerance, and moving at every
5496        // cycle between its start and its end; stopped at the corner, one cycle moves the tool by a few 1e-8 m only.
5497        let step = |points: &[(f64, Vec<f64>)]| {
5498            points[5..points.len() - 5].windows(2).map(|w| distance(&w[0].1, &w[1].1)).fold(f64::INFINITY, f64::min)
5499        };
5500        let points = plan(&axes, &start, &pieces, 1e-3, rounded, ARC_SLACK).unwrap();
5501        let furthest = points.iter().map(|(_, p)| (0.5 - p[0]).min(p[1] - 0.1).max(0.0)).fold(0.0, f64::max);
5502        let stopped = plan(&axes, &start, &pieces, 1e-3, 0.0, ARC_SLACK).unwrap();
5503        assert!(furthest <= e * (1.0 + 1e-9) && step(&points) > 1e-6 && step(&stopped) < 1e-7, "{furthest} m off");
5504    }
5505
5506    /// An arc on four axes: on the first three a quarter circle of 0.1 m from +x to +y (L = 0.05 pi = 0.15708 m), and the
5507    /// fourth (a turn) carried from 0 to 1 rad evenly with the distance along it. The piece counts the distance on all
5508    /// four, sqrt(L^2 + 1^2) = 1.01226, so at a share w of it the arc is at the angle w pi / 2 and the fourth axis at w:
5509    /// the fourth axis is linear in the arc's length. The direction has length 1, as on a line.
5510    #[test]
5511    fn a_four_axis_arc_keeps_its_fourth_axis_linear_in_the_arc_length() {
5512        let pieces = parse("arc,0.0,0.1,0.0,1.0,0.0,0.0,0.0,ccw").unwrap();
5513        assert_eq!(
5514            pieces[0],
5515            Piece::Arc { to: vec![0.0, 0.1, 0.0, 1.0], centre: vec![0.0; 3], clockwise: false, plane: None }
5516        );
5517        let (geo, off) = given(&[0.1, 0.0, 0.0, 0.0], &pieces, ARC_SLACK).unwrap();
5518        let length = (0.05f64 * std::f64::consts::PI).hypot(1.0);
5519        assert!((length - 1.01226).abs() < 1e-5 && (geo[0].length() - length).abs() < 1e-12 && off < 1e-12);
5520        for k in 0..=8 {
5521            let w = k as f64 / 8.0;
5522            let [pose, dir, _] = geo[0].at(w * length);
5523            let angle = pose[1].atan2(pose[0]);
5524            assert!(
5525                (angle - w * std::f64::consts::FRAC_PI_2).abs() < 1e-12
5526                    && (pose[0].hypot(pose[1]) - 0.1).abs() < 1e-12
5527                    && pose[2].abs() < 1e-12
5528                    && (pose[3] - w).abs() < 1e-12
5529                    && (norm(&dir) - 1.0).abs() < 1e-12,
5530                "at {w}: {pose:?} {dir:?}"
5531            );
5532        }
5533        // Planned within the limits of four axes, it ends where it was given.
5534        let axis =
5535            AxisInfo { id: "", key: "", unit: "m", min: -1.0, max: 2.0, max_vel: 1.0, max_acc: 10.0, max_jerk: 100.0 };
5536        let points = plan(
5537            &[axis.clone(), axis.clone(), axis.clone(), axis],
5538            &[0.1, 0.0, 0.0, 0.0],
5539            &pieces,
5540            1e-3,
5541            0.0,
5542            ARC_SLACK,
5543        )
5544        .unwrap();
5545        assert!(distance(&points[points.len() - 1].1, &[0.0, 0.1, 0.0, 1.0]) < 1e-12);
5546    }
5547
5548    /// A half turn on three axes lies in the plane its piece states: from (0.1, 0, 0) to (-0.1, 0, 0) around the origin,
5549    /// counter-clockwise, a normal along y (seen from -y, as the path reads x-z) goes through (0, 0, 0.1) at half way
5550    /// (u = e_x, w = n x u = (0, -1, 0) x (1, 0, 0) = (0, 0, 1)), a normal along z through (0, 0.1, 0), which is also what
5551    /// the plane left out gives (the first plane holding the start's radius); a normal the start's radius is not at right
5552    /// angles to (z for a start at (0, 0, 0.1)) is no plane for it.
5553    #[test]
5554    fn a_half_turn_takes_the_plane_its_piece_states() {
5555        let half = |plane| {
5556            let pieces = [Piece::Arc { to: vec![-0.1, 0.0, 0.0], centre: vec![0.0; 3], clockwise: false, plane }];
5557            given(&[0.1, 0.0, 0.0], &pieces, ARC_SLACK).map(|(geo, _)| geo[0].at(geo[0].length() / 2.0)[0].clone())
5558        };
5559        let near = |p: Vec<f64>, q: [f64; 3]| distance(&p, &q) < 1e-12;
5560        assert!(near(half(Some([0.0, 1.0, 0.0])).unwrap(), [0.0, 0.0, 0.1]));
5561        assert!(near(half(Some([0.0, 0.0, 1.0])).unwrap(), [0.0, 0.1, 0.0]));
5562        assert!(near(half(None).unwrap(), [0.0, 0.1, 0.0]));
5563        let up = [Piece::Arc {
5564            to: vec![0.0, 0.0, -0.1],
5565            centre: vec![0.0; 3],
5566            clockwise: false,
5567            plane: Some([0.0, 0.0, 1.0]),
5568        }];
5569        assert!(given(&[0.0, 0.0, 0.1], &up, ARC_SLACK).is_err());
5570    }
5571
5572    /// Places of a made-up piece of `count` + 1 places: an acceleration limit of 10 m/s^2 and the top speed `top` per
5573    /// share of the piece; with a jerk along the path of 1000 m/s^3.
5574    fn made_up(length: f64, count: usize, top: impl Fn(f64) -> f64) -> PieceLimits {
5575        let places = (0..=count)
5576            .map(|k| Place {
5577                rows: vec![[1.0, 0.0, 0.0, -10.0, 10.0]],
5578                low: Vec::new(),
5579                turn: Vec::new(),
5580                curves: Arc::from([]),
5581                guide: Vec::new(),
5582                speed: Vec::new(),
5583                bends: Vec::new(),
5584                top: top(k as f64 / count as f64),
5585                scale: 1.0,
5586            })
5587            .collect();
5588        piece_limits_of(places, length / count as f64, 1000.0).unwrap()
5589    }
5590
5591    /// Two arcs that meet in their direction, of 0.2 m and 0.1 m radius turning the same way: at the junction the
5592    /// curvature steps by 1 / 0.1 - 1 / 0.2 = 5 1/m across the path (along x), and over a profile cycle of 1 ms half the
5593    /// x axis's jerk limit of 100 m/s^3 allows v^2 * 5 = 0.5 * 100 * 1e-3, v = 0.1 m/s (`junction_speed`). The arcs' places
5594    /// allow 2 m/s, but for the far end of the second arc, which allows 0.05 m/s: the junction is passed at the 0.1 m/s
5595    /// the junction itself allows, no longer at the 0.05 m/s of the slowest place of either piece.
5596    #[test]
5597    fn the_junction_of_two_arcs_is_passed_at_the_hand_calculated_speed() {
5598        use std::f64::consts::{FRAC_PI_2, PI};
5599        let wide = Geo::Arc { centre: [0.0, 0.0], radius: 0.2, from_angle: -FRAC_PI_2, turn: 1.0, length: 0.1 * PI };
5600        let tight = Geo::Arc { centre: [0.1, 0.0], radius: 0.1, from_angle: 0.0, turn: 1.0, length: 0.05 * PI };
5601        assert!(distance(&wide.at(wide.length())[0], &tight.at(0.0)[0]) < 1e-12);
5602        let geo = [wide, tight];
5603        let limits = [made_up(0.1 * PI, 40, |_| 2.0), made_up(0.05 * PI, 40, |w| if w < 0.5 { 2.0 } else { 0.05 })];
5604        let by_hand = (0.5f64 * 100.0 * 1e-3 / 5.0).sqrt();
5605        assert!((junction_speed(&geo[0], &geo[1], &axes(), 1e-3) - by_hand).abs() < 1e-15);
5606        let speed = junction_speeds(&axes(), &geo, &limits, 1e-3, true);
5607        let before = junction_speeds(&axes(), &geo, &limits, 1e-3, false);
5608        assert!((speed[1] - 0.1).abs() < 1e-12 && (before[1] - 0.05).abs() < 1e-12, "{speed:?}, before {before:?}");
5609        // And the plan runs: each piece is timed from that speed to the next.
5610        for i in 0..2 {
5611            piece_knots(&limits[i], geo[i].length(), [speed[i], speed[i + 1]], 1e-3, true).unwrap();
5612        }
5613    }
5614
5615    /// A line at up to 1 m/s into a second line whose places allow 1 m/s at its start, falling evenly to 0.3 m/s at its
5616    /// end, from rest to rest. Joined on a cruise at no acceleration (and the junction no faster than the slowest place
5617    /// of either piece, 0.3 m/s) the second line is crossed at 0.3 m/s; joined on the speed curve the plan slows down
5618    /// along the curve and is quicker.
5619    #[test]
5620    fn a_path_without_the_forced_cruise_is_quicker_than_with_it() {
5621        let line = |x0: f64| Geo::Line { from: vec![x0, 0.1], dir: vec![1.0, 0.0], length: 0.5 };
5622        let geo = [line(0.0), line(0.5)];
5623        let limits = [made_up(0.5, 50, |_| 1.0), made_up(0.5, 50, |w| 1.0 - 0.7 * w)];
5624        let duration = |joins: bool| {
5625            let speed = junction_speeds(&axes(), &geo, &limits, 1e-3, joins);
5626            let pieces = (0..2).map(|i| piece_knots(&limits[i], 0.5, [speed[i], speed[i + 1]], 1e-3, joins).unwrap());
5627            (speed[1], pieces.map(|k| k[k.len() - 1][0]).sum::<f64>())
5628        };
5629        let ((joined, quick), (cruised, slow)) = (duration(true), duration(false));
5630        assert!(
5631            (cruised - 0.3).abs() < 1e-9 && joined > 0.9 && quick < slow - 0.05,
5632            "{joined} m/s {quick} s against {cruised} m/s {slow} s"
5633        );
5634    }
5635
5636    /// Where the run from the start meets the run from the end at a peak of speed, the plan switches from one to the other
5637    /// at the same place and speed: each span between its knots, a cubic at constant jerk, ends on the next knot's
5638    /// distance and speed. A line on which the motors accelerate at up to 2 m/s^2 and brake at up to 5 m/s^2, with a jerk
5639    /// of 1e5 m/s^3 along it (the ramps take 0.05 ms, less than a step of 0.25 ms) and a top speed it does not reach, from
5640    /// rest to rest, over lengths 0.30 to 0.70 m. Before 21 November the switch was the rise's knot past the meeting and
5641    /// a cubic from it to the fall's next knot, which ended short of that knot's speed by the step of the acceleration
5642    /// times half its span (up to 7 m/s^2 times 0.12 ms, 9e-4 m/s): a step in the speed the profile cycle reads as an
5643    /// acceleration beyond the ceiling.
5644    #[test]
5645    fn the_runs_meet_at_the_same_place_and_speed() {
5646        let (mut joined, mut worst) = (0, 0.0f64);
5647        for k in 0..=40 {
5648            let length = 0.3 + 0.01 * k as f64;
5649            let count = 100;
5650            let places = (0..=count)
5651                .map(|_| Place {
5652                    rows: vec![[1.0, 0.0, 0.0, -5.0, 2.0]],
5653                    low: Vec::new(),
5654                    turn: Vec::new(),
5655                    curves: Arc::from([]),
5656                    guide: Vec::new(),
5657                    speed: Vec::new(),
5658                    bends: Vec::new(),
5659                    top: 10.0,
5660                    scale: 1.0,
5661                })
5662                .collect();
5663            let limits = piece_limits_of(places, length / count as f64, 1e5).unwrap();
5664            let Some(knots) = curve_join(&limits, length, [0.0, 0.0], 2e-3, 1e-3 / STEPS_PER_CYCLE) else { continue };
5665            joined += 1;
5666            for pair in knots.windows(2) {
5667                let ([t0, s0, v0, a0], [t1, s1, v1, a1]) = (pair[0], pair[1]);
5668                let h = t1 - t0;
5669                let jerk = if h > 0.0 { (a1 - a0) / h } else { 0.0 };
5670                let (s, v) =
5671                    (s0 + v0 * h + a0 * h * h / 2.0 + jerk * h.powi(3) / 6.0, v0 + a0 * h + jerk * h * h / 2.0);
5672                // (The last knot is set onto the piece's end.)
5673                if t1 < knots[knots.len() - 1][0] {
5674                    worst = worst.max((s - s1).abs() / 1e-12).max((v - v1).abs() / 1e-9);
5675                }
5676            }
5677        }
5678        assert!(joined > 10 && worst <= 1.0, "{joined} joined, worst {worst} of the rounding");
5679    }
5680
5681    /// The lowest of a range of values from the table of lowest values over powers of two, against looking at each.
5682    #[test]
5683    fn the_lowest_over_a_range_is_the_lowest_of_its_values() {
5684        let values: Vec<f64> = (0..37).map(|k| ((k * 7919) % 101) as f64).collect();
5685        let table = lowest_ahead(&values);
5686        for i in 0..values.len() {
5687            for j in i..values.len() {
5688                let size = (usize::BITS - 1 - (j - i + 1).leading_zeros()) as usize;
5689                let lowest = table[size][i].min(table[size][j + 1 - (1 << size)]);
5690                assert_eq!(lowest, values[i..=j].iter().fold(f64::INFINITY, |a, b| a.min(*b)), "{i}..={j}");
5691            }
5692        }
5693    }
5694
5695    /// The binormal jerk of a spline span: p(u) = (u, u^2, u^3) has d = (1, 0, 0), d2 = (0, 2, 0), d3 = (0, 0, 6) at u = 0, so
5696    /// n = d x d2 = (0, 0, 2), kappa = |n| / |d|^3 = 2, tau = n . d3 / |n|^2 = 12 / 4 = 3 and kappa tau = 6, the largest
5697    /// on the span (n . d3 is 12 everywhere and |d|^3 |n| only grows with u); a span on two axes has none.
5698    #[test]
5699    fn a_spline_span_knows_its_curvature_times_torsion() {
5700        let mut c: Poly = [[0.0; WIDEST]; 6];
5701        (c[1][0], c[2][1], c[3][2]) = (1.0, 1.0, 1.0);
5702        let Some(Geo::Spline { binormal, .. }) = span(c, 0.1, 3) else { panic!("a span") };
5703        assert!((binormal / (SPLINE_MARGIN * 6.0) - 1.0).abs() < 1e-9, "{binormal}, 6 by hand with the margin");
5704        c[3][2] = 0.0;
5705        let Some(Geo::Spline { binormal, .. }) = span(c, 0.1, 2) else { panic!("a span") };
5706        assert_eq!(binormal, 0.0);
5707    }
5708
5709    /// `curved` with kappa tau = 6 on a gentle curve (r = 1000 m) at a = 1000 m/s^2 and j = 100 m/s^3: the binormal's cap is
5710    /// v = (0.3 j / 6)^(1/3) = 5^(1/3) = 1.709976 m/s, where it uses g = 6 v^3 / j = 0.3 of the jerk and the others
5711    /// sqrt(1 - 0.3^2) = 0.953939 of theirs: the ramps 0.4 j 0.953939 = 38.1576 m/s^3. Without torsion the speed is
5712    /// the arc's alone (the cube root of 0.4 j r^2 = 341.99 m/s, below the 10 m/s the axes give: 10) and the ramps 0.4 j.
5713    #[test]
5714    fn torsion_takes_its_share_of_the_jerk_limit_on_a_spline() {
5715        let [v, _, ramps] = curved(1e3, 1e6, 0.0, 6.0, [10.0, 1e3, 100.0]);
5716        assert!((v - 5f64.cbrt()).abs() < 1e-12 && (ramps - 38.1576).abs() < 1e-3, "{v} m/s {ramps} m/s^3");
5717        let [v, _, ramps] = curved(1e3, 1e6, 0.0, 0.0, [10.0, 1e3, 100.0]);
5718        assert!(v == 10.0 && (ramps - 40.0).abs() < 1e-12, "{v} m/s {ramps} m/s^3");
5719    }
5720
5721    /// A motor behind a gearbox of efficiency 0.9 (the one-axis belt drive: its rotor 0.0075 N m per m/s^2, the load's 0.017 N m per
5722    /// m/s^2) with 0.4 N m to give either way: accelerating the load it gives 0.0075 + 0.017 / 0.9 = 0.026389 N m per
5723    /// m/s^2, so 0.4 / 0.026389 = 15.158 m/s^2; braking it the load drives the motor and it gives 0.0075 + 0.017 * 0.9 =
5724    /// 0.0228 N m per m/s^2 (negative), so 0.4 / 0.0228 = 17.544 m/s^2 (15.158 when braking took 1 / eta as well). The
5725    /// same with the motor turning backwards along the path (its row negative). Where the rotor's inertia outweighs the
5726    /// load (rotor 0.03 N m per m/s^2, the load pushing on with 0.4 N m): accelerating, the load's torque 0.017 a - 0.4 is
5727    /// below zero up to 23.5 m/s^2, so the load drives the motor and it gives 0.03 a + 0.9 (0.017 a - 0.4) = 0.0453 a - 0.36
5728    /// <= 0.4: 16.777 m/s^2. The 1 / eta form alone allowed 17.27 m/s^2, where the motor gives 0.4227 N m.
5729    #[test]
5730    fn a_motor_that_brakes_through_a_lossy_gearbox_gives_eta_and_not_one_over_eta_of_the_loads_torque() {
5731        let place = |sign: f64, rotor: f64, push: f64| Place {
5732            rows: vec![[sign * (rotor + 0.017 / 0.9), 0.0, -sign * push / 0.9, -0.4, 0.4]],
5733            low: vec![[sign * (rotor + 0.017 * 0.9), 0.0, -sign * push * 0.9]],
5734            turn: vec![sign],
5735            curves: Arc::from([MotorCurve { step: 1.0, motoring: vec![0.4; 2], braking: vec![0.4; 2], power: 1e9 }]),
5736            guide: Vec::new(),
5737            speed: Vec::new(),
5738            bends: Vec::new(),
5739            top: 1.0,
5740            scale: 1.0,
5741        };
5742        for sign in [1.0, -1.0] {
5743            let (up, down) = (place(sign, 0.0075, 0.0).most(1.0, 1.0), place(sign, 0.0075, 0.0).most(1.0, -1.0));
5744            assert!((up - 15.158).abs() < 1e-3 && (down - 17.544).abs() < 1e-3, "{sign}: {up} and {down} m/s^2");
5745        }
5746        let up = place(1.0, 0.03, 0.4).most(1.0, 1.0);
5747        assert!((up - 0.76 / 0.0453).abs() < 1e-9, "{up} m/s^2");
5748    }
5749
5750    /// The share of the speed the plan keeps back (`speed_kept_of`): a loop with J = 0.01 kg m^2 and ki = 100 N m/rad has
5751    /// w_n = sqrt(ki / J) = 100 rad/s; a ramp of 1000 rad/s^2 with half of its torque from the precontrol leaves a peak
5752    /// error of 0.5 * 1000 / 100 = 5 rad/s, 0.025 of a top speed of 200 rad/s. With all of it from the precontrol 0 is
5753    /// left, so the fixed share (0.01) stays; the most is 0.5.
5754    #[test]
5755    fn the_speed_kept_back_follows_the_velocity_loop() {
5756        assert!((speed_kept_of(100.0, 0.01, 0.5, 1000.0, 200.0, 0.0) - 0.025).abs() < 1e-12);
5757        assert_eq!(speed_kept_of(100.0, 0.01, 1.0, 1000.0, 200.0, 0.0), SPEED_KEPT);
5758        assert_eq!(speed_kept_of(100.0, 0.01, 0.0, 1e6, 200.0, 0.0), SPEED_KEPT_MOST);
5759        assert_eq!(PlanLimits::new(0.8, [0.0; 3]).speed_kept, SPEED_KEPT);
5760        // An elastic train's 4 rad/s on top: 0.01 + 4 / 200 = 0.03.
5761        assert!((speed_kept_of(100.0, 0.01, 1.0, 1000.0, 200.0, 4.0) - 0.03).abs() < 1e-12);
5762    }
5763
5764    /// The speed an elastic train adds (`train_speed`), by hand: rotor side J_m = 1e-4, load J_L = 3e-4 kg m^2 and
5765    /// k = 30 N m/rad give w^2 = k / J_L = 1e5 1/s^2 (50.33 Hz) and s = 0.75, so a jerk of 1e6 rad/s^3 puts the motor
5766    /// 0.75 * 1e6 / 1e5 = 7.5 rad/s ahead. Integrated (the motor's torque the rigid (J_m + J_L) a(t), a going 0 -> 1e5
5767    /// rad/s^2 at that jerk over 0.1 s, five swings, held, back to 0): the motor leads the common speed by 7.5 rad/s on
5768    /// average over the ramp's jerk phase, and by at most twice that in it. (Undamped, the swings of the ramp's two jerk
5769    /// phases add: 17.8 rad/s after the second; the velocity loop damps them.)
5770    #[test]
5771    fn an_elastic_train_puts_the_motor_ahead_by_the_hand_calculated_speed() {
5772        let train = sim_core::Train::of(30.0, 1e-4, 4e-4).unwrap();
5773        assert!(
5774            (train.load_share - 0.75).abs() < 1e-12 && (train.hz - 1e5f64.sqrt() / std::f64::consts::TAU).abs() < 1e-9,
5775            "{train:?}"
5776        );
5777        assert!((train_speed(train, 1e6, 1e5) - 7.5).abs() < 1e-9);
5778        let (jm, jl, k, jerk, top) = (1e-4, 3e-4, 30.0, 1e6, 1e5);
5779        let rise = top / jerk;
5780        let acc = |t: f64| {
5781            if t < rise {
5782                jerk * t
5783            } else if t < 3.0 * rise {
5784                top
5785            } else {
5786                (top - jerk * (t - 3.0 * rise)).max(0.0)
5787            }
5788        };
5789        let (mut th, mut w, mut thl, mut wl, dt) = (0.0f64, 0.0f64, 0.0f64, 0.0f64, 1e-6);
5790        let (mut lead_sum, mut most, mut samples) = (0.0, 0f64, 0.0);
5791        let mut t = 0.0;
5792        while t < 6.0 * rise {
5793            let twist = th - thl;
5794            let torque = (jm + jl) * acc(t);
5795            let (am, al) = ((torque - k * twist) / jm, k * twist / jl);
5796            (w, wl) = (w + am * dt, wl + al * dt);
5797            (th, thl) = (th + w * dt, thl + wl * dt);
5798            t += dt;
5799            let lead = w - (jm * w + jl * wl) / (jm + jl);
5800            if t < rise {
5801                (lead_sum, samples, most) = (lead_sum + lead, samples + 1.0, most.max(lead.abs()));
5802            }
5803        }
5804        let mean = lead_sum / samples;
5805        assert!((mean - 7.5).abs() < 0.1 * 7.5 && most <= 2.0 * 7.5 * 1.01, "mean {mean}, most {most}");
5806    }
5807
5808    /// A jerk limit far quicker than the train's swing (`train_speed`), by hand: the train above (w^2 = 1e5 1/s^2,
5809    /// s = 0.75) swings at W = sqrt(30 (1e4 + 1e4 / 3)) = sqrt(4e5) = 632.5 rad/s, so a step of 1e3 rad/s^2 puts the motor
5810    /// at most 0.75 * 1e3 * 632.5 / 1e5 = 4.743 rad/s ahead, not the 0.75 * 1e9 / 1e5 = 7500 rad/s a jerk of 1e9 rad/s^3
5811    /// would say. Integrated (the step held for 20 ms, two swings): the lead peaks at that.
5812    #[test]
5813    fn an_elastic_train_after_a_step_of_acceleration_leads_by_the_swing() {
5814        let train = sim_core::Train::of(30.0, 1e-4, 4e-4).unwrap();
5815        let by_hand = 0.75 * 1e3 * 4e5f64.sqrt() / 1e5;
5816        assert!((by_hand - 4.743).abs() < 1e-3 && (train_speed(train, 1e9, 1e3) - by_hand).abs() < 1e-9);
5817        let (jm, jl, k, step) = (1e-4, 3e-4, 30.0, 1e3);
5818        let (mut th, mut w, mut thl, mut wl, dt) = (0.0f64, 0.0f64, 0.0f64, 0.0f64, 1e-7);
5819        let mut most = 0f64;
5820        for _ in 0..200_000 {
5821            let twist = th - thl;
5822            let (am, al) = (((jm + jl) * step - k * twist) / jm, k * twist / jl);
5823            (w, wl) = (w + am * dt, wl + al * dt);
5824            (th, thl) = (th + w * dt, thl + wl * dt);
5825            most = most.max(w - (jm * w + jl * wl) / (jm + jl));
5826        }
5827        assert!((most - by_hand).abs() < 1e-3 * by_hand, "{most}");
5828    }
5829
5830    /// The bound of a motor's turn per distance (`singular_turn`): at 400 rad/s on a piece of 2 m the slowest crawl is
5831    /// 2 m / 1000 s = 2 mm/s, so 400 / 0.002 = 2e5 rad per m; on a piece of 1 mm the bound would be 4e8, held to the cap 1e6.
5832    #[test]
5833    fn a_motors_turn_per_distance_is_bounded_by_its_speed_over_the_slowest_crawl() {
5834        assert!((singular_turn(400.0, 2.0) - 2e5).abs() < 1e-6);
5835        assert_eq!(singular_turn(400.0, 1e-3), SINGULAR_TURN);
5836    }
5837
5838    /// Two arcs of 0.1 m radius that meet with a tangent kink of 45 degrees, the first in the x-y plane and the second in
5839    /// the x-z plane (the plane of the two tangents), against the same two arcs both in the x-z plane. Both are rounded
5840    /// (`round_corners`) within the corner tolerance e = 0.1 mm: between lines 3 d sin(45) / 16 = e, d = 16 e / (3 sin 45)
5841    /// = 0.754 mm; the arcs bend d^2 / (2 R) = 2.8e-6 m away from their tangents, 3 % of e, so the deviation is e within
5842    /// the search's 2 % and that bend. The plans pass the junction without a stop and as fast as in one plane (the
5843    /// curvature of the arcs, 10 per m, is small against the curve's 3 |tb - ta| / (d |ta + tb|^2) = 400 per m).
5844    #[test]
5845    fn two_arcs_in_perpendicular_planes_with_a_kink_are_rounded_and_passed_as_in_one_plane() {
5846        let (axes, r, e) = (axes3(), 0.1, 1e-4);
5847        let (s, c) = (45f64.to_radians().sin(), 45f64.to_radians().cos());
5848        let at = |angle: f64| (r * angle.to_radians().cos(), r * angle.to_radians().sin());
5849        let arc = |to: Vec<f64>, centre: Vec<f64>| Piece::Arc { to, centre, clockwise: false, plane: None };
5850        let (x0, d0) = at(-120.0);
5851        let (x1, d1) = at(-15.0);
5852        // The first arc ends at (0, 0, -0.9) heading +x. The second leaves along (c, s) in the x-z plane, around the
5853        // centre r (-s, c) from there, 30 degrees on.
5854        let (xb, zb) = (-r * s, r * c);
5855        let second = arc(vec![xb + x1, 0.0, -0.9 + zb + d1], vec![xb, 0.0, -0.9 + zb]);
5856        let apart = [
5857            // In the x-y plane: centre (0, r, -0.9).
5858            (vec![x0, r + d0, -0.9], arc(vec![0.0, 0.0, -0.9], vec![0.0, r, -0.9])),
5859            // In the x-z plane: centre (0, 0, -0.9 + r).
5860            (vec![x0, 0.0, -0.9 + r + d0], arc(vec![0.0, 0.0, -0.9], vec![0.0, 0.0, -0.9 + r])),
5861        ];
5862        let tolerance = Tolerance { path: 0.0, corner: e };
5863        let results: Vec<_> = apart
5864            .iter()
5865            .map(|(start, first)| {
5866                let pieces = [first.clone(), second.clone()];
5867                let (geo, off) = geometry(&axes, start, &pieces, tolerance, &axis_speed(&axes), ARC_SLACK).unwrap();
5868                assert_eq!(geo.len(), 3, "arc, curve, arc");
5869                assert!((0.97e-4..=1.0e-4).contains(&off), "{off} m");
5870                let points = plan(&axes, start, &pieces, 1e-3, tolerance, ARC_SLACK).unwrap();
5871                // The slowest step within 5 mm of the junction is a speed, not a stop.
5872                let junction = [0.0, 0.0, -0.9];
5873                let slowest = points
5874                    .windows(2)
5875                    .filter(|w| distance(&w[0].1, &junction) < 5e-3)
5876                    .map(|w| distance(&w[0].1, &w[1].1))
5877                    .fold(f64::INFINITY, f64::min);
5878                assert!(slowest > 1e-6, "stops at the kink");
5879                (points.len(), slowest)
5880            })
5881            .collect();
5882        let ((n_a, v_a), (n_b, v_b)) = (results[0], results[1]);
5883        // Both curves' |p'''| is the quintic's 2.0e6 per m^2 (the curvature rising to ~950 per m over 1.43 mm). In one
5884        // plane it is the change of curvature, which takes 0.4 of the jerk: v^3 2e6 = 0.4 * 2500 m/s^3, v = 0.0794 m/s.
5885        // Across the planes the curve starts with the first arc's curvature (10 per m along y) and its jerk along z is
5886        // binormal there (kappa tau = 2.0e6), which takes `BINORMAL_SHARE` = 0.3: v = cbrt(0.3 * 2500 / 2e6) = 0.0721
5887        // m/s, cbrt(3 / 4) = 0.909 of the planar speed. Measured 0.0721 and 0.0794 (steps of 1 ms), ratio 0.9083.
5888        assert!((n_a as f64 / n_b as f64 - 1.0).abs() < 0.02, "{results:?}");
5889        assert!((v_a / v_b - 0.75f64.cbrt()).abs() < 0.005 && (v_b / 1e-3 - 0.0794).abs() < 1e-3, "{results:?}");
5890    }
5891
5892    /// A line 50 mm long that ends where an arc starts but begins 1 um off the arc's plane: it turns into the arc by
5893    /// 2e-5 rad, below the 1 mrad of a corner, and lies 1 um off the run's plane (more than its 1 nm), so it gets no
5894    /// transition curve and the path passes the junction at `junction_speed`: the arc's curvature, 10 per m along y, is a
5895    /// step of acceleration that half the y axis's jerk (1250 m/s^3) may make over one cycle of 1 ms: v^2 10 = 1250 *
5896    /// 1e-3, v = 0.354 m/s (the z kink allows 1250 * 1e-6 / 2e-5 = 62 m/s). Not a stop. In the plane the line gets
5897    /// its transition curve (15.5 mm for the 0.1 mm tolerance e: L^2 / (24 R) = e) and passes faster.
5898    #[test]
5899    fn a_line_one_micrometre_off_an_arcs_plane_passes_its_junction_at_the_curvature_step_speed() {
5900        let (axes, r) = (axes3(), 0.1);
5901        let arc = Piece::Arc { to: vec![r, r, -0.9], centre: vec![0.0, r, -0.9], clockwise: false, plane: None };
5902        let junction = [0.0, 0.0, -0.9];
5903        let slowest = |off: f64| {
5904            let pieces = [Piece::Line(junction.to_vec()), arc.clone()];
5905            let start = [-0.05, 0.0, -0.9 + off];
5906            let points = plan(&axes, &start, &pieces[..], 1e-3, 1e-4, ARC_SLACK).unwrap();
5907            points
5908                .windows(2)
5909                .filter(|w| distance(&w[0].1, &junction) < 3e-3)
5910                .map(|w| distance(&w[0].1, &w[1].1))
5911                .fold(f64::INFINITY, f64::min)
5912        };
5913        let (off, on) = (slowest(1e-6), slowest(0.0));
5914        let hand = (1250.0 * 1e-3 / 10.0_f64).sqrt() * 1e-3;
5915        assert!(off >= hand * 0.98 && off <= hand * 1.02, "{off} m per step against {hand}");
5916        assert!(on > 1.5 * off, "{on} m per step in the plane");
5917    }
5918}