1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 * Blue Engine by Elham Aryanpur
 *
 * The license is same as the one on the root.
*/

use crate::{
    header::{uniform_type::Matrix, Camera, Renderer},
    CameraContainer, Projection,
};
use eyre::Result;
use winit::dpi::PhysicalSize;

use super::default_resources::{DEFAULT_MATRIX_4, OPENGL_TO_WGPU_MATRIX};

impl Camera {
    /// Creates a new camera. this should've been automatically done at the time of creating an engine
    pub fn new(window_size: PhysicalSize<u32>, renderer: &mut Renderer) -> Result<Self> {
        let camera_uniform = renderer.build_uniform_buffer(&[
            renderer.build_uniform_buffer_part("Camera Uniform", DEFAULT_MATRIX_4)
        ])?;

        let mut camera = Self {
            position: nalgebra_glm::vec3(0.0, 0.0, 3.0),
            target: nalgebra_glm::vec3(0.0, 0.0, -1.0),
            up: nalgebra_glm::vec3(0.0, 1.0, 0.0),
            resolution: (window_size.width as f32, window_size.height as f32),
            projection: crate::Projection::Perspective {
                fov: 70f32 * (std::f32::consts::PI / 180f32),
            },
            near: 0.1,
            far: 100.0,
            view_data: DEFAULT_MATRIX_4.to_im(),
            changed: true,
            uniform_data: camera_uniform.0,
            add_position_and_target: false,
        };
        camera.build_view_projection_matrix()?;

        Ok(camera)
    }

    /// Updates the view uniform matrix that decides how camera works
    pub fn build_view_projection_matrix(&mut self) -> Result<()> {
        let view = self.build_view_matrix();
        let proj = self.build_projection_matrix();
        self.view_data = OPENGL_TO_WGPU_MATRIX * proj * view;
        self.changed = true;

        Ok(())
    }

    /// Updates the view uniform matrix that decides how camera works
    pub fn build_view_orthographic_matrix(&mut self) -> Result<()> {
        let view = self.build_view_matrix();
        let ortho = nalgebra_glm::ortho(
            0f32,
            self.resolution.0,
            0f32,
            self.resolution.1,
            self.near,
            self.far,
        );
        self.view_data = ortho * view;
        self.changed = true;

        Ok(())
    }

    /// Returns a matrix uniform buffer from camera data that can be sent to GPU
    pub fn camera_uniform_buffer(&self) -> Result<Matrix> {
        Ok(Matrix::from_im(self.view_data))
    }

    /// Sets the position of camera
    pub fn set_position(&mut self, x: f32, y: f32, z: f32) -> Result<()> {
        self.position = nalgebra_glm::vec3(x, y, z);
        self.build_view_projection_matrix()?;

        Ok(())
    }

    /// Sets the target of camera
    pub fn set_target(&mut self, x: f32, y: f32, z: f32) -> Result<()> {
        self.target = nalgebra_glm::vec3(x, y, z);
        self.build_view_projection_matrix()?;

        Ok(())
    }

    /// Sets the up of camera
    pub fn set_up(&mut self, x: f32, y: f32, z: f32) -> Result<()> {
        self.up = nalgebra_glm::vec3(x, y, z);
        self.build_view_projection_matrix()?;

        Ok(())
    }

    /// Sets how far camera can look
    pub fn set_far(&mut self, new_far: f32) -> Result<()> {
        self.far = new_far;
        self.build_view_projection_matrix()?;

        Ok(())
    }

    /// Sets how near the camera can look
    pub fn set_near(&mut self, new_near: f32) -> Result<()> {
        self.near = new_near;
        self.build_view_projection_matrix()?;

        Ok(())
    }

    /// Sets the aspect ratio of the camera
    pub fn set_resolution(&mut self, window_size: PhysicalSize<u32>) -> Result<()> {
        self.resolution = (window_size.width as f32, window_size.height as f32);
        self.build_view_projection_matrix()?;

        Ok(())
    }

    /// Sets the projection of the camera
    pub fn set_projection(&mut self, projection: Projection) -> Result<()> {
        self.projection = projection;
        self.build_view_projection_matrix()?;

        Ok(())
    }

    /// Enables adding position and target for the view target
    pub fn add_position_and_target(&mut self, enable: bool) {
        self.add_position_and_target = enable;
    }

    /// This builds a uniform buffer data from camera view data that is sent to the GPU in next frame
    pub fn update_view_projection(&mut self, renderer: &mut Renderer) -> Result<()> {
        if self.changed {
            let updated_buffer = renderer
                .build_uniform_buffer(&[renderer.build_uniform_buffer_part(
                    "Camera Uniform",
                    self.camera_uniform_buffer()
                        .expect("Couldn't build camera projection"),
                )])
                .expect("Couldn't update the camera uniform buffer")
                .0;
            self.uniform_data = updated_buffer;
            self.changed = false;
        }

        Ok(())
    }

    /// This builds a uniform buffer data from camera view data that is sent to the GPU in next frame, and returns the bindgroup
    pub fn update_view_projection_and_return(
        &mut self,
        renderer: &mut Renderer,
    ) -> Result<crate::UniformBuffers> {
        let updated_buffer = renderer
            .build_uniform_buffer(&[renderer.build_uniform_buffer_part(
                "Camera Uniform",
                self.camera_uniform_buffer()
                    .expect("Couldn't build camera projection"),
            )])
            .expect("Couldn't update the camera uniform buffer")
            .0;

        Ok(updated_buffer)
    }

    /// Builds a view matrix for camera projection
    pub fn build_view_matrix(&self) -> nalgebra_glm::Mat4 {
        nalgebra_glm::look_at_rh(
            &self.position,
            &if self.add_position_and_target {
                self.position + self.target
            } else {
                self.target
            },
            &self.up,
        )
    }

    /// Builds a projection matrix for camera
    pub fn build_projection_matrix(&self) -> nalgebra_glm::Mat4 {
        let aspect = self.resolution.0 / self.resolution.1;

        match self.projection {
            crate::Projection::Perspective { fov } => {
                nalgebra_glm::perspective(aspect, fov, self.near, self.far)
            }
            crate::Projection::Orthographic { zoom } => {
                let width = zoom;
                let height = width / aspect;

                let left = width * -0.5;
                let right = width * 0.5;
                let bottom = height * -0.5;
                let top = height * 0.5;

                nalgebra_glm::ortho(left, right, bottom, top, self.near, self.far)
            }
        }
    }
}

impl CameraContainer {
    /// Creates new CameraContainer with one main camera
    pub fn new(window_size: PhysicalSize<u32>, renderer: &mut Renderer) -> eyre::Result<Self> {
        let mut cameras = std::collections::HashMap::new();
        let main_camera = Camera::new(window_size, renderer)?;
        cameras.insert("main".into(), main_camera);

        Ok(CameraContainer { cameras })
    }

    /// Updates the view uniform matrix that decides how camera works
    pub fn build_view_projection_matrix(&mut self) -> eyre::Result<()> {
        self.cameras
            .get_mut("main")
            .unwrap()
            .build_view_projection_matrix()?;
        Ok(())
    }
    /// Updates the view uniform matrix that decides how camera works
    pub fn build_view_orthographic_matrix(&mut self) -> eyre::Result<()> {
        self.cameras
            .get_mut("main")
            .unwrap()
            .build_view_orthographic_matrix()?;
        Ok(())
    }
    /// Returns a matrix uniform buffer from camera data that can be sent to GPU
    pub fn camera_uniform_buffer(&self) -> eyre::Result<Matrix> {
        Ok(Matrix::from_im(self.cameras.get("main").unwrap().view_data))
    }
    /// Sets the position of camera
    pub fn set_position(&mut self, x: f32, y: f32, z: f32) -> eyre::Result<()> {
        self.cameras
            .get_mut("main")
            .unwrap()
            .set_position(x, y, z)?;
        Ok(())
    }
    /// Sets the target of camera
    pub fn set_target(&mut self, x: f32, y: f32, z: f32) -> eyre::Result<()> {
        self.cameras.get_mut("main").unwrap().set_target(x, y, z)?;
        Ok(())
    }
    /// Sets the up of camera
    pub fn set_up(&mut self, x: f32, y: f32, z: f32) -> eyre::Result<()> {
        self.cameras.get_mut("main").unwrap().set_up(x, y, z)?;
        Ok(())
    }
    /// Sets how far camera can look
    pub fn set_far(&mut self, new_far: f32) -> eyre::Result<()> {
        self.cameras.get_mut("main").unwrap().set_far(new_far)?;
        Ok(())
    }
    /// Sets how near the camera can look
    pub fn set_near(&mut self, new_near: f32) -> eyre::Result<()> {
        self.cameras.get_mut("main").unwrap().set_near(new_near)?;
        Ok(())
    }
    /// Sets the aspect ratio of the camera
    pub fn set_resolution(&mut self, window_size: PhysicalSize<u32>) -> eyre::Result<()> {
        self.cameras
            .get_mut("main")
            .unwrap()
            .set_resolution(window_size)?;
        Ok(())
    }
    /// Sets the projection of the camera
    pub fn set_projection(&mut self, projection: Projection) -> eyre::Result<()> {
        self.cameras
            .get_mut("main")
            .unwrap()
            .set_projection(projection)?;
        Ok(())
    }
    /// Enables adding position and target for the view target
    pub fn add_position_and_target(&mut self, enable: bool) {
        self.cameras
            .get_mut("main")
            .unwrap()
            .add_position_and_target(enable);
    }
    /// This builds a uniform buffer data from camera view data that is sent to the GPU in next frame
    pub fn update_view_projection(&mut self, renderer: &mut Renderer) -> eyre::Result<()> {
        self.cameras
            .get_mut("main")
            .unwrap()
            .update_view_projection(renderer)?;
        Ok(())
    }
    /// This builds a uniform buffer data from camera view data that is sent to the GPU in next frame, and returns the bindgroup
    pub fn update_view_projection_and_return(
        &mut self,
        renderer: &mut Renderer,
    ) -> eyre::Result<crate::UniformBuffers> {
        self.cameras
            .get_mut("main")
            .unwrap()
            .update_view_projection_and_return(renderer)
    }
    /// Builds a view matrix for camera projection
    pub fn build_view_matrix(&self) -> nalgebra_glm::Mat4 {
        self.cameras.get("main").unwrap().build_view_matrix()
    }
    /// Builds a projection matrix for camera
    pub fn build_projection_matrix(&self) -> nalgebra_glm::Mat4 {
        self.cameras.get("main").unwrap().build_projection_matrix()
    }
}