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

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

bbox.rs186 lines · 7.0 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 {
55 min_lon: v[0],
56 min_lat: v[1],
57 max_lon: v[2],
58 max_lat: v[3],
59 };
60 if bbox.min_lon >= bbox.max_lon || bbox.min_lat >= bbox.max_lat {
61 return Err(Error(format!(
62 "--bbox is empty or reversed: min ({}, {}) is not below max ({}, {})",
63 bbox.min_lon, bbox.min_lat, bbox.max_lon, bbox.max_lat
64 )));
65 }
66 if !(-180.0..=180.0).contains(&bbox.min_lon)
67 || !(-180.0..=180.0).contains(&bbox.max_lon)
68 || !(-90.0..=90.0).contains(&bbox.min_lat)
69 || !(-90.0..=90.0).contains(&bbox.max_lat)
70 {
71 return Err(Error(format!("--bbox is outside the world: {s}")));
72 }
73 Ok(bbox)
74 }
75
76 /// Inclusive on every edge, matching osmium: a node exactly on the boundary
77 /// is inside.
78 pub fn contains(&self, lon: f64, lat: f64) -> bool {
79 self.contains_e7(to_e7(lat), to_e7(lon))
80 }
81
82 /// The same test against the 1e-7 integers the PBF decoder produces, which is
83 /// what the hot paths have.
84 ///
85 /// Both entry points compare **integers**, not degrees. Going the other way
86 /// -- widening `lat_e7` to a float and comparing against the parsed bounds --
87 /// loses a coordinate that sits exactly on an edge: `1e-7` is not
88 /// representable in binary, so `-1_226_000_000 * 1e-7` lands a hair below
89 /// `-122.6` and falls out of a box whose western edge is exactly that. OSM
90 /// coordinates are 1e-7 integers to begin with, so rounding the bounds into
91 /// that space instead is both exact and the comparison the data deserves.
92 pub fn contains_e7(&self, lat_e7: i32, lon_e7: i32) -> bool {
93 lon_e7 >= to_e7(self.min_lon)
94 && lon_e7 <= to_e7(self.max_lon)
95 && lat_e7 >= to_e7(self.min_lat)
96 && lat_e7 <= to_e7(self.max_lat)
97 }
98}
99
100fn to_e7(deg: f64) -> i32 {
101 (deg * 1e7).round() as i32
102}
103
104/// `true` when there is no box, or the point is inside it. The shape callers
105/// actually want, since `--bbox` is optional everywhere.
106pub fn keep_e7(bbox: Option<&BBox>, lat_e7: i32, lon_e7: i32) -> bool {
107 bbox.is_none_or(|b| b.contains_e7(lat_e7, lon_e7))
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113
114 const SF: &str = "-122.6,37.2,-121.7,37.9";
115
116 #[test]
117 fn parses_the_script_form() {
118 let b = BBox::parse(SF).unwrap();
119 assert_eq!(
120 b,
121 BBox {
122 min_lon: -122.6,
123 min_lat: 37.2,
124 max_lon: -121.7,
125 max_lat: 37.9,
126 }
127 );
128 // Whitespace around the fields is tolerated.
129 assert_eq!(BBox::parse(" -122.6 , 37.2 , -121.7 , 37.9 ").unwrap(), b);
130 }
131
132 #[test]
133 fn rejects_malformed_boxes() {
134 for bad in [
135 "",
136 "1,2,3",
137 "1,2,3,4,5",
138 "a,2,3,4",
139 // Reversed rather than silently swapped: this is the lat/lon
140 // transposition mistake, and normalising it hides a wrong extract.
141 "-121.7,37.2,-122.6,37.9",
142 "-122.6,37.9,-121.7,37.2",
143 // Degenerate.
144 "-122.6,37.2,-122.6,37.9",
145 // Off the world.
146 "-200,37.2,-121.7,37.9",
147 "-122.6,-95,-121.7,37.9",
148 ] {
149 assert!(BBox::parse(bad).is_err(), "{bad:?} should not parse");
150 }
151 }
152
153 #[test]
154 fn containment_is_inclusive_on_every_edge() {
155 let b = BBox::parse(SF).unwrap();
156 assert!(b.contains(-122.4194, 37.7749)); // San Francisco
157 assert!(b.contains(-122.6, 37.2)); // min corner
158 assert!(b.contains(-121.7, 37.9)); // max corner
159 assert!(!b.contains(-122.61, 37.7)); // just west
160 assert!(!b.contains(-122.4, 38.0)); // just north
161 assert!(!b.contains(-74.0, 40.7)); // New York
162 }
163
164 #[test]
165 fn the_e7_path_agrees_with_the_float_path() {
166 let b = BBox::parse(SF).unwrap();
167 assert!(b.contains_e7(377_749_000, -1_224_194_000));
168 assert!(!b.contains_e7(407_000_000, -740_000_000));
169 // Exactly on both corners, expressed as integers. This is the case that
170 // a float comparison gets wrong: -1_226_000_000 * 1e-7 is very slightly
171 // west of -122.6, so the node falls out of its own bounding box.
172 assert!(b.contains_e7(372_000_000, -1_226_000_000));
173 assert!(b.contains_e7(379_000_000, -1_217_000_000));
174 // One unit outside is outside.
175 assert!(!b.contains_e7(372_000_000, -1_226_000_001));
176 assert!(!b.contains_e7(371_999_999, -1_226_000_000));
177 }
178
179 #[test]
180 fn no_box_keeps_everything() {
181 assert!(keep_e7(None, 407_000_000, -740_000_000));
182 let b = BBox::parse(SF).unwrap();
183 assert!(!keep_e7(Some(&b), 407_000_000, -740_000_000));
184 assert!(keep_e7(Some(&b), 377_749_000, -1_224_194_000));
185 }
186}