Skip to main content

rayengine_core/spatial/
visibility.rs

1//! Camera-space bounds for culling without a renderer or graphics context.
2
3use super::SpatialError;
4use crate::{
5    camera::{Camera2D, Camera3D},
6    collision::{Aabb2, Aabb3},
7    viewport::Viewport,
8};
9use glam::{Mat2, Vec2, Vec3, Vec4};
10
11/// Visible 2D camera rectangle, including rotation and fitted/expanded aspect.
12#[derive(Clone, Copy, Debug)]
13pub struct Frustum2D {
14    center: Vec2,
15    right: Vec2,
16    down: Vec2,
17    half: Vec2,
18}
19
20impl Frustum2D {
21    /// Captures the current camera/viewport. Touching boxes count as visible.
22    pub fn from_camera(camera: &Camera2D, viewport: &Viewport) -> Result<Self, SpatialError> {
23        let aspect = viewport.aspect();
24        let half = Vec2::new(camera.view_height * aspect * 0.5, camera.view_height * 0.5);
25        if !camera.target.is_finite()
26            || !camera.rotation.is_finite()
27            || !camera.view_height.is_finite()
28            || camera.view_height <= 0.0
29            || !aspect.is_finite()
30            || aspect <= 0.0
31            || !half.is_finite()
32        {
33            return Err(SpatialError::InvalidCamera);
34        }
35        let rotation = Mat2::from_angle(-camera.rotation);
36        Ok(Self {
37            center: camera.target,
38            right: rotation * Vec2::X,
39            down: rotation * Vec2::Y,
40            half,
41        })
42    }
43
44    /// Exact oriented-rectangle versus AABB visibility test, inclusive of edges.
45    pub fn intersects(&self, bounds: Aabb2) -> bool {
46        if !bounds.min.is_finite() || !bounds.max.is_finite() || !bounds.min.cmple(bounds.max).all()
47        {
48            return false;
49        }
50        let center = bounds.min * 0.5 + bounds.max * 0.5;
51        let extent = (bounds.max - bounds.min) * 0.5;
52        let delta = center - self.center;
53        let axes = [Vec2::X, Vec2::Y, self.right, self.down];
54        axes.into_iter().all(|axis| {
55            let box_radius = axis.x.abs() * extent.x + axis.y.abs() * extent.y;
56            let view_radius =
57                axis.dot(self.right).abs() * self.half.x + axis.dot(self.down).abs() * self.half.y;
58            axis.dot(delta).abs() <= box_radius + view_radius
59        })
60    }
61}
62
63/// Six-plane 3D camera frustum. Box results are conservative near corners.
64#[derive(Clone, Copy, Debug)]
65pub struct Frustum3D {
66    planes: [Vec4; 6],
67}
68
69impl Frustum3D {
70    /// Captures a perspective camera with explicit near/far distances.
71    ///
72    /// The clipping convention matches [`Camera3D::projection`]. Touching
73    /// planes count as visible. The camera must have a valid forward/up basis.
74    pub fn from_camera(
75        camera: &Camera3D,
76        viewport: &Viewport,
77        near: f32,
78        far: f32,
79    ) -> Result<Self, SpatialError> {
80        let aspect = viewport.aspect();
81        let forward = camera.target - camera.position;
82        if !camera.position.is_finite()
83            || !camera.target.is_finite()
84            || !camera.up.is_finite()
85            || !forward.is_finite()
86            || forward.length_squared() <= 0.0
87            || !forward.length_squared().is_finite()
88            || camera.up.cross(forward).length_squared() <= 0.0
89            || !camera.up.cross(forward).length_squared().is_finite()
90            || !camera.vertical_fov.is_finite()
91            || !(0.0..180.0).contains(&camera.vertical_fov)
92            || !aspect.is_finite()
93            || aspect <= 0.0
94            || !near.is_finite()
95            || !far.is_finite()
96            || near <= 0.0
97            || far <= near
98        {
99            return Err(SpatialError::InvalidCamera);
100        }
101        let clip = camera.projection(viewport, near, far) * camera.view_matrix();
102        if !clip.is_finite() {
103            return Err(SpatialError::InvalidCamera);
104        }
105        let columns = clip.to_cols_array_2d();
106        let row = |i| Vec4::new(columns[0][i], columns[1][i], columns[2][i], columns[3][i]);
107        let planes = [
108            row(3) + row(0),
109            row(3) - row(0),
110            row(3) + row(1),
111            row(3) - row(1),
112            row(3) + row(2),
113            row(3) - row(2),
114        ];
115        Ok(Self { planes })
116    }
117
118    /// Conservative AABB visibility: never culls a box touching the frustum.
119    /// May report a box near multiple clipped corners as visible.
120    pub fn intersects(&self, bounds: Aabb3) -> bool {
121        if !bounds.min.is_finite() || !bounds.max.is_finite() || !bounds.min.cmple(bounds.max).all()
122        {
123            return false;
124        }
125        self.planes.iter().all(|plane| {
126            let positive = Vec3::new(
127                if plane.x >= 0.0 {
128                    bounds.max.x
129                } else {
130                    bounds.min.x
131                },
132                if plane.y >= 0.0 {
133                    bounds.max.y
134                } else {
135                    bounds.min.y
136                },
137                if plane.z >= 0.0 {
138                    bounds.max.z
139                } else {
140                    bounds.min.z
141                },
142            );
143            plane.truncate().dot(positive) + plane.w >= 0.0
144        })
145    }
146}