Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / extract_part3.rs
extract_part3.rs438 lines · 20.6 KiBRaw
| 1 | /// One relation's geometry, built off the shared tables with nothing mutable touched, so a batch of |
| 2 | /// them fans out across the pool exactly as [`materialise_ways`] does. The sink and the conventions |
| 3 | /// grid are fed from these **in relation order** in the serial drain, which is what keeps the |
| 4 | /// archive byte-identical: the drain order is the spill order is the archive's. |
| 5 | /// |
| 6 | /// Geometry arrives spill-encoded ([`EncodedGeom`](crate::store::EncodedGeom)): the pool walks |
| 7 | /// vertices, the drain appends bytes. The region keep/drop decision is precomputed alongside |
| 8 | /// (pure per-relation work over the resolved shape), so the drain's only vertex touch is |
| 9 | /// `conventions.add`'s grid stamp — which must stay serial and ordered anyway (precedence). |
| 10 | enum BuiltRelation { |
| 11 | /// A label relation centroided to a point, `None` when it had no locatable members. |
| 12 | Label(Option<(f64, f64)>), |
| 13 | /// A border relation's member lines, spill-encoded, already filtered to those with two or |
| 14 | /// more points. Borders are never region-filtered (region shapes are always kept), so no |
| 15 | /// keep flag rides along. `empty` is the pre-encode shape test (`lines.is_empty()`): an |
| 16 | /// encoded empty still carries count bytes, so the drain cannot tell it from content by |
| 17 | /// looking at the bytes — and the old drain counted it `geometry_failed` rather than |
| 18 | /// pushing an empty record. |
| 19 | Border { encoded: Result<crate::store::EncodedGeom>, empty: bool }, |
| 20 | /// An area relation's stitched rings and the ring stats that stitching produced. The stats are |
| 21 | /// per-relation here and summed into [`Stats::rings`] serially — they are four additive counts, |
| 22 | /// so the sum is the same in any order. `encoded` is the assembled polygons, spill-ready; |
| 23 | /// `polygons` travels alongside for `conventions.add`, which needs rings rather than bytes. |
| 24 | /// `empty` is the pre-encode shape test (`polygons.is_empty()`), for the same reason as |
| 25 | /// [`BuiltRelation::Border`]'s. |
| 26 | Area { |
| 27 | polygons: Vec<rings::Polygon>, |
| 28 | encoded: Result<crate::store::EncodedGeom>, |
| 29 | empty: bool, |
| 30 | keep: bool, |
| 31 | rings: RingStats, |
| 32 | }, |
| 33 | } |
| 34 | |
| 35 | /// Build one relation's geometry. Reads only the shared `members` map and the resolved `table`, |
| 36 | /// both immutable, so it is safe to call across the pool. See [`BuiltRelation`]. |
| 37 | /// |
| 38 | /// `region` joins the pool inputs (shared ref): the buildings-area keep/drop test walks every |
| 39 | /// vertex (`polygons_touch`), and the drain must not. Labels keep their O(1) `point_touches` |
| 40 | /// in the drain — no walk to move. |
| 41 | fn build_relation( |
| 42 | relation: &Relation, |
| 43 | members: &MemberWays, |
| 44 | table: &NodeLocations, |
| 45 | region: Option<&osm_ingest::bbox::BBox>, |
| 46 | ) -> BuiltRelation { |
| 47 | // A `places` relation (a country, a region) is labelled at its centroid: one point, not a |
| 48 | // stitched shape. The border itself lives in `boundaries`; this is the name. |
| 49 | if is_label(relation.class.layer) { |
| 50 | let line: Vec<(f64, f64)> = relation |
| 51 | .members |
| 52 | .iter() |
| 53 | .filter_map(|(id, _)| members.get(*id)) |
| 54 | .flat_map(|refs| table.line(refs)) |
| 55 | .collect(); |
| 56 | return BuiltRelation::Label(centroid(&line)); |
| 57 | } |
| 58 | // A boundary relation's members are the border. Each is emitted as its own line rather than |
| 59 | // stitched: the renderer strokes them, and a gap between two member ways is invisible in a |
| 60 | // stroke while a failed stitch would drop the whole border. |
| 61 | if !relation.area { |
| 62 | let lines: Vec<Vec<(f64, f64)>> = relation |
| 63 | .members |
| 64 | .iter() |
| 65 | .filter_map(|(id, _)| members.get(*id)) |
| 66 | .map(|refs| table.line(refs)) |
| 67 | .filter(|line| line.len() >= 2) |
| 68 | .collect(); |
| 69 | // Captured, not `?`: encode counts cannot overflow on real ways, but a |
| 70 | // pool panic would abort the build where a channelled error fails it in |
| 71 | // spill order. The drain reports the first failure in relation order. |
| 72 | let empty = lines.is_empty(); |
| 73 | let encoded = crate::store::EncodedGeom::live(&Geometry::Lines(lines)); |
| 74 | return BuiltRelation::Border { encoded, empty }; |
| 75 | } |
| 76 | let member_ways: Vec<MemberWay> = relation |
| 77 | .members |
| 78 | .iter() |
| 79 | .filter_map(|(id, inner)| { |
| 80 | Some(MemberWay { refs: members.get(*id)?.clone(), outer: !inner }) |
| 81 | }) |
| 82 | .collect(); |
| 83 | let mut rings = RingStats::default(); |
| 84 | let polygons = rings::assemble(&member_ways, |id| locate(table, id), &mut rings); |
| 85 | // Buildings are region-filtered; every other area layer is always kept. |
| 86 | // Decided here, on the assembled rings, so the drain never walks vertices. |
| 87 | let keep = relation.class.layer != tilecodec::mamaps::dict::LAYER_BUILDINGS |
| 88 | || polygons_touch(&polygons, region); |
| 89 | let geometry = Geometry::Polygons(polygons); |
| 90 | let empty = match &geometry { |
| 91 | Geometry::Polygons(polygons) => polygons.is_empty(), |
| 92 | // Unreachable: built as Polygons two lines up. The match (rather than |
| 93 | // reading `polygons` before the move) keeps the emptiness test next to |
| 94 | // the value the drain decides on. |
| 95 | _ => unreachable!("just built as Polygons"), |
| 96 | }; |
| 97 | let encoded = crate::store::EncodedGeom::live(&geometry); |
| 98 | let Geometry::Polygons(polygons) = geometry else { |
| 99 | unreachable!("just built as Polygons"); |
| 100 | }; |
| 101 | BuiltRelation::Area { polygons, encoded, empty, keep, rings } |
| 102 | } |
| 103 | |
| 104 | /// Materialise relations; returns the driving-side conventions. |
| 105 | /// |
| 106 | /// `region` filters the built layers (`roads`, `poi`, `buildings`) the same |
| 107 | /// way [`materialise_ways`] does. `boundaries` region shapes are always kept |
| 108 | /// — the driving-side grid must cover the world even in a region build, or |
| 109 | /// the tiler mis-marks roads at the region's edge. |
| 110 | fn materialise_relations( |
| 111 | relations: &[Relation], |
| 112 | members: &MemberWays, |
| 113 | table: &NodeLocations, |
| 114 | region: Option<&osm_ingest::bbox::BBox>, |
| 115 | sink: &mut Sink, |
| 116 | stats: &mut Stats, |
| 117 | ) -> Result<schema::boundaries::Conventions> { |
| 118 | let mut bar = Progress::new( |
| 119 | "Materialise: relations".to_string(), |
| 120 | relations.len(), |
| 121 | "relation(s)", |
| 122 | true, |
| 123 | ); |
| 124 | // Which driving side and centre-line colour applies where, accumulated as the country shapes |
| 125 | // go past. |
| 126 | let mut conventions = schema::boundaries::Conventions::default(); |
| 127 | // Batched, the [`materialise_ways`] pattern: `rings::assemble`, `centroid` and `table.line` are |
| 128 | // the heavy per-relation work, are independent, and touch no shared mutable state, so a batch of |
| 129 | // them goes as wide as the pool. The sink and the conventions grid then take the results **in |
| 130 | // relation order**, which keeps the archive byte-identical. `conventions.add` in particular has |
| 131 | // precedence rules (an interior claim outranks a border one), so it must stay serial and in |
| 132 | // order. |
| 133 | const MATERIALISE_RELATIONS_BATCH: usize = 4096; |
| 134 | let mut built: Vec<BuiltRelation> = Vec::with_capacity(MATERIALISE_RELATIONS_BATCH); |
| 135 | for batch in relations.chunks(MATERIALISE_RELATIONS_BATCH) { |
| 136 | built.clear(); |
| 137 | par::install(|| { |
| 138 | batch |
| 139 | .par_iter() |
| 140 | .map(|relation| build_relation(relation, members, table, region)) |
| 141 | .collect_into_vec(&mut built); |
| 142 | }); |
| 143 | for (relation, built) in batch.iter().zip(built.drain(..)) { |
| 144 | // `?` in spill order: the first encode failure in relation order, |
| 145 | // exactly as inline encoding would report it. |
| 146 | match built { |
| 147 | BuiltRelation::Label(Some(point)) => { |
| 148 | // `poi` labels are region-filtered; `places` always kept. |
| 149 | // O(1) point test, no vertex walk — stays in the drain. |
| 150 | if relation.class.layer == tilecodec::mamaps::dict::LAYER_POI |
| 151 | && !point_touches(&point, region) |
| 152 | { |
| 153 | bar.tick("relation(s)"); |
| 154 | continue; |
| 155 | } |
| 156 | sink.push_named( |
| 157 | &relation.class, |
| 158 | &crate::store::EncodedGeom::live(&Geometry::Points(vec![point]))?, |
| 159 | relation.name.as_deref(), |
| 160 | tagged_id(relation.id, ELEMENT_RELATION), |
| 161 | )?; |
| 162 | stats.features += 1; |
| 163 | } |
| 164 | BuiltRelation::Label(None) => stats.geometry_failed += 1, |
| 165 | BuiltRelation::Border { encoded, empty } => { |
| 166 | let encoded = encoded?; |
| 167 | if empty { |
| 168 | stats.geometry_failed += 1; |
| 169 | } else { |
| 170 | sink.push_named( |
| 171 | &relation.class, |
| 172 | &encoded, |
| 173 | None, |
| 174 | tilecodec::mamaps::body::ID_NONE, |
| 175 | )?; |
| 176 | stats.features += 1; |
| 177 | } |
| 178 | } |
| 179 | BuiltRelation::Area { polygons, encoded, empty, keep, rings } => { |
| 180 | // Accumulated whether or not the stitch produced anything, exactly as the |
| 181 | // in-place `&mut stats.rings` did: a failed stitch still counted its unclosed |
| 182 | // and orphan rings. |
| 183 | stats.rings.outer_rings += rings.outer_rings; |
| 184 | stats.rings.inner_rings += rings.inner_rings; |
| 185 | stats.rings.unclosed += rings.unclosed; |
| 186 | stats.rings.orphan_inner += rings.orphan_inner; |
| 187 | let encoded = encoded?; |
| 188 | if empty { |
| 189 | stats.geometry_failed += 1; |
| 190 | } else { |
| 191 | // The buildings keep/drop was decided on the pool; every |
| 192 | // other area layer is always kept. |
| 193 | if !keep { |
| 194 | bar.tick("relation(s)"); |
| 195 | continue; |
| 196 | } |
| 197 | // The id is what lets the mask gather a region's tile-clipped pieces back |
| 198 | // together. |
| 199 | let id = if tracks_ids(&relation.class) { |
| 200 | tagged_id(relation.id, ELEMENT_RELATION) |
| 201 | } else { |
| 202 | tilecodec::mamaps::body::ID_NONE |
| 203 | }; |
| 204 | // A multipolygon building carries its S3DB attributes into the building side |
| 205 | // table, just as a building way does. |
| 206 | if let Some(building) = relation.building { |
| 207 | sink.push_building(&relation.class, &encoded, None, building)?; |
| 208 | } else { |
| 209 | // The country's own shape is also what says how its roads are marked. |
| 210 | // Stamped before the shape is moved into the sink, from the assembled |
| 211 | // rings, so the grid and the border line agree about where it is. |
| 212 | if let Some(iso) = &relation.iso { |
| 213 | conventions.add(iso, &polygons); |
| 214 | } |
| 215 | sink.push_named(&relation.class, &encoded, None, id)?; |
| 216 | } |
| 217 | stats.features += 1; |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | bar.tick("relation(s)"); |
| 222 | } |
| 223 | } |
| 224 | bar.finish("relation(s)"); |
| 225 | |
| 226 | Ok(conventions) |
| 227 | } |
| 228 | |
| 229 | /// Coastline, transit, graph, then finish the store. Moved whole from `extract`. |
| 230 | fn append_external_and_finish( |
| 231 | coastline: &Path, |
| 232 | transit_routes: &Path, |
| 233 | graph: &Path, |
| 234 | mut sink: Sink, |
| 235 | stats: &mut Stats, |
| 236 | conventions: schema::boundaries::Conventions, |
| 237 | spill_path: &Path, |
| 238 | timer: &mut crate::timing::PhaseTimer, |
| 239 | ) -> Result<Store> { |
| 240 | // The mainland, last, because clipping it needs the extract's own bounding box and that is |
| 241 | // only known once every OSM feature has been through the sink. Order in the file does not |
| 242 | // matter: the tiler groups by layer id, so `earth` is the first layer of every body whenever it |
| 243 | // was written. |
| 244 | match sink.bbox_degrees() { |
| 245 | Some(bbox) => { |
| 246 | println!( |
| 247 | "reading land polygons within {:.3},{:.3} .. {:.3},{:.3}", |
| 248 | bbox.0, bbox.1, bbox.2, bbox.3, |
| 249 | ); |
| 250 | stats.land_polygons = schema::landtype::stream_prepared(coastline, bbox, &mut sink)?; |
| 251 | stats.features += stats.land_polygons; |
| 252 | } |
| 253 | // Nothing to clip against. Land alone would be an archive of one layer, and the caller |
| 254 | // almost certainly pointed at the wrong extract. |
| 255 | None => return err("the extract produced no features to place land against".to_string()), |
| 256 | } |
| 257 | // The `transit` layer, for the same reason and against the same bounding box: its geometry is |
| 258 | // GTFS rather than OSM (see [`schema::transit`]), so it is read here rather than classified in |
| 259 | // any of the passes above. |
| 260 | timer.switch("transit-routes"); |
| 261 | match sink.bbox_degrees() { |
| 262 | Some(bbox) => { |
| 263 | println!( |
| 264 | "reading transit routes within {:.3},{:.3} .. {:.3},{:.3}", |
| 265 | bbox.0, bbox.1, bbox.2, bbox.3, |
| 266 | ); |
| 267 | stats.transit_routes = schema::transit::stream_routes(transit_routes, bbox, &mut sink)?; |
| 268 | stats.features += stats.transit_routes; |
| 269 | } |
| 270 | None => { |
| 271 | return err("the extract produced no features to place transit routes against" |
| 272 | .to_string()) |
| 273 | } |
| 274 | } |
| 275 | // The `traffic` layer is dropped as of the NA diet: its 12.37GB (360M |
| 276 | // per-segment features, 5x the roads layer) cost more than the overlay earns, |
| 277 | // and the live-traffic display path needs a server contract change before a |
| 278 | // cheaper per-edge form can replace it. The layer stays in the format |
| 279 | // (layer_count 12, dict entry kept) so readers need no change — with zero |
| 280 | // features no body carries it and it costs nothing. `junction` below still |
| 281 | // reads the same graph, which is why the graph build and its validation stay. |
| 282 | // (Formerly: `stats.traffic_segments = schema::traffic::stream_graph(...)`.) |
| 283 | // The `junction` layer rides the graph: a lane connector is built from the junction |
| 284 | // node's own incident edges, so there is nothing to read that the traffic pass did not |
| 285 | // already need. `conventions` decides which side of a road the direction of travel sits |
| 286 | // on, and is borrowed here because it is moved into the store below. |
| 287 | timer.switch("junctions"); |
| 288 | println!("building lane connectors from the v6 routing graph for the junction layer"); |
| 289 | stats.junction_connectors = schema::junction::stream_junctions(graph, &conventions, &mut sink)?; |
| 290 | stats.features += stats.junction_connectors; |
| 291 | println!(" {} lane connector(s)", stats.junction_connectors); |
| 292 | // `sink.finish` itself is a flush, not a loop: every feature was serialised and its coordinates |
| 293 | // e7-quantised in the `push` that spilled it, back in `materialise_ways`/`materialise_relations` |
| 294 | // (both parallel, both under a "Materialise:" bar) and in the streams above. The spill's byte |
| 295 | // order is the archive's, so that write stays serial by construction — there is nothing here to |
| 296 | // parallelise. The bar makes the finalise step visible rather than a silent tail of the ~25 s |
| 297 | // this phase costs; `stats.features` is the count the sink is closing over. |
| 298 | timer.switch("finalise"); |
| 299 | let mut bar = Progress::new( |
| 300 | "Finalise: features".to_string(), |
| 301 | stats.features as usize, |
| 302 | "feature(s)", |
| 303 | true, |
| 304 | ); |
| 305 | let store = sink.finish(spill_path)?; |
| 306 | bar.finish("feature(s)"); |
| 307 | let store = store.with_conventions(conventions); |
| 308 | |
| 309 | Ok(store) |
| 310 | } |
| 311 | |
| 312 | /// Node refs, duplicates included, above which the bitset replaces the sorted vector. |
| 313 | /// |
| 314 | /// 256 M refs is a 2 GB `Vec<i64>` plus a sort of 256 M elements, and it is roughly a us-west |
| 315 | /// extract. Below it the vector is smaller than the bitset and this stays exactly as it always was; |
| 316 | /// above it the vector is the largest thing in stage A and the bitset is a constant. |
| 317 | const REFS_IN_MEMORY: usize = 256 << 20; |
| 318 | |
| 319 | /// The node id a bitset will not be sized past. |
| 320 | /// |
| 321 | /// OSM assigns node ids monotonically and is near 13 G, so this is roughly 4x today's high-water |
| 322 | /// mark and 2.6 GB of bitset. It is a bound on the *data*, and a synthetic or non-OSM input with one |
| 323 | /// sparse enormous id would otherwise ask for a bitset the size of the id, so it is an error rather |
| 324 | /// than a clamp: a clamp would silently drop the nodes above it. |
| 325 | const MAX_NODE_ID: i64 = 48 << 30; |
| 326 | |
| 327 | /// The ids pass 3 must resolve, collected the way stage A always did. |
| 328 | /// |
| 329 | /// One bit per node id in `0..=max_id`. |
| 330 | struct NeededBits { |
| 331 | words: Vec<u64>, |
| 332 | /// `max_id + 1`. Kept because the last word is padded and a ref landing in that padding is out |
| 333 | /// of range, not merely addressable. |
| 334 | bits: usize, |
| 335 | count: usize, |
| 336 | } |
| 337 | |
| 338 | impl NeededBits { |
| 339 | fn new(max_id: i64) -> Result<NeededBits> { |
| 340 | if max_id > MAX_NODE_ID { |
| 341 | return err(format!( |
| 342 | "node id {max_id} is past the {MAX_NODE_ID} this build will size a bitset for; \ |
| 343 | OSM's own ids are near 13 billion, so this input is not an OSM extract" |
| 344 | )); |
| 345 | } |
| 346 | // `max_id` is a maximum, not a count, so the space is one larger. |
| 347 | let bits = max_id.max(0) as usize + 1; |
| 348 | Ok(NeededBits { words: vec![0u64; bits.div_ceil(64)], bits, count: 0 }) |
| 349 | } |
| 350 | |
| 351 | /// An unsized bitset that grows as larger ids arrive, for fusing collection |
| 352 | /// into pass 1's drain: the maximum is not known until the last way is |
| 353 | /// pushed, so the words extend on demand instead. Same guards as [`new`]; |
| 354 | /// the final size is identical to a sized bitset over the same ids. |
| 355 | fn new_growable() -> NeededBits { |
| 356 | NeededBits { words: Vec::new(), bits: 0, count: 0 } |
| 357 | } |
| 358 | |
| 359 | /// Set a bit, growing the words when the id lands past them. |
| 360 | /// |
| 361 | /// Refused rather than grown past [`MAX_NODE_ID`], like [`new`]: an id out |
| 362 | /// there is not an OSM node and growing for it would size the bitset for |
| 363 | /// one corrupt ref. |
| 364 | fn set_growable(&mut self, id: i64) -> Result<()> { |
| 365 | if id < 0 { |
| 366 | return err(format!("node ref {id} is negative")); |
| 367 | } |
| 368 | if id > MAX_NODE_ID { |
| 369 | return err(format!( |
| 370 | "node ref {id} is past the {MAX_NODE_ID} this build will size a bitset for" |
| 371 | )); |
| 372 | } |
| 373 | let at = id as usize; |
| 374 | if at >= self.bits { |
| 375 | self.bits = at + 1; |
| 376 | self.words.resize(self.bits.div_ceil(64), 0); |
| 377 | } |
| 378 | let word = &mut self.words[at / 64]; |
| 379 | let bit = 1u64 << (at % 64); |
| 380 | if *word & bit == 0 { |
| 381 | *word |= bit; |
| 382 | self.count += 1; |
| 383 | } |
| 384 | Ok(()) |
| 385 | } |
| 386 | |
| 387 | fn set(&mut self, id: i64) -> Result<()> { |
| 388 | // A negative ref is not a node this planet has. Refused rather than skipped: it means the |
| 389 | // spill or the PBF is not what it claims, and skipping would show as a way with a gap in it. |
| 390 | if id < 0 { |
| 391 | return err(format!("node ref {id} is negative")); |
| 392 | } |
| 393 | let at = id as usize; |
| 394 | if at >= self.bits { |
| 395 | return err(format!( |
| 396 | "node ref {id} is past the {} the bitset was sized for", |
| 397 | self.bits - 1 |
| 398 | )); |
| 399 | } |
| 400 | let word = &mut self.words[at / 64]; |
| 401 | let bit = 1u64 << (at % 64); |
| 402 | if *word & bit == 0 { |
| 403 | *word |= bit; |
| 404 | self.count += 1; |
| 405 | } |
| 406 | Ok(()) |
| 407 | } |
| 408 | |
| 409 | /// How many distinct ids were set. The `len` [`NodeLocations::from_bitset`] sizes from. |
| 410 | fn len(&self) -> usize { |
| 411 | self.count |
| 412 | } |
| 413 | |
| 414 | /// Hand the words over to the rank index: the collector is done setting bits and the index is |
| 415 | /// done needing a settable bitset, so one moves into the other rather than both living at once. |
| 416 | /// Consumes `self`; the count travels beside the words so the index need not recount them. |
| 417 | fn into_words(self) -> (Vec<u64>, usize) { |
| 418 | (self.words, self.count) |
| 419 | } |
| 420 | |
| 421 | /// Every set id, ascending. `trailing_zeros` on a word at a time, so an empty stretch of the id |
| 422 | /// space -- which is most of it, since a needed set is a subset of a subset -- costs one compare |
| 423 | /// per 64 ids rather than one per id. |
| 424 | fn ids(&self) -> impl Iterator<Item = i64> + '_ { |
| 425 | self.words.iter().enumerate().flat_map(|(w, word)| { |
| 426 | let mut rest = *word; |
| 427 | std::iter::from_fn(move || { |
| 428 | if rest == 0 { |
| 429 | return None; |
| 430 | } |
| 431 | let bit = rest.trailing_zeros() as usize; |
| 432 | rest &= rest - 1; |
| 433 | Some((w * 64 + bit) as i64) |
| 434 | }) |
| 435 | }) |
| 436 | } |
| 437 | } |
| 438 |