1use 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 Line(Vec<f64>),
44 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 Spline(Vec<f64>),
57}
58
59pub 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 "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
93pub 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#[derive(Clone)]
111enum Geo {
112 Line {
113 from: Vec<f64>,
114 dir: Vec<f64>,
115 length: f64,
116 },
117 Slerp {
122 from: Vec<f64>,
123 to: Vec<f64>,
124 length: f64,
125 at: usize,
126 },
127 Arc {
129 centre: [f64; 2],
130 radius: f64,
131 from_angle: f64,
132 turn: f64,
133 length: f64,
134 },
135 Arc3 {
138 centre: [f64; 3],
139 u: [f64; 3],
140 w: [f64; 3],
141 radius: f64,
142 length: f64,
143 },
144 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 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 Carried {
178 arc: Box<Geo>,
179 from: Vec<f64>,
180 by: Vec<f64>,
181 length: f64,
182 turn: Option<usize>,
183 },
184}
185
186const WIDEST: usize = 6;
188
189type Wide = [f64; WIDEST];
191
192type 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
207fn 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
216fn first3(a: &Wide) -> [f64; 3] {
218 [a[0], a[1], a[2]]
219}
220
221fn 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
226const SPLINE_PARTS: usize = 64;
228const SPLINE_MARGIN: f64 = 1.05;
231
232fn poly_rates(c: &Poly, u: f64) -> [Wide; 3] {
234 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
241fn poly_shift(c: &Poly, from: f64) -> Poly {
243 let mut out = [[0.0; WIDEST]; 6];
244 for (m, cm) in c.iter().enumerate() {
245 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
257fn 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
277fn 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 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 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 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 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 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 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 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 [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 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
470fn 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
481fn 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
489fn 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
501fn 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
514fn 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 let chord = |i: usize, axis: usize| if axis < dims { (points[i + 1][axis] - points[i][axis]) / h[i] } else { 0.0 };
535 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 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
582fn 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
599fn 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
626fn 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 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 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 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 (geo, moved.max(eased).max(rounded))
671}
672
673#[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
688fn axis_speed(axes: &[AxisInfo]) -> impl Fn(&Geo) -> f64 {
690 let bounds = axis_bounds(axes);
691 move |geo| limits(geo, &bounds)[0]
692}
693
694pub 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
710pub const ARC_SLACK: f64 = 1e-4;
716const FIRST_ARC: f64 = 1e-3;
722const 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#[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
738fn 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 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 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 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 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 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 = ¢re[..3];
852 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 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 if out.is_empty() { bad } else { Ok((out, if off > 1e-9 { off } else { 0.0 }, caps)) }
878}
879
880fn 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 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 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
929fn 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
946fn 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
959fn corner(a: &Geo, b: &Geo) -> bool {
962 distance(&a.at(a.length())[1], &b.at(0.0)[1]) > 1e-3
963}
964
965fn 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
973fn 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
995fn 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
1028fn 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 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
1083fn 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 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
1109fn 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
1143fn 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 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 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 out.extend(trimmed(&piece, cut[i][0], cut[i][1]));
1197 }
1198 }
1199 (out, off)
1200}
1201
1202#[derive(Clone, Copy)]
1207enum Side {
1208 Line { point: [f64; 2], dir: [f64; 2] },
1209 Circle { centre: [f64; 2], curvature: f64 },
1210}
1211
1212fn transition(a: Side, b: Side, gap: f64) -> Option<Geo> {
1217 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 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 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 (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 let apart = |length: f64| {
1263 if length == 0.0 {
1264 (1.0 / k1 - 1.0 / k0).abs()
1265 } else {
1266 distance(¢re_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 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
1288fn 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 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 let sweep = |i: usize| geo[i].length() * k[i].abs();
1340 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 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 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
1390fn 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 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 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 let same = |j: usize| (k[j] - k[j - 1]).abs() <= 1e-9 * k[j].abs().max(k[j - 1].abs());
1427 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 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 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 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 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 let angle = |p: &[f64]| (p[1] - centre[1]).atan2(p[0] - centre[0]);
1488 let sweep = length / radius;
1489 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 if before > reaches.0 || after > reaches.1 {
1499 return None;
1500 }
1501 let left = sweep - before - after;
1502 let shrink = radius - moved;
1506 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 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 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
1541type Plane = [[f64; 3]; 4];
1543
1544fn 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 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 (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 (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
1626fn 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(¢re);
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(¢re, 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
1680const EASE_PEAK: f64 = 0.01728;
1683const EASE_RATE: f64 = 9.0;
1686
1687fn 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 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 let (mut eased, rest) = if into { (c, poly_shift(&c, l)) } else { (poly_shift(&c, h - l), c) };
1737 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
1761fn 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
1771fn 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
1777fn 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
1789fn 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 if mid <= low || mid >= high {
1799 break;
1800 }
1801 if ok(mid) { low = mid } else { high = mid }
1802 }
1803 low
1804}
1805
1806fn 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
1819const TOPS_GRID: usize = 32;
1821
1822type Bounds = Vec<(Vec<f64>, f64)>;
1826
1827fn 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
1838fn 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 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 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 Geo::Spline { tightest, rate, binormal, .. } => {
1858 let r = 1.0 / tightest;
1859 curved(r, r * r, *rate, *binormal, any())
1860 }
1861 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
1871fn curved(r: f64, r_jerk2: f64, dk: f64, binormal: f64, [v, a, j]: [f64; 3]) -> [f64; 3] {
1889 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 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
1902fn 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 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 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 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 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
1966const SLERP_SAMPLES: usize = 256;
1968
1969const BINORMAL_SHARE: f64 = 0.3;
1971
1972fn 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
1987pub 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
2008pub 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
2023pub 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#[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
2082fn 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 let hold = 2.0 * cycle;
2094 let need = |i: usize, v0: f64, v1: f64| hold * (v0 + v1) + ramp_distance(v0, v1, limits[i][1], limits[i][2]);
2096
2097 let mut speed = vec![0.0; n + 1];
2099 for i in 1..n {
2100 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 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 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 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#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
2167pub struct PlanLimits {
2168 pub reserve: f64,
2171 pub tension: [f64; 3],
2173 pub gearbox: Vec<Option<[f64; 4]>>,
2179 pub guide: f64,
2181 #[serde(default)]
2185 pub friction: Vec<[f64; 5]>,
2186 #[serde(default)]
2192 pub ratings: Vec<[f64; 3]>,
2193 #[serde(default = "one")]
2195 pub margin: f64,
2196 #[serde(default)]
2199 pub hermite: bool,
2200 #[serde(default = "speed_kept")]
2203 pub speed_kept: f64,
2204 #[serde(default)]
2208 pub loops: Vec<LoopKeep>,
2209}
2210
2211#[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
2229pub 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
2245pub 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 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 pub fn kept_at(&self, machine: &dyn Machine, pose: &[f64]) -> f64 {
2282 self.kept_at_reserve(machine, pose, self.reserve)
2283 }
2284
2285 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 fn curve_kept(&self) -> f64 {
2309 if self.loops.is_empty() { self.speed_kept } else { SPEED_KEPT }
2310 }
2311
2312 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 fn rated(&self, drives: &[&DriveParams]) -> Vec<DriveParams> {
2323 self.rated_keeping(drives, self.speed_kept)
2324 }
2325
2326 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 fn braking(&self, m: usize) -> f64 {
2343 self.ratings.get(m).map_or(f64::INFINITY, |r| r[2] * self.margin)
2344 }
2345
2346 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
2356fn 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
2363const CURVE_SAMPLES: usize = 256;
2366
2367#[derive(Debug)]
2377struct MotorCurve {
2378 step: f64,
2379 motoring: Vec<f64>,
2380 braking: Vec<f64>,
2381 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 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 fn max_speed(&self) -> f64 {
2412 self.step * CURVE_SAMPLES as f64
2413 }
2414
2415 fn range(&self, speed: f64) -> (f64, f64) {
2419 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 let brakes = brakes.min(self.power / speed.abs());
2426 if speed >= 0.0 { (-brakes, *drives) } else { (-drives, brakes) }
2427 }
2428}
2429
2430pub 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 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
2489fn 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 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
2518pub 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
2534fn 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 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 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 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 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 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 let mut out = at_speed(low);
2634 out[0] = out[0].min(high);
2635 out
2636 }
2637}
2638
2639fn 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
2650fn 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 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 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
2680fn 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 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 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 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
2746const PLACE_SPACING: f64 = 2e-3;
2751const PLACE_TURN: f64 = 0.02;
2752const PLACES_LEAST: usize = 32;
2753const PLACES_MOST: usize = 1000;
2754const KEPT_BACK: f64 = 2e-4;
2757const SPEED_KEPT: f64 = 0.01;
2762const SPEED_KEPT_MOST: f64 = 0.5;
2764const STEPS_PER_CYCLE: f64 = 4.0;
2766const TURN_STEP: f64 = 1e-6;
2768const SINGULAR_TURN: f64 = 1e6;
2772
2773fn singular_turn(top: f64, length: f64) -> f64 {
2778 SINGULAR_TURN.min(top * PLAN_LONGEST / length)
2779}
2780const PLAN_LONGEST: f64 = 1000.0;
2783const BEND_STEP: f64 = 1e-4;
2786const CURVE_ACCELERATION: f64 = 0.9;
2789const CURVE_JERK: f64 = 0.5;
2790const CURVE_OVERSHOOT: f64 = 1e-3;
2795const CURVE_SWEEPS: usize = 300;
2797const LEVELS: usize = 32;
2800const RUN_STEPS: usize = 1 << 18;
2803const PLAN_POINTS_MOST: f64 = 1e7;
2806
2807struct Place {
2810 rows: Vec<[f64; 5]>,
2814 low: Vec<[f64; 3]>,
2818 turn: Vec<f64>,
2821 curves: Arc<[MotorCurve]>,
2822 guide: Vec<Friction>,
2825 speed: Vec<f64>,
2828 bends: Vec<[f64; 3]>,
2831 scale: f64,
2834 top: f64,
2836}
2837#[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 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 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 #[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 let (_, most) = range([0.0, 0.5, 1.0, 1.0], 2.0);
2926 assert!((most - top).abs() < 1e-9, "{most} against {top}");
2927 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 #[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 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 fn bounds(&self, i: usize, v: f64) -> (f64, f64) {
2955 match self.turn.get(i) {
2956 Some(turn) => {
2957 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 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 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 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 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 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
3025struct PieceLimits {
3032 places: Vec<Place>,
3033 spacing: f64,
3034 jerk: f64,
3035 lowest: f64,
3036 curve: [Vec<f64>; 2],
3037 lowest_ahead: [Vec<Vec<f64>>; 2],
3039 level: f64,
3040 most: [[Vec<Vec<f64>>; 2]; 2],
3041}
3042
3043impl PieceLimits {
3044 fn level_of(&self, v: f64) -> usize {
3046 ((v / self.level).ceil() as usize).clamp(1, LEVELS) - 1
3047 }
3048
3049 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
3060fn 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
3072fn 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
3126fn 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
3142fn 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
3164fn 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 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 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 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 let ramps = if matches!(geo, Geo::Line { .. } | Geo::Slerp { .. }) { 1.0 } else { ramp_share(axes, &derivatives) };
3216 let jerk = ramps * along;
3217 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 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 let (hold, per_acc, per_speed) = (torques(&zero, &zero), torques(&zero, d1), torques(d1, d2));
3233 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 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 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 let mut speed = vec![0.0; motors];
3265 if lowest.is_finite() || highest.is_finite() {
3266 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 rows.push([per_acc[k] - still[k], d, 0.0, -room, room]);
3284 speed.push(once[k] - still[k] - d);
3285 }
3286 }
3287 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 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 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 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 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 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 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 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 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 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
3447fn 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 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
3469fn 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
3476fn 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
3490fn 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 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 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 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 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 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 let reach = reach * (1.0 - 1e-9);
3559 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 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
3584fn 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 let (first, last) = (
3606 (reached / limits.spacing).floor() as usize,
3607 ((braking / limits.spacing).ceil() as usize).min(limits.places.len() - 1),
3608 );
3609 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
3633fn 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
3648fn 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 if fall.len() < 2 {
3662 return None;
3663 }
3664 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 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 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 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
3739fn 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 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 #[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 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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 #[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 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 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 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 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 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 #[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 #[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 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 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 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 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 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 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 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 #[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 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 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 #[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 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 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 #[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 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 #[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 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 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 #[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 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 #[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 #[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 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 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 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 #[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 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 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 #[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 #[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 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, ¢re), 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 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 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 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 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 #[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 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 #[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 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 #[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 #[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 #[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 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 #[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 #[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 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 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 #[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 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 #[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 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 #[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 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 #[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 struct Table {
5320 axes: [AxisInfo; 2],
5321 motors: [sim_core::MotorInfo; 2],
5322 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 #[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 #[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 #[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 #[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 assert!(x[21] < 0.43 - 0.01 && x[24] < 0.97, "{x:?}");
5468 }
5469
5470 #[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 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 #[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 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 #[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 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 #[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 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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 assert!((speed_kept_of(100.0, 0.01, 1.0, 1000.0, 200.0, 4.0) - 0.03).abs() < 1e-12);
5762 }
5763
5764 #[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 #[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 #[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 #[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 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 (vec![x0, r + d0, -0.9], arc(vec![0.0, 0.0, -0.9], vec![0.0, r, -0.9])),
5859 (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 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 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 #[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}