Skip to main content

flake/camera/
camera2d.rs

1use crate::camera::Camera;
2use cgmath::{Vector2, Zero};
3use crate::camera::render_target::RenderTarget;
4
5#[derive(Clone)]
6pub struct Camera2D {
7    pub position: Vector2<f32>,
8    pub width: f32,
9    pub height: f32,
10    pub zoom: f32,
11    pub render_target: Option<RenderTarget>
12}
13
14impl Camera for Camera2D {
15    fn matrix(&self) -> cgmath::Matrix4<f32> {
16        let left = self.position.x;
17        let right = self.position.x + self.width / self.zoom;
18        let top = self.position.y;
19        let bottom = self.position.y + self.height / self.zoom;
20
21        let (near, far) = (-1000.0, 1000.0);
22        let proj = cgmath::ortho(left, right, bottom, top, near, far);
23
24        // OpenGL clip z [-1,1] -> wgpu clip z [0,1]
25        #[rustfmt::skip]
26        let opengl_to_wgpu = cgmath::Matrix4::new(
27            1.0, 0.0, 0.0, 0.0,
28            0.0, 1.0, 0.0, 0.0,
29            0.0, 0.0, 0.5, 0.0,
30            0.0, 0.0, 0.5, 1.0,
31        );
32
33        opengl_to_wgpu * proj
34    }
35}
36
37impl Default for Camera2D {
38    fn default() -> Self {
39        Self {
40            position: Vector2::zero(),
41            width: 800.0,
42            height: 600.0,
43            zoom: 1.0,
44            render_target: None,
45        }
46    }
47}