1use std::collections::HashMap;
39
40use nalgebra::{Point2, Vector3};
41use visloc_core::geometry::{Pose, SE3};
42use visloc_core::types::{
43 Camera, CameraId, Keyframe, Landmark, LandmarkDescriptorStore, LandmarkId, Observation,
44 VisualMap,
45};
46use visloc_vision::matching::HammingMatcher;
47use visloc_vision::pnp::{GaussNewtonPoseRefiner, P3PGrunert};
48use visloc_vision::ransac::PnPRansac;
49
50use crate::odom_correction::{wrap_angle, yaw_of, Offset};
51use crate::{
52 AllLandmarksSelector, BinaryLandmarkIndex, BinaryMatchGates, LocalizationConfig,
53 LocalizationPipeline,
54};
55
56#[derive(Debug, Clone, PartialEq)]
58pub struct MapMergeConfig {
59 pub gates: BinaryMatchGates,
61 pub min_inliers: usize,
63 pub ransac_iterations: usize,
64 pub reprojection_px: f64,
65 pub min_keyframes: usize,
67 pub agreement_m: f64,
70 pub agreement_yaw_deg: f64,
73 pub fuse_radius_m: f64,
76 pub fuse_max_hamming: u32,
78 pub threads: usize,
80}
81
82impl Default for MapMergeConfig {
83 fn default() -> Self {
86 Self {
87 gates: BinaryMatchGates {
88 max_distance: 70,
89 ratio: Some(0.8),
90 },
91 min_inliers: 15,
92 ransac_iterations: 1000,
93 reprojection_px: 3.0,
94 min_keyframes: 3,
95 agreement_m: 0.25,
96 agreement_yaw_deg: 2.0,
97 fuse_radius_m: 0.10,
98 fuse_max_hamming: 50,
99 threads: 1,
100 }
101 }
102}
103
104#[derive(Debug, Clone, PartialEq)]
106pub struct MapRegistration {
107 pub base_from_other: SE3,
109 pub keyframes: usize,
111 pub localized_keyframes: usize,
113 pub agreeing_keyframes: usize,
115 pub keyframe_rms_m: f64,
118}
119
120#[derive(Debug, Clone)]
122pub struct MergedMap {
123 pub map: VisualMap,
124 pub descriptors: LandmarkDescriptorStore,
125 pub keyframe_ids: HashMap<u64, u64>,
127 pub landmark_ids: HashMap<LandmarkId, LandmarkId>,
130 pub fused_landmarks: usize,
132 pub camera_ids: HashMap<CameraId, CameraId>,
136}
137
138#[derive(Debug, Clone, PartialEq)]
139pub enum MapMergeError {
140 EmptyBaseMap,
142 TooFewKeyframes {
144 localized: usize,
145 agreeing: usize,
146 needed: usize,
147 },
148 CameraMismatch { camera_id: CameraId },
153}
154
155impl std::fmt::Display for MapMergeError {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 match self {
158 Self::EmptyBaseMap => write!(f, "the base map has no landmark descriptors"),
159 Self::TooFewKeyframes {
160 localized,
161 agreeing,
162 needed,
163 } => write!(
164 f,
165 "{localized} keyframes localized in the base map and at most {agreeing} agree \
166 on a transform; {needed} needed"
167 ),
168 Self::CameraMismatch { camera_id } => write!(
169 f,
170 "camera {camera_id} differs between the maps (or is missing from the base map)"
171 ),
172 }
173 }
174}
175
176impl std::error::Error for MapMergeError {}
177
178#[derive(Debug, Clone)]
180struct KeyframeFix {
181 other_centre: Vector3<f64>,
182 base_centre: Vector3<f64>,
183 yaw: f64,
185}
186
187impl KeyframeFix {
188 fn residual(&self, offset: &Offset) -> f64 {
191 (offset.rotation() * self.other_centre + offset.translation - self.base_centre).norm()
192 }
193
194 fn agrees(&self, offset: &Offset, config: &MapMergeConfig) -> bool {
195 self.residual(offset) <= config.agreement_m
196 && wrap_angle(self.yaw - offset.yaw).abs() <= config.agreement_yaw_deg.to_radians()
197 }
198
199 fn offset(&self) -> Offset {
201 fit_keyframes(&[self])
202 }
203}
204
205fn fit_keyframes(fixes: &[&KeyframeFix]) -> Offset {
207 let (sin, cos) = fixes.iter().fold((0.0, 0.0), |(sin, cos), fix| {
208 (sin + fix.yaw.sin(), cos + fix.yaw.cos())
209 });
210 let mut offset = Offset {
211 yaw: sin.atan2(cos),
212 translation: Vector3::zeros(),
213 };
214 let rotation = offset.rotation();
215 offset.translation = fixes
216 .iter()
217 .map(|fix| fix.base_centre - rotation * fix.other_centre)
218 .sum::<Vector3<f64>>()
219 / fixes.len() as f64;
220 offset
221}
222
223type Pipeline = LocalizationPipeline<HammingMatcher, AllLandmarksSelector, PnPRansac<P3PGrunert>>;
224
225fn pnp_pipeline(config: &MapMergeConfig) -> Pipeline {
226 let ransac = PnPRansac {
227 pose_estimator: P3PGrunert,
228 pose_refiner: Some(GaussNewtonPoseRefiner::default()),
229 iterations: config.ransac_iterations,
230 reprojection_threshold: config.reprojection_px,
231 seed: 7,
232 early_stop_min_iterations: 0,
233 early_stop_inlier_ratio: None,
234 confidence: Some(0.999),
235 inlier_refits: 0,
236 };
237 LocalizationPipeline::with_pose_estimator(
238 HammingMatcher {
239 max_distance: config.gates.max_distance,
240 ratio: config.gates.ratio,
241 },
242 AllLandmarksSelector,
243 ransac,
244 LocalizationConfig {
245 ratio: config.gates.ratio,
246 ransac_iterations: config.ransac_iterations,
247 reprojection_threshold: config.reprojection_px,
248 min_inliers: config.min_inliers,
249 ..LocalizationConfig::default()
250 },
251 )
252}
253
254fn localize_keyframe(
256 keyframe: &Keyframe,
257 other: &VisualMap,
258 other_descriptors: &LandmarkDescriptorStore,
259 index: &BinaryLandmarkIndex,
260 pipeline: &Pipeline,
261 config: &MapMergeConfig,
262) -> Option<KeyframeFix> {
263 let pose = keyframe.frame.pose.as_ref()?;
264 let camera = other.cameras.get(&keyframe.frame.camera_id)?;
265 let mut keypoints = Vec::<Point2<f64>>::new();
266 let mut descriptors = Vec::<&[f32]>::new();
267 for observation in &keyframe.observations {
268 if let (true, Some(descriptor)) = (
269 other.landmarks.contains_key(&observation.landmark_id),
270 other_descriptors.get(observation.landmark_id),
271 ) {
272 keypoints.push(observation.xy);
273 descriptors.push(descriptor);
274 }
275 }
276 if keypoints.len() < config.min_inliers {
277 return None;
278 }
279 let correspondences =
280 index.match_all(&keypoints, &index.pack_query(&descriptors), config.gates, 1);
281 let result = pipeline.localize_correspondences(camera, correspondences);
282 let base_pose = result.pose.as_ref().filter(|_| result.success)?;
283 let base_from_other = base_pose
284 .camera_to_world()
285 .compose(&pose.world_to_camera)
286 .rotation;
287 Some(KeyframeFix {
288 other_centre: pose.camera_center_world().coords,
289 base_centre: base_pose.camera_center_world().coords,
290 yaw: yaw_of(&base_from_other),
291 })
292}
293
294pub fn register_map(
297 base: &VisualMap,
298 base_descriptors: &LandmarkDescriptorStore,
299 other: &VisualMap,
300 other_descriptors: &LandmarkDescriptorStore,
301 config: &MapMergeConfig,
302) -> Result<MapRegistration, MapMergeError> {
303 let index = BinaryLandmarkIndex::new(base, base_descriptors);
304 if index.is_empty() {
305 return Err(MapMergeError::EmptyBaseMap);
306 }
307 let pipeline = pnp_pipeline(config);
308 let mut keyframes = other
309 .keyframes
310 .values()
311 .filter(|keyframe| keyframe.frame.pose.is_some())
312 .collect::<Vec<_>>();
313 keyframes.sort_by_key(|keyframe| keyframe.frame.id);
314
315 let localize = |keyframes: &[&Keyframe]| {
316 keyframes
317 .iter()
318 .map(|keyframe| {
319 localize_keyframe(
320 keyframe,
321 other,
322 other_descriptors,
323 &index,
324 &pipeline,
325 config,
326 )
327 })
328 .collect::<Vec<_>>()
329 };
330 let threads = config.threads.clamp(1, keyframes.len().max(1));
331 let fixes = if threads == 1 {
332 localize(&keyframes)
333 } else {
334 let chunk = keyframes.len().div_ceil(threads);
335 std::thread::scope(|scope| {
336 let handles = keyframes
337 .chunks(chunk)
338 .map(|chunk| {
339 let localize = &localize;
340 scope.spawn(move || localize(chunk))
341 })
342 .collect::<Vec<_>>();
343 handles
344 .into_iter()
345 .flat_map(|handle| handle.join().expect("registration thread panicked"))
346 .collect()
347 })
348 };
349 let fixes = fixes.into_iter().flatten().collect::<Vec<_>>();
350
351 let agreeing = |offset: &Offset| {
354 fixes
355 .iter()
356 .filter(|fix| fix.agrees(offset, config))
357 .collect::<Vec<_>>()
358 };
359 let mut best = Vec::new();
360 for fix in &fixes {
361 let candidate = agreeing(&fix.offset());
362 if candidate.len() > best.len() {
363 best = candidate;
364 }
365 }
366 for _ in 0..5 {
367 if best.is_empty() {
368 break;
369 }
370 let refitted = agreeing(&fit_keyframes(&best));
371 let settled = refitted.len() == best.len();
372 best = refitted;
373 if settled {
374 break;
375 }
376 }
377 if best.len() < config.min_keyframes.max(1) {
378 return Err(MapMergeError::TooFewKeyframes {
379 localized: fixes.len(),
380 agreeing: best.len(),
381 needed: config.min_keyframes.max(1),
382 });
383 }
384 let offset = fit_keyframes(&best);
385 let keyframe_rms_m = (best
386 .iter()
387 .map(|fix| fix.residual(&offset).powi(2))
388 .sum::<f64>()
389 / best.len() as f64)
390 .sqrt();
391
392 Ok(MapRegistration {
393 base_from_other: offset.se3(),
394 keyframes: keyframes.len(),
395 localized_keyframes: fixes.len(),
396 agreeing_keyframes: best.len(),
397 keyframe_rms_m,
398 })
399}
400
401fn same_camera(lhs: &Camera, rhs: &Camera) -> bool {
402 lhs.model == rhs.model
403 && (lhs.width, lhs.height) == (rhs.width, rhs.height)
404 && lhs.params.len() == rhs.params.len()
405 && lhs
406 .params
407 .iter()
408 .zip(&rhs.params)
409 .all(|(a, b)| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0))
410}
411
412fn bit_distance(lhs: &[f32], rhs: &[f32]) -> u32 {
415 if lhs.len() != rhs.len() {
416 return u32::MAX;
417 }
418 lhs.iter()
419 .zip(rhs)
420 .filter(|(a, b)| (**a >= 0.5) != (**b >= 0.5))
421 .count() as u32
422}
423
424fn fusion_targets(
428 base: &VisualMap,
429 base_descriptors: &LandmarkDescriptorStore,
430 other_positions: &[(LandmarkId, Vector3<f64>, &[f32])],
431 config: &MapMergeConfig,
432) -> HashMap<LandmarkId, LandmarkId> {
433 let radius = config.fuse_radius_m;
434 if radius <= 0.0 {
435 return HashMap::new();
436 }
437 let cell = |position: &Vector3<f64>| {
438 (
439 (position.x / radius).floor() as i64,
440 (position.y / radius).floor() as i64,
441 (position.z / radius).floor() as i64,
442 )
443 };
444 let mut grid = HashMap::<(i64, i64, i64), Vec<(LandmarkId, Vector3<f64>, &[f32])>>::new();
445 for landmark in base.landmarks.values() {
446 if let Some(descriptor) = base_descriptors.get(landmark.id) {
447 grid.entry(cell(&landmark.position.coords))
448 .or_default()
449 .push((landmark.id, landmark.position.coords, descriptor));
450 }
451 }
452 let mut candidates = Vec::new();
453 for &(other_id, position, descriptor) in other_positions {
454 let (x, y, z) = cell(&position);
455 for dx in -1..=1 {
456 for dy in -1..=1 {
457 for dz in -1..=1 {
458 for (base_id, base_position, base_descriptor) in
459 grid.get(&(x + dx, y + dy, z + dz)).into_iter().flatten()
460 {
461 let distance = (base_position - position).norm();
462 let bits = bit_distance(descriptor, base_descriptor);
463 if distance <= radius && bits <= config.fuse_max_hamming {
464 candidates.push((bits, distance, other_id, *base_id));
465 }
466 }
467 }
468 }
469 }
470 }
471 candidates.sort_by(|a, b| {
472 (a.0, a.1, a.2, a.3)
473 .partial_cmp(&(b.0, b.1, b.2, b.3))
474 .expect("finite distances")
475 });
476 let mut targets = HashMap::new();
477 let mut taken = std::collections::HashSet::new();
478 for (_, _, other_id, base_id) in candidates {
479 if !targets.contains_key(&other_id) && taken.insert(base_id) {
480 targets.insert(other_id, base_id);
481 }
482 }
483 targets
484}
485
486pub fn merge_maps(
490 base: &VisualMap,
491 base_descriptors: &LandmarkDescriptorStore,
492 other: &VisualMap,
493 other_descriptors: &LandmarkDescriptorStore,
494 base_from_other: &SE3,
495 config: &MapMergeConfig,
496) -> Result<MergedMap, MapMergeError> {
497 let mut map = base.clone();
500 let mut other_camera_ids = other.cameras.keys().copied().collect::<Vec<_>>();
501 other_camera_ids.sort_unstable();
502 let mut camera_ids = HashMap::with_capacity(other_camera_ids.len());
503 for camera_id in other_camera_ids {
504 let camera = &other.cameras[&camera_id];
505 let merged_id = match map.cameras.get(&camera_id) {
506 Some(existing) if same_camera(existing, camera) => camera_id,
507 None => camera_id,
508 Some(_) => map
509 .cameras
510 .iter()
511 .find(|(_, existing)| same_camera(existing, camera))
512 .map(|(&id, _)| id)
513 .unwrap_or_else(|| map.cameras.keys().max().map_or(1, |id| id + 1)),
514 };
515 map.cameras.entry(merged_id).or_insert_with(|| {
516 let mut added = camera.clone();
517 added.id = merged_id;
518 added
519 });
520 camera_ids.insert(camera_id, merged_id);
521 }
522
523 let mut other_keyframe_ids = other.keyframes.keys().copied().collect::<Vec<_>>();
524 other_keyframe_ids.sort_unstable();
525 let first_keyframe = base.keyframes.keys().max().map_or(1, |id| id + 1);
526 let keyframe_ids = other_keyframe_ids
527 .iter()
528 .enumerate()
529 .map(|(index, &id)| (id, first_keyframe + index as u64))
530 .collect::<HashMap<_, _>>();
531
532 let mut other_landmarks = other.landmarks.values().collect::<Vec<_>>();
533 other_landmarks.sort_by_key(|landmark| landmark.id);
534 let moved = other_landmarks
535 .iter()
536 .filter_map(|landmark| {
537 Some((
538 landmark.id,
539 base_from_other.transform_point(&landmark.position).coords,
540 other_descriptors.get(landmark.id)?,
541 ))
542 })
543 .collect::<Vec<_>>();
544 let fused = fusion_targets(base, base_descriptors, &moved, config);
545 let mut next_landmark = base.landmarks.keys().max().map_or(1, |id| id + 1);
546 let mut landmark_ids = HashMap::with_capacity(other_landmarks.len());
547 for landmark in &other_landmarks {
548 let id = fused.get(&landmark.id).copied().unwrap_or_else(|| {
549 next_landmark += 1;
550 next_landmark - 1
551 });
552 landmark_ids.insert(landmark.id, id);
553 }
554
555 let remap = |observation: &Observation| {
556 Some(Observation {
557 frame_id: *keyframe_ids.get(&observation.frame_id)?,
558 landmark_id: *landmark_ids.get(&observation.landmark_id)?,
559 keypoint_index: observation.keypoint_index,
560 xy: observation.xy,
561 })
562 };
563 let rotation = base_from_other.rotation.to_rotation_matrix();
564 let mut descriptors = base_descriptors.clone();
565 for landmark in &other_landmarks {
566 let id = landmark_ids[&landmark.id];
567 let observations = landmark
568 .observations
569 .iter()
570 .filter_map(remap)
571 .collect::<Vec<_>>();
572 if fused.contains_key(&landmark.id) {
573 if let Some(target) = map.landmarks.get_mut(&id) {
574 target.observations.extend(observations);
575 }
576 continue;
577 }
578 let mut moved = Landmark::new(id, base_from_other.transform_point(&landmark.position));
579 moved.descriptor.clone_from(&landmark.descriptor);
580 moved.observations = observations;
581 map.landmarks.insert(id, moved);
582 if let Some(descriptor) = other_descriptors.get(landmark.id) {
583 descriptors.insert(id, descriptor.to_vec());
584 }
585 if let Some(covariance) = other.landmark_position_covariances.get(&landmark.id) {
586 map.landmark_position_covariances.insert(
587 id,
588 rotation.matrix() * covariance * rotation.matrix().transpose(),
589 );
590 }
591 }
592
593 let other_from_base = base_from_other.inverse();
594 for id in &other_keyframe_ids {
595 let keyframe = &other.keyframes[id];
596 let mut frame = keyframe.frame.clone();
597 frame.id = keyframe_ids[id];
598 frame.camera_id = camera_ids
599 .get(&frame.camera_id)
600 .copied()
601 .unwrap_or(frame.camera_id);
602 frame.pose = frame.pose.map(|pose| Pose {
603 world_to_camera: pose.world_to_camera.compose(&other_from_base),
604 });
605 let mut observations = Vec::with_capacity(keyframe.observations.len());
606 for observation in &keyframe.observations {
607 let Some(merged) = remap(observation) else {
608 continue;
609 };
610 if let Some(confidence) = other.observation_confidence(observation) {
611 map.set_observation_confidence(&merged, confidence);
612 }
613 observations.push(merged);
614 }
615 map.keyframes.insert(
616 frame.id,
617 Keyframe {
618 frame,
619 observations,
620 },
621 );
622 }
623 for stereo in &other.stereo_observations {
624 if let (Some(&frame_id), Some(&landmark_id)) = (
625 keyframe_ids.get(&stereo.frame_id),
626 landmark_ids.get(&stereo.landmark_id),
627 ) {
628 let mut stereo = stereo.clone();
629 stereo.frame_id = frame_id;
630 stereo.landmark_id = landmark_id;
631 stereo.right_camera_id = camera_ids
632 .get(&stereo.right_camera_id)
633 .copied()
634 .unwrap_or(stereo.right_camera_id);
635 map.stereo_observations.push(stereo);
636 }
637 }
638
639 Ok(MergedMap {
640 map,
641 descriptors,
642 keyframe_ids,
643 landmark_ids,
644 fused_landmarks: fused.len(),
645 camera_ids,
646 })
647}
648
649#[cfg(test)]
650mod tests {
651 use std::f64::consts::TAU;
652
653 use nalgebra::{Matrix3, Point3, Rotation3, UnitQuaternion};
654 use visloc_core::types::Frame;
655
656 use super::*;
657
658 struct Rng(u64);
659
660 impl Rng {
661 fn next(&mut self) -> u64 {
662 self.0 ^= self.0 << 13;
663 self.0 ^= self.0 >> 7;
664 self.0 ^= self.0 << 17;
665 self.0
666 }
667
668 fn unit(&mut self) -> f64 {
669 (self.next() % 1_000_000) as f64 / 1_000_000.0
670 }
671
672 fn bits(&mut self) -> Vec<f32> {
673 (0..256).map(|_| (self.next() & 1) as f32).collect()
674 }
675 }
676
677 fn flip(descriptor: &[f32], count: usize, rng: &mut Rng) -> Vec<f32> {
678 let mut flipped = descriptor.to_vec();
679 for _ in 0..count {
680 let bit = (rng.next() % 256) as usize;
681 flipped[bit] = 1.0 - flipped[bit];
682 }
683 flipped
684 }
685
686 const CAMERA_ID: CameraId = 1;
687
688 fn camera() -> Camera {
689 Camera::pinhole(CAMERA_ID, 640, 480, 400.0, 400.0, 320.0, 240.0)
690 }
691
692 fn level_camera(position: Vector3<f64>, heading: f64) -> SE3 {
695 let forward = Vector3::new(heading.cos(), heading.sin(), 0.0);
696 let right = Vector3::new(heading.sin(), -heading.cos(), 0.0);
697 let down = Vector3::new(0.0, 0.0, -1.0);
698 let rotation =
699 Rotation3::from_matrix_unchecked(Matrix3::from_columns(&[right, down, forward]));
700 SE3::new(UnitQuaternion::from_rotation_matrix(&rotation), position)
701 }
702
703 fn room(rng: &mut Rng, count: usize) -> Vec<Point3<f64>> {
705 (0..count)
706 .map(|index| {
707 let (u, v) = (rng.unit(), rng.unit());
708 match index % 4 {
709 0 => Point3::new(u * 10.0, 0.0, v * 3.0),
710 1 => Point3::new(u * 10.0, 8.0, v * 3.0),
711 2 => Point3::new(0.0, u * 8.0, v * 3.0),
712 _ => Point3::new(10.0, u * 8.0, v * 3.0),
713 }
714 })
715 .collect()
716 }
717
718 fn session_map(
723 points: &[Point3<f64>],
724 descriptors: &[Vec<f32>],
725 cameras: &[SE3],
726 session_from_world: &SE3,
727 first_id: LandmarkId,
728 noise: f64,
729 rng: &mut Rng,
730 ) -> (VisualMap, LandmarkDescriptorStore) {
731 let camera = camera();
732 let mut map = VisualMap::new();
733 map.cameras.insert(CAMERA_ID, camera.clone());
734 let mut store = LandmarkDescriptorStore::new();
735 for (index, world_from_camera) in cameras.iter().enumerate() {
736 let id = index as u64 + 1;
737 let mut frame = Frame::new(id, CAMERA_ID);
738 frame.pose = Some(Pose {
739 world_to_camera: session_from_world.compose(world_from_camera).inverse(),
740 });
741 map.keyframes.insert(
742 id,
743 Keyframe {
744 frame,
745 observations: Vec::new(),
746 },
747 );
748 }
749 for (index, point) in points.iter().enumerate() {
750 let landmark_id = first_id + index as u64;
751 let mut observations = Vec::new();
752 for (camera_index, world_from_camera) in cameras.iter().enumerate() {
753 let in_camera = world_from_camera.inverse().transform_point(point);
754 let Some(pixel) = camera.project(&in_camera).filter(|pixel| {
755 in_camera.z > 0.5
756 && pixel.x >= 0.0
757 && pixel.x < 640.0
758 && pixel.y >= 0.0
759 && pixel.y < 480.0
760 }) else {
761 continue;
762 };
763 let frame_id = camera_index as u64 + 1;
764 let keyframe = map.keyframes.get_mut(&frame_id).expect("keyframe");
765 let observation = Observation {
766 frame_id,
767 landmark_id,
768 keypoint_index: keyframe.observations.len(),
769 xy: pixel,
770 };
771 keyframe.observations.push(observation.clone());
772 observations.push(observation);
773 }
774 if observations.is_empty() {
775 continue;
776 }
777 let jitter =
778 Vector3::new(rng.unit() - 0.5, rng.unit() - 0.5, rng.unit() - 0.5) * (2.0 * noise);
779 let mut landmark = Landmark::new(
780 landmark_id,
781 session_from_world.transform_point(&(point + jitter)),
782 );
783 landmark.observations = observations;
784 map.landmarks.insert(landmark_id, landmark);
785 store.insert(landmark_id, descriptors[index].clone());
786 }
787 (map, store)
788 }
789
790 struct Sessions {
791 base: (VisualMap, LandmarkDescriptorStore),
792 other: (VisualMap, LandmarkDescriptorStore),
793 base_from_other: SE3,
794 }
795
796 fn sessions() -> Sessions {
801 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
802 let points = room(&mut rng, 800);
803 let descriptors = (0..points.len()).map(|_| rng.bits()).collect::<Vec<_>>();
804 let other_descriptors = descriptors
805 .iter()
806 .map(|descriptor| flip(descriptor, (rng.next() % 12) as usize, &mut rng))
807 .collect::<Vec<_>>();
808 let around = |x: f64, phase: f64| {
809 (0..12)
810 .map(|k| level_camera(Vector3::new(x, 4.0, 1.5), phase + k as f64 * TAU / 12.0))
811 .collect::<Vec<_>>()
812 };
813 let base_from_other = SE3::new(
814 UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.6),
815 Vector3::new(1.0, -2.0, 0.3),
816 );
817 Sessions {
818 base: session_map(
819 &points[..600],
820 &descriptors,
821 &around(3.5, 0.0),
822 &SE3::identity(),
823 0,
824 0.01,
825 &mut rng,
826 ),
827 other: session_map(
828 &points,
829 &other_descriptors,
830 &around(6.5, 0.1),
831 &base_from_other.inverse(),
832 100_000,
833 0.01,
834 &mut rng,
835 ),
836 base_from_other,
837 }
838 }
839
840 fn assert_se3_close(actual: &SE3, expected: &SE3, metres: f64, degrees: f64) {
841 let error = expected.inverse().compose(actual);
842 assert!(
843 error.translation.norm() < metres,
844 "translation off by {} m",
845 error.translation.norm()
846 );
847 assert!(
848 error.rotation.angle().to_degrees() < degrees,
849 "rotation off by {} deg",
850 error.rotation.angle().to_degrees()
851 );
852 }
853
854 #[test]
855 fn registration_recovers_the_transform_between_sessions() {
856 let s = sessions();
857 let registration = register_map(
858 &s.base.0,
859 &s.base.1,
860 &s.other.0,
861 &s.other.1,
862 &MapMergeConfig {
863 threads: 3,
864 ..MapMergeConfig::default()
865 },
866 )
867 .expect("registered");
868 assert_se3_close(
869 ®istration.base_from_other,
870 &s.base_from_other,
871 0.005,
872 0.05,
873 );
874 assert_eq!(registration.keyframes, 12);
875 assert_eq!(
876 registration.agreeing_keyframes,
877 registration.localized_keyframes
878 );
879 assert!(registration.agreeing_keyframes >= 10, "{registration:?}");
880 assert!(registration.keyframe_rms_m < 0.02, "{registration:?}");
881
882 let serial = register_map(
884 &s.base.0,
885 &s.base.1,
886 &s.other.0,
887 &s.other.1,
888 &MapMergeConfig::default(),
889 )
890 .expect("registered");
891 assert_eq!(serial, registration);
892 }
893
894 #[test]
895 fn merging_fuses_shared_landmarks_and_adds_new_ones() {
896 let s = sessions();
897 let config = MapMergeConfig::default();
898 let merged = merge_maps(
899 &s.base.0,
900 &s.base.1,
901 &s.other.0,
902 &s.other.1,
903 &s.base_from_other,
904 &config,
905 )
906 .expect("merged");
907 let shared = s
908 .other
909 .0
910 .landmarks
911 .keys()
912 .filter(|id| s.base.0.landmarks.contains_key(&(*id - 100_000)))
913 .count();
914 assert!(shared > 500, "{shared}");
915 assert_eq!(merged.fused_landmarks, shared);
916 for (other_id, merged_id) in &merged.landmark_ids {
917 if s.base.0.landmarks.contains_key(&(other_id - 100_000)) {
918 assert_eq!(*merged_id, other_id - 100_000, "fused into its own point");
919 } else {
920 assert!(!s.base.0.landmarks.contains_key(merged_id));
921 }
922 }
923 assert_eq!(
924 merged.map.landmarks.len(),
925 s.base.0.landmarks.len() + s.other.0.landmarks.len() - shared
926 );
927 assert_eq!(merged.descriptors.len(), merged.map.landmarks.len());
928 assert_eq!(merged.map.keyframes.len(), 24);
929
930 let fused = &merged.map.landmarks[&5];
933 assert_eq!(fused.position, s.base.0.landmarks[&5].position);
934 let other_observations = fused
935 .observations
936 .iter()
937 .filter(|observation| observation.frame_id > 12)
938 .collect::<Vec<_>>();
939 assert_eq!(
940 other_observations.len(),
941 s.other.0.landmarks[&100_005].observations.len()
942 );
943 for observation in other_observations {
944 let keyframe = &merged.map.keyframes[&observation.frame_id];
945 assert!(keyframe.observations.contains(observation));
946 let pose = keyframe.frame.pose.as_ref().expect("pose");
947 let pixel = camera()
948 .project(&pose.transform_world_point(&fused.position))
949 .expect("in front");
950 assert!((pixel - observation.xy).norm() < 5.0);
951 }
952
953 let other_camera_one = level_camera(Vector3::new(6.5, 4.0, 1.5), 0.1);
955 let moved = merged.map.keyframes[&merged.keyframe_ids[&1]]
956 .frame
957 .pose
958 .as_ref()
959 .expect("pose")
960 .camera_to_world();
961 assert_se3_close(&moved, &other_camera_one, 1e-9, 1e-9);
962 }
963
964 #[test]
965 fn without_fusion_every_landmark_is_added() {
966 let s = sessions();
967 let merged = merge_maps(
968 &s.base.0,
969 &s.base.1,
970 &s.other.0,
971 &s.other.1,
972 &s.base_from_other,
973 &MapMergeConfig {
974 fuse_radius_m: 0.0,
975 ..MapMergeConfig::default()
976 },
977 )
978 .expect("merged");
979 assert_eq!(merged.fused_landmarks, 0);
980 assert_eq!(
981 merged.map.landmarks.len(),
982 s.base.0.landmarks.len() + s.other.0.landmarks.len()
983 );
984 }
985
986 #[test]
987 fn a_map_of_another_place_does_not_register() {
988 let s = sessions();
989 let mut rng = Rng(42);
990 let unrelated = s
991 .other
992 .0
993 .landmarks
994 .keys()
995 .map(|&id| (id, rng.bits()))
996 .collect::<Vec<_>>();
997 let mut store = LandmarkDescriptorStore::new();
998 for (id, descriptor) in unrelated {
999 store.insert(id, descriptor);
1000 }
1001 let error = register_map(
1002 &s.base.0,
1003 &s.base.1,
1004 &s.other.0,
1005 &store,
1006 &MapMergeConfig::default(),
1007 )
1008 .expect_err("nothing to register");
1009 assert!(matches!(
1010 error,
1011 MapMergeError::TooFewKeyframes { agreeing: 0, .. }
1012 ));
1013 }
1014
1015 #[test]
1016 fn another_calibration_is_added_under_a_new_camera_id() {
1017 let s = sessions();
1018 let mut other = s.other.0.clone();
1019 other.cameras.get_mut(&CAMERA_ID).expect("camera").params[0] += 1.0;
1020 let merged = merge_maps(
1021 &s.base.0,
1022 &s.base.1,
1023 &other,
1024 &s.other.1,
1025 &s.base_from_other,
1026 &MapMergeConfig::default(),
1027 )
1028 .expect("merged");
1029 let new_id = merged.camera_ids[&CAMERA_ID];
1030 assert_ne!(new_id, CAMERA_ID);
1031 assert_eq!(merged.map.cameras[&CAMERA_ID], s.base.0.cameras[&CAMERA_ID]);
1032 assert_eq!(
1033 merged.map.cameras[&new_id].params,
1034 other.cameras[&CAMERA_ID].params
1035 );
1036 assert_eq!(merged.map.cameras[&new_id].id, new_id);
1037 for (other_id, merged_id) in &merged.keyframe_ids {
1038 assert_eq!(other.keyframes[other_id].frame.camera_id, CAMERA_ID);
1039 assert_eq!(merged.map.keyframes[merged_id].frame.camera_id, new_id);
1040 }
1041 for keyframe in s.base.0.keyframes.values() {
1042 assert_eq!(
1043 merged.map.keyframes[&keyframe.frame.id].frame.camera_id,
1044 CAMERA_ID
1045 );
1046 }
1047 }
1048
1049 #[test]
1050 fn the_same_camera_keeps_its_id() {
1051 let s = sessions();
1052 let merged = merge_maps(
1053 &s.base.0,
1054 &s.base.1,
1055 &s.other.0,
1056 &s.other.1,
1057 &s.base_from_other,
1058 &MapMergeConfig::default(),
1059 )
1060 .expect("merged");
1061 assert_eq!(merged.camera_ids[&CAMERA_ID], CAMERA_ID);
1062 assert_eq!(merged.map.cameras.len(), 1);
1063 }
1064}