1use std::collections::{HashMap, HashSet};
2
3use nalgebra::Point3;
4use visloc_core::geometry::Pose;
5use visloc_core::types::{LandmarkDescriptorStore, LandmarkId, QueryImage, VisualMap};
6use visloc_vision::matching::{DescriptorMatch, Matcher};
7use visloc_vision::pnp::Correspondence2D3D;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum CorrespondenceBuildError {
11 QueryFeatureShapeMismatch {
12 keypoint_count: usize,
13 descriptor_count: usize,
14 },
15 NoCandidateLandmarks,
16 NoMapDescriptors {
17 candidate_landmark_count: usize,
18 },
19 NoDescriptorMatches {
20 candidate_landmark_count: usize,
21 },
22 InvalidQueryLandmarkRatio,
23}
24
25#[derive(Debug, Clone, PartialEq)]
26pub struct CorrespondenceSet {
27 pub correspondences: Vec<Correspondence2D3D>,
28 pub query_indices: Vec<usize>,
29 pub landmark_ids: Vec<LandmarkId>,
30 pub candidate_landmark_count: usize,
31 pub match_count: usize,
32 pub descriptor_matches: Vec<DescriptorMatch>,
33}
34
35pub trait CandidateSelector {
36 fn select_landmark_ids(&self, query: &QueryImage, map: &VisualMap) -> Vec<LandmarkId>;
37}
38
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
40pub struct AllLandmarksSelector;
41
42impl CandidateSelector for AllLandmarksSelector {
43 fn select_landmark_ids(&self, _query: &QueryImage, map: &VisualMap) -> Vec<LandmarkId> {
44 let mut landmark_ids = map.landmarks.keys().copied().collect::<Vec<_>>();
45 landmark_ids.sort_unstable();
46 landmark_ids
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct FixedLandmarkSelector {
52 landmark_ids: Vec<LandmarkId>,
53}
54
55impl FixedLandmarkSelector {
56 pub fn new(mut landmark_ids: Vec<LandmarkId>) -> Self {
57 landmark_ids.sort_unstable();
58 landmark_ids.dedup();
59 Self { landmark_ids }
60 }
61}
62
63impl CandidateSelector for FixedLandmarkSelector {
64 fn select_landmark_ids(&self, _query: &QueryImage, _map: &VisualMap) -> Vec<LandmarkId> {
65 self.landmark_ids.clone()
66 }
67}
68
69#[derive(Debug, Clone, PartialEq)]
70pub struct IntersectCandidateSelector<A, B> {
71 pub first: A,
72 pub second: B,
73}
74
75impl<A, B> IntersectCandidateSelector<A, B> {
76 pub const fn new(first: A, second: B) -> Self {
77 Self { first, second }
78 }
79}
80
81impl<A, B> CandidateSelector for IntersectCandidateSelector<A, B>
82where
83 A: CandidateSelector,
84 B: CandidateSelector,
85{
86 fn select_landmark_ids(&self, query: &QueryImage, map: &VisualMap) -> Vec<LandmarkId> {
87 let first_ids = self
88 .first
89 .select_landmark_ids(query, map)
90 .into_iter()
91 .collect::<HashSet<_>>();
92 let mut landmark_ids = self
93 .second
94 .select_landmark_ids(query, map)
95 .into_iter()
96 .filter(|landmark_id| first_ids.contains(landmark_id))
97 .collect::<Vec<_>>();
98 landmark_ids.sort_unstable();
99 landmark_ids.dedup();
100 landmark_ids
101 }
102}
103
104#[derive(Debug, Clone, PartialEq)]
105pub struct RadiusLandmarkSelector {
106 pub center_world: Point3<f64>,
107 pub radius: f64,
108}
109
110impl RadiusLandmarkSelector {
111 pub const fn new(center_world: Point3<f64>, radius: f64) -> Self {
112 Self {
113 center_world,
114 radius,
115 }
116 }
117}
118
119impl CandidateSelector for RadiusLandmarkSelector {
120 fn select_landmark_ids(&self, _query: &QueryImage, map: &VisualMap) -> Vec<LandmarkId> {
121 if self.radius < 0.0 {
122 return Vec::new();
123 }
124
125 let radius_squared = self.radius * self.radius;
126 let mut landmark_ids = map
127 .landmarks
128 .values()
129 .filter(|landmark| {
130 (landmark.position - self.center_world).norm_squared() <= radius_squared
131 })
132 .map(|landmark| landmark.id)
133 .collect::<Vec<_>>();
134 landmark_ids.sort_unstable();
135 landmark_ids
136 }
137}
138
139#[derive(Debug, Clone)]
140pub struct CorrespondenceBuilder<M, S = AllLandmarksSelector> {
141 matcher: M,
142 candidate_selector: S,
143}
144
145impl<M> CorrespondenceBuilder<M, AllLandmarksSelector>
146where
147 M: Matcher,
148{
149 pub const fn new(matcher: M) -> Self {
150 Self {
151 matcher,
152 candidate_selector: AllLandmarksSelector,
153 }
154 }
155}
156
157impl<M, S> CorrespondenceBuilder<M, S>
158where
159 M: Matcher,
160 S: CandidateSelector,
161{
162 pub const fn with_candidate_selector(matcher: M, candidate_selector: S) -> Self {
163 Self {
164 matcher,
165 candidate_selector,
166 }
167 }
168
169 pub fn build(
170 &self,
171 query: &QueryImage,
172 map: &VisualMap,
173 descriptor_store: &LandmarkDescriptorStore,
174 ) -> Result<CorrespondenceSet, CorrespondenceBuildError> {
175 if query.keypoints.len() != query.descriptors.len() {
176 return Err(CorrespondenceBuildError::QueryFeatureShapeMismatch {
177 keypoint_count: query.keypoints.len(),
178 descriptor_count: query.descriptors.len(),
179 });
180 }
181
182 let candidate_landmark_ids = self.candidate_selector.select_landmark_ids(query, map);
183 if candidate_landmark_ids.is_empty() {
184 return Err(CorrespondenceBuildError::NoCandidateLandmarks);
185 }
186
187 let candidate_landmark_count = candidate_landmark_ids.len();
188 let candidate_landmark_ids = candidate_landmark_ids.into_iter().collect::<HashSet<_>>();
189 let paired = descriptor_store
190 .ordered_landmark_descriptors(map)
191 .into_iter()
192 .filter(|(landmark, _)| candidate_landmark_ids.contains(&landmark.id))
193 .collect::<Vec<_>>();
194 if paired.is_empty() {
195 return Err(CorrespondenceBuildError::NoMapDescriptors {
196 candidate_landmark_count,
197 });
198 }
199
200 let (landmarks, descriptors): (Vec<_>, Vec<_>) = paired
201 .into_iter()
202 .map(|(landmark, descriptor)| (landmark, descriptor.to_vec()))
203 .unzip();
204
205 let matches = self
206 .matcher
207 .match_descriptors(&query.descriptors, &descriptors);
208 if matches.is_empty() {
209 return Err(CorrespondenceBuildError::NoDescriptorMatches {
210 candidate_landmark_count,
211 });
212 }
213
214 let mut correspondences = Vec::new();
215 let mut query_indices = Vec::new();
216 let mut landmark_ids = Vec::new();
217 for descriptor_match in &matches {
218 let Some(point2d) = query.keypoints.get(descriptor_match.query_index).copied() else {
219 continue;
220 };
221 let Some(landmark) = landmarks.get(descriptor_match.train_index) else {
222 continue;
223 };
224 correspondences.push(Correspondence2D3D {
225 point2d,
226 point3d: landmark.position,
227 confidence: descriptor_match.confidence,
228 });
229 query_indices.push(descriptor_match.query_index);
230 landmark_ids.push(landmark.id);
231 }
232
233 Ok(CorrespondenceSet {
234 correspondences,
235 query_indices,
236 landmark_ids,
237 candidate_landmark_count,
238 match_count: matches.len(),
239 descriptor_matches: matches,
240 })
241 }
242}
243
244#[derive(Debug, Clone)]
254pub struct ProjectionCorrespondenceBuilder<M, S = AllLandmarksSelector> {
255 matcher: M,
256 candidate_selector: S,
257}
258
259impl<M> ProjectionCorrespondenceBuilder<M, AllLandmarksSelector>
260where
261 M: Matcher,
262{
263 pub const fn new(matcher: M) -> Self {
264 Self {
265 matcher,
266 candidate_selector: AllLandmarksSelector,
267 }
268 }
269}
270
271impl<M, S> ProjectionCorrespondenceBuilder<M, S>
272where
273 M: Matcher,
274 S: CandidateSelector,
275{
276 pub const fn with_candidate_selector(matcher: M, candidate_selector: S) -> Self {
277 Self {
278 matcher,
279 candidate_selector,
280 }
281 }
282
283 pub fn build_with_pose_prior(
294 &self,
295 query: &QueryImage,
296 map: &VisualMap,
297 descriptor_store: &LandmarkDescriptorStore,
298 pose_prior: &Pose,
299 search_radius_px: f64,
300 ) -> Result<CorrespondenceSet, CorrespondenceBuildError> {
301 self.build_with_pose_prior_and_query_landmark_ratio(
302 query,
303 map,
304 descriptor_store,
305 pose_prior,
306 search_radius_px,
307 None,
308 )
309 }
310
311 pub fn build_with_pose_prior_and_query_landmark_ratio(
319 &self,
320 query: &QueryImage,
321 map: &VisualMap,
322 descriptor_store: &LandmarkDescriptorStore,
323 pose_prior: &Pose,
324 search_radius_px: f64,
325 max_query_landmark_distance_ratio: Option<f32>,
326 ) -> Result<CorrespondenceSet, CorrespondenceBuildError> {
327 if let Some(ratio) = max_query_landmark_distance_ratio {
328 if !ratio.is_finite() || ratio <= 0.0 || ratio >= 1.0 {
329 return Err(CorrespondenceBuildError::InvalidQueryLandmarkRatio);
330 }
331 }
332 if query.keypoints.len() != query.descriptors.len() {
333 return Err(CorrespondenceBuildError::QueryFeatureShapeMismatch {
334 keypoint_count: query.keypoints.len(),
335 descriptor_count: query.descriptors.len(),
336 });
337 }
338
339 let candidate_landmark_ids = self.candidate_selector.select_landmark_ids(query, map);
340 if candidate_landmark_ids.is_empty() {
341 return Err(CorrespondenceBuildError::NoCandidateLandmarks);
342 }
343
344 let candidate_landmark_count = candidate_landmark_ids.len();
345 let candidate_landmark_ids = candidate_landmark_ids.into_iter().collect::<HashSet<_>>();
346 let paired = descriptor_store
347 .ordered_landmark_descriptors(map)
348 .into_iter()
349 .filter(|(landmark, _)| candidate_landmark_ids.contains(&landmark.id))
350 .collect::<Vec<_>>();
351 if paired.is_empty() {
352 return Err(CorrespondenceBuildError::NoMapDescriptors {
353 candidate_landmark_count,
354 });
355 }
356
357 let radius_squared = search_radius_px * search_radius_px;
358 let mut proposals = Vec::new();
359
360 for (landmark_index, (landmark, descriptor)) in paired.iter().enumerate() {
361 let point_camera = pose_prior.transform_world_point(&landmark.position);
362 let Some(projected) = query.camera.project(&point_camera) else {
363 continue;
364 };
365 if projected.x < 0.0
366 || projected.y < 0.0
367 || projected.x >= query.camera.width as f64
368 || projected.y >= query.camera.height as f64
369 {
370 continue;
371 }
372
373 let mut window_indices = Vec::new();
374 let mut window_descriptors = Vec::new();
375 for (keypoint_index, keypoint) in query.keypoints.iter().enumerate() {
376 let dx = keypoint.x - projected.x;
377 let dy = keypoint.y - projected.y;
378 if dx * dx + dy * dy <= radius_squared {
379 window_indices.push(keypoint_index);
380 window_descriptors.push(query.descriptors[keypoint_index].clone());
381 }
382 }
383 if window_descriptors.is_empty() {
384 continue;
385 }
386
387 let landmark_query = [descriptor.to_vec()];
394 let window_matches = self
395 .matcher
396 .match_descriptors(&landmark_query, &window_descriptors);
397 for window_match in window_matches {
398 let Some(&global_query_index) = window_indices.get(window_match.train_index) else {
399 continue;
400 };
401 proposals.push((
402 landmark_index,
403 landmark.id,
404 landmark.position,
405 global_query_index,
406 DescriptorMatch {
407 query_index: global_query_index,
408 train_index: landmark_index,
409 ..window_match
410 },
411 ));
412 }
413 }
414
415 if proposals.is_empty() {
416 return Err(CorrespondenceBuildError::NoDescriptorMatches {
417 candidate_landmark_count,
418 });
419 }
420
421 if let Some(ratio) = max_query_landmark_distance_ratio {
422 let mut distances_by_query: HashMap<usize, Vec<f32>> = HashMap::new();
423 for proposal in &proposals {
424 if proposal.4.distance.is_finite() {
425 distances_by_query
426 .entry(proposal.3)
427 .or_default()
428 .push(proposal.4.distance);
429 }
430 }
431 for distances in distances_by_query.values_mut() {
432 distances.sort_by(f32::total_cmp);
433 }
434 proposals.retain(|proposal| {
435 let Some(distances) = distances_by_query.get(&proposal.3) else {
436 return false;
437 };
438 let Some(&best) = distances.first() else {
439 return false;
440 };
441 if proposal.4.distance != best {
442 return false;
443 }
444 match distances.get(1) {
445 Some(&second) => best < ratio * second,
446 None => true,
447 }
448 });
449 if proposals.is_empty() {
450 return Err(CorrespondenceBuildError::NoDescriptorMatches {
451 candidate_landmark_count,
452 });
453 }
454 }
455
456 proposals.sort_by(|left, right| {
461 left.4
462 .distance
463 .total_cmp(&right.4.distance)
464 .then_with(|| left.1.cmp(&right.1))
465 .then_with(|| left.3.cmp(&right.3))
466 });
467 let mut used_query_indices = HashSet::new();
468 let mut used_landmark_ids = HashSet::new();
469 let mut correspondences = Vec::new();
470 let mut query_indices = Vec::new();
471 let mut landmark_ids = Vec::new();
472 let mut descriptor_matches = Vec::new();
473 for (_, landmark_id, point3d, query_index, descriptor_match) in proposals {
474 if !used_query_indices.insert(query_index) || !used_landmark_ids.insert(landmark_id) {
475 continue;
476 }
477 let Some(point2d) = query.keypoints.get(query_index).copied() else {
478 continue;
479 };
480 correspondences.push(Correspondence2D3D {
481 point2d,
482 point3d,
483 confidence: descriptor_match.confidence,
484 });
485 query_indices.push(query_index);
486 landmark_ids.push(landmark_id);
487 descriptor_matches.push(descriptor_match);
488 }
489
490 Ok(CorrespondenceSet {
491 correspondences,
492 query_indices,
493 landmark_ids,
494 candidate_landmark_count,
495 match_count: descriptor_matches.len(),
496 descriptor_matches,
497 })
498 }
499}