gemath 0.1.0

Type-safe game math with type-level units/spaces, typed angles, and explicit fallible ops (plus optional geometry/collision).
Documentation
use crate::vec3::*;
use crate::math;
use core::marker::PhantomData;

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Aabb3<Unit: Copy = (), Space: Copy = ()> {
    pub center: Vec3<Unit, Space>,
    pub half_size: Vec3<Unit, Space>,
    #[cfg_attr(feature = "serde", serde(skip))]
    _unit: PhantomData<Unit>,
    #[cfg_attr(feature = "serde", serde(skip))]
    _space: PhantomData<Space>,
}

// Type aliases for common units and spaces
pub type Aabb3f32 = Aabb3<(),()>;
pub type Aabb3Meters = Aabb3<Meters,()>;
pub type Aabb3Pixels = Aabb3<Pixels,()>;
pub type Aabb3World = Aabb3<(),World>;
pub type Aabb3Local = Aabb3<(),Local>;
pub type Aabb3Screen = Aabb3<(),Screen>;
pub type Aabb3MetersWorld = Aabb3<Meters,World>;
pub type Aabb3PixelsScreen = Aabb3<Pixels,Screen>;

impl<Unit: Copy, Space: Copy> Aabb3<Unit, Space> {
    #[inline]
    pub const fn new(center: Vec3<Unit, Space>, half_size: Vec3<Unit, Space>) -> Self {
        Self { center, half_size, _unit: PhantomData, _space: PhantomData }
    }

    /// Returns the minimum corner of the AABB.
    pub fn min(&self) -> Vec3<Unit, Space> {
        self.center - self.half_size
    }

    /// Returns the maximum corner of the AABB.
    pub fn max(&self) -> Vec3<Unit, Space> {
        self.center + self.half_size
    }

    /// Constructs an AABB from min and max corners.
    pub fn from_min_max(min: Vec3<Unit, Space>, max: Vec3<Unit, Space>) -> Self {
        let center = (min + max) * 0.5;
        let half_size = (max - min) * 0.5;
        Self { center, half_size, _unit: PhantomData, _space: PhantomData }
    }

    /// Returns the size (width, height, depth) of the AABB.
    pub fn size(&self) -> Vec3<Unit, Space> {
        self.half_size * 2.0
    }

    /// Returns true if the AABB is empty (any half_size <= 0).
    pub fn is_empty(&self) -> bool {
        self.half_size.x <= 0.0 || self.half_size.y <= 0.0 || self.half_size.z <= 0.0
    }

    /// Returns the volume of the AABB.
    pub fn volume(&self) -> f32 {
        let size = self.size();
        size.x * size.y * size.z
    }

    /// Returns true if the point is inside the AABB (inclusive min, exclusive max).
    pub fn contains_point(&self, point: Vec3<Unit, Space>) -> bool {
        let min = self.min();
        let max = self.max();
        point.x >= min.x && point.x < max.x &&
        point.y >= min.y && point.y < max.y &&
        point.z >= min.z && point.z < max.z
    }

    /// Returns true if this AABB intersects with another.
    pub fn intersects(&self, other: &Self) -> bool {
        self.intersection(other).is_some()
    }

    /// Returns the intersection of this AABB with another, or None if they do not overlap.
    pub fn intersection(&self, other: &Self) -> Option<Self> {
        let min_a = self.min();
        let max_a = self.max();
        let min_b = other.min();
        let max_b = other.max();
        let min = min_a.max(min_b);
        let max = max_a.min(max_b);
        if min.x < max.x && min.y < max.y && min.z < max.z {
            Some(Self::from_min_max(min, max))
        } else {
            None
        }
    }

    /// Returns a new AABB expanded to include the given point.
    pub fn expand_to_include(&self, point: Vec3<Unit, Space>) -> Self {
        let min = self.min();
        let max = self.max();
        let new_min = min.min(point);
        let new_max = max.max(point);
        Self::from_min_max(new_min, new_max)
    }

    /// Returns the union (smallest AABB containing both) of self and other.
    pub fn union(&self, other: &Self) -> Self {
        let min = self.min().min(other.min());
        let max = self.max().max(other.max());
        Self::from_min_max(min, max)
    }

    /// Transforms the AABB by a Mat4. Returns the smallest AABB containing the transformed corners.
    #[cfg(feature = "mat4")]
    pub fn transform(&self, mat: &crate::mat4::Mat4) -> Self {
        let min = self.min();
        let max = self.max();
        let corners = [
            Vec3::new(min.x, min.y, min.z),
            Vec3::new(min.x, min.y, max.z),
            Vec3::new(min.x, max.y, min.z),
            Vec3::new(min.x, max.y, max.z),
            Vec3::new(max.x, min.y, min.z),
            Vec3::new(max.x, min.y, max.z),
            Vec3::new(max.x, max.y, min.z),
            Vec3::new(max.x, max.y, max.z),
        ];
        let mut tmin = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
        let mut tmax = Vec3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
        for &c in &corners {
            let v = mat.transform_point(c);
            let v3 = Vec3::new(v.x, v.y, v.z);
            tmin = tmin.min(v3);
            tmax = tmax.max(v3);
        }
        Self::from_min_max(tmin, tmax)
    }

    /// Returns the closest point in the AABB to the given point.
    pub fn closest_point(&self, point: Vec3<Unit, Space>) -> Vec3<Unit, Space> {
        let min = self.min();
        let max = self.max();
        point.clamp(min, max)
    }

    /// Returns the distance from the AABB to the given point (0 if inside).
    pub fn distance(&self, point: Vec3<Unit, Space>) -> f32 {
        let min = self.min();
        let max = self.max();
        let dx = if point.x < min.x {
            min.x - point.x
        } else if point.x > max.x {
            point.x - max.x
        } else {
            0.0
        };
        let dy = if point.y < min.y {
            min.y - point.y
        } else if point.y > max.y {
            point.y - max.y
        } else {
            0.0
        };
        let dz = if point.z < min.z {
            min.z - point.z
        } else if point.z > max.z {
            point.z - max.z
        } else {
            0.0
        };
        math::sqrt(dx * dx + dy * dy + dz * dz)
    }

    /// Ray-AABB intersection (slab method). Returns Some(t) for the first intersection, or None if no hit.
    /// Ray: origin + t * dir, t >= 0. Returns smallest t >= 0.
    pub fn intersect_ray(&self, origin: Vec3<Unit, Space>, dir: Vec3<Unit, Space>) -> Option<f32> {
        let min = self.min();
        let max = self.max();
        let mut tmin = (min.x - origin.x) / dir.x;
        let mut tmax = (max.x - origin.x) / dir.x;
        if tmin > tmax {
            core::mem::swap(&mut tmin, &mut tmax);
        }
        let mut tymin = (min.y - origin.y) / dir.y;
        let mut tymax = (max.y - origin.y) / dir.y;
        if tymin > tymax {
            core::mem::swap(&mut tymin, &mut tymax);
        }
        if (tmin > tymax) || (tymin > tmax) {
            return None;
        }
        tmin = tmin.max(tymin);
        tmax = tmax.min(tymax);
        let mut tzmin = (min.z - origin.z) / dir.z;
        let mut tzmax = (max.z - origin.z) / dir.z;
        if tzmin > tzmax {
            core::mem::swap(&mut tzmin, &mut tzmax);
        }
        if (tmin > tzmax) || (tzmin > tmax) {
            return None;
        }
        tmin = tmin.max(tzmin);
        tmax = tmax.min(tzmax);
        if tmax < 0.0 {
            return None;
        }
        Some(if tmin >= 0.0 { tmin } else { tmax })
    }
}