axioval-cli 0.3.0

Command-line runner for normalized Axioval packages
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
//! IFC body geometry as Axiolid meshes, registered into a check's session.
//!
//! This is host composition, not an adapter: `axioval-ifc` must not know
//! Axiolid and `axioval-axiolid` must not know IFC, so the CLI reads the same
//! model bytes a second time, meshes each product with `ifc-geometry`, and
//! hands the meshes to the geometry services under the object identities the
//! IFC session already uses.
//!
//! With several models, every source is meshed into one geometry set under
//! its own source-qualified identities, in one shared coordinate system, and
//! every service is bound to all the session's snapshots. A clash between
//! objects of two files is then an ordinary pair of the set.
//!
//! Every object ends up in exactly one of three states, because the geometry
//! services treat them differently:
//!
//! - **meshed**, either exactly (every face planar, so the mesh is the shape)
//!   or as a tessellation within the compiler's chord budget;
//! - **no body**: it occupies no material (a storey, a zone, an opening);
//! - **unmeasured**: it is physical but could not be meshed. Measurements it
//!   could affect refuse rather than act as if it were not there.
//!
//! A group (a zone) has no body, but its plan footprint is the union of its
//! members', so the bridge also declares every group's membership.
//!
//! Relationships derived from geometry (`axioval:derived.*`) need to know
//! which objects are spaces and which are doors, windows or openings. An
//! opening occupies no material, so its void is meshed separately and handed
//! to the derivation alone.

use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;

use axiolid_contracts::ExecutionOptions;
use axiolid_core::Tolerance;
use axiolid_curve::{Curve2, Curve3};
use axiolid_mesh_compile_contract::MeshCompiler;
use axiolid_model::{GeometryGraph, GeometryNode, NodeId, SolidOperation, SurfaceRelation};
use axiolid_primitive::Primitive;
use axiolid_profile::{Profile, SectionProfile};
use axiolid_surface::Surface;
use axioval::axiolid::{
    AxiolidBoundaryCoverageService, AxiolidContactService, AxiolidDerivedRelationshipService,
    AxiolidEnvelopeMembershipService, AxiolidFacadeAreaService, AxiolidFreeSpaceService,
    AxiolidGeometry, AxiolidGuardService, AxiolidLinearQuantityService,
    AxiolidMetricRoutingService, AxiolidPlanAreaService, AxiolidPlanSpanService,
    AxiolidProximityService, AxiolidSightService, AxiolidSpaceService, AxiolidTriangleCountService,
    AxiolidVerticalExtentService, AxiolidWalkabilityService, AxiolidWalkingSurfaceService,
};
use axioval::bcf;
use axioval::engine::{
    BoundaryCoverageServiceHandle, ContactServiceHandle, DerivedRelationshipServiceHandle,
    EnvelopeMembershipServiceHandle, EvidenceSession, FacadeAreaServiceHandle,
    FreeSpaceServiceHandle, GuardServiceHandle, LinearQuantityServiceHandle,
    MetricRoutingServiceHandle, PlanAreaServiceHandle, PlanSpanServiceHandle, PropertyRequest,
    PropertyResolution, PropertyResolutionServiceHandle, ProximityServiceHandle, RelationshipQuery,
    RelationshipSelectionRequest, RelationshipSelectionServiceHandle, SemanticRelationship,
    SightServiceHandle, SourceSnapshot, SpaceServiceHandle, TraversalDirection,
    TriangleCountServiceHandle, TypeHierarchyServiceHandle, VerticalExtentServiceHandle,
    WalkabilityServiceHandle, WalkingSurfaceServiceHandle,
};
use axioval::ir::{ObjectId, PropertyValue, Report, SourceId};
use ifc_geometry::lower::{LoweringSession, lower_connection_surface, lower_product_net};
use ifc_geometry::{RepresentationPurpose, Transform};
use ifc_model::{Codec, EntityId, Model};
use ifc_spatial::relation::boundary::{ConnectionGeometryAnomaly, SpaceBoundary};
use ifc_spatial::{SpatialAnomaly, SpatialKind, SpatialTree};
use ifc_step::StepCodec;
use std::sync::Arc;

/// Linear tolerance handed to the mesh compiler. With no explicit chord
/// budget, curved geometry stays within this distance of the true surface,
/// which is the deviation declared for every tessellated mesh.
const TOLERANCE: Tolerance = Tolerance::MILLIMETRE;
const CHORD_DEVIATION_METRES: f64 = 1e-3;

/// Graph nodes the planarity check visits before calling a product curved.
const NODE_BUDGET: usize = 100_000;

/// Entity types that occupy no material. Names from both IFC2X3 and IFC4;
/// a name a release does not declare simply matches nothing.
const NO_BODY: &[&str] = &[
    "IfcSpatialElement",
    "IfcSpatialStructureElement",
    "IfcFeatureElementSubtraction",
    "IfcVirtualElement",
    "IfcAnnotation",
    "IfcGrid",
    "IfcPort",
    "IfcStructuralItem",
    "IfcStructuralActivity",
];

/// What the bridge did, for the host to report.
#[derive(Debug, Default)]
pub struct GeometryReport {
    pub exact: usize,
    pub tessellated: usize,
    pub no_body: usize,
    /// Physical objects that could not be meshed, with the reason.
    pub unmeasured: Vec<(ObjectId, String)>,
}

/// Each source's model bytes, keyed by the source the session imported them as.
pub type ModelBytes = BTreeMap<SourceId, Vec<u8>>;

/// One parsed model and its unit scale, per source.
struct Parsed {
    model: Model,
    units: ifc_geometry::units::UnitScale,
}

/// Parses the model of every snapshot's source.
fn parse(
    snapshots: &[SourceSnapshot],
    models: &ModelBytes,
) -> Result<BTreeMap<SourceId, Parsed>, Box<dyn Error>> {
    let mut parsed = BTreeMap::new();
    for snapshot in snapshots {
        let source = snapshot.source();
        let bytes = models
            .get(source)
            .ok_or_else(|| format!("no model bytes for source `{source}`"))?;
        let model = StepCodec
            .read_bytes(bytes)
            .map_err(|error| format!("{}: {error}", source.document))?;
        let units = ifc_geometry::units::resolve(&model);
        parsed.insert(source.clone(), Parsed { model, units });
    }
    Ok(parsed)
}

/// Meshes every source's model and registers geometry services for
/// `session`, bound to all its snapshots.
///
/// `models` holds each source's bytes, keyed by the source the session
/// imported them as. Policy choices IFC does not state, such as which
/// surfaces are walkable or which spaces bound the envelope, are the rules'
/// own selections, carried in each request; the bridge declares none of them.
///
/// # Errors
///
/// Returns an error when a source has no bytes, the bytes do not parse (the
/// session already parsed them, so this means they changed) or a service
/// cannot be registered.
pub fn attach(
    session: EvidenceSession,
    models: &ModelBytes,
) -> Result<(EvidenceSession, GeometryReport), Box<dyn Error>> {
    let snapshots: Vec<SourceSnapshot> = session.snapshots().cloned().collect();
    let Some(first) = snapshots.first() else {
        return Err("geometry needs a session over at least one source".into());
    };
    // Set-level evidence (free space, guard, envelope, storey residuals) is
    // cited under one source; evidence about one object cites its own.
    let source = first.source().clone();
    let parsed = parse(&snapshots, models)?;
    let hierarchy = session
        .service::<TypeHierarchyServiceHandle>()
        .ok_or("the session has no type hierarchy to classify objects with")?
        .clone();
    let is_a = |id: &ObjectId, ancestor: &str, kinds: &BTreeMap<ObjectId, String>| {
        kinds
            .get(id)
            .is_some_and(|kind| hierarchy.is_a(&id.source, kind, ancestor).unwrap_or(false))
    };
    let kinds: BTreeMap<ObjectId, String> = session
        .project()
        .objects()
        .map(|object| (object.id.clone(), object.kind().to_owned()))
        .collect();
    let is_a = |id: &ObjectId, ancestor: &str| is_a(id, ancestor, &kinds);

    let backend = ifc_geometry::compile::default_backend();
    let mut geometry = AxiolidGeometry::new();
    let mut report = GeometryReport::default();
    let mut voids: Vec<(ObjectId, Void)> = Vec::new();

    for object in session.project().objects() {
        let id = object.id.clone();
        let Some(Parsed { model, units }) = parsed.get(&id.source) else {
            return Err(format!("no model for source `{}`", id.source).into());
        };
        let is_space = is_a(&id, "IfcSpace");
        let bodiless = !is_a(&id, "IfcProduct")
            || (!is_space && NO_BODY.iter().any(|ancestor| is_a(&id, ancestor)));
        if bodiless {
            if is_a(&id, "IfcOpeningElement") {
                let void = entity_id(&id)
                    .ok_or_else(|| "not a STEP instance id".to_owned())
                    .and_then(|entity| mesh(&backend, model, units, entity))
                    .and_then(|meshed| meshed.ok_or_else(|| "no body representation".into()));
                voids.push((id.clone(), void));
            }
            geometry = geometry.with_no_body(id);
            report.no_body += 1;
            continue;
        }
        let Some(entity) = entity_id(&id) else {
            report
                .unmeasured
                .push((id.clone(), "not a STEP instance id".into()));
            geometry = geometry.with_unmeasured(id, "not a STEP instance id");
            continue;
        };
        match mesh(&backend, model, units, entity) {
            Ok(Some((mesh, true))) => {
                geometry = geometry.with_mesh(id, mesh);
                report.exact += 1;
            }
            Ok(Some((mesh, false))) => {
                geometry = geometry.with_tessellated_mesh(id, mesh, CHORD_DEVIATION_METRES);
                report.tessellated += 1;
            }
            // A space without a body is still no material; it cannot be
            // measured itself, but it obstructs nothing.
            Ok(None) if is_space => {
                geometry = geometry.with_no_body(id);
                report.no_body += 1;
            }
            Ok(None) => {
                let reason = "no body representation";
                report.unmeasured.push((id.clone(), reason.into()));
                geometry = geometry.with_unmeasured(id, reason);
            }
            Err(error) => {
                report.unmeasured.push((id.clone(), error.clone()));
                geometry = geometry.with_unmeasured(id, error);
            }
        }
    }

    let relationships = session.service::<RelationshipSelectionServiceHandle>();
    for (group, members) in groups(relationships, &kinds, &is_a) {
        geometry = match members {
            Ok(members) => geometry.with_group(group, members),
            Err(reason) => geometry.with_undecided_group(group, reason),
        };
    }
    let envelope = envelope_service(&session, &geometry, &source, &kinds)?;
    let space = (
        space_service(&parsed, &geometry, &source, &kinds, &is_a),
        linear_service(&geometry, &voids),
        boundary_service(&backend, &parsed, &geometry, &kinds, &is_a),
        plan_area_service(&geometry, &source, &voids),
    );
    let routes = route_services(&geometry, &source, &kinds, &is_a, &voids);
    let derived = derived_service(&geometry, &parsed, &kinds, &is_a, voids);
    let facade = facade_service(&geometry, &kinds, &is_a);
    let session = register(session, &snapshots, geometry, space, envelope, routes)?
        .with_host_service(FacadeAreaServiceHandle::new(Arc::new(facade)), &snapshots)?
        .with_derived_relationships(
            DerivedRelationshipServiceHandle::new(Arc::new(derived)),
            &snapshots,
        )?;
    Ok((session, report))
}

/// Registers every geometry service over `geometry`, bound to `snapshots`.
fn register(
    session: EvidenceSession,
    snapshots: &[SourceSnapshot],
    geometry: AxiolidGeometry,
    (space, shelves, boundaries, plan_areas): (
        AxiolidSpaceService,
        AxiolidLinearQuantityService,
        AxiolidBoundaryCoverageService,
        AxiolidPlanAreaService,
    ),
    envelope: AxiolidEnvelopeMembershipService,
    (walkability, routing): (AxiolidWalkabilityService, AxiolidMetricRoutingService),
) -> Result<EvidenceSession, Box<dyn Error>> {
    let source = snapshots
        .first()
        .ok_or("geometry needs a session over at least one source")?
        .source()
        .clone();
    let bound = snapshots;
    let session = session
        .with_host_service(
            ContactServiceHandle::new(Arc::new(AxiolidContactService::new(geometry.clone()))),
            bound,
        )?
        .with_host_service(
            FreeSpaceServiceHandle::new(Arc::new(AxiolidFreeSpaceService::new(
                geometry.clone(),
                source.clone(),
            ))),
            bound,
        )?
        .with_host_service(SpaceServiceHandle::new(Arc::new(space)), bound)?
        // Spaces and their declared boundaries are IFC facts.
        .with_host_service(
            BoundaryCoverageServiceHandle::new(Arc::new(boundaries)),
            bound,
        )?
        // Walking surfaces are the guard rule's selection, carried in each
        // request; the host declares none of its own.
        .with_host_service(
            GuardServiceHandle::new(Arc::new(AxiolidGuardService::new(
                geometry.clone(),
                source.clone(),
            ))),
            bound,
        )?
        // Doors and openings are the shelf rule's selection, carried in each
        // request; the bridge hands over the voids of bodiless openings.
        .with_host_service(LinearQuantityServiceHandle::new(Arc::new(shelves)), bound)?
        .with_host_service(
            // Effects continue through the voids of bodiless openings.
            PlanAreaServiceHandle::new(Arc::new(plan_areas)),
            bound,
        )?
        .with_host_service(
            PlanSpanServiceHandle::new(Arc::new(AxiolidPlanSpanService::new(
                geometry.clone(),
                source.clone(),
            ))),
            bound,
        )?
        // Counts the triangles of the meshes this bridge produced, so a
        // count follows its chord budget for curved bodies.
        .with_host_service(
            TriangleCountServiceHandle::new(Arc::new(AxiolidTriangleCountService::new(
                geometry.clone(),
            ))),
            bound,
        )?
        .with_host_service(
            VerticalExtentServiceHandle::new(Arc::new(AxiolidVerticalExtentService::new(
                geometry.clone(),
            ))),
            bound,
        )?
        // Treads, ramp runs and headroom from the same meshes; obstacles are
        // the rule's selection, carried in each request.
        .with_host_service(
            WalkingSurfaceServiceHandle::new(Arc::new(AxiolidWalkingSurfaceService::new(
                geometry.clone(),
            ))),
            bound,
        )?
        // Eyes, targets and blockers are the visibility rule's selection,
        // carried in each request.
        .with_host_service(
            SightServiceHandle::new(Arc::new(AxiolidSightService::new(geometry.clone()))),
            bound,
        )?
        .with_host_service(
            ProximityServiceHandle::new(Arc::new(AxiolidProximityService::new(geometry))),
            bound,
        )?
        // Bounding spaces are the envelope rule's selection, carried in each
        // request; the host declares only what the model states external.
        .with_host_service(
            EnvelopeMembershipServiceHandle::new(Arc::new(envelope)),
            bound,
        )?
        // Walkable surfaces, entrances and obstacles are the walkability
        // rule's selection; metric routing's are IFC classes.
        .with_host_service(WalkabilityServiceHandle::new(Arc::new(walkability)), bound)?
        .with_host_service(MetricRoutingServiceHandle::new(Arc::new(routing)), bound)?;
    Ok(session)
}

/// Members of every group (`IfcGroup`: zones, systems), so a bodiless zone
/// has the union of its members' footprints.
///
/// Membership is `IfcRelAssignsToGroup`, read through the session's
/// relationship service over every object. A refused answer, or no service
/// at all, leaves the membership undecided: the group's footprint is then
/// unavailable, never the empty footprint of a group that groups nothing.
fn groups(
    relationships: Option<&RelationshipSelectionServiceHandle>,
    kinds: &BTreeMap<ObjectId, String>,
    is_a: &impl Fn(&ObjectId, &str) -> bool,
) -> Vec<(ObjectId, Result<Vec<ObjectId>, String>)> {
    let everything: Vec<ObjectId> = kinds.keys().cloned().collect();
    let members = |group: &ObjectId| -> Result<Vec<ObjectId>, String> {
        let relationships =
            relationships.ok_or("the session has no relationship service to read groups with")?;
        let query = RelationshipQuery::Related {
            relationship: SemanticRelationship::try_new("IfcRelAssignsToGroup")
                .map_err(|error| error.to_string())?,
            direction: TraversalDirection::Forward,
            follow_chain: false,
        };
        let request =
            RelationshipSelectionRequest::try_new(group.clone(), everything.clone(), query)
                .map_err(|error| error.to_string())?;
        let selection = relationships
            .select(&request)
            .map_err(|error| error.to_string())?;
        Ok(selection.candidates().to_vec())
    };
    kinds
        .keys()
        .filter(|id| is_a(id, "IfcGroup"))
        .map(|group| (group.clone(), members(group)))
        .collect()
}

/// Envelope membership declarations: what the model states external.
///
/// Which spaces bound the envelope is the envelope rule's selection, carried
/// in each request, so the bridge declares none. Each meshed object's
/// `IsExternal`, from whichever property set states it, is its declaration:
/// `true` external, `false` internal. An object without exactly one such
/// boolean stays undeclared and its rule reports not evaluated; absent is not
/// internal. A bounding space's own declaration is ignored by the adapter.
fn envelope_service(
    session: &EvidenceSession,
    geometry: &AxiolidGeometry,
    source: &SourceId,
    kinds: &BTreeMap<ObjectId, String>,
) -> Result<AxiolidEnvelopeMembershipService, Box<dyn Error>> {
    let properties = session
        .service::<PropertyResolutionServiceHandle>()
        .ok_or("the session has no property service to read declarations with")?;
    let value = |object: &ObjectId, name: &str| -> Option<PropertyValue> {
        let request = PropertyRequest::try_new(object.clone(), None, name).ok()?;
        match properties.resolve(&request).ok()? {
            PropertyResolution::Present(resolved) => Some(resolved.property().value.clone()),
            PropertyResolution::Absent(_) => None,
        }
    };

    let mut service = AxiolidEnvelopeMembershipService::new(geometry.clone(), source.clone());
    for object in kinds.keys() {
        if geometry.mesh(object).is_none() {
            continue;
        }
        match value(object, "IsExternal") {
            Some(PropertyValue::Boolean(true)) => {
                service = service.with_declared_external(object.clone());
            }
            Some(PropertyValue::Boolean(false)) => {
                service = service.with_declared_internal(object.clone());
            }
            _ => {}
        }
    }
    Ok(service)
}

/// An opening's meshed void and whether it is exact, or why it has none.
type Void = Result<(axiolid_mesh::TriMesh, bool), String>;

/// Relationships derived from geometry, over the model's spaces and its
/// doors, windows and openings.
///
/// Every `IfcSpace` is a space and every `IfcDoor`, `IfcWindow` and
/// `IfcOpeningElement` an opening; both are IFC facts. A void that could not
/// be meshed is declared unmeasured, so the derivation refuses it rather than
/// finding no space beside it.
fn derived_service(
    geometry: &AxiolidGeometry,
    parsed: &BTreeMap<SourceId, Parsed>,
    kinds: &BTreeMap<ObjectId, String>,
    is_a: &impl Fn(&ObjectId, &str) -> bool,
    voids: Vec<(ObjectId, Void)>,
) -> AxiolidDerivedRelationshipService {
    let mut service = AxiolidDerivedRelationshipService::new(geometry.clone());
    for id in kinds.keys() {
        if is_a(id, "IfcSpace") {
            service = service.with_space(id.clone());
        } else if is_a(id, "IfcDoor") || is_a(id, "IfcWindow") {
            service = service.with_opening(id.clone());
        }
    }
    for (id, void) in voids {
        service = match void {
            Ok((mesh, true)) => service.with_opening_void(id, mesh),
            Ok((mesh, false)) => {
                service.with_tessellated_opening_void(id, mesh, CHORD_DEVIATION_METRES)
            }
            Err(reason) => service.with_unmeasured_opening_void(id, reason),
        };
    }
    with_levels(service, parsed, kinds, is_a)
}

/// A storey's world height, or why it has none.
type Height = Result<f64, String>;

/// A storey's source and spatial parent: the storeys whose heights order
/// its band.
type Parent = (SourceId, Option<EntityId>);

/// Declares every `IfcBuildingStorey` a level for `spans-level`: its band
/// runs from its placement's height up to the next storey's of the same
/// parent (open above for the highest). A storey whose placement cannot be
/// read, is tilted, or shares its height with a sibling has no band, so a
/// request it could answer refuses.
fn with_levels(
    mut service: AxiolidDerivedRelationshipService,
    parsed: &BTreeMap<SourceId, Parsed>,
    kinds: &BTreeMap<ObjectId, String>,
    is_a: &impl Fn(&ObjectId, &str) -> bool,
) -> AxiolidDerivedRelationshipService {
    let trees: BTreeMap<&SourceId, SpatialTree> = parsed
        .iter()
        .map(|(source, Parsed { model, .. })| (source, SpatialTree::build(model)))
        .collect();
    let mut siblings: BTreeMap<Parent, Vec<(ObjectId, Height)>> = BTreeMap::new();
    for id in kinds.keys().filter(|id| is_a(id, "IfcBuildingStorey")) {
        let (Some(entity), Some(Parsed { model, units })) = (entity_id(id), parsed.get(&id.source))
        else {
            continue;
        };
        let parent = trees
            .get(&id.source)
            .and_then(|tree| tree.node(entity))
            .and_then(|node| node.parent);
        let height = ifc_geometry::product_world_transform(model, units, entity)
            .map_err(|error| error.to_string())
            .and_then(|frame| {
                let up = frame.basis[2];
                if up[0].abs() > 1e-12 || up[1].abs() > 1e-12 || (up[2] - 1.0).abs() > 1e-12 {
                    Err("the storey's placement is tilted".to_owned())
                } else {
                    Ok(frame.origin[2])
                }
            });
        siblings
            .entry((id.source.clone(), parent))
            .or_default()
            .push((id.clone(), height));
    }
    for levels in siblings.into_values() {
        let mut heights: Vec<f64> = levels
            .iter()
            .filter_map(|(_, height)| height.as_ref().ok().copied())
            .collect();
        heights.sort_by(f64::total_cmp);
        for (level, height) in levels {
            service = match height {
                Err(reason) => service.with_unmeasured_level(level, reason),
                #[allow(clippy::float_cmp)]
                Ok(height) if heights.iter().filter(|other| **other == height).count() > 1 => {
                    service.with_unmeasured_level(level, "another storey shares its elevation")
                }
                Ok(height) => {
                    let top = heights.iter().copied().find(|other| *other > height);
                    service.with_level(level, height, top)
                }
            };
        }
    }
    service
}

/// Plan areas over `geometry`, with the exact voids of bodiless openings so
/// an effect can continue through them; any other void is unmeasured.
fn plan_area_service(
    geometry: &AxiolidGeometry,
    source: &SourceId,
    voids: &[(ObjectId, Void)],
) -> AxiolidPlanAreaService {
    voids.iter().fold(
        AxiolidPlanAreaService::new(geometry.clone(), source.clone()),
        |service, (id, void)| match void {
            Ok((mesh, true)) => service.with_opening_void(id.clone(), mesh.clone()),
            Ok((_, false)) | Err(_) => service.with_unmeasured_opening_void(id.clone()),
        },
    )
}

/// Shelf lengths over `geometry`, with the voids of bodiless openings so a
/// shelf rule can place their clearances.
fn linear_service(
    geometry: &AxiolidGeometry,
    voids: &[(ObjectId, Void)],
) -> AxiolidLinearQuantityService {
    voids.iter().fold(
        AxiolidLinearQuantityService::new(geometry.clone()),
        |service, (id, void)| match void {
            Ok((mesh, true)) => service.with_opening_void(id.clone(), mesh.clone()),
            Ok((mesh, false)) => service.with_tessellated_opening_void(
                id.clone(),
                mesh.clone(),
                CHORD_DEVIATION_METRES,
            ),
            Err(_) => service.with_unmeasured_opening_void(id.clone()),
        },
    )
}

/// The walkability and metric-routing services over `geometry`.
fn route_services(
    geometry: &AxiolidGeometry,
    source: &SourceId,
    kinds: &BTreeMap<ObjectId, String>,
    is_a: &impl Fn(&ObjectId, &str) -> bool,
    voids: &[(ObjectId, Void)],
) -> (AxiolidWalkabilityService, AxiolidMetricRoutingService) {
    (
        walkability_service(geometry, source, voids),
        routing_service(geometry, source, kinds, is_a, voids),
    )
}

/// Walkable regions over the surfaces, entrances and obstacles each request
/// selects. The bridge only hands over the voids of opening elements, which
/// have no body of their own. IFC states no door clear width the bridge can
/// trust (a door's overall width includes its lining), so none is declared:
/// a door bounds route widths from above only.
fn walkability_service(
    geometry: &AxiolidGeometry,
    source: &SourceId,
    voids: &[(ObjectId, Void)],
) -> AxiolidWalkabilityService {
    voids.iter().fold(
        AxiolidWalkabilityService::new(geometry.clone(), source.clone()),
        |service, (id, void)| match void {
            Ok((mesh, true)) => service.with_opening_void(id.clone(), mesh.clone()),
            Ok((mesh, false)) => service.with_tessellated_opening_void(id.clone(), mesh.clone()),
            Err(reason) => service.with_unmeasured_opening_void(id.clone(), reason.clone()),
        },
    )
}

/// Metric routes over every `IfcSpace` as a walkable surface, every `IfcDoor`
/// and opening element as a portal, and every stair, ramp (and their flights)
/// and transport element as a vertical connector; all are IFC facts. Every
/// other body obstructs. Windows are not portals: a window filling an opening
/// obstructs it.
fn routing_service(
    geometry: &AxiolidGeometry,
    source: &SourceId,
    kinds: &BTreeMap<ObjectId, String>,
    is_a: &impl Fn(&ObjectId, &str) -> bool,
    voids: &[(ObjectId, Void)],
) -> AxiolidMetricRoutingService {
    let mut service = AxiolidMetricRoutingService::new(geometry.clone(), source.clone());
    for id in kinds.keys() {
        if is_a(id, "IfcSpace") {
            service = service.with_surface(id.clone());
        } else if is_a(id, "IfcDoor") {
            service = service.with_portal(id.clone());
        } else if CONNECTORS.iter().any(|connector| is_a(id, connector)) {
            service = service.with_connector(id.clone());
        }
    }
    for (id, void) in voids {
        service = match void {
            Ok((mesh, true)) => service.with_opening_void(id.clone(), mesh.clone()),
            Ok((mesh, false)) => service.with_tessellated_opening_void(id.clone(), mesh.clone()),
            Err(reason) => service.with_unmeasured_opening_void(id.clone(), reason.clone()),
        };
    }
    service
}

/// Entity types that join levels. Names from both IFC2X3 and IFC4.
const CONNECTORS: &[&str] = &[
    "IfcStair",
    "IfcStairFlight",
    "IfcRamp",
    "IfcRampFlight",
    "IfcTransportElement",
];

/// Facade areas, with every `IfcSpace` as the interior a face may look into.
///
/// Which objects are spaces is an IFC fact. Whether a wall is external is
/// not this bridge's to decide: the rule selects the walls it measures.
fn facade_service(
    geometry: &AxiolidGeometry,
    kinds: &BTreeMap<ObjectId, String>,
    is_a: &impl Fn(&ObjectId, &str) -> bool,
) -> AxiolidFacadeAreaService {
    kinds.keys().filter(|id| is_a(id, "IfcSpace")).fold(
        AxiolidFacadeAreaService::new(geometry.clone()),
        |service, id| service.with_space(id.clone()),
    )
}

/// Space-boundary coverage over every `IfcSpace` and the space boundaries
/// the model declares for it (`IfcRelSpaceBoundary` and its subtypes).
///
/// Which boundaries a space has is an IFC fact, so every declared boundary
/// is registered: with its connection surface meshed in the space body's
/// coordinates, or unmeasured with the reason, so its space is refused
/// rather than measured without it. A boundary stating no connection
/// geometry, one that is not a surface, and any surface the lowering or
/// compiler refuses are unmeasured.
fn boundary_service(
    backend: &impl MeshCompiler,
    parsed: &BTreeMap<SourceId, Parsed>,
    geometry: &AxiolidGeometry,
    kinds: &BTreeMap<ObjectId, String>,
    is_a: &impl Fn(&ObjectId, &str) -> bool,
) -> AxiolidBoundaryCoverageService {
    let mut service = AxiolidBoundaryCoverageService::new(geometry.clone());
    for id in kinds.keys().filter(|id| is_a(id, "IfcSpace")) {
        service = service.with_space(id.clone());
    }
    for (source, Parsed { model, units }) in parsed {
        let object = |entity: EntityId| ObjectId {
            source: source.clone(),
            local_id: entity.to_string(),
        };
        for boundary in ifc_spatial::relation::boundary::all(model) {
            let Some(space) = boundary.space.map(object).filter(|id| is_a(id, "IfcSpace")) else {
                continue;
            };
            let element = boundary
                .element
                .map(object)
                .filter(|id| kinds.contains_key(id));
            let id = object(boundary.id);
            service = match boundary_surface(backend, model, units, &boundary, &space) {
                Ok((mesh, true)) => service.with_boundary(space, id, element, mesh),
                Ok((mesh, false)) => service.with_tessellated_boundary(
                    space,
                    id,
                    element,
                    mesh,
                    CHORD_DEVIATION_METRES,
                ),
                Err(reason) => service.with_unmeasured_boundary(space, id, element, reason),
            };
        }
    }
    service
}

/// One boundary's connection surface as a mesh in the coordinates of its
/// space's body, and whether it is exact.
///
/// `ifc-spatial` reads the boundary's `ConnectionGeometry` and `ifc-geometry`
/// lowers its `SurfaceOnRelatingElement`: a surface, a face surface or a
/// face-based surface model; point, curve and volume connections are refused.
/// The surface is stated in the relating space's object coordinates, so it
/// is lowered in the frame `ifc-geometry` places the space's body in: the
/// body context's world coordinate system above the space's placement
/// (`product_representation_frame`, openbimrs/ifc#164). A curve-bounded
/// plane takes that frame on its basis plane only, its boundaries staying
/// in the plane's parameters (openbimrs/ifc#163).
fn boundary_surface(
    backend: &impl MeshCompiler,
    model: &Model,
    units: &ifc_geometry::units::UnitScale,
    boundary: &SpaceBoundary,
    space: &ObjectId,
) -> Result<(axiolid_mesh::TriMesh, bool), String> {
    let connection = match boundary.connection_geometry(model) {
        Ok(Some(connection)) => connection,
        Ok(None) => return Err("the boundary states no connection geometry".into()),
        Err(ConnectionGeometryAnomaly::Dangling { target, .. }) => {
            return Err(format!("the connection geometry {target} does not exist"));
        }
        Err(ConnectionGeometryAnomaly::WrongKind {
            target, type_name, ..
        }) => {
            return Err(format!(
                "{target} is a {type_name}, not a connection geometry"
            ));
        }
        Err(anomaly) => return Err(format!("unreadable connection geometry: {anomaly:?}")),
    };
    let frame = space_frame(model, units, space)?;
    let mut session = LoweringSession::new(model, units);
    let root = lower_connection_surface(&mut session, connection, frame)
        .map_err(|error| error.to_string())?;
    let lowered = session.finish(root).map_err(|error| error.to_string())?;
    let exact = planar(&lowered.graph, lowered.root, &mut NODE_BUDGET.clone());
    let mesh = backend
        .compile_mesh(
            &lowered.graph,
            lowered.root,
            &ExecutionOptions::new(TOLERANCE),
        )
        .map_err(|error| format!("mesh compilation refused: {error}"))?;
    if mesh.triangle_count() == 0 {
        return Err("mesh compilation produced no triangles".into());
    }
    Ok((mesh, exact))
}

/// The frame a space's body is placed in, as lowering places it: the world
/// coordinate system of its body representation's context above its
/// placement. A space with no body representation has only its placement;
/// its coverage is refused for want of a body anyway.
fn space_frame(
    model: &Model,
    units: &ifc_geometry::units::UnitScale,
    space: &ObjectId,
) -> Result<Transform, String> {
    let entity = entity_id(space).ok_or("the space is not a STEP instance")?;
    match ifc_geometry::product_representation_frame(
        model,
        units,
        entity,
        RepresentationPurpose::Body,
    ) {
        Ok(Some(frame)) => Ok(frame),
        Ok(None) => ifc_geometry::product_world_transform(model, units, entity)
            .map_err(|error| error.to_string()),
        Err(error) => Err(error.to_string()),
    }
}

fn entity_id(id: &ObjectId) -> Option<EntityId> {
    id.local_id.strip_prefix('#')?.parse().ok().map(EntityId)
}

/// One product's net body (openings subtracted) and whether it is exact.
fn mesh(
    backend: &impl MeshCompiler,
    model: &Model,
    units: &ifc_geometry::units::UnitScale,
    product: EntityId,
) -> Result<Option<(axiolid_mesh::TriMesh, bool)>, String> {
    let mut session = LoweringSession::new(model, units);
    let Some(net) = lower_product_net(&mut session, product).map_err(|e| e.to_string())? else {
        return Ok(None);
    };
    let lowered = session.finish(net.root).map_err(|e| e.to_string())?;
    let exact = planar(&lowered.graph, lowered.root, &mut NODE_BUDGET.clone());
    let mesh = backend
        .compile_mesh(
            &lowered.graph,
            lowered.root,
            &ExecutionOptions::new(TOLERANCE),
        )
        .map_err(|e| format!("mesh compilation refused: {e}"))?;
    if mesh.triangle_count() == 0 {
        return Err("mesh compilation produced no triangles".into());
    }
    Ok(Some((mesh, exact)))
}

/// Whether every face under `id` is planar, so its mesh is its exact shape.
///
/// Conservative: only structures known to stay planar count, and anything
/// else, including an exhausted budget, is treated as curved. A planar
/// product mis-called curved only loses exactness; the reverse would present
/// a chord approximation as exact.
fn planar(graph: &GeometryGraph, id: NodeId, budget: &mut usize) -> bool {
    if *budget == 0 {
        return false;
    }
    *budget -= 1;
    let Some(node) = graph.get(id) else {
        return false;
    };
    match node {
        GeometryNode::TriMesh(_)
        | GeometryNode::PolygonMesh(_)
        | GeometryNode::BoundingBox(_)
        | GeometryNode::HalfSpace(_)
        | GeometryNode::Primitive(Primitive::Block { .. }) => true,
        // An affine placement maps planes to planes.
        GeometryNode::Instance(instance) => planar(graph, instance.source, budget),
        GeometryNode::Collection(children) => {
            children.iter().all(|child| planar(graph, *child, budget))
        }
        GeometryNode::SolidOperation(SolidOperation::Extrusion { profile, .. }) => {
            planar(graph, *profile, budget)
        }
        GeometryNode::SolidOperation(SolidOperation::Boolean { left, right, .. }) => {
            planar(graph, *left, budget) && planar(graph, *right, budget)
        }
        GeometryNode::Profile(profile) => polygonal(profile),
        // A plane bounded by straight boundaries (a space boundary's
        // connection surface): its triangles are the region.
        GeometryNode::SurfaceRelation(SurfaceRelation::CurveBounded {
            basis, boundaries, ..
        }) => {
            matches!(
                graph.get(*basis),
                Some(GeometryNode::Surface(Surface::Plane(_)))
            ) && boundaries.iter().all(|boundary| {
                matches!(
                    graph.get(*boundary),
                    Some(
                        GeometryNode::Curve3(Curve3::Line(_) | Curve3::Polyline(_))
                            | GeometryNode::Curve2(Curve2::Line(_) | Curve2::Polyline(_))
                    )
                )
            })
        }
        // A faceted B-rep: every face on a plane (or given only by its
        // polygon, which IFC requires to be planar) and every edge straight.
        GeometryNode::BRep(brep) => {
            brep.faces().iter().all(|face| {
                face.surface.is_none_or(|surface| {
                    matches!(
                        graph.get(surface),
                        Some(GeometryNode::Surface(Surface::Plane(_)))
                    )
                })
            }) && brep.edges().iter().all(|edge| {
                edge.curve.is_none_or(|curve| {
                    matches!(
                        graph.get(curve),
                        Some(GeometryNode::Curve3(Curve3::Line(_) | Curve3::Polyline(_)))
                    )
                })
            })
        }
        _ => false,
    }
}

fn polygonal(profile: &Profile) -> bool {
    let straight = |curve: &Curve2| matches!(curve, Curve2::Line(_) | Curve2::Polyline(_));
    let sharp = |radius: Option<f64>| radius.is_none_or(|r| r == 0.0);
    match profile {
        Profile::Rectangle(rectangle) => {
            sharp(rectangle.outer_radius) && sharp(rectangle.inner_radius)
        }
        // A section meshes from its exact contour (axiolid-mesh-compile
        // 0.3.5): straight edges, sloped ones included, are exact and only
        // its fillets and rounded edges are chorded.
        Profile::Section(section) => match section {
            SectionProfile::I {
                fillet_radius,
                flange_edge_radius,
                ..
            } => sharp(*fillet_radius) && sharp(*flange_edge_radius),
            SectionProfile::AsymmetricI {
                bottom_fillet_radius,
                bottom_flange_edge_radius,
                top_fillet_radius,
                top_flange_edge_radius,
                ..
            } => [
                bottom_fillet_radius,
                bottom_flange_edge_radius,
                top_fillet_radius,
                top_flange_edge_radius,
            ]
            .into_iter()
            .all(|radius| sharp(*radius)),
            SectionProfile::L {
                fillet_radius,
                edge_radius,
                ..
            }
            | SectionProfile::U {
                fillet_radius,
                edge_radius,
                ..
            }
            | SectionProfile::Z {
                fillet_radius,
                edge_radius,
                ..
            } => sharp(*fillet_radius) && sharp(*edge_radius),
            SectionProfile::T {
                fillet_radius,
                flange_edge_radius,
                web_edge_radius,
                ..
            } => sharp(*fillet_radius) && sharp(*flange_edge_radius) && sharp(*web_edge_radius),
            SectionProfile::C {
                internal_fillet_radius,
                ..
            } => sharp(*internal_fillet_radius),
            SectionProfile::Trapezium { .. } => true,
            _ => false,
        },
        Profile::Contour(contour) => std::iter::once(&contour.outer)
            .chain(&contour.holes)
            .flat_map(|ring| &ring.segments)
            .all(|segment| straight(&segment.curve)),
        Profile::Derived { basis, .. } => polygonal(basis),
        Profile::Composite(parts) => parts.iter().all(polygonal),
        _ => false,
    }
}

/// Space validation needs roles and storeys, which are IFC facts.
///
/// Storeys come from each source's own spatial tree, so an object's storey
/// is always one of its own model's. An element the file places twice, or
/// anything under a structure aggregated twice, gets no storey: the tree
/// keeps one of the two parents, and a guessed storey would move floor area
/// between storeys without saying so.
fn space_service(
    parsed: &BTreeMap<SourceId, Parsed>,
    geometry: &AxiolidGeometry,
    source: &SourceId,
    kinds: &BTreeMap<ObjectId, String>,
    is_a: &impl Fn(&ObjectId, &str) -> bool,
) -> AxiolidSpaceService {
    let trees: BTreeMap<&SourceId, (SpatialTree, BTreeSet<EntityId>)> = parsed
        .iter()
        .map(|(source, Parsed { model, .. })| {
            let tree = SpatialTree::build(model);
            let ambiguous: BTreeSet<EntityId> = tree
                .anomalies()
                .iter()
                .filter_map(|anomaly| match anomaly {
                    SpatialAnomaly::ContainedTwice { element, .. } => Some(*element),
                    SpatialAnomaly::AggregatedTwice { child, .. } => Some(*child),
                    _ => None,
                })
                .collect();
            (source, (tree, ambiguous))
        })
        .collect();
    let storey_of = |tree: &SpatialTree,
                     ambiguous: &BTreeSet<EntityId>,
                     entity: EntityId|
     -> Option<EntityId> {
        let mut chain = vec![entity];
        chain.extend(tree.container_of(entity));
        let start = *chain.last()?;
        chain.extend(tree.ancestors(start));
        if chain.iter().any(|link| ambiguous.contains(link)) {
            return None;
        }
        chain.into_iter().skip(1).find(|link| {
            tree.node(*link)
                .is_some_and(|node| node.kind == SpatialKind::Storey)
        })
    };

    let mut service = AxiolidSpaceService::new(geometry.clone(), source.clone());
    for id in kinds.keys() {
        let (Some(entity), Some((tree, ambiguous))) = (entity_id(id), trees.get(&id.source)) else {
            continue;
        };
        if is_a(id, "IfcSpace") {
            service = service.with_space(id.clone());
        } else if is_a(id, "IfcSlab") {
            service = service.with_slab(id.clone());
        } else if is_a(id, "IfcRoof") {
            service = service.with_roof(id.clone());
        } else if is_a(id, "IfcBuilding") {
            service = service.with_building(id.clone());
        }
        let is_structure = tree.node(entity).is_some();
        if (!is_structure || is_a(id, "IfcSpace"))
            && !geometry.has_no_body(id)
            && let Some(storey) = storey_of(tree, ambiguous, entity)
        {
            let storey = ObjectId {
                source: id.source.clone(),
                local_id: storey.to_string(),
            };
            service = service.with_storey(id.clone(), storey);
        }
    }
    service
}

/// The measured extent of every object `report` names, for fitting BCF
/// cameras: each session's proximity service answers for its own objects.
///
/// An object no session measured is left out, so its viewpoint gets no
/// camera rather than a guessed one. The extent is the box that encloses the
/// true body (the mesh box grown by its chord deviation).
pub fn bounds(sessions: &[&EvidenceSession], report: &Report) -> BTreeMap<ObjectId, bcf::Bounds> {
    let mut named: BTreeSet<&ObjectId> = BTreeSet::new();
    for finding in report.findings() {
        named.extend(finding.object_id());
        named.extend(&finding.related);
    }
    for outcome in report.not_evaluated() {
        named.extend(outcome.object_id());
    }
    let mut bounds = BTreeMap::new();
    for object in named {
        let measured = sessions
            .iter()
            .filter(|session| session.project().object(object).is_some())
            .filter_map(|session| session.service::<ProximityServiceHandle>())
            .find_map(|service| service.bounds(object).ok())
            .map(|measured| measured.enclosing())
            .and_then(|extent| bcf::Bounds::new(extent.min(), extent.max()));
        if let Some(measured) = measured {
            bounds.insert(object.clone(), measured);
        }
    }
    bounds
}

#[cfg(test)]
mod tests {
    use super::attach;
    use axioval::engine::{
        MetricPoint, MetricRouteOutcome, MetricRouteRequest, MetricRoutingServiceHandle,
        MobilityProfile, WalkabilityRequest, WalkabilityRouteOutcome, WalkabilityServiceHandle,
    };
    use axioval::ifc::import_ifc_session;
    use axioval::ir::ObjectId;

    /// Rooms `#16` (x 0..4) and `#26` (x 4.2..8.2) with a 0.9 m door body
    /// `#40` in the gap between them, and nothing else.
    fn rooms_and_door() -> String {
        let body = |first: u32, x: f64, y: f64, dx: f64, dy: f64, depth: f64| {
            let [point, position, profile, solid, shape] = [0, 1, 2, 3, 4].map(|o| first + o);
            format!(
                "#{point}=IFCCARTESIANPOINT(({x},{y}));\n\
                 #{position}=IFCAXIS2PLACEMENT2D(#{point},$);\n\
                 #{profile}=IFCRECTANGLEPROFILEDEF(.AREA.,$,#{position},{dx},{dy});\n\
                 #{solid}=IFCEXTRUDEDAREASOLID(#{profile},#2,#4,{depth});\n\
                 #{shape}=IFCSHAPEREPRESENTATION(#5,'Body','SweptSolid',(#{solid}));\n\
                 #{}=IFCPRODUCTDEFINITIONSHAPE($,$,(#{shape}));\n",
                first + 5
            )
        };
        format!(
            "ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION((''),'2;1');\nFILE_NAME('n','t',(''),(''),'p','o','a');\nFILE_SCHEMA(('IFC4'));\nENDSEC;\nDATA;\n\
             #1=IFCCARTESIANPOINT((0.,0.,0.));\n\
             #2=IFCAXIS2PLACEMENT3D(#1,$,$);\n\
             #3=IFCLOCALPLACEMENT($,#2);\n\
             #4=IFCDIRECTION((0.,0.,1.));\n\
             #5=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#2,$);\n\
             {}#16=IFCSPACE('0000000000000000000016',$,$,$,$,#3,#15,$,.ELEMENT.,$,$);\n\
             {}#26=IFCSPACE('0000000000000000000026',$,$,$,$,#3,#25,$,.ELEMENT.,$,$);\n\
             {}#40=IFCDOOR('0000000000000000000040',$,$,$,$,#3,#35,$,2.1,0.9,$,$,$);\n\
             ENDSEC;\nEND-ISO-10303-21;\n",
            body(10, 2.0, 2.0, 4.0, 4.0, 3.0),
            body(20, 6.2, 2.0, 4.0, 4.0, 3.0),
            body(30, 4.1, 2.0, 0.1, 0.9, 2.1),
        )
    }

    #[test]
    fn geometry_registers_walkability_and_metric_routing() {
        let bytes = rooms_and_door();
        let session = import_ifc_session("rooms.ifc", bytes.as_bytes()).unwrap();
        let models: super::ModelBytes = session
            .snapshots()
            .map(|snapshot| (snapshot.source().clone(), bytes.as_bytes().to_vec()))
            .collect();
        let (session, report) = attach(session, &models).unwrap();
        assert_eq!(report.exact, 3, "{report:?}");
        let id = |local: &str| ObjectId {
            source: session.snapshots().next().unwrap().source().clone(),
            local_id: local.to_owned(),
        };

        let walkability = session.service::<WalkabilityServiceHandle>().unwrap();
        let request = |width: f64| {
            WalkabilityRequest::try_new(
                vec![id("#16"), id("#26")],
                vec![id("#40")],
                Vec::new(),
                width,
                None,
                true,
                false,
            )
            .unwrap()
        };
        // IFC states no clear width the bridge trusts, so a door that could
        // pass stays undecided, and one too narrow blocks.
        let wide_enough = walkability.snapshot(&request(0.8)).unwrap();
        assert_eq!(
            wide_enough.route_between(&id("#16"), &id("#26")).unwrap(),
            WalkabilityRouteOutcome::Indeterminate
        );
        let too_narrow = walkability.snapshot(&request(1.0)).unwrap();
        assert_eq!(
            too_narrow.route_between(&id("#16"), &id("#26")).unwrap(),
            WalkabilityRouteOutcome::Unreachable
        );

        let routing = session.service::<MetricRoutingServiceHandle>().unwrap();
        let route = MetricRouteRequest::new(
            MetricPoint::try_new(id("#16"), [1.0, 2.0, 0.0]).unwrap(),
            MetricPoint::try_new(id("#26"), [7.0, 2.0, 0.0]).unwrap(),
            MobilityProfile::try_new(0.5, 2.0, 0.02, 0.06).unwrap(),
        );
        assert!(matches!(
            routing.route(&route).unwrap(),
            MetricRouteOutcome::Blocked(_)
        ));
    }

    /// A section without fillets or rounded edges meshes to its exact
    /// contour, so its mesh is exact; any radius makes it a tessellation.
    #[test]
    fn only_sharp_sections_are_polygonal() {
        use super::polygonal;
        use axiolid_profile::{Profile, SectionProfile};

        let i = |fillet_radius| {
            Profile::Section(SectionProfile::I {
                depth: 0.3,
                width: 0.3,
                web_thickness: 0.011,
                flange_thickness: 0.019,
                fillet_radius,
                flange_edge_radius: None,
                flange_slope: Some(0.1),
            })
        };
        assert!(polygonal(&i(None)));
        assert!(polygonal(&i(Some(0.0))));
        assert!(!polygonal(&i(Some(0.027))));
        let c = |internal_fillet_radius| {
            Profile::Section(SectionProfile::C {
                depth: 0.2,
                width: 0.1,
                wall_thickness: 0.004,
                girth: 0.02,
                internal_fillet_radius,
            })
        };
        assert!(polygonal(&c(None)));
        assert!(!polygonal(&c(Some(0.004))));
        assert!(polygonal(&Profile::Section(SectionProfile::Trapezium {
            bottom_x: 0.4,
            top_x: 0.2,
            y: 0.3,
            top_offset: -0.05,
        })));
    }
}