Skip to main content

ifc_geometry/solid/tessellated/
polygonal.rs

1//! `IfcPolygonalFaceSet` and the indexed faces it is built from.
2//!
3//! Polygonal face sets carry n-gons rather than triangles, and their faces are
4//! separate entities so that a face with holes can add an attribute. Read the
5//! parent module's docs on 1-based indexing before using this.
6
7use super::{face_set_slot, int_grid, int_list, to_zero_based, TessellatedFaceSet};
8use crate::error::GeometryResult;
9use crate::slots::Slots;
10use ifc_model::{Entity, EntityId};
11
12/// `IfcPolygonalFaceSet` attribute slots.
13///
14/// EXPRESS (IFC4 ADD2 TC1): `Coordinates` is inherited at slot 0, then
15/// `Closed`, `Faces`, `PnIndex`. Note the order differs from
16/// `IfcTriangulatedFaceSet`, which has `Normals` at slot 1 -- so `Closed` is
17/// slot 1 here and slot 2 there. Copying one layout onto the other is a
18/// straightforward way to read a boolean as a list.
19pub(crate) mod set_slot {
20    /// `Closed : OPTIONAL IfcBoolean`, absolute slot 1.
21    pub const CLOSED: usize = 1;
22    /// `Faces : LIST [1:?] OF IfcIndexedPolygonalFace`, absolute slot 2.
23    pub const FACES: usize = 2;
24    /// `PnIndex : OPTIONAL LIST [1:?] OF IfcPositiveInteger`, slot 3.
25    pub const PN_INDEX: usize = 3;
26}
27
28/// `IfcIndexedPolygonalFace` slots.
29///
30/// EXPRESS: subtypes `IfcTessellatedItem`, which declares no explicit
31/// attributes, so `CoordIndex` is absolute slot 0 and the `WithVoids` subtype's
32/// `InnerCoordIndices` is slot 1.
33pub(crate) mod face_slot {
34    /// `CoordIndex : LIST [3:?] OF IfcPositiveInteger`, the outer loop.
35    pub const COORD_INDEX: usize = 0;
36    /// `InnerCoordIndices` on `IfcIndexedPolygonalFaceWithVoids`, slot 1.
37    pub const INNER_COORD_INDICES: usize = 1;
38}
39
40/// `IfcPolygonalFaceSet`: n-gon faces indexed into a shared point list.
41///
42/// # Winding
43///
44/// When `Closed` is TRUE the schema requires outer loops to wind
45/// counter-clockwise seen from outside the shell, and inner loops (holes) to
46/// wind clockwise. A consumer computing face normals from winding must respect
47/// that, or every hole's normal points into the material.
48#[derive(Debug, Clone, Copy)]
49pub struct PolygonalFaceSet<'m> {
50    slots: Slots<'m>,
51}
52
53impl<'m> PolygonalFaceSet<'m> {
54    /// Wrap an entity assumed to be an `IfcPolygonalFaceSet`.
55    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
56        Self {
57            slots: Slots::new(id, entity),
58        }
59    }
60
61    /// The entity id.
62    pub fn id(&self) -> EntityId {
63        self.slots.id()
64    }
65
66    /// The inherited `IfcTessellatedFaceSet` attributes.
67    pub fn base(&self) -> TessellatedFaceSet<'m> {
68        TessellatedFaceSet::from_slots(self.slots)
69    }
70
71    /// The `IfcCartesianPointList3D` reference holding the vertices.
72    pub fn coordinates(&self) -> GeometryResult<EntityId> {
73        self.slots
74            .req_ref(face_set_slot::COORDINATES, "Coordinates")
75    }
76
77    /// Whether the face set bounds a solid. `None` means the file did not say.
78    ///
79    /// Note this is slot 1 here but slot 2 on `IfcTriangulatedFaceSet`.
80    pub fn closed(&self) -> Option<bool> {
81        self.slots.opt_bool(set_slot::CLOSED)
82    }
83
84    /// The `IfcIndexedPolygonalFace` references making up the set.
85    pub fn faces(&self) -> GeometryResult<Vec<EntityId>> {
86        self.slots.req_ref_list(set_slot::FACES, "Faces")
87    }
88
89    /// `PnIndex` exactly as written: **1-based** positions in `Coordinates`.
90    pub fn pn_index_1based(&self) -> Option<Vec<i64>> {
91        int_list(self.slots.opt(set_slot::PN_INDEX)?)
92    }
93
94    /// `PnIndex` converted to 0-based, or `None` when absent.
95    ///
96    /// The same indirection as on `IfcTriangulatedFaceSet`: with `PnIndex`
97    /// present, a face's `CoordIndex` addresses `PnIndex`, not `Coordinates`.
98    pub fn pn_index_0based(&self) -> GeometryResult<Option<Vec<usize>>> {
99        let Some(raw) = self.pn_index_1based() else {
100            return Ok(None);
101        };
102        raw.into_iter()
103            .map(|i| to_zero_based(&self.slots, "PnIndex", i))
104            .collect::<GeometryResult<Vec<_>>>()
105            .map(Some)
106    }
107}
108
109/// `IfcIndexedPolygonalFace`: one planar n-gon, as indices.
110///
111/// A face is a separate entity rather than an inline list precisely so that
112/// [`IndexedPolygonalFaceWithVoids`] can extend it with holes.
113#[derive(Debug, Clone, Copy)]
114pub struct IndexedPolygonalFace<'m> {
115    slots: Slots<'m>,
116}
117
118impl<'m> IndexedPolygonalFace<'m> {
119    /// Wrap an entity assumed to be an `IfcIndexedPolygonalFace` or subtype.
120    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
121        Self {
122            slots: Slots::new(id, entity),
123        }
124    }
125
126    /// The entity id.
127    pub fn id(&self) -> EntityId {
128        self.slots.id()
129    }
130
131    /// The IFC type name, naming the concrete subtype.
132    pub fn type_name(&self) -> &'m str {
133        self.slots.type_name()
134    }
135
136    /// Does this face carry inner loops?
137    pub fn has_voids(&self) -> bool {
138        self.type_name()
139            .eq_ignore_ascii_case("IFCINDEXEDPOLYGONALFACEWITHVOIDS")
140    }
141
142    /// The outer loop, as the file wrote it: **1-based** indices.
143    pub fn outer_loop_1based(&self) -> GeometryResult<Vec<i64>> {
144        let value = self.slots.req(face_slot::COORD_INDEX, "CoordIndex")?;
145        int_list(value).ok_or_else(|| {
146            self.slots
147                .degenerate("CoordIndex is not a list of integers")
148        })
149    }
150
151    /// The outer loop as 0-based indices, ready to index a vertex `Vec`.
152    ///
153    /// Does **not** apply `PnIndex`: that lives on the containing
154    /// `IfcPolygonalFaceSet` and a face has no way to reach it. A caller
155    /// holding both must apply the mapping itself.
156    pub fn outer_loop_0based(&self) -> GeometryResult<Vec<usize>> {
157        self.outer_loop_1based()?
158            .into_iter()
159            .map(|i| to_zero_based(&self.slots, "CoordIndex", i))
160            .collect()
161    }
162}
163
164/// `IfcIndexedPolygonalFaceWithVoids`: an n-gon with holes.
165///
166/// # The loops must not be merged
167///
168/// `InnerCoordIndices` are **holes**. Concatenating them onto the outer loop
169/// produces a self-intersecting polygon that most triangulators will happily
170/// accept and fill in, so the hole disappears and the face is silently solid.
171/// Every accessor here keeps the outer loop and the inner loops separate, and
172/// there is deliberately no method that returns them as one list.
173#[derive(Debug, Clone, Copy)]
174pub struct IndexedPolygonalFaceWithVoids<'m> {
175    slots: Slots<'m>,
176}
177
178impl<'m> IndexedPolygonalFaceWithVoids<'m> {
179    /// Wrap an entity assumed to be an `IfcIndexedPolygonalFaceWithVoids`.
180    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
181        Self {
182            slots: Slots::new(id, entity),
183        }
184    }
185
186    /// The entity id.
187    pub fn id(&self) -> EntityId {
188        self.slots.id()
189    }
190
191    /// The inherited `IfcIndexedPolygonalFace` attributes, giving the outer
192    /// loop.
193    pub fn base(&self) -> IndexedPolygonalFace<'m> {
194        IndexedPolygonalFace { slots: self.slots }
195    }
196
197    /// The inner loops, as the file wrote them: **1-based** indices.
198    ///
199    /// Each entry is one hole. They are never to be appended to the outer loop.
200    pub fn inner_loops_1based(&self) -> GeometryResult<Vec<Vec<i64>>> {
201        let value = self
202            .slots
203            .req(face_slot::INNER_COORD_INDICES, "InnerCoordIndices")?;
204        int_grid(value).ok_or_else(|| {
205            self.slots
206                .degenerate("InnerCoordIndices is not a list of integer lists")
207        })
208    }
209
210    /// The inner loops as 0-based indices, one `Vec` per hole.
211    pub fn inner_loops_0based(&self) -> GeometryResult<Vec<Vec<usize>>> {
212        self.inner_loops_1based()?
213            .into_iter()
214            .map(|loop_| {
215                loop_
216                    .into_iter()
217                    .map(|i| to_zero_based(&self.slots, "InnerCoordIndices", i))
218                    .collect()
219            })
220            .collect()
221    }
222
223    /// How many holes the face has.
224    pub fn void_count(&self) -> GeometryResult<usize> {
225        Ok(self.inner_loops_1based()?.len())
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::solid::testkit::{entity, int_grid as grid, ints, r, refs};
233    use ifc_model::Value;
234
235    /// Closed is slot 1 here but slot 2 on IfcTriangulatedFaceSet; copying the
236    /// other layout reads Faces as the boolean.
237    #[test]
238    fn closed_precedes_faces_unlike_the_triangulated_layout() {
239        let e = entity(
240            "IFCPOLYGONALFACESET",
241            vec![r(50), Value::Bool(true), refs(&[10, 11]), Value::Null],
242        );
243        let view = PolygonalFaceSet::new(EntityId(1), &e);
244        assert_eq!(view.coordinates().unwrap(), EntityId(50));
245        assert_eq!(view.closed(), Some(true));
246        assert_eq!(view.faces().unwrap(), vec![EntityId(10), EntityId(11)]);
247    }
248
249    #[test]
250    fn face_set_pn_index_applies_the_same_one_based_rule() {
251        let e = entity(
252            "IFCPOLYGONALFACESET",
253            vec![r(50), Value::Bool(true), refs(&[10]), ints(&[3, 1, 2])],
254        );
255        let view = PolygonalFaceSet::new(EntityId(1), &e);
256        assert_eq!(view.pn_index_1based().unwrap(), vec![3, 1, 2]);
257        assert_eq!(view.pn_index_0based().unwrap().unwrap(), vec![2, 0, 1]);
258    }
259
260    #[test]
261    fn a_face_set_without_pn_index_reports_none() {
262        let e = entity(
263            "IFCPOLYGONALFACESET",
264            vec![r(50), Value::Bool(true), refs(&[10])],
265        );
266        let view = PolygonalFaceSet::new(EntityId(1), &e);
267        assert_eq!(view.pn_index_0based().unwrap(), None);
268    }
269
270    #[test]
271    fn a_face_outer_loop_converts_from_one_based_to_zero_based() {
272        let e = entity("IFCINDEXEDPOLYGONALFACE", vec![ints(&[1, 2, 3, 4])]);
273        let view = IndexedPolygonalFace::new(EntityId(1), &e);
274        assert_eq!(view.outer_loop_1based().unwrap(), vec![1, 2, 3, 4]);
275        assert_eq!(view.outer_loop_0based().unwrap(), vec![0, 1, 2, 3]);
276        assert!(!view.has_voids());
277    }
278
279    #[test]
280    fn a_zero_index_in_a_face_loop_is_rejected() {
281        let e = entity("IFCINDEXEDPOLYGONALFACE", vec![ints(&[0, 1, 2])]);
282        let err = IndexedPolygonalFace::new(EntityId(8), &e)
283            .outer_loop_0based()
284            .unwrap_err();
285        assert_eq!(err.entity(), Some(EntityId(8)));
286    }
287
288    /// THE property: holes stay separate from the outer loop. Merging them
289    /// yields a self-intersecting polygon that triangulates into a solid face.
290    #[test]
291    fn inner_loops_are_never_merged_into_the_outer_loop() {
292        let e = entity(
293            "IFCINDEXEDPOLYGONALFACEWITHVOIDS",
294            vec![
295                ints(&[1, 2, 3, 4]),
296                grid(&[&[5, 6, 7, 8], &[9, 10, 11, 12]]),
297            ],
298        );
299        let view = IndexedPolygonalFaceWithVoids::new(EntityId(1), &e);
300
301        let outer = view.base().outer_loop_0based().unwrap();
302        let inners = view.inner_loops_0based().unwrap();
303
304        assert_eq!(outer, vec![0, 1, 2, 3]);
305        assert_eq!(inners, vec![vec![4, 5, 6, 7], vec![8, 9, 10, 11]]);
306        assert_eq!(view.void_count().unwrap(), 2);
307
308        // No index of a hole may appear in the outer boundary.
309        for inner in &inners {
310            for i in inner {
311                assert!(
312                    !outer.contains(i),
313                    "hole index {i} leaked into the outer loop"
314                );
315            }
316        }
317    }
318
319    #[test]
320    fn a_face_with_voids_is_distinguishable_from_a_plain_face() {
321        let plain = entity("IFCINDEXEDPOLYGONALFACE", vec![ints(&[1, 2, 3])]);
322        let voided = entity(
323            "IFCINDEXEDPOLYGONALFACEWITHVOIDS",
324            vec![ints(&[1, 2, 3, 4]), grid(&[&[5, 6, 7]])],
325        );
326        assert!(!IndexedPolygonalFace::new(EntityId(1), &plain).has_voids());
327        assert!(IndexedPolygonalFace::new(EntityId(1), &voided).has_voids());
328    }
329
330    /// A plain face read through the WithVoids view has nothing at slot 1;
331    /// that must be an error rather than an empty hole list, since silently
332    /// dropping holes is exactly the failure this module guards against.
333    #[test]
334    fn missing_inner_coord_indices_is_an_error_not_an_empty_hole_list() {
335        let e = entity("IFCINDEXEDPOLYGONALFACEWITHVOIDS", vec![ints(&[1, 2, 3])]);
336        let view = IndexedPolygonalFaceWithVoids::new(EntityId(2), &e);
337        assert!(view.inner_loops_1based().is_err());
338        assert!(view.base().outer_loop_1based().is_ok());
339    }
340}