Skip to main content

visloc_slam/
global_sfm.rs

1//! GLOMAP-style global structure-from-motion back-end: rotation averaging
2//! followed by translation-direction position averaging.
3//!
4//! The incremental mapper ([`crate::incremental_sfm::incremental_sfm`]) grows one
5//! reconstruction image by image; the global SfM lineage (GLOMAP, Stumberger
6//! et al. 2024, and its ancestors) instead exploits verified pairwise
7//! relative poses directly: average all relative rotations into one
8//! consistent world frame, then solve camera positions jointly from the
9//! relative translation **directions**, and only afterwards run bundle
10//! adjustment. Global estimation avoids the sequential drift an incremental
11//! chain accumulates and parallelises trivially.
12//!
13//! This module implements that two-stage geometry pipeline in pure Rust:
14//!
15//! 1. **Rotation averaging** — maximum-spanning-tree propagation seeds every
16//!    camera of the root component, then iterative geodesic consensus sweeps
17//!    pull each orientation towards the weighted SO(3) mean of its
18//!    neighbours' predictions (the dominant eigenvector of each camera's
19//!    weighted quaternion outer-product sum, tracked by warm-started power
20//!    iteration — chordal-L2 relaxation evaluated lazily, no dense system).
21//! 2. **Position averaging** — with rotations fixed, every edge contributes
22//!    four least-squares rows on the unknown camera centres: three
23//!    perpendicular rows `(c_i − c_j) ⊥ d_ij` and one **unit-displacement**
24//!    row `d̂_ij · (c_i − c_j) = 1`. The perpendicular rows make displacements
25//!    parallel to the measured bearings; the unit rows give the problem a
26//!    non-trivial scale (each edge votes its own displacement magnitude),
27//!    which the joint solve arbitrates globally. Conjugate gradient on the
28//!    normal equations; a weak origin prior absorbs the free-translation
29//!    nullspace and the solved field is re-anchored so the seed centre sits
30//!    exactly at the origin.
31//!
32//! Monocular relative translations are scale-free per edge, so positions
33//! come out up to one global scale — the same gauge freedom every global SfM
34//! system carries into its similarity alignment against metric sources.
35//!
36//! Only the connected component containing the seed camera is solved;
37//! images outside it stay unposed.
38
39use std::collections::{HashMap, HashSet};
40
41use nalgebra::{DMatrix, DVector, Matrix3, Point2, Point3, UnitQuaternion, Vector3};
42
43use visloc_core::geometry::{Pose, Sim3, SE3};
44use visloc_core::types::Camera;
45use visloc_tracking::umeyama_similarity_transform;
46use visloc_vision::features::FeatureSet;
47use visloc_vision::stereo_bootstrap::triangulate_two_view_left_frame;
48use visloc_vision::two_view::{
49    recover_relative_pose_with_options, CheiralityOptions, ConfigurationType, RelativePose,
50    RelativePoseEstimator, TwoViewCorrespondence,
51};
52
53use crate::incremental_sfm::{
54    build_track_output, post_refinement_registration_pass, reprojection_error_px,
55    run_bundle_adjustment, triangulate_pending, PairwiseMatches, PnpSolver, SfmTrack,
56};
57use visloc_vision::pnp::{Correspondence2D3D, GaussNewtonPoseRefiner, P3PGrunert};
58use visloc_vision::ransac::{PnPRansac, RobustPoseEstimator};
59
60/// One verified pairwise constraint between two views of the view graph.
61#[derive(Debug, Clone, PartialEq)]
62pub struct GlobalSfmEdge {
63    /// First image index.
64    pub image_i: usize,
65    /// Second image index.
66    pub image_j: usize,
67    /// Relative rotation `R_ij` mapping camera-`i`-frame coordinates to
68    /// camera-`j`-frame coordinates (`X_j = R_ij · X_i + t_ij`). Composed
69    /// with world-to-camera orientations: `R_w2c_j = R_ij · R_w2c_i`.
70    pub rotation_ij: UnitQuaternion<f64>,
71    /// Relative translation **direction** from camera `i` to camera `j`,
72    /// expressed in camera `i`'s frame (unit length; essential-matrix
73    /// decompositions recover this up to per-edge scale only).
74    pub direction_ij: Vector3<f64>,
75    /// Edge weight (e.g., verified inlier count).
76    pub weight: f64,
77    /// Sample of inlier pixel correspondences retained so translation can be
78    /// re-estimated under globally-averaged rotations. Empty in synthetic
79    /// fixtures that only exercise averaging.
80    pub inlier_sample: Vec<(Point2<f64>, Point2<f64>)>,
81    /// Optional runner-up relative rotation from chirality-ambiguous essential
82    /// decomposition. Rotation averaging picks primary vs alternate by
83    /// agreement with the emerging global solution.
84    pub rotation_alt: Option<UnitQuaternion<f64>>,
85    /// Bearing paired with [`Self::rotation_alt`] (camera-j centre in cam-i).
86    pub direction_alt: Option<Vector3<f64>>,
87}
88
89impl GlobalSfmEdge {
90    /// Relative rotation step leaving `from` under the primary hypothesis.
91    fn step_primary(&self, from: usize) -> UnitQuaternion<f64> {
92        if self.image_i == from {
93            self.rotation_ij
94        } else {
95            self.rotation_ij.inverse()
96        }
97    }
98
99    /// Relative rotation step leaving `from`, choosing primary or alternate
100    /// by which better predicts `to_hint` when supplied.
101    fn step_adaptive(
102        &self,
103        from: usize,
104        from_q: UnitQuaternion<f64>,
105        to_hint: Option<UnitQuaternion<f64>>,
106    ) -> UnitQuaternion<f64> {
107        let primary = self.step_primary(from);
108        let Some(hint) = to_hint else {
109            return primary;
110        };
111        let Some(r_alt) = self.rotation_alt else {
112            return primary;
113        };
114        let alt = if self.image_i == from {
115            r_alt
116        } else {
117            r_alt.inverse()
118        };
119        let primary_pred = primary * from_q;
120        let alt_pred = alt * from_q;
121        if (alt_pred.inverse() * hint).angle() + 1e-12 < (primary_pred.inverse() * hint).angle() {
122            alt
123        } else {
124            primary
125        }
126    }
127
128    /// Select primary or alternate (R, direction) under current global
129    /// orientations of both endpoints.
130    fn select_pose(
131        &self,
132        qi: UnitQuaternion<f64>,
133        qj: UnitQuaternion<f64>,
134    ) -> (UnitQuaternion<f64>, Vector3<f64>) {
135        let primary_err = ((self.rotation_ij * qi).inverse() * qj).angle();
136        if let (Some(r_alt), Some(d_alt)) = (self.rotation_alt, self.direction_alt) {
137            let alt_err = ((r_alt * qi).inverse() * qj).angle();
138            if alt_err + 1e-12 < primary_err {
139                return (r_alt, d_alt);
140            }
141        }
142        (self.rotation_ij, self.direction_ij)
143    }
144
145    /// Swap primary ↔ alternate in place. No-op when no alternate is stored.
146    const fn swap_primary_alternate(&mut self) {
147        let Some(r_alt) = self.rotation_alt.take() else {
148            return;
149        };
150        let Some(d_alt) = self.direction_alt.take() else {
151            self.rotation_alt = Some(r_alt);
152            return;
153        };
154        self.rotation_alt = Some(self.rotation_ij);
155        self.direction_alt = Some(self.direction_ij);
156        self.rotation_ij = r_alt;
157        self.direction_ij = d_alt;
158    }
159}
160
161/// Result of the global pose solve.
162#[derive(Debug, Clone, PartialEq)]
163pub struct GlobalSfmPoses {
164    /// One pose per input image; `None` for images outside the solved
165    /// component (or everything when no usable edges exist).
166    pub poses: Vec<Option<Pose>>,
167    /// Mean angular residual over solved edges, in radians: the angle
168    /// between each edge's solved centre displacement and its measured
169    /// bearing direction.
170    pub mean_bearing_residual_rad: f64,
171    /// How many edge translation directions were flipped by
172    /// [`refine_edge_directions_under_rotations`] (0 when refine is off).
173    pub translation_refine_flips: usize,
174}
175
176type JointTrackPositioningInput<'a> = (&'a Camera, &'a [FeatureSet], &'a [Vec<(usize, usize)>]);
177
178/// Solve global camera poses from verified pairwise relative-pose edges.
179///
180/// `num_images` sizes the output; `seed` is the gauge camera (identity
181/// rotation, centre pinned at the origin); `sweeps` bounds the rotation
182/// consensus iterations (8–16 is ample on well-connected graphs);
183/// `cg_iterations` bounds the position least-squares solver.
184/// `max_edge_rotation_error_deg` trims edges whose implied relative rotation
185/// disagrees with the emerging global solution by more than this angle
186/// (IRLS-style outlier rejection; 10° is a reasonable default).
187///
188/// Returns `None` when no valid edge touches any image.
189///
190/// When `refine_translations` is true and `camera` is supplied, after
191/// rotation averaging each edge's `direction_ij` is re-scored under the
192/// consensus relative rotation (and optionally re-estimated from its
193/// inlier sample via a fixed-R epipolar nullspace). This is the lever that
194/// can flip chirality-ambiguous pairwise translations once the rotation
195/// graph has left the wrong basin.
196///
197/// `pose_priors`, when supplied, pins those cameras' world-to-camera
198/// orientations during averaging. When `pin_prior_centres` is true (default
199/// hybrid), Sim(3)-aligns the solved centres onto the prior centres and
200/// writes the full incremental pose back. When false (`--hybrid-rotation-priors-only`),
201/// incremental orientations stay pinned but camera centres come from global
202/// bearing averaging instead of the incremental solve.
203///
204/// `joint_tracks`, when supplied with `joint_global_positioning`, refines
205/// centres via GLOMAP-style camera+point ray IRLS after pairwise init.
206#[allow(clippy::too_many_arguments)]
207pub fn solve_global_sfm(
208    num_images: usize,
209    edges: &mut [GlobalSfmEdge],
210    seed: usize,
211    sweeps: usize,
212    cg_iterations: usize,
213    max_edge_rotation_error_deg: f64,
214    refine_translations: bool,
215    camera: Option<&Camera>,
216    pose_priors: Option<&[Option<Pose>]>,
217    pin_prior_centres: bool,
218    joint_tracks: Option<JointTrackPositioningInput<'_>>,
219    repair_prior_edges: bool,
220    metric_prior_scale: bool,
221) -> Option<GlobalSfmPoses> {
222    solve_global_sfm_with_options(
223        num_images,
224        edges,
225        seed,
226        sweeps,
227        cg_iterations,
228        max_edge_rotation_error_deg,
229        refine_translations,
230        camera,
231        pose_priors,
232        pin_prior_centres,
233        joint_tracks,
234        repair_prior_edges,
235        metric_prior_scale,
236        false,
237    )
238}
239
240/// Internal global pose solve with experimental position-averaging options.
241/// The public [`solve_global_sfm`] wrapper intentionally keeps the historical
242/// unit-displacement solver as its default.
243#[allow(clippy::too_many_arguments)]
244fn solve_global_sfm_with_options(
245    num_images: usize,
246    edges: &mut [GlobalSfmEdge],
247    seed: usize,
248    sweeps: usize,
249    cg_iterations: usize,
250    max_edge_rotation_error_deg: f64,
251    refine_translations: bool,
252    camera: Option<&Camera>,
253    pose_priors: Option<&[Option<Pose>]>,
254    pin_prior_centres: bool,
255    joint_tracks: Option<JointTrackPositioningInput<'_>>,
256    repair_prior_edges: bool,
257    metric_prior_scale: bool,
258    independent_edge_scales: bool,
259) -> Option<GlobalSfmPoses> {
260    let adjacency = build_adjacency(num_images, edges)?;
261    let fixed_rots: Option<Vec<Option<UnitQuaternion<f64>>>> = pose_priors.map(|priors| {
262        priors
263            .iter()
264            .map(|p| p.as_ref().map(|pose| pose.world_to_camera.rotation))
265            .collect()
266    });
267    let (mut rotations, mut edge_weights) = average_rotations_with_priors(
268        num_images,
269        edges,
270        &adjacency,
271        seed,
272        sweeps,
273        max_edge_rotation_error_deg,
274        fixed_rots.as_deref(),
275    );
276    let component: Vec<usize> = rotations
277        .iter()
278        .enumerate()
279        .filter(|(_, r)| r.is_some())
280        .map(|(i, _)| i)
281        .collect();
282    if component.is_empty() {
283        return None;
284    }
285    let mut translation_refine_flips = 0usize;
286    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
287        let mut errs: Vec<f64> = Vec::new();
288        let kept = edge_weights.iter().filter(|&&w| w > 0.0).count();
289        for (index, e) in edges.iter().enumerate() {
290            if edge_weights[index] <= 0.0 {
291                continue;
292            }
293            if let (Some(qi), Some(qj)) = (rotations[e.image_i], rotations[e.image_j]) {
294                let predicted = step_from(edges, index, e.image_i) * qi;
295                errs.push((predicted.inverse() * qj).angle());
296            }
297        }
298        errs.sort_by(|a, b| a.total_cmp(b));
299        let med = errs.get(errs.len() / 2).copied().unwrap_or(f64::NAN);
300        eprintln!(
301            "global-sfm debug: post-average rotation err median={:.4} deg max={:.4} deg kept={}/{}",
302            med.to_degrees(),
303            errs.last().map_or(f64::NAN, |e| e.to_degrees()),
304            kept,
305            edges.len()
306        );
307    }
308    if refine_translations {
309        if let Some(cam) = camera {
310            translation_refine_flips =
311                refine_edge_directions_under_rotations(edges, &rotations, &edge_weights, cam);
312            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
313                eprintln!(
314                    "global-sfm debug: global-R translation refine flipped {translation_refine_flips} edge directions"
315                );
316            }
317        }
318    }
319    if repair_prior_edges {
320        if let Some(priors) = pose_priors {
321            let (repaired, flipped) =
322                repair_edges_from_pose_priors(edges, &mut edge_weights, priors);
323            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
324                eprintln!(
325                    "global-sfm debug: prior-edge repair rewrote {repaired} edges (flipped {flipped})"
326                );
327            }
328        }
329    }
330    let mut centers = if independent_edge_scales {
331        average_positions_with_independent_edge_scales(
332            edges,
333            &edge_weights,
334            &rotations,
335            seed,
336            cg_iterations,
337        )
338        .unwrap_or_else(|| {
339            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
340                eprintln!(
341                    "global-sfm debug: independent edge-scale solve was rank-deficient; falling back to legacy position averaging"
342                );
343            }
344            average_positions_with_priors(
345                edges,
346                &edge_weights,
347                &rotations,
348                seed,
349                cg_iterations,
350                if metric_prior_scale {
351                    pose_priors
352                } else {
353                    None
354                },
355            )
356        })
357    } else {
358        average_positions_with_priors(
359            edges,
360            &edge_weights,
361            &rotations,
362            seed,
363            cg_iterations,
364            if metric_prior_scale {
365                pose_priors
366            } else {
367                None
368            },
369        )
370    };
371    if let Some((cam, feats, tracks)) = joint_tracks {
372        let pinned = if pin_prior_centres { pose_priors } else { None };
373        centers =
374            refine_centers_joint_tracks(cam, feats, tracks, &rotations, centers, seed, pinned);
375        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
376            let posed = centers.iter().filter(|c| c.is_some()).count();
377            eprintln!("global-sfm debug: joint track positioning kept {posed} centres");
378        }
379    }
380    if let Some(priors) = pose_priors {
381        if pin_prior_centres {
382            align_solution_to_pose_priors(&mut rotations, &mut centers, priors);
383        } else {
384            align_rotation_only_gauge(&mut centers, priors, seed);
385        }
386    }
387    let mut poses: Vec<Option<Pose>> = vec![None; num_images];
388    for &image in &component {
389        if let Some(priors) = pose_priors {
390            if let Some(Some(prior)) = priors.get(image) {
391                if pin_prior_centres {
392                    poses[image] = Some(prior.clone());
393                    continue;
394                }
395                let Some(center) = centers[image] else {
396                    continue;
397                };
398                let q = prior.world_to_camera.rotation;
399                let t_w2c = -q.transform_vector(&center.coords);
400                poses[image] = Some(Pose::from_world_to_camera(q, t_w2c));
401                continue;
402            }
403        }
404        let (Some(q_w2c), Some(center)) = (rotations[image], centers[image]) else {
405            continue;
406        };
407        let t_w2c = -q_w2c.transform_vector(&center.coords);
408        poses[image] = Some(Pose::from_world_to_camera(q_w2c, t_w2c));
409    }
410    let (mut sum, mut count) = (0.0f64, 0usize);
411    for (edge_index, edge) in edges.iter().enumerate() {
412        if edge_weights.get(edge_index).copied().unwrap_or(1.0) <= 0.0 {
413            continue;
414        }
415        let (Some(ci), Some(cj)) = (
416            centers.get(edge.image_i).copied().flatten(),
417            centers.get(edge.image_j).copied().flatten(),
418        ) else {
419            continue;
420        };
421        let Some(q_i) = rotations[edge.image_i] else {
422            continue;
423        };
424        let measured = q_i
425            .inverse()
426            .transform_vector(&edge.direction_ij)
427            .normalize();
428        let displacement = cj - ci;
429        let norm = displacement.norm();
430        if norm < 1e-12 {
431            continue;
432        }
433        let cos = (displacement.dot(&measured) / norm).clamp(-1.0, 1.0);
434        sum += cos.acos();
435        count += 1;
436    }
437    Some(GlobalSfmPoses {
438        mean_bearing_residual_rad: sum / count.max(1) as f64,
439        translation_refine_flips,
440        poses,
441    })
442}
443
444/// Scale + seed translation for hybrid rotation-only priors: robust inter-prior
445/// distance ratios set metric scale; the seed prior's incremental centre anchors
446/// translation. Prior cameras are not snapped to their incremental centres.
447fn align_rotation_only_gauge(
448    centers: &mut [Option<Point3<f64>>],
449    priors: &[Option<Pose>],
450    seed: usize,
451) {
452    let prior_indices: Vec<usize> = priors
453        .iter()
454        .enumerate()
455        .filter_map(|(i, p)| p.as_ref().map(|_| i))
456        .collect();
457    if prior_indices.len() < 2 {
458        return;
459    }
460    let mut ratios = Vec::new();
461    for a in 0..prior_indices.len() {
462        for b in (a + 1)..prior_indices.len() {
463            let i = prior_indices[a];
464            let j = prior_indices[b];
465            let (Some(ci), Some(cj), Some(pi), Some(pj)) = (
466                centers.get(i).copied().flatten(),
467                centers.get(j).copied().flatten(),
468                priors.get(i).and_then(|p| p.as_ref()),
469                priors.get(j).and_then(|p| p.as_ref()),
470            ) else {
471                continue;
472            };
473            let da = (ci - cj).norm();
474            let dp = (pi.camera_center_world() - pj.camera_center_world()).norm();
475            if da > 1e-9 && dp > 1e-9 {
476                ratios.push(dp / da);
477            }
478        }
479    }
480    if ratios.is_empty() {
481        return;
482    }
483    ratios.sort_by(f64::total_cmp);
484    // Need several prior pairs for incremental layout to constrain scale; with
485    // only one pair a wrong prior distance would corrupt the whole solve.
486    let scale = if ratios.len() >= 3 {
487        let s = ratios[ratios.len() / 2];
488        if s.is_finite() && s > 0.0 {
489            s
490        } else {
491            1.0
492        }
493    } else {
494        1.0
495    };
496    if !(scale.is_finite() && scale > 0.0) {
497        return;
498    }
499    for c in centers.iter_mut().flatten() {
500        *c = Point3::from(scale * c.coords);
501    }
502    let Some(seed_prior) = priors.get(seed).and_then(|p| p.as_ref()) else {
503        return;
504    };
505    let Some(seed_center) = centers.get(seed).copied().flatten() else {
506        return;
507    };
508    let delta = seed_prior.camera_center_world() - seed_center;
509    for c in centers.iter_mut().flatten() {
510        *c = Point3::from(c.coords + delta);
511    }
512    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
513        eprintln!(
514            "global-sfm debug: rotation-only gauge scale={scale:.4} from {} prior pairs (seed={seed})",
515            ratios.len()
516        );
517    }
518}
519
520/// Sim(3)-align solved centres (and free rotations) onto absolute pose priors.
521fn align_solution_to_pose_priors(
522    rotations: &mut [Option<UnitQuaternion<f64>>],
523    centers: &mut [Option<Point3<f64>>],
524    priors: &[Option<Pose>],
525) {
526    let mut src = Vec::new();
527    let mut dst = Vec::new();
528    let n = rotations.len().min(centers.len()).min(priors.len());
529    for i in 0..n {
530        let (Some(c), Some(prior)) = (centers[i], priors[i].as_ref()) else {
531            continue;
532        };
533        src.push(c);
534        dst.push(prior.camera_center_world());
535    }
536    if src.len() < 3 {
537        return;
538    }
539    let Some(fit) = umeyama_similarity_transform(&src, &dst, true) else {
540        return;
541    };
542    if !(fit.scale.is_finite() && fit.scale > 0.0) {
543        return;
544    }
545    let sim = Sim3::new(
546        UnitQuaternion::from_rotation_matrix(&fit.rotation),
547        fit.translation,
548        fit.scale,
549    );
550    let r_inv = UnitQuaternion::from_rotation_matrix(&fit.rotation).inverse();
551    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
552        eprintln!(
553            "global-sfm debug: aligned to {} pose priors (Sim3 scale={:.4})",
554            src.len(),
555            fit.scale
556        );
557    }
558    for i in 0..n {
559        if priors.get(i).and_then(|p| p.as_ref()).is_some() {
560            // Exact prior pose is written later; keep centre/rotation coherent.
561            if let Some(prior) = priors[i].as_ref() {
562                centers[i] = Some(prior.camera_center_world());
563                rotations[i] = Some(prior.world_to_camera.rotation);
564            }
565            continue;
566        }
567        if let Some(c) = centers[i] {
568            centers[i] = Some(sim.transform_point(&c));
569        }
570        if let Some(q) = rotations[i] {
571            rotations[i] = Some(q * r_inv);
572        }
573    }
574}
575
576/// Adjacency: image → [(neighbor, edge_index)].
577type Adjacency = HashMap<usize, Vec<(usize, usize)>>;
578
579fn build_adjacency(num_images: usize, edges: &[GlobalSfmEdge]) -> Option<Adjacency> {
580    if num_images == 0 || edges.is_empty() {
581        return None;
582    }
583    let mut adjacency: Adjacency = HashMap::new();
584    for (index, edge) in edges.iter().enumerate() {
585        if edge.image_i >= num_images || edge.image_j >= num_images || edge.image_i == edge.image_j
586        {
587            continue;
588        }
589        if !(edge.weight.is_finite() && edge.weight > 0.0) {
590            continue;
591        }
592        let n2 = edge.direction_ij.norm_squared();
593        if !n2.is_finite() || n2 < 1e-18 {
594            continue;
595        }
596        adjacency
597            .entry(edge.image_i)
598            .or_default()
599            .push((edge.image_j, index));
600        adjacency
601            .entry(edge.image_j)
602            .or_default()
603            .push((edge.image_i, index));
604    }
605    (!adjacency.is_empty()).then_some(adjacency)
606}
607
608/// Rotation step along an edge leaving `from`: composes onto `from`'s
609/// orientation to predict its neighbour's.
610fn step_from(edges: &[GlobalSfmEdge], index: usize, from: usize) -> UnitQuaternion<f64> {
611    edges[index].step_primary(from)
612}
613
614/// Maximum-spanning-tree rotation seeding (Prim-style over descending weights).
615/// Returns per-image orientations plus the reached member list; images not
616/// connected to the root (or prior set) stay `None`.
617///
618/// When `fixed_rotations` supplies absolute orientations (e.g. from an
619/// incremental solve), those cameras are pinned and the tree grows outward
620/// from their union instead of from a single identity seed.
621fn tree_seed_rotations(
622    num_images: usize,
623    edges: &[GlobalSfmEdge],
624    adjacency: &Adjacency,
625    root: usize,
626    fixed_rotations: Option<&[Option<UnitQuaternion<f64>>]>,
627) -> (Vec<Option<UnitQuaternion<f64>>>, Vec<usize>, Vec<bool>) {
628    // Maximum-spanning-tree growth from the root, Prim-style: always extend
629    // through the highest-weight edge leaving the reached set. A Kruskal
630    // pass cannot be used here because it consumes tree edges inside the
631    // unreached mass before the frontier ever reaches them, stranding the
632    // seed (observed as posed=4 on courtyard's 37-image component).
633    let mut reached = vec![false; num_images];
634    let mut rotations: Vec<Option<UnitQuaternion<f64>>> = vec![None; num_images];
635    let mut fixed_mask = vec![false; num_images];
636    let mut members = Vec::new();
637    if let Some(fixed) = fixed_rotations {
638        for (i, prior) in fixed.iter().enumerate().take(num_images) {
639            if let Some(q) = prior {
640                rotations[i] = Some(*q);
641                reached[i] = true;
642                fixed_mask[i] = true;
643                members.push(i);
644            }
645        }
646    }
647    if members.is_empty() {
648        reached[root] = true;
649        rotations[root] = Some(UnitQuaternion::identity());
650        members.push(root);
651    } else if !reached[root] {
652        // Priors define the gauge; keep `root` as a free camera grown from them.
653    }
654    // Frontier heap of (weight key, tie-break index, from, edge_index).
655    let mut heap: std::collections::BinaryHeap<(u64, usize, usize, usize)> =
656        std::collections::BinaryHeap::new();
657    let push_frontier = |heap: &mut std::collections::BinaryHeap<(u64, usize, usize, usize)>,
658                         node: usize,
659                         reached: &[bool]| {
660        if let Some(neighbors) = adjacency.get(&node) {
661            for &(neighbor, edge_index) in neighbors {
662                if !reached[neighbor] {
663                    let w = edges[edge_index].weight;
664                    let key = if w.is_finite() && w > 0.0 { w } else { 1.0 };
665                    // Quantize the weight into the u64 key (nanogram precision
666                    // is plenty for inlier counts) so the heap is total.
667                    let key_bits = (key.max(0.0) * 1e6).round().max(0.0) as u64;
668                    heap.push((key_bits, usize::MAX - edge_index, node, edge_index));
669                }
670            }
671        }
672    };
673    for &node in &members {
674        push_frontier(&mut heap, node, &reached);
675    }
676    while let Some((_, _, known, edge_index)) = heap.pop() {
677        let unknown = {
678            let e = &edges[edge_index];
679            if reached[e.image_i] && !reached[e.image_j] {
680                e.image_j
681            } else if reached[e.image_j] && !reached[e.image_i] {
682                e.image_i
683            } else {
684                continue;
685            }
686        };
687        let base = rotations[known].expect("frontier source carries a seeded orientation");
688        rotations[unknown] = Some(step_from(edges, edge_index, known) * base);
689        reached[unknown] = true;
690        members.push(unknown);
691        push_frontier(&mut heap, unknown, &reached);
692    }
693    members.sort_unstable();
694    (rotations, members, fixed_mask)
695}
696
697/// Iterative geodesic-consensus rotation averaging over the root's
698/// component. Each sweep recomputes every non-seed / non-fixed orientation
699/// as the weighted SO(3) mean of its neighbours' predictions.
700///
701/// `fixed_rotations`, when supplied, pins those cameras for the whole solve
702/// (hybrid incremental→global gauge).
703pub fn average_rotations(
704    num_images: usize,
705    edges: &[GlobalSfmEdge],
706    adjacency: &Adjacency,
707    seed: usize,
708    sweeps: usize,
709    max_edge_rotation_error_deg: f64,
710) -> (Vec<Option<UnitQuaternion<f64>>>, Vec<f64>) {
711    average_rotations_with_priors(
712        num_images,
713        edges,
714        adjacency,
715        seed,
716        sweeps,
717        max_edge_rotation_error_deg,
718        None,
719    )
720}
721
722fn average_rotations_with_priors(
723    num_images: usize,
724    edges: &[GlobalSfmEdge],
725    adjacency: &Adjacency,
726    seed: usize,
727    sweeps: usize,
728    max_edge_rotation_error_deg: f64,
729    fixed_rotations: Option<&[Option<UnitQuaternion<f64>>]>,
730) -> (Vec<Option<UnitQuaternion<f64>>>, Vec<f64>) {
731    // IRLS edge weights: start from the verified-inlier weight; each sweep
732    // zeroes edges whose implied relative rotation disagrees with the
733    // emerging global solution beyond the trim threshold.
734    let mut weights: Vec<f64> = edges.iter().map(|e| e.weight.max(1.0)).collect();
735    let max_error_rad = max_edge_rotation_error_deg.to_radians();
736    let (mut rotations, members, fixed_mask) =
737        tree_seed_rotations(num_images, edges, adjacency, seed, fixed_rotations);
738    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
739        let n_fixed = fixed_mask.iter().filter(|&&f| f).count();
740        eprintln!(
741            "global-sfm debug: tree seed reached {} of {} images from root {} ({} rotation priors)",
742            members.len(),
743            num_images,
744            seed,
745            n_fixed
746        );
747    }
748    let mut ordered_members = members;
749    ordered_members.sort_unstable();
750    for _ in 0..sweeps {
751        // Gauss-Seidel style: consume this sweep's own updates immediately
752        // (Jacobi snapshots can oscillate on noisy view graphs).
753        for &image in &ordered_members {
754            if image == seed || fixed_mask.get(image).copied().unwrap_or(false) {
755                continue;
756            }
757            let Some(neighbors) = adjacency.get(&image) else {
758                continue;
759            };
760            if neighbors.is_empty() {
761                continue;
762            }
763            // Weighted quaternion outer-product matrix M = Σ w q qᵀ over
764            // neighbour-implied predictions of this camera's orientation.
765            let mut m = [[0.0f64; 4]; 4];
766            for &(neighbor, edge_index) in neighbors {
767                let w = weights[edge_index];
768                if w <= 0.0 {
769                    continue;
770                }
771                let Some(neighbor_q) = rotations[neighbor] else {
772                    continue;
773                };
774                let predicted =
775                    edges[edge_index].step_adaptive(neighbor, neighbor_q, rotations[image])
776                        * neighbor_q;
777                let q = predicted.coords;
778                let w = w.max(1.0);
779                for r in 0..4 {
780                    for c in 0..4 {
781                        m[r][c] += w * q[r] * q[c];
782                    }
783                }
784            }
785            let Some(current) = rotations[image] else {
786                continue;
787            };
788            let mut v = *current.as_vector();
789            for _ in 0..8 {
790                let next = [
791                    m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] * v.w,
792                    m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] * v.w,
793                    m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] * v.w,
794                    m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3] * v.w,
795                ];
796                let norm =
797                    (next[0] * next[0] + next[1] * next[1] + next[2] * next[2] + next[3] * next[3])
798                        .sqrt();
799                if !norm.is_finite() || norm < 1e-15 {
800                    break;
801                }
802                v = nalgebra::Vector4::new(next[0], next[1], next[2], next[3]) / norm;
803            }
804            if v.dot(current.as_vector()) < 0.0 {
805                v = -v;
806            }
807            rotations[image] = Some(UnitQuaternion::from_quaternion(
808                nalgebra::Quaternion::from_vector(v),
809            ));
810        }
811        if max_error_rad.is_finite() && max_error_rad > 0.0 {
812            for (edge_index, e) in edges.iter().enumerate() {
813                if weights[edge_index] <= 0.0 {
814                    continue;
815                }
816                if let (Some(qi), Some(qj)) = (rotations[e.image_i], rotations[e.image_j]) {
817                    let (r_sel, _) = e.select_pose(qi, qj);
818                    let predicted = r_sel * qi;
819                    let err = (predicted.inverse() * qj).angle();
820                    if err > max_error_rad {
821                        weights[edge_index] = 0.0;
822                    }
823                }
824            }
825        }
826    }
827    (rotations, weights)
828}
829
830pub fn average_positions(
831    edges: &[GlobalSfmEdge],
832    edge_weights: &[f64],
833    rotations: &[Option<UnitQuaternion<f64>>],
834    seed: usize,
835    cg_iterations: usize,
836) -> Vec<Option<Point3<f64>>> {
837    average_positions_with_priors(edges, edge_weights, rotations, seed, cg_iterations, None)
838}
839
840/// Like [`average_positions`], but when `pose_priors` is supplied the global
841/// scale row is taken from the highest-weight prior–prior edge at its true
842/// metric length (instead of a unit displacement on a seed edge). Hybrid
843/// mappers use this so free cameras inherit the incremental metric frame.
844pub fn average_positions_with_priors(
845    edges: &[GlobalSfmEdge],
846    edge_weights: &[f64],
847    rotations: &[Option<UnitQuaternion<f64>>],
848    seed: usize,
849    cg_iterations: usize,
850    pose_priors: Option<&[Option<Pose>]>,
851) -> Vec<Option<Point3<f64>>> {
852    // World-frame bearings from every kept edge.
853    struct Bearing {
854        i: usize,
855        j: usize,
856        /// World-frame unit bearing from camera i towards camera j.
857        direction: Vector3<f64>,
858        weight: f64,
859    }
860    let mut bearings: Vec<Bearing> = Vec::new();
861    for (edge_index, edge) in edges.iter().enumerate() {
862        let weight = edge_weights.get(edge_index).copied().unwrap_or(1.0);
863        if weight <= 0.0 {
864            continue;
865        }
866        let Some(q) = rotations.get(edge.image_i).copied().flatten() else {
867            continue;
868        };
869        let Some(qj) = rotations.get(edge.image_j).copied().flatten() else {
870            continue;
871        };
872        let (_, direction_ij) = edge.select_pose(q, qj);
873        let world = q.inverse().transform_vector(&direction_ij);
874        let norm = world.norm();
875        if !norm.is_finite() || norm < 1e-12 {
876            continue;
877        }
878        bearings.push(Bearing {
879            i: edge.image_i,
880            j: edge.image_j,
881            direction: world / norm,
882            weight,
883        });
884    }
885    bearings.retain(|b| {
886        rotations.get(b.i).copied().flatten().is_some()
887            && rotations.get(b.j).copied().flatten().is_some()
888    });
889    if bearings.is_empty() {
890        return vec![None; rotations.len()];
891    }
892
893    // ---- Translation-sign repair via MST placement --------------------------
894    // Chirality-ambiguous essentials can flip `direction_ij` 180° while still
895    // passing per-pair RANSAC. Build a maximum-weight spanning tree, place
896    // cameras by walking unit steps along tree bearings, then flip any
897    // (tree or off-tree) bearing that is anti-aligned with the preliminary
898    // displacement. Self-consistent flip basins stay flipped together — this
899    // only repairs *isolated* sign errors against a trusted skeleton.
900    {
901        let members: Vec<usize> = (0..rotations.len())
902            .filter(|&i| rotations[i].is_some())
903            .collect();
904        let local_of: HashMap<usize, usize> =
905            members.iter().enumerate().map(|(k, &i)| (i, k)).collect();
906        let mut parent: Vec<usize> = (0..members.len()).collect();
907        fn find_sign(parent: &mut [usize], x: usize) -> usize {
908            let mut x = x;
909            while parent[x] != x {
910                parent[x] = parent[parent[x]];
911                x = parent[x];
912            }
913            x
914        }
915        let mut tree_edge: Vec<usize> = Vec::new();
916        let mut order: Vec<usize> = (0..bearings.len()).collect();
917        order.sort_by(|&a, &b| {
918            bearings[b]
919                .weight
920                .total_cmp(&bearings[a].weight)
921                .then_with(|| a.cmp(&b))
922        });
923        for &k in &order {
924            let Some(&li) = local_of.get(&bearings[k].i) else {
925                continue;
926            };
927            let Some(&lj) = local_of.get(&bearings[k].j) else {
928                continue;
929            };
930            let (ri, rj) = (find_sign(&mut parent, li), find_sign(&mut parent, lj));
931            if ri != rj {
932                parent[ri] = rj;
933                tree_edge.push(k);
934            }
935        }
936        // BFS place from seed along tree edges.
937        let mut adj: HashMap<usize, Vec<(usize, usize)>> = HashMap::new();
938        for &k in &tree_edge {
939            let b = &bearings[k];
940            adj.entry(b.i).or_default().push((b.j, k));
941            adj.entry(b.j).or_default().push((b.i, k));
942        }
943        let mut prelim: HashMap<usize, Vector3<f64>> = HashMap::new();
944        if rotations.get(seed).copied().flatten().is_some() {
945            prelim.insert(seed, Vector3::zeros());
946            let mut stack = vec![seed];
947            while let Some(node) = stack.pop() {
948                let Some(nbrs) = adj.get(&node) else {
949                    continue;
950                };
951                let c_node = prelim[&node];
952                for &(other, k) in nbrs {
953                    if prelim.contains_key(&other) {
954                        continue;
955                    }
956                    let b = &bearings[k];
957                    // Walking i→j along +direction; j→i along −direction.
958                    let step = if b.i == node {
959                        b.direction
960                    } else {
961                        -b.direction
962                    };
963                    prelim.insert(other, c_node + step);
964                    stack.push(other);
965                }
966            }
967        }
968        let mut flipped = 0usize;
969        for b in bearings.iter_mut() {
970            let (Some(ci), Some(cj)) = (prelim.get(&b.i), prelim.get(&b.j)) else {
971                continue;
972            };
973            let disp = *cj - *ci;
974            if disp.norm() < 1e-12 {
975                continue;
976            }
977            if disp.dot(&b.direction) < 0.0 {
978                b.direction = -b.direction;
979                flipped += 1;
980            }
981        }
982        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() && flipped > 0 {
983            eprintln!(
984                "global-sfm debug: translation-sign repair flipped {flipped}/{} bearings",
985                bearings.len()
986            );
987        }
988    }
989
990    const PRIOR_WEIGHT: f64 = 1e-6;
991    let members: Vec<usize> = (0..rotations.len())
992        .filter(|&i| rotations[i].is_some())
993        .collect();
994
995    // One scale-setting displacement row. Default: unit length on the
996    // highest-weight seed-touching edge. With pose priors: the highest-weight
997    // prior–prior bearing at its true metric length (all prior–prior metric
998    // rows A/B'd worse on courtyard: ~353 cm vs single-row ~311 cm).
999    struct MetricEdge {
1000        i: usize,
1001        j: usize,
1002        direction: Vector3<f64>,
1003        weight: f64,
1004        length: f64,
1005    }
1006    let mut metric_edges: Vec<MetricEdge> = Vec::new();
1007    if let Some(priors) = pose_priors {
1008        let best = bearings.iter().filter_map(|b| {
1009            let pi = priors.get(b.i).and_then(|p| p.as_ref())?;
1010            let pj = priors.get(b.j).and_then(|p| p.as_ref())?;
1011            let len = (pj.camera_center_world() - pi.camera_center_world()).norm();
1012            if !(len.is_finite() && len > 1e-6) {
1013                return None;
1014            }
1015            Some((b, len))
1016        });
1017        if let Some((b, len)) = best.max_by(|(a, _), (b, _)| {
1018            a.weight
1019                .total_cmp(&b.weight)
1020                .then_with(|| a.i.cmp(&b.i))
1021                .then_with(|| a.j.cmp(&b.j))
1022        }) {
1023            metric_edges.push(MetricEdge {
1024                i: b.i,
1025                j: b.j,
1026                direction: b.direction,
1027                weight: b.weight.max(1.0),
1028                length: len,
1029            });
1030            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
1031                eprintln!(
1032                    "global-sfm debug: metric scale from 1 prior–prior edge \
1033                     (i={}, j={}, len={len:.4}, w={:.3})",
1034                    b.i, b.j, b.weight
1035                );
1036            }
1037        }
1038    }
1039    if metric_edges.is_empty() {
1040        if let Some((_, b)) = bearings
1041            .iter()
1042            .enumerate()
1043            .filter(|(_, b)| b.i == seed || b.j == seed)
1044            .max_by(|(ia, a), (ib, b)| {
1045                a.weight
1046                    .total_cmp(&b.weight)
1047                    .then_with(|| a.j.cmp(&b.j).reverse())
1048                    .then_with(|| ib.cmp(ia))
1049            })
1050        {
1051            metric_edges.push(MetricEdge {
1052                i: b.i,
1053                j: b.j,
1054                direction: b.direction,
1055                weight: b.weight.max(1.0),
1056                length: 1.0,
1057            });
1058        }
1059    }
1060
1061    // ---- Trust-hierarchy graduated Huber ------------------------------------
1062    // Bent shapes come from systematically wrong bearings pulling the least
1063    // squares; the errors are not outlier-like, so plain robust weighting
1064    // cannot separate them. What does distinguish them is TRUST: a maximum-
1065    // weight spanning tree (Kruskal) marks the edges most likely to be right.
1066    // We therefore run graduated Huber rounds where every edge's threshold is
1067    // scaled by its trust tier — tree edges tolerate twice the angular error
1068    // of off-tree edges at every round — so systematically wrong off-tree
1069    // edges are demoted FIRST while the trusted skeleton survives to anchor
1070    // the shape. On clean data nothing ever exceeds even the tight threshold,
1071    // making the whole schedule an identity.
1072    let mut parent: Vec<usize> = (0..members.len()).collect();
1073    fn find(parent: &mut [usize], x: usize) -> usize {
1074        let mut x = x;
1075        while parent[x] != x {
1076            parent[x] = parent[parent[x]];
1077            x = parent[x];
1078        }
1079        x
1080    }
1081    let local_of: HashMap<usize, usize> =
1082        members.iter().enumerate().map(|(k, &i)| (i, k)).collect();
1083    let mut tree_flags = vec![false; bearings.len()];
1084    {
1085        let mut order: Vec<usize> = (0..bearings.len()).collect();
1086        order.sort_by(|&a, &b| {
1087            bearings[b]
1088                .weight
1089                .total_cmp(&bearings[a].weight)
1090                .then_with(|| a.cmp(&b))
1091        });
1092        for &k in &order {
1093            let li = *local_of.get(&bearings[k].i).unwrap();
1094            let lj = *local_of.get(&bearings[k].j).unwrap();
1095            let (ri, rj) = (find(&mut parent, li), find(&mut parent, lj));
1096            if ri != rj {
1097                parent[ri] = rj;
1098                tree_flags[k] = true;
1099            }
1100        }
1101    }
1102
1103    const WEIGHT_FLOOR: f64 = 1e-6;
1104    let mut bearing_weights: Vec<f64> = bearings.iter().map(|b| b.weight.max(1.0)).collect();
1105
1106    let mut rhs: HashMap<usize, Vector3<f64>> = HashMap::new();
1107    for m in &metric_edges {
1108        *rhs.entry(m.i).or_default() += m.direction.scale(-m.weight * m.length);
1109        *rhs.entry(m.j).or_default() += m.direction.scale(m.weight * m.length);
1110    }
1111
1112    let hess_vec = |bs: &[Bearing],
1113                    ws: &[f64],
1114                    metrics: &[MetricEdge],
1115                    v: &HashMap<usize, Vector3<f64>>|
1116     -> HashMap<usize, Vector3<f64>> {
1117        let mut out: HashMap<usize, Vector3<f64>> = HashMap::new();
1118        for (k, b) in bs.iter().enumerate() {
1119            let w = ws[k];
1120            if w <= 0.0 {
1121                continue;
1122            }
1123            let ci = v.get(&b.i).copied().unwrap_or(Vector3::zeros());
1124            let cj = v.get(&b.j).copied().unwrap_or(Vector3::zeros());
1125            // J_i v = d × (vi − vj); Aᵀ_i y = −w·(d × y), Aᵀ_j y = +w·(d×y).
1126            let y = b.direction.cross(&(ci - cj));
1127            *out.entry(b.i).or_default() += b.direction.cross(&y).scale(-w);
1128            *out.entry(b.j).or_default() += b.direction.cross(&y).scale(w);
1129        }
1130        // Parallel (metric) blocks: (H v)_i = w d (d·(vi−vj)).
1131        for m in metrics {
1132            let ci = v.get(&m.i).copied().unwrap_or(Vector3::zeros());
1133            let cj = v.get(&m.j).copied().unwrap_or(Vector3::zeros());
1134            let proj = m.direction.scale(m.direction.dot(&(ci - cj)) * m.weight);
1135            *out.entry(m.i).or_default() += proj;
1136            *out.entry(m.j).or_default() -= proj;
1137        }
1138        for (&node, val) in v {
1139            *out.entry(node).or_default() += val.scale(PRIOR_WEIGHT);
1140        }
1141        out
1142    };
1143
1144    let solve_cg = |ws: &[f64], cg_iterations: usize| -> HashMap<usize, Vector3<f64>> {
1145        let zero_field: HashMap<usize, Vector3<f64>> =
1146            members.iter().map(|&i| (i, Vector3::zeros())).collect();
1147        let mut out = zero_field.clone();
1148        let h0 = hess_vec(
1149            bearings.as_slice(),
1150            ws,
1151            metric_edges.as_slice(),
1152            &zero_field,
1153        );
1154        let mut r: HashMap<usize, Vector3<f64>> = rhs
1155            .iter()
1156            .map(|(k, v)| (*k, *v - h0.get(k).copied().unwrap_or(Vector3::zeros())))
1157            .collect();
1158        let mut p = r.clone();
1159        let mut rs_old: f64 = r.values().map(|g| g.norm_squared()).sum();
1160        for _ in 0..cg_iterations.max(1) {
1161            if !rs_old.is_finite() || rs_old < 1e-24 {
1162                break;
1163            }
1164            let hp = hess_vec(bearings.as_slice(), ws, metric_edges.as_slice(), &p);
1165            let denom: f64 = p
1166                .iter()
1167                .map(|(k, v)| v.dot(&hp.get(k).copied().unwrap_or(Vector3::zeros())))
1168                .sum();
1169            if !(denom.is_finite() && denom > 1e-30) {
1170                break;
1171            }
1172            let alpha = rs_old / denom;
1173            for (k, v) in &p {
1174                *out.entry(*k).or_default() += *v * alpha;
1175            }
1176            for (k, v) in &hp {
1177                *r.entry(*k).or_default() -= *v * alpha;
1178            }
1179            let rs_new: f64 = r.values().map(|g| g.norm_squared()).sum();
1180            if !rs_new.is_finite() {
1181                break;
1182            }
1183            let beta = rs_new / rs_old;
1184            for (k, v) in r.iter() {
1185                let pk = p.get(k).copied().unwrap_or(Vector3::zeros());
1186                *p.entry(*k).or_default() = *v + pk.scale(beta);
1187            }
1188            rs_old = rs_new;
1189        }
1190        out
1191    };
1192
1193    let bearing_angle_error = |positions: &HashMap<usize, Vector3<f64>>, k: usize| -> f64 {
1194        let b = &bearings[k];
1195        let ci = positions.get(&b.i).copied().unwrap_or(Vector3::zeros());
1196        let cj = positions.get(&b.j).copied().unwrap_or(Vector3::zeros());
1197        let disp = cj - ci;
1198        let norm = disp.norm();
1199        if norm < 1e-9 {
1200            return f64::INFINITY;
1201        }
1202        (disp.dot(&b.direction) / norm).clamp(-1.0, 1.0).acos()
1203    };
1204
1205    let metric_bearing_keys: HashSet<(usize, usize)> = metric_edges
1206        .iter()
1207        .map(|m| (m.i.min(m.j), m.i.max(m.j)))
1208        .collect();
1209    let is_metric_bearing = |k: usize| -> bool {
1210        let b = &bearings[k];
1211        metric_bearing_keys.contains(&(b.i.min(b.j), b.i.max(b.j)))
1212    };
1213
1214    let mut positions = solve_cg(bearing_weights.as_slice(), cg_iterations);
1215
1216    // Graduated rounds: the per-edge effective threshold is the round's base
1217    // relaxed over ~0.05 rad → ~0.4 rad, doubled for tree-tier edges.
1218    const ROUNDS: usize = 8;
1219    let bases: Vec<f64> = (0..ROUNDS)
1220        .map(|round| 0.05 * (8.0f64).powf(round as f64 / (ROUNDS - 1) as f64))
1221        .collect();
1222    for (round, &base) in bases.iter().enumerate() {
1223        let mut changed = false;
1224        for k in 0..bearings.len() {
1225            if is_metric_bearing(k) {
1226                continue;
1227            }
1228            let threshold = if tree_flags[k] { base * 2.0 } else { base };
1229            let err = bearing_angle_error(&positions, k);
1230            let factor = if err.is_finite() && err > threshold {
1231                (threshold / err).max(WEIGHT_FLOOR / bearing_weights[k].max(1e-12))
1232            } else {
1233                1.0
1234            };
1235            let target = bearing_weights[k] * factor;
1236            if (target - bearing_weights[k]).abs() > 1e-9 {
1237                bearing_weights[k] = target;
1238                changed = true;
1239            }
1240        }
1241        positions = solve_cg(bearing_weights.as_slice(), cg_iterations);
1242        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
1243            let mut errs: Vec<f64> = (0..bearings.len())
1244                .filter(|&k| !is_metric_bearing(k))
1245                .map(|k| bearing_angle_error(&positions, k))
1246                .collect();
1247            errs.sort_by(|a, b| a.total_cmp(b));
1248            eprintln!(
1249                "global-sfm debug: position round {round} base={:.3} rad                  median residual {:.2} deg",
1250                base,
1251                errs.get(errs.len() / 2).copied().unwrap_or(f64::NAN).to_degrees()
1252            );
1253        }
1254        if !changed {
1255            break;
1256        }
1257    }
1258
1259    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
1260        let mut errs: Vec<f64> = (0..bearings.len())
1261            .filter(|&k| !is_metric_bearing(k))
1262            .map(|k| bearing_angle_error(&positions, k))
1263            .collect();
1264        errs.sort_by(|a, b| a.total_cmp(b));
1265        eprintln!(
1266            "global-sfm debug: positions final: {} nodes, {} bearings, median angular residual {:.2} deg",
1267            positions.len(),
1268            errs.len(),
1269            errs.get(errs.len() / 2).copied().unwrap_or(f64::NAN).to_degrees()
1270        );
1271    }
1272
1273    // Re-anchor: seed centre becomes exactly the origin.
1274    let anchor = positions.get(&seed).copied().unwrap_or(Vector3::zeros());
1275    let mut out: Vec<Option<Point3<f64>>> = vec![None; rotations.len()];
1276    for (image, center) in positions {
1277        out[image] = Some(Point3::from(center - anchor));
1278    }
1279    out
1280}
1281
1282/// Position averaging with one independent (signed) scale per bearing edge.
1283/// The legacy solver adds a unit-displacement row to every edge; that silently
1284/// forces every baseline to have the same length.  This variant eliminates the
1285/// per-edge scales analytically: each edge contributes the two-dimensional
1286/// constraint `(I - d dᵀ)(c_j - c_i) = 0`, while one highest-support edge gets a
1287/// single longitudinal unit row to fix the global gauge.  The resulting solve
1288/// has only camera-centre unknowns, so dense view graphs do not become
1289/// rank-deficient merely because every edge has its own nuisance scale.  A
1290/// deterministic Huber IRLS loop downweights inconsistent bearing lines.  It is
1291/// intentionally separate from [`average_positions_with_priors`] so callers
1292/// can A/B the correction. `None` means the bearing graph is not sufficiently
1293/// constrained for a full-rank solve; callers should retain their existing
1294/// fallback in that case.
1295pub fn average_positions_with_independent_edge_scales(
1296    edges: &[GlobalSfmEdge],
1297    edge_weights: &[f64],
1298    rotations: &[Option<UnitQuaternion<f64>>],
1299    seed: usize,
1300    iterations: usize,
1301) -> Option<Vec<Option<Point3<f64>>>> {
1302    #[derive(Clone)]
1303    struct Bearing {
1304        i: usize,
1305        j: usize,
1306        direction: Vector3<f64>,
1307        base_weight: f64,
1308    }
1309
1310    let _seed_rotation = rotations.get(seed).copied().flatten()?;
1311    let mut bearings = Vec::new();
1312    for (edge_index, edge) in edges.iter().enumerate() {
1313        if edge.image_i == edge.image_j {
1314            continue;
1315        }
1316        let (Some(q_i), Some(q_j)) = (
1317            rotations.get(edge.image_i).copied().flatten(),
1318            rotations.get(edge.image_j).copied().flatten(),
1319        ) else {
1320            continue;
1321        };
1322        let (_, selected_direction) = edge.select_pose(q_i, q_j);
1323        let direction = q_i.inverse().transform_vector(&selected_direction);
1324        let Some(direction) = direction.try_normalize(1e-12) else {
1325            continue;
1326        };
1327        let base_weight = edge_weights
1328            .get(edge_index)
1329            .copied()
1330            .unwrap_or(edge.weight)
1331            .max(0.0);
1332        if !(base_weight.is_finite() && base_weight > 0.0) {
1333            continue;
1334        }
1335        bearings.push(Bearing {
1336            i: edge.image_i,
1337            j: edge.image_j,
1338            direction,
1339            base_weight,
1340        });
1341    }
1342    if bearings.is_empty() {
1343        return None;
1344    }
1345
1346    let members: Vec<usize> = rotations
1347        .iter()
1348        .enumerate()
1349        .filter_map(|(image, rotation)| rotation.as_ref().map(|_| image))
1350        .collect();
1351    if members.len() < 2 || !members.contains(&seed) {
1352        return None;
1353    }
1354    // A two-view edge is enough to set the gauge, but a larger tree has
1355    // unconstrained bending modes (one independent bearing line per edge).
1356    // Keep the established sparse-tree fallback while allowing cyclic graphs
1357    // to use the SVD's deterministic minimum-norm solution when the scene
1358    // itself leaves a small geometric nullspace.
1359    if members.len() > 2 && bearings.len() < members.len() {
1360        return None;
1361    }
1362    let mut connected = vec![false; rotations.len()];
1363    let mut adjacency = vec![Vec::new(); rotations.len()];
1364    for bearing in &bearings {
1365        adjacency[bearing.i].push(bearing.j);
1366        adjacency[bearing.j].push(bearing.i);
1367    }
1368    let mut stack = vec![seed];
1369    connected[seed] = true;
1370    while let Some(image) = stack.pop() {
1371        for &neighbor in &adjacency[image] {
1372            if !connected[neighbor] {
1373                connected[neighbor] = true;
1374                stack.push(neighbor);
1375            }
1376        }
1377    }
1378    if members.iter().any(|&image| !connected[image]) {
1379        return None;
1380    }
1381    let mut center_offset = vec![None; rotations.len()];
1382    let mut center_count = 0usize;
1383    for &image in &members {
1384        if image != seed {
1385            center_offset[image] = Some(center_count);
1386            center_count += 1;
1387        }
1388    }
1389
1390    // One longitudinal row fixes the otherwise-free global scale.  The
1391    // perpendicular constraints deliberately allow a signed edge scale: an
1392    // essential decomposition's antipodal translation has the same bearing
1393    // line, and forcing positivity here would reintroduce a discrete,
1394    // order-dependent sign decision before the graph has a pose solution.
1395    let anchor = bearings
1396        .iter()
1397        .enumerate()
1398        .max_by(|(ia, a), (ib, b)| {
1399            a.base_weight
1400                .total_cmp(&b.base_weight)
1401                .then_with(|| b.i.cmp(&a.i))
1402                .then_with(|| b.j.cmp(&a.j))
1403                .then_with(|| ib.cmp(ia))
1404        })
1405        .map(|(index, _)| index)?;
1406    let variable_count = center_count * 3;
1407    if variable_count == 0 {
1408        return None;
1409    }
1410
1411    let solve = |weights: &[f64], bearings: &[Bearing]| {
1412        // Three rows per edge are harmless (the projection has rank two) and
1413        // keep the matrix construction simple and deterministic.  The final
1414        // row is the gauge/scale anchor.
1415        let mut a = DMatrix::<f64>::zeros(bearings.len() * 3 + 1, variable_count);
1416        let mut b = DVector::<f64>::zeros(bearings.len() * 3 + 1);
1417        for (edge_index, edge) in bearings.iter().enumerate() {
1418            let sqrt_weight = weights[edge_index].max(1e-12).sqrt();
1419            let projection =
1420                Matrix3::<f64>::identity() - edge.direction * edge.direction.transpose();
1421            for projected_axis in 0..3 {
1422                let row = edge_index * 3 + projected_axis;
1423                for coordinate_axis in 0..3 {
1424                    let coefficient = sqrt_weight * projection[(projected_axis, coordinate_axis)];
1425                    if let Some(offset) = center_offset[edge.i] {
1426                        a[(row, offset * 3 + coordinate_axis)] -= coefficient;
1427                    }
1428                    if let Some(offset) = center_offset[edge.j] {
1429                        a[(row, offset * 3 + coordinate_axis)] += coefficient;
1430                    }
1431                }
1432            }
1433        }
1434        let anchor_edge = &bearings[anchor];
1435        let anchor_row = bearings.len() * 3;
1436        for axis in 0..3 {
1437            if let Some(offset) = center_offset[anchor_edge.i] {
1438                a[(anchor_row, offset * 3 + axis)] -= anchor_edge.direction[axis];
1439            }
1440            if let Some(offset) = center_offset[anchor_edge.j] {
1441                a[(anchor_row, offset * 3 + axis)] += anchor_edge.direction[axis];
1442            }
1443        }
1444        b[anchor_row] = 1.0;
1445        let svd = a.svd(true, true);
1446        let largest = svd.singular_values.iter().copied().fold(0.0f64, f64::max);
1447        let tolerance = (largest * 1e-10).max(1e-12);
1448        let rank = svd
1449            .singular_values
1450            .iter()
1451            .filter(|&&value| value > tolerance)
1452            .count();
1453        if rank < variable_count && std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
1454            let mut tail = svd.singular_values.as_slice().to_vec();
1455            tail.sort_by(f64::total_cmp);
1456            tail.truncate(8);
1457            eprintln!(
1458                "global-sfm debug: independent edge-scale geometric nullspace rank={rank}/{variable_count} singular_tail={tail:?} tolerance={tolerance:.3e} (minimum-norm solve)"
1459            );
1460        }
1461        let solution = svd
1462            .solve(&b, tolerance)
1463            .ok()?
1464            .iter()
1465            .copied()
1466            .collect::<Vec<_>>();
1467        if solution.iter().all(|value| value.is_finite()) {
1468            Some((solution, rank))
1469        } else {
1470            None
1471        }
1472    };
1473
1474    let mut weights: Vec<f64> = bearings.iter().map(|edge| edge.base_weight).collect();
1475    let mut final_solution = None;
1476    let mut final_rank = 0usize;
1477    let mut final_residuals = Vec::new();
1478    let rounds = iterations.clamp(1, 8);
1479    for _round in 0..rounds {
1480        let (solution, rank) = solve(&weights, &bearings)?;
1481        let mut scale_magnitudes = Vec::with_capacity(bearings.len());
1482        let mut residuals = Vec::with_capacity(bearings.len());
1483        for edge in &bearings {
1484            let ci = center_offset[edge.i].map_or_else(Vector3::zeros, |offset| {
1485                Vector3::new(
1486                    solution[offset * 3],
1487                    solution[offset * 3 + 1],
1488                    solution[offset * 3 + 2],
1489                )
1490            });
1491            let cj = center_offset[edge.j].map_or_else(Vector3::zeros, |offset| {
1492                Vector3::new(
1493                    solution[offset * 3],
1494                    solution[offset * 3 + 1],
1495                    solution[offset * 3 + 2],
1496                )
1497            });
1498            let displacement = cj - ci;
1499            let scale = displacement.dot(&edge.direction);
1500            let perpendicular = displacement - edge.direction * scale;
1501            if scale.is_finite() && scale.abs() > 1e-9 {
1502                scale_magnitudes.push(scale.abs());
1503            }
1504            residuals.push(perpendicular.norm());
1505        }
1506        if scale_magnitudes.is_empty() || residuals.iter().any(|value| !value.is_finite()) {
1507            return None;
1508        }
1509        scale_magnitudes.sort_by(f64::total_cmp);
1510        let scale_reference = scale_magnitudes[scale_magnitudes.len() / 2].max(1e-9);
1511        for residual in &mut residuals {
1512            *residual /= scale_reference;
1513        }
1514        let mut sorted = residuals.clone();
1515        sorted.sort_by(f64::total_cmp);
1516        let median = sorted[sorted.len() / 2];
1517        let mut deviations: Vec<f64> = residuals
1518            .iter()
1519            .map(|value| (value - median).abs())
1520            .collect();
1521        deviations.sort_by(f64::total_cmp);
1522        let mad = deviations[deviations.len() / 2];
1523        // 1.345 is the standard 95%-efficiency Huber transition for Gaussian
1524        // residuals; 1.4826 converts MAD to a robust sigma estimate.
1525        let huber_delta = (1.345 * 1.4826 * mad).max(1e-3);
1526        let next_weights: Vec<f64> = residuals
1527            .iter()
1528            .enumerate()
1529            .map(|(index, residual)| {
1530                let factor = if *residual > huber_delta {
1531                    huber_delta / *residual
1532                } else {
1533                    1.0
1534                };
1535                bearings[index].base_weight * factor.max(1e-6)
1536            })
1537            .collect();
1538        let stable = weights
1539            .iter()
1540            .zip(next_weights.iter())
1541            .all(|(old, new)| (old - new).abs() <= old.max(1.0) * 1e-3);
1542        final_solution = Some(solution);
1543        final_rank = rank;
1544        final_residuals = residuals;
1545        if stable {
1546            break;
1547        }
1548        weights = next_weights;
1549    }
1550    let solution = final_solution?;
1551    let mut centers = vec![None; rotations.len()];
1552    centers[seed] = Some(Point3::origin());
1553    for &image in &members {
1554        let Some(offset) = center_offset[image] else {
1555            continue;
1556        };
1557        centers[image] = Some(Point3::new(
1558            solution[offset * 3],
1559            solution[offset * 3 + 1],
1560            solution[offset * 3 + 2],
1561        ));
1562    }
1563    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
1564        let median = {
1565            let mut values = final_residuals;
1566            values.sort_by(f64::total_cmp);
1567            values[values.len() / 2]
1568        };
1569        let downweighted = weights
1570            .iter()
1571            .zip(bearings.iter())
1572            .filter(|(weight, edge)| **weight < edge.base_weight * 0.999)
1573            .count();
1574        let anchor_edge = &bearings[anchor];
1575        eprintln!(
1576            "global-sfm debug: independent edge-scale positions edges={} nodes={} rank={}/{} anchor={}-{} median_norm_residual={:.6} downweighted={}",
1577            bearings.len(),
1578            members.len(),
1579            final_rank,
1580            variable_count,
1581            anchor_edge.i,
1582            anchor_edge.j,
1583            median,
1584            downweighted,
1585        );
1586    }
1587    Some(centers)
1588}
1589
1590/// GLOMAP-style joint camera+point positioning (simplified): with rotations
1591/// fixed, alternate least-squares updates of 3D points and camera centres so
1592/// each observation's world bearing aligns with `(X - c)`. Pairwise
1593/// translation averaging alone cannot resolve chirality-bent façades; track
1594/// rays supply the missing multi-view scale.
1595///
1596/// `init_centers` seeds the solve (typically from [`average_positions`]).
1597/// `pinned_priors`, when set, freezes those cameras' centres at their prior
1598/// centres for the whole IRLS (hybrid gauge).
1599fn refine_centers_joint_tracks(
1600    camera: &Camera,
1601    features: &[FeatureSet],
1602    tracks: &[Vec<(usize, usize)>],
1603    rotations: &[Option<UnitQuaternion<f64>>],
1604    init_centers: Vec<Option<Point3<f64>>>,
1605    seed: usize,
1606    pinned_priors: Option<&[Option<Pose>]>,
1607) -> Vec<Option<Point3<f64>>> {
1608    let n = rotations.len();
1609    let seed_init = init_centers.get(seed).copied().flatten();
1610    let mut centers = init_centers;
1611    if centers.len() < n {
1612        centers.resize(n, None);
1613    }
1614    // World-frame unit bearings per track observation.
1615    struct Obs {
1616        image: usize,
1617        bearing_w: Vector3<f64>,
1618    }
1619    let mut track_obs: Vec<Vec<Obs>> = Vec::new();
1620    for track in tracks {
1621        if track.len() < 2 {
1622            continue;
1623        }
1624        let mut obs = Vec::with_capacity(track.len());
1625        for &(image, kp) in track {
1626            let Some(q) = rotations.get(image).copied().flatten() else {
1627                continue;
1628            };
1629            let Some(feats) = features.get(image) else {
1630                continue;
1631            };
1632            let Some(px) = feats.keypoints.get(kp) else {
1633                continue;
1634            };
1635            let Some(nrm) = camera.normalize_pixel(px) else {
1636                continue;
1637            };
1638            let cam_ray = Vector3::new(nrm.x, nrm.y, 1.0);
1639            let Some(unit) = cam_ray.try_normalize(1e-12) else {
1640                continue;
1641            };
1642            // Bearing in world: R_w2c^{-1} * ray_cam
1643            let bearing_w = q.inverse().transform_vector(&unit);
1644            let Some(bearing_w) = bearing_w.try_normalize(1e-12) else {
1645                continue;
1646            };
1647            obs.push(Obs { image, bearing_w });
1648        }
1649        if obs.len() >= 2 {
1650            track_obs.push(obs);
1651        }
1652    }
1653    if track_obs.is_empty() {
1654        return centers;
1655    }
1656
1657    let pin_center = |image: usize| -> Option<Point3<f64>> {
1658        pinned_priors
1659            .and_then(|p| p.get(image))
1660            .and_then(|o| o.as_ref())
1661            .map(|pose| pose.camera_center_world())
1662    };
1663    for (i, center) in centers.iter_mut().enumerate().take(n) {
1664        if let Some(c) = pin_center(i) {
1665            *center = Some(c);
1666        }
1667    }
1668
1669    // Init points: midpoints of first two rays with known centres.
1670    let mut points: Vec<Option<Point3<f64>>> = vec![None; track_obs.len()];
1671    for (ti, obs) in track_obs.iter().enumerate() {
1672        let mut mid = Vector3::zeros();
1673        let mut count = 0usize;
1674        for o in obs {
1675            let Some(c) = centers.get(o.image).copied().flatten() else {
1676                continue;
1677            };
1678            // Unit depth along ray as a crude init; refined below.
1679            mid += c.coords + o.bearing_w;
1680            count += 1;
1681        }
1682        if count >= 2 {
1683            points[ti] = Some(Point3::from(mid / count as f64));
1684        }
1685    }
1686
1687    let huber = |r: f64, delta: f64| -> f64 {
1688        let a = r.abs();
1689        if a <= delta {
1690            1.0
1691        } else {
1692            delta / a
1693        }
1694    };
1695
1696    const ROUNDS: usize = 8;
1697    for round in 0..ROUNDS {
1698        let delta = 0.05 + 0.05 * round as f64; // ~3°→~25° in sin-approx units
1699                                                // ---- Point update: X minimizes Σ w || û × (X - c) ||^2 ----
1700        for (ti, obs) in track_obs.iter().enumerate() {
1701            let mut ata = Matrix3::zeros();
1702            let mut atb = Vector3::zeros();
1703            let mut used = 0usize;
1704            for o in obs {
1705                let Some(c) = centers.get(o.image).copied().flatten() else {
1706                    continue;
1707                };
1708                let u = o.bearing_w;
1709                // Skew(u) * X = Skew(u) * c  → two independent rows
1710                let skew = Matrix3::new(0.0, -u.z, u.y, u.z, 0.0, -u.x, -u.y, u.x, 0.0);
1711                let residual = if let Some(x) = points[ti] {
1712                    (u.cross(&(x.coords - c.coords))).norm()
1713                } else {
1714                    1.0
1715                };
1716                let w = huber(residual, delta).max(1e-3);
1717                ata += skew.transpose() * skew * w;
1718                atb += skew.transpose() * (skew * c.coords) * w;
1719                used += 1;
1720            }
1721            if used < 2 {
1722                continue;
1723            }
1724            if let Some(x) = ata.try_inverse().map(|inv| inv * atb) {
1725                if x.iter().all(|v| v.is_finite()) {
1726                    points[ti] = Some(Point3::from(x));
1727                }
1728            }
1729        }
1730
1731        // ---- Camera update: c minimizes Σ w || û × (X - c) ||^2 ----
1732        // û × (X - c) = û × X - û × c ⇒ Skew(û) c = Skew(û) X
1733        let mut cam_ata = vec![Matrix3::zeros(); n];
1734        let mut cam_atb = vec![Vector3::zeros(); n];
1735        let mut cam_wsum = vec![0.0f64; n];
1736        for (ti, obs) in track_obs.iter().enumerate() {
1737            let Some(x) = points[ti] else {
1738                continue;
1739            };
1740            for o in obs {
1741                if o.image >= n {
1742                    continue;
1743                }
1744                if pin_center(o.image).is_some() {
1745                    continue;
1746                }
1747                let u = o.bearing_w;
1748                let skew = Matrix3::new(0.0, -u.z, u.y, u.z, 0.0, -u.x, -u.y, u.x, 0.0);
1749                let residual = if let Some(c) = centers[o.image] {
1750                    (u.cross(&(x.coords - c.coords))).norm()
1751                } else {
1752                    1.0
1753                };
1754                let w = huber(residual, delta).max(1e-3);
1755                cam_ata[o.image] += skew.transpose() * skew * w;
1756                cam_atb[o.image] += skew.transpose() * (skew * x.coords) * w;
1757                cam_wsum[o.image] += w;
1758            }
1759        }
1760        for i in 0..n {
1761            if pin_center(i).is_some() {
1762                continue;
1763            }
1764            if rotations[i].is_none() || cam_wsum[i] < 1e-6 {
1765                continue;
1766            }
1767            if let Some(c) = cam_ata[i].try_inverse().map(|inv| inv * cam_atb[i]) {
1768                if c.iter().all(|v| v.is_finite()) {
1769                    centers[i] = Some(Point3::from(c));
1770                }
1771            }
1772        }
1773        // Keep seed gauge: translate so seed stays at its init (or prior).
1774        let Some(seed_now) = centers.get(seed).copied().flatten() else {
1775            continue;
1776        };
1777        let seed_target = pin_center(seed).or(seed_init).unwrap_or(Point3::origin());
1778        let delta_c = seed_target - seed_now;
1779        if delta_c.norm() > 1e-12 {
1780            for c in centers.iter_mut().flatten() {
1781                *c = Point3::from(c.coords + delta_c);
1782            }
1783            for p in points.iter_mut().flatten() {
1784                *p = Point3::from(p.coords + delta_c);
1785            }
1786        }
1787    }
1788    centers
1789}
1790
1791/// Rewrite relative pose on edges whose both endpoints have absolute pose
1792/// priors: `R_ij` and `direction_ij` come from the prior metric frame, and the
1793/// edge weight is boosted so free cameras hang off a prior-consistent skeleton.
1794/// Returns `(rewritten, flipped)` counts (`flipped` ⊆ `rewritten`).
1795fn repair_edges_from_pose_priors(
1796    edges: &mut [GlobalSfmEdge],
1797    edge_weights: &mut [f64],
1798    priors: &[Option<Pose>],
1799) -> (usize, usize) {
1800    let mut rewritten = 0usize;
1801    let mut flipped = 0usize;
1802    for (idx, edge) in edges.iter_mut().enumerate() {
1803        if edge_weights.get(idx).copied().unwrap_or(0.0) <= 0.0 {
1804            continue;
1805        }
1806        let Some(Some(pi)) = priors.get(edge.image_i) else {
1807            continue;
1808        };
1809        let Some(Some(pj)) = priors.get(edge.image_j) else {
1810            continue;
1811        };
1812        let ci = pi.camera_center_world();
1813        let cj = pj.camera_center_world();
1814        let ri = pi.world_to_camera.rotation;
1815        let rj = pj.world_to_camera.rotation;
1816        let delta = cj.coords - ci.coords;
1817        if delta.norm() < 1e-9 {
1818            continue;
1819        }
1820        let Some(dir) = ri.transform_vector(&delta).try_normalize(1e-12) else {
1821            continue;
1822        };
1823        if dir.dot(&edge.direction_ij) < 0.0 {
1824            flipped += 1;
1825        }
1826        edge.direction_ij = dir;
1827        edge.rotation_ij = rj * ri.inverse();
1828        // Drop alternates — the prior frame is authoritative for this edge.
1829        edge.rotation_alt = None;
1830        edge.direction_alt = None;
1831        if let Some(w) = edge_weights.get_mut(idx) {
1832            *w = (*w).max(edge.weight) * 2.0;
1833        }
1834        rewritten += 1;
1835    }
1836    (rewritten, flipped)
1837}
1838
1839/// Squared distance between two 3D rays (origins + unit directions).
1840fn ray_ray_distance_sq(
1841    origin_a: &Vector3<f64>,
1842    dir_a: &Vector3<f64>,
1843    origin_b: &Vector3<f64>,
1844    dir_b: &Vector3<f64>,
1845) -> f64 {
1846    let w0 = origin_a - origin_b;
1847    let a = dir_a.dot(dir_a);
1848    let b = dir_a.dot(dir_b);
1849    let c = dir_b.dot(dir_b);
1850    let d = dir_a.dot(&w0);
1851    let e = dir_b.dot(&w0);
1852    let denom = a * c - b * b;
1853    if denom.abs() < 1e-18 {
1854        return w0.cross(dir_a).norm_squared();
1855    }
1856    let sc = (b * e - c * d) / denom;
1857    let tc = (a * e - b * d) / denom;
1858    let p1 = origin_a + dir_a * sc;
1859    let p2 = origin_b + dir_b * tc;
1860    (p1 - p2).norm_squared()
1861}
1862
1863/// World-space ray from a pose prior toward a free camera: origin at the
1864/// prior centre, direction unit-normalized in world coordinates.
1865fn prior_world_ray_toward_free(
1866    prior: &Pose,
1867    bearing_in_prior_frame: &Vector3<f64>,
1868) -> Option<(Vector3<f64>, Vector3<f64>)> {
1869    let origin = prior.camera_center_world().coords;
1870    let dir = prior
1871        .world_to_camera
1872        .rotation
1873        .inverse()
1874        .transform_vector(bearing_in_prior_frame)
1875        .try_normalize(1e-12)?;
1876    Some((origin, dir))
1877}
1878
1879/// Build pixel correspondences for a stored pair (essential inliers when set).
1880fn sampson_distance(
1881    essential: &Matrix3<f64>,
1882    correspondence: &TwoViewCorrespondence,
1883    camera: &Camera,
1884) -> Option<f64> {
1885    let prev = camera.normalize_pixel(&correspondence.previous_xy)?;
1886    let curr = camera.normalize_pixel(&correspondence.current_xy)?;
1887    let prev_h = Vector3::new(prev.x, prev.y, 1.0);
1888    let curr_h = Vector3::new(curr.x, curr.y, 1.0);
1889    let e_prev = essential * prev_h;
1890    let et_curr = essential.transpose() * curr_h;
1891    let numerator = curr_h.dot(&e_prev).powi(2);
1892    let denominator = e_prev.x.powi(2) + e_prev.y.powi(2) + et_curr.x.powi(2) + et_curr.y.powi(2);
1893    if denominator < 1e-18 {
1894        return None;
1895    }
1896    Some((numerator / denominator).sqrt())
1897}
1898
1899/// Mean Sampson distance (normalized coords) over essential inliers.
1900pub fn pair_essential_mean_sampson_error(
1901    pair: &PairwiseMatches,
1902    features: &[FeatureSet],
1903    camera: &Camera,
1904) -> Option<f64> {
1905    let essential = pair.essential_matrix.as_ref()?;
1906    let corrs = pair_correspondences(pair, features, true);
1907    if corrs.is_empty() {
1908        return None;
1909    }
1910    let mut total = 0.0;
1911    let mut count = 0.0;
1912    for corr in &corrs {
1913        if let Some(d) = sampson_distance(essential, corr, camera) {
1914            total += d;
1915            count += 1.0;
1916        }
1917    }
1918    if count > 0.0 {
1919        Some(total / count)
1920    } else {
1921        None
1922    }
1923}
1924
1925pub fn pair_correspondences(
1926    pair: &PairwiseMatches,
1927    features: &[FeatureSet],
1928    prefer_essential: bool,
1929) -> Vec<TwoViewCorrespondence> {
1930    let matches = if prefer_essential {
1931        pair.essential_matches
1932            .as_ref()
1933            .filter(|e| !e.is_empty())
1934            .unwrap_or(&pair.matches)
1935    } else {
1936        &pair.matches
1937    };
1938    matches
1939        .iter()
1940        .filter_map(|&(ki, kj)| {
1941            Some(TwoViewCorrespondence::new(
1942                *features[pair.image_i].keypoints.get(ki)?,
1943                *features[pair.image_j].keypoints.get(kj)?,
1944            ))
1945        })
1946        .collect()
1947}
1948
1949pub fn relative_pose_from_essential(
1950    essential: &Matrix3<f64>,
1951    correspondences: &[TwoViewCorrespondence],
1952    camera: &Camera,
1953) -> Option<RelativePose> {
1954    if correspondences.len() < 8 {
1955        return None;
1956    }
1957    let inliers: Vec<usize> = (0..correspondences.len()).collect();
1958    let cheirality = CheiralityOptions::hardened_keep_ambiguous();
1959    let recovered = recover_relative_pose_with_options(
1960        essential,
1961        correspondences,
1962        camera,
1963        &inliers,
1964        &cheirality,
1965    )?;
1966    let scale = RelativePoseEstimator::default().default_translation_scale;
1967    let se3 = SE3::new(recovered.rotation, recovered.translation_unit * scale);
1968    Some(RelativePose {
1969        previous_to_current: se3,
1970        translation_unit: recovered.translation_unit,
1971        translation_scale: scale,
1972        inliers,
1973        mean_sampson_error: 0.0,
1974        alternate: recovered.alternate,
1975        chirality_margin: recovered.chirality_margin(),
1976    })
1977}
1978
1979/// Unit bearing from `prior_idx` toward `free_idx` under the primary/alternate
1980/// essential hypothesis (`pair` is ordered `image_i` / `image_j`).
1981fn bearing_prior_to_free(
1982    pair: &PairwiseMatches,
1983    prior_idx: usize,
1984    free_idx: usize,
1985    features: &[FeatureSet],
1986    camera: &Camera,
1987    use_alternate: bool,
1988) -> Option<Vector3<f64>> {
1989    let essential = pair.essential_matrix.as_ref()?;
1990    let corrs = pair_correspondences(pair, features, true);
1991    let rel = relative_pose_from_essential(essential, &corrs, camera)?;
1992    let prior_is_i = pair.image_i == prior_idx && pair.image_j == free_idx;
1993    let prior_is_j = pair.image_j == prior_idx && pair.image_i == free_idx;
1994    if !prior_is_i && !prior_is_j {
1995        return None;
1996    }
1997    let (r, t_unit) = if use_alternate {
1998        let (r_alt, t_alt) = rel.alternate.as_ref()?;
1999        (r_alt, t_alt)
2000    } else {
2001        (&rel.previous_to_current.rotation, &rel.translation_unit)
2002    };
2003    let t = t_unit * rel.translation_scale;
2004    let d_ij = (-r.inverse().transform_vector(&t)).try_normalize(1e-12)?;
2005    if prior_is_i {
2006        Some(d_ij)
2007    } else {
2008        (-r.transform_vector(&d_ij)).try_normalize(1e-12)
2009    }
2010}
2011
2012fn triangulate_two_rays(
2013    origin_a: &Vector3<f64>,
2014    dir_a: &Vector3<f64>,
2015    origin_b: &Vector3<f64>,
2016    dir_b: &Vector3<f64>,
2017) -> Option<Vector3<f64>> {
2018    let w0 = origin_a - origin_b;
2019    let a = dir_a.dot(dir_a);
2020    let b = dir_a.dot(dir_b);
2021    let c = dir_b.dot(dir_b);
2022    let d = dir_a.dot(&w0);
2023    let e = dir_b.dot(&w0);
2024    let denom = a * c - b * b;
2025    if denom.abs() < 1e-18 {
2026        return None;
2027    }
2028    let sc = (b * e - c * d) / denom;
2029    let tc = (a * e - b * d) / denom;
2030    Some((origin_a + dir_a * sc + origin_b + dir_b * tc) * 0.5)
2031}
2032
2033fn ray_point_angular_error(origin: &Vector3<f64>, dir: &Vector3<f64>, point: &Vector3<f64>) -> f64 {
2034    let toward = point - origin;
2035    let n = toward.norm();
2036    if n < 1e-9 {
2037        return std::f64::consts::PI;
2038    }
2039    dir.normalize().dot(&(toward / n)).clamp(-1.0, 1.0).acos()
2040}
2041
2042/// Gate for free↔prior rematch E-gains: optional chirality margin floor and
2043/// optional triangulation anchor from two other prior↔free essentials.
2044#[allow(clippy::too_many_arguments)]
2045pub fn rematch_essential_admission_ok(
2046    pair: &PairwiseMatches,
2047    prior_idx: usize,
2048    free_idx: usize,
2049    features: &[FeatureSet],
2050    camera: &Camera,
2051    pose_priors: &[Option<Pose>],
2052    existing: &[PairwiseMatches],
2053    min_chirality_margin: f64,
2054    require_prior_anchor: bool,
2055    min_anchor_e_inliers: usize,
2056) -> bool {
2057    let Some(essential) = pair.essential_matrix.as_ref() else {
2058        return !require_prior_anchor;
2059    };
2060    let corrs = pair_correspondences(pair, features, true);
2061    let Some(rel) = relative_pose_from_essential(essential, &corrs, camera) else {
2062        return false;
2063    };
2064    if min_chirality_margin > 0.0 && rel.chirality_margin < min_chirality_margin {
2065        return false;
2066    }
2067    if !require_prior_anchor {
2068        return true;
2069    }
2070    let prior_pose = match pose_priors.get(prior_idx).and_then(|p| p.as_ref()) {
2071        Some(p) => p,
2072        None => return true,
2073    };
2074    let mut anchors: Vec<(usize, usize)> = Vec::new();
2075    for other in existing {
2076        if other.essential_matrix.is_none() {
2077            continue;
2078        }
2079        let e_count = other.essential_matches.as_ref().map_or(0, |e| e.len());
2080        if e_count < min_anchor_e_inliers {
2081            continue;
2082        }
2083        let other_prior = if other.image_i == free_idx {
2084            let k = other.image_j;
2085            if pose_priors.get(k).and_then(|p| p.as_ref()).is_some() {
2086                k
2087            } else {
2088                continue;
2089            }
2090        } else if other.image_j == free_idx {
2091            let k = other.image_i;
2092            if pose_priors.get(k).and_then(|p| p.as_ref()).is_some() {
2093                k
2094            } else {
2095                continue;
2096            }
2097        } else {
2098            continue;
2099        };
2100        if other_prior == prior_idx {
2101            continue;
2102        }
2103        anchors.push((other_prior, e_count));
2104    }
2105    anchors.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
2106    anchors.dedup_by_key(|(k, _)| *k);
2107    if anchors.len() < 2 {
2108        return true;
2109    }
2110    let (k1, _) = anchors[0];
2111    let (k2, _) = anchors[1];
2112    let Some(pose_k1) = pose_priors.get(k1).and_then(|p| p.as_ref()) else {
2113        return true;
2114    };
2115    let Some(pose_k2) = pose_priors.get(k2).and_then(|p| p.as_ref()) else {
2116        return true;
2117    };
2118    let Some(pair_k1) = existing.iter().find(|p| {
2119        (p.image_i == k1 && p.image_j == free_idx) || (p.image_j == k1 && p.image_i == free_idx)
2120    }) else {
2121        return true;
2122    };
2123    let Some(pair_k2) = existing.iter().find(|p| {
2124        (p.image_i == k2 && p.image_j == free_idx) || (p.image_j == k2 && p.image_i == free_idx)
2125    }) else {
2126        return true;
2127    };
2128    let Some(b1) = bearing_prior_to_free(pair_k1, k1, free_idx, features, camera, false) else {
2129        return true;
2130    };
2131    let Some(b2) = bearing_prior_to_free(pair_k2, k2, free_idx, features, camera, false) else {
2132        return true;
2133    };
2134    let Some((o1, d1)) = prior_world_ray_toward_free(pose_k1, &b1) else {
2135        return true;
2136    };
2137    let Some((o2, d2)) = prior_world_ray_toward_free(pose_k2, &b2) else {
2138        return true;
2139    };
2140    let Some(anchor) = triangulate_two_rays(&o1, &d1, &o2, &d2) else {
2141        return true;
2142    };
2143    let Some(b_primary) = bearing_prior_to_free(pair, prior_idx, free_idx, features, camera, false)
2144    else {
2145        return false;
2146    };
2147    let Some((origin_p, dir_primary)) = prior_world_ray_toward_free(prior_pose, &b_primary) else {
2148        return false;
2149    };
2150    let primary_err = ray_point_angular_error(&origin_p, &dir_primary, &anchor);
2151    let alt_err = bearing_prior_to_free(pair, prior_idx, free_idx, features, camera, true)
2152        .and_then(|b_alt| {
2153            prior_world_ray_toward_free(prior_pose, &b_alt)
2154                .map(|(o, d)| ray_point_angular_error(&o, &d, &anchor))
2155        })
2156        .unwrap_or(std::f64::consts::PI);
2157    primary_err + 1e-3 < alt_err
2158}
2159
2160/// Bearing from camera `from` toward camera `to` in `from`'s frame, using the
2161/// edge's primary or alternate relative pose.
2162fn edge_bearing_in_frame(
2163    edge: &GlobalSfmEdge,
2164    from: usize,
2165    use_alternate: bool,
2166) -> Option<Vector3<f64>> {
2167    if edge.image_i == from {
2168        if use_alternate {
2169            edge.direction_alt.as_ref().copied()
2170        } else {
2171            Some(edge.direction_ij)
2172        }
2173    } else if edge.image_j == from {
2174        let r = if use_alternate {
2175            edge.rotation_alt.as_ref()?
2176        } else {
2177            &edge.rotation_ij
2178        };
2179        let dir = if use_alternate {
2180            edge.direction_alt.as_ref()?
2181        } else {
2182            &edge.direction_ij
2183        };
2184        (-r.transform_vector(dir)).try_normalize(1e-12)
2185    } else {
2186        None
2187    }
2188}
2189
2190/// Least-squares closest point to a set of 3D rays `(origin, direction)`.
2191fn triangulate_point_from_rays(rays: &[(Vector3<f64>, Vector3<f64>)]) -> Option<Vector3<f64>> {
2192    if rays.len() < 2 {
2193        return None;
2194    }
2195    let mut ata = Matrix3::<f64>::zeros();
2196    let mut atb = Vector3::<f64>::zeros();
2197    for (origin, direction) in rays {
2198        let d = direction.normalize();
2199        let proj = Matrix3::identity() - d * d.transpose();
2200        ata += proj;
2201        atb += proj * origin;
2202    }
2203    ata.try_inverse().map(|inv| inv * atb)
2204}
2205
2206/// Unit bearing in a prior camera's frame toward a world-space point.
2207fn expected_bearing_prior_to_world_point(
2208    prior: &Pose,
2209    world_point: &Vector3<f64>,
2210) -> Option<Vector3<f64>> {
2211    let centre = prior.camera_center_world().coords;
2212    let toward = world_point - centre;
2213    prior
2214        .world_to_camera
2215        .rotation
2216        .transform_vector(&toward)
2217        .try_normalize(1e-12)
2218}
2219
2220/// Triangulate free-camera centres from prior↔free essentials using incremental
2221/// pose priors as the metric frame (external anchor vs self-consistent rays).
2222#[allow(clippy::type_complexity)]
2223pub fn estimate_free_centres_from_prior_rays(
2224    pairwise: &[PairwiseMatches],
2225    features: &[FeatureSet],
2226    camera: &Camera,
2227    pose_priors: &[Option<Pose>],
2228    min_rays: usize,
2229    min_e_inliers: usize,
2230) -> HashMap<usize, Vector3<f64>> {
2231    let is_prior = |i: usize| pose_priors.get(i).and_then(|p| p.as_ref()).is_some();
2232    let mut rays_by_free: HashMap<usize, Vec<(Vector3<f64>, Vector3<f64>)>> = HashMap::new();
2233    for pair in pairwise {
2234        let pi = is_prior(pair.image_i);
2235        let pj = is_prior(pair.image_j);
2236        if pi == pj {
2237            continue;
2238        }
2239        let (prior_idx, free_idx) = if pi {
2240            (pair.image_i, pair.image_j)
2241        } else {
2242            (pair.image_j, pair.image_i)
2243        };
2244        let e_count = pair.essential_matches.as_ref().map_or(0, |e| e.len());
2245        if e_count < min_e_inliers {
2246            continue;
2247        }
2248        let Some(prior_pose) = pose_priors.get(prior_idx).and_then(|p| p.as_ref()) else {
2249            continue;
2250        };
2251        let Some(bearing) =
2252            bearing_prior_to_free(pair, prior_idx, free_idx, features, camera, false)
2253        else {
2254            continue;
2255        };
2256        let Some((origin, dir)) = prior_world_ray_toward_free(prior_pose, &bearing) else {
2257            continue;
2258        };
2259        rays_by_free
2260            .entry(free_idx)
2261            .or_default()
2262            .push((origin, dir));
2263    }
2264    let mut centres = HashMap::new();
2265    for (free, rays) in rays_by_free {
2266        if rays.len() < min_rays {
2267            continue;
2268        }
2269        if let Some(point) = triangulate_point_from_rays(&rays) {
2270            centres.insert(free, point);
2271        }
2272    }
2273    centres
2274}
2275
2276/// Approximate free-camera poses by scaling a prior↔free essential edge to the
2277/// metric baseline implied by multi-ray centre triangulation in the incremental
2278/// prior frame.
2279pub fn estimate_free_poses_from_prior_rays(
2280    pairwise: &[PairwiseMatches],
2281    features: &[FeatureSet],
2282    camera: &Camera,
2283    pose_priors: &[Option<Pose>],
2284    min_rays: usize,
2285    min_anchor_e_inliers: usize,
2286) -> HashMap<usize, Pose> {
2287    let centres = estimate_free_centres_from_prior_rays(
2288        pairwise,
2289        features,
2290        camera,
2291        pose_priors,
2292        min_rays,
2293        min_anchor_e_inliers,
2294    );
2295    let is_prior = |i: usize| pose_priors.get(i).and_then(|p| p.as_ref()).is_some();
2296    let mut poses = HashMap::new();
2297    for (free_idx, centre) in centres {
2298        let mut best: Option<(usize, usize)> = None;
2299        for pair in pairwise {
2300            let pi = is_prior(pair.image_i);
2301            let pj = is_prior(pair.image_j);
2302            if pi == pj {
2303                continue;
2304            }
2305            let (prior_idx, other) = if pi {
2306                (pair.image_i, pair.image_j)
2307            } else {
2308                (pair.image_j, pair.image_i)
2309            };
2310            if other != free_idx {
2311                continue;
2312            }
2313            let e_count = pair.essential_matches.as_ref().map_or(0, |e| e.len());
2314            if e_count < min_anchor_e_inliers {
2315                continue;
2316            }
2317            if best.is_none_or(|(_, c)| e_count > c) {
2318                best = Some((prior_idx, e_count));
2319            }
2320        }
2321        let Some((anchor_prior, _)) = best else {
2322            continue;
2323        };
2324        let Some(prior_pose) = pose_priors.get(anchor_prior).and_then(|p| p.as_ref()) else {
2325            continue;
2326        };
2327        let pair = pairwise.iter().find(|p| {
2328            (p.image_i == anchor_prior && p.image_j == free_idx)
2329                || (p.image_j == anchor_prior && p.image_i == free_idx)
2330        });
2331        let Some(pair) = pair else { continue };
2332        let Some(essential) = pair.essential_matrix.as_ref() else {
2333            continue;
2334        };
2335        let corrs = pair_correspondences(pair, features, true);
2336        let Some(rel) = relative_pose_from_essential(essential, &corrs, camera) else {
2337            continue;
2338        };
2339        let c_prior = prior_pose.camera_center_world().coords;
2340        let dist = (centre - c_prior).norm();
2341        if dist < 1e-3 {
2342            continue;
2343        }
2344        let prior_is_i = pair.image_i == anchor_prior;
2345        let rel_se3 = SE3::new(
2346            rel.previous_to_current.rotation,
2347            rel.translation_unit * dist,
2348        );
2349        let w2c = if prior_is_i {
2350            rel_se3.compose(&prior_pose.world_to_camera)
2351        } else {
2352            rel_se3.inverse().compose(&prior_pose.world_to_camera)
2353        };
2354        poses.insert(
2355            free_idx,
2356            Pose {
2357                world_to_camera: w2c,
2358            },
2359        );
2360    }
2361    poses
2362}
2363
2364/// Unit bearing from `from` camera toward `to` camera, in `from`'s frame (GT).
2365pub fn gt_bearing_in_prior_frame(from: &Pose, to: &Pose) -> Option<Vector3<f64>> {
2366    let delta = to.camera_center_world().coords - from.camera_center_world().coords;
2367    from.world_to_camera
2368        .rotation
2369        .transform_vector(&delta)
2370        .try_normalize(1e-12)
2371}
2372
2373/// Angular error in degrees between two unit bearings (antipodal-aware).
2374pub fn bearing_alignment_error_deg(a: &Vector3<f64>, b: &Vector3<f64>) -> f64 {
2375    let dot = a.normalize().dot(&b.normalize()).abs().clamp(-1.0, 1.0);
2376    dot.acos().to_degrees()
2377}
2378
2379/// Essential primary-bearing error vs GT for a prior↔free pair (degrees).
2380pub fn prior_free_essential_gt_bearing_error_deg(
2381    pair: &PairwiseMatches,
2382    prior_idx: usize,
2383    free_idx: usize,
2384    features: &[FeatureSet],
2385    camera: &Camera,
2386    gt_prior: &Pose,
2387    gt_free: &Pose,
2388) -> Option<f64> {
2389    let gt = gt_bearing_in_prior_frame(gt_prior, gt_free)?;
2390    let est = bearing_prior_to_free(pair, prior_idx, free_idx, features, camera, false)?;
2391    Some(bearing_alignment_error_deg(&est, &gt))
2392}
2393
2394/// Bearing from `image_i` toward `image_j` in `image_i`'s frame.
2395pub const fn edge_bearing_i_to_j(
2396    _r_ij: &UnitQuaternion<f64>,
2397    direction_ij: &Vector3<f64>,
2398) -> Vector3<f64> {
2399    *direction_ij
2400}
2401
2402/// Bearing from `image_j` toward `image_i` in `image_j`'s frame.
2403pub fn edge_bearing_j_to_i(
2404    r_ij: &UnitQuaternion<f64>,
2405    direction_ij: &Vector3<f64>,
2406) -> Option<Vector3<f64>> {
2407    (-r_ij.transform_vector(direction_ij)).try_normalize(1e-12)
2408}
2409
2410/// For prior↔free edges with chirality alternates, swap primary/alternate
2411/// when the alternate bearing agrees better with other prior rays to the same
2412/// free camera (multi-view centre-ray consensus).
2413fn apply_prior_guided_free_chirality(edges: &mut [GlobalSfmEdge], priors: &[Option<Pose>]) {
2414    let is_prior = |i: usize| -> bool { priors.get(i).and_then(|p| p.as_ref()).is_some() };
2415    let mut flipped = 0usize;
2416    let mut candidates = 0usize;
2417    let mut free_nodes: HashSet<usize> = HashSet::new();
2418    for edge in edges.iter() {
2419        if edge.weight <= 0.0 {
2420            continue;
2421        }
2422        let pi = is_prior(edge.image_i);
2423        let pj = is_prior(edge.image_j);
2424        if pi == pj {
2425            continue;
2426        }
2427        let free = if pi { edge.image_j } else { edge.image_i };
2428        if edge.direction_alt.is_none() {
2429            continue;
2430        }
2431        free_nodes.insert(free);
2432    }
2433    for free in free_nodes {
2434        let incident: Vec<usize> = edges
2435            .iter()
2436            .enumerate()
2437            .filter(|(_, e)| {
2438                e.weight > 0.0
2439                    && e.direction_alt.is_some()
2440                    && ((e.image_i == free && is_prior(e.image_j))
2441                        || (e.image_j == free && is_prior(e.image_i)))
2442            })
2443            .map(|(idx, _)| idx)
2444            .collect();
2445        if incident.len() < 2 {
2446            continue;
2447        }
2448        for &edge_idx in &incident {
2449            candidates += 1;
2450            let edge = &edges[edge_idx];
2451            let prior_idx = if is_prior(edge.image_i) {
2452                edge.image_i
2453            } else {
2454                edge.image_j
2455            };
2456            let Some(prior_pose) = priors.get(prior_idx).and_then(|p| p.as_ref()) else {
2457                continue;
2458            };
2459            let score_hypothesis = |use_alt_on_edge: bool| -> f64 {
2460                let Some((origin, dir)) = edge_bearing_in_frame(edge, prior_idx, use_alt_on_edge)
2461                    .and_then(|b| prior_world_ray_toward_free(prior_pose, &b))
2462                else {
2463                    return f64::INFINITY;
2464                };
2465                let mut sum = 0.0f64;
2466                let mut count = 0usize;
2467                for &other_idx in &incident {
2468                    if other_idx == edge_idx {
2469                        continue;
2470                    }
2471                    let other = &edges[other_idx];
2472                    let other_prior = if other.image_i == free {
2473                        other.image_j
2474                    } else {
2475                        other.image_i
2476                    };
2477                    let Some(other_pose) = priors.get(other_prior).and_then(|p| p.as_ref()) else {
2478                        continue;
2479                    };
2480                    let Some(bearing) = edge_bearing_in_frame(other, other_prior, false) else {
2481                        continue;
2482                    };
2483                    let Some((o2, d2)) = prior_world_ray_toward_free(other_pose, &bearing) else {
2484                        continue;
2485                    };
2486                    sum += ray_ray_distance_sq(&origin, &dir, &o2, &d2);
2487                    count += 1;
2488                }
2489                if count == 0 {
2490                    f64::INFINITY
2491                } else {
2492                    sum / count as f64
2493                }
2494            };
2495            let primary_score = score_hypothesis(false);
2496            let alt_score = score_hypothesis(true);
2497            if alt_score + 1e-6 < primary_score {
2498                let edge = &mut edges[edge_idx];
2499                if let Some(mut r_alt) = edge.rotation_alt.take() {
2500                    std::mem::swap(&mut edge.rotation_ij, &mut r_alt);
2501                    edge.rotation_alt = Some(r_alt);
2502                }
2503                if let Some(mut d_alt) = edge.direction_alt.take() {
2504                    std::mem::swap(&mut edge.direction_ij, &mut d_alt);
2505                    edge.direction_alt = Some(d_alt);
2506                }
2507                flipped += 1;
2508            }
2509        }
2510    }
2511    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
2512        eprintln!(
2513            "global-sfm debug: prior-guided free chirality: {candidates} candidate edge(s), flipped {flipped}"
2514        );
2515    }
2516}
2517
2518/// Rewrite edges incident to at least one free (non-prior) camera using a
2519/// merged pose field (priors where pinned, pass-1 solve elsewhere). Prior–
2520/// prior edges are left to [`repair_edges_from_pose_priors`]. Returns
2521/// `(rewritten, flipped)`.
2522fn repair_free_incident_edges_from_poses(
2523    edges: &mut [GlobalSfmEdge],
2524    pose_field: &[Option<Pose>],
2525    priors: &[Option<Pose>],
2526    only_flipped: bool,
2527    limit_indices: &HashSet<usize>,
2528) -> (usize, usize) {
2529    let is_prior = |i: usize| -> bool { priors.get(i).and_then(|p| p.as_ref()).is_some() };
2530    let mut rewritten = 0usize;
2531    let mut flipped = 0usize;
2532    for edge in edges.iter_mut() {
2533        if edge.weight <= 0.0 {
2534            continue;
2535        }
2536        let free_incident = !is_prior(edge.image_i) || !is_prior(edge.image_j);
2537        if !free_incident {
2538            continue;
2539        }
2540        if !limit_indices.is_empty()
2541            && !limit_indices.contains(&edge.image_i)
2542            && !limit_indices.contains(&edge.image_j)
2543        {
2544            continue;
2545        }
2546        let (Some(pi), Some(pj)) = (
2547            pose_field.get(edge.image_i).and_then(|p| p.as_ref()),
2548            pose_field.get(edge.image_j).and_then(|p| p.as_ref()),
2549        ) else {
2550            continue;
2551        };
2552        let ci = pi.camera_center_world();
2553        let cj = pj.camera_center_world();
2554        let ri = pi.world_to_camera.rotation;
2555        let rj = pj.world_to_camera.rotation;
2556        let delta = cj.coords - ci.coords;
2557        if delta.norm() < 1e-9 {
2558            continue;
2559        }
2560        let Some(dir) = ri.transform_vector(&delta).try_normalize(1e-12) else {
2561            continue;
2562        };
2563        let antipodal = dir.dot(&edge.direction_ij) < 0.0;
2564        if only_flipped && !antipodal {
2565            continue;
2566        }
2567        if antipodal {
2568            flipped += 1;
2569        }
2570        edge.direction_ij = dir;
2571        edge.rotation_ij = rj * ri.inverse();
2572        edge.rotation_alt = None;
2573        edge.direction_alt = None;
2574        edge.weight = edge.weight.max(1.0) * 1.5;
2575        rewritten += 1;
2576    }
2577    (rewritten, flipped)
2578}
2579
2580/// Drop free-incident edges antipodal to a pass-1 pose field. Returns
2581/// `(dropped, antipodal_count)`.
2582fn drop_antipodal_free_incident_edges(
2583    edges: &mut [GlobalSfmEdge],
2584    pose_field: &[Option<Pose>],
2585    priors: &[Option<Pose>],
2586    limit_indices: &HashSet<usize>,
2587) -> (usize, usize) {
2588    let is_prior = |i: usize| -> bool { priors.get(i).and_then(|p| p.as_ref()).is_some() };
2589    let mut dropped = 0usize;
2590    let mut antipodal = 0usize;
2591    for edge in edges.iter_mut() {
2592        if edge.weight <= 0.0 {
2593            continue;
2594        }
2595        let free_incident = !is_prior(edge.image_i) || !is_prior(edge.image_j);
2596        if !free_incident {
2597            continue;
2598        }
2599        if !limit_indices.is_empty()
2600            && !limit_indices.contains(&edge.image_i)
2601            && !limit_indices.contains(&edge.image_j)
2602        {
2603            continue;
2604        }
2605        let (Some(pi), Some(pj)) = (
2606            pose_field.get(edge.image_i).and_then(|p| p.as_ref()),
2607            pose_field.get(edge.image_j).and_then(|p| p.as_ref()),
2608        ) else {
2609            continue;
2610        };
2611        let ci = pi.camera_center_world();
2612        let cj = pj.camera_center_world();
2613        let ri = pi.world_to_camera.rotation;
2614        let delta = cj.coords - ci.coords;
2615        if delta.norm() < 1e-9 {
2616            continue;
2617        }
2618        let Some(dir) = ri.transform_vector(&delta).try_normalize(1e-12) else {
2619            continue;
2620        };
2621        if dir.dot(&edge.direction_ij) < 0.0 {
2622            antipodal += 1;
2623            edge.weight = -1.0;
2624            dropped += 1;
2625        }
2626    }
2627    (dropped, antipodal)
2628}
2629
2630/// Re-score each edge's translation direction under the globally-averaged
2631/// relative rotation. Candidates are ±the pairwise direction plus an optional
2632/// fixed-R epipolar nullspace estimate from the retained inlier sample.
2633/// Returns how many edges flipped relative to their incoming direction.
2634fn refine_edge_directions_under_rotations(
2635    edges: &mut [GlobalSfmEdge],
2636    rotations: &[Option<UnitQuaternion<f64>>],
2637    edge_weights: &[f64],
2638    camera: &Camera,
2639) -> usize {
2640    let mut flipped = 0usize;
2641    for (idx, edge) in edges.iter_mut().enumerate() {
2642        if edge_weights.get(idx).copied().unwrap_or(0.0) <= 0.0 {
2643            continue;
2644        }
2645        if edge.inlier_sample.len() < 8 {
2646            continue;
2647        }
2648        let (Some(qi), Some(qj)) = (
2649            rotations.get(edge.image_i).copied().flatten(),
2650            rotations.get(edge.image_j).copied().flatten(),
2651        ) else {
2652            continue;
2653        };
2654        // Consensus relative rotation: R_w2c_j = R_ij · R_w2c_i.
2655        let r_ij = qj * qi.inverse();
2656        let r_mat: Matrix3<f64> = r_ij.to_rotation_matrix().into_inner();
2657        let mut candidates = vec![edge.direction_ij, -edge.direction_ij];
2658        if let Some(est) = estimate_direction_fixed_rotation(camera, &r_mat, &edge.inlier_sample) {
2659            candidates.push(est);
2660            candidates.push(-est);
2661        }
2662        let mut best_dir = edge.direction_ij;
2663        let mut best_score: i64 = -1;
2664        for dir in &candidates {
2665            let Some(unit) = dir.try_normalize(1e-12) else {
2666                continue;
2667            };
2668            // Camera-j centre in cam-i is `unit`; essential translation t
2669            // satisfies C = −Rᵀ t ⇒ t = −R C.
2670            let t = -(r_mat * unit);
2671            let score = cheirality_count_samples(camera, &r_mat, &t, &edge.inlier_sample);
2672            if score > best_score {
2673                best_score = score;
2674                best_dir = unit;
2675            }
2676        }
2677        if best_score <= 0 {
2678            continue;
2679        }
2680        if best_dir.dot(&edge.direction_ij) < 0.0 {
2681            flipped += 1;
2682        }
2683        edge.direction_ij = best_dir;
2684        edge.rotation_ij = r_ij;
2685    }
2686    flipped
2687}
2688
2689/// Fixed-R epipolar estimate of the camera-j centre direction in cam-i.
2690/// Solves `t · (x₂ × R x₁) = 0` over the sample, then `C = −Rᵀ t`.
2691fn estimate_direction_fixed_rotation(
2692    camera: &Camera,
2693    r_mat: &Matrix3<f64>,
2694    samples: &[(Point2<f64>, Point2<f64>)],
2695) -> Option<Vector3<f64>> {
2696    let mut ata = Matrix3::zeros();
2697    let mut used = 0usize;
2698    for (p1, p2) in samples {
2699        let Some(n1) = camera.normalize_pixel(p1) else {
2700            continue;
2701        };
2702        let Some(n2) = camera.normalize_pixel(p2) else {
2703            continue;
2704        };
2705        let x1 = Vector3::new(n1.x, n1.y, 1.0);
2706        let x2 = Vector3::new(n2.x, n2.y, 1.0);
2707        let rx1 = r_mat * x1;
2708        let cross = x2.cross(&rx1);
2709        ata += cross * cross.transpose();
2710        used += 1;
2711    }
2712    if used < 8 {
2713        return None;
2714    }
2715    let svd = ata.symmetric_eigen();
2716    // Smallest eigenvector of AᵀA.
2717    let mut best_i = 0usize;
2718    let mut best_v = f64::INFINITY;
2719    for i in 0..3 {
2720        let v = svd.eigenvalues[i];
2721        if v < best_v {
2722            best_v = v;
2723            best_i = i;
2724        }
2725    }
2726    let t = svd.eigenvectors.column(best_i).into_owned();
2727    let t = t.try_normalize(1e-12)?;
2728    (-r_mat.transpose() * t).try_normalize(1e-12)
2729}
2730
2731fn cheirality_count_samples(
2732    camera: &Camera,
2733    r_mat: &Matrix3<f64>,
2734    t: &Vector3<f64>,
2735    samples: &[(Point2<f64>, Point2<f64>)],
2736) -> i64 {
2737    use nalgebra::{DMatrix, Matrix3x4};
2738    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);
2739    let mut p_curr = Matrix3x4::zeros();
2740    p_curr.fixed_view_mut::<3, 3>(0, 0).copy_from(r_mat);
2741    p_curr.fixed_view_mut::<3, 1>(0, 3).copy_from(t);
2742    let mut score = 0i64;
2743    for (p1, p2) in samples {
2744        let Some(prev) = camera.normalize_pixel(p1) else {
2745            continue;
2746        };
2747        let Some(curr) = camera.normalize_pixel(p2) else {
2748            continue;
2749        };
2750        let mut a = DMatrix::<f64>::zeros(4, 4);
2751        for column in 0..4 {
2752            a[(0, column)] = prev.x * p_prev[(2, column)] - p_prev[(0, column)];
2753            a[(1, column)] = prev.y * p_prev[(2, column)] - p_prev[(1, column)];
2754            a[(2, column)] = curr.x * p_curr[(2, column)] - p_curr[(0, column)];
2755            a[(3, column)] = curr.y * p_curr[(2, column)] - p_curr[(1, column)];
2756        }
2757        let svd = a.svd(true, true);
2758        let Some(v_t) = svd.v_t else {
2759            continue;
2760        };
2761        let solution = v_t.row(v_t.nrows() - 1);
2762        let w = solution[3];
2763        if w.abs() < 1e-12 {
2764            continue;
2765        }
2766        let world = Vector3::new(solution[0] / w, solution[1] / w, solution[2] / w);
2767        let camera_curr = r_mat * world + t;
2768        if world.z > 0.0 && camera_curr.z > 0.0 {
2769            score += 1;
2770        }
2771    }
2772    score
2773}
2774
2775/// Drop incremental priors whose centres disagree with a free (rotation-
2776/// pinned, centre-free) global position solve after leave-one-out Sim(3)
2777/// alignment onto the other priors. Bent hubs that are locally consistent
2778/// with wrong edges still stick out against the free gauge. Returns filtered
2779/// priors and how many were kept.
2780pub fn filter_pose_priors_by_free_centre_residual(
2781    priors: &[Option<Pose>],
2782    free_centers: &[Option<Point3<f64>>],
2783    max_drops: usize,
2784    min_ratio_to_median: f64,
2785) -> (Vec<Option<Pose>>, usize) {
2786    let mut pairs: Vec<(usize, Point3<f64>, Point3<f64>)> = Vec::new();
2787    let n = priors.len().min(free_centers.len());
2788    for i in 0..n {
2789        let (Some(prior), Some(free_c)) = (priors[i].as_ref(), free_centers[i]) else {
2790            continue;
2791        };
2792        pairs.push((i, free_c, prior.camera_center_world()));
2793    }
2794    if pairs.len() < 4 || max_drops == 0 {
2795        let kept = priors.iter().filter(|p| p.is_some()).count();
2796        return (priors.to_vec(), kept);
2797    }
2798    let mut residuals: Vec<(usize, f64)> = Vec::with_capacity(pairs.len());
2799    for leave in 0..pairs.len() {
2800        let src: Vec<Point3<f64>> = pairs
2801            .iter()
2802            .enumerate()
2803            .filter(|&(k, _)| k != leave)
2804            .map(|(_, p)| p.1)
2805            .collect();
2806        let dst: Vec<Point3<f64>> = pairs
2807            .iter()
2808            .enumerate()
2809            .filter(|&(k, _)| k != leave)
2810            .map(|(_, p)| p.2)
2811            .collect();
2812        let Some(fit) = umeyama_similarity_transform(&src, &dst, true) else {
2813            continue;
2814        };
2815        if !(fit.scale.is_finite() && fit.scale > 0.0) {
2816            continue;
2817        }
2818        let sim = Sim3::new(
2819            UnitQuaternion::from_rotation_matrix(&fit.rotation),
2820            fit.translation,
2821            fit.scale,
2822        );
2823        let (i, free_c, prior_c) = pairs[leave];
2824        let aligned = sim.transform_point(&free_c);
2825        residuals.push((i, (aligned - prior_c).norm()));
2826    }
2827    if residuals.is_empty() {
2828        let kept = priors.iter().filter(|p| p.is_some()).count();
2829        return (priors.to_vec(), kept);
2830    }
2831    residuals.sort_by(|a, b| a.1.total_cmp(&b.1));
2832    let median = residuals[residuals.len() / 2].1;
2833    let threshold = (median * min_ratio_to_median).max(1e-6);
2834    let mut candidates: Vec<(usize, f64)> = residuals
2835        .into_iter()
2836        .filter(|&(_, r)| r >= threshold)
2837        .collect();
2838    candidates.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
2839    let drop_set: HashSet<usize> = candidates
2840        .into_iter()
2841        .take(max_drops)
2842        .map(|(i, _)| i)
2843        .collect();
2844    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
2845        eprintln!(
2846            "global-sfm debug: free-centre LOO residual filter median={median:.4} \
2847             thresh={threshold:.4} drop={drop_set:?}"
2848        );
2849    }
2850    let mut kept = 0usize;
2851    let filtered: Vec<Option<Pose>> = priors
2852        .iter()
2853        .enumerate()
2854        .map(|(i, p)| {
2855            if drop_set.contains(&i) {
2856                None
2857            } else if p.is_some() {
2858                kept += 1;
2859                p.clone()
2860            } else {
2861                None
2862            }
2863        })
2864        .collect();
2865    (filtered, kept)
2866}
2867
2868/// Drop incremental priors whose centres systematically disagree with
2869/// two-view edge bearings on prior–prior pairs (GT-free). For each prior,
2870/// `flip_fraction` is the weight-weighted share of incident prior–prior
2871/// edges whose essential `direction_ij` is antipodal to the prior
2872/// displacement. Priors with `incident >= min_incident` and
2873/// `flip_fraction >= min_flip_fraction` are candidates; at most
2874/// `max_drops` worst (highest flip fraction) are cleared.
2875///
2876/// Returns filtered priors and how many were kept.
2877pub fn filter_pose_priors_by_edge_disagreement(
2878    priors: &[Option<Pose>],
2879    edges: &[GlobalSfmEdge],
2880    min_incident: usize,
2881    min_flip_fraction: f64,
2882    max_drops: usize,
2883) -> (Vec<Option<Pose>>, usize) {
2884    let mut flip_w = vec![0.0f64; priors.len()];
2885    let mut total_w = vec![0.0f64; priors.len()];
2886    let mut incident = vec![0usize; priors.len()];
2887    for edge in edges {
2888        if edge.weight <= 0.0 {
2889            continue;
2890        }
2891        let (Some(Some(pi)), Some(Some(pj))) = (priors.get(edge.image_i), priors.get(edge.image_j))
2892        else {
2893            continue;
2894        };
2895        let delta = pj.camera_center_world().coords - pi.camera_center_world().coords;
2896        if delta.norm() < 1e-9 {
2897            continue;
2898        }
2899        let Some(dir) = pi
2900            .world_to_camera
2901            .rotation
2902            .transform_vector(&delta)
2903            .try_normalize(1e-12)
2904        else {
2905            continue;
2906        };
2907        let w = edge.weight.max(1.0);
2908        let flipped = dir.dot(&edge.direction_ij) < 0.0;
2909        for &idx in &[edge.image_i, edge.image_j] {
2910            incident[idx] += 1;
2911            total_w[idx] += w;
2912            if flipped {
2913                flip_w[idx] += w;
2914            }
2915        }
2916    }
2917    let mut candidates: Vec<(usize, f64)> = (0..priors.len())
2918        .filter(|&i| priors[i].is_some())
2919        .filter(|&i| incident[i] >= min_incident && total_w[i] > 0.0)
2920        .map(|i| (i, flip_w[i] / total_w[i]))
2921        .filter(|&(_, frac)| frac >= min_flip_fraction)
2922        .collect();
2923    candidates.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
2924    let drop_set: HashSet<usize> = candidates
2925        .into_iter()
2926        .take(max_drops)
2927        .map(|(i, _)| i)
2928        .collect();
2929    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() && !drop_set.is_empty() {
2930        let mut detail: Vec<_> = drop_set
2931            .iter()
2932            .map(|&i| (i, flip_w[i] / total_w[i], incident[i]))
2933            .collect();
2934        detail.sort_by(|a, b| b.1.total_cmp(&a.1));
2935        eprintln!(
2936            "global-sfm debug: edge-disagreement dropped priors {detail:?} \
2937             (min_frac={min_flip_fraction}, max_drops={max_drops})"
2938        );
2939    }
2940    let mut kept = 0usize;
2941    let filtered: Vec<Option<Pose>> = priors
2942        .iter()
2943        .enumerate()
2944        .map(|(i, p)| {
2945            if drop_set.contains(&i) {
2946                None
2947            } else if p.is_some() {
2948                kept += 1;
2949                p.clone()
2950            } else {
2951                None
2952            }
2953        })
2954        .collect();
2955    (filtered, kept)
2956}
2957
2958/// Drop incremental priors whose local track support is too thin or whose
2959/// mean reprojection exceeds `max_mean_reprojection_px`. Returns filtered
2960/// priors and how many were kept.
2961pub fn filter_pose_priors_by_track_quality(
2962    camera: &Camera,
2963    priors: &[Option<Pose>],
2964    tracks: &[SfmTrack],
2965    min_observations: usize,
2966    max_mean_reprojection_px: f64,
2967) -> (Vec<Option<Pose>>, usize) {
2968    let mut sum = vec![0.0f64; priors.len()];
2969    let mut count = vec![0usize; priors.len()];
2970    for track in tracks {
2971        for &(image, _, pixel) in &track.observations {
2972            if image >= priors.len() {
2973                continue;
2974            }
2975            let Some(pose) = priors[image].as_ref() else {
2976                continue;
2977            };
2978            let Some(err) = reprojection_error_px(camera, pose, &track.position, &pixel) else {
2979                continue;
2980            };
2981            sum[image] += err;
2982            count[image] += 1;
2983        }
2984    }
2985    let mut kept = 0usize;
2986    let filtered = priors
2987        .iter()
2988        .enumerate()
2989        .map(|(i, prior)| {
2990            let Some(p) = prior else {
2991                return None;
2992            };
2993            if count[i] < min_observations {
2994                return None;
2995            }
2996            let mean = sum[i] / count[i] as f64;
2997            if mean > max_mean_reprojection_px {
2998                return None;
2999            }
3000            kept += 1;
3001            Some(p.clone())
3002        })
3003        .collect();
3004    (filtered, kept)
3005}
3006
3007/// Tunables for [`reconstruct_global_sfm`] beyond the shared incremental-
3008/// mapper config (which supplies triangulation gates and the BA recipe).
3009#[derive(Debug, Clone, PartialEq)]
3010pub struct GlobalReconstructionTuning {
3011    /// Image whose frame becomes the reconstruction gauge.
3012    pub seed: usize,
3013    /// Rotation-consensus sweeps (8-16 is ample on connected graphs).
3014    pub sweeps: usize,
3015    /// Position least-squares conjugate-gradient budget.
3016    pub cg_iterations: usize,
3017    /// Pairs below this verified-match count are skipped when estimating
3018    /// relative poses.
3019    pub min_pair_matches: usize,
3020    /// Minimum essential inliers per pair for its edge to enter the graph.
3021    pub min_edge_inliers: usize,
3022    /// IRLS trim threshold for rotation averaging (degrees). Edges whose
3023    /// implied relative rotation disagrees with the emerging global solution
3024    /// by more than this are zeroed; view-graph triangles whose median loop
3025    /// error exceeds twice this are dropped outright.
3026    pub max_edge_rotation_error_deg: f64,
3027    /// GLOMAP-style baseline gate: an edge whose median two-view
3028    /// triangulation angle over its inliers falls below this (degrees)
3029    /// carries no usable positional information — its translation direction
3030    /// is noise — and is dropped from the view graph entirely. Pure-rotation
3031    /// / tiny-baseline pairs are exactly the ones whose bearings bend the
3032    /// position solve on repetitive scenes. Set to 0 to disable.
3033    pub min_edge_parallax_deg: f64,
3034    /// When true, relative-pose recovery uses
3035    /// [`visloc_vision::two_view::CheiralityOptions::hardened`]: min
3036    /// triangulation angle, ambiguity rejection, and a majority
3037    /// positive-depth fraction. Chirality-ambiguous essentials on repetitive
3038    /// façades are dropped instead of entering the view graph as bent
3039    /// bearings. Default false = byte-identical legacy decomposition.
3040    pub chirality_harden_edges: bool,
3041    /// Number of rotation-averaging seeds to try inside the largest
3042    /// connected component (highest-degree nodes preferred). The solve with
3043    /// the most kept edges / lowest median residual wins. `1` = legacy
3044    /// single-seed behaviour.
3045    pub rotation_seed_trials: usize,
3046    /// After rotation averaging, re-score / re-estimate each edge's
3047    /// translation direction under the consensus relative rotation using
3048    /// retained inlier samples. Flips chirality-ambiguous pairwise
3049    /// translations that survive per-pair RANSAC. Default false.
3050    pub refine_translations_with_global_rotations: bool,
3051    /// Solve camera centres together with one unknown scale per retained
3052    /// bearing edge instead of imposing a unit displacement on every edge.
3053    /// This is a default-off correction for connected global initialization;
3054    /// rank-deficient bearing graphs fall back to the legacy position solve.
3055    pub independent_edge_scales: bool,
3056    /// Keep chirality-ambiguous essentials as multi-hypothesis edges
3057    /// (primary + runner-up R/t). Rotation averaging and position bearings
3058    /// pick the hypothesis that agrees with the emerging global solution.
3059    /// When combined with [`Self::chirality_harden_edges`], uses angle /
3060    /// depth gates without the ambiguity *rejection* ratio. Default false.
3061    pub multi_hypothesis_edges: bool,
3062    /// Scale each edge weight by `(0.1 + chirality_margin)` so near-ambiguous
3063    /// façade essentials contribute less to rotation IRLS and positioning.
3064    /// Default false = weight = raw inlier count.
3065    pub weight_edges_by_chirality_margin: bool,
3066    /// Hybrid mapper: pin incremental orientations during rotation averaging
3067    /// but keep globally averaged centres for prior cameras instead of
3068    /// overwriting with incremental centres. Default false = full pose priors.
3069    pub hybrid_rotation_priors_only: bool,
3070    /// GLOMAP-style joint camera+point positioning after rotation averaging
3071    /// (ray cross-product IRLS on feature tracks) instead of pairwise
3072    /// translation averaging alone. Default false.
3073    pub joint_global_positioning: bool,
3074    /// When true, keep only view-graph edges whose stored
3075    /// [`PairwiseMatches::two_view_config`] is `Calibrated` (or `Multiple`),
3076    /// **or** Uncalibrated/other configs that still carry a strong
3077    /// [`PairwiseMatches::essential_matches`] subset (≥ `min_pair_matches`).
3078    /// Drops F-only / planar / panoramic admissions whose essential
3079    /// translation is often ill-conditioned. Requires the full verifier to
3080    /// have populated `two_view_config`. Default false.
3081    pub calibrated_view_edges_only: bool,
3082    /// When true, build relative-pose edges from
3083    /// [`PairwiseMatches::essential_matches`] when present (E RANSAC inliers)
3084    /// instead of the verifier's winning F/H inlier set. Tracks and
3085    /// incremental growth still use [`PairwiseMatches::matches`]. Default false.
3086    pub prefer_essential_edge_matches: bool,
3087    /// Like [`Self::prefer_essential_edge_matches`], but only for pairs where
3088    /// *at least one* endpoint lacks a pose prior (free camera). Prior–prior
3089    /// edges keep the winning F/H set (and may still be repaired). Default false.
3090    pub prefer_essential_edge_matches_free_endpoints: bool,
3091    /// Prefer E inliers only on edges incident to these image indices (hub
3092    /// surgery). Empty = unused. Checked after the global prefer flag and
3093    /// before the free-endpoint flag.
3094    pub prefer_essential_edge_image_indices: Vec<usize>,
3095    /// When true with a non-empty stem index list, require *both* endpoints in
3096    /// the set (clique edges only) instead of any incident edge.
3097    pub prefer_essential_edge_stem_clique: bool,
3098    /// Prefer E inliers only on these explicit `(image_i, image_j)` pairs
3099    /// (order-insensitive). Empty = unused. Checked before the stem list.
3100    pub prefer_essential_edge_pairs: Vec<(usize, usize)>,
3101    /// When a stem-list (or explicit pair list) selects a pair for E preference
3102    /// but `essential_matches` is missing/too short, drop the edge entirely
3103    /// instead of falling back to F/H. Default false.
3104    pub require_essential_for_selected_edges: bool,
3105    /// Drop edges incident to these images unless strong E inliers exist
3106    /// (no F/H fallback). Independent of the prefer-stem list so a bent free
3107    /// camera can be isolated without requiring E on the load-bearing hub.
3108    /// Empty = unused.
3109    pub require_essential_edge_image_indices: Vec<usize>,
3110    /// Minimum E inlier count for [`Self::require_essential_edge_image_indices`]
3111    /// (and selected-edge require). `0` = [`Self::min_pair_matches`]. Does not
3112    /// affect which E subsets are *stored* on pairs.
3113    pub require_essential_min_e_inliers: usize,
3114    /// Multiply view-graph edge weight when the edge was built from essential
3115    /// inliers (`prefer_essential_*`). `1.0` = no boost. Default 1.0.
3116    pub essential_edge_weight_boost: f64,
3117    /// Hybrid: overwrite relative rotation + translation direction on edges
3118    /// whose *both* endpoints have pose priors, using the prior metric frame.
3119    /// Boosts those edge weights so free cameras hang off a prior-consistent
3120    /// skeleton. Default false.
3121    pub repair_edges_from_pose_priors: bool,
3122    /// Hybrid: set the position-averaging scale row from a prior–prior edge's
3123    /// true metric length (instead of a unit seed edge). Default false.
3124    pub metric_scale_from_pose_priors: bool,
3125    /// Hybrid: drop priors that disagree with a free-centre (rotation-pinned)
3126    /// probe solve after Sim(3) onto the prior set. Default false.
3127    pub drop_inconsistent_pose_priors: bool,
3128    /// Unused for free-centre residual (kept for CLI/API stability).
3129    pub inconsistent_prior_min_incident: usize,
3130    /// Free-centre residual must be at least this × the median residual.
3131    pub inconsistent_prior_min_flip_fraction: f64,
3132    /// Cap on how many inconsistent priors to drop (worst first).
3133    pub inconsistent_prior_max_drops: usize,
3134    /// After hybrid BA, re-estimate free (non-prior) camera poses by PnP
3135    /// against tracks that are also observed by at least one prior-pinned
3136    /// camera — so free hubs hang off prior-anchored structure, not their
3137    /// own bent bearings. Default false.
3138    pub repnp_free_cameras_from_priors: bool,
3139    /// Minimum prior-anchored 2D–3D correspondences for
3140    /// [`Self::repnp_free_cameras_from_priors`]. `0` = mapper `min_pnp_inliers`.
3141    pub repnp_free_min_corrs: usize,
3142    /// Before the hybrid global solve, triangulate prior-only structure and
3143    /// PnP each free camera into it; successful poses are promoted to hard
3144    /// pose priors so averaging cannot bend them. Default false.
3145    pub repnp_seed_free_as_priors: bool,
3146    /// Image indices that must not be promoted by
3147    /// [`Self::repnp_seed_free_as_priors`] (e.g. explicitly dropped hubs).
3148    pub repnp_seed_exclude_image_indices: Vec<usize>,
3149    /// After the first global solve, rewrite edges incident to free cameras
3150    /// from pass-1 poses (priors stay authoritative) and re-run averaging.
3151    /// Targets chirality-flipped bearings on prior↔free bridges. Default false.
3152    pub repair_free_edges_from_solved_poses: bool,
3153    /// When repairing free-incident edges, only touch edges whose current
3154    /// bearing is antipodal (dot < 0) to the pass-1 pose field. Default false
3155    /// (= rewrite all free-incident edges when repair is enabled).
3156    pub repair_free_edges_only_flipped: bool,
3157    /// Limit free-incident repair to edges incident to these image indices.
3158    /// Empty = all free-incident edges.
3159    pub repair_free_edges_image_indices: Vec<usize>,
3160    /// After pass-1 global, drop (not rewrite) free-incident edges whose
3161    /// bearing is antipodal to the pass-1 pose field, then re-solve. Default
3162    /// false.
3163    pub drop_free_edges_antipodal_to_solved: bool,
3164    /// Before rotation averaging, flip prior↔free edges to the chirality
3165    /// alternate when multi-view prior rays to the same free camera agree
3166    /// better. Requires `--multi-hypothesis-edges`. Default false.
3167    pub prior_guided_free_chirality: bool,
3168    /// When building edges, triangulate each free camera from prior↔free
3169    /// essentials in the incremental metric frame and flip chirality on
3170    /// prior↔free pairs whose alternate bearing aligns better with that
3171    /// anchor. Requires `--multi-hypothesis-edges`. Default false.
3172    pub metric_prior_chirality_edges: bool,
3173    /// Min prior↔free rays to triangulate a free centre for
3174    /// [`Self::metric_prior_chirality_edges`].
3175    pub metric_prior_chirality_min_rays: usize,
3176    /// Pick primary vs alternate edge chirality by GT pose agreement (oracle
3177    /// ceiling experiment; requires per-image GT poses). Default false.
3178    pub gt_chirality_oracle: bool,
3179}
3180
3181impl Default for GlobalReconstructionTuning {
3182    fn default() -> Self {
3183        Self {
3184            seed: 0,
3185            sweeps: 12,
3186            cg_iterations: 500,
3187            min_pair_matches: 10,
3188            min_edge_inliers: 15,
3189            max_edge_rotation_error_deg: 10.0,
3190            min_edge_parallax_deg: 2.0,
3191            chirality_harden_edges: false,
3192            rotation_seed_trials: 1,
3193            refine_translations_with_global_rotations: false,
3194            independent_edge_scales: false,
3195            multi_hypothesis_edges: false,
3196            weight_edges_by_chirality_margin: false,
3197            hybrid_rotation_priors_only: false,
3198            joint_global_positioning: false,
3199            calibrated_view_edges_only: false,
3200            prefer_essential_edge_matches: false,
3201            prefer_essential_edge_matches_free_endpoints: false,
3202            prefer_essential_edge_image_indices: Vec::new(),
3203            prefer_essential_edge_stem_clique: false,
3204            prefer_essential_edge_pairs: Vec::new(),
3205            require_essential_for_selected_edges: false,
3206            require_essential_edge_image_indices: Vec::new(),
3207            require_essential_min_e_inliers: 0,
3208            essential_edge_weight_boost: 1.0,
3209            repair_edges_from_pose_priors: false,
3210            metric_scale_from_pose_priors: false,
3211            drop_inconsistent_pose_priors: false,
3212            inconsistent_prior_min_incident: 3,
3213            inconsistent_prior_min_flip_fraction: 2.0,
3214            inconsistent_prior_max_drops: 1,
3215            repnp_free_cameras_from_priors: false,
3216            repnp_free_min_corrs: 0,
3217            repnp_seed_free_as_priors: false,
3218            repnp_seed_exclude_image_indices: Vec::new(),
3219            repair_free_edges_from_solved_poses: false,
3220            repair_free_edges_only_flipped: false,
3221            repair_free_edges_image_indices: Vec::new(),
3222            drop_free_edges_antipodal_to_solved: false,
3223            prior_guided_free_chirality: false,
3224            metric_prior_chirality_edges: false,
3225            metric_prior_chirality_min_rays: 3,
3226            gt_chirality_oracle: false,
3227        }
3228    }
3229}
3230
3231/// Errors surfaced by [`reconstruct_global_sfm`].
3232#[derive(Debug, Clone, PartialEq)]
3233pub enum GlobalReconstructionError {
3234    /// The view-graph stage could not solve any component from the given
3235    /// edges (no usable pairs, or every pair failed estimation).
3236    NoUsableEdges,
3237    /// The final bundle adjustment failed; the pre-BA geometry is lost so
3238    /// only the error surfaces.
3239    Ba(String),
3240}
3241
3242impl std::fmt::Display for GlobalReconstructionError {
3243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3244        match self {
3245            GlobalReconstructionError::NoUsableEdges => {
3246                write!(f, "global SfM found no usable pairwise edges")
3247            }
3248            GlobalReconstructionError::Ba(error) => {
3249                write!(f, "global SfM bundle adjustment failed: {error}")
3250            }
3251        }
3252    }
3253}
3254impl std::error::Error for GlobalReconstructionError {}
3255
3256/// Re-estimate poses of free (non-prior) cameras via PnP on tracks that are
3257/// also seen by at least one prior-pinned camera. Returns how many poses were
3258/// replaced.
3259#[allow(clippy::too_many_arguments)]
3260fn repnp_free_cameras_from_prior_structure(
3261    camera: &Camera,
3262    features: &[FeatureSet],
3263    tracks: &[Vec<(usize, usize)>],
3264    track_point: &[Option<Point3<f64>>],
3265    poses: &mut [Option<Pose>],
3266    pose_priors: &[Option<Pose>],
3267    mapper: &crate::incremental_sfm::IncrementalSfmConfig,
3268    min_corrs: usize,
3269) -> usize {
3270    let prior_count = pose_priors.iter().filter(|p| p.is_some()).count();
3271    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3272        eprintln!(
3273            "global-sfm debug: re-PnP scan ({} priors, {} registered free candidates)",
3274            prior_count,
3275            poses
3276                .iter()
3277                .enumerate()
3278                .filter(
3279                    |(i, p)| p.is_some() && pose_priors.get(*i).and_then(|q| q.as_ref()).is_none()
3280                )
3281                .count()
3282        );
3283    }
3284    let mut replaced = 0usize;
3285    for image in 0..features.len() {
3286        if poses[image].is_none() {
3287            continue;
3288        }
3289        if pose_priors.get(image).and_then(|p| p.as_ref()).is_some() {
3290            continue; // keep pinned prior cameras
3291        }
3292        let mut corrs: Vec<Correspondence2D3D> = Vec::new();
3293        for (track_id, track) in tracks.iter().enumerate() {
3294            let Some(position) = track_point[track_id] else {
3295                continue;
3296            };
3297            let Some((_, kp)) = track.iter().find(|&&(img, _)| img == image) else {
3298                continue;
3299            };
3300            let anchored = track
3301                .iter()
3302                .any(|&(img, _)| pose_priors.get(img).and_then(|p| p.as_ref()).is_some());
3303            if !anchored {
3304                continue;
3305            }
3306            let Some(pixel) = features[image].keypoints.get(*kp).copied() else {
3307                continue;
3308            };
3309            corrs.push(Correspondence2D3D {
3310                point2d: pixel,
3311                point3d: position,
3312                confidence: None,
3313            });
3314        }
3315        if corrs.len() < min_corrs {
3316            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3317                eprintln!(
3318                    "global-sfm debug: re-PnP skip image {image}: only {} prior-anchored corrs (need {min_corrs})",
3319                    corrs.len(),
3320                );
3321            }
3322            continue;
3323        }
3324        let report = match mapper.pnp_solver {
3325            PnpSolver::P3p => PnPRansac {
3326                pose_estimator: P3PGrunert,
3327                pose_refiner: Some(GaussNewtonPoseRefiner::default()),
3328                iterations: mapper.pnp_max_iterations.max(128),
3329                confidence: Some(0.999),
3330                reprojection_threshold: mapper.max_reprojection_error_px,
3331                seed: 7,
3332                early_stop_min_iterations: 0,
3333                early_stop_inlier_ratio: None,
3334                inlier_refits: 0,
3335            }
3336            .estimate(&corrs, camera),
3337            PnpSolver::Dlt => PnPRansac {
3338                reprojection_threshold: mapper.max_reprojection_error_px,
3339                confidence: Some(0.999),
3340                ..PnPRansac::default()
3341            }
3342            .estimate(&corrs, camera),
3343        };
3344        let Some(report) =
3345            report.filter(|r| r.inliers.len() >= min_corrs.min(mapper.min_pnp_inliers).max(4))
3346        else {
3347            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3348                eprintln!(
3349                    "global-sfm debug: re-PnP fail image {image}: {} corrs, PnP rejected",
3350                    corrs.len()
3351                );
3352            }
3353            continue;
3354        };
3355        // Free cameras often sit in a self-consistent wrong basin with low
3356        // local reproj on prior-anchored tracks; still replace when PnP finds
3357        // a well-supported pose.
3358        let old_pose = poses[image].as_ref().unwrap();
3359        let mean = |pose: &Pose| -> f64 {
3360            let mut s = 0.0;
3361            let mut n = 0usize;
3362            for c in &corrs {
3363                if let Some(e) = reprojection_error_px(camera, pose, &c.point3d, &c.point2d) {
3364                    s += e;
3365                    n += 1;
3366                }
3367            }
3368            if n == 0 {
3369                f64::INFINITY
3370            } else {
3371                s / n as f64
3372            }
3373        };
3374        let old_mean = mean(old_pose);
3375        let new_mean = mean(&report.pose);
3376        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3377            eprintln!(
3378                "global-sfm debug: re-PnP free image {image}: {} corrs -> {} inliers, \
3379                 mean reproj {old_mean:.3} -> {new_mean:.3} px (accept)",
3380                corrs.len(),
3381                report.inliers.len()
3382            );
3383        }
3384        poses[image] = Some(report.pose);
3385        replaced += 1;
3386    }
3387    replaced
3388}
3389
3390/// Triangulate tracks using only already-pinned prior poses, then PnP each
3391/// free camera into that structure and write successful poses into
3392/// `pose_priors` (promoting them to hard pins for the subsequent global
3393/// solve). Returns how many free cameras were seeded.
3394fn pnp_seed_free_cameras_into_priors(
3395    camera: &Camera,
3396    features: &[FeatureSet],
3397    pairwise: &[PairwiseMatches],
3398    pose_priors: &mut [Option<Pose>],
3399    mapper: &crate::incremental_sfm::IncrementalSfmConfig,
3400    min_corrs: usize,
3401    exclude: &HashSet<usize>,
3402) -> usize {
3403    let prior_count = pose_priors.iter().filter(|p| p.is_some()).count();
3404    if prior_count < 2 {
3405        return 0;
3406    }
3407    let built = build_track_output(features, pairwise, mapper, Some(camera));
3408    let poses_for_tri: Vec<Option<Pose>> = pose_priors.to_vec();
3409    let mut track_point = vec![None; built.tracks.len()];
3410    triangulate_pending(
3411        camera,
3412        features,
3413        &built.tracks,
3414        &poses_for_tri,
3415        mapper,
3416        &mut track_point,
3417    );
3418    let tri_count = track_point.iter().filter(|p| p.is_some()).count();
3419    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3420        eprintln!(
3421            "global-sfm debug: pre-global PnP seed: {prior_count} priors triangulated \
3422             {tri_count} / {} tracks",
3423            built.tracks.len()
3424        );
3425    }
3426    let mut seeded = 0usize;
3427    for image in 0..features.len() {
3428        if pose_priors.get(image).and_then(|p| p.as_ref()).is_some() {
3429            continue;
3430        }
3431        if exclude.contains(&image) {
3432            continue;
3433        }
3434        let mut corrs: Vec<Correspondence2D3D> = Vec::new();
3435        for (track_id, track) in built.tracks.iter().enumerate() {
3436            let Some(position) = track_point[track_id] else {
3437                continue;
3438            };
3439            let Some((_, kp)) = track.iter().find(|&&(img, _)| img == image) else {
3440                continue;
3441            };
3442            let anchored = track
3443                .iter()
3444                .any(|&(img, _)| pose_priors.get(img).and_then(|p| p.as_ref()).is_some());
3445            if !anchored {
3446                continue;
3447            }
3448            let Some(pixel) = features[image].keypoints.get(*kp).copied() else {
3449                continue;
3450            };
3451            corrs.push(Correspondence2D3D {
3452                point2d: pixel,
3453                point3d: position,
3454                confidence: None,
3455            });
3456        }
3457        if corrs.len() < min_corrs {
3458            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3459                eprintln!(
3460                    "global-sfm debug: pre-global PnP seed skip image {image}: \
3461                     only {} prior-anchored corrs (need {min_corrs})",
3462                    corrs.len()
3463                );
3464            }
3465            continue;
3466        }
3467        let report = match mapper.pnp_solver {
3468            PnpSolver::P3p => PnPRansac {
3469                pose_estimator: P3PGrunert,
3470                pose_refiner: Some(GaussNewtonPoseRefiner::default()),
3471                iterations: mapper.pnp_max_iterations.max(128),
3472                confidence: Some(0.999),
3473                reprojection_threshold: mapper.max_reprojection_error_px,
3474                seed: 7,
3475                early_stop_min_iterations: 0,
3476                early_stop_inlier_ratio: None,
3477                inlier_refits: 0,
3478            }
3479            .estimate(&corrs, camera),
3480            PnpSolver::Dlt => PnPRansac {
3481                reprojection_threshold: mapper.max_reprojection_error_px,
3482                confidence: Some(0.999),
3483                ..PnPRansac::default()
3484            }
3485            .estimate(&corrs, camera),
3486        };
3487        let Some(report) =
3488            report.filter(|r| r.inliers.len() >= min_corrs.min(mapper.min_pnp_inliers).max(4))
3489        else {
3490            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3491                eprintln!(
3492                    "global-sfm debug: pre-global PnP seed fail image {image}: \
3493                     {} corrs, PnP rejected",
3494                    corrs.len()
3495                );
3496            }
3497            continue;
3498        };
3499        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3500            eprintln!(
3501                "global-sfm debug: pre-global PnP seed image {image}: \
3502                 {} corrs -> {} inliers (promote to prior)",
3503                corrs.len(),
3504                report.inliers.len()
3505            );
3506        }
3507        pose_priors[image] = Some(report.pose);
3508        seeded += 1;
3509    }
3510    seeded
3511}
3512
3513/// End-to-end GLOMAP-style reconstruction: estimate per-pair relative poses
3514/// from verified matches, average them globally, triangulate the feature
3515/// tracks against the averaged cameras, and finish with one bundle adjustment
3516/// over everything registered.
3517///
3518/// This is the global analogue of [`crate::incremental_sfm::incremental_sfm`]'s grow-from-a-
3519/// seed loop: instead of chaining registrations image by image, every camera
3520/// lands in one consistent frame at once and BA only has to polish local
3521/// geometry. Images outside the seed's view-graph component stay unposed.
3522///
3523/// Output: per-image poses (`None` outside the solved component), assembled
3524/// BA-refined tracks, and mean track reprojection in pixels.
3525#[allow(clippy::type_complexity)]
3526pub fn reconstruct_global_sfm(
3527    camera: &Camera,
3528    features: &[FeatureSet],
3529    pairwise: &[PairwiseMatches],
3530    tuning: &GlobalReconstructionTuning,
3531    mapper: &crate::incremental_sfm::IncrementalSfmConfig,
3532) -> Result<(Vec<Option<Pose>>, Vec<SfmTrack>, f64), GlobalReconstructionError> {
3533    reconstruct_global_sfm_with_priors(camera, features, pairwise, tuning, mapper, None, None)
3534}
3535
3536/// Like [`reconstruct_global_sfm`], but pins cameras that already have absolute
3537/// poses (typically from a prior incremental solve) and places the remaining
3538/// images in that gauge.
3539#[allow(clippy::type_complexity)]
3540pub fn reconstruct_global_sfm_with_priors(
3541    camera: &Camera,
3542    features: &[FeatureSet],
3543    pairwise: &[PairwiseMatches],
3544    tuning: &GlobalReconstructionTuning,
3545    mapper: &crate::incremental_sfm::IncrementalSfmConfig,
3546    pose_priors: Option<&[Option<Pose>]>,
3547    gt_poses: Option<&[Option<Pose>]>,
3548) -> Result<(Vec<Option<Pose>>, Vec<SfmTrack>, f64), GlobalReconstructionError> {
3549    // ---- Relative poses → global edges ------------------------------------
3550    let estimator = RelativePoseEstimator {
3551        cheirality: match (tuning.chirality_harden_edges, tuning.multi_hypothesis_edges) {
3552            (true, true) => CheiralityOptions::hardened_keep_ambiguous(),
3553            (true, false) => CheiralityOptions::hardened(),
3554            (false, _) => CheiralityOptions::default(),
3555        },
3556        ..RelativePoseEstimator::default()
3557    };
3558    let mut edges = Vec::new();
3559    let mut chirality_rejected = 0usize;
3560    let mut multi_hyp_edges = 0usize;
3561    let mut pair_fail_estimate = vec![0usize; features.len()];
3562    let mut pair_fail_inliers = vec![0usize; features.len()];
3563    let mut pair_fail_parallax = vec![0usize; features.len()];
3564    let mut pair_kept = vec![0usize; features.len()];
3565    let config_allowed = |pair: &PairwiseMatches| -> bool {
3566        if !tuning.calibrated_view_edges_only {
3567            return true;
3568        }
3569        match pair.two_view_config {
3570            None => true,
3571            Some(ConfigurationType::Calibrated | ConfigurationType::Multiple) => true,
3572            // F-won Uncalibrated pairs can still carry a strong essential
3573            // subset (courtyard stem-E / rematch bridges). Keep those so
3574            // calibrated-only filtering does not discard true E bearings.
3575            Some(_) => pair
3576                .essential_matches
3577                .as_ref()
3578                .is_some_and(|e| e.len() >= tuning.min_pair_matches),
3579        }
3580    };
3581    fn edge_matches(
3582        pair: &PairwiseMatches,
3583        prefer_essential: bool,
3584        min_pair_matches: usize,
3585    ) -> &[(usize, usize)] {
3586        if prefer_essential {
3587            if let Some(ess) = pair.essential_matches.as_ref() {
3588                if ess.len() >= min_pair_matches {
3589                    return ess.as_slice();
3590                }
3591            }
3592        }
3593        pair.matches.as_slice()
3594    }
3595    /// Prefer E inliers for this pair given the free-endpoint / global flags.
3596    fn prefer_essential_for_pair(
3597        tuning: &GlobalReconstructionTuning,
3598        pose_priors: Option<&[Option<Pose>]>,
3599        image_i: usize,
3600        image_j: usize,
3601    ) -> bool {
3602        if tuning.prefer_essential_edge_matches {
3603            return true;
3604        }
3605        let mut selected = false;
3606        if !tuning.prefer_essential_edge_pairs.is_empty() {
3607            let a = image_i.min(image_j);
3608            let b = image_i.max(image_j);
3609            selected |= tuning
3610                .prefer_essential_edge_pairs
3611                .iter()
3612                .any(|&(i, j)| i.min(j) == a && i.max(j) == b);
3613        }
3614        if !tuning.prefer_essential_edge_image_indices.is_empty() {
3615            let hit_i = tuning
3616                .prefer_essential_edge_image_indices
3617                .contains(&image_i);
3618            let hit_j = tuning
3619                .prefer_essential_edge_image_indices
3620                .contains(&image_j);
3621            selected |= if tuning.prefer_essential_edge_stem_clique {
3622                hit_i && hit_j
3623            } else {
3624                hit_i || hit_j
3625            };
3626        }
3627        // Require-stems also prefer E when present (so isolation uses E bearings).
3628        if !tuning.require_essential_edge_image_indices.is_empty() {
3629            selected |= tuning
3630                .require_essential_edge_image_indices
3631                .iter()
3632                .any(|&idx| idx == image_i || idx == image_j);
3633        }
3634        if selected {
3635            return true;
3636        }
3637        if !tuning.prefer_essential_edge_matches_free_endpoints {
3638            return false;
3639        }
3640        match pose_priors {
3641            None => true,
3642            Some(priors) => {
3643                let free_i = priors.get(image_i).is_none_or(Option::is_none);
3644                let free_j = priors.get(image_j).is_none_or(Option::is_none);
3645                free_i || free_j
3646            }
3647        }
3648    }
3649    /// True when this pair is in the stem/pair selection set (regardless of
3650    /// whether E inliers are actually available).
3651    fn essential_selection_covers_pair(
3652        tuning: &GlobalReconstructionTuning,
3653        image_i: usize,
3654        image_j: usize,
3655    ) -> bool {
3656        // Same coverage as prefer_essential_for_pair without the free-endpoint
3657        // fallback (require-E only applies to explicit stem/pair selections).
3658        if !tuning.prefer_essential_edge_pairs.is_empty() {
3659            let a = image_i.min(image_j);
3660            let b = image_i.max(image_j);
3661            if tuning
3662                .prefer_essential_edge_pairs
3663                .iter()
3664                .any(|&(i, j)| i.min(j) == a && i.max(j) == b)
3665            {
3666                return true;
3667            }
3668        }
3669        if !tuning.prefer_essential_edge_image_indices.is_empty() {
3670            let hit_i = tuning
3671                .prefer_essential_edge_image_indices
3672                .contains(&image_i);
3673            let hit_j = tuning
3674                .prefer_essential_edge_image_indices
3675                .contains(&image_j);
3676            return if tuning.prefer_essential_edge_stem_clique {
3677                hit_i && hit_j
3678            } else {
3679                hit_i || hit_j
3680            };
3681        }
3682        false
3683    }
3684    /// True when this pair must have strong E inliers or be dropped.
3685    fn requires_essential_for_pair(
3686        tuning: &GlobalReconstructionTuning,
3687        image_i: usize,
3688        image_j: usize,
3689    ) -> bool {
3690        if tuning.require_essential_for_selected_edges
3691            && essential_selection_covers_pair(tuning, image_i, image_j)
3692        {
3693            return true;
3694        }
3695        if !tuning.require_essential_edge_image_indices.is_empty() {
3696            return tuning
3697                .require_essential_edge_image_indices
3698                .iter()
3699                .any(|&idx| idx == image_i || idx == image_j);
3700        }
3701        false
3702    }
3703    let mut essential_edge_uses = 0usize;
3704    let mut essential_required_drops = 0usize;
3705    let metric_chirality_flips = std::cell::Cell::new(0usize);
3706    let gt_oracle_flips = std::cell::Cell::new(0usize);
3707    let free_centres = if tuning.metric_prior_chirality_edges {
3708        pose_priors
3709            .map(|priors| {
3710                estimate_free_centres_from_prior_rays(
3711                    pairwise,
3712                    features,
3713                    camera,
3714                    priors,
3715                    tuning.metric_prior_chirality_min_rays,
3716                    tuning.min_pair_matches,
3717                )
3718            })
3719            .unwrap_or_default()
3720    } else {
3721        HashMap::new()
3722    };
3723    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() && tuning.metric_prior_chirality_edges {
3724        eprintln!(
3725            "global-sfm debug: metric-prior chirality anchors for {} free camera(s)",
3726            free_centres.len()
3727        );
3728    }
3729    for pair in pairwise {
3730        let use_essential = tuning.independent_edge_scales
3731            || prefer_essential_for_pair(tuning, pose_priors, pair.image_i, pair.image_j);
3732        if requires_essential_for_pair(tuning, pair.image_i, pair.image_j) {
3733            let min_e = if tuning.require_essential_min_e_inliers > 0 {
3734                tuning.require_essential_min_e_inliers
3735            } else {
3736                tuning.min_pair_matches
3737            };
3738            let has_ess = pair
3739                .essential_matches
3740                .as_ref()
3741                .is_some_and(|e| e.len() >= min_e);
3742            if !has_ess {
3743                essential_required_drops += 1;
3744                continue;
3745            }
3746        }
3747        let matches = edge_matches(pair, use_essential, tuning.min_pair_matches);
3748        if matches.len() < tuning.min_pair_matches {
3749            continue;
3750        }
3751        if !config_allowed(pair) {
3752            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3753                eprintln!(
3754                    "global-sfm debug: dropped non-calibrated edge {}-{} ({:?})",
3755                    pair.image_i, pair.image_j, pair.two_view_config
3756                );
3757            }
3758            continue;
3759        }
3760        let used_essential = use_essential
3761            && pair
3762                .essential_matches
3763                .as_ref()
3764                .is_some_and(|e| e.len() >= tuning.min_pair_matches);
3765        if used_essential {
3766            essential_edge_uses += 1;
3767            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3768                eprintln!(
3769                    "global-sfm debug: essential-edge {}-{} ({} E inliers)",
3770                    pair.image_i,
3771                    pair.image_j,
3772                    pair.essential_matches.as_ref().map_or(0, |e| e.len())
3773                );
3774            }
3775        }
3776        let correspondences: Vec<TwoViewCorrespondence> = matches
3777            .iter()
3778            .filter_map(|&(ki, kj)| {
3779                Some(TwoViewCorrespondence::new(
3780                    *features[pair.image_i].keypoints.get(ki)?,
3781                    *features[pair.image_j].keypoints.get(kj)?,
3782                ))
3783            })
3784            .collect();
3785        let relative = estimator.estimate(&correspondences, camera);
3786        let Some(relative) = relative else {
3787            if tuning.chirality_harden_edges {
3788                chirality_rejected += 1;
3789            }
3790            pair_fail_estimate[pair.image_i] += 1;
3791            pair_fail_estimate[pair.image_j] += 1;
3792            continue;
3793        };
3794        if relative.inliers.len() < tuning.min_edge_inliers {
3795            pair_fail_inliers[pair.image_i] += 1;
3796            pair_fail_inliers[pair.image_j] += 1;
3797            continue;
3798        };
3799        // Bearing of camera j's centre expressed in camera i's frame:
3800        // C_j^(i) = −R_ijᵀ t_ij.
3801        let mut r_ij = relative.previous_to_current.rotation;
3802        let t_ij = relative.previous_to_current.translation;
3803        let Some(mut direction_ij) = (-r_ij.inverse().transform_vector(&t_ij)).try_normalize(1e-12)
3804        else {
3805            continue;
3806        };
3807        let (mut rotation_alt, mut direction_alt) = if tuning.multi_hypothesis_edges {
3808            match relative.alternate {
3809                Some((r_alt, t_alt_unit)) => {
3810                    let scale = relative.translation_scale;
3811                    let t_alt = t_alt_unit * scale;
3812                    match (-r_alt.inverse().transform_vector(&t_alt)).try_normalize(1e-12) {
3813                        Some(d_alt) => {
3814                            multi_hyp_edges += 1;
3815                            (Some(r_alt), Some(d_alt))
3816                        }
3817                        None => (None, None),
3818                    }
3819                }
3820                None => (None, None),
3821            }
3822        } else {
3823            (None, None)
3824        };
3825        if tuning.metric_prior_chirality_edges {
3826            let is_prior = |i: usize| {
3827                pose_priors
3828                    .and_then(|p| p.get(i))
3829                    .and_then(|p| p.as_ref())
3830                    .is_some()
3831            };
3832            let pi = is_prior(pair.image_i);
3833            let pj = is_prior(pair.image_j);
3834            if pi != pj {
3835                let (prior_idx, free_idx) = if pi {
3836                    (pair.image_i, pair.image_j)
3837                } else {
3838                    (pair.image_j, pair.image_i)
3839                };
3840                if let (Some(priors), Some(free_centre)) =
3841                    (pose_priors, free_centres.get(&free_idx))
3842                {
3843                    if let Some(prior_pose) = priors.get(prior_idx).and_then(|p| p.as_ref()) {
3844                        if let Some(expected) =
3845                            expected_bearing_prior_to_world_point(prior_pose, free_centre)
3846                        {
3847                            let flip = (|| {
3848                                let bearing_primary = if prior_idx == pair.image_i {
3849                                    direction_ij
3850                                } else {
3851                                    (-r_ij.transform_vector(&direction_ij)).try_normalize(1e-12)?
3852                                };
3853                                let primary_dot = bearing_primary.dot(&expected);
3854                                let r_alt = rotation_alt.as_ref()?;
3855                                let d_alt = direction_alt.as_ref()?;
3856                                let bearing_alt = if prior_idx == pair.image_i {
3857                                    *d_alt
3858                                } else {
3859                                    (-r_alt.transform_vector(d_alt)).try_normalize(1e-12)?
3860                                };
3861                                Some(bearing_alt.dot(&expected) > primary_dot + 1e-3)
3862                            })();
3863                            if flip == Some(true) {
3864                                std::mem::swap(&mut r_ij, rotation_alt.as_mut().unwrap());
3865                                std::mem::swap(&mut direction_ij, direction_alt.as_mut().unwrap());
3866                                metric_chirality_flips.set(metric_chirality_flips.get() + 1);
3867                            }
3868                        }
3869                    }
3870                }
3871            }
3872        }
3873        if tuning.gt_chirality_oracle {
3874            if let Some(gt) = gt_poses {
3875                if let (Some(gti), Some(gtj)) = (
3876                    gt.get(pair.image_i).and_then(|p| p.as_ref()),
3877                    gt.get(pair.image_j).and_then(|p| p.as_ref()),
3878                ) {
3879                    if let Some(gt_in_i) = gt_bearing_in_prior_frame(gti, gtj) {
3880                        let err_pri = bearing_alignment_error_deg(&direction_ij, &gt_in_i);
3881                        if let Some(d_alt) = direction_alt.as_ref() {
3882                            let err_alt = bearing_alignment_error_deg(d_alt, &gt_in_i);
3883                            if err_alt + 1e-3 < err_pri {
3884                                if let Some(r_alt) = rotation_alt.as_mut() {
3885                                    std::mem::swap(&mut r_ij, r_alt);
3886                                    std::mem::swap(
3887                                        &mut direction_ij,
3888                                        direction_alt.as_mut().unwrap(),
3889                                    );
3890                                    gt_oracle_flips.set(gt_oracle_flips.get() + 1);
3891                                }
3892                            }
3893                        }
3894                    }
3895                }
3896            }
3897        }
3898        // GLOMAP-style baseline gate: triangulate a sample of the inlier
3899        // correspondences under this pair's pose and measure the median ray
3900        // intersection angle. Tiny-baseline pairs produce well-fit essential
3901        // matrices whose translation direction is pure noise — dropping them
3902        // protects both averaging stages from systematically bent bearings.
3903        if tuning.min_edge_parallax_deg > 0.0 {
3904            let pose_i_to_j = relative.previous_to_current;
3905            let step: usize = (relative.inliers.len() / 100).max(1);
3906            let mut angles: Vec<f64> = Vec::new();
3907            for &idx in relative.inliers.iter().step_by(step) {
3908                let Some(corr) = correspondences.get(idx) else {
3909                    continue;
3910                };
3911                let Some(point) = triangulate_two_view_left_frame(
3912                    camera,
3913                    camera,
3914                    &pose_i_to_j,
3915                    &corr.previous_xy,
3916                    &corr.current_xy,
3917                ) else {
3918                    continue;
3919                };
3920                let cam_j_centre: Vector3<f64> = r_ij.inverse() * (-t_ij);
3921                let ray1 = point.coords;
3922                let ray2 = point.coords - cam_j_centre;
3923                let cos = ray1.normalize().dot(&ray2.normalize()).clamp(-1.0, 1.0);
3924                angles.push(cos.acos());
3925            }
3926            angles.sort_by(|a, b| a.total_cmp(b));
3927            if let Some(angle) = angles.get(angles.len() / 2).copied() {
3928                if angle < tuning.min_edge_parallax_deg.to_radians() {
3929                    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
3930                        eprintln!(
3931                            "global-sfm debug: dropped low-parallax edge {}-{} ({:.2} deg, {} inliers)",
3932                            pair.image_i,
3933                            pair.image_j,
3934                            angle.to_degrees(),
3935                            relative.inliers.len()
3936                        );
3937                    }
3938                    pair_fail_parallax[pair.image_i] += 1;
3939                    pair_fail_parallax[pair.image_j] += 1;
3940                    continue;
3941                }
3942            }
3943        }
3944        // Retain a subsample of inliers for post-rotation translation refine.
3945        let step = (relative.inliers.len() / 32).max(1);
3946        let inlier_sample: Vec<(Point2<f64>, Point2<f64>)> = relative
3947            .inliers
3948            .iter()
3949            .step_by(step)
3950            .filter_map(|&idx| {
3951                let c = correspondences.get(idx)?;
3952                Some((c.previous_xy, c.current_xy))
3953            })
3954            .collect();
3955        let mut weight = if tuning.weight_edges_by_chirality_margin {
3956            relative.inliers.len() as f64 * (0.1 + relative.chirality_margin.clamp(0.0, 1.0))
3957        } else {
3958            relative.inliers.len() as f64
3959        };
3960        if used_essential && tuning.essential_edge_weight_boost != 1.0 {
3961            weight *= tuning.essential_edge_weight_boost.max(0.0);
3962        }
3963        edges.push(GlobalSfmEdge {
3964            image_i: pair.image_i,
3965            image_j: pair.image_j,
3966            rotation_ij: r_ij,
3967            direction_ij,
3968            weight,
3969            inlier_sample,
3970            rotation_alt,
3971            direction_alt,
3972        });
3973        pair_kept[pair.image_i] += 1;
3974        pair_kept[pair.image_j] += 1;
3975    }
3976    if tuning.prior_guided_free_chirality {
3977        if let Some(priors) = pose_priors {
3978            apply_prior_guided_free_chirality(&mut edges, priors);
3979        }
3980    }
3981    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() && tuning.metric_prior_chirality_edges {
3982        eprintln!(
3983            "global-sfm debug: metric-prior chirality flipped {} prior↔free edge(s)",
3984            metric_chirality_flips.get()
3985        );
3986    }
3987    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() && tuning.gt_chirality_oracle {
3988        eprintln!(
3989            "global-sfm debug: GT chirality oracle flipped {} edge(s)",
3990            gt_oracle_flips.get()
3991        );
3992    }
3993    // Orphan rescue: images that lost every edge at the strict inlier gate get
3994    // one more chance at half the threshold (floored at 8). Courtyard's
3995    // DSC_0308 typically has a single verified pair whose essential inliers
3996    // sit just under the default 15 — connecting it beats leaving a hole.
3997    {
3998        let mut degree = vec![0usize; features.len()];
3999        for e in &edges {
4000            degree[e.image_i] += 1;
4001            degree[e.image_j] += 1;
4002        }
4003        let orphans: Vec<usize> = degree
4004            .iter()
4005            .enumerate()
4006            .filter(|&(_, &d)| d == 0)
4007            .map(|(i, _)| i)
4008            .collect();
4009        let rescue_inliers = (tuning.min_edge_inliers / 2).max(8);
4010        if !orphans.is_empty() && rescue_inliers < tuning.min_edge_inliers {
4011            let orphan_set: HashSet<usize> = orphans.iter().copied().collect();
4012            let existing: HashSet<(usize, usize)> = edges
4013                .iter()
4014                .map(|e| (e.image_i.min(e.image_j), e.image_i.max(e.image_j)))
4015                .collect();
4016            let mut rescued = 0usize;
4017            for pair in pairwise {
4018                if !orphan_set.contains(&pair.image_i) && !orphan_set.contains(&pair.image_j) {
4019                    continue;
4020                }
4021                if !config_allowed(pair) {
4022                    continue;
4023                }
4024                let key = (
4025                    pair.image_i.min(pair.image_j),
4026                    pair.image_i.max(pair.image_j),
4027                );
4028                if existing.contains(&key) {
4029                    continue;
4030                }
4031                if requires_essential_for_pair(tuning, pair.image_i, pair.image_j) {
4032                    let min_e = if tuning.require_essential_min_e_inliers > 0 {
4033                        tuning.require_essential_min_e_inliers
4034                    } else {
4035                        tuning.min_pair_matches
4036                    };
4037                    if pair
4038                        .essential_matches
4039                        .as_ref()
4040                        .is_none_or(|e| e.len() < min_e)
4041                    {
4042                        continue;
4043                    }
4044                }
4045                let matches = edge_matches(
4046                    pair,
4047                    tuning.independent_edge_scales
4048                        || prefer_essential_for_pair(
4049                            tuning,
4050                            pose_priors,
4051                            pair.image_i,
4052                            pair.image_j,
4053                        ),
4054                    tuning.min_pair_matches,
4055                );
4056                if matches.len() < tuning.min_pair_matches {
4057                    continue;
4058                }
4059                let correspondences: Vec<TwoViewCorrespondence> = matches
4060                    .iter()
4061                    .filter_map(|&(ki, kj)| {
4062                        Some(TwoViewCorrespondence::new(
4063                            *features[pair.image_i].keypoints.get(ki)?,
4064                            *features[pair.image_j].keypoints.get(kj)?,
4065                        ))
4066                    })
4067                    .collect();
4068                let Some(relative) = estimator.estimate(&correspondences, camera) else {
4069                    continue;
4070                };
4071                if relative.inliers.len() < rescue_inliers {
4072                    continue;
4073                }
4074                let r_ij = relative.previous_to_current.rotation;
4075                let t_ij = relative.previous_to_current.translation;
4076                let Some(direction_ij) =
4077                    (-r_ij.inverse().transform_vector(&t_ij)).try_normalize(1e-12)
4078                else {
4079                    continue;
4080                };
4081                let (rotation_alt, direction_alt) = if tuning.multi_hypothesis_edges {
4082                    match relative.alternate {
4083                        Some((r_alt, t_alt_unit)) => {
4084                            let t_alt = t_alt_unit * relative.translation_scale;
4085                            match (-r_alt.inverse().transform_vector(&t_alt)).try_normalize(1e-12) {
4086                                Some(d_alt) => (Some(r_alt), Some(d_alt)),
4087                                None => (None, None),
4088                            }
4089                        }
4090                        None => (None, None),
4091                    }
4092                } else {
4093                    (None, None)
4094                };
4095                let step = (relative.inliers.len() / 32).max(1);
4096                let inlier_sample: Vec<(Point2<f64>, Point2<f64>)> = relative
4097                    .inliers
4098                    .iter()
4099                    .step_by(step)
4100                    .filter_map(|&idx| {
4101                        let c = correspondences.get(idx)?;
4102                        Some((c.previous_xy, c.current_xy))
4103                    })
4104                    .collect();
4105                let weight = if tuning.weight_edges_by_chirality_margin {
4106                    relative.inliers.len() as f64
4107                        * (0.1 + relative.chirality_margin.clamp(0.0, 1.0))
4108                } else {
4109                    relative.inliers.len() as f64
4110                };
4111                edges.push(GlobalSfmEdge {
4112                    image_i: pair.image_i,
4113                    image_j: pair.image_j,
4114                    rotation_ij: r_ij,
4115                    direction_ij,
4116                    weight,
4117                    inlier_sample,
4118                    rotation_alt,
4119                    direction_alt,
4120                });
4121                pair_kept[pair.image_i] += 1;
4122                pair_kept[pair.image_j] += 1;
4123                rescued += 1;
4124            }
4125            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
4126                eprintln!(
4127                    "global-sfm debug: orphan-edge rescue (min_inliers={rescue_inliers}) \
4128                     added {rescued} edge(s) for {} orphan image(s)",
4129                    orphans.len()
4130                );
4131            }
4132        }
4133    }
4134    if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
4135        if tuning.chirality_harden_edges {
4136            eprintln!(
4137                "global-sfm debug: chirality-harden rejected {chirality_rejected} pairs; kept {} edges",
4138                edges.len()
4139            );
4140        }
4141        if tuning.multi_hypothesis_edges {
4142            eprintln!(
4143                "global-sfm debug: multi-hypothesis edges carrying alternate: {multi_hyp_edges} / {}",
4144                edges.len()
4145            );
4146        }
4147        if tuning.prefer_essential_edge_matches
4148            || tuning.prefer_essential_edge_matches_free_endpoints
4149            || !tuning.prefer_essential_edge_image_indices.is_empty()
4150            || !tuning.prefer_essential_edge_pairs.is_empty()
4151            || !tuning.require_essential_edge_image_indices.is_empty()
4152        {
4153            eprintln!(
4154                "global-sfm debug: prefer-essential-edge-matches used E inliers on {essential_edge_uses} pairs \
4155                 (all={} free-endpoints={} stem-indices={} clique={} pairs={} require-stems={} require-drop={essential_required_drops})",
4156                tuning.prefer_essential_edge_matches,
4157                tuning.prefer_essential_edge_matches_free_endpoints,
4158                tuning.prefer_essential_edge_image_indices.len(),
4159                tuning.prefer_essential_edge_stem_clique,
4160                tuning.prefer_essential_edge_pairs.len(),
4161                tuning.require_essential_edge_image_indices.len(),
4162            );
4163        }
4164        for i in 0..features.len() {
4165            if pair_kept[i] == 0
4166                && (pair_fail_estimate[i] + pair_fail_inliers[i] + pair_fail_parallax[i] > 0)
4167            {
4168                eprintln!(
4169                    "global-sfm debug: image {i} has 0 edges after relative-pose gates \
4170                     (fail estimate={} inliers={} parallax={})",
4171                    pair_fail_estimate[i], pair_fail_inliers[i], pair_fail_parallax[i]
4172                );
4173            }
4174        }
4175    }
4176
4177    // ---- Triplet loop-closure sanitisation ---------------------------------
4178    // Wrong-chirality / wrong-pose essential estimates survive per-pair
4179    // RANSAC on repetitive real scenes but fail three-edge rotation loops:
4180    // R_wu·R_vw·R_uv must be ≈ identity around every triangle. Score each
4181    // edge by the MEDIAN loop error over its common-neighbour triangles and
4182    // drop edges above twice the IRLS trim threshold.
4183    {
4184        let mut neighbors: HashMap<usize, HashSet<usize>> = HashMap::new();
4185        for e in &edges {
4186            neighbors.entry(e.image_i).or_default().insert(e.image_j);
4187            neighbors.entry(e.image_j).or_default().insert(e.image_i);
4188        }
4189        let mut edge_lookup: HashMap<(usize, usize), usize> = HashMap::new();
4190        for (index, e) in edges.iter().enumerate() {
4191            edge_lookup.insert((e.image_i, e.image_j), index);
4192            edge_lookup.insert((e.image_j, e.image_i), index);
4193        }
4194        let step_hyps = |from: usize, index: usize| -> Vec<UnitQuaternion<f64>> {
4195            let e = &edges[index];
4196            let mut hyps = vec![e.step_primary(from)];
4197            if let Some(r_alt) = e.rotation_alt {
4198                hyps.push(if e.image_i == from {
4199                    r_alt
4200                } else {
4201                    r_alt.inverse()
4202                });
4203            }
4204            hyps
4205        };
4206        let mut loop_errors: Vec<Vec<f64>> = vec![Vec::new(); edges.len()];
4207        for e_index in 0..edges.len() {
4208            let (u, v) = (edges[e_index].image_i, edges[e_index].image_j);
4209            let Some(common) = neighbors.get(&u) else {
4210                continue;
4211            };
4212            for &w in common {
4213                if w == v || !neighbors.get(&v).is_some_and(|nv| nv.contains(&w)) {
4214                    continue;
4215                }
4216                let Some(&vw) = edge_lookup.get(&(v, w)) else {
4217                    continue;
4218                };
4219                let Some(&wu) = edge_lookup.get(&(w, u)) else {
4220                    continue;
4221                };
4222                // Min loop error over primary/alternate combinations so an
4223                // edge with a wrong primary but correct alternate is not
4224                // dropped by triplet sanitation.
4225                let mut best = f64::INFINITY;
4226                for s_uv in step_hyps(u, e_index) {
4227                    for s_vw in step_hyps(v, vw) {
4228                        for s_wu in step_hyps(w, wu) {
4229                            best = best.min((s_wu * s_vw * s_uv).angle());
4230                        }
4231                    }
4232                }
4233                if best.is_finite() {
4234                    loop_errors[e_index].push(best);
4235                }
4236            }
4237        }
4238        let mut dropped = 0usize;
4239        for (index, errs) in loop_errors.iter_mut().enumerate() {
4240            if errs.is_empty() {
4241                continue;
4242            }
4243            errs.sort_by(|a, b| a.total_cmp(b));
4244            let median = errs[errs.len() / 2];
4245            if median > tuning.max_edge_rotation_error_deg.to_radians() * 2.0 {
4246                dropped += 1;
4247                edges[index].weight = -1.0; // marker: dropped
4248            }
4249        }
4250        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
4251            eprintln!("global-sfm debug: triplet sanitation dropped {dropped} edges");
4252            let mut deg = vec![0usize; features.len()];
4253            for e in &edges {
4254                deg[e.image_i] += 1;
4255                deg[e.image_j] += 1;
4256            }
4257            for (i, &d) in deg.iter().enumerate() {
4258                if d == 0 {
4259                    eprintln!(
4260                        "global-sfm debug: image {i} degree 0 after triplet sanitation (pre-sanitation kept edges involving it: {})",
4261                        pair_kept[i]
4262                    );
4263                }
4264            }
4265        }
4266        edges.retain(|e| e.weight > 0.0);
4267    }
4268
4269    // GT-free: probe with rotation-pinned / centre-free solve, drop priors
4270    // whose centres disagree with the free gauge after Sim(3), then continue
4271    // with the thinned prior set for the real hybrid solve.
4272    let pose_priors_filtered;
4273    let pose_priors: Option<&[Option<Pose>]> = if tuning.drop_inconsistent_pose_priors {
4274        match pose_priors {
4275            Some(priors) => {
4276                let before = priors.iter().filter(|p| p.is_some()).count();
4277                let mut probe_edges = edges.clone();
4278                let probe_seed = {
4279                    // Prefer any prior as probe seed (same component later).
4280                    priors
4281                        .iter()
4282                        .enumerate()
4283                        .find_map(|(i, p)| p.as_ref().map(|_| i))
4284                        .unwrap_or(0)
4285                };
4286                let filtered = match solve_global_sfm_with_options(
4287                    features.len(),
4288                    &mut probe_edges,
4289                    probe_seed,
4290                    tuning.sweeps,
4291                    tuning.cg_iterations,
4292                    tuning.max_edge_rotation_error_deg,
4293                    tuning.refine_translations_with_global_rotations,
4294                    Some(camera),
4295                    Some(priors),
4296                    false, // free centres
4297                    None,
4298                    false,
4299                    false,
4300                    tuning.independent_edge_scales,
4301                ) {
4302                    Some(probe) => {
4303                        let free_centers: Vec<Option<Point3<f64>>> = probe
4304                            .poses
4305                            .iter()
4306                            .map(|p| p.as_ref().map(|pose| pose.camera_center_world()))
4307                            .collect();
4308                        let (filtered, kept) = filter_pose_priors_by_free_centre_residual(
4309                            priors,
4310                            &free_centers,
4311                            tuning.inconsistent_prior_max_drops,
4312                            tuning.inconsistent_prior_min_flip_fraction,
4313                        );
4314                        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
4315                            eprintln!(
4316                                "global-sfm debug: free-centre prior filter kept {kept} / {before}"
4317                            );
4318                        }
4319                        filtered
4320                    }
4321                    None => {
4322                        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
4323                            eprintln!(
4324                                    "global-sfm debug: free-centre probe failed; keeping all {before} priors"
4325                                );
4326                        }
4327                        priors.to_vec()
4328                    }
4329                };
4330                pose_priors_filtered = filtered;
4331                Some(pose_priors_filtered.as_slice())
4332            }
4333            None => None,
4334        }
4335    } else {
4336        pose_priors
4337    };
4338
4339    // Optional: promote free cameras that PnP cleanly into prior-only
4340    // structure to hard pose priors before rotation/position averaging.
4341    let seeded_priors_storage = if tuning.repnp_seed_free_as_priors {
4342        pose_priors.map(|priors| {
4343            let mut owned = priors.to_vec();
4344            let min_corrs = if tuning.repnp_free_min_corrs > 0 {
4345                tuning.repnp_free_min_corrs
4346            } else {
4347                mapper.min_pnp_inliers
4348            };
4349            let n = pnp_seed_free_cameras_into_priors(
4350                camera,
4351                features,
4352                pairwise,
4353                &mut owned,
4354                mapper,
4355                min_corrs,
4356                &tuning
4357                    .repnp_seed_exclude_image_indices
4358                    .iter()
4359                    .copied()
4360                    .collect::<HashSet<_>>(),
4361            );
4362            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() || n > 0 {
4363                eprintln!(
4364                    "global-sfm: pre-global PnP seeded {n} free camera(s) as pose priors \
4365                     (min_corrs={min_corrs})"
4366                );
4367            }
4368            owned
4369        })
4370    } else {
4371        None
4372    };
4373    let pose_priors = seeded_priors_storage.as_deref().or(pose_priors);
4374
4375    // Seed selection: the caller's seed may sit in a small side component
4376    // (courtyard-class view graphs have them); solve the LARGEST connected
4377    // component instead.
4378    let adjacency_for_seed =
4379        build_adjacency(features.len(), &edges).ok_or(GlobalReconstructionError::NoUsableEdges)?;
4380    let seed = {
4381        let mut seen = vec![false; features.len()];
4382        let mut best = (0usize, usize::MAX); // (size, smallest member)
4383        let mut preferred_size = None;
4384        for start in 0..features.len() {
4385            if seen[start] || !adjacency_for_seed.contains_key(&start) {
4386                continue;
4387            }
4388            let mut stack = vec![start];
4389            seen[start] = true;
4390            let (mut size, mut smallest) = (0usize, usize::MAX);
4391            while let Some(node) = stack.pop() {
4392                size += 1;
4393                smallest = smallest.min(node);
4394                if let Some(nbrs) = adjacency_for_seed.get(&node) {
4395                    for &(n, _) in nbrs {
4396                        if !seen[n] {
4397                            seen[n] = true;
4398                            stack.push(n);
4399                        }
4400                    }
4401                }
4402            }
4403            if start == tuning.seed {
4404                preferred_size = Some(size);
4405            }
4406            if (size, std::cmp::Reverse(smallest)) > (best.0, std::cmp::Reverse(best.1)) {
4407                best = (size, smallest);
4408            }
4409        }
4410        // Hybrid: pin gauge to a prior camera inside the largest component.
4411        if let Some(priors) = pose_priors {
4412            let mut prior_in_best = None;
4413            let mut seen = vec![false; features.len()];
4414            // Re-walk the best component to find any prior member.
4415            if best.1 < features.len() && adjacency_for_seed.contains_key(&best.1) {
4416                let mut stack = vec![best.1];
4417                seen[best.1] = true;
4418                while let Some(node) = stack.pop() {
4419                    if priors.get(node).and_then(|p| p.as_ref()).is_some() {
4420                        prior_in_best = Some(node);
4421                        break;
4422                    }
4423                    if let Some(nbrs) = adjacency_for_seed.get(&node) {
4424                        for &(n, _) in nbrs {
4425                            if !seen[n] {
4426                                seen[n] = true;
4427                                stack.push(n);
4428                            }
4429                        }
4430                    }
4431                }
4432            }
4433            if let Some(p) = prior_in_best {
4434                p
4435            } else {
4436                match preferred_size {
4437                    Some(size) if size == best.0 => tuning.seed,
4438                    _ => best.1,
4439                }
4440            }
4441        } else {
4442            match preferred_size {
4443                Some(size) if size == best.0 => tuning.seed,
4444                _ => best.1,
4445            }
4446        }
4447    };
4448
4449    let solved = {
4450        // Multi-seed rotation averaging: try the component's highest-degree
4451        // nodes and keep the solve that triangulates with the lowest mean
4452        // reprojection. Bearing residual alone prefers self-consistent wrong
4453        // basins on repetitive façades; image reprojection breaks the tie.
4454        // With absolute pose priors the gauge is fixed — a single seed suffices.
4455        let trials = if pose_priors.is_some() {
4456            1
4457        } else {
4458            tuning.rotation_seed_trials.max(1)
4459        };
4460        let mut candidate_seeds = vec![seed];
4461        if trials > 1 {
4462            let mut degrees: Vec<(usize, usize)> = adjacency_for_seed
4463                .iter()
4464                .map(|(&node, nbrs)| (nbrs.len(), node))
4465                .collect();
4466            degrees.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
4467            for &(_, node) in degrees.iter().take(trials) {
4468                if !candidate_seeds.contains(&node) {
4469                    candidate_seeds.push(node);
4470                }
4471            }
4472            candidate_seeds.truncate(trials);
4473        }
4474        let built_for_score = build_track_output(features, pairwise, mapper, Some(camera));
4475        // (solution, registered, reproj, bearing_rad, obs_count, seed, flip_alts, trans_flips)
4476        let mut candidates: Vec<(
4477            GlobalSfmPoses,
4478            usize,
4479            f64,
4480            f64,
4481            usize,
4482            usize,
4483            bool,
4484            usize,
4485        )> = Vec::new();
4486        // When multi-hypothesis edges are present, also try the global
4487        // "all-alternates-as-primary" basin — MST seeding locks onto the
4488        // stored primary, so adaptive consensus alone may never leave it.
4489        let hyp_flips: &[bool] = if tuning.multi_hypothesis_edges {
4490            &[false, true]
4491        } else {
4492            &[false]
4493        };
4494        for &trial_seed in &candidate_seeds {
4495            for &flip_alts in hyp_flips {
4496                let mut trial_edges = edges.clone();
4497                if flip_alts {
4498                    for e in &mut trial_edges {
4499                        e.swap_primary_alternate();
4500                    }
4501                }
4502                let joint = if tuning.joint_global_positioning {
4503                    Some((
4504                        camera,
4505                        features,
4506                        built_for_score.tracks.as_slice(),
4507                    ))
4508                } else {
4509                    None
4510                };
4511                let Some(solution) = solve_global_sfm_with_options(
4512                    features.len(),
4513                    &mut trial_edges,
4514                    trial_seed,
4515                    tuning.sweeps,
4516                    tuning.cg_iterations,
4517                    tuning.max_edge_rotation_error_deg,
4518                    tuning.refine_translations_with_global_rotations,
4519                    Some(camera),
4520                    pose_priors,
4521                    !tuning.hybrid_rotation_priors_only,
4522                    joint,
4523                    tuning.repair_edges_from_pose_priors,
4524                    tuning.metric_scale_from_pose_priors,
4525                    tuning.independent_edge_scales,
4526                ) else {
4527                    continue;
4528                };
4529                let registered = solution.poses.iter().filter(|p| p.is_some()).count();
4530                let mut track_point = vec![None; built_for_score.tracks.len()];
4531                triangulate_pending(
4532                    camera,
4533                    features,
4534                    &built_for_score.tracks,
4535                    &solution.poses,
4536                    mapper,
4537                    &mut track_point,
4538                );
4539                let (mut reproj_sum, mut reproj_count) = (0.0f64, 0usize);
4540                for (track_id, track) in built_for_score.tracks.iter().enumerate() {
4541                    let Some(position) = track_point[track_id] else {
4542                        continue;
4543                    };
4544                    for &(image, kp) in track {
4545                        let Some(pose) = &solution.poses[image] else {
4546                            continue;
4547                        };
4548                        let Some(pixel) = features[image].keypoints.get(kp).copied() else {
4549                            continue;
4550                        };
4551                        if let Some(error) = reprojection_error_px(camera, pose, &position, &pixel)
4552                        {
4553                            reproj_sum += error;
4554                            reproj_count += 1;
4555                        }
4556                    }
4557                }
4558                let reproj = if reproj_count > 0 {
4559                    reproj_sum / reproj_count as f64
4560                } else {
4561                    f64::INFINITY
4562                };
4563                if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
4564                    eprintln!(
4565                        "global-sfm debug: seed {trial_seed} flip_alts={flip_alts} registered={registered} \
4566                         pre-BA reproj={reproj:.3} px bearing={:.2} deg obs={reproj_count}",
4567                        solution.mean_bearing_residual_rad.to_degrees()
4568                    );
4569                }
4570                let bearing = solution.mean_bearing_residual_rad;
4571                let trans_flips = solution.translation_refine_flips;
4572                candidates.push((
4573                    solution,
4574                    registered,
4575                    reproj,
4576                    bearing,
4577                    reproj_count,
4578                    trial_seed,
4579                    flip_alts,
4580                    trans_flips,
4581                ));
4582            }
4583        }
4584        // Rank: most cameras, then require ≥50% of the densest triangulation
4585        // among that registration count (rejects collapsed self-consistent
4586        // basins with tiny track support), then lowest reproj*(1+bearing)
4587        // score. `trans_flips` is logged for diagnostics only — courtyard A/B
4588        // showed fewer flips does not imply better GT alignment.
4589        let max_reg = candidates.iter().map(|c| c.1).max().unwrap_or(0);
4590        let max_obs = candidates
4591            .iter()
4592            .filter(|c| c.1 == max_reg)
4593            .map(|c| c.4)
4594            .max()
4595            .unwrap_or(0);
4596        let obs_floor = max_obs / 2;
4597        let best = candidates
4598            .into_iter()
4599            .filter(|c| c.1 == max_reg && c.4 >= obs_floor)
4600            .min_by(|a, b| {
4601                let score = |c: &(_, _, f64, f64, _, _, _, _)| {
4602                    if c.2.is_finite() {
4603                        c.2 * (1.0 + c.3)
4604                    } else {
4605                        f64::INFINITY
4606                    }
4607                };
4608                score(a)
4609                    .partial_cmp(&score(b))
4610                    .unwrap_or(std::cmp::Ordering::Equal)
4611            });
4612        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() && (trials > 1 || hyp_flips.len() > 1)
4613        {
4614            if let Some((_, reg, reproj, bearing, obs, chosen, flip, trans_flips)) = &best {
4615                eprintln!(
4616                    "global-sfm debug: multi-seed chose seed {chosen} flip_alts={flip} \
4617                     (registered={reg}, reproj={reproj:.3} px, bearing={:.2} deg, obs={obs}, \
4618                     trans_flips={trans_flips}, floor={obs_floor}) \
4619                     from {} seeds × {} hyp configs",
4620                    bearing.to_degrees(),
4621                    candidate_seeds.len(),
4622                    hyp_flips.len()
4623                );
4624            }
4625        }
4626        best.map(|(s, _, _, _, _, _, _, _)| s)
4627    }
4628    .ok_or(GlobalReconstructionError::NoUsableEdges)?;
4629    let mut solved = solved;
4630    if tuning.repair_free_edges_from_solved_poses {
4631        if let Some(priors) = pose_priors {
4632            let pose_field: Vec<Option<Pose>> = (0..features.len())
4633                .map(|i| {
4634                    priors
4635                        .get(i)
4636                        .and_then(|p| p.clone())
4637                        .or_else(|| solved.poses.get(i).cloned().flatten())
4638                })
4639                .collect();
4640            let limit: HashSet<usize> = tuning
4641                .repair_free_edges_image_indices
4642                .iter()
4643                .copied()
4644                .collect();
4645            let (rewritten, flipped) = repair_free_incident_edges_from_poses(
4646                &mut edges,
4647                &pose_field,
4648                priors,
4649                tuning.repair_free_edges_only_flipped,
4650                &limit,
4651            );
4652            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() || rewritten > 0 {
4653                eprintln!(
4654                    "global-sfm: free-incident edge repair from pass-1 poses rewrote \
4655                     {rewritten} edges (flipped {flipped}); re-solving"
4656                );
4657            }
4658            if rewritten > 0 {
4659                if let Some(solution2) = solve_global_sfm_with_options(
4660                    features.len(),
4661                    &mut edges,
4662                    seed,
4663                    tuning.sweeps,
4664                    tuning.cg_iterations,
4665                    tuning.max_edge_rotation_error_deg,
4666                    tuning.refine_translations_with_global_rotations,
4667                    Some(camera),
4668                    pose_priors,
4669                    !tuning.hybrid_rotation_priors_only,
4670                    None,
4671                    false,
4672                    tuning.metric_scale_from_pose_priors,
4673                    tuning.independent_edge_scales,
4674                ) {
4675                    solved = solution2;
4676                }
4677            }
4678        }
4679    }
4680    if tuning.drop_free_edges_antipodal_to_solved {
4681        if let Some(priors) = pose_priors {
4682            let pose_field: Vec<Option<Pose>> = (0..features.len())
4683                .map(|i| {
4684                    priors
4685                        .get(i)
4686                        .and_then(|p| p.clone())
4687                        .or_else(|| solved.poses.get(i).cloned().flatten())
4688                })
4689                .collect();
4690            let limit: HashSet<usize> = tuning
4691                .repair_free_edges_image_indices
4692                .iter()
4693                .copied()
4694                .collect();
4695            let (dropped, antipodal) =
4696                drop_antipodal_free_incident_edges(&mut edges, &pose_field, priors, &limit);
4697            if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() || dropped > 0 {
4698                eprintln!(
4699                    "global-sfm: dropped {dropped} antipodal free-incident edges \
4700                     ({antipodal} flipped vs pass-1); re-solving"
4701                );
4702            }
4703            if dropped > 0 {
4704                edges.retain(|e| e.weight > 0.0);
4705                if let Some(solution2) = solve_global_sfm_with_options(
4706                    features.len(),
4707                    &mut edges,
4708                    seed,
4709                    tuning.sweeps,
4710                    tuning.cg_iterations,
4711                    tuning.max_edge_rotation_error_deg,
4712                    tuning.refine_translations_with_global_rotations,
4713                    Some(camera),
4714                    pose_priors,
4715                    !tuning.hybrid_rotation_priors_only,
4716                    None,
4717                    false,
4718                    tuning.metric_scale_from_pose_priors,
4719                    tuning.independent_edge_scales,
4720                ) {
4721                    solved = solution2;
4722                }
4723            }
4724        }
4725    }
4726    let poses = solved.poses;
4727    if !poses.iter().any(Option::is_some) {
4728        return Err(GlobalReconstructionError::NoUsableEdges);
4729    }
4730
4731    // ---- Triangulate tracks against the averaged cameras -------------------
4732    let built = build_track_output(features, pairwise, mapper, Some(camera));
4733    let tracks = built.tracks;
4734    let mut track_point = vec![None; tracks.len()];
4735    let mut poses = poses;
4736    triangulate_pending(camera, features, &tracks, &poses, mapper, &mut track_point);
4737
4738    // ---- One joint bundle adjustment ---------------------------------------
4739    let _ba_result = run_bundle_adjustment(
4740        camera,
4741        features,
4742        &tracks,
4743        mapper,
4744        &mut poses,
4745        &mut track_point,
4746        false,
4747    )
4748    .map_err(|error| GlobalReconstructionError::Ba(error.to_string()))?;
4749
4750    if tuning.repnp_free_cameras_from_priors {
4751        if let Some(priors) = pose_priors {
4752            let min_corrs = if tuning.repnp_free_min_corrs > 0 {
4753                tuning.repnp_free_min_corrs
4754            } else {
4755                mapper.min_pnp_inliers
4756            };
4757            // Soft-anchors: free cameras that we preferred E for (hub stems)
4758            // count as structure anchors so a dropped hub (DSC_0296) can still
4759            // support its neighbour free cameras.
4760            let mut anchors = priors.to_vec();
4761            for &idx in &tuning.prefer_essential_edge_image_indices {
4762                if idx < anchors.len() && anchors[idx].is_none() {
4763                    if let Some(pose) = poses.get(idx).and_then(|p| p.as_ref()) {
4764                        anchors[idx] = Some(pose.clone());
4765                    }
4766                }
4767            }
4768            let n = repnp_free_cameras_from_prior_structure(
4769                camera,
4770                features,
4771                &tracks,
4772                &track_point,
4773                &mut poses,
4774                &anchors,
4775                mapper,
4776                min_corrs,
4777            );
4778            if n > 0 {
4779                if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
4780                    eprintln!(
4781                        "global-sfm debug: re-PnP replaced {n} free camera(s) from prior structure"
4782                    );
4783                }
4784                let _ = run_bundle_adjustment(
4785                    camera,
4786                    features,
4787                    &tracks,
4788                    mapper,
4789                    &mut poses,
4790                    &mut track_point,
4791                    false,
4792                )
4793                .map_err(|error| GlobalReconstructionError::Ba(error.to_string()))?;
4794            }
4795        }
4796    }
4797
4798    // ---- Residual PnP for images outside the view-graph component ----------
4799    // Same post-BA pass the incremental mapper uses: 2D–3D correspondences
4800    // from tracks that already have triangulated points. Courtyard's missing
4801    // DSC_0308 is typically disconnected from rotation averaging but may
4802    // still see enough reconstructed structure to register.
4803    let rescued = post_refinement_registration_pass(
4804        camera,
4805        features,
4806        &tracks,
4807        mapper,
4808        &mut poses,
4809        &mut track_point,
4810    )
4811    .map_err(|error| GlobalReconstructionError::Ba(error.to_string()))?;
4812    if rescued > 0 {
4813        if std::env::var_os("VISLOC_GLOBAL_DEBUG").is_some() {
4814            eprintln!("global-sfm debug: residual PnP registered {rescued} leftover image(s)");
4815        }
4816        let _ = run_bundle_adjustment(
4817            camera,
4818            features,
4819            &tracks,
4820            mapper,
4821            &mut poses,
4822            &mut track_point,
4823            false,
4824        )
4825        .map_err(|error| GlobalReconstructionError::Ba(error.to_string()))?;
4826    }
4827
4828    // ---- Assemble output tracks --------------------------------------------
4829    let mut out_tracks: Vec<SfmTrack> = Vec::new();
4830    let (mut reproj_sum, mut reproj_count) = (0.0f64, 0usize);
4831    for (track_id, track) in tracks.iter().enumerate() {
4832        let Some(position) = track_point[track_id] else {
4833            continue;
4834        };
4835        let mut observations = Vec::new();
4836        for &(image, kp) in track {
4837            let Some(pose) = &poses[image] else {
4838                continue;
4839            };
4840            let Some(pixel) = features[image].keypoints.get(kp).copied() else {
4841                continue;
4842            };
4843            observations.push((image, kp, pixel));
4844            if let Some(error) = reprojection_error_px(camera, pose, &position, &pixel) {
4845                reproj_sum += error;
4846                reproj_count += 1;
4847            }
4848        }
4849        if observations.len() >= 2.min(mapper.min_track_length) {
4850            out_tracks.push(SfmTrack {
4851                position,
4852                observations,
4853            });
4854        }
4855    }
4856    let mean_reprojection_px = if reproj_count > 0 {
4857        reproj_sum / reproj_count as f64
4858    } else {
4859        f64::NAN
4860    };
4861    Ok((poses, out_tracks, mean_reprojection_px))
4862}
4863
4864#[cfg(test)]
4865mod tests {
4866    use super::*;
4867    use nalgebra::Point2;
4868
4869    /// Project a world point into a pose; `None` if behind camera or off-image.
4870    fn project_point(camera: &Camera, pose: &Pose, p: &Point3<f64>) -> Option<Point2<f64>> {
4871        let cam = pose.transform_world_point(p);
4872        if cam.z <= 0.05 {
4873            return None;
4874        }
4875        let px = camera.project(&cam)?;
4876        if px.x < 0.0 || px.x >= camera.width as f64 || px.y < 0.0 || px.y >= camera.height as f64 {
4877            return None;
4878        }
4879        Some(Point2::new(px.x, px.y))
4880    }
4881
4882    /// A synthetic ring scene with rendered features and ground-truth
4883    /// pairwise matches across every co-observing pair — the global SfM
4884    /// end-to-end fixture (mirrors `incremental_sfm`'s own test scene).
4885    struct E2eScene {
4886        camera: Camera,
4887        gt_poses: Vec<Pose>,
4888        features: Vec<FeatureSet>,
4889        pairwise: Vec<PairwiseMatches>,
4890    }
4891
4892    fn build_e2e_scene(n: usize, radius: f64) -> E2eScene {
4893        use visloc_vision::features::FeatureSet as FS;
4894        // Point cloud around the origin.
4895        let mut points = Vec::new();
4896        for xi in -2..=2 {
4897            for yi in -2..=2 {
4898                for zi in 0..=2 {
4899                    points.push(Point3::new(
4900                        xi as f64 * 0.3,
4901                        yi as f64 * 0.3,
4902                        zi as f64 * 0.3,
4903                    ));
4904                }
4905            }
4906        }
4907        let camera = Camera::pinhole(0, 640, 480, 500.0, 500.0, 320.0, 240.0);
4908        let mut gt_poses = Vec::new();
4909        for k in 0..n {
4910            let angle = std::f64::consts::TAU * k as f64 / n as f64;
4911            let center = Point3::new(radius * angle.sin(), 0.0, -radius * angle.cos());
4912            let forward = (Point3::origin() - center).normalize();
4913            let world_up = Vector3::new(0.0, 1.0, 0.0);
4914            let right = forward.cross(&world_up).normalize();
4915            let up = right.cross(&forward);
4916            let r_c2w = nalgebra::Matrix3::from_columns(&[right, -up, forward]);
4917            let q_w2c = UnitQuaternion::from_rotation_matrix(
4918                &nalgebra::Rotation3::from_matrix_unchecked(r_c2w),
4919            )
4920            .inverse();
4921            let t_w2c = -(q_w2c * center.coords);
4922            gt_poses.push(Pose::from_world_to_camera(q_w2c, t_w2c));
4923        }
4924        let mut features = Vec::new();
4925        // Keep the rendered correspondence order deterministic. Randomized
4926        // HashMap iteration changes the samples seen by the two-view solver
4927        // between test processes, even though the scene itself is fixed.
4928        let mut visible: Vec<std::collections::BTreeMap<usize, usize>> = Vec::new();
4929        for pose in &gt_poses {
4930            let (kps, descs): (Vec<_>, Vec<_>) = points
4931                .iter()
4932                .enumerate()
4933                .filter_map(|(pidx, p)| {
4934                    project_point(&camera, pose, p).map(|px| (px, vec![pidx as f32, 1.0, 0.0, 0.0]))
4935                })
4936                .unzip();
4937            visible.push(
4938                points
4939                    .iter()
4940                    .enumerate()
4941                    .filter_map(|(pidx, p)| project_point(&camera, pose, p).map(|px| (pidx, px)))
4942                    .enumerate()
4943                    .map(|(kidx, (pidx, _))| (pidx, kidx))
4944                    .collect(),
4945            );
4946            features.push(FS::new(kps, descs).unwrap());
4947        }
4948        let mut pairwise = Vec::new();
4949        for i in 0..n {
4950            for j in (i + 1)..n {
4951                let mut matches = Vec::new();
4952                for (&pidx, &ki) in &visible[i] {
4953                    if let Some(&kj) = visible[j].get(&pidx) {
4954                        matches.push((ki, kj));
4955                    }
4956                }
4957                if matches.len() >= 8 {
4958                    pairwise.push(PairwiseMatches {
4959                        image_i: i,
4960                        image_j: j,
4961                        matches,
4962                        two_view_config: None,
4963                        essential_matches: None,
4964                        essential_matrix: None,
4965                    });
4966                }
4967            }
4968        }
4969        E2eScene {
4970            camera,
4971            gt_poses,
4972            features,
4973            pairwise,
4974        }
4975    }
4976
4977    #[test]
4978    fn reconstruct_global_sfm_end_to_end_recovers_the_ring() {
4979        let n = 6usize;
4980        let scene = build_e2e_scene(n, 3.0);
4981        assert!(
4982            scene.pairwise.len() >= n,
4983            "fixture sanity: the full ring must be connected"
4984        );
4985        let tuning = GlobalReconstructionTuning::default();
4986        let mapper = crate::incremental_sfm::IncrementalSfmConfig {
4987            min_track_length: 3,
4988            max_reprojection_error_px: 2.0,
4989            ..crate::incremental_sfm::IncrementalSfmConfig::default()
4990        };
4991        let (poses, tracks, mean_reproj) = reconstruct_global_sfm(
4992            &scene.camera,
4993            &scene.features,
4994            &scene.pairwise,
4995            &tuning,
4996            &mapper,
4997        )
4998        .expect("global reconstruction succeeds on the synthetic ring");
4999        assert_eq!(poses.iter().filter(|p| p.is_some()).count(), n);
5000        assert!(
5001            tracks.len() >= 20,
5002            "expected a dense track set, got {}",
5003            tracks.len()
5004        );
5005        assert!(
5006            mean_reproj.is_finite() && mean_reproj < 0.5,
5007            "mean reprojection {mean_reproj:.3} px too high"
5008        );
5009        // Gauge: the solver frame is camera 0's frame; rotations must match
5010        // R_i·R_0⁻¹ and centres up to one global scale.
5011        let gauge = scene.gt_poses[0].world_to_camera.rotation.inverse();
5012        for (image, pose) in poses.iter().enumerate() {
5013            let pose = pose.as_ref().unwrap();
5014            let expected = scene.gt_poses[image].world_to_camera.rotation * gauge;
5015            let rot_err = (pose.world_to_camera.rotation.inverse() * expected).angle();
5016            assert!(rot_err < 1e-2, "image {image} rotation error {rot_err} rad");
5017        }
5018        let c_est = |i: usize| poses[i].as_ref().unwrap().camera_center_world();
5019        let baseline_est = (c_est(0) - c_est(1)).norm();
5020        let r0 = scene.gt_poses[0].world_to_camera.rotation;
5021        let c0 = scene.gt_poses[0].camera_center_world();
5022        let scale = (r0 * (scene.gt_poses[1].camera_center_world() - c0)).norm() / baseline_est;
5023        for image in 0..n {
5024            let expected = r0 * (scene.gt_poses[image].camera_center_world() - c0);
5025            let err = (c_est(image) * scale - expected).coords.norm();
5026            assert!(err < 5e-2, "image {image} centre error {err} after scaling");
5027        }
5028    }
5029
5030    #[test]
5031    fn filter_pose_priors_drops_sparse_high_reproj_cameras() {
5032        use visloc_core::types::Camera;
5033        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
5034        let pose_a = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
5035        let pose_b = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::x());
5036        let priors = vec![Some(pose_a), Some(pose_b)];
5037        let tracks = vec![
5038            SfmTrack {
5039                position: Point3::new(0.0, 0.0, 5.0),
5040                observations: (0..60).map(|_| (0, 0, Point2::new(320.0, 240.0))).collect(),
5041            },
5042            SfmTrack {
5043                position: Point3::new(0.1, 0.0, 5.0),
5044                observations: vec![(1, 0, Point2::new(330.0, 240.0)); 3],
5045            },
5046        ];
5047        let (filtered, kept) =
5048            filter_pose_priors_by_track_quality(&camera, &priors, &tracks, 50, 0.45);
5049        assert_eq!(kept, 1);
5050        assert!(filtered[0].is_some());
5051        assert!(filtered[1].is_none());
5052    }
5053
5054    #[test]
5055    fn filter_pose_priors_by_edge_disagreement_drops_flipped_hub() {
5056        // Star of 3 cameras: essentials place hub 1 at (+1,0); prior puts it
5057        // at (−3,4) so both incident bearings flip → hub is dropped.
5058        let q = UnitQuaternion::identity();
5059        let pose = |c: Vector3<f64>| Pose::from_world_to_camera(q, -c);
5060        let priors = vec![
5061            Some(pose(Vector3::new(0.0, 0.0, 0.0))),
5062            Some(pose(Vector3::new(-3.0, 4.0, 0.0))),
5063            Some(pose(Vector3::new(0.0, 2.0, 0.0))),
5064        ];
5065        let edges = vec![
5066            GlobalSfmEdge {
5067                image_i: 0,
5068                image_j: 1,
5069                rotation_ij: q,
5070                direction_ij: Vector3::x(),
5071                weight: 100.0,
5072                inlier_sample: Vec::new(),
5073                rotation_alt: None,
5074                direction_alt: None,
5075            },
5076            GlobalSfmEdge {
5077                image_i: 2,
5078                image_j: 1,
5079                rotation_ij: q,
5080                direction_ij: Vector3::new(1.0, -2.0, 0.0).normalize(),
5081                weight: 100.0,
5082                inlier_sample: Vec::new(),
5083                rotation_alt: None,
5084                direction_alt: None,
5085            },
5086        ];
5087        let (filtered, kept) = filter_pose_priors_by_edge_disagreement(&priors, &edges, 2, 0.5, 1);
5088        assert_eq!(kept, 2);
5089        assert!(filtered[1].is_none(), "bent hub must be dropped");
5090        assert!(filtered[0].is_some());
5091        assert!(filtered[2].is_some());
5092    }
5093
5094    #[test]
5095    fn filter_pose_priors_by_free_centre_residual_drops_outlier() {
5096        let q = UnitQuaternion::identity();
5097        let pose = |c: Vector3<f64>| Pose::from_world_to_camera(q, -c);
5098        let priors = vec![
5099            Some(pose(Vector3::new(0.0, 0.0, 0.0))),
5100            Some(pose(Vector3::new(1.0, 0.0, 0.0))),
5101            Some(pose(Vector3::new(2.0, 0.0, 0.0))),
5102            Some(pose(Vector3::new(3.0, 0.0, 0.0))),
5103        ];
5104        // Free centres match priors except camera 1 is far off.
5105        let free = vec![
5106            Some(Point3::new(0.0, 0.0, 0.0)),
5107            Some(Point3::new(1.0, 5.0, 0.0)),
5108            Some(Point3::new(2.0, 0.0, 0.0)),
5109            Some(Point3::new(3.0, 0.0, 0.0)),
5110        ];
5111        let (filtered, kept) = filter_pose_priors_by_free_centre_residual(&priors, &free, 1, 2.0);
5112        assert_eq!(kept, 3);
5113        assert!(filtered[1].is_none());
5114        assert!(filtered[0].is_some() && filtered[2].is_some() && filtered[3].is_some());
5115    }
5116
5117    #[test]
5118    fn rotation_only_priors_keep_global_centres_not_incremental() {
5119        let n = 6usize;
5120        let (gt_poses, edges) = ring_scene(n, 3.0);
5121        let bad = 2usize;
5122        let gt_c = gt_poses[bad].camera_center_world();
5123        let wrong_c = gt_c + Vector3::new(5.0, 0.0, 0.0);
5124        let p = &gt_poses[bad];
5125        let wrong_prior = Pose::from_world_to_camera(
5126            p.world_to_camera.rotation,
5127            -p.world_to_camera.rotation.transform_vector(&wrong_c.coords),
5128        );
5129        let priors: Vec<Option<Pose>> = gt_poses
5130            .iter()
5131            .enumerate()
5132            .map(|(i, pose)| {
5133                if i == bad {
5134                    Some(wrong_prior.clone())
5135                } else {
5136                    Some(pose.clone())
5137                }
5138            })
5139            .collect();
5140        let mut edges_full = edges.clone();
5141        let full = solve_global_sfm(
5142            n,
5143            &mut edges_full,
5144            0,
5145            12,
5146            400,
5147            10.0,
5148            false,
5149            None,
5150            Some(&priors),
5151            true,
5152            None,
5153            false,
5154            false,
5155        )
5156        .unwrap();
5157        let mut edges_rot = edges;
5158        let rot_only = solve_global_sfm(
5159            n,
5160            &mut edges_rot,
5161            0,
5162            12,
5163            400,
5164            10.0,
5165            false,
5166            None,
5167            Some(&priors),
5168            false,
5169            None,
5170            false,
5171            false,
5172        )
5173        .unwrap();
5174        let full_c = full.poses[bad].as_ref().unwrap().camera_center_world();
5175        let rot_c = rot_only.poses[bad].as_ref().unwrap().camera_center_world();
5176        assert!(
5177            (full_c - wrong_c).norm() < 1e-3,
5178            "full priors must pin wrong incremental centre"
5179        );
5180        assert!(
5181            (rot_c - gt_c).norm() < (rot_c - wrong_c).norm(),
5182            "rotation-only {rot_c:?} should be closer to GT {gt_c:?} than wrong {wrong_c:?}"
5183        );
5184        assert!(
5185            (rot_c - gt_c).norm() < 0.5,
5186            "rotation-only should recover ring geometry within 50 cm"
5187        );
5188    }
5189
5190    #[test]
5191    fn calibrated_view_edges_only_skips_uncalibrated_pairs() {
5192        let n = 6usize;
5193        let mut scene = build_e2e_scene(n, 3.0);
5194        for pair in &mut scene.pairwise {
5195            pair.two_view_config = Some(ConfigurationType::Uncalibrated);
5196        }
5197        let mapper = crate::incremental_sfm::IncrementalSfmConfig {
5198            min_track_length: 3,
5199            max_reprojection_error_px: 2.0,
5200            ..crate::incremental_sfm::IncrementalSfmConfig::default()
5201        };
5202        let blocked = GlobalReconstructionTuning {
5203            calibrated_view_edges_only: true,
5204            ..GlobalReconstructionTuning::default()
5205        };
5206        let err = reconstruct_global_sfm(
5207            &scene.camera,
5208            &scene.features,
5209            &scene.pairwise,
5210            &blocked,
5211            &mapper,
5212        );
5213        assert_eq!(err, Err(GlobalReconstructionError::NoUsableEdges));
5214
5215        for pair in &mut scene.pairwise {
5216            pair.two_view_config = Some(ConfigurationType::Calibrated);
5217        }
5218        let (poses, _, _) = reconstruct_global_sfm(
5219            &scene.camera,
5220            &scene.features,
5221            &scene.pairwise,
5222            &blocked,
5223            &mapper,
5224        )
5225        .expect("calibrated configs remain usable");
5226        assert_eq!(poses.iter().filter(|p| p.is_some()).count(), n);
5227
5228        // Uncalibrated config with a strong essential subset must still pass
5229        // the calibrated-only gate (courtyard F-won / E-bearing bridges).
5230        for pair in &mut scene.pairwise {
5231            pair.two_view_config = Some(ConfigurationType::Uncalibrated);
5232            pair.essential_matches = Some(pair.matches.clone());
5233        }
5234        let (poses_e, _, _) = reconstruct_global_sfm(
5235            &scene.camera,
5236            &scene.features,
5237            &scene.pairwise,
5238            &blocked,
5239            &mapper,
5240        )
5241        .expect("uncalibrated+essential remains usable");
5242        assert_eq!(poses_e.iter().filter(|p| p.is_some()).count(), n);
5243    }
5244
5245    #[test]
5246    fn reconstruct_global_sfm_reports_no_usable_edges_on_disconnected_input() {
5247        let scene = build_e2e_scene(4, 3.0);
5248        // Keep only pairs among images {0, 1}; images 2 and 3 become islands.
5249        let pairwise: Vec<PairwiseMatches> = scene
5250            .pairwise
5251            .iter()
5252            .filter(|p| p.image_i <= 1 && p.image_j <= 1)
5253            .cloned()
5254            .collect();
5255        let tuning = GlobalReconstructionTuning::default();
5256        // Two-image component can only form length-2 tracks.
5257        let mapper = crate::incremental_sfm::IncrementalSfmConfig {
5258            min_track_length: 2,
5259            ..crate::incremental_sfm::IncrementalSfmConfig::default()
5260        };
5261        let (poses, _tracks, _mean) =
5262            reconstruct_global_sfm(&scene.camera, &scene.features, &pairwise, &tuning, &mapper)
5263                .expect("the connected pair still solves");
5264        assert!(poses[0].is_some() && poses[1].is_some());
5265        assert!(
5266            poses[2].is_none() && poses[3].is_none(),
5267            "islands stay unposed"
5268        );
5269    }
5270
5271    /// Deterministic pseudo-random unit vector.
5272    fn rand_unit(rng: &mut u64) -> Vector3<f64> {
5273        let next = |rng: &mut u64| {
5274            *rng = rng
5275                .wrapping_mul(6364136223846793005)
5276                .wrapping_add(1442695040888963407);
5277            ((*rng >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
5278        };
5279        loop {
5280            let v = Vector3::new(next(rng), next(rng), next(rng));
5281            let n = v.norm();
5282            if n.is_finite() && n > 1e-3 {
5283                return v / n;
5284            }
5285        }
5286    }
5287
5288    fn random_rotation(rng: &mut u64) -> UnitQuaternion<f64> {
5289        let axis = nalgebra::Unit::new_normalize(rand_unit(rng));
5290        let angle = next_u01(rng) * std::f64::consts::PI;
5291        UnitQuaternion::from_axis_angle(&axis, angle)
5292    }
5293
5294    fn next_u01(rng: &mut u64) -> f64 {
5295        *rng = rng
5296            .wrapping_mul(6364136223846793005)
5297            .wrapping_add(1442695040888963407);
5298        (*rng >> 11) as f64 / (1u64 << 53) as f64
5299    }
5300
5301    /// A ring of `n` cameras at radius `radius` looking at the origin, with
5302    /// exact pairwise edges (rotation + bearing direction derived from GT).
5303    fn ring_scene(n: usize, radius: f64) -> (Vec<Pose>, Vec<GlobalSfmEdge>) {
5304        let mut poses = Vec::new();
5305        for k in 0..n {
5306            let angle = std::f64::consts::TAU * k as f64 / n as f64;
5307            let center = Point3::new(radius * angle.sin(), 0.0, -radius * angle.cos());
5308            let forward = (Point3::origin() - center).normalize();
5309            let world_up = Vector3::new(0.0, 1.0, 0.0);
5310            let right = forward.cross(&world_up).normalize();
5311            let up = right.cross(&forward);
5312            let r_c2w = nalgebra::Matrix3::from_columns(&[right, -up, forward]);
5313            let q_w2c = UnitQuaternion::from_rotation_matrix(
5314                &nalgebra::Rotation3::from_matrix_unchecked(r_c2w),
5315            )
5316            .inverse();
5317            let t_w2c = -(q_w2c * center.coords);
5318            poses.push(Pose::from_world_to_camera(q_w2c, t_w2c));
5319        }
5320        let mut edges = Vec::new();
5321        for i in 0..n {
5322            // Consecutive neighbour plus one skip edge per camera.
5323            for &skip in &[1usize, 2] {
5324                let j = (i + skip) % n;
5325                if j == i
5326                    || edges.iter().any(|e: &GlobalSfmEdge| {
5327                        (e.image_i == j && e.image_j == i) || (e.image_i == i && e.image_j == j)
5328                    })
5329                {
5330                    continue;
5331                }
5332                let ci = poses[i].camera_center_world();
5333                let cj = poses[j].camera_center_world();
5334                let r_i = poses[i].world_to_camera.rotation;
5335                let r_j = poses[j].world_to_camera.rotation;
5336                let rotation_ij = r_j * r_i.inverse();
5337                let direction_world = cj - ci;
5338                let direction_ij = r_i.transform_vector(&direction_world).normalize();
5339                edges.push(GlobalSfmEdge {
5340                    image_i: i,
5341                    image_j: j,
5342                    rotation_ij,
5343                    direction_ij,
5344                    weight: 100.0,
5345                    inlier_sample: Vec::new(),
5346                    rotation_alt: None,
5347                    direction_alt: None,
5348                });
5349            }
5350        }
5351        (poses, edges)
5352    }
5353
5354    #[test]
5355    fn prior_edge_repair_unflips_prior_pair_direction() {
5356        let n = 6usize;
5357        let (gt_poses, mut edges) = ring_scene(n, 3.0);
5358        // Flip the 0-1 edge direction (both will be priors).
5359        let target = edges
5360            .iter_mut()
5361            .find(|e| (e.image_i == 0 && e.image_j == 1) || (e.image_i == 1 && e.image_j == 0))
5362            .expect("ring has 0-1 edge");
5363        let before = target.direction_ij;
5364        target.direction_ij = -before;
5365        let priors: Vec<Option<Pose>> = gt_poses.iter().cloned().map(Some).collect();
5366        let mut weights: Vec<f64> = edges.iter().map(|e| e.weight).collect();
5367        let (rewritten, flipped) = repair_edges_from_pose_priors(&mut edges, &mut weights, &priors);
5368        assert!(
5369            rewritten >= n,
5370            "every consecutive prior pair should rewrite"
5371        );
5372        assert!(
5373            flipped >= 1,
5374            "the deliberately flipped edge must be counted"
5375        );
5376        let fixed = edges
5377            .iter()
5378            .find(|e| (e.image_i == 0 && e.image_j == 1) || (e.image_i == 1 && e.image_j == 0))
5379            .unwrap();
5380        assert!(
5381            fixed.direction_ij.dot(&before) > 0.9,
5382            "repaired direction should match the original prior-consistent bearing"
5383        );
5384    }
5385
5386    #[test]
5387    fn free_incident_edge_repair_uses_solved_poses() {
5388        let n = 6usize;
5389        let (gt_poses, mut edges) = ring_scene(n, 3.0);
5390        // Priors on 0..3; free on 3..6 — use 0,1,2 as priors
5391        let priors: Vec<Option<Pose>> = (0..n)
5392            .map(|i| {
5393                if i < 3 {
5394                    Some(gt_poses[i].clone())
5395                } else {
5396                    None
5397                }
5398            })
5399            .collect();
5400        let pose_field: Vec<Option<Pose>> = gt_poses.iter().cloned().map(Some).collect();
5401        // Flip a free-incident edge 2-4
5402        let target = edges
5403            .iter_mut()
5404            .find(|e| (e.image_i == 2 && e.image_j == 4) || (e.image_i == 4 && e.image_j == 2))
5405            .expect("ring has 2-4 edge");
5406        let before = target.direction_ij;
5407        target.direction_ij = -before;
5408        let (rewritten, flipped) = repair_free_incident_edges_from_poses(
5409            &mut edges,
5410            &pose_field,
5411            &priors,
5412            false,
5413            &HashSet::new(),
5414        );
5415        assert!(rewritten >= 1);
5416        assert!(flipped >= 1);
5417        let fixed = edges
5418            .iter()
5419            .find(|e| (e.image_i == 2 && e.image_j == 4) || (e.image_i == 4 && e.image_j == 2))
5420            .unwrap();
5421        assert!(fixed.direction_ij.dot(&before) > 0.9);
5422    }
5423
5424    #[test]
5425    fn global_sfm_recovers_ring_rotations_and_center_geometry() {
5426        let n = 12usize;
5427        let (gt_poses, edges) = ring_scene(n, 3.0);
5428        let mut edges = edges;
5429        let result = solve_global_sfm(
5430            n, &mut edges, 0, 16, 400, 10.0, false, None, None, true, None, false, false,
5431        )
5432        .expect("graph is usable");
5433        // Every camera solved; rotations match GT directly (seed pins the
5434        // gauge frame), centre geometry matches up to the monocular scale.
5435        // The solver's world frame is camera 0's frame (seed w2c = identity),
5436        // so the gauge-corrected ground truth is R_i ∘ R_0⁻¹.
5437        let gauge = gt_poses[0].world_to_camera.rotation.inverse();
5438        for (image, pose) in result.poses.iter().enumerate() {
5439            let pose = pose
5440                .as_ref()
5441                .unwrap_or_else(|| panic!("image {image} unposed"));
5442            let expected = gt_poses[image].world_to_camera.rotation * gauge;
5443            let rot_err = (pose.world_to_camera.rotation.inverse() * expected).angle();
5444            assert!(rot_err < 1e-3, "image {image} rotation error {rot_err} rad");
5445        }
5446        // Centres: map GT into the solver frame (camera 0 at origin, its
5447        // axes as world axes) and align the monocular global scale on a
5448        // baseline pair before comparing.
5449        let r0 = gt_poses[0].world_to_camera.rotation;
5450        let c0 = gt_poses[0].camera_center_world();
5451        let mapped: Vec<Point3<f64>> = (0..n)
5452            .map(|i| Point3::from(r0 * (gt_poses[i].camera_center_world() - c0)))
5453            .collect();
5454        let baseline_true = (mapped[0] - mapped[1]).norm();
5455        let baseline_est = (result.poses[0].as_ref().unwrap().camera_center_world()
5456            - result.poses[1].as_ref().unwrap().camera_center_world())
5457        .norm();
5458        let scale = baseline_true / baseline_est;
5459        for (est, expected) in result.poses.iter().zip(mapped.iter()) {
5460            let est = est.as_ref().unwrap().camera_center_world() * scale;
5461            let err = (est - expected).norm();
5462            assert!(err < 5e-3, "centre error {err} after scaling");
5463        }
5464        assert!(
5465            result.mean_bearing_residual_rad < 1e-3,
5466            "bearing residual {}",
5467            result.mean_bearing_residual_rad
5468        );
5469    }
5470
5471    #[test]
5472    fn global_sfm_leaves_disconnected_images_unposed() {
5473        let (_poses, mut edges) = ring_scene(8, 3.0);
5474        // Drop every edge touching image 7: the ring becomes a chain over 0..7
5475        // plus an isolated vertex. Rebuild edges only among 0..=6.
5476        edges.retain(|e| e.image_i != 7 && e.image_j != 7);
5477        let result = solve_global_sfm(
5478            9, &mut edges, 0, 12, 300, 10.0, false, None, None, true, None, false, false,
5479        )
5480        .expect("graph is usable");
5481        for image in 0..7 {
5482            assert!(result.poses[image].is_some(), "image {image} should solve");
5483        }
5484        assert!(
5485            result.poses[7].is_none(),
5486            "isolated image must stay unposed"
5487        );
5488        assert!(
5489            result.poses[8].is_none(),
5490            "out-of-range image must stay unposed"
5491        );
5492    }
5493
5494    #[test]
5495    fn global_sfm_survives_small_edge_noise() {
5496        let n = 10usize;
5497        let (_gt_poses, edges) = ring_scene(n, 3.0);
5498        let mut rng = 42u64;
5499        let noisy: Vec<GlobalSfmEdge> = edges
5500            .iter()
5501            .map(|edge| {
5502                let jitter_axis = nalgebra::Unit::new_normalize(rand_unit(&mut rng));
5503                let jitter = UnitQuaternion::from_axis_angle(
5504                    &jitter_axis,
5505                    (next_u01(&mut rng) - 0.5) * 0.02,
5506                );
5507                GlobalSfmEdge {
5508                    rotation_ij: jitter * edge.rotation_ij,
5509                    direction_ij: (edge.direction_ij + rand_unit(&mut rng) * 0.02).normalize(),
5510                    ..edge.clone()
5511                }
5512            })
5513            .collect();
5514        let mut noisy = noisy;
5515        let result = solve_global_sfm(
5516            n, &mut noisy, 0, 16, 600, 10.0, false, None, None, true, None, false, false,
5517        )
5518        .unwrap();
5519        assert!(
5520            result.mean_bearing_residual_rad < 0.15,
5521            "residual {} too large under small noise",
5522            result.mean_bearing_residual_rad
5523        );
5524        for (image, pose) in result.poses.iter().enumerate() {
5525            assert!(pose.is_some(), "image {image} dropped under small noise");
5526        }
5527    }
5528
5529    #[test]
5530    fn rotation_averaging_converges_from_inconsistent_tree_seed() {
5531        // Three cameras, fully connected with EXACT edges — but the tree seed
5532        // uses only two of them, so the third starts inconsistent and the
5533        // consensus sweeps must pull it to the exact solution (which here is
5534        // globally consistent by construction).
5535        let (poses, edges) = ring_scene(3, 3.0);
5536        let adjacency = build_adjacency(3, &edges).unwrap();
5537        let averaged = average_rotations(3, &edges, &adjacency, 0, 24, 10.0).0;
5538        let gauge = poses[0].world_to_camera.rotation.inverse();
5539        for (image, rotation) in averaged.iter().enumerate() {
5540            let q = rotation.expect("all three cameras reachable");
5541            let expected = poses[image].world_to_camera.rotation * gauge;
5542            let err = (q.inverse() * expected).angle();
5543            assert!(err < 1e-6, "image {image} rotation error {err}");
5544        }
5545    }
5546
5547    #[test]
5548    fn position_averaging_recovers_collinear_and_offaxis_centers() {
5549        // Four centres forming a tetrahedron-ish configuration; directions
5550        // and rotations consistent with GT. The unit-displacement rows give a
5551        // well-posed scale.
5552        let gt_centers = [
5553            Point3::new(0.0f64, 0.0, 0.0),
5554            Point3::new(1.5, 0.2, -0.3),
5555            Point3::new(-0.4, 1.1, 0.5),
5556            Point3::new(0.3, -0.6, 1.4),
5557        ];
5558        // Identity world-to-camera rotations keep the frame mapping trivial:
5559        // bearings equal world displacement directions.
5560        let identity: Vec<Option<UnitQuaternion<f64>>> = vec![Some(UnitQuaternion::identity()); 4];
5561        let mut edges = Vec::new();
5562        for (i, _) in gt_centers.iter().enumerate() {
5563            for j in (i + 1)..4 {
5564                let d = gt_centers[j] - gt_centers[i];
5565                edges.push(GlobalSfmEdge {
5566                    image_i: i,
5567                    image_j: j,
5568                    rotation_ij: UnitQuaternion::identity(),
5569                    direction_ij: d.normalize(),
5570                    weight: 10.0,
5571                    inlier_sample: Vec::new(),
5572                    rotation_alt: None,
5573                    direction_alt: None,
5574                });
5575            }
5576        }
5577        let weights = vec![1.0; edges.len()];
5578        let positions = average_positions(&edges, &weights, &identity, 0, 500);
5579        // Gauge: seed pinned at the origin and exactly one unit-displacement
5580        // scale row, so the solution equals the true configuration up to one
5581        // uniform scale. Align on camera 1 and verify the rest.
5582        let s = (gt_centers[1] - gt_centers[0]).norm()
5583            / (positions[1].expect("member") - positions[0].expect("seed")).norm();
5584        for (image, expected) in gt_centers.iter().enumerate() {
5585            let got = positions[image].expect("tetrahedron member");
5586            let err =
5587                ((got - positions[0].expect("seed")).scale(s) - (expected - gt_centers[0])).norm();
5588            assert!(err < 1e-2, "centre {image}: {err:.4} off after scaling");
5589        }
5590    }
5591
5592    #[test]
5593    fn independent_edge_scale_positions_recover_variable_baselines() {
5594        // Unlike the legacy unit-displacement formulation, this fixture has
5595        // six edges with deliberately different lengths.  A complete
5596        // four-camera bearing graph constrains the per-edge scales up to one
5597        // global gauge.
5598        let gt_centers = [
5599            Point3::new(0.0f64, 0.0, 0.0),
5600            Point3::new(1.5, 0.2, -0.3),
5601            Point3::new(-0.4, 1.1, 0.5),
5602            Point3::new(0.3, -0.6, 1.4),
5603        ];
5604        let identity: Vec<Option<UnitQuaternion<f64>>> =
5605            vec![Some(UnitQuaternion::identity()); gt_centers.len()];
5606        let mut edges = Vec::new();
5607        for i in 0..gt_centers.len() {
5608            for j in (i + 1)..gt_centers.len() {
5609                let d = gt_centers[j] - gt_centers[i];
5610                edges.push(GlobalSfmEdge {
5611                    image_i: i,
5612                    image_j: j,
5613                    rotation_ij: UnitQuaternion::identity(),
5614                    direction_ij: d.normalize(),
5615                    weight: 10.0,
5616                    inlier_sample: Vec::new(),
5617                    rotation_alt: None,
5618                    direction_alt: None,
5619                });
5620            }
5621        }
5622        let weights = vec![10.0; edges.len()];
5623        let positions =
5624            average_positions_with_independent_edge_scales(&edges, &weights, &identity, 0, 8)
5625                .expect("complete bearing graph should have full rank");
5626        let estimate = |i: usize| positions[i].expect("all cameras are reachable");
5627        let scale = (gt_centers[1] - gt_centers[0]).norm() / (estimate(1) - estimate(0)).norm();
5628        for (image, expected) in gt_centers.iter().enumerate() {
5629            let got = (estimate(image) - estimate(0)).scale(scale);
5630            let want = *expected - gt_centers[0];
5631            assert!(
5632                (got - want).norm() < 1e-6,
5633                "camera {image} differs by {:.6} m",
5634                (got - want).norm()
5635            );
5636        }
5637
5638        // The linear system is built from physical endpoints, not traversal
5639        // order.  Reversing the edge stream must preserve the solution.
5640        let mut reversed = edges.clone();
5641        reversed.reverse();
5642        let reversed_positions =
5643            average_positions_with_independent_edge_scales(&reversed, &weights, &identity, 0, 8)
5644                .expect("reordered complete bearing graph should remain solvable");
5645        for (image, _) in gt_centers.iter().enumerate() {
5646            let a = estimate(image);
5647            let b = reversed_positions[image].expect("reordered camera");
5648            assert!((a - b).norm() < 1e-8, "camera {image} changed with order");
5649        }
5650    }
5651
5652    #[test]
5653    fn independent_edge_scale_positions_reject_rank_deficient_tree() {
5654        let identity = vec![Some(UnitQuaternion::identity()); 3];
5655        let edges = vec![
5656            GlobalSfmEdge {
5657                image_i: 0,
5658                image_j: 1,
5659                rotation_ij: UnitQuaternion::identity(),
5660                direction_ij: Vector3::x(),
5661                weight: 1.0,
5662                inlier_sample: Vec::new(),
5663                rotation_alt: None,
5664                direction_alt: None,
5665            },
5666            GlobalSfmEdge {
5667                image_i: 1,
5668                image_j: 2,
5669                rotation_ij: UnitQuaternion::identity(),
5670                direction_ij: Vector3::y(),
5671                weight: 1.0,
5672                inlier_sample: Vec::new(),
5673                rotation_alt: None,
5674                direction_alt: None,
5675            },
5676        ];
5677        assert!(
5678            average_positions_with_independent_edge_scales(&edges, &[1.0, 1.0], &identity, 0, 8)
5679                .is_none(),
5680            "a tree has unconstrained edge scales and must use the legacy fallback"
5681        );
5682    }
5683
5684    #[test]
5685    fn invalid_edges_are_rejected() {
5686        let good = GlobalSfmEdge {
5687            image_i: 0,
5688            image_j: 1,
5689            rotation_ij: UnitQuaternion::identity(),
5690            direction_ij: Vector3::x(),
5691            weight: 5.0,
5692            inlier_sample: Vec::new(),
5693            rotation_alt: None,
5694            direction_alt: None,
5695        };
5696        let degenerate = GlobalSfmEdge {
5697            image_i: 0,
5698            image_j: 0,
5699            ..good.clone()
5700        };
5701        assert!(build_adjacency(2, &[degenerate]).is_none());
5702        let zero_direction = GlobalSfmEdge {
5703            direction_ij: Vector3::zeros(),
5704            ..good.clone()
5705        };
5706        assert!(build_adjacency(2, &[zero_direction]).is_none());
5707        let negative_weight = GlobalSfmEdge {
5708            weight: -1.0,
5709            ..good.clone()
5710        };
5711        assert!(build_adjacency(2, &[negative_weight]).is_none());
5712        assert!(build_adjacency(2, &[good]).is_some());
5713        let _ = random_rotation(&mut 1u64); // exercised helper stays referenced
5714    }
5715
5716    #[test]
5717    fn global_r_translation_refine_unflips_wrong_chirality() {
5718        use visloc_core::types::Camera;
5719        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
5720        // Cam0 at origin looking +Z; cam1 translated along +X by 0.5.
5721        let r = UnitQuaternion::identity();
5722        let t_cam = Vector3::new(-0.5, 0.0, 0.0); // world-to-cam translation for cam1
5723                                                  // C_1 in cam0 = -R^T t = (0.5, 0, 0)
5724        let true_dir = Vector3::new(0.5, 0.0, 0.0).normalize();
5725        let mut samples = Vec::new();
5726        for xi in -2..=2 {
5727            for yi in -2..=2 {
5728                let p = Point3::new(xi as f64 * 0.3, yi as f64 * 0.3, 4.0);
5729                let p0 = camera.project(&p).unwrap();
5730                let p1_cam = r * p + t_cam;
5731                let p1 = camera.project(&Point3::from(p1_cam)).unwrap();
5732                samples.push((p0, p1));
5733            }
5734        }
5735        assert!(samples.len() >= 8);
5736        let mut edges = [GlobalSfmEdge {
5737            image_i: 0,
5738            image_j: 1,
5739            rotation_ij: r,
5740            direction_ij: -true_dir, // deliberately flipped
5741            weight: samples.len() as f64,
5742            inlier_sample: samples,
5743            rotation_alt: None,
5744            direction_alt: None,
5745        }];
5746        let rotations = vec![Some(r), Some(r)];
5747        let weights = vec![1.0];
5748        let flipped =
5749            refine_edge_directions_under_rotations(&mut edges, &rotations, &weights, &camera);
5750        assert_eq!(flipped, 1, "must flip the wrong-chirality edge");
5751        assert!(
5752            edges[0].direction_ij.dot(&true_dir) > 0.9,
5753            "refined direction {:?} should align with {:?}",
5754            edges[0].direction_ij,
5755            true_dir
5756        );
5757    }
5758
5759    #[test]
5760    fn multi_hypothesis_rotation_averaging_picks_alternate() {
5761        // Triangle of identity cameras. Edge 0–1 and 0–2 are exact. Edge 1–2
5762        // stores a *wrong* primary rotation (90° about Z) but the correct
5763        // identity as alternate. Adaptive averaging must select the alternate
5764        // so all three orientations stay identity in the seed frame.
5765        let identity = UnitQuaternion::identity();
5766        let wrong =
5767            UnitQuaternion::from_axis_angle(&Vector3::z_axis(), std::f64::consts::FRAC_PI_2);
5768        let edges = vec![
5769            GlobalSfmEdge {
5770                image_i: 0,
5771                image_j: 1,
5772                rotation_ij: identity,
5773                direction_ij: Vector3::x(),
5774                weight: 100.0,
5775                inlier_sample: Vec::new(),
5776                rotation_alt: None,
5777                direction_alt: None,
5778            },
5779            GlobalSfmEdge {
5780                image_i: 0,
5781                image_j: 2,
5782                rotation_ij: identity,
5783                direction_ij: Vector3::y(),
5784                weight: 100.0,
5785                inlier_sample: Vec::new(),
5786                rotation_alt: None,
5787                direction_alt: None,
5788            },
5789            GlobalSfmEdge {
5790                image_i: 1,
5791                image_j: 2,
5792                rotation_ij: wrong,
5793                direction_ij: (Vector3::y() - Vector3::x()).normalize(),
5794                weight: 50.0,
5795                inlier_sample: Vec::new(),
5796                rotation_alt: Some(identity),
5797                direction_alt: Some((Vector3::y() - Vector3::x()).normalize()),
5798            },
5799        ];
5800        let adjacency = build_adjacency(3, &edges).unwrap();
5801        let averaged = average_rotations(3, &edges, &adjacency, 0, 16, 10.0).0;
5802        for (image, rotation) in averaged.iter().enumerate() {
5803            let q = rotation.expect("reachable");
5804            let err = q.angle();
5805            assert!(
5806                err < 1e-3,
5807                "image {image} should stay near identity, err={err}"
5808            );
5809        }
5810        // Without the alternate, IRLS would zero the inconsistent edge or
5811        // bend image 2 — pin that primary-only fails the tight check.
5812        let primary_only: Vec<GlobalSfmEdge> = edges
5813            .iter()
5814            .map(|e| GlobalSfmEdge {
5815                rotation_alt: None,
5816                direction_alt: None,
5817                ..e.clone()
5818            })
5819            .collect();
5820        let adjacency_po = build_adjacency(3, &primary_only).unwrap();
5821        let averaged_po = average_rotations(3, &primary_only, &adjacency_po, 0, 16, 10.0).0;
5822        // With a wrong primary and no alt, at least one non-seed rotation
5823        // drifts OR the bad edge is trimmed — either way image 2 or the
5824        // consensus is worse than the multi-hyp solve. Require multi-hyp
5825        // strictly better on image 2.
5826        let err_multi = averaged[2].unwrap().angle();
5827        let err_primary = averaged_po[2].unwrap().angle();
5828        assert!(
5829            err_multi + 1e-6 < err_primary || err_primary > 0.1,
5830            "multi-hyp err={err_multi} should beat primary-only err={err_primary}"
5831        );
5832    }
5833}