Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / extract_part2.rs
extract_part2.rs702 lines · 30.2 KiBRaw
| 1 | /// Pass 2: refs of every relation member way. Moved whole from `extract`. |
| 2 | fn load_member_ways( |
| 3 | input: &Path, |
| 4 | blobs: &[pbf::BlobLoc], |
| 5 | blob_kinds: &[u8], |
| 6 | relations: &[Relation], |
| 7 | ) -> Result<MemberWays> { |
| 8 | // --- pass 2: the refs of every relation member way ------------------------------------ |
| 9 | // |
| 10 | // **Every** member, not just the ones pass 1 did not classify. A relation reaches its members by |
| 11 | // id, in the order it lists them, which is the one random access in this stage and the one thing |
| 12 | // a sequential spill file cannot serve. So the members — and only the members — stay resident, |
| 13 | // and that is what lets the other several million classified ways go to disk. California has |
| 14 | // 63 156 relations, so this table is small next to the one it replaces; planet has 8.4 M, so |
| 15 | // it is a sorted vector rather than a hash map (see [`MemberWays`]). |
| 16 | let wanted: Vec<i64> = { |
| 17 | let mut wanted: Vec<i64> = relations |
| 18 | .iter() |
| 19 | .flat_map(|r| r.members.iter().map(|(id, _)| *id)) |
| 20 | .collect(); |
| 21 | wanted.sort_unstable(); |
| 22 | wanted.dedup(); |
| 23 | wanted |
| 24 | }; |
| 25 | let mut members = MemberWays::empty(); |
| 26 | if !wanted.is_empty() { |
| 27 | let (chunks, _) = pbf::run_pass( |
| 28 | input, |
| 29 | &blobs, |
| 30 | Some(&blob_kinds), |
| 31 | KIND_WAYS, |
| 32 | "Pass 2: member ways", |
| 33 | Vec::<(i64, Vec<i64>)>::new, |
| 34 | |state, block| { |
| 35 | let mut kinds = 0u8; |
| 36 | visit_block(block, KIND_WAYS, &mut kinds, &mut |el| { |
| 37 | if let Element::Way(way) = el { |
| 38 | if wanted.binary_search(&way.id).is_ok() { |
| 39 | state.push((way.id, way.refs.to_vec())); |
| 40 | } |
| 41 | } |
| 42 | Ok(()) |
| 43 | })?; |
| 44 | Ok(kinds) |
| 45 | }, |
| 46 | )?; |
| 47 | // Chunks arrive in file order and ways are sorted by id, so concatenation is sorted as |
| 48 | // long as no way id appears in two chunks (ids are unique in the PBF). Sortedness is |
| 49 | // asserted, not assumed: `MemberWays::build` sorts anyway, which is also what absorbs |
| 50 | // the (impossible in practice) duplicate across chunks. |
| 51 | let all: Vec<(i64, Vec<i64>)> = chunks.into_iter().flatten().collect(); |
| 52 | members = MemberWays::build(all); |
| 53 | } |
| 54 | |
| 55 | Ok(members) |
| 56 | } |
| 57 | |
| 58 | /// Relation member ways by id: the one random access in stage A. |
| 59 | /// |
| 60 | /// A `HashMap<i64, Vec<i64>>` costs ~48 B overhead per entry plus the hasher's table slack -- |
| 61 | /// at planet's 8.4 M member ways that is hundreds of MB beside the ref bytes themselves. This is |
| 62 | /// a sorted `Vec` with binary search instead: lookups are `O(log n)` rather than `O(1)`, but a |
| 63 | /// lookup is followed by cloning a ref vec and resolving every ref through the coordinate table, |
| 64 | /// so the search is noise next to the use. Built sorted once; every reader shares the shape. |
| 65 | pub struct MemberWays { |
| 66 | entries: Vec<(i64, Vec<i64>)>, |
| 67 | } |
| 68 | |
| 69 | impl MemberWays { |
| 70 | fn empty() -> MemberWays { |
| 71 | MemberWays { entries: Vec::new() } |
| 72 | } |
| 73 | |
| 74 | /// Build from `(way id, refs)` pairs in any order. Sorts by id; a duplicated id keeps its |
| 75 | /// first occurrence (ids are unique in the PBF, so this is defence, not logic). |
| 76 | fn build(mut all: Vec<(i64, Vec<i64>)>) -> MemberWays { |
| 77 | all.sort_by_key(|(id, _)| *id); |
| 78 | all.dedup_by_key(|(id, _)| *id); |
| 79 | MemberWays { entries: all } |
| 80 | } |
| 81 | |
| 82 | /// The refs of member way `id`, or `None` if pass 2 never saw it (an extract cut it away). |
| 83 | pub fn get(&self, id: i64) -> Option<&Vec<i64>> { |
| 84 | self.entries |
| 85 | .binary_search_by_key(&id, |(id, _)| *id) |
| 86 | .ok() |
| 87 | .map(|at| &self.entries[at].1) |
| 88 | } |
| 89 | |
| 90 | /// Every member's refs, for the ref collectors (order irrelevant: both collectors only add). |
| 91 | pub fn values(&self) -> impl Iterator<Item = &Vec<i64>> { |
| 92 | self.entries.iter().map(|(_, refs)| refs) |
| 93 | } |
| 94 | |
| 95 | /// How many member ways are held. |
| 96 | pub fn len(&self) -> usize { |
| 97 | self.entries.len() |
| 98 | } |
| 99 | |
| 100 | pub fn is_empty(&self) -> bool { |
| 101 | self.entries.is_empty() |
| 102 | } |
| 103 | |
| 104 | #[cfg(test)] |
| 105 | pub fn from_map(map: HashMap<i64, Vec<i64>>) -> MemberWays { |
| 106 | MemberWays::build(map.into_iter().collect()) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | #[cfg(test)] |
| 111 | mod member_ways_tests { |
| 112 | use super::*; |
| 113 | |
| 114 | /// The whole contract: lookups answer like the map, whatever order the pairs arrived in, and |
| 115 | /// a duplicated id keeps its first occurrence. |
| 116 | #[test] |
| 117 | fn lookups_match_the_map_regardless_of_input_order() { |
| 118 | let table = MemberWays::build(vec![ |
| 119 | (9, vec![10_000, 9_999]), |
| 120 | (1, vec![7, 8]), |
| 121 | (9, vec![1, 2, 3]), |
| 122 | (5, vec![]), |
| 123 | ]); |
| 124 | assert_eq!(table.len(), 3, "the duplicate id is absorbed"); |
| 125 | assert_eq!(table.get(1), Some(&vec![7, 8])); |
| 126 | assert_eq!(table.get(5), Some(&vec![]), "an empty ref list is still a member"); |
| 127 | assert_eq!(table.get(9), Some(&vec![10_000, 9_999]), "first occurrence wins"); |
| 128 | assert_eq!(table.get(2), None, "not a member at all"); |
| 129 | assert_eq!(table.get(-1), None, "negative ids never resolve"); |
| 130 | assert_eq!(table.get(i64::MAX), None, "past the end"); |
| 131 | // `values` covers every entry exactly once, for the ref collectors. |
| 132 | let mut seen: Vec<i64> = table.values().flatten().copied().collect(); |
| 133 | seen.sort_unstable(); |
| 134 | assert_eq!(seen, vec![7, 8, 9_999, 10_000]); |
| 135 | assert!(MemberWays::empty().is_empty(), "empty is empty"); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /// Pass 3: id index plus resolved coordinates, with `places`/`poi` label nodes classified and |
| 140 | /// spilled in the same pass. Grew the sink, select and layers params when pass 4 was folded in. |
| 141 | /// |
| 142 | /// `region` filters `poi` label NODES to the bbox. `places` nodes are always |
| 143 | /// kept. Ways and relations are filtered later at materialise time, where the |
| 144 | /// resolved coordinates are in hand. |
| 145 | #[allow(clippy::too_many_arguments)] |
| 146 | fn build_resolved_table( |
| 147 | input: &Path, |
| 148 | blobs: &[pbf::BlobLoc], |
| 149 | blob_kinds: &[u8], |
| 150 | members: &MemberWays, |
| 151 | needed: NeededBits, |
| 152 | select: &Select, |
| 153 | layers: Layers, |
| 154 | region: Option<&osm_ingest::bbox::BBox>, |
| 155 | sink: &mut Sink, |
| 156 | stats: &mut Stats, |
| 157 | timer: &mut crate::timing::PhaseTimer, |
| 158 | ) -> Result<NodeLocations> { |
| 159 | // The fused bitset already holds every classified way's refs (set in pass |
| 160 | // 1's drain); member ways join here. No ways-spill re-scan: the refs were |
| 161 | // decoded and in hand where they were set. |
| 162 | let mut needed = needed; |
| 163 | for refs in members.values() { |
| 164 | for &id in refs { |
| 165 | needed.set_growable(id)?; |
| 166 | } |
| 167 | } |
| 168 | // Small extracts take the exact vector; planet-scale takes the bitset the |
| 169 | // words move straight into. The threshold now counts distinct ids (the old |
| 170 | // one counted duplicates), which only moves borderline extracts toward the |
| 171 | // vector path — whose input arrives sorted-unique, so its sort is trivial. |
| 172 | let table = if needed.len() <= REFS_IN_MEMORY { |
| 173 | let ids: Vec<i64> = needed.ids().collect(); |
| 174 | timer.switch("id-index"); |
| 175 | NodeLocations::new(ids)? |
| 176 | } else { |
| 177 | timer.switch("id-index"); |
| 178 | // The bitset's words move into the rank index directly (`from_bitset`), |
| 179 | // not through `ids()`: walking them out as ids and re-setting them |
| 180 | // would hold two ~1.5 GB words arrays at once. |
| 181 | let (words, count) = needed.into_words(); |
| 182 | NodeLocations::from_bitset(words, count)? |
| 183 | }; |
| 184 | timer.switch("coords-resolve"); |
| 185 | stats.nodes_needed = table.len() as u64; |
| 186 | // The node region is the bulk of a planet PBF, so it is inflated once: the coordinate resolve |
| 187 | // and the label-node classification share this pass. `classify` runs in the block visitor across |
| 188 | // the pool and is pure -- it is exactly what the old pass 4 body did per node -- and the labels |
| 189 | // it returns are drained to the sink **in chunk order**, ahead of every way and relation, which |
| 190 | // is the order pass 4 spilled them in and what keeps the archive byte-identical. |
| 191 | // |
| 192 | // Only label layers are consulted: a node is never a road, a lake or a building, so running the |
| 193 | // full schema over 2 B nodes would pay the tag scan for nothing. |
| 194 | // |
| 195 | // The region filter drops `poi` label nodes outside the bbox here. `places` |
| 196 | // nodes are always kept — a region build still names its countries. A `poi` |
| 197 | // node carries its own coordinates, so no location table is needed. |
| 198 | let classify = |node: &NodeView| { |
| 199 | if !select.matches(|k| node.tags.get_str(k)) { |
| 200 | return None; |
| 201 | } |
| 202 | // A node no label claimed may still be road furniture. Safety is asked only here, in the |
| 203 | // node pass, so a way or relation can never land in the point-only `safety` layer. |
| 204 | let class = schema::classify(&node.tags, false, layers) |
| 205 | .filter(|c| is_label(c.layer)) |
| 206 | .or_else(|| schema::safety::classify(&node.tags))?; |
| 207 | let safety = class.layer == tilecodec::mamaps::dict::LAYER_SAFETY; |
| 208 | if (safety || class.layer == tilecodec::mamaps::dict::LAYER_POI) |
| 209 | && !osm_ingest::bbox::keep_e7(region, node.lat_e7, node.lon_e7) |
| 210 | { |
| 211 | return None; |
| 212 | } |
| 213 | let name = schema::display_name(&node.tags, class.layer); |
| 214 | Some(( |
| 215 | class, |
| 216 | node.lon_e7 as f64 * 1e-7, |
| 217 | node.lat_e7 as f64 * 1e-7, |
| 218 | name, |
| 219 | if safety { tilecodec::mamaps::body::ID_NONE } else { tagged_id(node.id, ELEMENT_NODE) }, |
| 220 | )) |
| 221 | }; |
| 222 | let drain = |hits: Vec<(Class, f64, f64, Option<String>, u64)>| -> Result<()> { |
| 223 | for (class, lon, lat, name, id) in hits { |
| 224 | let encoded = |
| 225 | crate::store::EncodedGeom::live(&Geometry::Points(vec![(lon, lat)]))?; |
| 226 | sink.push_named(&class, &encoded, name.as_deref(), id)?; |
| 227 | stats.features += 1; |
| 228 | stats.nodes_classified += 1; |
| 229 | } |
| 230 | Ok(()) |
| 231 | }; |
| 232 | let table = resolve_nodes_with(input, &blobs, &blob_kinds, "Pass 3: nodes", table, classify, drain)?; |
| 233 | |
| 234 | Ok(table) |
| 235 | } |
| 236 | |
| 237 | /// Open the ways spill for sequential reading, from whichever backend the budget gate chose: |
| 238 | /// the shared anonymous store when present, else the file at `ways_path`. One helper so the four |
| 239 | /// readers (two ref collectors, lanefill scan, materialise) share one backend. |
| 240 | fn open_ways_reader( |
| 241 | ways_path: &Path, |
| 242 | ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>, |
| 243 | ) -> Result<WayReader> { |
| 244 | WayReader::open_either(ways_path, ways_anon) |
| 245 | } |
| 246 | |
| 247 | /// One named, non-link road way held for parallel coordinate resolve. |
| 248 | /// |
| 249 | /// Owns its refs and name: the spill cursor cannot be re-read, so a batch row carries |
| 250 | /// everything the serial push needs after the parallel phase hands the geometry back. |
| 251 | struct LaneRow { |
| 252 | id: i64, |
| 253 | /// The class flags: the link test already passed, but the one-way bit rides here for |
| 254 | /// the segment the push builds. |
| 255 | flags: u8, |
| 256 | name: String, |
| 257 | lanes: u8, |
| 258 | refs: Vec<i64>, |
| 259 | } |
| 260 | |
| 261 | /// The region bbox expanded for the lane join, in degrees. |
| 262 | /// |
| 263 | /// A recipient is at most 50 m long (`lanefill::MAX_STUB_M`, enforced again in `push`), |
| 264 | /// and a donor must share an endpoint node with it — so the shared node sits within ~50 m |
| 265 | /// of the recipient, and any donor that can pair with a kept recipient touches the bbox |
| 266 | /// expanded by a small margin. 0.1° (~11 km) is two orders of magnitude past the ~100 m |
| 267 | /// worst case (a 50 m recipient straddling the border sharing its far endpoint), so the |
| 268 | /// fringe keeps every pair materialise can consult while dropping the rest of the planet. |
| 269 | /// `None` (world) disables the filter: every way can pair, everything resolves. |
| 270 | fn expanded_fringe(region: &osm_ingest::bbox::BBox) -> osm_ingest::bbox::BBox { |
| 271 | const MARGIN_DEG: f64 = 0.1; |
| 272 | osm_ingest::bbox::BBox { |
| 273 | min_lon: (region.min_lon - MARGIN_DEG).max(-180.0), |
| 274 | min_lat: (region.min_lat - MARGIN_DEG).max(-90.0), |
| 275 | max_lon: (region.max_lon + MARGIN_DEG).min(180.0), |
| 276 | max_lat: (region.max_lat + MARGIN_DEG).min(90.0), |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | /// Whether the resolved line touches the fringe box. `None` (world) is always true. |
| 281 | fn fringe_touches( |
| 282 | fringe: Option<&osm_ingest::bbox::BBox>, |
| 283 | line: &[(f64, f64)], |
| 284 | ) -> bool { |
| 285 | let Some(fringe) = fringe else { |
| 286 | return true; |
| 287 | }; |
| 288 | line.iter().any(|&(lon, lat)| fringe.contains(lon, lat)) |
| 289 | } |
| 290 | |
| 291 | #[cfg(test)] |
| 292 | mod fringe_tests { |
| 293 | use super::*; |
| 294 | |
| 295 | fn california() -> osm_ingest::bbox::BBox { |
| 296 | osm_ingest::bbox::BBox { |
| 297 | min_lon: -124.5, |
| 298 | min_lat: 32.5, |
| 299 | max_lon: -114.0, |
| 300 | max_lat: 42.0, |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn the_fringe_is_the_bbox_expanded_a_hair_in_every_direction() { |
| 306 | let fringe = expanded_fringe(&california()); |
| 307 | assert!((fringe.min_lon - (-124.6)).abs() < 1e-9); |
| 308 | assert!((fringe.min_lat - 32.4).abs() < 1e-9); |
| 309 | assert!((fringe.max_lon - (-113.9)).abs() < 1e-9); |
| 310 | assert!((fringe.max_lat - 42.1).abs() < 1e-9); |
| 311 | } |
| 312 | |
| 313 | #[test] |
| 314 | fn the_fringe_clamps_at_the_world_edges() { |
| 315 | let world = osm_ingest::bbox::BBox { |
| 316 | min_lon: -180.0, |
| 317 | min_lat: -90.0, |
| 318 | max_lon: 180.0, |
| 319 | max_lat: 90.0, |
| 320 | }; |
| 321 | assert_eq!(expanded_fringe(&world), world, "clamped, not wrapped"); |
| 322 | } |
| 323 | |
| 324 | #[test] |
| 325 | fn world_keeps_everything_and_the_fringe_keeps_only_what_touches() { |
| 326 | let fringe = expanded_fringe(&california()); |
| 327 | let inside = vec![(-122.4, 37.8)]; |
| 328 | let straddling = vec![(-124.55, 39.0)]; |
| 329 | let far = vec![(-100.0, 40.0)]; |
| 330 | assert!(fringe_touches(None, &far), "world disables the filter"); |
| 331 | assert!(fringe_touches(Some(&fringe), &inside)); |
| 332 | assert!( |
| 333 | fringe_touches(Some(&fringe), &straddling), |
| 334 | "a border-straddling recipient is within the margin", |
| 335 | ); |
| 336 | assert!(!fringe_touches(Some(&fringe), &far), "Nevada never pairs with California"); |
| 337 | assert!( |
| 338 | !fringe_touches(Some(&fringe), &[]), |
| 339 | "a way with no resolved geometry joins nothing", |
| 340 | ); |
| 341 | } |
| 342 | |
| 343 | /// The soundness case: a ≤50 m recipient straddling the border and its donor's |
| 344 | /// endpoint at their shared node — both within the margin, so the pair survives. |
| 345 | #[test] |
| 346 | fn a_border_pair_survives_the_fringe() { |
| 347 | let fringe = expanded_fringe(&california()); |
| 348 | // Recipient crossing the western edge; shared node 20 m outside. |
| 349 | let recipient = vec![(-124.52, 39.0), (-124.4999, 39.0)]; |
| 350 | // Donor running outward from the shared node. |
| 351 | let donor = vec![(-124.52, 39.0), (-124.53, 39.001)]; |
| 352 | assert!(fringe_touches(Some(&fringe), &recipient)); |
| 353 | assert!(fringe_touches(Some(&fringe), &donor)); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | /// Lane inheritance over the ways spill. Moved whole from `extract`. |
| 358 | /// |
| 359 | /// The scan is batched: the expensive per-way work (coordinate lookup through the node |
| 360 | /// table — a rank-bitset search plus a mapped-file read per node) runs on the pool, while |
| 361 | /// the collector push stays serial in spill order. `table.line` is shared-read-only (the |
| 362 | /// materialise pass already calls it from `par_iter`), and the collector's output order |
| 363 | /// never reaches the archive — `finish` sorts every partition — so the bytes are identical. |
| 364 | /// What this buys: the scan is ~1.1 B sequential ways on a planet input, each paying ~10 |
| 365 | /// node lookups; serially that is tens of minutes of mapped-file random reads. |
| 366 | /// |
| 367 | /// `region` limits the join to the ways that can pair with a materialised way (see |
| 368 | /// [`fringe_touches`]): on a `--region` build over a larger input, the ways outside the |
| 369 | /// fringe can never share an endpoint node with a kept recipient, so resolving them would |
| 370 | /// be pure waste. `None` (world) disables the filter entirely. |
| 371 | fn inherit_lane_counts( |
| 372 | spill_path: &Path, |
| 373 | ways_path: &Path, |
| 374 | ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>, |
| 375 | table: &NodeLocations, |
| 376 | ways_classified: usize, |
| 377 | region: Option<&osm_ingest::bbox::BBox>, |
| 378 | ) -> Result<Vec<(i64, u8)>> { |
| 379 | // --- lane inheritance ------------------------------------------------------------------- |
| 380 | // |
| 381 | // A junction stub OSM left untagged takes a lane count from the road it interrupts, instead of |
| 382 | // the renderer's flat `oneway ? 1 : 2`. See [`crate::lanefill`] for the conditions and the |
| 383 | // measurements behind each of them. It runs here rather than in pass 1 because the conditions |
| 384 | // are geometric — a length and a turn angle — and coordinates are only resolved above. |
| 385 | let fringe = region.map(expanded_fringe); |
| 386 | let inherited_lanes = { |
| 387 | let mut collector = crate::lanefill::Collector::create(spill_path)?; |
| 388 | let mut reader = open_ways_reader(ways_path, &ways_anon)?; |
| 389 | let mut refs: Vec<i64> = Vec::new(); |
| 390 | let mut bar = Progress::new( |
| 391 | "Lane inheritance: scan".to_string(), |
| 392 | ways_classified, |
| 393 | "way(s)", |
| 394 | true, |
| 395 | ); |
| 396 | // One batch of spill rows at a time: 64 Ki ways at ~10 nodes each is a few tens of |
| 397 | // MB of geometry in flight, the same budget the materialise pass uses. |
| 398 | const LANE_BATCH: usize = 64 * 1024; |
| 399 | let mut batch: Vec<LaneRow> = Vec::with_capacity(LANE_BATCH); |
| 400 | let mut lines: Vec<Vec<(f64, f64)>> = Vec::with_capacity(LANE_BATCH); |
| 401 | let mut exhausted = false; |
| 402 | loop { |
| 403 | batch.clear(); |
| 404 | // Serial fill: the spill is a sequential varint stream — one cursor, no seeking. |
| 405 | // The bar ticks here, per way read, so it still spans the whole spill exactly as |
| 406 | // before — the batching below must not move the tick or the count drifts. |
| 407 | while batch.len() < LANE_BATCH { |
| 408 | let Some((id, class, name, lane_count, _, _, _, _)) = reader.next(&mut refs)? |
| 409 | else { |
| 410 | exhausted = true; |
| 411 | break; |
| 412 | }; |
| 413 | bar.tick("way(s)"); |
| 414 | // Roads, and not slip roads. A ramp leaves a junction carrying its parent's name on |
| 415 | // very nearly its parent's heading, so it would inherit the mainline's width onto a |
| 416 | // single-lane ramp; `corridor` leaves links out of a corridor for the same reason. |
| 417 | if class.layer != tilecodec::mamaps::dict::LAYER_ROADS |
| 418 | || class.flags & tilecodec::mamaps::body::FLAG_IS_LINK != 0 |
| 419 | { |
| 420 | continue; |
| 421 | } |
| 422 | let Some(name) = name else { continue }; |
| 423 | batch.push(LaneRow { |
| 424 | id, |
| 425 | flags: class.flags, |
| 426 | name, |
| 427 | lanes: lane_count, |
| 428 | refs: std::mem::take(&mut refs), |
| 429 | }); |
| 430 | } |
| 431 | if batch.is_empty() { |
| 432 | debug_assert!(exhausted, "an empty batch means the spill is done"); |
| 433 | break; |
| 434 | } |
| 435 | // Parallel resolve: the dominant cost, shared-read-only. |
| 436 | lines.clear(); |
| 437 | par::install(|| { |
| 438 | batch |
| 439 | .par_iter() |
| 440 | .map(|row| table.line(&row.refs)) |
| 441 | .collect_into_vec(&mut lines) |
| 442 | }); |
| 443 | // Serial push, in spill order: the collector's file order never reaches the |
| 444 | // archive (`finish` sorts), but keeping it ordered keeps the temp bytes — and |
| 445 | // any future debugging of them — deterministic. |
| 446 | for (row, line) in batch.iter().zip(lines.drain(..)) { |
| 447 | // A region build only joins the fringe: a recipient is at most 50 m long, so |
| 448 | // a donor sharing an endpoint node with a kept recipient always touches the |
| 449 | // expanded box (see `expanded_fringe`). Anything else can pair only with |
| 450 | // ways materialise drops — work with no reader. |
| 451 | if !fringe_touches(fringe.as_ref(), &line) { |
| 452 | continue; |
| 453 | } |
| 454 | let oneway = |
| 455 | row.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0; |
| 456 | collector.push(&crate::lanefill::Segment { |
| 457 | id: row.id, |
| 458 | name: &row.name, |
| 459 | lanes: row.lanes, |
| 460 | oneway, |
| 461 | nodes: &row.refs, |
| 462 | line: &line, |
| 463 | })?; |
| 464 | } |
| 465 | if exhausted { |
| 466 | break; |
| 467 | } |
| 468 | } |
| 469 | bar.finish("way(s)"); |
| 470 | collector.finish()? |
| 471 | }; |
| 472 | |
| 473 | Ok(inherited_lanes) |
| 474 | } |
| 475 | |
| 476 | /// One materialised way, decided on the pool: the serial drain only appends. |
| 477 | /// |
| 478 | /// `Failed` (no geometry) counts `geometry_failed`; `Dropped` (region-filtered) |
| 479 | /// counts nothing — exactly the two non-pushed paths the inline drain had. |
| 480 | /// `Kept` carries the spill record's geometry bytes plus the facts the spill |
| 481 | /// derives, so the drain does no vertex walk. |
| 482 | enum BuiltWay { |
| 483 | Failed, |
| 484 | Dropped, |
| 485 | Kept(crate::store::EncodedGeom), |
| 486 | } |
| 487 | |
| 488 | /// Resolve one batch item's fate: geometry, region keep/drop, spill encoding. |
| 489 | /// |
| 490 | /// Pure over shared tables (`table`, `region`): safe across the pool. The |
| 491 | /// region test runs here rather than in the drain — it walks every vertex |
| 492 | /// (`geometry_touches`), and the drain must not. Order-independent: one slot |
| 493 | /// per batch item, drained positionally. |
| 494 | fn build_way( |
| 495 | class: &Class, |
| 496 | geometry: Option<Geometry>, |
| 497 | region: Option<&osm_ingest::bbox::BBox>, |
| 498 | ) -> Result<BuiltWay> { |
| 499 | let Some(geometry) = geometry else { |
| 500 | return Ok(BuiltWay::Failed); |
| 501 | }; |
| 502 | // Region filter: roads, pois and buildings outside the bbox are dropped. |
| 503 | // The geometry is resolved by now, so this is a direct touches-box test |
| 504 | // on the line the way produced (a centroided point for labels). |
| 505 | if is_region_filtered(class.layer) && !geometry_touches(&geometry, region) { |
| 506 | return Ok(BuiltWay::Dropped); |
| 507 | } |
| 508 | Ok(BuiltWay::Kept(crate::store::EncodedGeom::live(&geometry)?)) |
| 509 | } |
| 510 | |
| 511 | /// Materialise classified ways off disk, in id order. Moved whole from `extract`. |
| 512 | /// |
| 513 | /// `region` filters the built layers (`roads`, `poi`, `buildings`): a way in |
| 514 | /// one of those layers whose resolved line touches no bbox point is dropped. |
| 515 | /// Every other layer is always kept. Kept whole, never clipped — the tiler |
| 516 | /// clips per tile later. |
| 517 | fn materialise_ways( |
| 518 | ways_path: &Path, |
| 519 | ways_anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>, |
| 520 | promoted: &[(i64, u8)], |
| 521 | inherited_lanes: &[(i64, u8)], |
| 522 | table: &NodeLocations, |
| 523 | region: Option<&osm_ingest::bbox::BBox>, |
| 524 | sink: &mut Sink, |
| 525 | stats: &mut Stats, |
| 526 | ) -> Result<()> { |
| 527 | let mut reader = open_ways_reader(ways_path, ways_anon)?; |
| 528 | let mut refs: Vec<i64> = Vec::new(); |
| 529 | // Silent until now, and it is not a short step: on a north-america extract this loop ran 623 |
| 530 | // seconds on one thread with nothing on stdout, which is indistinguishable from a hang. |
| 531 | let mut bar = Progress::new( |
| 532 | "Materialise: ways".to_string(), |
| 533 | stats.ways_classified as usize, |
| 534 | "way(s)", |
| 535 | true, |
| 536 | ); |
| 537 | // Batched, because the expensive part of a way is embarrassingly parallel and the cheap part |
| 538 | // cannot be. `table.line` is a coordinate lookup per node -- an id search plus a random read of a |
| 539 | // mapped file -- and `way_geometry` closes and winds rings; neither touches shared mutable state, |
| 540 | // so a batch of them goes as wide as the pool. The sink then takes the results **in order**, |
| 541 | // which is what keeps the archive byte-identical: the spill's feature order is the archive's. |
| 542 | // |
| 543 | // 64 Ki ways at ~10 nodes each is a few tens of MB of geometry in flight, against a build that |
| 544 | // peaks near 7 GB. |
| 545 | const MATERIALISE_BATCH: usize = 64 * 1024; |
| 546 | #[allow(clippy::type_complexity)] |
| 547 | let mut batch: Vec<( |
| 548 | Class, |
| 549 | Option<String>, |
| 550 | Vec<i64>, |
| 551 | u64, |
| 552 | u8, |
| 553 | Vec<u16>, |
| 554 | Vec<u16>, |
| 555 | Carriageway, |
| 556 | Option<BuildingAttrs>, |
| 557 | )> = Vec::with_capacity(MATERIALISE_BATCH); |
| 558 | let mut built: Vec<Result<BuiltWay>> = Vec::with_capacity(MATERIALISE_BATCH); |
| 559 | // TEMP-PROFILE: split the batch loop into fill / resolve / drain walls. |
| 560 | // Removed once the split is measured (naonly run). |
| 561 | let mut t_fill = std::time::Duration::ZERO; |
| 562 | let mut t_resolve = std::time::Duration::ZERO; |
| 563 | let mut t_push = std::time::Duration::ZERO; |
| 564 | let mut t_rest = std::time::Duration::ZERO; |
| 565 | let mut t0 = std::time::Instant::now(); |
| 566 | loop { |
| 567 | let more = reader.next(&mut refs)?; |
| 568 | // Moved out of `more` by value below, so named ways cost no `String` clone and |
| 569 | // turn-mask vectors move rather than copy: over ~1 B ways the allocator traffic |
| 570 | // of cloning is minutes, and the batch owns every field anyway. |
| 571 | let done = more.is_none(); |
| 572 | if let Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)) = |
| 573 | more |
| 574 | { |
| 575 | let mut class = class; |
| 576 | // The corridor's zoom, where it is shallower than this way's own. Corridors |
| 577 | // are built from numbered roads alone, so a non-road way can never have an |
| 578 | // entry — searching for one is ~17 wasted compares per boundary, building |
| 579 | // and waterway on a region build. |
| 580 | if class.layer == tilecodec::mamaps::dict::LAYER_ROADS { |
| 581 | if let Ok(at) = promoted.binary_search_by_key(&id, |(id, _)| *id) { |
| 582 | class.min_zoom = promoted[at].1; |
| 583 | } |
| 584 | } |
| 585 | // A neighbour's lane count, where OSM tagged none on this way. Only ever consulted |
| 586 | // for a way that has none of its own, so a tag is never overridden. |
| 587 | let lane_count = if lane_count == 0 { |
| 588 | inherited_lanes |
| 589 | .binary_search_by_key(&id, |(id, _)| *id) |
| 590 | .map_or(0, |at| inherited_lanes[at].1) |
| 591 | } else { |
| 592 | lane_count |
| 593 | }; |
| 594 | // Only a label way carries its id onward. A road or a building is merged with its |
| 595 | // neighbours by `coalesce`, which leaves the survivor's id arbitrary, and the id |
| 596 | // table exists for `poi` and `places` alone. |
| 597 | let id = if is_label(class.layer) { |
| 598 | tagged_id(id, ELEMENT_WAY) |
| 599 | } else { |
| 600 | tilecodec::mamaps::body::ID_NONE |
| 601 | }; |
| 602 | batch.push(( |
| 603 | class, |
| 604 | name, |
| 605 | std::mem::take(&mut refs), |
| 606 | id, |
| 607 | lane_count, |
| 608 | turn_fwd, |
| 609 | turn_bwd, |
| 610 | carriageway, |
| 611 | building, |
| 612 | )); |
| 613 | } |
| 614 | // Flushed when full, and once more at the end with whatever is left. |
| 615 | if batch.len() >= MATERIALISE_BATCH || (done && !batch.is_empty()) { |
| 616 | t_fill += t0.elapsed(); |
| 617 | let t1 = std::time::Instant::now(); |
| 618 | built.clear(); |
| 619 | par::install(|| { |
| 620 | batch |
| 621 | .par_iter() |
| 622 | .map(|(class, _, refs, _, _, _, _, _, _)| { |
| 623 | let line = table.line(refs); |
| 624 | // A label layer's ways are centroided to points: a town mapped as an area |
| 625 | // is still one label, not a loop. Everything else keeps its geometry. |
| 626 | let geometry = if is_label(class.layer) { |
| 627 | centroid(&line).map(|point| Geometry::Points(vec![point])) |
| 628 | } else { |
| 629 | way_geometry(&line, class.area) |
| 630 | }; |
| 631 | build_way(class, geometry, region) |
| 632 | }) |
| 633 | .collect_into_vec(&mut built); |
| 634 | }); |
| 635 | t_resolve += t1.elapsed(); |
| 636 | let t2 = std::time::Instant::now(); |
| 637 | let push_before = t_push; |
| 638 | for ( |
| 639 | (class, name, _, id, lane_count, turn_fwd, turn_bwd, carriageway, building), |
| 640 | built, |
| 641 | ) in batch.iter().zip(built.drain(..)) |
| 642 | { |
| 643 | // `?` in spill order: the first encode failure in feature order, |
| 644 | // exactly as inline encoding would report it. |
| 645 | let tp0 = std::time::Instant::now(); |
| 646 | match built? { |
| 647 | BuiltWay::Failed => stats.geometry_failed += 1, |
| 648 | BuiltWay::Dropped => {} |
| 649 | BuiltWay::Kept(encoded) => { |
| 650 | // A building carries its S3DB attributes; a road with lane data carries |
| 651 | // those; everything else — and a plain road — goes the plain, named way. |
| 652 | if let Some(b) = building { |
| 653 | sink.push_building(class, &encoded, name.as_deref(), *b)?; |
| 654 | } else if *lane_count > 0 |
| 655 | || !turn_fwd.is_empty() |
| 656 | || !turn_bwd.is_empty() |
| 657 | || !carriageway.is_empty() |
| 658 | { |
| 659 | sink.push_road( |
| 660 | class, |
| 661 | &encoded, |
| 662 | name.as_deref(), |
| 663 | *lane_count, |
| 664 | turn_fwd, |
| 665 | turn_bwd, |
| 666 | *carriageway, |
| 667 | )?; |
| 668 | } else { |
| 669 | sink.push_named(class, &encoded, name.as_deref(), *id)?; |
| 670 | } |
| 671 | stats.features += 1; |
| 672 | } |
| 673 | } |
| 674 | t_push += tp0.elapsed(); |
| 675 | bar.tick("way(s)"); |
| 676 | } |
| 677 | batch.clear(); |
| 678 | // Drain wall minus the sink pushes: match + stats + tick + drops. |
| 679 | t_rest += t2.elapsed() - (t_push - push_before); |
| 680 | t0 = std::time::Instant::now(); |
| 681 | } |
| 682 | if done { |
| 683 | break; |
| 684 | } |
| 685 | } |
| 686 | eprintln!( |
| 687 | " [profile] materialise-ways fill={:.1}s resolve={:.1}s push={:.1}s rest={:.1}s spill={:.2}GB", |
| 688 | t_fill.as_secs_f64(), |
| 689 | t_resolve.as_secs_f64(), |
| 690 | t_push.as_secs_f64(), |
| 691 | t_rest.as_secs_f64(), |
| 692 | sink.staged_bytes() as f64 / 1e9 |
| 693 | ); |
| 694 | bar.finish("way(s)"); |
| 695 | // Nothing reads the ways spill after this: the relations below reach their members through |
| 696 | // `members`, which is why that table is kept at all. The file backend's `.tmp` is removed; |
| 697 | // the anon backend's segments unmap with the last `Arc`. |
| 698 | drop(reader); |
| 699 | let _ = std::fs::remove_file(&ways_path); |
| 700 | |
| 701 | Ok(()) |
| 702 | } |