1use std::{error::Error, fmt, sync::Arc};
4
5use crate::{Color, Vec3};
6
7mod attributes;
8mod environment;
9mod material;
10mod style;
11#[cfg(test)]
12mod tests;
13mod uv;
14
15pub use attributes::Mesh3dAttributes;
16pub use environment::{
17 AmbientLight3d, DirectionalLight3d, Fog3d, Fog3dError, Lighting3d, Lighting3dError,
18 SurfaceLighting3d,
19};
20pub use material::{SurfaceAlphaMode3d, SurfaceSidedness3d, SurfaceStyle3d};
21pub use style::{Mesh3dStyleError, MeshStyle3d, WireframeStyle3d};
22pub use uv::{TextureAddressMode3d, TextureUvTransform3d, TextureUvTransformError};
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
29pub struct MeshEdge3d {
30 start: u32,
31 end: u32,
32}
33
34impl MeshEdge3d {
35 pub fn new(start: u32, end: u32) -> Result<Self, Mesh3dError> {
37 if start == end {
38 return Err(Mesh3dError::DegenerateDisplayEdge { start, end });
39 }
40 Ok(Self { start, end })
41 }
42
43 pub const fn start(self) -> u32 {
45 self.start
46 }
47
48 pub const fn end(self) -> u32 {
50 self.end
51 }
52
53 fn canonical(self) -> (u32, u32) {
54 if self.start < self.end {
55 (self.start, self.end)
56 } else {
57 (self.end, self.start)
58 }
59 }
60}
61
62#[derive(Debug, PartialEq)]
63struct Mesh3dStorage {
64 vertices: Vec<Vec3>,
65 triangle_indices: Vec<u32>,
66 display_edges: Vec<MeshEdge3d>,
67 texture_coordinates: Vec<TextureCoordinate2d>,
68 vertex_colors: Vec<Color>,
69 normals: Vec<Vec3>,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq)]
81pub struct TextureCoordinate2d {
82 u: f32,
83 v: f32,
84}
85
86impl TextureCoordinate2d {
87 pub fn new(u: f32, v: f32) -> Result<Self, Mesh3dError> {
89 if !u.is_finite()
90 || !v.is_finite()
91 || !(0.0..=1.0).contains(&u)
92 || !(0.0..=1.0).contains(&v)
93 {
94 return Err(Mesh3dError::InvalidTextureCoordinate);
95 }
96 Ok(Self { u, v })
97 }
98 pub const fn u(self) -> f32 {
100 self.u
101 }
102 pub const fn v(self) -> f32 {
104 self.v
105 }
106}
107
108#[derive(Debug, Clone, PartialEq)]
119pub struct Mesh3d {
120 storage: Arc<Mesh3dStorage>,
121 bounds_min: Vec3,
122 bounds_max: Vec3,
123 minimum_nonzero_components: [f32; 3],
124}
125
126impl Mesh3d {
127 pub fn new(vertices: Vec<Vec3>, triangle_indices: Vec<u32>) -> Result<Self, Mesh3dError> {
129 Self::with_display_edges(vertices, triangle_indices, Vec::new())
130 }
131
132 pub fn with_display_edges(
140 vertices: Vec<Vec3>,
141 triangle_indices: Vec<u32>,
142 display_edges: Vec<MeshEdge3d>,
143 ) -> Result<Self, Mesh3dError> {
144 Self::with_attributes(
145 vertices,
146 triangle_indices,
147 display_edges,
148 Mesh3dAttributes::new(),
149 )
150 }
151
152 pub fn textured(
159 vertices: Vec<Vec3>,
160 texture_coordinates: Vec<TextureCoordinate2d>,
161 triangle_indices: Vec<u32>,
162 display_edges: Vec<MeshEdge3d>,
163 ) -> Result<Self, Mesh3dError> {
164 if texture_coordinates.len() != vertices.len() {
165 return Err(Mesh3dError::TextureCoordinateCountMismatch {
166 vertex_count: vertices.len(),
167 coordinate_count: texture_coordinates.len(),
168 });
169 }
170 Self::with_attributes(
171 vertices,
172 triangle_indices,
173 display_edges,
174 Mesh3dAttributes::new().with_texture_coordinates(texture_coordinates),
175 )
176 }
177
178 pub fn with_attributes(
183 vertices: Vec<Vec3>,
184 triangle_indices: Vec<u32>,
185 display_edges: Vec<MeshEdge3d>,
186 attributes: Mesh3dAttributes,
187 ) -> Result<Self, Mesh3dError> {
188 if let Some(coordinates) = &attributes.texture_coordinates
189 && coordinates.len() != vertices.len()
190 {
191 return Err(Mesh3dError::TextureCoordinateCountMismatch {
192 vertex_count: vertices.len(),
193 coordinate_count: coordinates.len(),
194 });
195 }
196 if let Some(colors) = &attributes.vertex_colors
197 && colors.len() != vertices.len()
198 {
199 return Err(Mesh3dError::VertexColorCountMismatch {
200 vertex_count: vertices.len(),
201 color_count: colors.len(),
202 });
203 }
204 if let Some(normals) = &attributes.normals
205 && normals.len() != vertices.len()
206 {
207 return Err(Mesh3dError::NormalCountMismatch {
208 vertex_count: vertices.len(),
209 normal_count: normals.len(),
210 });
211 }
212 if vertices.is_empty() {
213 return Err(Mesh3dError::EmptyVertices);
214 }
215 if triangle_indices.is_empty() && display_edges.is_empty() {
216 return Err(Mesh3dError::EmptyGeometry);
217 }
218 if !triangle_indices.len().is_multiple_of(3) {
219 return Err(Mesh3dError::InvalidTriangleIndexCount {
220 index_count: triangle_indices.len(),
221 });
222 }
223
224 for (triangle, indices) in triangle_indices.chunks_exact(3).enumerate() {
225 let [first, second, third] = [indices[0], indices[1], indices[2]];
226 validate_index(first, vertices.len())?;
227 validate_index(second, vertices.len())?;
228 validate_index(third, vertices.len())?;
229 if first == second
230 || second == third
231 || first == third
232 || triangle_is_degenerate(
233 vertices[first as usize],
234 vertices[second as usize],
235 vertices[third as usize],
236 )
237 {
238 return Err(Mesh3dError::DegenerateTriangle { triangle });
239 }
240 }
241
242 for edge in &display_edges {
243 validate_index(edge.start, vertices.len())?;
244 validate_index(edge.end, vertices.len())?;
245 if vertices[edge.start as usize] == vertices[edge.end as usize] {
246 return Err(Mesh3dError::DegenerateDisplayEdge {
247 start: edge.start,
248 end: edge.end,
249 });
250 }
251 }
252
253 let canonical_bytes = display_edges
254 .len()
255 .checked_mul(std::mem::size_of::<((u32, u32), usize)>())
256 .ok_or(Mesh3dError::AllocationFailed {
257 requested_bytes: usize::MAX,
258 })?;
259 let mut canonical_edges = Vec::new();
260 canonical_edges
261 .try_reserve_exact(display_edges.len())
262 .map_err(|_| Mesh3dError::AllocationFailed {
263 requested_bytes: canonical_bytes,
264 })?;
265 for (index, edge) in display_edges.iter().enumerate() {
266 canonical_edges.push((edge.canonical(), index));
267 }
268 canonical_edges.sort_unstable_by_key(|entry| entry.0);
269 if let Some(pair) = canonical_edges
270 .windows(2)
271 .find(|pair| pair[0].0 == pair[1].0)
272 {
273 let duplicate = display_edges[pair[0].1.max(pair[1].1)];
274 return Err(Mesh3dError::DuplicateDisplayEdge {
275 start: duplicate.start,
276 end: duplicate.end,
277 });
278 }
279
280 let (bounds_min, bounds_max, minimum_nonzero_components) = mesh_bounds(&vertices);
281 Ok(Self {
282 storage: Arc::new(Mesh3dStorage {
285 vertices,
286 triangle_indices,
287 display_edges,
288 texture_coordinates: attributes.texture_coordinates.unwrap_or_default(),
289 vertex_colors: attributes.vertex_colors.unwrap_or_default(),
290 normals: attributes.normals.unwrap_or_default(),
291 }),
292 bounds_min,
293 bounds_max,
294 minimum_nonzero_components,
295 })
296 }
297
298 pub fn vertices(&self) -> &[Vec3] {
300 &self.storage.vertices
301 }
302
303 pub fn triangle_indices(&self) -> &[u32] {
305 &self.storage.triangle_indices
306 }
307
308 pub fn display_edges(&self) -> &[MeshEdge3d] {
310 &self.storage.display_edges
311 }
312
313 pub fn texture_coordinates(&self) -> &[TextureCoordinate2d] {
315 &self.storage.texture_coordinates
316 }
317
318 pub fn vertex_colors(&self) -> &[Color] {
321 &self.storage.vertex_colors
322 }
323
324 pub fn normals(&self) -> &[Vec3] {
327 &self.storage.normals
328 }
329
330 pub fn triangle_count(&self) -> usize {
332 self.storage.triangle_indices.len() / 3
333 }
334
335 pub const fn bounds_min(&self) -> Vec3 {
337 self.bounds_min
338 }
339
340 pub const fn bounds_max(&self) -> Vec3 {
342 self.bounds_max
343 }
344
345 #[cfg(feature = "wgpu")]
348 pub(crate) const fn minimum_nonzero_components(&self) -> [f32; 3] {
349 self.minimum_nonzero_components
350 }
351
352 pub fn recovery_memory_bytes(&self) -> usize {
354 self.storage
355 .vertices
356 .capacity()
357 .saturating_mul(std::mem::size_of::<Vec3>())
358 .saturating_add(
359 self.storage
360 .triangle_indices
361 .capacity()
362 .saturating_mul(std::mem::size_of::<u32>()),
363 )
364 .saturating_add(
365 self.storage
366 .display_edges
367 .capacity()
368 .saturating_mul(std::mem::size_of::<MeshEdge3d>()),
369 )
370 .saturating_add(
371 self.storage
372 .texture_coordinates
373 .capacity()
374 .saturating_mul(std::mem::size_of::<TextureCoordinate2d>()),
375 )
376 .saturating_add(
377 self.storage
378 .vertex_colors
379 .capacity()
380 .saturating_mul(std::mem::size_of::<Color>()),
381 )
382 .saturating_add(
383 self.storage
384 .normals
385 .capacity()
386 .saturating_mul(std::mem::size_of::<Vec3>()),
387 )
388 }
389}
390
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
393pub enum Mesh3dError {
394 InvalidVertexNormal {
396 vertex_index: usize,
398 },
399 NormalCountMismatch {
401 vertex_count: usize,
403 normal_count: usize,
405 },
406 InvalidVertexColor {
408 vertex_index: usize,
410 },
411 VertexColorCountMismatch {
413 vertex_count: usize,
415 color_count: usize,
417 },
418 InvalidTextureCoordinate,
420 TextureCoordinateCountMismatch {
422 vertex_count: usize,
424 coordinate_count: usize,
426 },
427 EmptyVertices,
429 EmptyGeometry,
431 InvalidTriangleIndexCount {
433 index_count: usize,
435 },
436 IndexOutOfBounds {
438 index: u32,
440 vertex_count: usize,
442 },
443 DegenerateTriangle {
445 triangle: usize,
447 },
448 DegenerateDisplayEdge {
450 start: u32,
452 end: u32,
454 },
455 DuplicateDisplayEdge {
457 start: u32,
459 end: u32,
461 },
462 AllocationFailed {
464 requested_bytes: usize,
466 },
467}
468
469impl fmt::Display for Mesh3dError {
470 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
471 match self {
472 Self::InvalidVertexNormal { vertex_index } => write!(
473 formatter,
474 "3D vertex {vertex_index} normal must be a nonzero finite direction"
475 ),
476 Self::NormalCountMismatch {
477 vertex_count,
478 normal_count,
479 } => write!(
480 formatter,
481 "{vertex_count} mesh vertices require matching normals, got {normal_count}"
482 ),
483 Self::InvalidVertexColor { vertex_index } => write!(
484 formatter,
485 "3D vertex {vertex_index} color must be finite straight-linear RGBA in 0..=1"
486 ),
487 Self::VertexColorCountMismatch {
488 vertex_count,
489 color_count,
490 } => write!(
491 formatter,
492 "{vertex_count} mesh vertices require matching colors, got {color_count}"
493 ),
494 Self::InvalidTextureCoordinate => {
495 write!(formatter, "texture coordinates must be finite in 0..=1")
496 }
497 Self::TextureCoordinateCountMismatch {
498 vertex_count,
499 coordinate_count,
500 } => write!(
501 formatter,
502 "{vertex_count} mesh vertices require matching UVs, got {coordinate_count}"
503 ),
504 Self::EmptyVertices => write!(formatter, "3D mesh requires at least one vertex"),
505 Self::EmptyGeometry => {
506 write!(formatter, "3D mesh requires triangles or display edges")
507 }
508 Self::InvalidTriangleIndexCount { index_count } => write!(
509 formatter,
510 "3D mesh triangle index count, when present, must be divisible by three, got {index_count}"
511 ),
512 Self::IndexOutOfBounds {
513 index,
514 vertex_count,
515 } => write!(
516 formatter,
517 "3D mesh index {index} is outside {vertex_count} vertices"
518 ),
519 Self::DegenerateTriangle { triangle } => {
520 write!(formatter, "3D mesh triangle {triangle} has zero area")
521 }
522 Self::DegenerateDisplayEdge { start, end } => {
523 write!(formatter, "3D display edge {start}-{end} has zero length")
524 }
525 Self::DuplicateDisplayEdge { start, end } => {
526 write!(formatter, "3D display edge {start}-{end} is duplicated")
527 }
528 Self::AllocationFailed { requested_bytes } => write!(
529 formatter,
530 "could not reserve {requested_bytes} bytes for 3D mesh validation"
531 ),
532 }
533 }
534}
535
536impl Error for Mesh3dError {}
537
538fn validate_index(index: u32, vertex_count: usize) -> Result<(), Mesh3dError> {
539 ((index as u64) < vertex_count as u64)
540 .then_some(())
541 .ok_or(Mesh3dError::IndexOutOfBounds {
542 index,
543 vertex_count,
544 })
545}
546
547fn triangle_is_degenerate(first: Vec3, second: Vec3, third: Vec3) -> bool {
548 let ab = (
549 second.x() as f64 - first.x() as f64,
550 second.y() as f64 - first.y() as f64,
551 second.z() as f64 - first.z() as f64,
552 );
553 let ac = (
554 third.x() as f64 - first.x() as f64,
555 third.y() as f64 - first.y() as f64,
556 third.z() as f64 - first.z() as f64,
557 );
558 let cross = (
559 ab.1 * ac.2 - ab.2 * ac.1,
560 ab.2 * ac.0 - ab.0 * ac.2,
561 ab.0 * ac.1 - ab.1 * ac.0,
562 );
563 cross.0 == 0.0 && cross.1 == 0.0 && cross.2 == 0.0
564}
565
566fn mesh_bounds(vertices: &[Vec3]) -> (Vec3, Vec3, [f32; 3]) {
567 let first = vertices[0];
568 let mut minimum = [first.x(), first.y(), first.z()];
569 let mut maximum = minimum;
570 let mut minimum_nonzero = [f32::INFINITY; 3];
571 for vertex in vertices {
572 let components = [vertex.x(), vertex.y(), vertex.z()];
573 for axis in 0..3 {
574 minimum[axis] = minimum[axis].min(components[axis]);
575 maximum[axis] = maximum[axis].max(components[axis]);
576 if components[axis] != 0.0 {
577 minimum_nonzero[axis] = minimum_nonzero[axis].min(components[axis].abs());
578 }
579 }
580 }
581 (
582 Vec3::new_unchecked(minimum[0], minimum[1], minimum[2]),
583 Vec3::new_unchecked(maximum[0], maximum[1], maximum[2]),
584 minimum_nonzero,
585 )
586}