midpoint_ui/renderer/
Transform.rs1use nalgebra::{Matrix4, Point3, Vector3};
2use wgpu::util::DeviceExt;
3
4use crate::renderer::core::Vertex;
5
6pub struct Transform {
7 position: Vector3<f32>,
8 rotation: Vector3<f32>,
9 scale: Vector3<f32>,
10 uniform_buffer: wgpu::Buffer,
11}
12
13impl Transform {
14 pub fn new(
15 position: Vector3<f32>,
16 rotation: Vector3<f32>,
17 scale: Vector3<f32>,
18 uniform_buffer: wgpu::Buffer,
19 ) -> Self {
20 Self {
21 position,
22 rotation,
23 scale,
24 uniform_buffer,
25 }
26 }
27
28 pub fn update_transform(&self) -> Matrix4<f32> {
29 let translation = Matrix4::new_translation(&self.position);
30 let rotation =
31 Matrix4::from_euler_angles(self.rotation.x, self.rotation.y, self.rotation.z);
32 let scale = Matrix4::new_nonuniform_scaling(&self.scale);
33 translation * rotation * scale
35 }
36
37 pub fn update_uniform_buffer(&self, queue: &wgpu::Queue) {
38 let transform_matrix = self.update_transform();
39 let transform_matrix = transform_matrix.transpose(); let raw_matrix = matrix4_to_raw_array(&transform_matrix);
41 queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&raw_matrix));
42 }
43
44 pub fn translate(&mut self, translation: Vector3<f32>) {
45 self.position += translation;
46 }
47
48 pub fn rotate(&mut self, rotation: Vector3<f32>) {
49 self.rotation += rotation;
50 }
51
52 pub fn scale(&mut self, scale: Vector3<f32>) {
53 self.scale.component_mul_assign(&scale);
54 }
55}
56
57pub fn matrix4_to_raw_array(matrix: &Matrix4<f32>) -> [[f32; 4]; 4] {
58 let mut array = [[0.0; 4]; 4];
59 for i in 0..4 {
60 for j in 0..4 {
61 array[i][j] = matrix[(i, j)];
62 }
63 }
64 array
65}
66
67