Skip to main content

ifc_geometry/solid/tessellated/
triangulated.rs

1//! `IfcTriangulatedFaceSet`: an indexed triangle mesh.
2//!
3//! The commonest mesh form in IFC4 and the one most exchange pipelines emit.
4//! Read the parent module's docs on 1-based indexing before using this.
5
6use super::{face_set_slot, int_grid, int_list, to_zero_based, TessellatedFaceSet};
7use crate::error::GeometryResult;
8use crate::slots::Slots;
9use ifc_model::{Entity, EntityId};
10
11/// `IfcTriangulatedFaceSet` attribute slots.
12///
13/// EXPRESS (IFC4 ADD2 TC1): `Coordinates` is inherited from
14/// `IfcTessellatedFaceSet` at slot 0, then `Normals`, `Closed`, `CoordIndex`,
15/// `PnIndex`. Note `Normals` sits **before** `Closed` and `CoordIndex`, so
16/// `CoordIndex` is slot 3 and not slot 1 as its prominence suggests.
17pub(crate) mod slot {
18    /// `Normals : OPTIONAL LIST OF LIST [3:3] OF IfcParameterValue`, slot 1.
19    pub const NORMALS: usize = 1;
20    /// `Closed : OPTIONAL IfcBoolean`, absolute slot 2.
21    pub const CLOSED: usize = 2;
22    /// `CoordIndex : LIST OF LIST [3:3] OF IfcPositiveInteger`, slot 3.
23    pub const COORD_INDEX: usize = 3;
24    /// `PnIndex : OPTIONAL LIST OF IfcPositiveInteger`, absolute slot 4.
25    pub const PN_INDEX: usize = 4;
26}
27
28/// `IfcTriangulatedFaceSet`: triangles indexed into a shared point list.
29///
30/// # `Closed` decides what this even is
31///
32/// `Closed = TRUE` means the set is a boundary representation, a solid.
33/// `Closed = FALSE` or absent means it is a surface model with no interior.
34/// Only a closed set is a legal boolean operand, and only a closed set has a
35/// volume; treating an open one as a solid produces nonsense quantities.
36///
37/// # Normals
38///
39/// `Normals` is optional and, when present, is indexed **per face** or **per
40/// vertex** depending on `Closed` -- the schema ties the two. Rather than guess,
41/// this view exposes the raw triples and leaves the choice to a consumer that
42/// has read the rule for its case.
43#[derive(Debug, Clone, Copy)]
44pub struct TriangulatedFaceSet<'m> {
45    slots: Slots<'m>,
46}
47
48impl<'m> TriangulatedFaceSet<'m> {
49    /// Wrap an entity assumed to be an `IfcTriangulatedFaceSet`.
50    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
51        Self {
52            slots: Slots::new(id, entity),
53        }
54    }
55
56    /// The entity id.
57    pub fn id(&self) -> EntityId {
58        self.slots.id()
59    }
60
61    /// The inherited `IfcTessellatedFaceSet` attributes.
62    pub fn base(&self) -> TessellatedFaceSet<'m> {
63        TessellatedFaceSet::from_slots(self.slots)
64    }
65
66    /// The `IfcCartesianPointList3D` reference holding the vertices.
67    pub fn coordinates(&self) -> GeometryResult<EntityId> {
68        self.slots
69            .req_ref(face_set_slot::COORDINATES, "Coordinates")
70    }
71
72    /// Whether the mesh bounds a solid.
73    ///
74    /// `None` means the file did not say. That is **not** the same as `false`
75    /// for a consumer deciding whether the set may be a boolean operand: an
76    /// unstated flag is a file defect worth reporting, not a licence to assume.
77    pub fn closed(&self) -> Option<bool> {
78        self.slots.opt_bool(slot::CLOSED)
79    }
80
81    /// Optional normal triples, exactly as written.
82    pub fn normals(&self) -> Option<Vec<[f64; 3]>> {
83        let value = self.slots.opt(slot::NORMALS)?;
84        let rows = value.as_list()?;
85        rows.iter()
86            .map(|row| {
87                let v = row.unwrap_typed().as_list()?;
88                if v.len() != 3 {
89                    return None;
90                }
91                Some([
92                    v[0].unwrap_typed().as_f64()?,
93                    v[1].unwrap_typed().as_f64()?,
94                    v[2].unwrap_typed().as_f64()?,
95                ])
96            })
97            .collect()
98    }
99
100    /// Triangles as the file wrote them: **1-based** vertex indices.
101    ///
102    /// Use this to round-trip or to diff against a file. To index a Rust slice,
103    /// use [`Self::triangles_0based`] instead.
104    pub fn triangles_1based(&self) -> GeometryResult<Vec<[i64; 3]>> {
105        let value = self.slots.req(slot::COORD_INDEX, "CoordIndex")?;
106        let rows = int_grid(value).ok_or_else(|| {
107            self.slots
108                .degenerate("CoordIndex is not a list of integer lists")
109        })?;
110        rows.into_iter()
111            .map(|row| {
112                <[i64; 3]>::try_from(row.as_slice()).map_err(|_| {
113                    self.slots.degenerate(format!(
114                        "CoordIndex entry has {} indices, but a triangle needs exactly 3",
115                        row.len()
116                    ))
117                })
118            })
119            .collect()
120    }
121
122    /// Triangles as 0-based indices, ready to index a vertex `Vec`.
123    ///
124    /// Applies `PnIndex` when it is present, so the result always addresses
125    /// `Coordinates` directly. Rejects a 0 or negative index rather than
126    /// wrapping it.
127    pub fn triangles_0based(&self) -> GeometryResult<Vec<[usize; 3]>> {
128        let pn = self.pn_index_0based()?;
129        self.triangles_1based()?
130            .into_iter()
131            .map(|tri| {
132                let mut out = [0usize; 3];
133                for (slot_i, raw) in tri.iter().enumerate() {
134                    let direct = to_zero_based(&self.slots, "CoordIndex", *raw)?;
135                    out[slot_i] = match &pn {
136                        Some(map) => *map.get(direct).ok_or_else(|| {
137                            self.slots.degenerate(format!(
138                                "CoordIndex {raw} is past the end of PnIndex ({} entries)",
139                                map.len()
140                            ))
141                        })?,
142                        None => direct,
143                    };
144                }
145                Ok(out)
146            })
147            .collect()
148    }
149
150    /// `PnIndex` exactly as written: **1-based** positions in `Coordinates`.
151    pub fn pn_index_1based(&self) -> Option<Vec<i64>> {
152        int_list(self.slots.opt(slot::PN_INDEX)?)
153    }
154
155    /// `PnIndex` converted to 0-based, or `None` when absent.
156    ///
157    /// When present, a `CoordIndex` value `i` selects `PnIndex[i - 1]`, and
158    /// *that* is the position in `Coordinates`. Skipping the hop silently
159    /// permutes the mesh's vertices.
160    pub fn pn_index_0based(&self) -> GeometryResult<Option<Vec<usize>>> {
161        let Some(raw) = self.pn_index_1based() else {
162            return Ok(None);
163        };
164        raw.into_iter()
165            .map(|i| to_zero_based(&self.slots, "PnIndex", i))
166            .collect::<GeometryResult<Vec<_>>>()
167            .map(Some)
168    }
169
170    /// How many triangles the set declares.
171    pub fn triangle_count(&self) -> GeometryResult<usize> {
172        Ok(self.triangles_1based()?.len())
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use crate::solid::testkit::{entity, int_grid as grid, ints, list, n, r};
180    use ifc_model::Value;
181
182    fn face_set(coord_index: Value, pn: Value) -> Entity {
183        entity(
184            "IFCTRIANGULATEDFACESET",
185            vec![r(50), Value::Null, Value::Bool(true), coord_index, pn],
186        )
187    }
188
189    /// CoordIndex sits at slot 3, after the optional Normals and Closed.
190    #[test]
191    fn coord_index_follows_normals_and_closed_in_the_slot_order() {
192        let e = face_set(grid(&[&[1, 2, 3]]), Value::Null);
193        let view = TriangulatedFaceSet::new(EntityId(1), &e);
194        assert_eq!(view.coordinates().unwrap(), EntityId(50));
195        assert_eq!(view.closed(), Some(true));
196        assert_eq!(view.triangles_1based().unwrap(), vec![[1, 2, 3]]);
197    }
198
199    /// THE critical property: file indices are 1-based, slice indices are
200    /// 0-based, and the first vertex of the file is element 0 of the slice.
201    #[test]
202    fn coord_index_is_one_based_and_converts_to_zero_based_slice_indices() {
203        let e = face_set(grid(&[&[1, 2, 3], &[1, 3, 4]]), Value::Null);
204        let view = TriangulatedFaceSet::new(EntityId(1), &e);
205
206        assert_eq!(
207            view.triangles_1based().unwrap(),
208            vec![[1, 2, 3], [1, 3, 4]],
209            "the raw form must preserve the file's own numbers"
210        );
211        assert_eq!(
212            view.triangles_0based().unwrap(),
213            vec![[0, 1, 2], [0, 2, 3]],
214            "index 1 in the file is element 0 of a Rust slice"
215        );
216    }
217
218    /// A mesh whose highest index equals the vertex count is exactly in range
219    /// once converted; off by one here reads past the end.
220    #[test]
221    fn the_highest_one_based_index_maps_to_the_last_slice_element() {
222        let vertex_count = 4usize;
223        let e = face_set(grid(&[&[2, 3, 4]]), Value::Null);
224        let view = TriangulatedFaceSet::new(EntityId(1), &e);
225        let tri = view.triangles_0based().unwrap()[0];
226        assert_eq!(tri, [1, 2, 3]);
227        assert!(
228            tri.iter().all(|i| *i < vertex_count),
229            "a valid file's converted indices must all be in range"
230        );
231    }
232
233    /// A 0 index is impossible in valid IFC and must not wrap to usize::MAX.
234    #[test]
235    fn a_zero_coord_index_is_rejected_rather_than_wrapping() {
236        let e = face_set(grid(&[&[0, 1, 2]]), Value::Null);
237        let view = TriangulatedFaceSet::new(EntityId(9), &e);
238        assert!(view.triangles_1based().is_ok(), "raw form stays readable");
239        let err = view.triangles_0based().unwrap_err();
240        assert_eq!(err.entity(), Some(EntityId(9)));
241    }
242
243    /// With PnIndex present, CoordIndex points into PnIndex, not straight into
244    /// Coordinates; skipping the hop permutes the mesh.
245    #[test]
246    fn pn_index_indirection_is_applied_not_skipped() {
247        // PnIndex reverses a 4-point list: file index 1 selects point 4.
248        let e = face_set(grid(&[&[1, 2, 3]]), ints(&[4, 3, 2, 1]));
249        let view = TriangulatedFaceSet::new(EntityId(1), &e);
250
251        assert_eq!(view.pn_index_1based().unwrap(), vec![4, 3, 2, 1]);
252        assert_eq!(view.pn_index_0based().unwrap().unwrap(), vec![3, 2, 1, 0]);
253        assert_eq!(
254            view.triangles_0based().unwrap(),
255            vec![[3, 2, 1]],
256            "CoordIndex 1,2,3 selects PnIndex entries 4,3,2 -> slice 3,2,1"
257        );
258    }
259
260    #[test]
261    fn without_pn_index_the_coord_index_addresses_coordinates_directly() {
262        let e = face_set(grid(&[&[1, 2, 3]]), Value::Null);
263        let view = TriangulatedFaceSet::new(EntityId(1), &e);
264        assert_eq!(view.pn_index_1based(), None);
265        assert_eq!(view.pn_index_0based().unwrap(), None);
266        assert_eq!(view.triangles_0based().unwrap(), vec![[0, 1, 2]]);
267    }
268
269    /// Closed decides whether this is a solid at all, so an unstated flag must
270    /// stay distinguishable from an explicit false.
271    #[test]
272    fn an_absent_closed_flag_is_distinguishable_from_an_explicit_false() {
273        let stated = entity(
274            "IFCTRIANGULATEDFACESET",
275            vec![r(50), Value::Null, Value::Bool(false), grid(&[&[1, 2, 3]])],
276        );
277        assert_eq!(
278            TriangulatedFaceSet::new(EntityId(1), &stated).closed(),
279            Some(false)
280        );
281
282        let unstated = entity(
283            "IFCTRIANGULATEDFACESET",
284            vec![r(50), Value::Null, Value::Null, grid(&[&[1, 2, 3]])],
285        );
286        assert_eq!(
287            TriangulatedFaceSet::new(EntityId(1), &unstated).closed(),
288            None
289        );
290    }
291
292    /// A triangle with the wrong arity is a corrupt file, not a polygon.
293    #[test]
294    fn a_face_without_exactly_three_indices_is_degenerate() {
295        let e = face_set(grid(&[&[1, 2, 3, 4]]), Value::Null);
296        let err = TriangulatedFaceSet::new(EntityId(4), &e)
297            .triangles_1based()
298            .unwrap_err();
299        assert!(err.to_string().contains("exactly 3"));
300    }
301
302    #[test]
303    fn normals_are_returned_as_written_without_reinterpretation() {
304        let e = entity(
305            "IFCTRIANGULATEDFACESET",
306            vec![
307                r(50),
308                list(vec![list(vec![n(0.0), n(0.0), n(1.0)])]),
309                Value::Bool(true),
310                grid(&[&[1, 2, 3]]),
311            ],
312        );
313        let view = TriangulatedFaceSet::new(EntityId(1), &e);
314        assert_eq!(view.normals().unwrap(), vec![[0.0, 0.0, 1.0]]);
315        assert_eq!(view.triangle_count().unwrap(), 1);
316    }
317}