Skip to main content

visloc_slam/
online_slam_motion_vi_init.rs

1//! Pipeline-side glue for the motion-based VI initialiser.
2//!
3//! Companion to [`crate::online_slam_vi_init`]: where the static stage
4//! recovers `(R_w←b, b_g, b_a)` from a stationary IMU window, this stage
5//! holds the known-scale visual body-pose trajectory fixed while refining
6//! per-keyframe velocity and a shared `(b_g, b_a)` once the body has moved
7//! enough to give the IMU
8//! translational excitation. It is the analogue of ORB-SLAM3's VIBA1 /
9//! VIBA2 inside [`crate::OnlineSlamPipeline`].
10//!
11//! Lifecycle:
12//!
13//! 1. The pipeline normally feeds this stage AFTER static VI init succeeds and
14//!    consumes that bias seed as its starting linearisation point. With
15//!    `allow_after_static_give_up`, a motion-start sequence may instead begin
16//!    after static initialization terminally fails, using configured IMU biases.
17//! 2. On every new keyframe, the pipeline calls
18//!    `OnlineSlamMotionViInitState::register_keyframe` with the
19//!    keyframe id + world-frame camera centre, and banks the freshly-
20//!    staged [`ImuPreintegrationFactor`] into
21//!    `OnlineSlamMotionViInitState::factor_history`.
22//! 3. Once both trigger gates (keyframe count + cumulative translation)
23//!    fire, the pipeline calls [`MotionBasedViInitializer::try_initialize`]
24//!    against the banked factors. On success the pipeline atomically:
25//!    (a) mirrors refined `(velocity_world, bias_gyro, bias_acc)` into
26//!    `local_vi_ba_state.keyframe_state` so the existing local-VI-BA
27//!    trigger restarts from the refined linearisation point;
28//!    (b) mirrors the refined biases onto `imu_state.config.{bias_*}` +
29//!    resets the running pre-integrator's bias linearisation;
30//!    (c) marks `vi_motion_init_state.completed = Some(...)` so the stage
31//!    does not fire again until [`crate::OnlineSlamPipeline::reset_sequence_state`].
32
33use std::collections::VecDeque;
34
35use crate::imu_preintegration::ImuPreintegrationFactor;
36use crate::vi_motion_initializer::{
37    GravityVelocityAlignment, GyroBiasAlignment, MotionBasedViInitializationResult,
38    MotionBasedViInitializer, MotionBasedViInitializerConfig, MotionBasedViRejectionReason,
39};
40
41/// Pipeline-level configuration for the motion-based VI init stage.
42///
43/// Requires [`crate::OnlineSlamConfig::vi_init`] and
44/// [`crate::OnlineSlamConfig::imu`] to both be `Some(_)`: the static stage
45/// controls whether a recovered or explicit post-give-up bias seed is used,
46/// and the IMU stream supplies the pre-integration factors that drive the solve.
47#[derive(Debug, Clone, PartialEq)]
48pub struct OnlineSlamMotionViInitConfig {
49    /// Inner motion-based initialiser config (trigger thresholds + inner
50    /// BA config).
51    pub initializer: MotionBasedViInitializerConfig,
52    /// Whether to mirror refined per-keyframe `(velocity, bias)` into the
53    /// pipeline's `local_vi_ba_state.keyframe_state` table. Defaults to
54    /// `true`; set to `false` if a caller wants the inner solve to be
55    /// purely diagnostic (rare).
56    pub mirror_into_local_vi_ba: bool,
57    /// Whether to mirror refined biases onto `imu_state.config.bias_*` +
58    /// reset the running pre-integrator. Defaults to `true`; the same
59    /// hand-off the static stage performs.
60    pub mirror_into_imu_state: bool,
61    /// Permit the motion-based solver to start from the configured running IMU
62    /// biases after the stationary initializer reaches `GaveUp` while keeping
63    /// its existing seed. Off by default: callers must explicitly acknowledge
64    /// that their sequence may begin in motion and that no stationary bias
65    /// estimate is available.
66    pub allow_after_static_give_up: bool,
67    /// Permit a moving-start sequence to begin VIBA1 immediately from the
68    /// configured running IMU biases, without waiting for the stationary
69    /// initializer to succeed or reach its give-up horizon. This is an
70    /// explicit opt-in because the configured biases may be inaccurate.
71    pub allow_from_configured_bias_before_static: bool,
72    /// Cap on the number of IMU factors banked in
73    /// `OnlineSlamMotionViInitState::factor_history`. Bounds memory on
74    /// long sequences where the trigger never fires. `0` disables the
75    /// cap. Default `64`.
76    pub max_buffered_factors: usize,
77}
78
79impl Default for OnlineSlamMotionViInitConfig {
80    fn default() -> Self {
81        Self {
82            initializer: MotionBasedViInitializerConfig::default(),
83            mirror_into_local_vi_ba: true,
84            mirror_into_imu_state: true,
85            allow_after_static_give_up: false,
86            allow_from_configured_bias_before_static: false,
87            max_buffered_factors: 64,
88        }
89    }
90}
91
92/// Read-only snapshot of the motion-based VI init stage. Returned by
93/// [`crate::OnlineSlamPipeline::motion_vi_initialization_status`].
94#[derive(Debug, Clone, PartialEq)]
95pub enum MotionViInitializationStatus {
96    /// The parent pipeline has no `vi_motion_init` config.
97    Disabled,
98    /// Static seed in hand; accumulating keyframes / translation until
99    /// the trigger fires.
100    Waiting {
101        keyframes_observed: usize,
102        cumulative_translation_meters: f64,
103        buffered_factor_count: usize,
104        last_rejection: Option<MotionBasedViRejectionReason>,
105        /// `true` once a [`crate::BiasReleaseSchedule`] Stage A ("velocity
106        /// stage") solve has fired and is cached on the inner
107        /// [`MotionBasedViInitializer`] (see
108        /// [`MotionBasedViInitializer::velocity_stage_result`]). Always
109        /// `false` when no bias-release schedule is configured.
110        velocity_stage_completed: bool,
111        /// Mirrors [`MotionBasedViInitializer::last_gravity_alignment`]:
112        /// the most recent gravity/velocity alignment attempt, kept even
113        /// when `last_rejection` reports a later gate rejected it. `None`
114        /// when `estimate_gravity` is off or no attempt has run yet.
115        last_gravity_alignment: Option<GravityVelocityAlignment>,
116        /// Mirrors [`MotionBasedViInitializer::last_gyro_bias_alignment`]:
117        /// the most recent gyro-bias rotation-only alignment attempt, kept
118        /// even when `last_rejection` reports a later gate rejected it.
119        /// `None` when `estimate_gyro_bias` is off or no attempt has run
120        /// yet.
121        last_gyro_bias_alignment: Option<GyroBiasAlignment>,
122    },
123    /// VIBA1 has fired and succeeded; the result is the recovered
124    /// refinement.
125    Initialised {
126        result: MotionBasedViInitializationResult,
127    },
128}
129
130/// State-transition event exposed on [`crate::OnlineSlamResult::vi_motion_init`].
131/// `Some` only on the frame where the motion-based stage actually
132/// changed state.
133// `Succeeded` intentionally carries the complete public initialization
134// result, while `StillWaiting` carries only a compact reason. Keep this event
135// shape stable for downstream consumers rather than boxing the public result.
136#[allow(clippy::large_enum_variant)]
137#[derive(Debug, Clone, PartialEq)]
138pub enum MotionViInitializationEvent {
139    /// VIBA1 fired and succeeded this frame. The pipeline has atomically
140    /// mirrored refined `(velocity, bias)` into the local-VI-BA state
141    /// table and reset the IMU pre-integrator if so configured.
142    ///
143    /// Consumers MUST check `result.bias_released` before treating this as
144    /// the terminal motion-VI-init outcome: when a
145    /// [`crate::BiasReleaseSchedule`] is configured, this event may instead
146    /// report a non-terminal Stage A ("velocity stage") firing
147    /// (`bias_released == false`) — velocities were refined and mirrored,
148    /// but biases still sit at the seed, and the stage remains active
149    /// awaiting a later Stage B firing (`bias_released == true`). `true`
150    /// on both the legacy single-stage path and Stage B.
151    Succeeded {
152        result: MotionBasedViInitializationResult,
153    },
154    /// Trigger evaluated this frame but rejected (gate not yet met, no
155    /// usable factor, or solver failure).
156    StillWaiting {
157        reason: MotionBasedViRejectionReason,
158    },
159}
160
161/// Private. Owned only by [`crate::OnlineSlamPipeline`].
162#[derive(Debug, Clone, PartialEq)]
163pub(crate) struct OnlineSlamMotionViInitState {
164    pub(crate) config: OnlineSlamMotionViInitConfig,
165    pub(crate) initializer: MotionBasedViInitializer,
166    pub(crate) completed: Option<MotionBasedViInitializationResult>,
167    pub(crate) last_rejection: Option<MotionBasedViRejectionReason>,
168    /// Ring buffer of recently-staged IMU pre-integration factors.
169    /// Capped by `config.max_buffered_factors`. The motion-based solver
170    /// scans this buffer for factors that connect any pair of registered
171    /// keyframes.
172    pub(crate) factor_history: VecDeque<ImuPreintegrationFactor>,
173}
174
175impl OnlineSlamMotionViInitState {
176    pub(crate) fn new(config: OnlineSlamMotionViInitConfig) -> Self {
177        let initializer = MotionBasedViInitializer::new(config.initializer.clone());
178        Self {
179            config,
180            initializer,
181            completed: None,
182            last_rejection: None,
183            factor_history: VecDeque::new(),
184        }
185    }
186
187    pub(crate) fn reset(&mut self) {
188        self.initializer.reset();
189        self.completed = None;
190        self.last_rejection = None;
191        self.factor_history.clear();
192    }
193
194    /// `true` while the motion-based stage is waiting for its trigger.
195    /// Mirrors the convention used by [`crate::OnlineSlamViInitState::is_active`].
196    pub(crate) const fn is_active(&self) -> bool {
197        self.completed.is_none()
198    }
199
200    /// `true` once a [`crate::BiasReleaseSchedule`] Stage A ("velocity
201    /// stage") solve has fired on the inner [`MotionBasedViInitializer`],
202    /// regardless of whether the stage has since gone on to reach the
203    /// terminal Stage B `completed` state. Always `false` when no
204    /// `bias_release` schedule is configured (the legacy path never parks
205    /// in a non-terminal success, so it either has `completed.is_some()`
206    /// or has not fired at all).
207    ///
208    /// Used by [`crate::OnlineSlamPipeline::vi_initialization_pending`] to
209    /// decide whether local VI-BA may run: a Stage A firing has already
210    /// replaced the placeholder-zero bias linearisation with the
211    /// refined/estimated seed (see that method's doc comment), so it
212    /// counts as "no longer pending" exactly like a terminal `completed`.
213    pub(crate) const fn velocity_stage_fired(&self) -> bool {
214        self.initializer.velocity_stage_result().is_some()
215    }
216
217    pub(crate) fn snapshot(&self) -> MotionViInitializationStatus {
218        if let Some(result) = &self.completed {
219            MotionViInitializationStatus::Initialised {
220                result: result.clone(),
221            }
222        } else {
223            MotionViInitializationStatus::Waiting {
224                keyframes_observed: self.initializer.keyframes_observed(),
225                cumulative_translation_meters: self.initializer.cumulative_translation_meters(),
226                buffered_factor_count: self.factor_history.len(),
227                last_rejection: self.last_rejection.clone(),
228                velocity_stage_completed: self.initializer.velocity_stage_result().is_some(),
229                last_gravity_alignment: self.initializer.last_gravity_alignment().cloned(),
230                last_gyro_bias_alignment: self.initializer.last_gyro_bias_alignment().cloned(),
231            }
232        }
233    }
234
235    /// Push a freshly-staged IMU factor onto the rolling history, evicting
236    /// the oldest if `max_buffered_factors` would be exceeded.
237    pub(crate) fn push_factor(&mut self, factor: ImuPreintegrationFactor) {
238        self.factor_history.push_back(factor);
239        let cap = self.config.max_buffered_factors;
240        if cap > 0 {
241            while self.factor_history.len() > cap {
242                self.factor_history.pop_front();
243            }
244        }
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251    use nalgebra::{Point3, Vector3};
252
253    use crate::imu_preintegration::ImuPreintegratedDelta;
254
255    fn test_factor(from: u64, to: u64) -> ImuPreintegrationFactor {
256        ImuPreintegrationFactor {
257            keyframe_id_from: from,
258            keyframe_id_to: to,
259            delta: ImuPreintegratedDelta::identity(),
260            gravity_world: Vector3::zeros(),
261            weight_position: 1.0,
262            weight_velocity: 1.0,
263            weight_rotation: 1.0,
264        }
265    }
266
267    #[test]
268    fn factor_history_respects_cap() {
269        let mut state = OnlineSlamMotionViInitState::new(OnlineSlamMotionViInitConfig {
270            max_buffered_factors: 2,
271            ..OnlineSlamMotionViInitConfig::default()
272        });
273        state.push_factor(test_factor(1, 2));
274        state.push_factor(test_factor(2, 3));
275        state.push_factor(test_factor(3, 4));
276        assert_eq!(state.factor_history.len(), 2);
277        // The oldest (1→2) was evicted; the remaining two are 2→3 and 3→4.
278        let front = state.factor_history.front().unwrap();
279        assert_eq!(front.keyframe_id_from, 2);
280    }
281
282    #[test]
283    fn factor_history_cap_zero_disables_eviction() {
284        let mut state = OnlineSlamMotionViInitState::new(OnlineSlamMotionViInitConfig {
285            max_buffered_factors: 0,
286            ..OnlineSlamMotionViInitConfig::default()
287        });
288        for i in 0..10 {
289            state.push_factor(test_factor(i, i + 1));
290        }
291        assert_eq!(state.factor_history.len(), 10);
292    }
293
294    #[test]
295    fn reset_clears_everything() {
296        let mut state = OnlineSlamMotionViInitState::new(OnlineSlamMotionViInitConfig::default());
297        state.push_factor(test_factor(1, 2));
298        state
299            .initializer
300            .register_keyframe(1, Point3::new(0.0, 0.0, 0.0));
301        state
302            .initializer
303            .register_keyframe(2, Point3::new(1.0, 0.0, 0.0));
304        assert_eq!(state.initializer.keyframes_observed(), 2);
305        assert_eq!(state.factor_history.len(), 1);
306        state.reset();
307        assert!(state.factor_history.is_empty());
308        assert_eq!(state.initializer.keyframes_observed(), 0);
309        assert!(state.completed.is_none());
310        assert!(state.last_rejection.is_none());
311    }
312
313    #[test]
314    fn snapshot_reports_waiting_with_buffered_counts() {
315        let state = OnlineSlamMotionViInitState::new(OnlineSlamMotionViInitConfig::default());
316        let snap = state.snapshot();
317        match snap {
318            MotionViInitializationStatus::Waiting {
319                keyframes_observed,
320                cumulative_translation_meters,
321                buffered_factor_count,
322                last_rejection,
323                velocity_stage_completed,
324                last_gravity_alignment,
325                last_gyro_bias_alignment,
326            } => {
327                assert_eq!(keyframes_observed, 0);
328                assert!(cumulative_translation_meters.abs() < 1e-12);
329                assert_eq!(buffered_factor_count, 0);
330                assert!(last_rejection.is_none());
331                assert!(!velocity_stage_completed);
332                assert!(last_gravity_alignment.is_none());
333                assert!(last_gyro_bias_alignment.is_none());
334            }
335            other => panic!("expected Waiting, got {other:?}"),
336        }
337    }
338}