three_rs/extras/
bezier_curves.rs1use super::curve::{Curve, CurveVector};
9use super::interpolations::{cubic_bezier, quadratic_bezier};
10use crate::math::{Vector2, Vector3};
11
12pub trait BezierVector: CurveVector {
15 fn map_components(points: &[&Self], f: impl Fn(&[f64]) -> f64) -> Self;
17 const QUADRATIC_TYPE_NAME: &'static str;
19 const CUBIC_TYPE_NAME: &'static str;
21}
22
23impl BezierVector for Vector2 {
24 fn map_components(points: &[&Self], f: impl Fn(&[f64]) -> f64) -> Self {
25 let xs: Vec<f64> = points.iter().map(|p| p.x).collect();
26 let ys: Vec<f64> = points.iter().map(|p| p.y).collect();
27 Vector2::new(f(&xs), f(&ys))
28 }
29 const QUADRATIC_TYPE_NAME: &'static str = "QuadraticBezierCurve";
30 const CUBIC_TYPE_NAME: &'static str = "CubicBezierCurve";
31}
32
33impl BezierVector for Vector3 {
34 fn map_components(points: &[&Self], f: impl Fn(&[f64]) -> f64) -> Self {
35 let xs: Vec<f64> = points.iter().map(|p| p.x).collect();
36 let ys: Vec<f64> = points.iter().map(|p| p.y).collect();
37 let zs: Vec<f64> = points.iter().map(|p| p.z).collect();
38 Vector3::new(f(&xs), f(&ys), f(&zs))
39 }
40 const QUADRATIC_TYPE_NAME: &'static str = "QuadraticBezierCurve3";
41 const CUBIC_TYPE_NAME: &'static str = "CubicBezierCurve3";
42}
43
44#[derive(Clone, Debug, Default, PartialEq)]
47pub struct QuadraticBezierCurve<P> {
48 pub v0: P,
50 pub v1: P,
52 pub v2: P,
54}
55
56pub type QuadraticBezierCurve3 = QuadraticBezierCurve<Vector3>;
58
59impl<P> QuadraticBezierCurve<P> {
60 pub fn new(v0: P, v1: P, v2: P) -> Self {
62 Self { v0, v1, v2 }
63 }
64}
65
66impl<P: BezierVector> Curve for QuadraticBezierCurve<P> {
67 type Point = P;
68
69 fn type_name(&self) -> &'static str {
70 P::QUADRATIC_TYPE_NAME
71 }
72
73 fn get_point(&self, t: f64) -> P {
74 P::map_components(&[&self.v0, &self.v1, &self.v2], |c| {
75 quadratic_bezier(t, c[0], c[1], c[2])
76 })
77 }
78}
79
80#[derive(Clone, Debug, Default, PartialEq)]
82pub struct CubicBezierCurve<P> {
83 pub v0: P,
85 pub v1: P,
87 pub v2: P,
89 pub v3: P,
91}
92
93pub type CubicBezierCurve3 = CubicBezierCurve<Vector3>;
95
96impl<P> CubicBezierCurve<P> {
97 pub fn new(v0: P, v1: P, v2: P, v3: P) -> Self {
99 Self { v0, v1, v2, v3 }
100 }
101}
102
103impl<P: BezierVector> Curve for CubicBezierCurve<P> {
104 type Point = P;
105
106 fn type_name(&self) -> &'static str {
107 P::CUBIC_TYPE_NAME
108 }
109
110 fn get_point(&self, t: f64) -> P {
111 P::map_components(&[&self.v0, &self.v1, &self.v2, &self.v3], |c| {
112 cubic_bezier(t, c[0], c[1], c[2], c[3])
113 })
114 }
115}