rayengine_core/spatial/
ray.rs1use super::{SpatialError, valid_distance};
4use crate::collision::{Aabb2, Aabb3};
5use glam::{Vec2, Vec3};
6
7#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct Ray2 {
10 pub(crate) origin: Vec2,
12 pub(crate) direction: Vec2,
14}
15
16#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct Ray3 {
19 pub(crate) origin: Vec3,
21 pub(crate) direction: Vec3,
23}
24
25#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct RayHit2 {
28 pub distance: f32,
30 pub point: Vec2,
32 pub normal: Vec2,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq)]
38pub struct RayHit3 {
39 pub distance: f32,
41 pub point: Vec3,
43 pub normal: Vec3,
45}
46
47fn unit<const N: usize>(origin: [f32; N], direction: [f32; N]) -> Result<[f32; N], SpatialError> {
48 if !origin.iter().chain(direction.iter()).all(|v| v.is_finite()) {
49 return Err(SpatialError::InvalidRay);
50 }
51 let scale = direction
52 .iter()
53 .fold(0.0_f32, |largest, v| largest.max(v.abs()));
54 if scale == 0.0 {
55 return Err(SpatialError::InvalidRay);
56 }
57 let scaled = direction.map(|v| v / scale);
60 let squared: f32 = scaled.iter().map(|v| v * v).sum();
61 let length = squared.sqrt();
62 Ok(scaled.map(|v| v / length))
63}
64
65pub(crate) fn slab<const N: usize>(
67 origin: [f32; N],
68 direction: [f32; N],
69 min: [f32; N],
70 max: [f32; N],
71 limit: f32,
72) -> Option<(f32, [f32; N])> {
73 let mut enter = 0.0_f32;
74 let mut exit = limit;
75 let mut normal = [0.0; N];
76 for axis in 0..N {
77 let d = direction[axis];
78 if d == 0.0 {
79 if origin[axis] < min[axis] || origin[axis] > max[axis] {
80 return None;
81 }
82 continue;
83 }
84 let (near, far, side) = if d > 0.0 {
85 (
86 (min[axis] - origin[axis]) / d,
87 (max[axis] - origin[axis]) / d,
88 -1.0,
89 )
90 } else {
91 (
92 (max[axis] - origin[axis]) / d,
93 (min[axis] - origin[axis]) / d,
94 1.0,
95 )
96 };
97 if near >= 0.0 && near >= enter {
98 enter = near;
99 normal = [0.0; N];
100 normal[axis] = side;
101 }
102 exit = exit.min(far);
103 if enter > exit {
104 return None;
105 }
106 }
107 if enter.is_finite() && exit >= 0.0 {
108 Some((enter, normal))
109 } else {
110 None
111 }
112}
113
114macro_rules! ray_impl {
115 ($ray:ident, $hit:ident, $vec:ident, $box:ident, $n:expr) => {
116 impl $ray {
117 pub fn origin(self) -> $vec {
119 self.origin
120 }
121
122 pub fn direction(self) -> $vec {
124 self.direction
125 }
126
127 pub fn new(origin: $vec, direction: $vec) -> Result<Self, SpatialError> {
129 let direction =
130 <$vec>::from_array(unit::<$n>(origin.to_array(), direction.to_array())?);
131 Ok(Self { origin, direction })
132 }
133
134 pub fn at(self, distance: f32) -> $vec {
136 self.origin + self.direction * distance
137 }
138
139 pub fn cast(
146 self,
147 bounds: $box,
148 max_distance: f32,
149 ) -> Result<Option<$hit>, SpatialError> {
150 valid_distance(max_distance)?;
151 if !bounds.min.is_finite()
152 || !bounds.max.is_finite()
153 || !bounds.min.cmple(bounds.max).all()
154 {
155 return Err(SpatialError::InvalidBounds(0));
156 }
157 Ok(slab::<$n>(
158 self.origin.to_array(),
159 self.direction.to_array(),
160 bounds.min.to_array(),
161 bounds.max.to_array(),
162 max_distance,
163 )
164 .map(|(distance, normal)| $hit {
165 distance,
166 point: self.at(distance),
167 normal: <$vec>::from_array(normal),
168 }))
169 }
170 }
171 };
172}
173
174ray_impl!(Ray2, RayHit2, Vec2, Aabb2, 2);
175ray_impl!(Ray3, RayHit3, Vec3, Aabb3, 3);