Skip to main content

ifc_geometry/lower/
brep.rs

1//! Faceted B-rep lowering into exact topology.
2//!
3//! # Why topology and not a mesh
4//!
5//! An `IfcFacetedBrep` is a solid with planar faces, not a render mesh. It
6//! carries face adjacency, bound nesting (holes), and void shells. Flattening
7//! it to triangles at read time destroys exactly the information a boolean or
8//! a volume query needs, and triangulation is a kernel decision. So this
9//! builds `BRep<NodeId>` and leaves tessellation to the
10//! `axiolid-tessellation-contract` operation boundary.
11//!
12//! # Sharing is the whole problem
13//!
14//! In `shared_point_faceted_brep.ifc`, 12 solids and 2028 faces are built
15//! from ONE pool of 196 `IfcCartesianPoint` records. Every point is reused by
16//! several faces, and every interior edge is shared by exactly two. Emitting
17//! one vertex per polygon slot would produce 8112 vertices where 196 exist,
18//! and no edge would ever be shared -- which silently turns a closed solid
19//! into a pile of disconnected facets. Interning by `EntityId` (vertices) and
20//! by unordered endpoint pair (edges) is what preserves the manifold.
21
22use std::collections::BTreeMap;
23
24use axiolid_core::Point3;
25use axiolid_model::{GeometryNode, NodeId};
26use axiolid_topology::{
27    BRep, Edge, EdgeId, EdgeUse, Face, FaceBound, Loop, Orientation, Shell, ShellId, Solid, Vertex,
28    VertexId,
29};
30use ifc_model::EntityId;
31
32use crate::error::{GeometryError, GeometryResult};
33use crate::lower::curve::lower_curve_node;
34use crate::lower::session::{DegenerateFacePolicy, LoweringSession};
35use crate::lower::surface::lower_surface_node;
36use crate::resource::point::CartesianPoint;
37use crate::resource::topology::{
38    expect_type, ConnectedFaceSet, EdgeCurve as EdgeCurveView, EdgeLoop as EdgeLoopView,
39    Face as FaceView, FaceBound as FaceBoundView, FaceSurface as FaceSurfaceView,
40    ManifoldSolidBrep, OrientedEdge as OrientedEdgeView, PolyLoop, Subedge as SubedgeView,
41    VertexPoint as VertexPointView,
42};
43use crate::select::is_a;
44use crate::transform::Transform;
45
46/// Chain kind reported when a brep nests too deeply or cycles.
47const KIND: &str = "faceted brep";
48
49/// Accumulates one solid's topology, interning shared vertices and edges.
50///
51/// Scoped to a single brep: two solids that quote the same points are still
52/// independent bodies, so ids must not leak between them.
53struct TopologyBuilder {
54    brep: BRep<NodeId>,
55    vertices: BTreeMap<EntityId, VertexId>,
56    edges: BTreeMap<(usize, usize), EdgeId>,
57    /// Advanced-brep edges, interned by source entity rather than by endpoint
58    /// pair: two edges may share endpoints yet follow different curves.
59    curved_edges: BTreeMap<EntityId, EdgeUse<NodeId>>,
60}
61
62impl TopologyBuilder {
63    fn new() -> Self {
64        Self {
65            brep: BRep::default(),
66            vertices: BTreeMap::new(),
67            edges: BTreeMap::new(),
68            curved_edges: BTreeMap::new(),
69        }
70    }
71
72    /// Intern a vertex by source entity, so one point is one vertex.
73    fn vertex(&mut self, point: EntityId, position: Point3) -> VertexId {
74        if let Some(existing) = self.vertices.get(&point) {
75            return *existing;
76        }
77        let id = self.brep.add_vertex(Vertex { position });
78        self.vertices.insert(point, id);
79        id
80    }
81
82    /// Intern an edge by its unordered endpoints and report its traversal sense.
83    ///
84    /// A closed manifold shares each edge between two faces that walk it in
85    /// opposite directions. Keying on the sorted pair makes both walks find the
86    /// same edge; the returned orientation records which way this use goes.
87    fn edge(&mut self, start: VertexId, end: VertexId) -> EdgeUse<NodeId> {
88        let (low, high) = (start.index(), end.index());
89        let forward = low <= high;
90        let key = if forward { (low, high) } else { (high, low) };
91        let edge = *self.edges.entry(key).or_insert_with(|| {
92            let (a, b) = if forward { (start, end) } else { (end, start) };
93            self.brep.add_edge(Edge {
94                start: a,
95                end: b,
96                curve: None,
97            })
98        });
99        EdgeUse {
100            edge,
101            orientation: if forward {
102                Orientation::Forward
103            } else {
104                Orientation::Reversed
105            },
106            // A faceted loop has no parametric curve: IfcPolyLoop gives
107            // vertices only. A pcurve would have to be invented.
108            pcurve: None,
109        }
110    }
111}
112
113/// Lower one `IfcFacetedBrep` (or `WithVoids`) into a `BRep` node.
114///
115/// `frame` places the solid; brep coordinates are absolute in the file's
116/// length unit, so the world frame is applied to each vertex here rather than
117/// wrapped around the result. That keeps one body one node.
118pub fn lower_faceted_brep_node(
119    session: &mut LoweringSession<'_>,
120    id: EntityId,
121    frame: Transform,
122) -> GeometryResult<NodeId> {
123    if let Some(node) = session.memoized(id, KIND, frame) {
124        return Ok(node);
125    }
126    session.enter(id, KIND)?;
127    let result = build(session, id, frame);
128    session.exit(id);
129    let node = result?;
130    session.memoize(id, KIND, frame, node);
131    Ok(node)
132}
133
134fn build(
135    session: &mut LoweringSession<'_>,
136    id: EntityId,
137    frame: Transform,
138) -> GeometryResult<NodeId> {
139    let entity = session.entity(id, id)?;
140    let view = ManifoldSolidBrep::new(id, entity);
141    let outer_ref = view.outer()?;
142    let void_refs = view.voids()?;
143
144    let mut builder = TopologyBuilder::new();
145    let outer = shell(session, &mut builder, id, outer_ref, frame)?;
146    let mut voids = Vec::with_capacity(void_refs.len());
147    for void_ref in void_refs {
148        voids.push(shell(session, &mut builder, id, void_ref, frame)?);
149    }
150    builder.brep.add_solid(Solid { outer, voids });
151    session.node_for(id, GeometryNode::BRep(builder.brep))
152}
153
154/// Lower one shell or connected face set as a standalone `BRep` node.
155///
156/// A surface model's members are shells, which are not representation items
157/// and so cannot go through the item dispatcher. Each becomes its own BRep
158/// carrying exactly one shell and NO solid: a surface model asserts no
159/// volume, and adding a `Solid` here would manufacture one.
160pub fn lower_shell_node(
161    session: &mut LoweringSession<'_>,
162    referrer: EntityId,
163    id: EntityId,
164    frame: Transform,
165) -> GeometryResult<NodeId> {
166    if let Some(node) = session.memoized(id, KIND, frame) {
167        return Ok(node);
168    }
169    session.enter(id, KIND)?;
170    let mut builder = TopologyBuilder::new();
171    let result = shell(session, &mut builder, referrer, id, frame);
172    session.exit(id);
173    result?;
174    let node = session.node_for(id, GeometryNode::BRep(builder.brep))?;
175    session.memoize(id, KIND, frame, node);
176    Ok(node)
177}
178
179/// Chain kind reported when a standalone face surface nests or cycles.
180const FACE_KIND: &str = "face surface";
181
182/// Lower one `IfcFaceSurface` or `IfcAdvancedFace` as a single-face open `BRep`.
183///
184/// `IfcFaceSurface` is an `IfcFace`, NOT an `IfcSurface`, in every release
185/// (IFC2X3 TC1, IFC4 ADD2 TC1 and IFC4X3 ADD2 all declare it
186/// `SUBTYPE OF (IfcFace)`), so the surface lowerer never sees one and it is
187/// dispatched here instead.
188///
189/// A face surface is a legal representation item and a member of
190/// `IfcSurfaceOrFaceSurface`, so a connection surface or a topology
191/// representation may name one directly rather than through a shell. It is
192/// lowered through the same face path a B-rep uses -- carrier surface,
193/// `SameSense`, and each bound's `Orientation` all compose exactly as they do
194/// inside a solid -- into ONE open shell holding that face and NO solid. A
195/// face bounds no volume; closing the shell or adding a `Solid` would
196/// manufacture one.
197///
198/// Refuses anything other than the two face-surface types with
199/// [`crate::GeometryError::WrongEntityType`] (a plain `IfcFace` has no
200/// carrier surface and is not a member of `IfcSurfaceOrFaceSurface`), and a
201/// face whose only area collapses under
202/// [`DegenerateFacePolicy::DropAndReport`] with
203/// [`crate::GeometryError::Degenerate`]: nothing is left to return.
204pub fn lower_face_surface_node(
205    session: &mut LoweringSession<'_>,
206    id: EntityId,
207    frame: Transform,
208) -> GeometryResult<NodeId> {
209    if let Some(node) = session.memoized(id, FACE_KIND, frame) {
210        return Ok(node);
211    }
212    let entity = expect_type(
213        session.model(),
214        id,
215        id,
216        &["IFCFACESURFACE", "IFCADVANCEDFACE"],
217        "IfcFaceSurface",
218    )?;
219    session.enter(id, FACE_KIND)?;
220    let mut builder = TopologyBuilder::new();
221    let result = face(session, &mut builder, id, id, frame);
222    session.exit(id);
223    let Some(face_id) = result? else {
224        return Err(session.degenerate(
225            id,
226            &entity.type_name.to_ascii_uppercase(),
227            "the face's outer bound collapsed and the face was dropped",
228        ));
229    };
230    builder.brep.add_shell(Shell {
231        faces: vec![(face_id, Orientation::Forward)],
232        closed: false,
233    });
234    let node = session.node_for(id, GeometryNode::BRep(builder.brep))?;
235    session.memoize(id, FACE_KIND, frame, node);
236    Ok(node)
237}
238
239/// Lower one shell and every face it holds.
240fn shell(
241    session: &mut LoweringSession<'_>,
242    builder: &mut TopologyBuilder,
243    referrer: EntityId,
244    id: EntityId,
245    frame: Transform,
246) -> GeometryResult<ShellId> {
247    let entity = expect_type(
248        session.model(),
249        referrer,
250        id,
251        &["IFCCLOSEDSHELL", "IFCOPENSHELL", "IFCCONNECTEDFACESET"],
252        "IfcConnectedFaceSet",
253    )?;
254    let view = ConnectedFaceSet::new(id, entity);
255    let closed = view.is_closed();
256    let mut faces = Vec::new();
257    for face_ref in view.faces()? {
258        // `None` is a face dropped under DegenerateFacePolicy::DropAndReport.
259        if let Some(face_id) = face(session, builder, id, face_ref, frame)? {
260            faces.push((face_id, Orientation::Forward));
261        }
262    }
263    if faces.is_empty() {
264        // Only reachable when every face was dropped. An empty shell is not
265        // "the shell minus its slivers"; it is nothing, so say so here.
266        return Err(session.degenerate(
267            id,
268            "IFCCONNECTEDFACESET",
269            "every face of the shell collapsed and was dropped".to_string(),
270        ));
271    }
272    Ok(builder.brep.add_shell(Shell { faces, closed }))
273}
274
275/// Lower one face and all of its bounds.
276///
277/// A planar facet needs no support surface: the loop's points define the plane
278/// exactly. `Face::surface` stays `None` rather than inventing a fitted plane
279/// that could disagree with the vertices.
280///
281/// Returns `Ok(None)` only under [`DegenerateFacePolicy::DropAndReport`], for
282/// a face whose outer bound (or only bound) collapses. Such a face covers no
283/// area. A collapsed INNER bound of a face that keeps a valid outer bound is
284/// refused under every policy: dropping that face would remove real area.
285fn face(
286    session: &mut LoweringSession<'_>,
287    builder: &mut TopologyBuilder,
288    referrer: EntityId,
289    id: EntityId,
290    frame: Transform,
291) -> GeometryResult<Option<axiolid_topology::FaceId>> {
292    let entity = expect_type(
293        session.model(),
294        referrer,
295        id,
296        &["IFCFACE", "IFCFACESURFACE", "IFCADVANCEDFACE"],
297        "IfcFace",
298    )?;
299    let view = FaceView::new(id, entity);
300    let bound_refs = view.bounds()?;
301    // Decide before interning anything, so a dropped face leaves no dangling
302    // vertices or edges behind in the shared topology.
303    if session.face_policy() == DegenerateFacePolicy::DropAndReport {
304        let mut collapsed_outer = false;
305        for &bound_ref in &bound_refs {
306            if collapsed_poly_loop(session, bound_ref)?.is_none() {
307                continue;
308            }
309            let bound_entity = session.entity(id, bound_ref)?;
310            // A collapsed inner bound is left to `poly_loop`, which refuses it
311            // with the usual error.
312            if bound_refs.len() == 1 || FaceBoundView::new(bound_ref, bound_entity).is_outer() {
313                collapsed_outer = true;
314            }
315        }
316        if collapsed_outer {
317            session.report_dropped_face(id);
318            return Ok(None);
319        }
320    }
321    let mut bounds = Vec::new();
322    for bound_ref in bound_refs {
323        bounds.push(bound(session, builder, id, bound_ref, frame)?);
324    }
325    // An IfcFaceSurface names the surface its boundary lies on, and SameSense
326    // says whether the face agrees with that surface's normal. A plain
327    // IfcFace has neither: its loop points define the plane exactly, so the
328    // handle stays None rather than fitting a plane that could disagree.
329    let (surface, orientation) = if session.type_name(id)?.eq_ignore_ascii_case("IFCFACE") {
330        (None, Orientation::Forward)
331    } else {
332        let surface_view = FaceSurfaceView::new(id, entity);
333        let surface_ref = surface_view.face_surface()?;
334        // Resolve against the face first: the surface lowerer can only report
335        // a dangling id against itself, which hides which face named it, and
336        // reports a non-surface as an unsupported surface family rather than
337        // the broken reference it is.
338        let surface_type = &session.entity(id, surface_ref)?.type_name;
339        if !is_a(&surface_type.to_ascii_uppercase(), "IFCSURFACE") {
340            return Err(GeometryError::WrongEntityType {
341                entity: surface_ref,
342                actual: surface_type.to_string(),
343                expected: "IfcSurface",
344            });
345        }
346        let node = lower_surface_node(session, surface_ref, frame)?;
347        let sense = if surface_view.same_sense() {
348            Orientation::Forward
349        } else {
350            Orientation::Reversed
351        };
352        (Some(node), sense)
353    };
354    Ok(Some(builder.brep.add_face(Face {
355        surface,
356        bounds,
357        orientation,
358    })))
359}
360
361/// The poly loop a face bound names, if that loop collapses.
362///
363/// Uses the same test as [`poly_loop`]'s refusal, on point ids, so the drop
364/// policy can never disagree with what the default would have refused.
365/// Anything that is not a well-formed poly loop returns `None` and is left to
366/// the normal path, which reports it with its usual error.
367fn collapsed_poly_loop(
368    session: &LoweringSession<'_>,
369    bound_ref: EntityId,
370) -> GeometryResult<Option<EntityId>> {
371    let Some(bound_entity) = session.model().get(bound_ref) else {
372        return Ok(None);
373    };
374    let Ok(loop_ref) = FaceBoundView::new(bound_ref, bound_entity).bound() else {
375        return Ok(None);
376    };
377    let Some(loop_entity) = session.model().get(loop_ref) else {
378        return Ok(None);
379    };
380    if !loop_entity.type_name.eq_ignore_ascii_case("IFCPOLYLOOP") {
381        return Ok(None);
382    }
383    let Ok(points) = PolyLoop::new(loop_ref, loop_entity).polygon() else {
384        return Ok(None);
385    };
386    Ok((distinct_edge_count(&points) < 3).then_some(loop_ref))
387}
388
389/// Implied edges of a closed polygon that join two different points.
390///
391/// Vertices are interned by point entity, so two slots naming the same
392/// `IfcCartesianPoint` are one vertex and the edge between them vanishes.
393fn distinct_edge_count(points: &[EntityId]) -> usize {
394    (0..points.len())
395        .filter(|&index| points[index] != points[(index + 1) % points.len()])
396        .count()
397}
398
399/// Lower one face bound into a loop plus its orientation flags.
400fn bound(
401    session: &mut LoweringSession<'_>,
402    builder: &mut TopologyBuilder,
403    referrer: EntityId,
404    id: EntityId,
405    frame: Transform,
406) -> GeometryResult<FaceBound> {
407    let entity = expect_type(
408        session.model(),
409        referrer,
410        id,
411        &["IFCFACEBOUND", "IFCFACEOUTERBOUND"],
412        "IfcFaceBound",
413    )?;
414    let view = FaceBoundView::new(id, entity);
415    let bound_ref = view.bound()?;
416    let bound_type = session.type_name(bound_ref)?;
417    // Each loop kind that cannot bound a face is named here. Falling through
418    // to `poly_loop` reported "not a IfcPolyLoop", which a caller reads as a
419    // broken file rather than valid IFC this bridge declines to interpret.
420    for (name, rationale) in [
421        (
422            "IFCVERTEXLOOP",
423            "a single-vertex loop bounds zero area, so it contributes no face bound",
424        ),
425        (
426            "IFCLOOP",
427            "generic loop has no concrete point or edge representation",
428        ),
429        ("IFCPATH", "path topology is not a face-bound loop"),
430    ] {
431        if bound_type.eq_ignore_ascii_case(name) {
432            return Err(session.unsupported(bound_ref, &bound_type, rationale));
433        }
434    }
435    let loop_id = if bound_type.eq_ignore_ascii_case("IFCEDGELOOP") {
436        edge_loop(session, builder, id, bound_ref, frame)?
437    } else {
438        poly_loop(session, builder, id, bound_ref, frame)?
439    };
440    Ok(FaceBound {
441        loop_id,
442        orientation: if view.orientation()? {
443            Orientation::Forward
444        } else {
445            Orientation::Reversed
446        },
447        outer: view.is_outer(),
448    })
449}
450
451/// Lower one `IfcPolyLoop` into interned vertices and edges.
452///
453/// The polygon is implicitly closed: the schema lists N points and the closing
454/// edge from the last back to the first is implied. Emitting only N-1 edges
455/// leaves the loop open and every downstream closure check fails.
456fn poly_loop(
457    session: &mut LoweringSession<'_>,
458    builder: &mut TopologyBuilder,
459    referrer: EntityId,
460    id: EntityId,
461    frame: Transform,
462) -> GeometryResult<axiolid_topology::LoopId> {
463    let entity = expect_type(
464        session.model(),
465        referrer,
466        id,
467        &["IFCPOLYLOOP"],
468        "IfcPolyLoop",
469    )?;
470    let view = PolyLoop::new(id, entity);
471    let points = view.polygon()?;
472
473    let mut vertices = Vec::with_capacity(points.len());
474    for point_ref in &points {
475        let point_entity = session.entity(id, *point_ref)?;
476        let raw = CartesianPoint::new(*point_ref, point_entity).coordinates_3d()?;
477        let scaled = raw.map(|value| session.units().length(value));
478        let placed = frame.apply(scaled);
479        vertices.push(builder.vertex(*point_ref, Point3::from_array(placed)));
480    }
481
482    let mut edges = Vec::with_capacity(vertices.len());
483    for (index, start) in vertices.iter().enumerate() {
484        let end = vertices[(index + 1) % vertices.len()];
485        if *start == end {
486            continue;
487        }
488        edges.push(builder.edge(*start, end));
489    }
490    if edges.len() < 3 {
491        return Err(session.degenerate(
492            id,
493            "IFCPOLYLOOP",
494            format!("loop collapses to {} distinct edges", edges.len()),
495        ));
496    }
497    Ok(builder.brep.add_loop(Loop { edges }))
498}
499
500/// Lower one `IfcEdgeLoop` into interned vertices and shared edges.
501///
502/// Unlike a poly loop this is already a list of edges, and the sharing is
503/// explicit: several oriented edges point at one `IfcEdgeCurve`. Interning by
504/// the underlying edge entity is what keeps the two faces meeting at a seam
505/// attached to the SAME topological edge.
506fn edge_loop(
507    session: &mut LoweringSession<'_>,
508    builder: &mut TopologyBuilder,
509    referrer: EntityId,
510    id: EntityId,
511    frame: Transform,
512) -> GeometryResult<axiolid_topology::LoopId> {
513    let entity = expect_type(
514        session.model(),
515        referrer,
516        id,
517        &["IFCEDGELOOP"],
518        "IfcEdgeLoop",
519    )?;
520    let view = EdgeLoopView::new(id, entity);
521    let mut edges = Vec::new();
522    for oriented_ref in view.edge_list()? {
523        edges.push(oriented_edge(session, builder, id, oriented_ref, frame)?);
524    }
525    Ok(builder.brep.add_loop(Loop { edges }))
526}
527
528/// Resolve one `IfcOrientedEdge` to a use of a shared, interned edge.
529///
530/// The oriented edge's own flag composes with the sense the interned edge was
531/// first created in: an edge stored reversed and then used reversed runs
532/// forward. Dropping either flag half-flips seams and the shell stops closing.
533fn oriented_edge(
534    session: &mut LoweringSession<'_>,
535    builder: &mut TopologyBuilder,
536    referrer: EntityId,
537    id: EntityId,
538    frame: Transform,
539) -> GeometryResult<EdgeUse<NodeId>> {
540    let entity = expect_type(
541        session.model(),
542        referrer,
543        id,
544        &["IFCORIENTEDEDGE"],
545        "IfcOrientedEdge",
546    )?;
547    let view = OrientedEdgeView::new(id, entity);
548    let base = edge_of_any_kind(session, builder, id, view.edge_element()?, frame)?;
549    if view.orientation() {
550        Ok(base)
551    } else {
552        Ok(EdgeUse {
553            edge: base.edge,
554            orientation: flip(base.orientation),
555            pcurve: base.pcurve,
556        })
557    }
558}
559
560/// Intern one `IfcEdgeCurve` (or plain `IfcEdge`) and lower its support curve.
561///
562/// Keyed by entity id, not by endpoint pair: two edges can share endpoints and
563/// still be different curves (the two halves of a full circle, for instance),
564/// so the geometric key used for poly loops would wrongly merge them.
565fn edge_curve(
566    session: &mut LoweringSession<'_>,
567    builder: &mut TopologyBuilder,
568    referrer: EntityId,
569    id: EntityId,
570    frame: Transform,
571) -> GeometryResult<EdgeUse<NodeId>> {
572    if let Some(existing) = builder.curved_edges.get(&id) {
573        return Ok(*existing);
574    }
575    let entity = expect_type(
576        session.model(),
577        referrer,
578        id,
579        &["IFCEDGE", "IFCEDGECURVE"],
580        "IfcEdge",
581    )?;
582    let view = EdgeCurveView::new(id, entity);
583    let start = topological_vertex(session, builder, id, view.start()?, frame)?;
584    let end = topological_vertex(session, builder, id, view.end()?, frame)?;
585    let (curve, pcurve) = match view.edge_geometry() {
586        Some(curve_ref) if session.type_name(curve_ref)? == "IFCPCURVE" => {
587            (None, Some(lower_curve_node(session, curve_ref, frame)?))
588        }
589        Some(curve_ref) => (Some(lower_curve_node(session, curve_ref, frame)?), None),
590        None => (None, None),
591    };
592    // An Axiolid edge runs from `start` to `end` in its curve's own sense,
593    // and a curve without a p-curve is trimmed at those vertices: a circle
594    // or an ellipse is the arc going FORWARD from `start` to `end`
595    // (axiolid/kernel#319). `SameSense = .F.` says the IFC edge runs from
596    // EdgeStart to EdgeEnd against its curve, so the curve runs from
597    // EdgeEnd to EdgeStart: that is the stored edge, and the IFC edge is
598    // its reversed use. Keeping the file's vertex order with a reversed use
599    // would select the other arc of a closed curve.
600    let (start, end, orientation) = if view.same_sense() {
601        (start, end, Orientation::Forward)
602    } else {
603        (end, start, Orientation::Reversed)
604    };
605    let edge = builder.brep.add_edge(Edge { start, end, curve });
606    // IFC permits EdgeGeometry itself to be an IfcPCurve. Keep that
607    // parameter-space relation on the use; placing it in Edge.curve would
608    // mislabel it as the edge's 3D carrier geometry.
609    let use_ = EdgeUse {
610        edge,
611        orientation,
612        pcurve,
613    };
614    builder.curved_edges.insert(id, use_);
615    Ok(use_)
616}
617
618/// Resolve one `IfcSubedge` to an interned edge carrying the parent's curve.
619///
620/// A subedge states its own `EdgeStart`/`EdgeEnd` and names a `ParentEdge`
621/// that supplies the carrier geometry. The carved piece is therefore the
622/// subedge's own vertices riding the parent's curve -- no trim is computed
623/// here, because IFC states the endpoints outright and the kernel edge
624/// already means "this curve between these two vertices".
625///
626/// `ParentEdge` may itself be an `IfcSubedge`, so the carrier is reached by
627/// walking to the first ancestor that supplies geometry. The walk is bounded
628/// by the session's own chain limit: a cyclic ParentEdge would otherwise
629/// recurse forever.
630fn subedge(
631    session: &mut LoweringSession<'_>,
632    builder: &mut TopologyBuilder,
633    referrer: EntityId,
634    id: EntityId,
635    frame: Transform,
636) -> GeometryResult<EdgeUse<NodeId>> {
637    if let Some(existing) = builder.curved_edges.get(&id) {
638        return Ok(*existing);
639    }
640    let entity = expect_type(session.model(), referrer, id, &["IFCSUBEDGE"], "IfcSubedge")?;
641    let view = SubedgeView::new(id, entity);
642    let start = topological_vertex(session, builder, id, view.start()?, frame)?;
643    let end = topological_vertex(session, builder, id, view.end()?, frame)?;
644
645    // The parent supplies geometry and sense; the subedge supplies extent.
646    let parent = edge_of_any_kind(session, builder, id, view.parent_edge()?, frame)?;
647    let curve = builder
648        .brep
649        .edges()
650        .get(parent.edge.index())
651        .and_then(|parent_edge| parent_edge.curve);
652
653    // The subedge runs in its parent's sense. A parent that runs against
654    // its curve (`SameSense = .F.`) is stored from its curve's start and
655    // used reversed; the subedge is stored the same way round, so the
656    // kernel reads the piece of the curve between its own vertices.
657    let (start, end) = match parent.orientation {
658        Orientation::Forward => (start, end),
659        Orientation::Reversed => (end, start),
660    };
661    let edge = builder.brep.add_edge(Edge { start, end, curve });
662    let use_ = EdgeUse {
663        edge,
664        orientation: parent.orientation,
665        pcurve: parent.pcurve,
666    };
667    builder.curved_edges.insert(id, use_);
668    Ok(use_)
669}
670
671/// Route one edge reference to the lowering its concrete type needs.
672///
673/// `IfcOrientedEdge.EdgeElement` and `IfcSubedge.ParentEdge` are both typed
674/// `IfcEdge`, so either may name a subedge. Dispatching on the concrete type
675/// keeps that decision in one place.
676fn edge_of_any_kind(
677    session: &mut LoweringSession<'_>,
678    builder: &mut TopologyBuilder,
679    referrer: EntityId,
680    id: EntityId,
681    frame: Transform,
682) -> GeometryResult<EdgeUse<NodeId>> {
683    if session.type_name(id)? == "IFCSUBEDGE" {
684        subedge(session, builder, referrer, id, frame)
685    } else {
686        edge_curve(session, builder, referrer, id, frame)
687    }
688}
689
690/// Intern an `IfcVertexPoint`, reusing the vertex when several edges meet.
691fn topological_vertex(
692    session: &mut LoweringSession<'_>,
693    builder: &mut TopologyBuilder,
694    referrer: EntityId,
695    id: EntityId,
696    frame: Transform,
697) -> GeometryResult<VertexId> {
698    // `IfcVertex` is the abstract supertype: it carries no point geometry, so
699    // there is nothing to place. Naming it as unsupported keeps it distinct
700    // from a malformed file that put an unrelated entity here.
701    let type_name = session.type_name(id)?;
702    if type_name.eq_ignore_ascii_case("IFCVERTEX") {
703        return Err(session.unsupported(
704            id,
705            &type_name,
706            "generic vertex carries no point geometry",
707        ));
708    }
709    let entity = expect_type(
710        session.model(),
711        referrer,
712        id,
713        &["IFCVERTEXPOINT"],
714        "IfcVertexPoint",
715    )?;
716    let point_ref = VertexPointView::new(id, entity).vertex_geometry()?;
717    let point_entity = session.entity(id, point_ref)?;
718    let raw = CartesianPoint::new(point_ref, point_entity).coordinates_3d()?;
719    let scaled = raw.map(|value| session.units().length(value));
720    let placed = frame.apply(scaled);
721    Ok(builder.vertex(id, Point3::from_array(placed)))
722}
723
724/// Reverse a traversal sense.
725fn flip(orientation: Orientation) -> Orientation {
726    match orientation {
727        Orientation::Forward => Orientation::Reversed,
728        Orientation::Reversed => Orientation::Forward,
729    }
730}