BREP_kernel 0.2.0

A boundary representation (BREP) geometry kernel for building CAD applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
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
use super::*;

fn body(id: &str, fixed: bool, rotation: [f64; 4], translation: [f64; 3]) -> AssemblyBody {
    AssemblyBody {
        id: id.into(),
        fixed,
        rotation,
        translation,
    }
}

fn quat_axis_angle(axis: [f64; 3], angle_deg: f64) -> [f64; 4] {
    let axis = vec3(axis).normalized().unwrap();
    let half = angle_deg.to_radians() * 0.5;
    let s = half.sin();
    [half.cos(), s * axis.x, s * axis.y, s * axis.z]
}

fn mate(id: &str, body_a: usize, body_b: usize, kind: MateKind) -> AssemblyMate {
    AssemblyMate {
        id: Some(id.into()),
        body_a,
        body_b,
        kind,
    }
}

fn plane(origin: [f64; 3], normal: [f64; 3]) -> MatePlane {
    MatePlane { origin, normal }
}

fn axis(origin: [f64; 3], direction: [f64; 3]) -> MateAxis {
    MateAxis { origin, direction }
}

fn rot(sol: &AssemblySolution, body: usize, v: [f64; 3]) -> Vec3 {
    quat_rotate(sol.poses[body].rotation, vec3(v))
}

fn assert_close(actual: Vec3, expected: [f64; 3], tol: f64, what: &str) {
    let d = actual.sub(vec3(expected)).length();
    assert!(
        d <= tol,
        "{what}: expected {:?}, got ({}, {}, {}) (delta {d:.3e})",
        expected,
        actual.x,
        actual.y,
        actual.z
    );
}

/// Two unit boxes: B stacked flush on top of A (three plane-plane
/// coincidents on mutually perpendicular faces → unique pose).
fn stacked_boxes_mates(a: usize, b: usize) -> Vec<AssemblyMate> {
    vec![
        // A's top face against B's bottom face (normals opposed).
        mate(
            "top-bottom",
            a,
            b,
            MateKind::CoincidentPlanePlane {
                plane_a: plane([0.0, 0.0, 1.0], [0.0, 0.0, 1.0]),
                plane_b: plane([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]),
                align: MateAlign::AntiAligned,
            },
        ),
        // Left faces flush (normals aligned) — perpendicular to the first.
        mate(
            "left-flush",
            a,
            b,
            MateKind::CoincidentPlanePlane {
                plane_a: plane([0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]),
                plane_b: plane([0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]),
                align: MateAlign::Aligned,
            },
        ),
        // Front faces flush — perpendicular to both.
        mate(
            "front-flush",
            a,
            b,
            MateKind::CoincidentPlanePlane {
                plane_a: plane([0.0, 0.0, 0.0], [0.0, -1.0, 0.0]),
                plane_b: plane([0.0, 0.0, 0.0], [0.0, -1.0, 0.0]),
                align: MateAlign::Aligned,
            },
        ),
    ]
}

/// (1) Two boxes, one plane-plane coincident plus two perpendicular
/// plane-plane coincidents → unique pose, exact.
#[test]
fn boxes_three_plane_coincidents_unique_pose() {
    let bodies = vec![
        body("base", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body(
            "lid",
            false,
            quat_axis_angle([1.0, 1.0, 0.3], 20.0),
            [0.3, -0.2, 0.5],
        ),
    ];
    let mates = stacked_boxes_mates(0, 1);
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();

    assert_close(
        vec3(sol.poses[1].translation),
        [0.0, 0.0, 1.0],
        1e-9,
        "lid translation",
    );
    assert_close(
        rot(&sol, 1, [1.0, 0.0, 0.0]),
        [1.0, 0.0, 0.0],
        1e-9,
        "lid x-axis",
    );
    assert_close(
        rot(&sol, 1, [0.0, 0.0, 1.0]),
        [0.0, 0.0, 1.0],
        1e-9,
        "lid z-axis",
    );
    assert_eq!(sol.dof, 0, "unique pose leaves no DOF");
    assert_eq!(sol.rank, 6);
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );
    assert_eq!(sol.mate_residuals.len(), 3);
    // Three plane coincidents over-specify rotation: redundant but consistent.
    assert_eq!(sol.redundant, 3);
    assert_eq!(sol.status, "over");
}

/// (2) Shaft in hole: concentric + plane-plane distance → position exact,
/// spin about the axis stays a free DOF (reported as dof == 1).
#[test]
fn shaft_in_hole_concentric_plus_distance() {
    let bodies = vec![
        body("block", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body(
            "shaft",
            false,
            quat_axis_angle([1.0, 0.4, 0.0], 10.0),
            [0.2, -0.3, 0.7],
        ),
    ];
    let mates = vec![
        mate(
            "bore",
            0,
            1,
            MateKind::ConcentricAxisAxis {
                axis_a: axis([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
                axis_b: axis([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
                align: MateAlign::Any,
            },
        ),
        mate(
            "standoff",
            0,
            1,
            MateKind::DistancePlanePlane {
                plane_a: plane([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
                plane_b: plane([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]),
                distance: 0.25,
                align: MateAlign::AntiAligned,
            },
        ),
    ];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();

    assert_close(
        vec3(sol.poses[1].translation),
        [0.0, 0.0, 0.25],
        1e-9,
        "shaft translation",
    );
    assert_close(
        rot(&sol, 1, [0.0, 0.0, 1.0]),
        [0.0, 0.0, 1.0],
        1e-9,
        "shaft axis",
    );
    assert_eq!(sol.dof, 1, "spin about the bore axis must stay free");
    assert_eq!(sol.rank, 5);
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );
}

/// (3) Angle mate: two plates hinged about a shared axis at 45 degrees.
#[test]
fn angle_mate_45_between_plates() {
    let bodies = vec![
        body("plate_a", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body(
            "plate_b",
            false,
            quat_axis_angle([1.0, 0.0, 0.0], 30.0),
            [0.05, -0.02, 0.04],
        ),
    ];
    let mates = vec![
        mate(
            "hinge-pin",
            0,
            1,
            MateKind::ConcentricAxisAxis {
                axis_a: axis([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]),
                axis_b: axis([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]),
                align: MateAlign::Aligned,
            },
        ),
        mate(
            "hinge-end",
            0,
            1,
            MateKind::CoincidentPointPoint {
                point_a: [0.0, 0.0, 0.0],
                point_b: [0.0, 0.0, 0.0],
            },
        ),
        mate(
            "open-45",
            0,
            1,
            MateKind::Angle {
                direction_a: [0.0, 0.0, 1.0],
                direction_b: [0.0, 0.0, 1.0],
                angle_deg: 45.0,
            },
        ),
    ];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();

    let half = std::f64::consts::FRAC_1_SQRT_2;
    assert_close(
        vec3(sol.poses[1].translation),
        [0.0, 0.0, 0.0],
        1e-9,
        "hinge origin",
    );
    assert_close(
        rot(&sol, 1, [1.0, 0.0, 0.0]),
        [1.0, 0.0, 0.0],
        1e-9,
        "hinge axis",
    );
    // R_x(45°)·ẑ = (0, −sin45, cos45); descent from +30° lands on +45°.
    assert_close(
        rot(&sol, 1, [0.0, 0.0, 1.0]),
        [0.0, -half, half],
        1e-9,
        "plate normal",
    );
    assert_eq!(sol.dof, 0);
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );
}

/// (4) Over-constrained conflict: two contradictory distances on the same
/// point pair → Err naming the conflicting mates.
#[test]
fn conflicting_distances_err() {
    let bodies = vec![
        body("base", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body("part", false, identity_rotation(), [1.4, 0.0, 0.0]),
    ];
    let mates = vec![
        mate(
            "d1",
            0,
            1,
            MateKind::DistancePointPoint {
                point_a: [0.0, 0.0, 0.0],
                point_b: [0.0, 0.0, 0.0],
                distance: 1.0,
            },
        ),
        mate(
            "d2",
            0,
            1,
            MateKind::DistancePointPoint {
                point_a: [0.0, 0.0, 0.0],
                point_b: [0.0, 0.0, 0.0],
                distance: 2.0,
            },
        ),
    ];
    let err = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap_err();
    assert!(
        err.contains("conflict"),
        "error must flag the conflict: {err}"
    );
    assert!(
        err.contains("d1") && err.contains("d2"),
        "error must name the conflicting mates: {err}"
    );
}

/// (5) Chain of three bodies (A grounded, B mated to A, C mated to B)
/// solves in one shot.
#[test]
fn chain_of_three_bodies_one_shot() {
    let bodies = vec![
        body("a", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body(
            "b",
            false,
            quat_axis_angle([0.2, 1.0, 0.1], 15.0),
            [0.2, -0.1, 0.6],
        ),
        body(
            "c",
            false,
            quat_axis_angle([1.0, 0.0, 1.0], -10.0),
            [0.1, 0.3, 1.4],
        ),
    ];
    let mut mates = stacked_boxes_mates(0, 1);
    mates.extend(stacked_boxes_mates(1, 2));
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();

    assert_close(
        vec3(sol.poses[1].translation),
        [0.0, 0.0, 1.0],
        1e-9,
        "b translation",
    );
    assert_close(
        vec3(sol.poses[2].translation),
        [0.0, 0.0, 2.0],
        1e-9,
        "c translation",
    );
    for bi in [1usize, 2] {
        assert_close(
            rot(&sol, bi, [1.0, 0.0, 0.0]),
            [1.0, 0.0, 0.0],
            1e-9,
            "x-axis",
        );
        assert_close(
            rot(&sol, bi, [0.0, 0.0, 1.0]),
            [0.0, 0.0, 1.0],
            1e-9,
            "z-axis",
        );
    }
    assert_eq!(sol.dof, 0);
    assert_eq!(sol.rank, 12);
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );
}

/// (6) Determinism: the same input yields bit-identical solutions.
#[test]
fn determinism_bit_identical() {
    let bodies = vec![
        body("block", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body(
            "shaft",
            false,
            quat_axis_angle([1.0, 0.4, 0.0], 10.0),
            [0.2, -0.3, 0.7],
        ),
    ];
    let mates = vec![
        mate(
            "bore",
            0,
            1,
            MateKind::ConcentricAxisAxis {
                axis_a: axis([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
                axis_b: axis([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
                align: MateAlign::Any,
            },
        ),
        mate(
            "standoff",
            0,
            1,
            MateKind::DistancePlanePlane {
                plane_a: plane([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
                plane_b: plane([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]),
                distance: 0.25,
                align: MateAlign::AntiAligned,
            },
        ),
    ];
    let opts = AssemblySolveOptions::default();
    let runs: Vec<AssemblySolution> = (0..3)
        .map(|_| solve_assembly(&bodies, &mates, &opts).unwrap())
        .collect();
    for run in &runs[1..] {
        for (pa, pb) in runs[0].poses.iter().zip(&run.poses) {
            for c in 0..4 {
                assert_eq!(
                    pa.rotation[c].to_bits(),
                    pb.rotation[c].to_bits(),
                    "rotation must be bit-identical"
                );
            }
            for c in 0..3 {
                assert_eq!(
                    pa.translation[c].to_bits(),
                    pb.translation[c].to_bits(),
                    "translation must be bit-identical"
                );
            }
        }
        assert_eq!(runs[0].max_residual.to_bits(), run.max_residual.to_bits());
        assert_eq!(runs[0].iterations, run.iterations);
    }
    // Serialized forms match too (serde round-trip is shortest-float exact).
    let json0 = serde_json::to_string(&runs[0]).unwrap();
    let json1 = serde_json::to_string(&runs[1]).unwrap();
    assert_eq!(json0, json1);
}

/// Tangent mates: sphere-plane rests a ball on a table (free DOF keep the
/// initial guess — minimum-norm steps); cylinder-plane lays a rod flat.
#[test]
fn tangent_sphere_and_cylinder_on_plane() {
    // Ball of radius 0.5 dropped onto the z=0 table of a grounded body.
    let bodies = vec![
        body("table", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body("ball", false, identity_rotation(), [0.1, 0.2, 1.3]),
    ];
    let mates = vec![mate(
        "rest",
        1,
        0,
        MateKind::TangentSpherePlane {
            center_a: [0.0, 0.0, 0.0],
            radius: 0.5,
            plane_b: plane([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    assert_close(
        vec3(sol.poses[1].translation),
        [0.1, 0.2, 0.5],
        1e-9,
        "ball keeps x/y, drops to r above the table",
    );
    assert_eq!(sol.dof, 5);
    assert!(sol.max_residual <= 1e-9);

    // Rod of radius 0.3 laid flat: axis parallel to the table at height r.
    let bodies = vec![
        body("table", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body(
            "rod",
            false,
            quat_axis_angle([0.0, 1.0, 0.0], 5.0),
            [0.0, 0.0, 1.0],
        ),
    ];
    let mates = vec![mate(
        "lay-flat",
        1,
        0,
        MateKind::TangentCylinderPlane {
            axis_a: axis([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]),
            radius: 0.3,
            plane_b: plane([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    assert!(
        (sol.poses[1].translation[2] - 0.3).abs() <= 1e-9,
        "rod axis height {}",
        sol.poses[1].translation[2]
    );
    let axis_w = rot(&sol, 1, [1.0, 0.0, 0.0]);
    assert!(
        axis_w.z.abs() <= 1e-9,
        "rod axis parallel to table: z = {}",
        axis_w.z
    );
    assert_eq!(sol.dof, 4);
    assert!(sol.max_residual <= 1e-9);
}

/// Parallel (either sense) and perpendicular direction mates.
#[test]
fn parallel_any_and_perpendicular() {
    // Nearly opposed directions with align=Any converge to anti-parallel.
    let bodies = vec![
        body("a", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body(
            "b",
            false,
            quat_axis_angle([1.0, 0.0, 0.0], 170.0),
            [0.0, 0.0, 0.0],
        ),
    ];
    let mates = vec![mate(
        "par",
        0,
        1,
        MateKind::Parallel {
            direction_a: [0.0, 0.0, 1.0],
            direction_b: [0.0, 0.0, 1.0],
            align: MateAlign::Any,
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    let d = rot(&sol, 1, [0.0, 0.0, 1.0]).dot(Vec3::new(0.0, 0.0, 1.0));
    assert!((d.abs() - 1.0).abs() <= 1e-9, "parallel-any dot {d}");
    assert!(d < 0.0, "nearest sense from 170 degrees is anti-parallel");
    assert_eq!(sol.dof, 4);

    // Perpendicular from an 80-degree start closes to 90 degrees.
    let bodies = vec![
        body("a", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body(
            "b",
            false,
            quat_axis_angle([1.0, 0.0, 0.0], 80.0),
            [0.0, 0.0, 0.0],
        ),
    ];
    let mates = vec![mate(
        "perp",
        0,
        1,
        MateKind::Perpendicular {
            direction_a: [0.0, 0.0, 1.0],
            direction_b: [0.0, 0.0, 1.0],
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    let d = rot(&sol, 1, [0.0, 0.0, 1.0]).dot(Vec3::new(0.0, 0.0, 1.0));
    assert!(d.abs() <= 1e-9, "perpendicular dot {d}");
    assert_eq!(sol.dof, 5);
}

/// Input validation: bad body indices, self-mates, degenerate normals.
#[test]
fn validation_errors() {
    let bodies = vec![
        body("a", true, identity_rotation(), [0.0, 0.0, 0.0]),
        body("b", false, identity_rotation(), [0.0, 0.0, 0.0]),
    ];
    let opts = AssemblySolveOptions::default();

    let bad_index = vec![mate(
        "m",
        0,
        7,
        MateKind::CoincidentPointPoint {
            point_a: [0.0; 3],
            point_b: [0.0; 3],
        },
    )];
    assert!(solve_assembly(&bodies, &bad_index, &opts)
        .unwrap_err()
        .contains("out of range"));

    let self_mate = vec![mate(
        "m",
        1,
        1,
        MateKind::CoincidentPointPoint {
            point_a: [0.0; 3],
            point_b: [0.0; 3],
        },
    )];
    assert!(solve_assembly(&bodies, &self_mate, &opts)
        .unwrap_err()
        .contains("must differ"));

    let zero_normal = vec![mate(
        "m",
        0,
        1,
        MateKind::CoincidentPointPlane {
            point_a: [0.0; 3],
            plane_b: plane([0.0; 3], [0.0; 3]),
        },
    )];
    assert!(solve_assembly(&bodies, &zero_normal, &opts)
        .unwrap_err()
        .contains("nonzero"));

    let bad_quat = vec![body("a", false, [0.0; 4], [0.0; 3])];
    assert!(solve_assembly(&bad_quat, &[], &opts)
        .unwrap_err()
        .contains("quaternion"));
}

/// No mates: every movable body keeps its pose; all DOF free.
#[test]
fn no_mates_trivial() {
    let bodies = vec![
        body("a", true, identity_rotation(), [1.0, 2.0, 3.0]),
        body(
            "b",
            false,
            quat_axis_angle([0.0, 0.0, 1.0], 30.0),
            [4.0, 5.0, 6.0],
        ),
    ];
    let sol = solve_assembly(&bodies, &[], &AssemblySolveOptions::default()).unwrap();
    assert_eq!(sol.poses.len(), 2);
    assert_eq!(sol.dof, 6);
    assert_eq!(sol.rank, 0);
    assert_eq!(sol.status, "under");
    assert_eq!(sol.max_residual, 0.0);
    assert_close(
        vec3(sol.poses[1].translation),
        [4.0, 5.0, 6.0],
        0.0,
        "pose kept",
    );
}

/// Serde round-trip of the public request/response types (the WASM layer
/// will speak JSON).
#[test]
fn serde_round_trip() {
    let mates = vec![
        mate(
            "bore",
            0,
            1,
            MateKind::ConcentricAxisAxis {
                axis_a: axis([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
                axis_b: axis([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
                align: MateAlign::Any,
            },
        ),
        mate(
            "open-45",
            0,
            1,
            MateKind::Angle {
                direction_a: [0.0, 0.0, 1.0],
                direction_b: [0.0, 0.0, 1.0],
                angle_deg: 45.0,
            },
        ),
    ];
    let json = serde_json::to_string(&mates).unwrap();
    assert!(json.contains("\"type\":\"concentric_axis_axis\""), "{json}");
    assert!(json.contains("\"type\":\"angle\""), "{json}");
    let back: Vec<AssemblyMate> = serde_json::from_str(&json).unwrap();
    assert_eq!(back.len(), 2);
    match &back[0].kind {
        MateKind::ConcentricAxisAxis { align, .. } => assert_eq!(*align, MateAlign::Any),
        other => panic!("wrong kind after round-trip: {other:?}"),
    }
    // Defaults: align omitted deserializes to the documented default.
    let coincident: AssemblyMate = serde_json::from_str(
        r#"{"body_a":0,"body_b":1,"type":"coincident_plane_plane",
                "plane_a":{"origin":[0,0,1],"normal":[0,0,1]},
                "plane_b":{"origin":[0,0,0],"normal":[0,0,-1]}}"#,
    )
    .unwrap();
    match coincident.kind {
        MateKind::CoincidentPlanePlane { align, .. } => {
            assert_eq!(align, MateAlign::AntiAligned)
        }
        other => panic!("wrong kind: {other:?}"),
    }
}

// -----------------------------------------------------------------------
// §7.5–7.6 decomposition tests
// -----------------------------------------------------------------------

fn opts(strategy: SolveStrategy) -> AssemblySolveOptions {
    AssemblySolveOptions {
        strategy,
        ..AssemblySolveOptions::default()
    }
}

/// Chain options: a tighter tolerance than the default so both strategies
/// converge comfortably below the 1e-9 pose-agreement assertions (the
/// chain's scale is ~10, so the default absolute target is only ~1e-9).
fn chain_opts(strategy: SolveStrategy) -> AssemblySolveOptions {
    AssemblySolveOptions {
        strategy,
        tolerance: 1e-11,
        ..AssemblySolveOptions::default()
    }
}

/// Grounded body `g` plus `n` movable unit boxes stacked into a chain,
/// each fully mated (three plane coincidents) to the previous one, with
/// per-body rotation/translation errors in the initial guesses.
fn chain_bodies(n: usize) -> (Vec<AssemblyBody>, Vec<AssemblyMate>) {
    let mut bodies = vec![body("g", true, identity_rotation(), [0.0; 3])];
    for i in 1..=n {
        let fi = i as f64;
        bodies.push(body(
            &format!("b{i}"),
            false,
            quat_axis_angle([0.2 + 0.07 * fi, 1.0, 0.3 - 0.04 * fi], 10.0 + 2.5 * fi),
            [0.15 - 0.02 * fi, 0.1 * ((i % 3) as f64) - 0.1, fi + 0.35],
        ));
    }
    let mut mates = Vec::new();
    for i in 0..n {
        mates.extend(stacked_boxes_mates(i, i + 1));
    }
    (bodies, mates)
}

fn assert_poses_close(a: &AssemblySolution, b: &AssemblySolution, tol: f64, what: &str) {
    assert_eq!(a.poses.len(), b.poses.len());
    for i in 0..a.poses.len() {
        let dt = vec3(a.poses[i].translation)
            .sub(vec3(b.poses[i].translation))
            .length();
        assert!(dt <= tol, "{what}: body {i} translation delta {dt:.3e}");
        for axis in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] {
            let da = rot(a, i, axis).sub(rot(b, i, axis)).length();
            assert!(da <= tol, "{what}: body {i} axis delta {da:.3e}");
        }
    }
}

fn assert_poses_bit_identical(a: &AssemblySolution, b: &AssemblySolution) {
    for (pa, pb) in a.poses.iter().zip(&b.poses) {
        for c in 0..4 {
            assert_eq!(
                pa.rotation[c].to_bits(),
                pb.rotation[c].to_bits(),
                "rotation must be bit-identical"
            );
        }
        for c in 0..3 {
            assert_eq!(
                pa.translation[c].to_bits(),
                pb.translation[c].to_bits(),
                "translation must be bit-identical"
            );
        }
    }
}

/// (§7.6 / test 1) 10-body chain: the decomposed strategy peels one body
/// at a time (nine small sequential solves), lands on the same poses as
/// the monolithic strategy within 1e-9, and is bit-deterministic.
#[test]
fn chain_ten_bodies_decomposed_sequential_matches_monolithic() {
    let (bodies, mates) = chain_bodies(9);
    let mono = solve_assembly(&bodies, &mates, &chain_opts(SolveStrategy::Monolithic)).unwrap();
    let deco = solve_assembly(&bodies, &mates, &chain_opts(SolveStrategy::Decomposed)).unwrap();
    assert_eq!(mono.strategy, "monolithic");
    assert_eq!(deco.strategy, "decomposed");
    assert_eq!(mono.steps.len(), 1);
    assert_eq!(mono.steps[0].method, "monolithic");
    assert_eq!(mono.steps[0].bodies.len(), 9);

    // Per-body small solves, in chain order.
    assert_eq!(deco.steps.len(), 9);
    for (i, step) in deco.steps.iter().enumerate() {
        assert_eq!(step.method, "sequential", "step {i}");
        assert_eq!(step.bodies, vec![format!("b{}", i + 1)], "step {i}");
        assert!(step.iterations > 0, "step {i} did no work");
    }

    // Both strategies land on the exact stacked poses…
    for sol in [&mono, &deco] {
        for i in 1..bodies.len() {
            assert_close(
                vec3(sol.poses[i].translation),
                [0.0, 0.0, i as f64],
                1e-9,
                "chain translation",
            );
            assert_close(
                rot(sol, i, [1.0, 0.0, 0.0]),
                [1.0, 0.0, 0.0],
                1e-9,
                "x-axis",
            );
            assert_close(
                rot(sol, i, [0.0, 0.0, 1.0]),
                [0.0, 0.0, 1.0],
                1e-9,
                "z-axis",
            );
        }
        assert!(sol.max_residual <= 1e-9);
        assert_eq!(sol.dof, 0);
    }
    // …and agree with each other within 1e-9.
    assert_poses_close(&mono, &deco, 1e-9, "mono vs deco");

    // Bit determinism of the decomposed path.
    let again =
        solve_assembly(&bodies, &mates, &chain_opts(SolveStrategy::Decomposed)).unwrap();
    assert_poses_bit_identical(&deco, &again);
    assert_eq!(deco.iterations, again.iterations);
    assert_eq!(deco.residual_rows_evaluated, again.residual_rows_evaluated);

    // Auto decomposes when possible: identical to the explicit strategy.
    let auto = solve_assembly(&bodies, &mates, &chain_opts(SolveStrategy::Auto)).unwrap();
    assert_eq!(auto.strategy, "decomposed");
    assert_poses_bit_identical(&deco, &auto);
}

/// (test 4) Performance guard: on the 10-body chain the decomposed solve
/// does strictly less work than the monolithic one, measured by the
/// residual-row work counter in the diagnostics.
#[test]
fn chain_ten_decomposed_costs_less_than_monolithic() {
    let (bodies, mates) = chain_bodies(9);
    let mono = solve_assembly(&bodies, &mates, &chain_opts(SolveStrategy::Monolithic)).unwrap();
    let deco = solve_assembly(&bodies, &mates, &chain_opts(SolveStrategy::Decomposed)).unwrap();
    println!(
        "PERF mono: iterations {} rows {} | deco: iterations {} rows {}",
        mono.iterations,
        mono.residual_rows_evaluated,
        deco.iterations,
        deco.residual_rows_evaluated
    );
    assert!(
        deco.residual_rows_evaluated < mono.residual_rows_evaluated,
        "decomposed work {} must be below monolithic {}",
        deco.residual_rows_evaluated,
        mono.residual_rows_evaluated
    );
}

/// (§7.6 / test 2) A cycle of partially-binding mates (g→b1→b2→b3→g, all
/// concentric) can neither be peeled nor clustered: the cycle falls back
/// to one monolithic solve of exactly its bodies, the diagnostics say so,
/// and the result is bit-identical to the monolithic strategy.
#[test]
fn four_body_cycle_falls_back_to_monolithic() {
    let bodies = vec![
        body("g", true, identity_rotation(), [0.0; 3]),
        body(
            "b1",
            false,
            quat_axis_angle([1.0, 0.2, 0.0], 8.0),
            [0.1, -0.05, 1.1],
        ),
        body(
            "b2",
            false,
            quat_axis_angle([0.0, 1.0, 0.1], -7.0),
            [-0.08, 0.12, 2.2],
        ),
        body(
            "b3",
            false,
            quat_axis_angle([0.3, 0.0, 1.0], 6.0),
            [0.05, 0.03, 3.1],
        ),
    ];
    let conc = |id: &str, a: usize, b: usize| {
        mate(
            id,
            a,
            b,
            MateKind::ConcentricAxisAxis {
                axis_a: axis([0.0; 3], [0.0, 0.0, 1.0]),
                axis_b: axis([0.0; 3], [0.0, 0.0, 1.0]),
                align: MateAlign::Any,
            },
        )
    };
    let mates = vec![
        conc("g-b1", 0, 1),
        conc("b1-b2", 1, 2),
        conc("b2-b3", 2, 3),
        conc("b3-g", 3, 0),
    ];
    let deco = solve_assembly(&bodies, &mates, &opts(SolveStrategy::Decomposed)).unwrap();
    assert_eq!(deco.strategy, "decomposed");
    assert_eq!(deco.steps.len(), 1, "one fallback step for the whole cycle");
    assert_eq!(deco.steps[0].method, "monolithic_fallback");
    assert_eq!(deco.steps[0].bodies, vec!["b1", "b2", "b3"]);

    // All axes collapse onto the world z line.
    for i in 1..4 {
        let axis_w = rot(&deco, i, [0.0, 0.0, 1.0]);
        let lateral = axis_w.cross(Vec3::new(0.0, 0.0, 1.0)).length();
        assert!(lateral <= 1e-9, "body {i} axis off z by {lateral:.3e}");
        let t = vec3(deco.poses[i].translation);
        assert!(t.x.abs() <= 1e-9 && t.y.abs() <= 1e-9, "body {i} off-axis");
    }
    assert!(deco.max_residual <= 1e-9);

    // The component fallback IS the monolithic solve of the same
    // subproblem: bit-identical poses and iteration count.
    let mono = solve_assembly(&bodies, &mates, &opts(SolveStrategy::Monolithic)).unwrap();
    assert_poses_bit_identical(&deco, &mono);
    assert_eq!(deco.iterations, mono.iterations);
}

/// (§7.5 / test 3) Two bodies fully mated to each other and only jointly
/// mated to ground: detected as a rigid cluster (pairwise rank 6, cluster
/// rank 6·(k−1)), solved hierarchically (internal solve, then rigid
/// placement), same result as the monolithic strategy.
#[test]
fn rigid_pair_cluster_detected_and_solved_hierarchically() {
    let bodies = vec![
        body("g", true, identity_rotation(), [0.0; 3]),
        body(
            "b1",
            false,
            quat_axis_angle([1.0, 1.0, 0.2], 14.0),
            [0.2, -0.15, 1.2],
        ),
        body(
            "b2",
            false,
            quat_axis_angle([0.1, 1.0, 0.6], -11.0),
            [-0.1, 0.2, 2.3],
        ),
    ];
    // b1–b2 fully bound to each other…
    let mut mates = stacked_boxes_mates(1, 2);
    // …and only JOINTLY placed by ground mates split across both bodies:
    // z-planes via b1, x- and y-planes via b2. Neither body alone is
    // peelable, the pair is.
    mates.push(mate(
        "g-top",
        0,
        1,
        MateKind::CoincidentPlanePlane {
            plane_a: plane([0.0, 0.0, 1.0], [0.0, 0.0, 1.0]),
            plane_b: plane([0.0, 0.0, 0.0], [0.0, 0.0, -1.0]),
            align: MateAlign::AntiAligned,
        },
    ));
    mates.push(mate(
        "g-left",
        0,
        2,
        MateKind::CoincidentPlanePlane {
            plane_a: plane([0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]),
            plane_b: plane([0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]),
            align: MateAlign::Aligned,
        },
    ));
    mates.push(mate(
        "g-front",
        0,
        2,
        MateKind::CoincidentPlanePlane {
            plane_a: plane([0.0, 0.0, 0.0], [0.0, -1.0, 0.0]),
            plane_b: plane([0.0, 0.0, 0.0], [0.0, -1.0, 0.0]),
            align: MateAlign::Aligned,
        },
    ));

    let deco = solve_assembly(&bodies, &mates, &opts(SolveStrategy::Decomposed)).unwrap();
    assert_eq!(deco.strategy, "decomposed");
    assert_eq!(deco.steps.len(), 2, "internal solve then rigid placement");
    assert_eq!(deco.steps[0].method, "cluster_internal");
    assert_eq!(deco.steps[0].bodies, vec!["b1", "b2"]);
    assert_eq!(deco.steps[1].method, "cluster_sequential");
    assert_eq!(deco.steps[1].bodies, vec!["b1", "b2"]);

    // Exact solution: b1 stacked on g, b2 on b1, identity orientation.
    for (i, z) in [(1usize, 1.0f64), (2, 2.0)] {
        assert_close(
            vec3(deco.poses[i].translation),
            [0.0, 0.0, z],
            1e-9,
            "translation",
        );
        assert_close(
            rot(&deco, i, [1.0, 0.0, 0.0]),
            [1.0, 0.0, 0.0],
            1e-9,
            "x-axis",
        );
        assert_close(
            rot(&deco, i, [0.0, 0.0, 1.0]),
            [0.0, 0.0, 1.0],
            1e-9,
            "z-axis",
        );
    }
    assert_eq!(deco.dof, 0);
    assert!(deco.max_residual <= 1e-9);

    // Identical to the monolithic strategy within tolerance.
    let mono = solve_assembly(&bodies, &mates, &opts(SolveStrategy::Monolithic)).unwrap();
    assert_poses_close(&mono, &deco, 1e-9, "mono vs cluster");
    assert_eq!(mono.dof, deco.dof);
    assert_eq!(mono.rank, deco.rank);
    assert_eq!(mono.redundant, deco.redundant);

    // Auto takes the same decomposed path bit-for-bit.
    let auto = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    assert_eq!(auto.strategy, "decomposed");
    assert_poses_bit_identical(&deco, &auto);
}

// -----------------------------------------------------------------------
// Point-line / line-line distance mates
// -----------------------------------------------------------------------

/// Analytic closest approach between two infinite WORLD lines (unit
/// directions; parallel fallback: point-to-line), for verifying solved
/// configurations independently of the solver's own residual.
fn analytic_line_line_distance(o1: Vec3, d1: Vec3, o2: Vec3, d2: Vec3) -> f64 {
    let u = o1.sub(o2);
    let c = d1.cross(d2);
    let s = c.length();
    if s <= 1e-9 {
        u.sub(d2.scale(d2.dot(u))).length()
    } else {
        (u.dot(c) / s).abs()
    }
}

/// World origin + direction of a body-local line at the solved pose.
fn world_line(
    sol: &AssemblySolution,
    body: usize,
    origin: [f64; 3],
    dir: [f64; 3],
) -> (Vec3, Vec3) {
    let o = quat_rotate(sol.poses[body].rotation, vec3(origin))
        .add(vec3(sol.poses[body].translation));
    let d = quat_rotate(sol.poses[body].rotation, vec3(dir));
    (o, d)
}

fn assert_bit_deterministic_3x(bodies: &[AssemblyBody], mates: &[AssemblyMate]) {
    let opts = AssemblySolveOptions::default();
    let runs: Vec<AssemblySolution> = (0..3)
        .map(|_| solve_assembly(bodies, mates, &opts).unwrap())
        .collect();
    for run in &runs[1..] {
        assert_poses_bit_identical(&runs[0], run);
        assert_eq!(runs[0].max_residual.to_bits(), run.max_residual.to_bits());
        assert_eq!(runs[0].iterations, run.iterations);
    }
}

/// (new 1) distance_point_line positions a body exactly: a point at the
/// body origin held 2.0 from the grounded z-axis slides radially from
/// (3,0,5) to the closed-form (2,0,5) — rotation never engages because
/// the point sits on the rotation centre, and minimum-norm steps keep z.
#[test]
fn point_line_distance_positions_body_closed_form() {
    let bodies = vec![
        body("frame", true, identity_rotation(), [0.0; 3]),
        body("part", false, identity_rotation(), [3.0, 0.0, 5.0]),
    ];
    let mates = vec![mate(
        "standoff",
        1,
        0,
        MateKind::DistancePointLine {
            point_a: [0.0, 0.0, 0.0],
            axis_b: axis([0.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
            distance: 2.0,
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    assert_close(
        vec3(sol.poses[1].translation),
        [2.0, 0.0, 5.0],
        1e-9,
        "part slides radially to the closed-form point",
    );
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );
    assert_eq!(sol.rank, 1, "one scalar distance row binds one DOF");
    assert_eq!(sol.dof, 5);
    assert_eq!(sol.status, "under");
    assert_bit_deterministic_3x(&bodies, &mates);
}

/// (new 2) distance_line_line on genuinely skew lines: the solved
/// configuration's ANALYTIC closest approach (|u·(da×db)|/‖da×db‖)
/// equals the target, and the solution stays far from the parallel
/// blend band so the mate's measure is the true skew formula.
#[test]
fn line_line_skew_distance_matches_analytic() {
    let bodies = vec![
        body("frame", true, identity_rotation(), [0.0; 3]),
        // World line through (0.5, 3, 0) along x: skew to the frame's
        // z-axis with closest approach 3.
        body("rod", false, identity_rotation(), [0.5, 3.0, 0.0]),
    ];
    let mates = vec![mate(
        "clearance",
        0,
        1,
        MateKind::DistanceLineLine {
            axis_a: axis([0.0; 3], [0.0, 0.0, 1.0]),
            axis_b: axis([0.0; 3], [1.0, 0.0, 0.0]),
            distance: 1.0,
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    let (o2, d2) = world_line(&sol, 1, [0.0; 3], [1.0, 0.0, 0.0]);
    let dist =
        analytic_line_line_distance(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), o2, d2);
    assert!((dist - 1.0).abs() <= 1e-9, "closest approach {dist}");
    let sin = Vec3::new(0.0, 0.0, 1.0).cross(d2).length();
    assert!(sin >= ASM_LL_SIN_SKEW, "solution stayed skew: sin {sin}");
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );
    assert_bit_deterministic_3x(&bodies, &mates);
}

/// (new 3) Parallel-line degeneracy: exactly parallel lines, where the
/// skew closest-approach formula is 0/0. The parallel branch (point-to-
/// line measure) takes over, converges with no NaN and no oscillation to
/// the closed-form radial slide, and the solution stays in the parallel
/// branch so the report means the parallel distance.
#[test]
fn line_line_parallel_degeneracy_converges() {
    let bodies = vec![
        body("frame", true, identity_rotation(), [0.0; 3]),
        // Line through t along z: exactly parallel to the frame's z-axis
        // at lateral offset 0.5. The origin sits at the foot of the
        // common perpendicular (u ⊥ z), so the rotation gradient is zero
        // and the closed form is the pure radial slide t → 2·t̂.
        body("rod", false, identity_rotation(), [0.3, 0.4, 0.0]),
    ];
    let mates = vec![mate(
        "offset",
        0,
        1,
        MateKind::DistanceLineLine {
            axis_a: axis([0.0; 3], [0.0, 0.0, 1.0]),
            axis_b: axis([0.0; 3], [0.0, 0.0, 1.0]),
            distance: 2.0,
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    for pose in &sol.poses {
        for c in pose.rotation.iter().chain(pose.translation.iter()) {
            assert!(c.is_finite(), "non-finite pose component");
        }
    }
    // 1e-8: the RADIAL coordinate is exact to the solve tolerance; the
    // tangential coordinates are free directions and may drift a few nm
    // of second-order LM step (minimum-norm holds them only to first
    // order).
    assert_close(
        vec3(sol.poses[1].translation),
        [1.2, 1.6, 0.0],
        1e-8,
        "radial slide to the closed form",
    );
    let (o2, d2) = world_line(&sol, 1, [0.0; 3], [0.0, 0.0, 1.0]);
    let sin = Vec3::new(0.0, 0.0, 1.0).cross(d2).length();
    assert!(
        sin <= ASM_LL_SIN_PARALLEL,
        "solution stayed in the parallel branch: sin {sin}"
    );
    let dist =
        analytic_line_line_distance(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), o2, d2);
    assert!((dist - 2.0).abs() <= 1e-9, "parallel distance {dist}");
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );
    assert!(
        sol.iterations <= 50,
        "no oscillation: {} iterations",
        sol.iterations
    );
    assert_eq!(sol.dof, 5);
    assert_bit_deterministic_3x(&bodies, &mates);
}

/// (new 4, shortcut) distance_point_line at 0 degrades to the point-on-
/// line lateral atom — the coincident point-line mate: the point drops
/// exactly onto the axis (minimum-norm keeps z) and removes 2 DOF.
#[test]
fn coincident_point_line_via_zero_distance() {
    let bodies = vec![
        body("frame", true, identity_rotation(), [0.0; 3]),
        body("part", false, identity_rotation(), [0.3, 0.4, 0.2]),
    ];
    let mates = vec![mate(
        "on-axis",
        1,
        0,
        MateKind::DistancePointLine {
            point_a: [0.0; 3],
            axis_b: axis([0.0; 3], [0.0, 0.0, 1.0]),
            distance: 0.0,
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    assert_close(
        vec3(sol.poses[1].translation),
        [0.0, 0.0, 0.2],
        1e-9,
        "point dropped onto the axis",
    );
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );
    assert_eq!(sol.rank, 2, "a point on a line removes exactly 2 DOF");
    assert_eq!(sol.dof, 4);
    assert_eq!(sol.redundant, 0);
}

/// (new 5, shortcut) parallel + distance_line_line(0) ≡ concentric: from
/// a tilted, offset guess (which starts in the SKEW branch and crosses
/// the blend band while converging) the axes end collinear with the same
/// rank/DOF signature as a genuine concentric mate (spin + slide free).
#[test]
fn concentric_via_parallel_plus_zero_line_line_distance() {
    let bodies = vec![
        body("frame", true, identity_rotation(), [0.0; 3]),
        body(
            "shaft",
            false,
            quat_axis_angle([1.0, 0.0, 0.0], 2.0),
            [0.4, -0.3, 0.7],
        ),
    ];
    let mates = vec![
        mate(
            "par",
            0,
            1,
            MateKind::Parallel {
                direction_a: [0.0, 0.0, 1.0],
                direction_b: [0.0, 0.0, 1.0],
                align: MateAlign::Any,
            },
        ),
        mate(
            "touch",
            0,
            1,
            MateKind::DistanceLineLine {
                axis_a: axis([0.0; 3], [0.0, 0.0, 1.0]),
                axis_b: axis([0.0; 3], [0.0, 0.0, 1.0]),
                distance: 0.0,
            },
        ),
    ];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    let (o2, d2) = world_line(&sol, 1, [0.0; 3], [0.0, 0.0, 1.0]);
    let sin = Vec3::new(0.0, 0.0, 1.0).cross(d2).length();
    assert!(sin <= 1e-9, "axes parallel: sin {sin}");
    let lateral = (o2.x * o2.x + o2.y * o2.y).sqrt();
    assert!(lateral <= 1e-9, "axes collinear: lateral {lateral}");
    assert!(
        sol.max_residual <= 1e-9,
        "max residual {}",
        sol.max_residual
    );

    // Same DOF signature as a genuine concentric mate.
    let concentric = vec![mate(
        "bore",
        0,
        1,
        MateKind::ConcentricAxisAxis {
            axis_a: axis([0.0; 3], [0.0, 0.0, 1.0]),
            axis_b: axis([0.0; 3], [0.0, 0.0, 1.0]),
            align: MateAlign::Any,
        },
    )];
    let reference =
        solve_assembly(&bodies, &concentric, &AssemblySolveOptions::default()).unwrap();
    assert_eq!(sol.rank, reference.rank);
    assert_eq!(sol.dof, reference.dof);
    assert_eq!(sol.dof, 2, "spin and slide stay free");
    assert_bit_deterministic_3x(&bodies, &mates);
}

/// (new 6, DOF) A body held ONLY by a line-line distance mate keeps five
/// degrees of freedom (rank 1). The initial config already satisfies the
/// target, so nothing moves at all.
#[test]
fn line_line_distance_only_reports_five_dof() {
    let bodies = vec![
        body("frame", true, identity_rotation(), [0.0; 3]),
        // Skew pair at exactly the target distance 3.
        body("rod", false, identity_rotation(), [0.5, 3.0, 0.0]),
    ];
    let mates = vec![mate(
        "clearance",
        0,
        1,
        MateKind::DistanceLineLine {
            axis_a: axis([0.0; 3], [0.0, 0.0, 1.0]),
            axis_b: axis([0.0; 3], [1.0, 0.0, 0.0]),
            distance: 3.0,
        },
    )];
    let sol = solve_assembly(&bodies, &mates, &AssemblySolveOptions::default()).unwrap();
    assert_eq!(sol.rank, 1, "one scalar distance row binds one DOF");
    assert_eq!(sol.dof, 5);
    assert_eq!(sol.redundant, 0);
    assert_eq!(sol.status, "under");
    assert_eq!(sol.iterations, 0, "already satisfied: nothing moves");
    assert_close(
        vec3(sol.poses[1].translation),
        [0.5, 3.0, 0.0],
        0.0,
        "pose kept",
    );
}

/// (new 7) Serde: the new distance mates use the snake_case tags the app
/// layer sends, and round-trip.
#[test]
fn distance_line_mates_serde_round_trip() {
    let mates = vec![
        mate(
            "pl",
            0,
            1,
            MateKind::DistancePointLine {
                point_a: [1.0, 2.0, 3.0],
                axis_b: axis([0.0; 3], [0.0, 0.0, 1.0]),
                distance: 2.5,
            },
        ),
        mate(
            "ll",
            0,
            1,
            MateKind::DistanceLineLine {
                axis_a: axis([0.0; 3], [0.0, 0.0, 1.0]),
                axis_b: axis([1.0, 0.0, 0.0], [1.0, 0.0, 0.0]),
                distance: 0.5,
            },
        ),
    ];
    let json = serde_json::to_string(&mates).unwrap();
    assert!(json.contains("\"type\":\"distance_point_line\""), "{json}");
    assert!(json.contains("\"type\":\"distance_line_line\""), "{json}");
    let back: Vec<AssemblyMate> = serde_json::from_str(&json).unwrap();
    match &back[0].kind {
        MateKind::DistancePointLine { distance, .. } => assert_eq!(*distance, 2.5),
        other => panic!("wrong kind after round-trip: {other:?}"),
    }
    match &back[1].kind {
        MateKind::DistanceLineLine { distance, .. } => assert_eq!(*distance, 0.5),
        other => panic!("wrong kind after round-trip: {other:?}"),
    }
    // The app-side JSON shape parses directly.
    let from_app: AssemblyMate = serde_json::from_str(
        r#"{"id":"edge-gap","body_a":0,"body_b":1,"type":"distance_line_line",
                "axis_a":{"origin":[0,0,0],"direction":[0,0,1]},
                "axis_b":{"origin":[0,1,0],"direction":[0,0,1]},
                "distance":1.5}"#,
    )
    .unwrap();
    match from_app.kind {
        MateKind::DistanceLineLine { distance, .. } => assert_eq!(distance, 1.5),
        other => panic!("wrong kind: {other:?}"),
    }
}

/// Strategy options serde: omitted strategy defaults to Auto; the enum
/// round-trips in snake_case.
#[test]
fn strategy_serde_default_and_round_trip() {
    let parsed: AssemblySolveOptions = serde_json::from_str("{}").unwrap();
    assert_eq!(parsed.strategy, SolveStrategy::Auto);
    assert_eq!(parsed.tolerance, default_tolerance());
    let parsed: AssemblySolveOptions =
        serde_json::from_str(r#"{"strategy":"decomposed"}"#).unwrap();
    assert_eq!(parsed.strategy, SolveStrategy::Decomposed);
    let json = serde_json::to_string(&AssemblySolveOptions {
        strategy: SolveStrategy::Monolithic,
        ..AssemblySolveOptions::default()
    })
    .unwrap();
    assert!(json.contains("\"strategy\":\"monolithic\""), "{json}");
}