//! POI extraction: `.osm.pbf` -> a geojsonseq for tippecanoe plus //! `poi_names.bin`, `poi_index.bin` and `poi_attrs.bin`. //! //! A port of the former `scripts/maps/poi_extract.cpp`. The seven outputs are //! mutually consistent — same POI set, same order, same coordinates: //! //! 1. **geojsonseq** newline-delimited GeoJSON `Point` features, fed to //! tippecanoe to build the `ma_pois` source layer. Properties: `name` //! (string), `type` (number), `osm_id` (number). //! 2. **`poi_names.bin`** deduped NUL-terminated UTF-8 name table; a "name start //! index" is the byte offset of a name's first byte (the same convention as //! `road_names.bin`). //! 3. **`poi_index.bin`** flat 14-byte little-endian records — //! `i32 lat_e7, i32 lon_e7, u32 name_off, u16 type` — sorted by the 64-bit //! Morton key of `(lat, lon)`, so the app can mmap and binary-scan a spatial //! range. The record contract lives in //! `maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt`. //! 4. **`poi_attrs.bin`** the attribute sidecar: opening hours, phone, website, //! address, cuisine and wheelchair access, indexed by the ORDINAL of the //! matching `poi_index.bin` record. See [`crate::poi_attrs`] for the layout. //! Kept separate because the 14-byte record is full and its width is load //! bearing in three places. //! 5. **`poi_spatial.bin`** coarse-grid CSR over the record coordinates, so the //! app can jump to a spatial range. See [`crate::poi_side`]. //! 6. **`poi_name_index.bin`** word-level inverted index into the record //! ordinals for name search. See [`crate::poi_side`]. //! 7. **`poi_region.bin`** one tagged OSM boundary id per record ordinal — the //! 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 //! geometry is reduced to a representative centroid because POIs render as //! points. //! //! ## Where this differs from the libosmium version //! //! libosmium assembled true polygon rings (`MultipolygonManager` + `Assembler`). //! Porting a ring assembler is a large piece of work on its own, so a relation's //! outer ring is approximated by the deduplicated node ids of its `outer`-role //! member ways. That is exact when the ring is a single closed way; when it is //! split across several, the ring's true vertex order is lost and the centroid //! shifts by a few metres at most. Node- and closed-way-derived POIs match the //! old tool exactly. use std::collections::HashMap; use std::fs::File; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use crate::geojson::{json_escape, Coord}; use crate::names::NamePool; use crate::osm::{self, visit_block, Element, MEMBER_NODE, MEMBER_WAY}; use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS}; use crate::poi_attrs::AttrPool; use crate::poi_reviews::{ReviewTable, ELEMENT_NODE, ELEMENT_RELATION, ELEMENT_WAY}; use crate::poi_side; use crate::proto::{Error, Result}; use crate::rings::{self, MemberWay, RingStats}; use crate::spatial::spatial_from_e7; use crate::tags::{self, PoiTags}; /// Relation types libosmium's `MultipolygonManager` accepts as areas. const AREA_RELATION_TYPES: [&str; 2] = ["multipolygon", "boundary"]; /// Sentinel latitude for "this node's location was never seen". const NO_LOC: i32 = i32::MIN; pub struct Stats { pub records: usize, pub unique_names: usize, pub name_bytes: u32, pub from_nodes: usize, pub from_ways: usize, pub from_relations: usize, /// POIs carrying at least one sidecar attribute. pub with_attrs: usize, pub unique_attrs: usize, pub attr_bytes: usize, /// Populated cells in `poi_spatial.bin`. pub spatial_cells: usize, /// `(record, word)` entries in `poi_name_index.bin`. pub name_entries: usize, /// POIs that matched a row of the `--reviews` table. 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 { lat: f64, lon: f64, lat_e7: i32, lon_e7: i32, morton: u64, type_: u16, osm_id: i64, name: Vec, /// Encoded sidecar record body, empty when the POI has no attributes. attrs: Vec, /// Tagged OSM boundary id (`poi_side::tag_relation`/`tag_way`), or /// [`crate::poi_side::REGION_NONE`]. A self-link is stamped at creation; /// member-link and containment links are resolved pre-sort in [`build`]. region: u64, /// Deepest `admin_level` this POI may link to: place-implied /// (country 2, state/province 4, everything else 8). place_cap: u8, } /// A `type=multipolygon`/`boundary` relation that is itself a POI. struct RelArea { id: i64, type_: u16, name: Vec, attrs: Vec, outer_ways: Vec, /// [`crate::poi_side::tag_relation`] of this relation when it is itself an /// administrative boundary, else [`crate::poi_side::REGION_NONE`]. self_region: u64, place_cap: u8, } /// A `type=boundary` + `boundary=administrative` relation (POI or not) whose /// geometry POIs link against. struct BoundaryRel { id: i64, admin_level: u8, /// `name` and `name:en`, for `poi_admin.bin` (empty when untagged). name: Vec, name_en: Vec, /// `(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. label_nodes: Vec, } #[derive(Default)] struct RelPass { areas: Vec, boundaries: Vec, } /// A closed way that is a POI in its own right. struct WayArea { id: i64, type_: u16, name: Vec, attrs: Vec, refs: Vec, /// [`crate::poi_side::tag_way`] of this way when it is itself tagged /// `boundary=administrative`, else [`crate::poi_side::REGION_NONE`]. self_region: u64, place_cap: u8, } #[derive(Default)] struct WayPass { areas: Vec, /// Node refs of ways that are outer members of a POI relation. outer_refs: Vec<(i64, Vec)>, } #[derive(Default)] struct NodePass { pois: Vec, /// `(index into the needed-node table, lat_e7, lon_e7)`. locs: Vec<(u32, i32, i32)>, } /// The input PBF and every output file of a POI build, grouped so the build /// entry points take one paths argument instead of eight loose ones. #[derive(Clone, Copy)] pub struct Paths<'a> { /// Input `.osm.pbf`. pub input: &'a Path, /// GeoJSONSeq output. pub geojson: &'a Path, /// Name pool output. pub names: &'a Path, /// POI index output. pub index: &'a Path, /// Attribute sidecar output. pub attrs: &'a Path, /// Spatial grid output. pub spatial: &'a Path, /// Name index output. pub name_index: &'a Path, /// Region (boundary link) output. pub region: &'a Path, } pub fn build(paths: Paths<'_>) -> Result { build_with(paths, None) } /// [`build`] with a region bbox filter: `Some` keeps only POIs touching the /// box, `None` (world) keeps everything. Ways and relations are kept whole /// when any vertex touches — the `complete_ways` rule — so a POI straddling /// the border keeps its true centroid rather than one computed from a clip. pub fn build_with(paths: Paths<'_>, bbox: Option) -> Result { build_with_reviews(paths, bbox, None) } /// [`build_with`] plus an external review table whose rows are appended to the /// matching POIs' attribute records (see [`crate::poi_reviews`]). pub fn build_with_reviews( paths: Paths<'_>, bbox: Option, reviews: Option<&ReviewTable>, ) -> Result { build_inner( paths.input, paths.geojson, paths.names, paths.index, paths.attrs, paths.spatial, paths.name_index, paths.region, bbox, match reviews { Some(t) => Reviews::Ready(t), None => Reviews::None, }, ) } /// A review table still being loaded on another thread; see /// [`build_with_review_loader`]. pub type ReviewLoader = std::thread::JoinHandle>; /// [`build_with_reviews`], with the table still loading on `loader`'s thread. /// /// The table is ~400 MB of TSV on a planet build and is not needed until after /// the three PBF passes, so loading it up front serialised a second-scale parse /// in front of the whole run. The join happens right before the reviews are /// applied; a loader that has already failed is noticed between passes, so a bad /// table still fails the run early rather than after the node pass. /// /// `on_loaded` runs once with the joined table (the binary prints its row /// count there). pub fn build_with_review_loader( paths: Paths<'_>, bbox: Option, loader: ReviewLoader, on_loaded: &dyn Fn(&ReviewTable), ) -> Result { build_inner( paths.input, paths.geojson, paths.names, paths.index, paths.attrs, paths.spatial, paths.name_index, paths.region, bbox, Reviews::Loading(Some(loader), on_loaded, None), ) } /// Where the review table comes from. enum Reviews<'a> { None, Ready(&'a ReviewTable), /// The loader (until joined), the joined-callback, and the joined table. Loading(Option, &'a dyn Fn(&ReviewTable), Option), } impl Reviews<'_> { /// Join the loader if it has already finished, so a failed load surfaces now. fn poll(&mut self) -> Result<()> { if let Reviews::Loading(h, _, _) = self { if h.as_ref().is_some_and(|h| h.is_finished()) { return self.join(); } } Ok(()) } /// Block until the table is loaded (no-op unless loading). fn join(&mut self) -> Result<()> { if let Reviews::Loading(h, cb, table) = self { if let Some(h) = h.take() { let t = h.join().map_err(|_| Error("the review loader panicked".into()))??; cb(&t); *table = Some(t); } } Ok(()) } fn table(&self) -> Option<&ReviewTable> { match self { Reviews::None => None, Reviews::Ready(t) => Some(t), Reviews::Loading(_, _, t) => t.as_ref(), } } } include!("poi_build_s1.rs"); include!("poi_build_s2.rs"); include!("poi_build_part1.rs"); include!("poi_build_part2.rs"); include!("poi_build_part3.rs"); include!("poi_build_part4.rs");