1#![no_std]
2#![deny(missing_docs)]
3use scalars::{InverseTrigonometry, One, Sqrt};
13
14pub use vector_space::*;
15
16pub trait DotProduct<T = Self>: VectorSpace {
18 type Output;
20
21 fn dot(&self, other: &T) -> <Self as DotProduct<T>>::Output;
23
24 fn scalar(&self, other: &T) -> <Self as DotProduct<T>>::Output {
29 self.dot(other)
30 }
31}
32
33impl DotProduct for f32 {
34 type Output = Self;
35 fn dot(&self, other: &Self) -> Self {
36 *self * *other
37 }
38}
39impl DotProduct for f64 {
40 type Output = Self;
41 fn dot(&self, other: &Self) -> Self {
42 *self * *other
43 }
44}
45
46pub trait InnerSpace: DotProduct<Output = <Self as VectorSpace>::Scalar> {
48 #[inline]
53 fn magnitude2(&self) -> Self::Scalar {
54 self.scalar(self)
55 }
56
57 #[inline]
59 fn magnitude(&self) -> Self::Scalar {
60 self.magnitude2().sqrt()
61 }
62
63 #[inline]
65 fn normalize(self) -> Self {
66 let mag = self.magnitude();
67 self / mag
68 }
69
70 #[inline]
72 fn angle(&self, other: &Self) -> Self::Scalar {
73 (self.dot(other) / (self.magnitude() * other.magnitude())).acos()
74 }
75
76 #[inline]
78 fn with_magnitude(self, magnitude: Self::Scalar) -> Self {
79 let mag = self.magnitude();
80 self * (magnitude / mag)
81 }
82
83 #[inline]
85 fn with_direction(self, dir: Self) -> Self {
86 dir * self.magnitude()
87 }
88
89 #[inline]
91 fn query_axis(&self, dir: Self) -> Self::Scalar {
92 self.dot(&dir.normalize())
93 }
94
95 #[inline]
97 fn normalized_project(self, dir: Self) -> Self {
98 let scalar = self.dot(&dir);
99 dir * scalar
100 }
101
102 #[inline]
104 fn project(self, dir: Self) -> Self {
105 let ratio = self.dot(&dir) / dir.magnitude2();
106 dir * ratio
107 }
108
109 #[inline]
111 fn normalized_reject(self, dir: Self) -> Self {
112 let scalar = self.dot(&dir);
113 let proj = dir * scalar;
114 self - proj
115 }
116
117 #[inline]
119 fn reject(self, dir: Self) -> Self {
120 let ratio = self.dot(&dir) / dir.magnitude2();
121 self - dir * ratio
122 }
123
124 #[inline]
126 fn normalized_reflect(self, dir: Self) -> Self {
127 let scalar = self.dot(&dir);
128 let proj = dir * scalar;
129 proj * (Self::Scalar::one() + Self::Scalar::one()) - self
130 }
131
132 #[inline]
134 fn reflect(self, dir: Self) -> Self {
135 let ratio = self.dot(&dir) / dir.magnitude2();
136 dir * ratio * (Self::Scalar::one() + Self::Scalar::one()) - self
137 }
138}
139
140impl<T: DotProduct<Output = Self::Scalar>> InnerSpace for T {}
141
142pub fn distance<T: AffineSpace>(a: T, b: T) -> <T::Diff as VectorSpace>::Scalar
144where
145 T::Diff: InnerSpace,
146{
147 (b - a).magnitude()
148}
149
150pub fn distance2<T: AffineSpace>(a: T, b: T) -> <T::Diff as VectorSpace>::Scalar
152where
153 T::Diff: InnerSpace,
154{
155 (b - a).magnitude2()
156}
157
158pub fn direction<T: AffineSpace>(a: T, b: T) -> T::Diff
160where
161 T::Diff: InnerSpace,
162{
163 (b - a).normalize()
164}