Skip to main content

rayengine_core/
mesh.rs

1//! CPU triangle data for procedural geometry, independent of a graphics context.
2
3use glam::{Vec2, Vec3};
4use std::fmt;
5
6/// Largest vertex count accepted by raylib's 16-bit indexed mesh builder.
7pub const MAX_INDEXED_VERTICES: usize = u16::MAX as usize;
8/// Largest vertex count whose position buffer fits raylib's signed byte count.
9pub const MAX_MESH_VERTICES: usize = i32::MAX as usize / size_of::<[f32; 3]>();
10
11/// Owned CPU mesh data. Safe to build on a worker and send to the render thread.
12///
13/// Triangles use counterclockwise winding when viewed from the front. With no
14/// indices, each consecutive three positions form a triangle. Optional vertex
15/// attributes must contain one element per position. Missing UVs use zero;
16/// missing colors use white. Normals are optional and are not generated.
17#[derive(Clone, Debug, Default)]
18pub struct MeshData {
19    /// Local-space vertex positions.
20    pub positions: Vec<Vec3>,
21    /// Optional local-space normals, usually unit vectors.
22    pub normals: Option<Vec<Vec3>>,
23    /// Optional texture coordinates. Values outside 0..1 are allowed.
24    pub texcoords: Option<Vec<Vec2>>,
25    /// Optional RGBA vertex colors, with components in 0..=255.
26    pub colors: Option<Vec<[u8; 4]>>,
27    /// Optional triangle indices, three per triangle.
28    pub indices: Option<Vec<u16>>,
29}
30
31/// Counts returned by successful mesh validation.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct MeshInfo {
34    /// Number of vertices, including unused indexed vertices.
35    pub vertex_count: usize,
36    /// Number of complete triangles.
37    pub triangle_count: usize,
38}
39
40/// Vertex attribute referenced by a validation error.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum MeshAttribute {
43    /// Local positions.
44    Positions,
45    /// Vertex normals.
46    Normals,
47    /// Texture coordinates.
48    Texcoords,
49    /// RGBA colors.
50    Colors,
51}
52
53/// Invalid mesh data, detected before any GPU allocation.
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub enum MeshError {
56    /// Positions or the selected triangle stream are empty.
57    Empty,
58    /// A vertex or index buffer exceeds the backend's supported count.
59    TooLarge,
60    /// The vertex/index stream is not a multiple of three.
61    IncompleteTriangle,
62    /// An optional attribute has a different length from the positions.
63    AttributeLength {
64        /// Attribute with the wrong length.
65        attribute: MeshAttribute,
66        /// Required length.
67        expected: usize,
68        /// Supplied length.
69        actual: usize,
70    },
71    /// A position, normal, or UV contains NaN or infinity.
72    NonFinite {
73        /// Attribute containing the invalid value.
74        attribute: MeshAttribute,
75        /// Vertex offset in that attribute.
76        vertex: usize,
77    },
78    /// A triangle index references a missing vertex.
79    IndexOutOfBounds {
80        /// Offset in the index stream.
81        offset: usize,
82        /// Referenced vertex.
83        index: u16,
84        /// Number of available vertices.
85        vertex_count: usize,
86    },
87}
88
89impl fmt::Display for MeshError {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        match self {
92            Self::Empty => write!(f, "mesh must contain vertices and at least one triangle"),
93            Self::TooLarge => write!(
94                f,
95                "mesh exceeds backend limits; split it into smaller meshes"
96            ),
97            Self::IncompleteTriangle => write!(f, "triangle stream length must be a multiple of 3"),
98            Self::AttributeLength {
99                attribute,
100                expected,
101                actual,
102            } => write!(
103                f,
104                "{attribute:?} has {actual} elements; expected {expected}"
105            ),
106            Self::NonFinite { attribute, vertex } => {
107                write!(f, "{attribute:?} vertex {vertex} contains NaN or infinity")
108            }
109            Self::IndexOutOfBounds {
110                offset,
111                index,
112                vertex_count,
113            } => write!(
114                f,
115                "index {offset} references vertex {index}; only {vertex_count} vertices exist"
116            ),
117        }
118    }
119}
120
121impl std::error::Error for MeshError {}
122
123impl MeshData {
124    /// Creates an unindexed mesh with no optional attributes.
125    pub fn new(positions: Vec<Vec3>) -> Self {
126        Self {
127            positions,
128            ..Self::default()
129        }
130    }
131
132    /// Checks counts, attribute lengths, finite values, and index bounds.
133    ///
134    /// This performs no allocation and needs no display. Degenerate triangles,
135    /// overlapping triangles, and non-unit normals are permitted.
136    pub fn validate(&self) -> Result<MeshInfo, MeshError> {
137        let vertex_count = self.positions.len();
138        let stream_len = self.indices.as_ref().map_or(vertex_count, Vec::len);
139        validate_counts(vertex_count, stream_len, self.indices.is_some())?;
140        for (attribute, actual) in [
141            (MeshAttribute::Normals, self.normals.as_ref().map(Vec::len)),
142            (
143                MeshAttribute::Texcoords,
144                self.texcoords.as_ref().map(Vec::len),
145            ),
146            (MeshAttribute::Colors, self.colors.as_ref().map(Vec::len)),
147        ] {
148            if let Some(actual) = actual.filter(|&len| len != vertex_count) {
149                return Err(MeshError::AttributeLength {
150                    attribute,
151                    expected: vertex_count,
152                    actual,
153                });
154            }
155        }
156        check_finite(
157            MeshAttribute::Positions,
158            self.positions.iter().map(|v| v.is_finite()),
159        )?;
160        if let Some(normals) = &self.normals {
161            check_finite(
162                MeshAttribute::Normals,
163                normals.iter().map(|v| v.is_finite()),
164            )?;
165        }
166        if let Some(texcoords) = &self.texcoords {
167            check_finite(
168                MeshAttribute::Texcoords,
169                texcoords.iter().map(|v| v.is_finite()),
170            )?;
171        }
172        if let Some(indices) = &self.indices
173            && let Some((offset, &index)) = indices
174                .iter()
175                .enumerate()
176                .find(|(_, i)| usize::from(**i) >= vertex_count)
177        {
178            return Err(MeshError::IndexOutOfBounds {
179                offset,
180                index,
181                vertex_count,
182            });
183        }
184        Ok(MeshInfo {
185            vertex_count,
186            triangle_count: stream_len / 3,
187        })
188    }
189}
190
191fn validate_counts(vertices: usize, stream: usize, indexed: bool) -> Result<(), MeshError> {
192    if vertices == 0 || stream == 0 {
193        return Err(MeshError::Empty);
194    }
195    if vertices > MAX_MESH_VERTICES
196        || (indexed
197            && (vertices > MAX_INDEXED_VERTICES || stream > i32::MAX as usize / size_of::<u16>()))
198    {
199        return Err(MeshError::TooLarge);
200    }
201    if !stream.is_multiple_of(3) {
202        return Err(MeshError::IncompleteTriangle);
203    }
204    Ok(())
205}
206
207fn check_finite(
208    attribute: MeshAttribute,
209    mut values: impl Iterator<Item = bool>,
210) -> Result<(), MeshError> {
211    if let Some(vertex) = values.position(|finite| !finite) {
212        Err(MeshError::NonFinite { attribute, vertex })
213    } else {
214        Ok(())
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    fn triangle() -> MeshData {
223        MeshData::new(vec![Vec3::ZERO, Vec3::X, Vec3::Y])
224    }
225
226    #[test]
227    fn indexed_quad_and_unindexed_triangle() {
228        assert_eq!(
229            triangle().validate().unwrap(),
230            MeshInfo {
231                vertex_count: 3,
232                triangle_count: 1
233            }
234        );
235        let mesh = MeshData {
236            positions: vec![Vec3::ZERO, Vec3::X, Vec3::ONE, Vec3::Y],
237            indices: Some(vec![0, 1, 2, 0, 2, 3]),
238            normals: Some(vec![Vec3::Z; 4]),
239            texcoords: Some(vec![Vec2::splat(2.0); 4]),
240            colors: Some(vec![[255; 4]; 4]),
241        };
242        assert_eq!(
243            mesh.validate().unwrap(),
244            MeshInfo {
245                vertex_count: 4,
246                triangle_count: 2
247            }
248        );
249    }
250
251    #[test]
252    fn rejects_empty_and_incomplete_streams() {
253        assert_eq!(MeshData::default().validate(), Err(MeshError::Empty));
254        let mut mesh = triangle();
255        mesh.positions.pop();
256        assert_eq!(mesh.validate(), Err(MeshError::IncompleteTriangle));
257        mesh.indices = Some(vec![]);
258        assert_eq!(mesh.validate(), Err(MeshError::Empty));
259        mesh.indices = Some(vec![0, 1]);
260        assert_eq!(mesh.validate(), Err(MeshError::IncompleteTriangle));
261    }
262
263    #[test]
264    fn checks_optional_lengths_and_all_float_channels() {
265        for attribute in [
266            MeshAttribute::Normals,
267            MeshAttribute::Texcoords,
268            MeshAttribute::Colors,
269        ] {
270            let mut mesh = triangle();
271            match attribute {
272                MeshAttribute::Normals => mesh.normals = Some(vec![]),
273                MeshAttribute::Texcoords => mesh.texcoords = Some(vec![Vec2::ZERO]),
274                MeshAttribute::Colors => mesh.colors = Some(vec![[0; 4]; 4]),
275                MeshAttribute::Positions => unreachable!(),
276            }
277            assert!(
278                matches!(mesh.validate(), Err(MeshError::AttributeLength { attribute: a, expected: 3, .. }) if a == attribute)
279            );
280        }
281        for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
282            for attribute in [
283                MeshAttribute::Positions,
284                MeshAttribute::Normals,
285                MeshAttribute::Texcoords,
286            ] {
287                let mut mesh = triangle();
288                match attribute {
289                    MeshAttribute::Positions => mesh.positions[1].x = invalid,
290                    MeshAttribute::Normals => {
291                        mesh.normals = Some(vec![Vec3::ZERO, Vec3::splat(invalid), Vec3::ZERO])
292                    }
293                    MeshAttribute::Texcoords => {
294                        mesh.texcoords = Some(vec![Vec2::ZERO, Vec2::splat(invalid), Vec2::ZERO])
295                    }
296                    MeshAttribute::Colors => unreachable!(),
297                }
298                assert_eq!(
299                    mesh.validate(),
300                    Err(MeshError::NonFinite {
301                        attribute,
302                        vertex: 1
303                    })
304                );
305            }
306        }
307    }
308
309    #[test]
310    fn validates_index_bounds_and_backend_count_limits() {
311        let mut mesh = triangle();
312        mesh.indices = Some(vec![0, 1, 3]);
313        assert_eq!(
314            mesh.validate(),
315            Err(MeshError::IndexOutOfBounds {
316                offset: 2,
317                index: 3,
318                vertex_count: 3
319            })
320        );
321        mesh.positions = vec![Vec3::ZERO; MAX_INDEXED_VERTICES];
322        mesh.indices = Some(vec![0, 1, u16::MAX - 1]);
323        assert!(mesh.validate().is_ok());
324        mesh.positions.push(Vec3::ZERO);
325        assert_eq!(mesh.validate(), Err(MeshError::TooLarge));
326        assert_eq!(
327            validate_counts(MAX_MESH_VERTICES + 1, 3, false),
328            Err(MeshError::TooLarge)
329        );
330        assert_eq!(
331            validate_counts(3, i32::MAX as usize / 2 + 1, true),
332            Err(MeshError::TooLarge)
333        );
334        assert!(validate_counts(MAX_MESH_VERTICES, 3, false).is_ok());
335    }
336
337    #[test]
338    fn mesh_data_can_cross_threads() {
339        let info = std::thread::spawn(|| triangle().validate())
340            .join()
341            .unwrap()
342            .unwrap();
343        assert_eq!(info.triangle_count, 1);
344    }
345}