use std::collections::{HashMap, HashSet};
use nalgebra::Point2;
use visloc_core::geometry::{Pose, SE3};
use visloc_core::types::{Camera, FrameId, VisualMap};
use visloc_vision::features::FeatureSet;
use visloc_vision::matching::BruteForceMatcher;
use visloc_vision::stereo_bootstrap::{bootstrap_stereo_landmarks, StereoBootstrapConfig};
use crate::{LandmarkCandidate, LandmarkCandidateId, LandmarkCandidateObservation};
#[derive(Debug, Clone, PartialEq)]
pub struct StereoReplenishConfig {
pub max_candidates_per_frame: usize,
pub bootstrap_config: StereoBootstrapConfig,
pub anchor_keypoint_match_radius_px: f64,
pub anchor_keypoint_max_descriptor_distance: Option<f32>,
pub duplicate_suppression_radius_px: f64,
pub min_parallax_deg: f64,
pub min_depth_meters: f64,
pub max_depth_meters: f64,
}
impl Default for StereoReplenishConfig {
fn default() -> Self {
Self {
max_candidates_per_frame: 100,
bootstrap_config: StereoBootstrapConfig::default(),
anchor_keypoint_match_radius_px: 5.0,
anchor_keypoint_max_descriptor_distance: None,
duplicate_suppression_radius_px: 3.0,
min_parallax_deg: 0.5,
min_depth_meters: 0.1,
max_depth_meters: 50.0,
}
}
}
pub fn build_stereo_metric_points(
cam0_camera: &Camera,
cam1_camera: &Camera,
cam0_to_cam1: &SE3,
cam0_features: &FeatureSet,
cam1_features: &FeatureSet,
config: &StereoReplenishConfig,
) -> HashMap<usize, nalgebra::Point3<f64>> {
bootstrap_stereo_landmarks(
cam0_camera,
cam1_camera,
cam0_to_cam1,
cam0_features,
cam1_features,
&config.bootstrap_config,
)
.into_iter()
.filter(|survivor| {
let depth = survivor.point_left_camera_frame.z;
depth.is_finite() && depth >= config.min_depth_meters && depth <= config.max_depth_meters
})
.map(|survivor| {
(
survivor.left_keypoint_index,
survivor.point_left_camera_frame,
)
})
.collect()
}
#[allow(clippy::too_many_arguments)]
pub fn build_stereo_replenish_candidates(
map: &VisualMap,
anchor_frame_id: FrameId,
frame_id: FrameId,
cam1_camera: &Camera,
cam0_to_cam1: &SE3,
cam0_features: &FeatureSet,
cam1_features: &FeatureSet,
matched_cam0_indices: &HashSet<usize>,
current_pose: &Pose,
next_candidate_id: LandmarkCandidateId,
config: &StereoReplenishConfig,
) -> Vec<LandmarkCandidate> {
let Some(anchor_keyframe) = map.keyframes.get(&anchor_frame_id) else {
return Vec::new();
};
let Some(anchor_pose) = anchor_keyframe.frame.pose.as_ref() else {
return Vec::new();
};
let Some(cam0_camera) = map.cameras.get(&anchor_keyframe.frame.camera_id) else {
return Vec::new();
};
if anchor_keyframe.frame.keypoints.is_empty() {
return Vec::new();
}
let survivors = bootstrap_stereo_landmarks(
cam0_camera,
cam1_camera,
cam0_to_cam1,
cam0_features,
cam1_features,
&config.bootstrap_config,
);
if survivors.is_empty() {
return Vec::new();
}
let mut existing_reprojections: Vec<Point2<f64>> =
Vec::with_capacity(anchor_keyframe.observations.len());
let mut claimed_anchor_indices: HashSet<usize> =
HashSet::with_capacity(anchor_keyframe.observations.len());
for observation in &anchor_keyframe.observations {
claimed_anchor_indices.insert(observation.keypoint_index);
if let Some(landmark) = map.landmarks.get(&observation.landmark_id) {
let point_current = current_pose.transform_world_point(&landmark.position);
if let Some(pixel) = cam0_camera.project(&point_current) {
existing_reprojections.push(pixel);
}
}
}
let camera_to_world = current_pose.camera_to_world();
let anchor_center = anchor_pose.camera_center_world();
let current_center = current_pose.camera_center_world();
let min_parallax_cos = config.min_parallax_deg.to_radians().cos();
let width = cam0_camera.width as f64;
let height = cam0_camera.height as f64;
let mut candidates: Vec<LandmarkCandidate> = Vec::new();
let mut next_id = next_candidate_id;
for survivor in &survivors {
if candidates.len() >= config.max_candidates_per_frame {
break;
}
if matched_cam0_indices.contains(&survivor.left_keypoint_index) {
continue;
}
let raw_left_pixel = cam0_features.keypoints[survivor.left_keypoint_index];
if existing_reprojections.iter().any(|reprojection| {
(reprojection - raw_left_pixel).norm() <= config.duplicate_suppression_radius_px
}) {
continue;
}
let world_point = camera_to_world.transform_point(&survivor.point_left_camera_frame);
let anchor_camera_point = anchor_pose.transform_world_point(&world_point);
if anchor_camera_point.z <= 0.0 {
continue;
}
let Some(anchor_xy) = cam0_camera.project(&anchor_camera_point) else {
continue;
};
if anchor_xy.x < 0.0 || anchor_xy.x > width || anchor_xy.y < 0.0 || anchor_xy.y > height {
continue;
}
let depth = survivor.point_left_camera_frame.z;
if !depth.is_finite() || depth < config.min_depth_meters || depth > config.max_depth_meters
{
continue;
}
let anchor_ray = world_point - anchor_center;
let current_ray = world_point - current_center;
let anchor_ray_norm = anchor_ray.norm();
let current_ray_norm = current_ray.norm();
if anchor_ray_norm <= f64::EPSILON || current_ray_norm <= f64::EPSILON {
continue;
}
let cos_parallax = anchor_ray.dot(¤t_ray) / (anchor_ray_norm * current_ray_norm);
if cos_parallax.clamp(-1.0, 1.0) >= min_parallax_cos {
continue;
}
let mut best_index: Option<usize> = None;
let mut best_distance = config.anchor_keypoint_match_radius_px;
for (index, keypoint) in anchor_keyframe.frame.keypoints.iter().enumerate() {
if claimed_anchor_indices.contains(&index) {
continue;
}
let distance = (keypoint - anchor_xy).norm();
if distance <= best_distance {
best_distance = distance;
best_index = Some(index);
}
}
let Some(anchor_keypoint_index) = best_index else {
continue;
};
let anchor_measured_xy = anchor_keyframe.frame.keypoints[anchor_keypoint_index];
let candidate_descriptor = &cam0_features.descriptors[survivor.left_keypoint_index];
if let Some(max_descriptor_distance) = config.anchor_keypoint_max_descriptor_distance {
let Some(anchor_descriptor) =
anchor_keyframe.frame.descriptors.get(anchor_keypoint_index)
else {
continue;
};
match BruteForceMatcher::l2_distance(candidate_descriptor, anchor_descriptor) {
Some(distance) if distance <= max_descriptor_distance => {}
_ => continue,
}
}
claimed_anchor_indices.insert(anchor_keypoint_index);
let candidate_id = next_id;
next_id += 1;
let rotation_camera_to_world = camera_to_world.rotation.to_rotation_matrix().into_inner();
let covariance_world = rotation_camera_to_world
* survivor.point_covariance_left_camera_frame
* rotation_camera_to_world.transpose();
candidates.push(
LandmarkCandidate::new(candidate_id)
.with_observation(
LandmarkCandidateObservation::new(
frame_id,
survivor.left_keypoint_index,
raw_left_pixel,
)
.with_stereo_measurement(
cam1_camera.id,
cam1_features.keypoints[survivor.right_keypoint_index],
cam0_to_cam1.clone(),
),
)
.with_observation(LandmarkCandidateObservation::new(
anchor_frame_id,
anchor_keypoint_index,
anchor_measured_xy,
))
.with_descriptor(candidate_descriptor.clone())
.with_position_covariance_world(covariance_world),
);
}
candidates
}
#[cfg(test)]
mod tests {
use super::*;
use nalgebra::{Point2, Point3, UnitQuaternion, Vector3};
use visloc_core::types::{Frame, Keyframe, Landmark, Observation};
fn cam0() -> Camera {
Camera::pinhole(1, 752, 480, 458.0, 457.0, 367.0, 248.0)
}
fn cam0_to_cam1() -> SE3 {
SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0))
}
fn anchor_keyframe(frame_id: u64, keypoints: Vec<Point2<f64>>) -> Keyframe {
let mut frame = Frame::new(frame_id, 1);
frame.descriptors = keypoints.iter().map(|_| vec![1.0_f32, 0.0]).collect();
frame.keypoints = keypoints;
frame.pose = Some(Pose::identity());
Keyframe {
frame,
observations: Vec::new(),
}
}
fn base_map(anchor: Keyframe) -> VisualMap {
let mut map = VisualMap::new();
map.cameras.insert(1, cam0());
map.keyframes.insert(anchor.frame.id, anchor);
map
}
fn project_identity(point: &Point3<f64>) -> Point2<f64> {
cam0().project(point).expect("in front of camera")
}
fn stereo_features(
world_points: &[Point3<f64>],
current_pose: &Pose,
) -> (FeatureSet, FeatureSet) {
let cam = cam0();
let l2r = cam0_to_cam1();
let mut cam0_kps = Vec::new();
let mut cam1_kps = Vec::new();
let mut cam0_desc = Vec::new();
let mut cam1_desc = Vec::new();
for (i, world) in world_points.iter().enumerate() {
let point_left = current_pose.transform_world_point(world);
let point_right = l2r.transform_point(&point_left);
cam0_kps.push(cam.project(&point_left).expect("left in front"));
cam1_kps.push(cam.project(&point_right).expect("right in front"));
let mut desc = vec![0.0_f32; world_points.len()];
desc[i] = 1.0;
cam0_desc.push(desc.clone());
cam1_desc.push(desc);
}
(
FeatureSet::new(cam0_kps, cam0_desc).unwrap(),
FeatureSet::new(cam1_kps, cam1_desc).unwrap(),
)
}
fn current_pose_shifted(tx: f64) -> Pose {
Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-tx, 0.0, 0.0))
}
#[test]
fn happy_path_builds_candidate_with_real_anchor_keypoint_index() {
let current = current_pose_shifted(0.3);
let world = Point3::new(0.2, -0.1, 4.0);
let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
let anchor_pixel = project_identity(&world);
let anchor = anchor_keyframe(
10,
vec![
Point2::new(5.0, 5.0),
Point2::new(700.0, 400.0),
anchor_pixel,
],
);
let map = base_map(anchor);
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&HashSet::new(),
¤t,
1000,
&StereoReplenishConfig::default(),
);
assert_eq!(candidates.len(), 1);
let candidate = &candidates[0];
assert_eq!(candidate.id, 1000);
assert_eq!(candidate.observations.len(), 2);
assert_eq!(candidate.observations[0].frame_id, 42);
assert_eq!(candidate.observations[0].keypoint_index, 0);
let stereo = candidate.observations[0]
.stereo
.as_ref()
.expect("current observation retains its cam1 measurement");
assert_eq!(stereo.right_camera_id, cam0().id);
assert_eq!(stereo.xy_right, cam1_features.keypoints[0]);
assert_eq!(stereo.left_to_right, cam0_to_cam1());
assert_eq!(candidate.observations[1].frame_id, 10);
assert_eq!(candidate.observations[1].keypoint_index, 2);
assert_eq!(candidate.observations[1].xy, anchor_pixel);
assert!(candidate.observations[1].stereo.is_none());
assert!(candidate.descriptor.is_some());
let covariance = candidate
.position_covariance_world
.expect("stereo uncertainty is retained for downstream backend factors");
assert!(covariance.iter().all(|value| value.is_finite()));
assert!(covariance.trace() > 0.0);
}
#[test]
fn anchor_observation_uses_measured_pixel_not_stereo_prediction() {
let current = current_pose_shifted(0.3);
let world = Point3::new(0.2, -0.1, 4.0);
let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
let predicted = project_identity(&world);
let measured = predicted + nalgebra::Vector2::new(1.25, -0.75);
let map = base_map(anchor_keyframe(10, vec![measured]));
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&HashSet::new(),
¤t,
1000,
&StereoReplenishConfig::default(),
);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].observations[1].keypoint_index, 0);
assert_eq!(candidates[0].observations[1].xy, measured);
assert_ne!(candidates[0].observations[1].xy, predicted);
}
#[test]
fn matched_index_is_excluded() {
let current = current_pose_shifted(0.3);
let world = Point3::new(0.2, -0.1, 4.0);
let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
let anchor_pixel = project_identity(&world);
let anchor = anchor_keyframe(10, vec![anchor_pixel]);
let map = base_map(anchor);
let mut matched = HashSet::new();
matched.insert(0usize);
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&matched,
¤t,
1000,
&StereoReplenishConfig::default(),
);
assert!(candidates.is_empty());
}
#[test]
fn duplicate_suppression_drops_survivor_near_existing_landmark() {
let current = current_pose_shifted(0.3);
let world = Point3::new(0.2, -0.1, 4.0);
let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
let anchor_pixel = project_identity(&world);
let mut anchor = anchor_keyframe(10, vec![anchor_pixel]);
let mut map = base_map(anchor.clone());
map.landmarks.insert(500, Landmark::new(500, world));
anchor.observations.push(Observation {
frame_id: 10,
landmark_id: 500,
keypoint_index: 0,
xy: anchor_pixel,
});
map.keyframes.insert(10, anchor);
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&HashSet::new(),
¤t,
1000,
&StereoReplenishConfig::default(),
);
assert!(candidates.is_empty());
}
#[test]
fn parallax_gate_drops_zero_baseline_geometry() {
let current = Pose::identity();
let world = Point3::new(0.2, -0.1, 4.0);
let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
let anchor_pixel = project_identity(&world);
let anchor = anchor_keyframe(10, vec![anchor_pixel]);
let map = base_map(anchor);
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&HashSet::new(),
¤t,
1000,
&StereoReplenishConfig::default(),
);
assert!(
candidates.is_empty(),
"zero anchor/current baseline must fail the parallax gate"
);
}
#[test]
fn anchor_reprojection_out_of_bounds_is_dropped() {
let current = current_pose_shifted(0.3);
let world = Point3::new(0.2, -0.1, 4.0);
let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
let mut anchor = anchor_keyframe(10, vec![Point2::new(367.0, 248.0)]);
anchor.frame.pose = Some(Pose::from_world_to_camera(
UnitQuaternion::from_axis_angle(&Vector3::y_axis(), std::f64::consts::PI),
Vector3::zeros(),
));
let map = base_map(anchor);
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&HashSet::new(),
¤t,
1000,
&StereoReplenishConfig::default(),
);
assert!(
candidates.is_empty(),
"point behind the anchor camera must be dropped"
);
}
#[test]
fn no_anchor_keypoint_within_radius_is_dropped() {
let current = current_pose_shifted(0.3);
let world = Point3::new(0.2, -0.1, 4.0);
let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
let anchor = anchor_keyframe(10, vec![Point2::new(5.0, 5.0)]);
let map = base_map(anchor);
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&HashSet::new(),
¤t,
1000,
&StereoReplenishConfig::default(),
);
assert!(
candidates.is_empty(),
"no real anchor keypoint nearby → no fabricated index"
);
}
#[test]
fn per_frame_cap_truncates_returned_candidates() {
let current = current_pose_shifted(0.3);
let worlds = [
Point3::new(-0.4, 0.1, 4.0),
Point3::new(0.0, -0.2, 5.0),
Point3::new(0.5, 0.2, 3.5),
];
let (cam0_features, cam1_features) = stereo_features(&worlds, ¤t);
let anchor_pixels: Vec<Point2<f64>> = worlds.iter().map(project_identity).collect();
let anchor = anchor_keyframe(10, anchor_pixels);
let map = base_map(anchor);
let config = StereoReplenishConfig {
max_candidates_per_frame: 2,
..StereoReplenishConfig::default()
};
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&HashSet::new(),
¤t,
2000,
&config,
);
assert_eq!(candidates.len(), 2, "cap must truncate to 2");
assert_eq!(candidates[0].id, 2000);
assert_eq!(candidates[1].id, 2001);
assert_ne!(
candidates[0].observations[1].keypoint_index,
candidates[1].observations[1].keypoint_index
);
}
#[test]
fn missing_anchor_keyframe_returns_empty() {
let current = current_pose_shifted(0.3);
let world = Point3::new(0.2, -0.1, 4.0);
let (cam0_features, cam1_features) = stereo_features(&[world], ¤t);
let map = VisualMap::new();
let candidates = build_stereo_replenish_candidates(
&map,
10,
42,
&cam0(),
&cam0_to_cam1(),
&cam0_features,
&cam1_features,
&HashSet::new(),
¤t,
1000,
&StereoReplenishConfig::default(),
);
assert!(candidates.is_empty());
}
}