1use glam::{Mat4, Vec3};
4
5#[derive(Clone, Copy, Debug)]
6pub struct Camera {
7 pub view: Mat4,
8 pub proj: Mat4,
9 pub clear_color: [f32; 4],
11}
12
13const NEAR: f32 = 0.1;
14const FAR: f32 = 4000.0;
15
16impl Camera {
17 pub fn perspective(eye: Vec3, target: Vec3, up: Vec3, fovy_rad: f32, aspect: f32) -> Self {
19 Self {
20 view: Mat4::look_at_rh(eye, target, up),
21 proj: Mat4::perspective_rh(fovy_rad, aspect.max(1e-6), NEAR, FAR),
22 clear_color: [0.02, 0.03, 0.05, 1.0],
23 }
24 }
25
26 pub fn orthographic(eye: Vec3, target: Vec3, up: Vec3, height: f32, aspect: f32) -> Self {
28 let h = height * 0.5;
29 let w = h * aspect.max(1e-6);
30 Self {
31 view: Mat4::look_at_rh(eye, target, up),
32 proj: Mat4::orthographic_rh(-w, w, -h, h, NEAR, FAR),
33 clear_color: [0.0, 0.0, 0.0, 1.0],
34 }
35 }
36
37 pub fn view_proj(&self) -> Mat4 {
39 self.proj * self.view
40 }
41
42 pub fn depth_range(&self) -> Option<(f32, f32)> {
56 let zz = self.proj.z_axis.z;
57 let wz = self.proj.w_axis.z;
58 if self.proj.z_axis.w != -1.0 || !zz.is_finite() || !wz.is_finite() || zz >= 0.0 {
59 return None;
60 }
61 let n = wz / zz;
62 let f = wz / (zz + 1.0);
63 if n > 0.0 && f > n {
64 Some((n, f))
65 } else {
66 None
67 }
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn perspektiv_matrix_ist_nicht_entartet() {
77 let cam = Camera::perspective(
78 Vec3::Z * 10.0,
79 Vec3::ZERO,
80 Vec3::Y,
81 std::f32::consts::FRAC_PI_3,
82 1.6,
83 );
84 let p = cam.view_proj().transform_point3(Vec3::ZERO);
85 assert!(p.x.abs() < 1e-3 && p.y.abs() < 1e-3);
87 }
88
89 #[test]
90 fn depth_range_gibt_perspektive_zurueck_ortho_ist_none() {
91 let cam = Camera::perspective(
92 Vec3::Z * 2.0,
93 Vec3::ZERO,
94 Vec3::Y,
95 std::f32::consts::FRAC_PI_3,
96 1.0,
97 );
98 let (n, f) = cam
99 .depth_range()
100 .expect("Perspektive hat eine Tiefen-Spanne");
101 assert!((n - 0.1).abs() < 1e-6, "near {n}");
107 assert!((f - 4000.0).abs() / 4000.0 < 5e-3, "far {f}");
108 let ortho = Camera::orthographic(Vec3::Z * 2.0, Vec3::ZERO, Vec3::Y, 2.0, 1.0);
109 assert_eq!(ortho.depth_range(), None, "orthografisch hat keine");
110 }
111}