1use alloc::vec::Vec;
5use core::f64::consts::{FRAC_PI_2, PI, TAU};
6
7use super::Se2State;
8use super::curve::{Segment, SegmentKind, local_goal, total_length, walk};
9use crate::StateSpace;
10
11const ZERO: f64 = 1e-10;
14
15#[derive(Debug, Clone, Copy)]
18struct Goal {
19 x: f64,
21 y: f64,
23 phi: f64,
25 sin: f64,
27 cos: f64,
29}
30
31type Formula = fn(Goal) -> Option<(f64, f64, f64)>;
34
35type Layout = fn(f64, f64, f64) -> [f64; 5];
37
38const WORDS: [&[SegmentKind]; 18] = {
41 use SegmentKind::{Left as L, Right as R, Straight as S};
42
43 [
44 &[L, R, L],
45 &[R, L, R],
46 &[L, R, L, R],
47 &[R, L, R, L],
48 &[L, R, S, L],
49 &[R, L, S, R],
50 &[L, S, R, L],
51 &[R, S, L, R],
52 &[L, R, S, R],
53 &[R, L, S, L],
54 &[R, S, R, L],
55 &[L, S, L, R],
56 &[L, S, R],
57 &[R, S, L],
58 &[L, S, L],
59 &[R, S, R],
60 &[L, R, S, L, R],
61 &[R, L, S, R, L],
62 ]
63};
64
65#[derive(Debug, Clone, Copy, PartialEq)]
68pub struct ReedsSheppPath {
69 segments: [Segment; 5],
71 count: usize,
73 pub radius: f64,
75}
76
77impl ReedsSheppPath {
78 fn new(word: usize, lengths: [f64; 5], radius: f64) -> Self {
80 let kinds = WORDS[word];
81
82 Self {
83 segments: core::array::from_fn(|i| Segment {
84 kind: kinds.get(i).copied().unwrap_or(SegmentKind::Straight),
85 length: if i < kinds.len() { lengths[i] } else { 0.0 },
86 }),
87 count: kinds.len(),
88 radius,
89 }
90 }
91
92 #[must_use]
94 pub fn segments(&self) -> &[Segment] {
95 &self.segments[..self.count]
96 }
97
98 #[must_use]
100 pub fn length(&self) -> f64 {
101 self.radius * total_length(self.segments())
102 }
103
104 #[must_use]
106 pub fn state_at(&self, from: &Se2State, distance: f64) -> Se2State {
107 walk(
108 from,
109 self.segments(),
110 distance.max(0.0) / self.radius,
111 self.radius,
112 )
113 }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq)]
139pub struct ReedsShepp {
140 radius: f64,
142}
143
144impl ReedsShepp {
145 #[must_use]
151 pub fn new(radius: f64) -> Self {
152 assert!(
153 radius.is_finite() && radius > 0.0,
154 "turning radius must be positive and finite"
155 );
156
157 Self { radius }
158 }
159
160 #[must_use]
162 pub const fn radius(&self) -> f64 {
163 self.radius
164 }
165
166 #[must_use]
173 pub fn path(&self, from: &Se2State, to: &Se2State) -> ReedsSheppPath {
174 let (x, y, phi) = local_goal(from, to, self.radius);
175 let mut best: Option<(f64, usize, [f64; 5])> = None;
176
177 for_each_candidate(x, y, phi, |word, lengths| {
178 let length: f64 = lengths.iter().map(|l| libm::fabs(*l)).sum();
179
180 if best.is_none_or(|(b, _, _)| length < b) {
181 best = Some((length, word, lengths));
182 }
183 });
184
185 let (_, word, lengths) = best.expect("the CSC family always has a solution");
186
187 ReedsSheppPath::new(word, lengths, self.radius)
188 }
189
190 #[must_use]
193 pub fn candidates(&self, from: &Se2State, to: &Se2State) -> Vec<ReedsSheppPath> {
194 let (x, y, phi) = local_goal(from, to, self.radius);
195 let mut all = Vec::new();
196
197 for_each_candidate(x, y, phi, |word, lengths| {
198 all.push(ReedsSheppPath::new(word, lengths, self.radius));
199 });
200
201 all
202 }
203}
204
205impl StateSpace for ReedsShepp {
206 type State = Se2State;
207
208 fn dimension(&self) -> usize {
209 3
210 }
211
212 fn distance(&self, from: &Se2State, to: &Se2State) -> f64 {
213 self.path(from, to).length()
214 }
215
216 fn interpolate(&self, from: &Se2State, to: &Se2State, t: f64) -> Se2State {
217 if t <= 0.0 {
218 return *from;
219 }
220
221 if t >= 1.0 {
222 return *to;
223 }
224
225 let path = self.path(from, to);
226
227 path.state_at(from, t * path.length())
228 }
229}
230
231fn for_each_candidate(x: f64, y: f64, phi: f64, mut emit: impl FnMut(usize, [f64; 5])) {
234 let (sin, cos) = (libm::sin(phi), libm::cos(phi));
235 let (xb, yb) = (x * cos + y * sin, x * sin - y * cos);
236 let mut family = |at: (f64, f64), formula: Formula, words: (usize, usize), layout: Layout| {
237 let goal = Goal {
238 x: at.0,
239 y: at.1,
240 phi,
241 sin,
242 cos,
243 };
244 symmetric_variants(goal, formula, words, layout, &mut emit);
245 };
246
247 family((x, y), lp_sp_lp, (14, 15), |t, u, v| [t, u, v, 0.0, 0.0]);
248 family((x, y), lp_sp_rp, (12, 13), |t, u, v| [t, u, v, 0.0, 0.0]);
249 family((x, y), lp_rm_l, (0, 1), |t, u, v| [t, u, v, 0.0, 0.0]);
250 family((xb, yb), lp_rm_l, (0, 1), |t, u, v| [v, u, t, 0.0, 0.0]);
251 family((x, y), lp_rup_lum_rm, (2, 3), |t, u, v| [t, u, -u, v, 0.0]);
252 family((x, y), lp_rum_lum_rp, (2, 3), |t, u, v| [t, u, u, v, 0.0]);
253 family((x, y), lp_rm_sm_lm, (4, 5), |t, u, v| {
254 [t, -FRAC_PI_2, u, v, 0.0]
255 });
256 family((x, y), lp_rm_sm_rm, (8, 9), |t, u, v| {
257 [t, -FRAC_PI_2, u, v, 0.0]
258 });
259 family((xb, yb), lp_rm_sm_lm, (6, 7), |t, u, v| {
260 [v, u, -FRAC_PI_2, t, 0.0]
261 });
262 family((xb, yb), lp_rm_sm_rm, (10, 11), |t, u, v| {
263 [v, u, -FRAC_PI_2, t, 0.0]
264 });
265 family((x, y), lp_rm_s_lm_rp, (16, 17), |t, u, v| {
266 [t, -FRAC_PI_2, u, -FRAC_PI_2, v]
267 });
268}
269
270fn symmetric_variants(
274 goal: Goal,
275 formula: Formula,
276 words: (usize, usize),
277 layout: Layout,
278 emit: &mut impl FnMut(usize, [f64; 5]),
279) {
280 let Goal {
281 x,
282 y,
283 phi,
284 sin,
285 cos,
286 } = goal;
287 let flipped = |x, y, phi, sin| Goal {
288 x,
289 y,
290 phi,
291 sin,
292 cos,
293 };
294 let variants = [
295 (goal, words.0, 1.0),
296 (flipped(-x, y, -phi, -sin), words.0, -1.0),
297 (flipped(x, -y, -phi, -sin), words.1, 1.0),
298 (flipped(-x, -y, phi, sin), words.1, -1.0),
299 ];
300
301 for (variant, word, sign) in variants {
302 if let Some((t, u, v)) = formula(variant) {
303 emit(word, layout(t, u, v).map(|length| sign * length));
304 }
305 }
306}
307
308fn mod2pi(x: f64) -> f64 {
310 let v = x - TAU * libm::round(x / TAU);
313
314 if v < -PI {
315 v + TAU
316 } else if v > PI {
317 v - TAU
318 } else {
319 v
320 }
321}
322
323fn polar(x: f64, y: f64) -> (f64, f64) {
325 (libm::sqrt(x * x + y * y), libm::atan2(y, x))
326}
327
328fn tau_omega(u: f64, v: f64, xi: f64, eta: f64, phi: f64) -> (f64, f64) {
330 let delta = mod2pi(u - v);
331 let a = libm::sin(u) - libm::sin(delta);
332 let b = libm::cos(u) - libm::cos(delta) - 1.0;
333 let t1 = libm::atan2(eta * a - xi * b, xi * a + eta * b);
334 let t2 = 2.0 * (libm::cos(delta) - libm::cos(v) - libm::cos(u)) + 3.0;
335 let tau = if t2 < 0.0 {
336 mod2pi(t1 + PI)
337 } else {
338 mod2pi(t1)
339 };
340
341 (tau, mod2pi(tau - u + v - phi))
342}
343
344fn lp_sp_lp(g: Goal) -> Option<(f64, f64, f64)> {
346 let Goal {
347 x,
348 y,
349 phi,
350 sin,
351 cos,
352 } = g;
353 let (u, t) = polar(x - sin, y - 1.0 + cos);
354 let v = mod2pi(phi - t);
355
356 (t >= -ZERO && v >= -ZERO).then_some((t, u, v))
357}
358
359fn lp_sp_rp(g: Goal) -> Option<(f64, f64, f64)> {
361 let Goal {
362 x,
363 y,
364 phi,
365 sin,
366 cos,
367 } = g;
368 let (u1, t1) = polar(x + sin, y - 1.0 - cos);
369 let u1 = u1 * u1;
370
371 if u1 < 4.0 {
372 return None;
373 }
374
375 let u = libm::sqrt(u1 - 4.0);
376 let t = mod2pi(t1 + libm::atan2(2.0, u));
377 let v = mod2pi(t - phi);
378
379 (t >= -ZERO && v >= -ZERO).then_some((t, u, v))
380}
381
382fn lp_rm_l(g: Goal) -> Option<(f64, f64, f64)> {
384 let Goal {
385 x,
386 y,
387 phi,
388 sin,
389 cos,
390 } = g;
391 let (u1, theta) = polar(x - sin, y - 1.0 + cos);
392
393 if u1 > 4.0 {
394 return None;
395 }
396
397 let u = -2.0 * libm::asin(0.25 * u1);
398 let t = mod2pi(theta + 0.5 * u + PI);
399 let v = mod2pi(phi - t + u);
400
401 (t >= -ZERO && u <= ZERO).then_some((t, u, v))
402}
403
404fn lp_rup_lum_rm(g: Goal) -> Option<(f64, f64, f64)> {
406 let Goal {
407 x,
408 y,
409 phi,
410 sin,
411 cos,
412 } = g;
413 let xi = x + sin;
414 let eta = y - 1.0 - cos;
415 let rho = 0.25 * (2.0 + libm::sqrt(xi * xi + eta * eta));
416
417 if rho > 1.0 {
418 return None;
419 }
420
421 let u = libm::acos(rho);
422 let (t, v) = tau_omega(u, -u, xi, eta, phi);
423
424 (t >= -ZERO && v <= ZERO).then_some((t, u, v))
425}
426
427fn lp_rum_lum_rp(g: Goal) -> Option<(f64, f64, f64)> {
429 let Goal {
430 x,
431 y,
432 phi,
433 sin,
434 cos,
435 } = g;
436 let xi = x + sin;
437 let eta = y - 1.0 - cos;
438 let rho = (20.0 - xi * xi - eta * eta) / 16.0;
439
440 if !(0.0..=1.0).contains(&rho) {
441 return None;
442 }
443
444 let u = -libm::acos(rho);
445 if u < -0.5 * PI {
446 return None;
447 }
448
449 let (t, v) = tau_omega(u, u, xi, eta, phi);
450
451 (t >= -ZERO && v >= -ZERO).then_some((t, u, v))
452}
453
454#[expect(
456 clippy::many_single_char_names,
457 reason = "t, u, v, x, y follow the nomenclature of Reeds and Shepp"
458)]
459fn lp_rm_sm_lm(g: Goal) -> Option<(f64, f64, f64)> {
460 let Goal {
461 x,
462 y,
463 phi,
464 sin,
465 cos,
466 } = g;
467 let (rho, theta) = polar(x - sin, y - 1.0 + cos);
468
469 if rho < 2.0 {
470 return None;
471 }
472
473 let r = libm::sqrt(rho * rho - 4.0);
474 let u = 2.0 - r;
475 let t = mod2pi(theta + libm::atan2(r, -2.0));
476 let v = mod2pi(phi - 0.5 * PI - t);
477
478 (t >= -ZERO && u <= ZERO && v <= ZERO).then_some((t, u, v))
479}
480
481fn lp_rm_sm_rm(g: Goal) -> Option<(f64, f64, f64)> {
483 let Goal {
484 x,
485 y,
486 phi,
487 sin,
488 cos,
489 } = g;
490 let xi = x + sin;
491 let eta = y - 1.0 - cos;
492 let (rho, theta) = polar(-eta, xi);
493
494 if rho < 2.0 {
495 return None;
496 }
497
498 let t = theta;
499 let u = 2.0 - rho;
500 let v = mod2pi(t + 0.5 * PI - phi);
501
502 (t >= -ZERO && u <= ZERO && v <= ZERO).then_some((t, u, v))
503}
504
505fn lp_rm_s_lm_rp(g: Goal) -> Option<(f64, f64, f64)> {
507 let Goal {
508 x,
509 y,
510 phi,
511 sin,
512 cos,
513 } = g;
514 let xi = x + sin;
515 let eta = y - 1.0 - cos;
516 let (rho, _) = polar(xi, eta);
517
518 if rho < 2.0 {
519 return None;
520 }
521
522 let u = 4.0 - libm::sqrt(rho * rho - 4.0);
523 if u > ZERO {
524 return None;
525 }
526
527 let t = mod2pi(libm::atan2(
528 (4.0 - u) * xi - 2.0 * eta,
529 -2.0 * xi + (u - 4.0) * eta,
530 ));
531 let v = mod2pi(t - phi);
532
533 (t >= -ZERO && v >= -ZERO).then_some((t, u, v))
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539 use crate::Dubins;
540 use crate::space::curve::tests::{assert_same_pose, pose_pairs};
541
542 #[test]
543 fn known_path_lengths() {
544 let car = ReedsShepp::new(1.0);
545 let origin = Se2State::new(0.0, 0.0, 0.0);
546
547 assert!((car.distance(&origin, &Se2State::new(4.0, 0.0, 0.0)) - 4.0).abs() < 1e-9);
548 assert!((car.distance(&origin, &Se2State::new(-4.0, 0.0, 0.0)) - 4.0).abs() < 1e-9);
549 assert!((car.distance(&origin, &Se2State::new(0.0, 2.0, PI)) - PI).abs() < 1e-9);
550 assert!(car.distance(&origin, &origin).abs() < 1e-12);
551
552 let reversed = Se2State::new(-1.0, 1.0, -FRAC_PI_2);
554 assert!((car.distance(&origin, &reversed) - FRAC_PI_2).abs() < 1e-9);
555 }
556
557 #[test]
558 fn every_candidate_reaches_its_target_and_all_families_occur() {
559 let mut words_seen = [false; 18];
560
561 for radius in [0.5, 1.0, 2.5] {
562 let car = ReedsShepp::new(radius);
563
564 for (from, to) in pose_pairs(600, 5) {
565 for path in car.candidates(&from, &to) {
566 assert_same_pose(&path.state_at(&from, path.length()), &to, 1e-6);
567
568 let kinds: Vec<_> = path.segments().iter().map(|s| s.kind).collect();
569 let word = WORDS
570 .iter()
571 .position(|w| *w == kinds.as_slice())
572 .expect("known");
573 words_seen[word] = true;
574 }
575 }
576 }
577
578 assert_eq!(
579 words_seen, [true; 18],
580 "every word shape was a feasible candidate"
581 );
582 }
583
584 #[test]
585 fn distance_is_a_metric_no_longer_than_dubins() {
586 let (car, forward) = (ReedsShepp::new(1.2), Dubins::new(1.2));
587 let pairs = pose_pairs(400, 6);
588
589 for window in pairs.windows(2) {
590 let ((a, b), (c, _)) = (window[0], window[1]);
591 let ab = car.distance(&a, &b);
592
593 assert!((ab - car.distance(&b, &a)).abs() < 1e-9, "symmetric");
594 assert!(ab <= forward.distance(&a, &b) + 1e-6);
596 assert!(car.distance(&a, &c) <= ab + car.distance(&b, &c) + 1e-6);
597 }
598 }
599
600 #[test]
601 fn interpolation_follows_the_path() {
602 let car = ReedsShepp::new(1.0);
603
604 let from = Se2State::new(
606 -1.154_810_577_189_199_2,
607 -2.493_659_442_506_264,
608 1.290_460_292_765_287_2,
609 );
610 let to = Se2State::new(
611 0.680_688_762_351_618_2,
612 0.957_761_849_729_337_2,
613 -1.377_344_206_800_952_3,
614 );
615 let t = 0.043_926_969_507_538_036;
616 let mid = car.interpolate(&from, &to, t);
617 assert!(car.distance(&from, &mid) <= t * car.distance(&from, &to) + 1e-9);
618
619 for (from, to) in pose_pairs(300, 7) {
620 let total = car.distance(&from, &to);
621 assert_eq!(car.interpolate(&from, &to, 0.0), from);
622 assert_eq!(car.interpolate(&from, &to, 1.0), to);
623
624 for t in [0.25, 0.5, 0.75] {
625 let mid = car.interpolate(&from, &to, t);
626 assert!((car.distance(&from, &mid) - t * total).abs() < 1e-6);
627 }
628 }
629 }
630}