maps: poi_extract writes poi_admin.bin, the boundary hierarchy (#mapsearch)
- Commit
a671fa2b0271c0f676694dca80921c0bf1b72b6d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 20:45 UTC (22 days ago)
- Parents
aebed73
Why: search rows should read "City, State, Country", but the archive
cannot say that today. poi_region.bin (kind 15) stores ONE tagged
boundary id per POI — its label link or smallest containing admin —
and nothing anywhere in the POI sections names a boundary, gives its
admin_level, or links it to the boundary containing it. On device the
app can at best name the city (via a place label carrying the same
id); state and country live only in compressed tile bodies.
What: poi_extract (and mamaps_build's in-process POI build, which calls
the same poi_build entry points) now also writes poi_admin.bin beside
poi_region.bin — no new flag, so every existing caller emits it:
magic "PAD1" | u32 version 1 | u32 entry_count | u32 names_len
entry[entry_count], 32 B, ascending tagged_id:
u64 tagged_id (same tagging as poi_region.bin)
u64 parent_tagged (0 at the top)
u32 name_off | u32 name_en_off (u32::MAX: none / same as name)
u8 admin_level | u8[7] reserved
NUL-terminated UTF-8 name pool, deduplicated
Contents: every assembled boundary relation some POI links to, plus all
of their ancestors — everything a reader can reach from a POI, not
every admin relation on earth. BoundaryRel now keeps `name` and
`name:en`. The parent of boundary B is the smallest-area boundary of
the deepest LOWER admin_level containing a point strictly inside B
(scanline interior point of B's largest polygon: mid-way between two
vertex latitudes, midpoint of the widest even-odd stretch, so it is
never on a shared border or in a hole), using the same 1-degree
candidate grid and banded ring index as stamp_regions. Parents resolve
breadth-first from the linked boundaries on the rayon pool; output is
sorted by id, so the file is deterministic.
Expected planet size: planet4's poi_region.bin links 601,533 distinct
boundaries (593,240 relations, 8,293 ways; ways have no assembled
polygon and are not written). ~600 k entries x 32 B = ~19 MB plus a
~10 MB name pool => ~30 MB, 0.04% of the 81 GB archive. Format is
additive: nothing existing changes, and the next commit packs it as its
own archive kind that older apps skip.
Tests (cargo test --release --lib: 315 pass): poi_admin layout unit
tests (sorted fixed-width entries, shared pool, name:en elision, empty
table), and a new synthetic-PBF fixture (testpbf_part2.rs:
country > state > city squares + an unreached "Ghosttown" + three
cafes) asserting levels, names, name:en, parent chain to the top, and
that unreached boundaries are left out; an interior-point test with a
hole. (pbf_extra's reorder-buffer test is timing-sensitive and fails
~1 in 3 runs on this loaded box with or without this change.)Diff
scripts/maps/osm_ingest/README.md
diff --git a/scripts/maps/osm_ingest/README.md b/scripts/maps/osm_ingest/README.mdindex 19d74cba0b..a9aa0907fa 100644--- a/scripts/maps/osm_ingest/README.md+++ b/scripts/maps/osm_ingest/README.md@@ -6,7 +6,7 @@ Maps app's offline artifacts. Three binaries share one library: | Binary | Replaces | Emits | |---|---|---| | `road_graph` | `scripts/maps/generator.cpp` | `metadata.bin`, `nodes.bin`, `edges.bin`, `lanes.bin`, `intermediate.bin`, `road_names.bin` |-| `poi_extract` | `scripts/maps/poi_extract.cpp` | `<name>.geojsonseq`, `poi_names.bin`, `poi_index.bin`, `poi_attrs.bin`, `poi_spatial.bin`, `poi_name_index.bin` |+| `poi_extract` | `scripts/maps/poi_extract.cpp` | `<name>.geojsonseq`, `poi_names.bin`, `poi_index.bin`, `poi_attrs.bin`, `poi_spatial.bin`, `poi_name_index.bin`, `poi_region.bin`, `poi_admin.bin` | | `osm_extract` | `osmium tags-filter \| osmium export \| normalize_*.py` | one `<layer>.geojsonseq` per baked vector layer | ## Why Rust (LANGUAGE RULE)@@ -138,6 +138,8 @@ changing its reader produces a graph that loads as garbage, which is why | `poi_attrs.bin` | attribute sidecar keyed by `poi_index.bin` record ordinal; layout in `src/poi_attrs.rs` | `PoiIndex.kt` | | `poi_spatial.bin` | sparse CSR lat/lon grid over record ordinals, so a bbox query is cell-local; layout in `src/poi_side.rs` | `PoiIndex.kt` | | `poi_name_index.bin` | one `(record, word)` entry per word of every name, sorted by word; layout in `src/poi_side.rs` | `PoiIndex.kt` |+| `poi_region.bin` | one tagged OSM boundary id per record ordinal (label link, else smallest containing admin); layout in `src/poi_side.rs` | `PoiIndexRegion.kt` |+| `poi_admin.bin` | the hierarchy behind those ids: per linked boundary and ancestor, `name`, `name:en`, `admin_level` and parent, sorted by tagged id; written beside `poi_region.bin`, layout in `src/poi_admin.rs` | `PoiIndexAdmin.kt` (archive kind 16) | `GRAPH_VERSION` is **5**. Version 1 stored a 16-byte node record and a dense `u64` offset per edge in both blob files; version 2 fixed that, and version 3 gave
scripts/maps/osm_ingest/src/lib.rs
diff --git a/scripts/maps/osm_ingest/src/lib.rs b/scripts/maps/osm_ingest/src/lib.rsindex 0edaf01832..39f05c6406 100644--- a/scripts/maps/osm_ingest/src/lib.rs+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -36,6 +36,7 @@ pub mod par; pub mod pbf; pub(crate) mod progress; pub mod pbf_extra;+pub mod poi_admin; pub mod poi_attrs; pub mod timing; pub mod poi_build;
scripts/maps/osm_ingest/src/poi_admin.rs
diff --git a/scripts/maps/osm_ingest/src/poi_admin.rs b/scripts/maps/osm_ingest/src/poi_admin.rsnew file mode 100644index 0000000000..35115e1e8f--- /dev/null+++ b/scripts/maps/osm_ingest/src/poi_admin.rs@@ -0,0 +1,174 @@+//! `poi_admin.bin`: the administrative hierarchy behind `poi_region.bin`.+//!+//! `poi_region.bin` gives every POI ONE tagged boundary id — its native label+//! link or the smallest administrative boundary containing it — but nothing+//! says what that boundary is called, what level it is, or what contains it, so+//! the app could name at most the city and never the state or country. This+//! sidecar is the missing table: for every boundary a POI links to, and every+//! boundary above those, its name, its `admin_level` and its parent.+//!+//! ## Layout (little-endian)+//!+//! ```text+//! magic "PAD1" | u32 version | u32 entry_count | u32 names_len (16-byte header)+//! entry[entry_count], 32 bytes each, ascending by tagged_id:+//! u64 tagged_id same tagging as poi_region.bin ((osm_id << 2) | space)+//! u64 parent_tagged the containing boundary one level up, 0 at the top+//! u32 name_off byte offset of `name` in the pool+//! u32 name_en_off byte offset of `name:en`, or u32::MAX when absent+//! or identical to `name`+//! u8 admin_level OSM admin_level (2 country, 4 state/province, ...)+//! u8[7] reserved zero+//! names: names_len bytes of NUL-terminated UTF-8, deduplicated+//! ```+//!+//! A reader binary-searches `tagged_id` (fixed-width entries) and follows+//! `parent_tagged` to the top. The parent is the smallest-area boundary of a+//! LOWER `admin_level` that contains a point strictly inside the child (see+//! `poi_build::admin_table`), so a city's parent is its county where one exists+//! and its state otherwise; a reader wanting "the state" walks up to the first+//! level 3-4 entry.+//!+//! Additive and versioned: an archive packs it as its own section kind+//! (`ARCHIVE_KIND_POI_ADMIN`, 16), which older apps skip like any unknown kind,+//! and a reader refuses a version it does not know.++use std::collections::HashMap;+use std::io::{self, Write};++pub const ADMIN_MAGIC: &[u8; 4] = b"PAD1";+pub const ADMIN_VERSION: u32 = 1;+pub const ADMIN_HEADER_BYTES: usize = 16;+pub const ADMIN_ENTRY_BYTES: usize = 32;+/// `name_en_off` for an entry without a distinct English name.+pub const ADMIN_NO_NAME: u32 = u32::MAX;++/// One boundary of the hierarchy.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AdminEntry {+ /// Tagged OSM id, as in `poi_region.bin`.+ pub tagged: u64,+ /// Tagged id of the containing boundary one level up, or 0.+ pub parent: u64,+ pub admin_level: u8,+ /// The `name` tag (may be empty when OSM has none).+ pub name: Vec<u8>,+ /// The `name:en` tag, empty when absent.+ pub name_en: Vec<u8>,+}++/// Write `poi_admin.bin` for `entries` (any order; written sorted by tagged id,+/// one entry per id). Returns the entry count.+pub fn write_admin<W: Write>(out: &mut W, entries: &[AdminEntry]) -> io::Result<usize> {+ let mut sorted: Vec<&AdminEntry> = entries.iter().collect();+ sorted.sort_by_key(|e| e.tagged);+ sorted.dedup_by_key(|e| e.tagged);++ let mut pool: Vec<u8> = Vec::new();+ let mut offsets: HashMap<&[u8], u32> = HashMap::new();++ let mut body: Vec<u8> = Vec::with_capacity(sorted.len() * ADMIN_ENTRY_BYTES);+ for e in &sorted {+ let name_off = *offsets+ .entry(e.name.as_slice())+ .or_insert_with(|| intern_owned(&e.name, &mut pool));+ let name_en_off = if e.name_en.is_empty() || e.name_en == e.name {+ ADMIN_NO_NAME+ } else {+ *offsets+ .entry(e.name_en.as_slice())+ .or_insert_with(|| intern_owned(&e.name_en, &mut pool))+ };+ body.extend_from_slice(&e.tagged.to_le_bytes());+ body.extend_from_slice(&e.parent.to_le_bytes());+ body.extend_from_slice(&name_off.to_le_bytes());+ body.extend_from_slice(&name_en_off.to_le_bytes());+ body.push(e.admin_level);+ body.extend_from_slice(&[0u8; 7]);+ }++ out.write_all(ADMIN_MAGIC)?;+ out.write_all(&ADMIN_VERSION.to_le_bytes())?;+ out.write_all(&(sorted.len() as u32).to_le_bytes())?;+ out.write_all(&(pool.len() as u32).to_le_bytes())?;+ out.write_all(&body)?;+ out.write_all(&pool)?;+ Ok(sorted.len())+}++fn intern_owned(s: &[u8], pool: &mut Vec<u8>) -> u32 {+ let off = pool.len() as u32;+ // A NUL inside a name would cut it short for the reader; OSM never has one,+ // but the pool's framing must not depend on that.+ pool.extend(s.iter().copied().filter(|b| *b != 0));+ pool.push(0);+ off+}++#[cfg(test)]+mod tests {+ use super::*;++ fn u32_at(b: &[u8], at: usize) -> u32 {+ u32::from_le_bytes(b[at..at + 4].try_into().unwrap())+ }++ fn u64_at(b: &[u8], at: usize) -> u64 {+ u64::from_le_bytes(b[at..at + 8].try_into().unwrap())+ }++ fn cstr(pool: &[u8], off: u32) -> &[u8] {+ let s = &pool[off as usize..];+ &s[..s.iter().position(|b| *b == 0).unwrap()]+ }++ #[test]+ fn layout_is_sorted_fixed_width_with_a_shared_pool() {+ let e = |tagged, parent, level, name: &str, en: &str| AdminEntry {+ tagged,+ parent,+ admin_level: level,+ name: name.as_bytes().to_vec(),+ name_en: en.as_bytes().to_vec(),+ };+ let entries = vec![+ e(903, 902, 8, "Köln", "Cologne"),+ e(901, 0, 2, "Deutschland", "Germany"),+ e(902, 901, 4, "Nordrhein-Westfalen", "North Rhine-Westphalia"),+ // Same name and name:en: stored once, no English offset.+ e(907, 902, 8, "Bonn", "Bonn"),+ // A duplicate id is written once.+ e(901, 0, 2, "Deutschland", "Germany"),+ ];+ let mut out = Vec::new();+ assert_eq!(write_admin(&mut out, &entries).unwrap(), 4);+ assert_eq!(&out[0..4], ADMIN_MAGIC);+ assert_eq!(u32_at(&out, 4), ADMIN_VERSION);+ assert_eq!(u32_at(&out, 8), 4);+ let names_len = u32_at(&out, 12) as usize;+ let pool_at = ADMIN_HEADER_BYTES + 4 * ADMIN_ENTRY_BYTES;+ assert_eq!(out.len(), pool_at + names_len);+ let pool = &out[pool_at..];++ let at = |i: usize| ADMIN_HEADER_BYTES + i * ADMIN_ENTRY_BYTES;+ let ids: Vec<u64> = (0..4).map(|i| u64_at(&out, at(i))).collect();+ assert_eq!(ids, vec![901, 902, 903, 907], "ascending tagged ids");+ // Köln: parent, level, both names.+ assert_eq!(u64_at(&out, at(2) + 8), 902);+ assert_eq!(out[at(2) + 24], 8);+ assert_eq!(cstr(pool, u32_at(&out, at(2) + 16)), "Köln".as_bytes());+ assert_eq!(cstr(pool, u32_at(&out, at(2) + 20)), b"Cologne");+ assert!(out[at(2) + 25..at(2) + 32].iter().all(|b| *b == 0), "reserved bytes are zero");+ // Bonn: identical English name is not stored twice.+ assert_eq!(u32_at(&out, at(3) + 20), ADMIN_NO_NAME);+ // The country is the top: parent 0.+ assert_eq!(u64_at(&out, at(0) + 8), 0);+ }++ #[test]+ fn an_empty_table_is_just_a_header() {+ let mut out = Vec::new();+ assert_eq!(write_admin(&mut out, &[]).unwrap(), 0);+ assert_eq!(out.len(), ADMIN_HEADER_BYTES);+ }+}
scripts/maps/osm_ingest/src/poi_build.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build.rs b/scripts/maps/osm_ingest/src/poi_build.rsindex b385fbb2da..793c770033 100644--- a/scripts/maps/osm_ingest/src/poi_build.rs+++ b/scripts/maps/osm_ingest/src/poi_build.rs@@ -28,6 +28,9 @@ //! member link first, else the smallest containing administrative boundary — //! so the app can mask search results to a region. Zero where the POI //! matched nothing. See [`crate::poi_side`].+//! 8. **`poi_admin.bin`** the hierarchy behind those links: name, `name:en`,+//! `admin_level` and parent of every linked boundary and its ancestors,+//! written beside `poi_region.bin`. See [`crate::poi_admin`]. //! //! A POI is any node, or closed-way / multipolygon area, carrying BOTH a `name` //! and one of the recognised POI keys (see [`crate::tags::classify`]). Area@@ -86,6 +89,8 @@ pub struct Stats { pub with_reviews: usize, /// POIs stamped with a non-zero boundary link in `poi_region.bin`. pub with_region: usize,+ /// Boundaries written to `poi_admin.bin` (linked ones plus their ancestors).+ pub admin_entries: usize, } struct Poi {@@ -126,6 +131,9 @@ struct RelArea { struct BoundaryRel { id: i64, admin_level: u8,+ /// `name` and `name:en`, for `poi_admin.bin` (empty when untagged).+ name: Vec<u8>,+ name_en: Vec<u8>, /// `(way id, outer)` — empty-role ways count as outer per OSM convention. member_ways: Vec<(i64, bool)>, /// Node members with a `label`/`admin_centre` role.@@ -541,6 +549,13 @@ fn build_inner( crate::par::install(|| pois.par_sort_by_key(|p| (p.morton, p.osm_id))); let written = write_outputs(&pois, geojson, names, index, attrs, spatial, name_index, region, &mut timer)?;+ // `poi_admin.bin` rides beside `poi_region.bin` (no new flag, so every caller emits it).+ timer.switch("admin");+ let admin = admin_table(&boundaries, &assembled, &pois);+ let admin_entries = write_with(®ion.with_file_name("poi_admin.bin"), |out| {+ crate::poi_admin::write_admin(out, &admin)+ })?;+ println!("Wrote {admin_entries} administrative boundar(ies) to poi_admin.bin"); timer.finish(); Ok(Stats { records: written.records,@@ -556,6 +571,7 @@ fn build_inner( name_entries: written.name_entries, with_reviews, with_region,+ admin_entries, }) } @@ -644,6 +660,8 @@ fn relation_blob(state: &mut RelPass, block: &pbf::PrimitiveBlock) -> Result<u8> state.boundaries.push(BoundaryRel { id: r.id, admin_level,+ name: r.tags.get("name").map(|v| v.to_vec()).unwrap_or_default(),+ name_en: r.tags.get("name:en").map(|v| v.to_vec()).unwrap_or_default(), member_ways: r .members .iter()@@ -833,4 +851,5 @@ where include!("poi_build_part1.rs"); include!("poi_build_part2.rs");-include!("poi_build_part3.rs");\ No newline at end of file+include!("poi_build_part3.rs");+include!("poi_build_part4.rs");\ No newline at end of file
scripts/maps/osm_ingest/src/poi_build_part4.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build_part4.rs b/scripts/maps/osm_ingest/src/poi_build_part4.rsnew file mode 100644index 0000000000..0123483072--- /dev/null+++ b/scripts/maps/osm_ingest/src/poi_build_part4.rs@@ -0,0 +1,243 @@+// ---- poi_admin.bin: names, levels and parents of the linked boundaries -------+//+// `stamp_regions` gives each POI one boundary; this walks those boundaries up+// to the top so the app can say "City, State, Country" without a polygon. The+// table carries only boundaries some POI links to plus their ancestors, not+// every admin relation on earth: that is everything a reader can reach from a+// POI, at a fraction of the size.++/// Degrees in one cell of the boundary-candidate grid (as in `stamp_regions`).+const ADMIN_GRID_DEG: f64 = 1.0;++/// The boundary table for `poi_admin.bin`: one entry per assembled boundary that+/// a POI in `pois` links to, and per ancestor of those.+///+/// The parent of boundary B is the boundary of a LOWER `admin_level` that+/// contains a point strictly inside B ([`interior_point`]) — the deepest such+/// level, smallest area on a tie. Vertices are useless as probes: a city's+/// border runs along its county's, so a vertex is on the parent's edge, where+/// the ray cast may answer either way.+fn admin_table(+ boundaries: &[BoundaryRel],+ assembled: &[BoundaryPoly],+ pois: &[Poi],+) -> Vec<crate::poi_admin::AdminEntry> {+ use rayon::prelude::*;+ let by_tag: HashMap<u64, usize> = assembled.iter().enumerate().map(|(i, b)| (b.tagged, i)).collect();+ let names: HashMap<u64, &BoundaryRel> =+ boundaries.iter().map(|b| (poi_side::tag_relation(b.id), b)).collect();+ let grid = boundary_grid(assembled);++ // Parent of every assembled boundary, computed only for the ones reached.+ let parent_of = |i: usize| -> u64 {+ let b = &assembled[i];+ let Some(probe) = b.polys.iter().zip(&b.areas).max_by(|x, y| x.1.total_cmp(y.1)).and_then(|(p, _)| interior_point(p))+ else {+ return poi_side::REGION_NONE;+ };+ let cell = ((probe.0 / ADMIN_GRID_DEG).floor() as i32, (probe.1 / ADMIN_GRID_DEG).floor() as i32);+ let mut best: Option<(u8, f64, u64)> = None;+ for &ci in grid.get(&cell).map(Vec::as_slice).unwrap_or(&[]) {+ let c = &assembled[ci];+ if c.admin_level >= b.admin_level {+ continue;+ }+ for ((poly, idx), area) in c.polys.iter().zip(&c.index).zip(&c.areas) {+ let better = best.is_none_or(|(lvl, a, _)| c.admin_level > lvl || (c.admin_level == lvl && *area < a));+ if better && polygon_contains(poly, idx, probe) {+ best = Some((c.admin_level, *area, c.tagged));+ }+ }+ }+ best.map_or(poi_side::REGION_NONE, |(_, _, t)| t)+ };++ // Breadth-first from the linked boundaries; each round resolves one level of parents.+ let mut parents: HashMap<u64, u64> = HashMap::new();+ let mut frontier: Vec<u64> = pois.iter().map(|p| p.region).filter(|t| by_tag.contains_key(t)).collect();+ frontier.sort_unstable();+ frontier.dedup();+ while !frontier.is_empty() {+ let resolved: Vec<(u64, u64)> = crate::par::install(|| {+ frontier.par_iter().with_max_len(1).map(|t| (*t, parent_of(by_tag[t]))).collect()+ });+ let mut next = Vec::new();+ for (t, p) in resolved {+ parents.insert(t, p);+ if p != poi_side::REGION_NONE && !parents.contains_key(&p) && by_tag.contains_key(&p) {+ next.push(p);+ }+ }+ next.sort_unstable();+ next.dedup();+ frontier = next;+ }++ let mut out: Vec<crate::poi_admin::AdminEntry> = parents+ .iter()+ .map(|(t, p)| {+ let rel = names.get(t);+ crate::poi_admin::AdminEntry {+ tagged: *t,+ parent: *p,+ admin_level: assembled[by_tag[t]].admin_level,+ name: rel.map(|r| r.name.clone()).unwrap_or_default(),+ name_en: rel.map(|r| r.name_en.clone()).unwrap_or_default(),+ }+ })+ .collect();+ out.sort_by_key(|e| e.tagged);+ out+}++/// Boundary indices per [`ADMIN_GRID_DEG`] cell of their bbox.+fn boundary_grid(assembled: &[BoundaryPoly]) -> HashMap<(i32, i32), Vec<usize>> {+ let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();+ for (i, b) in assembled.iter().enumerate() {+ for cx in b.min_lon.floor() as i32..=b.max_lon.floor() as i32 {+ for cy in b.min_lat.floor() as i32..=b.max_lat.floor() as i32 {+ grid.entry((cx, cy)).or_default().push(i);+ }+ }+ }+ grid+}++/// Whether `p` is inside the polygon's exterior ring and outside all its holes.+fn polygon_contains(poly: &rings::Polygon, idx: &[RingIndex], p: Coord) -> bool {+ idx[0].contains(p, &poly[0]) && !poly[1..].iter().zip(&idx[1..]).any(|(h, hi)| hi.contains(p, h))+}++/// A point strictly inside `poly` (exterior minus holes), or `None` for a+/// degenerate polygon.+///+/// Scanline: a horizontal line between two distinct vertex latitudes near the+/// middle of the ring (so it passes through no vertex) crosses the rings an+/// even number of times; by the even-odd rule the stretches between crossings+/// 1-2, 3-4, ... are inside, holes included. The midpoint of the widest one is+/// as far from the border as that line allows.+fn interior_point(poly: &rings::Polygon) -> Option<Coord> {+ let outer = poly.first()?;+ let mut ys: Vec<f64> = outer.iter().map(|c| c.1).collect();+ ys.sort_by(f64::total_cmp);+ ys.dedup();+ if ys.len() < 2 {+ return None;+ }+ let k = (ys.len() - 1) / 2;+ let y = (ys[k] + ys[k + 1]) / 2.0;+ let mut xs: Vec<f64> = Vec::new();+ for ring in poly {+ let n = ring.len();+ for i in 0..n {+ let (x1, y1) = ring[i];+ let (x2, y2) = ring[(i + 1) % n];+ if (y1 > y) != (y2 > y) {+ xs.push(x1 + (y - y1) / (y2 - y1) * (x2 - x1));+ }+ }+ }+ xs.sort_by(f64::total_cmp);+ xs.chunks_exact(2)+ .max_by(|a, b| (a[1] - a[0]).total_cmp(&(b[1] - b[0])))+ .filter(|w| w[1] > w[0])+ .map(|w| ((w[0] + w[1]) / 2.0, y))+}++#[cfg(test)]+mod admin_tests {+ use super::*;+ use crate::poi_admin::{ADMIN_ENTRY_BYTES, ADMIN_HEADER_BYTES, ADMIN_MAGIC, ADMIN_NO_NAME};+ use crate::testpbf;++ struct Admin {+ parent: u64,+ level: u8,+ name: String,+ name_en: Option<String>,+ }++ /// Decode `poi_admin.bin` the way [`crate::poi_admin`] documents it.+ fn read_admin(dir: &Path) -> HashMap<u64, Admin> {+ let b = std::fs::read(dir.join("poi_admin.bin")).unwrap();+ assert_eq!(&b[0..4], ADMIN_MAGIC);+ let u32_at = |at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap());+ let u64_at = |at: usize| u64::from_le_bytes(b[at..at + 8].try_into().unwrap());+ let count = u32_at(8) as usize;+ let pool = &b[ADMIN_HEADER_BYTES + count * ADMIN_ENTRY_BYTES..];+ let cstr = |off: u32| {+ let s = &pool[off as usize..];+ String::from_utf8(s[..s.iter().position(|c| *c == 0).unwrap()].to_vec()).unwrap()+ };+ (0..count)+ .map(|i| {+ let at = ADMIN_HEADER_BYTES + i * ADMIN_ENTRY_BYTES;+ let en = u32_at(at + 20);+ (+ u64_at(at),+ Admin {+ parent: u64_at(at + 8),+ level: b[at + 24],+ name: cstr(u32_at(at + 16)),+ name_en: (en != ADMIN_NO_NAME).then(|| cstr(en)),+ },+ )+ })+ .collect()+ }++ fn tagged(id: i64) -> u64 {+ poi_side::tag_relation(id)+ }++ /// Country > state > city on a synthetic PBF: each POI links to its smallest+ /// boundary, the table walks every linked boundary to the top, and a+ /// boundary no POI reaches is left out.+ #[test]+ fn the_admin_table_walks_linked_boundaries_to_the_top() {+ let (pbf_path, dir) = testpbf::write_admin_sample("poi_admin");+ let stats = build(+ &pbf_path,+ &dir.join("pois.geojsonseq"),+ &dir.join("poi_names.bin"),+ &dir.join("poi_index.bin"),+ &dir.join("poi_attrs.bin"),+ &dir.join("poi_spatial.bin"),+ &dir.join("poi_name_index.bin"),+ &dir.join("poi_region.bin"),+ )+ .unwrap();+ let admin = read_admin(&dir);+ assert_eq!(stats.admin_entries, 3);+ assert_eq!(admin.len(), 3, "country, state, city; the unreached town is not written");++ let city = &admin[&tagged(testpbf::ADMIN_CITY_ID)];+ assert_eq!((city.level, city.name.as_str()), (8, "Testcity"));+ assert_eq!(city.parent, tagged(testpbf::ADMIN_STATE_ID));+ assert_eq!(city.name_en, None);++ let state = &admin[&tagged(testpbf::ADMIN_STATE_ID)];+ assert_eq!((state.level, state.name.as_str()), (4, "Teststate"));+ assert_eq!(state.parent, tagged(testpbf::ADMIN_COUNTRY_ID));++ let country = &admin[&tagged(testpbf::ADMIN_COUNTRY_ID)];+ assert_eq!((country.level, country.name.as_str()), (2, "Testlandia"));+ assert_eq!(country.name_en.as_deref(), Some("Testland"));+ assert_eq!(country.parent, 0, "the country is the top");+ assert!(!admin.contains_key(&tagged(testpbf::ADMIN_GHOST_ID)));+ }++ #[test]+ fn the_interior_point_avoids_holes_and_borders() {+ // A 4x4 square with a 2x2 hole in its middle: the probe must land in the+ // ring around the hole, never in the hole or on an edge.+ let outer = vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)];+ let hole = vec![(1.0, 1.0), (3.0, 1.0), (3.0, 3.0), (1.0, 3.0), (1.0, 1.0)];+ let poly: rings::Polygon = vec![outer.clone(), hole.clone()];+ let (x, y) = interior_point(&poly).unwrap();+ assert!(rings::point_in_ring((x, y), &outer));+ assert!(!rings::point_in_ring((x, y), &hole));+ assert!(x > 0.0 && x < 4.0 && y > 0.0 && y < 4.0);+ assert!(interior_point(&vec![vec![(0.0, 0.0), (1.0, 0.0), (0.0, 0.0)]]).is_none());+ }+}
scripts/maps/osm_ingest/src/testpbf.rs
diff --git a/scripts/maps/osm_ingest/src/testpbf.rs b/scripts/maps/osm_ingest/src/testpbf.rsindex 0b1090cfca..dee2479058 100644--- a/scripts/maps/osm_ingest/src/testpbf.rs+++ b/scripts/maps/osm_ingest/src/testpbf.rs@@ -552,4 +552,5 @@ const ADMIN_NODES: [(i64, i32, i32); 8] = [ /// One node in the vector-layer fixture: `(id, lat_e7, lon_e7, tags)`. type FixtureNode = (i64, i32, i32, Vec<(u32, u32)>); -include!("testpbf_part1.rs");\ No newline at end of file+include!("testpbf_part2.rs");+include!("testpbf_part1.rs");
scripts/maps/osm_ingest/src/testpbf_part2.rs
diff --git a/scripts/maps/osm_ingest/src/testpbf_part2.rs b/scripts/maps/osm_ingest/src/testpbf_part2.rsnew file mode 100644index 0000000000..51dccb6c3d--- /dev/null+++ b/scripts/maps/osm_ingest/src/testpbf_part2.rs@@ -0,0 +1,105 @@+// ---- the POI admin-hierarchy fixture ----------------------------------------+//+// A FIFTH fixture, for `poi_admin.bin`: three nested administrative squares+// (country > state > city), each its own `type=boundary` relation over one+// closed way, a fourth level-8 boundary ("Ghosttown") inside the state that no+// POI falls in, and three cafes — one in the city, one in the state outside the+// city, one in the country outside the state.++/// `admin_level=2`, `name=Testlandia`, `name:en=Testland`.+pub const ADMIN_COUNTRY_ID: i64 = 901;+/// `admin_level=4`, `name=Teststate`.+pub const ADMIN_STATE_ID: i64 = 902;+/// `admin_level=8`, `name=Testcity`.+pub const ADMIN_CITY_ID: i64 = 903;+/// `admin_level=8`, `name=Ghosttown`: inside the state, reached by no POI.+pub const ADMIN_GHOST_ID: i64 = 904;++/// `(way id, relation id, [south, west, north, east] in 1e-7 degrees)` per square.+const ADMIN_SQUARES: [(i64, i64, [i32; 4]); 4] = [+ (811, ADMIN_COUNTRY_ID, [400_000_000, -1_000_000_000, 410_000_000, -990_000_000]),+ (812, ADMIN_STATE_ID, [402_000_000, -998_000_000, 408_000_000, -992_000_000]),+ (813, ADMIN_CITY_ID, [404_000_000, -996_000_000, 406_000_000, -994_000_000]),+ (814, ADMIN_GHOST_ID, [402_500_000, -997_500_000, 403_000_000, -997_000_000]),+];++/// The three cafes: in the city, in the state only, in the country only.+const ADMIN_CAFES: [(i64, i32, i32, &str); 3] = [+ (821, 405_000_000, -995_000_000, "City Cafe"),+ (822, 407_500_000, -993_000_000, "State Cafe"),+ (823, 409_000_000, -991_000_000, "Country Cafe"),+];++fn admin_block() -> Vec<u8> {+ let mut st = StringTable::new();+ let k_amenity = st.id("amenity");+ let v_cafe = st.id("cafe");+ let k_name = st.id("name");+ let k_name_en = st.id("name:en");+ let k_type = st.id("type");+ let k_boundary = st.id("boundary"); // also the value of `type=*`+ let v_admin = st.id("administrative");+ let k_admin_level = st.id("admin_level");+ let role_outer = st.id("outer");+ let levels = [st.id("2"), st.id("4"), st.id("8"), st.id("8")];+ let names = [st.id("Testlandia"), st.id("Teststate"), st.id("Testcity"), st.id("Ghosttown")];+ let v_testland = st.id("Testland");++ // Ring corners: four nodes per square, ids way_id * 10 + 1..=4.+ let mut nodes: Vec<FixtureNode> = Vec::new();+ for (way_id, _, [s, w, n, e]) in ADMIN_SQUARES {+ for (k, (lat, lon)) in [(s, w), (s, e), (n, e), (n, w)].into_iter().enumerate() {+ nodes.push((way_id * 10 + k as i64 + 1, lat, lon, Vec::new()));+ }+ }+ for (id, lat, lon, name) in ADMIN_CAFES {+ nodes.push((id, lat, lon, vec![(k_amenity, v_cafe), (k_name, st.id(name))]));+ }+ nodes.sort_by_key(|n| n.0);+ let dense = dense_group(&nodes);+ let ways: Vec<Vec<u8>> = ADMIN_SQUARES+ .iter()+ .map(|(way_id, _, _)| {+ let c = |k: i64| way_id * 10 + k;+ way(*way_id, &[], &[c(1), c(2), c(3), c(4), c(1)])+ })+ .collect();+ let rels: Vec<Vec<u8>> = ADMIN_SQUARES+ .iter()+ .enumerate()+ .map(|(i, (way_id, rel_id, _))| {+ let mut tags = vec![+ (k_type, k_boundary),+ (k_boundary, v_admin),+ (k_admin_level, levels[i]),+ (k_name, names[i]),+ ];+ if *rel_id == ADMIN_COUNTRY_ID {+ tags.push((k_name_en, v_testland));+ }+ relation(*rel_id, &tags, &[(*way_id, role_outer, 1)])+ })+ .collect();++ let mut node_group = Vec::new();+ bytes_field(2, &dense, &mut node_group);+ let mut way_group = Vec::new();+ for w in &ways {+ bytes_field(3, w, &mut way_group);+ }+ let mut rel_group = Vec::new();+ for r in &rels {+ bytes_field(4, r, &mut rel_group);+ }+ let mut block = Vec::new();+ bytes_field(1, &st.encode(), &mut block);+ bytes_field(2, &node_group, &mut block);+ bytes_field(2, &way_group, &mut block);+ bytes_field(2, &rel_group, &mut block);+ varint_field(17, 100, &mut block); // granularity+ block+}++pub fn write_admin_sample(tag: &str) -> (std::path::PathBuf, std::path::PathBuf) {+ write_pbf(tag, &pbf_from_block(&admin_block()))+}