use crcbl_core::bounds::{max_lanes_d, min_lanes_d};
use glam::{DMat3, DQuat, DVec3};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Aabb {
pub min: DVec3,
pub max: DVec3,
}
impl Aabb {
pub const EMPTY: Self = Self {
min: DVec3::splat(f64::INFINITY),
max: DVec3::splat(f64::NEG_INFINITY),
};
#[inline]
#[must_use]
pub fn new(min: DVec3, max: DVec3) -> Self {
Self { min, max }
}
#[inline]
#[must_use]
pub fn from_centre_half(centre: DVec3, half: DVec3) -> Self {
Self {
min: centre - half,
max: centre + half,
}
}
#[inline]
#[must_use]
pub fn centre(&self) -> DVec3 {
(self.min + self.max) * 0.5
}
#[inline]
#[must_use]
pub fn extents(&self) -> DVec3 {
self.max - self.min
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.min.x > self.max.x || self.min.y > self.max.y || self.min.z > self.max.z
}
#[inline]
#[must_use]
pub(crate) fn half_surface_area(&self) -> f64 {
if self.is_empty() {
return 0.0;
}
let e = self.extents();
e.x * e.y + e.y * e.z + e.z * e.x
}
#[inline]
#[must_use]
pub fn inflated(self, margin: f64) -> Self {
Self {
min: self.min - DVec3::splat(margin),
max: self.max + DVec3::splat(margin),
}
}
#[inline]
#[must_use]
pub fn union(self, other: Self) -> Self {
if other.is_empty() {
return self;
}
if self.is_empty() {
return other;
}
Self {
min: min_lanes_d(self.min, other.min),
max: max_lanes_d(self.max, other.max),
}
}
#[inline]
#[must_use]
pub fn intersects(&self, other: &Self) -> bool {
self.min.x <= other.max.x
&& self.max.x >= other.min.x
&& self.min.y <= other.max.y
&& self.max.y >= other.min.y
&& self.min.z <= other.max.z
&& self.max.z >= other.min.z
}
#[inline]
#[must_use]
pub fn contains(&self, other: &Self) -> bool {
self.min.x <= other.min.x
&& self.min.y <= other.min.y
&& self.min.z <= other.min.z
&& self.max.x >= other.max.x
&& self.max.y >= other.max.y
&& self.max.z >= other.max.z
}
#[inline]
#[must_use]
pub fn closest_point(&self, point: DVec3) -> Option<DVec3> {
if !self.min.cmple(self.max).all() || point.is_nan() {
return None;
}
Some(point.clamp(self.min, self.max))
}
#[must_use]
pub(crate) fn ray_slab(
&self,
origin: DVec3,
inv_dir: DVec3,
dir_is_neg: [bool; 3],
) -> Option<(f64, f64)> {
let origin = origin.to_array();
let inv_dir = inv_dir.to_array();
let min = self.min.to_array();
let max = self.max.to_array();
let mut t_near = f64::NEG_INFINITY;
let mut t_far = f64::INFINITY;
for axis in 0..3 {
let (lo, hi) = if dir_is_neg[axis] {
(max[axis], min[axis])
} else {
(min[axis], max[axis])
};
if inv_dir[axis].is_finite() {
t_near = t_near.max((lo - origin[axis]) * inv_dir[axis]);
t_far = t_far.min((hi - origin[axis]) * inv_dir[axis]);
} else if origin[axis] < min[axis] || origin[axis] > max[axis] {
return None;
}
}
if t_near > t_far {
return None;
}
Some((t_near, t_far))
}
#[inline]
#[must_use]
pub fn intersect_ray(
&self,
origin: DVec3,
inv_dir: DVec3,
dir_is_neg: [bool; 3],
t_min: f64,
t_max: f64,
) -> bool {
self.ray_slab(origin, inv_dir, dir_is_neg)
.is_some_and(|(t_near, t_far)| t_near <= t_max && t_far >= t_min)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sphere {
pub centre: DVec3,
pub radius: f64,
}
impl Sphere {
#[inline]
#[must_use]
pub fn new(centre: DVec3, radius: f64) -> Self {
debug_assert!(radius >= 0.0, "sphere radius must be non-negative");
Self { centre, radius }
}
#[inline]
#[must_use]
pub fn aabb(&self) -> Aabb {
let r = DVec3::splat(self.radius);
Aabb {
min: self.centre - r,
max: self.centre + r,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BoxCollider {
pub centre: DVec3,
pub half_extents: DVec3,
pub rotation: DQuat,
}
impl BoxCollider {
#[inline]
#[must_use]
pub fn new(centre: DVec3, half_extents: DVec3) -> Self {
debug_assert!(
half_extents.x >= 0.0 && half_extents.y >= 0.0 && half_extents.z >= 0.0,
"box half-extents must be non-negative"
);
Self {
centre,
half_extents,
rotation: DQuat::IDENTITY,
}
}
#[inline]
#[must_use]
pub const fn with_rotation(self, rotation: DQuat) -> Self {
Self { rotation, ..self }
}
#[inline]
#[must_use]
pub fn aabb(&self) -> Aabb {
if !self.is_turned() {
return Aabb {
min: self.centre - self.half_extents,
max: self.centre + self.half_extents,
};
}
let turned = DMat3::from_quat(self.rotation);
let reach = DVec3::new(
turned.row(0).abs().dot(self.half_extents),
turned.row(1).abs().dot(self.half_extents),
turned.row(2).abs().dot(self.half_extents),
);
Aabb {
min: self.centre - reach,
max: self.centre + reach,
}
}
#[inline]
#[must_use]
pub fn is_turned(&self) -> bool {
self.rotation != DQuat::IDENTITY
}
#[inline]
#[must_use]
pub(crate) fn local_aabb(&self) -> Aabb {
Aabb {
min: -self.half_extents,
max: self.half_extents,
}
}
#[inline]
#[must_use]
pub(crate) fn local_point(&self, point: DVec3) -> DVec3 {
self.rotation.inverse() * (point - self.centre)
}
#[inline]
#[must_use]
pub(crate) fn world_point(&self, local: DVec3) -> DVec3 {
self.centre + self.rotation * local
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Capsule {
pub centre: DVec3,
pub radius: f64,
pub half_height: f64,
}
impl Capsule {
#[inline]
#[must_use]
pub fn new(centre: DVec3, radius: f64, half_height: f64) -> Self {
debug_assert!(radius >= 0.0, "capsule radius must be non-negative");
debug_assert!(
half_height >= 0.0,
"capsule half-height must be non-negative"
);
Self {
centre,
radius,
half_height,
}
}
#[inline]
#[must_use]
pub fn aabb(&self) -> Aabb {
let total_half = DVec3::new(self.radius, self.half_height + self.radius, self.radius);
Aabb {
min: self.centre - total_half,
max: self.centre + total_half,
}
}
#[inline]
#[must_use]
pub fn top(&self) -> DVec3 {
DVec3::new(
self.centre.x,
self.centre.y + self.half_height,
self.centre.z,
)
}
#[inline]
#[must_use]
pub fn bottom(&self) -> DVec3 {
DVec3::new(
self.centre.x,
self.centre.y - self.half_height,
self.centre.z,
)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LyingCapsule {
pub head: DVec3,
pub yaw: f64,
pub pitch_sine: f64,
pub radius: f64,
pub length: f64,
}
impl LyingCapsule {
#[inline]
#[must_use]
pub fn new(head: DVec3, yaw: f64, radius: f64, length: f64) -> Self {
debug_assert!(radius >= 0.0, "capsule radius must be non-negative");
debug_assert!(length >= 0.0, "capsule length must be non-negative");
Self {
head,
yaw,
pitch_sine: 0.0,
radius,
length,
}
}
#[inline]
#[must_use]
pub fn with_pitch_sine(self, pitch_sine: f64) -> Self {
debug_assert!(
(-1.0..=1.0).contains(&pitch_sine),
"a pitch sine lies in [-1, 1], not {pitch_sine}"
);
Self { pitch_sine, ..self }
}
#[inline]
#[must_use]
pub fn facing(&self) -> DVec3 {
DVec3::new(
-crcbl_core::trig::sin(self.yaw),
0.0,
-crcbl_core::trig::cos(self.yaw),
)
}
#[inline]
#[must_use]
pub fn axis(&self) -> DVec3 {
let facing = self.facing();
let level = (1.0 - self.pitch_sine * self.pitch_sine).max(0.0).sqrt();
DVec3::new(facing.x * level, self.pitch_sine, facing.z * level)
}
#[inline]
#[must_use]
pub fn feet(&self) -> DVec3 {
self.head - self.axis() * self.length
}
#[inline]
#[must_use]
pub fn aabb(&self) -> Aabb {
let feet = self.feet();
let r = DVec3::splat(self.radius);
Aabb {
min: self.head.min(feet) - r,
max: self.head.max(feet) + r,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_nan_box_does_not_shrink_the_union_it_is_folded_into() {
let low = Aabb::from_centre_half(DVec3::splat(-2.0), DVec3::splat(1.0));
let high = Aabb::from_centre_half(DVec3::splat(2.0), DVec3::splat(1.0));
let nan = Aabb {
min: DVec3::new(f64::NAN, 0.0, 0.0),
max: DVec3::new(f64::NAN, 0.0, 0.0),
};
assert!(
!nan.is_empty(),
"a NaN box reads as non-empty, which is why the early-outs above do not catch it"
);
let folded = [low, high, nan, low]
.into_iter()
.fold(Aabb::EMPTY, Aabb::union);
assert!(
folded.min.x <= low.min.x && folded.max.x >= high.max.x,
"the union came back as {:?}..{:?}, which does not contain the boxes it was folded \
from — a BVH node like this misses every pair in the part it dropped",
folded.min,
folded.max
);
}
#[test]
fn empty_aabb_is_empty() {
assert!(Aabb::EMPTY.is_empty());
}
#[test]
fn point_aabb_is_not_empty() {
let aabb = Aabb::new(DVec3::splat(1.0), DVec3::splat(1.0));
assert!(!aabb.is_empty());
assert_eq!(aabb.min, DVec3::splat(1.0));
assert_eq!(aabb.max, DVec3::splat(1.0));
}
#[test]
fn union_with_empty_is_identity() {
let a = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
assert_eq!(a.union(Aabb::EMPTY), a);
assert_eq!(Aabb::EMPTY.union(a), a);
}
#[test]
fn union_expands_to_contain_both() {
let a = Aabb::from_centre_half(DVec3::new(-2.0, 0.0, 0.0), DVec3::splat(1.0));
let b = Aabb::from_centre_half(DVec3::new(2.0, 0.0, 0.0), DVec3::splat(1.0));
let u = a.union(b);
assert_eq!(u.min.x, -3.0);
assert_eq!(u.max.x, 3.0);
}
#[test]
fn two_overlapping_aabbs_report_that_they_intersect() {
let a = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(2.0));
let b = Aabb::from_centre_half(DVec3::new(1.0, 0.0, 0.0), DVec3::splat(2.0));
assert!(a.intersects(&b));
}
#[test]
fn aabb_does_not_intersect_separated() {
let a = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
let b = Aabb::from_centre_half(DVec3::new(5.0, 0.0, 0.0), DVec3::splat(1.0));
assert!(!a.intersects(&b));
}
#[test]
fn a_ray_aimed_at_a_box_passes_the_slab_test() {
let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
let origin = DVec3::new(-5.0, 0.0, 0.0);
let dir = DVec3::new(1.0, 0.0, 0.0);
let inv_dir = dir.recip();
let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
assert!(aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
}
#[test]
fn a_ray_passing_above_a_box_fails_the_slab_test() {
let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
let origin = DVec3::new(-5.0, 10.0, 0.0);
let dir = DVec3::new(1.0, 0.0, 0.0);
let inv_dir = dir.recip();
let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
assert!(!aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
}
#[test]
fn ray_hits_from_inside() {
let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
let origin = DVec3::ZERO;
let dir = DVec3::new(1.0, 0.0, 0.0);
let inv_dir = dir.recip();
let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
assert!(aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
}
#[test]
fn ray_on_face_with_zero_dir_component_hits() {
let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
let origin = DVec3::new(0.0, 1.0, 0.0);
let dir = DVec3::new(1.0, 0.0, 0.0);
let inv_dir = dir.recip();
let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
assert!(aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
}
#[test]
fn ray_on_face_with_zero_dir_component_parallel_miss() {
let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
let origin = DVec3::new(0.0, 5.0, 0.0);
let dir = DVec3::new(1.0, 0.0, 0.0);
let inv_dir = dir.recip();
let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
assert!(!aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
}
#[test]
fn ray_slab_reports_entry_and_exit() {
let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
let dir = DVec3::X;
let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
let (near, far) = aabb.ray_slab(DVec3::ZERO, dir.recip(), neg).unwrap();
assert!((near + 1.0).abs() < 1e-12);
assert!((far - 1.0).abs() < 1e-12);
}
#[test]
fn the_closest_point_of_a_box_is_on_its_surface_from_outside() {
let aabb = Aabb::new(DVec3::ZERO, DVec3::new(1.0, 2.0, 3.0));
assert_eq!(
aabb.closest_point(DVec3::new(0.5, 5.0, 1.0)),
Some(DVec3::new(0.5, 2.0, 1.0))
);
assert_eq!(
aabb.closest_point(DVec3::new(-4.0, -1.0, 9.0)),
Some(DVec3::new(0.0, 0.0, 3.0))
);
}
#[test]
fn the_closest_point_of_a_box_to_a_point_inside_it_is_that_point() {
let aabb = Aabb::new(DVec3::ZERO, DVec3::new(1.0, 2.0, 3.0));
let inside = DVec3::new(0.25, 1.5, 2.75);
assert_eq!(aabb.closest_point(inside), Some(inside));
let flat = Aabb::new(DVec3::ZERO, DVec3::new(1.0, 0.0, 1.0));
assert_eq!(
flat.closest_point(DVec3::new(0.5, 3.0, 0.5)),
Some(DVec3::new(0.5, 0.0, 0.5))
);
}
#[test]
fn an_empty_or_nan_box_or_a_nan_point_has_no_closest_point() {
let unit = Aabb::new(DVec3::ZERO, DVec3::ONE);
assert_eq!(Aabb::EMPTY.closest_point(DVec3::ZERO), None);
assert_eq!(
Aabb::new(DVec3::ONE, DVec3::ZERO).closest_point(DVec3::ZERO),
None
);
let poisoned = Aabb::new(DVec3::new(f64::NAN, 0.0, 0.0), DVec3::ONE);
assert!(
!poisoned.is_empty(),
"a NaN box reads as non-empty, so is_empty alone would not refuse it"
);
assert_eq!(poisoned.closest_point(DVec3::ZERO), None);
assert_eq!(unit.closest_point(DVec3::new(0.0, f64::NAN, 0.0)), None);
}
#[test]
fn inflated_aabb_is_larger() {
let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
let inflated = aabb.inflated(0.5);
assert_eq!(inflated.min, DVec3::splat(-1.5));
assert_eq!(inflated.max, DVec3::splat(1.5));
}
#[test]
fn from_centre_half_roundtrips() {
let aabb = Aabb::from_centre_half(DVec3::new(1.0, 2.0, 3.0), DVec3::new(0.5, 1.0, 1.5));
assert_eq!(aabb.centre(), DVec3::new(1.0, 2.0, 3.0));
assert_eq!(aabb.extents(), DVec3::new(1.0, 2.0, 3.0));
}
#[test]
fn a_spheres_bounds_are_its_centre_expanded_by_its_radius() {
let s = Sphere::new(DVec3::new(1.0, 2.0, 3.0), 0.5);
let aabb = s.aabb();
assert_eq!(aabb.min, DVec3::new(0.5, 1.5, 2.5));
assert_eq!(aabb.max, DVec3::new(1.5, 2.5, 3.5));
}
#[test]
fn a_box_colliders_bounds_are_its_centre_expanded_by_its_half_extents() {
let b = BoxCollider::new(DVec3::ZERO, DVec3::splat(2.0));
let aabb = b.aabb();
assert_eq!(aabb.min, DVec3::splat(-2.0));
assert_eq!(aabb.max, DVec3::splat(2.0));
}
#[test]
fn a_capsules_bounds_reach_a_radius_past_each_cap_and_a_radius_sideways() {
let c = Capsule::new(DVec3::ZERO, 0.5, 1.0);
let aabb = c.aabb();
assert_eq!(aabb.min, DVec3::new(-0.5, -1.5, -0.5));
assert_eq!(aabb.max, DVec3::new(0.5, 1.5, 0.5));
}
#[test]
fn a_capsules_end_points_exclude_the_radius_its_caps_add() {
let c = Capsule::new(DVec3::new(0.0, 5.0, 0.0), 0.5, 2.0);
assert_eq!(c.top(), DVec3::new(0.0, 7.0, 0.0));
assert_eq!(c.bottom(), DVec3::new(0.0, 3.0, 0.0));
}
#[test]
fn a_lying_capsules_feet_lie_behind_its_head_at_each_quarter_turn() {
use std::f64::consts::{FRAC_PI_2, PI};
let head = DVec3::new(1.0, 2.0, 3.0);
for (yaw, facing) in [
(0.0, DVec3::NEG_Z),
(FRAC_PI_2, DVec3::NEG_X),
(PI, DVec3::Z),
(3.0 * FRAC_PI_2, DVec3::X),
] {
let capsule = LyingCapsule::new(head, yaw, 0.3, 1.6);
assert!(
(capsule.facing() - facing).length() < 1e-12,
"yaw {yaw} faces {:?}, not {facing:?}",
capsule.facing()
);
let feet = head - facing * 1.6;
assert!(
(capsule.feet() - feet).length() < 1e-12,
"yaw {yaw} puts the feet at {:?}, not {feet:?}",
capsule.feet()
);
}
}
#[test]
fn a_lying_capsule_faces_where_the_engines_yaw_rotation_turns_minus_z() {
for yaw in [-2.5, -0.7, 0.3, 1.1, 4.0] {
let turned = crate::rotation_from_scaled_axis(DVec3::Y * yaw) * DVec3::NEG_Z;
let facing = LyingCapsule::new(DVec3::ZERO, yaw, 0.3, 1.6).facing();
assert!(
(facing - turned).length() < 1e-12,
"yaw {yaw}: {facing:?} against {turned:?}"
);
}
}
#[test]
fn a_lying_capsules_bounds_reach_a_radius_past_its_head_and_feet() {
let c = LyingCapsule::new(DVec3::new(0.0, 0.5, 0.0), 0.0, 0.5, 1.5);
let aabb = c.aabb();
assert!((aabb.min - DVec3::new(-0.5, 0.0, -0.5)).length() < 1e-12);
assert!((aabb.max - DVec3::new(0.5, 1.0, 2.0)).length() < 1e-12);
}
#[test]
fn a_positive_pitch_puts_the_head_above_the_feet_a_length_along_the_core() {
let head = DVec3::new(1.0, 2.0, 3.0);
let level = LyingCapsule::new(head, 0.0, 0.3, 1.6);
assert_eq!(level.with_pitch_sine(0.0).feet(), level.feet());
assert_eq!(level.feet(), head + DVec3::Z * 1.6);
let raised = level.with_pitch_sine(0.6);
let feet = raised.feet();
assert!(
(feet - (head + DVec3::new(0.0, -0.6 * 1.6, 0.8 * 1.6))).length() < 1e-12,
"head up by a pitch sine of 0.6 puts the feet at {feet:?}"
);
assert!(((head - feet).length() - 1.6).abs() < 1e-12);
assert!((raised.axis().length() - 1.0).abs() < 1e-12);
let lowered = level.with_pitch_sine(-0.6);
assert!(
lowered.feet().y > head.y,
"a negative pitch raises the feet"
);
assert_eq!(lowered.facing(), raised.facing(), "the yaw alone faces");
}
}