Skip to main content

visloc_tracking/
lib.rs

1#![forbid(unsafe_code)]
2// The DPVO-port and verification modules document internal (crate-private)
3// items extensively; intra-doc links to them are intentional and resolve
4// under --document-private-items. Tolerated repo-wide until that doc pass.
5#![allow(rustdoc::private_intra_doc_links, rustdoc::broken_intra_doc_links)]
6//! Lightweight localization-based tracking scaffold.
7//!
8//! This crate does not implement full SLAM. It keeps temporal state around
9//! repeated localization calls, exposes motion-model pose priors, tracks
10//! failure/lost/relocalization events, and leaves keyframe management, map
11//! updates, loop closure, and bundle adjustment to future layers.
12
13use std::collections::{HashMap, HashSet};
14use std::fmt;
15use std::fmt::Write as _;
16use std::path::Path;
17
18use nalgebra::{Matrix3, Point3, Quaternion, Rotation3, UnitQuaternion, Vector3};
19use visloc_core::geometry::{Pose, Sim3, SE3};
20use visloc_core::types::{
21    CameraId, Frame, FrameId, LandmarkDescriptorStore, LandmarkId, LocalizationFailureReason,
22    LocalizationResult, QueryImage, VisualMap,
23};
24use visloc_localization::{
25    map_provider_stats, CandidateSelector, DescriptorProvider, InMemoryMapProvider,
26    IntersectCandidateSelector, LocalizationPipeline, LocalizationPrior, MapProvider,
27    MapProviderStats, RadiusLandmarkSelector,
28};
29use visloc_vision::features::{FeatureExtractor, FeatureSet};
30use visloc_vision::matching::Matcher;
31use visloc_vision::ransac::RobustPoseEstimator;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum TrackingState {
35    Uninitialized,
36    Tracking,
37    Lost,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum TrackingEvent {
42    Initialized,
43    Tracked,
44    TrackingFailed,
45    Lost,
46    Relocalized,
47}
48
49#[derive(Debug, Clone, PartialEq)]
50pub struct TrackingConfig {
51    pub min_successive_failures_to_lost: usize,
52    pub last_pose_candidate_radius: Option<f64>,
53    pub max_pose_prior_translation_error: Option<f64>,
54    /// Permit a bounded widening of the pose-prior translation gate when the
55    /// independently estimated visual pose has unusually strong geometric
56    /// support. This addresses motion-prior disagreement during fast motion
57    /// without disabling the teleport guard for weak/repetitive matches.
58    pub pose_prior_visual_override: Option<PosePriorVisualOverrideConfig>,
59    pub min_inliers: usize,
60    pub min_inlier_ratio: f64,
61    pub max_mean_reprojection_error: Option<f64>,
62    /// Restrict descriptor-matching candidates to a local map built from the
63    /// covisibility graph around the last successfully tracked keyframe. When
64    /// the local map is too small (e.g. early-startup, lost-state, or below
65    /// `min_local_map_landmarks`), the tracker falls back to the full map.
66    pub covisibility_local_map: Option<CovisibilityLocalMapConfig>,
67    /// When `true`, hand the motion-model pose prior to the PnP RANSAC as a
68    /// warm-start hypothesis (ORB-SLAM3-style motion-only BA seed). Random
69    /// samples must beat the prior's inlier count to win, so a well-aligned
70    /// prior short-circuits RANSAC on hard scenes while a misaligned prior
71    /// gracefully degrades to the standard random search. Off by default to
72    /// preserve the existing behaviour where the prior is consumed only as a
73    /// candidate-radius filter.
74    pub pnp_pose_prior_warm_start: bool,
75    /// When `true`, scale `max_pose_prior_translation_error` by the number
76    /// of frames elapsed since the last successful track (capped at
77    /// `pose_jump_gap_scaling_max_multiplier`, floored at 1). A pose prior
78    /// that has gone stale because tracking failed for several frames in a
79    /// row is compared against a proportionally widened gate instead of the
80    /// fixed radius, so a good PnP solution arriving after a gap is not
81    /// rejected purely because the (frozen) prior is far from it. When the
82    /// immediately preceding frame tracked successfully the gap is 1 and
83    /// the gate is unchanged from today's fixed-radius behaviour. Off by
84    /// default.
85    pub pose_jump_gap_scaling: bool,
86    /// Cap on the gap-scaling multiplier applied when `pose_jump_gap_scaling`
87    /// is enabled. Prevents an extended tracking outage from inflating the
88    /// gate to an unbounded radius.
89    pub pose_jump_gap_scaling_max_multiplier: usize,
90    /// ORB-SLAM3-style projection-guided tracking: when a pose prior is
91    /// available, restrict descriptor matching to a per-landmark projection
92    /// window instead of an appearance-global search, with a widen-retry
93    /// ladder and post-hoc local-map refinement. `None` (the default)
94    /// preserves today's appearance-global-then-warm-start behaviour
95    /// bit-for-bit; enabling the feature can only ADD tracking chances,
96    /// because the widen-retry ladder falls back to the existing
97    /// appearance-global path if every projection attempt fails.
98    pub projection_guided_tracking: Option<ProjectionGuidedTrackingConfig>,
99    /// When `true` and the motion model exposes a predictive prior
100    /// (`allows_pnp_pose_prior_warm_start`), accept that prior as the
101    /// frame pose whenever visual localization / quality gates fail.
102    /// Keeps the IMU strapdown window draining and the trajectory
103    /// continuous through brief visual cliffs without writing a bad
104    /// PnP teleport; keyframe policies should still reject 0-inlier
105    /// coasts. Off by default.
106    pub accept_motion_prior_on_failure: bool,
107    /// Cap on consecutive motion-prior coasts. After this many coasts
108    /// without a visual success, fall back to reporting failure so the
109    /// adaptive model can switch / reloc can fire. `None` = unlimited
110    /// (gate67: 626 coasts collapsed Sim(3) scale to 0.02 — do not use).
111    pub max_consecutive_motion_prior_coasts: Option<usize>,
112    /// When `true`, try matching the current frame against only the
113    /// landmark ids that were inliers on the previous successful track
114    /// before falling back to the full appearance-global / projection
115    /// path. This is the image-free temporal track analogue of Basalt
116    /// KLT: keep associating the same 3D points frame-to-frame via
117    /// descriptors. Off by default.
118    pub temporal_landmark_tracking: bool,
119    /// Minimum retained previous-inlier landmarks required to attempt
120    /// the temporal track stage. Below this, skip straight to the
121    /// normal path.
122    pub temporal_landmark_tracking_min_landmarks: usize,
123    /// Number of recent successful inlier sets whose landmark ids are
124    /// unioned for the temporal store. `1` is last-frame-only (gate70);
125    /// larger values keep short-term tracks alive across brief dropouts.
126    pub temporal_landmark_tracking_history_frames: usize,
127    /// Inlier floor applied only when the temporal landmark stage produced
128    /// the candidate pose. Can be lower than [`Self::min_inliers`] so a
129    /// brief dropout does not discard a still-associated track, without
130    /// softening the full-map appearance path (gate72 softened global
131    /// min_inliers to 20 and path-dependently hurt coverage).
132    pub temporal_landmark_tracking_min_inliers: usize,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq)]
136pub struct PosePriorVisualOverrideConfig {
137    /// Minimum PnP inlier count required to widen the prior gate.
138    pub min_inliers: usize,
139    /// Minimum PnP inlier fraction required to widen the prior gate.
140    pub min_inlier_ratio: f64,
141    /// Optional mean reprojection-error ceiling for the visual solution.
142    pub max_mean_reprojection_error: Option<f64>,
143    /// Require the innovation to exceed this multiple of the ordinary gate
144    /// before widening it. Hysteresis avoids perturbing the map for marginal
145    /// threshold crossings that recover naturally on the next frame.
146    pub min_translation_error_multiplier: f64,
147    /// Optional rotation innovation ceiling in radians. Translation-only
148    /// disagreement may indicate a stale velocity prior; simultaneous large
149    /// rotation disagreement is more likely an unsafe pose branch.
150    pub max_rotation_error_radians: Option<f64>,
151    /// Isotropic translation standard deviation assigned to the motion prior
152    /// for continuation-state fusion.
153    pub continuation_prior_translation_std_m: f64,
154    /// Pixel noise used when converting the PnP inlier reprojection Hessian
155    /// into a translation covariance.
156    pub continuation_visual_pixel_sigma_px: f64,
157    /// Spectral cap on the covariance-derived continuation Kalman gain.
158    pub continuation_max_gain: f64,
159    /// Maximum accepted condition number of the translation Hessian.
160    pub continuation_max_condition_number: f64,
161    /// Maximum widened gate as a multiple of
162    /// `TrackingConfig::max_pose_prior_translation_error`. Must be >= 1.
163    pub max_translation_error_multiplier: f64,
164}
165
166impl Default for PosePriorVisualOverrideConfig {
167    fn default() -> Self {
168        Self {
169            min_inliers: 100,
170            min_inlier_ratio: 0.6,
171            max_mean_reprojection_error: Some(3.0),
172            min_translation_error_multiplier: 1.25,
173            max_rotation_error_radians: Some(std::f64::consts::PI / 180.0),
174            continuation_prior_translation_std_m: 0.02,
175            continuation_visual_pixel_sigma_px: 2.0,
176            continuation_max_gain: 0.5,
177            continuation_max_condition_number: 1.0e6,
178            max_translation_error_multiplier: 2.5,
179        }
180    }
181}
182
183#[derive(Debug, Clone, Copy, PartialEq)]
184pub struct ProjectionGuidedTrackingConfig {
185    /// Initial per-landmark projection-window radius, in pixels.
186    pub search_radius_px: f64,
187    /// Multiplier applied to `search_radius_px` on each widen-retry attempt
188    /// after a stage-1 projection attempt fails the pose-estimation quality
189    /// gate.
190    pub widen_factor: f64,
191    /// Maximum number of widen-retry attempts after the initial one. Total
192    /// projection attempts per frame is `1 + max_widen_retries`; if all of
193    /// them fail, the tracker falls back to the appearance-global path.
194    pub max_widen_retries: u32,
195    /// Optional reverse ambiguity ratio across landmarks competing for the
196    /// same query keypoint. `Some(r)` requires the best descriptor distance
197    /// to be strictly below `r * second_best`; `None` preserves deterministic
198    /// first-wins assignment for overlapping projection windows.
199    pub max_query_landmark_distance_ratio: Option<f32>,
200    /// When `true`, after ANY successful pose estimate (projection path or
201    /// appearance-global fallback), project the covisibility local map with
202    /// the estimated pose and re-optimize over the union of harvested and
203    /// existing inlier correspondences. Requires `covisibility_local_map`
204    /// to also be configured (the local-map landmark set the brief and
205    /// `build_covisibility_local_map_store` compute); otherwise this stage
206    /// is a no-op since there is no local-map landmark set to project.
207    pub local_map_refinement: bool,
208    /// Per-landmark projection-window radius, in pixels, used by the
209    /// local-map refinement stage. Independent of `search_radius_px` since
210    /// refinement starts from an already-estimated (not merely predicted)
211    /// pose and can afford a tighter window.
212    pub refinement_search_radius_px: f64,
213    /// Number of alternating correspondence-rebuild / pose-update rounds.
214    /// One preserves the original single-pass behavior.
215    pub refinement_iterations: u32,
216    /// Multiplier applied to the projection radius after each refinement
217    /// round. Values in `(0, 1]` progressively tighten geometric support.
218    pub refinement_radius_shrink_factor: f64,
219    /// Rebuild each round from fresh projected correspondences, allowing a
220    /// query keypoint to change its landmark assignment. When false, retain
221    /// the conservative legacy union-with-existing-inliers behavior.
222    pub refinement_reassign_correspondences: bool,
223    /// Minimum fraction of the current inlier query/landmark pairs that must
224    /// survive a revised round. Zero disables the factor-graph edge-retention
225    /// gate; values near one permit only bounded correspondence revisions.
226    pub refinement_min_inlier_pair_retention_ratio: f64,
227    /// Optional trust-region bound on camera-centre correction per accepted
228    /// refinement round.
229    pub refinement_max_pose_translation_correction_m: Option<f64>,
230    /// Optional trust-region bound on rotation correction per accepted round.
231    pub refinement_max_pose_rotation_correction_rad: Option<f64>,
232}
233
234impl Default for ProjectionGuidedTrackingConfig {
235    fn default() -> Self {
236        Self {
237            search_radius_px: 15.0,
238            widen_factor: 2.0,
239            max_widen_retries: 2,
240            max_query_landmark_distance_ratio: None,
241            local_map_refinement: true,
242            refinement_search_radius_px: 8.0,
243            refinement_iterations: 1,
244            refinement_radius_shrink_factor: 1.0,
245            refinement_reassign_correspondences: false,
246            refinement_min_inlier_pair_retention_ratio: 0.0,
247            refinement_max_pose_translation_correction_m: None,
248            refinement_max_pose_rotation_correction_rad: None,
249        }
250    }
251}
252
253#[derive(Debug, Clone, Copy, PartialEq)]
254pub struct CovisibilityLocalMapConfig {
255    /// Cap on number of co-visible keyframes (the reference keyframe is always
256    /// included). Set to `None` for unlimited.
257    pub max_keyframes: Option<usize>,
258    /// Minimum number of shared landmarks between a candidate keyframe and the
259    /// reference keyframe for the candidate to enter the local map.
260    pub min_shared_landmarks: usize,
261    /// If the resulting local-map landmark set is smaller than this, fall back
262    /// to the full descriptor store. Guards against accidentally collapsing the
263    /// match candidate pool in degenerate early-startup states.
264    pub min_local_map_landmarks: usize,
265}
266
267impl Default for CovisibilityLocalMapConfig {
268    fn default() -> Self {
269        Self {
270            max_keyframes: Some(10),
271            min_shared_landmarks: 15,
272            min_local_map_landmarks: 30,
273        }
274    }
275}
276
277impl Default for TrackingConfig {
278    fn default() -> Self {
279        Self {
280            min_successive_failures_to_lost: 3,
281            last_pose_candidate_radius: None,
282            max_pose_prior_translation_error: None,
283            pose_prior_visual_override: None,
284            min_inliers: 0,
285            min_inlier_ratio: 0.0,
286            max_mean_reprojection_error: None,
287            covisibility_local_map: None,
288            pnp_pose_prior_warm_start: false,
289            pose_jump_gap_scaling: false,
290            pose_jump_gap_scaling_max_multiplier: 10,
291            projection_guided_tracking: None,
292            accept_motion_prior_on_failure: false,
293            max_consecutive_motion_prior_coasts: Some(5),
294            temporal_landmark_tracking: false,
295            temporal_landmark_tracking_min_landmarks: 20,
296            temporal_landmark_tracking_history_frames: 1,
297            temporal_landmark_tracking_min_inliers: 20,
298        }
299    }
300}
301
302#[derive(Debug, Clone, PartialEq)]
303pub enum TrackingFailureReason {
304    InsufficientInliers {
305        inlier_count: usize,
306        min_inliers: usize,
307    },
308    InlierRatioTooLow {
309        inlier_ratio: f64,
310        min_inlier_ratio: f64,
311    },
312    MeanReprojectionErrorTooHigh {
313        reprojection_error: f64,
314        max_reprojection_error: f64,
315    },
316    PosePriorTranslationErrorExceeded {
317        translation_error: f64,
318        max_translation_error: f64,
319    },
320}
321
322#[derive(Debug, Clone, PartialEq)]
323pub struct TrackingResult {
324    pub frame_id: FrameId,
325    pub state: TrackingState,
326    pub event: TrackingEvent,
327    pub successive_failures: usize,
328    pub pose_prior: Option<Pose>,
329    pub used_pose_prior: bool,
330    pub used_external_localization_prior: bool,
331    pub external_localization_prior_radius: Option<f64>,
332    pub tracking_failure_reason: Option<TrackingFailureReason>,
333    pub map_landmark_count: usize,
334    pub map_stats: MapProviderStats,
335    pub localization: LocalizationResult,
336    /// Number of landmarks in the covisibility-derived local map used to
337    /// restrict descriptor matching for this frame. `None` when the local-map
338    /// filter was disabled or fell back to the full map.
339    pub covisibility_local_map_size: Option<usize>,
340}
341
342impl TrackingResult {
343    pub fn localization_prior(&self, radius: f64) -> LocalizationPrior {
344        if let Some(pose_prior) = self.pose_prior.clone() {
345            LocalizationPrior::from_pose(pose_prior, radius)
346        } else {
347            LocalizationPrior::none()
348        }
349    }
350}
351
352pub mod motion;
353pub use motion::*;
354
355pub mod report;
356pub use report::*;
357
358pub mod tracker;
359pub use tracker::*;
360
361pub mod trajectory;
362pub use trajectory::*;