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

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

poi_build.rs540 lines · 18.7 KiBRaw
1//! POI extraction: `.osm.pbf` -> a geojsonseq for tippecanoe plus
2//! `poi_names.bin`, `poi_index.bin` and `poi_attrs.bin`.
3//!
4//! A port of the former `scripts/maps/poi_extract.cpp`. The four outputs are
5//! mutually consistent — same POI set, same order, same coordinates:
6//!
7//! 1. **geojsonseq** newline-delimited GeoJSON `Point` features, fed to
8//! tippecanoe to build the `ma_pois` source layer. Properties: `name`
9//! (string), `type` (number), `osm_id` (number).
10//! 2. **`poi_names.bin`** deduped NUL-terminated UTF-8 name table; a "name start
11//! index" is the byte offset of a name's first byte (the same convention as
12//! `road_names.bin`).
13//! 3. **`poi_index.bin`** flat 14-byte little-endian records —
14//! `i32 lat_e7, i32 lon_e7, u32 name_off, u16 type` — sorted by the 64-bit
15//! Morton key of `(lat, lon)`, so the app can mmap and binary-scan a spatial
16//! range. The record contract lives in
17//! `maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt`.
18//! 4. **`poi_attrs.bin`** the attribute sidecar: opening hours, phone, website,
19//! address, cuisine and wheelchair access, indexed by the ORDINAL of the
20//! matching `poi_index.bin` record. See [`crate::poi_attrs`] for the layout.
21//! Kept separate because the 14-byte record is full and its width is load
22//! bearing in three places.
23//!
24//! A POI is any node, or closed-way / multipolygon area, carrying BOTH a `name`
25//! and one of the recognised POI keys (see [`crate::tags::classify`]). Area
26//! geometry is reduced to a representative centroid because POIs render as
27//! points.
28//!
29//! ## Where this differs from the libosmium version
30//!
31//! libosmium assembled true polygon rings (`MultipolygonManager` + `Assembler`).
32//! Porting a ring assembler is a large piece of work on its own, so a relation's
33//! outer ring is approximated by the deduplicated node ids of its `outer`-role
34//! member ways. That is exact when the ring is a single closed way; when it is
35//! split across several, the ring's true vertex order is lost and the centroid
36//! shifts by a few metres at most. Node- and closed-way-derived POIs match the
37//! old tool exactly.
38
39use std::collections::HashMap;
40use std::fs::File;
41use std::io::{BufWriter, Write};
42use std::path::{Path, PathBuf};
43
44use crate::geojson::json_escape;
45use crate::names::NamePool;
46use crate::osm::{self, visit_block, Element, MEMBER_WAY};
47use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS};
48use crate::poi_attrs::AttrPool;
49use crate::poi_reviews::{ReviewTable, ELEMENT_NODE, ELEMENT_RELATION, ELEMENT_WAY};
50use crate::poi_side;
51use crate::proto::{Error, Result};
52use crate::spatial::spatial_from_e7;
53use crate::tags::{self, PoiTags};
54
55/// Relation types libosmium's `MultipolygonManager` accepts as areas.
56const AREA_RELATION_TYPES: [&str; 2] = ["multipolygon", "boundary"];
57
58/// Sentinel latitude for "this node's location was never seen".
59const NO_LOC: i32 = i32::MIN;
60
61pub struct Stats {
62 pub records: usize,
63 pub unique_names: usize,
64 pub name_bytes: u32,
65 pub from_nodes: usize,
66 pub from_ways: usize,
67 pub from_relations: usize,
68 /// POIs carrying at least one sidecar attribute.
69 pub with_attrs: usize,
70 pub unique_attrs: usize,
71 pub attr_bytes: usize,
72 /// Populated cells in `poi_spatial.bin`.
73 pub spatial_cells: usize,
74 /// `(record, word)` entries in `poi_name_index.bin`.
75 pub name_entries: usize,
76 /// POIs that matched a row of the `--reviews` table.
77 pub with_reviews: usize,
78}
79
80struct Poi {
81 lat: f64,
82 lon: f64,
83 lat_e7: i32,
84 lon_e7: i32,
85 morton: u64,
86 type_: u16,
87 osm_id: i64,
88 name: Vec<u8>,
89 /// Encoded sidecar record body, empty when the POI has no attributes.
90 attrs: Vec<u8>,
91}
92
93/// A `type=multipolygon`/`boundary` relation that is itself a POI.
94struct RelArea {
95 id: i64,
96 type_: u16,
97 name: Vec<u8>,
98 attrs: Vec<u8>,
99 outer_ways: Vec<i64>,
100}
101
102#[derive(Default)]
103struct RelPass {
104 areas: Vec<RelArea>,
105}
106
107/// A closed way that is a POI in its own right.
108struct WayArea {
109 id: i64,
110 type_: u16,
111 name: Vec<u8>,
112 attrs: Vec<u8>,
113 refs: Vec<i64>,
114}
115
116#[derive(Default)]
117struct WayPass {
118 areas: Vec<WayArea>,
119 /// Node refs of ways that are outer members of a POI relation.
120 outer_refs: Vec<(i64, Vec<i64>)>,
121}
122
123#[derive(Default)]
124struct NodePass {
125 pois: Vec<Poi>,
126 /// `(index into the needed-node table, lat_e7, lon_e7)`.
127 locs: Vec<(u32, i32, i32)>,
128}
129
130pub fn build(
131 input: &Path,
132 geojson: &Path,
133 names: &Path,
134 index: &Path,
135 attrs: &Path,
136 spatial: &Path,
137 name_index: &Path,
138) -> Result<Stats> {
139 build_with(input, geojson, names, index, attrs, spatial, name_index, None)
140}
141
142/// [`build`] with a region bbox filter: `Some` keeps only POIs touching the
143/// box, `None` (world) keeps everything. Ways and relations are kept whole
144/// when any vertex touches — the `complete_ways` rule — so a POI straddling
145/// the border keeps its true centroid rather than one computed from a clip.
146pub fn build_with(
147 input: &Path,
148 geojson: &Path,
149 names: &Path,
150 index: &Path,
151 attrs: &Path,
152 spatial: &Path,
153 name_index: &Path,
154 bbox: Option<crate::bbox::BBox>,
155) -> Result<Stats> {
156 build_with_reviews(input, geojson, names, index, attrs, spatial, name_index, bbox, None)
157}
158
159/// [`build_with`] plus an external review table whose rows are appended to the
160/// matching POIs' attribute records (see [`crate::poi_reviews`]).
161#[allow(clippy::too_many_arguments)]
162pub fn build_with_reviews(
163 input: &Path,
164 geojson: &Path,
165 names: &Path,
166 index: &Path,
167 attrs: &Path,
168 spatial: &Path,
169 name_index: &Path,
170 bbox: Option<crate::bbox::BBox>,
171 reviews: Option<&ReviewTable>,
172) -> Result<Stats> {
173 // Fail before the three passes rather than after them if an output path is
174 // unwritable.
175 for path in [geojson, names, index, attrs, spatial, name_index] {
176 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
177 std::fs::create_dir_all(parent)
178 .map_err(|e| Error(format!("cannot create {}: {e}", parent.display())))?;
179 }
180 }
181
182 let mut timer = crate::timing::PhaseTimer::start("poi");
183 let blobs = pbf::scan_blobs(input)?;
184 println!("[poi] Scanned {} data blob(s) in {}", blobs.len(), input.display());
185
186 timer.switch("relations");
187 // --- Pass 1: area relations ---------------------------------------------
188 let (chunks, blob_kinds) = pbf::run_pass(
189 input,
190 &blobs,
191 None,
192 KIND_RELATIONS,
193 "Pass 1: relations",
194 RelPass::default,
195 relation_blob,
196 )?;
197 let mut rel_areas: Vec<RelArea> = Vec::new();
198 for chunk in chunks {
199 rel_areas.extend(chunk.areas);
200 }
201 let mut outer_wanted: Vec<i64> = rel_areas
202 .iter()
203 .flat_map(|a| a.outer_ways.iter().copied())
204 .collect();
205 outer_wanted.sort_unstable();
206 outer_wanted.dedup();
207 println!("{} POI relation(s)", rel_areas.len());
208
209 timer.switch("ways");
210 // --- Pass 2: closed-way areas + the relations' outer ways ----------------
211 let (chunks, _) = pbf::run_pass(
212 input,
213 &blobs,
214 Some(&blob_kinds),
215 KIND_WAYS,
216 "Pass 2: ways",
217 WayPass::default,
218 |state, block| way_blob(state, block, &outer_wanted),
219 )?;
220 let mut way_areas: Vec<WayArea> = Vec::new();
221 let mut outer_refs: HashMap<i64, Vec<i64>> = HashMap::new();
222 for chunk in chunks {
223 way_areas.extend(chunk.areas);
224 outer_refs.extend(chunk.outer_refs);
225 }
226
227 // Every node whose location an area centroid needs.
228 let mut needed: Vec<i64> = way_areas
229 .iter()
230 .flat_map(|a| a.refs.iter().copied())
231 .chain(outer_refs.values().flat_map(|r| r.iter().copied()))
232 .collect();
233 needed.sort_unstable();
234 needed.dedup();
235 println!(
236 "{} closed-way area(s), {} node location(s) needed",
237 way_areas.len(),
238 needed.len()
239 );
240
241 timer.switch("nodes");
242 // --- Pass 3: node POIs + the node locations areas need -------------------
243 let (chunks, _) = pbf::run_pass(
244 input,
245 &blobs,
246 Some(&blob_kinds),
247 KIND_NODES,
248 "Pass 3: nodes",
249 NodePass::default,
250 |state, block| node_blob(state, block, &needed, bbox.as_ref()),
251 )?;
252 let mut pois: Vec<Poi> = Vec::new();
253 let mut locs: Vec<(i32, i32)> = vec![(NO_LOC, NO_LOC); needed.len()];
254 for chunk in chunks {
255 pois.extend(chunk.pois);
256 for (idx, lat, lon) in chunk.locs {
257 locs[idx as usize] = (lat, lon);
258 }
259 }
260 let from_nodes = pois.len();
261
262 let location = |id: i64| -> Option<(i32, i32)> {
263 let idx = needed.binary_search(&id).ok()?;
264 let (lat, lon) = locs[idx];
265 (lat != NO_LOC).then_some((lat, lon))
266 };
267
268 // A POI touches the region when any of its vertices does — same
269 // `complete_ways` rule as the graph. The centroid is computed from the
270 // whole ring regardless, so a border-straddling POI keeps its true
271 // location.
272 let touches = |ids: &mut dyn Iterator<Item = i64>| -> bool {
273 let Some(b) = bbox.as_ref() else {
274 return true;
275 };
276 ids.filter_map(&location).any(|(lat, lon)| b.contains_e7(lat, lon))
277 };
278
279 timer.switch("centroids");
280 // --- Area centroids ------------------------------------------------------
281 for area in &way_areas {
282 if !touches(&mut area.refs.iter().copied()) {
283 continue;
284 }
285 // A closed way's ring is its own node list minus the repeated closing
286 // node.
287 if let Some(poi) = ring_centroid(area.refs[..area.refs.len() - 1].iter().copied(), &location)
288 {
289 pois.push(make_poi(poi, area.type_, area.id, &area.name, area.attrs.clone()));
290 }
291 }
292 let from_ways = pois.len() - from_nodes;
293
294 for area in &rel_areas {
295 // libosmium assembled a true ring from the member ways; we cannot, so
296 // deduplicate the member node ids instead. That is exact when the outer
297 // ring is a single closed way, and drops the endpoints shared between
298 // consecutive ways when it is split across several.
299 let mut refs: Vec<i64> = area
300 .outer_ways
301 .iter()
302 .filter_map(|w| outer_refs.get(w))
303 .flat_map(|r| r.iter().copied())
304 .collect();
305 refs.sort_unstable();
306 refs.dedup();
307 if !touches(&mut refs.iter().copied()) {
308 continue;
309 }
310 if let Some(poi) = ring_centroid(refs.iter().copied(), &location) {
311 pois.push(make_poi(poi, area.type_, -area.id, &area.name, area.attrs.clone()));
312 }
313 }
314 let from_relations = pois.len() - from_nodes - from_ways;
315 println!(
316 "Extracted {} POI(s): {from_nodes} node, {from_ways} closed-way, {from_relations} relation",
317 pois.len()
318 );
319
320 // Before the sort: `pois` is still nodes, then ways, then relations, which is
321 // the only place the OSM element type is known.
322 let with_reviews = match reviews {
323 Some(table) => {
324 let n = apply_reviews(&mut pois, from_nodes, from_ways, table);
325 println!("{n} POI(s) with review data ({} review row(s) loaded)", table.len());
326 n
327 }
328 None => 0,
329 };
330
331 // Morton order, ties broken by osm_id, so both poi_index.bin and the geojson
332 // are stable across runs.
333 timer.switch("sort");
334 pois.sort_by_key(|p| (p.morton, p.osm_id));
335
336 timer.switch("write");
337 let written = write_outputs(&pois, geojson, names, index, attrs, spatial, name_index)?;
338 timer.finish();
339 Ok(Stats {
340 records: written.records,
341 unique_names: written.unique_names,
342 name_bytes: written.name_bytes,
343 from_nodes,
344 from_ways,
345 from_relations,
346 with_attrs: written.with_attrs,
347 unique_attrs: written.unique_attrs,
348 attr_bytes: written.attr_bytes,
349 spatial_cells: written.spatial_cells,
350 name_entries: written.name_entries,
351 with_reviews,
352 })
353}
354
355/// Append each matching review row to its POI's attribute body; returns the match
356/// count. `pois[..from_nodes]` are nodes, the next `from_ways` closed ways, the
357/// rest relations (whose `osm_id` is stored negated).
358fn apply_reviews(pois: &mut [Poi], from_nodes: usize, from_ways: usize, table: &ReviewTable) -> usize {
359 let mut matched = 0;
360 for (i, p) in pois.iter_mut().enumerate() {
361 let (element, id) = if i < from_nodes {
362 (ELEMENT_NODE, p.osm_id)
363 } else if i < from_nodes + from_ways {
364 (ELEMENT_WAY, p.osm_id)
365 } else {
366 (ELEMENT_RELATION, -p.osm_id)
367 };
368 if let Some(review) = table.get(element, id) {
369 p.attrs = crate::poi_attrs::append(std::mem::take(&mut p.attrs), &review.fields());
370 matched += 1;
371 }
372 }
373 matched
374}
375
376fn poi_tags<'a>(t: &osm::Tags<'_, 'a>) -> PoiTags<'a> {
377 PoiTags {
378 railway: t.get_str("railway"),
379 public_transport: t.get_str("public_transport"),
380 amenity: t.get_str("amenity"),
381 shop: t.get_str("shop"),
382 tourism: t.get_str("tourism"),
383 leisure: t.get_str("leisure"),
384 healthcare: t.get_str("healthcare"),
385 office: t.get_str("office"),
386 }
387}
388
389fn relation_blob(state: &mut RelPass, block: &pbf::PrimitiveBlock) -> Result<u8> {
390 let mut kinds = 0u8;
391 visit_block(block, KIND_RELATIONS, &mut kinds, &mut |el: Element| {
392 if let Element::Relation(r) = el {
393 let is_area = r
394 .tags
395 .get_str("type")
396 .is_some_and(|t| AREA_RELATION_TYPES.contains(&t));
397 if !is_area {
398 return Ok(());
399 }
400 let name = match r.tags.get("name") {
401 Some(n) if !n.is_empty() => n,
402 _ => return Ok(()),
403 };
404 if let Some(type_) = tags::classify(&poi_tags(&r.tags)) {
405 state.areas.push(RelArea {
406 id: r.id,
407 type_,
408 name: name.to_vec(),
409 attrs: crate::poi_attrs::encode(|k| r.tags.get(k)),
410 outer_ways: r
411 .members
412 .iter()
413 .filter(|m| m.kind == MEMBER_WAY && (m.role == b"outer" || m.role.is_empty()))
414 .map(|m| m.id)
415 .collect(),
416 });
417 }
418 }
419 Ok(())
420 })?;
421 Ok(kinds)
422}
423
424fn way_blob(
425 state: &mut WayPass,
426 block: &pbf::PrimitiveBlock,
427 outer_wanted: &[i64],
428) -> Result<u8> {
429 let mut kinds = 0u8;
430 visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {
431 if let Element::Way(w) = el {
432 if outer_wanted.binary_search(&w.id).is_ok() {
433 state.outer_refs.push((w.id, w.refs.to_vec()));
434 }
435 // libosmium's `MultipolygonManager::after_way` builds a standalone
436 // area from every closed way with more than 3 nodes that is not
437 // tagged `area=no` — including ways that are also members of a
438 // multipolygon relation, so a campus tagged on both the relation and
439 // its rings yields a POI either way. It compares end *locations*;
440 // comparing the end refs is equivalent for real OSM data and needs no
441 // location index here.
442 let closed = w.refs.len() > 3 && w.refs.first() == w.refs.last();
443 if !closed || w.tags.get_str("area") == Some("no") {
444 return Ok(());
445 }
446 let name = match w.tags.get("name") {
447 Some(n) if !n.is_empty() => n,
448 _ => return Ok(()),
449 };
450 if let Some(type_) = tags::classify(&poi_tags(&w.tags)) {
451 state.areas.push(WayArea {
452 id: w.id,
453 type_,
454 name: name.to_vec(),
455 attrs: crate::poi_attrs::encode(|k| w.tags.get(k)),
456 refs: w.refs.to_vec(),
457 });
458 }
459 }
460 Ok(())
461 })?;
462 Ok(kinds)
463}
464
465fn node_blob(
466 state: &mut NodePass,
467 block: &pbf::PrimitiveBlock,
468 needed: &[i64],
469 bbox: Option<&crate::bbox::BBox>,
470) -> Result<u8> {
471 let mut kinds = 0u8;
472 visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {
473 if let Element::Node(n) = el {
474 if let Ok(idx) = needed.binary_search(&n.id) {
475 state.locs.push((idx as u32, n.lat_e7, n.lon_e7));
476 }
477 if n.tags.is_empty() {
478 return Ok(());
479 }
480 // A node POI outside the region is dropped here; its own location
481 // arrives with it, so no location table is needed.
482 if !crate::bbox::keep_e7(bbox, n.lat_e7, n.lon_e7) {
483 return Ok(());
484 }
485 let name = match n.tags.get("name") {
486 Some(v) if !v.is_empty() => v,
487 _ => return Ok(()),
488 };
489 if let Some(type_) = tags::classify(&poi_tags(&n.tags)) {
490 state.pois.push(make_poi(
491 (n.lat_e7 as f64 * 1e-7, n.lon_e7 as f64 * 1e-7),
492 type_,
493 n.id,
494 name,
495 crate::poi_attrs::encode(|k| n.tags.get(k)),
496 ));
497 }
498 }
499 Ok(())
500 })?;
501 Ok(kinds)
502}
503
504/// Average of an area ring's vertices, reproducing libosmium's representative
505/// point.
506///
507/// `refs` is the ring's *distinct* vertices. libosmium stored a ring closed — the
508/// start vertex appears again at the end — and its Assembler sorted the ring's
509/// segments before walking them, so the ring always starts at the vertex with the
510/// smallest `(lon, lat)`. That vertex is therefore the one counted twice, which is
511/// why it is added again here: averaging the way's own node list instead would
512/// double the way's *first* node and land metres off on a small building.
513fn ring_centroid<I, L>(refs: I, location: &L) -> Option<(f64, f64)>
514where
515 I: Iterator<Item = i64>,
516 L: Fn(i64) -> Option<(i32, i32)>,
517{
518 let mut sum_lat = 0.0f64;
519 let mut sum_lon = 0.0f64;
520 let mut n = 0u64;
521 let mut start: Option<(i32, i32)> = None;
522 for id in refs {
523 if let Some((lat_e7, lon_e7)) = location(id) {
524 sum_lat += lat_e7 as f64 * 1e-7;
525 sum_lon += lon_e7 as f64 * 1e-7;
526 n += 1;
527 // libosmium's Location orders by x (lon) then y (lat).
528 if start.is_none_or(|(slat, slon)| (lon_e7, lat_e7) < (slon, slat)) {
529 start = Some((lat_e7, lon_e7));
530 }
531 }
532 }
533 let (slat, slon) = start?;
534 sum_lat += slat as f64 * 1e-7;
535 sum_lon += slon as f64 * 1e-7;
536 Some((sum_lat / (n + 1) as f64, sum_lon / (n + 1) as f64))
537}
538
539include!("poi_build_part1.rs");
540include!("poi_build_part2.rs");