BREP_kernel 0.3.1

A boundary representation (BREP) geometry kernel for building CAD applications.
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
use crate::fit::solve_dense;
use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, VertexRecord};
use crate::{
    interpolate_curve, measure_edge_against_pcurve_image,
    measure_surface_fit_against_pointwise_offset, offset_construction_band, solid_model_scale,
    vertex_endpoint_gap, vertex_tolerance_from_edges, KnotVector, MeasuredTolerance, NurbsCurve,
    NurbsSurface, OffsetEvaluator, OffsetNormal, Vec3, Vec4,
};
use rustc_hash::FxHashMap as HashMap;
use serde::Serialize;

fn domains(surface: &NurbsSurface) -> Result<([f64; 2], [f64; 2]), String> {
    Ok((
        KnotVector::new(surface.knots_u.clone(), surface.degree_u)?.domain(),
        KnotVector::new(surface.knots_v.clone(), surface.degree_v)?.domain(),
    ))
}

/// The normal `offset_surface` offsets along: the face's oriented normal with
/// the singular-row recovery, i.e. the shared evaluator's
/// [`OffsetNormal::FaceStable`] lane, whose body this function used to be.
fn stable_face_normal(face: &FaceRecord, u: f64, v: f64) -> Result<Vec3, String> {
    OffsetEvaluator::new(
        "offset_surface",
        &face.surface,
        OffsetNormal::FaceStable {
            same_sense: face.same_sense,
        },
    )
    .normal(u, v)
}

fn greville_parameters(knots: &KnotVector) -> Vec<f64> {
    let mut parameters = (0..knots.control_point_count())
        .map(|index| {
            knots.knots[index + 1..=index + knots.degree]
                .iter()
                .sum::<f64>()
                / knots.degree as f64
        })
        .collect::<Vec<_>>();
    let domain = knots.domain();
    parameters[0] = domain[0];
    *parameters.last_mut().unwrap() = domain[1];
    parameters
}

/// Rational collocation matrix: rows are the rational basis functions
/// R_i(t) = N_i(t)·w_i / Σ_k N_k(t)·w_k evaluated at each parameter. With
/// uniform weights this reduces to the ordinary B-spline collocation matrix.
fn collocation_matrix(knots: &KnotVector, parameters: &[f64], weights: &[f64]) -> Vec<Vec<f64>> {
    parameters
        .iter()
        .map(|parameter| {
            let mut row = vec![0.0; knots.control_point_count()];
            let span = knots.find_span(*parameter);
            for (offset, value) in knots
                .basis_functions(span, *parameter)
                .into_iter()
                .enumerate()
            {
                let index = span - knots.degree + offset;
                row[index] = value * weights[index];
            }
            let denominator: f64 = row.iter().sum();
            if denominator.abs() > 0.0 {
                for value in &mut row {
                    *value /= denominator;
                }
            }
            row
        })
        .collect()
}

/// Split the weight grid into per-direction factors when it is separable
/// (w_ij = a_i·b_j), which covers every tensor surface built from rational
/// profile/rail curves (cylinders, cones, spheres, tori, revolves).
fn separable_weights(weights: &[Vec<f64>]) -> Option<(Vec<f64>, Vec<f64>)> {
    let first_row = weights.first()?;
    let anchor = *first_row.first()?;
    if anchor.abs() <= 1e-12 {
        return None;
    }
    let a: Vec<f64> = weights.iter().map(|row| row[0]).collect();
    let b: Vec<f64> = first_row.iter().map(|w| w / anchor).collect();
    for (i, row) in weights.iter().enumerate() {
        for (j, &w) in row.iter().enumerate() {
            if (w - a[i] * b[j]).abs() > 1e-10 * (1.0 + w.abs()) {
                return None;
            }
        }
    }
    Some((a, b))
}

/// Interpolate the sample grid in the SOURCE surface's rational basis (same
/// knots and weights). When the true offset is representable in that basis —
/// planes, cylinders, cones, spheres, tori — collocation at the Greville grid
/// recovers it EXACTLY, so offset carriers stay real analytic surfaces
/// instead of non-rational approximations with span-scale wobble.
fn interpolate_tensor(
    knot_u: &KnotVector,
    knot_v: &KnotVector,
    parameters_u: &[f64],
    parameters_v: &[f64],
    samples: &[Vec<Vec3>],
    weights: &[Vec<f64>],
) -> Result<Vec<Vec<Vec4>>, String> {
    let count_u = parameters_u.len();
    let count_v = parameters_v.len();
    if let Some((weights_u, weights_v)) = separable_weights(weights) {
        let matrix_u = collocation_matrix(knot_u, parameters_u, &weights_u);
        let matrix_v = collocation_matrix(knot_v, parameters_v, &weights_v);
        let mut intermediate = vec![vec![Vec3::default(); count_v]; count_u];
        for column in 0..count_v {
            let solve_axis = |axis: fn(Vec3) -> f64| {
                solve_dense(
                    matrix_u.clone(),
                    samples.iter().map(|row| axis(row[column])).collect(),
                )
            };
            let x = solve_axis(|point| point.x)?;
            let y = solve_axis(|point| point.y)?;
            let z = solve_axis(|point| point.z)?;
            for row in 0..count_u {
                intermediate[row][column] = Vec3::new(x[row], y[row], z[row]);
            }
        }
        let mut controls = vec![vec![Vec4::from_point(Vec3::default(), 1.0); count_v]; count_u];
        for row in 0..count_u {
            let solve_axis = |axis: fn(Vec3) -> f64| {
                solve_dense(
                    matrix_v.clone(),
                    intermediate[row].iter().copied().map(axis).collect(),
                )
            };
            let x = solve_axis(|point| point.x)?;
            let y = solve_axis(|point| point.y)?;
            let z = solve_axis(|point| point.z)?;
            for column in 0..count_v {
                controls[row][column] = Vec4::from_point(
                    Vec3::new(x[column], y[column], z[column]),
                    weights[row][column],
                );
            }
        }
        return Ok(controls);
    }

    // Non-separable weights: solve the full tensor collocation system with
    // the exact 2D rational basis. Nets are small in practice.
    let unknowns = count_u * count_v;
    let mut matrix = vec![vec![0.0; unknowns]; unknowns];
    for (k, &u) in parameters_u.iter().enumerate() {
        let span_u = knot_u.find_span(u);
        let basis_u = knot_u.basis_functions(span_u, u);
        for (l, &v) in parameters_v.iter().enumerate() {
            let span_v = knot_v.find_span(v);
            let basis_v = knot_v.basis_functions(span_v, v);
            let row = &mut matrix[k * count_v + l];
            let mut denominator = 0.0;
            for (du, value_u) in basis_u.iter().enumerate() {
                let i = span_u - knot_u.degree + du;
                for (dv, value_v) in basis_v.iter().enumerate() {
                    let j = span_v - knot_v.degree + dv;
                    let entry = value_u * value_v * weights[i][j];
                    row[i * count_v + j] = entry;
                    denominator += entry;
                }
            }
            if denominator.abs() > 0.0 {
                for value in row.iter_mut() {
                    *value /= denominator;
                }
            }
        }
    }
    let solve_axis = |axis: fn(Vec3) -> f64| {
        solve_dense(
            matrix.clone(),
            samples
                .iter()
                .flat_map(|row| row.iter().copied().map(axis))
                .collect(),
        )
    };
    let x = solve_axis(|point| point.x)?;
    let y = solve_axis(|point| point.y)?;
    let z = solve_axis(|point| point.z)?;
    let mut controls = vec![vec![Vec4::from_point(Vec3::default(), 1.0); count_v]; count_u];
    for row in 0..count_u {
        for column in 0..count_v {
            let index = row * count_v + column;
            controls[row][column] = Vec4::from_point(
                Vec3::new(x[index], y[index], z[index]),
                weights[row][column],
            );
        }
    }
    Ok(controls)
}

/// Which branch of [`offset_surface`] built a carrier — and, with it, whether
/// comparing that carrier against the pointwise offset at the same `(u, v)` is
/// even the right question.
///
/// Recorded rather than inferred, in the pattern `offset/reintersect.rs`
/// established for its own two lanes: two of this function's three branches
/// deliberately move the result off the pointwise offset, and a measurement that
/// did not know which branch ran would report a designed divergence as a fit
/// error.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OffsetSurfaceLane {
    /// A rigid control-net shift of an affine (plane-like) carrier. The normal
    /// is constant, so the shifted net IS the pointwise offset — exact by
    /// construction, with no fit to measure.
    Affine,
    /// Greville collocation of the pointwise offset. `S_fit(u, v)` is meant to
    /// BE `offset(u, v)`, and the distance between them is the fit error this
    /// slice measures.
    #[default]
    Fit,
    /// The result was deliberately moved off the pointwise offset: the planar /
    /// ruled EXTENSION (which grows the carrier past its source rim, so the same
    /// `(u, v)` names a different point) or the apex-cone PINCH RETRIM (which
    /// pulls the crossed sample row back to the offset cone's own apex). Both
    /// are correct and intended; neither is comparable pointwise.
    Reparameterised,
}

/// A fitted offset carrier together with what its construction measured about
/// itself.
#[derive(Clone, Debug)]
pub struct MeasuredOffsetSurface {
    pub surface: NurbsSurface,
    pub lane: OffsetSurfaceLane,
    /// `max ‖S_fit(u, v) − offset(u, v)‖` over
    /// [`crate::measure_surface_fit_against_pointwise_offset`]'s grid, against
    /// the band it was judged with.
    ///
    /// `None` for [`OffsetSurfaceLane::Reparameterised`] — see that variant.
    pub fit: Option<MeasuredTolerance>,
}

/// Construct the same fitted offset carrier surface as the reference shell
/// implementation. Positive distance follows its convention and moves
/// opposite the face's outward normal.
pub fn offset_surface(
    face: &FaceRecord,
    distance: f64,
    planar_extension: f64,
) -> Result<NurbsSurface, String> {
    offset_surface_with_lane(face, distance, planar_extension).map(|(surface, _)| surface)
}

/// [`offset_surface`], plus the deviation MEASURED between the carrier it built
/// and the pointwise offset that carrier approximates.
///
/// The surface is bit-identical to [`offset_surface`]'s — this calls the same
/// body and adds a read-only pass afterwards. Nothing here can change the
/// carrier: `occt-offset-algorithms.md` §6.1's ADOPT is a record of what
/// happened, never a new budget.
pub fn offset_surface_measured(
    face: &FaceRecord,
    distance: f64,
    planar_extension: f64,
    band: f64,
) -> Result<MeasuredOffsetSurface, String> {
    let (surface, lane) = offset_surface_with_lane(face, distance, planar_extension)?;
    let fit = match lane {
        OffsetSurfaceLane::Affine => Some(MeasuredTolerance::exact(band)),
        OffsetSurfaceLane::Fit => Some(measure_surface_fit_against_pointwise_offset(
            &face.surface,
            face.same_sense,
            &surface,
            distance,
            band,
        )?),
        OffsetSurfaceLane::Reparameterised => None,
    };
    Ok(MeasuredOffsetSurface { surface, lane, fit })
}

fn offset_surface_with_lane(
    face: &FaceRecord,
    distance: f64,
    planar_extension: f64,
) -> Result<(NurbsSurface, OffsetSurfaceLane), String> {
    let source = &face.surface;
    if source.is_affine()? {
        let ([u0, u1], [v0, v1]) = domains(source)?;
        let normal = stable_face_normal(face, (u0 + u1) / 2.0, (v0 + v1) / 2.0)?;
        let shift = normal.scale(-distance);
        let mut points = source
            .control_points
            .iter()
            .map(|row| {
                row.iter()
                    .map(|control| Ok(control.point()?.add(shift)))
                    .collect::<Result<Vec<_>, String>>()
            })
            .collect::<Result<Vec<_>, String>>()?;
        if planar_extension > 0.0 {
            let p00 = points[0][0];
            let p01 = points[0][1];
            let p10 = points[1][0];
            let direction_u = p10.sub(p00).normalized()?;
            let direction_v = p01.sub(p00).normalized()?;
            points[0][0] = p00
                .sub(direction_u.scale(planar_extension))
                .sub(direction_v.scale(planar_extension));
            points[0][1] = p01
                .sub(direction_u.scale(planar_extension))
                .add(direction_v.scale(planar_extension));
            points[1][0] = p10
                .add(direction_u.scale(planar_extension))
                .sub(direction_v.scale(planar_extension));
            points[1][1] = points[1][1]
                .add(direction_u.scale(planar_extension))
                .add(direction_v.scale(planar_extension));
        }
        let controls = points
            .into_iter()
            .enumerate()
            .map(|(row, points)| {
                points
                    .into_iter()
                    .enumerate()
                    .map(|(column, point)| {
                        Vec4::from_point(point, source.control_points[row][column].w)
                    })
                    .collect()
            })
            .collect();
        // The extension slides the control net along the plane, so the same
        // `(u, v)` no longer names the pointwise offset of the same source
        // point; without it the shift is rigid and exact.
        let lane = if planar_extension > 0.0 {
            OffsetSurfaceLane::Reparameterised
        } else {
            OffsetSurfaceLane::Affine
        };
        return Ok((
            NurbsSurface::new(
                source.degree_u,
                source.degree_v,
                source.knots_u.clone(),
                source.knots_v.clone(),
                controls,
            )?,
            lane,
        ));
    }

    let knot_u = KnotVector::new(source.knots_u.clone(), source.degree_u)?;
    let knot_v = KnotVector::new(source.knots_v.clone(), source.degree_v)?;
    let parameters_u = greville_parameters(&knot_u);
    let parameters_v = greville_parameters(&knot_v);
    // The Greville sample grid IS a pointwise offset evaluation — this fit is
    // the shared evaluator's consumer, not its peer. `offset_surface`'s
    // positive distance moves OPPOSITE the face normal while the evaluator's
    // moves ALONG it, so the negation happens once, here, with a name on it
    // (audit §4.1's four hand negations get no fifth).
    let evaluator = OffsetEvaluator::new(
        "offset_surface",
        source,
        OffsetNormal::FaceStable {
            same_sense: face.same_sense,
        },
    );
    let mut samples = Vec::new();
    for &u in &parameters_u {
        let mut row = Vec::new();
        for &v in &parameters_v {
            row.push(evaluator.at(u, v, -distance)?.point);
        }
        samples.push(row);
    }
    // APEX-CONE PINCH RETRIM: offsetting an apex cone INWARD moves each
    // ruling past the axis — the sampled far row becomes a ring on the far
    // side (radius d·cos half-angle, mirrored through the axis) and the
    // offset surface self-pinches inside the v-domain. The genuine cavity
    // ends AT the pinch (the offset cone's own apex). For a linear-v net
    // (two sample rows — every made/booleaned cone) the pinch lies on each
    // ruling at the fraction where the radial vector vanishes: detect the
    // inversion (far-row radials anti-parallel to near-row radials about the
    // row centroids) and pull the far row back to the pinch point, so the
    // fitted surface ends in a proper degenerate apex row instead of a
    // parasitic inverted tip ending in an unweldable ring.
    // Both blocks below move the sample grid OFF the pointwise offset on
    // purpose. Recording that is what lets `offset_surface_measured` decline to
    // report a designed divergence as a fit error.
    let mut reparameterised = false;
    if parameters_v.len() == 2 && parameters_u.len() >= 3 {
        let centroid = |column: usize| {
            let mut sum = Vec3::default();
            for row in &samples {
                sum = sum.add(row[column]);
            }
            sum.scale(1.0 / samples.len() as f64)
        };
        let near_centroid = centroid(0);
        let far_centroid = centroid(1);
        let mut inverted = true;
        let mut pinch_fraction = 0.0f64;
        let mut near_mean = 0.0f64;
        let mut far_mean = 0.0f64;
        for row in &samples {
            let near_radial = row[0].sub(near_centroid);
            let far_radial = row[1].sub(far_centroid);
            let near_len = near_radial.length();
            let far_len = far_radial.length();
            if near_len <= 1e-9 || far_len <= 1e-9 {
                inverted = false;
                break;
            }
            if near_radial.dot(far_radial) >= 0.0 {
                inverted = false;
                break;
            }
            pinch_fraction += near_len / (near_len + far_len) / samples.len() as f64;
            near_mean += near_len / samples.len() as f64;
            far_mean += far_len / samples.len() as f64;
        }
        if inverted {
            // Pull the crossed (smaller-ring, past-the-pinch) end back to the
            // pinch point on each ruling.
            reparameterised = true;
            let retrim_far = far_mean <= near_mean;
            for row in &mut samples {
                let near = row[0];
                let far = row[1];
                let pinch = near.add(far.sub(near).scale(pinch_fraction));
                if retrim_far {
                    row[1] = pinch;
                } else {
                    row[0] = pinch;
                }
            }
        }
        // RULED EXTENSION: `planar_extension` is a no-op for curved carriers
        // above, but a cone/cylinder lateral joined at a reflex edge needs
        // its offset skin to GROW past the source rim exactly like a plane
        // (a cylinder piercing a cone: the two offsets only meet past both
        // cloned rims). A linear-v net is ruled — stretching each sampled
        // ruling beyond both ends stays ON the same surface, so the fitted
        // carrier keeps its parameterization (knots/pcurves untouched) while
        // its world image (and with it the cloned trim's image) inflates.
        if planar_extension > 0.0 && !inverted {
            let mut min_ruling = f64::MAX;
            let mut back_allowance = f64::MAX;
            let mut forward_allowance = f64::MAX;
            let mut extendable = true;
            for row in &samples {
                let ruling = row[1].sub(row[0]);
                let length = ruling.length();
                min_ruling = min_ruling.min(length);
                // Radii about the row centroids expose a converging (conic)
                // ruling sheaf; the extension must stop short of its apex or
                // the sheet folds through it.
                let near_radial = row[0].sub(near_centroid).length();
                let far_radial = row[1].sub(far_centroid).length();
                if (far_radial - near_radial).abs() > 1e-9 {
                    let apex_at = near_radial / (near_radial - far_radial);
                    if (-1e-9..=1.0 + 1e-9).contains(&apex_at) {
                        // Apex inside the span: degenerate sheet, do not touch.
                        extendable = false;
                        break;
                    }
                    if apex_at < 0.0 {
                        back_allowance = back_allowance.min(0.9 * -apex_at);
                    } else {
                        forward_allowance = forward_allowance.min(0.9 * (apex_at - 1.0));
                    }
                }
            }
            if extendable && min_ruling > 1e-9 {
                reparameterised = true;
                let stretch = planar_extension / min_ruling;
                let back = stretch.min(back_allowance);
                let forward = stretch.min(forward_allowance);
                for row in &mut samples {
                    let ruling = row[1].sub(row[0]);
                    row[0] = row[0].sub(ruling.scale(back));
                    row[1] = row[1].add(ruling.scale(forward));
                }
            }
        }
    }
    let weights = source
        .control_points
        .iter()
        .map(|row| row.iter().map(|point| point.w).collect::<Vec<_>>())
        .collect::<Vec<_>>();
    let lane = if reparameterised {
        OffsetSurfaceLane::Reparameterised
    } else {
        OffsetSurfaceLane::Fit
    };
    Ok((
        NurbsSurface::new(
            source.degree_u,
            source.degree_v,
            source.knots_u.clone(),
            source.knots_v.clone(),
            interpolate_tensor(
                &knot_u,
                &knot_v,
                &parameters_u,
                &parameters_v,
                &samples,
                &weights,
            )?,
        )?,
        lane,
    ))
}

fn mapped_pcurve_polyline(
    surface: &NurbsSurface,
    pcurve: &NurbsCurve,
    degenerate: bool,
) -> Result<(Vec<Vec3>, Vec<f64>), String> {
    let [start, end] = pcurve.domain()?;
    let evaluate = |fraction: f64| {
        let uv = pcurve.evaluate(start + (end - start) * fraction)?;
        surface.evaluate(uv.x, uv.y)
    };
    let first = evaluate(0.0)?;
    let last = evaluate(1.0)?;
    if degenerate {
        return Ok((vec![first, last], vec![0.0, 1.0]));
    }
    fn append(
        evaluate: &impl Fn(f64) -> Result<Vec3, String>,
        a_fraction: f64,
        a: Vec3,
        b_fraction: f64,
        b: Vec3,
        depth: usize,
        parameters: &mut Vec<f64>,
        points: &mut Vec<Vec3>,
    ) -> Result<(), String> {
        let fractions =
            [0.25, 0.5, 0.75].map(|local| a_fraction + (b_fraction - a_fraction) * local);
        let samples = fractions
            .map(evaluate)
            .into_iter()
            .collect::<Result<Vec<_>, String>>()?;
        let deviation = samples
            .iter()
            .enumerate()
            .map(|(index, point)| {
                point
                    .sub(a.add(b.sub(a).scale((index + 1) as f64 * 0.25)))
                    .length()
            })
            .fold(0.0, f64::max);
        if deviation <= 5e-4 || depth >= 10 {
            parameters.push(b_fraction);
            points.push(b);
            return Ok(());
        }
        append(
            evaluate,
            a_fraction,
            a,
            fractions[1],
            samples[1],
            depth + 1,
            parameters,
            points,
        )?;
        append(
            evaluate,
            fractions[1],
            samples[1],
            b_fraction,
            b,
            depth + 1,
            parameters,
            points,
        )
    }
    let mut parameters = vec![0.0];
    let mut points = vec![first];
    append(
        &evaluate,
        0.0,
        first,
        1.0,
        last,
        0,
        &mut parameters,
        &mut points,
    )?;
    Ok((points, parameters))
}

/// Everything an offset carrier's construction MEASURED about itself.
///
/// The measured half of `occt-offset-algorithms.md` §6.1's ADOPT, in the place
/// this kernel can put it without a durable-format change: alongside the
/// transient construction result, never as a field on a
/// [`crate::BrepSolid`] record. `io/snapshot.rs` is a documented durable format
/// and `SOLID_CODEC_VERSION` a versioned wire layout; persisting per-entity
/// tolerances is real, planned, and separately designed
/// (`docs/developer/kernel-plans/per-entity-tolerances.md` S3). This lands the
/// measurement with no format churn at all.
///
/// Every number here is a RECORD. None of it widens a band — see
/// [`MeasuredTolerance`]'s direction rule.
#[derive(Clone, Debug)]
pub struct CarrierDeviation {
    /// The derived band every measurement below was judged against:
    /// [`crate::offset_construction_band`] of the source solid's extent.
    pub band: f64,
    /// Which branch built the carrier surface.
    pub lane: OffsetSurfaceLane,
    /// The carrier surface's own fit error, when the lane has one.
    pub surface: Option<MeasuredTolerance>,
    /// `max_t ‖C_3d(t) − S_off(p(t))‖` per carrier edge id, folded over every
    /// coedge that references the edge — OCCT's `FillEdgeData` rule
    /// (`BRepOffset_SimpleOffset.cxx:296-310`), which takes the maximum over
    /// **every** adjacent face rather than the first one.
    pub edges: Vec<(u64, MeasuredTolerance)>,
    /// Per carrier vertex id, propagated from the incident edge ends by
    /// [`crate::vertex_tolerance_from_edges`] — which is also where the verdict
    /// on OCCT's 1.001 inflation factor is recorded.
    pub vertices: Vec<(u64, f64)>,
}

impl CarrierDeviation {
    /// The worst thing the construction did, against the tightest band it
    /// faced. `None` only when there was nothing at all to measure.
    pub fn worst(&self) -> Option<MeasuredTolerance> {
        MeasuredTolerance::worst(
            self.surface
                .into_iter()
                .chain(self.edges.iter().map(|(_, measured)| *measured))
                .chain(
                    self.vertices
                        .iter()
                        .map(|(_, gap)| MeasuredTolerance::new(*gap, self.band)),
                ),
        )
    }

    /// The entities whose measured deviation exceeded the derived band — the
    /// interesting case, and the only one any gate acts on.
    pub fn exceedances(&self) -> Vec<String> {
        let mut out = Vec::new();
        if let Some(surface) = self.surface {
            if surface.exceeds_band() {
                out.push(format!("carrier surface fit {}", surface.describe()));
            }
        }
        for (id, measured) in &self.edges {
            if measured.exceeds_band() {
                out.push(format!("edge {id} {}", measured.describe()));
            }
        }
        for (id, gap) in &self.vertices {
            let measured = MeasuredTolerance::new(*gap, self.band);
            if measured.exceeds_band() {
                out.push(format!("vertex {id} {}", measured.describe()));
            }
        }
        out
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct OffsetFaceCarrier {
    pub vertices: Vec<VertexRecord>,
    pub edges: Vec<EdgeRecord>,
    pub face: FaceRecord,
    /// What the construction measured about itself, or `None` when it was built
    /// through the unmeasured [`offset_face_carrier`] entry point.
    ///
    /// `#[serde(skip)]` on purpose: this struct crosses the wasm ABI as JSON
    /// (`abi/modeling_b.rs:500`), and a measurement is a diagnostic about a
    /// build, not part of the carrier the caller asked for. Skipping it keeps
    /// that payload byte-identical.
    #[serde(skip)]
    pub deviation: Option<CarrierDeviation>,
}

fn claim_vertex_image(
    source_id: u64,
    point: Vec3,
    vertex_images: &mut HashMap<u64, u64>,
    vertices: &mut Vec<VertexRecord>,
    next_id: &mut u64,
) -> u64 {
    if let Some(id) = vertex_images.get(&source_id) {
        return *id;
    }
    let id = *next_id;
    *next_id += 1;
    vertices.push(VertexRecord { id, point });
    vertex_images.insert(source_id, id);
    id
}

pub fn offset_face_carrier(
    solid: &BrepSolid,
    face_id: u64,
    distance: f64,
    planar_extension: f64,
) -> Result<OffsetFaceCarrier, String> {
    offset_face_carrier_impl(solid, face_id, distance, planar_extension, false)
}

/// [`offset_face_carrier`], with every entity it builds measured against the
/// deviation it was meant to reproduce.
///
/// The carrier is bit-identical to [`offset_face_carrier`]'s — same body, same
/// arithmetic, in the same order — with a read-only measurement pass appended.
/// Three quantities land in [`CarrierDeviation`]:
///
/// * the carrier SURFACE's fit against the pointwise offset it interpolates
///   ([`offset_surface_measured`]);
/// * each carrier EDGE's 3D curve against the locus its pcurve traces on that
///   surface — the trim boundary is built by sampling exactly that composition
///   and interpolating the images, so this is the construction's own claim,
///   measured rather than assumed;
/// * each carrier VERTEX, propagated from the incident edge ends.
///
/// The interesting output is [`CarrierDeviation::exceedances`]: an entity whose
/// measured deviation is worse than the size-derived band assumed. That is a
/// construction that went wrong in a way the derived band alone cannot see, and
/// it is the case a caller should refuse on rather than ship.
pub fn offset_face_carrier_measured(
    solid: &BrepSolid,
    face_id: u64,
    distance: f64,
    planar_extension: f64,
) -> Result<OffsetFaceCarrier, String> {
    offset_face_carrier_impl(solid, face_id, distance, planar_extension, true)
}

/// The measured deviations of one built carrier: surface fit, per edge, per
/// vertex.
///
/// Read-only over what the construction produced. The edge measurement is
/// [`crate::measure_edge_against_pcurve_image`] — validate's own
/// `adaptive_coedge_error` floored by a span-midpoint pass, because the sampler
/// alone is aliased against exactly the curves this construction builds (see
/// that module's doc) — taken against the far tighter
/// [`crate::offset_construction_band`] instead of the vendor-forgiving
/// `pcurve_acceptance` validate will use later.
fn measure_carrier(
    surface: &NurbsSurface,
    vertices: &[VertexRecord],
    edges: &[EdgeRecord],
    loops: &[LoopRecord],
    lane: OffsetSurfaceLane,
    surface_fit: Option<MeasuredTolerance>,
    band: f64,
) -> Result<CarrierDeviation, String> {
    let edge_by_id: HashMap<u64, &EdgeRecord> = edges.iter().map(|edge| (edge.id, edge)).collect();
    // Fold over coedges, not edges: a seam edge is referenced twice with two
    // different pcurves, and OCCT's `FillEdgeData` takes the maximum over every
    // adjacent face for exactly that reason.
    let mut per_edge: HashMap<u64, MeasuredTolerance> = HashMap::default();
    for loop_record in loops {
        for coedge in &loop_record.coedges {
            let Some(edge) = edge_by_id.get(&coedge.edge_id) else {
                continue;
            };
            let measured = measure_edge_against_pcurve_image(
                surface,
                &coedge.pcurve,
                edge,
                coedge.forward,
                band,
            )?;
            per_edge
                .entry(edge.id)
                .and_modify(|existing| *existing = existing.worse_of(measured))
                .or_insert(measured);
        }
    }

    let mut measured_edges: Vec<(u64, MeasuredTolerance)> = per_edge.into_iter().collect();
    measured_edges.sort_by_key(|(id, _)| *id);
    let deviation_of: HashMap<u64, f64> = measured_edges
        .iter()
        .map(|(id, measured)| (*id, measured.deviation()))
        .collect();

    // Edge ENDS by the vertex they claim, built once. A degenerate edge claims
    // the same vertex at both ends and contributes both, which is right: the
    // question is how far every representation meeting there actually lands.
    let mut ends_at: HashMap<u64, Vec<(&EdgeRecord, f64)>> = HashMap::default();
    for edge in edges {
        ends_at
            .entry(edge.start_vertex_id)
            .or_default()
            .push((edge, edge.t0));
        ends_at
            .entry(edge.end_vertex_id)
            .or_default()
            .push((edge, edge.t1));
    }

    let mut measured_vertices = Vec::with_capacity(vertices.len());
    for vertex in vertices {
        let mut gaps = Vec::new();
        let mut incident = Vec::new();
        for (edge, parameter) in ends_at.get(&vertex.id).into_iter().flatten() {
            gaps.push(vertex_endpoint_gap(
                vertex.point,
                edge.curve.evaluate(*parameter)?,
            ));
            incident.push(deviation_of.get(&edge.id).copied().unwrap_or(0.0));
        }
        measured_vertices.push((vertex.id, vertex_tolerance_from_edges(gaps, incident)));
    }

    Ok(CarrierDeviation {
        band,
        lane,
        surface: surface_fit,
        edges: measured_edges,
        vertices: measured_vertices,
    })
}

fn offset_face_carrier_impl(
    solid: &BrepSolid,
    face_id: u64,
    distance: f64,
    planar_extension: f64,
    measure: bool,
) -> Result<OffsetFaceCarrier, String> {
    let source = solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .find(|face| face.id == face_id)
        .ok_or_else(|| format!("offset_face_carrier: missing face {face_id}"))?;
    // The band is derived from the SOURCE SOLID's extent, matching every other
    // direct-edit/offset site (`face_offset.rs:103` and its siblings all take
    // `solid_model_scale`). `occt-offset-algorithms.md` §7 item 8 / UNKNOWN 3
    // proposes keying such bands on the FACE's own extent instead; that is a
    // measurement to make before switching, not a change to smuggle in here.
    let band = offset_construction_band(solid_model_scale(solid));
    let (surface, lane, surface_fit) = if measure {
        let measured = offset_surface_measured(source, distance, planar_extension, band)?;
        (measured.surface, measured.lane, measured.fit)
    } else {
        let (surface, lane) = offset_surface_with_lane(source, distance, planar_extension)?;
        (surface, lane, None)
    };
    let source_edges = solid
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let source_vertices = solid
        .vertices
        .iter()
        .map(|vertex| (vertex.id, vertex))
        .collect::<HashMap<_, _>>();
    let mut vertices = Vec::new();
    let mut vertex_images = HashMap::default();
    let mut edges = Vec::new();
    let mut edge_images = HashMap::default();
    let mut loops = Vec::new();
    let mut next_id = 1u64;

    for source_loop in &source.loops {
        let mut coedges = Vec::new();
        for source_coedge in &source_loop.coedges {
            let source_edge = source_edges
                .get(&source_coedge.edge_id)
                .ok_or_else(|| "offset_face_carrier: missing source edge".to_string())?;
            let (source_start, source_end) = if source_coedge.forward {
                (source_edge.start_vertex_id, source_edge.end_vertex_id)
            } else {
                (source_edge.end_vertex_id, source_edge.start_vertex_id)
            };
            if !source_vertices.contains_key(&source_start)
                || !source_vertices.contains_key(&source_end)
            {
                return Err("offset_face_carrier: missing source vertex".into());
            }
            // Map even DEGENERATE source edges through the full polyline: a
            // cone apex's image on the offset surface is a genuine CIRCLE
            // (radius d·cos half-angle), not a point — shortcutting to the
            // two endpoints would collapse the ring and leave the carrier's
            // topology inconsistent with its surface. Edges whose image truly
            // collapses (sphere poles, planar corners) still interpolate to a
            // point-sized curve and keep their degenerate flag below.
            // Map even DEGENERATE source edges through the full polyline: an
            // EXTERIOR cone offset turns the apex point into a genuine RING
            // (radius d·cos half-angle) — shortcutting to the endpoints would
            // collapse it and leave the carrier topology inconsistent with
            // its surface (and the ring imprint would be dropped as
            // boundary-coincident with a "degenerate" edge). Images that
            // truly collapse (sphere poles; interior apexes after the pinch
            // retrim) stay degenerate below. The threshold scales with the
            // offset distance: a real ring measures ~d·cos α, while fitted
            // pole rows wobble ~1e-4 absolute.
            let (points, parameters) =
                mapped_pcurve_polyline(&surface, &source_coedge.pcurve, false)?;
            let collapse_tolerance = 1e-6f64.max(distance.abs() * 1e-2);
            let image_collapsed = points
                .iter()
                .all(|point| point.sub(points[0]).length() <= collapse_tolerance);
            let (edge_id, forward) =
                if let Some((edge_id, edge_start_vertex_id, creator_forward)) =
                    edge_images.get(&source_edge.id)
                {
                    if source_start == source_end {
                        // A CLOSED source edge (a seam of a periodic face: both
                        // ends are the same vertex) is referenced twice by the
                        // same loop, once per seam side, and the two references
                        // traverse it in OPPOSITE senses — that is what closes
                        // the loop. The endpoint test below cannot see that:
                        // both ends map to the same vertex image, so it answers
                        // `true` for both references and the returning coedge
                        // comes back mis-oriented.
                        //
                        // Measured on a full torus (one vertex, two seam edges):
                        // the source records `forward: false` on the two
                        // returning coedges and validates clean, while the
                        // carrier recorded `forward: true` on both and its rim
                        // edge measured 12.5 — a whole part diameter — against
                        // its own composed pcurve image. The measured tolerance
                        // this slice adds is what surfaced it; no existing gate
                        // reaches this shape.
                        //
                        // The source coedge's own sense is the answer: the image
                        // edge runs along the CREATING coedge's pcurve, so a
                        // later reference runs with it exactly when the two
                        // source coedges traverse the source edge the same way.
                        (*edge_id, source_coedge.forward == *creator_forward)
                    } else {
                        // UNCHANGED for every open edge: the image edge's start
                        // vertex identifies which way this coedge runs.
                        (
                            *edge_id,
                            vertex_images.get(&source_start) == Some(edge_start_vertex_id),
                        )
                    }
                } else {
                    let curve = if image_collapsed {
                        NurbsCurve::new(
                            1,
                            vec![0.0, 0.0, 1.0, 1.0],
                            vec![
                                Vec4::from_point(points[0], 1.0),
                                Vec4::from_point(points[0], 1.0),
                            ],
                        )?
                    } else {
                        interpolate_curve(&points, 1, &parameters)?
                    };
                    let start_vertex_id = claim_vertex_image(
                        source_start,
                        points[0],
                        &mut vertex_images,
                        &mut vertices,
                        &mut next_id,
                    );
                    let end_vertex_id = claim_vertex_image(
                        source_end,
                        points[points.len() - 1],
                        &mut vertex_images,
                        &mut vertices,
                        &mut next_id,
                    );
                    let id = next_id;
                    next_id += 1;
                    let domain = curve.domain()?;
                    edges.push(EdgeRecord {
                        id,
                        curve,
                        t0: domain[0],
                        t1: domain[1],
                        start_vertex_id,
                        end_vertex_id,
                        // Degenerate only if the IMAGE collapsed too — a cone
                        // apex maps to a real ring on the offset surface and
                        // must carry a real closed edge.
                        degenerate: source_edge.degenerate && image_collapsed,
                        // Image of a named source edge on the offset carrier;
                        // suffixed so it cannot collide with the source edge
                        // when both faces survive into one solid.
                        name: source_edge
                            .name
                            .as_ref()
                            .map(|name| format!("{name}_Offset")),
                    });
                    edge_images.insert(
                        source_edge.id,
                        (id, start_vertex_id, source_coedge.forward),
                    );
                    (id, true)
                };
            let id = next_id;
            next_id += 1;
            coedges.push(CoedgeRecord {
                id,
                edge_id,
                forward,
                pcurve: source_coedge.pcurve.clone(),
            });
        }
        let id = next_id;
        next_id += 1;
        loops.push(LoopRecord { id, coedges });
    }
    let deviation = if measure {
        Some(measure_carrier(
            &surface,
            &vertices,
            &edges,
            &loops,
            lane,
            surface_fit,
            band,
        )?)
    } else {
        None
    };
    Ok(OffsetFaceCarrier {
        vertices,
        edges,
        face: FaceRecord {
            id: next_id,
            surface,
            same_sense: source.same_sense,
            loops,
            name: source.name.as_ref().map(|name| format!("{name}_Offset")),
        },
        deviation,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{make_box_brep, make_cylinder_brep};

    /// A CLOSED source edge (a periodic face's seam) is referenced twice by the
    /// same loop with OPPOSITE senses, and the carrier must reproduce that.
    ///
    /// Before this was fixed the endpoint test could not see the difference —
    /// both ends of a closed edge map to the same vertex image, so it answered
    /// `forward: true` for both references. The measured tolerance is what found
    /// it: the returning rim edge of a full torus measured 12.5 against its own
    /// composed pcurve image, a whole part diameter, on a part 13 across. The
    /// source solid records `forward: false` on those coedges and validates
    /// clean, so the source is the oracle here, not an opinion.
    #[test]
    fn a_full_torus_carrier_reproduces_the_source_seam_senses() {
        let solid =
            crate::make_torus_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 1.5).unwrap();
        assert!(
            solid.validate().is_empty(),
            "the source torus is the oracle and must be clean"
        );
        let face = &solid.shells[0].faces[0];
        let source_senses: Vec<bool> = face
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
            .map(|coedge| coedge.forward)
            .collect();
        assert_eq!(
            source_senses,
            vec![true, true, false, false],
            "a full torus's two seam edges are each traversed both ways"
        );

        let carrier = offset_face_carrier_measured(&solid, face.id, 0.25, 0.0).unwrap();
        let carrier_senses: Vec<bool> = carrier
            .face
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
            .map(|coedge| coedge.forward)
            .collect();
        assert_eq!(
            carrier_senses, source_senses,
            "the carrier copies the source topology, senses included"
        );

        // And the measurement agrees: every rim edge now sits within the
        // polyline sag of its own image instead of a part diameter away.
        let deviation = carrier.deviation.expect("measured");
        for (id, measured) in &deviation.edges {
            assert!(
                measured.deviation() < 1e-3,
                "carrier edge {id} deviates {:.3e} from its pcurve image",
                measured.deviation()
            );
        }
    }

    /// Measuring is a read-only pass: the carrier it returns must be the one the
    /// unmeasured entry point returns, byte for byte.
    ///
    /// This is the per-call unit form of the slice's bit-identity claim; the
    /// corpus form is `examples/retrim_bitidentity_probe.rs`.
    #[test]
    fn measuring_a_carrier_cannot_change_it() {
        let cases: Vec<(&str, BrepSolid)> = vec![
            ("box", make_box_brep(Vec3::default(), 20.0, 20.0, 4.0).unwrap()),
            (
                "cylinder",
                make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 12.0).unwrap(),
            ),
            (
                "cone",
                crate::make_cone_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 2.5, 10.0)
                    .unwrap(),
            ),
            (
                "sphere",
                crate::make_sphere_brep(Vec3::default(), 5.0, Vec3::new(0.0, 0.0, 1.0)).unwrap(),
            ),
        ];
        for (label, solid) in cases {
            let face_ids: Vec<u64> = solid
                .shells
                .iter()
                .flat_map(|shell| &shell.faces)
                .map(|face| face.id)
                .collect();
            for face_id in face_ids {
                for distance in [0.25, -0.25] {
                    for extension in [0.0, 0.5] {
                        let plain = offset_face_carrier(&solid, face_id, distance, extension);
                        let measured =
                            offset_face_carrier_measured(&solid, face_id, distance, extension);
                        match (plain, measured) {
                            (Ok(plain), Ok(measured)) => assert_eq!(
                                serde_json::to_string(&plain).unwrap(),
                                serde_json::to_string(&measured).unwrap(),
                                "{label} face {face_id} d={distance} ext={extension} moved"
                            ),
                            (Err(plain), Err(measured)) => assert_eq!(
                                plain, measured,
                                "{label} face {face_id} refusal text moved"
                            ),
                            (plain, measured) => panic!(
                                "{label} face {face_id}: outcomes disagree ({:?} vs {:?})",
                                plain.is_ok(),
                                measured.is_ok()
                            ),
                        }
                    }
                }
            }
        }
    }

    /// The lane is what tells a measurement whether a pointwise comparison is
    /// even the right question — the extension and the pinch retrim move the
    /// result off the pointwise offset on purpose.
    #[test]
    fn the_surface_lane_names_the_branch_that_ran() {
        let plate = make_box_brep(Vec3::default(), 20.0, 20.0, 4.0).unwrap();
        let plane = &plate.shells[0].faces[0];
        assert_eq!(
            offset_surface_measured(plane, 0.25, 0.0, 1e-2).unwrap().lane,
            OffsetSurfaceLane::Affine
        );
        assert_eq!(
            offset_surface_measured(plane, 0.25, 0.5, 1e-2).unwrap().lane,
            OffsetSurfaceLane::Reparameterised,
            "a grown plane no longer names the same point at the same (u, v)"
        );
        assert!(
            offset_surface_measured(plane, 0.25, 0.5, 1e-2)
                .unwrap()
                .fit
                .is_none(),
            "a deliberate divergence is not reported as a fit error"
        );

        let ball = crate::make_sphere_brep(Vec3::default(), 5.0, Vec3::new(0.0, 0.0, 1.0)).unwrap();
        let sphere = &ball.shells[0].faces[0];
        let measured = offset_surface_measured(sphere, 0.25, 0.0, 1e-2).unwrap();
        assert_eq!(measured.lane, OffsetSurfaceLane::Fit);
        let fit = measured.fit.expect("a fit has an error to report");
        assert!(
            fit.deviation() > 0.0 && fit.deviation() < 1e-4,
            "the sphere's collocation fit is small but not exact (got {:.3e})",
            fit.deviation()
        );
    }

    #[test]
    fn affine_offset_is_exact_and_preserves_weights() {
        let solid = make_box_brep(Vec3::default(), 4.0, 4.0, 4.0).unwrap();
        let face = &solid.shells[0].faces[0];
        let offset = offset_surface(face, 0.75, 0.0).unwrap();
        let domain_u = KnotVector::new(face.surface.knots_u.clone(), 1)
            .unwrap()
            .domain();
        let domain_v = KnotVector::new(face.surface.knots_v.clone(), 1)
            .unwrap()
            .domain();
        let u = (domain_u[0] + domain_u[1]) / 2.0;
        let v = (domain_v[0] + domain_v[1]) / 2.0;
        let displacement = offset
            .evaluate(u, v)
            .unwrap()
            .sub(face.surface.evaluate(u, v).unwrap());
        assert!((displacement.length() - 0.75).abs() < 1e-12);
    }

    #[test]
    fn curved_offset_carrier_maps_every_trim_to_new_surface() {
        let solid =
            make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 2.0, 4.0).unwrap();
        let side = &solid.shells[0].faces[0];
        let carrier = offset_face_carrier(&solid, side.id, 0.5, 0.0).unwrap();
        for coedge in carrier
            .face
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
        {
            let edge = carrier
                .edges
                .iter()
                .find(|edge| edge.id == coedge.edge_id)
                .unwrap();
            for fraction in [0.0, 0.3, 0.8, 1.0] {
                let uv = coedge.pcurve.evaluate(fraction).unwrap();
                let on_surface = carrier.face.surface.evaluate(uv.x, uv.y).unwrap();
                let parameter = if coedge.forward {
                    edge.t0 + (edge.t1 - edge.t0) * fraction
                } else {
                    edge.t1 - (edge.t1 - edge.t0) * fraction
                };
                assert!(
                    on_surface
                        .sub(edge.curve.evaluate(parameter).unwrap())
                        .length()
                        < 7e-4
                );
            }
        }
    }
}