Skip to main content

nsi_intermediate/resolve/
mesh.rs

1//! A `mesh`'s face structure, with `nholes` applied.
2//!
3//! ɴsɪ describes faces in two attributes that only mean something
4//! together. Without `nholes`, `nvertices` is one count per face. With
5//! it, the face count is the number of `nholes` values and each face
6//! takes `nholes + 1` values from `nvertices` -- the outer perimeter
7//! first, then one per hole.
8//!
9//! A backend that reads `nvertices` as one-count-per-face therefore
10//! draws a *different mesh* for any scene with holes, silently: the
11//! counts are all valid, there are simply too many faces and each one
12//! is wrong. This resolves the pair once, here, and refuses a scene
13//! where they disagree instead of guessing.
14
15use super::*;
16
17/// One face: an outer perimeter, and one perimeter per hole.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub struct Face<'a> {
20    /// How many vertices the outer perimeter has.
21    pub outer: usize,
22    /// How many vertices each hole's perimeter has, in order.
23    ///
24    /// Borrowed from the node's `nvertices`: a Moana-scale mesh has
25    /// millions of faces, and a `Vec` each would cost more than the
26    /// attribute it describes.
27    pub holes: &'a [i32],
28}
29
30impl Face<'_> {
31    /// Every vertex this face consumes, holes included.
32    ///
33    /// This is the stride into face-varying data, and into `P.indices`
34    /// where one is given.
35    #[must_use]
36    pub fn vertices(&self) -> usize {
37        self.outer
38            + self
39                .holes
40                .iter()
41                .map(|count| *count as usize)
42                .sum::<usize>()
43    }
44}
45
46/// The faces of a mesh, in order.
47#[derive(Debug, Clone)]
48pub struct Faces<'a> {
49    counts: &'a [i32],
50    holes: Option<&'a [i32]>,
51    face: usize,
52    taken: usize,
53}
54
55impl<'a> Iterator for Faces<'a> {
56    type Item = Face<'a>;
57
58    fn next(&mut self) -> Option<Self::Item> {
59        match self.holes {
60            None => {
61                let outer = *self.counts.get(self.face)?;
62                self.face += 1;
63                Some(Face {
64                    outer: outer as usize,
65                    holes: &[],
66                })
67            }
68            Some(holes) => {
69                let count = *holes.get(self.face)? as usize;
70                let outer = *self.counts.get(self.taken)?;
71                let holes =
72                    &self.counts[self.taken + 1..self.taken + 1 + count];
73                self.face += 1;
74                self.taken += 1 + count;
75                Some(Face {
76                    outer: outer as usize,
77                    holes,
78                })
79            }
80        }
81    }
82}
83
84impl Scene {
85    /// The faces of a `mesh`, with `nholes` resolved.
86    ///
87    /// # Errors
88    ///
89    /// [`ResolveError::MissingFaceCounts`] when the mesh sets no
90    /// `nvertices`, which ɴsɪ requires, and
91    /// [`ResolveError::MalformedFaceCounts`] when `nholes` asks for
92    /// more or fewer `nvertices` values than the mesh carries -- the
93    /// case that otherwise renders as a different mesh with no report.
94    pub fn faces(&self, handle: &str) -> Result<Faces<'_>, ResolveError> {
95        let node = self.node(handle).ok_or_else(|| {
96            ResolveError::MissingFaceCounts {
97                handle: handle.to_string(),
98            }
99        })?;
100        let counts = node
101            .effective(FACE_VERTEX_COUNTS)
102            .and_then(OwnedArgument::as_i32s)
103            .ok_or_else(|| ResolveError::MissingFaceCounts {
104                handle: handle.to_string(),
105            })?;
106        let holes =
107            node.effective(HOLE_COUNTS).and_then(OwnedArgument::as_i32s);
108
109        if let Some(holes) = holes {
110            // Each face takes its outer perimeter plus one value per
111            // hole; the total is what `nvertices` must carry.
112            let expected = holes.len()
113                + holes.iter().map(|count| *count as usize).sum::<usize>();
114            if expected != counts.len() {
115                return Err(ResolveError::MalformedFaceCounts {
116                    handle: handle.to_string(),
117                    expected,
118                    found: counts.len(),
119                });
120            }
121        }
122
123        Ok(Faces {
124            counts,
125            holes,
126            face: 0,
127            taken: 0,
128        })
129    }
130}