ga2 0.3.0

Common types for 2D geometric algebra
Documentation
use crate::*;

use derive_more::{Add, AddAssign, Neg, Sub, SubAssign};
use num_traits::{real::Real, Zero};
use std::ops::{Div, DivAssign, Mul, MulAssign};
use vector_space::{DotProduct, InnerSpace, VectorSpace};

/// The 2D bivector type.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Add, AddAssign, Sub, SubAssign, Neg)]
pub struct Bivector<T> {
    /// The component representing the xy plane.
    pub xy: T,
}

impl<T> Bivector<T> {
    /// Creates a new bivector from its components.
    pub fn new(xy: T) -> Self {
        Self { xy }
    }
}

impl<T: Real> Bivector<T> {
    /// Returns the exponent of the bivector as a rotor.
    pub fn exp(self) -> Rotor<T> {
        let (xy, scalar) = self.xy.sin_cos();
        Rotor { scalar, xy }
    }
}

impl<T: Zero> Bivector<T> {
    /// Creates a new bivector along the xy plane.
    pub fn xy(xy: T) -> Self {
        Self { xy }
    }
}

impl<T: Zero> Zero for Bivector<T> {
    fn zero() -> Self {
        Self { xy: T::zero() }
    }

    fn is_zero(&self) -> bool {
        self.xy.is_zero()
    }
}

impl<T> Mul<T> for Bivector<T>
where
    T: Mul<Output = T> + Copy,
{
    type Output = Self;
    fn mul(self, other: T) -> Self {
        Self {
            xy: self.xy * other,
        }
    }
}

impl<T> MulAssign<T> for Bivector<T>
where
    T: MulAssign + Copy,
{
    fn mul_assign(&mut self, other: T) {
        self.xy *= other;
    }
}

impl<T> Div<T> for Bivector<T>
where
    T: Div<Output = T> + Copy,
{
    type Output = Self;
    fn div(self, other: T) -> Self {
        Self {
            xy: self.xy / other,
        }
    }
}

impl<T> DivAssign<T> for Bivector<T>
where
    T: DivAssign + Copy,
{
    fn div_assign(&mut self, other: T) {
        self.xy /= other;
    }
}

impl<T: Real> VectorSpace for Bivector<T> {
    type Scalar = T;
}

impl<T: Real> DotProduct for Bivector<T> {
    type Output = Self::Scalar;
    fn dot(self, other: Self) -> T {
        -self.xy * other.xy
    }
}

impl<T: Real> DotProduct<Vector<T>> for Bivector<T> {
    type Output = Vector<T>;
    #[inline]
    fn dot(self, other: Vector<T>) -> Vector<T> {
        other.dot(self)
    }
}

impl<T: Real> DotProduct<Rotor<T>> for Bivector<T> {
    type Output = Rotor<T>;
    fn dot(self, other: Rotor<T>) -> Rotor<T> {
        Rotor {
            scalar: -self.xy * other.xy,
            xy: self.xy * other.scalar,
        }
    }
}

impl<T: Real> InnerSpace for Bivector<T> {
    fn scalar(self, other: Self) -> T {
        self.dot(other)
    }

    fn magnitude2(self) -> T {
        -self.dot(self)
    }
}