rvt 0.4.0

Apache-2.0 clean-room reader for Autodesk Revit files (.rvt, .rfa, .rte, .rft) without Revit: metadata, previews and the embedded schema of 2016-2026 files, and typed elements with measured geometry from Revit 2024 and 2025 projects, exported as IFC4, glTF and plan SVG.
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
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
//! Wall bodies: the record box is the *untrimmed* wall, the joins cut it.
//!
//! A Revit 2024 `OST_Walls` partition element record carries the
//! wall's model bounding box (`partition_element_records`). Measured
//! against Revit's own IFC export of `2024_Core_Interior.rvt`, that
//! box is **not** the wall's exported body: it is the wall's location
//! line taken to its raw endpoints, inflated by half the wall's
//! thickness across the run. Revit's exported body is the same prism
//! after the joins have cut it back.
//!
//! Two facts make the difference recoverable from the records alone
//! (#215/#227 background; RE-26 has the tables):
//!
//! 1. **The box's thin plan extent is the wall's thickness.** On the
//!    recorded edge the thin extent equals the nominal thickness of
//!    the `IfcWallType` Revit's export assigns on **360 of 360**
//!    walls, once the newest frame of each element is the one read
//!    (`partition_schema_mvp::select_instance_records`).
//! 2. **The trim at an end is half the thickness of the wall whose
//!    centreline lands on that end.** Every non-zero end delta
//!    between the record box and Revit's `Axis` polyline on the
//!    recorded edge is exactly one of `0.25`, `0.3333`, `0.75` ft —
//!    half of the 6", 8" and 18" wall thicknesses on the file — and
//!    zero everywhere else.
//!
//! 3. **The record names the walls it joins.** The counted reference
//!    list at `+0x88` holds, besides the type and the two Levels, the
//!    ElementIds of the other walls this wall is joined to. Requiring
//!    a candidate to be named there removes 14 over-trims on the
//!    recorded edge and costs nothing: 16 of the 360 walls name no
//!    other wall at all, and every one of them is a wall Revit leaves
//!    untrimmed (#238, RE-29 §2).
//!
//! 4. **A candidate only cuts where its own cut-back run reaches.**
//!    A wall whose end has itself been cut back no longer covers the
//!    centreline of a wall beyond that cut, and Revit does not trim
//!    there. The candidate's run is therefore reduced by its own
//!    trims before the span test — ignoring the trims imposed by
//!    walls on the line being resolved, which are the joins this very
//!    end makes and cannot pre-empt itself (RE-29 §3).
//!
//! [`join_trims`] applies (2)–(4) to the wall set recovered from the
//! records. It is a solver over recorded boxes, not a fit: a
//! candidate must be perpendicular, must be named in this record's
//! reference list, must have its centreline exactly on the end being
//! resolved, must span this wall's centreline along its own reduced
//! run, and must overlap it in elevation. When the candidates at one
//! end disagree about their thickness the **whole element** is
//! declined and keeps its record box.
//!
//! # Honesty
//!
//! - The *which walls join* half is read from the file; the *where
//!   the join cuts* half is still modelled. Revit's per-pair
//!   butt/mitre choice is not in the record — the trimmed endpoints
//!   were searched as `f64` over 4 KiB past every wall record on the
//!   recorded edge and no fixed carrier holds them.
//! - Measured end to end on `2024_Core_Interior.rvt`, world
//!   axis-aligned bounding box against Revit's own export: the
//!   trimmed box is exact on **351 of 360** walls, up from 336 for
//!   the geometry-only solver and 39 for the untrimmed box; worst
//!   corner residual 0.3333 ft, mean 0.0220 → 0.0081 ft. Per end,
//!   689 → **711 of 720** correct, with no end that the geometry-only
//!   solver had right made wrong.
//! - The 9 residual ends are one side of a **true L corner** — two
//!   walls whose runs both stop at the other's centreline, with
//!   nothing continuing past the corner. Revit cuts exactly one of
//!   the pair and the file offers no feature that says which: across
//!   the two distinct corners on the recorded edge the survivor is
//!   the thicker wall once and the thinner wall once, the lower
//!   ElementId once and the higher once. They are recorded, not
//!   papered over (#238, RE-29 §4).
//! - Only axis-parallel walls are resolved. Every wall on the
//!   recorded edge is axis-parallel; a wall whose box is square in
//!   plan has no identifiable thin axis and is declined.

use crate::partition_element_records::PartitionElementRecord;
use std::collections::{BTreeMap, BTreeSet};

/// Field carrying which body a recovered wall is emitting.
pub const WALL_BODY_SOURCE_FIELD: &str = "m_wall_body_source";
/// Value of [`WALL_BODY_SOURCE_FIELD`] when the joins were resolved.
pub const WALL_BODY_JOIN_TRIMMED: &str = "partition_element_record_join_trimmed";
/// Field carrying the wall thickness read off the box's thin axis.
pub const WALL_THICKNESS_FIELD: &str = "m_wall_thickness";
/// Field carrying the trim applied at the low end of the wall run.
pub const WALL_TRIM_START_FIELD: &str = "m_wall_trim_start";
/// Field carrying the trim applied at the high end of the wall run.
pub const WALL_TRIM_END_FIELD: &str = "m_wall_trim_end";
/// Value of the thickness-source property for the thin-axis read.
pub const WALL_THICKNESS_SOURCE: &str = "partition_element_record_bbox_thin_axis";

/// Plan tolerance for "this centreline lands on that end", in feet.
///
/// Revit writes these coordinates as exact doubles and the record
/// carries the same bits, so the tolerance only absorbs the last
/// bits of a subtraction.
pub const JOIN_EPS_FEET: f64 = 1e-6;

/// One wall reduced to the run / thickness / elevation the solver needs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct WallRun {
    /// The wall's own ElementId.
    pub element_id: u32,
    /// Plan axis the wall runs along: `0` = x, `1` = y.
    pub axis: usize,
    /// Thickness in feet — the box's extent across the run.
    pub thickness_feet: f64,
    /// Centreline coordinate across the run, in feet.
    pub centre_feet: f64,
    /// Low end of the untrimmed run, in feet.
    pub start_feet: f64,
    /// High end of the untrimmed run, in feet.
    pub end_feet: f64,
    /// Base of the box, in feet.
    pub base_feet: f64,
    /// Top of the box, in feet.
    pub top_feet: f64,
}

/// The trims a wall's two ends take, in feet.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct WallJoinTrim {
    /// Plan axis the wall runs along: `0` = x, `1` = y.
    pub axis: usize,
    /// Thickness in feet.
    pub thickness_feet: f64,
    /// Trim at the low end.
    pub start_feet: f64,
    /// Trim at the high end.
    pub end_feet: f64,
}

impl WallJoinTrim {
    /// True when either end was actually cut back.
    pub fn is_trimmed(&self) -> bool {
        self.start_feet > 0.0 || self.end_feet > 0.0
    }
}

/// Reduce a record to a [`WallRun`], or `None` when its plan box has
/// no identifiable long axis.
pub fn wall_run(record: &PartitionElementRecord) -> Option<WallRun> {
    let (dx, dy, _) = record.extents_feet();
    if !dx.is_finite() || !dy.is_finite() {
        return None;
    }
    if (dx - dy).abs() <= JOIN_EPS_FEET {
        return None;
    }
    let axis = usize::from(dy > dx);
    let across = 1 - axis;
    let thickness_feet = if axis == 0 { dy } else { dx };
    if thickness_feet <= 0.0 {
        return None;
    }
    Some(WallRun {
        element_id: record.element_id,
        axis,
        thickness_feet,
        centre_feet: (record.bbox_feet[across] + record.bbox_feet[across + 3]) * 0.5,
        start_feet: record.bbox_feet[axis],
        end_feet: record.bbox_feet[axis + 3],
        base_feet: record.bbox_feet[2],
        top_feet: record.bbox_feet[5],
    })
}

/// The other recovered walls a record names in its counted reference
/// list at `+0x88` (#238, RE-29 §2).
///
/// `wall_ids` is the ElementId set of the recovered wall instances,
/// so a slot that names a type, a Level, a column or an id this
/// decoder has not recovered is dropped rather than guessed at. The
/// record's own id is never a join partner and is excluded.
pub fn joined_walls(record: &PartitionElementRecord, wall_ids: &BTreeSet<u32>) -> BTreeSet<u32> {
    record
        .references
        .iter()
        .filter(|slot| **slot <= u64::from(u32::MAX))
        .map(|slot| *slot as u32)
        .filter(|id| *id != record.element_id && wall_ids.contains(id))
        .collect()
}

/// The wall set plus the join partners each record names, which is
/// everything the solver reads.
struct Solver<'a> {
    runs: &'a [WallRun],
    joined: &'a BTreeMap<u32, BTreeSet<u32>>,
}

impl<'a> Solver<'a> {
    fn names(&self, wall: &WallRun, other: &WallRun) -> bool {
        self.joined
            .get(&wall.element_id)
            .is_some_and(|set| set.contains(&other.element_id))
    }

    /// Every wall that is perpendicular to `wall`, named by it, whose
    /// centreline lands on `coord`, whose own run spans `wall`'s
    /// centreline and whose elevation range overlaps it.
    ///
    /// `skip_centre` drops candidates sitting on that plan line; it is
    /// how a candidate's own reduction ignores the joins it makes with
    /// the line currently being resolved.
    fn candidates(&self, wall: &WallRun, coord: f64, skip_centre: Option<f64>) -> Vec<&'a WallRun> {
        self.runs
            .iter()
            .filter(|other| other.element_id != wall.element_id && other.axis != wall.axis)
            .filter(|other| (other.centre_feet - coord).abs() <= JOIN_EPS_FEET)
            .filter(|other| self.names(wall, other))
            .filter(|other| {
                skip_centre.is_none_or(|line| (other.centre_feet - line).abs() > JOIN_EPS_FEET)
            })
            .filter(|other| {
                wall.centre_feet >= other.start_feet - JOIN_EPS_FEET
                    && wall.centre_feet <= other.end_feet + JOIN_EPS_FEET
            })
            .filter(|other| {
                wall.top_feet.min(other.top_feet) - wall.base_feet.max(other.base_feet)
                    > JOIN_EPS_FEET
            })
            .collect()
    }

    /// Half the one thickness the candidates agree on, `Some(0.0)`
    /// when there are none, `None` when they disagree.
    fn half_thickness(candidates: &[&WallRun]) -> Option<f64> {
        let mut thickness: Option<f64> = None;
        for other in candidates {
            match thickness {
                None => thickness = Some(other.thickness_feet),
                Some(held) if (held - other.thickness_feet).abs() <= JOIN_EPS_FEET => {}
                Some(_) => return None,
            }
        }
        Some(thickness.map_or(0.0, |value| value * 0.5))
    }

    /// `candidate`'s own run, cut back by the joins it makes with
    /// walls that are **not** on `line` — the plan line whose trim is
    /// being resolved. Disagreeing candidates reduce nothing, which
    /// keeps the run at its recorded length rather than inventing one.
    fn reduced_run(&self, candidate: &WallRun, line: f64) -> (f64, f64) {
        let start =
            Self::half_thickness(&self.candidates(candidate, candidate.start_feet, Some(line)))
                .unwrap_or(0.0);
        let end = Self::half_thickness(&self.candidates(candidate, candidate.end_feet, Some(line)))
            .unwrap_or(0.0);
        (candidate.start_feet + start, candidate.end_feet - end)
    }

    /// The trim `wall` takes at `coord`, or `None` when the candidates
    /// there disagree about their thickness.
    fn trim_at(&self, wall: &WallRun, coord: f64) -> Option<f64> {
        let reaching: Vec<&WallRun> = self
            .candidates(wall, coord, None)
            .into_iter()
            .filter(|candidate| {
                let (start, end) = self.reduced_run(candidate, wall.centre_feet);
                wall.centre_feet >= start - JOIN_EPS_FEET && wall.centre_feet <= end + JOIN_EPS_FEET
            })
            .collect();
        Self::half_thickness(&reaching)
    }
}

/// The join trim of every wall in `records`, keyed by ElementId.
///
/// Walls that decline — no long axis, disagreeing candidates, or a
/// trim that would collapse the run — are simply absent from the map
/// and keep their record box.
pub fn join_trims(records: &[PartitionElementRecord]) -> BTreeMap<u32, WallJoinTrim> {
    let wall_ids: BTreeSet<u32> = records.iter().map(|record| record.element_id).collect();
    let joined: BTreeMap<u32, BTreeSet<u32>> = records
        .iter()
        .map(|record| (record.element_id, joined_walls(record, &wall_ids)))
        .collect();
    let runs: Vec<WallRun> = records.iter().filter_map(wall_run).collect();
    let solver = Solver {
        runs: &runs,
        joined: &joined,
    };
    let mut out = BTreeMap::new();
    for wall in &runs {
        let (Some(start), Some(end)) = (
            solver.trim_at(wall, wall.start_feet),
            solver.trim_at(wall, wall.end_feet),
        ) else {
            continue;
        };
        if wall.end_feet - end - (wall.start_feet + start) <= JOIN_EPS_FEET {
            continue;
        }
        out.insert(
            wall.element_id,
            WallJoinTrim {
                axis: wall.axis,
                thickness_feet: wall.thickness_feet,
                start_feet: start,
                end_feet: end,
            },
        );
    }
    out
}

/// How far off perpendicular two centrelines may be for their butt join to
/// be read, as the cosine of the angle between them. Revit writes the
/// joined ends as the same doubles; every such pair on Snowdon Towers is
/// within `1e-12`.
pub const PERPENDICULAR_EPS: f64 = 1e-6;

/// The largest `|cos|` of the angle between two walls at which an angled
/// join is read: 45 to 135 degrees. On Snowdon Towers Revit butt-joins walls
/// whose corner is 82.5 to 114.5 degrees, and none of the 14 ends at sharper
/// corners (7.5 and 24.5 degrees) or shallower bends (148 to 172.5 degrees).
pub const ANGLED_JOIN_MAX_COSINE: f64 = std::f64::consts::FRAC_1_SQRT_2;

/// A wall's centreline, its type's thickness and layers, its exterior side
/// and its elevation range, which is what [`butt_joins`] reads.
#[derive(Debug, Clone, PartialEq)]
pub struct WallLine {
    /// The wall's own ElementId.
    pub element_id: u32,
    /// Plan start of the centreline, feet.
    pub start: [f64; 2],
    /// Plan end of the centreline, feet.
    pub end: [f64; 2],
    /// The type's layers summed, feet.
    pub thickness_feet: f64,
    /// The type's layers of non-zero width, exterior first, each its width
    /// in feet and its function (1 structure, 2 substrate, 3 thermal or
    /// air, 4 finish 1, 5 finish 2).
    pub layers: Vec<(f64, u32)>,
    /// Plan unit vector towards the wall's exterior face.
    pub exterior: [f64; 2],
    /// Base of the wall's record box, feet.
    pub base_feet: f64,
    /// Top of the wall's record box, feet.
    pub top_feet: f64,
}

/// How one end of a wall meets another wall: a butt join its join lists
/// decide (RE-70), or a T joint (RE-73).
#[derive(Debug, Clone, PartialEq)]
pub struct ButtJoin {
    /// The one other wall whose centreline ends there too, or, at a T
    /// joint, whose centreline the end lies on.
    pub partner: u32,
    /// True where this wall runs on to the partner's far face, false where
    /// it stops at its near face.
    pub runs_through: bool,
    /// How far past the line's end the body reaches, negative where it
    /// stops short: half the partner's thickness. `None` unless both walls
    /// have a single layer, or, at a T joint, this one has.
    pub reach_feet: Option<f64>,
    /// How far past the line's end each layer reaches, exterior first,
    /// where both walls are layered alike (RE-71) or where this wall is
    /// layered and stops at a T joint (RE-73). `None` otherwise.
    pub layer_reach_feet: Option<Vec<f64>>,
    /// Where the two walls meet at an angle, how far past the line's end
    /// each layer reaches along its exterior-side and its interior-side
    /// edge, exterior first: its end is a slanted line (RE-74). A
    /// single-layer wall has one pair, its two faces. `None` otherwise.
    pub layer_edge_reach_feet: Option<Vec<[f64; 2]>>,
}

/// The butt join at each end of each wall, keyed by ElementId,
/// `[start, end]` (RE-70).
///
/// An end is read when exactly one other wall overlapping it in elevation
/// ends its centreline there too, perpendicular to it. Revit runs one of
/// the two on to the other's far face and stops the other at its near
/// face, and the wall that runs through is the one that names the other
/// in its join lists (`partners`,
/// [`crate::partition_compound_structure::scan_wall_join_partners`]) and
/// is not named back. A pair that name each other or neither, a joint of
/// three walls and an angled joint stay `None`.
///
/// Where either wall has several layers the end is still read, but it has
/// no `reach_feet`. Revit cleans such a join layer by layer and its
/// finishes wrap the corner, so the body's end is no longer one face: on
/// Snowdon Towers 631 of 667 such ends, against none of the 158 where both
/// walls have one layer.
///
/// The layers then nest like concentric Ls ([`layer_reaches`], RE-71):
/// counting both walls' layers from the outside of the corner, layer `i` of
/// the wall that runs through reaches the outer edge of the partner's layer
/// `i`, and layer `i` of the wall that stops, its inner edge. That holds
/// where both walls show the same layer functions in the same order from
/// the corner and share their base and top, and those ends get
/// `layer_reach_feet`.
///
/// An end no other wall's centreline ends at is read as a T joint where it
/// lies part way along another wall's centreline ([`tee_join`], RE-73).
///
/// Two walls that meet at 45 to 135 degrees, rather than at a right angle,
/// are read the same way, and their ends slant along the other
/// wall's lines ([`angled_layer_edges`], [`angled_tee_edges`], RE-74).
pub fn butt_joins(
    walls: &[WallLine],
    partners: &BTreeMap<u32, BTreeSet<u32>>,
) -> BTreeMap<u32, [Option<ButtJoin>; 2]> {
    let length = |wall: &WallLine| (wall.end[0] - wall.start[0]).hypot(wall.end[1] - wall.start[1]);
    let lines: Vec<&WallLine> = walls
        .iter()
        .filter(|wall| length(wall).is_finite() && length(wall) > 1e-9)
        .collect();
    let mut ends: Vec<([f64; 2], usize)> = lines
        .iter()
        .enumerate()
        .flat_map(|(index, wall)| [(wall.start, index), (wall.end, index)])
        .collect();
    ends.sort_by(|a, b| a.0[0].total_cmp(&b.0[0]));
    let names = |from: &WallLine, to: &WallLine| {
        partners
            .get(&from.element_id)
            .is_some_and(|named| named.contains(&to.element_id))
    };
    let mut out = BTreeMap::new();
    for (index, wall) in lines.iter().enumerate() {
        let run = length(wall);
        let along = [
            (wall.end[0] - wall.start[0]) / run,
            (wall.end[1] - wall.start[1]) / run,
        ];
        let mut joins = [None, None];
        for (slot, point) in [wall.start, wall.end].into_iter().enumerate() {
            let from = ends.partition_point(|(p, _)| p[0] < point[0] - JOIN_EPS_FEET);
            let mates: BTreeSet<usize> = ends[from..]
                .iter()
                .take_while(|(p, _)| p[0] <= point[0] + JOIN_EPS_FEET)
                .filter(|(p, other)| *other != index && (p[1] - point[1]).abs() <= JOIN_EPS_FEET)
                .map(|(_, other)| *other)
                .filter(|other| {
                    let other = lines[*other];
                    wall.top_feet.min(other.top_feet) - wall.base_feet.max(other.base_feet)
                        > JOIN_EPS_FEET
                })
                .collect();
            let into = if slot == 0 {
                along
            } else {
                [-along[0], -along[1]]
            };
            if mates.is_empty() {
                joins[slot] = tee_join(wall, &lines, point, into);
                continue;
            }
            let [mate] = mates.into_iter().collect::<Vec<_>>()[..] else {
                continue;
            };
            let other = lines[mate];
            let other_run = length(other);
            let cosine = (along[0] * (other.end[0] - other.start[0])
                + along[1] * (other.end[1] - other.start[1]))
                / other_run;
            if cosine.abs() > PERPENDICULAR_EPS && cosine.abs() > ANGLED_JOIN_MAX_COSINE {
                continue;
            }
            let runs_through = match (names(wall, other), names(other, wall)) {
                (true, false) => true,
                (false, true) => false,
                _ => continue,
            };
            if cosine.abs() > PERPENDICULAR_EPS {
                joins[slot] = Some(ButtJoin {
                    partner: other.element_id,
                    runs_through,
                    reach_feet: None,
                    layer_reach_feet: None,
                    layer_edge_reach_feet: angled_layer_edges(
                        wall,
                        other,
                        point,
                        into,
                        runs_through,
                    ),
                });
                continue;
            }
            let half = other.thickness_feet * 0.5;
            let single = wall.layers.len() == 1 && other.layers.len() == 1;
            joins[slot] = Some(ButtJoin {
                partner: other.element_id,
                runs_through,
                reach_feet: single.then_some(if runs_through { half } else { -half }),
                layer_reach_feet: layer_reaches(wall, other, point, into, runs_through),
                layer_edge_reach_feet: None,
            });
        }
        if joins.iter().any(Option::is_some) {
            out.insert(wall.element_id, joins);
        }
    }
    out
}

/// The T joint `wall` makes where its centreline ends at `point`, part way
/// along one other wall's centreline (RE-73). `into` points from `point`
/// along `wall`.
///
/// The other wall runs through, and `wall` stops against it layer by layer,
/// by Revit's layer priorities (1 structure, 2 substrate, 3 thermal or air,
/// 4 finish 1, 5 finish 2): each of `wall`'s layers runs on into the other
/// wall through its layers of lower priority, counted from the face `wall`
/// meets, and stops at the first of equal or higher priority. So a core
/// passes the other wall's finishes and stops at its core, and a finish
/// stops at its face. A single-layer wall stops at the other wall's face.
/// On Snowdon Towers that is every layer's end on 280 of the 313 T joints
/// measured against Revit's IFC4 bodies; 16 of the rest Revit draws as a
/// clean stop at the face, as it does at all three on RE1 (Revit 2025).
///
/// `None` unless exactly one other wall overlapping it in elevation has
/// `point` on its centreline, at 45 to 135 degrees to `wall` (a slanted
/// end below a right angle, [`angled_tee_edges`]), far enough from its ends
/// that all of `wall`'s width meets its side. Where the other wall ends
/// within that width, Revit stops `wall` at the other wall's face or does
/// not join the two at all (Core Interior's 8), so it is left alone.
pub fn tee_join(
    wall: &WallLine,
    lines: &[&WallLine],
    point: [f64; 2],
    into: [f64; 2],
) -> Option<ButtJoin> {
    let dot = |a: [f64; 2], b: [f64; 2]| a[0] * b[0] + a[1] * b[1];
    let hosts: Vec<&WallLine> = lines
        .iter()
        .copied()
        .filter(|other| other.element_id != wall.element_id)
        .filter(|other| {
            wall.top_feet.min(other.top_feet) - wall.base_feet.max(other.base_feet) > JOIN_EPS_FEET
        })
        .filter(|other| {
            let run = (other.end[0] - other.start[0]).hypot(other.end[1] - other.start[1]);
            let axis = [
                (other.end[0] - other.start[0]) / run,
                (other.end[1] - other.start[1]) / run,
            ];
            let offset = [point[0] - other.start[0], point[1] - other.start[1]];
            let at = dot(offset, axis);
            let across = dot(offset, [-axis[1], axis[0]]);
            // At an angle the wall's width meets more of the other's side.
            let sine = (1.0 - dot(into, axis).powi(2)).max(0.0).sqrt();
            if sine <= 0.0 {
                return false;
            }
            let clear = wall.thickness_feet * 0.5 / sine - JOIN_EPS_FEET;
            at > clear && at < run - clear && across.abs() <= JOIN_EPS_FEET
        })
        .collect();
    let [host] = hosts[..] else {
        return None;
    };
    let run = (host.end[0] - host.start[0]).hypot(host.end[1] - host.start[1]);
    let cosine = dot(
        into,
        [
            (host.end[0] - host.start[0]) / run,
            (host.end[1] - host.start[1]) / run,
        ],
    );
    if cosine.abs() > ANGLED_JOIN_MAX_COSINE || wall.layers.is_empty() || host.layers.is_empty() {
        return None;
    }
    if cosine.abs() > PERPENDICULAR_EPS {
        return Some(ButtJoin {
            partner: host.element_id,
            runs_through: false,
            reach_feet: None,
            layer_reach_feet: None,
            layer_edge_reach_feet: Some(angled_tee_edges(wall, host, point, into)?),
        });
    }
    let half = host.thickness_feet * 0.5;
    if wall.layers.len() == 1 {
        return Some(ButtJoin {
            partner: host.element_id,
            runs_through: false,
            reach_feet: Some(-half),
            layer_reach_feet: None,
            layer_edge_reach_feet: None,
        });
    }
    // The host's layers from the face `wall` meets: its exterior faces
    // `wall` where it points along `into`.
    let near_first: Vec<(f64, u32)> = if dot(host.exterior, into) > 0.0 {
        host.layers.clone()
    } else {
        host.layers.iter().rev().copied().collect()
    };
    let reaches: Vec<f64> = wall
        .layers
        .iter()
        .map(|(_, function)| {
            -half
                + near_first
                    .iter()
                    .take_while(|(_, other)| other > function)
                    .map(|(width, _)| width)
                    .sum::<f64>()
        })
        .collect();
    Some(ButtJoin {
        partner: host.element_id,
        runs_through: false,
        reach_feet: None,
        layer_reach_feet: Some(reaches),
        layer_edge_reach_feet: None,
    })
}

/// Where the line through `from` along `direction` meets the line through
/// `on` along `along`, as a multiple of `direction`. `None` for parallel
/// lines.
fn meet(from: [f64; 2], direction: [f64; 2], on: [f64; 2], along: [f64; 2]) -> Option<f64> {
    let cross = direction[0] * along[1] - direction[1] * along[0];
    if cross.abs() < 1e-12 {
        return None;
    }
    let gap = [on[0] - from[0], on[1] - from[1]];
    Some((gap[0] * along[1] - gap[1] * along[0]) / cross)
}

/// How far past `point` each of `wall`'s layers reaches along its two edges,
/// exterior first, where every edge of layer `i` stops on the line
/// `targets[i]` (a point on it and its direction). `into` points from
/// `point` along `wall`.
fn edge_reaches(
    wall: &WallLine,
    point: [f64; 2],
    into: [f64; 2],
    targets: &[([f64; 2], [f64; 2])],
) -> Option<Vec<[f64; 2]>> {
    if targets.len() != wall.layers.len() {
        return None;
    }
    let mut edge = wall.thickness_feet * 0.5;
    let mut out = Vec::with_capacity(targets.len());
    for ((width, _), (on, along)) in wall.layers.iter().zip(targets) {
        let mut pair = [0.0; 2];
        for (side, offset) in [edge, edge - width].into_iter().enumerate() {
            let from = [
                point[0] + wall.exterior[0] * offset,
                point[1] + wall.exterior[1] * offset,
            ];
            let reach = -meet(from, into, *on, *along)?;
            if !reach.is_finite() {
                return None;
            }
            pair[side] = reach;
        }
        out.push(pair);
        edge -= width;
    }
    Some(out)
}

/// The lines `other`'s layer boundaries lie on, from the face
/// `side_normal` points out of: its offsets from `other`'s centreline along
/// `side_normal`, with its layers in that order.
fn boundaries_from(other: &WallLine, side_normal: [f64; 2]) -> (Vec<f64>, Vec<(f64, u32)>) {
    let layers: Vec<(f64, u32)> =
        if other.exterior[0] * side_normal[0] + other.exterior[1] * side_normal[1] > 0.0 {
            other.layers.clone()
        } else {
            other.layers.iter().rev().copied().collect()
        };
    let mut at = other.thickness_feet * 0.5;
    let mut offsets = vec![at];
    for (width, _) in &layers {
        at -= width;
        offsets.push(at);
    }
    (offsets, layers)
}

/// The slanted end `wall` takes at an angled butt join with `other`, whose
/// centreline ends at `point` too (RE-74). Each of its layers ends on one of
/// `other`'s boundary lines, along both of its edges:
/// - between single-layer walls, the wall that runs through reaches the
///   other's far face and the other stops at its near face (RE-70);
/// - between layered walls whose layers match from the outside of the
///   corner and which share their base and top, layer `i` of the wall that
///   runs through reaches the outer edge of the other's layer `i`, and
///   layer `i` of the wall that stops, its inner edge (RE-71).
///
/// `into` points from `point` along `wall`. `None` for any other pair.
pub fn angled_layer_edges(
    wall: &WallLine,
    other: &WallLine,
    point: [f64; 2],
    into: [f64; 2],
    runs_through: bool,
) -> Option<Vec<[f64; 2]>> {
    let dot = |a: [f64; 2], b: [f64; 2]| a[0] * b[0] + a[1] * b[1];
    let far = if (other.start[0] - point[0]).hypot(other.start[1] - point[1]) <= JOIN_EPS_FEET {
        other.end
    } else {
        other.start
    };
    let run = (far[0] - point[0]).hypot(far[1] - point[1]);
    if !(run.is_finite() && run > 1e-9) {
        return None;
    }
    let away = [(far[0] - point[0]) / run, (far[1] - point[1]) / run];
    // Each wall's outer side faces away from the other wall.
    let normal = [-away[1], away[0]];
    let outer = if dot(normal, into) < 0.0 {
        normal
    } else {
        [-normal[0], -normal[1]]
    };
    let (offsets, theirs) = boundaries_from(other, outer);
    let line = |offset: f64| {
        (
            [point[0] + outer[0] * offset, point[1] + outer[1] * offset],
            away,
        )
    };
    let exterior_outside = dot(wall.exterior, away) < 0.0;
    let targets: Vec<([f64; 2], [f64; 2])> = if wall.layers.len() == 1 && other.layers.len() == 1 {
        vec![line(if runs_through { offsets[0] } else { offsets[1] })]
    } else {
        if wall.layers.len() < 2
            || other.layers.len() != wall.layers.len()
            || (wall.base_feet - other.base_feet).abs() > LAYER_JOIN_HEIGHT_EPS_FEET
            || (wall.top_feet - other.top_feet).abs() > LAYER_JOIN_HEIGHT_EPS_FEET
        {
            return None;
        }
        let ours: Vec<u32> = if exterior_outside {
            wall.layers.iter().map(|(_, f)| *f).collect()
        } else {
            wall.layers.iter().rev().map(|(_, f)| *f).collect()
        };
        let theirs: Vec<u32> = theirs.iter().map(|(_, f)| *f).collect();
        if ours != theirs {
            return None;
        }
        let from_corner: Vec<([f64; 2], [f64; 2])> = (0..wall.layers.len())
            .map(|rank| line(offsets[if runs_through { rank } else { rank + 1 }]))
            .collect();
        if exterior_outside {
            from_corner
        } else {
            from_corner.into_iter().rev().collect()
        }
    };
    edge_reaches(wall, point, into, &targets)
}

/// The slanted end `wall` takes where it stops against `host` at an angled
/// T joint (RE-74): each of its layers ends, along both of its edges, on
/// the host boundary line RE-73's layer priorities give, counted from the
/// face it meets. A single-layer wall stops at that face.
pub fn angled_tee_edges(
    wall: &WallLine,
    host: &WallLine,
    point: [f64; 2],
    into: [f64; 2],
) -> Option<Vec<[f64; 2]>> {
    let run = (host.end[0] - host.start[0]).hypot(host.end[1] - host.start[1]);
    let axis = [
        (host.end[0] - host.start[0]) / run,
        (host.end[1] - host.start[1]) / run,
    ];
    let normal = [-axis[1], axis[0]];
    let near = if normal[0] * into[0] + normal[1] * into[1] > 0.0 {
        normal
    } else {
        [-normal[0], -normal[1]]
    };
    let (offsets, near_first) = boundaries_from(host, near);
    let targets: Vec<([f64; 2], [f64; 2])> = wall
        .layers
        .iter()
        .map(|(_, function)| {
            let passed = if wall.layers.len() == 1 {
                0
            } else {
                near_first
                    .iter()
                    .take_while(|(_, other)| other > function)
                    .count()
            };
            (
                [
                    point[0] + near[0] * offsets[passed],
                    point[1] + near[1] * offsets[passed],
                ],
                axis,
            )
        })
        .collect();
    edge_reaches(wall, point, into, &targets)
}

/// How far past the joint `point` each of `wall`'s layers reaches, exterior
/// first, where `wall` meets `other` at a layered butt join (RE-71).
/// `into` points from the joint along `wall`.
///
/// `None` unless both walls have several layers, both show the same layer
/// functions in the same order counted from the outside of the corner, and
/// both share their base and top: on Snowdon Towers, 522 of the 528 such
/// ends are cleaned layer by layer, against 17 of 75 clean where the walls'
/// heights differ.
pub fn layer_reaches(
    wall: &WallLine,
    other: &WallLine,
    point: [f64; 2],
    into: [f64; 2],
    runs_through: bool,
) -> Option<Vec<f64>> {
    if wall.layers.len() < 2
        || other.layers.len() != wall.layers.len()
        || (wall.base_feet - other.base_feet).abs() > LAYER_JOIN_HEIGHT_EPS_FEET
        || (wall.top_feet - other.top_feet).abs() > LAYER_JOIN_HEIGHT_EPS_FEET
    {
        return None;
    }
    let dot = |a: [f64; 2], b: [f64; 2]| a[0] * b[0] + a[1] * b[1];
    // The partner runs from the joint to its other end. On the side of
    // `wall` it runs to, `wall`'s face is inside the corner.
    let far = if (other.start[0] - point[0]).hypot(other.start[1] - point[1]) <= JOIN_EPS_FEET {
        other.end
    } else {
        other.start
    };
    let partner_on_exterior = dot([far[0] - point[0], far[1] - point[1]], wall.exterior) > 0.0;
    // How far past the joint each of the partner's layer boundaries lies,
    // its exterior face first: the partner is perpendicular, so its
    // exterior points along `into` or against it.
    let outward = if dot(other.exterior, [-into[0], -into[1]]) >= 0.0 {
        1.0
    } else {
        -1.0
    };
    let mut bound = other.thickness_feet * 0.5;
    let mut bounds = vec![bound * outward];
    for (width, _) in &other.layers {
        bound -= width;
        bounds.push(bound * outward);
    }
    // Both walls' layers counted from the outside of the corner.
    let ours: Vec<u32> = if partner_on_exterior {
        wall.layers.iter().rev().map(|(_, f)| *f).collect()
    } else {
        wall.layers.iter().map(|(_, f)| *f).collect()
    };
    let partner_outside_first = outward > 0.0;
    let theirs: Vec<u32> = if partner_outside_first {
        other.layers.iter().map(|(_, f)| *f).collect()
    } else {
        other.layers.iter().rev().map(|(_, f)| *f).collect()
    };
    if ours != theirs {
        return None;
    }
    bounds.sort_by(|a, b| b.total_cmp(a));
    let reaches: Vec<f64> = (0..wall.layers.len())
        .map(|rank| bounds[if runs_through { rank } else { rank + 1 }])
        .collect();
    Some(if partner_on_exterior {
        reaches.into_iter().rev().collect()
    } else {
        reaches
    })
}

/// How closely two walls' bases and tops must agree for their layered join
/// to be read ([`layer_reaches`]), in feet.
pub const LAYER_JOIN_HEIGHT_EPS_FEET: f64 = 1e-3;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::partition_element_records as per;

    /// A wall record shaped like the ones on the recorded edge: the
    /// counted list at `+0x88` holds the leading `3`, the type, the
    /// two Levels, the joined walls and the record's own id, all in
    /// ascending order.
    fn wall(element_id: u32, bbox_feet: [f64; 6], joins: &[u32]) -> PartitionElementRecord {
        let mut references: Vec<u64> = vec![3, 17328, 20307, 20308];
        references.extend(joins.iter().map(|id| u64::from(*id)));
        references.push(u64::from(element_id));
        references.sort_unstable();
        PartitionElementRecord {
            stream: "Partitions/59".into(),
            offset: element_id as usize,
            element_id,
            flags: 0x0121,
            builtin_category: per::OST_WALLS,
            container: per::CONTAINER_NONE,
            placement_kind: per::PLACEMENT_KIND_INSTANCE,
            class_tag: 0,
            bbox_feet,
            preceding_reference: None,
            owner_reference: None,
            references,
            id_from_enclosing_record: false,
            design_option: None,
        }
    }

    /// The Core Interior corner that RE-26 §4 walks through: wall
    /// 20796 runs in x at y = 81 and ends on 20799's centreline at
    /// x = 75, so it is cut back to 74.6667; 20797 runs in y at
    /// x = 48 and ends on 20796's centreline at y = 81, so it is cut
    /// back to 80.6667. Neither is cut at its other end.
    fn core_interior_corner() -> Vec<PartitionElementRecord> {
        vec![
            wall(
                20796,
                [47.75, 80.66667, 76.0, 75.0, 81.33333, 91.0],
                &[20797, 20799],
            ),
            wall(20797, [47.75, 57.66667, 76.0, 48.25, 81.0, 91.0], &[20796]),
            wall(
                20799,
                [74.66667, 58.0, 76.0, 75.33333, 81.33333, 91.0],
                &[20796],
            ),
        ]
    }

    #[test]
    fn a_wall_is_cut_back_by_half_the_wall_it_ends_on() {
        let trims = join_trims(&core_interior_corner());
        let t = trims[&20796];
        assert_eq!(t.axis, 0);
        assert!((t.thickness_feet - 0.66666).abs() < 1e-4);
        assert!((t.start_feet - 0.0).abs() < 1e-9, "47.75 joins nothing");
        assert!((t.end_feet - 0.33333).abs() < 1e-4, "half of 20799");
    }

    #[test]
    fn the_perpendicular_wall_is_cut_by_the_one_it_ends_on() {
        let trims = join_trims(&core_interior_corner());
        let t = trims[&20797];
        assert_eq!(t.axis, 1);
        assert!((t.start_feet - 0.0).abs() < 1e-9);
        assert!((t.end_feet - 0.33333).abs() < 1e-4, "half of 20796");
    }

    #[test]
    fn a_wall_that_ends_short_of_a_centreline_is_not_cut() {
        // 20799's high end sits at 81.3333, which is 20796's face and
        // not its centreline, so nothing joins there.
        let trims = join_trims(&core_interior_corner());
        let t = trims[&20799];
        assert!((t.end_feet - 0.0).abs() < 1e-9);
        assert!((t.start_feet - 0.0).abs() < 1e-9, "58.0 joins nothing");
    }

    #[test]
    fn a_candidate_out_of_elevation_range_does_not_cut() {
        let mut records = core_interior_corner();
        // Push 20799 up a storey: it no longer overlaps 20796.
        records[2].bbox_feet[2] = 106.0;
        records[2].bbox_feet[5] = 121.0;
        let trims = join_trims(&records);
        assert!((trims[&20796].end_feet - 0.0).abs() < 1e-9);
    }

    #[test]
    fn candidates_that_disagree_on_thickness_decline_the_element() {
        let mut records = core_interior_corner();
        // A second wall on the same centreline, different thickness.
        records.push(wall(
            21000,
            [74.75, 58.0, 76.0, 75.25, 81.33333, 91.0],
            &[20796],
        ));
        records[0].references.push(21000);
        records[0].references.sort_unstable();
        let trims = join_trims(&records);
        assert!(!trims.contains_key(&20796), "ambiguous join declines");
        assert!(trims.contains_key(&20797), "other walls are unaffected");
    }

    #[test]
    fn a_square_plan_box_has_no_wall_axis() {
        let records = vec![wall(30000, [0.0, 0.0, 0.0, 2.0, 2.0, 10.0], &[])];
        assert!(join_trims(&records).is_empty());
    }

    #[test]
    fn a_trim_that_would_collapse_the_run_is_declined() {
        // A 1 ft stub between two 2 ft walls: each end would be cut
        // back a full foot, which leaves nothing.
        let records = vec![
            wall(
                31000,
                [0.0, 9.66667, 0.0, 1.0, 10.33333, 10.0],
                &[31001, 31002],
            ),
            wall(31001, [-1.0, 0.0, 0.0, 1.0, 20.0, 10.0], &[31000]),
            wall(31002, [0.0, 0.0, 0.0, 2.0, 20.0, 10.0], &[31000]),
        ];
        let trims = join_trims(&records);
        assert!(!trims.contains_key(&31000));
    }

    /// Wall 20826 of the recorded edge: an 8" wall whose two ends sit
    /// exactly on the centrelines of two 8" walls that pass through
    /// them, and which Revit leaves at full length. Its record names
    /// no other wall at all, and that is the only thing in the file
    /// that says so (#238, RE-29 §2).
    fn unjoined_span() -> Vec<PartitionElementRecord> {
        vec![
            wall(20826, [119.5, 67.41667, 76.0, 129.0, 68.08333, 91.0], &[]),
            wall(20825, [119.16667, 58.0, 76.0, 119.83333, 81.0, 91.0], &[]),
            wall(20804, [128.66667, 58.0, 76.0, 129.33333, 81.0, 91.0], &[]),
        ]
    }

    #[test]
    fn a_wall_that_names_no_join_partner_is_not_trimmed() {
        let trims = join_trims(&unjoined_span());
        let t = trims[&20826];
        assert!((t.start_feet - 0.0).abs() < 1e-9, "119.5 is not cut");
        assert!((t.end_feet - 0.0).abs() < 1e-9, "129.0 is not cut");
    }

    #[test]
    fn naming_the_same_two_walls_restores_the_trim() {
        let mut records = unjoined_span();
        records[0] = wall(
            20826,
            [119.5, 67.41667, 76.0, 129.0, 68.08333, 91.0],
            &[20804, 20825],
        );
        let t = join_trims(&records)[&20826];
        assert!((t.start_feet - 0.33333).abs() < 1e-4);
        assert!((t.end_feet - 0.33333).abs() < 1e-4);
    }

    /// The recorded edge's `x = 137` cluster. 20800 runs in x at
    /// y = 81 and its high end is cut back to 136.9167 by 20816; that
    /// cut puts 20803's centreline (137.1667) past the end of 20800,
    /// so 20803 has nothing to butt into and Revit leaves it at 81.0
    /// (#238, RE-29 §3).
    fn cut_back_candidate() -> Vec<PartitionElementRecord> {
        vec![
            wall(
                20800,
                [85.5, 80.66667, 76.0, 137.25, 81.33333, 91.0],
                &[20803, 20805, 20816],
            ),
            wall(
                20805,
                [85.16667, 58.0, 76.0, 85.83333, 81.33333, 91.0],
                &[20800],
            ),
            wall(
                20816,
                [136.91667, 58.0, 76.0, 137.58333, 81.0, 91.0],
                &[20800],
            ),
            wall(20803, [136.83333, 81.0, 76.0, 137.5, 87.5, 91.0], &[20800]),
        ]
    }

    #[test]
    fn a_candidate_cut_back_short_of_the_line_does_not_trim() {
        let trims = join_trims(&cut_back_candidate());
        assert!(
            (trims[&20800].end_feet - 0.33333).abs() < 1e-4,
            "20800 is still cut by 20816"
        );
        assert!(
            (trims[&20803].start_feet - 0.0).abs() < 1e-9,
            "20800 no longer reaches 137.1667"
        );
    }

    /// The same fixture records the one thing the solver still gets
    /// wrong: 20800 and 20816 form a true L corner and Revit cuts
    /// only 20800. Nothing in the file says which side survives, so
    /// the solver cuts both and this test pins the residual rather
    /// than hiding it (#238, RE-29 §4).
    #[test]
    fn the_surviving_side_of_a_true_l_corner_is_still_over_trimmed() {
        let trims = join_trims(&cut_back_candidate());
        assert!(
            (trims[&20816].end_feet - 0.33333).abs() < 1e-4,
            "Revit leaves 20816 at 81.0; the solver cuts it"
        );
    }

    /// Where the line being resolved is itself what cut the candidate
    /// back, the cut must not disqualify it: 20798's low end is cut
    /// by the `x = 48` wall line, and 20817 — part of that same line —
    /// is still trimmed by 20798 (RE-29 §3).
    #[test]
    fn a_cut_the_resolved_line_imposed_does_not_disqualify_the_candidate() {
        let records = vec![
            wall(
                20798,
                [48.0, 57.66667, 76.0, 100.25, 58.33333, 91.0],
                &[20797, 20817],
            ),
            wall(20817, [47.75, 51.5, 76.0, 48.25, 58.0, 91.0], &[20798]),
            wall(20797, [47.75, 57.66667, 76.0, 48.25, 81.0, 91.0], &[20798]),
        ];
        let trims = join_trims(&records);
        assert!(
            (trims[&20798].start_feet - 0.25).abs() < 1e-4,
            "20798 is cut by the x = 48 line"
        );
        assert!(
            (trims[&20817].end_feet - 0.33333).abs() < 1e-4,
            "and 20817 is still cut by 20798"
        );
    }

    #[test]
    fn joined_walls_keeps_only_recovered_wall_ids() {
        let record = wall(
            20796,
            [47.75, 80.66667, 76.0, 75.0, 81.33333, 91.0],
            &[20797],
        );
        let ids = [20796u32, 20797].into_iter().collect();
        let joined = joined_walls(&record, &ids);
        assert_eq!(joined.iter().copied().collect::<Vec<u32>>(), vec![20797]);
    }
}