visloc-vision 0.5.0

Feature, matching, PnP, RANSAC, and pose-refinement building blocks for visloc-rs.
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
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
//! Classical two-view geometry building blocks.
//!
//! The module exposes a small, testable pipeline:
//! 1. Normalize pixel correspondences with camera intrinsics.
//! 2. Estimate the essential matrix with the 8-point algorithm in a
//!    Sampson-distance scored RANSAC loop (`EssentialRansac`).
//! 3. Decompose the essential matrix into the four (R, t) candidates and pick
//!    the one with the most correspondences in front of both cameras
//!    (`recover_relative_pose`).
//! 4. Compose the above as a `RelativePoseEstimator`, optionally applying a
//!    caller-supplied translation scale.
//!
//! These components are intentionally independent of `Frame`, `FrameId`, or
//! the tracking pipeline so they can be used as the geometric core of any
//! `VisualOdometryFrontend` implementation. The
//! `EssentialMatrixVisualOdometryFrontend` in the top-level `visloc-rs` crate
//! wires this module into the existing tracking layer.
//!
//! [`colmap_verification`] adds a second, opt-in tier on top of the essential-
//! matrix-only pipeline above: COLMAP-style multi-model (essential /
//! fundamental / homography) two-view verification with
//! [`colmap_verification::ConfigurationType`] classification
//! (`CALIBRATED`/`UNCALIBRATED`/`PLANAR`/`PANORAMIC`/`WATERMARK`/`DEGENERATE`/
//! `MULTIPLE`). It is a drop-in alternative — every existing caller of
//! `EssentialRansac`/`RelativePoseEstimator` is unchanged; see
//! `examples/unordered_sfm_demo.rs`'s `--colmap-verification` flag for the
//! A/B wiring. [`homography`] and [`fundamental`] hold the estimators the
//! classifier composes.
//!
//! [`correspondence_graph`] adds a third, independent tier: COLMAP's
//! persistent `CorrespondenceGraph` view-graph structure (M2 in
//! `docs/colmap_port_plan.md`), which stores per-image-pair
//! [`colmap_verification::ConfigurationType`] and per-feature adjacency for
//! track building and transitive-correspondence queries. It is consumed by
//! `pipelines/slam/src/incremental_sfm.rs`'s `build_tracks_via_graph` as an
//! opt-in alternative to the legacy ad hoc union-find.
//!
//! [`rescue`] adds a fourth, independent tier: M5's disconnection detector +
//! cross-component candidate generator, used by `examples/unordered_sfm_demo
//! .rs`'s `--rescue-bridging` pass to propose and (after re-verification)
//! admit bridge pairs between components the standard pipeline left
//! disconnected — see `docs/colmap_port_plan.md`'s "M5 results".

use nalgebra::{DMatrix, Matrix3, Matrix3x4, Point2, UnitQuaternion, Vector3};
use rand::rngs::SmallRng;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use visloc_core::geometry::SE3;
use visloc_core::types::Camera;

pub mod colmap_verification;
pub mod correspondence_graph;
pub mod five_point;
pub mod fundamental;
pub mod homography;
pub mod rescue;
pub mod spherical;

pub use colmap_verification::{
    two_view_pose_and_triangulation_angle, two_view_triangulation_angle, ConfigurationType,
    TwoViewGeometryOptions, TwoViewGeometryReport, TwoViewGeometryVerifier,
};
pub use correspondence_graph::{
    Correspondence, CorrespondenceGraph, CorrespondenceGraphError, EdgeMetadata, IngestStats,
    PairMatches,
};
pub use fundamental::{
    estimate_fundamental_dlt, fundamental_ransac, fundamental_squared_sampson_error,
    FundamentalRansacConfig, FundamentalReport,
};
pub use homography::{
    decompose_homography_matrix, estimate_homography_dlt, homography_ransac,
    homography_squared_error, pose_from_homography_matrix, HomographyMotion,
    HomographyRansacConfig, HomographyReport,
};
pub use rescue::{connected_components, generate_bridge_candidates, BridgeCandidateOptions};

/// One pixel-space correspondence between a previous and a current frame.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TwoViewCorrespondence {
    pub previous_xy: Point2<f64>,
    pub current_xy: Point2<f64>,
}

impl TwoViewCorrespondence {
    pub const fn new(previous_xy: Point2<f64>, current_xy: Point2<f64>) -> Self {
        Self {
            previous_xy,
            current_xy,
        }
    }
}

/// Output of the essential-matrix RANSAC loop.
#[derive(Debug, Clone, PartialEq)]
pub struct EssentialRansacReport {
    pub essential: Matrix3<f64>,
    pub inliers: Vec<usize>,
    pub mean_sampson_error: f64,
}

/// Output of relative-pose recovery: rotation, unit translation direction,
/// applied scale, the implied `SE3` previous-to-current transform, inlier
/// indices, and Sampson diagnostics.
#[derive(Debug, Clone, PartialEq)]
pub struct RelativePose {
    pub previous_to_current: SE3,
    pub translation_unit: Vector3<f64>,
    pub translation_scale: f64,
    pub inliers: Vec<usize>,
    pub mean_sampson_error: f64,
    /// Runner-up (R, t_unit) when essential decomposition is chirality-
    /// ambiguous. Global SfM can keep this as an alternate view-graph edge
    /// hypothesis; `None` when the margin is decisive or unused.
    pub alternate: Option<(UnitQuaternion<f64>, Vector3<f64>)>,
    /// `(best - second) / best` from cheirality scoring; near zero means the
    /// essential was ambiguous. View-graph builders can down-weight such edges.
    pub chirality_margin: f64,
}

/// Estimator for an essential matrix from pixel correspondences plus
/// intrinsics. Implementors return `None` when the input is degenerate.
pub trait EssentialMatrixEstimator {
    fn estimate(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
    ) -> Option<Matrix3<f64>>;
    fn minimum_correspondences(&self) -> usize;

    /// All model hypotheses for the given sample. Linear estimators admit a
    /// single solution and inherit the default (forwarding to
    /// [`Self::estimate`]); minimal solvers with several algebraic solutions
    /// (the five-point essential solver) override this so RANSAC can score
    /// every hypothesis from one sample.
    fn estimate_all(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
    ) -> Vec<Matrix3<f64>> {
        self.estimate(correspondences, camera).into_iter().collect()
    }
}

/// Hartley-normalized 8-point essential-matrix estimator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EightPointEssentialMatrixEstimator {
    pub min_correspondences: usize,
}

impl Default for EightPointEssentialMatrixEstimator {
    fn default() -> Self {
        Self {
            min_correspondences: 8,
        }
    }
}

impl EssentialMatrixEstimator for EightPointEssentialMatrixEstimator {
    fn minimum_correspondences(&self) -> usize {
        self.min_correspondences
    }

    fn estimate(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
    ) -> Option<Matrix3<f64>> {
        if correspondences.len() < self.min_correspondences {
            return None;
        }

        let normalized = normalize_pairs(correspondences, camera)?;
        let (previous_normalization, previous_points) =
            hartley_normalization(normalized.iter().map(|(p, _)| *p))?;
        let (current_normalization, current_points) =
            hartley_normalization(normalized.iter().map(|(_, c)| *c))?;

        let mut a = DMatrix::<f64>::zeros(normalized.len(), 9);
        for row in 0..normalized.len() {
            let (x, y) = (previous_points[row].x, previous_points[row].y);
            let (xp, yp) = (current_points[row].x, current_points[row].y);
            a[(row, 0)] = xp * x;
            a[(row, 1)] = xp * y;
            a[(row, 2)] = xp;
            a[(row, 3)] = yp * x;
            a[(row, 4)] = yp * y;
            a[(row, 5)] = yp;
            a[(row, 6)] = x;
            a[(row, 7)] = y;
            a[(row, 8)] = 1.0;
        }

        // The 8-point linear system A * f = 0 has 9 unknowns. When there are
        // fewer than 9 rows the thin SVD that nalgebra computes for non-square
        // inputs drops the last right singular vector — the very direction we
        // want. Multiply by A^T A so the SVD always operates on a 9x9 matrix.
        let ata = a.transpose() * a;
        // Bounded SVD: `.svd(..)` calls the unbounded `SVD::new_unordered`
        // (`max_niter=0`, hangs forever on non-finite input, same class of
        // bug as `pnp/gp3p.rs::real_roots_of_degree_le_8`). A degenerate
        // minimal/near-minimal correspondence sample can produce a
        // non-finite `ata`, so use the bounded variant and let the existing
        // `?` reject the sample like any other SVD failure.
        let svd = ata.try_svd(true, true, f64::EPSILON * 5.0, 10_000)?;
        let v_t = svd.v_t?;
        let last = v_t.row(v_t.nrows() - 1);
        let mut essential_normalized = Matrix3::new(
            last[0], last[1], last[2], last[3], last[4], last[5], last[6], last[7], last[8],
        );

        // Project E_normalized onto the essential manifold.
        let essential_norm_svd =
            essential_normalized.try_svd(true, true, f64::EPSILON * 5.0, 10_000)?;
        let u_n = essential_norm_svd.u?;
        let v_t_n = essential_norm_svd.v_t?;
        let s_n =
            (essential_norm_svd.singular_values[0] + essential_norm_svd.singular_values[1]) * 0.5;
        let constrained_n = Matrix3::from_diagonal(&Vector3::new(s_n, s_n, 0.0));
        essential_normalized = u_n * constrained_n * v_t_n;

        let essential_calibrated: Matrix3<f64> =
            current_normalization.transpose() * essential_normalized * previous_normalization;
        Some(essential_calibrated)
    }
}

/// Nister five-point essential-matrix estimator (PoseLib `relpose_5pt`,
/// `docs` in [`five_point`]).
///
/// Unlike the eight-point estimator this is a minimal solver: RANSAC draws
/// five correspondences per hypothesis, matching COLMAP's
/// `EssentialMatrixFivePointEstimator`. The resulting E inlier count is what
/// drives COLMAP's calibrated-vs-uncalibrated E/F-ratio test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FivePointEssentialMatrixEstimator {
    pub min_correspondences: usize,
}

impl Default for FivePointEssentialMatrixEstimator {
    fn default() -> Self {
        Self {
            min_correspondences: 5,
        }
    }
}

impl EssentialMatrixEstimator for FivePointEssentialMatrixEstimator {
    fn minimum_correspondences(&self) -> usize {
        self.min_correspondences
    }

    fn estimate(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
    ) -> Option<Matrix3<f64>> {
        self.estimate_all(correspondences, camera)
            .into_iter()
            .next()
    }

    fn estimate_all(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
    ) -> Vec<Matrix3<f64>> {
        if correspondences.len() < self.min_correspondences {
            return Vec::new();
        }
        let rays1: Option<Vec<Vector3<f64>>> = correspondences
            .iter()
            .map(|c| {
                camera
                    .normalize_pixel(&c.previous_xy)
                    .map(|p| Vector3::new(p.x, p.y, 1.0))
            })
            .collect();
        let rays2: Option<Vec<Vector3<f64>>> = correspondences
            .iter()
            .map(|c| {
                camera
                    .normalize_pixel(&c.current_xy)
                    .map(|p| Vector3::new(p.x, p.y, 1.0))
            })
            .collect();
        let (Some(rays1), Some(rays2)) = (rays1, rays2) else {
            return Vec::new();
        };

        let models = five_point::relpose_5pt(&rays1, &rays2);

        // COLMAP's minimal path keeps only hypotheses whose minimal sample
        // triangulates in front of both cameras. The over-determined path
        // (used for the inlier refit) returns every root.
        if correspondences.len() == self.min_correspondences {
            models
                .into_iter()
                .filter(|essential| all_in_front_for_some_pose(essential, correspondences, camera))
                .collect()
        } else {
            models
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EssentialRansacConfig {
    pub iterations: usize,
    /// Sampson distance threshold in normalized image-plane units. A 1-pixel
    /// reprojection error at focal length `f` corresponds to a normalized
    /// distance of `1.0 / f`.
    pub sampson_threshold: f64,
    pub seed: u64,
}

impl Default for EssentialRansacConfig {
    fn default() -> Self {
        Self {
            iterations: 256,
            sampson_threshold: 5.0e-3,
            seed: 7,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EssentialRansac<E = EightPointEssentialMatrixEstimator> {
    pub estimator: E,
    pub config: EssentialRansacConfig,
}

impl Default for EssentialRansac {
    fn default() -> Self {
        Self {
            estimator: EightPointEssentialMatrixEstimator::default(),
            config: EssentialRansacConfig::default(),
        }
    }
}

impl<E> EssentialRansac<E>
where
    E: EssentialMatrixEstimator,
{
    pub fn estimate(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
    ) -> Option<EssentialRansacReport> {
        self.estimate_with_optional_weights(correspondences, camera, None)
    }

    /// PROSAC-style confidence-weighted variant: sort correspondences by
    /// `weights` descending, then for iteration `k` draw the minimal
    /// sample uniformly from the top-`m_k` correspondences where `m_k`
    /// expands from `sample_size` to `correspondences.len()` over the
    /// configured iteration budget. High-confidence matches anchor the
    /// early iterations (so RANSAC finds a consensus quickly when the
    /// weights are informative) and the worst candidates get evaluated
    /// only late in the schedule. Falls back to the uniform-shuffle
    /// behaviour when `weights` is `None` or all weights are zero.
    pub fn estimate_with_weights(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
        weights: &[f32],
    ) -> Option<EssentialRansacReport> {
        if weights.len() != correspondences.len() {
            return self.estimate(correspondences, camera);
        }
        self.estimate_with_optional_weights(correspondences, camera, Some(weights))
    }

    fn estimate_with_optional_weights(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
        weights: Option<&[f32]>,
    ) -> Option<EssentialRansacReport> {
        let sample_size = self.estimator.minimum_correspondences();
        if correspondences.len() < sample_size {
            return None;
        }

        // PROSAC ordering: sort indices by descending weight when weights
        // are usable; otherwise fall back to natural order + uniform
        // shuffle (the original behaviour).
        let weighted = weights.filter(|w| w.iter().any(|&v| v.is_finite() && v > 0.0));
        let mut sorted_indices: Vec<usize> = (0..correspondences.len()).collect();
        if let Some(w) = weighted {
            sorted_indices
                .sort_by(|&a, &b| w[b].partial_cmp(&w[a]).unwrap_or(std::cmp::Ordering::Equal));
        }

        let mut rng = SmallRng::seed_from_u64(self.config.seed);
        let mut best_inliers: Vec<usize> = Vec::new();
        let mut best_essential: Option<Matrix3<f64>> = None;
        let threshold_sq = self.config.sampson_threshold * self.config.sampson_threshold;
        let n = correspondences.len();
        let total_iters = self.config.iterations.max(1);

        for iteration in 0..self.config.iterations {
            // PROSAC shrinking sample-set: m_k expands linearly from
            // `sample_size` to `n` over the iteration budget. When
            // weights are absent this collapses to `m_k = n` and the
            // shuffle samples uniformly across all correspondences.
            let m_k = if weighted.is_some() {
                let progress = iteration as f64 / total_iters as f64;
                let m = sample_size as f64 + (n - sample_size) as f64 * progress;
                (m.ceil() as usize).clamp(sample_size, n)
            } else {
                n
            };

            // Sample `sample_size` distinct indices uniformly from the
            // top-m_k of the (possibly sorted) index list.
            let mut subset: Vec<usize> = sorted_indices[..m_k].to_vec();
            subset.shuffle(&mut rng);
            let sample: Vec<TwoViewCorrespondence> = subset[..sample_size]
                .iter()
                .map(|&i| correspondences[i])
                .collect();
            for candidate in self.estimator.estimate_all(&sample, camera) {
                let Some(inliers) = score_inliers_if_competitive(
                    &candidate,
                    correspondences,
                    camera,
                    threshold_sq,
                    best_inliers.len(),
                ) else {
                    continue;
                };
                if inliers.len() > best_inliers.len() {
                    best_inliers = inliers;
                    best_essential = Some(candidate);
                }
            }
        }

        let essential = best_essential?;
        if best_inliers.len() < sample_size {
            return None;
        }

        let inlier_correspondences: Vec<TwoViewCorrespondence> =
            best_inliers.iter().map(|&i| correspondences[i]).collect();
        let refined = self
            .estimator
            .estimate_all(&inlier_correspondences, camera)
            .into_iter()
            .max_by_key(|candidate| {
                score_inliers(candidate, correspondences, camera, threshold_sq).len()
            })
            .unwrap_or(essential);
        let final_inliers = score_inliers(&refined, correspondences, camera, threshold_sq);
        let final_inliers = if final_inliers.len() >= best_inliers.len() {
            final_inliers
        } else {
            best_inliers
        };
        let mean = mean_sampson_error(&refined, correspondences, camera, &final_inliers);

        Some(EssentialRansacReport {
            essential: refined,
            inliers: final_inliers,
            mean_sampson_error: mean,
        })
    }
}

/// Scores a RANSAC hypothesis only while it can still strictly beat the
/// incumbent. The loop's winner update uses `>`, so equality cannot change
/// the selected model and the unvisited suffix is safe to skip.
fn score_inliers_if_competitive(
    essential: &Matrix3<f64>,
    correspondences: &[TwoViewCorrespondence],
    camera: &Camera,
    threshold_sq: f64,
    incumbent_count: usize,
) -> Option<Vec<usize>> {
    let mut inliers = Vec::new();
    for (i, correspondence) in correspondences.iter().enumerate() {
        if sampson_distance_squared(essential, correspondence, camera)
            .is_some_and(|distance_sq| distance_sq <= threshold_sq)
        {
            inliers.push(i);
        }
        let remaining = correspondences.len() - i - 1;
        if inliers.len() + remaining <= incumbent_count {
            return None;
        }
    }
    Some(inliers)
}

/// Gates applied when selecting among the four essential-matrix (R, t)
/// hypotheses. Default values reproduce the legacy positive-depth-only
/// count that [`recover_relative_pose`] has always used.
///
/// Hardened settings ([`CheiralityOptions::hardened`]) additionally require a
/// minimum triangulation angle, reject poses whose second-best hypothesis
/// scores nearly as well as the winner (chirality / façade ambiguity), and
/// demand that a minimum fraction of inliers pass the positive-depth test.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CheiralityOptions {
    /// Minimum ray-intersection angle (degrees) for a triangulated point to
    /// count toward the cheirality score. `0.0` = legacy (depth-only).
    pub min_tri_angle_deg: f64,
    /// Reject the recovery when `second_best / best` exceeds this ratio.
    /// `1.0` never rejects on ratio alone (legacy); values like `0.85` drop
    /// chirality-ambiguous essentials that survive plain inlier counts on
    /// repetitive façades.
    pub max_ambiguity_ratio: f64,
    /// Require `best_score >= fraction * inliers.len()`. `0.0` = legacy.
    pub min_positive_depth_fraction: f64,
}

impl Default for CheiralityOptions {
    fn default() -> Self {
        Self {
            min_tri_angle_deg: 0.0,
            max_ambiguity_ratio: 1.0,
            min_positive_depth_fraction: 0.0,
        }
    }
}

impl CheiralityOptions {
    /// Courtyard-class edge quality: angle-gated cheirality, ambiguity
    /// rejection, and a majority positive-depth requirement.
    pub const fn hardened() -> Self {
        Self {
            min_tri_angle_deg: 1.0,
            max_ambiguity_ratio: 0.85,
            min_positive_depth_fraction: 0.5,
        }
    }

    /// Like [`Self::hardened`] but never drops on `second/best` ratio alone —
    /// the runner-up is exposed via [`RelativePoseRecovery::alternate`] so the
    /// view-graph can carry multi-hypothesis edges instead of discarding the
    /// pair.
    pub const fn hardened_keep_ambiguous() -> Self {
        Self {
            max_ambiguity_ratio: 1.0,
            ..Self::hardened()
        }
    }
}

/// Result of decomposing an essential matrix, including the margin that
/// separates the winning hypothesis from the runner-up. Callers that build
/// view-graph edges can down-weight low-margin recoveries or keep the
/// runner-up as an alternate.
#[derive(Debug, Clone, PartialEq)]
pub struct RelativePoseRecovery {
    pub rotation: UnitQuaternion<f64>,
    pub translation_unit: Vector3<f64>,
    /// Cheirality (positive-depth [+ angle]) count for the winning hypothesis.
    pub best_score: i64,
    /// Same count for the second-best of the four hypotheses.
    pub second_score: i64,
    /// Runner-up (R, t) when its score is positive and the rotation differs
    /// from the winner; used for multi-hypothesis view-graph edges.
    pub alternate: Option<(UnitQuaternion<f64>, Vector3<f64>)>,
}

impl RelativePoseRecovery {
    /// `(best - second) / best`, or `0` when `best == 0`. Near-zero means the
    /// essential was chirality-ambiguous.
    pub fn chirality_margin(&self) -> f64 {
        if self.best_score <= 0 {
            return 0.0;
        }
        (self.best_score - self.second_score) as f64 / self.best_score as f64
    }
}

/// Composes essential-matrix RANSAC with relative-pose recovery, applying a
/// caller-controlled translation scale.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RelativePoseEstimator<E = EightPointEssentialMatrixEstimator> {
    pub ransac: EssentialRansac<E>,
    /// Default translation scale applied when no per-call scale is supplied.
    /// Stays at 1.0 unless the caller knows the metric scale (e.g., from a
    /// GNSS displacement, the previous frame's translation, or a configured
    /// default).
    pub default_translation_scale: f64,
    /// Cheirality gates applied during essential decomposition. Default is
    /// byte-identical to the historical positive-depth-only selector.
    pub cheirality: CheiralityOptions,
}

impl Default for RelativePoseEstimator {
    fn default() -> Self {
        Self {
            ransac: EssentialRansac::default(),
            default_translation_scale: 1.0,
            cheirality: CheiralityOptions::default(),
        }
    }
}

impl<E> RelativePoseEstimator<E>
where
    E: EssentialMatrixEstimator,
{
    pub fn estimate(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
    ) -> Option<RelativePose> {
        self.estimate_with_scale(correspondences, camera, self.default_translation_scale)
    }

    pub fn estimate_with_scale(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
        translation_scale: f64,
    ) -> Option<RelativePose> {
        self.estimate_with_scale_and_optional_weights(
            correspondences,
            camera,
            translation_scale,
            None,
        )
    }

    /// Estimate a relative pose when the two images have different pinhole
    /// calibrations.  Each endpoint is first converted to its own normalized
    /// bearing and the existing deterministic estimator then runs in a unit
    /// pinhole convention.  Inlier indices and pose conventions are identical
    /// to [`Self::estimate`]; no descriptor or correspondence order changes.
    pub fn estimate_with_cameras(
        &self,
        correspondences: &[TwoViewCorrespondence],
        previous_camera: &Camera,
        current_camera: &Camera,
    ) -> Option<RelativePose> {
        let normalized = normalize_correspondences_with_cameras(
            correspondences,
            previous_camera,
            current_camera,
        )?;
        let unit_camera = Camera::pinhole(0, 1, 1, 1.0, 1.0, 0.0, 0.0);
        self.estimate(&normalized, &unit_camera)
    }

    /// PROSAC-flavoured variant: order RANSAC sampling by `weights` (e.g.
    /// matcher confidence) so high-confidence correspondences anchor early
    /// iterations. Falls back to the uniform path when `weights` is the
    /// wrong length / all-zero / all-non-finite.
    pub fn estimate_with_scale_and_weights(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
        translation_scale: f64,
        weights: &[f32],
    ) -> Option<RelativePose> {
        self.estimate_with_scale_and_optional_weights(
            correspondences,
            camera,
            translation_scale,
            Some(weights),
        )
    }

    fn estimate_with_scale_and_optional_weights(
        &self,
        correspondences: &[TwoViewCorrespondence],
        camera: &Camera,
        translation_scale: f64,
        weights: Option<&[f32]>,
    ) -> Option<RelativePose> {
        let report = match weights {
            Some(w) if w.len() == correspondences.len() => {
                self.ransac
                    .estimate_with_weights(correspondences, camera, w)
            }
            _ => self.ransac.estimate(correspondences, camera),
        }?;
        let recovered = recover_relative_pose_with_options(
            &report.essential,
            correspondences,
            camera,
            &report.inliers,
            &self.cheirality,
        )?;
        let se3 = SE3::new(
            recovered.rotation,
            recovered.translation_unit * translation_scale,
        );
        Some(RelativePose {
            previous_to_current: se3,
            translation_unit: recovered.translation_unit,
            translation_scale,
            inliers: report.inliers,
            mean_sampson_error: report.mean_sampson_error,
            alternate: recovered.alternate,
            chirality_margin: recovered.chirality_margin(),
        })
    }
}

/// Decompose an essential matrix into the (R, t_unit) pair that puts the most
/// inlier correspondences in front of both cameras. Legacy gates only
/// ([`CheiralityOptions::default`]).
pub fn recover_relative_pose(
    essential: &Matrix3<f64>,
    correspondences: &[TwoViewCorrespondence],
    camera: &Camera,
    inliers: &[usize],
) -> Option<(UnitQuaternion<f64>, Vector3<f64>)> {
    let recovered = recover_relative_pose_with_options(
        essential,
        correspondences,
        camera,
        inliers,
        &CheiralityOptions::default(),
    )?;
    Some((recovered.rotation, recovered.translation_unit))
}

/// Decompose an essential matrix with explicit [`CheiralityOptions`] gates.
/// Returns `None` when every hypothesis fails the positive-depth test, when
/// the winner's margin against the runner-up is too thin (ambiguous
/// chirality), or when too few inliers pass the depth/angle gates.
pub fn recover_relative_pose_with_options(
    essential: &Matrix3<f64>,
    correspondences: &[TwoViewCorrespondence],
    camera: &Camera,
    inliers: &[usize],
    options: &CheiralityOptions,
) -> Option<RelativePoseRecovery> {
    let svd = essential.try_svd(true, true, f64::EPSILON * 5.0, 10_000)?;
    let u = svd.u?;
    let v_t = svd.v_t?;

    let w = Matrix3::new(0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
    let mut r1 = u * w * v_t;
    let mut r2 = u * w.transpose() * v_t;
    if r1.determinant() < 0.0 {
        r1 = -r1;
    }
    if r2.determinant() < 0.0 {
        r2 = -r2;
    }
    let t_unit = u.column(2).into_owned();

    let candidates = [(r1, t_unit), (r1, -t_unit), (r2, t_unit), (r2, -t_unit)];
    let mut ranked: Vec<(i64, Matrix3<f64>, Vector3<f64>)> = Vec::with_capacity(4);
    let min_angle_rad = options.min_tri_angle_deg.to_radians();
    for (rotation, translation) in candidates {
        let score = cheirality_score(
            &rotation,
            &translation,
            correspondences,
            camera,
            inliers,
            min_angle_rad,
        );
        if score > 0 {
            ranked.push((score, rotation, translation));
        }
    }
    ranked.sort_by(|a, b| b.0.cmp(&a.0));
    let (best_score, rotation, translation) = ranked.first().copied()?;
    let second_score = ranked.get(1).map_or(0, |(s, _, _)| *s);
    if options.min_positive_depth_fraction > 0.0 {
        let required = (options.min_positive_depth_fraction * inliers.len() as f64).ceil() as i64;
        if best_score < required {
            return None;
        }
    }
    // Ambiguity gate: when the runner-up scores nearly as well as the winner,
    // the essential is chirality-ambiguous (typical on repetitive façades) and
    // the recovered translation direction is not trustworthy as a view-graph
    // bearing. `max_ambiguity_ratio == 1.0` never rejects on ratio alone.
    // Callers that want multi-hypothesis edges should use
    // `max_ambiguity_ratio = 1.0` and read `alternate`.
    if options.max_ambiguity_ratio < 1.0
        && second_score > 0
        && (second_score as f64) > (best_score as f64) * options.max_ambiguity_ratio
    {
        return None;
    }
    let rotation = visloc_core::geometry::rotation_from_matrix(&rotation);
    let alternate = ranked.get(1).and_then(|(score, r, t)| {
        if *score <= 0 {
            return None;
        }
        let r = visloc_core::geometry::rotation_from_matrix(r);
        // Keep only if it is a meaningfully different pose (different R or
        // anti-aligned t).
        let rot_diff = r.rotation_to(&rotation).angle();
        let t_anti = t.dot(&translation) < 0.0;
        if rot_diff > 1e-2 || t_anti {
            Some((r, *t))
        } else {
            None
        }
    });
    Some(RelativePoseRecovery {
        rotation,
        translation_unit: translation,
        best_score,
        second_score: second_score.max(0),
        alternate,
    })
}

/// Linear two-view triangulation of one normalized correspondence; `Some`
/// only when the point lies in front of both cameras. Fixed-size 4x4 SVD
/// (the same algorithm and operation order as the former `DMatrix` path).
#[inline]
fn triangulate_in_front(
    p_prev: &Matrix3x4<f64>,
    p_curr: &Matrix3x4<f64>,
    rotation: &Matrix3<f64>,
    translation: &Vector3<f64>,
    prev: Point2<f64>,
    curr: Point2<f64>,
) -> Option<Vector3<f64>> {
    let mut a = nalgebra::Matrix4::<f64>::zeros();
    for column in 0..4 {
        a[(0, column)] = prev.x * p_prev[(2, column)] - p_prev[(0, column)];
        a[(1, column)] = prev.y * p_prev[(2, column)] - p_prev[(1, column)];
        a[(2, column)] = curr.x * p_curr[(2, column)] - p_curr[(0, column)];
        a[(3, column)] = curr.y * p_curr[(2, column)] - p_curr[(1, column)];
    }
    let svd = a.try_svd(false, true, f64::EPSILON * 5.0, 10_000)?;
    let v_t = svd.v_t?;
    let solution = v_t.row(3);
    let w = solution[3];
    if w.abs() < 1e-12 {
        return None;
    }
    let world = Vector3::new(solution[0] / w, solution[1] / w, solution[2] / w);
    let camera_curr = rotation * world + translation;
    if world.z <= 0.0 || camera_curr.z <= 0.0 {
        return None;
    }
    Some(world)
}

/// Whether some decomposition of `essential` puts *every* correspondence in
/// front of both cameras, stopping each candidate pose at its first failing
/// point. Called on every minimal-sample hypothesis of the five-point
/// RANSAC, so it tests depths in closed form ([`depths_positive`]) rather
/// than by the DLT triangulation of `recover_relative_pose_with_options`
/// (one 4x4 SVD per point, most of the verification time). The two agree
/// except for points within rounding of zero depth.
fn all_in_front_for_some_pose(
    essential: &Matrix3<f64>,
    correspondences: &[TwoViewCorrespondence],
    camera: &Camera,
) -> bool {
    if correspondences.is_empty() {
        return false;
    }
    let Some(svd) = essential.try_svd(true, true, f64::EPSILON * 5.0, 10_000) else {
        return false;
    };
    let (Some(u), Some(v_t)) = (svd.u, svd.v_t) else {
        return false;
    };
    let w = Matrix3::new(0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
    let mut r1 = u * w * v_t;
    let mut r2 = u * w.transpose() * v_t;
    if r1.determinant() < 0.0 {
        r1 = -r1;
    }
    if r2.determinant() < 0.0 {
        r2 = -r2;
    }
    let t_unit = u.column(2).into_owned();
    let points: Option<Vec<(Point2<f64>, Point2<f64>)>> = correspondences
        .iter()
        .map(|c| {
            Some((
                camera.normalize_pixel(&c.previous_xy)?,
                camera.normalize_pixel(&c.current_xy)?,
            ))
        })
        .collect();
    let Some(points) = points else {
        return false;
    };
    let rays: Vec<(Vector3<f64>, Vector3<f64>)> = points
        .iter()
        .map(|(p, c)| {
            (
                Vector3::new(p.x, p.y, 1.0).normalize(),
                Vector3::new(c.x, c.y, 1.0).normalize(),
            )
        })
        .collect();
    [(r1, t_unit), (r1, -t_unit), (r2, t_unit), (r2, -t_unit)]
        .iter()
        .any(|(rotation, translation)| {
            rays.iter()
                .all(|(x1, x2)| depths_positive(rotation, translation, x1, x2))
        })
}

/// Whether the point seen along unit bearings `x1` (camera 1) and `x2`
/// (camera 2, `X2 = R X1 + t`) lies in front of both cameras: the closed-form
/// least-squares depths of `l2 x2 = l1 R x1 + t` are both positive. This is
/// PoseLib's `check_cheirality` (min depth 0), the test COLMAP's five-point
/// estimator gets from PoseLib; it needs no SVD.
fn depths_positive(
    rotation: &Matrix3<f64>,
    translation: &Vector3<f64>,
    x1: &Vector3<f64>,
    x2: &Vector3<f64>,
) -> bool {
    let rx1 = rotation * x1;
    let a = -rx1.dot(x2);
    let b1 = -rx1.dot(translation);
    let b2 = x2.dot(translation);
    // Depths times 1 / (1 - a^2) > 0.
    let lambda1 = b1 - a * b2;
    let lambda2 = -a * b1 + b2;
    lambda1 > 0.0 && lambda2 > 0.0
}

fn cheirality_score(
    rotation: &Matrix3<f64>,
    translation: &Vector3<f64>,
    correspondences: &[TwoViewCorrespondence],
    camera: &Camera,
    inliers: &[usize],
    min_tri_angle_rad: f64,
) -> i64 {
    let p_prev = Matrix3x4::new(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    let mut p_curr = Matrix3x4::zeros();
    p_curr.fixed_view_mut::<3, 3>(0, 0).copy_from(rotation);
    p_curr.fixed_view_mut::<3, 1>(0, 3).copy_from(translation);

    // Camera-2 centre in camera-1 coordinates: C2 = −Rᵀ t.
    let cam2_centre = -(rotation.transpose() * translation);

    let mut score: i64 = 0;
    for &index in inliers {
        let correspondence = &correspondences[index];
        let Some(prev) = camera.normalize_pixel(&correspondence.previous_xy) else {
            continue;
        };
        let Some(curr) = camera.normalize_pixel(&correspondence.current_xy) else {
            continue;
        };

        let Some(world) = triangulate_in_front(&p_prev, &p_curr, rotation, translation, prev, curr)
        else {
            continue;
        };
        if min_tri_angle_rad > 0.0 {
            let ray1 = world;
            let ray2 = world - cam2_centre;
            let n1 = ray1.norm();
            let n2 = ray2.norm();
            if n1 < 1e-12 || n2 < 1e-12 {
                continue;
            }
            let cos = (ray1.dot(&ray2) / (n1 * n2)).clamp(-1.0, 1.0);
            if cos.acos() < min_tri_angle_rad {
                continue;
            }
        }
        score += 1;
    }
    score
}

/// Hartley normalization for a set of 2D points: translate so the centroid is
/// at the origin and scale so the average distance to the origin is sqrt(2).
/// Returns the 3x3 transform `T` (so `T * [x, y, 1]` gives the normalized
/// point) and the normalized points themselves.
fn hartley_normalization<I>(points: I) -> Option<(Matrix3<f64>, Vec<Point2<f64>>)>
where
    I: IntoIterator<Item = Point2<f64>>,
{
    let collected: Vec<Point2<f64>> = points.into_iter().collect();
    if collected.is_empty() {
        return None;
    }

    let mut mean_x = 0.0;
    let mut mean_y = 0.0;
    for point in &collected {
        mean_x += point.x;
        mean_y += point.y;
    }
    let count = collected.len() as f64;
    mean_x /= count;
    mean_y /= count;

    let mut mean_distance = 0.0;
    for point in &collected {
        let dx = point.x - mean_x;
        let dy = point.y - mean_y;
        mean_distance += (dx * dx + dy * dy).sqrt();
    }
    mean_distance /= count;
    if mean_distance < 1.0e-12 {
        return None;
    }
    let scale = std::f64::consts::SQRT_2 / mean_distance;
    let transform = Matrix3::new(
        scale,
        0.0,
        -scale * mean_x,
        0.0,
        scale,
        -scale * mean_y,
        0.0,
        0.0,
        1.0,
    );

    let normalized = collected
        .into_iter()
        .map(|point| Point2::new(scale * (point.x - mean_x), scale * (point.y - mean_y)))
        .collect();
    Some((transform, normalized))
}

fn normalize_pairs(
    correspondences: &[TwoViewCorrespondence],
    camera: &Camera,
) -> Option<Vec<(Point2<f64>, Point2<f64>)>> {
    correspondences
        .iter()
        .map(|correspondence| {
            Some((
                camera.normalize_pixel(&correspondence.previous_xy)?,
                camera.normalize_pixel(&correspondence.current_xy)?,
            ))
        })
        .collect()
}

fn normalize_correspondences_with_cameras(
    correspondences: &[TwoViewCorrespondence],
    previous_camera: &Camera,
    current_camera: &Camera,
) -> Option<Vec<TwoViewCorrespondence>> {
    correspondences
        .iter()
        .map(|correspondence| {
            Some(TwoViewCorrespondence::new(
                previous_camera.normalize_pixel(&correspondence.previous_xy)?,
                current_camera.normalize_pixel(&correspondence.current_xy)?,
            ))
        })
        .collect()
}

fn score_inliers(
    essential: &Matrix3<f64>,
    correspondences: &[TwoViewCorrespondence],
    camera: &Camera,
    threshold_sq: f64,
) -> Vec<usize> {
    let mut inliers = Vec::with_capacity(correspondences.len());
    for (index, correspondence) in correspondences.iter().enumerate() {
        let Some(distance_sq) = sampson_distance_squared(essential, correspondence, camera) else {
            continue;
        };
        if distance_sq <= threshold_sq {
            inliers.push(index);
        }
    }
    inliers
}

fn mean_sampson_error(
    essential: &Matrix3<f64>,
    correspondences: &[TwoViewCorrespondence],
    camera: &Camera,
    inliers: &[usize],
) -> f64 {
    if inliers.is_empty() {
        return f64::INFINITY;
    }
    let mut total = 0.0;
    let mut count = 0.0;
    for &index in inliers {
        if let Some(distance_sq) =
            sampson_distance_squared(essential, &correspondences[index], camera)
        {
            total += distance_sq.sqrt();
            count += 1.0;
        }
    }
    if count > 0.0 {
        total / count
    } else {
        f64::INFINITY
    }
}

fn sampson_distance_squared(
    essential: &Matrix3<f64>,
    correspondence: &TwoViewCorrespondence,
    camera: &Camera,
) -> Option<f64> {
    let prev = camera.normalize_pixel(&correspondence.previous_xy)?;
    let curr = camera.normalize_pixel(&correspondence.current_xy)?;
    let prev_h = Vector3::new(prev.x, prev.y, 1.0);
    let curr_h = Vector3::new(curr.x, curr.y, 1.0);
    let e_prev = essential * prev_h;
    let et_curr = essential.transpose() * curr_h;
    let numerator = curr_h.dot(&e_prev).powi(2);
    let denominator = e_prev.x.powi(2) + e_prev.y.powi(2) + et_curr.x.powi(2) + et_curr.y.powi(2);
    if denominator < 1e-18 {
        return None;
    }
    Some(numerator / denominator)
}

#[cfg(test)]
mod tests {
    use super::*;
    use nalgebra::{Point3, UnitQuaternion};
    use visloc_core::geometry::Pose;

    fn synthetic_camera() -> Camera {
        Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0)
    }

    fn project(pose: &Pose, camera: &Camera, point: &Point3<f64>) -> Point2<f64> {
        camera
            .project(&pose.transform_world_point(point))
            .expect("synthetic point must project in front of the camera")
    }

    fn synthetic_world_points() -> Vec<Point3<f64>> {
        vec![
            Point3::new(-1.0, -1.0, 5.0),
            Point3::new(1.0, -1.0, 5.0),
            Point3::new(-1.0, 1.0, 5.0),
            Point3::new(1.0, 1.0, 5.0),
            Point3::new(0.0, 0.0, 5.0),
            Point3::new(0.5, -0.25, 6.0),
            Point3::new(-0.7, 0.4, 4.5),
            Point3::new(0.6, 0.8, 5.5),
            Point3::new(-0.3, -0.6, 4.8),
            Point3::new(0.2, 0.2, 6.5),
        ]
    }

    fn correspondences(
        previous_pose: &Pose,
        current_pose: &Pose,
        camera: &Camera,
        points: &[Point3<f64>],
    ) -> Vec<TwoViewCorrespondence> {
        points
            .iter()
            .map(|point| TwoViewCorrespondence {
                previous_xy: project(previous_pose, camera, point),
                current_xy: project(current_pose, camera, point),
            })
            .collect()
    }

    #[test]
    fn essential_ransac_recovers_pure_translation() {
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
        let correspondences =
            correspondences(&previous, &current, &camera, &synthetic_world_points());

        let estimator = RelativePoseEstimator::default();
        let pose = estimator
            .estimate_with_scale(&correspondences, &camera, 0.3)
            .expect("relative pose must be recovered");

        let translation = pose.previous_to_current.translation;
        assert!(
            (translation - Vector3::new(-0.3, 0.0, 0.0)).norm() < 5.0e-3,
            "translation drifted: {translation:?}"
        );
        let rotation = pose.previous_to_current.rotation.angle();
        assert!(
            rotation < 5.0e-3,
            "rotation should be near zero: {rotation}"
        );
        assert!(pose.inliers.len() >= 8);
        assert!(pose.mean_sampson_error < 5.0e-3);
    }

    #[test]
    fn essential_ransac_accepts_distinct_pinhole_cameras() {
        // The two endpoint images deliberately have different sizes and
        // focal lengths.  A shared-camera call would interpret the right
        // pixels with the wrong bearing; the camera-aware entry point must
        // normalize each endpoint before running the unchanged estimator.
        let previous_camera = synthetic_camera();
        let current_camera = Camera::pinhole(2, 800, 600, 700.0, 680.0, 400.0, 300.0);
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
        let correspondences = synthetic_world_points()
            .iter()
            .map(|point| {
                TwoViewCorrespondence::new(
                    project(&previous, &previous_camera, point),
                    project(&current, &current_camera, point),
                )
            })
            .collect::<Vec<_>>();

        let estimated = RelativePoseEstimator::default()
            .estimate_with_cameras(&correspondences, &previous_camera, &current_camera)
            .expect("distinct pinhole calibrations must still recover a pose");
        assert!(estimated.inliers.len() >= 8);
        assert!(estimated.previous_to_current.rotation.angle() < 5.0e-3);
        assert!(
            (estimated.translation_unit - Vector3::new(-1.0, 0.0, 0.0)).norm() < 5.0e-3,
            "translation direction drifted: {:?}",
            estimated.translation_unit
        );
    }

    #[test]
    fn essential_ransac_recovers_translation_with_yaw() {
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let yaw = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.05);
        let current_world_to_camera = SE3::new(yaw, Vector3::new(-0.2, 0.0, -0.05));
        let current = Pose {
            world_to_camera: current_world_to_camera.clone(),
        };
        let correspondences =
            correspondences(&previous, &current, &camera, &synthetic_world_points());

        let estimator = RelativePoseEstimator::default();
        let scale = current_world_to_camera.translation.norm();
        let pose = estimator
            .estimate_with_scale(&correspondences, &camera, scale)
            .expect("relative pose must be recovered");

        assert!(pose.inliers.len() >= 8);
        let translation_error =
            (pose.previous_to_current.translation - current_world_to_camera.translation).norm();
        assert!(
            translation_error < 5.0e-3,
            "translation drifted: error={translation_error}"
        );
        let rotation_error = pose
            .previous_to_current
            .rotation
            .rotation_to(&current_world_to_camera.rotation)
            .angle()
            .abs();
        assert!(
            rotation_error < 5.0e-3,
            "rotation drifted: error_rad={rotation_error}"
        );
    }

    #[test]
    fn essential_ransac_recovers_pure_translation_with_eight_points() {
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.30, 0.0, 0.0));
        let points = [
            Point3::new(-1.0, -1.0, 4.5),
            Point3::new(1.0, -1.0, 4.6),
            Point3::new(-1.0, 1.0, 5.5),
            Point3::new(1.0, 1.0, 5.4),
            Point3::new(0.0, 0.0, 5.0),
            Point3::new(0.5, -0.25, 6.0),
            Point3::new(-0.6, 0.4, 4.8),
            Point3::new(0.4, 0.7, 5.2),
        ];
        let correspondences = correspondences(&previous, &current, &camera, &points);

        let estimator = RelativePoseEstimator::default();
        let pose = estimator
            .estimate_with_scale(&correspondences, &camera, 0.30)
            .expect("relative pose must be recovered");
        let translation = pose.previous_to_current.translation;
        assert!(
            (translation - Vector3::new(-0.30, 0.0, 0.0)).norm() < 5.0e-3,
            "translation drifted: {translation:?}"
        );
        assert!(pose.inliers.len() >= 8);
    }

    #[test]
    fn essential_ransac_returns_none_for_too_few_points() {
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.2, 0.0, 0.0));
        let mut points = synthetic_world_points();
        points.truncate(6);
        let correspondences = correspondences(&previous, &current, &camera, &points);

        let estimator = RelativePoseEstimator::default();
        assert!(estimator.estimate(&correspondences, &camera).is_none());
    }

    #[test]
    fn weighted_ransac_recovers_pose_with_correctly_ordered_confidence_weights() {
        // 12 inlier correspondences from a real essential geometry, plus
        // 18 outlier correspondences sprinkled in random positions. The
        // inliers carry confidence ~ 0.9, the outliers ~ 0.05. The
        // weighted estimator must recover the same pose as the uniform
        // path (this checks that the PROSAC ordering doesn't break clean
        // inputs and that the confidence-driven priority correctly anchors
        // the early iterations on the inliers).
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
        let mut correspondences =
            correspondences(&previous, &current, &camera, &synthetic_world_points());
        let n_inliers = correspondences.len();
        let mut weights: Vec<f32> = vec![0.9; n_inliers];

        // Inject outlier correspondences whose pixel positions are
        // shuffled — they cannot satisfy the true essential geometry.
        let outlier_seeds = [
            (50.0, 60.0, 200.0, 90.0),
            (310.0, 100.0, 70.0, 410.0),
            (250.0, 200.0, 100.0, 100.0),
            (440.0, 330.0, 200.0, 60.0),
            (90.0, 350.0, 320.0, 240.0),
            (10.0, 410.0, 540.0, 430.0),
            (280.0, 70.0, 110.0, 200.0),
            (190.0, 30.0, 460.0, 160.0),
            (370.0, 250.0, 50.0, 50.0),
            (230.0, 410.0, 600.0, 100.0),
            (100.0, 110.0, 300.0, 350.0),
            (420.0, 90.0, 30.0, 220.0),
            (150.0, 300.0, 480.0, 60.0),
            (350.0, 150.0, 70.0, 320.0),
            (60.0, 250.0, 230.0, 70.0),
            (270.0, 380.0, 540.0, 290.0),
            (390.0, 20.0, 90.0, 270.0),
            (210.0, 170.0, 470.0, 380.0),
        ];
        for (px, py, cx, cy) in outlier_seeds {
            correspondences.push(TwoViewCorrespondence::new(
                nalgebra::Point2::new(px, py),
                nalgebra::Point2::new(cx, cy),
            ));
            weights.push(0.05);
        }
        assert_eq!(weights.len(), correspondences.len());

        let ransac = EssentialRansac {
            estimator: EightPointEssentialMatrixEstimator::default(),
            config: EssentialRansacConfig {
                iterations: 64,
                sampson_threshold: 5.0e-3,
                seed: 11,
            },
        };

        let weighted_report = ransac
            .estimate_with_weights(&correspondences, &camera, &weights)
            .expect("weighted RANSAC must recover a model from clean inliers");

        // The first n_inliers correspondences are the geometric inliers;
        // the weighted RANSAC should recover essentially all of them.
        let recovered_inliers: usize = weighted_report
            .inliers
            .iter()
            .filter(|&&i| i < n_inliers)
            .count();
        assert!(
            recovered_inliers >= n_inliers - 1,
            "weighted RANSAC should recover the geometric inliers, got {recovered_inliers}/{n_inliers}"
        );
        assert!(weighted_report.mean_sampson_error < 5.0e-3);
    }

    #[test]
    fn weighted_ransac_falls_back_to_uniform_when_weights_are_all_zero() {
        // Same clean correspondences, but all weights are zero — the
        // PROSAC ordering should fall back to the uniform sampling path
        // (no iteration_progress shrinking) and the recovery should
        // match the unweighted estimate.
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
        let correspondences =
            correspondences(&previous, &current, &camera, &synthetic_world_points());
        let weights: Vec<f32> = vec![0.0; correspondences.len()];

        let ransac = EssentialRansac::default();
        let unweighted = ransac.estimate(&correspondences, &camera).unwrap();
        let weighted = ransac
            .estimate_with_weights(&correspondences, &camera, &weights)
            .unwrap();
        assert_eq!(unweighted.inliers, weighted.inliers);
    }

    #[test]
    fn hardened_cheirality_recovers_clean_translation() {
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
        let correspondences =
            correspondences(&previous, &current, &camera, &synthetic_world_points());
        let estimator = RelativePoseEstimator {
            cheirality: CheiralityOptions::hardened(),
            ..RelativePoseEstimator::default()
        };
        let pose = estimator
            .estimate_with_scale(&correspondences, &camera, 0.3)
            .expect("hardened recovery must succeed on a clean baseline");
        assert!(
            (pose.previous_to_current.translation - Vector3::new(-0.3, 0.0, 0.0)).norm() < 5e-3
        );
    }

    #[test]
    fn hardened_cheirality_rejects_near_planar_pure_rotation() {
        // Near-zero baseline: every (R, ±t) hypothesis triangulates with tiny
        // angles, so the angle gate + ambiguity ratio should refuse recovery.
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let yaw = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.02);
        let current = Pose::from_world_to_camera(yaw, Vector3::new(-1e-4, 0.0, 0.0));
        let correspondences =
            correspondences(&previous, &current, &camera, &synthetic_world_points());
        let report = EssentialRansac::default()
            .estimate(&correspondences, &camera)
            .expect("essential still fits a near-planar pair");
        let recovered = recover_relative_pose_with_options(
            &report.essential,
            &correspondences,
            &camera,
            &report.inliers,
            &CheiralityOptions::hardened(),
        );
        assert!(
            recovered.is_none(),
            "pure-rotation / tiny-baseline essentials must fail hardened gates"
        );
    }

    #[test]
    fn chirality_margin_is_high_on_clean_baseline() {
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
        let correspondences =
            correspondences(&previous, &current, &camera, &synthetic_world_points());
        let report = EssentialRansac::default()
            .estimate(&correspondences, &camera)
            .unwrap();
        let recovered = recover_relative_pose_with_options(
            &report.essential,
            &correspondences,
            &camera,
            &report.inliers,
            &CheiralityOptions::default(),
        )
        .unwrap();
        assert!(
            recovered.chirality_margin() > 0.5,
            "clean baseline should separate winner from runner-up, margin={}",
            recovered.chirality_margin()
        );
    }

    #[test]
    fn hardened_keep_ambiguous_exposes_alternate_on_clean_pair() {
        // Even a clean pair has a runner-up (usually −t or the other R); with
        // keep-ambiguous gates that runner-up is returned rather than rejected.
        let camera = synthetic_camera();
        let previous =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        let current =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
        let correspondences =
            correspondences(&previous, &current, &camera, &synthetic_world_points());
        let report = EssentialRansac::default()
            .estimate(&correspondences, &camera)
            .unwrap();
        let recovered = recover_relative_pose_with_options(
            &report.essential,
            &correspondences,
            &camera,
            &report.inliers,
            &CheiralityOptions::hardened_keep_ambiguous(),
        )
        .expect("clean pair must recover under keep-ambiguous");
        assert!(recovered.best_score > 0);
        // Runner-up score may be low; alternate is only set when it differs.
        if recovered.second_score > 0 {
            assert!(
                recovered.alternate.is_some() || recovered.chirality_margin() > 0.99,
                "expected an alternate or a decisive margin"
            );
        }
    }
}