Struct truck_polymesh::Faces

source ·
pub struct Faces<V = StandardVertex> { /* private fields */ }
Expand description

Faces of polygon mesh

To optimize for the case where the polygon mesh consists only triangles and quadrangle, there are vectors which consist by each triangles and quadrilaterals, internally.

Implementations§

Extends faces by an iterator.

Examples found in repository?
src/faces.rs (line 96)
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Faces {
        let mut faces = Faces::default();
        faces.extend(iter);
        faces
    }
}

impl<S: AsRef<[usize]>> FromIterator<S> for Faces<usize> {
    #[inline(always)]
    fn from_iter<I: IntoIterator<Item = S>>(iter: I) -> Faces<usize> {
        let mut faces = Faces::default();
        faces.extend(iter);
        faces
    }

Creates faces of a polygon mesh by the vectors of triangle and quadrangle.

Examples
// Creates faces consisis only triangles.
use truck_polymesh::*;
let tri_faces: Vec<[StandardVertex; 3]> = vec![
    [[0, 0, 0].into(), [1, 1, 1].into(), [2, 2, 2].into()],
    [[0, 0, 0].into(), [2, 2, 2].into(), [3, 3, 3].into()],
];
let faces = Faces::from_tri_and_quad_faces(tri_faces, Vec::new());
Examples found in repository?
src/stl.rs (line 317)
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
    fn from_iter<I: IntoIterator<Item = STLFace>>(iter: I) -> PolygonMesh {
        let mut positions = HashMap::<[i64; 3], usize>::default();
        let mut normals = HashMap::<[i64; 3], usize>::default();
        let faces: Vec<[Vertex; 3]> = iter
            .into_iter()
            .map(|face| {
                let n = signup_vector(face.normal, &mut normals);
                let p = [
                    signup_vector(face.vertices[0], &mut positions),
                    signup_vector(face.vertices[1], &mut positions),
                    signup_vector(face.vertices[2], &mut positions),
                ];
                [
                    (p[0], None, Some(n)).into(),
                    (p[1], None, Some(n)).into(),
                    (p[2], None, Some(n)).into(),
                ]
            })
            .collect();
        let faces = Faces::from_tri_and_quad_faces(faces, Vec::new());
        let mut positions: Vec<([i64; 3], usize)> = positions.into_iter().collect();
        positions.sort_by(|a, b| a.1.cmp(&b.1));
        let positions: Vec<Point3> = positions
            .into_iter()
            .map(|(p, _)| {
                Point3::new(
                    p[0] as f64 * TOLERANCE * 0.5,
                    p[1] as f64 * TOLERANCE * 0.5,
                    p[2] as f64 * TOLERANCE * 0.5,
                )
            })
            .collect();
        let mut normals: Vec<([i64; 3], usize)> = normals.into_iter().collect();
        normals.sort_by(|a, b| a.1.cmp(&b.1));
        let normals: Vec<Vector3> = normals
            .into_iter()
            .map(|(p, _)| {
                Vector3::new(
                    p[0] as f64 * TOLERANCE * 0.5,
                    p[1] as f64 * TOLERANCE * 0.5,
                    p[2] as f64 * TOLERANCE * 0.5,
                )
            })
            .collect();
        PolygonMesh::debug_new(
            StandardAttributes {
                positions,
                uv_coords: Vec::new(),
                normals,
            },
            faces,
        )
    }

Push a face to the faces.

If face.len() < 3, the face is ignored with warning.

Examples
use truck_polymesh::*;
let mut faces = Faces::<StandardVertex>::default(); // empty faces
faces.push(&[[0, 0, 0], [1, 1, 1], [2, 2, 2]]);
faces.push(&[[3, 3, 3], [0, 0, 0], [2, 2, 2]]);
faces.push(&[[0, 0, 0], [4, 4, 4], [5, 5, 5], [1, 1, 1]]);
faces.push(&[[100, 1000, 10]]); // Wargning: ignored one vertex "face"
Examples found in repository?
src/faces.rs (line 124)
123
124
125
    pub fn extend<U: Copy + Into<V>, T: AsRef<[U]>, I: IntoIterator<Item = T>>(&mut self, iter: I) {
        iter.into_iter().for_each(|face| self.push(face))
    }
More examples
Hide additional examples
src/obj.rs (line 174)
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
pub fn read<R: Read>(reader: R) -> Result<PolygonMesh> {
    let mut positions = Vec::new();
    let mut uv_coords = Vec::new();
    let mut normals = Vec::new();
    let mut faces = Faces::default();
    let reader = BufReader::new(reader);
    for line in reader.lines().map(|s| s.unwrap()) {
        let mut args = line.split_whitespace();
        if let Some(first_str) = args.next() {
            if first_str == "v" {
                let x = args.next().unwrap().parse::<f64>()?;
                let y = args.next().unwrap().parse::<f64>()?;
                let z = args.next().unwrap().parse::<f64>()?;
                positions.push(Point3::new(x, y, z));
            } else if first_str == "vt" {
                let u = args.next().unwrap().parse::<f64>()?;
                let v = args.next().unwrap().parse::<f64>()?;
                uv_coords.push(Vector2::new(u, v));
            } else if first_str == "vn" {
                let x = args.next().unwrap().parse::<f64>()?;
                let y = args.next().unwrap().parse::<f64>()?;
                let z = args.next().unwrap().parse::<f64>()?;
                normals.push(Vector3::new(x, y, z));
            } else if first_str == "f" {
                let mut face = Vec::new();
                for vert_str in args {
                    if &vert_str[0..1] == "#" {
                        break;
                    }
                    let mut iter = vert_str.split('/');
                    let pos = iter
                        .next()
                        .map(|val| val.parse::<usize>().map(|i| i - 1).ok())
                        .unwrap_or(None);
                    let uv = iter
                        .next()
                        .map(|val| val.parse::<usize>().map(|i| i - 1).ok())
                        .unwrap_or(None);
                    let nor = iter
                        .next()
                        .map(|val| val.parse::<usize>().map(|i| i - 1).ok())
                        .unwrap_or(None);
                    let vert = match (pos, uv, nor) {
                        (None, _, _) => continue,
                        (Some(pos), uv, nor) => Vertex { pos, uv, nor },
                    };
                    face.push(vert);
                }
                faces.push(face);
            }
        }
    }
    PolygonMesh::try_new(
        StandardAttributes {
            positions,
            uv_coords,
            normals,
        },
        faces,
    )
}

Returns the vector of triangles.

Returns the mutable slice of triangles.

Returns the vector of quadrangles.

Returns the mutable slice of quadrangles.

Returns the vector of n-gons (n > 4).

Returns the mutable iterator of n-gons (n > 4).

Returns the iterator of the slice.

By the internal optimization, this iterator does not runs in the simple order in which they are registered, but runs order: triangle, square, and the others.

Examples
use truck_polymesh::*;
let slice: &[&[usize]] = &[
    &[0, 1, 2],
    &[0, 4, 5, 1],
    &[1, 2, 6, 7, 8, 9],
    &[0, 2, 3],
];
let faces = Faces::<usize>::from_iter(slice);
let mut iter = faces.face_iter();
assert_eq!(iter.next(), Some([0, 1, 2].as_ref()));
assert_eq!(iter.next(), Some([0, 2, 3].as_ref()));
assert_eq!(iter.next(), Some([0, 4, 5, 1].as_ref()));
assert_eq!(iter.next(), Some([1, 2, 6, 7, 8, 9].as_ref()));
assert_eq!(iter.next(), None);
Examples found in repository?
src/polygon_mesh.rs (line 70)
70
    pub fn face_iter(&self) -> impl Iterator<Item = &[V]> { self.faces.face_iter() }
More examples
Hide additional examples
src/obj.rs (line 106)
105
106
107
108
109
110
111
112
113
114
115
    fn write<W: Write>(&self, writer: &mut W) -> Result<()> {
        for face in self.face_iter() {
            writer.write_all(b"f")?;
            for v in face {
                writer.write_all(b" ")?;
                v.write(writer)?;
            }
            writer.write_all(b"\n")?;
        }
        Ok(())
    }
src/faces.rs (line 272)
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
    pub(super) fn is_compatible(&self, attrs: &impl Attributes<V>) -> Result<(), Error<V>>
    where V: std::fmt::Debug {
        self.face_iter()
            .flatten()
            .try_for_each(|v| match attrs.get(*v) {
                Some(_) => Ok(()),
                None => Err(Error::OutOfRange(*v)),
            })
    }

    /// Returns iterator with triangulation faces
    ///
    /// # Examples
    /// ```
    /// use truck_polymesh::*;
    /// let slice: &[&[usize]] = &[
    ///     &[0, 1, 2],
    ///     &[0, 4, 5, 1],
    ///     &[1, 2, 6, 7, 8, 9],
    ///     &[1, 2, 4, 3],
    ///     &[0, 2, 3],
    /// ];
    /// let faces = Faces::<usize>::from_iter(slice);
    /// let mut iter = faces.triangle_iter();
    /// assert_eq!(iter.len(), 10);
    /// assert_eq!(iter.next(), Some([0, 1, 2]));
    /// assert_eq!(iter.next(), Some([0, 2, 3]));
    /// assert_eq!(iter.next(), Some([0, 4, 5]));
    /// assert_eq!(iter.next(), Some([0, 5, 1]));
    /// assert_eq!(iter.next(), Some([1, 2, 4]));
    /// assert_eq!(iter.next(), Some([1, 4, 3]));
    /// assert_eq!(iter.next(), Some([1, 2, 6]));
    /// assert_eq!(iter.next(), Some([1, 6, 7]));
    /// assert_eq!(iter.next(), Some([1, 7, 8]));
    /// assert_eq!(iter.next(), Some([1, 8, 9]));
    /// assert_eq!(iter.len(), 0);
    /// assert_eq!(iter.next(), None);
    /// ```
    #[inline(always)]
    pub fn triangle_iter(&self) -> TriangleIterator<'_, V> {
        let len = self.face_iter().fold(0, |sum, face| sum + face.len() - 2);
        TriangleIterator {
            tri_faces: self.tri_faces.iter(),
            quad_faces: self.quad_faces.iter(),
            other_faces: self.other_faces.iter(),
            current_face: None,
            current_vertex: 0,
            len,
        }
    }

Returns the iterator of the slice.

By the internal optimization, this iterator does not runs in the simple order in which they are registered, but runs order: triangle, square, and the others. cf: Faces:face_iter

Examples found in repository?
src/faces.rs (line 347)
347
    fn invert(&mut self) { self.face_iter_mut().for_each(|f| f.reverse()); }
More examples
Hide additional examples
src/polygon_mesh.rs (line 78)
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    pub fn face_iter_mut(&mut self) -> impl Iterator<Item = &mut [V]> { self.faces.face_iter_mut() }
    /// Creates an editor that performs boundary checking on dropped.
    #[inline(always)]
    pub fn editor(&mut self) -> PolygonMeshEditor<'_, V, A> {
        PolygonMeshEditor {
            attributes: &mut self.attributes,
            faces: &mut self.faces,
            bound_check: true,
        }
    }
    /// Creates an editor that does NOT perform boundary checking on dropped.
    #[inline(always)]
    pub fn uncheck_editor(&mut self) -> PolygonMeshEditor<'_, V, A> {
        PolygonMeshEditor {
            attributes: &mut self.attributes,
            faces: &mut self.faces,
            bound_check: false,
        }
    }
    /// Creates an editor that performs boundary checking on dropped ONLY in debug build.
    #[inline(always)]
    pub fn debug_editor(&mut self) -> PolygonMeshEditor<'_, V, A> {
        PolygonMeshEditor {
            attributes: &mut self.attributes,
            faces: &mut self.faces,
            bound_check: cfg!(debug_assertions),
        }
    }
}

impl PolygonMesh {
    /// Returns polygonmesh merged `self` and `mesh`.
    pub fn merge(&mut self, mut mesh: PolygonMesh) {
        let n_pos = self.positions().len();
        let n_uv = self.uv_coords().len();
        let n_nor = self.normals().len();
        mesh.faces.face_iter_mut().for_each(move |face| {
            face.iter_mut().for_each(|v| {
                v.pos += n_pos;
                v.uv = v.uv.map(|uv| uv + n_uv);
                v.nor = v.nor.map(|nor| nor + n_nor);
            })
        });
        self.attributes.positions.extend(mesh.attributes.positions);
        self.attributes.uv_coords.extend(mesh.attributes.uv_coords);
        self.attributes.normals.extend(mesh.attributes.normals);
        self.faces.naive_concat(mesh.faces);
    }

Returns true if the faces is empty.

Returns the number of faces.

Examples found in repository?
src/faces.rs (line 253)
253
    pub fn is_empty(&self) -> bool { self.len() == 0 }

Merges other into self.

Examples found in repository?
src/polygon_mesh.rs (line 124)
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    pub fn merge(&mut self, mut mesh: PolygonMesh) {
        let n_pos = self.positions().len();
        let n_uv = self.uv_coords().len();
        let n_nor = self.normals().len();
        mesh.faces.face_iter_mut().for_each(move |face| {
            face.iter_mut().for_each(|v| {
                v.pos += n_pos;
                v.uv = v.uv.map(|uv| uv + n_uv);
                v.nor = v.nor.map(|nor| nor + n_nor);
            })
        });
        self.attributes.positions.extend(mesh.attributes.positions);
        self.attributes.uv_coords.extend(mesh.attributes.uv_coords);
        self.attributes.normals.extend(mesh.attributes.normals);
        self.faces.naive_concat(mesh.faces);
    }

Returns iterator with triangulation faces

Examples
use truck_polymesh::*;
let slice: &[&[usize]] = &[
    &[0, 1, 2],
    &[0, 4, 5, 1],
    &[1, 2, 6, 7, 8, 9],
    &[1, 2, 4, 3],
    &[0, 2, 3],
];
let faces = Faces::<usize>::from_iter(slice);
let mut iter = faces.triangle_iter();
assert_eq!(iter.len(), 10);
assert_eq!(iter.next(), Some([0, 1, 2]));
assert_eq!(iter.next(), Some([0, 2, 3]));
assert_eq!(iter.next(), Some([0, 4, 5]));
assert_eq!(iter.next(), Some([0, 5, 1]));
assert_eq!(iter.next(), Some([1, 2, 4]));
assert_eq!(iter.next(), Some([1, 4, 3]));
assert_eq!(iter.next(), Some([1, 2, 6]));
assert_eq!(iter.next(), Some([1, 6, 7]));
assert_eq!(iter.next(), Some([1, 7, 8]));
assert_eq!(iter.next(), Some([1, 8, 9]));
assert_eq!(iter.len(), 0);
assert_eq!(iter.next(), None);
Examples found in repository?
src/stl.rs (line 269)
268
269
270
271
272
273
274
275
    fn into_iter(self) -> Self::IntoIter {
        let iter = self.faces().triangle_iter();
        Self::IntoIter {
            positions: self.positions(),
            len: iter.len(),
            faces: iter,
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Deserialize this value from the given Serde deserializer. Read more
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more
The returned type after indexing.
Performs the indexing (container[index]) operation. Read more
Performs the mutable indexing (container[index]) operation. Read more
Inverts self
Returns the inverse.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.