Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / boundaries.rs
boundaries.rs386 lines · 18.3 KiBRaw
| 1 | //! `boundaries`: the one layer whose detail is a number. |
| 2 | //! |
| 3 | //! An administrative boundary's whole meaning is its **level** — 2 is a country, 4 a state, 6 a |
| 4 | //! county, 8 a city — and the style compares it with `<=` rather than matching a name: one layer for |
| 5 | //! country borders and another for everything below. So the level is carried as a plain integer in |
| 6 | //! the `kind_detail` field under [`FLAG_DETAIL_NUMERIC`], rather than interned. Interning it would |
| 7 | //! mean interning every integer, and comparing `<=` against an id that is not ordered like the value |
| 8 | //! would be worse than useless. |
| 9 | //! |
| 10 | //! A `kind` is carried too, for the differential harness and for a future style that wants a county |
| 11 | //! line dashed differently from a state line. It is derivable from the level, which is exactly why |
| 12 | //! the level is what the style reads. |
| 13 | //! |
| 14 | //! # A boundary is a line, and cannot be an area |
| 15 | //! |
| 16 | //! Carrying the region as an area was tried, so that tapping a city could dim everything outside |
| 17 | //! it, and it has to be reverted: **clipping a polygon to a tile adds segments along the tile |
| 18 | //! edge** to close the ring, and the style's boundary layers are `line`, which strokes a polygon's |
| 19 | //! outline. Those synthetic edges are then drawn, and the map is covered in a grid of tile borders. |
| 20 | //! Clipping a *line* merely truncates it, which is why the line form has never had this problem. |
| 21 | //! |
| 22 | //! There is no way to opt out from the style side either: the `boundaries` entry declares no |
| 23 | //! `kinds`, so it matches every feature in the layer and would stroke a polygon whatever kind it |
| 24 | //! carried. |
| 25 | //! |
| 26 | //! Whatever eventually feeds a region mask therefore needs somewhere the boundary style does not |
| 27 | //! reach — a kind the layer excludes, or a layer of its own — decided together with the mask |
| 28 | //! rather than guessed at here. |
| 29 | //! |
| 30 | //! # The marking convention rides on this layer too |
| 31 | //! |
| 32 | //! Which side traffic keeps and what colour separates the directions are properties of the |
| 33 | //! *country*, and the only country geometry this build has is the `admin_level=2` relations it |
| 34 | //! already streams for the border lines. [`Conventions`] turns those into a coarse grid the tiler |
| 35 | //! stamps onto each tile's body, so the renderer never has to carry a polygon set to answer a |
| 36 | //! question that never changes for a given tile. |
| 37 | |
| 38 | use std::collections::HashMap; |
| 39 | |
| 40 | use tilecodec::mamaps::body::{MarkingConvention, FLAG_DETAIL_NUMERIC}; |
| 41 | use tilecodec::mamaps::dict::LAYER_BOUNDARIES; |
| 42 | |
| 43 | use super::{kind, Class, TagSource}; |
| 44 | |
| 45 | pub const FILTERS: &[&str] = &["boundary", "admin_level", "maritime"]; |
| 46 | |
| 47 | /// Every `kind` this module can emit. |
| 48 | #[cfg_attr(not(test), allow(dead_code))] |
| 49 | pub const KINDS: &[&str] = &["country", "region", "county", "locality", "region_area"]; |
| 50 | |
| 51 | /// The deepest administrative level worth drawing. |
| 52 | /// |
| 53 | /// Below 8 is a ward or a neighbourhood: real data, and a line nobody has ever wanted on a basemap. |
| 54 | const MAX_LEVEL: u16 = 8; |
| 55 | |
| 56 | /// The region's *shape*, for a relation that has one. |
| 57 | /// |
| 58 | /// Emitted **in addition to** the border line from [`classify`], never instead of it: the line is |
| 59 | /// what draws the border, and this is only read by the region mask. Both are needed, and they |
| 60 | /// cannot be the same feature — see the module docs for the tile-edge grid that results from |
| 61 | /// trying. |
| 62 | /// |
| 63 | /// `None` for a way, because a single way is one segment of a border and encloses nothing. A |
| 64 | /// relation whose rings will not close simply yields no area, and the border is unaffected. |
| 65 | pub fn region_area(tags: &(impl TagSource + ?Sized), is_way: bool) -> Option<Class> { |
| 66 | if is_way { |
| 67 | return None; |
| 68 | } |
| 69 | let line = classify(tags)?; |
| 70 | Some(Class { |
| 71 | layer: LAYER_BOUNDARIES, |
| 72 | kind: kind("region_area"), |
| 73 | // The same level the border carries, so the mask can tell a country from a city. |
| 74 | kind_detail: line.kind_detail, |
| 75 | flags: FLAG_DETAIL_NUMERIC, |
| 76 | area: true, |
| 77 | // One level shallower than the border line. A mask is drawn over a whole region, so it is |
| 78 | // wanted at the zoom where the region *fits on screen* — which is about where its label |
| 79 | // appears, not where its border becomes legible. |
| 80 | min_zoom: line.min_zoom.saturating_sub(1), |
| 81 | min_area_px: 0.0, |
| 82 | }) |
| 83 | } |
| 84 | |
| 85 | pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> { |
| 86 | if tags.get("boundary") != Some("administrative") { |
| 87 | return None; |
| 88 | } |
| 89 | // A maritime boundary (an EEZ or territorial-water limit drawn across open sea) is |
| 90 | // `boundary=administrative` over water, not inland/coastline admin, and the reference |
| 91 | // style's boundary layers do not show it. Dropped here, in the tiler, so the layer |
| 92 | // carries what the style draws rather than lines across the ocean. |
| 93 | if tags.get("maritime") == Some("yes") { |
| 94 | return None; |
| 95 | } |
| 96 | let level: u16 = tags.get("admin_level")?.trim().parse().ok()?; |
| 97 | if level == 0 || level > MAX_LEVEL { |
| 98 | return None; |
| 99 | } |
| 100 | Some(Class { |
| 101 | layer: LAYER_BOUNDARIES, |
| 102 | kind: kind(kind_for(level)), |
| 103 | // The level itself, not an id. This is the only field in the format that is a number. |
| 104 | kind_detail: level, |
| 105 | flags: FLAG_DETAIL_NUMERIC, |
| 106 | // A border is a line even when it closes. Filling it would paint over every layer inside |
| 107 | // the country, and — the reason an attempt to make it an area had to be reverted — a |
| 108 | // polygon clipped to a tile grows edges along the tile boundary, which the style's `line` |
| 109 | // layers then stroke as a grid across the whole map. See the module docs. |
| 110 | area: false, |
| 111 | min_zoom: min_zoom_for(level), |
| 112 | min_area_px: 0.0, |
| 113 | }) |
| 114 | } |
| 115 | |
| 116 | /// The name for an administrative level, as upstream spells it. |
| 117 | fn kind_for(level: u16) -> &'static str { |
| 118 | match level { |
| 119 | 0..=2 => "country", |
| 120 | 3..=4 => "region", |
| 121 | 5..=6 => "county", |
| 122 | _ => "locality", |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// How shallow a level is worth drawing. |
| 127 | /// |
| 128 | /// A country border carries a world tile. A city limit at z4 is noise — and there are a hundred |
| 129 | /// thousand of them. Levels 5+ start at z12, and the layer itself caps at z12 |
| 130 | /// (`MAX_ZOOM_PER_LAYER`): county/city lines tile exactly one zoom, so the |
| 131 | /// z13 copies the old cap carried are gone and z13+ overzooms from z12. |
| 132 | fn min_zoom_for(level: u16) -> u8 { |
| 133 | match level { |
| 134 | 0..=2 => 0, |
| 135 | 3..=4 => 3, |
| 136 | 5..=6 => 12, |
| 137 | _ => 12, |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /// The ISO 3166-1 alpha-2 code of a country relation, or `None` for anything that is not one. |
| 142 | /// |
| 143 | /// `admin_level=2` and nothing else: level 4 is a state, and a state has no traffic convention of |
| 144 | /// its own anywhere this build covers. The code is read verbatim rather than matched against a |
| 145 | /// list, because [`convention_for`] is the only thing that looks at it and an unknown code there |
| 146 | /// is already the default rather than an error. |
| 147 | pub fn country_code(tags: &(impl TagSource + ?Sized)) -> Option<&str> { |
| 148 | if tags.get("boundary") != Some("administrative") || tags.get("admin_level")?.trim() != "2" { |
| 149 | return None; |
| 150 | } |
| 151 | tags.get("ISO3166-1").map(str::trim).filter(|code| code.len() == 2) |
| 152 | } |
| 153 | |
| 154 | /// Countries where traffic keeps left. |
| 155 | /// |
| 156 | /// The list is what it is: there is no rule to derive it from, and the ones missing from it get |
| 157 | /// right-hand traffic, which is most of the world by land area and the safer thing to be wrong |
| 158 | /// about. British overseas territories are here individually because OSM gives each its own |
| 159 | /// `admin_level=2` relation and its own code. |
| 160 | const LEFT_HAND: &[&str] = &[ |
| 161 | "AG", "AI", "AU", "BB", "BD", "BM", "BN", "BS", "BT", "BW", "CC", "CK", "CX", "CY", "DM", "FJ", |
| 162 | "FK", "GB", "GD", "GG", "GY", "HK", "ID", "IE", "IM", "IN", "JE", "JM", "JP", "KE", "KI", "KN", |
| 163 | "KY", "LC", "LK", "LS", "MO", "MS", "MT", "MU", "MV", "MW", "MY", "MZ", "NA", "NF", "NP", "NR", |
| 164 | "NU", "NZ", "PG", "PK", "PN", "SB", "SC", "SG", "SH", "SR", "SZ", "TC", "TH", "TL", "TO", "TT", |
| 165 | "TV", "TZ", "UG", "VC", "VG", "VI", "WS", "ZA", "ZM", "ZW", |
| 166 | ]; |
| 167 | |
| 168 | /// Countries where a **yellow** line separates opposing directions. |
| 169 | /// |
| 170 | /// The Americas, plus Japan and South Korea. Everywhere else the centre line is white and only its |
| 171 | /// style distinguishes it from a lane divider, which is what [`MarkingConvention`]'s default says. |
| 172 | const YELLOW_CENTRE: &[&str] = &[ |
| 173 | "AR", "BO", "BR", "BS", "BZ", "CA", "CL", "CO", "CR", "CU", "DO", "EC", "GT", "GY", "HN", "HT", |
| 174 | "JM", "JP", "KR", "MX", "NI", "PA", "PE", "PR", "PY", "SR", "SV", "TT", "US", "UY", "VE", |
| 175 | ]; |
| 176 | |
| 177 | /// The convention a country's roads are marked to. |
| 178 | /// |
| 179 | /// An unlisted code is right-hand traffic with a white centre line, which is |
| 180 | /// [`MarkingConvention`]'s own default and what the renderer falls back to when a tile carries no |
| 181 | /// convention at all — so an unrecognised country and an unresolved tile draw the same, rather |
| 182 | /// than differently for no reason a reader could see. |
| 183 | pub fn convention_for(code: &str) -> MarkingConvention { |
| 184 | let listed = |list: &[&str]| list.iter().any(|entry| entry.eq_ignore_ascii_case(code)); |
| 185 | MarkingConvention { left_hand: listed(LEFT_HAND), yellow_centre: listed(YELLOW_CENTRE) } |
| 186 | } |
| 187 | |
| 188 | /// The zoom the country under a tile is resolved at. |
| 189 | /// |
| 190 | /// **This is the whole affordability argument.** A California build is 12.7 M z14 tiles and a |
| 191 | /// planet build is billions, and a point-in-polygon test against every country for each of them is |
| 192 | /// not a cost this build can carry — while the answer is identical across enormous stretches of |
| 193 | /// them, because a convention is a property of a country rather than of a street. So it is |
| 194 | /// resolved once per z6 tile (4096 of them for the whole world, a few hundred kilometres each) and |
| 195 | /// every tile below inherits its ancestor's. |
| 196 | /// |
| 197 | /// The error that buys is confined to z6 tiles a border runs through, and only where the two |
| 198 | /// countries either side disagree — the United States and Mexico agree, so do France and Germany; |
| 199 | /// Thailand and Cambodia do not. A handful of tiles drawing a centre line on the wrong side is the |
| 200 | /// price of not projecting a polygon set per tile. |
| 201 | pub const COARSE_ZOOM: u8 = 6; |
| 202 | |
| 203 | /// Which convention applies where, as a sparse grid of [`COARSE_ZOOM`] tiles. |
| 204 | /// |
| 205 | /// Sparse because most of the grid is ocean, and because a build of one state has no opinion about |
| 206 | /// the rest of the world: an unclaimed tile reads back as [`MarkingConvention::default`], which is |
| 207 | /// exactly what a tile with no convention at all means to the renderer. |
| 208 | #[derive(Debug, Default, Clone, PartialEq, Eq)] |
| 209 | pub struct Conventions { |
| 210 | /// `(convention, was claimed by an interior tile)`, keyed by `y * 2^COARSE_ZOOM + x`. |
| 211 | /// |
| 212 | /// The flag is what settles a coastal or border tile. A country claims a tile twice over: once |
| 213 | /// for covering its centre, which is unambiguous, and once for merely having a boundary vertex |
| 214 | /// in it, which several countries can do at once. An interior claim therefore overrides a |
| 215 | /// border claim, and between two claims of the same standing the first wins — which is |
| 216 | /// relation order, which is the PBF's order, which is what keeps the archive reproducible. |
| 217 | at: HashMap<u32, (MarkingConvention, bool)>, |
| 218 | } |
| 219 | |
| 220 | impl Conventions { |
| 221 | /// Stamp one country's shape onto the grid. |
| 222 | /// |
| 223 | /// `polygons` is the relation's assembled rings in lon/lat, exactly as the `boundaries` region |
| 224 | /// shape carries them — outer first, then holes, which is what makes the even-odd fill below |
| 225 | /// treat an enclave as a hole rather than as more of the country. |
| 226 | pub fn add(&mut self, code: &str, polygons: &[Vec<Vec<(f64, f64)>>]) { |
| 227 | let convention = convention_for(code); |
| 228 | let side = (1u32 << COARSE_ZOOM) as f64; |
| 229 | for rings in polygons { |
| 230 | // Projected once per ring rather than per scanline: this is the same |
| 231 | // [`tile_build::geom::project`] the tiler places every feature with, so a country's |
| 232 | // edge lands where its border line does. |
| 233 | let projected: Vec<Vec<(f64, f64)>> = rings |
| 234 | .iter() |
| 235 | .map(|ring| { |
| 236 | ring.iter() |
| 237 | .map(|&(lon, lat)| tile_build::geom::project(lon, lat, COARSE_ZOOM)) |
| 238 | .collect() |
| 239 | }) |
| 240 | .collect(); |
| 241 | for ring in &projected { |
| 242 | for &(x, y) in ring { |
| 243 | self.claim(x, y, convention, false); |
| 244 | } |
| 245 | } |
| 246 | self.fill(&projected, convention, side); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | /// Claim every coarse tile whose centre the polygon covers, one row at a time. |
| 251 | /// |
| 252 | /// A scanline rather than a test per tile: the crossings of one horizontal line against every |
| 253 | /// ring cost one pass over the vertices, and there are only 64 rows in the whole world. Testing |
| 254 | /// each candidate tile instead would walk a country's rings once per tile, and a country's |
| 255 | /// rings run to hundreds of thousands of points. |
| 256 | fn fill(&mut self, rings: &[Vec<(f64, f64)>], convention: MarkingConvention, side: f64) { |
| 257 | let (mut top, mut bottom) = (f64::MAX, f64::MIN); |
| 258 | for ring in rings { |
| 259 | for &(_, y) in ring { |
| 260 | top = top.min(y); |
| 261 | bottom = bottom.max(y); |
| 262 | } |
| 263 | } |
| 264 | if top > bottom { |
| 265 | return; |
| 266 | } |
| 267 | let first = top.floor().max(0.0) as u32; |
| 268 | let last = bottom.floor().min(side - 1.0) as u32; |
| 269 | let mut crossings: Vec<f64> = Vec::new(); |
| 270 | for row in first..=last { |
| 271 | let at = row as f64 + 0.5; |
| 272 | crossings.clear(); |
| 273 | for ring in rings { |
| 274 | // Wrapping rather than `windows(2)`, so a ring that arrived unclosed still gets its |
| 275 | // closing edge. A closed one's wrap edge is degenerate and crosses nothing. |
| 276 | for i in 0..ring.len() { |
| 277 | let (ax, ay) = ring[i]; |
| 278 | let (bx, by) = ring[(i + 1) % ring.len()]; |
| 279 | // Half-open in `y`, so a vertex exactly on the scanline is counted once rather |
| 280 | // than zero or twice — the usual even-odd rule. |
| 281 | if (ay <= at) == (by <= at) { |
| 282 | continue; |
| 283 | } |
| 284 | crossings.push(ax + (at - ay) * (bx - ax) / (by - ay)); |
| 285 | } |
| 286 | } |
| 287 | crossings.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); |
| 288 | for span in crossings.chunks(2) { |
| 289 | let [from, to] = span else { continue }; |
| 290 | // A tile is inside when its *centre* is, which is `tx + 0.5` in `from..=to`. |
| 291 | let low = (from - 0.5).ceil().max(0.0); |
| 292 | let high = (to - 0.5).floor().min(side - 1.0); |
| 293 | let mut tx = low; |
| 294 | while tx <= high { |
| 295 | self.claim(tx, row as f64, convention, true); |
| 296 | tx += 1.0; |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | fn claim(&mut self, x: f64, y: f64, convention: MarkingConvention, interior: bool) { |
| 303 | let side = 1u32 << COARSE_ZOOM; |
| 304 | if !(x.is_finite() && y.is_finite()) { |
| 305 | return; |
| 306 | } |
| 307 | let (tx, ty) = |
| 308 | ((x.floor().max(0.0) as u32).min(side - 1), (y.floor().max(0.0) as u32).min(side - 1)); |
| 309 | let held = self.at.entry(ty * side + tx).or_insert((convention, interior)); |
| 310 | // An interior claim outranks the border claim of whichever country reached the tile first. |
| 311 | if interior && !held.1 { |
| 312 | *held = (convention, true); |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | /// The convention for a tile, or the default where nothing claimed its coarse ancestor. |
| 317 | /// |
| 318 | /// A tile at or below [`COARSE_ZOOM`] inherits the grid cell it sits in; one above it takes |
| 319 | /// the cell at its own centre, which is the only sensible answer when a tile spans several |
| 320 | /// countries and is drawn at a zoom where no lane marking is visible anyway. |
| 321 | pub fn at_tile(&self, z: u8, x: u64, y: u64) -> MarkingConvention { |
| 322 | let side = 1u64 << COARSE_ZOOM; |
| 323 | let (cx, cy) = if z >= COARSE_ZOOM { |
| 324 | let shift = z - COARSE_ZOOM; |
| 325 | (x >> shift, y >> shift) |
| 326 | } else { |
| 327 | let step = 1u64 << (COARSE_ZOOM - z); |
| 328 | ((x * step) + step / 2, (y * step) + step / 2) |
| 329 | }; |
| 330 | let key = (cy.min(side - 1) * side + cx.min(side - 1)) as u32; |
| 331 | self.at.get(&key).map(|(convention, _)| *convention).unwrap_or_default() |
| 332 | } |
| 333 | |
| 334 | /// Does the grid know anything at all? Empty for a build with the `boundaries` layer switched |
| 335 | /// off, or one whose extract holds no country relation. |
| 336 | #[cfg(test)] |
| 337 | pub fn is_empty(&self) -> bool { |
| 338 | self.at.is_empty() |
| 339 | } |
| 340 | |
| 341 | /// The grid as the store index carries it: a `u32` count, then a `u32` cell key and a |
| 342 | /// [`MarkingConvention`] byte each, ascending by key so a reused store reproduces the run that |
| 343 | /// built it byte for byte. |
| 344 | #[cfg(test)] |
| 345 | pub fn to_bytes(&self) -> Vec<u8> { |
| 346 | let mut keys: Vec<&u32> = self.at.keys().collect(); |
| 347 | keys.sort_unstable(); |
| 348 | let mut out = Vec::with_capacity(4 + keys.len() * 5); |
| 349 | out.extend_from_slice(&(keys.len() as u32).to_le_bytes()); |
| 350 | for key in keys { |
| 351 | out.extend_from_slice(&key.to_le_bytes()); |
| 352 | out.push(self.at[key].0.to_byte()); |
| 353 | } |
| 354 | out |
| 355 | } |
| 356 | |
| 357 | /// The inverse of [`Conventions::to_bytes`], returning the grid and the bytes it consumed. |
| 358 | #[cfg(test)] |
| 359 | pub fn from_bytes(raw: &[u8]) -> osm_ingest::proto::Result<(Conventions, usize)> { |
| 360 | if raw.len() < 4 { |
| 361 | return osm_ingest::proto::err( |
| 362 | "a store index's convention grid is truncated".to_string(), |
| 363 | ); |
| 364 | } |
| 365 | let count = u32::from_le_bytes(raw[..4].try_into().expect("four bytes")) as usize; |
| 366 | let end = 4 + count * 5; |
| 367 | if raw.len() < end { |
| 368 | return osm_ingest::proto::err(format!( |
| 369 | "a store index claims {count} convention cell(s) and holds {}", |
| 370 | (raw.len() - 4) / 5, |
| 371 | )); |
| 372 | } |
| 373 | let mut at = HashMap::with_capacity(count); |
| 374 | for cell in raw[4..end].chunks_exact(5) { |
| 375 | let key = u32::from_le_bytes(cell[..4].try_into().expect("four bytes")); |
| 376 | let convention = MarkingConvention::from_byte(cell[4]) |
| 377 | .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; |
| 378 | // Resolved already, so every reloaded cell counts as an interior claim — nothing adds |
| 379 | // to a grid that came off disk. |
| 380 | at.insert(key, (convention, true)); |
| 381 | } |
| 382 | Ok((Conventions { at }, end)) |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | include!("boundaries_part1.rs"); |