Skip to main content

buttery_engine/
camera.rs

1use cgmath::{InnerSpace, Matrix4, Point3, Rad, Vector3};
2
3#[rustfmt::skip]
4pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4<f32> = cgmath::Matrix4::from_cols(
5    cgmath::Vector4::new(1.0, 0.0, 0.0, 0.0),
6    cgmath::Vector4::new(0.0, 1.0, 0.0, 0.0),
7    cgmath::Vector4::new(0.0, 0.0, 0.5, 0.0),
8    cgmath::Vector4::new(0.0, 0.0, 0.5, 1.0),
9);
10
11#[derive(Debug, Clone, Copy)]
12pub struct Camera {
13    pub position: Point3<f32>,
14    pub yaw: Rad<f32>,
15    pub pitch: Rad<f32>,
16}
17
18impl Camera {
19    pub fn new<V: Into<Point3<f32>>, Y: Into<Rad<f32>>, P: Into<Rad<f32>>>(
20        position: V,
21        yaw: Y,
22        pitch: P,
23    ) -> Self {
24        Self {
25            position: position.into(),
26            yaw: yaw.into(),
27            pitch: pitch.into(),
28        }
29    }
30
31    pub fn calc_matrix(&self) -> Matrix4<f32> {
32        Matrix4::look_to_rh(self.position, self.direction(), Vector3::unit_y())
33    }
34
35    pub fn direction(&self) -> Vector3<f32> {
36        let (sin_pitch, cos_pitch) = self.pitch.0.sin_cos();
37        let (sin_yaw, cos_yaw) = self.yaw.0.sin_cos();
38        Vector3::new(cos_pitch * cos_yaw, sin_pitch, cos_pitch * sin_yaw).normalize()
39    }
40}