brepkit-math 4.11.37

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
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
//! Bezier decomposition and degree elevation for NURBS curves and surfaces.

use crate::MathError;
use crate::aabb::Aabb3;
use crate::madd::Madd;
use crate::nurbs::curve::NurbsCurve;
use crate::nurbs::knot_ops::KNOT_EPS;
use crate::nurbs::surface::NurbsSurface;
use crate::nurbs::{cartesian, cartesian_net, span_around};
use crate::vec::Point3;

/// Decompose a NURBS curve into Bezier segments.
///
/// Each segment is a NURBS curve of the same degree with a clamped knot vector
/// over one knot span of the curve's domain, in order: segment *i* runs from
/// the domain's *i*-th distinct knot to the next. Each is read off its span's
/// de Boor points ([`curve_bezier_between`]) with no knot inserted, so a knot
/// vector that is not clamped, a degree of zero, or an interior knot repeated
/// past the degree needs no special case.
///
/// # Errors
///
/// Returns [`MathError::PoleAtInfinity`] if a span's Bezier form has a
/// control point at infinity, as weights of mixed sign can give, or another
/// error if a segment cannot be built.
pub fn curve_to_bezier_segments(curve: &NurbsCurve) -> Result<Vec<NurbsCurve>, MathError> {
    let p = curve.degree();
    let (d0, d1) = curve.domain();
    let mut cuts: Vec<f64> = std::iter::once(d0)
        .chain(curve.knots().iter().copied().filter(|&k| k > d0 && k < d1))
        .chain(std::iter::once(d1))
        .collect();
    // By value: -0 and 0 are one knot.
    cuts.dedup_by(|a, b| (*a - *b).abs() <= 0.0);
    if cuts.len() < 2 {
        return Ok(vec![curve.clone()]);
    }
    let mut segments = Vec::with_capacity(cuts.len() - 1);
    for w in cuts.windows(2) {
        let homogeneous = curve_bezier_between(curve, w[0], w[1])?;
        let mut points = Vec::with_capacity(p + 1);
        let mut weights = Vec::with_capacity(p + 1);
        for q in homogeneous {
            points.push(cartesian(q).ok_or(MathError::PoleAtInfinity {
                start: w[0],
                end: w[1],
            })?);
            weights.push(q[3]);
        }
        let mut knots = vec![w[0]; p + 1];
        knots.extend(std::iter::repeat_n(w[1], p + 1));
        segments.push(NurbsCurve::new(p, knots, points, weights)?);
    }
    Ok(segments)
}

/// The rational Bezier form of `curve` from parameter `a` to parameter `b`.
///
/// `a` and `b` lie in one knot span of the domain. The result is `degree + 1`
/// control points in homogeneous form `[w x, w y, w z, w]`, the first at `a`
/// and the last at `b`, so in reverse when `a > b`.
///
/// Control point `j` is the curve's blossom at `a` taken `degree - j` times
/// and `b` taken `j` times, read off the span's de Boor points. No knot is
/// inserted, so a piece of a span and an unclamped knot vector need no
/// special case. When every returned weight is positive the piece lies in
/// the convex hull of the points.
///
/// # Errors
///
/// Returns [`MathError::ParameterOutOfRange`] if `a` and `b` do not lie in
/// one knot span of the curve's domain.
pub fn curve_bezier_between(
    curve: &NurbsCurve,
    a: f64,
    b: f64,
) -> Result<Vec<[f64; 4]>, MathError> {
    let p = curve.degree();
    let knots = curve.knots();
    let n = curve.control_points().len();
    let (lo, hi) = (a.min(b), a.max(b));
    let (d0, d1) = curve.domain();
    let out_of_range = MathError::ParameterOutOfRange {
        value: if lo < d0 { lo } else { hi },
        min: d0,
        max: d1,
    };
    if n <= p {
        return Err(out_of_range);
    }
    let i = p + knots[p..n].partition_point(|&k| k <= lo).saturating_sub(1);
    if !(knots[i] <= lo && hi <= knots[i + 1] && knots[i] < knots[i + 1]) {
        return Err(out_of_range);
    }
    let homogeneous = homogeneous(
        &curve.control_points()[i - p..=i],
        &curve.weights()[i - p..=i],
    );
    Ok(span_bezier(&homogeneous, knots, p, i, (a, b)))
}

/// The Bezier points, in homogeneous form, of knot span `i` of a B-spline
/// of degree `p` on `knots`, from parameter `a` to parameter `b` in the
/// span, from the span's `p + 1` de Boor points `de_boor` in homogeneous
/// form. Point `j` is the blossom at `a` taken `p - j` times and `b` taken
/// `j` times.
fn span_bezier(
    de_boor: &[[f64; 4]],
    knots: &[f64],
    p: usize,
    i: usize,
    (a, b): (f64, f64),
) -> Vec<[f64; 4]> {
    let blossom = |at_b: usize| {
        let mut d = de_boor.to_vec();
        for level in 1..=p {
            let u = if level <= at_b { b } else { a };
            for j in (level..=p).rev() {
                let (left, right) = (knots[i - p + j], knots[i + 1 + j - level]);
                let alpha = (u - left) / (right - left);
                let prev = d[j - 1];
                for (c, q) in d[j].iter_mut().zip(prev) {
                    *c = (1.0 - alpha).madd(q, alpha * *c);
                }
            }
        }
        d[p]
    };
    (0..=p).map(blossom).collect()
}

/// A single Bezier patch extracted from a NURBS surface decomposition.
///
/// Each patch has `(degree_u + 1) × (degree_v + 1)` control points and
/// corresponds to a rectangular region in the original parameter space.
#[derive(Debug, Clone)]
pub struct BezierPatch {
    /// The Bezier patch as a NURBS surface (clamped knots, single span).
    pub surface: NurbsSurface,
    /// Parameter range in u on the original surface: `(u_start, u_end)`.
    pub u_range: (f64, f64),
    /// Parameter range in v on the original surface: `(v_start, v_end)`.
    pub v_range: (f64, f64),
}

impl BezierPatch {
    /// Compute the axis-aligned bounding box from control point extrema.
    ///
    /// For a Bezier patch (single-span), the convex hull property guarantees
    /// the geometry lies entirely within the control point AABB.
    #[must_use]
    pub fn aabb(&self) -> Aabb3 {
        self.surface.aabb()
    }

    /// Compute the diagonal length of the control-point AABB.
    #[must_use]
    pub fn diagonal(&self) -> f64 {
        let aabb = self.aabb();
        let dx = aabb.max.x() - aabb.min.x();
        let dy = aabb.max.y() - aabb.min.y();
        let dz = aabb.max.z() - aabb.min.z();
        dx.madd(dx, dy.madd(dy, dz * dz)).sqrt()
    }

    /// Compute the midpoint in the u parameter range.
    #[must_use]
    pub fn u_mid(&self) -> f64 {
        (self.u_range.0 + self.u_range.1) * 0.5
    }

    /// Compute the midpoint in the v parameter range.
    #[must_use]
    pub fn v_mid(&self) -> f64 {
        (self.v_range.0 + self.v_range.1) * 0.5
    }
}

/// Decompose a NURBS surface into Bezier patches.
///
/// Inserts knots in both u and v directions until all interior knots reach
/// at least full multiplicity (the degree), then extracts one patch for each
/// pair of knot spans of nonzero width, in u-major order. Each patch has
/// `(degree_u + 1) × (degree_v + 1)` control points. A direction of degree
/// zero gives one patch for each of its spans, constant along it.
///
/// Where a span's control points are its Bezier points, the patch takes
/// them as they are. Where they are not, because a knot at an end of the
/// span falls short of the degree's multiplicity, the patch takes the
/// span's Bezier points by blossoming: at the ends of a knot vector that is
/// not clamped, and next to knots nearer than `KNOT_EPS` (1e-15), which the
/// insertion counts as one knot.
///
/// # Errors
///
/// Returns [`MathError::PoleAtInfinity`] if a blossomed patch has a control
/// point at infinity, as weights of mixed sign can give, or another error if
/// knot insertion fails or the surface is degenerate.
pub fn surface_to_bezier_patches(surface: &NurbsSurface) -> Result<Vec<BezierPatch>, MathError> {
    let pu = surface.degree_u();
    let pv = surface.degree_v();

    // Steps 1 and 2: insert u- then v-knots to full multiplicity.
    let refined = refine_to_full_multiplicity(surface)?;

    // Step 3: Extract unique knot spans in u and v.
    let ref_knots_u = refined.knots_u();
    let ref_knots_v = refined.knots_v();
    let ref_cps = refined.control_points();
    let ref_ws = refined.weights();

    let n_rows = ref_cps.len();
    let n_cols = if n_rows > 0 { ref_cps[0].len() } else { 0 };

    let spans_u = spans_of_width(ref_knots_u, pu, n_rows);
    let spans_v = spans_of_width(ref_knots_v, pv, n_cols);

    if spans_u.is_empty() || spans_v.is_empty() {
        // Single patch: return the whole surface.
        let (u_start, u_end) = refined.domain_u();
        let (v_start, v_end) = refined.domain_v();
        return Ok(vec![BezierPatch {
            surface: refined,
            u_range: (u_start, u_end),
            v_range: (v_start, v_end),
        }]);
    }

    let mut patches = Vec::with_capacity(spans_u.len() * spans_v.len());

    for &su in &spans_u {
        let (row_start, row_end) = (su - pu, su + 1);
        let (u_start, u_end) = (ref_knots_u[su], ref_knots_u[su + 1]);
        let bezier_u = span_is_bezier(ref_knots_u, pu, su);
        // The span's rows along u in homogeneous form, read off its de Boor
        // points column by column, when they are not its Bezier points.
        let blossomed_rows = (!bezier_u).then(|| {
            let columns: Vec<Vec<[f64; 4]>> = (0..n_cols)
                .map(|c| {
                    let de_boor: Vec<[f64; 4]> = (row_start..row_end)
                        .map(|r| {
                            let (pt, w) = (ref_cps[r][c], ref_ws[r][c]);
                            [pt.x() * w, pt.y() * w, pt.z() * w, w]
                        })
                        .collect();
                    span_bezier(&de_boor, ref_knots_u, pu, su, (u_start, u_end))
                })
                .collect();
            transpose(&columns)
        });

        for &sv in &spans_v {
            let (col_start, col_end) = (sv - pv, sv + 1);
            let (v_start, v_end) = (ref_knots_v[sv], ref_knots_v[sv + 1]);
            let bezier_v = span_is_bezier(ref_knots_v, pv, sv);

            // Extract (pu+1) × (pv+1) control point sub-grid.
            let mut patch_cps = Vec::with_capacity(pu + 1);
            let mut patch_ws = Vec::with_capacity(pu + 1);

            if bezier_u && bezier_v {
                for row in row_start..row_end {
                    patch_cps.push(ref_cps[row][col_start..col_end].to_vec());
                    patch_ws.push(ref_ws[row][col_start..col_end].to_vec());
                }
            } else {
                let (start, end) = if bezier_u {
                    (v_start, v_end)
                } else {
                    (u_start, u_end)
                };
                for k in 0..=pu {
                    let along_v = match &blossomed_rows {
                        Some(rows) => std::borrow::Cow::Borrowed(&rows[k][col_start..col_end]),
                        None => std::borrow::Cow::Owned(homogeneous(
                            &ref_cps[row_start + k][col_start..col_end],
                            &ref_ws[row_start + k][col_start..col_end],
                        )),
                    };
                    let net = if bezier_v {
                        along_v.into_owned()
                    } else {
                        span_bezier(&along_v, ref_knots_v, pv, sv, (v_start, v_end))
                    };
                    let mut points = Vec::with_capacity(net.len());
                    for &q in &net {
                        points.push(cartesian(q).ok_or(MathError::PoleAtInfinity { start, end })?);
                    }
                    patch_cps.push(points);
                    patch_ws.push(net.iter().map(|q| q[3]).collect());
                }
            }

            // Build Bezier knot vectors: (p+1) copies of start, (p+1) copies of end.
            let mut knots_u = vec![u_start; pu + 1];
            knots_u.extend(std::iter::repeat_n(u_end, pu + 1));

            let mut knots_v = vec![v_start; pv + 1];
            knots_v.extend(std::iter::repeat_n(v_end, pv + 1));

            let patch_surface = NurbsSurface::new(pu, pv, knots_u, knots_v, patch_cps, patch_ws)?;

            patches.push(BezierPatch {
                surface: patch_surface,
                u_range: (u_start, u_end),
                v_range: (v_start, v_end),
            });
        }
    }

    Ok(patches)
}

/// The index `i` of each knot span `[knots[i], knots[i + 1]]` of nonzero
/// width in the domain of a direction of degree `p` over `n` control points.
/// A span counts however narrow it is: the surface can cross a long way in
/// it.
fn spans_of_width(knots: &[f64], p: usize, n: usize) -> Vec<usize> {
    (p..n).filter(|&i| knots[i] < knots[i + 1]).collect()
}

/// Whether control points `i - p` to `i` are the Bezier points of knot
/// span `i`: the `p` knots up to `knots[i]` equal it, and the `p` knots
/// from `knots[i + 1]` equal that.
fn span_is_bezier(knots: &[f64], p: usize, i: usize) -> bool {
    // By value: -0 and 0 are one knot.
    let same = |a: f64, b: f64| (a - b).abs() <= 0.0;
    knots[i + 1 - p..=i].iter().all(|&k| same(k, knots[i]))
        && knots[i + 1..=i + p].iter().all(|&k| same(k, knots[i + 1]))
}

/// The knots `surface_to_bezier_patches` inserts along one direction, in
/// order, each with the count it asks for: every interior knot of `knots`
/// short of multiplicity `p`.
fn full_multiplicity_insertions(knots: &[f64], p: usize) -> Vec<(f64, usize)> {
    let mut out = Vec::new();
    let mut i = p + 1;
    while i < knots.len() - p - 1 {
        let u = knots[i];
        let mut mult = 1;
        while i + mult < knots.len() - p - 1 && (knots[i + mult] - u).abs() < 1e-15 {
            mult += 1;
        }
        let deficit = p.saturating_sub(mult);
        if deficit > 0 {
            out.push((u, deficit));
        }
        i += mult;
    }
    out
}

/// `surface` with every interior knot raised to full multiplicity, u then
/// v: what inserting each with [`surface_knot_insert_u`] and
/// [`surface_knot_insert_v`] gives, bit for bit, on one grid rather than a
/// curve per row or column and a surface per knot.
fn refine_to_full_multiplicity(surface: &NurbsSurface) -> Result<NurbsSurface, MathError> {
    let (pu, pv) = (surface.degree_u(), surface.degree_v());
    let mut cps = surface.control_points().to_vec();
    let mut ws = surface.weights().to_vec();
    let mut knots_u = surface.knots_u().to_vec();
    let mut knots_v = surface.knots_v().to_vec();
    let along_u = full_multiplicity_insertions(&knots_u, pu);
    let along_v = full_multiplicity_insertions(&knots_v, pv);
    if cps.first().is_none_or(Vec::is_empty) && !(along_u.is_empty() && along_v.is_empty()) {
        return Err(MathError::EmptyInput);
    }
    for (u, r) in along_u {
        insert_along_rows(&mut cps, &mut ws, &mut knots_u, pu, u, r)?;
    }
    if !along_v.is_empty() {
        let (mut cols, mut wcols) = (transpose(&cps), transpose(&ws));
        for (v, r) in along_v {
            insert_along_rows(&mut cols, &mut wcols, &mut knots_v, pv, v, r)?;
        }
        cps = transpose(&cols);
        ws = transpose(&wcols);
    }
    NurbsSurface::new(pu, pv, knots_u, knots_v, cps, ws)
}

fn transpose<T: Copy>(grid: &[Vec<T>]) -> Vec<Vec<T>> {
    let n = grid.first().map_or(0, Vec::len);
    (0..n)
        .map(|j| grid.iter().map(|row| row[j]).collect())
        .collect()
}

/// A row of the grid [`insert_along_rows`] works on: one of the grid's
/// rows as it came, or a blended row in homogeneous form.
enum Row {
    Kept(usize),
    Blended(Vec<[f64; 4]>),
}

/// A row in homogeneous form.
fn homogeneous(row: &[Point3], wrow: &[f64]) -> Vec<[f64; 4]> {
    row.iter()
        .zip(wrow)
        .map(|(pt, &w)| [pt.x() * w, pt.y() * w, pt.z() * w, w])
        .collect()
}

/// `row` in homogeneous form, a kept row read from `cps` and `ws`.
fn row_view<'a>(
    row: &'a Row,
    cps: &[Vec<Point3>],
    ws: &[Vec<f64>],
) -> std::borrow::Cow<'a, [[f64; 4]]> {
    match row {
        Row::Kept(at) => std::borrow::Cow::Owned(homogeneous(&cps[*at], &ws[*at])),
        Row::Blended(h) => std::borrow::Cow::Borrowed(h),
    }
}

/// [`crate::nurbs::knot_ops::curve_knot_insert`] of `u`, `r` times, on
/// every column of the grid at once (its rows run along the curves): the
/// same multiplicity cap, homogeneous points, blends, knot vector and
/// refusal of a control point at infinity.
fn insert_along_rows(
    cps: &mut Vec<Vec<Point3>>,
    ws: &mut Vec<Vec<f64>>,
    knots: &mut Vec<f64>,
    p: usize,
    u: f64,
    r: usize,
) -> Result<(), MathError> {
    let s = knots
        .iter()
        .filter(|&&kv| (kv - u).abs() < KNOT_EPS)
        .count();
    let r = r.min(p.saturating_sub(s));
    if r == 0 {
        return Ok(());
    }
    let span = span_around(knots, u);
    // Each row is blended in homogeneous form and written back; a row the
    // blends do not touch is only taken there and back, which leaves a row
    // whose weights are all exactly 1 as it was, so such a row stays in
    // place (on a surface of many spans the round trips were most of the
    // work, as they repeat for every knot).
    let mut rows: Vec<Row> = (0..cps.len()).map(Row::Kept).collect();
    for _ in 0..r {
        let ck = crate::nurbs::basis::find_span(rows.len(), p, u, knots);
        let new_rows: Vec<Row> = ((ck - p + 1)..=ck)
            .map(|i| {
                let denom = knots[i + p] - knots[i];
                let alpha = if denom.abs() < KNOT_EPS {
                    0.0
                } else {
                    (u - knots[i]) / denom
                };
                Row::Blended(
                    row_view(&rows[i - 1], cps, ws)
                        .iter()
                        .zip(row_view(&rows[i], cps, ws).iter())
                        .map(|(prev, curr)| {
                            [
                                alpha * curr[0] + (1.0 - alpha) * prev[0],
                                alpha * curr[1] + (1.0 - alpha) * prev[1],
                                alpha * curr[2] + (1.0 - alpha) * prev[2],
                                alpha * curr[3] + (1.0 - alpha) * prev[3],
                            ]
                        })
                        .collect(),
                )
            })
            .collect();
        rows.splice((ck - p + 1)..ck, new_rows);
        knots.insert(ck + 1, u);
    }
    let mut old: Vec<Option<(Vec<Point3>, Vec<f64>)>> = std::mem::take(cps)
        .into_iter()
        .zip(std::mem::take(ws))
        .map(Some)
        .collect();
    let mut grid = Vec::with_capacity(rows.len());
    for row in rows {
        grid.push(match row {
            Row::Kept(at) => match old[at].take() {
                Some((row, wrow)) if wrow.iter().all(|&w| w.to_bits() == 1.0_f64.to_bits()) => {
                    (row, wrow)
                }
                Some((row, wrow)) => cartesian_net(&homogeneous(&row, &wrow), span)?,
                None => continue,
            },
            Row::Blended(h) => cartesian_net(&h, span)?,
        });
    }
    (*cps, *ws) = grid.into_iter().unzip();
    Ok(())
}

/// Elevate the degree of a NURBS curve by `t` (A5.9).
///
/// The resulting curve has degree `p + t` and represents the same geometry.
///
/// # Errors
///
/// Returns [`MathError::PoleAtInfinity`] if an elevated control point is at
/// infinity, as weights of mixed sign can blend to, or another error if the
/// resulting curve cannot be constructed.
pub fn curve_degree_elevate(curve: &NurbsCurve, t: usize) -> Result<NurbsCurve, MathError> {
    if t == 0 {
        return Ok(curve.clone());
    }

    let p = curve.degree();
    let new_p = p + t;

    let segments = curve_to_bezier_segments(curve)?;
    let n_segs = segments.len();

    let bezalfs = compute_bezalfs(p, t);

    let mut all_cps: Vec<[f64; 4]> = Vec::new();
    let mut all_knots: Vec<f64> = Vec::new();

    // Whether each piece ends where the next starts, read off the knot's
    // repeats: the curve is continuous at a knot repeated at most its degree
    // times. One repeated more (or any knot of a degree-zero curve) may jump
    // there, so both ends stay and the elevated knot repeats once more.
    // Comparing the ends' coordinates instead would hang on the weights'
    // scale, which leaves the curve unchanged.
    // Breaks and knots both ascend, so one pass counts every break's repeats.
    let knots = curve.knots();
    let mut at = 0;
    let joined: Vec<bool> = segments
        .iter()
        .take(n_segs.saturating_sub(1))
        .map(|seg| {
            let u = seg.knots()[p + 1];
            while at < knots.len() && knots[at] < u {
                at += 1;
            }
            let repeats = knots[at..]
                .iter()
                .take_while(|&&k| (k - u).abs() <= 0.0)
                .count();
            repeats <= p
        })
        .collect();

    for (seg_idx, seg) in segments.iter().enumerate() {
        let seg_cps = seg.control_points();
        let seg_ws = seg.weights();
        let seg_pw: Vec<[f64; 4]> = seg_cps
            .iter()
            .zip(seg_ws.iter())
            .map(|(pt, &w)| [pt.x() * w, pt.y() * w, pt.z() * w, w])
            .collect();

        let mut elevated = vec![[0.0; 4]; new_p + 1];
        for i in 0..=new_p {
            for j in i.saturating_sub(t)..=(i.min(p)) {
                if j <= p {
                    let coeff = bezalfs[i][j];
                    elevated[i][0] += coeff * seg_pw[j][0];
                    elevated[i][1] += coeff * seg_pw[j][1];
                    elevated[i][2] += coeff * seg_pw[j][2];
                    elevated[i][3] += coeff * seg_pw[j][3];
                }
            }
        }

        if seg_idx == 0 {
            // First segment: add all control points and start knot.
            let u_start = seg.knots()[0];
            for _ in 0..=new_p {
                all_knots.push(u_start);
            }
            all_cps.extend_from_slice(&elevated);
        } else if joined[seg_idx - 1] {
            // Subsequent segments: skip first control point (shared with previous).
            all_cps.extend_from_slice(&elevated[1..]);
        } else {
            all_cps.extend_from_slice(&elevated);
        }

        if seg_idx == n_segs - 1 {
            // Last segment: add end knot.
            let u_end = seg.knots()[p + 1];
            for _ in 0..=new_p {
                all_knots.push(u_end);
            }
        } else {
            // Interior break: new_p copies of the break knot, one more
            // where the curve jumps.
            let u_break = seg.knots()[p + 1];
            let copies = if joined[seg_idx] { new_p } else { new_p + 1 };
            for _ in 0..copies {
                all_knots.push(u_break);
            }
        }
    }

    // Handle single-segment case (no segments produced)
    if segments.is_empty() {
        // Should not happen if curve is valid, but handle gracefully.
        return Ok(curve.clone());
    }

    let (u0, u1) = curve.domain();
    let (new_cps, new_ws) = cartesian_net(&all_cps, (u0, u1))?;
    NurbsCurve::new(new_p, all_knots, new_cps, new_ws)
}

/// Compute the Bezier degree elevation coefficients.
///
/// `bezalfs[i][j] = C(p,j) * C(t, i-j) / C(p+t, i)`
#[allow(clippy::cast_precision_loss)]
fn compute_bezalfs(p: usize, t: usize) -> Vec<Vec<f64>> {
    let new_p = p + t;
    let mut bezalfs = vec![vec![0.0; p + 1]; new_p + 1];

    for (i, row) in bezalfs.iter_mut().enumerate().take(new_p + 1) {
        let j_min = i.saturating_sub(t);
        let j_max = i.min(p);
        for (j, val) in row.iter_mut().enumerate().take(j_max + 1).skip(j_min) {
            *val = binomial(p, j) as f64 * binomial(t, i - j) as f64 / binomial(new_p, i) as f64;
        }
    }

    bezalfs
}

use super::basis::binomial;

#[cfg(test)]
#[allow(clippy::expect_used, clippy::cast_lossless, clippy::suboptimal_flops)]
mod tests {
    use super::*;

    /// Steps 1 and 2 of `surface_to_bezier_patches` as they were: a
    /// surface rebuilt per knot inserted.
    fn refine_by_insertion(surface: &NurbsSurface) -> NurbsSurface {
        use crate::nurbs::knot_ops::{surface_knot_insert_u, surface_knot_insert_v};
        let (pu, pv) = (surface.degree_u(), surface.degree_v());
        // Step 1: Insert u-knots to full multiplicity.
        let mut refined = surface.clone();
        {
            let knots_u = refined.knots_u().to_vec();
            let mut i = pu + 1;
            while i < knots_u.len() - pu - 1 {
                let u = knots_u[i];
                let mut mult = 1;
                while i + mult < knots_u.len() - pu - 1 && (knots_u[i + mult] - u).abs() < 1e-15 {
                    mult += 1;
                }
                let deficit = pu.saturating_sub(mult);
                if deficit > 0 {
                    refined = surface_knot_insert_u(&refined, u, deficit).expect("inserted");
                }
                i += mult;
            }
        }

        // Step 2: Insert v-knots to full multiplicity.
        {
            let knots_v = refined.knots_v().to_vec();
            let mut i = pv + 1;
            while i < knots_v.len() - pv - 1 {
                let v = knots_v[i];
                let mut mult = 1;
                while i + mult < knots_v.len() - pv - 1 && (knots_v[i + mult] - v).abs() < 1e-15 {
                    mult += 1;
                }
                let deficit = pv.saturating_sub(mult);
                if deficit > 0 {
                    refined = surface_knot_insert_v(&refined, v, deficit).expect("inserted");
                }
                i += mult;
            }
        }

        refined
    }

    /// The grid refinement is the knot-by-knot insertion's, bit for bit:
    /// rational and polynomial nets, degrees 1 to 4, knots already at full
    /// multiplicity or past half of it, uneven spans.
    #[test]
    fn refinement_matches_insertion_knot_by_knot() {
        let net = |pu: usize, pv: usize, n: usize, m: usize, rational: bool, double: bool| {
            let knots = |p: usize, n: usize| {
                let mut k = vec![0.0; p + 1];
                let mut i = 1;
                while k.len() < n {
                    let t = i as f64 / (n - p) as f64;
                    let t = t * t.madd(0.3, 0.7);
                    k.push(t);
                    if double && i % 3 == 0 && k.len() < n {
                        k.push(t);
                    }
                    i += 1;
                }
                k.extend(vec![1.0; p + 1]);
                k
            };
            let points = (0..n)
                .map(|i| {
                    (0..m)
                        .map(|j| {
                            let (x, y) = (i as f64, j as f64);
                            Point3::new(x * 1.7, y * 0.3, (x * 0.7 + y * 1.3).sin())
                        })
                        .collect()
                })
                .collect();
            let weights = (0..n)
                .map(|i| {
                    (0..m)
                        .map(|j| {
                            if rational {
                                0.3 + 1.4 * ((i * 3 + j * 5) % 7) as f64 / 7.0
                            } else {
                                1.0
                            }
                        })
                        .collect()
                })
                .collect();
            NurbsSurface::new(pu, pv, knots(pu, n), knots(pv, m), points, weights)
                .expect("valid net")
        };
        let bits = |s: &NurbsSurface| {
            let pts: Vec<u64> = s
                .control_points()
                .iter()
                .flatten()
                .flat_map(|p| [p.x().to_bits(), p.y().to_bits(), p.z().to_bits()])
                .collect();
            let ws: Vec<u64> = s.weights().iter().flatten().map(|w| w.to_bits()).collect();
            let k: Vec<u64> = s
                .knots_u()
                .iter()
                .chain(s.knots_v())
                .map(|k| k.to_bits())
                .collect();
            (pts, ws, k)
        };
        for (pu, pv) in [(1, 1), (2, 3), (3, 2), (3, 3), (4, 1), (1, 4)] {
            for rational in [false, true] {
                for double in [false, true] {
                    let s = net(pu, pv, pu + 9, pv + 7, rational, double);
                    let fast = refine_to_full_multiplicity(&s).expect("refined");
                    assert_eq!(
                        bits(&fast),
                        bits(&refine_by_insertion(&s)),
                        "degrees ({pu}, {pv}), rational {rational}, double {double}"
                    );
                    // Rows whose weights are all 1 among rows whose are not
                    // (a refinement keeps the former in place).
                    let mixed = NurbsSurface::new(
                        pu,
                        pv,
                        s.knots_u().to_vec(),
                        s.knots_v().to_vec(),
                        s.control_points().to_vec(),
                        s.weights()
                            .iter()
                            .enumerate()
                            .map(|(i, row)| {
                                if i % 3 == 0 {
                                    vec![1.0; row.len()]
                                } else {
                                    row.clone()
                                }
                            })
                            .collect(),
                    )
                    .expect("valid net");
                    assert_eq!(
                        bits(&refine_to_full_multiplicity(&mixed).expect("refined")),
                        bits(&refine_by_insertion(&mixed)),
                        "degrees ({pu}, {pv}), mixed rows, double {double}"
                    );
                }
            }
        }
    }

    fn cubic_bezier() -> NurbsCurve {
        NurbsCurve::new(
            3,
            vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
            vec![
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(1.0, 2.0, 0.0),
                Point3::new(3.0, 2.0, 0.0),
                Point3::new(4.0, 0.0, 0.0),
            ],
            vec![1.0, 1.0, 1.0, 1.0],
        )
        .expect("valid")
    }

    fn multi_span_curve() -> NurbsCurve {
        NurbsCurve::new(
            3,
            vec![0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0],
            vec![
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(1.0, 2.0, 0.0),
                Point3::new(2.0, 2.0, 0.0),
                Point3::new(3.0, 1.0, 0.0),
                Point3::new(4.0, 0.0, 0.0),
            ],
            vec![1.0, 1.0, 1.0, 1.0, 1.0],
        )
        .expect("valid")
    }

    #[test]
    fn bezier_decompose_single_span() {
        let c = cubic_bezier();
        let segs = curve_to_bezier_segments(&c).expect("valid");
        assert_eq!(segs.len(), 1);
        // The single segment should match the original curve.
        for i in 0..=10 {
            let u = i as f64 / 10.0;
            let p1 = c.evaluate(u);
            let p2 = segs[0].evaluate(u);
            assert!(
                (p1.x() - p2.x()).abs() < 1e-12 && (p1.y() - p2.y()).abs() < 1e-12,
                "mismatch at u={u}"
            );
        }
    }

    #[test]
    fn bezier_decompose_multi_span() {
        let c = multi_span_curve();
        let segs = curve_to_bezier_segments(&c).expect("valid");
        assert!(segs.len() >= 2, "expected at least 2 segments");

        // Each segment should be degree 3 with 4 control points.
        for seg in &segs {
            assert_eq!(seg.degree(), 3);
            assert_eq!(seg.control_points().len(), 4);
        }
    }

    #[test]
    fn degree_elevate_preserves_shape() {
        let c = cubic_bezier();
        let elevated = curve_degree_elevate(&c, 1).expect("valid");
        assert_eq!(elevated.degree(), 4);

        for i in 0..=10 {
            let u = i as f64 / 10.0;
            let p1 = c.evaluate(u);
            let p2 = elevated.evaluate(u);
            assert!(
                (p1.x() - p2.x()).abs() < 1e-10 && (p1.y() - p2.y()).abs() < 1e-10,
                "mismatch at u={u}: ({},{}) vs ({},{})",
                p1.x(),
                p1.y(),
                p2.x(),
                p2.y()
            );
        }
    }

    #[test]
    fn degree_elevate_by_two() {
        let c = cubic_bezier();
        let elevated = curve_degree_elevate(&c, 2).expect("valid");
        assert_eq!(elevated.degree(), 5);

        for i in 0..=10 {
            let u = i as f64 / 10.0;
            let p1 = c.evaluate(u);
            let p2 = elevated.evaluate(u);
            assert!(
                (p1.x() - p2.x()).abs() < 1e-9 && (p1.y() - p2.y()).abs() < 1e-9,
                "mismatch at u={u}"
            );
        }
    }

    // ── Surface Bezier decomposition tests ────────────────

    fn bilinear_surface() -> NurbsSurface {
        NurbsSurface::new(
            1,
            1,
            vec![0.0, 0.0, 1.0, 1.0],
            vec![0.0, 0.0, 1.0, 1.0],
            vec![
                vec![Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 0.0, 0.0)],
                vec![Point3::new(0.0, 1.0, 0.0), Point3::new(1.0, 1.0, 0.0)],
            ],
            vec![vec![1.0, 1.0], vec![1.0, 1.0]],
        )
        .expect("valid")
    }

    fn quadratic_surface_multi_span() -> NurbsSurface {
        // Degree 2×2 with an interior knot at u=0.5 and v=0.5
        NurbsSurface::new(
            2,
            2,
            vec![0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0],
            vec![0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0],
            vec![
                vec![
                    Point3::new(0.0, 0.0, 0.0),
                    Point3::new(0.25, 0.0, 0.1),
                    Point3::new(0.5, 0.0, 0.0),
                    Point3::new(1.0, 0.0, 0.0),
                ],
                vec![
                    Point3::new(0.0, 0.25, 0.1),
                    Point3::new(0.25, 0.25, 0.5),
                    Point3::new(0.5, 0.25, 0.1),
                    Point3::new(1.0, 0.25, 0.1),
                ],
                vec![
                    Point3::new(0.0, 0.5, 0.0),
                    Point3::new(0.25, 0.5, 0.1),
                    Point3::new(0.5, 0.5, 0.0),
                    Point3::new(1.0, 0.5, 0.0),
                ],
                vec![
                    Point3::new(0.0, 1.0, 0.0),
                    Point3::new(0.25, 1.0, 0.0),
                    Point3::new(0.5, 1.0, 0.0),
                    Point3::new(1.0, 1.0, 0.0),
                ],
            ],
            vec![vec![1.0; 4]; 4],
        )
        .expect("valid")
    }

    #[test]
    fn bezier_patches_single_span() {
        let surf = bilinear_surface();
        let patches = surface_to_bezier_patches(&surf).expect("valid");
        assert_eq!(patches.len(), 1, "single-span surface = 1 patch");

        // Patch should evaluate identically to original
        for i in 0..=4 {
            for j in 0..=4 {
                let u = i as f64 / 4.0;
                let v = j as f64 / 4.0;
                let p1 = surf.evaluate(u, v);
                let p2 = patches[0].surface.evaluate(u, v);
                assert!(
                    (p1.x() - p2.x()).abs() < 1e-10
                        && (p1.y() - p2.y()).abs() < 1e-10
                        && (p1.z() - p2.z()).abs() < 1e-10,
                    "mismatch at ({u}, {v})"
                );
            }
        }
    }

    #[test]
    fn bezier_patches_cover_surface() {
        let surf = quadratic_surface_multi_span();
        let patches = surface_to_bezier_patches(&surf).expect("valid");

        // With interior knots at u=0.5 and v=0.5, should produce 2×2 = 4 patches
        assert!(
            patches.len() >= 4,
            "expected at least 4 patches, got {}",
            patches.len()
        );

        // Each patch should be degree 2×2 with 3×3 = 9 control points
        for patch in &patches {
            assert_eq!(patch.surface.degree_u(), 2);
            assert_eq!(patch.surface.degree_v(), 2);
            assert_eq!(patch.surface.control_points().len(), 3);
            assert_eq!(patch.surface.control_points()[0].len(), 3);
        }

        // Evaluate at patch midpoints and verify they match original surface
        for patch in &patches {
            let u_mid = (patch.u_range.0 + patch.u_range.1) * 0.5;
            let v_mid = (patch.v_range.0 + patch.v_range.1) * 0.5;

            let p_orig = surf.evaluate(u_mid, v_mid);
            // Map to local patch parameter
            let patch_u = (u_mid - patch.u_range.0) / (patch.u_range.1 - patch.u_range.0);
            let patch_v = (v_mid - patch.v_range.0) / (patch.v_range.1 - patch.v_range.0);
            // Bezier patch uses its own knot domain
            let pu = patch.surface.domain_u();
            let pv = patch.surface.domain_v();
            let local_u = pu.0 + patch_u * (pu.1 - pu.0);
            let local_v = pv.0 + patch_v * (pv.1 - pv.0);
            let p_patch = patch.surface.evaluate(local_u, local_v);

            assert!(
                (p_orig.x() - p_patch.x()).abs() < 1e-8
                    && (p_orig.y() - p_patch.y()).abs() < 1e-8
                    && (p_orig.z() - p_patch.z()).abs() < 1e-8,
                "patch mismatch at ({u_mid}, {v_mid}): orig=({},{},{}), patch=({},{},{})",
                p_orig.x(),
                p_orig.y(),
                p_orig.z(),
                p_patch.x(),
                p_patch.y(),
                p_patch.z()
            );
        }
    }

    #[test]
    fn bezier_patch_aabb_and_diagonal() {
        let surf = bilinear_surface();
        let patches = surface_to_bezier_patches(&surf).expect("valid");
        let patch = &patches[0];
        let diag = patch.diagonal();
        // Unit square on XY plane: diagonal ≈ sqrt(2)
        assert!(
            (diag - std::f64::consts::SQRT_2).abs() < 0.1,
            "expected diagonal ≈ √2, got {diag}"
        );
    }

    /// The point at `s` along homogeneous Bezier control points `q`.
    fn bezier_at(q: &[[f64; 4]], s: f64) -> Point3 {
        let mut d = q.to_vec();
        for r in 1..d.len() {
            for j in 0..d.len() - r {
                for c in 0..4 {
                    d[j][c] = (1.0 - s) * d[j][c] + s * d[j + 1][c];
                }
            }
        }
        let [x, y, z, w] = d[0];
        Point3::new(x / w, y / w, z / w)
    }

    /// A rational cubic with an unclamped knot vector: domain `[0.2, 1.0]`,
    /// spans `[0.2, 0.5]`, `[0.5, 0.7]`, `[0.7, 1.0]`.
    fn unclamped_rational_cubic() -> NurbsCurve {
        NurbsCurve::new(
            3,
            vec![-0.3, -0.1, 0.0, 0.2, 0.5, 0.7, 1.0, 1.2, 1.4, 1.5],
            vec![
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(1.0, 2.0, 0.5),
                Point3::new(2.0, -1.0, 1.0),
                Point3::new(3.0, 2.0, 0.0),
                Point3::new(4.0, 0.5, -1.0),
                Point3::new(5.0, 1.0, 0.0),
            ],
            vec![1.0, 0.7, 1.3, 0.9, 1.1, 0.8],
        )
        .expect("valid")
    }

    /// The Bezier form between two parameters traces the curve between them,
    /// in either direction, on part of a span, a whole span, and the span
    /// ending the domain.
    #[test]
    fn bezier_between_traces_the_curve_between_its_parameters() {
        let curve = unclamped_rational_cubic();
        for (a, b) in [
            (0.25, 0.45),
            (0.45, 0.25),
            (0.5, 0.7),
            (0.7, 1.0),
            (1.0, 0.7),
        ] {
            let q = curve_bezier_between(&curve, a, b).expect("one span");
            assert_eq!(q.len(), 4);
            for k in 0..=8 {
                let s = f64::from(k) / 8.0;
                let on_curve = curve.evaluate(a + s * (b - a));
                let gap = (bezier_at(&q, s) - on_curve).length();
                assert!(gap < 1e-12, "({a}, {b}) at {s}: {gap}");
            }
        }
    }

    /// Parameters across a knot or outside the domain have no single span.
    #[test]
    fn bezier_between_refuses_more_than_one_span() {
        let curve = unclamped_rational_cubic();
        assert!(curve_bezier_between(&curve, 0.4, 0.6).is_err());
        assert!(curve_bezier_between(&curve, 0.1, 0.3).is_err());
        assert!(curve_bezier_between(&curve, 0.9, 1.1).is_err());
    }

    /// A curve's Bezier pieces trace it: each at 7 points inside its span
    /// holds the curve to 1e-12 there (a curve of degree zero jumps at its
    /// knots).
    fn pieces_trace(c: &NurbsCurve, spans: usize) {
        let segs = curve_to_bezier_segments(c).expect("valid");
        assert_eq!(segs.len(), spans);
        for seg in &segs {
            let (a, b) = seg.domain();
            for k in 1..8 {
                let t = (b - a).madd(f64::from(k) / 8.0, a);
                let off = (seg.evaluate(t) - c.evaluate(t)).length();
                assert!(off < 1e-12, "at {t}: {off}");
            }
        }
    }

    /// A degree-1 side on knots 0, 0, 0.5, 0.5, 1, 1 through its ends and its
    /// middle twice, an interior knot repeated past the degree: two pieces.
    #[test]
    fn a_knot_repeated_past_the_degree_cuts_two_pieces() {
        let p = Point3::new;
        let c = NurbsCurve::new(
            1,
            vec![0.0, 0.0, 0.5, 0.5, 1.0, 1.0],
            vec![
                p(1.0, 1.0, 0.0),
                p(0.0, 1.0, 0.0),
                p(0.0, 1.0, 0.0),
                p(-1.0, 1.0, 0.0),
            ],
            vec![1.0; 4],
        )
        .expect("valid");
        pieces_trace(&c, 2);
    }

    /// A degree-0 curve on knots 0, 0.5, 1: two constant pieces.
    #[test]
    fn a_degree_zero_curve_cuts_into_its_spans() {
        let p = Point3::new;
        let c = NurbsCurve::new(
            0,
            vec![0.0, 0.5, 1.0],
            vec![p(0.0, 0.0, 0.0), p(1.0, 0.0, 0.0)],
            vec![1.0; 2],
        )
        .expect("valid");
        pieces_trace(&c, 2);
    }

    /// A cubic on the uniform knots 0 to 7, not clamped: the pieces of its
    /// domain, 3 to 4, cut at its knots.
    #[test]
    fn a_curve_not_clamped_cuts_into_its_domains_spans() {
        let c = NurbsCurve::new(
            3,
            (0..8).map(f64::from).collect(),
            vec![
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(1.0, 2.0, 0.0),
                Point3::new(3.0, -1.0, 1.0),
                Point3::new(4.0, 1.0, 0.0),
            ],
            vec![1.0, 2.0, 0.5, 1.0],
        )
        .expect("valid");
        pieces_trace(&c, 1);
    }

    /// A quadratic weighted 1, 0, 1: its piece evaluates as it does, the
    /// zero-weight pole kept rather than divided by.
    #[test]
    fn a_zero_weight_pole_cuts_a_piece_that_traces_the_curve() {
        let p = Point3::new;
        let c = NurbsCurve::new(
            2,
            vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
            vec![p(0.0, 0.0, 0.0), p(1.0, 1.0, 0.0), p(2.0, 0.0, 0.0)],
            vec![1.0, 0.0, 1.0],
        )
        .expect("valid");
        pieces_trace(&c, 1);
    }

    /// A quadratic on knots -1, -1, -1, -0, 0, 1, 1, 1: -0 and 0 are one
    /// knot, so two pieces and none of no width.
    #[test]
    fn a_signed_zero_knot_cuts_no_piece_of_no_width() {
        let p = Point3::new;
        let c = NurbsCurve::new(
            2,
            vec![-1.0, -1.0, -1.0, -0.0, 0.0, 1.0, 1.0, 1.0],
            vec![
                p(0.0, 0.0, 0.0),
                p(1.0, 1.0, 0.0),
                p(2.0, 0.0, 0.0),
                p(3.0, 1.0, 0.0),
                p(4.0, 0.0, 0.0),
            ],
            vec![1.0; 5],
        )
        .expect("valid");
        pieces_trace(&c, 2);
    }

    /// A degree-1 curve that jumps at 0.5, its knot repeated past its
    /// degree: raised to degree 3, it still jumps there, and traces the
    /// curve inside each span.
    #[test]
    fn a_curve_raised_in_degree_keeps_its_jump() {
        let p = Point3::new;
        let c = NurbsCurve::new(
            1,
            vec![0.0, 0.0, 0.5, 0.5, 1.0, 1.0],
            vec![
                p(0.0, 0.0, 0.0),
                p(1.0, 0.0, 0.0),
                p(1.0, 2.0, 0.0),
                p(2.0, 2.0, 0.0),
            ],
            vec![1.0; 4],
        )
        .expect("valid");
        let raised = curve_degree_elevate(&c, 2).expect("valid");
        assert_eq!(raised.degree(), 3);
        for t in [0.1, 0.25, 0.4, 0.6, 0.75, 0.9] {
            let off = (raised.evaluate(t) - c.evaluate(t)).length();
            assert!(off < 1e-12, "at {t}: {off}");
        }
    }

    #[test]
    fn a_jump_raised_in_degree_does_not_hang_on_the_weights_scale() {
        let p = Point3::new;
        for w in [1.0, 1e-14, 1e14] {
            let c = NurbsCurve::new(
                1,
                vec![0.0, 0.0, 0.5, 0.5, 1.0, 1.0],
                vec![
                    p(0.0, 0.0, 0.0),
                    p(1.0, 0.0, 0.0),
                    p(10.0, 0.0, 0.0),
                    p(11.0, 0.0, 0.0),
                ],
                vec![w; 4],
            )
            .expect("valid");
            let raised = curve_degree_elevate(&c, 2).expect("valid");
            for t in [0.1, 0.25, 0.4, 0.6, 0.75, 0.9] {
                let off = (raised.evaluate(t) - c.evaluate(t)).length();
                assert!(off < 1e-9, "weights {w}, at {t}: {off}");
            }
        }
    }

    #[test]
    fn a_span_whose_weights_cancel_to_a_pole_at_infinity_cuts_no_piece() {
        let p = Point3::new;
        let c = NurbsCurve::new(
            3,
            vec![0.0, 0.0, 1.0, 2.0, 3.0, 5.0, 5.0, 5.0],
            vec![
                p(0.0, 0.0, 0.0),
                p(1.0, 0.0, 0.0),
                p(2.0, 0.0, 0.0),
                p(3.0, 0.0, 0.0),
            ],
            vec![10.0, -1.0, 3.0, 1.0],
        )
        .expect("valid");
        let q = curve_bezier_between(&c, 2.0, 3.0).expect("in one span");
        assert!(
            q.iter().any(|h| h[3] == 0.0 && h[0] != 0.0),
            "no pole at infinity: {q:?}"
        );
        assert!(matches!(
            curve_to_bezier_segments(&c),
            Err(MathError::PoleAtInfinity { .. })
        ));
    }

    #[test]
    fn a_curve_continuous_at_its_knots_raised_in_degree_stays_joined() {
        let p = Point3::new;
        let c = NurbsCurve::new(
            2,
            vec![0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, 1.0],
            vec![
                p(0.0, 0.0, 0.0),
                p(1.0, 1.0, 0.0),
                p(2.0, 0.0, 0.0),
                p(3.0, 1.0, 0.0),
                p(4.0, 0.0, 0.0),
            ],
            vec![1.0, 2.0, 1.0, 0.5, 1.0],
        )
        .expect("valid");
        let raised = curve_degree_elevate(&c, 1).expect("valid");
        assert_eq!(raised.control_points().len(), 7);
        for t in [0.1, 0.25, 0.4, 0.5, 0.6, 0.75, 0.9] {
            let off = (raised.evaluate(t) - c.evaluate(t)).length();
            assert!(off < 1e-12, "at {t}: {off}");
        }
    }

    /// Rows of a rational quadratic whose weights change sign: raising its
    /// knot at 1 to full multiplicity puts a control point at infinity, and
    /// the patches are refused rather than built from the bare numerator.
    #[test]
    fn a_surface_whose_refinement_puts_a_point_at_infinity_is_refused() {
        let p = Point3::new;
        let row = |z: f64| {
            vec![
                p(0.0, 0.0, z),
                p(1.0, 1.0, z),
                p(2.0, 0.0, z),
                p(3.0, 1.0, z),
            ]
        };
        let s = NurbsSurface::new(
            2,
            1,
            vec![0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0],
            vec![0.0, 0.0, 1.0, 1.0],
            transpose(&[row(0.0), row(1.0)]),
            vec![vec![1.0; 2], vec![1.0; 2], vec![-1.0; 2], vec![1.0; 2]],
        )
        .expect("valid");
        assert!(matches!(
            surface_to_bezier_patches(&s),
            Err(MathError::PoleAtInfinity { .. })
        ));
    }

    /// A surface's Bezier patches trace it: each at 7 by 7 points inside its
    /// ranges holds the surface to 1e-12 there (a direction of degree zero
    /// jumps at its knots).
    fn patches_trace(s: &NurbsSurface, count: usize) {
        let patches = surface_to_bezier_patches(s).expect("valid");
        assert_eq!(patches.len(), count);
        for patch in &patches {
            assert_eq!(patch.surface.degree_u(), s.degree_u());
            assert_eq!(patch.surface.degree_v(), s.degree_v());
            let ((u0, u1), (v0, v1)) = (patch.u_range, patch.v_range);
            for i in 1..8 {
                let u = (u1 - u0).madd(f64::from(i) / 8.0, u0);
                for j in 1..8 {
                    let v = (v1 - v0).madd(f64::from(j) / 8.0, v0);
                    let off = (patch.surface.evaluate(u, v) - s.evaluate(u, v)).length();
                    assert!(off < 1e-12, "at ({u}, {v}): {off}");
                }
            }
        }
    }

    /// Degree 0 along u on the knots 0, 1, and a line along v: one patch.
    #[test]
    fn a_surface_of_degree_zero_cuts_one_patch() {
        let p = Point3::new;
        let s = NurbsSurface::new(
            0,
            1,
            vec![0.0, 1.0],
            vec![0.0, 0.0, 1.0, 1.0],
            vec![vec![p(0.0, 0.0, 0.0), p(0.0, 1.0, 0.0)]],
            vec![vec![1.0; 2]],
        )
        .expect("valid");
        patches_trace(&s, 1);
    }

    /// Degree 0 along u on the knots 0, 0.25, 0.25, 1 and quadratic along
    /// v: one constant patch for each span of width, two.
    #[test]
    fn a_degree_zero_direction_cuts_a_patch_per_span() {
        let p = Point3::new;
        let row = |x: f64| vec![p(x, 0.0, 0.0), p(x, 1.0, x), p(x, 2.0, 0.0)];
        let s = NurbsSurface::new(
            0,
            2,
            vec![0.0, 0.25, 0.25, 1.0],
            vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
            vec![row(0.0), row(1.0), row(2.0)],
            vec![vec![1.0, 0.5, 1.0]; 3],
        )
        .expect("valid");
        patches_trace(&s, 2);
    }

    /// Degree 0 both ways on the knots 0, 0.5, 1 and 0, 1/3, 2/3, 1: six
    /// constant patches.
    #[test]
    fn a_surface_of_degree_zero_both_ways_cuts_a_patch_per_cell() {
        let s = NurbsSurface::new(
            0,
            0,
            vec![0.0, 0.5, 1.0],
            vec![0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0],
            (0..2)
                .map(|i| {
                    (0..3)
                        .map(|j| Point3::new(f64::from(i), f64::from(j), f64::from(i * j)))
                        .collect()
                })
                .collect(),
            vec![vec![1.0; 3]; 2],
        )
        .expect("valid");
        patches_trace(&s, 6);
    }

    /// A bilinear sheet on the u knots 0, 0, 5e-16, 1, 1: the sheet runs
    /// from its first row to its second inside the narrow span, and a patch
    /// holds that part too.
    #[test]
    fn a_narrow_span_keeps_its_patch() {
        let p = Point3::new;
        let row = |x: f64| vec![p(x, 0.0, 0.0), p(x, 1.0, 0.0)];
        let s = NurbsSurface::new(
            1,
            1,
            vec![0.0, 0.0, 5e-16, 1.0, 1.0],
            vec![0.0, 0.0, 1.0, 1.0],
            vec![row(0.0), row(1.0), row(2.0)],
            vec![vec![1.0; 2]; 3],
        )
        .expect("valid");
        patches_trace(&s, 2);
        let narrow = surface_to_bezier_patches(&s).expect("valid");
        assert!(narrow[0].aabb().min.x() <= 0.0 && narrow[0].aabb().max.x() >= 1.0);
    }

    /// A sheet quadratic along u on the knots 0, 0, 0, 0.5, 0.5 + 2^-51, 1,
    /// 1, 1, two knots nearer than the insertion tells apart: three patches,
    /// each the surface over its span, the narrow one too.
    #[test]
    fn knots_a_hair_apart_cut_patches_on_the_surface() {
        let p = Point3::new;
        let row = |x: f64| vec![p(x, 0.0, 0.0), p(x, 1.0, x)];
        let s = NurbsSurface::new(
            2,
            1,
            vec![0.0, 0.0, 0.0, 0.5, 0.5 + 2f64.powi(-51), 1.0, 1.0, 1.0],
            vec![0.0, 0.0, 1.0, 1.0],
            vec![row(0.0), row(1.0), row(0.0), row(1.0), row(0.0)],
            vec![vec![1.0; 2]; 5],
        )
        .expect("valid");
        patches_trace(&s, 3);
    }

    /// A rational bicubic on the uniform knots 0 to 8 each way, clamped in
    /// neither: its domain is 3 to 5 each way, in four patches on it.
    #[test]
    fn a_surface_not_clamped_cuts_patches_on_its_domain() {
        let points: Vec<Vec<Point3>> = (0..5)
            .map(|i| {
                (0..5)
                    .map(|j| Point3::new(f64::from(i), f64::from(j), f64::from((i * j) % 3) * 2.0))
                    .collect()
            })
            .collect();
        let weights = (0..5)
            .map(|i| {
                (0..5)
                    .map(|j| 1.0 + 0.25 * f64::from((i + j) % 2))
                    .collect()
            })
            .collect();
        let knots: Vec<f64> = (0..9).map(f64::from).collect();
        let s = NurbsSurface::new(3, 3, knots.clone(), knots, points, weights).expect("valid");
        patches_trace(&s, 4);
    }

    /// A sheet quadratic along u on the knots 0 to 5, clamped in neither
    /// end, with the weights 1, -1, 1 along u: its one patch has a control
    /// point at infinity, which the split refuses.
    #[test]
    fn a_patch_with_a_pole_at_infinity_is_refused() {
        let p = Point3::new;
        let row = |x: f64| vec![p(x, 0.0, 0.0), p(x, 1.0, 0.0)];
        let s = NurbsSurface::new(
            2,
            1,
            (0..6).map(f64::from).collect(),
            vec![0.0, 0.0, 1.0, 1.0],
            vec![row(0.0), row(1.0), row(2.0)],
            vec![vec![1.0; 2], vec![-1.0; 2], vec![1.0; 2]],
        )
        .expect("valid");
        assert!(matches!(
            surface_to_bezier_patches(&s),
            Err(MathError::PoleAtInfinity { .. })
        ));
    }

    /// A bilinear sheet on knots 0, 0, 0.5, 0.5, 1, 1 along u, an interior
    /// knot repeated past the degree: two patches, none across the jump.
    #[test]
    fn a_knot_repeated_past_the_degree_cuts_no_patch_across_it() {
        let p = Point3::new;
        let s = NurbsSurface::new(
            1,
            1,
            vec![0.0, 0.0, 0.5, 0.5, 1.0, 1.0],
            vec![0.0, 0.0, 1.0, 1.0],
            vec![
                vec![p(0.0, 0.0, 0.0), p(0.0, 1.0, 0.0)],
                vec![p(1.0, 0.0, 0.0), p(1.0, 1.0, 0.0)],
                vec![p(1.0, 0.0, 1.0), p(1.0, 1.0, 1.0)],
                vec![p(2.0, 0.0, 1.0), p(2.0, 1.0, 1.0)],
            ],
            vec![vec![1.0; 2]; 4],
        )
        .expect("valid");
        patches_trace(&s, 2);
    }
}