Skip to main content

webizen_studio/render/
mesh.rs

1//! Mesh primitives and transforms — the geometry half of the engine dev-kit.
2//!
3//! A [`Mesh`] is backend-neutral: vertices in local space plus edge and face
4//! index lists. The [`Renderer`](super::Renderer) draws edges as lines, faces as
5//! filled polygons, and vertices as points, so the same mesh works on the CPU
6//! Canvas2D backend today and a WebGPU backend later. Primitive builders
7//! (`cube`, `grid`, `uv_sphere`, `quad`, `line`) replace the hand-rolled geometry
8//! that JS engines (three.js/Babylon) used to provide.
9
10use super::scene::Vec3;
11
12/// Position / Euler-rotation / scale transform. Rotation is applied X→Y→Z.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub struct Transform {
15    pub position: Vec3,
16    pub rotation: Vec3,
17    pub scale: Vec3,
18}
19
20impl Default for Transform {
21    fn default() -> Self {
22        Self {
23            position: Vec3::default(),
24            rotation: Vec3::default(),
25            scale: Vec3::new(1.0, 1.0, 1.0),
26        }
27    }
28}
29
30fn rotate_x(v: Vec3, a: f64) -> Vec3 {
31    let (s, c) = a.sin_cos();
32    Vec3::new(v.x, v.y * c - v.z * s, v.y * s + v.z * c)
33}
34fn rotate_y(v: Vec3, a: f64) -> Vec3 {
35    let (s, c) = a.sin_cos();
36    Vec3::new(v.x * c + v.z * s, v.y, -v.x * s + v.z * c)
37}
38fn rotate_z(v: Vec3, a: f64) -> Vec3 {
39    let (s, c) = a.sin_cos();
40    Vec3::new(v.x * c - v.y * s, v.x * s + v.y * c, v.z)
41}
42
43impl Transform {
44    /// Identity transform translated to `position`.
45    pub fn at(position: Vec3) -> Self {
46        Self {
47            position,
48            ..Default::default()
49        }
50    }
51
52    /// Builder — sets scale.
53    pub fn with_scale(mut self, s: f64) -> Self {
54        self.scale = Vec3::new(s, s, s);
55        self
56    }
57
58    /// Builder — sets rotation.
59    pub fn with_rotation(mut self, rotation: Vec3) -> Self {
60        self.rotation = rotation;
61        self
62    }
63
64    /// Map a local-space point to this transform's space: scale → rotate → translate.
65    pub fn apply(&self, v: Vec3) -> Vec3 {
66        let scaled = Vec3::new(v.x * self.scale.x, v.y * self.scale.y, v.z * self.scale.z);
67        let rotated = rotate_z(
68            rotate_y(rotate_x(scaled, self.rotation.x), self.rotation.y),
69            self.rotation.z,
70        );
71        rotated.add(self.position)
72    }
73}
74
75/// Backend-neutral geometry: local-space vertices plus edge and face index lists.
76#[derive(Clone, Debug, Default, PartialEq)]
77pub struct Mesh {
78    pub vertices: Vec<Vec3>,
79    pub edges: Vec<(usize, usize)>,
80    pub faces: Vec<Vec<usize>>,
81}
82
83impl Mesh {
84    /// A single line segment.
85    pub fn line(a: Vec3, b: Vec3) -> Self {
86        Self {
87            vertices: vec![a, b],
88            edges: vec![(0, 1)],
89            faces: vec![],
90        }
91    }
92
93    /// An axis-aligned cube of the given edge length, centered at the origin.
94    pub fn cube(size: f64) -> Self {
95        let h = size * 0.5;
96        let vertices = vec![
97            Vec3::new(-h, -h, -h),
98            Vec3::new(h, -h, -h),
99            Vec3::new(h, h, -h),
100            Vec3::new(-h, h, -h),
101            Vec3::new(-h, -h, h),
102            Vec3::new(h, -h, h),
103            Vec3::new(h, h, h),
104            Vec3::new(-h, h, h),
105        ];
106        let edges = vec![
107            (0, 1),
108            (1, 2),
109            (2, 3),
110            (3, 0),
111            (4, 5),
112            (5, 6),
113            (6, 7),
114            (7, 4),
115            (0, 4),
116            (1, 5),
117            (2, 6),
118            (3, 7),
119        ];
120        let faces = vec![
121            vec![0, 1, 2, 3],
122            vec![4, 5, 6, 7],
123            vec![0, 1, 5, 4],
124            vec![2, 3, 7, 6],
125            vec![1, 2, 6, 5],
126            vec![0, 3, 7, 4],
127        ];
128        Self {
129            vertices,
130            edges,
131            faces,
132        }
133    }
134
135    /// A single quad face on the XZ plane, centered at the origin.
136    pub fn quad(size: f64) -> Self {
137        let h = size * 0.5;
138        Self {
139            vertices: vec![
140                Vec3::new(-h, 0.0, -h),
141                Vec3::new(h, 0.0, -h),
142                Vec3::new(h, 0.0, h),
143                Vec3::new(-h, 0.0, h),
144            ],
145            edges: vec![(0, 1), (1, 2), (2, 3), (3, 0)],
146            faces: vec![vec![0, 1, 2, 3]],
147        }
148    }
149
150    /// A wireframe grid on the XZ plane: `steps`×`steps` cells spanning ±`span`.
151    pub fn grid(span: f64, steps: usize) -> Self {
152        let steps = steps.max(1);
153        let step = span * 2.0 / steps as f64;
154        let mut vertices = Vec::with_capacity((steps + 1) * (steps + 1));
155        let idx = |x: usize, z: usize| z * (steps + 1) + x;
156        for z in 0..=steps {
157            for x in 0..=steps {
158                vertices.push(Vec3::new(
159                    -span + x as f64 * step,
160                    0.0,
161                    -span + z as f64 * step,
162                ));
163            }
164        }
165        let mut edges = Vec::new();
166        for z in 0..=steps {
167            for x in 0..steps {
168                edges.push((idx(x, z), idx(x + 1, z)));
169            }
170        }
171        for x in 0..=steps {
172            for z in 0..steps {
173                edges.push((idx(x, z), idx(x, z + 1)));
174            }
175        }
176        Self {
177            vertices,
178            edges,
179            faces: vec![],
180        }
181    }
182
183    /// A UV sphere of `radius` with `rings` latitude bands and `segments`
184    /// longitude divisions. Edges trace the wire mesh; faces are the quads.
185    pub fn uv_sphere(radius: f64, rings: usize, segments: usize) -> Self {
186        let rings = rings.max(2);
187        let segments = segments.max(3);
188        let mut vertices = Vec::new();
189        let idx = |r: usize, s: usize| r * segments + s;
190        for r in 0..=rings {
191            let phi = std::f64::consts::PI * r as f64 / rings as f64;
192            let (sp, cp) = phi.sin_cos();
193            for s in 0..segments {
194                let theta = std::f64::consts::TAU * s as f64 / segments as f64;
195                let (st, ct) = theta.sin_cos();
196                vertices.push(Vec3::new(radius * sp * ct, radius * cp, radius * sp * st));
197            }
198        }
199        let mut edges = Vec::new();
200        let mut faces = Vec::new();
201        for r in 0..rings {
202            for s in 0..segments {
203                let s_next = (s + 1) % segments;
204                edges.push((idx(r, s), idx(r, s_next)));
205                edges.push((idx(r, s), idx(r + 1, s)));
206                faces.push(vec![
207                    idx(r, s),
208                    idx(r, s_next),
209                    idx(r + 1, s_next),
210                    idx(r + 1, s),
211                ]);
212            }
213        }
214        Self {
215            vertices,
216            edges,
217            faces,
218        }
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn cube_topology() {
228        let c = Mesh::cube(2.0);
229        assert_eq!(c.vertices.len(), 8);
230        assert_eq!(c.edges.len(), 12);
231        assert_eq!(c.faces.len(), 6);
232        // corner sits at half-size
233        assert_eq!(c.vertices[6], Vec3::new(1.0, 1.0, 1.0));
234    }
235
236    #[test]
237    fn transform_scale_then_translate() {
238        let t = Transform::at(Vec3::new(10.0, 0.0, 0.0)).with_scale(2.0);
239        assert_eq!(t.apply(Vec3::new(1.0, 0.0, 0.0)), Vec3::new(12.0, 0.0, 0.0));
240    }
241
242    #[test]
243    fn grid_vertex_count() {
244        let g = Mesh::grid(5.0, 4);
245        assert_eq!(g.vertices.len(), 25);
246        assert!(g.faces.is_empty());
247    }
248}