ifc-geometry 0.4.4

IFC semantic views lowered into the format-neutral geometry DAG.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! Faceted B-rep lowering into exact topology.
//!
//! # Why topology and not a mesh
//!
//! An `IfcFacetedBrep` is a solid with planar faces, not a render mesh. It
//! carries face adjacency, bound nesting (holes), and void shells. Flattening
//! it to triangles at read time destroys exactly the information a boolean or
//! a volume query needs, and triangulation is a kernel decision. So this
//! builds `BRep<NodeId>` and leaves tessellation to the
//! `axiolid-tessellation-contract` operation boundary.
//!
//! # Sharing is the whole problem
//!
//! In `shared_point_faceted_brep.ifc`, 12 solids and 2028 faces are built
//! from ONE pool of 196 `IfcCartesianPoint` records. Every point is reused by
//! several faces, and every interior edge is shared by exactly two. Emitting
//! one vertex per polygon slot would produce 8112 vertices where 196 exist,
//! and no edge would ever be shared -- which silently turns a closed solid
//! into a pile of disconnected facets. Interning by `EntityId` (vertices) and
//! by unordered endpoint pair (edges) is what preserves the manifold.

use std::collections::BTreeMap;

use axiolid_core::Point3;
use axiolid_model::{GeometryNode, NodeId};
use axiolid_topology::{
    BRep, Edge, EdgeId, EdgeUse, Face, FaceBound, Loop, Orientation, Shell, ShellId, Solid, Vertex,
    VertexId,
};
use ifc_model::EntityId;

use crate::error::{GeometryError, GeometryResult};
use crate::lower::curve::lower_curve_node;
use crate::lower::session::{DegenerateFacePolicy, LoweringSession};
use crate::lower::surface::lower_surface_node;
use crate::resource::point::CartesianPoint;
use crate::resource::topology::{
    expect_type, ConnectedFaceSet, EdgeCurve as EdgeCurveView, EdgeLoop as EdgeLoopView,
    Face as FaceView, FaceBound as FaceBoundView, FaceSurface as FaceSurfaceView,
    ManifoldSolidBrep, OrientedEdge as OrientedEdgeView, PolyLoop, Subedge as SubedgeView,
    VertexPoint as VertexPointView,
};
use crate::select::is_a;
use crate::transform::Transform;

/// Chain kind reported when a brep nests too deeply or cycles.
const KIND: &str = "faceted brep";

/// Accumulates one solid's topology, interning shared vertices and edges.
///
/// Scoped to a single brep: two solids that quote the same points are still
/// independent bodies, so ids must not leak between them.
struct TopologyBuilder {
    brep: BRep<NodeId>,
    vertices: BTreeMap<EntityId, VertexId>,
    edges: BTreeMap<(usize, usize), EdgeId>,
    /// Advanced-brep edges, interned by source entity rather than by endpoint
    /// pair: two edges may share endpoints yet follow different curves.
    curved_edges: BTreeMap<EntityId, EdgeUse<NodeId>>,
}

impl TopologyBuilder {
    fn new() -> Self {
        Self {
            brep: BRep::default(),
            vertices: BTreeMap::new(),
            edges: BTreeMap::new(),
            curved_edges: BTreeMap::new(),
        }
    }

    /// Intern a vertex by source entity, so one point is one vertex.
    fn vertex(&mut self, point: EntityId, position: Point3) -> VertexId {
        if let Some(existing) = self.vertices.get(&point) {
            return *existing;
        }
        let id = self.brep.add_vertex(Vertex { position });
        self.vertices.insert(point, id);
        id
    }

    /// Intern an edge by its unordered endpoints and report its traversal sense.
    ///
    /// A closed manifold shares each edge between two faces that walk it in
    /// opposite directions. Keying on the sorted pair makes both walks find the
    /// same edge; the returned orientation records which way this use goes.
    fn edge(&mut self, start: VertexId, end: VertexId) -> EdgeUse<NodeId> {
        let (low, high) = (start.index(), end.index());
        let forward = low <= high;
        let key = if forward { (low, high) } else { (high, low) };
        let edge = *self.edges.entry(key).or_insert_with(|| {
            let (a, b) = if forward { (start, end) } else { (end, start) };
            self.brep.add_edge(Edge {
                start: a,
                end: b,
                curve: None,
            })
        });
        EdgeUse {
            edge,
            orientation: if forward {
                Orientation::Forward
            } else {
                Orientation::Reversed
            },
            // A faceted loop has no parametric curve: IfcPolyLoop gives
            // vertices only. A pcurve would have to be invented.
            pcurve: None,
        }
    }
}

/// Lower one `IfcFacetedBrep` (or `WithVoids`) into a `BRep` node.
///
/// `frame` places the solid; brep coordinates are absolute in the file's
/// length unit, so the world frame is applied to each vertex here rather than
/// wrapped around the result. That keeps one body one node.
pub fn lower_faceted_brep_node(
    session: &mut LoweringSession<'_>,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<NodeId> {
    if let Some(node) = session.memoized(id, KIND, frame) {
        return Ok(node);
    }
    session.enter(id, KIND)?;
    let result = build(session, id, frame);
    session.exit(id);
    let node = result?;
    session.memoize(id, KIND, frame, node);
    Ok(node)
}

fn build(
    session: &mut LoweringSession<'_>,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<NodeId> {
    let entity = session.entity(id, id)?;
    let view = ManifoldSolidBrep::new(id, entity);
    let outer_ref = view.outer()?;
    let void_refs = view.voids()?;

    let mut builder = TopologyBuilder::new();
    let outer = shell(session, &mut builder, id, outer_ref, frame)?;
    let mut voids = Vec::with_capacity(void_refs.len());
    for void_ref in void_refs {
        voids.push(shell(session, &mut builder, id, void_ref, frame)?);
    }
    builder.brep.add_solid(Solid { outer, voids });
    session.node_for(id, GeometryNode::BRep(builder.brep))
}

/// Lower one shell or connected face set as a standalone `BRep` node.
///
/// A surface model's members are shells, which are not representation items
/// and so cannot go through the item dispatcher. Each becomes its own BRep
/// carrying exactly one shell and NO solid: a surface model asserts no
/// volume, and adding a `Solid` here would manufacture one.
pub fn lower_shell_node(
    session: &mut LoweringSession<'_>,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<NodeId> {
    if let Some(node) = session.memoized(id, KIND, frame) {
        return Ok(node);
    }
    session.enter(id, KIND)?;
    let mut builder = TopologyBuilder::new();
    let result = shell(session, &mut builder, referrer, id, frame);
    session.exit(id);
    result?;
    let node = session.node_for(id, GeometryNode::BRep(builder.brep))?;
    session.memoize(id, KIND, frame, node);
    Ok(node)
}

/// Chain kind reported when a standalone face surface nests or cycles.
const FACE_KIND: &str = "face surface";

/// Lower one `IfcFaceSurface` or `IfcAdvancedFace` as a single-face open `BRep`.
///
/// `IfcFaceSurface` is an `IfcFace`, NOT an `IfcSurface`, in every release
/// (IFC2X3 TC1, IFC4 ADD2 TC1 and IFC4X3 ADD2 all declare it
/// `SUBTYPE OF (IfcFace)`), so the surface lowerer never sees one and it is
/// dispatched here instead.
///
/// A face surface is a legal representation item and a member of
/// `IfcSurfaceOrFaceSurface`, so a connection surface or a topology
/// representation may name one directly rather than through a shell. It is
/// lowered through the same face path a B-rep uses -- carrier surface,
/// `SameSense`, and each bound's `Orientation` all compose exactly as they do
/// inside a solid -- into ONE open shell holding that face and NO solid. A
/// face bounds no volume; closing the shell or adding a `Solid` would
/// manufacture one.
///
/// Refuses anything other than the two face-surface types with
/// [`crate::GeometryError::WrongEntityType`] (a plain `IfcFace` has no
/// carrier surface and is not a member of `IfcSurfaceOrFaceSurface`), and a
/// face whose only area collapses under
/// [`DegenerateFacePolicy::DropAndReport`] with
/// [`crate::GeometryError::Degenerate`]: nothing is left to return.
pub fn lower_face_surface_node(
    session: &mut LoweringSession<'_>,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<NodeId> {
    if let Some(node) = session.memoized(id, FACE_KIND, frame) {
        return Ok(node);
    }
    let entity = expect_type(
        session.model(),
        id,
        id,
        &["IFCFACESURFACE", "IFCADVANCEDFACE"],
        "IfcFaceSurface",
    )?;
    session.enter(id, FACE_KIND)?;
    let mut builder = TopologyBuilder::new();
    let result = face(session, &mut builder, id, id, frame);
    session.exit(id);
    let Some(face_id) = result? else {
        return Err(session.degenerate(
            id,
            &entity.type_name.to_ascii_uppercase(),
            "the face's outer bound collapsed and the face was dropped",
        ));
    };
    builder.brep.add_shell(Shell {
        faces: vec![(face_id, Orientation::Forward)],
        closed: false,
    });
    let node = session.node_for(id, GeometryNode::BRep(builder.brep))?;
    session.memoize(id, FACE_KIND, frame, node);
    Ok(node)
}

/// Lower one shell and every face it holds.
fn shell(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<ShellId> {
    let entity = expect_type(
        session.model(),
        referrer,
        id,
        &["IFCCLOSEDSHELL", "IFCOPENSHELL", "IFCCONNECTEDFACESET"],
        "IfcConnectedFaceSet",
    )?;
    let view = ConnectedFaceSet::new(id, entity);
    let closed = view.is_closed();
    let mut faces = Vec::new();
    for face_ref in view.faces()? {
        // `None` is a face dropped under DegenerateFacePolicy::DropAndReport.
        if let Some(face_id) = face(session, builder, id, face_ref, frame)? {
            faces.push((face_id, Orientation::Forward));
        }
    }
    if faces.is_empty() {
        // Only reachable when every face was dropped. An empty shell is not
        // "the shell minus its slivers"; it is nothing, so say so here.
        return Err(session.degenerate(
            id,
            "IFCCONNECTEDFACESET",
            "every face of the shell collapsed and was dropped".to_string(),
        ));
    }
    Ok(builder.brep.add_shell(Shell { faces, closed }))
}

/// Lower one face and all of its bounds.
///
/// A planar facet needs no support surface: the loop's points define the plane
/// exactly. `Face::surface` stays `None` rather than inventing a fitted plane
/// that could disagree with the vertices.
///
/// Returns `Ok(None)` only under [`DegenerateFacePolicy::DropAndReport`], for
/// a face whose outer bound (or only bound) collapses. Such a face covers no
/// area. A collapsed INNER bound of a face that keeps a valid outer bound is
/// refused under every policy: dropping that face would remove real area.
fn face(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<Option<axiolid_topology::FaceId>> {
    let entity = expect_type(
        session.model(),
        referrer,
        id,
        &["IFCFACE", "IFCFACESURFACE", "IFCADVANCEDFACE"],
        "IfcFace",
    )?;
    let view = FaceView::new(id, entity);
    let bound_refs = view.bounds()?;
    // Decide before interning anything, so a dropped face leaves no dangling
    // vertices or edges behind in the shared topology.
    if session.face_policy() == DegenerateFacePolicy::DropAndReport {
        let mut collapsed_outer = false;
        for &bound_ref in &bound_refs {
            if collapsed_poly_loop(session, bound_ref)?.is_none() {
                continue;
            }
            let bound_entity = session.entity(id, bound_ref)?;
            // A collapsed inner bound is left to `poly_loop`, which refuses it
            // with the usual error.
            if bound_refs.len() == 1 || FaceBoundView::new(bound_ref, bound_entity).is_outer() {
                collapsed_outer = true;
            }
        }
        if collapsed_outer {
            session.report_dropped_face(id);
            return Ok(None);
        }
    }
    let mut bounds = Vec::new();
    for bound_ref in bound_refs {
        bounds.push(bound(session, builder, id, bound_ref, frame)?);
    }
    // An IfcFaceSurface names the surface its boundary lies on, and SameSense
    // says whether the face agrees with that surface's normal. A plain
    // IfcFace has neither: its loop points define the plane exactly, so the
    // handle stays None rather than fitting a plane that could disagree.
    let (surface, orientation) = if session.type_name(id)?.eq_ignore_ascii_case("IFCFACE") {
        (None, Orientation::Forward)
    } else {
        let surface_view = FaceSurfaceView::new(id, entity);
        let surface_ref = surface_view.face_surface()?;
        // Resolve against the face first: the surface lowerer can only report
        // a dangling id against itself, which hides which face named it, and
        // reports a non-surface as an unsupported surface family rather than
        // the broken reference it is.
        let surface_type = &session.entity(id, surface_ref)?.type_name;
        if !is_a(&surface_type.to_ascii_uppercase(), "IFCSURFACE") {
            return Err(GeometryError::WrongEntityType {
                entity: surface_ref,
                actual: surface_type.to_string(),
                expected: "IfcSurface",
            });
        }
        let node = lower_surface_node(session, surface_ref, frame)?;
        let sense = if surface_view.same_sense() {
            Orientation::Forward
        } else {
            Orientation::Reversed
        };
        (Some(node), sense)
    };
    Ok(Some(builder.brep.add_face(Face {
        surface,
        bounds,
        orientation,
    })))
}

/// The poly loop a face bound names, if that loop collapses.
///
/// Uses the same test as [`poly_loop`]'s refusal, on point ids, so the drop
/// policy can never disagree with what the default would have refused.
/// Anything that is not a well-formed poly loop returns `None` and is left to
/// the normal path, which reports it with its usual error.
fn collapsed_poly_loop(
    session: &LoweringSession<'_>,
    bound_ref: EntityId,
) -> GeometryResult<Option<EntityId>> {
    let Some(bound_entity) = session.model().get(bound_ref) else {
        return Ok(None);
    };
    let Ok(loop_ref) = FaceBoundView::new(bound_ref, bound_entity).bound() else {
        return Ok(None);
    };
    let Some(loop_entity) = session.model().get(loop_ref) else {
        return Ok(None);
    };
    if !loop_entity.type_name.eq_ignore_ascii_case("IFCPOLYLOOP") {
        return Ok(None);
    }
    let Ok(points) = PolyLoop::new(loop_ref, loop_entity).polygon() else {
        return Ok(None);
    };
    Ok((distinct_edge_count(&points) < 3).then_some(loop_ref))
}

/// Implied edges of a closed polygon that join two different points.
///
/// Vertices are interned by point entity, so two slots naming the same
/// `IfcCartesianPoint` are one vertex and the edge between them vanishes.
fn distinct_edge_count(points: &[EntityId]) -> usize {
    (0..points.len())
        .filter(|&index| points[index] != points[(index + 1) % points.len()])
        .count()
}

/// Lower one face bound into a loop plus its orientation flags.
fn bound(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<FaceBound> {
    let entity = expect_type(
        session.model(),
        referrer,
        id,
        &["IFCFACEBOUND", "IFCFACEOUTERBOUND"],
        "IfcFaceBound",
    )?;
    let view = FaceBoundView::new(id, entity);
    let bound_ref = view.bound()?;
    let bound_type = session.type_name(bound_ref)?;
    // Each loop kind that cannot bound a face is named here. Falling through
    // to `poly_loop` reported "not a IfcPolyLoop", which a caller reads as a
    // broken file rather than valid IFC this bridge declines to interpret.
    for (name, rationale) in [
        (
            "IFCVERTEXLOOP",
            "a single-vertex loop bounds zero area, so it contributes no face bound",
        ),
        (
            "IFCLOOP",
            "generic loop has no concrete point or edge representation",
        ),
        ("IFCPATH", "path topology is not a face-bound loop"),
    ] {
        if bound_type.eq_ignore_ascii_case(name) {
            return Err(session.unsupported(bound_ref, &bound_type, rationale));
        }
    }
    let loop_id = if bound_type.eq_ignore_ascii_case("IFCEDGELOOP") {
        edge_loop(session, builder, id, bound_ref, frame)?
    } else {
        poly_loop(session, builder, id, bound_ref, frame)?
    };
    Ok(FaceBound {
        loop_id,
        orientation: if view.orientation()? {
            Orientation::Forward
        } else {
            Orientation::Reversed
        },
        outer: view.is_outer(),
    })
}

/// Lower one `IfcPolyLoop` into interned vertices and edges.
///
/// The polygon is implicitly closed: the schema lists N points and the closing
/// edge from the last back to the first is implied. Emitting only N-1 edges
/// leaves the loop open and every downstream closure check fails.
fn poly_loop(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<axiolid_topology::LoopId> {
    let entity = expect_type(
        session.model(),
        referrer,
        id,
        &["IFCPOLYLOOP"],
        "IfcPolyLoop",
    )?;
    let view = PolyLoop::new(id, entity);
    let points = view.polygon()?;

    let mut vertices = Vec::with_capacity(points.len());
    for point_ref in &points {
        let point_entity = session.entity(id, *point_ref)?;
        let raw = CartesianPoint::new(*point_ref, point_entity).coordinates_3d()?;
        let scaled = raw.map(|value| session.units().length(value));
        let placed = frame.apply(scaled);
        vertices.push(builder.vertex(*point_ref, Point3::from_array(placed)));
    }

    let mut edges = Vec::with_capacity(vertices.len());
    for (index, start) in vertices.iter().enumerate() {
        let end = vertices[(index + 1) % vertices.len()];
        if *start == end {
            continue;
        }
        edges.push(builder.edge(*start, end));
    }
    if edges.len() < 3 {
        return Err(session.degenerate(
            id,
            "IFCPOLYLOOP",
            format!("loop collapses to {} distinct edges", edges.len()),
        ));
    }
    Ok(builder.brep.add_loop(Loop { edges }))
}

/// Lower one `IfcEdgeLoop` into interned vertices and shared edges.
///
/// Unlike a poly loop this is already a list of edges, and the sharing is
/// explicit: several oriented edges point at one `IfcEdgeCurve`. Interning by
/// the underlying edge entity is what keeps the two faces meeting at a seam
/// attached to the SAME topological edge.
fn edge_loop(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<axiolid_topology::LoopId> {
    let entity = expect_type(
        session.model(),
        referrer,
        id,
        &["IFCEDGELOOP"],
        "IfcEdgeLoop",
    )?;
    let view = EdgeLoopView::new(id, entity);
    let mut edges = Vec::new();
    for oriented_ref in view.edge_list()? {
        edges.push(oriented_edge(session, builder, id, oriented_ref, frame)?);
    }
    Ok(builder.brep.add_loop(Loop { edges }))
}

/// Resolve one `IfcOrientedEdge` to a use of a shared, interned edge.
///
/// The oriented edge's own flag composes with the sense the interned edge was
/// first created in: an edge stored reversed and then used reversed runs
/// forward. Dropping either flag half-flips seams and the shell stops closing.
fn oriented_edge(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<EdgeUse<NodeId>> {
    let entity = expect_type(
        session.model(),
        referrer,
        id,
        &["IFCORIENTEDEDGE"],
        "IfcOrientedEdge",
    )?;
    let view = OrientedEdgeView::new(id, entity);
    let base = edge_of_any_kind(session, builder, id, view.edge_element()?, frame)?;
    if view.orientation() {
        Ok(base)
    } else {
        Ok(EdgeUse {
            edge: base.edge,
            orientation: flip(base.orientation),
            pcurve: base.pcurve,
        })
    }
}

/// Intern one `IfcEdgeCurve` (or plain `IfcEdge`) and lower its support curve.
///
/// Keyed by entity id, not by endpoint pair: two edges can share endpoints and
/// still be different curves (the two halves of a full circle, for instance),
/// so the geometric key used for poly loops would wrongly merge them.
fn edge_curve(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<EdgeUse<NodeId>> {
    if let Some(existing) = builder.curved_edges.get(&id) {
        return Ok(*existing);
    }
    let entity = expect_type(
        session.model(),
        referrer,
        id,
        &["IFCEDGE", "IFCEDGECURVE"],
        "IfcEdge",
    )?;
    let view = EdgeCurveView::new(id, entity);
    let start = topological_vertex(session, builder, id, view.start()?, frame)?;
    let end = topological_vertex(session, builder, id, view.end()?, frame)?;
    let (curve, pcurve) = match view.edge_geometry() {
        Some(curve_ref) if session.type_name(curve_ref)? == "IFCPCURVE" => {
            (None, Some(lower_curve_node(session, curve_ref, frame)?))
        }
        Some(curve_ref) => (Some(lower_curve_node(session, curve_ref, frame)?), None),
        None => (None, None),
    };
    // SameSense false means the edge runs against its curve. Record that as
    // the stored edge's orientation rather than swapping the vertices, so the
    // curve handle and the vertex order stay consistent with the file.
    let orientation = if view.same_sense() {
        Orientation::Forward
    } else {
        Orientation::Reversed
    };
    let edge = builder.brep.add_edge(Edge { start, end, curve });
    // IFC permits EdgeGeometry itself to be an IfcPCurve. Keep that
    // parameter-space relation on the use; placing it in Edge.curve would
    // mislabel it as the edge's 3D carrier geometry.
    let use_ = EdgeUse {
        edge,
        orientation,
        pcurve,
    };
    builder.curved_edges.insert(id, use_);
    Ok(use_)
}

/// Resolve one `IfcSubedge` to an interned edge carrying the parent's curve.
///
/// A subedge states its own `EdgeStart`/`EdgeEnd` and names a `ParentEdge`
/// that supplies the carrier geometry. The carved piece is therefore the
/// subedge's own vertices riding the parent's curve -- no trim is computed
/// here, because IFC states the endpoints outright and the kernel edge
/// already means "this curve between these two vertices".
///
/// `ParentEdge` may itself be an `IfcSubedge`, so the carrier is reached by
/// walking to the first ancestor that supplies geometry. The walk is bounded
/// by the session's own chain limit: a cyclic ParentEdge would otherwise
/// recurse forever.
fn subedge(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<EdgeUse<NodeId>> {
    if let Some(existing) = builder.curved_edges.get(&id) {
        return Ok(*existing);
    }
    let entity = expect_type(session.model(), referrer, id, &["IFCSUBEDGE"], "IfcSubedge")?;
    let view = SubedgeView::new(id, entity);
    let start = topological_vertex(session, builder, id, view.start()?, frame)?;
    let end = topological_vertex(session, builder, id, view.end()?, frame)?;

    // The parent supplies geometry and sense; the subedge supplies extent.
    let parent = edge_of_any_kind(session, builder, id, view.parent_edge()?, frame)?;
    let curve = builder
        .brep
        .edges()
        .get(parent.edge.index())
        .and_then(|parent_edge| parent_edge.curve);

    let edge = builder.brep.add_edge(Edge { start, end, curve });
    let use_ = EdgeUse {
        edge,
        orientation: parent.orientation,
        pcurve: parent.pcurve,
    };
    builder.curved_edges.insert(id, use_);
    Ok(use_)
}

/// Route one edge reference to the lowering its concrete type needs.
///
/// `IfcOrientedEdge.EdgeElement` and `IfcSubedge.ParentEdge` are both typed
/// `IfcEdge`, so either may name a subedge. Dispatching on the concrete type
/// keeps that decision in one place.
fn edge_of_any_kind(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<EdgeUse<NodeId>> {
    if session.type_name(id)? == "IFCSUBEDGE" {
        subedge(session, builder, referrer, id, frame)
    } else {
        edge_curve(session, builder, referrer, id, frame)
    }
}

/// Intern an `IfcVertexPoint`, reusing the vertex when several edges meet.
fn topological_vertex(
    session: &mut LoweringSession<'_>,
    builder: &mut TopologyBuilder,
    referrer: EntityId,
    id: EntityId,
    frame: Transform,
) -> GeometryResult<VertexId> {
    // `IfcVertex` is the abstract supertype: it carries no point geometry, so
    // there is nothing to place. Naming it as unsupported keeps it distinct
    // from a malformed file that put an unrelated entity here.
    let type_name = session.type_name(id)?;
    if type_name.eq_ignore_ascii_case("IFCVERTEX") {
        return Err(session.unsupported(
            id,
            &type_name,
            "generic vertex carries no point geometry",
        ));
    }
    let entity = expect_type(
        session.model(),
        referrer,
        id,
        &["IFCVERTEXPOINT"],
        "IfcVertexPoint",
    )?;
    let point_ref = VertexPointView::new(id, entity).vertex_geometry()?;
    let point_entity = session.entity(id, point_ref)?;
    let raw = CartesianPoint::new(point_ref, point_entity).coordinates_3d()?;
    let scaled = raw.map(|value| session.units().length(value));
    let placed = frame.apply(scaled);
    Ok(builder.vertex(id, Point3::from_array(placed)))
}

/// Reverse a traversal sense.
fn flip(orientation: Orientation) -> Orientation {
    match orientation {
        Orientation::Forward => Orientation::Reversed,
        Orientation::Reversed => Orientation::Forward,
    }
}