Skip to main content

visloc_mapping/
stereo_replenish.rs

1//! Per-frame stereo landmark replenishment.
2//!
3//! The stereo *bootstrap* seeds the map once at the seed frame. As the
4//! camera moves the map is only extended by whatever tracking re-observes,
5//! so long runs slowly starve the tracker of fresh landmarks. This module
6//! *replenishes* the map every frame: for each cam0 keypoint that tracking
7//! did **not** match to an existing landmark, it stereo-matches against the
8//! same-instant cam1 image (reusing [`bootstrap_stereo_landmarks`]),
9//! triangulates the survivor, and stages a two-observation
10//! [`LandmarkCandidate`] — the current frame's real detected pixel plus the
11//! matched real keypoint in an already-existing keyframe (the "anchor"). The
12//! provisional stereo point is used to predict and gate that anchor match; the
13//! [`crate::LinearTriangulator`] that runs at the next keyframe receives two
14//! honest image measurements.
15//!
16//! The anchor association is the delicate part: naively fabricating it
17//! (hardcoded keypoint index, no quality gates, no duplicate suppression) or
18//! pairing a real keypoint index with a synthetic pixel pollutes the map with
19//! bogus / over-confident landmarks. Every gate below exists to keep that
20//! association honest and the triangulation well-conditioned; each is
21//! config-gated with permissive defaults so the common case still admits
22//! plenty of fresh landmarks.
23
24use std::collections::{HashMap, HashSet};
25
26use nalgebra::Point2;
27use visloc_core::geometry::{Pose, SE3};
28use visloc_core::types::{Camera, FrameId, VisualMap};
29use visloc_vision::features::FeatureSet;
30use visloc_vision::matching::BruteForceMatcher;
31use visloc_vision::stereo_bootstrap::{bootstrap_stereo_landmarks, StereoBootstrapConfig};
32
33use crate::{LandmarkCandidate, LandmarkCandidateId, LandmarkCandidateObservation};
34
35/// Tunable knobs for [`build_stereo_replenish_candidates`].
36///
37/// Defaults are deliberately **permissive**: replenishment only helps if it
38/// actually admits new landmarks, so the gates are sized to reject
39/// clearly-degenerate / duplicate geometry without strangling recall. Values
40/// mirror [`StereoBootstrapConfig::default`]'s own gates (2.0 px reprojection,
41/// 0.1–50.0 m depth) where the two overlap.
42#[derive(Debug, Clone, PartialEq)]
43pub struct StereoReplenishConfig {
44    /// Cap on accepted candidates returned per call. Survivors are processed
45    /// in `left_keypoint_index` order (the deterministic order
46    /// [`bootstrap_stereo_landmarks`] returns), so truncation is stable.
47    pub max_candidates_per_frame: usize,
48    /// Stereo match / triangulate / reprojection gates applied to the
49    /// same-instant cam0/cam1 pair. Reused verbatim from the bootstrap path.
50    pub bootstrap_config: StereoBootstrapConfig,
51    /// Radius (px) around the reprojected anchor pixel within which a *real*
52    /// detected anchor-keyframe keypoint must exist for the candidate to be
53    /// accepted. The anchor observation uses both THAT keypoint's index and
54    /// its measured pixel coordinate; the stereo reprojection remains only a
55    /// search prediction. A few pixels of slack absorbs the accumulated
56    /// anchor-pose / current-pose error; too tight would strangle recall.
57    pub anchor_keypoint_match_radius_px: f64,
58    /// Optional descriptor-distance gate between the candidate's cam0
59    /// descriptor and the matched anchor keypoint's descriptor (L2, via
60    /// [`BruteForceMatcher::l2_distance`]). `None` (default) disables it —
61    /// the geometric radius match is usually enough, and requiring
62    /// descriptor agreement across the (often large) anchor→current baseline
63    /// noticeably cuts recall.
64    pub anchor_keypoint_max_descriptor_distance: Option<f32>,
65    /// Radius (px) for geometric duplicate suppression. Each of the anchor
66    /// keyframe's *own* existing landmark observations is reprojected into
67    /// the current frame using the current tracked pose; any stereo survivor
68    /// whose raw cam0 pixel lands within this radius of such a reprojection
69    /// is dropped as a probable duplicate of an already-mapped point. This
70    /// catches both PnP-outlier-but-really-matched keypoints and keypoints
71    /// the descriptor matcher missed entirely (the more likely driver of
72    /// duplicate landmarks). Kept small so genuinely new nearby structure
73    /// still survives.
74    pub duplicate_suppression_radius_px: f64,
75    /// Minimum parallax angle (degrees) between the ray from the anchor
76    /// camera centre to the triangulated world point and the ray from the
77    /// current camera centre to the same point. The downstream two-view
78    /// [`crate::LinearTriangulator`] re-triangulates the candidate from
79    /// exactly these two views, so a near-zero angle (stationary / tiny
80    /// baseline) yields a degenerate, depth-unstable solve. Small permissive
81    /// default; only rejects the clearly-degenerate tail.
82    pub min_parallax_deg: f64,
83    /// Minimum triangulated depth (m) in the current cam0 frame. Independent,
84    /// tunable re-check of [`StereoBootstrapConfig::min_depth_meters`].
85    pub min_depth_meters: f64,
86    /// Maximum triangulated depth (m) in the current cam0 frame. Independent,
87    /// tunable re-check of [`StereoBootstrapConfig::max_depth_meters`].
88    pub max_depth_meters: f64,
89}
90
91impl Default for StereoReplenishConfig {
92    fn default() -> Self {
93        Self {
94            // Matches the demo's historical `--stereo-landmark-replenish-max-per-frame`.
95            max_candidates_per_frame: 100,
96            bootstrap_config: StereoBootstrapConfig::default(),
97            // A few px of slack: the reprojected anchor pixel is only as
98            // accurate as the anchor + current pose estimates, so a strict
99            // 1-2 px match would reject good candidates. 5 px keeps a genuine
100            // nearby detection requirement without over-rejecting.
101            anchor_keypoint_match_radius_px: 5.0,
102            // Off by default (see field doc): descriptor agreement across the
103            // anchor→current baseline is a weak, recall-cutting signal.
104            anchor_keypoint_max_descriptor_distance: None,
105            // 3 px: two detections this close to the same reprojected existing
106            // landmark are almost certainly the same physical point; larger
107            // would suppress legitimate new structure.
108            duplicate_suppression_radius_px: 3.0,
109            // 0.5°: rejects only the near-stationary degenerate tail while
110            // keeping most genuine motion-parallax points (0.5° at 5 m depth
111            // is ~4 cm baseline).
112            min_parallax_deg: 0.5,
113            // Mirror the bootstrap depth window.
114            min_depth_meters: 0.1,
115            max_depth_meters: 50.0,
116        }
117    }
118}
119
120/// Triangulate same-instant stereo features into metric cam0-frame points,
121/// keyed by cam0 keypoint index. Unlike replenishment candidate construction,
122/// this requires neither a tracked pose nor an anchor keyframe and can run
123/// before online tracking/loop closure.
124pub fn build_stereo_metric_points(
125    cam0_camera: &Camera,
126    cam1_camera: &Camera,
127    cam0_to_cam1: &SE3,
128    cam0_features: &FeatureSet,
129    cam1_features: &FeatureSet,
130    config: &StereoReplenishConfig,
131) -> HashMap<usize, nalgebra::Point3<f64>> {
132    bootstrap_stereo_landmarks(
133        cam0_camera,
134        cam1_camera,
135        cam0_to_cam1,
136        cam0_features,
137        cam1_features,
138        &config.bootstrap_config,
139    )
140    .into_iter()
141    .filter(|survivor| {
142        let depth = survivor.point_left_camera_frame.z;
143        depth.is_finite() && depth >= config.min_depth_meters && depth <= config.max_depth_meters
144    })
145    .map(|survivor| {
146        (
147            survivor.left_keypoint_index,
148            survivor.point_left_camera_frame,
149        )
150    })
151    .collect()
152}
153
154/// Build stereo-replenishment [`LandmarkCandidate`]s for the current frame.
155///
156/// For each cam0 keypoint that tracking did not match this frame
157/// (`matched_cam0_indices` are the PnP-inlier query indices to exclude),
158/// stereo-match against `cam1_features`, triangulate, gate, and — for
159/// survivors — stage a two-observation candidate: the current frame's real
160/// detection plus the nearest gated real detection in the
161/// `anchor_frame_id` keyframe. The stereo reprojection is a prediction, not a
162/// replacement measurement.
163///
164/// Returns an empty `Vec` (bails cleanly) when the anchor keyframe, its
165/// pose, its camera, or its keypoints are missing/empty — mirroring the
166/// guard clauses of the original inline demo block.
167///
168/// Candidate ids are assigned sequentially starting at `next_candidate_id`.
169///
170/// # Gate order (per survivor)
171/// 1. matched-index exclusion (skip keypoints tracking already used),
172/// 2. geometric duplicate suppression (skip near an existing landmark's
173///    reprojection),
174/// 3. per-frame cap,
175/// 4. world point (current-pose camera-to-world) + anchor reprojection,
176/// 5. anchor in-front + image-bounds gate,
177/// 6. current-frame depth window,
178/// 7. anchor↔current parallax,
179/// 8. nearest real anchor keypoint (excluding already-claimed indices) with
180///    optional descriptor gate.
181///
182/// # Note on exclusion scope
183/// `matched_cam0_indices` only carries PnP *inliers* (the pre-RANSAC match
184/// set is not threaded out of localization), so a keypoint that really
185/// matched an existing landmark but was a PnP outlier is not in the set.
186/// The geometric duplicate-suppression gate (step 2) is what actually
187/// catches those, plus matcher misses — but only against the anchor
188/// keyframe's *own* observations, kept deliberately cheap: duplicates only
189/// visible via other nearby keyframes are not suppressed here.
190#[allow(clippy::too_many_arguments)]
191pub fn build_stereo_replenish_candidates(
192    map: &VisualMap,
193    anchor_frame_id: FrameId,
194    frame_id: FrameId,
195    cam1_camera: &Camera,
196    cam0_to_cam1: &SE3,
197    cam0_features: &FeatureSet,
198    cam1_features: &FeatureSet,
199    matched_cam0_indices: &HashSet<usize>,
200    current_pose: &Pose,
201    next_candidate_id: LandmarkCandidateId,
202    config: &StereoReplenishConfig,
203) -> Vec<LandmarkCandidate> {
204    // Guard clauses: bail cleanly if the anchor keyframe context is missing.
205    let Some(anchor_keyframe) = map.keyframes.get(&anchor_frame_id) else {
206        return Vec::new();
207    };
208    let Some(anchor_pose) = anchor_keyframe.frame.pose.as_ref() else {
209        return Vec::new();
210    };
211    // The anchor keyframe's camera is the same cam0 model used to triangulate
212    // and to reproject into both the anchor and the current frame.
213    let Some(cam0_camera) = map.cameras.get(&anchor_keyframe.frame.camera_id) else {
214        return Vec::new();
215    };
216    if anchor_keyframe.frame.keypoints.is_empty() {
217        return Vec::new();
218    }
219
220    let survivors = bootstrap_stereo_landmarks(
221        cam0_camera,
222        cam1_camera,
223        cam0_to_cam1,
224        cam0_features,
225        cam1_features,
226        &config.bootstrap_config,
227    );
228    if survivors.is_empty() {
229        return Vec::new();
230    }
231
232    // Precompute the anchor keyframe's own existing landmarks reprojected into
233    // the CURRENT frame (for geometric duplicate suppression), plus the set of
234    // anchor keypoint indices already claimed by an existing observation (so a
235    // newly associated anchor observation never collides with one). We seed
236    // `claimed_anchor_indices` with the existing observations and extend it as
237    // we accept candidates, so two survivors in this same call cannot both
238    // claim the same anchor keypoint either.
239    let mut existing_reprojections: Vec<Point2<f64>> =
240        Vec::with_capacity(anchor_keyframe.observations.len());
241    let mut claimed_anchor_indices: HashSet<usize> =
242        HashSet::with_capacity(anchor_keyframe.observations.len());
243    for observation in &anchor_keyframe.observations {
244        claimed_anchor_indices.insert(observation.keypoint_index);
245        if let Some(landmark) = map.landmarks.get(&observation.landmark_id) {
246            let point_current = current_pose.transform_world_point(&landmark.position);
247            if let Some(pixel) = cam0_camera.project(&point_current) {
248                existing_reprojections.push(pixel);
249            }
250        }
251    }
252
253    let camera_to_world = current_pose.camera_to_world();
254    let anchor_center = anchor_pose.camera_center_world();
255    let current_center = current_pose.camera_center_world();
256    let min_parallax_cos = config.min_parallax_deg.to_radians().cos();
257    let width = cam0_camera.width as f64;
258    let height = cam0_camera.height as f64;
259
260    let mut candidates: Vec<LandmarkCandidate> = Vec::new();
261    let mut next_id = next_candidate_id;
262
263    for survivor in &survivors {
264        // (3) Per-frame cap. Break rather than continue: survivors are in a
265        // stable order, so the accepted prefix is deterministic.
266        if candidates.len() >= config.max_candidates_per_frame {
267            break;
268        }
269
270        // (1) Skip keypoints tracking already matched to an existing landmark.
271        if matched_cam0_indices.contains(&survivor.left_keypoint_index) {
272            continue;
273        }
274
275        let raw_left_pixel = cam0_features.keypoints[survivor.left_keypoint_index];
276
277        // (2) Geometric duplicate suppression against the anchor keyframe's
278        // own landmarks reprojected into this frame.
279        if existing_reprojections.iter().any(|reprojection| {
280            (reprojection - raw_left_pixel).norm() <= config.duplicate_suppression_radius_px
281        }) {
282            continue;
283        }
284
285        // (4) Lift the triangulated left-frame point to the world, then into
286        // the anchor camera.
287        let world_point = camera_to_world.transform_point(&survivor.point_left_camera_frame);
288        let anchor_camera_point = anchor_pose.transform_world_point(&world_point);
289
290        // (5) In front of the anchor camera. `project` also returns `None` for
291        // z <= 0, but we check explicitly so the intent is documented and not
292        // an implicit side effect.
293        if anchor_camera_point.z <= 0.0 {
294            continue;
295        }
296        let Some(anchor_xy) = cam0_camera.project(&anchor_camera_point) else {
297            continue;
298        };
299        // Anchor reprojection must land inside the anchor image (cheap
300        // early-out before the nearest-keypoint search).
301        if anchor_xy.x < 0.0 || anchor_xy.x > width || anchor_xy.y < 0.0 || anchor_xy.y > height {
302            continue;
303        }
304
305        // (6) Current-frame depth window (independent re-check of the bootstrap
306        // depth gate).
307        let depth = survivor.point_left_camera_frame.z;
308        if !depth.is_finite() || depth < config.min_depth_meters || depth > config.max_depth_meters
309        {
310            continue;
311        }
312
313        // (7) Parallax between anchor and current views of this world point.
314        let anchor_ray = world_point - anchor_center;
315        let current_ray = world_point - current_center;
316        let anchor_ray_norm = anchor_ray.norm();
317        let current_ray_norm = current_ray.norm();
318        if anchor_ray_norm <= f64::EPSILON || current_ray_norm <= f64::EPSILON {
319            continue;
320        }
321        let cos_parallax = anchor_ray.dot(&current_ray) / (anchor_ray_norm * current_ray_norm);
322        // cos is monotonically decreasing in angle, so "angle > min" ⇔
323        // "cos < cos(min)". Clamp guards against fp overshoot past ±1.
324        if cos_parallax.clamp(-1.0, 1.0) >= min_parallax_cos {
325            continue;
326        }
327
328        // (8) Nearest real anchor keypoint within radius, excluding indices
329        // already claimed (existing observations + earlier accepted
330        // candidates this call).
331        let mut best_index: Option<usize> = None;
332        let mut best_distance = config.anchor_keypoint_match_radius_px;
333        for (index, keypoint) in anchor_keyframe.frame.keypoints.iter().enumerate() {
334            if claimed_anchor_indices.contains(&index) {
335                continue;
336            }
337            let distance = (keypoint - anchor_xy).norm();
338            if distance <= best_distance {
339                best_distance = distance;
340                best_index = Some(index);
341            }
342        }
343        let Some(anchor_keypoint_index) = best_index else {
344            // No honest real anchor keypoint nearby: drop rather than fabricate
345            // an index (defect (a)).
346            continue;
347        };
348        let anchor_measured_xy = anchor_keyframe.frame.keypoints[anchor_keypoint_index];
349
350        let candidate_descriptor = &cam0_features.descriptors[survivor.left_keypoint_index];
351
352        // Optional descriptor-distance gate on the associated anchor keypoint.
353        if let Some(max_descriptor_distance) = config.anchor_keypoint_max_descriptor_distance {
354            let Some(anchor_descriptor) =
355                anchor_keyframe.frame.descriptors.get(anchor_keypoint_index)
356            else {
357                continue;
358            };
359            match BruteForceMatcher::l2_distance(candidate_descriptor, anchor_descriptor) {
360                Some(distance) if distance <= max_descriptor_distance => {}
361                _ => continue,
362            }
363        }
364
365        claimed_anchor_indices.insert(anchor_keypoint_index);
366        let candidate_id = next_id;
367        next_id += 1;
368        let rotation_camera_to_world = camera_to_world.rotation.to_rotation_matrix().into_inner();
369        let covariance_world = rotation_camera_to_world
370            * survivor.point_covariance_left_camera_frame
371            * rotation_camera_to_world.transpose();
372        candidates.push(
373            LandmarkCandidate::new(candidate_id)
374                .with_observation(
375                    LandmarkCandidateObservation::new(
376                        frame_id,
377                        survivor.left_keypoint_index,
378                        raw_left_pixel,
379                    )
380                    .with_stereo_measurement(
381                        cam1_camera.id,
382                        cam1_features.keypoints[survivor.right_keypoint_index],
383                        cam0_to_cam1.clone(),
384                    ),
385                )
386                .with_observation(LandmarkCandidateObservation::new(
387                    anchor_frame_id,
388                    anchor_keypoint_index,
389                    anchor_measured_xy,
390                ))
391                .with_descriptor(candidate_descriptor.clone())
392                .with_position_covariance_world(covariance_world),
393        );
394    }
395
396    candidates
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402    use nalgebra::{Point2, Point3, UnitQuaternion, Vector3};
403    use visloc_core::types::{Frame, Keyframe, Landmark, Observation};
404
405    fn cam0() -> Camera {
406        Camera::pinhole(1, 752, 480, 458.0, 457.0, 367.0, 248.0)
407    }
408
409    /// cam0→cam1 pure-translation baseline along cam0 +x (EuRoC-style nominal).
410    fn cam0_to_cam1() -> SE3 {
411        SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0))
412    }
413
414    /// Identity-pose (world == camera) anchor keyframe with `keypoint_count`
415    /// keypoints laid out on a horizontal line, no observations.
416    fn anchor_keyframe(frame_id: u64, keypoints: Vec<Point2<f64>>) -> Keyframe {
417        let mut frame = Frame::new(frame_id, 1);
418        frame.descriptors = keypoints.iter().map(|_| vec![1.0_f32, 0.0]).collect();
419        frame.keypoints = keypoints;
420        frame.pose = Some(Pose::identity());
421        Keyframe {
422            frame,
423            observations: Vec::new(),
424        }
425    }
426
427    fn base_map(anchor: Keyframe) -> VisualMap {
428        let mut map = VisualMap::new();
429        map.cameras.insert(1, cam0());
430        map.keyframes.insert(anchor.frame.id, anchor);
431        map
432    }
433
434    /// Project a world point through an identity-pose cam0 to get its pixel.
435    fn project_identity(point: &Point3<f64>) -> Point2<f64> {
436        cam0().project(point).expect("in front of camera")
437    }
438
439    /// Build a synthetic same-instant cam0/cam1 stereo pair for `world_points`
440    /// viewed from `current_pose`, with one-hot descriptors so cross-check
441    /// matching is unambiguous. Returns `(cam0_features, cam1_features)`.
442    fn stereo_features(
443        world_points: &[Point3<f64>],
444        current_pose: &Pose,
445    ) -> (FeatureSet, FeatureSet) {
446        let cam = cam0();
447        let l2r = cam0_to_cam1();
448        let mut cam0_kps = Vec::new();
449        let mut cam1_kps = Vec::new();
450        let mut cam0_desc = Vec::new();
451        let mut cam1_desc = Vec::new();
452        for (i, world) in world_points.iter().enumerate() {
453            let point_left = current_pose.transform_world_point(world);
454            let point_right = l2r.transform_point(&point_left);
455            cam0_kps.push(cam.project(&point_left).expect("left in front"));
456            cam1_kps.push(cam.project(&point_right).expect("right in front"));
457            let mut desc = vec![0.0_f32; world_points.len()];
458            desc[i] = 1.0;
459            cam0_desc.push(desc.clone());
460            cam1_desc.push(desc);
461        }
462        (
463            FeatureSet::new(cam0_kps, cam0_desc).unwrap(),
464            FeatureSet::new(cam1_kps, cam1_desc).unwrap(),
465        )
466    }
467
468    /// Current pose translated `tx` metres along world +x from the anchor
469    /// (identity), so anchor↔current has a real baseline.
470    fn current_pose_shifted(tx: f64) -> Pose {
471        // world_to_camera translation of -tx puts the camera centre at +tx.
472        Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-tx, 0.0, 0.0))
473    }
474
475    #[test]
476    fn happy_path_builds_candidate_with_real_anchor_keypoint_index() {
477        let current = current_pose_shifted(0.3);
478        // One world point well in front of both anchor and current cameras.
479        let world = Point3::new(0.2, -0.1, 4.0);
480        let (cam0_features, cam1_features) = stereo_features(&[world], &current);
481
482        // Anchor keypoint list: put the real detection exactly where `world`
483        // reprojects into the identity-pose anchor, at index 2 (NOT 0), plus
484        // two decoys far away.
485        let anchor_pixel = project_identity(&world);
486        let anchor = anchor_keyframe(
487            10,
488            vec![
489                Point2::new(5.0, 5.0),
490                Point2::new(700.0, 400.0),
491                anchor_pixel,
492            ],
493        );
494        let map = base_map(anchor);
495
496        let candidates = build_stereo_replenish_candidates(
497            &map,
498            10,
499            42,
500            &cam0(),
501            &cam0_to_cam1(),
502            &cam0_features,
503            &cam1_features,
504            &HashSet::new(),
505            &current,
506            1000,
507            &StereoReplenishConfig::default(),
508        );
509
510        assert_eq!(candidates.len(), 1);
511        let candidate = &candidates[0];
512        assert_eq!(candidate.id, 1000);
513        assert_eq!(candidate.observations.len(), 2);
514        // Current-frame real observation.
515        assert_eq!(candidate.observations[0].frame_id, 42);
516        assert_eq!(candidate.observations[0].keypoint_index, 0);
517        let stereo = candidate.observations[0]
518            .stereo
519            .as_ref()
520            .expect("current observation retains its cam1 measurement");
521        assert_eq!(stereo.right_camera_id, cam0().id);
522        assert_eq!(stereo.xy_right, cam1_features.keypoints[0]);
523        assert_eq!(stereo.left_to_right, cam0_to_cam1());
524        // Anchor observation uses the REAL nearest detection at index 2.
525        assert_eq!(candidate.observations[1].frame_id, 10);
526        assert_eq!(candidate.observations[1].keypoint_index, 2);
527        assert_eq!(candidate.observations[1].xy, anchor_pixel);
528        assert!(candidate.observations[1].stereo.is_none());
529        assert!(candidate.descriptor.is_some());
530        let covariance = candidate
531            .position_covariance_world
532            .expect("stereo uncertainty is retained for downstream backend factors");
533        assert!(covariance.iter().all(|value| value.is_finite()));
534        assert!(covariance.trace() > 0.0);
535    }
536
537    #[test]
538    fn anchor_observation_uses_measured_pixel_not_stereo_prediction() {
539        let current = current_pose_shifted(0.3);
540        let world = Point3::new(0.2, -0.1, 4.0);
541        let (cam0_features, cam1_features) = stereo_features(&[world], &current);
542        let predicted = project_identity(&world);
543        // Stay inside the 5 px association radius while making the measured
544        // coordinate observably different from the stereo prediction.
545        let measured = predicted + nalgebra::Vector2::new(1.25, -0.75);
546        let map = base_map(anchor_keyframe(10, vec![measured]));
547
548        let candidates = build_stereo_replenish_candidates(
549            &map,
550            10,
551            42,
552            &cam0(),
553            &cam0_to_cam1(),
554            &cam0_features,
555            &cam1_features,
556            &HashSet::new(),
557            &current,
558            1000,
559            &StereoReplenishConfig::default(),
560        );
561
562        assert_eq!(candidates.len(), 1);
563        assert_eq!(candidates[0].observations[1].keypoint_index, 0);
564        assert_eq!(candidates[0].observations[1].xy, measured);
565        assert_ne!(candidates[0].observations[1].xy, predicted);
566    }
567
568    #[test]
569    fn matched_index_is_excluded() {
570        let current = current_pose_shifted(0.3);
571        let world = Point3::new(0.2, -0.1, 4.0);
572        let (cam0_features, cam1_features) = stereo_features(&[world], &current);
573        let anchor_pixel = project_identity(&world);
574        let anchor = anchor_keyframe(10, vec![anchor_pixel]);
575        let map = base_map(anchor);
576
577        // Mark cam0 keypoint 0 as already tracked → no candidate.
578        let mut matched = HashSet::new();
579        matched.insert(0usize);
580
581        let candidates = build_stereo_replenish_candidates(
582            &map,
583            10,
584            42,
585            &cam0(),
586            &cam0_to_cam1(),
587            &cam0_features,
588            &cam1_features,
589            &matched,
590            &current,
591            1000,
592            &StereoReplenishConfig::default(),
593        );
594        assert!(candidates.is_empty());
595    }
596
597    #[test]
598    fn duplicate_suppression_drops_survivor_near_existing_landmark() {
599        let current = current_pose_shifted(0.3);
600        let world = Point3::new(0.2, -0.1, 4.0);
601        let (cam0_features, cam1_features) = stereo_features(&[world], &current);
602        let anchor_pixel = project_identity(&world);
603        let mut anchor = anchor_keyframe(10, vec![anchor_pixel]);
604
605        // Existing landmark at the same world point → its current-frame
606        // reprojection coincides with the survivor's raw cam0 pixel.
607        let mut map = base_map(anchor.clone());
608        map.landmarks.insert(500, Landmark::new(500, world));
609        anchor.observations.push(Observation {
610            frame_id: 10,
611            landmark_id: 500,
612            keypoint_index: 0,
613            xy: anchor_pixel,
614        });
615        map.keyframes.insert(10, anchor);
616
617        let candidates = build_stereo_replenish_candidates(
618            &map,
619            10,
620            42,
621            &cam0(),
622            &cam0_to_cam1(),
623            &cam0_features,
624            &cam1_features,
625            &HashSet::new(),
626            &current,
627            1000,
628            &StereoReplenishConfig::default(),
629        );
630        assert!(candidates.is_empty());
631    }
632
633    #[test]
634    fn parallax_gate_drops_zero_baseline_geometry() {
635        // Anchor == current pose (both identity) → zero anchor↔current
636        // parallax → degenerate two-view geometry → dropped.
637        let current = Pose::identity();
638        let world = Point3::new(0.2, -0.1, 4.0);
639        let (cam0_features, cam1_features) = stereo_features(&[world], &current);
640        let anchor_pixel = project_identity(&world);
641        let anchor = anchor_keyframe(10, vec![anchor_pixel]);
642        let map = base_map(anchor);
643
644        let candidates = build_stereo_replenish_candidates(
645            &map,
646            10,
647            42,
648            &cam0(),
649            &cam0_to_cam1(),
650            &cam0_features,
651            &cam1_features,
652            &HashSet::new(),
653            &current,
654            1000,
655            &StereoReplenishConfig::default(),
656        );
657        assert!(
658            candidates.is_empty(),
659            "zero anchor/current baseline must fail the parallax gate"
660        );
661    }
662
663    #[test]
664    fn anchor_reprojection_out_of_bounds_is_dropped() {
665        // World point in front of the current camera but whose reprojection
666        // into the anchor camera lands off-image. Achieved by making the
667        // anchor look the other way (180° yaw) so the point is behind /
668        // projects out of frame.
669        let current = current_pose_shifted(0.3);
670        let world = Point3::new(0.2, -0.1, 4.0);
671        let (cam0_features, cam1_features) = stereo_features(&[world], &current);
672
673        // Anchor rotated 180° about y: the world point is now behind it.
674        let mut anchor = anchor_keyframe(10, vec![Point2::new(367.0, 248.0)]);
675        anchor.frame.pose = Some(Pose::from_world_to_camera(
676            UnitQuaternion::from_axis_angle(&Vector3::y_axis(), std::f64::consts::PI),
677            Vector3::zeros(),
678        ));
679        let map = base_map(anchor);
680
681        let candidates = build_stereo_replenish_candidates(
682            &map,
683            10,
684            42,
685            &cam0(),
686            &cam0_to_cam1(),
687            &cam0_features,
688            &cam1_features,
689            &HashSet::new(),
690            &current,
691            1000,
692            &StereoReplenishConfig::default(),
693        );
694        assert!(
695            candidates.is_empty(),
696            "point behind the anchor camera must be dropped"
697        );
698    }
699
700    #[test]
701    fn no_anchor_keypoint_within_radius_is_dropped() {
702        let current = current_pose_shifted(0.3);
703        let world = Point3::new(0.2, -0.1, 4.0);
704        let (cam0_features, cam1_features) = stereo_features(&[world], &current);
705        // Anchor's only keypoint is far from where `world` reprojects.
706        let anchor = anchor_keyframe(10, vec![Point2::new(5.0, 5.0)]);
707        let map = base_map(anchor);
708
709        let candidates = build_stereo_replenish_candidates(
710            &map,
711            10,
712            42,
713            &cam0(),
714            &cam0_to_cam1(),
715            &cam0_features,
716            &cam1_features,
717            &HashSet::new(),
718            &current,
719            1000,
720            &StereoReplenishConfig::default(),
721        );
722        assert!(
723            candidates.is_empty(),
724            "no real anchor keypoint nearby → no fabricated index"
725        );
726    }
727
728    #[test]
729    fn per_frame_cap_truncates_returned_candidates() {
730        let current = current_pose_shifted(0.3);
731        // Three well-separated world points.
732        let worlds = [
733            Point3::new(-0.4, 0.1, 4.0),
734            Point3::new(0.0, -0.2, 5.0),
735            Point3::new(0.5, 0.2, 3.5),
736        ];
737        let (cam0_features, cam1_features) = stereo_features(&worlds, &current);
738        // Anchor keypoints exactly where each world point reprojects.
739        let anchor_pixels: Vec<Point2<f64>> = worlds.iter().map(project_identity).collect();
740        let anchor = anchor_keyframe(10, anchor_pixels);
741        let map = base_map(anchor);
742
743        let config = StereoReplenishConfig {
744            max_candidates_per_frame: 2,
745            ..StereoReplenishConfig::default()
746        };
747        let candidates = build_stereo_replenish_candidates(
748            &map,
749            10,
750            42,
751            &cam0(),
752            &cam0_to_cam1(),
753            &cam0_features,
754            &cam1_features,
755            &HashSet::new(),
756            &current,
757            2000,
758            &config,
759        );
760        assert_eq!(candidates.len(), 2, "cap must truncate to 2");
761        // Sequential ids from the start value.
762        assert_eq!(candidates[0].id, 2000);
763        assert_eq!(candidates[1].id, 2001);
764        // Distinct real anchor keypoint indices (no intra-call collision).
765        assert_ne!(
766            candidates[0].observations[1].keypoint_index,
767            candidates[1].observations[1].keypoint_index
768        );
769    }
770
771    #[test]
772    fn missing_anchor_keyframe_returns_empty() {
773        let current = current_pose_shifted(0.3);
774        let world = Point3::new(0.2, -0.1, 4.0);
775        let (cam0_features, cam1_features) = stereo_features(&[world], &current);
776        let map = VisualMap::new(); // no keyframes / cameras
777
778        let candidates = build_stereo_replenish_candidates(
779            &map,
780            10,
781            42,
782            &cam0(),
783            &cam0_to_cam1(),
784            &cam0_features,
785            &cam1_features,
786            &HashSet::new(),
787            &current,
788            1000,
789            &StereoReplenishConfig::default(),
790        );
791        assert!(candidates.is_empty());
792    }
793}