Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / junction_part1.rs
junction_part1.rs565 lines · 26.2 KiBRaw
| 1 | /// Bucket a signed turn angle (degrees, positive clockwise/right) into a [`Turn`]. |
| 2 | /// |
| 3 | /// The thresholds are OSM's own reading of the `turn` vocabulary: `slight` up to 45°, the plain |
| 4 | /// direction out to 135°, `sharp` beyond that, and a reversal past 170°. |
| 5 | fn classify_turn(delta_degrees: f64) -> Turn { |
| 6 | let magnitude = delta_degrees.abs(); |
| 7 | let right = delta_degrees > 0.0; |
| 8 | if magnitude <= 20.0 { |
| 9 | Turn::Through |
| 10 | } else if magnitude > 170.0 { |
| 11 | Turn::Reverse |
| 12 | } else if magnitude <= 45.0 { |
| 13 | if right { |
| 14 | Turn::SlightRight |
| 15 | } else { |
| 16 | Turn::SlightLeft |
| 17 | } |
| 18 | } else if magnitude <= 135.0 { |
| 19 | if right { |
| 20 | Turn::Right |
| 21 | } else { |
| 22 | Turn::Left |
| 23 | } |
| 24 | } else if right { |
| 25 | Turn::SharpRight |
| 26 | } else { |
| 27 | Turn::SharpLeft |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /// Wrap an angle difference into `(-180, 180]`, so a turn's sign is its direction. |
| 32 | fn normalise_degrees(mut d: f64) -> f64 { |
| 33 | while d > 180.0 { |
| 34 | d -= 360.0; |
| 35 | } |
| 36 | while d <= -180.0 { |
| 37 | d += 360.0; |
| 38 | } |
| 39 | d |
| 40 | } |
| 41 | |
| 42 | // --- local geometry ------------------------------------------------------------------------- |
| 43 | |
| 44 | /// Bearing from `a` to `b` in degrees clockwise from north, on the local tangent plane. |
| 45 | /// |
| 46 | /// The `e7` units cancel in the ratio; only the `cos(lat)` correction on the east component |
| 47 | /// matters, and without it every heading north of the tropics comes out rotated. |
| 48 | fn bearing_degrees(a: (i32, i32), b: (i32, i32)) -> f64 { |
| 49 | let mid_lat = (f64::from(a.0) + f64::from(b.0)) * 0.5 * 1e-7; |
| 50 | let north = f64::from(b.0) - f64::from(a.0); |
| 51 | let east = (f64::from(b.1) - f64::from(a.1)) * mid_lat.to_radians().cos(); |
| 52 | east.atan2(north).to_degrees() |
| 53 | } |
| 54 | |
| 55 | /// Ground distance between two `e7` points, in metres. |
| 56 | fn distance_m(a: (i32, i32), b: (i32, i32)) -> f64 { |
| 57 | let mid_lat = (f64::from(a.0) + f64::from(b.0)) * 0.5 * 1e-7; |
| 58 | let north = (f64::from(b.0) - f64::from(a.0)) * 1e-7 * METRES_PER_DEGREE; |
| 59 | let east = |
| 60 | (f64::from(b.1) - f64::from(a.1)) * 1e-7 * METRES_PER_DEGREE * mid_lat.to_radians().cos(); |
| 61 | (north * north + east * east).sqrt() |
| 62 | } |
| 63 | |
| 64 | /// The length of a polyline, in metres. |
| 65 | fn polyline_length_m(verts: &[(i32, i32)]) -> f64 { |
| 66 | verts.windows(2).map(|w| distance_m(w[0], w[1])).sum() |
| 67 | } |
| 68 | |
| 69 | /// A point offset from `origin` by `(east, north)` metres, as `(lon, lat)` degrees. |
| 70 | fn offset_degrees(origin: (i32, i32), east_m: f64, north_m: f64) -> (f64, f64) { |
| 71 | let lat = f64::from(origin.0) * 1e-7; |
| 72 | let lon = f64::from(origin.1) * 1e-7; |
| 73 | let d_lat = north_m / METRES_PER_DEGREE; |
| 74 | // At the poles this divisor collapses; the Mercator clamp means no tile is drawn there anyway, |
| 75 | // and a floor keeps a degenerate coordinate from becoming an infinity in the output. |
| 76 | let d_lon = east_m / (METRES_PER_DEGREE * lat.to_radians().cos().abs().max(1e-6)); |
| 77 | (lon + d_lon, lat + d_lat) |
| 78 | } |
| 79 | |
| 80 | /// The unit vector pointing along `heading` (degrees clockwise from north), as `(east, north)`. |
| 81 | fn forward(heading_degrees: f64) -> (f64, f64) { |
| 82 | let r = heading_degrees.to_radians(); |
| 83 | (r.sin(), r.cos()) |
| 84 | } |
| 85 | |
| 86 | /// The unit vector 90° clockwise of `heading` — "right of the direction of travel". |
| 87 | fn rightward(heading_degrees: f64) -> (f64, f64) { |
| 88 | let r = heading_degrees.to_radians(); |
| 89 | (r.cos(), -r.sin()) |
| 90 | } |
| 91 | |
| 92 | // --- the graph, one junction at a time -------------------------------------------------------- |
| 93 | |
| 94 | /// Is this road class one a car drives on? The same `1..=9` (motorway..living_street) the traffic |
| 95 | /// layer uses, masked so the reverse-geometry flag cannot trip the range test. |
| 96 | fn is_drivable(type_: u8) -> bool { |
| 97 | (1..=9).contains(&(type_ & ROAD_TYPE_MASK)) |
| 98 | } |
| 99 | |
| 100 | /// Incoming drivable edges per node, as a CSR built in one pass over the graph. |
| 101 | /// |
| 102 | /// `nodes.bin` is out-edges only and there is no reverse index on disk, so this is the whole reason |
| 103 | /// approaches can be found at all. [`Graph::has_drivable_twin`] is the existing primitive and would |
| 104 | /// do for a two-way street, but it can only find an approach from a node the junction also has an |
| 105 | /// out-edge *to* — which misses every one-way approach, and a one-way approach is exactly the |
| 106 | /// motorway slip road this layer is meant to get right. |
| 107 | /// |
| 108 | /// Costs `4 * (node_count + 1)` bytes plus 4 per drivable edge, and stores only the edge index: an |
| 109 | /// in-edge's source node is recovered by [`source_of`], which is a binary search over the same |
| 110 | /// `edge_ptr` array rather than another 4 bytes an edge. |
| 111 | struct InEdges { |
| 112 | start: Vec<u32>, |
| 113 | edges: Vec<u32>, |
| 114 | } |
| 115 | |
| 116 | impl InEdges { |
| 117 | fn build(graph: &Graph) -> Result<InEdges> { |
| 118 | let node_count = graph.node_count; |
| 119 | // Parallel counting sort, not a naive `par_iter`: the serial |
| 120 | // `start[target + 1] += 1` is a cross-iteration hazard, so the count |
| 121 | // goes through one shared atomic slot per target instead — spread |
| 122 | // over `node_count + 1` slots, so the updates are essentially |
| 123 | // uncontended — and the fill through the same slots as cursors. |
| 124 | // |
| 125 | // Memory is the serial shape, not per-shard histograms (shards x |
| 126 | // nodes would be tens of GB at planet scale): one atomic slot per |
| 127 | // node plus the edge table itself, the same peak as the serial |
| 128 | // `start` + `fill` pair this replaces. |
| 129 | // |
| 130 | // Order is the serial order: sources are visited `n` ascending, |
| 131 | // `edge_ptr` ascending, and each node's slice is restored to |
| 132 | // ascending `edge_idx` after the fill, so `incoming.of(n)` holds |
| 133 | // exactly what the serial loop built and downstream pairing is |
| 134 | // unchanged at every thread count. |
| 135 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; |
| 136 | use std::sync::Mutex; |
| 137 | let slots = node_count as usize + 2; |
| 138 | let counts: Vec<AtomicU32> = (0..slots).map(|_| AtomicU32::new(0)).collect(); |
| 139 | // The first corrupt edge met, serialised: a bounds failure and an |
| 140 | // escape-row failure are both fatal, and the message keeps the |
| 141 | // serial wording. Checked between phases, so a corrupt graph never |
| 142 | // fills (or sorts) a partial index. |
| 143 | let first_err: Mutex<Option<osm_ingest::proto::Error>> = Mutex::new(None); |
| 144 | let failed = AtomicBool::new(false); |
| 145 | // Shards partition the *source* nodes: every edge is visited exactly |
| 146 | // once however the ranges fall, so each target's total is exact. |
| 147 | let threads = par::threads().max(1); |
| 148 | let want_tasks = threads.saturating_mul(4).max(1); |
| 149 | let shard_len = ((node_count as usize) / want_tasks).max(1); |
| 150 | let mut shards: Vec<std::ops::Range<u64>> = Vec::new(); |
| 151 | let mut lo = 0u64; |
| 152 | while lo < node_count { |
| 153 | let hi = (lo + shard_len as u64).min(node_count); |
| 154 | shards.push(lo..hi); |
| 155 | lo = hi; |
| 156 | } |
| 157 | // Phase 1: count one slot high, so the prefix sum below leaves |
| 158 | // `start[t]` pointing at node `t`'s first slot. |
| 159 | par::install(|| { |
| 160 | shards.par_iter().for_each(|range| { |
| 161 | for n in range.clone() { |
| 162 | // Another shard already found corruption: stop feeding |
| 163 | // counts nobody will read. Checked per node, not per |
| 164 | // edge, so the fast path pays one relaxed load. |
| 165 | if failed.load(Ordering::Relaxed) { |
| 166 | break; |
| 167 | } |
| 168 | for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) { |
| 169 | if !is_drivable(graph.edge_type(idx)) { |
| 170 | continue; |
| 171 | } |
| 172 | let target = match graph.edge_target(idx, n as u32) { |
| 173 | Ok(t) => t, |
| 174 | Err(e) => { |
| 175 | failed.store(true, Ordering::Relaxed); |
| 176 | let mut guard = first_err |
| 177 | .lock() |
| 178 | .unwrap_or_else(|p| p.into_inner()); |
| 179 | if guard.is_none() { |
| 180 | *guard = Some(e); |
| 181 | } |
| 182 | break; |
| 183 | } |
| 184 | }; |
| 185 | if u64::from(target) >= node_count { |
| 186 | failed.store(true, Ordering::Relaxed); |
| 187 | let mut guard = |
| 188 | first_err.lock().unwrap_or_else(|p| p.into_inner()); |
| 189 | if guard.is_none() { |
| 190 | *guard = Some(osm_ingest::proto::Error(format!( |
| 191 | "edge {idx} targets node {target}, past the {node_count} in the graph" |
| 192 | ))); |
| 193 | } |
| 194 | break; |
| 195 | } |
| 196 | counts[target as usize + 1].fetch_add(1, Ordering::Relaxed); |
| 197 | } |
| 198 | } |
| 199 | }); |
| 200 | }); |
| 201 | if let Some(e) = first_err.lock().unwrap_or_else(|p| p.into_inner()).take() { |
| 202 | return Err(e); |
| 203 | } |
| 204 | // Serial prefix sum, in place: the same array then serves as the |
| 205 | // phase-2 fill cursors with no second allocation. The add comes |
| 206 | // *before* the snapshot — slot i counts edges targeting node i-1, |
| 207 | // so the running total *with* this slot folded in is node i's |
| 208 | // block start (slot 0 targets no node and is always empty, pinning |
| 209 | // start[0] at 0). Snapshotting before the add shifts every block |
| 210 | // one slot down and empties node 0, which is exactly the failure |
| 211 | // mode to watch for here. |
| 212 | let mut total = 0u32; |
| 213 | let mut start = vec![0u32; slots]; |
| 214 | for (i, slot) in counts.iter().enumerate() { |
| 215 | let c = slot.load(Ordering::Relaxed); |
| 216 | total = total.checked_add(c).expect( |
| 217 | "drivable edges fit u32: Graph::load refuses an edge_count past u32::MAX", |
| 218 | ); |
| 219 | slot.store(total, Ordering::Relaxed); |
| 220 | start[i] = total; |
| 221 | } |
| 222 | // Phase 2: disjoint-slice fill. Every slot written is claimed by |
| 223 | // exactly one `fetch_add`, so no two threads share one; phase 1 |
| 224 | // validated every edge, so the defensive skips below are unreachable |
| 225 | // and only guard against filling a corrupt index silently. |
| 226 | // |
| 227 | // `Vec<AtomicU32>` rather than `&mut Vec<u32>`: the table is shared |
| 228 | // across workers, and atomics are `Sync` where a unique borrow is |
| 229 | // not. Same 4 bytes a slot, converted back after the join. |
| 230 | let edges: Vec<AtomicU32> = |
| 231 | std::iter::repeat_with(|| AtomicU32::new(0)).take(total as usize).collect(); |
| 232 | failed.store(false, Ordering::Relaxed); |
| 233 | par::install(|| { |
| 234 | shards.par_iter().for_each(|range| { |
| 235 | for n in range.clone() { |
| 236 | if failed.load(Ordering::Relaxed) { |
| 237 | break; |
| 238 | } |
| 239 | for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) { |
| 240 | if !is_drivable(graph.edge_type(idx)) { |
| 241 | continue; |
| 242 | } |
| 243 | let Ok(target) = graph.edge_target(idx, n as u32) else { |
| 244 | failed.store(true, Ordering::Relaxed); |
| 245 | continue; |
| 246 | }; |
| 247 | if u64::from(target) >= node_count { |
| 248 | failed.store(true, Ordering::Relaxed); |
| 249 | continue; |
| 250 | } |
| 251 | let at = |
| 252 | counts[target as usize].fetch_add(1, Ordering::Relaxed) as usize; |
| 253 | // `at` is in-bounds by construction (cursor < start |
| 254 | // + count); the check keeps a logic bug a panic |
| 255 | // rather than memory unsafety. |
| 256 | if let Some(slot) = edges.get(at) { |
| 257 | slot.store(idx, Ordering::Relaxed); |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | }); |
| 262 | }); |
| 263 | if failed.load(Ordering::Relaxed) { |
| 264 | return err( |
| 265 | "the graph changed between the junction count and fill passes".to_string(), |
| 266 | ); |
| 267 | } |
| 268 | let mut edges: Vec<u32> = |
| 269 | edges.into_iter().map(AtomicU32::into_inner).collect(); |
| 270 | // Restore ascending `edge_idx` within each node: the serial visit |
| 271 | // order, and what `incoming.of(n)` has always held. Slices average a |
| 272 | // couple of edges, so this pass is a linear walk, not a sort cost. |
| 273 | for n in 0..node_count as usize { |
| 274 | let (lo, hi) = (start[n] as usize, start[n + 1] as usize); |
| 275 | edges[lo..hi].sort_unstable(); |
| 276 | } |
| 277 | start.truncate(node_count as usize + 1); |
| 278 | Ok(InEdges { start, edges }) |
| 279 | } |
| 280 | |
| 281 | fn of(&self, n: u64) -> &[u32] { |
| 282 | let lo = self.start[n as usize] as usize; |
| 283 | let hi = self.start[n as usize + 1] as usize; |
| 284 | &self.edges[lo..hi] |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | /// The node edge `idx` leaves from: the last node whose `edge_ptr` is at or below it. |
| 289 | /// |
| 290 | /// `edge_ptr` ascends across `nodes.bin` and the sentinel record holds `edge_count`, so the answer |
| 291 | /// is always in `0..node_count` for a valid edge index. |
| 292 | fn source_of(graph: &Graph, idx: u32) -> u64 { |
| 293 | let (mut lo, mut hi) = (1u64, graph.node_count + 1); |
| 294 | while lo < hi { |
| 295 | let mid = lo + (hi - lo) / 2; |
| 296 | if graph.edge_ptr(mid) > idx { |
| 297 | hi = mid; |
| 298 | } else { |
| 299 | lo = mid + 1; |
| 300 | } |
| 301 | } |
| 302 | lo - 1 |
| 303 | } |
| 304 | |
| 305 | /// An edge's polyline in the order it is travelled, `from -> to`. |
| 306 | /// |
| 307 | /// A reverse-geometry edge stores no shape of its own — its twin running the other way owns it — so |
| 308 | /// the twin's polyline is found and reversed. Without this every curved two-way approach would get |
| 309 | /// its heading from the straight chord instead of the road, which at a bend is a wrong turn angle |
| 310 | /// and therefore a wrong lane pairing. |
| 311 | fn travel_polyline(graph: &Graph, idx: u32, from: u32, to: u32) -> Vec<(i32, i32)> { |
| 312 | if graph.geom_contains(idx) { |
| 313 | return graph.polyline(idx, from, to); |
| 314 | } |
| 315 | for twin in graph.edge_ptr(u64::from(to))..graph.edge_ptr(u64::from(to) + 1) { |
| 316 | if !graph.geom_contains(twin) || !is_drivable(graph.edge_type(twin)) { |
| 317 | continue; |
| 318 | } |
| 319 | if graph.edge_target(twin, to).is_ok_and(|t| t == from) { |
| 320 | let mut verts = graph.polyline(twin, to, from); |
| 321 | verts.reverse(); |
| 322 | return verts; |
| 323 | } |
| 324 | } |
| 325 | // A genuine straight chord: source and target, and nothing between them. |
| 326 | graph.polyline(idx, from, to) |
| 327 | } |
| 328 | |
| 329 | /// One movement into or out of a junction, resolved into everything a connector needs. |
| 330 | struct Arm { |
| 331 | /// The node at the far end. |
| 332 | neighbour: u32, |
| 333 | /// Degrees clockwise from north, always in the direction of travel — so for an approach this is |
| 334 | /// the heading traffic *arrives* on, and for an exit the heading it *departs* on. |
| 335 | heading: f64, |
| 336 | /// The edge's own length in metres, which caps how far the connector may reach along it. |
| 337 | length_m: f64, |
| 338 | /// Whether the road carries traffic the other way too, which decides whether this direction's |
| 339 | /// lanes sit on the centreline or a half-carriageway to one side of it. |
| 340 | two_way: bool, |
| 341 | /// Per-lane `turn:lanes` masks, left→right, when `lanes.bin` has them. `None` is the common |
| 342 | /// case. This is also the arm's only lane-count source — see [`effective_lanes`], which is |
| 343 | /// deliberately the one way to ask, so a count can never be fabricated from something that |
| 344 | /// merely happened to be in scope. |
| 345 | masks: Option<Vec<u16>>, |
| 346 | /// The edge's road class (`graph.edge_type & ROAD_TYPE_MASK`: motorway=1 … |
| 347 | /// tertiary=5, unclassified=6, …). Read off the edge, never inferred, so the |
| 348 | /// arterial gate in `junctions_for_node` is data rather than a second guess. |
| 349 | road_class: u8, |
| 350 | } |
| 351 | |
| 352 | /// Resolve one incident edge, or `None` when it is not usable as an arm of this junction. |
| 353 | fn arm( |
| 354 | graph: &Graph, |
| 355 | lanes: Option<&LaneTable>, |
| 356 | idx: u32, |
| 357 | from: u32, |
| 358 | to: u32, |
| 359 | outgoing: bool, |
| 360 | ) -> Option<Arm> { |
| 361 | let verts = travel_polyline(graph, idx, from, to); |
| 362 | // The heading is the first geometry step leaving the junction, or the last arriving at it. A |
| 363 | // repeated vertex has no direction, so the scan walks past duplicates rather than dividing by |
| 364 | // zero — the graph does contain them at edges that were split at a coincident point. |
| 365 | let node = if outgoing { verts.first().copied()? } else { verts.last().copied()? }; |
| 366 | let (heading, ok) = if outgoing { |
| 367 | match verts.iter().skip(1).find(|v| **v != node) { |
| 368 | Some(next) => (bearing_degrees(node, *next), true), |
| 369 | None => (0.0, false), |
| 370 | } |
| 371 | } else { |
| 372 | match verts.iter().rev().skip(1).find(|v| **v != node) { |
| 373 | Some(prev) => (bearing_degrees(*prev, node), true), |
| 374 | None => (0.0, false), |
| 375 | } |
| 376 | }; |
| 377 | if !ok { |
| 378 | return None; |
| 379 | } |
| 380 | let length_m = polyline_length_m(&verts); |
| 381 | if length_m < MIN_SETBACK_M { |
| 382 | return None; |
| 383 | } |
| 384 | let masks = lanes.and_then(|table| table.masks(idx)).filter(|m| !m.is_empty()); |
| 385 | let two_way = graph.has_drivable_twin(to, from).unwrap_or(false); |
| 386 | let road_class = graph.edge_type(idx) & ROAD_TYPE_MASK; |
| 387 | Some(Arm { neighbour: if outgoing { to } else { from }, heading, length_m, two_way, masks, road_class }) |
| 388 | } |
| 389 | |
| 390 | /// A lane's centre, in metres right of the road's centreline as seen by traffic travelling this |
| 391 | /// arm's direction. |
| 392 | /// |
| 393 | /// Two offsets stacked. A two-way road's centreline runs between the two directions, so the |
| 394 | /// carriageway a driver is on sits a half-carriageway to their own side of it — right in a |
| 395 | /// right-hand-traffic country, left in a left-hand one. Within that carriageway lane `k` of `count` |
| 396 | /// sits at the usual centred spacing, counted left→right in the direction of travel, which is the |
| 397 | /// order `lanes.bin` stores masks in. |
| 398 | /// |
| 399 | /// `width` is the lane width in ground metres at this junction's latitude — see |
| 400 | /// [`lane_width_ground_m`], and the module docs for why it is not simply [`LANE_WIDTH_MERCATOR_M`]. |
| 401 | /// |
| 402 | /// The opposite direction is assumed to have the same lane count, because the graph gives no way to |
| 403 | /// ask. An asymmetric road — three lanes one way and one the other — puts its connectors half a |
| 404 | /// carriageway off. |
| 405 | fn lane_offset_m(k: usize, count: usize, two_way: bool, left_hand: bool, width: f64) -> f64 { |
| 406 | let count = count.max(1); |
| 407 | let side = if left_hand { -1.0 } else { 1.0 }; |
| 408 | let carriageway = if two_way { side * count as f64 * 0.5 * width } else { 0.0 }; |
| 409 | let within = (k as f64 - (count as f64 - 1.0) * 0.5) * width; |
| 410 | carriageway + within |
| 411 | } |
| 412 | |
| 413 | /// How many lanes to spread one arm's connector ends across, in its direction of travel. |
| 414 | /// |
| 415 | /// **A lane count is a property of the arm and of nothing else.** That is why this takes only an |
| 416 | /// [`Arm`] and why it is the single way to ask: both ends of a connector read it, so neither can |
| 417 | /// drift from the other, and no caller can substitute a number that merely happened to be in scope. |
| 418 | /// An earlier version took the junction's shape as a fallback and produced a count that varied with |
| 419 | /// which approach was looking at the arm. |
| 420 | /// |
| 421 | /// `turn:lanes` from `lanes.bin` is the only real value reachable here — the v6 routing graph |
| 422 | /// carries no lane count, and OSM's own `lanes` tag lives in the extract path keyed by way rather |
| 423 | /// than by directed edge, so joining to it is a separate piece of work. |
| 424 | /// |
| 425 | /// **The fallback of 1 is the carriageway renderer's own default, not a guess.** `tile/geometry.rs` |
| 426 | /// turns `lane_count 0` into `oneway ? 1 : 2`, counted across *both* directions; a two-way road is |
| 427 | /// therefore one lane each way and a one-way road one lane. [`lane_offset_m`] counts per direction |
| 428 | /// and adds the opposing half-carriageway itself, so both of those cases are 1 in this function's |
| 429 | /// units. Matching it is the whole point: a connector then starts and ends where the asphalt is |
| 430 | /// actually painted instead of where a second, disagreeing default put it. |
| 431 | /// |
| 432 | /// The cost is honest and worth stating. At an untagged junction every movement out of an arm |
| 433 | /// shares that arm's single lane, so the connectors meet at the arm's mouth rather than fanning. |
| 434 | /// That is what a single-lane road *is*. Inventing a wider fan to separate them draws lanes that |
| 435 | /// are not there and puts the endpoints off the carriageway, which is the defect this replaces. |
| 436 | fn effective_lanes(arm: &Arm) -> usize { |
| 437 | arm.masks.as_ref().map_or(1, Vec::len) |
| 438 | } |
| 439 | |
| 440 | /// Sample the connector from lane `in_lane` of `approach` into lane `out_lane` of `exit`. |
| 441 | /// |
| 442 | /// A cubic bezier in a local tangent plane centred on the junction node, with its handles along the |
| 443 | /// two headings so the curve leaves the approach and meets the exit tangentially. Sampled here, in |
| 444 | /// `f64` and once per build, rather than on device once per frame — which is the whole point of |
| 445 | /// carrying a polyline instead of control points. |
| 446 | fn connector( |
| 447 | node: (i32, i32), |
| 448 | approach: &Arm, |
| 449 | in_lane: usize, |
| 450 | approach_lanes: usize, |
| 451 | exit: &Arm, |
| 452 | out_lane: usize, |
| 453 | exit_lanes: usize, |
| 454 | turn: Turn, |
| 455 | left_hand: bool, |
| 456 | ) -> Option<Vec<(f64, f64)>> { |
| 457 | let back = (SETBACK_M).min(approach.length_m * SETBACK_EDGE_FRACTION); |
| 458 | let ahead = (SETBACK_M).min(exit.length_m * SETBACK_EDGE_FRACTION); |
| 459 | if back < MIN_SETBACK_M || ahead < MIN_SETBACK_M { |
| 460 | return None; |
| 461 | } |
| 462 | // The setback is real ground distance: the intersection is that big and the roads it joins are |
| 463 | // where they are. The lateral offset is not — it shrinks with `cos φ` so that it stays a fixed |
| 464 | // size in projected units, and therefore a fixed size in pixels, at every latitude. |
| 465 | // |
| 466 | // Both ends are placed by the same call with the same rule. Taking the counts as arguments |
| 467 | // rather than off each `Arm` is what makes that structural: an arm's own `lanes` is whatever |
| 468 | // `lanes.bin` happened to say, and reading it directly at one end while the caller overrode it |
| 469 | // at the other is exactly how every connector into an exit came to share one endpoint. |
| 470 | let width = lane_width_ground_m(f64::from(node.0) * 1e-7); |
| 471 | let in_off = lane_offset_m(in_lane, approach_lanes, approach.two_way, left_hand, width); |
| 472 | let out_off = lane_offset_m(out_lane, exit_lanes, exit.two_way, left_hand, width); |
| 473 | |
| 474 | let (fin_e, fin_n) = forward(approach.heading); |
| 475 | let (rin_e, rin_n) = rightward(approach.heading); |
| 476 | let (fout_e, fout_n) = forward(exit.heading); |
| 477 | let (rout_e, rout_n) = rightward(exit.heading); |
| 478 | |
| 479 | // Start: back along the approach from the node, then across to the lane's centre. |
| 480 | let p0 = (-fin_e * back + rin_e * in_off, -fin_n * back + rin_n * in_off); |
| 481 | // End: forward along the exit, then across. |
| 482 | let p3 = (fout_e * ahead + rout_e * out_off, fout_n * ahead + rout_n * out_off); |
| 483 | let p1 = (p0.0 + fin_e * back * HANDLE, p0.1 + fin_n * back * HANDLE); |
| 484 | let p2 = (p3.0 - fout_e * ahead * HANDLE, p3.1 - fout_n * ahead * HANDLE); |
| 485 | |
| 486 | // A straight-through movement needs two points; a U-turn needs every one of these. Anything |
| 487 | // flatter than the sampling would resolve is dropped by the tiler's simplifier anyway. |
| 488 | // |
| 489 | // Sampled at roughly half the historical density: a z14 connector spans |
| 490 | // tens of metres, so ~5 points resolve its curve at display scale and the |
| 491 | // rest were coordinate bytes. Minimum 3 keeps a curve a curve. |
| 492 | let sweep = normalise_degrees(exit.heading - approach.heading).abs(); |
| 493 | let samples = if turn == Turn::Through && sweep < 3.0 && (in_off - out_off).abs() < 0.05 { |
| 494 | 2 |
| 495 | } else { |
| 496 | (3.0 + sweep / 36.0).round().clamp(3.0, 7.0) as usize |
| 497 | }; |
| 498 | |
| 499 | let mut out = Vec::with_capacity(samples); |
| 500 | for i in 0..samples { |
| 501 | let t = i as f64 / (samples - 1) as f64; |
| 502 | let u = 1.0 - t; |
| 503 | let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); |
| 504 | let east = w0 * p0.0 + w1 * p1.0 + w2 * p2.0 + w3 * p3.0; |
| 505 | let north = w0 * p0.1 + w1 * p1.1 + w2 * p2.1 + w3 * p3.1; |
| 506 | out.push(offset_degrees(node, east, north)); |
| 507 | } |
| 508 | Some(out) |
| 509 | } |
| 510 | |
| 511 | /// Which lane of the exit a connector lands in. |
| 512 | /// |
| 513 | /// Inference, and the ordinary road convention; the rule is written out in full in the module docs. |
| 514 | /// `rank` is this lane's place, left→right, among the `siblings` approach lanes making the same |
| 515 | /// movement into the same exit — which is what keeps a dual left turn two ribbons wide instead of |
| 516 | /// two ribbons on one point. A movement only one lane makes passes `rank` 0 and `siblings` 1, and |
| 517 | /// reduces to "the exit's leftmost" or "its rightmost". |
| 518 | fn exit_lane( |
| 519 | turn: Turn, |
| 520 | in_lane: usize, |
| 521 | in_lanes: usize, |
| 522 | out_lanes: usize, |
| 523 | rank: usize, |
| 524 | siblings: usize, |
| 525 | ) -> usize { |
| 526 | let last = out_lanes.saturating_sub(1); |
| 527 | if turn.is_left() { |
| 528 | rank.min(last) |
| 529 | } else if turn.is_right() { |
| 530 | last - siblings.saturating_sub(1).saturating_sub(rank).min(last) |
| 531 | } else { |
| 532 | (in_lane * out_lanes / in_lanes.max(1)).min(last) |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | /// The exits a lane tagged for `turn` should connect to. |
| 537 | /// |
| 538 | /// Exact bucket first: every legal exit the junction's own geometry classes as this movement. When |
| 539 | /// none matches — a `turn:lanes=right` onto a road that leaves at 140°, say — the single closest |
| 540 | /// exit by angle is used instead, because a tagged indication with nowhere to go is far more likely |
| 541 | /// to be a threshold disagreement than a lane that leads nowhere. |
| 542 | fn exits_for(turn: Turn, legal: &[(usize, f64, Turn)]) -> Vec<usize> { |
| 543 | // A lane tagged `turn:lanes=reverse` has nowhere to go, because reversals are not legal |
| 544 | // movements here. Returning empty rather than falling through matters: `legal` holds no |
| 545 | // reversal, so the closest-by-angle fallback below would attach the lane to whatever sharp |
| 546 | // turn happens to be nearest and emit a connector into a road the lane does not feed. |
| 547 | if turn == Turn::Reverse { |
| 548 | return Vec::new(); |
| 549 | } |
| 550 | let exact: Vec<usize> = |
| 551 | legal.iter().filter(|(_, _, t)| *t == turn).map(|(i, _, _)| *i).collect(); |
| 552 | if !exact.is_empty() { |
| 553 | return exact; |
| 554 | } |
| 555 | let nominal = turn.nominal_degrees(); |
| 556 | legal |
| 557 | .iter() |
| 558 | .min_by(|a, b| { |
| 559 | normalise_degrees(a.1 - nominal) |
| 560 | .abs() |
| 561 | .total_cmp(&normalise_degrees(b.1 - nominal).abs()) |
| 562 | }) |
| 563 | .map(|(i, _, _)| vec![*i]) |
| 564 | .unwrap_or_default() |
| 565 | } |