dubins_path 0.0.2

Dubins Path pathfinding algorithm
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! This Crate calculates Dubins Paths
//!
//! The start point is (0,0) facing in positive y-direction
//!
//! The arguments to get a path are
//!
//!   - radius: the minimum radius you can drive or respectively the radius you want to drive (f64)
//!   - end_point: the point you want to end up at (Point)
//!   - end_angle: the angle you want to have in the end (Angle)
//!
//! The paths can be categorized into two subsections:
//!
//!   - The circle straight circle (CSC) paths:
//!
//!     - right straight right (rsr) paths
//!     - right straight left  (rsl) paths
//!     - left straight right  (lsr) paths
//!     - left straight left   (lsl) paths
//!
//!   note: rsr and lsl paths can be constructed on every point on the plane,
//!         rsl and lsr might return an error if the circles overlap each other,
//!         because then the path cannot be constructed
//!
//!   - The circle circle circle (CCC) paths:
//!
//!     - right left right (rlr) paths
//!     - left right left  (lrl) paths
//!
//!   note: both paths can return an error if the points are too far apart
//!
//!

use euclid::{approxeq::ApproxEq, Point2D, Rotation2D, UnknownUnit};
use thiserror::Error;

pub type Angle = euclid::Angle<f64>;
pub type Point = Point2D<f64, UnknownUnit>;
pub type Vector = euclid::Vector2D<f64, UnknownUnit>;
type Rotation = Rotation2D<f64, UnknownUnit, UnknownUnit>;

#[derive(Debug, Error)]
pub enum Error {
    #[error("inside tangent cannot be constructed (circles too close together)")]
    CirclesTooClose,
    #[error("ccc path cannot be constructed (circles too far apart)")]
    CirclesTooFarApart,
}

/// Vector with origin, angle and magnitude
#[derive(Debug, Copy, Clone)]
pub struct StraightPath {
    pub origin: Point,
    pub vector: Vector,
}

impl StraightPath {
    /// approximate equality to other Vector
    pub fn approx_eq(&self, other: Self) -> bool {
        ApproxEq::approx_eq(&self.vector, &other.vector)
            && ApproxEq::approx_eq(&self.origin, &other.origin)
    }
}

/// Circle vector (Circle + Angle)
#[derive(Debug, Copy, Clone)]
pub struct CirclePath {
    pub center: Point,
    pub radius: f64,
    pub angle: Angle,
}

impl CirclePath {
    ///get the length of the circle vector
    pub fn get_length(&self) -> f64 {
        self.angle.radians * self.radius
    }
    /// approximate equality to other CirclePath
    pub fn approx_eq(&self, other: Self) -> bool {
        if !ApproxEq::approx_eq(&self.center, &other.center) {
            false
        } else if !ApproxEq::approx_eq(&self.radius, &other.radius) {
            false
        } else if !(ApproxEq::approx_eq(&self.angle, &other.angle)
            || ApproxEq::approx_eq(&self.angle.signed(), &other.angle.signed()))
        {
            false
        } else {
            true
        }
    }
}

/// Route with a start Circle, a tangent straight and a end Circle
#[derive(Debug, Copy, Clone)]
pub struct RouteCSC {
    pub start: CirclePath,
    pub tangent: StraightPath,
    pub end: CirclePath,
}

/// Route with 3 Circles
#[derive(Debug, Copy, Clone)]
pub struct RouteCCC {
    pub start: CirclePath,
    pub middle: CirclePath,
    pub end: CirclePath,
}

#[derive(Debug, Copy, Clone)]
pub enum Path {
    CSC(RouteCSC),
    CCC(RouteCCC),
}

/// Route with a start Circle, a tangent straight and a end Circle
impl RouteCSC {
    /// right straight right route
    pub fn rsr(radius: f64, end_point: Point, end_angle: Angle) -> Result<Self, Error> {
        let start_center = Point::new(radius, 0.0);

        // get the center point by adding the end vector to the end point
        // this works because the argument is the angle in positive y direction
        // not positive x direction so we dont have to rotate it here anymore
        // the angle has to be counter clockwise though (thats why we use the inverse end.angle)
        let end_center = end_point
            + Rotation::new(end_angle)
                .inverse()
                .transform_vector(Vector::new(radius, 0.0));

        // get the tangent pitch which is the same as the pitch between the two
        // circle centers since our circles have the same radius
        let mut tangent_angle = Angle::radians(
            ((end_center.y - start_center.y) / (end_center.x - start_center.x)).atan(),
        );

        // if the end circle center x value is smaller than the
        // start circle center x value
        // the angle would be rotated by π so to prevent that:
        if end_center.x < start_center.x {
            tangent_angle += Angle::pi();
        }

        // get the tangent magnitude this, again, is the same as the distance
        // between the two circle centers since our circles have the same radius
        let tangent_magnitude = ((end_center.x - start_center.x).powi(2)
            + (end_center.y - start_center.y).powi(2))
        .sqrt();

        // get the angle of the start circle
        let start_angle = (Angle::frac_pi_2() - tangent_angle).positive();

        // get the tangent origin by moving the vector from the start circle center
        // π/2 to it's own direction and the magnitude of the circle radius
        let tangent_origin = start_center
            + Rotation::new(Angle::pi() - end_angle).transform_vector(Vector::new(radius, 0.0));

        // get the angle of the start circle
        // the angle where we start from the tangent equals the one we finish
        // so we can use that in here
        let end_angle = (end_angle - start_angle).positive();

        Ok(Self {
            start: CirclePath {
                center: start_center,
                radius: radius,
                angle: start_angle,
            },
            tangent: StraightPath {
                origin: tangent_origin,
                vector: Vector::from_angle_and_length(tangent_angle, tangent_magnitude),
            },
            end: CirclePath {
                center: end_center,
                radius: radius,
                angle: end_angle,
            },
        })
    }

    /// left straight left route
    pub fn lsl(radius: f64, end_point: Point, end_angle: Angle) -> Result<Self, Error> {
        let start_center = Point::new(-radius, 0.0);

        // get the center point by adding the end vector to the end point
        // we have to rotate the vector π (π/2 because the given angle is from the y axis
        // and π/2 more to not get the tangent but the vector to the center point)
        // and again we have to use the counter clockwise direction
        let end_center = end_point
            + Rotation::new(Angle::pi() - end_angle).transform_vector(Vector::new(radius, 0.0));

        // get the tangent pitch which is the same as the pitch between the two
        // circle centers since our circles have the same radius
        let mut tangent_angle = Angle::radians(
            ((end_center.y - start_center.y) / (end_center.x - start_center.x)).atan(),
        )
        .positive();

        // if the end circle center x value is smaller than the
        // start circle center x value
        // the angle would be π rotated so to prevent that:
        if end_center.x < start_center.x {
            tangent_angle = (tangent_angle + Angle::pi()).positive();
        }

        // get the tangent magnitude this, again, is the same as the distance
        // between the two circle centers since our circles have the same radius
        let tangent_magnitude = ((end_center.x - start_center.x).abs().powi(2)
            + (end_center.y - start_center.y).abs().powi(2))
        .sqrt();

        // get the angle of the start circle
        let start_angle = (tangent_angle - Angle::frac_pi_2()).positive();

        // get the tangent origin by moving the vector from the start circle center
        // π/2 to it's own direction and the magnitude of the circle radius
        let tangent_origin =
            start_center + Rotation::new(start_angle).transform_vector(Vector::new(radius, 0.0));

        // get the angle of the start circle
        // the angle where we start from the tangent equals the one we finish
        // so we can use that in here
        let end_angle = (end_angle - start_angle).positive();

        Ok(Self {
            start: CirclePath {
                center: start_center,
                radius: radius,
                angle: start_angle,
            },
            tangent: StraightPath {
                origin: tangent_origin,
                vector: Vector::from_angle_and_length(tangent_angle, tangent_magnitude),
            },
            end: CirclePath {
                center: end_center,
                radius: radius,
                angle: end_angle,
            },
        })
    }

    /// right straight left route
    pub fn rsl(radius: f64, end_point: Point, end_angle: Angle) -> Result<Self, Error> {
        let start_center = Point::new(radius, 0.0);

        // get the center point by adding the end vector to the end point
        // we have to rotate the vector π (π/2 because the given angle is from the y axis
        // and π/2 more to not get the tangent but the vector to the center point)
        // and again we have to use the counter clockwise direction
        let end_center = end_point
            + Rotation::new(Angle::pi() - end_angle).transform_vector(Vector::new(radius, 0.0));

        // check if inside tangent can even be constructed
        if ((end_center.x - start_center.x).powi(2) + (end_center.y - start_center.y).powi(2))
            .sqrt()
            < 2.0 * radius
        {
            return Err(Error::CirclesTooClose);
        }

        // get the tangent length via some simple trigonometry
        let tangent_magnitude = ((end_center.x - start_center.x).powi(2)
            + (end_center.y - start_center.y).powi(2)
            - (2.0 * radius).powi(2))
        .sqrt();

        // tangent middle is the same as the middle of the straight from the center of the start
        let tangent_middle = end_center.lerp(start_center, 0.5);

        // get the tangent angle
        let mut tangent_angle = Angle::radians(
            ((end_center.y - tangent_middle.y) / (end_center.x - tangent_middle.x)).atan()
                - (2.0 * radius / tangent_magnitude).atan(),
        );

        // if the end circle center x value is smaller than the
        // start circle center x value
        // the angle would be π rotated so to prevent that:
        if end_center.x < start_center.x {
            tangent_angle += Angle::pi();
        }

        // get the angle of the start circle
        let start_angle = (Angle::frac_pi_2() - tangent_angle).positive();

        // get the tangent origin by moving the vector from the start circle center
        // along its right angle vector
        let tangent_origin = start_center
            + Rotation::new(Angle::pi() - start_angle).transform_vector(Vector::new(radius, 0.0));

        // get the angle of the end circle
        let end_angle = ((Angle::frac_pi_2() - end_angle) - tangent_angle).positive();

        Ok(Self {
            start: CirclePath {
                center: start_center,
                radius: radius,
                angle: start_angle,
            },
            tangent: StraightPath {
                origin: tangent_origin,
                vector: Vector::from_angle_and_length(tangent_angle, tangent_magnitude),
            },
            end: CirclePath {
                center: end_center,
                radius: radius,
                angle: end_angle,
            },
        })
    }

    /// left straight right route
    pub fn lsr(radius: f64, end_point: Point, end_angle: Angle) -> Result<Self, Error> {
        let start_center = Point::new(-radius, 0.0);

        // get the center point by adding the end vector to the end point
        // this works because the argument is the angle in positive y direction
        // not positive x direction so we dont have to rotate it here anymore
        // the angle has to be counter clockwise though (thats why 2π - end.angle)
        let end_center = end_point
            + Rotation::new(end_angle)
                .inverse()
                .transform_vector(Vector::new(radius, 0.0));

        // check if inside tangent can even be constructed
        if ((end_center.x - start_center.x).powi(2) + (end_center.y - start_center.y).powi(2))
            .sqrt()
            < 2.0 * radius
        {
            return Err(Error::CirclesTooClose);
        }

        // get the tangent length via some simple trigonometry
        let tangent_magnitude = ((end_center.x - start_center.x).powi(2)
            + (end_center.y - start_center.y).powi(2)
            - (2.0 * radius).powi(2))
        .sqrt();

        // tangent middle is the same as the middle of the straight from the center of the start
        let tangent_middle = end_center.lerp(start_center, 0.5);

        // get the tangent angle
        let mut tangent_angle = Angle::radians(
            ((end_center.y - tangent_middle.y) / (end_center.x - tangent_middle.x)).atan()
                + (2.0 * radius / tangent_magnitude).atan(),
        );

        // if the end circle center x value is smaller than the
        // start circle center x value
        // the angle would rotated by π so to prevent that:
        if end_center.x < start_center.x {
            tangent_angle += Angle::pi();
        }

        // get the angle of the start circle
        let start_angle = (tangent_angle - Angle::frac_pi_2()).positive();

        // get the tangent origin by moving the vector from the start circle center
        // π/2 to it's own direction and the magnitude of the circle radius
        let tangent_origin =
            start_center + Rotation::new(start_angle).transform_vector(Vector::new(radius, 0.0));

        // get the angle of the end circle
        let end_angle = ((Angle::frac_pi_2() - end_angle) - tangent_angle).positive();

        Ok(Self {
            start: CirclePath {
                center: start_center,
                radius: radius,
                angle: start_angle,
            },
            tangent: StraightPath {
                origin: tangent_origin,
                vector: Vector::from_angle_and_length(tangent_angle, tangent_magnitude),
            },
            end: CirclePath {
                center: end_center,
                radius: radius,
                angle: end_angle,
            },
        })
    }

    /// get the length of the path
    pub fn get_length(&self) -> f64 {
        self.start.get_length() + self.tangent.vector.length() + self.end.get_length()
    }

    /// get the shortest circle straight circle route
    pub fn get_shortest(radius: f64, end_point: Point, end_angle: Angle) -> Result<Self, Error> {
        let mut route_csc;

        let route_rsr = Self::rsr(radius, end_point, end_angle).unwrap();
        let route_lsl = Self::rsr(radius, end_point, end_angle).unwrap();
        let route_lsr = Self::rsr(radius, end_point, end_angle);
        let route_rsl = Self::rsr(radius, end_point, end_angle);

        route_csc = route_rsr;
        if route_lsl.get_length() < route_csc.get_length() {
            route_csc = route_lsl;
        }
        if let Ok(route_lsr) = route_lsr {
            if route_lsr.get_length() < route_csc.get_length() {
                route_csc = route_lsr;
            }
        }
        if let Ok(route_rsl) = route_rsl {
            if route_rsl.get_length() < route_csc.get_length() {
                route_csc = route_rsl;
            }
        }

        Ok(route_csc)
    }
}

/// Route with 3 Circles
impl RouteCCC {
    /// right left right route (not working yet)
    pub fn rlr(radius: f64, end_point: Point, end_angle: Angle) -> Result<Self, Error> {
        let start_center = Point::new(radius, 0.0);

        // get the center point by adding the end vector to the end point
        // this works because the argument is the angle in positive y direction
        // not positive x direction so we dont have to rotate it here anymore
        // the angle has to be counter clockwise though (thats why we use the inverse end.angle)
        let end_center = end_point
            + Rotation::new(end_angle)
                .inverse()
                .transform_vector(Vector::new(radius, 0.0));

        // check if path can be constructed or if the circles are too far apart
        if ((end_center.x - start_center.x).powi(2) + (end_center.y - start_center.y).powi(2))
            .sqrt()
            > (4.0 * radius)
        {
            return Err(Error::CirclesTooFarApart);
        }

        let vector_start_center_middle_center: Vector;

        let middle_center = {
            let vector_start_center_end_center =
                Vector::new(end_center.x - start_center.x, end_center.y - start_center.y);

            let vector_start_center_middle_center_angle =
                vector_start_center_end_center.angle_from_x_axis().radians
                    + (vector_start_center_end_center.length() / (4.0 * radius)).acos();

            vector_start_center_middle_center = Vector::new(
                (2.0 * radius) * vector_start_center_middle_center_angle.cos(),
                (2.0 * radius) * vector_start_center_middle_center_angle.sin(),
            );

            Point::new(
                start_center.x + vector_start_center_middle_center.x,
                start_center.y + vector_start_center_middle_center.y,
            )
        };

        let vector_middle_center_end_center = Vector::new(
            end_center.x - middle_center.x,
            end_center.y - middle_center.y,
        );

        let start_angle =
            (Angle::pi() - vector_start_center_middle_center.angle_from_x_axis()).positive();

        let middle_angle = Rotation::new(Angle::pi())
            .transform_vector(vector_start_center_middle_center)
            .angle_to(vector_middle_center_end_center)
            .positive();

        let end_angle = Rotation::new(Angle::pi())
            .transform_vector(vector_middle_center_end_center)
            .angle_to(Vector::new(
                end_point.x - end_center.x,
                end_point.y - end_center.y,
            ))
            .positive();

        Ok(Self {
            start: CirclePath {
                center: start_center,
                radius: radius,
                angle: start_angle,
            },
            middle: CirclePath {
                center: middle_center,
                radius: radius,
                angle: middle_angle,
            },
            end: CirclePath {
                center: end_center,
                radius: radius,
                angle: end_angle,
            },
        })
    }

    /// left right left route (not working yet)
    pub fn lrl(radius: f64, end_point: Point, end_angle: Angle) -> Result<Self, Error> {
        let start_center = Point::new(-radius, 0.0);

        // get the center point by adding the end vector to the end point
        // we have to rotate the vector π (π/2 because the given angle is from the y axis
        // and π/2 more to not get the tangent but the vector to the center point)
        // and again we have to use the counter clockwise direction
        let end_center = end_point
            + Rotation::new(Angle::pi() - end_angle).transform_vector(Vector::new(radius, 0.0));

        // check if path can be constructed or if the circles are too far apart
        if ((end_center.x - start_center.x).powi(2) + (end_center.y - start_center.y).powi(2))
            .sqrt()
            > (4.0 * radius)
        {
            return Err(Error::CirclesTooFarApart);
        }

        let vector_start_center_middle_center: Vector;

        let middle_center = {
            let vector_start_center_end_center =
                Vector::new(end_center.x - start_center.x, end_center.y - start_center.y);

            let vector_start_center_middle_center_angle =
                vector_start_center_end_center.angle_from_x_axis().radians
                    - (vector_start_center_end_center.length() / (4.0 * radius)).acos();

            vector_start_center_middle_center = Vector::new(
                (2.0 * radius) * vector_start_center_middle_center_angle.cos(),
                (2.0 * radius) * vector_start_center_middle_center_angle.sin(),
            );

            Point::new(
                start_center.x + vector_start_center_middle_center.x,
                start_center.y + vector_start_center_middle_center.y,
            )
        };

        let vector_middle_center_end_center = Vector::new(
            end_center.x - middle_center.x,
            end_center.y - middle_center.y,
        );

        let start_angle = (vector_start_center_middle_center.angle_from_x_axis()).positive();

        let middle_angle = vector_middle_center_end_center
            .angle_to(
                Rotation::new(Angle::pi()).transform_vector(vector_start_center_middle_center),
            )
            .positive();

        let end_angle = Vector::new(end_point.x - end_center.x, end_point.y - end_center.y)
            .angle_to(Rotation::new(Angle::pi()).transform_vector(vector_middle_center_end_center))
            .positive();

        Ok(Self {
            start: CirclePath {
                center: start_center,
                radius: radius,
                angle: start_angle,
            },
            middle: CirclePath {
                center: middle_center,
                radius: radius,
                angle: middle_angle,
            },
            end: CirclePath {
                center: end_center,
                radius: radius,
                angle: end_angle,
            },
        })
    }

    /// get the length of the path
    pub fn get_length(&self) -> f64 {
        self.start.get_length() + self.middle.get_length() + self.end.get_length()
    }

    /// get the shortest circle circle circle route
    pub fn get_shortest(radius: f64, end_point: Point, end_angle: Angle) -> Result<Self, Error> {
        let route_rlr = Self::rlr(radius, end_point, end_angle);
        let route_lrl = Self::lrl(radius, end_point, end_angle);

        if let Ok(route_rlr) = route_rlr {
            if let Ok(route_lrl) = route_lrl {
                if route_rlr.get_length() < route_lrl.get_length() {
                    Ok(route_rlr)
                } else {
                    Ok(route_lrl)
                }
            } else {
                Ok(route_rlr)
            }
        } else if let Ok(route_lrl) = route_lrl {
            Ok(route_lrl)
        } else {
            Err(Error::CirclesTooFarApart)
        }
    }
}

/// get the shortest path
pub fn get_shortest(radius: f64, end_point: Point, end_angle: Angle) -> Path {
    let route_csc = RouteCSC::get_shortest(radius, end_point, end_angle).unwrap();
    let route_ccc = RouteCCC::get_shortest(radius, end_point, end_angle);
    if let Ok(route_ccc) = route_ccc {
        if route_ccc.get_length() < route_csc.get_length() {
            Path::CCC(route_ccc)
        } else {
            Path::CSC(route_csc)
        }
    } else {
        Path::CSC(route_csc)
    }
}