1use super::*;
5
6pub trait MotionModel {
7 fn predict_pose(
8 &self,
9 frame: &Frame,
10 last_result: Option<&TrackingResult>,
11 last_successful_pose: Option<&Pose>,
12 ) -> Option<Pose>;
13
14 fn observe(&mut self, _result: &TrackingResult) {}
15
16 fn reset(&mut self) {}
17
18 fn allows_pnp_pose_prior_warm_start(&self) -> bool {
27 true
28 }
29
30 fn apply_pose_correction(&mut self, _correction: &SE3) {}
45
46 fn apply_similarity_correction(&mut self, correction: &Sim3) {
66 let se3_part = SE3::new(correction.rotation, correction.translation);
67 self.apply_pose_correction(&se3_part);
68 }
69}
70
71pub trait VisualOdometryFrontend {
72 type Error;
73
74 fn estimate_relative_pose(
75 &self,
76 previous_frame: &Frame,
77 current_frame: &Frame,
78 ) -> Result<Option<VisualOdometryEstimate>, Self::Error>;
79}
80
81#[derive(Debug, Clone, PartialEq)]
82pub struct VisualOdometryEstimate {
83 pub previous_frame_id: FrameId,
84 pub current_frame_id: FrameId,
85 pub previous_to_current: SE3,
86 pub match_count: usize,
87 pub inlier_count: usize,
88 pub mean_reprojection_error: Option<f64>,
89}
90
91impl VisualOdometryEstimate {
92 pub const fn new(
93 previous_frame_id: FrameId,
94 current_frame_id: FrameId,
95 previous_to_current: SE3,
96 ) -> Self {
97 Self {
98 previous_frame_id,
99 current_frame_id,
100 previous_to_current,
101 match_count: 0,
102 inlier_count: 0,
103 mean_reprojection_error: None,
104 }
105 }
106
107 pub fn pose_prior_from_previous_pose(&self, previous_pose: &Pose) -> Pose {
108 Pose {
109 world_to_camera: self
110 .previous_to_current
111 .compose(&previous_pose.world_to_camera),
112 }
113 }
114}
115
116#[derive(Debug, Clone, PartialEq)]
117pub struct VisualOdometryPosePrior {
118 pub estimate: VisualOdometryEstimate,
119 pub pose: Pose,
120}
121
122#[derive(Debug, Clone, PartialEq)]
123pub struct VisualOdometryPriorProvider<F> {
124 frontend: F,
125}
126
127impl<F> VisualOdometryPriorProvider<F> {
128 pub const fn new(frontend: F) -> Self {
129 Self { frontend }
130 }
131
132 pub const fn frontend(&self) -> &F {
133 &self.frontend
134 }
135
136 pub const fn frontend_mut(&mut self) -> &mut F {
137 &mut self.frontend
138 }
139
140 pub fn into_inner(self) -> F {
141 self.frontend
142 }
143}
144
145impl<F> VisualOdometryPriorProvider<F>
146where
147 F: VisualOdometryFrontend,
148{
149 pub fn predict_pose_prior(
150 &self,
151 previous_frame: &Frame,
152 previous_pose: &Pose,
153 current_frame: &Frame,
154 ) -> Result<Option<VisualOdometryPosePrior>, F::Error> {
155 let Some(estimate) = self
156 .frontend
157 .estimate_relative_pose(previous_frame, current_frame)?
158 else {
159 return Ok(None);
160 };
161 let pose = estimate.pose_prior_from_previous_pose(previous_pose);
162 Ok(Some(VisualOdometryPosePrior { estimate, pose }))
163 }
164}
165
166#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
167pub struct NoopVisualOdometryFrontend;
168
169impl VisualOdometryFrontend for NoopVisualOdometryFrontend {
170 type Error = std::convert::Infallible;
171
172 fn estimate_relative_pose(
173 &self,
174 _previous_frame: &Frame,
175 _current_frame: &Frame,
176 ) -> Result<Option<VisualOdometryEstimate>, Self::Error> {
177 Ok(None)
178 }
179}
180
181#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
182pub struct ConstantPoseMotionModel;
183
184impl MotionModel for ConstantPoseMotionModel {
185 fn predict_pose(
186 &self,
187 _frame: &Frame,
188 _last_result: Option<&TrackingResult>,
189 last_successful_pose: Option<&Pose>,
190 ) -> Option<Pose> {
191 last_successful_pose.cloned()
192 }
193
194 fn allows_pnp_pose_prior_warm_start(&self) -> bool {
195 false
196 }
197}
198
199#[derive(Debug, Clone, PartialEq)]
231pub struct ImuPredictiveMotionModel {
232 pub config: ImuPredictiveMotionModelConfig,
235 pending_samples: Vec<ImuPredictivePendingSample>,
238 velocity_world: nalgebra::Vector3<f64>,
245 last_predict_consumed_samples: bool,
250 last_successful_pose: Option<Pose>,
256}
257
258#[derive(Debug, Clone, PartialEq)]
260pub struct ImuPredictiveMotionModelConfig {
261 pub gravity_world: nalgebra::Vector3<f64>,
264 pub bias_gyro: nalgebra::Vector3<f64>,
266 pub bias_acc: nalgebra::Vector3<f64>,
268 pub body_to_sensor: SE3,
280 pub carry_forward_velocity_world: bool,
289}
290
291impl Default for ImuPredictiveMotionModelConfig {
292 fn default() -> Self {
293 Self {
294 gravity_world: nalgebra::Vector3::new(0.0, 9.81, 0.0),
295 bias_gyro: nalgebra::Vector3::zeros(),
296 bias_acc: nalgebra::Vector3::zeros(),
297 body_to_sensor: SE3::identity(),
298 carry_forward_velocity_world: false,
299 }
300 }
301}
302
303#[derive(Debug, Clone, PartialEq)]
304struct ImuPredictivePendingSample {
305 gyro: nalgebra::Vector3<f64>,
306 accel: nalgebra::Vector3<f64>,
307 dt: f64,
308}
309
310impl ImuPredictiveMotionModel {
311 pub fn new(config: ImuPredictiveMotionModelConfig) -> Self {
312 Self {
313 config,
314 pending_samples: Vec::new(),
315 velocity_world: nalgebra::Vector3::zeros(),
316 last_predict_consumed_samples: false,
317 last_successful_pose: None,
318 }
319 }
320
321 pub fn push_imu_measurement(
325 &mut self,
326 gyro: nalgebra::Vector3<f64>,
327 accel: nalgebra::Vector3<f64>,
328 dt: f64,
329 ) {
330 if dt <= 0.0 || dt.is_nan() {
331 return;
332 }
333 self.pending_samples
334 .push(ImuPredictivePendingSample { gyro, accel, dt });
335 }
336
337 pub const fn set_velocity_world(&mut self, velocity_world: nalgebra::Vector3<f64>) {
342 self.velocity_world = velocity_world;
343 }
344
345 pub fn body_velocity_from_camera_pose_difference(
354 &self,
355 prev: &Pose,
356 curr: &Pose,
357 dt_seconds: f64,
358 ) -> Option<nalgebra::Vector3<f64>> {
359 if dt_seconds <= 0.0 || !dt_seconds.is_finite() {
360 return None;
361 }
362 let body_prev = self
363 .config
364 .body_to_sensor
365 .compose(&prev.world_to_camera)
366 .inverse()
367 .translation;
368 let body_curr = self
369 .config
370 .body_to_sensor
371 .compose(&curr.world_to_camera)
372 .inverse()
373 .translation;
374 Some((body_curr - body_prev) / dt_seconds)
375 }
376
377 pub fn update_velocity_from_camera_pose_difference(
389 &mut self,
390 prev: &Pose,
391 curr: &Pose,
392 dt_seconds: f64,
393 ) {
394 if let Some(v) = self.body_velocity_from_camera_pose_difference(prev, curr, dt_seconds) {
395 self.velocity_world = v;
396 }
397 }
398
399 pub const fn set_biases(
401 &mut self,
402 bias_gyro: nalgebra::Vector3<f64>,
403 bias_acc: nalgebra::Vector3<f64>,
404 ) {
405 self.config.bias_gyro = bias_gyro;
406 self.config.bias_acc = bias_acc;
407 }
408
409 pub fn pending_samples_len(&self) -> usize {
412 self.pending_samples.len()
413 }
414
415 pub fn pending_samples_total_dt(&self) -> f64 {
422 self.pending_samples.iter().map(|s| s.dt).sum()
423 }
424
425 pub const fn velocity_world(&self) -> nalgebra::Vector3<f64> {
427 self.velocity_world
428 }
429}
430
431impl MotionModel for ImuPredictiveMotionModel {
432 fn predict_pose(
433 &self,
434 _frame: &Frame,
435 _last_result: Option<&TrackingResult>,
436 last_successful_pose: Option<&Pose>,
437 ) -> Option<Pose> {
438 let prev = last_successful_pose?;
439 if self.pending_samples.is_empty() {
440 return Some(prev.clone());
441 }
442 let t_bw_initial = self.config.body_to_sensor.compose(&prev.world_to_camera);
450 let t_wb_initial = t_bw_initial.inverse();
451 let mut r_wb = t_wb_initial.rotation;
452 let mut p_wb = t_wb_initial.translation;
453 let mut v_w = self.velocity_world;
454 for sample in &self.pending_samples {
455 let gyro_unbiased = sample.gyro - self.config.bias_gyro;
456 let accel_unbiased = sample.accel - self.config.bias_acc;
457 let accel_world = r_wb.transform_vector(&accel_unbiased) + self.config.gravity_world;
458 p_wb += v_w * sample.dt + 0.5 * accel_world * sample.dt * sample.dt;
463 v_w += accel_world * sample.dt;
464 r_wb *= UnitQuaternion::from_scaled_axis(gyro_unbiased * sample.dt);
465 }
466 let t_wb_new = SE3::new(r_wb, p_wb);
470 let t_bw_new = t_wb_new.inverse();
471 let t_cw_new = self.config.body_to_sensor.inverse().compose(&t_bw_new);
472 Some(Pose {
473 world_to_camera: t_cw_new,
474 })
475 }
476
477 fn observe(&mut self, result: &TrackingResult) {
478 if !result.localization.success {
479 return;
480 }
481 if self.config.carry_forward_velocity_world {
491 if let Some(prev) = self.last_successful_pose.as_ref() {
492 let t_bw_initial = self.config.body_to_sensor.compose(&prev.world_to_camera);
493 let t_wb_initial = t_bw_initial.inverse();
494 let mut r_wb = t_wb_initial.rotation;
495 let mut v_w = self.velocity_world;
496 for sample in &self.pending_samples {
497 let gyro_unbiased = sample.gyro - self.config.bias_gyro;
498 let accel_unbiased = sample.accel - self.config.bias_acc;
499 let accel_world =
500 r_wb.transform_vector(&accel_unbiased) + self.config.gravity_world;
501 v_w += accel_world * sample.dt;
502 r_wb *= UnitQuaternion::from_scaled_axis(gyro_unbiased * sample.dt);
503 }
504 self.velocity_world = v_w;
505 }
506 if let Some(pose) = result.localization.pose.as_ref() {
507 self.last_successful_pose = Some(pose.clone());
508 }
509 }
510 self.pending_samples.clear();
513 self.last_predict_consumed_samples = false;
514 }
515
516 fn reset(&mut self) {
517 self.pending_samples.clear();
518 self.velocity_world = nalgebra::Vector3::zeros();
519 self.last_predict_consumed_samples = false;
520 self.last_successful_pose = None;
521 }
522
523 fn apply_pose_correction(&mut self, correction: &SE3) {
524 self.velocity_world = correction.rotation.transform_vector(&self.velocity_world);
528 if let Some(pose) = self.last_successful_pose.as_mut() {
529 pose.world_to_camera = pose.world_to_camera.compose(&correction.inverse());
530 }
531 }
532
533 fn apply_similarity_correction(&mut self, correction: &Sim3) {
534 let se3_part = SE3::new(correction.rotation, correction.translation);
535 self.apply_pose_correction(&se3_part);
536 self.velocity_world *= correction.scale;
541 }
542}
543
544#[derive(Debug, Clone, Default, PartialEq)]
545pub struct ConstantVelocityMotionModel {
546 previous_successful_pose: Option<Pose>,
547 latest_successful_pose: Option<Pose>,
548}
549
550impl ConstantVelocityMotionModel {
551 pub fn new() -> Self {
552 Self::default()
553 }
554}
555
556impl MotionModel for ConstantVelocityMotionModel {
557 fn predict_pose(
558 &self,
559 _frame: &Frame,
560 _last_result: Option<&TrackingResult>,
561 last_successful_pose: Option<&Pose>,
562 ) -> Option<Pose> {
563 let (Some(previous), Some(latest)) = (
564 self.previous_successful_pose.as_ref(),
565 self.latest_successful_pose.as_ref(),
566 ) else {
567 return last_successful_pose.cloned();
568 };
569
570 let previous_center = previous.camera_center_world();
571 let latest_center = latest.camera_center_world();
572 let predicted_center = latest_center + (latest_center - previous_center);
573 let rotation = latest.world_to_camera.rotation;
574 let translation = -(rotation.transform_vector(&predicted_center.coords));
575 Some(Pose::from_world_to_camera(rotation, translation))
576 }
577
578 fn observe(&mut self, result: &TrackingResult) {
579 if !result.localization.success {
580 return;
581 }
582 let Some(pose) = result.localization.pose.as_ref() else {
583 return;
584 };
585 self.previous_successful_pose = self.latest_successful_pose.take();
586 self.latest_successful_pose = Some(pose.clone());
587 }
588
589 fn reset(&mut self) {
590 self.previous_successful_pose = None;
591 self.latest_successful_pose = None;
592 }
593
594 fn apply_pose_correction(&mut self, correction: &SE3) {
595 let inverse = correction.inverse();
596 if let Some(pose) = self.previous_successful_pose.as_mut() {
597 pose.world_to_camera = pose.world_to_camera.compose(&inverse);
598 }
599 if let Some(pose) = self.latest_successful_pose.as_mut() {
600 pose.world_to_camera = pose.world_to_camera.compose(&inverse);
601 }
602 }
603}
604
605#[derive(Debug, Clone, Copy, PartialEq, Eq)]
642pub enum ImuVelocityRefreshPolicy {
643 None,
648 FiniteDifference,
655 ZeroReset,
661 ThreePoseSmoother,
670}
671
672impl Default for ImuVelocityRefreshPolicy {
673 fn default() -> Self {
682 Self::ThreePoseSmoother
683 }
684}
685
686#[derive(Debug, Clone, PartialEq)]
687pub struct AdaptiveImuPoseMotionModelConfig {
688 pub failures_to_switch_to_pose: usize,
692 pub successes_to_switch_to_imu: usize,
697 pub imu_velocity_refresh_policy: ImuVelocityRefreshPolicy,
702}
703
704impl Default for AdaptiveImuPoseMotionModelConfig {
705 fn default() -> Self {
706 Self {
707 failures_to_switch_to_pose: 2,
708 successes_to_switch_to_imu: 5,
709 imu_velocity_refresh_policy: ImuVelocityRefreshPolicy::default(),
710 }
711 }
712}
713
714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
717pub enum AdaptiveMotionMode {
718 Imu,
719 Pose,
720}
721
722#[derive(Debug, Clone)]
738pub struct AdaptiveImuPoseMotionModel {
739 imu: ImuPredictiveMotionModel,
740 pose: ConstantPoseMotionModel,
741 config: AdaptiveImuPoseMotionModelConfig,
742 mode: AdaptiveMotionMode,
743 consecutive_failures_under_imu: usize,
744 consecutive_successes_under_pose: usize,
745 switches_to_pose: u64,
746 switches_to_imu: u64,
747 oldest_successful_pose: Option<Pose>,
755 previous_successful_pose: Option<Pose>,
763 latest_successful_pose: Option<Pose>,
764 dt_between_previous_two_observations: f64,
770 dt_between_latest_two_observations: f64,
777 velocity_refreshes_on_switch_to_imu: u64,
783}
784
785impl AdaptiveImuPoseMotionModel {
786 pub const fn new(
787 imu: ImuPredictiveMotionModel,
788 pose: ConstantPoseMotionModel,
789 config: AdaptiveImuPoseMotionModelConfig,
790 ) -> Self {
791 Self {
792 imu,
793 pose,
794 config,
795 mode: AdaptiveMotionMode::Imu,
796 consecutive_failures_under_imu: 0,
797 consecutive_successes_under_pose: 0,
798 switches_to_pose: 0,
799 switches_to_imu: 0,
800 oldest_successful_pose: None,
801 previous_successful_pose: None,
802 latest_successful_pose: None,
803 dt_between_previous_two_observations: 0.0,
804 dt_between_latest_two_observations: 0.0,
805 velocity_refreshes_on_switch_to_imu: 0,
806 }
807 }
808
809 pub fn with_defaults() -> Self {
813 Self::new(
814 ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
815 ConstantPoseMotionModel,
816 AdaptiveImuPoseMotionModelConfig::default(),
817 )
818 }
819
820 pub const fn imu(&self) -> &ImuPredictiveMotionModel {
821 &self.imu
822 }
823
824 pub const fn imu_mut(&mut self) -> &mut ImuPredictiveMotionModel {
829 &mut self.imu
830 }
831
832 pub const fn config(&self) -> &AdaptiveImuPoseMotionModelConfig {
833 &self.config
834 }
835
836 pub const fn mode(&self) -> AdaptiveMotionMode {
837 self.mode
838 }
839
840 pub const fn switches_to_pose(&self) -> u64 {
843 self.switches_to_pose
844 }
845
846 pub const fn switches_to_imu(&self) -> u64 {
849 self.switches_to_imu
850 }
851
852 pub const fn velocity_refreshes_on_switch_to_imu(&self) -> u64 {
860 self.velocity_refreshes_on_switch_to_imu
861 }
862}
863
864impl MotionModel for AdaptiveImuPoseMotionModel {
865 fn predict_pose(
866 &self,
867 frame: &Frame,
868 last_result: Option<&TrackingResult>,
869 last_successful_pose: Option<&Pose>,
870 ) -> Option<Pose> {
871 match self.mode {
872 AdaptiveMotionMode::Imu => {
873 self.imu
874 .predict_pose(frame, last_result, last_successful_pose)
875 }
876 AdaptiveMotionMode::Pose => {
877 self.pose
878 .predict_pose(frame, last_result, last_successful_pose)
879 }
880 }
881 }
882
883 fn allows_pnp_pose_prior_warm_start(&self) -> bool {
884 self.mode == AdaptiveMotionMode::Imu
885 }
886
887 fn observe(&mut self, result: &TrackingResult) {
888 let pending_dt_before_observe = self.imu.pending_samples_total_dt();
897 self.imu.observe(result);
901 self.pose.observe(result);
902 if result.localization.success {
903 if let Some(pose) = result.localization.pose.as_ref() {
904 self.oldest_successful_pose = self.previous_successful_pose.take();
905 self.previous_successful_pose = self.latest_successful_pose.take();
906 self.latest_successful_pose = Some(pose.clone());
907 self.dt_between_previous_two_observations = self.dt_between_latest_two_observations;
908 self.dt_between_latest_two_observations = pending_dt_before_observe;
909 }
910 match self.mode {
911 AdaptiveMotionMode::Imu => {
912 self.consecutive_failures_under_imu = 0;
913 }
914 AdaptiveMotionMode::Pose => {
915 self.consecutive_successes_under_pose += 1;
916 if self.consecutive_successes_under_pose
917 >= self.config.successes_to_switch_to_imu
918 {
919 self.mode = AdaptiveMotionMode::Imu;
920 self.switches_to_imu += 1;
921 self.consecutive_failures_under_imu = 0;
922 self.consecutive_successes_under_pose = 0;
923 self.maybe_refresh_imu_velocity_on_switch_to_imu();
924 }
925 }
926 }
927 } else {
928 match self.mode {
929 AdaptiveMotionMode::Imu => {
930 self.consecutive_failures_under_imu += 1;
931 if self.consecutive_failures_under_imu >= self.config.failures_to_switch_to_pose
932 {
933 self.mode = AdaptiveMotionMode::Pose;
934 self.switches_to_pose += 1;
935 self.consecutive_failures_under_imu = 0;
936 self.consecutive_successes_under_pose = 0;
937 }
938 }
939 AdaptiveMotionMode::Pose => {
940 self.consecutive_successes_under_pose = 0;
941 }
942 }
943 }
944 }
945
946 fn reset(&mut self) {
947 self.imu.reset();
948 self.pose.reset();
949 self.mode = AdaptiveMotionMode::Imu;
950 self.consecutive_failures_under_imu = 0;
951 self.consecutive_successes_under_pose = 0;
952 self.switches_to_pose = 0;
953 self.switches_to_imu = 0;
954 self.oldest_successful_pose = None;
955 self.previous_successful_pose = None;
956 self.latest_successful_pose = None;
957 self.dt_between_previous_two_observations = 0.0;
958 self.dt_between_latest_two_observations = 0.0;
959 self.velocity_refreshes_on_switch_to_imu = 0;
960 }
961
962 fn apply_pose_correction(&mut self, correction: &SE3) {
963 self.imu.apply_pose_correction(correction);
964 self.pose.apply_pose_correction(correction);
965 let inverse = correction.inverse();
966 for pose in [
967 self.oldest_successful_pose.as_mut(),
968 self.previous_successful_pose.as_mut(),
969 self.latest_successful_pose.as_mut(),
970 ]
971 .into_iter()
972 .flatten()
973 {
974 pose.world_to_camera = pose.world_to_camera.compose(&inverse);
975 }
976 }
977
978 fn apply_similarity_correction(&mut self, correction: &Sim3) {
979 self.imu.apply_similarity_correction(correction);
980 self.pose.apply_similarity_correction(correction);
981 let se3_part = SE3::new(correction.rotation, correction.translation);
987 let inverse = se3_part.inverse();
988 for pose in [
989 self.oldest_successful_pose.as_mut(),
990 self.previous_successful_pose.as_mut(),
991 self.latest_successful_pose.as_mut(),
992 ]
993 .into_iter()
994 .flatten()
995 {
996 pose.world_to_camera = pose.world_to_camera.compose(&inverse);
997 }
998 }
999}
1000
1001impl AdaptiveImuPoseMotionModel {
1002 fn maybe_refresh_imu_velocity_on_switch_to_imu(&mut self) {
1013 match self.config.imu_velocity_refresh_policy {
1014 ImuVelocityRefreshPolicy::None => {}
1015 ImuVelocityRefreshPolicy::ZeroReset => {
1016 self.imu.set_velocity_world(nalgebra::Vector3::zeros());
1017 self.velocity_refreshes_on_switch_to_imu += 1;
1018 }
1019 ImuVelocityRefreshPolicy::FiniteDifference => {
1020 let (Some(prev), Some(curr)) = (
1021 self.previous_successful_pose.as_ref(),
1022 self.latest_successful_pose.as_ref(),
1023 ) else {
1024 return;
1025 };
1026 let dt = self.dt_between_latest_two_observations;
1027 let Some(v) = self
1028 .imu
1029 .body_velocity_from_camera_pose_difference(prev, curr, dt)
1030 else {
1031 return;
1032 };
1033 self.imu.set_velocity_world(v);
1034 self.velocity_refreshes_on_switch_to_imu += 1;
1035 }
1036 ImuVelocityRefreshPolicy::ThreePoseSmoother => {
1037 let (Some(prev), Some(curr)) = (
1038 self.previous_successful_pose.as_ref(),
1039 self.latest_successful_pose.as_ref(),
1040 ) else {
1041 return;
1042 };
1043 let dt_latest = self.dt_between_latest_two_observations;
1044 let Some(v_latest) = self
1045 .imu
1046 .body_velocity_from_camera_pose_difference(prev, curr, dt_latest)
1047 else {
1048 return;
1049 };
1050 let v_write = match self.oldest_successful_pose.as_ref() {
1057 Some(oldest) => self
1058 .imu
1059 .body_velocity_from_camera_pose_difference(
1060 oldest,
1061 prev,
1062 self.dt_between_previous_two_observations,
1063 )
1064 .map_or(v_latest, |v_prev| (v_prev + v_latest) * 0.5),
1065 None => v_latest,
1066 };
1067 self.imu.set_velocity_world(v_write);
1068 self.velocity_refreshes_on_switch_to_imu += 1;
1069 }
1070 }
1071 }
1072}
1073
1074#[cfg(test)]
1075mod imu_predictive_motion_tests {
1076 use super::*;
1077 use nalgebra::{UnitQuaternion, Vector3};
1078 use visloc_core::geometry::Pose;
1079 use visloc_core::types::Frame;
1080
1081 fn make_dummy_frame() -> Frame {
1082 Frame::new(1, 1)
1083 }
1084
1085 fn rotation_angle_deg(a: &Pose, b: &Pose) -> f64 {
1086 let q_a = a.world_to_camera.rotation;
1087 let q_b = b.world_to_camera.rotation;
1088 q_a.rotation_to(&q_b).angle().to_degrees()
1089 }
1090
1091 #[test]
1092 fn imu_predictive_motion_returns_last_pose_when_no_samples_pushed() {
1093 let model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1094 let prev =
1095 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 5.0));
1096 let predicted = model
1097 .predict_pose(&make_dummy_frame(), None, Some(&prev))
1098 .expect("predicted pose");
1099 assert_eq!(
1100 predicted.world_to_camera.translation,
1101 prev.world_to_camera.translation
1102 );
1103 assert_eq!(
1104 predicted.world_to_camera.rotation,
1105 prev.world_to_camera.rotation
1106 );
1107 }
1108
1109 #[test]
1110 fn imu_predictive_motion_returns_none_when_no_previous_pose() {
1111 let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1112 model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
1113 assert!(model
1114 .predict_pose(&make_dummy_frame(), None, None)
1115 .is_none());
1116 }
1117
1118 #[test]
1119 fn imu_predictive_motion_stationary_under_gravity_holds_pose() {
1120 let config = ImuPredictiveMotionModelConfig {
1125 gravity_world: Vector3::new(0.0, 0.0, -9.81),
1126 ..ImuPredictiveMotionModelConfig::default()
1127 };
1128 let mut model = ImuPredictiveMotionModel::new(config);
1129 for _ in 0..10 {
1130 model.push_imu_measurement(Vector3::zeros(), Vector3::new(0.0, 0.0, 9.81), 0.05);
1131 }
1132 let prev = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1133 let predicted = model
1134 .predict_pose(&make_dummy_frame(), None, Some(&prev))
1135 .expect("predicted");
1136 let predicted_center = predicted.camera_center_world();
1137 assert!(
1138 predicted_center.coords.norm() < 1.0e-9,
1139 "predicted center should stay at origin under stationary IMU, got {:?}",
1140 predicted_center
1141 );
1142 assert!(rotation_angle_deg(&predicted, &prev) < 1.0e-6);
1143 }
1144
1145 #[test]
1146 fn imu_predictive_motion_pure_yaw_rotation_propagates_rotation() {
1147 let config = ImuPredictiveMotionModelConfig {
1151 gravity_world: Vector3::zeros(),
1152 ..ImuPredictiveMotionModelConfig::default()
1153 };
1154 let mut model = ImuPredictiveMotionModel::new(config);
1155 let yaw_rate = std::f64::consts::FRAC_PI_2;
1156 for _ in 0..100 {
1157 model.push_imu_measurement(Vector3::new(0.0, 0.0, yaw_rate), Vector3::zeros(), 0.01);
1158 }
1159 let prev = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1160 let predicted = model
1161 .predict_pose(&make_dummy_frame(), None, Some(&prev))
1162 .expect("predicted");
1163 let expected_r_bw = UnitQuaternion::from_axis_angle(&Vector3::z_axis(), yaw_rate);
1166 let expected_r_wc = expected_r_bw.inverse();
1167 let actual_r_wc = predicted.world_to_camera.rotation;
1168 let angle_err = actual_r_wc.rotation_to(&expected_r_wc).angle().to_degrees();
1169 assert!(
1170 angle_err < 0.1,
1171 "yaw rotation drift too large: {angle_err} deg"
1172 );
1173 }
1174
1175 #[test]
1176 fn imu_predictive_motion_constant_velocity_translates_position() {
1177 let config = ImuPredictiveMotionModelConfig {
1181 gravity_world: Vector3::zeros(),
1182 ..ImuPredictiveMotionModelConfig::default()
1183 };
1184 let mut model = ImuPredictiveMotionModel::new(config);
1185 model.set_velocity_world(Vector3::new(1.0, 0.0, 0.0));
1186 for _ in 0..100 {
1187 model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.01);
1188 }
1189 let prev = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1190 let predicted = model
1191 .predict_pose(&make_dummy_frame(), None, Some(&prev))
1192 .expect("predicted");
1193 let center = predicted.camera_center_world();
1194 assert!(
1195 (center.x - 1.0).abs() < 1.0e-9,
1196 "predicted x should be 1.0 (start 0 + 1 m/s * 1 s), got {}",
1197 center.x
1198 );
1199 assert!(center.y.abs() < 1.0e-9);
1200 assert!(center.z.abs() < 1.0e-9);
1201 }
1202
1203 #[test]
1204 fn imu_predictive_motion_observe_drains_pending_window_on_success() {
1205 use visloc_core::types::LocalizationSuccess;
1206 let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1207 for _ in 0..3 {
1208 model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.05);
1209 }
1210 assert_eq!(model.pending_samples_len(), 3);
1211 let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1212 let localization = LocalizationResult::success(LocalizationSuccess {
1213 pose,
1214 candidate_landmark_count: 4,
1215 match_count: 4,
1216 correspondence_count: 4,
1217 inliers: vec![0, 1, 2, 3],
1218 inlier_query_indices: vec![0, 1, 2, 3],
1219 inlier_landmark_ids: vec![1, 2, 3, 4],
1220 inlier_confidences: vec![None; 4],
1221 inlier_reprojection_errors: vec![0.0; 4],
1222 mean_reprojection_error: 0.0,
1223 median_reprojection_error: 0.0,
1224 max_reprojection_error: 0.0,
1225 });
1226 let success = TrackingResult {
1227 frame_id: 1,
1228 state: TrackingState::Tracking,
1229 event: TrackingEvent::Tracked,
1230 successive_failures: 0,
1231 pose_prior: None,
1232 used_pose_prior: false,
1233 used_external_localization_prior: false,
1234 external_localization_prior_radius: None,
1235 tracking_failure_reason: None,
1236 map_landmark_count: 0,
1237 map_stats: MapProviderStats::default(),
1238 localization,
1239 covisibility_local_map_size: None,
1240 };
1241 model.observe(&success);
1242 assert_eq!(model.pending_samples_len(), 0);
1243 }
1244
1245 #[test]
1246 fn imu_predictive_motion_reset_clears_velocity_and_samples() {
1247 let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1248 model.set_velocity_world(Vector3::new(3.0, 0.0, 0.0));
1249 model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.05);
1250 model.reset();
1251 assert_eq!(model.pending_samples_len(), 0);
1252 assert_eq!(model.velocity_world(), Vector3::zeros());
1253 }
1254
1255 #[test]
1256 fn imu_predictive_motion_carry_forward_default_off_leaves_velocity_frozen() {
1257 use visloc_core::types::LocalizationSuccess;
1258 let config = ImuPredictiveMotionModelConfig {
1262 gravity_world: Vector3::zeros(),
1263 ..ImuPredictiveMotionModelConfig::default()
1264 };
1265 let mut model = ImuPredictiveMotionModel::new(config);
1266 model.set_velocity_world(Vector3::new(1.0, 0.0, 0.0));
1267 for _ in 0..10 {
1268 model.push_imu_measurement(Vector3::zeros(), Vector3::new(2.0, 0.0, 0.0), 0.1);
1269 }
1270 let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1271 let localization = LocalizationResult::success(LocalizationSuccess {
1272 pose,
1273 candidate_landmark_count: 4,
1274 match_count: 4,
1275 correspondence_count: 4,
1276 inliers: vec![0, 1, 2, 3],
1277 inlier_query_indices: vec![0, 1, 2, 3],
1278 inlier_landmark_ids: vec![1, 2, 3, 4],
1279 inlier_confidences: vec![None; 4],
1280 inlier_reprojection_errors: vec![0.0; 4],
1281 mean_reprojection_error: 0.0,
1282 median_reprojection_error: 0.0,
1283 max_reprojection_error: 0.0,
1284 });
1285 let result = TrackingResult {
1286 frame_id: 1,
1287 state: TrackingState::Tracking,
1288 event: TrackingEvent::Tracked,
1289 successive_failures: 0,
1290 pose_prior: None,
1291 used_pose_prior: false,
1292 used_external_localization_prior: false,
1293 external_localization_prior_radius: None,
1294 tracking_failure_reason: None,
1295 map_landmark_count: 0,
1296 map_stats: MapProviderStats::default(),
1297 localization,
1298 covisibility_local_map_size: None,
1299 };
1300 model.observe(&result);
1301 let v = model.velocity_world();
1302 assert!((v - Vector3::new(1.0, 0.0, 0.0)).norm() < 1.0e-12);
1303 }
1304
1305 #[test]
1306 fn imu_predictive_motion_carry_forward_on_advances_velocity_per_frame() {
1307 use visloc_core::types::LocalizationSuccess;
1308 let config = ImuPredictiveMotionModelConfig {
1313 gravity_world: Vector3::zeros(),
1314 carry_forward_velocity_world: true,
1315 ..ImuPredictiveMotionModelConfig::default()
1316 };
1317 let mut model = ImuPredictiveMotionModel::new(config);
1318 model.set_velocity_world(Vector3::new(1.0, 0.0, 0.0));
1319 let pose_zero = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1323 let localization_zero = LocalizationResult::success(LocalizationSuccess {
1324 pose: pose_zero.clone(),
1325 candidate_landmark_count: 4,
1326 match_count: 4,
1327 correspondence_count: 4,
1328 inliers: vec![0, 1, 2, 3],
1329 inlier_query_indices: vec![0, 1, 2, 3],
1330 inlier_landmark_ids: vec![1, 2, 3, 4],
1331 inlier_confidences: vec![None; 4],
1332 inlier_reprojection_errors: vec![0.0; 4],
1333 mean_reprojection_error: 0.0,
1334 median_reprojection_error: 0.0,
1335 max_reprojection_error: 0.0,
1336 });
1337 let make_result = |pose: Pose| TrackingResult {
1338 frame_id: 1,
1339 state: TrackingState::Tracking,
1340 event: TrackingEvent::Tracked,
1341 successive_failures: 0,
1342 pose_prior: None,
1343 used_pose_prior: false,
1344 used_external_localization_prior: false,
1345 external_localization_prior_radius: None,
1346 tracking_failure_reason: None,
1347 map_landmark_count: 0,
1348 map_stats: MapProviderStats::default(),
1349 localization: LocalizationResult::success(LocalizationSuccess {
1350 pose,
1351 candidate_landmark_count: 4,
1352 match_count: 4,
1353 correspondence_count: 4,
1354 inliers: vec![0, 1, 2, 3],
1355 inlier_query_indices: vec![0, 1, 2, 3],
1356 inlier_landmark_ids: vec![1, 2, 3, 4],
1357 inlier_confidences: vec![None; 4],
1358 inlier_reprojection_errors: vec![0.0; 4],
1359 mean_reprojection_error: 0.0,
1360 median_reprojection_error: 0.0,
1361 max_reprojection_error: 0.0,
1362 }),
1363 covisibility_local_map_size: None,
1364 };
1365 model.observe(&TrackingResult {
1367 localization: localization_zero,
1368 ..make_result(pose_zero)
1369 });
1370 for _ in 0..10 {
1372 model.push_imu_measurement(Vector3::zeros(), Vector3::new(2.0, 0.0, 0.0), 0.1);
1373 }
1374 let pose_next =
1378 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-2.0, 0.0, 0.0));
1379 model.observe(&make_result(pose_next));
1380 let v = model.velocity_world();
1381 assert!(
1382 (v - Vector3::new(3.0, 0.0, 0.0)).norm() < 1.0e-9,
1383 "velocity_world should have advanced from (1,0,0) by ∫(2,0,0) dt = (2,0,0) to (3,0,0); got {v:?}",
1384 );
1385 }
1386
1387 #[test]
1388 fn imu_predictive_motion_carry_forward_reset_clears_last_successful_pose() {
1389 use visloc_core::types::LocalizationSuccess;
1390 let config = ImuPredictiveMotionModelConfig {
1394 gravity_world: Vector3::zeros(),
1395 carry_forward_velocity_world: true,
1396 ..ImuPredictiveMotionModelConfig::default()
1397 };
1398 let mut model = ImuPredictiveMotionModel::new(config);
1399 let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1400 let localization = LocalizationResult::success(LocalizationSuccess {
1401 pose,
1402 candidate_landmark_count: 4,
1403 match_count: 4,
1404 correspondence_count: 4,
1405 inliers: vec![0, 1, 2, 3],
1406 inlier_query_indices: vec![0, 1, 2, 3],
1407 inlier_landmark_ids: vec![1, 2, 3, 4],
1408 inlier_confidences: vec![None; 4],
1409 inlier_reprojection_errors: vec![0.0; 4],
1410 mean_reprojection_error: 0.0,
1411 median_reprojection_error: 0.0,
1412 max_reprojection_error: 0.0,
1413 });
1414 let result = TrackingResult {
1415 frame_id: 1,
1416 state: TrackingState::Tracking,
1417 event: TrackingEvent::Tracked,
1418 successive_failures: 0,
1419 pose_prior: None,
1420 used_pose_prior: false,
1421 used_external_localization_prior: false,
1422 external_localization_prior_radius: None,
1423 tracking_failure_reason: None,
1424 map_landmark_count: 0,
1425 map_stats: MapProviderStats::default(),
1426 localization,
1427 covisibility_local_map_size: None,
1428 };
1429 model.observe(&result);
1430 model.set_velocity_world(Vector3::new(5.0, 0.0, 0.0));
1431 model.push_imu_measurement(Vector3::zeros(), Vector3::new(99.0, 0.0, 0.0), 0.1);
1432 model.reset();
1433 model.push_imu_measurement(Vector3::zeros(), Vector3::new(99.0, 0.0, 0.0), 0.1);
1437 model.observe(&result);
1438 assert_eq!(model.velocity_world(), Vector3::zeros());
1439 }
1440
1441 #[test]
1442 fn imu_predictive_motion_t_bs_offset_preserves_extrinsic_under_translation() {
1443 let body_to_sensor = SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0));
1453 let config = ImuPredictiveMotionModelConfig {
1454 gravity_world: Vector3::zeros(),
1455 body_to_sensor,
1456 ..ImuPredictiveMotionModelConfig::default()
1457 };
1458 let mut model = ImuPredictiveMotionModel::new(config);
1459 model.set_velocity_world(Vector3::new(1.0, 0.0, 0.0));
1460 for _ in 0..50 {
1461 model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.01);
1462 }
1463 let prev =
1468 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.1, 0.0, 0.0));
1469 let predicted = model
1470 .predict_pose(&make_dummy_frame(), None, Some(&prev))
1471 .expect("predicted");
1472 let center = predicted.camera_center_world();
1473 assert!(
1474 (center.x - 0.6).abs() < 1.0e-9,
1475 "predicted camera x should be 0.6 (body 0.5 + extrinsic 0.1), got {}",
1476 center.x
1477 );
1478 assert!(center.y.abs() < 1.0e-9);
1479 assert!(center.z.abs() < 1.0e-9);
1480 assert!(rotation_angle_deg(&predicted, &prev) < 1.0e-6);
1482 }
1483
1484 #[test]
1485 fn imu_predictive_motion_update_velocity_from_camera_pose_diff_recovers_body_velocity() {
1486 let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1491 let prev = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1492 let curr =
1493 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.5, 0.0, 0.0));
1494 model.update_velocity_from_camera_pose_difference(&prev, &curr, 0.5);
1495 let v = model.velocity_world();
1496 assert!((v.x - 1.0).abs() < 1.0e-9);
1497 assert!(v.y.abs() < 1.0e-9);
1498 assert!(v.z.abs() < 1.0e-9);
1499 }
1500
1501 #[test]
1502 fn imu_predictive_motion_update_velocity_with_lever_arm_uses_body_centre() {
1503 let body_to_sensor = SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0));
1510 let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig {
1511 body_to_sensor,
1512 ..ImuPredictiveMotionModelConfig::default()
1513 });
1514 let prev =
1517 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.1, 0.0, 0.0));
1518 let curr =
1519 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.6, 0.0, 0.0));
1520 model.update_velocity_from_camera_pose_difference(&prev, &curr, 0.5);
1521 let v = model.velocity_world();
1522 assert!((v.x - 1.0).abs() < 1.0e-9);
1523 }
1524
1525 #[test]
1526 fn imu_predictive_motion_update_velocity_rejects_nonpositive_dt() {
1527 let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1528 model.set_velocity_world(Vector3::new(5.0, 0.0, 0.0));
1529 let p = Pose::identity();
1530 model.update_velocity_from_camera_pose_difference(&p, &p, 0.0);
1531 assert_eq!(model.velocity_world(), Vector3::new(5.0, 0.0, 0.0));
1532 model.update_velocity_from_camera_pose_difference(&p, &p, -1.0);
1533 assert_eq!(model.velocity_world(), Vector3::new(5.0, 0.0, 0.0));
1534 model.update_velocity_from_camera_pose_difference(&p, &p, f64::NAN);
1535 assert_eq!(model.velocity_world(), Vector3::new(5.0, 0.0, 0.0));
1536 }
1537
1538 #[test]
1539 fn imu_predictive_motion_t_bs_offset_propagates_rotation_with_lever_arm() {
1540 let body_to_sensor = SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0));
1549 let config = ImuPredictiveMotionModelConfig {
1550 gravity_world: Vector3::zeros(),
1551 body_to_sensor,
1552 ..ImuPredictiveMotionModelConfig::default()
1553 };
1554 let mut model = ImuPredictiveMotionModel::new(config);
1555 let yaw_rate = std::f64::consts::FRAC_PI_2;
1556 for _ in 0..100 {
1557 model.push_imu_measurement(Vector3::new(0.0, 0.0, yaw_rate), Vector3::zeros(), 0.01);
1558 }
1559 let prev =
1562 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.1, 0.0, 0.0));
1563 let predicted = model
1564 .predict_pose(&make_dummy_frame(), None, Some(&prev))
1565 .expect("predicted");
1566 let center = predicted.camera_center_world();
1567 assert!(
1570 center.x.abs() < 1.0e-3,
1571 "predicted camera x should be ≈0 after +90° yaw with lever arm, got {}",
1572 center.x
1573 );
1574 assert!(
1575 (center.y - 0.1).abs() < 1.0e-3,
1576 "predicted camera y should be ≈0.1 after +90° yaw, got {}",
1577 center.y
1578 );
1579 assert!(center.z.abs() < 1.0e-9);
1580 }
1581}