midpoint_ui/renderer/
SimpleCamera.rs

1use nalgebra::{Matrix4, Perspective3, Point3, Rotation3, Unit, Vector3};
2
3pub struct SimpleCamera {
4    pub position: Point3<f32>,
5    pub direction: Vector3<f32>,
6    pub up: Vector3<f32>,
7    pub aspect_ratio: f32,
8    pub fovy: f32,
9    pub znear: f32,
10    pub zfar: f32,
11    pub view_projection_matrix: Matrix4<f32>,
12}
13
14impl SimpleCamera {
15    pub fn new(
16        position: Point3<f32>,
17        direction: Vector3<f32>,
18        up: Vector3<f32>,
19        // aspect_ratio: f32,
20        fovy: f32,
21        znear: f32,
22        zfar: f32,
23    ) -> Self {
24        Self {
25            position,
26            direction,
27            up,
28            // aspect_ratio,
29            aspect_ratio: 16.0 / 9.0, // default aspect ratio
30            fovy,
31            znear,
32            zfar,
33            view_projection_matrix: Matrix4::identity(),
34        }
35    }
36
37    pub fn update_aspect_ratio(&mut self, aspect_ratio: f32) {
38        self.aspect_ratio = aspect_ratio;
39    }
40
41    // pub fn build_view_projection_matrix(&self) -> Matrix4<f32> {
42    //     let view = Matrix4::look_at_rh(&self.position, &(self.position + self.direction), &self.up);
43    //     let proj =
44    //         Perspective3::new(self.aspect_ratio, self.fovy, self.znear, self.zfar).to_homogeneous();
45    //     proj * view
46    // }
47
48    pub fn update_view_projection_matrix(&mut self) {
49        let view_matrix =
50            Matrix4::look_at_rh(&self.position, &(self.position + self.direction), &self.up);
51        let projection_matrix =
52            Matrix4::new_perspective(self.aspect_ratio, self.fovy, self.znear, self.zfar);
53        self.view_projection_matrix = projection_matrix * view_matrix;
54    }
55
56    pub fn update(&mut self) {
57        self.update_view_projection_matrix();
58    }
59
60    pub fn rotate(&mut self, yaw: f32, pitch: f32) {
61        let yaw_rotation = Rotation3::from_axis_angle(&Unit::new_normalize(self.up), yaw);
62        let right = self.up.cross(&self.direction).normalize();
63        let pitch_rotation = Rotation3::from_axis_angle(&Unit::new_normalize(right), pitch);
64
65        let rotation = yaw_rotation * pitch_rotation;
66        self.direction = rotation * self.direction;
67
68        self.update_view_projection_matrix();
69    }
70}