BREP_topology 0.26.0

Topology layer of the BREP kernel: B-rep solids, validation, soundness, classification, mass properties and tessellation.
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
pub(super) use crate::curve::interior_knots;
use super::*;

pub fn curve_breaks(curve: &NurbsCurve) -> Result<Vec<f64>, String> {
    let [start, end] = curve.domain()?;
    let mut result = vec![start];
    result.extend(interior_knots(&curve.knots, curve.degree));
    result.push(end);
    Ok(result)
}

pub fn parameter_space_area(face: &FaceRecord) -> Result<f64, String> {
    let mut area = 0.0;
    for loop_record in &face.loops {
        for coedge in &loop_record.coedges {
            for pair in curve_breaks(&coedge.pcurve)?.windows(2) {
                for panel in rule::curve_panels(&coedge.pcurve, pair[0], pair[1])? {
                    for (parameter, weight) in panel.stations() {
                        let (point, tangent) = coedge.pcurve.deriv1(parameter)?;
                        area += weight * 0.5 * (point.x * tangent.y - point.y * tangent.x);
                    }
                }
            }
        }
    }
    Ok(area)
}

/// One pcurve's share of [`parameter_space_area`]: each quadrature station's term, in the
/// order the sum adds them.
fn pcurve_area_terms(pcurve: &NurbsCurve) -> Result<Vec<f64>, String> {
    let mut terms = Vec::new();
    for pair in curve_breaks(pcurve)?.windows(2) {
        for panel in rule::curve_panels(pcurve, pair[0], pair[1])? {
            for (parameter, weight) in panel.stations() {
                let (point, tangent) = pcurve.deriv1(parameter)?;
                terms.push(weight * 0.5 * (point.x * tangent.y - point.y * tangent.x));
            }
        }
    }
    Ok(terms)
}

/// Station terms of the pcurves read so far, keyed by each pcurve's content, for a caller
/// that reads [`parameter_space_area`] again and again on faces that change a few pcurves
/// at a time ([`parameter_space_area_with`]). Hold one for one task; it is not bounded.
#[derive(Default)]
pub struct AreaTerms {
    terms: rustc_hash::FxHashMap<[u64; 2], std::rc::Rc<[f64]>>,
}

impl AreaTerms {
    fn of(&mut self, pcurve: &NurbsCurve) -> Result<std::rc::Rc<[f64]>, String> {
        let mut key = crate::identity_hash::TwoLane::new();
        crate::identity_hash::hash_curve(&mut key, pcurve);
        let key = key.finish();
        if let Some(terms) = self.terms.get(&key) {
            return Ok(terms.clone());
        }
        let terms: std::rc::Rc<[f64]> = pcurve_area_terms(pcurve)?.into();
        self.terms.insert(key, terms.clone());
        Ok(terms)
    }
}

/// [`parameter_space_area`], bit for bit: the same terms added in the same order, each
/// pcurve's terms computed once per content and read from `memo` after that.
pub fn parameter_space_area_with(face: &FaceRecord, memo: &mut AreaTerms) -> Result<f64, String> {
    let mut area = 0.0;
    for loop_record in &face.loops {
        for coedge in &loop_record.coedges {
            for term in memo.of(&coedge.pcurve)?.iter() {
                area += *term;
            }
        }
    }
    Ok(area)
}

/// The escape hatch for [`closed_parameter_space_area`]: `BREP_OPEN_PLANAR_LOOPS=1`
/// reads every planar face's trim loops open again, as they were read before
/// the closing chords, so the two readings are two cells of one binary.
fn open_planar_loops() -> bool {
    debug_flag!("BREP_OPEN_PLANAR_LOOPS")
}

/// Every straight uv chord that closes a trim loop of `face`: from where one
/// coedge's pcurve ends to where the next one's begins, the last back to the
/// first. A loop whose pcurves meet contributes chords of zero length.
pub(super) fn loop_closing_chords(face: &FaceRecord) -> Result<Vec<(Vec3, Vec3)>, String> {
    let mut chords = Vec::new();
    if open_planar_loops() {
        return Ok(chords);
    }
    for loop_record in &face.loops {
        let count = loop_record.coedges.len();
        for index in 0..count {
            let [_, end] = loop_record.coedges[index].pcurve.domain()?;
            let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
            chords.push((
                loop_record.coedges[index].pcurve.evaluate(end)?,
                loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?,
            ));
        }
    }
    Ok(chords)
}

/// [`parameter_space_area`] with every trim loop CLOSED by its chords
/// ([`loop_closing_chords`]). The mass lane of a planar face reads its area
/// here.
///
/// `½∮(u dv − v du)` is independent of where the uv origin sits only over a
/// closed path. Summed over pcurves whose ends miss one another by `δ`, it
/// reads `½(e × δ)` too much or too little at each joint `e`, so the same
/// region read about a translated parameterization gives a different area.
/// The offset shell's planar faces carry such joints — the pcurve ends of the
/// box-bore-sphere shells' opening cork miss their vertices by up to 5.6e-5
/// while the 3D vertices are exact — and on `offsetShellProblem` that alone
/// put the cork's area 6.680e-4 short and the solid's volume 4.453e-3 short of
/// a kernel-free integral. Closed, the same face reads within 1e-8 of it.
///
/// The chord closes what the face record names. The curved lane's trim
/// polygons close the same way, implicitly, which is why a curved face with
/// the same gaps already read true. [`parameter_space_area`] itself stays
/// OPEN: its other callers read its SIGN as a loop's winding, and on a
/// periodic carrier a loop that wraps once is not closed in uv by design.
pub fn closed_parameter_space_area(face: &FaceRecord) -> Result<f64, String> {
    let mut area = parameter_space_area(face)?;
    for (end, start) in loop_closing_chords(face)? {
        area += 0.5 * (crate::polygon::area_term([end.x, end.y], [start.x, start.y]));
    }
    Ok(area)
}

/// The fraction of a face's own extent within which two parameter points are the SAME
/// point of the carrier. It separates a SEAM — where a loop steps from one edge of the
/// domain to the other and both parameters name one 3D point, so their evaluations agree
/// to floating-point rounding — from a trim that misses its own joint.
///
/// Set from the separation the population shows, not picked: across 92,000 readings of
/// this kernel's corpus and both suites, a seam or pole joint's two images agree to
/// ~1e-14 of the face's extent, while the smallest real miss measured is 1.06e-7 — five
/// orders above this bar, and a hundred above double-precision evaluation noise.
const SEAM_COINCIDENCE_REL: f64 = 1e-12;

/// [`parameter_space_area`] with every joint that MISSES closed by a chord, and every
/// joint that steps across a SEAM left open — the reading a caller on a carrier that may
/// be periodic or have a pole needs.
///
/// The affine lane closes every joint ([`closed_parameter_space_area`]) because a plane has
/// neither. A general carrier has both: a loop that wraps a closed direction steps a whole
/// period at one joint by design, and a chord there cancels the sweep — measured on the lib
/// suite, such a reading collapses to 5e-17 — while a pole's degenerate edge steps a whole
/// domain edge that is one point. Both are recognised the same way, and by GEOMETRY rather
/// than by a flag: the two parameters name one point or they do not. `closed_directions()`
/// is analytic-keyed and answers `false` for a FITTED periodic patch, which is exactly the
/// carrier a flag-keyed test would mistake.
///
/// Nothing is evaluated for a joint whose pcurves meet exactly, which is all but 216 of the
/// 15,443 calls one corpus replay makes through here.
pub fn closed_parameter_space_area_on_carrier(face: &FaceRecord) -> Result<f64, String> {
    let mut area = parameter_space_area(face)?;
    let mut coincidence: Option<f64> = None;
    for loop_record in &face.loops {
        let count = loop_record.coedges.len();
        for index in 0..count {
            let [_, end] = loop_record.coedges[index].pcurve.domain()?;
            let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
            let here = loop_record.coedges[index].pcurve.evaluate(end)?;
            let next = loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?;
            if here.x == next.x && here.y == next.y {
                continue;
            }
            let bar = *coincidence.get_or_insert_with(|| {
                SEAM_COINCIDENCE_REL
                    * crate::tolerance::model_scale(
                        face.surface
                            .control_points
                            .iter()
                            .flatten()
                            .filter_map(|control| control.point().ok()),
                    )
            });
            let (image_here, image_next) = (
                face.surface.evaluate_extended(here.x, here.y)?,
                face.surface.evaluate_extended(next.x, next.y)?,
            );
            if image_here.sub(image_next).length() <= bar {
                continue;
            }
            area += 0.5 * (crate::polygon::area_term([here.x, here.y], [next.x, next.y]));
        }
    }
    Ok(area)
}

pub fn is_affine(surface: &NurbsSurface) -> Result<bool, String> {
    // Keep exact metric shortcuts consistent with geometry recognition.
    surface.is_affine()
}

pub fn surface_breaks(surface: &NurbsSurface) -> Result<(Vec<f64>, Vec<f64>), String> {
    let ku = crate::KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
    let kv = crate::KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
    let [u0, u1] = ku.domain();
    let [v0, v1] = kv.domain();
    let mut u = vec![u0];
    u.extend(interior_knots(&surface.knots_u, surface.degree_u));
    u.push(u1);
    let mut v = vec![v0];
    v.extend(interior_knots(&surface.knots_v, surface.degree_v));
    v.push(v1);
    Ok((u, v))
}

pub fn integrand_value(kind: Integrand, point: Vec3, weighted_normal: Vec3) -> f64 {
    let (x, y, z) = (point.x, point.y, point.z);
    match kind {
        Integrand::Area => weighted_normal.length(),
        Integrand::Volume => point.dot(weighted_normal),
        Integrand::VolumeAbout(reference) => point.sub(reference).dot(weighted_normal),
        Integrand::NormalX => weighted_normal.x,
        Integrand::NormalY => weighted_normal.y,
        Integrand::NormalZ => weighted_normal.z,
        Integrand::MomentX => 0.5 * x * x * weighted_normal.x,
        Integrand::MomentY => 0.5 * y * y * weighted_normal.y,
        Integrand::MomentZ => 0.5 * z * z * weighted_normal.z,
        Integrand::SecondXX => x * x * x / 3.0 * weighted_normal.x,
        Integrand::SecondYY => y * y * y / 3.0 * weighted_normal.y,
        Integrand::SecondZZ => z * z * z / 3.0 * weighted_normal.z,
        Integrand::ProductXY => 0.5 * x * x * y * weighted_normal.x,
        Integrand::ProductXZ => 0.5 * x * x * z * weighted_normal.x,
        Integrand::ProductYZ => 0.5 * y * y * z * weighted_normal.y,
        Integrand::MomentAbout(axis, reference) => {
            let d = point.sub(reference);
            let (c, n) = component(d, weighted_normal, axis);
            0.5 * c * c * n
        }
        Integrand::SecondAbout(axis, reference) => {
            let d = point.sub(reference);
            let (c, n) = component(d, weighted_normal, axis);
            c * c * c / 3.0 * n
        }
        Integrand::ProductAbout(pair, reference) => {
            let d = point.sub(reference);
            match pair {
                0 => 0.5 * d.x * d.x * d.y * weighted_normal.x,
                1 => 0.5 * d.x * d.x * d.z * weighted_normal.x,
                _ => 0.5 * d.y * d.y * d.z * weighted_normal.y,
            }
        }
    }
}

/// The `axis` components (0 = x, 1 = y, otherwise z) of `d` and `n`.
fn component(d: Vec3, n: Vec3, axis: usize) -> (f64, f64) {
    match axis {
        0 => (d.x, n.x),
        1 => (d.y, n.y),
        _ => (d.z, n.z),
    }
}


/// Stations per direction in a fixed tensor Gauss block.
pub const GAUSS_COUNT: usize = GAUSS_X.len();

/// The tensor-block station evaluator is on unless `BREP_MASS_TENSOR_BLOCK=0`
/// turns it off. It is bit-identical to the per-station path by construction
/// (`NurbsSurface::deriv1_tensor_each`), so the switch buys nothing but a
/// paired A/B timing of the two in ONE binary under ONE load — which is the
/// only honest way to quote a speed-up on a box that runs eight agents.
pub(super) fn tensor_blocks_on() -> bool {
    switch!("BREP_MASS_TENSOR_BLOCK", true)
}

/// Accumulate every `kind` over ONE parameter cell by tensor Gauss–Legendre,
/// with every station's weight scaled — the trimmed path's full cells carry
/// their winding and the sweep's orientation there. `scale` multiplies FIRST,
/// as every call site has always written the product, so a cell read at the
/// base rule is bit-identical to the one-block rule it replaces.
///
/// Identical arithmetic to the per-station loop it replaces (kept as the
/// tests' reference sweep) — the same stations in the same i-outer/j-inner
/// order, the same `weight_u * weight_v * half_u * half_v * value` product and
/// the same running sum per slot — but each of the block's u and v
/// spans/basis rows is evaluated ONCE rather than once per station it takes
/// part in, which at the base rule is eight rows each instead of sixty-four
/// evaluations.
pub fn integrate_cell_scaled(
    face: &FaceRecord,
    cell: [f64; 4],
    scale: f64,
    kinds: &[Integrand],
    totals: &mut [f64],
    rules: &mut rule::SurfaceRules,
) -> Result<usize, String> {
    // A rational carrier's cell is read on the panels and at the orders its
    // own weights ask for (`rule`); a polynomial one keeps ONE base-order
    // block over the whole cell.
    let (u_panels, v_panels) = rules.panels(&face.surface, cell)?;
    let area_slot = if area_adaptive_on() {
        kinds.iter().position(|kind| matches!(kind, Integrand::Area))
    } else {
        None
    };
    let before = area_slot.map(|slot| totals[slot]);
    let mut stations = 0;
    for u_panel in &u_panels {
        for v_panel in &v_panels {
            integrate_block(face, *u_panel, *v_panel, scale, kinds, totals, rules.station_identity)?;
            stations += u_panel.order * v_panel.order;
        }
    }
    if let (Some(slot), Some(before)) = (area_slot, before) {
        // The area integrand |S_u × S_v| is a square root: no fixed-order
        // rule reads it exactly, polynomial carrier or not, so the cell's
        // AREA alone is re-read adaptively and every other integrand keeps
        // the reading above bit for bit.
        let area = match rules.take_local_area_face(face) {
            // `BREP_MASS_AREA_LOCAL_FRAME`: the same cell of the carrier
            // translated to its own poles, read afresh there (the station
            // memo is keyed by the untranslated carrier, so it is not asked).
            Some(local) => {
                let coarse = cell_area_reading(&local, cell, rules, None, &mut stations)?;
                let area = adaptive_cell_area(&local, cell, coarse, rules, None, AREA_ADAPTIVE_DEPTH, &mut stations)?;
                rules.restore_local_area_face(local);
                area
            }
            None => {
                let coarse = (totals[slot] - before) / scale;
                let identity = rules.station_identity;
                adaptive_cell_area(face, cell, coarse, rules, identity, AREA_ADAPTIVE_DEPTH, &mut stations)?
            }
        };
        totals[slot] = before + scale * area;
    }
    Ok(stations)
}

/// `BREP_MASS_AREA_LOCAL_FRAME` (default on; `=0` restores the global-frame
/// reading): the adaptive AREA re-read evaluates the carrier translated by
/// [`local_frame_reference`] (the centre of its poles, where they stand away
/// from the origin).
///
/// `|S_u × S_v|` does not depend on where the surface stands, but its
/// reading does: the partials are sums of basis-weighted poles, and poles at
/// a distance `D` from the origin leave about `D · ε` of rounding in a
/// partial of the patch's own size. A unit fill patch at `x = 1e6` read its
/// partials ~1e-10 off, ten times the refinement's 1e-11 agreement bar, so
/// every knot cell was quartered to the depth cap (4^6 sub-cells): 16-18 s
/// per three-patch fill face against ~4 ms at the origin, the same at
/// `x = 1e5` (30 s a fill) and already 10x at `x = 1e4`. Translated, the
/// rounding is that of the patch's own size and the bar is met where it is
/// met at the origin. The bar itself is unchanged. Only the area is read
/// there: every other integrand (volume, moments) depends on the frame and
/// keeps its reading bit for bit.
pub fn area_local_frame_on() -> bool {
    switch!("BREP_MASS_AREA_LOCAL_FRAME", true)
}

/// `a - b` when it is exact in floating point (the TwoSum error term is
/// zero), else `None`.
fn exact_difference(a: f64, b: f64) -> Option<f64> {
    let sum = a - b;
    let virtual_b = sum - a;
    let error = (a - (sum - virtual_b)) + (-b - virtual_b);
    (sum.is_finite() && error == 0.0).then_some(sum)
}

/// `w · r` when the product is exact (its FMA residual is zero).
fn exact_product(w: f64, r: f64) -> Option<f64> {
    let product = w * r;
    (product.is_finite() && w.mul_add(r, -product) == 0.0).then_some(product)
}

/// Where the area re-read stands the carrier of `face`: per coordinate, the
/// centre of the poles rounded to a multiple of the power of two at or above
/// their extent (a flat coordinate, extent 0, takes the centre itself), when
/// the poles stand farther from the origin than they spread
/// (`|centre| > extent`) AND every pole's homogeneous shift `x - w·r` is
/// EXACT (the product by its FMA residual, the difference by TwoSum). So the
/// translated carrier is the same surface moved by `r`, never a rounded
/// copy: a carrier reaching from near the origin out to far coordinates
/// keeps its frame (its small spans would not survive the move), and so does
/// a weighted carrier whose `w·r` rounds (a generic weight times a far
/// reference does), which is read in the global frame as before, correct and
/// as slow as before. A unit-weight pole's shift is exact whenever it stands
/// within a factor of two of `r` (Sterbenz). `None` when no coordinate moves,
/// which leaves the reading as it was, bit for bit.
pub(super) fn local_frame_reference(face: &FaceRecord) -> Option<Vec3> {
    let poles = || face.surface.control_points.iter().flatten();
    let mut low = [f64::INFINITY; 3];
    let mut high = [f64::NEG_INFINITY; 3];
    for pole in poles() {
        if !(pole.w > 0.0) {
            return None;
        }
        for (axis, value) in [pole.x, pole.y, pole.z].into_iter().enumerate() {
            let value = value / pole.w;
            low[axis] = low[axis].min(value);
            high[axis] = high[axis].max(value);
        }
    }
    let mut reference = [0.0f64; 3];
    for axis in 0..3 {
        let (centre, extent) = (0.5 * (low[axis] + high[axis]), high[axis] - low[axis]);
        if !(centre.is_finite() && extent.is_finite()) || centre.abs() <= extent {
            continue;
        }
        let candidate = if extent == 0.0 {
            centre
        } else {
            let quantum = 2.0f64.powi(extent.log2().ceil() as i32);
            (centre / quantum).round() * quantum
        };
        let exact = poles().all(|pole| {
            exact_product(pole.w, candidate)
                .and_then(|shift| exact_difference([pole.x, pole.y, pole.z][axis], shift))
                .is_some()
        });
        if exact {
            reference[axis] = candidate;
        }
    }
    (reference != [0.0; 3]).then(|| Vec3::new(reference[0], reference[1], reference[2]))
}

/// `face` with its carrier translated by `-reference`: every homogeneous
/// pole `(x - w·r, y - w·r, z - w·r, w)`, weights, knots, orientation and
/// trims unchanged. `None` when the carrier refuses to rebuild.
pub(super) fn translated_face(face: &FaceRecord, reference: Vec3) -> Option<FaceRecord> {
    let surface = &face.surface;
    let poles = surface
        .control_points
        .iter()
        .map(|row| {
            row.iter()
                .map(|pole| crate::Vec4 {
                    x: pole.x - pole.w * reference.x,
                    y: pole.y - pole.w * reference.y,
                    z: pole.z - pole.w * reference.z,
                    w: pole.w,
                })
                .collect()
        })
        .collect();
    let surface = crate::NurbsSurface::new(
        surface.degree_u,
        surface.degree_v,
        surface.knots_u.clone(),
        surface.knots_v.clone(),
        poles,
    )
    .ok()?;
    let mut local = face.clone();
    local.surface = surface;
    Some(local)
}

/// The area over `cell` (unscaled) on the cell's own panels.
fn cell_area_reading(
    face: &FaceRecord,
    cell: [f64; 4],
    rules: &mut rule::SurfaceRules,
    station_identity: Option<[u64; 2]>,
    stations: &mut usize,
) -> Result<f64, String> {
    let (u_panels, v_panels) = rules.panels(&face.surface, cell)?;
    let mut area = [0.0f64];
    for u_panel in &u_panels {
        for v_panel in &v_panels {
            integrate_block(face, *u_panel, *v_panel, 1.0, &[Integrand::Area], &mut area, station_identity)?;
            *stations += u_panel.order * v_panel.order;
        }
    }
    Ok(area[0])
}

/// `BREP_MASS_AREA_ADAPTIVE` (default on) re-reads each cell's AREA by quadrant
/// refinement until a cell and its four quadrants agree to
/// [`AREA_ADAPTIVE_TOLERANCE`] of the cell's own area. Default ON since the
/// 2026-11-05 promotion (owner: accuracy beats speed); `=0` restores one
/// fixed-rule reading per cell for every integrand.
///
/// brep-bench 2026-11-05: one 8-point block per knot cell read the degree-15
/// Bézier dome's patch (`geometry/high-degree-bezier-dome`) 2.3e-5 small and
/// the twisted sweep's degree 1×3 blade faces (`loft/twisted-thin-blade`)
/// 1.7e-5 large, while their volumes were exact to round-off; refined, they
/// read 1.6e-9 and 1.4e-7 of the closed forms.
pub fn area_adaptive_on() -> bool {
    switch!("BREP_MASS_AREA_ADAPTIVE", true)
}

/// How many times a cell may be quartered while its area is re-read.
const AREA_ADAPTIVE_DEPTH: usize = 6;

/// Relative agreement between a cell's area and the sum of its quadrants'
/// that ends the refinement: a few hundred ulps of the cell's own area.
const AREA_ADAPTIVE_TOLERANCE: f64 = 1e-11;

/// The area over `cell` (unscaled), given the reading `coarse` of the whole
/// cell: the four quadrants are read on their own panels, and any quadrant
/// whose own refinement still moves is quartered again, to `depth` levels.
fn adaptive_cell_area(
    face: &FaceRecord,
    cell: [f64; 4],
    coarse: f64,
    rules: &mut rule::SurfaceRules,
    station_identity: Option<[u64; 2]>,
    depth: usize,
    stations: &mut usize,
) -> Result<f64, String> {
    if depth == 0 {
        return Ok(coarse);
    }
    let [u_lo, u_hi, v_lo, v_hi] = cell;
    let (u_mid, v_mid) = (0.5 * (u_lo + u_hi), 0.5 * (v_lo + v_hi));
    let quadrants = [
        [u_lo, u_mid, v_lo, v_mid],
        [u_mid, u_hi, v_lo, v_mid],
        [u_lo, u_mid, v_mid, v_hi],
        [u_mid, u_hi, v_mid, v_hi],
    ];
    let mut readings = [0.0f64; 4];
    for (index, quadrant) in quadrants.iter().enumerate() {
        readings[index] = cell_area_reading(face, *quadrant, rules, station_identity, stations)?;
    }
    let fine: f64 = readings.iter().sum();
    if (fine - coarse).abs() <= AREA_ADAPTIVE_TOLERANCE * fine.abs() {
        return Ok(fine);
    }
    let mut total = 0.0;
    for (index, quadrant) in quadrants.iter().enumerate() {
        total += adaptive_cell_area(face, *quadrant, readings[index], rules, station_identity, depth - 1, stations)?;
    }
    Ok(total)
}

/// One tensor Gauss block: every station of `u_panel × v_panel`, every kind.
/// The existing tensor rule without area refinement, for an interior cell
/// of an extended trim. The covering-grid caller already used this rule;
/// only repeated surface-basis evaluation is removed.
pub(super) fn integrate_interior_cell_base(
    face: &FaceRecord, cell: [f64; 4], scale: f64, kinds: &[Integrand],
    totals: &mut [f64], rules: &mut rule::SurfaceRules,
) -> Result<Option<usize>, String> {
    let (us, vs) = rules.panels(&face.surface, cell)?;
    if us.len() != 1 || vs.len() != 1 || us[0].order != GAUSS_COUNT || vs[0].order != GAUSS_COUNT {
        return Ok(None);
    }
    integrate_block(face, us[0], vs[0], scale, kinds, totals, rules.station_identity)?;
    Ok(Some(GAUSS_COUNT * GAUSS_COUNT))
}

fn integrate_block(
    face: &FaceRecord,
    u_panel: rule::Panel,
    v_panel: rule::Panel,
    scale: f64,
    kinds: &[Integrand],
    totals: &mut [f64],
    station_identity: Option<[u64; 2]>,
) -> Result<(), String> {
    let half_u = (u_panel.hi - u_panel.lo) * 0.5;
    let middle_u = (u_panel.hi + u_panel.lo) * 0.5;
    let half_v = (v_panel.hi - v_panel.lo) * 0.5;
    let middle_v = (v_panel.hi + v_panel.lo) * 0.5;
    let (u_x, u_w) = u_panel.nodes();
    let (v_x, v_w) = v_panel.nodes();
    let sign = if face.same_sense { 1.0 } else { -1.0 };
    // The base rule, written against the fixed-size tables: its trip count is
    // a constant the compiler unrolls, and reading the nodes through a slice
    // of run-time length instead cost 0.28 µs a station on a 900 000-station
    // import (measured 2026-09-15). Every polynomial carrier is on this path,
    // and it is the arithmetic the one-block rule always did.
    let base_rule = u_x.len() == GAUSS_COUNT && v_x.len() == GAUSS_COUNT;
    if base_rule && tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
        let mut u_stations = [0.0f64; GAUSS_COUNT];
        let mut v_stations = [0.0f64; GAUSS_COUNT];
        for index in 0..GAUSS_COUNT {
            u_stations[index] = middle_u + half_u * GAUSS_X[index];
            v_stations[index] = middle_v + half_v * GAUSS_X[index];
        }
        return super::cell_memo::each(&face.surface, station_identity, &u_stations, &v_stations, |i, j, point, su, sv| {
                let weighted_normal = su.cross(sv).scale(sign);
                for (slot, kind) in kinds.iter().enumerate() {
                    totals[slot] += scale
                        * GAUSS_W[i]
                        * GAUSS_W[j]
                        * half_u
                        * half_v
                        * integrand_value(*kind, point, weighted_normal);
                }
                Ok(())
            });
    }
    if base_rule && !face.surface.deriv1_tensor_supported() {
        for i in 0..GAUSS_COUNT {
            for j in 0..GAUSS_COUNT {
                let (point, su, sv) = face
                    .surface
                    .deriv1(middle_u + half_u * GAUSS_X[i], middle_v + half_v * GAUSS_X[j])?;
                let weighted_normal = su.cross(sv).scale(sign);
                for (slot, kind) in kinds.iter().enumerate() {
                    totals[slot] += scale
                        * GAUSS_W[i]
                        * GAUSS_W[j]
                        * half_u
                        * half_v
                        * integrand_value(*kind, point, weighted_normal);
                }
            }
        }
        return Ok(());
    }
    if tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
        let mut u_stations = [0.0f64; rule::MAX_ORDER];
        let mut v_stations = [0.0f64; rule::MAX_ORDER];
        for index in 0..u_x.len() {
            u_stations[index] = middle_u + half_u * u_x[index];
        }
        for index in 0..v_x.len() {
            v_stations[index] = middle_v + half_v * v_x[index];
        }
        return super::cell_memo::each(
            &face.surface, station_identity,
            &u_stations[..u_x.len()],
            &v_stations[..v_x.len()],
            |i, j, point, su, sv| {
                let weighted_normal = su.cross(sv).scale(sign);
                for (slot, kind) in kinds.iter().enumerate() {
                    totals[slot] += scale
                        * u_w[i]
                        * v_w[j]
                        * half_u
                        * half_v
                        * integrand_value(*kind, point, weighted_normal);
                }
                Ok(())
            },
        );
    }
    for i in 0..u_x.len() {
        for j in 0..v_x.len() {
            let (point, su, sv) = face
                .surface
                .deriv1(middle_u + half_u * u_x[i], middle_v + half_v * v_x[j])?;
            let weighted_normal = su.cross(sv).scale(sign);
            for (slot, kind) in kinds.iter().enumerate() {
                totals[slot] += scale
                    * u_w[i]
                    * v_w[j]
                    * half_u
                    * half_v
                    * integrand_value(*kind, point, weighted_normal);
            }
        }
    }
    Ok(())
}

/// Every `kind` over the whole (untrimmed) knot-span grid in ONE sweep.
/// `solid_mass_properties` asks an untrimmed face for its area and its volume
/// flux; two single-kind sweeps evaluated every station twice for a second
/// integrand that costs a multiply.
pub fn integrate_untrimmed_multi(
    face: &FaceRecord,
    kinds: &[Integrand],
) -> Result<Vec<f64>, String> {
    let (u_breaks, v_breaks) = surface_breaks(&face.surface)?;
    let mut totals = vec![0.0f64; kinds.len()];
    let mut rules = rule::SurfaceRules::new(&face.surface)?;
    for upair in u_breaks.windows(2) {
        for vpair in v_breaks.windows(2) {
            integrate_cell_scaled(
                face,
                [upair[0], upair[1], vpair[0], vpair[1]],
                1.0,
                kinds,
                &mut totals,
                &mut rules,
            )?;
        }
    }
    Ok(totals)
}

/// Every `kind` over the knot-span grid CLIPPED to `rectangle`
/// (`[u_lo, u_hi, v_lo, v_hi]`, inside the domain): the untrimmed sweep's
/// own rules on each cell's intersection with the rectangle, so a face whose
/// single loop is an iso-rectangle (`polygons::iso_rectangle_trim`) is read
/// without the trimmed route's chord polygons, cell quadtree and triangle
/// cubature. Lane O, 2026-10-28: the filleted box's outward offset carried
/// its quarter-cylinder image as such a face (the carrier extended past the
/// walls, the trim v in [0.069, 0.931]) and the trimmed route spent 6.5 ms
/// on 496 full cells and 31 744 stations for a one-span surface; this sweep
/// reads it in a few stations per span.
pub fn integrate_iso_rectangle_multi(
    face: &FaceRecord,
    rectangle: [f64; 4],
    kinds: &[Integrand],
) -> Result<Vec<f64>, String> {
    let (u_breaks, v_breaks) = surface_breaks(&face.surface)?;
    let mut totals = vec![0.0f64; kinds.len()];
    let mut rules = rule::SurfaceRules::new(&face.surface)?;
    for upair in u_breaks.windows(2) {
        let (u_lo, u_hi) = (upair[0].max(rectangle[0]), upair[1].min(rectangle[1]));
        if u_hi <= u_lo {
            continue;
        }
        for vpair in v_breaks.windows(2) {
            let (v_lo, v_hi) = (vpair[0].max(rectangle[2]), vpair[1].min(rectangle[3]));
            if v_hi <= v_lo {
                continue;
            }
            integrate_cell_scaled(face, [u_lo, u_hi, v_lo, v_hi], 1.0, kinds, &mut totals, &mut rules)?;
        }
    }
    Ok(totals)
}

pub fn integrate_untrimmed(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
    Ok(integrate_untrimmed_multi(face, &[kind])?[0])
}

/// A bi-periodic band face (surface closed in both u and v, exactly two loops
/// each a full-wrap constant-cross-level rim) whose trim is NOT expressed with a
/// seam ruling — the fillet-torus bands OCC/STEP emit as two rim circles. Such a
/// face integrates to ZERO on the trimmed path (both loops are degenerate iso
/// lines in parameter space), so it is handled analytically over the seam-cut
/// rectangle instead. See [`biperiodic_band_range`].
#[derive(Clone, Copy)]
pub struct BiBand {
    /// Which parameter is the periodic (full-wrap) one.
    pub(super) p_is_u: bool,
    /// The two rim cross-levels, ascending (q_lo <= q_hi) in the cross param.
    pub q_lo: f64,
    pub q_hi: f64,
    /// True when the material band is the CROSS-SEAM COMPLEMENT of [q_lo, q_hi]
    /// rather than the between-rims strip (mirrors the tessellator's
    /// `close_periodic_trim_dir` orientation test).
    pub(super) complement: bool,
    /// The larger of the two rims' cross-parameter extents, as a fraction of
    /// the cross domain. Zero (to double noise) for the rim circles OCC/STEP
    /// emit as exact iso lines; a few 1e-3 for a rim PROJECTED from a vendor
    /// 3D curve that sits off the carrier, whose pcurve then wanders in the
    /// cross parameter. Decides between the seam-cut rectangle and the
    /// rim-following strip — see [`biperiodic_band_integral`].
    pub rim_wobble: f64,
}

/// Above this fraction of the cross domain a rim is not an iso line, and the
/// band between the rims is integrated along the rims' own pcurves instead
/// of over the rectangle between their mean levels.
///
/// The bar is double noise, not a geometric tolerance: a rim that IS an iso
/// line measures ~1e-15 here, and the two paths agree on it to quadrature
/// precision, so nothing that reads exactly today moves. Set at 1e-9 rather
/// than at the noise floor so a level rim of a large-domain surface is never
/// pushed onto the pcurve walk by rounding alone. `importTestWorking`
/// SOLID_03 face 90: a torus fillet strip whose upper rim was projected from
/// an edge 2.2e-3 mm off the torus wanders over v ∈ [0.746903, 0.750195] —
/// 3.3e-3 of the period — and the rectangle at the mean level 0.748549 read
/// the strip 9.67e-3 mm² (0.09%) small and its origin flux 0.388 low.
pub const BAND_RIM_LEVEL_TOLERANCE_REL: f64 = 1e-9;

/// Detect the bi-periodic band configuration of `face` and choose which of the
/// two regions its rims bound is material. The choice replicates the watertight
/// tessellator (`watertight_tessellation::close_periodic_trim_dir`): the
/// material is to the LEFT of the boundary traversal, so the between-rims strip
/// is kept unless the cross direction wraps AND the rim senses conclusively name
/// the complement. Returns None for anything that is not a clean two-rim band.
pub fn biperiodic_band_range(face: &FaceRecord) -> Result<Option<BiBand>, String> {
    let surface = &face.surface;
    let (closed_u, closed_v) = surface.closed_directions()?;
    if !(closed_u && closed_v) {
        return Ok(None);
    }
    let [u0, u1] = surface.domain_u()?;
    let [v0, v1] = surface.domain_v()?;
    let u_span = (u1 - u0).abs().max(1e-30);
    let v_span = (v1 - v0).abs().max(1e-30);
    // Sample each loop's pcurves (in coedge/traversal order) into (u,v) points.
    // A DEGENERATE loop — a pole/apex vertex whose whole trace collapses to one
    // parameter point (a fat fillet torus touches its outer equator at a single
    // seam point: ABC 00000039 faces 68/70) — is not a band boundary; drop it
    // and keep the two real rims. Anything else leaves the band ambiguous.
    let mut loop_points: Vec<Vec<[f64; 2]>> = Vec::with_capacity(2);
    for loop_record in &face.loops {
        let mut points = Vec::new();
        for coedge in &loop_record.coedges {
            let [d0, d1] = coedge.pcurve.domain()?;
            // 32 per coedge: enough to see a projected rim wander, which a
            // 12-sample read of a smooth pcurve could straddle.
            let samples = 32;
            for k in 0..=samples {
                let t = d0 + (d1 - d0) * k as f64 / samples as f64;
                let p = coedge.pcurve.evaluate(t)?;
                points.push([p.x, p.y]);
            }
        }
        if points.len() < 2 {
            return Ok(None);
        }
        let (mut umin, mut umax, mut vmin, mut vmax) = (
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::INFINITY,
            f64::NEG_INFINITY,
        );
        for pt in &points {
            umin = umin.min(pt[0]);
            umax = umax.max(pt[0]);
            vmin = vmin.min(pt[1]);
            vmax = vmax.max(pt[1]);
        }
        if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
            continue; // degenerate pole/apex loop
        }
        loop_points.push(points);
    }
    if loop_points.len() != 2 {
        return Ok(None);
    }
    for p_is_u in [true, false] {
        let (period, _p0, _p1) = if p_is_u {
            (u1 - u0, u0, u1)
        } else {
            (v1 - v0, v0, v1)
        };
        let (q_dom_lo, q_dom_hi) = if p_is_u { (v0, v1) } else { (u0, u1) };
        let q_extent = (q_dom_hi - q_dom_lo).abs().max(1e-30);
        if !(period > 0.0) {
            continue;
        }
        let coord = |pt: &[f64; 2]| -> (f64, f64) {
            if p_is_u {
                (pt[0], pt[1])
            } else {
                (pt[1], pt[0])
            }
        };
        // (level, winding-direction) for each rim; None if any loop is not a
        // clean full-wrap constant-cross-level rim in this p direction.
        let mut rings: Vec<(f64, i32)> = Vec::with_capacity(2);
        let mut clean = true;
        let mut rim_wobble = 0.0f64;
        for points in &loop_points {
            let (mut pmin, mut pmax, mut qmin, mut qmax) = (
                f64::INFINITY,
                f64::NEG_INFINITY,
                f64::INFINITY,
                f64::NEG_INFINITY,
            );
            for pt in points {
                let (p, q) = coord(pt);
                pmin = pmin.min(p);
                pmax = pmax.max(p);
                qmin = qmin.min(q);
                qmax = qmax.max(q);
            }
            if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
                clean = false;
                break;
            }
            rim_wobble = rim_wobble.max((qmax - qmin) / q_extent);
            let mut net = 0.0;
            for pair in points.windows(2) {
                let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
                if delta > 0.5 * period {
                    delta -= period;
                } else if delta < -0.5 * period {
                    delta += period;
                }
                net += delta;
            }
            let direction = if net > 0.25 * period {
                1
            } else if net < -0.25 * period {
                -1
            } else {
                0
            };
            rings.push((0.5 * (qmin + qmax), direction));
        }
        if !clean || rings.len() != 2 {
            continue;
        }
        rings.sort_by(|a, b| a.0.total_cmp(&b.0));
        let (q_lo, lower_dir) = rings[0];
        let (q_hi, upper_dir) = rings[1];
        let inconclusive = lower_dir == 0 || upper_dir == 0 || lower_dir == upper_dir;
        let between_rims_is_ccw_uv = if p_is_u { lower_dir > 0 } else { lower_dir < 0 };
        let complement = !inconclusive && between_rims_is_ccw_uv != face.same_sense;
        return Ok(Some(BiBand {
            p_is_u,
            q_lo,
            q_hi,
            complement,
            rim_wobble,
        }));
    }
    Ok(None)
}

/// A bi-periodic band (two full-wrap rims) pierced by holes: a caster tread's
/// slots, a signet ring's bore. [`biperiodic_band_range`] reads only a face of
/// exactly two rims, so such a face fell to the trimmed path, where both rims
/// are zero-area iso lines and only the holes were integrated (a caster's
/// band read 680.8 for a numeric 1155.3). Read the band from its two rims as
/// for a plain band, then take each hole away, integrated over its own
/// polygon; a hole that straddles a seam is reconnected across it
/// ([`crate::topology::loop_seam_offsets`]) and integrated through the
/// domain-wrapping evaluator. None (the previous path) unless exactly two
/// loops wind and every other loop is closed in parameter space.
fn band_with_holes_integral(face: &FaceRecord, kinds: &[Integrand]) -> Result<Option<Vec<f64>>, String> {
    let (closed_u, closed_v) = face.surface.closed_directions()?;
    if !(closed_u && closed_v) {
        return Ok(None);
    }
    let [u0, u1] = face.surface.domain_u()?;
    let [v0, v1] = face.surface.domain_v()?;
    let (u_span, v_span) = (u1 - u0, v1 - v0);
    let mut rims = Vec::new();
    let mut holes = Vec::new();
    for (loop_index, loop_record) in face.loops.iter().enumerate() {
        let (mut travel_u, mut travel_v) = (0.0, 0.0);
        for coedge in &loop_record.coedges {
            let [t0, t1] = coedge.pcurve.domain()?;
            let (start, end) = (coedge.pcurve.evaluate(t0)?, coedge.pcurve.evaluate(t1)?);
            travel_u += end.x - start.x;
            travel_v += end.y - start.y;
        }
        let turns = |travel: f64, span: f64| {
            let turns = (travel / span).round();
            ((travel - turns * span).abs() <= 1e-3 * span.abs()).then_some(turns)
        };
        match (turns(travel_u, u_span), turns(travel_v, v_span)) {
            (Some(tu), Some(tv)) if tu == 0.0 && tv == 0.0 => holes.push(loop_index),
            (Some(tu), Some(tv)) if (tu == 0.0) != (tv == 0.0) => rims.push(loop_index),
            _ => return Ok(None),
        }
    }
    if rims.len() != 2 || holes.is_empty() {
        return Ok(None);
    }
    let mut rim_face = face.clone();
    rim_face.loops = rims.iter().map(|&index| face.loops[index].clone()).collect();
    if biperiodic_band_range(&rim_face)?.is_none() {
        return Ok(None);
    }
    let Some(band) = biperiodic_band_integral(&rim_face, kinds)? else {
        return Ok(None);
    };
    let domain = [u0, u1, v0, v1];
    let mut polygons = Vec::with_capacity(holes.len());
    for &loop_index in &holes {
        let coedges = &face.loops[loop_index].coedges;
        let offsets = crate::topology::loop_seam_offsets(coedges, closed_u, closed_v, u_span, v_span)?;
        let mut polygon = TrimPolygon::new(domain);
        for (coedge_index, coedge) in coedges.iter().enumerate() {
            polygon.push_coedge(loop_index, coedge_index, coedge, offsets[coedge_index])?;
        }
        polygon.finish();
        // All holes one way round, so the integrator's orientation read
        // (the sign of the summed area) holds for every one of them.
        if polygon_signed_area(&polygon.points) < 0.0 {
            polygon.reverse();
        }
        polygons.push(polygon);
    }
    // Past the domain by more than rounding, relative to each span: an
    // absolute band would read a whole straddling hole on a tiny domain as
    // in-domain and clip half of it away.
    let (du, dv) = (1e-9 * u_span.abs(), 1e-9 * v_span.abs());
    let extended = polygons.iter().flat_map(|polygon| polygon.points.iter()).any(|point| {
        point[0] < u0 - du || point[0] > u1 + du || point[1] < v0 - dv || point[1] > v1 + dv
    });
    let removed = integrate_trimmed_polys(face, kinds, &polygons, extended, domain)?;
    Ok(Some(band.iter().zip(removed).map(|(band, hole)| band - hole).collect()))
}

/// Gauss–Legendre integral of `kind` over the axis-aligned parameter rectangle
/// \[u_lo,u_hi\]×\[v_lo,v_hi\], subdividing at knot spans clipped to the rectangle.
pub fn integrate_rectangle(
    face: &FaceRecord,
    u_lo: f64,
    u_hi: f64,
    v_lo: f64,
    v_hi: f64,
    kind: Integrand,
) -> Result<f64, String> {
    let (u_full, v_full) = surface_breaks(&face.surface)?;
    let clamp = |breaks: &[f64], lo: f64, hi: f64| -> Vec<f64> {
        let eps = 1e-9 * (hi - lo).abs().max(1e-30);
        let mut out = vec![lo];
        for &b in breaks {
            if b > lo + eps && b < hi - eps {
                out.push(b);
            }
        }
        out.push(hi);
        out
    };
    let u_breaks = clamp(&u_full, u_lo, u_hi);
    let v_breaks = clamp(&v_full, v_lo, v_hi);
    let mut totals = [0.0f64];
    let mut rules = rule::SurfaceRules::new(&face.surface)?;
    for upair in u_breaks.windows(2) {
        for vpair in v_breaks.windows(2) {
            integrate_cell_scaled(
                face,
                [upair[0], upair[1], vpair[0], vpair[1]],
                1.0,
                &[kind],
                &mut totals,
                &mut rules,
            )?;
        }
    }
    Ok(totals[0])
}

/// Integrate each of `kinds` over a bi-periodic band face, or return None when
/// `face` is not such a band. The between-rims strip integrates over the full
/// periodic span × the cross-level strip; the complement is the full-domain
/// integral MINUS that strip (the two tile the closed cross period, so no
/// domain-extended evaluation is needed).
///
/// Two readings of the strip. Rims that ARE iso lines (every rim circle a
/// kernel-built or exactly exported torus carries) integrate over the
/// seam-cut rectangle between their levels. A rim that wanders in the cross
/// parameter — a pcurve PROJECTED from a vendor edge that sits off the
/// carrier — is not at any one level, and the rectangle at its mean level
/// mis-reads the strip by the wander times the rim length; such a band is
/// integrated along the rims' own pcurves by the winding boundary integral
/// (`∮ −G du`, [`super::winding::winding_loops_integral`]), which reads the
/// trim exactly as given. The material choice (`complement`) is the same in
/// both readings; only the strip's quadrature differs.
pub(super) fn biperiodic_band_integral(
    face: &FaceRecord,
    kinds: &[Integrand],
) -> Result<Option<Vec<f64>>, String> {
    if face.loops.len() > 2 && switch!("BREP_MASS_BAND_HOLES", true) {
        if let Some(values) = band_with_holes_integral(face, kinds)? {
            return Ok(Some(values));
        }
    }
    let Some(band) = biperiodic_band_range(face)? else {
        if switch!("BREP_MASS_TORUS_LIFT", true) {
            return super::torus::lifted_band_integral(face, kinds);
        }
        return Ok(None);
    };
    let [u0, u1] = face.surface.domain_u()?;
    let [v0, v1] = face.surface.domain_v()?;
    let (u_lo, u_hi, v_lo, v_hi) = if band.p_is_u {
        (u0, u1, band.q_lo, band.q_hi)
    } else {
        (band.q_lo, band.q_hi, v0, v1)
    };
    let strips: Vec<f64> = if band.rim_wobble <= BAND_RIM_LEVEL_TOLERANCE_REL {
        kinds
            .iter()
            .map(|&kind| integrate_rectangle(face, u_lo, u_hi, v_lo, v_hi, kind))
            .collect::<Result<_, _>>()?
    } else {
        super::winding::winding_loops_integral(face, kinds, band.p_is_u, 1)?
    };
    let mut out = Vec::with_capacity(kinds.len());
    for (&kind, strip) in kinds.iter().zip(strips) {
        let value = if band.complement {
            integrate_untrimmed(face, kind)? - strip
        } else {
            strip
        };
        out.push(value);
    }
    Ok(Some(out))
}