1use crate::madd::Madd;
17use std::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign};
18
19use crate::MathError;
20
21#[derive(Debug, Clone, Copy, PartialEq)]
27pub struct Vector<const N: usize>(pub [f64; N]);
28
29pub type Vec2 = Vector<2>;
31
32pub type Vec3 = Vector<3>;
34
35impl<const N: usize> Vector<N> {
40 #[must_use]
42 pub fn length_squared(self) -> f64 {
43 let mut sum = 0.0;
44 let mut i = 0;
45 while i < N {
46 sum = self.0[i].madd(self.0[i], sum);
47 i += 1;
48 }
49 sum
50 }
51
52 #[must_use]
54 pub fn length(self) -> f64 {
55 self.length_squared().sqrt()
56 }
57
58 pub fn normalize(self) -> Result<Self, MathError> {
66 let len = self.length();
67 if !len.is_finite() || len < f64::MIN_POSITIVE {
68 return Err(MathError::ZeroVector);
69 }
70 let inv = 1.0 / len;
71 Ok(Self(std::array::from_fn(|i| self.0[i] * inv)))
72 }
73}
74
75impl Vector<2> {
80 #[must_use]
82 pub const fn new(x: f64, y: f64) -> Self {
83 Self([x, y])
84 }
85
86 #[must_use]
88 pub const fn x(self) -> f64 {
89 self.0[0]
90 }
91
92 #[must_use]
94 pub const fn y(self) -> f64 {
95 self.0[1]
96 }
97
98 #[must_use]
100 pub fn dot(self, rhs: Self) -> f64 {
101 self.0[0].madd(rhs.0[0], self.0[1] * rhs.0[1])
102 }
103}
104
105impl Vector<3> {
110 #[must_use]
112 pub const fn new(x: f64, y: f64, z: f64) -> Self {
113 Self([x, y, z])
114 }
115
116 #[must_use]
118 pub const fn x(self) -> f64 {
119 self.0[0]
120 }
121
122 #[must_use]
124 pub const fn y(self) -> f64 {
125 self.0[1]
126 }
127
128 #[must_use]
130 pub const fn z(self) -> f64 {
131 self.0[2]
132 }
133
134 #[must_use]
136 pub fn dot(self, rhs: Self) -> f64 {
137 self.0[0].madd(rhs.0[0], self.0[1].madd(rhs.0[1], self.0[2] * rhs.0[2]))
138 }
139
140 #[must_use]
142 pub fn cross(self, rhs: Self) -> Self {
143 Self([
144 self.0[1].madd(rhs.0[2], -(self.0[2] * rhs.0[1])),
145 self.0[2].madd(rhs.0[0], -(self.0[0] * rhs.0[2])),
146 self.0[0].madd(rhs.0[1], -(self.0[1] * rhs.0[0])),
147 ])
148 }
149}
150
151impl<const N: usize> Add for Vector<N> {
156 type Output = Self;
157
158 fn add(self, rhs: Self) -> Self {
159 Self(std::array::from_fn(|i| self.0[i] + rhs.0[i]))
160 }
161}
162
163impl<const N: usize> AddAssign for Vector<N> {
164 fn add_assign(&mut self, rhs: Self) {
165 for i in 0..N {
166 self.0[i] += rhs.0[i];
167 }
168 }
169}
170
171impl<const N: usize> Sub for Vector<N> {
172 type Output = Self;
173
174 fn sub(self, rhs: Self) -> Self {
175 Self(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
176 }
177}
178
179impl<const N: usize> SubAssign for Vector<N> {
180 fn sub_assign(&mut self, rhs: Self) {
181 for i in 0..N {
182 self.0[i] -= rhs.0[i];
183 }
184 }
185}
186
187impl<const N: usize> Mul<f64> for Vector<N> {
189 type Output = Self;
190
191 fn mul(self, s: f64) -> Self {
192 Self(std::array::from_fn(|i| self.0[i] * s))
193 }
194}
195
196impl<const N: usize> Mul<Vector<N>> for f64 {
198 type Output = Vector<N>;
199
200 fn mul(self, rhs: Vector<N>) -> Vector<N> {
201 Vector(std::array::from_fn(|i| self * rhs.0[i]))
202 }
203}
204
205impl<const N: usize> Neg for Vector<N> {
206 type Output = Self;
207
208 fn neg(self) -> Self {
209 Self(std::array::from_fn(|i| -self.0[i]))
210 }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq)]
219pub struct Position<const N: usize>(pub [f64; N]);
220
221pub type Point2 = Position<2>;
223
224pub type Point3 = Position<3>;
226
227impl Position<2> {
232 #[must_use]
234 pub const fn new(x: f64, y: f64) -> Self {
235 Self([x, y])
236 }
237
238 #[must_use]
240 pub const fn x(self) -> f64 {
241 self.0[0]
242 }
243
244 #[must_use]
246 pub const fn y(self) -> f64 {
247 self.0[1]
248 }
249}
250
251impl Position<3> {
256 #[must_use]
258 pub const fn new(x: f64, y: f64, z: f64) -> Self {
259 Self([x, y, z])
260 }
261
262 #[must_use]
264 pub const fn x(self) -> f64 {
265 self.0[0]
266 }
267
268 #[must_use]
270 pub const fn y(self) -> f64 {
271 self.0[1]
272 }
273
274 #[must_use]
276 pub const fn z(self) -> f64 {
277 self.0[2]
278 }
279}
280
281impl<const N: usize> Add<Vector<N>> for Position<N> {
287 type Output = Self;
288
289 fn add(self, rhs: Vector<N>) -> Self {
290 Self(std::array::from_fn(|i| self.0[i] + rhs.0[i]))
291 }
292}
293
294impl<const N: usize> Sub<Vector<N>> for Position<N> {
296 type Output = Self;
297
298 fn sub(self, rhs: Vector<N>) -> Self {
299 Self(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
300 }
301}
302
303impl<const N: usize> Sub for Position<N> {
305 type Output = Vector<N>;
306
307 fn sub(self, rhs: Self) -> Vector<N> {
308 Vector(std::array::from_fn(|i| self.0[i] - rhs.0[i]))
309 }
310}
311
312macro_rules! impl_serde_for_array_newtype {
320 ($ty:ident, $name:expr) => {
321 #[cfg(feature = "serde")]
322 impl<const N: usize> serde::Serialize for $ty<N> {
323 fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
324 use serde::ser::SerializeTuple;
325 let mut tup = ser.serialize_tuple(N)?;
326 for &val in &self.0 {
327 tup.serialize_element(&val)?;
328 }
329 tup.end()
330 }
331 }
332
333 #[cfg(feature = "serde")]
334 impl<'de, const N: usize> serde::Deserialize<'de> for $ty<N> {
335 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
336 struct ArrayVisitor<const M: usize>;
337
338 impl<'de, const M: usize> serde::de::Visitor<'de> for ArrayVisitor<M> {
339 type Value = [f64; M];
340
341 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342 write!(f, "an array of {} floats", M)
343 }
344
345 fn visit_seq<A: serde::de::SeqAccess<'de>>(
346 self,
347 mut seq: A,
348 ) -> Result<Self::Value, A::Error> {
349 let mut arr = [0.0; M];
350 for (i, slot) in arr.iter_mut().enumerate() {
351 *slot = seq
352 .next_element()?
353 .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
354 }
355 Ok(arr)
356 }
357 }
358
359 de.deserialize_tuple(N, ArrayVisitor::<N>).map($ty)
360 }
361 }
362 };
363}
364
365impl_serde_for_array_newtype!(Vector, "Vector");
366impl_serde_for_array_newtype!(Position, "Position");
367
368#[cfg(test)]
373#[allow(clippy::unwrap_used, clippy::expect_used)]
374mod tests {
375 use super::*;
376
377 #[test]
378 fn vec3_dot() {
379 let a = Vec3::new(1.0, 2.0, 3.0);
380 let b = Vec3::new(4.0, 5.0, 6.0);
381 assert!((a.dot(b) - 32.0).abs() < 1e-14);
382 }
383
384 #[test]
385 fn vec3_cross() {
386 let x = Vec3::new(1.0, 0.0, 0.0);
387 let y = Vec3::new(0.0, 1.0, 0.0);
388 let z = x.cross(y);
389 assert!((z.x()).abs() < 1e-14);
390 assert!((z.y()).abs() < 1e-14);
391 assert!((z.z() - 1.0).abs() < 1e-14);
392 }
393
394 #[test]
395 fn vec3_normalize() {
396 let v = Vec3::new(3.0, 4.0, 0.0);
397 let n = v.normalize().expect("non-zero");
398 assert!((n.length() - 1.0).abs() < 1e-14);
399 }
400
401 #[test]
402 fn vec3_zero_normalize_fails() {
403 let v = Vec3::new(0.0, 0.0, 0.0);
404 assert!(v.normalize().is_err());
405 }
406
407 #[test]
408 fn vec3_denormal_normalize_fails() {
409 let v = Vec3::new(1e-320, 0.0, 0.0);
411 assert!(v.normalize().is_err());
412 }
413
414 #[test]
415 fn vec2_dot() {
416 let a = Vec2::new(3.0, 4.0);
417 let b = Vec2::new(1.0, 2.0);
418 assert!((a.dot(b) - 11.0).abs() < 1e-14);
419 }
420
421 #[test]
422 fn point3_sub_gives_vec3() {
423 let a = Point3::new(3.0, 4.0, 5.0);
424 let b = Point3::new(1.0, 1.0, 1.0);
425 let v = a - b;
426 assert!((v.x() - 2.0).abs() < 1e-14);
427 assert!((v.y() - 3.0).abs() < 1e-14);
428 assert!((v.z() - 4.0).abs() < 1e-14);
429 }
430
431 #[test]
432 fn point3_add_vec3() {
433 let p = Point3::new(1.0, 2.0, 3.0);
434 let v = Vec3::new(1.0, 1.0, 1.0);
435 let q = p + v;
436 assert!((q.x() - 2.0).abs() < 1e-14);
437 }
438
439 #[test]
440 fn point3_sub_vec3() {
441 let p = Point3::new(3.0, 4.0, 5.0);
442 let v = Vec3::new(1.0, 1.0, 1.0);
443 let q = p - v;
444 assert!((q.x() - 2.0).abs() < 1e-14);
445 assert!((q.y() - 3.0).abs() < 1e-14);
446 assert!((q.z() - 4.0).abs() < 1e-14);
447 }
448
449 #[test]
450 fn scalar_times_vec3() {
451 let v = Vec3::new(1.0, 2.0, 3.0);
452 let scaled = 2.0 * v;
453 assert!((scaled.x() - 2.0).abs() < 1e-14);
454 assert!((scaled.y() - 4.0).abs() < 1e-14);
455 assert!((scaled.z() - 6.0).abs() < 1e-14);
456 }
457
458 #[test]
459 fn vec3_add_assign() {
460 let mut a = Vec3::new(1.0, 2.0, 3.0);
461 a += Vec3::new(4.0, 5.0, 6.0);
462 assert!((a.x() - 5.0).abs() < 1e-14);
463 assert!((a.y() - 7.0).abs() < 1e-14);
464 assert!((a.z() - 9.0).abs() < 1e-14);
465 }
466
467 #[test]
468 fn vec3_sub_assign() {
469 let mut a = Vec3::new(5.0, 7.0, 9.0);
470 a -= Vec3::new(1.0, 2.0, 3.0);
471 assert!((a.x() - 4.0).abs() < 1e-14);
472 assert!((a.y() - 5.0).abs() < 1e-14);
473 assert!((a.z() - 6.0).abs() < 1e-14);
474 }
475
476 use proptest::prelude::*;
477
478 proptest! {
479 #[test]
480 fn prop_normalize_unit_length(x in -10.0f64..10.0, y in -10.0f64..10.0, z in -10.0f64..10.0) {
481 let v = Vec3::new(x, y, z);
482 if let Ok(n) = v.normalize() {
483 prop_assert!((n.length() - 1.0).abs() < 1e-12, "length = {}", n.length());
484 }
485 }
486
487 #[test]
488 fn prop_cross_anticommutative(
489 ax in -10.0f64..10.0, ay in -10.0f64..10.0, az in -10.0f64..10.0,
490 bx in -10.0f64..10.0, by in -10.0f64..10.0, bz in -10.0f64..10.0,
491 ) {
492 let a = Vec3::new(ax, ay, az);
493 let b = Vec3::new(bx, by, bz);
494 let ab = a.cross(b);
495 let ba = b.cross(a);
496 prop_assert!((ab.x() + ba.x()).abs() < 1e-10);
498 prop_assert!((ab.y() + ba.y()).abs() < 1e-10);
499 prop_assert!((ab.z() + ba.z()).abs() < 1e-10);
500 }
501
502 #[test]
503 fn prop_point_sub_vec_inverse_of_add(
504 px in -100.0f64..100.0, py in -100.0f64..100.0, pz in -100.0f64..100.0,
505 vx in -100.0f64..100.0, vy in -100.0f64..100.0, vz in -100.0f64..100.0,
506 ) {
507 let p = Point3::new(px, py, pz);
508 let v = Vec3::new(vx, vy, vz);
509 let roundtrip = (p + v) - v;
511 prop_assert!((roundtrip.x() - p.x()).abs() < 1e-10);
512 prop_assert!((roundtrip.y() - p.y()).abs() < 1e-10);
513 prop_assert!((roundtrip.z() - p.z()).abs() < 1e-10);
514 }
515 }
516}