1use nalgebra::{Matrix2, Matrix2x4, Matrix4, Point3, UnitQuaternion, Vector2, Vector3, Vector4};
30
31use crate::BBox;
32
33#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct GroundParams {
37 pub bin: f64,
39 pub min_below_camera: f64,
41 pub min_points: usize,
43 pub local_neighbours: usize,
46 pub local_radius: f64,
48 pub local_min_points: usize,
50 pub local_min_shift: f64,
52 pub path_stretch: f64,
55}
56
57impl Default for GroundParams {
58 fn default() -> Self {
59 Self {
60 bin: 0.05,
61 min_below_camera: 0.3,
62 min_points: 20,
63 local_neighbours: 12,
64 local_radius: 1.5,
65 local_min_points: 3,
66 local_min_shift: 0.1,
67 path_stretch: 20.0,
68 }
69 }
70}
71
72pub fn estimate_ground_height(
75 points: &[Point3<f64>],
76 lowest_camera_z: f64,
77 params: &GroundParams,
78) -> Option<f64> {
79 densest_layer(
80 points.iter().map(|p| p.z),
81 lowest_camera_z - params.min_below_camera,
82 params.bin,
83 params.min_points,
84 )
85}
86
87fn densest_layer(
90 heights: impl Iterator<Item = f64>,
91 ceiling: f64,
92 bin: f64,
93 min_points: usize,
94) -> Option<f64> {
95 densest_band(heights, ceiling, bin, 0, min_points)
96}
97
98fn densest_band(
101 heights: impl Iterator<Item = f64>,
102 ceiling: f64,
103 bin: f64,
104 spread: i64,
105 min_points: usize,
106) -> Option<f64> {
107 let mut bins: std::collections::HashMap<i64, Vec<f64>> = std::collections::HashMap::new();
108 for z in heights.filter(|z| z.is_finite() && *z < ceiling) {
109 bins.entry((z / bin).floor() as i64).or_default().push(z);
110 }
111 let band = |k: i64| {
112 (k - spread..=k + spread)
113 .filter_map(|j| bins.get(&j))
114 .flatten()
115 };
116 let (best, count) = bins
117 .keys()
118 .map(|&k| (k, band(k).count()))
119 .filter(|(_, n)| *n >= min_points)
120 .max_by_key(|(k, n)| (*n, std::cmp::Reverse(*k)))?;
121 Some(band(best).sum::<f64>() / count as f64)
122}
123
124#[derive(Debug, Clone, PartialEq)]
133pub struct PathGround {
134 pub path: Vec<Point3<f64>>,
136 pub camera_heights: Vec<f64>,
138}
139
140impl PathGround {
141 pub fn estimate(
147 path: &[Point3<f64>],
148 points: &[Point3<f64>],
149 params: &GroundParams,
150 ) -> Option<Self> {
151 path.first()?;
152 let mut along = vec![0.0];
153 for pair in path.windows(2) {
154 let step =
155 (Vector2::new(pair[1].x, pair[1].y) - Vector2::new(pair[0].x, pair[0].y)).norm();
156 along.push(along.last()? + step);
157 }
158 let ground = Self {
159 path: path.to_vec(),
160 camera_heights: Vec::new(),
161 };
162 let below: Vec<(usize, f64)> = points
163 .iter()
164 .map(|p| {
165 let i = ground.nearest(&Vector2::new(p.x, p.y));
166 (i, p.z - path[i].z)
167 })
168 .collect();
169 let found: Vec<Option<f64>> = along
170 .iter()
171 .map(|s| {
172 let heights = below
173 .iter()
174 .filter(|(i, _)| (along[*i] - s).abs() <= params.path_stretch)
175 .map(|(_, z)| *z);
176 densest_band(
177 heights,
178 -params.min_below_camera,
179 params.bin,
180 1,
181 params.min_points,
182 )
183 .map(|layer| -layer)
184 })
185 .collect();
186 let camera_heights = (0..found.len())
187 .map(|i| {
188 (0..found.len())
189 .filter_map(|j| found[j].map(|h| ((along[i] - along[j]).abs(), h)))
190 .min_by(|a, b| a.0.total_cmp(&b.0))
191 .map(|(_, h)| h)
192 })
193 .collect::<Option<Vec<f64>>>()?;
194 Some(Self {
195 camera_heights,
196 ..ground
197 })
198 }
199
200 pub fn height_at(&self, xy: &Vector2<f64>) -> f64 {
202 let i = self.nearest(xy);
203 self.path[i].z - self.camera_heights[i]
204 }
205
206 pub fn camera_height_at(&self, xy: &Vector2<f64>) -> f64 {
208 self.camera_heights[self.nearest(xy)]
209 }
210
211 fn nearest(&self, xy: &Vector2<f64>) -> usize {
212 let d = |i: &usize| (Vector2::new(self.path[*i].x, self.path[*i].y) - xy).norm_squared();
213 (0..self.path.len())
214 .min_by(|a, b| d(a).total_cmp(&d(b)))
215 .expect("a path")
216 }
217}
218
219#[derive(Debug, Clone, Copy, PartialEq)]
221pub struct GroundObservation {
222 pub timestamp_ns: i64,
223 pub contact: Point3<f64>,
225 pub camera: Point3<f64>,
227 pub height: f64,
228 pub width: f64,
229 pub distance: f64,
231}
232
233#[derive(Debug, Clone, Copy, PartialEq)]
236pub struct BoxRays {
237 pub edge_midpoints: [Vector3<f64>; 4],
238 pub corners: [Vector3<f64>; 4],
239}
240
241impl BoxRays {
242 pub fn from_box(
246 bbox: &BBox,
247 camera_to_world: &UnitQuaternion<f64>,
248 unproject: impl Fn(f64, f64) -> Option<Vector3<f64>>,
249 ) -> Option<Self> {
250 let (xm, ym) = bbox.center();
251 let ray = |x: f64, y: f64| unproject(x, y).map(|r| camera_to_world * r);
252 Some(Self {
253 edge_midpoints: [
254 ray(xm, bbox.y_min)?,
255 ray(bbox.x_max, ym)?,
256 ray(xm, bbox.y_max)?,
257 ray(bbox.x_min, ym)?,
258 ],
259 corners: [
260 ray(bbox.x_min, bbox.y_min)?,
261 ray(bbox.x_max, bbox.y_min)?,
262 ray(bbox.x_max, bbox.y_max)?,
263 ray(bbox.x_min, bbox.y_max)?,
264 ],
265 })
266 }
267}
268
269pub fn place_on_ground(
273 camera_center: &Point3<f64>,
274 rays: &BoxRays,
275 ground_z: f64,
276 timestamp_ns: i64,
277) -> Option<GroundObservation> {
278 let height_above = camera_center.z - ground_z;
279 if height_above <= 0.0 {
280 return None;
281 }
282 let unit = |r: &Vector3<f64>| r.try_normalize(1e-12);
283 let foot = rays
284 .edge_midpoints
285 .iter()
286 .filter_map(unit)
287 .min_by(|a, b| a.z.total_cmp(&b.z))?;
288 if foot.z >= -1e-6 {
289 return None;
290 }
291 let contact = camera_center + foot * (height_above / -foot.z);
292 let normal = Vector3::new(
295 contact.x - camera_center.x,
296 contact.y - camera_center.y,
297 0.0,
298 );
299 let distance = normal.norm();
300 let normal = normal.try_normalize(1e-9)?;
301 let across = Vector3::new(-normal.y, normal.x, 0.0);
302 let depth = normal.dot(&(contact - camera_center));
303 let hits: Vec<Point3<f64>> = rays
304 .corners
305 .iter()
306 .chain(&rays.edge_midpoints)
307 .filter_map(unit)
308 .filter(|r| normal.dot(r) > 1e-6)
309 .map(|r| camera_center + r * (depth / normal.dot(&r)))
310 .collect();
311 let top = hits.iter().map(|p| p.z).fold(f64::NEG_INFINITY, f64::max);
312 let sideways: Vec<f64> = hits.iter().map(|p| across.dot(&p.coords)).collect();
313 let width = sideways.iter().copied().fold(f64::NEG_INFINITY, f64::max)
314 - sideways.iter().copied().fold(f64::INFINITY, f64::min);
315 Some(GroundObservation {
316 timestamp_ns,
317 contact,
318 camera: *camera_center,
319 height: top - ground_z,
320 width,
321 distance,
322 })
323}
324
325pub fn plausible_height(class_id: u32) -> Option<(f64, f64)> {
330 Some(match class_id {
331 0 => (1.0, 2.1), 1 => (0.8, 1.4), 2 => (1.2, 2.1), 3 => (0.9, 1.6), 5 => (2.7, 4.5), 6 => (2.8, 4.8), 7 => (2.0, 4.2), 16 => (0.2, 1.0), 17 => (1.2, 2.0), _ => return None,
341 })
342}
343
344#[derive(Debug, Clone, Copy, PartialEq)]
346pub struct GroundView {
347 pub timestamp_ns: i64,
348 pub camera_center: Point3<f64>,
349 pub rays: BoxRays,
350}
351
352pub fn place_on_local_ground(
361 views: &[GroundView],
362 points: &[Point3<f64>],
363 ground_z: f64,
364 params: &GroundParams,
365) -> Option<(f64, Vec<GroundObservation>)> {
366 const ROUNDS: usize = 5;
367 let ceiling = views
368 .iter()
369 .map(|v| v.camera_center.z)
370 .fold(f64::INFINITY, f64::min)
371 - params.min_below_camera;
372 let mut ground = ground_z;
373 for round in 0.. {
374 let placed: Vec<GroundObservation> = views
375 .iter()
376 .filter_map(|v| place_on_ground(&v.camera_center, &v.rays, ground, v.timestamp_ns))
377 .collect();
378 if placed.is_empty() {
379 return None;
380 }
381 let median = |f: fn(&Point3<f64>) -> f64| {
382 let mut v: Vec<f64> = placed.iter().map(|o| f(&o.contact)).collect();
383 v.sort_by(f64::total_cmp);
384 v[v.len() / 2]
385 };
386 let foot = Vector2::new(median(|p| p.x), median(|p| p.y));
387 let mut near: Vec<(f64, f64)> = points
388 .iter()
389 .filter(|p| p.z < ceiling)
390 .map(|p| ((Vector2::new(p.x, p.y) - foot).norm(), p.z))
391 .filter(|(d, _)| *d < params.local_radius)
392 .collect();
393 near.sort_by(|a, b| a.0.total_cmp(&b.0));
394 near.truncate(params.local_neighbours);
395 let local = densest_layer(
396 near.iter().map(|(_, z)| *z),
397 ceiling,
398 params.bin,
399 params.local_min_points,
400 );
401 match local {
402 Some(z) if (z - ground).abs() > params.local_min_shift && round + 1 < ROUNDS => {
403 ground = z
404 }
405 _ => return Some((ground, placed)),
406 }
407 }
408 unreachable!()
409}
410
411#[derive(Debug, Clone, Copy, PartialEq)]
413pub struct GroundTrackParams {
414 pub min_seconds: f64,
416 pub angular_noise: f64,
421 pub extent_noise: f64,
425 pub min_extent_noise: f64,
427 pub still_chi2: f64,
430 pub outlier_chi2: f64,
433}
434
435impl Default for GroundTrackParams {
436 fn default() -> Self {
437 Self {
438 min_seconds: 1.0,
439 angular_noise: 0.004,
440 extent_noise: 0.5,
441 min_extent_noise: 0.2,
442 still_chi2: 9.21,
443 outlier_chi2: 9.21,
444 }
445 }
446}
447
448#[derive(Debug, Clone, PartialEq)]
450pub struct GroundTrack {
451 pub object_id: u64,
452 pub class_id: u32,
453 pub height: f64,
455 pub width: f64,
456 pub distance: f64,
457 pub path: Vec<(i64, Point3<f64>)>,
459 pub velocity: Vector2<f64>,
461 pub speed_sigma: f64,
463 pub moving: bool,
465 pub speed: f64,
467}
468
469pub fn summarize_ground_track(
480 object_id: u64,
481 class_id: u32,
482 observations: &[GroundObservation],
483 params: &GroundTrackParams,
484) -> Option<GroundTrack> {
485 if observations.len() < 3 {
486 return None;
487 }
488 let t0 = observations.iter().map(|o| o.timestamp_ns).min()?;
489 let times: Vec<f64> = observations
490 .iter()
491 .map(|o| (o.timestamp_ns - t0) as f64 * 1e-9)
492 .collect();
493 if times.iter().copied().fold(0.0, f64::max) < params.min_seconds {
494 return None;
495 }
496 let mut widths: Vec<f64> = observations.iter().map(|o| o.width).collect();
497 widths.sort_by(f64::total_cmp);
498 let extent = (params.extent_noise * widths[widths.len() / 2]).max(params.min_extent_noise);
499 let feet: Vec<(Vector2<f64>, Matrix2<f64>)> = observations
501 .iter()
502 .map(|o| {
503 let foot = Vector2::new(o.contact.x, o.contact.y);
504 let ray = foot - Vector2::new(o.camera.x, o.camera.y);
505 let d = ray.norm();
506 let along = ray.try_normalize(1e-9).unwrap_or_else(Vector2::x);
507 let across = Vector2::new(-along.y, along.x);
508 let h = (o.camera.z - o.contact.z).max(0.3);
509 let sigma_along = params.angular_noise * (h * h + d * d) / h + extent;
510 let sigma_across = params.angular_noise * d + extent;
511 let information = along * along.transpose() / (sigma_along * sigma_along)
512 + across * across.transpose() / (sigma_across * sigma_across);
513 (foot, information)
514 })
515 .collect();
516 let mut keep = vec![true; feet.len()];
520 let mut fit = None;
521 for _ in 0..4 {
522 let kept: Vec<usize> = (0..feet.len()).filter(|&i| keep[i]).collect();
523 let mean_t = kept.iter().map(|&i| times[i]).sum::<f64>() / kept.len() as f64;
524 let mut normal = Matrix4::<f64>::zeros();
525 let mut rhs = Vector4::<f64>::zeros();
526 for &i in &kept {
527 let (foot, information) = &feet[i];
528 let mut jacobian = Matrix2x4::<f64>::zeros();
529 jacobian
530 .fixed_view_mut::<2, 2>(0, 0)
531 .copy_from(&Matrix2::identity());
532 jacobian
533 .fixed_view_mut::<2, 2>(0, 2)
534 .copy_from(&(Matrix2::identity() * (times[i] - mean_t)));
535 normal += jacobian.transpose() * information * jacobian;
536 rhs += jacobian.transpose() * information * foot;
537 }
538 let covariance = normal.try_inverse()?;
539 let solution = covariance * rhs;
540 let inliers: Vec<bool> = (0..feet.len())
541 .map(|i| {
542 let (foot, information) = &feet[i];
543 let r = foot
544 - Vector2::new(solution[0], solution[1])
545 - Vector2::new(solution[2], solution[3]) * (times[i] - mean_t);
546 r.dot(&(information * r)) < params.outlier_chi2
547 })
548 .collect();
549 fit = Some((covariance, solution));
550 if inliers == keep || inliers.iter().filter(|&&k| k).count() < 3 {
551 break;
552 }
553 keep = inliers;
554 }
555 let (covariance, solution) = fit?;
556 let velocity = Vector2::new(solution[2], solution[3]);
557 let velocity_covariance: Matrix2<f64> = covariance.fixed_view::<2, 2>(2, 2).into();
558 let chi2 = velocity.dot(&(velocity_covariance.try_inverse()? * velocity));
559 let direction = velocity.try_normalize(1e-12).unwrap_or_else(Vector2::x);
560 let speed_sigma = direction
561 .dot(&(velocity_covariance * direction))
562 .max(0.0)
563 .sqrt();
564 let moving = chi2 > params.still_chi2;
565 let median = |f: fn(&GroundObservation) -> f64| {
566 let mut v: Vec<f64> = observations.iter().map(f).collect();
567 v.sort_by(f64::total_cmp);
568 v[v.len() / 2]
569 };
570 Some(GroundTrack {
571 object_id,
572 class_id,
573 height: median(|o| o.height),
574 width: median(|o| o.width),
575 distance: median(|o| o.distance),
576 path: observations
577 .iter()
578 .map(|o| (o.timestamp_ns, o.contact))
579 .collect(),
580 velocity,
581 speed_sigma,
582 moving,
583 speed: if moving { velocity.norm() } else { 0.0 },
584 })
585}
586
587#[cfg(test)]
588mod tests {
589 use super::*;
590 use nalgebra::{Isometry3, Matrix3, Point2, Rotation3, Translation3, UnitQuaternion};
591
592 const F: f64 = 400.0;
593 const C: (f64, f64) = (320.0, 240.0);
594
595 fn camera(position: Vector3<f64>, forward: Vector3<f64>, roll: f64) -> Isometry3<f64> {
598 let z = forward.normalize();
599 let x = z.cross(&Vector3::z()).normalize();
600 let y = z.cross(&x);
601 let base = Rotation3::from_matrix_unchecked(Matrix3::from_columns(&[x, y, z]));
602 let rolled = base * Rotation3::from_axis_angle(&Vector3::z_axis(), roll);
603 Isometry3::from_parts(
604 Translation3::from(position),
605 UnitQuaternion::from_rotation_matrix(&rolled),
606 )
607 }
608
609 fn project(pose: &Isometry3<f64>, p: &Point3<f64>) -> Point2<f64> {
610 let c = pose.inverse() * p;
611 Point2::new(F * c.x / c.z + C.0, F * c.y / c.z + C.1)
612 }
613
614 fn outline(pose: &Isometry3<f64>, foot: Point3<f64>, size: (f64, f64, f64)) -> BoxRays {
617 padded_outline(pose, foot, size, 0.0)
618 }
619
620 fn padded_outline(
623 pose: &Isometry3<f64>,
624 foot: Point3<f64>,
625 size: (f64, f64, f64),
626 pad: f64,
627 ) -> BoxRays {
628 let (w, d, h) = size;
629 let corners: Vec<Point2<f64>> = [-0.5, 0.5]
630 .iter()
631 .flat_map(|&a| {
632 [-0.5, 0.5]
633 .iter()
634 .flat_map(move |&b| [0.0, 1.0].iter().map(move |&c| (a, b, c)))
635 })
636 .map(|(a, b, c)| project(pose, &(foot + Vector3::new(a * w, b * d, c * h))))
637 .collect();
638 let (x0, x1) = corners.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| {
639 (lo.min(p.x), hi.max(p.x))
640 });
641 let (y0, y1) = corners.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| {
642 (lo.min(p.y), hi.max(p.y))
643 });
644 BoxRays::from_box(&BBox::new(x0, y0, x1, y1 + pad), &pose.rotation, |x, y| {
645 Some(Vector3::new((x - C.0) / F, (y - C.1) / F, 1.0))
646 })
647 .unwrap()
648 }
649
650 const SPEED: f64 = 1.442_220_510_185_596; fn walk(roll: f64, scale: f64) -> GroundTrack {
658 let observations: Vec<GroundObservation> = (0..30)
659 .map(|k| {
660 let t = k as f64 / 10.0;
661 let camera_position = Vector3::new(0.0, 0.8 * t, 1.5);
662 let true_pose = camera(camera_position, Vector3::new(0.3, 1.0, 0.0), roll);
663 let foot = Point3::new(-1.8 + 1.2 * t, 5.0 + 0.8 * t, 0.0);
664 let rays = outline(&true_pose, foot, (0.5, 0.3, 1.75));
665 place_on_ground(
666 &Point3::from(camera_position * scale),
667 &rays,
668 0.0,
669 (t * 1e9) as i64,
670 )
671 .unwrap()
672 })
673 .collect();
674 summarize_ground_track(1, 0, &observations, &GroundTrackParams::default()).unwrap()
675 }
676
677 #[test]
678 fn a_walking_person_comes_out_in_metres_and_metres_per_second() {
679 for roll in [0.0, std::f64::consts::FRAC_PI_2] {
680 let track = walk(roll, 1.0);
681 assert!((track.height - 1.75).abs() < 0.1, "roll {roll}: {track:?}");
683 assert!((track.width - 0.5).abs() < 0.15, "roll {roll}: {track:?}");
684 assert!((track.speed - SPEED).abs() < 0.05, "roll {roll}: {track:?}");
685 let (start, end) = (track.path[0].1, track.path[29].1);
687 assert!(
688 (start - Point3::new(-1.8, 5.0, 0.0)).norm() < 0.35,
689 "{start}"
690 );
691 assert!(
692 (end - Point3::new(-1.8 + 3.48, 7.32, 0.0)).norm() < 0.35,
693 "{end}"
694 );
695 }
696 }
697
698 fn drive_past(velocity: f64) -> GroundTrack {
703 let observations: Vec<GroundObservation> = (0..30)
704 .map(|k| {
705 let t = k as f64 / 10.0;
706 let position = Vector3::new(0.0, 10.0 * t, 1.6);
707 let pose = camera(position, Vector3::new(0.0, 1.0, 0.0), 0.0);
708 let foot = Point3::new(3.0 + velocity * t, 40.0, 0.0);
709 let rays = padded_outline(&pose, foot, (1.8, 4.5, 1.5), 1.5);
710 place_on_ground(&Point3::from(position), &rays, 0.0, (t * 1e9) as i64).unwrap()
711 })
712 .collect();
713 summarize_ground_track(1, 2, &observations, &GroundTrackParams::default()).unwrap()
714 }
715
716 #[test]
717 fn a_parked_car_driven_past_stands_still() {
718 let track = drive_past(0.0);
719 assert!(track.velocity.norm() > 0.5, "{track:?}");
722 assert!(!track.moving, "{track:?}");
723 assert_eq!(track.speed, 0.0);
724 }
725
726 #[test]
727 fn a_car_crossing_ahead_moves() {
728 let track = drive_past(5.0);
729 assert!(track.moving, "{track:?}");
730 assert!((track.speed - 5.0).abs() < 1.0, "{track:?}");
731 assert!(track.speed_sigma < 1.0, "{track:?}");
732 }
733
734 #[test]
735 fn a_track_that_jumps_to_a_neighbour_stays_still() {
736 let position = Vector3::new(0.0, 0.0, 1.5);
739 let pose = camera(position, Vector3::new(0.0, 1.0, 0.0), 0.0);
740 let observations: Vec<GroundObservation> = (0..30)
741 .map(|k| {
742 let x = if (12..18).contains(&k) { 2.5 } else { 0.5 };
743 let rays = outline(&pose, Point3::new(x, 8.0, 0.0), (0.5, 0.3, 1.75));
744 place_on_ground(&Point3::from(position), &rays, 0.0, k * 100_000_000).unwrap()
745 })
746 .collect();
747 let track =
748 summarize_ground_track(1, 0, &observations, &GroundTrackParams::default()).unwrap();
749 assert!(!track.moving, "{track:?}");
750 let plain = GroundTrackParams {
751 outlier_chi2: f64::INFINITY,
752 ..GroundTrackParams::default()
753 };
754 let jumped = summarize_ground_track(1, 0, &observations, &plain).unwrap();
755 assert!(jumped.velocity.norm() > track.velocity.norm(), "{jumped:?}");
756 }
757
758 #[test]
759 fn a_wrong_scale_makes_the_person_a_giant() {
760 let track = walk(0.0, 2.0);
761 assert!((track.height / 1.75 - 2.0).abs() < 0.1, "{track:?}");
762 assert!((track.speed / SPEED - 2.0).abs() < 0.1, "{track:?}");
763 let (low, high) = plausible_height(0).unwrap();
764 assert!((low..=high).contains(&1.75) && !(low..=high).contains(&track.height));
765 }
766
767 #[test]
768 fn rejects_a_camera_below_ground_and_rays_that_do_not_go_down() {
769 let rays = |z: f64| BoxRays {
770 edge_midpoints: [Vector3::new(0.0, 1.0, z); 4],
771 corners: [Vector3::new(0.1, 1.0, z); 4],
772 };
773 assert!(place_on_ground(&Point3::new(0.0, 0.0, 1.5), &rays(0.1), 0.0, 0).is_none());
774 assert!(place_on_ground(&Point3::new(0.0, 0.0, -0.5), &rays(-0.3), 0.0, 0).is_none());
775 assert!(place_on_ground(&Point3::new(0.0, 0.0, 1.5), &rays(-0.3), 0.0, 0).is_some());
776 }
777
778 fn below_the_steps(level: f64) -> (Vec<GroundView>, Vec<Point3<f64>>) {
784 let views = (0..20)
785 .map(|k| {
786 let t = k as f64 / 10.0;
787 let position = Vector3::new(0.0, 0.0, 1.5);
788 let pose = camera(position, Vector3::new(0.0, 1.0, -0.2), 0.0);
789 let foot = Point3::new(-1.0 + t, 6.0, -level);
790 GroundView {
791 timestamp_ns: (t * 1e9) as i64,
792 camera_center: Point3::from(position),
793 rays: outline(&pose, foot, (0.5, 0.3, 1.75)),
794 }
795 })
796 .collect();
797 let mut points = Vec::new();
798 for i in 0..40 {
799 for j in 0..30 {
800 let (x, y) = (-2.0 + i as f64 * 0.1, j as f64 * 0.1);
801 points.push(Point3::new(x, y, 0.0));
802 }
803 for step in 0..5 {
804 let y = 3.0 + step as f64 * 0.2;
805 points.push(Point3::new(
806 -2.0 + i as f64 * 0.1,
807 y,
808 -level * (step as f64 + 1.0) / 5.0,
809 ));
810 }
811 for j in 0..30 {
812 let (x, y) = (-2.0 + i as f64 * 0.1, 4.0 + j as f64 * 0.15);
813 points.push(Point3::new(x, y, -level));
814 }
815 }
816 (views, points)
817 }
818
819 #[test]
820 fn a_person_below_the_steps_stands_on_the_lower_level() {
821 let (views, points) = below_the_steps(1.0);
822 let params = GroundParams::default();
823 let flat: Vec<GroundObservation> = views
825 .iter()
826 .filter_map(|v| place_on_ground(&v.camera_center, &v.rays, 0.0, v.timestamp_ns))
827 .collect();
828 let flat = summarize_ground_track(1, 0, &flat, &GroundTrackParams::default()).unwrap();
829 assert!(flat.height < 1.2, "{flat:?}");
830 let (ground, placed) = place_on_local_ground(&views, &points, 0.0, ¶ms).unwrap();
832 assert!((ground + 1.0).abs() < 0.05, "{ground}");
833 let track = summarize_ground_track(1, 0, &placed, &GroundTrackParams::default()).unwrap();
834 assert!((track.height - 1.75).abs() < 0.1, "{track:?}");
835 assert!((track.distance - 6.0).abs() < 0.3, "{track:?}");
836 }
837
838 #[test]
839 fn a_person_up_the_steps_stands_on_the_upper_level() {
840 let (views, points) = below_the_steps(-0.5);
841 let (ground, placed) =
842 place_on_local_ground(&views, &points, 0.0, &GroundParams::default()).unwrap();
843 assert!((ground - 0.5).abs() < 0.05, "{ground}");
844 let track = summarize_ground_track(1, 0, &placed, &GroundTrackParams::default()).unwrap();
845 assert!((track.height - 1.75).abs() < 0.1, "{track:?}");
846 assert!((track.distance - 6.0).abs() < 0.3, "{track:?}");
847 }
848
849 #[test]
850 fn a_person_on_the_camera_ground_stays_there() {
851 let (views, points) = below_the_steps(0.0);
852 let (ground, placed) =
853 place_on_local_ground(&views, &points, 0.0, &GroundParams::default()).unwrap();
854 assert_eq!(ground, 0.0);
855 let track = summarize_ground_track(1, 0, &placed, &GroundTrackParams::default()).unwrap();
856 assert!((track.height - 1.75).abs() < 0.1, "{track:?}");
857 }
858
859 #[test]
860 fn the_path_ground_follows_a_falling_road() {
861 let road = |x: f64| -0.05 * x;
864 let path: Vec<Point3<f64>> = (0..100)
865 .map(|i| Point3::new(i as f64, 0.0, road(i as f64) + 1.6))
866 .collect();
867 let mut points = Vec::new();
868 for i in 0..400 {
869 let x = i as f64 * 0.25;
870 points.push(Point3::new(x, -2.0 + (i % 5) as f64, road(x)));
871 if i % 3 == 0 {
872 points.push(Point3::new(
873 x,
874 3.0,
875 road(x) + 0.8 + 0.1 * ((i / 3) % 4) as f64,
876 ));
877 }
878 }
879 let ground = PathGround::estimate(&path, &points, &GroundParams::default()).unwrap();
880 let height = ground.camera_height_at(&Vector2::new(50.0, 0.0));
881 assert!((height - 1.6).abs() < 0.05, "{height}");
882 assert!((ground.height_at(&Vector2::new(60.0, 2.5)) - road(60.0)).abs() < 0.1);
883 let flat = estimate_ground_height(&points, path[0].z, &GroundParams::default());
885 assert!(
886 flat.is_none_or(|z| (z - road(60.0)).abs() > 0.5),
887 "{flat:?}"
888 );
889 }
890
891 #[test]
892 fn finds_the_floor_under_clutter() {
893 let mut points = Vec::new();
894 for i in 0..200 {
895 let a = i as f64 * 0.37;
896 points.push(Point3::new(
897 a.sin() * 4.0,
898 a.cos() * 4.0,
899 -1.52 + 0.01 * (a * 7.0).sin(),
900 ));
901 }
902 points.extend((0..60).map(|i| Point3::new(i as f64 * 0.05, 2.0, -0.78)));
904 points.extend((0..300).map(|i| Point3::new(3.0, i as f64 * 0.01, -1.4 + i as f64 * 0.01)));
905 let ground = estimate_ground_height(&points, 0.0, &GroundParams::default()).unwrap();
906 assert!((ground + 1.52).abs() < 0.02, "{ground}");
907 }
908}