/// One relation's geometry, built off the shared tables with nothing mutable touched, so a batch of /// them fans out across the pool exactly as [`materialise_ways`] does. The sink and the conventions /// grid are fed from these **in relation order** in the serial drain, which is what keeps the /// archive byte-identical: the drain order is the spill order is the archive's. /// /// Geometry arrives spill-encoded ([`EncodedGeom`](crate::store::EncodedGeom)): the pool walks /// vertices, the drain appends bytes. The region keep/drop decision is precomputed alongside /// (pure per-relation work over the resolved shape), so the drain's only vertex touch is /// `conventions.add`'s grid stamp — which must stay serial and ordered anyway (precedence). enum BuiltRelation { /// A label relation centroided to a point, `None` when it had no locatable members. Label(Option<(f64, f64)>), /// A border relation's member lines, spill-encoded, already filtered to those with two or /// more points. Borders are never region-filtered (region shapes are always kept), so no /// keep flag rides along. `empty` is the pre-encode shape test (`lines.is_empty()`): an /// encoded empty still carries count bytes, so the drain cannot tell it from content by /// looking at the bytes — and the old drain counted it `geometry_failed` rather than /// pushing an empty record. Border { encoded: Result, empty: bool }, /// An area relation's stitched rings and the ring stats that stitching produced. The stats are /// per-relation here and summed into [`Stats::rings`] serially — they are four additive counts, /// so the sum is the same in any order. `encoded` is the assembled polygons, spill-ready; /// `polygons` travels alongside for `conventions.add`, which needs rings rather than bytes. /// `empty` is the pre-encode shape test (`polygons.is_empty()`), for the same reason as /// [`BuiltRelation::Border`]'s. Area { polygons: Vec, encoded: Result, empty: bool, keep: bool, rings: RingStats, }, } /// Build one relation's geometry. Reads only the shared `members` map and the resolved `table`, /// both immutable, so it is safe to call across the pool. See [`BuiltRelation`]. /// /// `region` joins the pool inputs (shared ref): the buildings-area keep/drop test walks every /// vertex (`polygons_touch`), and the drain must not. Labels keep their O(1) `point_touches` /// in the drain — no walk to move. fn build_relation( relation: &Relation, members: &MemberWays, table: &NodeLocations, region: Option<&osm_ingest::bbox::BBox>, ) -> BuiltRelation { // A `places` relation (a country, a region) is labelled at its centroid: one point, not a // stitched shape. The border itself lives in `boundaries`; this is the name. if is_label(relation.class.layer) { let line: Vec<(f64, f64)> = relation .members .iter() .filter_map(|(id, _)| members.get(*id)) .flat_map(|refs| table.line(refs)) .collect(); return BuiltRelation::Label(centroid(&line)); } // A boundary relation's members are the border. Each is emitted as its own line rather than // stitched: the renderer strokes them, and a gap between two member ways is invisible in a // stroke while a failed stitch would drop the whole border. if !relation.area { let lines: Vec> = relation .members .iter() .filter_map(|(id, _)| members.get(*id)) .map(|refs| table.line(refs)) .filter(|line| line.len() >= 2) .collect(); // Captured, not `?`: encode counts cannot overflow on real ways, but a // pool panic would abort the build where a channelled error fails it in // spill order. The drain reports the first failure in relation order. let empty = lines.is_empty(); let encoded = crate::store::EncodedGeom::live(&Geometry::Lines(lines)); return BuiltRelation::Border { encoded, empty }; } let member_ways: Vec = relation .members .iter() .filter_map(|(id, inner)| { Some(MemberWay { refs: members.get(*id)?.clone(), outer: !inner }) }) .collect(); let mut rings = RingStats::default(); let polygons = rings::assemble(&member_ways, |id| locate(table, id), &mut rings); // Buildings are region-filtered; every other area layer is always kept. // Decided here, on the assembled rings, so the drain never walks vertices. let keep = relation.class.layer != tilecodec::mamaps::dict::LAYER_BUILDINGS || polygons_touch(&polygons, region); let geometry = Geometry::Polygons(polygons); let empty = match &geometry { Geometry::Polygons(polygons) => polygons.is_empty(), // Unreachable: built as Polygons two lines up. The match (rather than // reading `polygons` before the move) keeps the emptiness test next to // the value the drain decides on. _ => unreachable!("just built as Polygons"), }; let encoded = crate::store::EncodedGeom::live(&geometry); let Geometry::Polygons(polygons) = geometry else { unreachable!("just built as Polygons"); }; BuiltRelation::Area { polygons, encoded, empty, keep, rings } } /// Materialise relations; returns the driving-side conventions. /// /// `region` filters the built layers (`roads`, `poi`, `buildings`) the same /// way [`materialise_ways`] does. `boundaries` region shapes are always kept /// — the driving-side grid must cover the world even in a region build, or /// the tiler mis-marks roads at the region's edge. fn materialise_relations( relations: &[Relation], members: &MemberWays, table: &NodeLocations, region: Option<&osm_ingest::bbox::BBox>, sink: &mut Sink, stats: &mut Stats, ) -> Result { let mut bar = Progress::new( "Materialise: relations".to_string(), relations.len(), "relation(s)", true, ); // Which driving side and centre-line colour applies where, accumulated as the country shapes // go past. let mut conventions = schema::boundaries::Conventions::default(); // Batched, the [`materialise_ways`] pattern: `rings::assemble`, `centroid` and `table.line` are // the heavy per-relation work, are independent, and touch no shared mutable state, so a batch of // them goes as wide as the pool. The sink and the conventions grid then take the results **in // relation order**, which keeps the archive byte-identical. `conventions.add` in particular has // precedence rules (an interior claim outranks a border one), so it must stay serial and in // order. const MATERIALISE_RELATIONS_BATCH: usize = 4096; let mut built: Vec = Vec::with_capacity(MATERIALISE_RELATIONS_BATCH); for batch in relations.chunks(MATERIALISE_RELATIONS_BATCH) { built.clear(); par::install(|| { batch .par_iter() .map(|relation| build_relation(relation, members, table, region)) .collect_into_vec(&mut built); }); for (relation, built) in batch.iter().zip(built.drain(..)) { // `?` in spill order: the first encode failure in relation order, // exactly as inline encoding would report it. match built { BuiltRelation::Label(Some(point)) => { // `poi` labels are region-filtered; `places` always kept. // O(1) point test, no vertex walk — stays in the drain. if relation.class.layer == tilecodec::mamaps::dict::LAYER_POI && !point_touches(&point, region) { bar.tick("relation(s)"); continue; } sink.push_named( &relation.class, &crate::store::EncodedGeom::live(&Geometry::Points(vec![point]))?, relation.name.as_deref(), tagged_id(relation.id, ELEMENT_RELATION), )?; stats.features += 1; } BuiltRelation::Label(None) => stats.geometry_failed += 1, BuiltRelation::Border { encoded, empty } => { let encoded = encoded?; if empty { stats.geometry_failed += 1; } else { sink.push_named( &relation.class, &encoded, None, tilecodec::mamaps::body::ID_NONE, )?; stats.features += 1; } } BuiltRelation::Area { polygons, encoded, empty, keep, rings } => { // Accumulated whether or not the stitch produced anything, exactly as the // in-place `&mut stats.rings` did: a failed stitch still counted its unclosed // and orphan rings. stats.rings.outer_rings += rings.outer_rings; stats.rings.inner_rings += rings.inner_rings; stats.rings.unclosed += rings.unclosed; stats.rings.orphan_inner += rings.orphan_inner; let encoded = encoded?; if empty { stats.geometry_failed += 1; } else { // The buildings keep/drop was decided on the pool; every // other area layer is always kept. if !keep { bar.tick("relation(s)"); continue; } // The id is what lets the mask gather a region's tile-clipped pieces back // together. let id = if tracks_ids(&relation.class) { tagged_id(relation.id, ELEMENT_RELATION) } else { tilecodec::mamaps::body::ID_NONE }; // A multipolygon building carries its S3DB attributes into the building side // table, just as a building way does. if let Some(building) = relation.building { sink.push_building(&relation.class, &encoded, None, building)?; } else { // The country's own shape is also what says how its roads are marked. // Stamped before the shape is moved into the sink, from the assembled // rings, so the grid and the border line agree about where it is. if let Some(iso) = &relation.iso { conventions.add(iso, &polygons); } sink.push_named(&relation.class, &encoded, None, id)?; } stats.features += 1; } } } bar.tick("relation(s)"); } } bar.finish("relation(s)"); Ok(conventions) } /// Coastline, transit, graph, then finish the store. Moved whole from `extract`. fn append_external_and_finish( coastline: &Path, transit_routes: &Path, graph: &Path, mut sink: Sink, stats: &mut Stats, conventions: schema::boundaries::Conventions, spill_path: &Path, timer: &mut crate::timing::PhaseTimer, ) -> Result { // The mainland, last, because clipping it needs the extract's own bounding box and that is // only known once every OSM feature has been through the sink. Order in the file does not // matter: the tiler groups by layer id, so `earth` is the first layer of every body whenever it // was written. match sink.bbox_degrees() { Some(bbox) => { println!( "reading land polygons within {:.3},{:.3} .. {:.3},{:.3}", bbox.0, bbox.1, bbox.2, bbox.3, ); stats.land_polygons = schema::landtype::stream_prepared(coastline, bbox, &mut sink)?; stats.features += stats.land_polygons; } // Nothing to clip against. Land alone would be an archive of one layer, and the caller // almost certainly pointed at the wrong extract. None => return err("the extract produced no features to place land against".to_string()), } // The `transit` layer, for the same reason and against the same bounding box: its geometry is // GTFS rather than OSM (see [`schema::transit`]), so it is read here rather than classified in // any of the passes above. timer.switch("transit-routes"); match sink.bbox_degrees() { Some(bbox) => { println!( "reading transit routes within {:.3},{:.3} .. {:.3},{:.3}", bbox.0, bbox.1, bbox.2, bbox.3, ); stats.transit_routes = schema::transit::stream_routes(transit_routes, bbox, &mut sink)?; stats.features += stats.transit_routes; } None => { return err("the extract produced no features to place transit routes against" .to_string()) } } // The `traffic` layer is dropped as of the NA diet: its 12.37GB (360M // per-segment features, 5x the roads layer) cost more than the overlay earns, // and the live-traffic display path needs a server contract change before a // cheaper per-edge form can replace it. The layer stays in the format // (layer_count 12, dict entry kept) so readers need no change — with zero // features no body carries it and it costs nothing. `junction` below still // reads the same graph, which is why the graph build and its validation stay. // (Formerly: `stats.traffic_segments = schema::traffic::stream_graph(...)`.) // The `junction` layer rides the graph: a lane connector is built from the junction // node's own incident edges, so there is nothing to read that the traffic pass did not // already need. `conventions` decides which side of a road the direction of travel sits // on, and is borrowed here because it is moved into the store below. timer.switch("junctions"); println!("building lane connectors from the v6 routing graph for the junction layer"); stats.junction_connectors = schema::junction::stream_junctions(graph, &conventions, &mut sink)?; stats.features += stats.junction_connectors; println!(" {} lane connector(s)", stats.junction_connectors); // `sink.finish` itself is a flush, not a loop: every feature was serialised and its coordinates // e7-quantised in the `push` that spilled it, back in `materialise_ways`/`materialise_relations` // (both parallel, both under a "Materialise:" bar) and in the streams above. The spill's byte // order is the archive's, so that write stays serial by construction — there is nothing here to // parallelise. The bar makes the finalise step visible rather than a silent tail of the ~25 s // this phase costs; `stats.features` is the count the sink is closing over. timer.switch("finalise"); let mut bar = Progress::new( "Finalise: features".to_string(), stats.features as usize, "feature(s)", true, ); let store = sink.finish(spill_path)?; bar.finish("feature(s)"); let store = store.with_conventions(conventions); Ok(store) } /// Node refs, duplicates included, above which the bitset replaces the sorted vector. /// /// 256 M refs is a 2 GB `Vec` plus a sort of 256 M elements, and it is roughly a us-west /// extract. Below it the vector is smaller than the bitset and this stays exactly as it always was; /// above it the vector is the largest thing in stage A and the bitset is a constant. const REFS_IN_MEMORY: usize = 256 << 20; /// The node id a bitset will not be sized past. /// /// OSM assigns node ids monotonically and is near 13 G, so this is roughly 4x today's high-water /// mark and 2.6 GB of bitset. It is a bound on the *data*, and a synthetic or non-OSM input with one /// sparse enormous id would otherwise ask for a bitset the size of the id, so it is an error rather /// than a clamp: a clamp would silently drop the nodes above it. const MAX_NODE_ID: i64 = 48 << 30; /// The ids pass 3 must resolve, collected the way stage A always did. /// /// One bit per node id in `0..=max_id`. struct NeededBits { words: Vec, /// `max_id + 1`. Kept because the last word is padded and a ref landing in that padding is out /// of range, not merely addressable. bits: usize, count: usize, } impl NeededBits { fn new(max_id: i64) -> Result { if max_id > MAX_NODE_ID { return err(format!( "node id {max_id} is past the {MAX_NODE_ID} this build will size a bitset for; \ OSM's own ids are near 13 billion, so this input is not an OSM extract" )); } // `max_id` is a maximum, not a count, so the space is one larger. let bits = max_id.max(0) as usize + 1; Ok(NeededBits { words: vec![0u64; bits.div_ceil(64)], bits, count: 0 }) } /// An unsized bitset that grows as larger ids arrive, for fusing collection /// into pass 1's drain: the maximum is not known until the last way is /// pushed, so the words extend on demand instead. Same guards as [`new`]; /// the final size is identical to a sized bitset over the same ids. fn new_growable() -> NeededBits { NeededBits { words: Vec::new(), bits: 0, count: 0 } } /// Set a bit, growing the words when the id lands past them. /// /// Refused rather than grown past [`MAX_NODE_ID`], like [`new`]: an id out /// there is not an OSM node and growing for it would size the bitset for /// one corrupt ref. fn set_growable(&mut self, id: i64) -> Result<()> { if id < 0 { return err(format!("node ref {id} is negative")); } if id > MAX_NODE_ID { return err(format!( "node ref {id} is past the {MAX_NODE_ID} this build will size a bitset for" )); } let at = id as usize; if at >= self.bits { self.bits = at + 1; self.words.resize(self.bits.div_ceil(64), 0); } let word = &mut self.words[at / 64]; let bit = 1u64 << (at % 64); if *word & bit == 0 { *word |= bit; self.count += 1; } Ok(()) } fn set(&mut self, id: i64) -> Result<()> { // A negative ref is not a node this planet has. Refused rather than skipped: it means the // spill or the PBF is not what it claims, and skipping would show as a way with a gap in it. if id < 0 { return err(format!("node ref {id} is negative")); } let at = id as usize; if at >= self.bits { return err(format!( "node ref {id} is past the {} the bitset was sized for", self.bits - 1 )); } let word = &mut self.words[at / 64]; let bit = 1u64 << (at % 64); if *word & bit == 0 { *word |= bit; self.count += 1; } Ok(()) } /// How many distinct ids were set. The `len` [`NodeLocations::from_bitset`] sizes from. fn len(&self) -> usize { self.count } /// Hand the words over to the rank index: the collector is done setting bits and the index is /// done needing a settable bitset, so one moves into the other rather than both living at once. /// Consumes `self`; the count travels beside the words so the index need not recount them. fn into_words(self) -> (Vec, usize) { (self.words, self.count) } /// Every set id, ascending. `trailing_zeros` on a word at a time, so an empty stretch of the id /// space -- which is most of it, since a needed set is a subset of a subset -- costs one compare /// per 64 ids rather than one per id. fn ids(&self) -> impl Iterator + '_ { self.words.iter().enumerate().flat_map(|(w, word)| { let mut rest = *word; std::iter::from_fn(move || { if rest == 0 { return None; } let bit = rest.trailing_zeros() as usize; rest &= rest - 1; Some((w * 64 + bit) as i64) }) }) } }