Skip to main content

vector_space/
lib.rs

1#![no_std]
2#![deny(missing_docs)]
3/*!
4Minimal `VectorSpace` trait for generic vector math.
5
6Defines `Scalar` type and core operation bounds. Use as compatibility layer across vector libraries (math, physics, rendering).
7
8Implement once, use everywhere.
9*/
10
11use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
12use scalars::{Real, Zero};
13
14/// This trait specifies some type to be a vector type.
15/// It specifies the scalar type and is required for other vector types.
16pub trait VectorSpace: Sized + Zero + PartialEq
17where
18    Self: Add<Output = Self>
19        + Sub<Output = Self>
20        + Mul<<Self as VectorSpace>::Scalar, Output = Self>
21        + Div<<Self as VectorSpace>::Scalar, Output = Self>
22        + Neg<Output = Self>,
23{
24    /// The scalar type of the vector space.
25    type Scalar: Real;
26}
27
28impl VectorSpace for f32 {
29    type Scalar = Self;
30}
31impl VectorSpace for f64 {
32    type Scalar = Self;
33}
34
35/// This trait is automatically implemented for vector spaces, which also implement assignment operations.
36pub trait VectorSpaceAssign:
37    VectorSpace + AddAssign + SubAssign + MulAssign<Self::Scalar> + DivAssign<Self::Scalar>
38{
39}
40impl<T> VectorSpaceAssign for T where
41    T: VectorSpace + AddAssign + SubAssign + MulAssign<Self::Scalar> + DivAssign<Self::Scalar>
42{
43}
44
45/// Marker trait for affine spaces, types whose differences are vectors.
46pub trait AffineSpace: Sub<Output = Self::Diff> + Sized {
47    /// The difference type.
48    type Diff: VectorSpace;
49}
50
51impl<T, D> AffineSpace for T
52where
53    T: Sub<Output = D>,
54    D: VectorSpace,
55{
56    type Diff = D;
57}
58
59/// A transformation that maps vectors to vectors.
60///
61/// Math libraries can implement this for their transform types
62/// (matrices, quaternions, rotors, etc.) to enable generic transform support
63/// across libraries that depend on `vector-space`.
64pub trait Transform<V> {
65    /// Applies this transformation to a point.
66    fn apply_point(&self, point: V) -> V;
67}
68
69/// Linear interpolation of two points.
70#[inline]
71pub fn interpolate<T>(a: T, b: T, ratio: <T::Diff as VectorSpace>::Scalar) -> T
72where
73    T: Clone + AffineSpace + Add<T::Diff, Output = T>,
74{
75    a.clone() + (b - a) * ratio
76}