Skip to main content

scal_core/
camera.rs

1use glam::{Mat4, Vec2, vec3};
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
5/// Camera LOL
6pub struct Camera {
7    /// Makes the renderer write camera's matrix into buffer
8    pub dirty: bool,
9    // Size of the space that is used in animations.
10    /// For example, if the virtual_size= 1080 then objects with transform at y= 540 will be at the
11    /// center of your screen no mater the render resolution.
12    pub virtual_size: Vec2,
13    /// Offsets the whole scene
14    pub position: Vec2,
15    /// Zooms in on the whole scene
16    pub zoom: f32,
17}
18
19impl Camera {
20    #[must_use]
21    /// ``virtual_size``- Size of the space that is used in animations.
22    /// For example, if the virtual_size= 1080 then objects with transform at y= 540 will be at the
23    /// center of your screen no mater the render resolution.
24    /// ``position``- Offsets the whole scene
25    /// ``zoom``- Zooms in on the whole scene
26    pub const fn new(virtual_size: Vec2, position: Vec2, zoom: f32) -> Self {
27        Self {
28            dirty: true,
29            virtual_size,
30            position,
31            zoom,
32        }
33    }
34    #[must_use]
35    /// Internal function go the projection matrix
36    pub fn get_matrix(&self) -> Mat4 {
37        let view = Mat4::from_translation(vec3(-self.position.x, -self.position.y, 0.0))
38            * Mat4::from_scale(vec3(self.zoom, self.zoom, 1.0));
39
40        let projection = ortho(0.0, self.virtual_size.x, self.virtual_size.y, 0.0);
41
42        projection * view
43    }
44}
45
46fn ortho(left: f32, right: f32, bottom: f32, top: f32) -> Mat4 {
47    Mat4::from_cols_array(&[
48        2.0 / (right - left),
49        0.0,
50        0.0,
51        0.0,
52        0.0,
53        2.0 / (top - bottom),
54        0.0,
55        0.0,
56        0.0,
57        0.0,
58        1.0,
59        0.0,
60        -(right + left) / (right - left),
61        -(top + bottom) / (top - bottom),
62        0.0,
63        1.0,
64    ])
65}