Skip to main content

strata_render/
geometry3d.rs

1//! Parametric 3D Geometry Generators: Box, Sphere, Plane, Cylinder, and Custom Buffers.
2
3use crate::math3d::Vec3;
4
5/// An interleaved 3D vertex with position, normal, and UV coordinates.
6#[repr(C)]
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub struct Vertex3D {
9    pub position: Vec3,
10    pub normal: Vec3,
11    pub uv: (f32, f32),
12}
13
14impl Vertex3D {
15    #[inline(always)]
16    pub const fn new(position: Vec3, normal: Vec3, uv: (f32, f32)) -> Self {
17        Self {
18            position,
19            normal,
20            uv,
21        }
22    }
23}
24
25/// Generated GPU mesh buffers (interleaved vertices and index list).
26#[derive(Debug, Clone, PartialEq, Default)]
27pub struct MeshBuffers {
28    pub vertices: Vec<Vertex3D>,
29    pub indices: Vec<u32>,
30}
31
32impl MeshBuffers {
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    pub fn vertex_count(&self) -> usize {
38        self.vertices.len()
39    }
40
41    pub fn triangle_count(&self) -> usize {
42        self.indices.len() / 3
43    }
44}
45
46/// Generates a 3D Box (cube) with distinct face normals (24 vertices, 36 indices).
47pub fn generate_box(width: f32, height: f32, depth: f32) -> MeshBuffers {
48    let w = width * 0.5;
49    let h = height * 0.5;
50    let d = depth * 0.5;
51
52    let mut vertices = Vec::with_capacity(24);
53    let mut indices = Vec::with_capacity(36);
54
55    let faces = [
56        // Front (+Z)
57        (
58            Vec3::new(0.0, 0.0, 1.0),
59            [
60                Vec3::new(-w, -h, d),
61                Vec3::new(w, -h, d),
62                Vec3::new(w, h, d),
63                Vec3::new(-w, h, d),
64            ],
65        ),
66        // Back (-Z)
67        (
68            Vec3::new(0.0, 0.0, -1.0),
69            [
70                Vec3::new(w, -h, -d),
71                Vec3::new(-w, -h, -d),
72                Vec3::new(-w, h, -d),
73                Vec3::new(w, h, -d),
74            ],
75        ),
76        // Top (+Y)
77        (
78            Vec3::new(0.0, 1.0, 0.0),
79            [
80                Vec3::new(-w, h, d),
81                Vec3::new(w, h, d),
82                Vec3::new(w, h, -d),
83                Vec3::new(-w, h, -d),
84            ],
85        ),
86        // Bottom (-Y)
87        (
88            Vec3::new(0.0, -1.0, 0.0),
89            [
90                Vec3::new(-w, -h, -d),
91                Vec3::new(w, -h, -d),
92                Vec3::new(w, -h, d),
93                Vec3::new(-w, -h, d),
94            ],
95        ),
96        // Right (+X)
97        (
98            Vec3::new(1.0, 0.0, 0.0),
99            [
100                Vec3::new(w, -h, d),
101                Vec3::new(w, -h, -d),
102                Vec3::new(w, h, -d),
103                Vec3::new(w, h, d),
104            ],
105        ),
106        // Left (-X)
107        (
108            Vec3::new(-1.0, 0.0, 0.0),
109            [
110                Vec3::new(-w, -h, -d),
111                Vec3::new(-w, -h, d),
112                Vec3::new(-w, h, d),
113                Vec3::new(-w, h, -d),
114            ],
115        ),
116    ];
117
118    let uvs = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)];
119
120    for (normal, corners) in faces {
121        let base_idx = vertices.len() as u32;
122        for i in 0..4 {
123            vertices.push(Vertex3D::new(corners[i], normal, uvs[i]));
124        }
125        indices.extend_from_slice(&[
126            base_idx,
127            base_idx + 1,
128            base_idx + 2,
129            base_idx,
130            base_idx + 2,
131            base_idx + 3,
132        ]);
133    }
134
135    MeshBuffers { vertices, indices }
136}
137
138/// Generates a UV Sphere with configurable radial rings and segments.
139pub fn generate_sphere(radius: f32, width_segments: u32, height_segments: u32) -> MeshBuffers {
140    let ws = width_segments.max(3);
141    let hs = height_segments.max(2);
142
143    let mut vertices = Vec::new();
144    let mut indices = Vec::new();
145
146    for y in 0..=hs {
147        let v = y as f32 / hs as f32;
148        let theta = v * std::f32::consts::PI;
149
150        for x in 0..=ws {
151            let u = x as f32 / ws as f32;
152            let phi = u * std::f32::consts::TAU;
153
154            let sin_theta = theta.sin();
155            let cos_theta = theta.cos();
156            let sin_phi = phi.sin();
157            let cos_phi = phi.cos();
158
159            let nx = sin_theta * cos_phi;
160            let ny = cos_theta;
161            let nz = sin_theta * sin_phi;
162
163            let normal = Vec3::new(nx, ny, nz);
164            let position = normal * radius;
165
166            vertices.push(Vertex3D::new(position, normal, (u, 1.0 - v)));
167        }
168    }
169
170    for y in 0..hs {
171        for x in 0..ws {
172            let i0 = y * (ws + 1) + x;
173            let i1 = i0 + 1;
174            let i2 = i0 + (ws + 1);
175            let i3 = i2 + 1;
176
177            if y != 0 {
178                indices.extend_from_slice(&[i0, i1, i2]);
179            }
180            if y != hs - 1 {
181                indices.extend_from_slice(&[i1, i3, i2]);
182            }
183        }
184    }
185
186    MeshBuffers { vertices, indices }
187}
188
189/// Generates a planar subdivided grid quad.
190pub fn generate_plane(
191    width: f32,
192    height: f32,
193    width_segments: u32,
194    height_segments: u32,
195) -> MeshBuffers {
196    let ws = width_segments.max(1);
197    let hs = height_segments.max(1);
198
199    let w_half = width * 0.5;
200    let h_half = height * 0.5;
201
202    let mut vertices = Vec::new();
203    let mut indices = Vec::new();
204
205    for y in 0..=hs {
206        let v = y as f32 / hs as f32;
207        let pos_y = h_half - v * height;
208
209        for x in 0..=ws {
210            let u = x as f32 / ws as f32;
211            let pos_x = -w_half + u * width;
212
213            vertices.push(Vertex3D::new(
214                Vec3::new(pos_x, pos_y, 0.0),
215                Vec3::new(0.0, 0.0, 1.0),
216                (u, 1.0 - v),
217            ));
218        }
219    }
220
221    for y in 0..hs {
222        for x in 0..ws {
223            let a = y * (ws + 1) + x;
224            let b = a + 1;
225            let c = a + (ws + 1);
226            let d = c + 1;
227
228            indices.extend_from_slice(&[a, b, c]);
229            indices.extend_from_slice(&[b, d, c]);
230        }
231    }
232
233    MeshBuffers { vertices, indices }
234}
235
236/// Generates a cylinder geometry with top and bottom caps.
237pub fn generate_cylinder(
238    radius_top: f32,
239    radius_bottom: f32,
240    height: f32,
241    radial_segments: u32,
242) -> MeshBuffers {
243    let segments = radial_segments.max(3);
244    let half_h = height * 0.5;
245
246    let mut vertices = Vec::new();
247    let mut indices = Vec::new();
248
249    // 1. Mantle
250    for y in 0..=1 {
251        let v = y as f32;
252        let radius = if y == 0 { radius_top } else { radius_bottom };
253        let py = if y == 0 { half_h } else { -half_h };
254
255        for x in 0..=segments {
256            let u = x as f32 / segments as f32;
257            let phi = u * std::f32::consts::TAU;
258
259            let sin_phi = phi.sin();
260            let cos_phi = phi.cos();
261
262            let position = Vec3::new(radius * cos_phi, py, radius * sin_phi);
263            let normal = Vec3::new(cos_phi, 0.0, sin_phi).normalize();
264
265            vertices.push(Vertex3D::new(position, normal, (u, v)));
266        }
267    }
268
269    for x in 0..segments {
270        let a = x;
271        let b = a + 1;
272        let c = a + (segments + 1);
273        let d = c + 1;
274
275        indices.extend_from_slice(&[a, c, b]);
276        indices.extend_from_slice(&[b, c, d]);
277    }
278
279    MeshBuffers { vertices, indices }
280}
281
282/// Wraps arbitrary flat vertices into MeshBuffers.
283pub fn generate_custom(vertices_flat: &[f32], indices: &[u32]) -> MeshBuffers {
284    let mut vertices = Vec::new();
285    // Interleaved layout: pos(3), norm(3), uv(2) = 8 floats per vertex
286    let stride = 8;
287    for chunk in vertices_flat.chunks_exact(stride) {
288        vertices.push(Vertex3D::new(
289            Vec3::new(chunk[0], chunk[1], chunk[2]),
290            Vec3::new(chunk[3], chunk[4], chunk[5]),
291            (chunk[6], chunk[7]),
292        ));
293    }
294
295    MeshBuffers {
296        vertices,
297        indices: indices.to_vec(),
298    }
299}
300
301/// Interleaved float stride of the textured custom vertex layout.
302pub const TEXTURED_VERTEX_STRIDE: usize = 8;
303
304/// Builds mesh buffers for a textured custom mesh.
305///
306/// The stride is the same eight floats as [`generate_custom`] but the contract is
307/// explicit: `x, y, z, nx, ny, nz, u, v`. Degenerate indices are dropped so a
308/// malformed tile quad cannot index out of bounds later.
309pub fn generate_custom_textured(vertices_flat: &[f32], indices: &[u32]) -> MeshBuffers {
310    let mut buffers = generate_custom(vertices_flat, indices);
311    let vertex_count = buffers.vertices.len() as u32;
312    if buffers.indices.iter().any(|&i| i >= vertex_count) {
313        buffers.indices.retain(|&i| i < vertex_count);
314    }
315    buffers.indices.truncate(buffers.indices.len() / 3 * 3);
316    buffers
317}