Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / bbox.rs

bbox.rs173 lines · 6.8 KiBRaw
1//! Bounding-box filtering: the `osmium extract -b` equivalent.
2//!
3//! The layer scripts clip a PBF with `osmium extract --overwrite -b BOX` before
4//! reading it. Doing the clip inline instead removes both the osmium dependency
5//! and the intermediate file, at the cost of still walking the whole PBF -- which
6//! the extractor has to do anyway to resolve way and relation members.
7//!
8//! ## Which strategy this reproduces
9//!
10//! `osmium extract`'s default is `complete_ways`: a way is kept if **any** of its
11//! nodes falls inside the box, and then *all* of that way's nodes are kept, even
12//! the ones outside. That is why a clipped extract has geometry hanging past the
13//! box edge, and it is the right behaviour here too -- truncating a way at the box
14//! boundary would invent a vertex that is not in OSM, and the tiler clips
15//! properly per tile later anyway.
16//!
17//! So [`BBox`] only ever answers "is this coordinate inside", and the callers
18//! decide what that means for a multi-node element: keep the whole thing if one
19//! vertex qualifies.
20
21use crate::proto::{Error, Result};
22
23/// A geographic bounding box in degrees.
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub struct BBox {
26 pub min_lon: f64,
27 pub min_lat: f64,
28 pub max_lon: f64,
29 pub max_lat: f64,
30}
31
32impl BBox {
33 /// Parse the `minlon,minlat,maxlon,maxlat` form every script in this
34 /// directory uses for `--bbox`.
35 ///
36 /// Reversed bounds are an error rather than being silently swapped: a
37 /// transposed box usually means lat and lon were entered the wrong way round,
38 /// and normalising it would produce a plausible-looking extract of the wrong
39 /// place.
40 pub fn parse(s: &str) -> Result<BBox> {
41 let parts: Vec<&str> = s.split(',').map(str::trim).collect();
42 if parts.len() != 4 {
43 return Err(Error(format!(
44 "--bbox wants minlon,minlat,maxlon,maxlat, got {} field(s): {s}",
45 parts.len()
46 )));
47 }
48 let mut v = [0.0f64; 4];
49 for (i, p) in parts.iter().enumerate() {
50 v[i] = p
51 .parse()
52 .map_err(|_| Error(format!("--bbox field {} is not a number: {p}", i + 1)))?;
53 }
54 let bbox = BBox { min_lon: v[0], min_lat: v[1], max_lon: v[2], max_lat: v[3] };
55 if bbox.min_lon >= bbox.max_lon || bbox.min_lat >= bbox.max_lat {
56 return Err(Error(format!(
57 "--bbox is empty or reversed: min ({}, {}) is not below max ({}, {})",
58 bbox.min_lon, bbox.min_lat, bbox.max_lon, bbox.max_lat
59 )));
60 }
61 if !(-180.0..=180.0).contains(&bbox.min_lon)
62 || !(-180.0..=180.0).contains(&bbox.max_lon)
63 || !(-90.0..=90.0).contains(&bbox.min_lat)
64 || !(-90.0..=90.0).contains(&bbox.max_lat)
65 {
66 return Err(Error(format!("--bbox is outside the world: {s}")));
67 }
68 Ok(bbox)
69 }
70
71 /// Inclusive on every edge, matching osmium: a node exactly on the boundary
72 /// is inside.
73 pub fn contains(&self, lon: f64, lat: f64) -> bool {
74 self.contains_e7(to_e7(lat), to_e7(lon))
75 }
76
77 /// The same test against the 1e-7 integers the PBF decoder produces, which is
78 /// what the hot paths have.
79 ///
80 /// Both entry points compare **integers**, not degrees. Going the other way
81 /// -- widening `lat_e7` to a float and comparing against the parsed bounds --
82 /// loses a coordinate that sits exactly on an edge: `1e-7` is not
83 /// representable in binary, so `-1_226_000_000 * 1e-7` lands a hair below
84 /// `-122.6` and falls out of a box whose western edge is exactly that. OSM
85 /// coordinates are 1e-7 integers to begin with, so rounding the bounds into
86 /// that space instead is both exact and the comparison the data deserves.
87 pub fn contains_e7(&self, lat_e7: i32, lon_e7: i32) -> bool {
88 lon_e7 >= to_e7(self.min_lon)
89 && lon_e7 <= to_e7(self.max_lon)
90 && lat_e7 >= to_e7(self.min_lat)
91 && lat_e7 <= to_e7(self.max_lat)
92 }
93}
94
95fn to_e7(deg: f64) -> i32 {
96 (deg * 1e7).round() as i32
97}
98
99/// `true` when there is no box, or the point is inside it. The shape callers
100/// actually want, since `--bbox` is optional everywhere.
101pub fn keep_e7(bbox: Option<&BBox>, lat_e7: i32, lon_e7: i32) -> bool {
102 bbox.is_none_or(|b| b.contains_e7(lat_e7, lon_e7))
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 const SF: &str = "-122.6,37.2,-121.7,37.9";
110
111 #[test]
112 fn parses_the_script_form() {
113 let b = BBox::parse(SF).unwrap();
114 assert_eq!(b, BBox { min_lon: -122.6, min_lat: 37.2, max_lon: -121.7, max_lat: 37.9 });
115 // Whitespace around the fields is tolerated.
116 assert_eq!(BBox::parse(" -122.6 , 37.2 , -121.7 , 37.9 ").unwrap(), b);
117 }
118
119 #[test]
120 fn rejects_malformed_boxes() {
121 for bad in [
122 "",
123 "1,2,3",
124 "1,2,3,4,5",
125 "a,2,3,4",
126 // Reversed rather than silently swapped: this is the lat/lon
127 // transposition mistake, and normalising it hides a wrong extract.
128 "-121.7,37.2,-122.6,37.9",
129 "-122.6,37.9,-121.7,37.2",
130 // Degenerate.
131 "-122.6,37.2,-122.6,37.9",
132 // Off the world.
133 "-200,37.2,-121.7,37.9",
134 "-122.6,-95,-121.7,37.9",
135 ] {
136 assert!(BBox::parse(bad).is_err(), "{bad:?} should not parse");
137 }
138 }
139
140 #[test]
141 fn containment_is_inclusive_on_every_edge() {
142 let b = BBox::parse(SF).unwrap();
143 assert!(b.contains(-122.4194, 37.7749)); // San Francisco
144 assert!(b.contains(-122.6, 37.2)); // min corner
145 assert!(b.contains(-121.7, 37.9)); // max corner
146 assert!(!b.contains(-122.61, 37.7)); // just west
147 assert!(!b.contains(-122.4, 38.0)); // just north
148 assert!(!b.contains(-74.0, 40.7)); // New York
149 }
150
151 #[test]
152 fn the_e7_path_agrees_with_the_float_path() {
153 let b = BBox::parse(SF).unwrap();
154 assert!(b.contains_e7(377_749_000, -1_224_194_000));
155 assert!(!b.contains_e7(407_000_000, -740_000_000));
156 // Exactly on both corners, expressed as integers. This is the case that
157 // a float comparison gets wrong: -1_226_000_000 * 1e-7 is very slightly
158 // west of -122.6, so the node falls out of its own bounding box.
159 assert!(b.contains_e7(372_000_000, -1_226_000_000));
160 assert!(b.contains_e7(379_000_000, -1_217_000_000));
161 // One unit outside is outside.
162 assert!(!b.contains_e7(372_000_000, -1_226_000_001));
163 assert!(!b.contains_e7(371_999_999, -1_226_000_000));
164 }
165
166 #[test]
167 fn no_box_keeps_everything() {
168 assert!(keep_e7(None, 407_000_000, -740_000_000));
169 let b = BBox::parse(SF).unwrap();
170 assert!(!keep_e7(Some(&b), 407_000_000, -740_000_000));
171 assert!(keep_e7(Some(&b), 377_749_000, -1_224_194_000));
172 }
173}