Skip to main content

sim_engine/mesh3d/
attributes.rs

1//! Optional, validated application-owned model-vertex attributes.
2
3use super::{Color, Mesh3dError, TextureCoordinate2d, Vec3};
4
5/// Extensible model-vertex data for [`super::Mesh3d::with_attributes`].
6///
7/// Omitted colors multiply by white. Supplied arrays must match the model
8/// vertex count exactly, including unused vertices; an explicit empty array
9/// is not omission. No normals or simulation quantities are generated here.
10///
11/// ```
12/// use sim_engine::{Color, Mesh3d, Mesh3dAttributes, Vec3};
13/// let attributes = Mesh3dAttributes::new().with_vertex_colors(vec![
14///     Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 1.0, 0.0), Color::rgb(0.0, 0.0, 1.0),
15/// ])?;
16/// let mesh = Mesh3d::with_attributes(
17///     vec![Vec3::ZERO, Vec3::X, Vec3::Y], vec![0, 1, 2], Vec::new(), attributes,
18/// )?;
19/// assert_eq!(mesh.vertex_colors().len(), 3);
20/// # Ok::<(), sim_engine::Mesh3dError>(())
21/// ```
22#[derive(Debug, Default, PartialEq)]
23pub struct Mesh3dAttributes {
24    pub(super) texture_coordinates: Option<Vec<TextureCoordinate2d>>,
25    pub(super) vertex_colors: Option<Vec<Color>>,
26    pub(super) normals: Option<Vec<Vec3>>,
27}
28
29impl Mesh3dAttributes {
30    /// Omits every optional attribute without allocating backing arrays.
31    pub const fn new() -> Self {
32        Self {
33            texture_coordinates: None,
34            vertex_colors: None,
35            normals: None,
36        }
37    }
38
39    /// Supplies normalized model UVs; mesh construction validates the count.
40    pub fn with_texture_coordinates(mut self, coordinates: Vec<TextureCoordinate2d>) -> Self {
41        self.texture_coordinates = Some(coordinates);
42        self
43    }
44
45    /// Supplies normalized, straight-linear RGBA colors without clamping.
46    ///
47    /// Reports the source vertex index of the first non-finite or out-of-range
48    /// channel. Mesh construction separately checks the exact vertex count.
49    /// Opaque surfaces ignore vertex alpha; Mask and Blend use the combined
50    /// alpha. RGBA is interpolated perspectively and multiplies surface/texture tint.
51    /// Mathematical display edges keep their independent wireframe colors.
52    pub fn with_vertex_colors(mut self, colors: Vec<Color>) -> Result<Self, Mesh3dError> {
53        if let Some(vertex_index) = colors.iter().position(|color| !color.is_normalized()) {
54            return Err(Mesh3dError::InvalidVertexColor { vertex_index });
55        }
56        self.vertex_colors = Some(colors);
57        Ok(self)
58    }
59
60    /// Supplies finite nonzero model normals, normalized robustly in place.
61    /// No face normals are inferred. Every value, including unused vertices, is
62    /// validated; mesh construction separately requires an exact vertex count.
63    /// Nonuniform transforms use inverse-transpose direction transport, followed
64    /// by perspective interpolation and fragment normalization, not vertex normalization.
65    pub fn with_normals(mut self, mut normals: Vec<Vec3>) -> Result<Self, Mesh3dError> {
66        for (vertex_index, normal) in normals.iter_mut().enumerate() {
67            *normal = normal
68                .normalized()
69                .map_err(|_| Mesh3dError::InvalidVertexNormal { vertex_index })?;
70        }
71        self.normals = Some(normals);
72        Ok(self)
73    }
74
75    /// Supplied normalized model normals, distinguishing omission from empty.
76    pub fn normals(&self) -> Option<&[Vec3]> {
77        self.normals.as_deref()
78    }
79
80    /// Supplied UVs, distinguishing omission from an explicit empty array.
81    pub fn texture_coordinates(&self) -> Option<&[TextureCoordinate2d]> {
82        self.texture_coordinates.as_deref()
83    }
84
85    /// Supplied straight-linear colors, distinguishing omission from empty.
86    pub fn vertex_colors(&self) -> Option<&[Color]> {
87        self.vertex_colors.as_deref()
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    use crate::{Mesh3d, Vec3};
95
96    #[test]
97    fn normals_validate_exact_count_and_normalize_extreme_directions() {
98        let normal = Vec3::new(f32::MAX, f32::MAX, f32::MAX).unwrap();
99        let attributes = Mesh3dAttributes::new()
100            .with_normals(vec![normal; 3])
101            .unwrap();
102        let normalized = attributes.normals().unwrap()[0];
103        assert!((normalized.x() - 1.0 / 3.0_f32.sqrt()).abs() < 1e-6);
104        let tiny = Vec3::new(f32::from_bits(1), 0.0, 0.0).unwrap();
105        assert_eq!(
106            Mesh3dAttributes::new()
107                .with_normals(vec![tiny])
108                .unwrap()
109                .normals()
110                .unwrap(),
111            &[Vec3::X]
112        );
113        assert_eq!(
114            Mesh3dAttributes::new().with_normals(vec![normal, Vec3::ZERO]),
115            Err(Mesh3dError::InvalidVertexNormal { vertex_index: 1 })
116        );
117        for count in [0, 1, 2, 4] {
118            assert_eq!(
119                Mesh3d::with_attributes(
120                    vec![Vec3::ZERO, Vec3::X, Vec3::Y],
121                    vec![0, 1, 2],
122                    vec![],
123                    Mesh3dAttributes::new()
124                        .with_normals(vec![Vec3::Z; count])
125                        .unwrap()
126                ),
127                Err(Mesh3dError::NormalCountMismatch {
128                    vertex_count: 3,
129                    normal_count: count
130                })
131            );
132        }
133        let mesh = Mesh3d::with_attributes(
134            vec![Vec3::ZERO, Vec3::X, Vec3::Y],
135            vec![0, 1, 2],
136            vec![],
137            attributes,
138        )
139        .unwrap();
140        assert_eq!(mesh.normals().as_ptr(), mesh.clone().normals().as_ptr());
141        let plain = Mesh3d::new(vec![Vec3::ZERO, Vec3::X, Vec3::Y], vec![0, 1, 2]).unwrap();
142        assert_eq!(
143            mesh.recovery_memory_bytes(),
144            plain.recovery_memory_bytes() + 3 * std::mem::size_of::<Vec3>()
145        );
146        assert!(plain.normals().is_empty());
147    }
148
149    #[test]
150    fn vertex_colors_validate_all_channels_and_attribute_indices() {
151        for channel in 0..4 {
152            for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 1.1] {
153                let mut components = [0.5; 4];
154                components[channel] = value;
155                let invalid =
156                    Color::rgba(components[0], components[1], components[2], components[3]);
157                assert_eq!(
158                    Mesh3dAttributes::new().with_vertex_colors(vec![Color::WHITE, invalid]),
159                    Err(Mesh3dError::InvalidVertexColor { vertex_index: 1 })
160                );
161            }
162        }
163        assert!(
164            Mesh3dAttributes::new()
165                .with_vertex_colors(vec![Color::rgba(0.0, f32::from_bits(1), 1.0, 0.0)])
166                .is_ok()
167        );
168    }
169
170    #[test]
171    fn optional_colors_require_exact_count_preserve_alpha_and_share_storage() {
172        let vertices = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z];
173        for count in [0, 1, 3, 5] {
174            let attributes = Mesh3dAttributes::new()
175                .with_vertex_colors(vec![Color::WHITE; count])
176                .unwrap();
177            assert_eq!(
178                Mesh3d::with_attributes(vertices.clone(), vec![0, 1, 2], vec![], attributes),
179                Err(Mesh3dError::VertexColorCountMismatch {
180                    vertex_count: 4,
181                    color_count: count
182                })
183            );
184        }
185        let color = Color::rgba(0.25, 0.5, 1.0, 0.0);
186        let mut colors = Vec::with_capacity(9);
187        colors.resize(4, color);
188        let capacity_bytes = colors.capacity() * std::mem::size_of::<Color>();
189        let colored = Mesh3d::with_attributes(
190            vertices.clone(),
191            vec![0, 1, 2],
192            vec![],
193            Mesh3dAttributes::new().with_vertex_colors(colors).unwrap(),
194        )
195        .unwrap();
196        let plain = Mesh3d::new(vertices, vec![0, 1, 2]).unwrap();
197        assert!(plain.vertex_colors().is_empty());
198        assert_eq!(
199            colored.recovery_memory_bytes(),
200            plain.recovery_memory_bytes() + capacity_bytes
201        );
202        assert_eq!(colored.vertex_colors()[3], color);
203        let alias = colored.clone();
204        assert_eq!(
205            colored.vertex_colors().as_ptr(),
206            alias.vertex_colors().as_ptr()
207        );
208    }
209}