Skip to main content

sampling_planning/space/
dubins.rs

1//! Dubins curves: shortest paths of a car that only drives forward (Dubins 1957).
2
3use core::f64::consts::TAU;
4
5use super::Se2State;
6use super::curve::{Segment, SegmentKind, total_length, walk};
7use crate::StateSpace;
8
9/// Below this the normalized distance and heading difference count as zero (OMPL's
10/// `DUBINS_EPS`).
11const DUBINS_EPS: f64 = 1e-6;
12
13/// Slightly negative values above this count as zero (OMPL's `DUBINS_ZERO`).
14const DUBINS_ZERO: f64 = -1e-7;
15
16/// The six Dubins words: L and R are arcs of the turning radius, S is a straight line.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum DubinsWord {
19    /// Left, straight, left.
20    Lsl,
21    /// Right, straight, right.
22    Rsr,
23    /// Right, straight, left.
24    Rsl,
25    /// Left, straight, right.
26    Lsr,
27    /// Right, left, right.
28    Rlr,
29    /// Left, right, left.
30    Lrl,
31}
32
33impl DubinsWord {
34    /// All words, in the order [`Dubins::candidates`] reports them.
35    pub const ALL: [Self; 6] = [
36        Self::Lsl,
37        Self::Rsr,
38        Self::Rsl,
39        Self::Lsr,
40        Self::Rlr,
41        Self::Lrl,
42    ];
43
44    /// The segment motions of this word.
45    #[must_use]
46    pub const fn kinds(self) -> [SegmentKind; 3] {
47        use SegmentKind::{Left as L, Right as R, Straight as S};
48
49        match self {
50            Self::Lsl => [L, S, L],
51            Self::Rsr => [R, S, R],
52            Self::Rsl => [R, S, L],
53            Self::Lsr => [L, S, R],
54            Self::Rlr => [R, L, R],
55            Self::Lrl => [L, R, L],
56        }
57    }
58}
59
60/// A Dubins path: a word and its three non-negative segment lengths.
61#[derive(Debug, Clone, Copy, PartialEq)]
62pub struct DubinsPath {
63    /// The word.
64    pub word: DubinsWord,
65    /// The segments, in driving order; lengths are non-negative, in units of the radius.
66    pub segments: [Segment; 3],
67    /// The turning radius the path was computed for.
68    pub radius: f64,
69}
70
71impl DubinsPath {
72    /// The path for `word` with normalized segment lengths `lengths`.
73    fn new(word: DubinsWord, lengths: [f64; 3], radius: f64) -> Self {
74        let kinds = word.kinds();
75
76        Self {
77            word,
78            segments: core::array::from_fn(|i| Segment {
79                kind: kinds[i],
80                length: lengths[i],
81            }),
82            radius,
83        }
84    }
85
86    /// The path length in world units.
87    #[must_use]
88    pub fn length(&self) -> f64 {
89        self.radius * total_length(&self.segments)
90    }
91
92    /// The pose after driving `distance` (world units, clamped to the path) from `from`.
93    #[must_use]
94    pub fn state_at(&self, from: &Se2State, distance: f64) -> Se2State {
95        walk(
96            from,
97            &self.segments,
98            distance.max(0.0) / self.radius,
99            self.radius,
100        )
101    }
102}
103
104/// The Dubins car: SE(2) poses ([`Se2State`]) of a vehicle that drives only forward, at unit
105/// speed, with a minimum turning radius.
106///
107/// [`StateSpace::distance`] is the length of the shortest Dubins path and
108/// [`StateSpace::interpolate`] follows that path. Ported from OMPL's `DubinsStateSpace`
109/// (Mark Moll), with the exhaustive search over all six words instead of OMPL's
110/// classification shortcut for long paths: both return the shortest word. As in OMPL, poses
111/// closer than `1e-6` turning radii with headings within `1e-6` radians count as coincident:
112/// their distance is the position distance, not the loop a real car would need.
113///
114/// **The distance is not symmetric**: `d(a, b)` is the length from `a` to `b`, which differs
115/// from the way back. Planners that measure from tree nodes toward targets (RRT, RRT*, RRT#,
116/// SST) are fine; see [`StateSpace::distance`] for the planners that need symmetry. It does
117/// satisfy the triangle inequality.
118///
119/// [`StraightLine`](crate::StraightLine) steering works as is: it interpolates the fraction
120/// `max_step / d` of the way, and a prefix of a shortest path is a shortest path, so the steered
121/// state is `max_step` away along the curve.
122///
123/// # Examples
124///
125/// ```
126/// use sampling_planning::{Dubins, Se2State, StateSpace};
127///
128/// let car = Dubins::new(1.0);
129/// let half_loop = car.distance(&Se2State::new(0.0, 0.0, 0.0), &Se2State::new(0.0, 2.0, std::f64::consts::PI));
130///
131/// assert!((half_loop - std::f64::consts::PI).abs() < 1e-9);
132/// ```
133#[derive(Debug, Clone, Copy, PartialEq)]
134pub struct Dubins {
135    /// The minimum turning radius; positive and finite.
136    radius: f64,
137}
138
139impl Dubins {
140    /// The Dubins car with the given minimum turning radius.
141    ///
142    /// # Panics
143    ///
144    /// Panics if `radius` is not positive and finite.
145    #[must_use]
146    pub fn new(radius: f64) -> Self {
147        assert!(
148            radius.is_finite() && radius > 0.0,
149            "turning radius must be positive and finite"
150        );
151
152        Self { radius }
153    }
154
155    /// The minimum turning radius.
156    #[must_use]
157    pub const fn radius(&self) -> f64 {
158        self.radius
159    }
160
161    /// The shortest Dubins path from `from` to `to`; the earliest of
162    /// [`DubinsWord::ALL`] on ties.
163    ///
164    /// # Panics
165    ///
166    /// Never for finite poses: LSL and RSR always have a solution. Non-finite poses panic.
167    #[must_use]
168    pub fn path(&self, from: &Se2State, to: &Se2State) -> DubinsPath {
169        let (d, alpha, beta) = self.normalize(from, to);
170
171        if d < DUBINS_EPS && libm::fabs(alpha - beta) < DUBINS_EPS {
172            return DubinsPath::new(DubinsWord::Lsl, [0.0, d, 0.0], self.radius);
173        }
174
175        let mut best: Option<DubinsPath> = None;
176        for path in self.candidates(from, to).into_iter().flatten() {
177            if best.is_none_or(|b| path.length() < b.length()) {
178                best = Some(path);
179            }
180        }
181
182        best.expect("LSL or RSR always exists")
183    }
184
185    /// Every feasible word from `from` to `to`, in [`DubinsWord::ALL`] order; `None` where a
186    /// word has no solution (the CCC words when the poses are far apart, for example).
187    #[must_use]
188    pub fn candidates(&self, from: &Se2State, to: &Se2State) -> [Option<DubinsPath>; 6] {
189        let (d, alpha, beta) = self.normalize(from, to);
190        let trig = Trig::new(alpha, beta);
191
192        DubinsWord::ALL.map(|word| {
193            let lengths = match word {
194                DubinsWord::Lsl => lsl(d, alpha, beta, &trig),
195                DubinsWord::Rsr => rsr(d, alpha, beta, &trig),
196                DubinsWord::Rsl => rsl(d, alpha, beta, &trig),
197                DubinsWord::Lsr => lsr(d, alpha, beta, &trig),
198                DubinsWord::Rlr => rlr(d, alpha, beta, &trig),
199                DubinsWord::Lrl => lrl(d, alpha, beta, &trig),
200            };
201
202            lengths.map(|lengths| DubinsPath::new(word, lengths, self.radius))
203        })
204    }
205
206    /// The normalized distance `d` and the headings `alpha` and `beta` relative to the line
207    /// from `from` to `to`, as in Shkel and Lumelsky.
208    fn normalize(self, from: &Se2State, to: &Se2State) -> (f64, f64, f64) {
209        let (dx, dy) = (to.x - from.x, to.y - from.y);
210        let d = libm::hypot(dx, dy) / self.radius;
211        let th = libm::atan2(dy, dx);
212
213        (d, mod2pi(from.theta - th), mod2pi(to.theta - th))
214    }
215}
216
217impl StateSpace for Dubins {
218    type State = Se2State;
219
220    fn dimension(&self) -> usize {
221        3
222    }
223
224    fn distance(&self, from: &Se2State, to: &Se2State) -> f64 {
225        self.path(from, to).length()
226    }
227
228    fn interpolate(&self, from: &Se2State, to: &Se2State, t: f64) -> Se2State {
229        if t <= 0.0 {
230            return *from;
231        }
232
233        if t >= 1.0 {
234            return *to;
235        }
236
237        let path = self.path(from, to);
238
239        path.state_at(from, t * path.length())
240    }
241}
242
243/// `x` modulo `2 pi` in `[0, 2 pi)`, with OMPL's snapping of near-zero and near-`2 pi` values
244/// to zero.
245fn mod2pi(x: f64) -> f64 {
246    if x < 0.0 && x > DUBINS_ZERO {
247        return 0.0;
248    }
249
250    let xm = x - TAU * libm::floor(x / TAU);
251
252    if TAU - xm < 0.5 * DUBINS_EPS { 0.0 } else { xm }
253}
254
255/// Sines and cosines of `alpha` and `beta`, shared by the six word formulas.
256struct Trig {
257    /// `cos(alpha)`.
258    ca: f64,
259    /// `sin(alpha)`.
260    sa: f64,
261    /// `cos(beta)`.
262    cb: f64,
263    /// `sin(beta)`.
264    sb: f64,
265}
266
267impl Trig {
268    /// The sines and cosines of the two headings.
269    fn new(alpha: f64, beta: f64) -> Self {
270        Self {
271            ca: libm::cos(alpha),
272            sa: libm::sin(alpha),
273            cb: libm::cos(beta),
274            sb: libm::sin(beta),
275        }
276    }
277}
278
279/// The LSL lengths, if the word is feasible.
280fn lsl(d: f64, alpha: f64, beta: f64, g: &Trig) -> Option<[f64; 3]> {
281    let tmp = 2.0 + d * d - 2.0 * (g.ca * g.cb + g.sa * g.sb - d * (g.sa - g.sb));
282    (tmp >= DUBINS_ZERO).then(|| {
283        let theta = libm::atan2(g.cb - g.ca, d + g.sa - g.sb);
284
285        [
286            mod2pi(-alpha + theta),
287            libm::sqrt(tmp.max(0.0)),
288            mod2pi(beta - theta),
289        ]
290    })
291}
292
293/// The RSR lengths, if the word is feasible.
294fn rsr(d: f64, alpha: f64, beta: f64, g: &Trig) -> Option<[f64; 3]> {
295    let tmp = 2.0 + d * d - 2.0 * (g.ca * g.cb + g.sa * g.sb - d * (g.sb - g.sa));
296    (tmp >= DUBINS_ZERO).then(|| {
297        let theta = libm::atan2(g.ca - g.cb, d - g.sa + g.sb);
298
299        [
300            mod2pi(alpha - theta),
301            libm::sqrt(tmp.max(0.0)),
302            mod2pi(-beta + theta),
303        ]
304    })
305}
306
307/// The RSL lengths, if the word is feasible.
308fn rsl(d: f64, alpha: f64, beta: f64, g: &Trig) -> Option<[f64; 3]> {
309    let tmp = d * d - 2.0 + 2.0 * (g.ca * g.cb + g.sa * g.sb - d * (g.sa + g.sb));
310    (tmp >= DUBINS_ZERO).then(|| {
311        let p = libm::sqrt(tmp.max(0.0));
312        let theta = libm::atan2(g.ca + g.cb, d - g.sa - g.sb) - libm::atan2(2.0, p);
313
314        [mod2pi(alpha - theta), p, mod2pi(beta - theta)]
315    })
316}
317
318/// The LSR lengths, if the word is feasible.
319fn lsr(d: f64, alpha: f64, beta: f64, g: &Trig) -> Option<[f64; 3]> {
320    let tmp = -2.0 + d * d + 2.0 * (g.ca * g.cb + g.sa * g.sb + d * (g.sa + g.sb));
321    (tmp >= DUBINS_ZERO).then(|| {
322        let p = libm::sqrt(tmp.max(0.0));
323        let theta = libm::atan2(-g.ca - g.cb, d + g.sa + g.sb) - libm::atan2(-2.0, p);
324
325        [mod2pi(-alpha + theta), p, mod2pi(-beta + theta)]
326    })
327}
328
329/// The RLR lengths, if the word is feasible.
330fn rlr(d: f64, alpha: f64, beta: f64, g: &Trig) -> Option<[f64; 3]> {
331    let tmp = 0.125 * (6.0 - d * d + 2.0 * (g.ca * g.cb + g.sa * g.sb + d * (g.sa - g.sb)));
332    (libm::fabs(tmp) < 1.0).then(|| {
333        let p = TAU - libm::acos(tmp);
334        let theta = libm::atan2(g.ca - g.cb, d - g.sa + g.sb);
335        let t = mod2pi(alpha - theta + 0.5 * p);
336
337        [t, p, mod2pi(alpha - beta - t + p)]
338    })
339}
340
341/// The LRL lengths, if the word is feasible.
342fn lrl(d: f64, alpha: f64, beta: f64, g: &Trig) -> Option<[f64; 3]> {
343    let tmp = 0.125 * (6.0 - d * d + 2.0 * (g.ca * g.cb + g.sa * g.sb - d * (g.sa - g.sb)));
344    (libm::fabs(tmp) < 1.0).then(|| {
345        let p = TAU - libm::acos(tmp);
346        let theta = libm::atan2(-g.ca + g.cb, d + g.sa - g.sb);
347        let t = mod2pi(-alpha + theta + 0.5 * p);
348
349        [t, p, mod2pi(beta - alpha - t + p)]
350    })
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use crate::space::curve::tests::{assert_same_pose, pose_pairs};
357    use core::f64::consts::{FRAC_PI_2, PI};
358
359    /// The Dubins distance between two poses given as tuples.
360    fn length(radius: f64, from: (f64, f64, f64), to: (f64, f64, f64)) -> f64 {
361        Dubins::new(radius).distance(
362            &Se2State::new(from.0, from.1, from.2),
363            &Se2State::new(to.0, to.1, to.2),
364        )
365    }
366
367    #[test]
368    fn known_path_lengths() {
369        // pydubins tests/test-dubins.py and Dubins-Curves tests/stableapi_tests.cpp.
370        assert!((length(1.0, (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)) - 10.0).abs() < 1e-9);
371        assert!((length(2.0, (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)) - 10.0).abs() < 1e-9);
372        assert!((length(1.0, (0.0, 0.0, 0.0), (4.0, 0.0, 0.0)) - 4.0).abs() < 1e-9);
373        assert!((length(2.0, (0.0, 0.0, 0.0), (0.0, -0.1, 0.0)) - (4.0 * PI + 0.1)).abs() < 1e-9);
374        assert!((length(1.0, (0.0, 0.0, 0.0), (0.0, 2.0, -PI)) - PI).abs() < 1e-9);
375        assert!(length(1.0, (0.0, 0.0, 0.0), (0.0, 0.0, 0.0)).abs() < 1e-12);
376        assert!(
377            length(2.0, (0.0, 0.0, 0.0), (10.0, 10.0, FRAC_PI_2 / 2.0))
378                > length(1.0, (0.0, 0.0, 0.0), (10.0, 10.0, FRAC_PI_2 / 2.0))
379        );
380
381        // Hand-derived: a quarter turn left of radius 2, then 3 straight up.
382        assert!((length(2.0, (0.0, 0.0, 0.0), (2.0, 5.0, FRAC_PI_2)) - (PI + 3.0)).abs() < 1e-9);
383    }
384
385    #[test]
386    fn known_words_and_segments() {
387        let car = Dubins::new(1.0);
388        let (a, b) = (
389            Se2State::new(0.0, 0.0, FRAC_PI_2),
390            Se2State::new(1.0, 0.0, -FRAC_PI_2),
391        );
392        assert_eq!(
393            car.path(&a, &b).word,
394            DubinsWord::Lrl,
395            "pydubins test_easy_lrl"
396        );
397
398        let (a, b) = (Se2State::new(0.0, 0.0, 0.0), Se2State::new(4.0, 0.0, 0.0));
399        let lsl = car.candidates(&a, &b)[0].expect("LSL exists");
400        let lengths = lsl.segments.map(|segment| segment.length);
401        assert!(
402            lengths
403                .iter()
404                .zip([0.0, 4.0, 0.0])
405                .all(|(l, e)| (l - e).abs() < 1e-12)
406        );
407
408        let far = Se2State::new(10.0, 0.0, 0.0);
409        assert_eq!(
410            car.candidates(&a, &far)[5],
411            None,
412            "LRL is infeasible beyond 4 radii"
413        );
414    }
415
416    #[test]
417    fn every_candidate_reaches_its_target() {
418        for radius in [0.5, 1.0, 2.5] {
419            let car = Dubins::new(radius);
420
421            for (from, to) in pose_pairs(500, 3) {
422                for path in car.candidates(&from, &to).into_iter().flatten() {
423                    assert!(path.segments.iter().all(|segment| segment.length >= 0.0));
424                    assert_same_pose(&path.state_at(&from, path.length()), &to, 1e-6);
425                }
426
427                let best = car.path(&from, &to);
428                assert_same_pose(&best.state_at(&from, best.length()), &to, 1e-6);
429            }
430        }
431    }
432
433    #[test]
434    fn distance_satisfies_the_triangle_inequality_and_interpolates_along_the_path() {
435        let car = Dubins::new(1.3);
436        let pairs = pose_pairs(300, 4);
437
438        for window in pairs.windows(2) {
439            let ((a, b), (c, _)) = (window[0], window[1]);
440            assert!(car.distance(&a, &c) <= car.distance(&a, &b) + car.distance(&b, &c) + 1e-6);
441        }
442
443        for (from, to) in pairs {
444            let total = car.distance(&from, &to);
445            assert_eq!(car.interpolate(&from, &to, 0.0), from);
446            assert_eq!(car.interpolate(&from, &to, 1.0), to);
447
448            for t in [0.1, 0.5, 0.9] {
449                let mid = car.interpolate(&from, &to, t);
450                assert!(
451                    (car.distance(&from, &mid) - t * total).abs() < 1e-6,
452                    "prefixes of shortest paths are shortest"
453                );
454            }
455        }
456    }
457
458    #[test]
459    #[should_panic(expected = "turning radius")]
460    fn rejects_non_positive_radii() {
461        let _ = Dubins::new(-1.0);
462    }
463}