Skip to main content

three_rs/extras/
line_curve.rs

1//! Port of `three.js/src/extras/curves/LineCurve.js` and `LineCurve3.js`.
2
3use super::curve::{Curve, CurveVector};
4use crate::math::{Vector2, Vector3};
5
6/// `LineCurve` (`P = Vector2`) and `LineCurve3` (`P = Vector3`): a straight
7/// segment from `v1` to `v2`. The two three.js classes are the same code over
8/// a different vector, so they are one generic struct here.
9#[derive(Clone, Debug, Default, PartialEq)]
10pub struct LineCurve<P> {
11    /// The start point.
12    pub v1: P,
13    /// The end point.
14    pub v2: P,
15}
16
17/// `LineCurve3`.
18pub type LineCurve3 = LineCurve<Vector3>;
19
20impl<P> LineCurve<P> {
21    /// `new LineCurve( v1, v2 )` / `new LineCurve3( v1, v2 )`.
22    pub fn new(v1: P, v2: P) -> Self {
23        Self { v1, v2 }
24    }
25}
26
27/// The arithmetic `LineCurve.getPoint` / `getTangent` need beyond
28/// [`CurveVector`]; implemented for `Vector2` and `Vector3`.
29pub trait LineVector: CurveVector {
30    /// `point.copy( v2 ).sub( v1 ); point.multiplyScalar( t ).add( v1 )`.
31    fn lerp_line(v1: &Self, v2: &Self, t: f64) -> Self;
32    /// `optionalTarget.subVectors( v2, v1 ).normalize()`.
33    fn direction(v1: &Self, v2: &Self) -> Self;
34    /// `'LineCurve'` or `'LineCurve3'`.
35    const TYPE_NAME: &'static str;
36}
37
38macro_rules! line_vector {
39    ($v:ty, $name:literal) => {
40        impl LineVector for $v {
41            fn lerp_line(v1: &Self, v2: &Self, t: f64) -> Self {
42                let mut point = *v2;
43                point.sub(v1);
44                point.multiply_scalar(t).add(v1);
45                point
46            }
47            fn direction(v1: &Self, v2: &Self) -> Self {
48                let mut target = <$v>::default();
49                target.sub_vectors(v2, v1).normalize();
50                target
51            }
52            const TYPE_NAME: &'static str = $name;
53        }
54    };
55}
56
57line_vector!(Vector2, "LineCurve");
58line_vector!(Vector3, "LineCurve3");
59
60impl<P: LineVector> Curve for LineCurve<P> {
61    type Point = P;
62
63    fn type_name(&self) -> &'static str {
64        P::TYPE_NAME
65    }
66
67    /// `isLineCurve` / `isLineCurve3`: a single division.
68    fn curve_path_resolution(&self, _divisions: usize) -> usize {
69        1
70    }
71
72    fn get_point(&self, t: f64) -> P {
73        if t == 1.0 {
74            self.v2
75        } else {
76            P::lerp_line(&self.v1, &self.v2, t)
77        }
78    }
79
80    /// Line curves do not need an arc length mapping.
81    fn get_point_at(&self, u: f64) -> P {
82        self.get_point(u)
83    }
84
85    fn get_tangent(&self, _t: f64) -> P {
86        P::direction(&self.v1, &self.v2)
87    }
88
89    fn get_tangent_at(&self, u: f64) -> P {
90        self.get_tangent(u)
91    }
92}