mraphics_core/geometry/
cube.rs1use crate::{GadgetData, Geometry, GeometryIndices};
2use nalgebra::Vector3;
3
4pub struct Cube {
5 pub width: f32,
6 pub height: f32,
7 pub depth: f32,
8}
9
10impl Cube {
11 pub fn new() -> Self {
12 Self::default()
13 }
14}
15
16impl Default for Cube {
17 fn default() -> Self {
18 Self {
19 width: 1.0,
20 height: 1.0,
21 depth: 1.0,
22 }
23 }
24}
25
26impl Geometry for Cube {
27 fn update_view(&self, view: &mut super::GeometryView) {
28 let mut vertices: Vec<f32> = Vec::new();
29
30 let mut build_plane =
31 |position: Vector3<f32>, width_len: f32, height_len: f32, normal: Vector3<f32>| {
32 let mut height = normal.yzx();
33 height.set_magnitude(height_len);
34
35 let mut width = height.cross(&normal);
36 width.set_magnitude(width_len);
37
38 vertices.extend(position.iter().chain(std::iter::once(&1.0)));
39 vertices.extend((position + width).iter().chain(std::iter::once(&1.0)));
40 vertices.extend(
41 (position + width + height)
42 .iter()
43 .chain(std::iter::once(&1.0)),
44 );
45 vertices.extend((position + height).iter().chain(std::iter::once(&1.0)));
46 vertices.extend(position.iter().chain(std::iter::once(&1.0)));
47 vertices.extend(
48 (position + width + height)
49 .iter()
50 .chain(std::iter::once(&1.0)),
51 );
52 };
53
54 let w = self.width;
55 let h = self.height;
56 let d = self.depth;
57
58 build_plane(
59 Vector3::new(-w / 2.0, -h / 2.0, -d / 2.0),
60 w,
61 h,
62 Vector3::z(),
63 );
64 build_plane(
65 Vector3::new(-w / 2.0, -h / 2.0, d / 2.0),
66 w,
67 h,
68 Vector3::z(),
69 );
70 build_plane(
71 Vector3::new(w / 2.0, -h / 2.0, -d / 2.0),
72 h,
73 d,
74 Vector3::x(),
75 );
76 build_plane(
77 Vector3::new(-w / 2.0, -h / 2.0, d / 2.0),
78 h,
79 d,
80 -Vector3::x(),
81 );
82 build_plane(
83 Vector3::new(-w / 2.0, h / 2.0, -d / 2.0),
84 d,
85 w,
86 Vector3::y(),
87 );
88 build_plane(
89 Vector3::new(w / 2.0, -h / 2.0, -d / 2.0),
90 d,
91 w,
92 -Vector3::y(),
93 );
94
95 view.reset_vertices();
96
97 view.attributes.push(GadgetData {
98 label: String::from(crate::constants::POSITION_ATTR_LABEL),
99 index: crate::constants::POSITION_ATTR_INDEX,
100 data: Vec::from(bytemuck::cast_slice::<f32, u8>(&vertices)),
101 needs_update_value: true,
102 needs_update_buffer: true,
103 });
104 view.indices = GeometryIndices::Sequential(vertices.len() as u32);
105 }
106}