axiolid-evaluate 0.3.18

Analytic and spline curve/surface evaluation, jets, and inversion
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
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
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
//! A composite station basis: stations along pieces of curves laid end to
//! end (#285, ADR 0082 amendment).
//!
//! A [`CompositeBasis`] is a run of [`StationPiece`]s. Each piece is a span
//! of an atomic 2D or 3D curve ([`StationCurve`]) between two distances in
//! that curve's own station measure, traversed forwards or backwards, and
//! optionally carried by a rigid placement; or of an offset of such a span
//! ([`StationCurve::Offset`], #289), in the offset's own length (see
//! [the offset module](super::offset)). This is the form of a composite
//! curve relation this module measures: a format adapter or a graph
//! compiler flattens its trims, sense flags, nested composites and curves
//! placed at stations into pieces, and this module measures stations along
//! them.
//!
//! The same pieces as an owned, neutral value are `axiolid-curve`'s
//! [`CurvePath`] (#290), which the curve-evaluation contract can see:
//! [`CompositeBasis::from_path`] measures a path with its pieces borrowed
//! from it, [`CompositeBasis::path`] hands the pieces out as one, and a
//! [`StationPiece`] converts to a [`PathPiece`] and back
//! ([`StationPiece::from_path_piece`]). The contract's `path_*` queries
//! read a path through the same [`CompositeBasis::section_on`] in the
//! reference provider. A [`StationPiece`] borrows its curve so that a
//! station on a graph relation, resolved again for every station of a run,
//! copies none.
//!
//! # Distance convention
//!
//! A composite measures stations as its pieces do, end to end: the
//! distance of a point is the sum of the lengths of the pieces before it
//! plus its distance into its own piece, each in its piece's station
//! measure. A piece measures in its atomic curve's convention ([the parent
//! module](super)): PLAN distance on an elevated or banked curve, arc
//! length on every other curve (a 2D curve's arc length is its plan
//! length). A rigid placement keeps arc length; it keeps plan distance only
//! when it keeps `+Z`, and a plan-measured piece placed by one that tilts
//! `+Z` is refused by name ([`SectionFrame::carried`]). So:
//!
//! - every piece plan-measured (elevated or banked curves, trimmed,
//!   reversed or placed upright): the composite is measured in plan
//!   distance, [`DistanceConvention::PlanDistance`];
//! - every piece arc-length-measured (lines, conics, polylines,
//!   B-splines, intrinsic curves and chains, 2D or 3D, placed or not): the
//!   composite is measured in arc length,
//!   [`DistanceConvention::ArcLength3d`]. A composite of segments placed at
//!   stations of an elevated curve is measured in ITS OWN pieces' arc
//!   length, whatever the base the segments were placed on;
//! - pieces of both kinds: refused by name, since no one distance runs
//!   through it.
//!
//! A piece with no length is refused by name, as is an unbounded one: an
//! untrimmed line inside a composite is its parameter domain `[0, 1]`, as
//! a composite directrix reads it ([`StationPiece::whole`]).
//!
//! # Joints
//!
//! Consecutive pieces must meet: the end of one within [`JOINT_TOLERANCE`]
//! `* max(1, |p|)` of the start of the next, `|p|` the largest coordinate
//! magnitude of the joint. A joint whose pieces do not meet is refused by
//! name: as a reversed piece where the next piece's END meets the previous
//! one (or the first piece's start meets the second), which is a piece
//! whose sense was not declared; as a gap otherwise.
//!
//! Every interior joint is a seam under the #263 rule
//! ([the seam module](super::seam)): it is never smooth, since a
//! declared continuity is not a guarantee in the data. A station within
//! [`ARC_LENGTH_TOLERANCE`]` * max(1, s)` of a joint is ON it and reads the
//! piece its [`SeamSide`] names at the joint's own distance:
//! [`SeamSide::Outgoing`] the piece that starts there, at its start;
//! [`SeamSide::Incoming`] the piece that ends there, at its end. Each side
//! reads its own piece's point: two pieces that meet within the joint
//! tolerance are not snapped onto one another. At the composite's start
//! and end only one piece exists, and both sides read it; likewise a piece
//! is always read from the inside at its own ends, so a trim that starts
//! on a seam of its curve never reads the part of the curve it trims away.
//! The seams of a piece's curve strictly inside the piece are the
//! composite's seams too, read by the curve's own rule.
//!
//! # Reversed and placed pieces
//!
//! A reversed piece is its span read from its end: the point at distance
//! `u` into the piece is the curve's at `end - u`, the side of a seam is
//! swapped (the incoming piece of the composite is the curve's outgoing
//! one), and the frame's tangent and lateral are negated while up is kept,
//! which is the section frame of the curve traversed the other way (the
//! reference-up frame and the planar frame are exactly that; a banked
//! curve's rolled section keeps its up and keeps the left rail on the
//! left).
//!
//! A placed piece's frame is its curve's carried by the placement
//! ([`SectionFrame::carried`]): moved rigidly where the placement keeps
//! `+Z`; where it tilts `+Z`, the reference-up frame of the placed curve's
//! own point and tangent, since the moved frame would not be the placed 3D
//! curve's own section frame. A plan-measured curve placed tilted is
//! refused by name.
//!
//! # Open ends (#298)
//!
//! A [`PathPiece`] may leave its end open ([`PathPiece::to_end`],
//! [`PathPiece::whole`]): a caller with no provider cannot state the length
//! of an offset beside a gradient curve, a clothoid or a B-spline. Its end
//! is resolved, when the path is read, to where the curve ends by THIS
//! evaluator's length, the number [`StationPiece::whole`] and so a graph
//! compiler's flattening measure the whole curve by: a line's parameter
//! domain end, a length read from stored data exactly, and otherwise the
//! numerical estimate (an ellipse's or a B-spline's arc-length quadrature,
//! an offset's own table, to [`super::OFFSET_TOLERANCE`]). An open path is
//! therefore read exactly as the stated path holding those numbers,
//! which [`CompositeBasis::path`] hands back: bitwise as a station resolved
//! on the same pieces. The distance arithmetic, which joint a station is
//! on and how far into its piece, runs through those numbers; where a
//! joint truly lies is [`CompositeBasis::joint_intervals`]' certified
//! interval, whose piece ends are the curve's own (no station is refused
//! for falling within it: a caller who must know a side certifies the
//! joint, or snaps by a window).
//!
//! # Bounds at a parameter or a point (#304)
//!
//! A [`PathPiece`] may start or end at a [`PathBound`]: a native parameter
//! of its curve, or a point on it in the curve's own coordinates, since
//! the distance to an interior parameter of an ellipse or a B-spline is a
//! quadrature a caller with no provider cannot state. A point is resolved
//! to the one parameter naming it, or refused by name when it is off the
//! curve or several parameters name it ([the path-bound
//! module](super::path_bound)). A parameter is resolved to the curve's
//! measure there, the number [`StationPiece::between_parameters`] measures
//! by: exact where the arc length to it is read from stored data (a line,
//! a circle, a polyline, a curve parameterised by its measure), the
//! arc-length quadrature of an ellipse or a B-spline otherwise. A piece
//! bounded at both ends IS the piece between those parameters, so it reads
//! bitwise as the composite a graph compiler builds for a trim between
//! them in the curve's sense. A closed conic's angle runs round, as in
//! such a trim: from the start's angle forwards by `t1 - t0` where that is
//! within one turn, else by it wrapped into one turn (a point's angle lies
//! in `[0, 2 pi)`, so an end before the start crosses the seam; the same
//! place at both ends is the whole turn). One bound beside a stated or
//! open other end is folded into the first turn, `[0, 2 pi)`, and an end
//! not after the start lies a turn further. Offsets take
//! no bound of their own (their base piece may carry one). Certification
//! is unchanged: [`CompositeBasis::joint_intervals`] bounds each numerical
//! piece's length between the points the kernel reads as its ends, which
//! for a bounded piece are the curve's at its resolved measures.
//!
//! # Exactness
//!
//! A station frame on a composite is exact, rounding aside, only where
//! every piece up to and including the one it is read on is exact
//! ([`CompositeBasis::frame_is_exact_at`]): those pieces' lengths make the
//! distance, and the read piece makes the frame. A piece is exact when its
//! curve is a line and its placement, if any, was exact
//! ([`StationPiece::frame_is_exact`]). Elsewhere the frame carries the
//! tolerances of the parent module.

use axiolid_contracts::{BackendId, GeomError, GeomResult, Operation};
use axiolid_core::{Point3, Scalar, Transform3};
use axiolid_curve::{
    Curve2, Curve3, CurvePath, PathBound, PathCurve, PathOffset, PathPiece, SeamSide,
};
use axiolid_curve_evaluate_contract::{window_span, DistanceConvention};

use super::certify::{
    checked_tolerance, curve_span, piece_length, CertifiedSeam, DistanceInterval, Running,
    POINT_ROUNDING, UNCERTIFIED_LENGTH,
};
use super::offset::{OffsetTable, StationOffset};
use super::seam::tidy;
use super::window::{certification, checked_window, snap};
use super::{
    admitted, invalid, start2, start3, station_length2, station_length3, station_seams2,
    station_seams3, station_section2_on, station_section3_on, SectionFrame, StationSeam,
};
use crate::arc_parameter::{
    arc_length2, arc_length3, parameter_at_arc_length2, parameter_at_arc_length3,
    ARC_LENGTH_TOLERANCE,
};
use crate::curve::{evaluate2, evaluate3};

/// Relative tolerance within which two consecutive pieces of a
/// [`CompositeBasis`] meet: their joint points may be `JOINT_TOLERANCE *
/// max(1, |p|)` apart, `|p|` the joint's largest coordinate magnitude.
pub const JOINT_TOLERANCE: Scalar = 1e-9;

/// The rounding a piece's chord ([`StationPiece::length_floor`]) is reduced
/// by, relative to the largest coordinate of its end points and its
/// length: a hundred times [`POINT_ROUNDING`], so the floor stays below the
/// lower bound [`super::certify`] certifies, whose chords carry that
/// rounding once each.
const CHORD_ROUNDING: Scalar = 100.0 * POINT_ROUNDING;

/// Relative slack within which a closed conic's piece bounded at two
/// parameters (#304) still spans `t1 - t0` rather than that wrapped into
/// one turn: a graph compiler's slack for a periodic trim, so both read
/// the same span.
const TURN_SLACK: Scalar = 1e-9;

/// The arc-length tolerance around a distance: what counts as ON a seam or
/// a joint.
fn slack(distance: Scalar) -> Scalar {
    ARC_LENGTH_TOLERANCE * distance.abs().max(1.0)
}

fn unsupported(input: &'static str) -> GeomError {
    GeomError::UnsupportedInput {
        backend: BackendId::new("axiolid-evaluate"),
        operation: Operation::CurveEvaluation,
        input,
    }
}

/// The atomic curve under a [`StationPiece`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StationCurve<'c> {
    /// A 2D curve, lying in `z = 0`.
    Two(&'c Curve2),
    /// A 3D curve.
    Three(&'c Curve3),
    /// An offset of a base piece, measured in its own length (#289; see
    /// [the offset module](super::offset)).
    Offset(StationOffset<'c>),
}

impl From<StationCurve<'_>> for PathCurve {
    /// The curve, copied.
    fn from(curve: StationCurve<'_>) -> Self {
        match curve {
            StationCurve::Two(curve) => PathCurve::Two(curve.clone()),
            StationCurve::Three(curve) => PathCurve::Three(curve.clone()),
            StationCurve::Offset(offset) => PathCurve::Offset(Box::new(PathOffset::new(
                PathPiece::from(offset.base()),
                offset.law(),
            ))),
        }
    }
}

impl<'c> StationCurve<'c> {
    /// The station curve of a path piece's curve, borrowed from it.
    ///
    /// # Errors
    ///
    /// A piece kind this evaluator does not know, by name.
    pub fn from_path_curve(curve: &'c PathCurve) -> GeomResult<Self> {
        match curve {
            PathCurve::Two(curve) => Ok(Self::Two(curve)),
            PathCurve::Three(curve) => Ok(Self::Three(curve)),
            PathCurve::Offset(offset) => Ok(Self::Offset(StationOffset::new(
                StationPiece::from_path_piece(&offset.base)?,
                offset.law,
            )?)),
            _ => Err(unsupported(
                "a curve path piece of a kind this evaluator does not know",
            )),
        }
    }
}

impl StationCurve<'_> {
    /// The distance convention a station on this curve is measured in:
    /// plan distance on an elevated or banked curve, arc length on every
    /// other (a 2D curve's arc length is its plan length).
    /// An offset is measured as its base is (#289).
    #[must_use]
    pub fn convention(self) -> DistanceConvention {
        match self {
            Self::Three(Curve3::Elevated(_) | Curve3::Banked(_)) => {
                DistanceConvention::PlanDistance
            }
            Self::Offset(offset) => offset.convention(),
            _ => DistanceConvention::ArcLength3d,
        }
    }

    /// The station length (the parent module's `station_length`).
    fn length(self) -> GeomResult<Option<Scalar>> {
        match self {
            Self::Two(curve) => station_length2(curve),
            Self::Three(curve) => station_length3(curve),
            Self::Offset(offset) => offset.length().map(Some),
        }
    }

    /// Whether a frame read on it is exact: a line, or an offset of a line
    /// by a constant law.
    fn frame_is_exact(self) -> bool {
        match self {
            Self::Offset(offset) => offset.frame_is_exact(),
            _ => self.is_line(),
        }
    }

    /// Where the curve ends in its station measure, by this evaluator's own
    /// length (what an open end resolves to, #298): an unbounded line's
    /// parameter domain end `|d|`, else its station length, exact where it
    /// is read from stored data and the numerical estimate otherwise (an
    /// ellipse's or a B-spline's quadrature, an offset's table).
    fn end(self) -> GeomResult<Scalar> {
        match self.line_speed() {
            Some(speed) => Ok(speed),
            None => self
                .length()?
                .ok_or_else(|| invalid("station: a composite piece has no bounded length".into())),
        }
    }

    fn is_line(self) -> bool {
        matches!(
            self,
            Self::Two(Curve2::Line(_)) | Self::Three(Curve3::Line(_))
        )
    }

    /// A circle or an ellipse: its measure runs round, so a span may cross
    /// its parameter seam.
    fn is_closed_conic(self) -> bool {
        matches!(
            self,
            Self::Two(Curve2::Circle(_) | Curve2::Ellipse(_))
                | Self::Three(Curve3::Circle(_) | Curve3::Ellipse(_))
        )
    }

    /// Whether a distance on it is read from stored data alone: false for
    /// an ellipse and a B-spline, whose arc length is a quadrature, and an
    /// offset other than a line or a circle.
    pub(super) fn measure_is_exact(self) -> bool {
        match self {
            Self::Offset(offset) => offset.measure_is_exact(),
            _ => !matches!(
                self,
                Self::Two(Curve2::Ellipse(_) | Curve2::BSpline(_))
                    | Self::Three(Curve3::Ellipse(_) | Curve3::BSpline(_))
            ),
        }
    }

    /// A line's direction length, `None` for any other family.
    fn line_speed(self) -> Option<Scalar> {
        match self {
            Self::Two(Curve2::Line(line)) => Some(line.direction.length()),
            Self::Three(Curve3::Line(line)) => Some(line.direction.length()),
            _ => None,
        }
    }

    /// A closed conic's angle folded into the turn from its seam, `[0, 2
    /// pi)`; any other curve's parameter as it is.
    fn turned(self, t: Scalar) -> Scalar {
        if self.is_closed_conic() {
            t.rem_euclid(core::f64::consts::TAU)
        } else {
            t
        }
    }

    /// The parameters a piece bounded at both ends spans (#304): as given,
    /// except on a closed conic, whose angle runs round: from `t0` forwards
    /// by `t1 - t0` where that is within one turn (to [`TURN_SLACK`]),
    /// else by `t1 - t0` wrapped into one turn, a whole turn where the two
    /// are whole turns apart. That is the span a graph compiler reads for
    /// a trim of the conic in its sense, with the same arithmetic.
    fn wound(self, t0: Scalar, t1: Scalar) -> (Scalar, Scalar) {
        if !self.is_closed_conic() {
            return (t0, t1);
        }
        let turn = core::f64::consts::TAU;
        let travelled = t1 - t0;
        let span = if travelled > 0.0 && travelled <= turn * (1.0 + TURN_SLACK) {
            travelled
        } else {
            match travelled.rem_euclid(turn) {
                0.0 => turn,
                wrapped => wrapped,
            }
        };
        (t0, t0 + span)
    }

    /// The measure an end bounded at parameter `t` stands at after a span
    /// starting at measure `start` (#304): the measure at `t`; on a closed
    /// conic at its angle in `[0, 2 pi)`, a turn further where that is not
    /// after `start` (the span crosses the seam, ends on it, or is the
    /// whole turn).
    fn measure_after(self, t: Scalar, start: Scalar) -> GeomResult<Scalar> {
        let m = self.measure_at(self.turned(t))?;
        if self.is_closed_conic() && m <= start {
            return Ok(self.length()?.unwrap_or(Scalar::INFINITY) + m);
        }
        Ok(m)
    }

    /// The native parameter a path piece bound names on the curve (#304):
    /// a parameter as it is, a point the one parameter naming it (see
    /// [the path-bound module](super::path_bound)).
    ///
    /// # Errors
    ///
    /// A bound that is not finite; a point off the curve, named by several
    /// parameters, or on a curve this evaluator does not invert; each by
    /// name.
    pub fn parameter_at_bound(self, bound: PathBound) -> GeomResult<Scalar> {
        super::path_bound::bound_parameter(self, bound)
    }

    /// A closed conic's measure `m` folded into one turn `[0, L]`.
    fn folded(self, m: Scalar) -> GeomResult<Scalar> {
        if !self.is_closed_conic() {
            return Ok(m);
        }
        let turn = self.length()?.unwrap_or(Scalar::INFINITY);
        Ok(if m > turn { m - turn } else { m })
    }

    /// The station measure at native parameter `t`, from the curve's
    /// start: `t |d|` on a line (any sign), `r t` on a circle, the arc
    /// length from the domain's start on a polyline, a B-spline or an
    /// ellipse, `t` itself on a curve parameterised by its measure.
    fn measure_at(self, t: Scalar) -> GeomResult<Scalar> {
        Ok(match self {
            Self::Two(Curve2::Line(line)) => t * line.direction.length(),
            Self::Three(Curve3::Line(line)) => t * line.direction.length(),
            Self::Two(Curve2::Circle(circle)) => t * circle.radius,
            Self::Three(Curve3::Circle(circle)) => t * circle.radius,
            Self::Two(curve @ (Curve2::Polyline(_) | Curve2::BSpline(_) | Curve2::Ellipse(_))) => {
                arc_length2(curve, start2(curve), t)?
            }
            Self::Three(
                curve @ (Curve3::Polyline(_) | Curve3::BSpline(_) | Curve3::Ellipse(_)),
            ) => arc_length3(curve, start3(curve), t)?,
            Self::Offset(_) => {
                return Err(unsupported(
                    "the native parameter of an offset piece: an offset takes its basis's \
                     parameter, not its own length",
                ))
            }
            _ => t,
        })
    }

    /// The point at measure `m` from the curve's start; an offset's
    /// through `table`.
    fn point_at(self, m: Scalar, table: Option<&OffsetTable>) -> GeomResult<Point3> {
        let m = self.folded(m)?;
        match self {
            Self::Offset(offset) => offset.point_at(m, table),
            Self::Two(curve) => {
                let t = match curve {
                    Curve2::Line(line) => m / line.direction.length(),
                    _ => parameter_at_arc_length2(curve, start2(curve), m)?,
                };
                let p = evaluate2(curve, t)?;
                Ok(Point3::new(p.x, p.y, 0.0))
            }
            Self::Three(curve) => match curve {
                Curve3::Elevated(elevated) => crate::arc_length::elevated_point(elevated, m),
                Curve3::Banked(banked) => crate::banked::banked_point(banked, m),
                Curve3::Line(line) => evaluate3(curve, m / line.direction.length()),
                _ => evaluate3(curve, parameter_at_arc_length3(curve, start3(curve), m)?),
            },
        }
    }

    /// The section frame at measure `m`, read from `side` on a seam; an
    /// offset's through `table`.
    fn section_at(
        self,
        m: Scalar,
        side: SeamSide,
        table: Option<&OffsetTable>,
    ) -> GeomResult<SectionFrame> {
        let m = self.folded(m)?;
        match self {
            Self::Offset(offset) => offset.section_at(m, table),
            // A line inside a composite may be trimmed before its origin, so
            // its measure may be negative: read it directly.
            Self::Two(Curve2::Line(line)) => {
                let point = line.origin + line.direction * (m / line.direction.length());
                super::planar_frame(point, line.direction)
            }
            Self::Three(curve @ Curve3::Line(line)) => super::reference_up_frame(
                evaluate3(curve, m / line.direction.length())?,
                line.direction,
            ),
            Self::Two(curve) => station_section2_on(curve, m, side),
            Self::Three(curve) => station_section3_on(curve, m, side),
        }
    }

    fn seams(self) -> GeomResult<Vec<StationSeam>> {
        if self.is_closed_conic() {
            return Ok(Vec::new());
        }
        match self {
            Self::Two(curve) => station_seams2(curve),
            Self::Three(curve) => station_seams3(curve),
            // Its base spans no seam of its curve.
            Self::Offset(_) => Ok(Vec::new()),
        }
    }
}

/// One piece of a [`CompositeBasis`]: the span `[start, end]` of an atomic
/// curve, in that curve's station measure, traversed forwards or
/// backwards, optionally placed by a rigid motion; see the
/// [module documentation](self).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StationPiece<'c> {
    /// The atomic curve.
    pub curve: StationCurve<'c>,
    /// Where the span starts, in the curve's station measure from its
    /// start (negative only on a line).
    pub start: Scalar,
    /// Where the span ends, greater than `start`.
    pub end: Scalar,
    /// Whether the composite runs from `end` to `start`.
    pub reversed: bool,
    /// The rigid motion carrying the curve, if it is placed.
    pub placement: Option<Transform3>,
    /// Whether that placement is exact, rounding aside (`true` with no
    /// placement).
    pub placement_exact: bool,
}

impl<'c> StationPiece<'c> {
    /// The whole curve: `[0, L]`, `L` its station length; an unbounded
    /// line is its parameter domain `[0, 1]`, from its origin to `origin +
    /// direction`.
    ///
    /// # Errors
    ///
    /// A curve whose length a station cannot be measured against, by name.
    pub fn whole(curve: StationCurve<'c>) -> GeomResult<Self> {
        Self::between(curve, 0.0, curve.end()?)
    }

    /// The span `[start, end]` of `curve`, in its station measure.
    ///
    /// # Errors
    ///
    /// A non-finite or empty span, and one outside the curve's measure
    /// (before its start or past its length, beyond the arc-length
    /// tolerance; a closed conic's span may cross its parameter seam but
    /// not exceed one turn), by name.
    pub fn between(curve: StationCurve<'c>, start: Scalar, end: Scalar) -> GeomResult<Self> {
        if !(start.is_finite() && end.is_finite()) || end <= start {
            return Err(GeomError::Degenerate(format!(
                "station: a composite piece spans [{start}, {end}], which is empty or not finite"
            )));
        }
        if curve
            .line_speed()
            .is_some_and(|speed| !(speed.is_finite() && speed > 0.0))
        {
            return Err(GeomError::Degenerate(
                "station: a composite piece is a line with no direction".into(),
            ));
        }
        if !curve.is_line() {
            let length = curve.length()?.unwrap_or(Scalar::INFINITY);
            let reach = if curve.is_closed_conic() {
                start + length
            } else {
                length
            };
            if start < -slack(0.0) || start > length + slack(length) || end > reach + slack(reach) {
                return Err(invalid(format!(
                    "station: a composite piece spans [{start}, {end}], outside its curve's \
                     measure [0, {length}]"
                )));
            }
        }
        Ok(Self {
            curve,
            start,
            end,
            reversed: false,
            placement: None,
            placement_exact: true,
        })
    }

    /// The span between native parameters `t0 < t1` of `curve`, converted
    /// to its station measure. A closed conic's span may start anywhere
    /// and cross its parameter seam (at most one turn).
    ///
    /// # Errors
    ///
    /// As [`Self::between`], and the arc-length quadrature's refusals.
    pub fn between_parameters(curve: StationCurve<'c>, t0: Scalar, t1: Scalar) -> GeomResult<Self> {
        if !(t0.is_finite() && t1.is_finite()) || t1 <= t0 {
            return Err(GeomError::Degenerate(format!(
                "station: a composite piece spans parameters [{t0}, {t1}], which is empty or \
                 not finite"
            )));
        }
        if curve.is_closed_conic() {
            let turn = core::f64::consts::TAU;
            let from = t0.rem_euclid(turn);
            let to = from + (t1 - t0);
            let start = curve.measure_at(from)?;
            let end = if to <= turn {
                curve.measure_at(to)?
            } else {
                let length = curve.length()?.unwrap_or(Scalar::INFINITY);
                length + curve.measure_at(to - turn)?
            };
            return Self::between(curve, start, end);
        }
        Self::between(curve, curve.measure_at(t0)?, curve.measure_at(t1)?)
    }

    /// The same span traversed the other way.
    #[must_use]
    pub const fn reversed(mut self) -> Self {
        self.reversed = !self.reversed;
        self
    }

    /// The same piece carried further by the rigid motion `rigid` (applied
    /// after any placement it already has), `exact` when that motion is
    /// (as [`PathPiece::placed`]).
    #[must_use]
    pub fn placed(mut self, rigid: Transform3, exact: bool) -> Self {
        self.placement = Some(match self.placement {
            Some(inner) => rigid * inner,
            None => rigid,
        });
        self.placement_exact &= exact;
        self
    }

    /// The whole of an offset (#289): `[0, L]`, `L` its own length.
    ///
    /// # Errors
    ///
    /// The offset's refusals (a collapse, a cusp, a self-crossing), by
    /// name.
    pub fn offset(offset: StationOffset<'c>) -> GeomResult<Self> {
        let end = offset.length()?;
        if !(end.is_finite() && end > 0.0) {
            return Err(GeomError::Degenerate(
                "station: an offset piece has no length".into(),
            ));
        }
        Ok(Self {
            curve: StationCurve::Offset(offset),
            start: 0.0,
            end,
            reversed: false,
            placement: None,
            placement_exact: true,
        })
    }

    /// The offset's measure table, for an offset piece.
    pub(super) fn table(&self) -> GeomResult<Option<OffsetTable>> {
        match self.curve {
            StationCurve::Offset(offset) => offset.table().map(Some),
            _ => Ok(None),
        }
    }

    /// The station piece of a path piece: its span checked against its
    /// curve as [`Self::between`] checks it, then reversed and placed as
    /// the path piece is. An open end ([`PathPiece::open_end`], #298) is
    /// resolved first to where the curve ends by this evaluator's own
    /// length, the end [`Self::whole`] reads (see the
    /// [module documentation](self#open-ends-298)). A bound at a parameter
    /// or a point ([`PathPiece::start_bound`], [`PathPiece::end_bound`],
    /// #304) is resolved to the curve's parameter there
    /// ([`StationCurve::parameter_at_bound`]) and that to its measure: a
    /// piece bounded at both ends is [`Self::between_parameters`] (see the
    /// [module documentation](self#bounds-at-a-parameter-or-a-point-304)).
    ///
    /// # Errors
    ///
    /// As [`Self::between`] and [`Self::between_parameters`], an open end on
    /// a curve with no bounded length, an end both open and bounded, a
    /// bound's refusals ([`StationCurve::parameter_at_bound`]), and a piece
    /// kind this evaluator does not know, by name.
    pub fn from_path_piece(piece: &'c PathPiece) -> GeomResult<Self> {
        let curve = StationCurve::from_path_curve(&piece.curve)?;
        if piece.open_end && piece.end_bound.is_some() {
            return Err(invalid(
                "station: a curve path piece whose end is both open and bounded by a parameter \
                 or a point"
                    .into(),
            ));
        }
        let t0 = piece
            .start_bound
            .map(|bound| curve.parameter_at_bound(bound))
            .transpose()?;
        let t1 = piece
            .end_bound
            .map(|bound| curve.parameter_at_bound(bound))
            .transpose()?;
        let span = match (t0, t1) {
            // Both ends at parameters: the piece between them, bitwise.
            (Some(t0), Some(t1)) => {
                let (t0, t1) = curve.wound(t0, t1);
                Self::between_parameters(curve, t0, t1)?
            }
            _ => {
                let start = match t0 {
                    Some(t) => curve.measure_at(curve.turned(t))?,
                    None => piece.start,
                };
                let end = if piece.open_end {
                    curve.end()?
                } else if let Some(t) = t1 {
                    curve.measure_after(t, start)?
                } else {
                    piece.end
                };
                Self::between(curve, start, end)?
            }
        };
        Ok(Self {
            reversed: piece.reversed,
            placement: piece.placement,
            placement_exact: piece.placement_exact,
            ..span
        })
    }

    /// The piece's length in its station measure.
    #[must_use]
    pub fn length(&self) -> Scalar {
        self.end - self.start
    }

    /// The distance convention the piece is measured in.
    #[must_use]
    pub fn convention(&self) -> DistanceConvention {
        self.curve.convention()
    }

    /// Whether a frame read on this piece is exact, rounding aside: a line
    /// (an offset of a line by a constant law included), placed, if at
    /// all, exactly (as [`PathPiece::frame_is_exact`]).
    #[must_use]
    pub fn frame_is_exact(&self) -> bool {
        self.curve.frame_is_exact() && self.placement_exact
    }

    /// The curve's measure at distance `u` into the piece, and the side of
    /// a seam of the curve that `side` (in the composite's direction) is.
    fn measure(&self, u: Scalar, side: SeamSide) -> (Scalar, SeamSide) {
        if self.reversed {
            let swapped = match side {
                SeamSide::Incoming => SeamSide::Outgoing,
                _ => SeamSide::Incoming,
            };
            (self.end - u, swapped)
        } else {
            (self.start + u, side)
        }
    }

    /// The point at distance `u` into the piece; an offset's through
    /// `table`.
    fn point_at(&self, u: Scalar, table: Option<&OffsetTable>) -> GeomResult<Point3> {
        let (m, _) = self.measure(u, SeamSide::Outgoing);
        let point = self.curve.point_at(m, table)?;
        Ok(match self.placement {
            Some(rigid) => rigid.transform_point3(point),
            None => point,
        })
    }

    /// A certified lower bound of the piece's length in its station measure
    /// (#305), with no quadrature: the chord between the points read as its
    /// ends, in the plan where it is measured in plan (a plan length is
    /// never shorter than its plan chord), less their rounding. Read
    /// unplaced: a placement is rigid, and one that tilts `+Z` under a
    /// plan-measured curve is refused where the piece is read.
    fn length_floor(&self, table: Option<&OffsetTable>) -> GeomResult<Scalar> {
        let a = self.curve.point_at(self.start, table)?;
        let b = self.curve.point_at(self.end, table)?;
        let d = b - a;
        let chord = match self.convention() {
            DistanceConvention::PlanDistance => d.x.hypot(d.y),
            _ => d.length(),
        };
        let scale = a
            .abs()
            .max_element()
            .max(b.abs().max_element())
            .max(self.length())
            .max(1.0);
        Ok((chord - CHORD_ROUNDING * scale).max(0.0))
    }

    /// The section frame at distance `u` into the piece, read from `side`
    /// on a seam of its curve; at the piece's own ends it is always read
    /// from inside the piece.
    ///
    /// # Errors
    ///
    /// The curve evaluators' refusals, and a plan-measured curve placed by
    /// a motion that tilts `+Z`, by name.
    pub fn section_on(&self, u: Scalar, side: SeamSide) -> GeomResult<SectionFrame> {
        self.section_with(u, side, None)
    }

    /// [`Self::section_on`], an offset read through `table`.
    pub(crate) fn section_with(
        &self,
        u: Scalar,
        side: SeamSide,
        table: Option<&OffsetTable>,
    ) -> GeomResult<SectionFrame> {
        let (_, section) = self.raw_section(u, side, table)?;
        self.finished(section)
    }

    /// The curve's own measure a read at distance `u` into the piece from
    /// `side` stands at, and the curve's section there before the piece
    /// reverses or places it: what [`Self::section_on`] reads (#316).
    pub(crate) fn raw_section(
        &self,
        u: Scalar,
        side: SeamSide,
        table: Option<&OffsetTable>,
    ) -> GeomResult<(Scalar, SectionFrame)> {
        let length = self.length();
        let u = u.clamp(0.0, length);
        let side = if u <= slack(u) {
            SeamSide::Outgoing
        } else if u >= length - slack(length) {
            SeamSide::Incoming
        } else {
            side
        };
        let (m, curve_side) = self.measure(u, side);
        Ok((m, self.curve.section_at(m, curve_side, table)?))
    }

    /// A curve's section as the piece presents it: reversed, then placed.
    pub(crate) fn finished(&self, mut section: SectionFrame) -> GeomResult<SectionFrame> {
        if self.reversed {
            section.tangent = -section.tangent;
            section.lateral = -section.lateral;
        }
        match self.placement {
            Some(rigid) => section.carried(rigid, self.convention()),
            None => Ok(section),
        }
    }

    /// The seams of the curve strictly inside the piece, at their distance
    /// into the piece in the composite's direction.
    pub(super) fn seams(&self) -> GeomResult<Vec<StationSeam>> {
        let mut out: Vec<StationSeam> = self
            .curve
            .seams()?
            .into_iter()
            .filter(|seam| {
                seam.distance > self.start + slack(self.start)
                    && seam.distance < self.end - slack(self.end)
            })
            .map(|seam| {
                let u = if self.reversed {
                    self.end - seam.distance
                } else {
                    seam.distance - self.start
                };
                StationSeam::new(u, u, seam.smooth, seam.exact)
            })
            .collect();
        out.sort_by(|a, b| a.distance.total_cmp(&b.distance));
        Ok(out)
    }
}

impl From<StationPiece<'_>> for PathPiece {
    /// The piece, its curve copied.
    fn from(piece: StationPiece<'_>) -> Self {
        let mut out = PathPiece::new(piece.curve.into(), piece.start, piece.end);
        out.reversed = piece.reversed;
        out.placement = piece.placement;
        out.placement_exact = piece.placement_exact;
        out
    }
}

/// Pieces of curves laid end to end as one station basis; see the
/// [module documentation](self).
#[derive(Debug, Clone, PartialEq)]
pub struct CompositeBasis<'c> {
    pieces: Vec<StationPiece<'c>>,
    /// Each offset piece's measure table, built once (#289).
    tables: Vec<Option<OffsetTable>>,
    /// Each piece's start distance, and the total length last.
    starts: Vec<Scalar>,
    convention: DistanceConvention,
}

impl<'c> CompositeBasis<'c> {
    /// The composite of `pieces`, in order.
    ///
    /// # Errors
    ///
    /// No pieces, a piece with no length, pieces measured in different
    /// conventions, and a joint whose pieces do not meet (a reversed piece
    /// or a gap), each by name; and the evaluators' refusals reading the
    /// joints' points.
    pub fn new(pieces: Vec<StationPiece<'c>>) -> GeomResult<Self> {
        let Some(first) = pieces.first() else {
            return Err(invalid("station: a composite basis has no pieces".into()));
        };
        let convention = first.convention();
        for (index, piece) in pieces.iter().enumerate() {
            let length = piece.length();
            if !length.is_finite() || length <= 0.0 {
                return Err(GeomError::Degenerate(format!(
                    "station: piece {index} of a composite basis has no length"
                )));
            }
            if piece.convention() != convention {
                return Err(unsupported(
                    "a composite station basis whose pieces measure stations differently (plan \
                     distance on an elevated or banked piece, arc length on another): no one \
                     distance runs through it",
                ));
            }
        }
        let tables = pieces
            .iter()
            .map(StationPiece::table)
            .collect::<GeomResult<Vec<_>>>()?;
        for index in 1..pieces.len() {
            check_joint(
                (&pieces[index - 1], tables[index - 1].as_ref()),
                (&pieces[index], tables[index].as_ref()),
                index,
            )?;
        }
        let mut starts = Vec::with_capacity(pieces.len() + 1);
        let mut run = 0.0;
        for piece in &pieces {
            starts.push(run);
            run += piece.length();
        }
        starts.push(run);
        Ok(Self {
            pieces,
            tables,
            starts,
            convention,
        })
    }

    /// The composite along `path` (#290), its curves borrowed from it: each
    /// piece checked against its curve ([`StationPiece::from_path_piece`]),
    /// then measured as [`Self::new`] measures them.
    ///
    /// # Errors
    ///
    /// As [`StationPiece::from_path_piece`] for each piece, naming its
    /// index, and as [`Self::new`].
    pub fn from_path(path: &'c CurvePath) -> GeomResult<Self> {
        let pieces = path
            .pieces()
            .iter()
            .map(StationPiece::from_path_piece)
            .collect::<GeomResult<Vec<_>>>()?;
        Self::new(pieces)
    }

    /// The composite's pieces as a neutral [`CurvePath`] (#290), their
    /// curves copied.
    #[must_use]
    pub fn path(&self) -> CurvePath {
        self.pieces
            .iter()
            .map(|piece| PathPiece::from(*piece))
            .collect()
    }

    /// The pieces, in order.
    #[must_use]
    pub fn pieces(&self) -> &[StationPiece<'c>] {
        &self.pieces
    }

    /// Each piece's start distance, and the total length last.
    pub(crate) fn starts(&self) -> &[Scalar] {
        &self.starts
    }

    /// Each offset piece's measure table.
    pub(crate) fn tables(&self) -> &[Option<OffsetTable>] {
        &self.tables
    }

    /// Certified bounds on the frame law along the composite (#316), its
    /// quadratures certified to `tolerance` ([`super::FrameLaw`]).
    ///
    /// # Errors
    ///
    /// A tolerance that is not finite and positive, by name.
    pub fn frame_law(&self, tolerance: Scalar) -> GeomResult<super::FrameLaw<'_, 'c>> {
        super::FrameLaw::composite(self, tolerance)
    }

    /// The total length in the composite's station measure.
    #[must_use]
    pub fn length(&self) -> Scalar {
        self.starts[self.pieces.len()]
    }

    /// The convention every piece, and so the composite, is measured in.
    #[must_use]
    pub fn convention(&self) -> DistanceConvention {
        self.convention
    }

    /// The piece a station at the admitted `distance` reads on `side`, and
    /// the distance into it.
    fn locate(&self, distance: Scalar, side: SeamSide) -> (usize, Scalar) {
        let count = self.pieces.len();
        for joint in 1..count {
            let at = self.starts[joint];
            if (at - distance).abs() <= slack(distance) {
                return match side {
                    SeamSide::Incoming => (joint - 1, self.pieces[joint - 1].length()),
                    _ => (joint, 0.0),
                };
            }
        }
        let k = self.starts[1..count].partition_point(|start| *start <= distance);
        (k, distance - self.starts[k])
    }

    /// The piece a station at `distance` reads on `side` (the one
    /// [`Self::section_on`] reads).
    ///
    /// # Errors
    ///
    /// As [`Self::section_on`] for the distance.
    pub(crate) fn piece_read(
        &self,
        distance: Scalar,
        side: SeamSide,
    ) -> GeomResult<&StationPiece<'c>> {
        let distance = admitted(distance, Some(self.length()))?;
        Ok(&self.pieces[self.locate(distance, side).0])
    }

    /// The section frame at `distance` along the composite, read from
    /// `side` on a joint or a seam inside a piece; see the
    /// [module documentation](self#joints).
    ///
    /// # Errors
    ///
    /// A distance that is not finite, negative or beyond the composite's
    /// length (by more than the arc-length tolerance), and the piece's
    /// refusals, by name.
    pub fn section_on(&self, distance: Scalar, side: SeamSide) -> GeomResult<SectionFrame> {
        let distance = admitted(distance, Some(self.length()))?;
        let (piece, into) = self.locate(distance, side);
        self.pieces[piece].section_with(into, side, self.tables[piece].as_ref())
    }

    /// Whether the frame at `distance`, read from `side`, is exact: every
    /// piece up to and including the one it is read on is
    /// ([`StationPiece::frame_is_exact`]). `false` for a distance outside
    /// the composite.
    #[must_use]
    pub fn frame_is_exact_at(&self, distance: Scalar, side: SeamSide) -> bool {
        let Ok(distance) = admitted(distance, Some(self.length())) else {
            return false;
        };
        let (piece, _) = self.locate(distance, side);
        self.pieces[..=piece]
            .iter()
            .all(StationPiece::frame_is_exact)
    }

    /// The composite's seams: every interior joint (never smooth) and the
    /// seams of each piece's curve strictly inside the piece, at their
    /// distance along the composite, which is also the parameter reported.
    /// A seam's distance is exact when every piece before it, and its own
    /// seam, is measured from stored data alone (not an ellipse or a
    /// B-spline).
    ///
    /// # Errors
    ///
    /// The seam readers' refusals.
    pub fn seams(&self) -> GeomResult<Vec<StationSeam>> {
        let mut out = Vec::new();
        let mut exact_before = true;
        for (k, piece) in self.pieces.iter().enumerate() {
            let at = self.starts[k];
            if k > 0 {
                out.push(StationSeam::new(at, at, false, exact_before));
            }
            for seam in piece.seams()? {
                let distance = at + seam.distance;
                out.push(StationSeam::new(
                    distance,
                    distance,
                    seam.smooth,
                    seam.exact && exact_before,
                ));
            }
            exact_before &= piece.curve.measure_is_exact();
        }
        Ok(tidy(out, Some(self.length())))
    }

    /// [`Self::seams`], every one exact or refused.
    ///
    /// # Errors
    ///
    /// As [`Self::seams`], and [`GeomError::UnsupportedInput`] for a seam
    /// whose distance needs a quadrature: one after an ellipse or a
    /// B-spline piece, or a B-spline's corner knot.
    pub fn exact_seams(&self) -> GeomResult<Vec<StationSeam>> {
        let seams = self.seams()?;
        if seams.iter().any(|seam| !seam.exact) {
            return Err(unsupported(
                "exact seam distances of a composite with an ellipse or a B-spline piece before \
                 a seam, or a B-spline's corner knot: their arc length is a quadrature",
            ));
        }
        Ok(seams)
    }

    /// Each piece's share of a `tolerance` on a sum of their lengths: a
    /// numerical piece's in proportion to its length, kept a little under
    /// the whole so the rounding of the sum fits.
    fn shares(&self, tolerance: Scalar) -> Vec<Scalar> {
        self.shares_until(tolerance, Scalar::INFINITY)
    }

    /// [`Self::shares`] among the pieces starting by `until` (where the
    /// kernel reads them), the only ones a sum up to there holds; a piece
    /// past it keeps the share it would have had.
    fn shares_until(&self, tolerance: Scalar, until: Scalar) -> Vec<Scalar> {
        let numeric: Scalar = self
            .pieces
            .iter()
            .zip(&self.starts)
            .filter(|(_, start)| **start <= until)
            .map(|(piece, _)| piece)
            .filter(|piece| !piece.curve.measure_is_exact())
            .map(StationPiece::length)
            .sum();
        self.pieces
            .iter()
            .map(|piece| {
                if numeric > 0.0 {
                    0.9 * tolerance * piece.length() / numeric
                } else {
                    tolerance
                }
            })
            .collect()
    }

    /// Where the composite's interior joints truly lie (#294): for each
    /// joint, in order, a [`DistanceInterval`] containing the sum of the
    /// true lengths of the pieces before it, each between the points read
    /// as its ends, no wider than `tolerance`. A sum of lengths read from
    /// stored data is a point interval; see [`super::certify`] for how a
    /// numerical length is bounded.
    ///
    /// # Errors
    ///
    /// A tolerance that is not finite and positive, a piece whose length
    /// cannot be certified ([`super::certify::UNCERTIFIED_LENGTH`]) or not
    /// within the panel budget, and the evaluators' refusals, by name.
    pub fn joint_intervals(&self, tolerance: Scalar) -> GeomResult<Vec<DistanceInterval>> {
        let tolerance = checked_tolerance(tolerance)?;
        Ok(self
            .certified_joints(tolerance, None)?
            .into_iter()
            .map(|(_, interval)| interval)
            .collect())
    }

    /// The composite's interior joints that can fall within `window` of
    /// `around` (#305): each with its index among the joints and the
    /// interval [`Self::joint_intervals`] gives it at `tolerance`,
    /// bitwise (the tolerance shared among the same pieces, summed in the
    /// same order), for every joint whose interval meets `[around - window,
    /// around + window]`, edges included.
    ///
    /// Only the pieces those joints lie after are certified. Every piece
    /// before the window is, since its length moves the joints after it.
    /// A joint is known to lie past the window, and no piece after it is
    /// read, once the certified lower end of the joint before it plus a
    /// certified lower bound of its piece's length with no quadrature (the
    /// chord between its ends, in the plan where it is measured in plan)
    /// passes the window's end. So a piece whose length cannot be certified does not refuse the query
    /// when it lies after the window, or across its end far enough that
    /// its chord carries its own end past it; before the window, or ending
    /// within reach of it, it refuses by name. A joint left out truly lies
    /// outside the window, and one whose interval lies inside it is
    /// returned.
    ///
    /// # Errors
    ///
    /// A tolerance that is not finite and positive, an `around` that is not
    /// finite or a `window` that is negative or not finite, by name; and as
    /// [`Self::joint_intervals`], for the pieces before and within the
    /// window only.
    pub fn joint_intervals_within(
        &self,
        around: Scalar,
        window: Scalar,
        tolerance: Scalar,
    ) -> GeomResult<Vec<(usize, DistanceInterval)>> {
        let tolerance = checked_tolerance(tolerance)?;
        let span = window_span(around, window)?;
        self.certified_joints(tolerance, Some(span))
    }

    /// Each interior joint's index and certified interval at `tolerance`;
    /// within `span` only, when one is given (see
    /// [`Self::joint_intervals_within`]).
    fn certified_joints(
        &self,
        tolerance: Scalar,
        span: Option<DistanceInterval>,
    ) -> GeomResult<Vec<(usize, DistanceInterval)>> {
        let shares = self.shares(tolerance);
        let joints = self.pieces.len().saturating_sub(1);
        let mut run = Running::ZERO;
        let mut out = Vec::with_capacity(joints);
        for (k, ((piece, table), share)) in self
            .pieces
            .iter()
            .zip(&self.tables)
            .zip(shares)
            .take(joints)
            .enumerate()
        {
            if let Some(span) = span {
                // The joint's lower end with no quadrature, rounded down.
                let floor = (run.interval().lower + piece.length_floor(table.as_ref())?)
                    * (1.0 - 4.0 * Scalar::EPSILON);
                if floor > span.upper {
                    break;
                }
            }
            run = run.plus(piece_length(piece, table.as_ref(), share)?);
            let interval = run.interval();
            if interval.width().is_nan() || interval.width() > tolerance {
                return Err(unsupported(UNCERTIFIED_LENGTH));
            }
            if span.is_none_or(|span| interval.meets(&span)) {
                out.push((k, interval));
            }
        }
        Ok(out)
    }

    /// The composite's seams whose frame may jump, each with its certified
    /// distance, up to the first whose interval starts past `until`: every
    /// interior joint, and each piece's own seams inside it.
    pub(crate) fn certified_seams(
        &self,
        tolerance: Scalar,
        until: Scalar,
    ) -> GeomResult<Vec<CertifiedSeam>> {
        let shares = self.shares_until(tolerance, until);
        let mut run = Running::ZERO;
        let mut out = Vec::new();
        for (k, piece) in self.pieces.iter().enumerate() {
            if k > 0 {
                out.push(CertifiedSeam {
                    distance: self.starts[k],
                    interval: run.interval(),
                });
            }
            if run.interval().lower > until {
                break;
            }
            for seam in piece.seams()? {
                if seam.smooth {
                    continue;
                }
                let part = if seam.exact {
                    DistanceInterval::point(seam.distance)
                } else {
                    let u = seam.distance;
                    let (m0, m1) = if piece.reversed {
                        (piece.end - u, piece.end)
                    } else {
                        (piece.start, piece.start + u)
                    };
                    curve_span(piece.curve, m0, m1, shares[k])?
                };
                out.push(CertifiedSeam {
                    distance: self.starts[k] + seam.distance,
                    interval: run.plus(part).interval(),
                });
            }
            if k + 1 < self.pieces.len() {
                run = run.plus(piece_length(piece, self.tables[k].as_ref(), shares[k])?);
            }
        }
        Ok(out)
    }

    /// The distance a station at `distance` with the seam-snapping
    /// `window` is read at along the composite (#294): the joint's or
    /// seam's own distance when exactly one lies within the window, else
    /// `distance`; see [`super::window`].
    ///
    /// # Errors
    ///
    /// A negative or non-finite window, two seams within it
    /// ([`super::window::SEAM_WINDOW_AMBIGUOUS`]), a seam straddling its
    /// edge ([`super::window::SEAM_WINDOW_STRADDLED`]), and a seam whose
    /// distance cannot be certified, by name.
    pub fn snapped_distance(&self, distance: Scalar, window: Scalar) -> GeomResult<Scalar> {
        if checked_window(window)? == 0.0 || !distance.is_finite() {
            return Ok(distance);
        }
        let seams = self.certified_seams(certification(window), distance + window)?;
        snap(&seams, distance, window)
    }

    /// The pieces between distances `start < end` along the composite,
    /// clipped: what a trim of the composite by its station measure keeps.
    ///
    /// # Errors
    ///
    /// A non-finite or empty interval, or one outside `[0, L]` beyond the
    /// arc-length tolerance, by name.
    pub fn pieces_between(&self, start: Scalar, end: Scalar) -> GeomResult<Vec<StationPiece<'c>>> {
        let length = self.length();
        if !(start.is_finite() && end.is_finite()) || end <= start {
            return Err(GeomError::Degenerate(format!(
                "station: a trim of a composite basis spans [{start}, {end}], which is empty or \
                 not finite"
            )));
        }
        if start < -slack(0.0) || end > length + slack(length) {
            return Err(invalid(format!(
                "station: a trim of a composite basis spans [{start}, {end}], outside its \
                 length {length}"
            )));
        }
        let (start, end) = (start.max(0.0), end.min(length));
        let mut out = Vec::new();
        for (k, piece) in self.pieces.iter().enumerate() {
            let (lo, hi) = (self.starts[k], self.starts[k + 1]);
            let (a, b) = (start.max(lo) - lo, end.min(hi) - lo);
            if b - a <= slack(b) {
                continue;
            }
            let mut clipped = *piece;
            if piece.reversed {
                clipped.start = piece.end - b;
                clipped.end = piece.end - a;
            } else {
                clipped.start = piece.start + a;
                clipped.end = piece.start + b;
            }
            out.push(clipped);
        }
        Ok(out)
    }
}

/// A piece with its offset table, if any.
type Read<'a, 'c> = (&'a StationPiece<'c>, Option<&'a OffsetTable>);

/// Refuse a joint whose pieces do not meet, naming an offset across a
/// corner, a reversed piece or the gap.
fn check_joint(
    (before, before_table): Read<'_, '_>,
    (after, after_table): Read<'_, '_>,
    index: usize,
) -> GeomResult<()> {
    let end = before.point_at(before.length(), before_table)?;
    let start = after.point_at(0.0, after_table)?;
    let tolerance = |p: Point3| JOINT_TOLERANCE * p.abs().max_element().max(1.0);
    let meets = |a: Point3, b: Point3| (a - b).length() <= tolerance(a);
    if meets(end, start) {
        return Ok(());
    }
    if [before, after]
        .iter()
        .any(|piece| matches!(piece.curve, StationCurve::Offset(_)))
    {
        return Err(invalid(format!(
            "station: an offset across a corner of its basis at joint {index}: the offsets of \
             the two sides do not meet (a gap of {}), so no distance runs across it (the \
             basis's tangent or roll jumps there)",
            (end - start).length()
        )));
    }
    let after_end = after.point_at(after.length(), after_table)?;
    let reversed = meets(end, after_end)
        || (index == 1 && {
            let before_start = before.point_at(0.0, before_table)?;
            meets(before_start, start) || meets(before_start, after_end)
        });
    if reversed {
        return Err(invalid(format!(
            "station: a reversed piece at joint {index} of a composite basis: its pieces meet \
             end to end or start to start, so one runs against the composite (its sense is not \
             declared)"
        )));
    }
    Err(invalid(format!(
        "station: a gap of {} at joint {index} of a composite basis: its pieces do not meet, so \
         no distance runs across it",
        (end - start).length()
    )))
}