brepkit-math 4.12.7

Vector math, transforms, NURBS, and geometric predicates for brepkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
//! A proof that the march reaches every part of the section of two
//! analytic surfaces that crosses a patch of the first.
//!
//! The patch is cut into leaves, rectangles of its parameters `u` and `v`.
//! On a leaf, `g` is the second surface's signed distance read at the first
//! surface's point. Its second derivatives are bounded by the first
//! surface's derivatives and a bound on the curvature of the second
//! surface's distance near the leaf. A leaf is proved empty where `g` keeps
//! one sign over it. A leaf is simple where one partial derivative of `g`
//! keeps one sign over it, and each of the two edges along the other
//! parameter holds at most one zero of `g`. On a simple leaf, each line
//! along that derivative's parameter holds at most one zero, so the section
//! on the leaf is one arc or none, and each edge holds at most one point of
//! it, where `g` changes sign between the edge's ends. Two simple leaves
//! whose shared edge holds such a point hold one arc of the section, and are
//! linked in one class. Any other leaf is cut, until it is too small for a
//! fit within the linear tolerance of both surfaces to tell its arc from
//! another's.
//!
//! A section loop needs a point where `g`'s derivative along `u` is zero and
//! one where that along `v` is zero, so it cannot lie inside one simple
//! leaf. Each part of the section on the patch that reaches a leaf the fit
//! resolves runs through a class of linked leaves. A class is reached when a
//! marched point lies in it, when a marched curve's fit passes through it,
//! or when a seed from it settles on a marched curve or starts a march.

use std::collections::HashMap;

use super::AnalyticSurface;
use super::section_fit::Carrier;
use crate::MathError;
use crate::aabb::Aabb3;
use crate::madd::Madd;
use crate::vec::{Point3, Vec3};

/// The halvings of a grid cell's side down to the finest leaf.
const DEPTH: u32 = 40;

/// How far the leaves' lattice sits from the seeding grid along `u` and
/// `v`, as shares of a cell: odd counts of the finest steps, so no edge or
/// corner of a leaf falls on a line of the grid. A section of a symmetric
/// pair can run along such a line, or through its crossings, where no
/// edge's sign can be read.
const SHIFT: (f64, f64) = (0.3719, 0.2913);

/// The most leaves a patch is cut into before the proof is given up.
pub(super) const MOST_LEAVES: usize = 1 << 16;

/// How many times the linear tolerance over the sine of the crossing a
/// leaf must reach for a fit within the tolerance to tell its arc from
/// another's: [`Cover::holds`] places a point of a fit to within two and a
/// half times, on each side of a leaf's middle.
const RESOLVED: f64 = 16.0;

/// How many seeds of a class that settle are marched from before it is cut
/// or refused.
const SEED_TRIES: usize = 4;

/// A bound read up by this share, to cover the rounding of its terms.
const UP: f64 = 1.0 + 1e-9;

/// What a leaf holds, as far as its bounds prove.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
    /// Not yet read.
    Open,
    /// No point of the section.
    Empty,
    /// No point of the section that the march could trace: off the region,
    /// or off the second surface's patch.
    Off,
    /// One arc of the section or none; `g`'s derivative along `v` keeps one
    /// sign when `along_u` is false, along `u` when true.
    Simple { along_u: bool },
    /// Too small for a fit within the linear tolerance to resolve its arc
    /// (see [`RESOLVED`]), or past the finest leaf.
    Fine,
    /// Cut into smaller leaves.
    Cut,
}

#[derive(Clone, Copy, Debug)]
struct Leaf {
    u: (u64, u64),
    v: (u64, u64),
    kind: Kind,
    /// Whether the leaf lies inside the region the march follows and on
    /// the second surface's patch, where a simple leaf links to others.
    inside: bool,
    /// A bound on how far a point of the leaf lies from its middle.
    reach: f64,
    /// The first surface's point at the leaf's middle, and the second
    /// surface's distance and normal there.
    middle: Point3,
    gap: f64,
    normal: Vec3,
    /// Whether a seed from the leaf was tried, or a marched curve runs
    /// through it.
    done: bool,
    /// Where a cut leaf's parts start among the leaves, and how many.
    first: usize,
    parts: usize,
}

/// The first surface's point, its two partial derivatives, `g` there, its
/// two partial derivatives, and a bound on the rounding of `g`.
#[derive(Clone, Copy)]
struct Reading {
    p: Point3,
    /// The sine of the angle between the surfaces' normals at `p`.
    sin: f64,
    g: f64,
    gu: f64,
    gv: f64,
    normal: Vec3,
    slack: f64,
}

/// Bounds over a leaf of the lengths of the first surface's first and
/// second partial derivatives.
#[derive(Clone, Copy)]
struct Rates {
    u: f64,
    v: f64,
    uu: f64,
    uv: f64,
    vv: f64,
}

/// Where a ball lies against a box or a patch.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Place {
    Inside,
    Across,
    Outside,
}

/// The leaves of a patch of `a` against `b`, and the classes of simple
/// leaves that hold one arc of the section.
pub(super) struct Cover<'s, 'a> {
    a: &'s AnalyticSurface<'a>,
    b: &'s AnalyticSurface<'a>,
    u_range: (f64, f64),
    v_range: (f64, f64),
    b_v_range: (f64, f64),
    /// Integer steps across the patch along `u` and `v`.
    steps: u64,
    /// Where the leaves' lattice starts along `u` and `v`, in steps.
    shift: (u64, u64),
    u_periodic: bool,
    v_periodic: bool,
    /// The region the faces can meet in, and the larger one the march
    /// follows.
    region: Option<(Aabb3, Aabb3)>,
    floor: f64,
    /// The most leaves the patch is cut into.
    most: usize,
    leaves: Vec<Leaf>,
    roots: HashMap<(u64, u64), usize>,
    corners: HashMap<(u64, u64), Option<(f64, f64)>>,
}

impl<'s, 'a> Cover<'s, 'a> {
    /// The leaves of the cells `kept` (row along `u`, column along `v`) of
    /// a `grid` by `grid` cut of `a`'s patch, cut until each is empty,
    /// simple, set aside or too fine, or `most` are cut. `floor` is the
    /// linear tolerance.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn new(
        a: &'s AnalyticSurface<'a>,
        b: &'s AnalyticSurface<'a>,
        (u_range, v_range): ((f64, f64), (f64, f64)),
        b_v_range: (f64, f64),
        grid: usize,
        kept: &[(usize, usize)],
        region: Option<(Aabb3, Aabb3)>,
        floor: f64,
        most: usize,
    ) -> Self {
        let side = 1_u64 << DEPTH;
        let n = grid as u64;
        let full = |r: (f64, f64)| (r.1 - r.0 - std::f64::consts::TAU).abs() <= 1e-12;
        #[allow(
            clippy::cast_precision_loss,
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss
        )]
        let odd = |share: f64| ((share * side as f64) as u64) | 1;
        let mut cover = Self {
            a,
            b,
            u_range,
            v_range,
            b_v_range,
            steps: n * side,
            shift: (odd(SHIFT.0), odd(SHIFT.1)),
            u_periodic: full(u_range),
            v_periodic: matches!(a, AnalyticSurface::Torus(_)) && full(v_range),
            region,
            floor,
            most,
            leaves: Vec::with_capacity(4 * kept.len()),
            roots: HashMap::with_capacity(kept.len()),
            corners: HashMap::new(),
        };
        for &(i, j) in kept {
            let (i, j) = (i as u64, j as u64);
            for uu in [i * side, (i + 1) * side - 1] {
                for vv in [j * side, (j + 1) * side - 1] {
                    let (Some(u), Some(v)) = (cover.row(uu, true), cover.row(vv, false)) else {
                        continue;
                    };
                    if !cover.roots.contains_key(&(u.0, v.0)) {
                        cover.roots.insert((u.0, v.0), cover.leaves.len());
                        cover.push(u, v);
                    }
                }
            }
        }
        cover.settle_from(0);
        cover
    }

    /// The span of the lattice's cell along `u` (or `v`) that holds the
    /// step `x`: a whole cell where the parameter wraps round, and one cut
    /// at the patch's ends where it does not.
    fn row(&self, x: u64, along_u: bool) -> Option<(u64, u64)> {
        let side = 1_u64 << DEPTH;
        let (shift, periodic) = if along_u {
            (self.shift.0, self.u_periodic)
        } else {
            (self.shift.1, self.v_periodic)
        };
        if periodic {
            let x = if x < shift { x + self.steps } else { x };
            let lo = shift + ((x - shift) >> DEPTH << DEPTH);
            return Some((lo, lo + side));
        }
        if x >= self.steps {
            return None;
        }
        if x < shift {
            return Some((0, shift));
        }
        let lo = shift + ((x - shift) >> DEPTH << DEPTH);
        Some((lo, (lo + side).min(self.steps)))
    }

    fn push(&mut self, u: (u64, u64), v: (u64, u64)) {
        self.leaves.push(Leaf {
            u,
            v,
            kind: Kind::Open,
            inside: false,
            reach: f64::INFINITY,
            middle: Point3::new(0.0, 0.0, 0.0),
            gap: 0.0,
            normal: Vec3::new(0.0, 0.0, 0.0),
            done: false,
            first: 0,
            parts: 0,
        });
    }

    /// Whether every leaf was read: the cuts settled within the budget.
    pub(super) fn complete(&self) -> bool {
        self.leaves.iter().all(|l| l.kind != Kind::Open)
    }

    /// Reads and cuts every open leaf from `start` on, broadest first, up
    /// to the budget: past that the leaves left open prove nothing.
    fn settle_from(&mut self, start: usize) {
        let mut k = start;
        while k < self.leaves.len() && self.leaves.len() <= self.most {
            if self.leaves[k].kind == Kind::Open {
                self.read_leaf(k);
            }
            k += 1;
        }
    }

    #[allow(clippy::cast_precision_loss)]
    fn param(&self, uu: u64, vv: u64) -> (f64, f64) {
        let s = self.steps as f64;
        (
            (self.u_range.1 - self.u_range.0).madd(uu as f64 / s, self.u_range.0),
            (self.v_range.1 - self.v_range.0).madd(vv as f64 / s, self.v_range.0),
        )
    }

    /// The leaf's half widths in `u` and `v`, and a step more, as its
    /// middle rounds to a step.
    #[allow(clippy::cast_precision_loss)]
    fn half_widths(&self, leaf: &Leaf) -> (f64, f64) {
        let s = self.steps as f64;
        let half = |w: u64| (w as f64).madd(0.5, 1.0) / s;
        (
            (self.u_range.1 - self.u_range.0) * half(leaf.u.1 - leaf.u.0),
            (self.v_range.1 - self.v_range.0) * half(leaf.v.1 - leaf.v.0),
        )
    }

    fn read(&self, u: f64, v: f64) -> Option<Reading> {
        let (p, au, av) = frame(self.a, u, v);
        let (g, normal) = self.b.distance(p)?;
        if !(g.is_finite() && normal.length().is_finite()) {
            return None;
        }
        let size = p.x().abs().max(p.y().abs()).max(p.z().abs());
        let slack = 128.0 * f64::EPSILON * (self.a.scale(p) + self.b.scale(p) + size);
        let across = au.cross(av);
        let sin = normal.cross(across).length() / across.length();
        Some(Reading {
            p,
            sin: if sin.is_finite() { sin } else { 0.0 },
            g,
            gu: normal.dot(au),
            gv: normal.dot(av),
            normal,
            slack,
        })
    }

    /// `g` at a corner of the leaves, with the bound on its rounding.
    fn corner(&mut self, uu: u64, vv: u64) -> Option<(f64, f64)> {
        let key = (
            if self.u_periodic { uu % self.steps } else { uu },
            if self.v_periodic { vv % self.steps } else { vv },
        );
        if let Some(&known) = self.corners.get(&key) {
            return known;
        }
        let (u, v) = self.param(uu, vv);
        let value = self.read(u, v).map(|r| (r.g, r.slack));
        self.corners.insert(key, value);
        value
    }

    /// Where the ball of `reach` about `p` lies against the region and the
    /// second surface's patch.
    fn place(&self, p: Point3, reach: f64) -> Place {
        let ball = Aabb3 { min: p, max: p }.expanded(reach);
        let in_region = match self.region {
            None => Place::Inside,
            Some((meet, march)) => {
                if !ball.intersects(meet) {
                    Place::Outside
                } else if inside_box(ball, march) {
                    Place::Inside
                } else {
                    Place::Across
                }
            }
        };
        if in_region == Place::Outside {
            return Place::Outside;
        }
        match (in_region, on_patch(self.b, self.b_v_range, p, reach)) {
            (_, Place::Outside) => Place::Outside,
            (Place::Inside, Place::Inside) => Place::Inside,
            _ => Place::Across,
        }
    }

    #[allow(clippy::similar_names, clippy::too_many_lines)]
    fn read_leaf(&mut self, k: usize) {
        let leaf = self.leaves[k];
        let (hu, hv) = self.half_widths(&leaf);
        let (um, vm) = self.param(
            leaf.u.0 + (leaf.u.1 - leaf.u.0) / 2,
            leaf.v.0 + (leaf.v.1 - leaf.v.0) / 2,
        );
        // Each point of the leaf lies within the half widths times the
        // greatest rates at which the surface moves with each parameter over
        // it: near a ball's pole, where it moves slowly along `u`, a leaf is
        // far smaller than its parameters' spans read at the equator.
        let rates = rates(self.a, hv, vm);
        let reach = hu.madd(rates.u, hv * rates.v) * UP;
        let Some(r) = self.read(um, vm).filter(|_| reach.is_finite()) else {
            self.leaves[k].reach = reach;
            self.cut_or_stop(k, (hu * rates.u, hv * rates.v), reach);
            return;
        };
        {
            let leaf = &mut self.leaves[k];
            leaf.reach = reach;
            leaf.middle = r.p;
            leaf.gap = r.g;
            leaf.normal = r.normal;
        }
        let place = self.place(r.p, reach);
        if place == Place::Outside {
            self.leaves[k].kind = Kind::Off;
            return;
        }
        let gap = r.g.abs() - r.slack;
        if gap > reach {
            self.leaves[k].kind = Kind::Empty;
            return;
        }
        let Some(bend) = self.b.curvature_within(r.p, reach) else {
            self.cut_or_stop(k, (hu * rates.u, hv * rates.v), reach);
            return;
        };
        // Where the surfaces cross at an angle whose sine is at most `s`
        // over the leaf, a fit within the linear tolerance of both places
        // the section only to within that tolerance over `s`: a leaf a few
        // times that is below what the fit resolves, as a leaf below the
        // tolerance is where they cross square. Each normal turns by at most
        // its distance's curvature times the reach.
        let fine = RESOLVED * self.floor;
        let crossing = || {
            self.a
                .distance(r.p)
                .zip(self.a.curvature_within(r.p, reach))
                .map_or(1.0, |((_, na), bend_a)| {
                    let turn = (bend_a * reach).madd(1.0 + bend * reach, bend * reach);
                    (na.cross(r.normal).length() + turn).min(1.0)
                })
        };
        if reach <= fine || (reach * r.sin * 0.5 <= fine && reach * crossing() <= fine) {
            self.leaves[k].kind = Kind::Fine;
            return;
        }
        let luu = rates.u.madd(rates.u * bend, rates.uu) * UP;
        let luv = rates.u.madd(rates.v * bend, rates.uv) * UP;
        let lvv = rates.v.madd(rates.v * bend, rates.vv) * UP;
        let (su, sv) = (64.0 * f64::EPSILON * rates.u, 64.0 * f64::EPSILON * rates.v);
        let second = 0.5 * (luu * hu).madd(hu, (2.0 * luv * hu).madd(hv, lvv * hv * hv));
        let first = (r.gu.abs() + su).madd(hu, (r.gv.abs() + sv) * hv);
        if gap > (first + second) * UP {
            self.leaves[k].kind = Kind::Empty;
            return;
        }
        // An edge along `u` (or `v`) holds at most one zero: none where `g`
        // keeps its sign along it, one at most where its derivative along
        // the edge does.
        let single = |edge: Option<Reading>, along_u: bool| {
            let (rate, slope, half, slack) = if along_u {
                (rates.u, luu, hu, su)
            } else {
                (rates.v, lvv, hv, sv)
            };
            edge.is_some_and(|e| {
                let level = e.g.abs() - e.slack;
                let along = if along_u { e.gu.abs() } else { e.gv.abs() };
                let moves =
                    (rate * half).min((along + slack).madd(half, 0.5 * slope * half * half));
                level > moves * UP || along - slack > slope * half * UP
            })
        };
        let (low, high) = (
            self.param(leaf.u.0, leaf.v.0),
            self.param(leaf.u.1, leaf.v.1),
        );
        if r.gv.abs() - sv > luv.madd(hu, lvv * hv) * UP
            && single(self.read(um, low.1), true)
            && single(self.read(um, high.1), true)
        {
            self.simple(k, false, place);
            return;
        }
        if r.gu.abs() - su > luu.madd(hu, luv * hv) * UP
            && single(self.read(low.0, vm), false)
            && single(self.read(high.0, vm), false)
        {
            self.simple(k, true, place);
            return;
        }
        self.cut_or_stop(k, (hu * rates.u, hv * rates.v), reach);
    }

    fn simple(&mut self, k: usize, along_u: bool, place: Place) {
        let leaf = &mut self.leaves[k];
        leaf.kind = Kind::Simple { along_u };
        leaf.inside = place == Place::Inside;
    }

    /// Cuts the leaf across its longer side, or both where neither is more
    /// than twice the other, or stops where it is below the floor or cannot
    /// be cut.
    fn cut_or_stop(&mut self, k: usize, (wide_u, wide_v): (f64, f64), reach: f64) {
        let leaf = self.leaves[k];
        let can_u = leaf.u.1 - leaf.u.0 >= 2;
        let can_v = leaf.v.1 - leaf.v.0 >= 2;
        let cut_u = can_u && (!wide_u.is_finite() || 2.0 * wide_u >= wide_v);
        let cut_v = can_v && (!wide_v.is_finite() || 2.0 * wide_v >= wide_u);
        if reach <= self.floor || !(cut_u || cut_v) {
            self.leaves[k].kind = Kind::Fine;
            return;
        }
        self.leaves[k].kind = Kind::Cut;
        self.leaves[k].first = self.leaves.len();
        let halves = |r: (u64, u64), cut: bool| {
            if cut {
                let mid = r.0 + (r.1 - r.0) / 2;
                vec![(r.0, mid), (mid, r.1)]
            } else {
                vec![r]
            }
        };
        for u in halves(leaf.u, cut_u) {
            for v in halves(leaf.v, cut_v) {
                self.push(u, v);
            }
        }
        self.leaves[k].parts = self.leaves.len() - self.leaves[k].first;
    }

    /// The sign of `g` at a corner, `None` where rounding or an unread
    /// distance leaves it open.
    fn sign(&mut self, uu: u64, vv: u64) -> Option<bool> {
        let (g, slack) = self.corner(uu, vv)?;
        (g.abs() > slack).then_some(g > 0.0)
    }

    /// Whether `g` surely changes sign between two corners.
    fn changes(&mut self, p: (u64, u64), q: (u64, u64)) -> bool {
        matches!((self.sign(p.0, p.1), self.sign(q.0, q.1)), (Some(x), Some(y)) if x != y)
    }

    /// Whether a simple leaf may hold an arc: its corners' signs are not all
    /// surely alike.
    fn may_hold(&mut self, k: usize) -> bool {
        let Leaf { u, v, .. } = self.leaves[k];
        let signs = [
            self.sign(u.0, v.0),
            self.sign(u.1, v.0),
            self.sign(u.0, v.1),
            self.sign(u.1, v.1),
        ];
        !(signs.iter().all(|s| *s == Some(true)) || signs.iter().all(|s| *s == Some(false)))
    }

    /// The classes of leaves still to be seeded: simple leaves that may
    /// hold an arc, linked where they share an edge holding one point of
    /// it and lie inside both the region and the second patch. A class any
    /// of whose leaves was seeded, or holds a marched point, is left out.
    ///
    /// A fine leaf is not seeded: a part of the section that leaves it runs
    /// through a simple leaf, and one that stays in it is finer than a fit
    /// within the linear tolerance resolves.
    pub(super) fn classes(&mut self) -> Vec<Vec<usize>> {
        let mut parent: Vec<usize> = (0..self.leaves.len()).collect();
        let mut live = vec![false; self.leaves.len()];
        for k in 0..self.leaves.len() {
            live[k] = matches!(self.leaves[k].kind, Kind::Simple { .. }) && self.may_hold(k);
        }
        // Edges of linkable leaves along each line: (line, from, to, leaf,
        // whether the leaf lies before the line).
        let mut across_u: Vec<(u64, u64, u64, usize, bool)> = Vec::new();
        let mut across_v: Vec<(u64, u64, u64, usize, bool)> = Vec::new();
        let (wrap_u, wrap_v) = (self.u_periodic, self.v_periodic);
        let steps = self.steps;
        let line = |x: u64, wrap: bool| if wrap { x % steps } else { x };
        for (k, leaf) in self.leaves.iter().enumerate() {
            if live[k] && leaf.inside && matches!(leaf.kind, Kind::Simple { .. }) {
                across_u.push((line(leaf.u.0, wrap_u), leaf.v.0, leaf.v.1, k, false));
                across_u.push((line(leaf.u.1, wrap_u), leaf.v.0, leaf.v.1, k, true));
                across_v.push((line(leaf.v.0, wrap_v), leaf.u.0, leaf.u.1, k, false));
                across_v.push((line(leaf.v.1, wrap_v), leaf.u.0, leaf.u.1, k, true));
            }
        }
        let mut links = Vec::new();
        for (edges, u_line) in [(&mut across_u, true), (&mut across_v, false)] {
            edges.sort_unstable_by_key(|e| (e.0, e.4, e.1));
            let mut i = 0;
            while i < edges.len() {
                let mut j = i;
                while j < edges.len() && edges[j].0 == edges[i].0 {
                    j += 1;
                }
                let group = &edges[i..j];
                let split = group.partition_point(|e| !e.4);
                let (after, before) = group.split_at(split);
                let (mut x, mut y) = (0, 0);
                while x < before.len() && y < after.len() {
                    let (p, q) = (before[x], after[y]);
                    let (lo, hi) = (p.1.max(q.1), p.2.min(q.2));
                    if hi > lo {
                        links.push((p.0, lo, hi, p.3, q.3, u_line));
                    }
                    if p.2 <= q.2 {
                        x += 1;
                    } else {
                        y += 1;
                    }
                }
                i = j;
            }
        }
        for (at, lo, hi, p, q, u_line) in links {
            let (from, to) = if u_line {
                ((at, lo), (at, hi))
            } else {
                ((lo, at), (hi, at))
            };
            if self.changes(from, to) {
                let (rp, rq) = (find(&mut parent, p), find(&mut parent, q));
                parent[rp] = rq;
            }
        }
        let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
        for k in 0..self.leaves.len() {
            if live[k] {
                let root = find(&mut parent, k);
                groups.entry(root).or_default().push(k);
            }
        }
        let mut out: Vec<Vec<usize>> = groups
            .into_values()
            .filter(|class| class.iter().all(|&k| !self.leaves[k].done))
            .collect();
        for class in &mut out {
            class.sort_unstable();
        }
        out.sort_unstable();
        out
    }

    /// Points to seed a class from: each point where a leaf's edge holds a
    /// zero of `g`, found by halving the edge.
    pub(super) fn seeds(&mut self, class: &[usize]) -> Vec<Point3> {
        let mut out = Vec::new();
        for &k in class {
            let leaf = self.leaves[k];
            let (u, v) = (leaf.u, leaf.v);
            let corners = [(u.0, v.0), (u.1, v.0), (u.1, v.1), (u.0, v.1)];
            let before = out.len();
            for e in 0..4 {
                let (from, to) = (corners[e], corners[(e + 1) % 4]);
                if self.changes(from, to)
                    && let Some(p) = self.zero_between(from, to)
                {
                    out.push(p);
                }
            }
            // A corner whose sign rounding leaves open lies on the section
            // to within that rounding.
            for &(cu, cv) in &corners {
                if self.sign(cu, cv).is_none() {
                    let (pu, pv) = self.param(cu, cv);
                    out.push(frame(self.a, pu, pv).0);
                }
            }
            if out.len() == before {
                out.push(leaf.middle - leaf.normal * (0.5 * leaf.gap));
            }
        }
        out
    }

    /// The first surface's point where `g` is zero on the edge between two
    /// corners where it has opposite signs, by halving.
    fn zero_between(&mut self, from: (u64, u64), to: (u64, u64)) -> Option<Point3> {
        let low = self.sign(from.0, from.1)?;
        let (u, v) = self.zero_on(self.param(from.0, from.1), self.param(to.0, to.1), low)?;
        Some(frame(self.a, u, v).0)
    }

    /// The parameters where `g` is zero between `(u0, v0)`, where its sign
    /// is `low`, and `(u1, v1)`, where it has the other, by halving.
    fn zero_on(&self, (u0, v0): (f64, f64), (u1, v1): (f64, f64), low: bool) -> Option<(f64, f64)> {
        let (mut lo, mut hi) = (0.0_f64, 1.0_f64);
        for _ in 0..64 {
            let mid = f64::midpoint(lo, hi);
            if mid <= lo || mid >= hi {
                break;
            }
            let r = self.read((u1 - u0).madd(mid, u0), (v1 - v0).madd(mid, v0))?;
            if (r.g > 0.0) == low {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        let t = f64::midpoint(lo, hi);
        Some(((u1 - u0).madd(t, u0), (v1 - v0).madd(t, v0)))
    }

    /// A point inside each leaf of a class on its arc: halfway along the
    /// parameter the arc is a graph over, between where it leaves the leaf,
    /// or else the leaf's middle moved onto the section where that lands
    /// inside the leaf, as where the arc ends on a pole.
    pub(super) fn interiors(&mut self, class: &[usize]) -> Vec<Point3> {
        let mut out = Vec::new();
        for &k in class {
            let before = out.len();
            self.interior(k, &mut out);
            if out.len() == before
                && let Some(q) =
                    super::section_fit::settle_on_section(self.a, self.b, self.leaves[k].middle)
                && self.locate(q, 0.0) == Some(k)
            {
                out.push(q);
            }
        }
        out
    }

    fn interior(&mut self, k: usize, out: &mut Vec<Point3>) {
        {
            let leaf = self.leaves[k];
            let Kind::Simple { along_u } = leaf.kind else {
                return;
            };
            let (u, v) = (leaf.u, leaf.v);
            let corners = [(u.0, v.0), (u.1, v.0), (u.1, v.1), (u.0, v.1)];
            let mut ends = Vec::new();
            for e in 0..4 {
                let (from, to) = (corners[e], corners[(e + 1) % 4]);
                if self.changes(from, to)
                    && let Some(low) = self.sign(from.0, from.1)
                    && let Some(end) =
                        self.zero_on(self.param(from.0, from.1), self.param(to.0, to.1), low)
                {
                    ends.push(end);
                }
            }
            let [first, second, ..] = ends[..] else {
                return;
            };
            let (lo, hi) = (self.param(u.0, v.0), self.param(u.1, v.1));
            let (from, to) = if along_u {
                let v = f64::midpoint(first.1, second.1);
                ((lo.0, v), (hi.0, v))
            } else {
                let u = f64::midpoint(first.0, second.0);
                ((u, lo.1), (u, hi.1))
            };
            let (Some(a), Some(b)) = (self.read(from.0, from.1), self.read(to.0, to.1)) else {
                return;
            };
            if a.g.abs() > a.slack
                && b.g.abs() > b.slack
                && (a.g > 0.0) != (b.g > 0.0)
                && let Some((pu, pv)) = self.zero_on(from, to, a.g > 0.0)
            {
                out.push(frame(self.a, pu, pv).0);
            }
        }
    }

    /// Marks every leaf of a class reached.
    pub(super) fn mark(&mut self, class: &[usize]) {
        for &k in class {
            self.leaves[k].done = true;
        }
    }

    /// Cuts a lone leaf that straddles the region's or the second patch's
    /// edge, so its parts either lie off both, or inside both where a seed
    /// reaches them, and reads them; `false` where there is none to cut, or
    /// where the parts cannot all be read within the budget: the cut is then
    /// undone, so every leaf stays read.
    pub(super) fn refine(&mut self, class: &[usize]) -> bool {
        let &[k] = class else {
            return false;
        };
        let leaf = self.leaves[k];
        let start = self.leaves.len();
        if leaf.inside || start + 4 > self.most {
            return false;
        }
        let (hu, hv) = self.half_widths(&leaf);
        let (_, vm) = self.param(leaf.u.0, leaf.v.0 + (leaf.v.1 - leaf.v.0) / 2);
        let rates = rates(self.a, hv, vm);
        self.cut_or_stop(k, (hu * rates.u, hv * rates.v), leaf.reach);
        if self.leaves[k].kind == Kind::Fine {
            self.leaves[k] = leaf;
            return false;
        }
        self.settle_from(start);
        if self.leaves[start..].iter().any(|l| l.kind == Kind::Open) {
            self.leaves.truncate(start);
            self.leaves[k] = leaf;
            return false;
        }
        true
    }

    /// Settles a class. It is reached only where a marched point lies in
    /// one of its leaves, or a fitted curve passes through one: `fitted`
    /// reads whether the curve nearest a probe does, and `seed` settles a
    /// probe and marches from it, returning the points of the march where
    /// it lies on a marched branch (none where it traced nothing), or
    /// `None` where it does not settle. `Ok(true)` where the class is
    /// reached, `Ok(false)` where a lone leaf across an edge was cut and
    /// its parts are to be read again.
    ///
    /// # Errors
    ///
    /// Any error of `seed`, and [`MathError::ConvergenceFailure`] where no
    /// seed reaches the class and it cannot be cut: its arc may lie on both
    /// patches, and it is refused rather than dropped.
    pub(super) fn resolve(
        &mut self,
        class: &[usize],
        fitted: &dyn Fn(&Self, &[usize], Point3) -> bool,
        seed: &mut dyn FnMut(Point3) -> Result<Option<Vec<Point3>>, MathError>,
    ) -> Result<bool, MathError> {
        let mut probes = self.interiors(class);
        probes.extend(self.seeds(class));
        let reached = |cover: &Self| {
            class.iter().any(|&k| cover.leaves[k].done)
                || probes.iter().any(|&z| fitted(cover, class, z))
        };
        if reached(self) {
            self.mark(class);
            return Ok(true);
        }
        let mut tries = 0;
        for &z in &probes {
            let Some(points) = seed(z)? else {
                continue;
            };
            self.mark_marched(&points);
            if reached(self) {
                self.mark(class);
                return Ok(true);
            }
            tries += 1;
            if tries == SEED_TRIES {
                break;
            }
        }
        if self.refine(class) {
            return Ok(false);
        }
        Err(MathError::ConvergenceFailure { iterations: 0 })
    }

    /// Marks the leaf each point of a marched section lies in, where it
    /// lies inside that leaf by more than the rounding of its place on the
    /// section: the leaf's arc is then that section's.
    pub(super) fn mark_marched(&mut self, points: &[Point3]) {
        for &q in points {
            if let Some(k) = self.locate(q, 0.0) {
                self.leaves[k].done = true;
            }
        }
    }

    /// Whether `q`, a point within `off` of both surfaces, lies on the arc
    /// of a leaf of `class`.
    pub(super) fn holds(&self, class: &[usize], q: Point3, off: f64) -> bool {
        self.locate(q, off)
            .is_some_and(|k| class.binary_search(&k).is_ok())
    }

    /// The simple leaf whose arc holds the point of the section nearest
    /// `q`, a point within `off` of both surfaces (and within rounding):
    /// that point lies within `off`, and its rounding, over the sine of the
    /// angle between the surfaces' normals, and this leaf must hold the
    /// parameters of every point that near `q`, as the projection reads
    /// them (see [`projection_rates`]). `None` where none is sure.
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss
    )]
    fn locate(&self, q: Point3, off: f64) -> Option<usize> {
        let steps = self.steps as f64;
        let (span_u, span_v) = (
            self.u_range.1 - self.u_range.0,
            self.v_range.1 - self.v_range.0,
        );
        let (Some((_, na)), Some((_, nb))) = (self.a.distance(q), self.b.distance(q)) else {
            return None;
        };
        let sin = na.cross(nb).length();
        let (u, v) = sheet_params(self.a, q, self.u_range, self.v_range);
        let size = q.x().abs().max(q.y().abs()).max(q.z().abs());
        let rounding = 1024.0 * f64::EPSILON * (self.a.scale(q) + self.b.scale(q) + size);
        let reach = 2.5 * (off + rounding) / sin;
        let (rate_u, rate_v) = projection_rates(self.a, q, reach)?;
        let (mu, mv) = (
            reach * rate_u / span_u * steps,
            reach * rate_v / span_v * steps,
        );
        let (fu, fv) = (
            (u - self.u_range.0) / span_u * steps,
            (v - self.v_range.0) / span_v * steps,
        );
        let inside_patch = |f: f64, m: f64, periodic: bool| {
            f.is_finite() && (periodic || (f >= m && f <= steps - m))
        };
        if !(mu.is_finite()
            && mv.is_finite()
            && inside_patch(fu, mu, self.u_periodic)
            && inside_patch(fv, mv, self.v_periodic))
        {
            return None;
        }
        let lift = |f: f64, shift: u64, periodic: bool| {
            let f = if periodic { f.rem_euclid(steps) } else { f };
            if periodic && f < shift as f64 {
                f + steps
            } else {
                f
            }
        };
        let (fu, fv) = (
            lift(fu, self.shift.0, self.u_periodic),
            lift(fv, self.shift.1, self.v_periodic),
        );
        let (uu, vv) = (fu as u64, fv as u64);
        let (ru, rv) = (self.row(uu, true)?, self.row(vv, false)?);
        let mut k = *self.roots.get(&(ru.0, rv.0))?;
        while self.leaves[k].kind == Kind::Cut {
            let first = self.leaves[k].first;
            let last = first + self.leaves[k].parts;
            let next = self.leaves[first..last]
                .iter()
                .position(|c| c.u.0 <= uu && uu < c.u.1 && c.v.0 <= vv && vv < c.v.1)?;
            k = first + next;
        }
        let leaf = self.leaves[k];
        let inside = |x: f64, lo: u64, hi: u64, m: f64| x - lo as f64 >= m && hi as f64 - x >= m;
        (matches!(leaf.kind, Kind::Simple { .. })
            && inside(fu, leaf.u.0, leaf.u.1, mu)
            && inside(fv, leaf.v.0, leaf.v.1, mv))
        .then_some(k)
    }
}

fn find(parent: &mut [usize], mut k: usize) -> usize {
    while parent[k] != k {
        parent[k] = parent[parent[k]];
        k = parent[k];
    }
    k
}

/// The parameters of the point of `surface` nearest `q`, within the
/// patch's ranges: on a spindle torus, on whichever sheet `q` lies nearer,
/// where the plain projection reads the near tube's.
fn sheet_params(
    surface: &AnalyticSurface<'_>,
    q: Point3,
    u_range: (f64, f64),
    v_range: (f64, f64),
) -> (f64, f64) {
    match surface {
        AnalyticSurface::Torus(t) => {
            let (u, v) = t.project_point_nearest(q);
            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
        }
        _ => super::project_analytic(surface, q, u_range, v_range),
    }
}

/// Bounds over the ball of `reach` about `q` of how fast the parameters
/// [`sheet_params`] reads move with the point: `u` about an axis at one over
/// the distance from it, a cylinder's `v` at one, a cone's at one over the
/// sine of its half-angle, a ball's latitude at one over the distance from its
/// centre, and a torus's tube angle at one over the distance from its centre
/// circle. A cone's `v` moves at that rate where it is the height over the
/// sine; at or under `ConicalSurface::FOOT_SINE`, where it is the foot on a
/// generator, it moves no faster than the point, so there the bound is loose.
/// `None` where the ball reaches a point where they jump or have no bound: an
/// axis, a centre, a cone's apex plane, or where a spindle torus's nearer
/// sheet changes.
fn projection_rates(surface: &AnalyticSurface<'_>, q: Point3, reach: f64) -> Option<(f64, f64)> {
    let up = 1.0 + 1e-12;
    let inverse = |least: f64| (least > 0.0).then(|| up / least);
    let off_axis = |o: Point3, axis: Vec3| {
        let w = q - o;
        (w - axis * axis.dot(w)).length()
    };
    match surface {
        AnalyticSurface::Cylinder(c) => {
            Some((inverse(off_axis(c.origin(), c.axis()) - reach)?, up))
        }
        AnalyticSurface::Cone(c) => {
            if c.axis().dot(q - c.apex()).abs() <= reach * up {
                return None;
            }
            let along = up / c.half_angle().sin();
            Some((inverse(off_axis(c.apex(), c.axis()) - reach)?, along))
        }
        AnalyticSurface::Sphere(s) => Some((
            inverse(off_axis(s.center(), s.z_axis()) - reach)?,
            inverse((q - s.center()).length() - reach)?,
        )),
        AnalyticSurface::Torus(t) => {
            let w = q - t.center();
            let h = t.z_axis().dot(w);
            let rho = (w - t.z_axis() * h).length();
            let (big, small) = (t.major_radius(), t.minor_radius());
            let (near, far) = ((rho - big).hypot(h), (rho + big).hypot(h));
            let tube = if small > big {
                let (dn, df) = ((near - small).abs(), (far - small).abs());
                if (dn - df).abs() <= 2.0 * reach * up {
                    return None;
                }
                if df < dn { far } else { near }
            } else {
                near
            };
            Some((inverse(rho - reach)?, inverse(tube - reach)?))
        }
    }
}

/// Whether `inner` lies inside `outer`, off its faces.
fn inside_box(inner: Aabb3, outer: Aabb3) -> bool {
    inner.min.x() > outer.min.x()
        && inner.min.y() > outer.min.y()
        && inner.min.z() > outer.min.z()
        && inner.max.x() < outer.max.x()
        && inner.max.y() < outer.max.y()
        && inner.max.z() < outer.max.z()
}

/// Where the points of `surface` within `reach` of `p` lie against its
/// patch from `v0` to `v1`: its `v` there moves from `p`'s by at most
/// `reach` times the greatest rate at which `v` moves with the point.
fn on_patch(surface: &AnalyticSurface<'_>, (v0, v1): (f64, f64), p: Point3, reach: f64) -> Place {
    let (v, rate, turn) = match surface {
        AnalyticSurface::Cylinder(c) => (c.axis().dot(p - c.origin()), 1.0, None),
        AnalyticSurface::Cone(c) => {
            let sin = c.half_angle().sin();
            (c.axis().dot(p - c.apex()) / sin, 1.0 / sin, None)
        }
        AnalyticSurface::Sphere(s) => {
            let w = p - s.center();
            let r = w.length();
            if r <= reach {
                return Place::Across;
            }
            let z = (s.z_axis().dot(w) / r).clamp(-1.0, 1.0);
            (z.asin(), 1.0 / (r - reach), None)
        }
        AnalyticSurface::Torus(t) => {
            if v1 - v0 >= std::f64::consts::TAU {
                return Place::Inside;
            }
            // A spindle torus's far sheet reads its `v` about the centre
            // circle's far point, which the bound below does not follow.
            if t.minor_radius() >= t.major_radius() {
                return Place::Across;
            }
            let w = p - t.center();
            let h = t.z_axis().dot(w);
            let rho = (w - t.z_axis() * h).length();
            let q = (rho - t.major_radius()).hypot(h);
            if rho <= reach || q <= reach {
                return Place::Across;
            }
            let v = h
                .atan2(rho - t.major_radius())
                .rem_euclid(std::f64::consts::TAU);
            (v, 1.0 / (q - reach), Some(std::f64::consts::TAU))
        }
    };
    let spread = reach * rate * UP;
    let (lo, hi) = (v - spread, v + spread);
    let shifts: &[f64] = match turn {
        Some(t) => &[-t, 0.0, t],
        None => &[0.0],
    };
    if shifts.iter().any(|s| lo + s > v0 && hi + s < v1) {
        Place::Inside
    } else if shifts.iter().all(|s| hi + s < v0 || lo + s > v1) {
        Place::Outside
    } else {
        Place::Across
    }
}

/// The point of `surface` at `(u, v)` and its partial derivatives there.
fn frame(surface: &AnalyticSurface<'_>, u: f64, v: f64) -> (Point3, Vec3, Vec3) {
    let (sin_u, cos_u) = u.sin_cos();
    match surface {
        AnalyticSurface::Cylinder(c) => {
            let out = c.x_axis() * cos_u + c.y_axis() * sin_u;
            let turn = c.y_axis() * cos_u - c.x_axis() * sin_u;
            (
                c.origin() + out * c.radius() + c.axis() * v,
                turn * c.radius(),
                c.axis(),
            )
        }
        AnalyticSurface::Cone(c) => {
            let (sin_a, cos_a) = c.half_angle().sin_cos();
            let out = c.x_axis() * cos_u + c.y_axis() * sin_u;
            let turn = c.y_axis() * cos_u - c.x_axis() * sin_u;
            let ray = out * cos_a + c.axis() * sin_a;
            (c.apex() + ray * v, turn * (v * cos_a), ray)
        }
        AnalyticSurface::Sphere(s) => {
            let (sin_v, cos_v) = v.sin_cos();
            let out = s.x_axis() * cos_u + s.y_axis() * sin_u;
            let turn = s.y_axis() * cos_u - s.x_axis() * sin_u;
            let r = s.radius();
            (
                s.center() + (out * cos_v + s.z_axis() * sin_v) * r,
                turn * (r * cos_v),
                (s.z_axis() * cos_v - out * sin_v) * r,
            )
        }
        AnalyticSurface::Torus(t) => {
            let (sin_v, cos_v) = v.sin_cos();
            let out = t.x_axis() * cos_u + t.y_axis() * sin_u;
            let turn = t.y_axis() * cos_u - t.x_axis() * sin_u;
            let (big, small) = (t.major_radius(), t.minor_radius());
            let tube = small.madd(cos_v, big);
            (
                t.center() + out * tube + t.z_axis() * (small * sin_v),
                turn * tube,
                (t.z_axis() * cos_v - out * sin_v) * small,
            )
        }
    }
}

/// Bounds of the lengths of `surface`'s partial derivatives over the
/// parameters within `hv` of `v`, along `u` anywhere.
fn rates(surface: &AnalyticSurface<'_>, hv: f64, v: f64) -> Rates {
    match surface {
        AnalyticSurface::Cylinder(c) => Rates {
            u: c.radius(),
            v: 1.0,
            uu: c.radius(),
            uv: 0.0,
            vv: 0.0,
        },
        AnalyticSurface::Cone(c) => {
            let cos_a = c.half_angle().cos();
            let far = (v.abs() + hv) * cos_a;
            Rates {
                u: far,
                v: 1.0,
                uu: far,
                uv: cos_a,
                vv: 0.0,
            }
        }
        AnalyticSurface::Sphere(s) => {
            let r = s.radius();
            let (lo, hi) = (v - hv, v + hv);
            // `cos` is greatest nearest 0 and `sin` farthest from it.
            let cos = if lo <= 0.0 && hi >= 0.0 {
                1.0
            } else {
                lo.abs().min(hi.abs()).cos()
            };
            let sin = lo
                .abs()
                .max(hi.abs())
                .min(std::f64::consts::FRAC_PI_2)
                .sin();
            Rates {
                u: r * cos,
                v: r,
                uu: r * cos,
                uv: r * sin,
                vv: r,
            }
        }
        AnalyticSurface::Torus(t) => {
            let (big, small) = (t.major_radius(), t.minor_radius());
            Rates {
                u: big + small,
                v: small,
                uu: big + small,
                uv: small,
                vv: small,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use std::f64::consts::{PI, TAU};

    use super::*;
    use crate::surfaces::{CylindricalSurface, ToroidalSurface};

    /// The spindle torus of radii 1 and 2 about the origin's z axis.
    fn spindle() -> ToroidalSurface {
        ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap()
    }

    /// A point of a spindle torus's far sheet, where `1 + 2 cos v` is
    /// negative, lies half a turn round from the near tube's point that the
    /// plain projection reads: read there, it lay 0.469 off, and its leaf
    /// could be another class's. It is read on its own sheet.
    #[test]
    fn a_spindle_torus_point_on_its_far_sheet_is_read_there() {
        let torus = spindle();
        let surface = AnalyticSurface::Torus(&torus);
        let q = torus.evaluate(0.0, 0.75 * PI);
        let (u, v) = sheet_params(&surface, q, (0.0, TAU), (0.0, TAU));
        let off = (frame(&surface, u, v).0 - q).length();
        assert!(off < 1e-12, "read {off:.3e} off");
    }

    /// The point at `v` 2.5 of a spindle torus of radii 1 and 2 lies on the
    /// patch from `v` 2.4 to 2.6, but its near tube's parameter is 1.89:
    /// the patch was read as off the ball about it, and a cell holding it
    /// was set aside.
    #[test]
    fn a_spindle_torus_patch_holds_its_far_sheet_points() {
        let torus = spindle();
        let surface = AnalyticSurface::Torus(&torus);
        let p = torus.evaluate(0.0, 2.5);
        assert!(on_patch(&surface, (2.4, 2.6), p, 1e-3) != Place::Outside);
    }

    /// The rod and ring of the two dips in one cell (see
    /// `two_loops_in_one_cell_of_each_patch_are_both_traced`).
    fn rod_and_ring() -> (CylindricalSurface, ToroidalSurface) {
        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
        let rod = CylindricalSurface::new(
            Point3::new(0.0, 4.0 - 0.007, 2.1 - 8e-6),
            Vec3::new(1.0, 0.0, 0.0),
            0.6,
        )
        .unwrap();
        (rod, ring)
    }

    fn every_cell(n: usize) -> Vec<(usize, usize)> {
        (0..n).flat_map(|i| (0..n).map(move |j| (i, j))).collect()
    }

    /// A class whose seeds do not settle, or whose march traces nothing, is
    /// not reached: it was marked reached all the same, and its arc was
    /// lost with no error. Only a marched point in one of its leaves
    /// reaches it.
    #[test]
    fn a_class_no_march_reaches_is_not_taken_as_reached() {
        let (rod, ring) = rod_and_ring();
        let (a, b) = (
            AnalyticSurface::Cylinder(&rod),
            AnalyticSurface::Torus(&ring),
        );
        let mut cover = Cover::new(
            &a,
            &b,
            ((0.0, TAU), (-10.0, 10.0)),
            (0.0, TAU),
            32,
            &every_cell(32),
            None,
            1e-7,
            MOST_LEAVES,
        );
        assert!(cover.complete());
        let classes = cover.classes();
        let class = classes
            .iter()
            .find(|c| c.iter().all(|&k| cover.leaves[k].inside))
            .expect("a class inside both patches")
            .clone();
        let never = |_: &Cover<'_, '_>, _: &[usize], _: Point3| false;
        let traced_nothing = cover.resolve(&class, &never, &mut |_: Point3| Ok(Some(Vec::new())));
        assert!(traced_nothing.is_err(), "{traced_nothing:?}");
        let unsettled = cover.resolve(&class, &never, &mut |_: Point3| Ok(None));
        assert!(unsettled.is_err(), "{unsettled:?}");
        assert!(cover.classes().contains(&class));
        let reached = cover.resolve(&class, &never, &mut |z: Point3| Ok(Some(vec![z])));
        assert!(
            reached.is_ok_and(|r| r),
            "a marched point on its arc reaches it"
        );
    }

    /// A lone cell across the region's edge cut past the budget left its
    /// parts unread after the cover was proved complete: the arcs in them
    /// were dropped, and the second patch's seeds no longer ran. The cut is
    /// undone, and every leaf stays read.
    #[test]
    fn a_cut_past_the_budget_is_undone() {
        let (rod, ring) = rod_and_ring();
        let (a, b) = (
            AnalyticSurface::Cylinder(&rod),
            AnalyticSurface::Torus(&ring),
        );
        // The region's edge across one loop, at a few places along it.
        let mut tried = 0;
        for edge in [0.17, 0.2, 0.23, 0.25, 0.27, 0.29] {
            let meet = Aabb3 {
                min: Point3::new(edge, 3.9, 1.4),
                max: Point3::new(1.0, 4.1, 1.6),
            };
            let mut cover = Cover::new(
                &a,
                &b,
                ((0.0, TAU), (-10.0, 10.0)),
                (0.0, TAU),
                32,
                &every_cell(32),
                Some((meet, meet.expanded(1e-4))),
                1e-7,
                MOST_LEAVES,
            );
            assert!(cover.complete());
            let classes = cover.classes();
            let Some(lone) = classes
                .iter()
                .find(|c| c.len() == 1 && !cover.leaves[c[0]].inside)
                .cloned()
            else {
                continue;
            };
            tried += 1;
            let before = cover.leaves.len();
            cover.most = before + 2;
            let cut = cover.refine(&lone);
            assert!(
                cover.complete(),
                "edge {edge}: cut {cut}, a leaf is left unread"
            );
            assert!(!cut && cover.leaves.len() == before, "edge {edge}");
        }
        assert!(tried > 0, "no cell across the region's edge");
    }

    /// A cut whose first parts fit the budget but whose parts' own cuts do
    /// not is undone: the leaf is as it was, its parts are gone, and every
    /// leaf stays read.
    #[test]
    fn a_cut_whose_parts_run_past_the_budget_is_undone() {
        let (rod, ring) = rod_and_ring();
        let (a, b) = (
            AnalyticSurface::Cylinder(&rod),
            AnalyticSurface::Torus(&ring),
        );
        let mut undone = 0;
        for edge in [0.17, 0.2, 0.23, 0.25, 0.27, 0.29] {
            let meet = Aabb3 {
                min: Point3::new(edge, 3.9, 1.4),
                max: Point3::new(1.0, 4.1, 1.6),
            };
            let build = |most: usize| {
                Cover::new(
                    &a,
                    &b,
                    ((0.0, TAU), (-10.0, 10.0)),
                    (0.0, TAU),
                    32,
                    &every_cell(32),
                    Some((meet, meet.expanded(1e-4))),
                    1e-7,
                    most,
                )
            };
            let mut cover = build(MOST_LEAVES);
            let lone: Vec<Vec<usize>> = cover
                .classes()
                .into_iter()
                .filter(|c| c.len() == 1 && !cover.leaves[c[0]].inside)
                .collect();
            for class in &lone {
                // Only a cut whose parts are cut again adds more than four.
                let mut free = build(MOST_LEAVES);
                let start = free.leaves.len();
                if !free.refine(class) || free.leaves.len() <= start + 4 {
                    continue;
                }
                let k = class[0];
                let saved = cover.leaves[k];
                let before = cover.leaves.len();
                cover.most = before + 4;
                assert!(!cover.refine(class), "edge {edge}: cut past the budget");
                assert_eq!(cover.leaves.len(), before, "edge {edge}: parts left");
                let now = cover.leaves[k];
                assert!(
                    now.kind == saved.kind
                        && (now.first, now.parts) == (saved.first, saved.parts)
                        && (now.u, now.v) == (saved.u, saved.v),
                    "edge {edge}: leaf not restored"
                );
                assert!(cover.complete(), "edge {edge}: a leaf is left unread");
                cover.most = MOST_LEAVES;
                undone += 1;
            }
        }
        assert!(undone > 0, "no cut whose parts are cut again");
    }

    /// A cone of half-angle 0.001 reads `v` as its height over the sine of
    /// that angle, so a point 1e-7 off it along its axis reads `v` 1e-4
    /// away. A point that near a leaf's edge was placed inside the leaf
    /// beyond the edge, where `v` was read at the rate along the cone: a
    /// fitted curve's point could mark a class it does not pass through.
    #[test]
    fn a_point_near_a_flat_cones_section_is_not_placed_past_its_reach() {
        use crate::surfaces::ConicalSurface;
        let up = Vec3::new(0.0, 0.0, 1.0);
        let cone = ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 0.001).unwrap();
        let rod = CylindricalSurface::new(Point3::new(3.0, 0.0, 0.0), up, 1.0).unwrap();
        let (a, b) = (
            AnalyticSurface::Cone(&cone),
            AnalyticSurface::Cylinder(&rod),
        );
        let mut cover = Cover::new(
            &a,
            &b,
            ((0.0, TAU), (1.0, 5.0)),
            (-1.0, 1.0),
            32,
            &every_cell(32),
            None,
            1e-7,
            MOST_LEAVES,
        );
        assert!(cover.complete());
        let classes = cover.classes();
        assert!(!classes.is_empty());
        let mut tried = 0;
        for class in &classes {
            for z in cover.seeds(class) {
                for sign in [1.0, -1.0] {
                    let q = z + up * (sign * 1e-7);
                    tried += 1;
                    let placed = cover.locate(q, 1e-7);
                    assert!(placed.is_none(), "{q:?}, by an edge, placed in {placed:?}");
                }
            }
        }
        assert!(tried > 0);
    }
}