Skip to main content

ifc_geometry/lower/
tessellated.rs

1//! Tessellated face-set lowering into indexed meshes.
2//!
3//! # Why a mesh and not topology
4//!
5//! A tessellated face set is *already* a discretisation. Unlike an
6//! `IfcFacetedBrep`, which is an exact solid whose planar faces happen to be
7//! polygons, a face set carries no adjacency, no bound nesting, and no claim
8//! to exactness. Recovering topology from it means inferring shared edges by
9//! comparing float positions, which invents information the file never had.
10//! So these lower to `axiolid-mesh` types and stay meshes.
11//!
12//! # Authored n-gons survive
13//!
14//! `IfcPolygonalFaceSet` faces are n-gons with optional holes. Triangulating
15//! them here would be a lossy decision taken at read time, in the wrong crate:
16//! a hole-aware tessellator needs a fill rule and a tolerance, both of which
17//! belong to the kernel. `PolygonMesh` stores the authored loops verbatim, so
18//! the choice stays with whoever consumes the graph.
19//!
20//! # Coordinates are shared, indices are not
21//!
22//! Both families index one `IfcCartesianPointList3D`. The point list is read
23//! once and scaled once; faces only carry indices into it. Emitting one vertex
24//! per face corner would multiply a wall's vertex count by roughly six and
25//! break every consumer that relies on shared positions.
26
27use axiolid_core::{Point3, Vec3};
28use axiolid_mesh::{NormalAttribute, PolygonFace, PolygonMesh, TriMesh};
29use axiolid_model::{GeometryNode, NodeId};
30use ifc_model::EntityId;
31
32use crate::error::GeometryResult;
33use crate::lower::session::LoweringSession;
34use crate::resource::point::CartesianPointList3D;
35use crate::solid::tessellated::{
36    irregular_network, IndexedPolygonalFace, IndexedPolygonalFaceWithVoids, PolygonalFaceSet,
37    TriangulatedFaceSet, TriangulatedIrregularNetwork,
38};
39use crate::transform::Transform;
40
41/// Chain kind reported when a face set nests too deeply or cycles.
42const KIND: &str = "tessellated face set";
43
44/// Read `Coordinates`, convert to metres, and place by `frame`.
45///
46/// One pass over the shared point list. The scale is applied before the frame
47/// because the frame is already expressed in metres.
48fn positions(
49    session: &mut LoweringSession<'_>,
50    owner: EntityId,
51    coordinates: EntityId,
52    frame: Transform,
53) -> GeometryResult<Vec<Point3>> {
54    let entity = session.entity(owner, coordinates)?;
55    let raw = CartesianPointList3D::new(coordinates, entity).coordinates()?;
56    Ok(raw
57        .into_iter()
58        .map(|point| {
59            let scaled = point.map(|value| session.units().length(value));
60            Point3::from_array(frame.apply(scaled))
61        })
62        .collect())
63}
64
65/// Reject an index that addresses past the end of the coordinate list.
66///
67/// A face set whose indices dangle is not recoverable: the vertex it names
68/// does not exist, and substituting the origin would render a spike to
69/// (0,0,0) that looks like geometry. Fail with the entity named instead.
70fn checked_index(
71    session: &LoweringSession<'_>,
72    owner: EntityId,
73    index: usize,
74    vertex_count: usize,
75    field: &str,
76) -> GeometryResult<u32> {
77    if index >= vertex_count {
78        return Err(session.degenerate(
79            owner,
80            KIND,
81            format!(
82                "{field} addresses vertex {} but Coordinates has {vertex_count}",
83                index + 1
84            ),
85        ));
86    }
87    Ok(index as u32)
88}
89
90/// Lower an `IfcTriangulatedFaceSet` into [`GeometryNode::TriMesh`].
91///
92/// Also lowers the IFC4X3 subtype `IfcTriangulatedIrregularNetwork` when
93/// [`TriangulatedIrregularNetwork::admit`] accepts its flags.
94pub fn lower_triangulated_face_set_node(
95    session: &mut LoweringSession<'_>,
96    id: EntityId,
97    frame: Transform,
98) -> GeometryResult<NodeId> {
99    if let Some(node) = session.memoized(id, KIND, frame) {
100        return Ok(node);
101    }
102    session.enter(id, KIND)?;
103    let result = build_triangulated(session, id, frame);
104    session.exit(id);
105    let node = result?;
106    session.memoize(id, KIND, frame, node);
107    Ok(node)
108}
109
110fn build_triangulated(
111    session: &mut LoweringSession<'_>,
112    id: EntityId,
113    frame: Transform,
114) -> GeometryResult<NodeId> {
115    let entity = session.entity(id, id)?;
116    let view = TriangulatedFaceSet::new(id, entity);
117    let coordinates = view.coordinates()?;
118    let triangles = view.triangles_0based()?;
119    // The IFC4X3 subtype adds per-triangle `Flags`; the dispatcher routes it
120    // here only because the triangle surface is the same when every flag is a
121    // breakline code. A void or hole changes it, so admission is checked
122    // before any node exists.
123    if entity.is_type(irregular_network::TYPE) {
124        TriangulatedIrregularNetwork::new(id, entity).admit(triangles.len())?;
125    }
126    let normals = view.normals();
127    let positions = positions(session, id, coordinates, frame)?;
128
129    // `triangles.len() * 3` is the index count. Compute it in u128 so a huge
130    // face set cannot wrap to a small usize that passes the budget check.
131    let index_count = session.check_aggregate(
132        id,
133        "IFCTRIANGULATEDFACESET",
134        "triangle indices",
135        triangles.len() as u128 * 3,
136    )?;
137    let mut indices = Vec::with_capacity(index_count);
138    for triangle in &triangles {
139        for corner in triangle {
140            indices.push(checked_index(
141                session,
142                id,
143                *corner,
144                positions.len(),
145                "CoordIndex",
146            )?);
147        }
148    }
149
150    let mut mesh = TriMesh::new(positions, indices);
151    // Normals are directions: the linear part applies, the translation does
152    // not. Sending them through `apply` would drag every normal to the frame's
153    // origin and invert lighting on any placed product.
154    if let Some(values) = normals {
155        mesh.normals = Some(NormalAttribute {
156            values: values
157                .into_iter()
158                .map(|normal| Vec3::from_array(frame.apply_direction(normal)))
159                .collect(),
160            indices: None,
161        });
162    }
163    // Texture coordinates ride along as corner-indexed channels (#30); see
164    // `texture` for why they cannot be per-vertex.
165    mesh.attributes = texture::channels(session, id, triangles.len())?;
166    session.node_for(id, GeometryNode::TriMesh(mesh))
167}
168
169/// Lower an `IfcPolygonalFaceSet` into [`GeometryNode::PolygonMesh`].
170pub fn lower_polygonal_face_set_node(
171    session: &mut LoweringSession<'_>,
172    id: EntityId,
173    frame: Transform,
174) -> GeometryResult<NodeId> {
175    if let Some(node) = session.memoized(id, KIND, frame) {
176        return Ok(node);
177    }
178    session.enter(id, KIND)?;
179    let result = build_polygonal(session, id, frame);
180    session.exit(id);
181    let node = result?;
182    session.memoize(id, KIND, frame, node);
183    Ok(node)
184}
185
186fn build_polygonal(
187    session: &mut LoweringSession<'_>,
188    id: EntityId,
189    frame: Transform,
190) -> GeometryResult<NodeId> {
191    let entity = session.entity(id, id)?;
192    let view = PolygonalFaceSet::new(id, entity);
193    let coordinates = view.coordinates()?;
194    let face_refs = view.faces()?;
195    let pn = view.pn_index_0based()?;
196    let positions = positions(session, id, coordinates, frame)?;
197
198    let mut faces = Vec::with_capacity(face_refs.len());
199    for face_ref in &face_refs {
200        let face_entity = session.entity(id, *face_ref)?;
201        let face = IndexedPolygonalFace::new(*face_ref, face_entity);
202        let outer = resolve_loop(session, id, &face.outer_loop_0based()?, &pn, &positions)?;
203
204        // `IfcIndexedPolygonalFaceWithVoids` is a subtype, so the outer loop
205        // reads identically; only the inner loops are extra.
206        let holes = if face.has_voids() {
207            IndexedPolygonalFaceWithVoids::new(*face_ref, face_entity)
208                .inner_loops_0based()?
209                .iter()
210                .map(|inner| resolve_loop(session, id, inner, &pn, &positions))
211                .collect::<GeometryResult<Vec<_>>>()?
212        } else {
213            Vec::new()
214        };
215
216        faces.push(PolygonFace { outer, holes });
217    }
218
219    session.node_for(
220        id,
221        GeometryNode::PolygonMesh(PolygonMesh { positions, faces }),
222    )
223}
224
225/// Map one authored loop through `PnIndex` and bounds-check every entry.
226///
227/// The face readers already converted from 1-based and applied `PnIndex` where
228/// the face itself declares it; the set-level `PnIndex` hop is applied here so
229/// both families resolve to direct positions in `Coordinates`.
230fn resolve_loop(
231    session: &LoweringSession<'_>,
232    owner: EntityId,
233    authored: &[usize],
234    pn: &Option<Vec<usize>>,
235    positions: &[Point3],
236) -> GeometryResult<Vec<u32>> {
237    authored
238        .iter()
239        .map(|index| {
240            let direct = match pn {
241                Some(map) => *map.get(*index).ok_or_else(|| {
242                    session.degenerate(
243                        owner,
244                        KIND,
245                        format!(
246                            "CoordIndex {} is past the end of PnIndex ({} entries)",
247                            index + 1,
248                            map.len()
249                        ),
250                    )
251                })?,
252                None => *index,
253            };
254            checked_index(session, owner, direct, positions.len(), "CoordIndex")
255        })
256        .collect()
257}
258
259#[cfg(test)]
260mod tests;
261
262mod texture;
263pub use texture::UV_CHANNEL;