Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / junction.rs
junction.rs473 lines · 25.6 KiBRaw
| 1 | //! `junction`: one line per **lane connector** through an intersection. |
| 2 | //! |
| 3 | //! A lane connector is the path a single lane follows from an approach into an exit — the left-turn |
| 4 | //! lane's arc, the through lane's stripe, the slip road peeling off a motorway. The renderer draws |
| 5 | //! each as a one-lane ribbon and does no curve maths, so every feature here is an already-sampled |
| 6 | //! polyline rather than a control-point set. |
| 7 | //! |
| 8 | //! Geometry comes from the same v6 routing graph [`crate::schema::traffic`] reads — |
| 9 | //! `metadata.bin`, `nodes.bin`, `edges.bin`, `intermediate.bin`, plus `lanes.bin` — and that module |
| 10 | //! is where the on-disk format, the escape tables and the polyline decode are documented. This one |
| 11 | //! only adds what a connector needs on top: which nodes are junctions, which way each incident edge |
| 12 | //! points, and which lane goes where. |
| 13 | //! |
| 14 | //! # What is data and what is inference |
| 15 | //! |
| 16 | //! **Be clear about this, because most of it is inference.** OSM has essentially no lane |
| 17 | //! connectivity data. `connectivity` relations exist but are vanishingly rare and nothing in this |
| 18 | //! tree reads them. So: |
| 19 | //! |
| 20 | //! | Thing | Where it comes from | |
| 21 | //! |---|---| |
| 22 | //! | Which nodes are junctions | **Data.** The generator collapses degree-2 chains, so a surviving node of degree ≥ 3 is a real fork. | |
| 23 | //! | Where each approach and exit runs | **Data.** Node coordinates and edge polylines. | |
| 24 | //! | Approach and exit headings | **Data**, derived: `atan2` over the first geometry step, because the graph stores no headings. | |
| 25 | //! | Which movements are legal | **Inference.** Every exit but a reversal is assumed legal — excluded by *angle*, not just by whether it returns to the same neighbour, because a divided highway's median slot reverses onto a different node. The graph carries no turn restrictions. | |
| 26 | //! | A lane's turn indication, where `turn:lanes` is tagged | **Data.** `lanes.bin`, keyed by directed edge, ordered left→right. | |
| 27 | //! | A lane's turn indication everywhere else | **Inference**, and this is the overwhelming majority of roads. | |
| 28 | //! | How many lanes an arm has, absent `turn:lanes` | **Neither, and the important row.** One lane in the direction of travel — not a guess but the carriageway renderer's own default, so a connector lands on the painted asphalt. [`effective_lanes`]. | |
| 29 | //! | Which lane of the exit a movement lands in | **Inference.** The convention in [`exit_lane`], stated below. | |
| 30 | //! | Lane width | |
| 31 | //! | Lane width | **Neither, and worth knowing which.** [`LANE_WIDTH_MERCATOR_M`] is not a road measurement — it is tuned to the width the renderer paints a lane at. | |
| 32 | //! | The setback the arc starts at | **Neither.** [`SETBACK_M`] is a nominal guess at how big an intersection is. | |
| 33 | //! |
| 34 | //! Motorway exits are the case this should look good on: they are comparatively well tagged, they |
| 35 | //! are geometrically simple, and a slip road's heading separates cleanly from the mainline's. |
| 36 | //! Ordinary urban intersections are a heuristic and will need tuning against screenshots. Nothing |
| 37 | //! here should be read as knowing where the paint is. |
| 38 | //! |
| 39 | //! # Thinning (size) |
| 40 | //! |
| 41 | //! The junction layer is the archive's largest single line item, so three |
| 42 | //! principled rules thin it — predicates, never count caps, so no junction is |
| 43 | //! thinned arbitrarily: |
| 44 | //! |
| 45 | //! * **Arterial gate.** A junction emits nothing unless at least one arm is |
| 46 | //! [`ARTERIAL_MAX_CLASS`] or better. Residential-only crossings keep their |
| 47 | //! carriageways; they lose only the lane markings. |
| 48 | //! * **Slight turns at degree 3.** A 20–45° movement at a three-way node is a |
| 49 | //! road bend, not a turn, and the carriageway already shows the path. Kept |
| 50 | //! at degree ≥ 4, where a slight exit is a real choice. |
| 51 | //! * **Halved sampling.** Connectors sample at roughly half the old density; |
| 52 | //! the curve shape is unchanged to the eye at display scale. |
| 53 | //! |
| 54 | //! # Both ends of a connector are placed by the same rule, and a lane count is never invented |
| 55 | //! |
| 56 | //! A connector runs from a lane to a lane, so both ends need a lane index and a lane count. Those |
| 57 | //! come from [`effective_lanes`] and [`lane_offset_m`], called once per end. Two defects lived |
| 58 | //! here and they had to be fixed together, because fixing either alone makes the other worse. |
| 59 | //! |
| 60 | //! **The ends disagreed.** The exit end kept whatever `lanes.bin` left on its [`Arm`], while the |
| 61 | //! approach end was widened to the junction's exit count, so [`exit_lane`] returned lane 0 for |
| 62 | //! every movement and every connector entering an arm terminated on one identical point. A |
| 63 | //! degree-`d` junction emitted the correct `d * (d - 1)` connectors and only `d` distinct |
| 64 | //! endpoints: a wide fan at one end collapsing to a pencil point at the other, which is the tangle |
| 65 | //! of hairlines that reached a device. |
| 66 | //! |
| 67 | //! **The width was fabricated.** `legal.len()` is a count of *exits*, borrowed as a lane count |
| 68 | //! because it was in scope. It is not a measurement of anything. At a 4-way it claims three lanes |
| 69 | //! per direction where the renderer paints one, so the outermost connector starts 2.5 lane widths |
| 70 | //! off the centreline on a carriageway whose kerb is at 1.0 — off the road entirely. |
| 71 | //! |
| 72 | //! Mirroring the fabricated count to the exit end would have made both ends agree, and put *both* |
| 73 | //! of them off the asphalt instead of one. So the count is not mirrored; it is removed. |
| 74 | //! [`effective_lanes`] takes an [`Arm`] and nothing else, which makes the two ends agree by |
| 75 | //! construction and makes an observer-dependent count unrepresentable rather than merely absent. |
| 76 | //! |
| 77 | //! The honest consequence: at an untagged junction every movement out of an arm shares that arm's |
| 78 | //! one lane, so connectors meet at the arm's mouth instead of fanning, and `d` distinct endpoints |
| 79 | //! at a degree-`d` junction is now the *correct* answer rather than the symptom. Separating them |
| 80 | //! would mean drawing lanes that do not exist. |
| 81 | //! |
| 82 | //! ## Which lane of the exit a movement lands in |
| 83 | //! |
| 84 | //! Only ever more than one lane where `turn:lanes` says so. With `N` approach lanes and `M` exit |
| 85 | //! lanes, for the group of approach lanes making the *same* movement into the *same* exit, ranked |
| 86 | //! `0..r` left→right: |
| 87 | //! |
| 88 | //! - **Through and reverse** hold position: `floor(in_lane * M / N)`, clamped. Identity when |
| 89 | //! `N == M`, which is what a straight-through wants and is what lets it draw as a straight line |
| 90 | //! rather than a slight S. |
| 91 | //! - **Left turns** fill the exit from its left: `min(rank, M - 1)`. |
| 92 | //! - **Right turns** fill the exit from its right: `M - 1 - min(r - 1 - rank, M - 1)`. |
| 93 | //! |
| 94 | //! The rank is what makes a tagged dual left turn two ribbons in two lanes instead of two ribbons |
| 95 | //! on one point. A single-lane movement has `r == 1` and reduces to "the leftmost" or "the |
| 96 | //! rightmost". |
| 97 | //! |
| 98 | //! **This is convention, not data, and it is written down so it can be argued with.** Nothing in |
| 99 | //! the graph says which lane feeds which. |
| 100 | //! |
| 101 | //! ## The setback does not scale with the junction's degree |
| 102 | //! |
| 103 | //! Worth recording, because the measurement that suggested it did was reading the fabricated width. |
| 104 | //! [`SETBACK_M`] is constant and additionally clamped to a fraction of each arm's own length. The |
| 105 | //! furthest a connector reached from the node used to grow with degree — about 14.5 m at degree 3 |
| 106 | //! against 20.9 m at degree 8 — because the *lateral* fan grew: its outermost lane sat at |
| 107 | //! `(count - 0.5)` widths with `count = degree - 1`. With the fabricated count gone the lateral |
| 108 | //! term is half a lane at every degree and the reach is the setback, flat. No change to |
| 109 | //! [`SETBACK_M`] was needed and none was made. |
| 110 | //! |
| 111 | //! ## Reading a screenshot of this layer |
| 112 | //! |
| 113 | //! Counter-intuitive, and worth knowing before judging a geometry change here by eye. A connector |
| 114 | //! draws as a one-lane carriageway ribbon, so by width it is mostly asphalt — but the |
| 115 | //! `junction-connector` style layer declares the *same* colours as `roads-carriageway`, on purpose, |
| 116 | //! so that a connector reads as the carriageway continued rather than as a stripe laid over it. |
| 117 | //! Across the junction box, which the crossing road ribbons already cover, that makes the ribbon's |
| 118 | //! asphalt an exact identity against what is beneath it: same style entry, same colour, depth off. |
| 119 | //! |
| 120 | //! **So where a connector overlies road surface, its only visible signature is the fraction of its |
| 121 | //! width that is lane marking** — which is why the geometry here says ribbons while the screenshot |
| 122 | //! that prompted this work said thin white strokes. Where a connector leaves the road the asphalt |
| 123 | //! does show, as grey against bare earth; the tangle this layer first shipped with had both, white |
| 124 | //! over the carriageway and grey beyond it. Figures measured on the renderer side. |
| 125 | //! |
| 126 | //! The practical consequence: do not judge a change to the geometry above by how much asphalt |
| 127 | //! appears. Judge it by where the markings fall. |
| 128 | //! |
| 129 | //! **First, though, check that connectors are drawn at all.** `style::LANE_RENDERING` is a release |
| 130 | //! kill switch that defaults to `false`, and it works by dropping every `carriageway: true` layer |
| 131 | //! from `style::layers()` — which is `roads-carriageway` *and* `junction-connector`. It is a |
| 132 | //! *drawing* gate and it is not this module's. The tiler does not link the renderer, so connectors |
| 133 | //! are written into the archive exactly as before and only the painting stops: the screen goes |
| 134 | //! empty rather than going wrong. |
| 135 | //! |
| 136 | //! **So a blank connector screenshot is not evidence about [`MIN_ZOOM`], and must not be read as |
| 137 | //! any.** The two gates are independent and are currently in opposite states — [`MIN_ZOOM`] decides |
| 138 | //! what reaches the archive and is satisfied; the style layer decides what is painted and is |
| 139 | //! switched off. Debugging an empty screen inward lands on the tiler, and "fixing" a tiling gate |
| 140 | //! that is already right is what silently shipped an archive with zero junction features once |
| 141 | //! already. That failure is documented at [`MIN_ZOOM`]; this is the same confusion running the |
| 142 | //! other way. Nothing in this module can cause a blank screen and nothing in this module can fix |
| 143 | //! one. |
| 144 | //! |
| 145 | //! The renderer's own tests read `style::layers_with_lane_rendering()` so they keep asserting |
| 146 | //! against the real style, which is right — but it does mean a green test run says nothing about |
| 147 | //! whether the switch is on. |
| 148 | //! |
| 149 | //! # Lateral offset is baked in projected units, not ground metres |
| 150 | //! |
| 151 | //! Each connector's polyline already carries its lane's offset across the carriageway. That offset |
| 152 | //! is expressed as a fixed number of **Web Mercator** units — spelled here as the ground metres a |
| 153 | //! lane occupies *at the equator*, which is the same thing — and **not** as ground metres at the |
| 154 | //! junction's own latitude. |
| 155 | //! |
| 156 | //! This is structural rather than cosmetic. The carriageway ribbon's lane width is a screen-space |
| 157 | //! quantity: a dp ramp turned into a half-width in pixels and pushed per draw. Web Mercator's scale |
| 158 | //! carries a `1 / cos φ` term, so a fixed ground distance is a *different* number of pixels at |
| 159 | //! every latitude. Measured against the style's painted lane, 3.5 m of ground comes out at 0.97 of |
| 160 | //! a lane at the equator, 0.76 at 38°N and 0.48 at 60°N — so a naively baked ground offset lands |
| 161 | //! 2.3× too far out in Scandinavia, which is more than two lane widths and puts the connector off |
| 162 | //! the road it is meant to join. |
| 163 | //! |
| 164 | //! No zoom gate can rescue that, because `cos φ` is not a function of zoom. Scaling the offset by |
| 165 | //! `cos φ` before it is converted to degrees cancels the projection's stretch exactly, costs one |
| 166 | //! multiply, and needs no wire field and no shader change. The along-road setback is deliberately |
| 167 | //! *not* scaled: [`SETBACK_M`] is a real distance on the ground, because the intersection it spans |
| 168 | //! and the road geometry it must meet are both real distances on the ground. |
| 169 | //! |
| 170 | //! ## The projection correction is exact; the lane width is not |
| 171 | //! |
| 172 | //! "Exactly" above is a claim about the projection and nothing else: `cos φ` cancels Mercator's |
| 173 | //! `1 / cos φ`, which is pure geometry and leaves nothing over at any latitude. It is *not* a |
| 174 | //! claim that a connector lands on the paint. Read as one it is actively dangerous, because a |
| 175 | //! reader who believes the whole thing is exact has no reason to expect a residual, and on meeting |
| 176 | //! one will look for it in the projection — where it is not — and close it by putting a `cos φ` |
| 177 | //! back somewhere. That is the bug this section exists to prevent. |
| 178 | //! |
| 179 | //! A second and smaller discrepancy does survive, and it is not projection error. |
| 180 | //! [`LANE_WIDTH_MERCATOR_M`] is a single number, while the width the renderer actually paints a |
| 181 | //! lane at comes from the style's dp ramp, which is not linear in ground metres — so the two agree |
| 182 | //! at one zoom and drift either side of it. The ramp is `roads-carriageway`'s `width` in |
| 183 | //! `basemap.flat.json` — exponential, base 2.0, over stops |
| 184 | //! `[[16, 3.0], [18, 11.0], [20, 40.0], [22, 160.0]]`, one lane's width in dp. Read at the |
| 185 | //! equator, where the `cos φ` term is already 1 and the ramp is therefore read cleanly on its |
| 186 | //! own, and against a 512 dp tile, a painted lane is worth about 3.40 m of ground at z17 falling |
| 187 | //! to 2.98 m by z20, against a fixed 3.0 m of connector pitch: roughly 12% narrow at z17, |
| 188 | //! crossing over to about 1% wide by z20. Those figures are reproducible from those stops rather |
| 189 | //! than asserted. The change of sign is the part that matters: no single percentage describes the |
| 190 | //! residual, and anyone who reads "the connector is N% wider" will reach for a correction that is |
| 191 | //! wrong at one end of the zoom range. That the fit crosses zero at all is the point — it is |
| 192 | //! centred across the zoom band rather than biased to one end, which is what fitting on absolute |
| 193 | //! dp instead of relative error buys. The residual is also latitude-independent, which together |
| 194 | //! with the drift in zoom is the signature of a ramp mismatch rather than of a projection. |
| 195 | //! |
| 196 | //! **It cannot be closed by a projection term, because it is not a projection error.** The only |
| 197 | //! two levers on it are [`LANE_WIDTH_MERCATOR_M`] and the style's width ramp; the constant is |
| 198 | //! already fitted against that ramp, and where the residual is deliberately put — in percent |
| 199 | //! rather than in pixels — is argued at the constant. A `cos φ` introduced to chase it would be 1 |
| 200 | //! at the equator, which is exactly where the residual was measured, and wrong everywhere else. |
| 201 | |
| 202 | use std::collections::BTreeSet; |
| 203 | use std::path::Path; |
| 204 | |
| 205 | use osm_ingest::proto::{err, Result}; |
| 206 | use rayon::prelude::*; |
| 207 | use tile_build::geom::Geometry; |
| 208 | use tile_build::par; |
| 209 | use tile_build::progress::Progress; |
| 210 | use tilecodec::mamaps::body::{ |
| 211 | LANE_LEFT, LANE_NONE, LANE_REVERSE, LANE_RIGHT, LANE_SHARP_LEFT, LANE_SHARP_RIGHT, |
| 212 | LANE_SLIGHT_LEFT, LANE_SLIGHT_RIGHT, LANE_THROUGH, |
| 213 | }; |
| 214 | use tilecodec::mamaps::dict::{self, LAYER_JUNCTION}; |
| 215 | |
| 216 | use super::boundaries::Conventions; |
| 217 | use super::traffic::{Graph, ROAD_TYPE_MASK}; |
| 218 | use super::Class; |
| 219 | use crate::store::Sink; |
| 220 | |
| 221 | /// The shallowest zoom lane connectors are **tiled** into. |
| 222 | /// |
| 223 | /// This is a tiling gate and nothing else, so it is bounded above by the deepest zoom an archive |
| 224 | /// is built to — z14, [`crate::DEFAULT_MAX_ZOOM`]. Set past that there |
| 225 | /// is no tile deep enough to hold a connector, so every one of them is computed and then dropped, |
| 226 | /// and the layer is missing from the archive entirely while the build still reports success. |
| 227 | /// |
| 228 | /// 14 is that bound, which puts connectors in the deepest tiles only and is the least size they |
| 229 | /// can cost. The zoom they are *drawn* from is a separate gate living in the style — the |
| 230 | /// `junction-connector` layer's `minzoom`, which is 16 — and the renderer overzooms the z14 tile |
| 231 | /// above it. That split is how `roads-lanes` already carries lane detail. |
| 232 | pub const MIN_ZOOM: u8 = 14; |
| 233 | |
| 234 | /// The largest (least significant) road class that still counts as an arterial. |
| 235 | /// |
| 236 | /// Graph edge types share OSM's highway vocabulary as integers |
| 237 | /// (`osm_ingest::tags`: motorway=1 … tertiary=5, unclassified=6, |
| 238 | /// residential=7, …). A junction emits connectors only when at least one arm |
| 239 | /// is this class or better: quiet residential crossings lose lane markings |
| 240 | /// they barely show, while every junction an arterial touches keeps its own. |
| 241 | pub const ARTERIAL_MAX_CLASS: u8 = 5; |
| 242 | |
| 243 | /// Width of one lane, in **Web Mercator metres** — ground metres at the equator, which at any |
| 244 | /// other latitude is a smaller ground distance and the same projected one. That is what makes it a |
| 245 | /// fixed number of pixels everywhere; see the module docs, where expressing it as ground metres at |
| 246 | /// the junction's own latitude is what puts a connector two lanes off the road at 60°N. |
| 247 | /// [`lane_width_ground_m`] converts it for a given latitude. |
| 248 | /// |
| 249 | /// **3.0, not the 3.5 a real lane is designed to, and that is deliberate — do not "correct" it.** |
| 250 | /// This is not a measurement of a road. It is fitted to the width the renderer actually paints a |
| 251 | /// lane at, which is a dp ramp and is not linear in ground metres. Measured against that ramp, a |
| 252 | /// lane is worth about 3.40 m of ground at z17 falling to 2.98 m by z20, so no single constant is |
| 253 | /// right at every zoom and the only question is where to put the residual. |
| 254 | /// |
| 255 | /// It is fitted on **absolute misalignment in dp, not relative error**, and the two disagree: a dp |
| 256 | /// is 1.7 per ground metre at z17 and 13.4 at z20, so the same percentage costs eight times the |
| 257 | /// pixels at the deep end. 3.2 minimises worst-case percentage but leaves ~5 dp of visible gap at |
| 258 | /// z20; 3.0 is a worse percentage fit and keeps the gap near a pixel at every zoom, which is the |
| 259 | /// one that cannot be seen. Percentage error is not what a viewer looks at. |
| 260 | pub const LANE_WIDTH_MERCATOR_M: f64 = 3.0; |
| 261 | |
| 262 | /// [`LANE_WIDTH_MERCATOR_M`] as ground metres at `lat_degrees`, which is a lane's width shrinking |
| 263 | /// toward the poles exactly as fast as Mercator stretches it. Exact as a statement about the |
| 264 | /// projection — `cos φ` against `1 / cos φ`, with no approximation in it — and only that: it says |
| 265 | /// nothing about whether the result matches the painted lane, which is the ramp residual the |
| 266 | /// module docs describe and is not fixable here. |
| 267 | fn lane_width_ground_m(lat_degrees: f64) -> f64 { |
| 268 | LANE_WIDTH_MERCATOR_M * lat_degrees.to_radians().cos().abs().max(1e-6) |
| 269 | } |
| 270 | |
| 271 | /// How far back from the junction node a connector starts, and how far past it the connector ends. |
| 272 | /// |
| 273 | /// The node is a point; a real intersection is a box some tens of metres across. This is the |
| 274 | /// half-width that box is assumed to have, so a connector spans roughly `2 * SETBACK_M` of ground. |
| 275 | /// Clamped per edge to a fraction of that edge's own length, so a short block does not produce a |
| 276 | /// connector running past the next junction. |
| 277 | const SETBACK_M: f64 = 14.0; |
| 278 | |
| 279 | /// The most of an incident edge's length a connector may consume at either end. |
| 280 | const SETBACK_EDGE_FRACTION: f64 = 0.4; |
| 281 | |
| 282 | /// Below this the connector is shorter than a lane is wide and draws as a blob. |
| 283 | const MIN_SETBACK_M: f64 = 2.0; |
| 284 | |
| 285 | /// Bezier handle length as a fraction of the setback. |
| 286 | /// |
| 287 | /// 0.55 is the usual circular-arc approximation constant; it makes the curve leave the approach and |
| 288 | /// meet the exit tangentially without bulging past the intersection box. |
| 289 | const HANDLE: f64 = 0.55; |
| 290 | |
| 291 | /// Metres per degree of latitude. Spherical, which is the same approximation |
| 292 | /// [`tile_build::geom::project`] makes and is worth centimetres over a connector's length. |
| 293 | const METRES_PER_DEGREE: f64 = 111_320.0; |
| 294 | |
| 295 | /// The class every lane connector carries: layer `junction`, no kind and no detail. |
| 296 | /// |
| 297 | /// No `kind`/`kind_detail` for the same reason [`crate::schema::traffic::traffic_class`] has none: |
| 298 | /// the basemap style does not draw this layer, the carriageway renderer does, and it selects the |
| 299 | /// whole layer rather than filtering within it. Keeping the name out of [`dict::KINDS`] avoids |
| 300 | /// disturbing the frozen kind table for a value nothing matches by name. |
| 301 | pub fn junction_class() -> Class { |
| 302 | Class { |
| 303 | layer: LAYER_JUNCTION, |
| 304 | kind: dict::NONE, |
| 305 | kind_detail: dict::NONE, |
| 306 | flags: 0, |
| 307 | area: false, |
| 308 | min_zoom: MIN_ZOOM, |
| 309 | min_area_px: 0.0, |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // --- lanes.bin ------------------------------------------------------------------------------ |
| 314 | |
| 315 | /// `lanes.bin`: `[u32 n][(u32 edge_idx, u32 blob_off) x (n + 1)][u16 mask blob]`. |
| 316 | /// |
| 317 | /// **Sparse**: only edges that carry a `turn:lanes` tag appear, ascending by `edge_idx`, so absence |
| 318 | /// from the index is how "this edge has no lane data" is spelled. Mirrors |
| 319 | /// `maps/src/main/rust/src/graph.rs::edge_lane_masks`; the trailing sentinel entry exists only to |
| 320 | /// give the last real edge a length. |
| 321 | /// |
| 322 | /// Mapped, not read: a planet `lanes.bin` is looked up by binary search, so only its index pages |
| 323 | /// stay resident. Matches [`Graph`]. |
| 324 | struct LaneTable { |
| 325 | raw: osm_ingest::mem::Mapped, |
| 326 | count: u32, |
| 327 | blob_off: usize, |
| 328 | } |
| 329 | |
| 330 | impl LaneTable { |
| 331 | /// Read `lanes.bin`, or `None` when the graph was built without lane data. A missing file is |
| 332 | /// not an error — every connector then falls back to the inferred path, which is what happens |
| 333 | /// for most edges even when the file is present. |
| 334 | fn load(dir: &Path) -> Result<Option<LaneTable>> { |
| 335 | let path = dir.join("lanes.bin"); |
| 336 | // Absence is not an error (a graph built without lane data); any other failure to open |
| 337 | // or map is. Checked by existence first so a mapping failure on a present file is not |
| 338 | // misread as "no lane data". |
| 339 | if std::fs::metadata(&path).is_err() { |
| 340 | return Ok(None); |
| 341 | } |
| 342 | let raw = osm_ingest::mem::Mapped::open(&path).map_err(osm_ingest::proto::Error)?; |
| 343 | if raw.len() < 4 { |
| 344 | return err("lanes.bin is too short to hold its entry count".to_string()); |
| 345 | } |
| 346 | let count = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]); |
| 347 | // n + 1 entries: the trailing sentinel is what gives the last edge an end offset. |
| 348 | let index_bytes = 4usize |
| 349 | .checked_add((count as usize + 1).saturating_mul(8)) |
| 350 | .ok_or_else(|| osm_ingest::proto::Error("lanes.bin index size overflows".to_string()))?; |
| 351 | if raw.len() < index_bytes { |
| 352 | return err(format!( |
| 353 | "lanes.bin is {} bytes, too short for its {count}-entry index", |
| 354 | raw.len(), |
| 355 | )); |
| 356 | } |
| 357 | Ok(Some(LaneTable { raw, count, blob_off: index_bytes })) |
| 358 | } |
| 359 | |
| 360 | fn entry(&self, i: u32) -> (u32, u32) { |
| 361 | let at = 4 + (i as usize) * 8; |
| 362 | let edge = u32::from_le_bytes([self.raw[at], self.raw[at + 1], self.raw[at + 2], self.raw[at + 3]]); |
| 363 | let off = u32::from_le_bytes([ |
| 364 | self.raw[at + 4], |
| 365 | self.raw[at + 5], |
| 366 | self.raw[at + 6], |
| 367 | self.raw[at + 7], |
| 368 | ]); |
| 369 | (edge, off) |
| 370 | } |
| 371 | |
| 372 | /// The per-lane `LANE_*` masks for directed edge `idx`, ordered left→right, or `None` when it |
| 373 | /// carries none. Binary search, because the index is sparse. |
| 374 | fn masks(&self, idx: u32) -> Option<Vec<u16>> { |
| 375 | let (mut lo, mut hi) = (0u32, self.count); |
| 376 | while lo < hi { |
| 377 | let mid = lo + (hi - lo) / 2; |
| 378 | if self.entry(mid).0 < idx { |
| 379 | lo = mid + 1; |
| 380 | } else { |
| 381 | hi = mid; |
| 382 | } |
| 383 | } |
| 384 | if lo >= self.count || self.entry(lo).0 != idx { |
| 385 | return None; |
| 386 | } |
| 387 | let start = self.blob_off + self.entry(lo).1 as usize; |
| 388 | let end = self.blob_off + self.entry(lo + 1).1 as usize; |
| 389 | if end <= start || end > self.raw.len() { |
| 390 | return None; |
| 391 | } |
| 392 | Some( |
| 393 | self.raw[start..end] |
| 394 | .chunks_exact(2) |
| 395 | .map(|c| u16::from_le_bytes([c[0], c[1]])) |
| 396 | .collect(), |
| 397 | ) |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // --- turns ---------------------------------------------------------------------------------- |
| 402 | |
| 403 | /// A movement's turn class, the same vocabulary `turn:lanes` uses. |
| 404 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 405 | enum Turn { |
| 406 | SharpLeft, |
| 407 | Left, |
| 408 | SlightLeft, |
| 409 | Through, |
| 410 | SlightRight, |
| 411 | Right, |
| 412 | SharpRight, |
| 413 | /// A reversal back the way the driver came — the `LANE_REVERSE` indication. |
| 414 | Reverse, |
| 415 | } |
| 416 | |
| 417 | impl Turn { |
| 418 | /// The `LANE_*` bit a lane tagged for this movement sets. |
| 419 | fn bit(self) -> u16 { |
| 420 | match self { |
| 421 | Turn::SharpLeft => LANE_SHARP_LEFT, |
| 422 | Turn::Left => LANE_LEFT, |
| 423 | Turn::SlightLeft => LANE_SLIGHT_LEFT, |
| 424 | Turn::Through => LANE_THROUGH, |
| 425 | Turn::SlightRight => LANE_SLIGHT_RIGHT, |
| 426 | Turn::Right => LANE_RIGHT, |
| 427 | Turn::SharpRight => LANE_SHARP_RIGHT, |
| 428 | Turn::Reverse => LANE_REVERSE, |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | /// The angle, in degrees clockwise, this movement nominally turns through. Used to pick the |
| 433 | /// closest real exit for a tagged indication that no exit's own bucket matches — a |
| 434 | /// `turn:lanes=right` onto a road the graph classes as a sharp right, say. |
| 435 | fn nominal_degrees(self) -> f64 { |
| 436 | match self { |
| 437 | Turn::SharpLeft => -155.0, |
| 438 | Turn::Left => -90.0, |
| 439 | Turn::SlightLeft => -32.0, |
| 440 | Turn::Through => 0.0, |
| 441 | Turn::SlightRight => 32.0, |
| 442 | Turn::Right => 90.0, |
| 443 | Turn::SharpRight => 155.0, |
| 444 | Turn::Reverse => 180.0, |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | /// Does this movement go left? Decides which lane of the exit a connector lands in. |
| 449 | fn is_left(self) -> bool { |
| 450 | matches!(self, Turn::SharpLeft | Turn::Left | Turn::SlightLeft) |
| 451 | } |
| 452 | |
| 453 | fn is_right(self) -> bool { |
| 454 | matches!(self, Turn::SharpRight | Turn::Right | Turn::SlightRight) |
| 455 | } |
| 456 | |
| 457 | /// Every turn a `LANE_*` mask can name, so a lane's bits can be walked. |
| 458 | const ALL: [Turn; 8] = [ |
| 459 | Turn::SharpLeft, |
| 460 | Turn::Left, |
| 461 | Turn::SlightLeft, |
| 462 | Turn::Through, |
| 463 | Turn::SlightRight, |
| 464 | Turn::Right, |
| 465 | Turn::SharpRight, |
| 466 | Turn::Reverse, |
| 467 | ]; |
| 468 | } |
| 469 | |
| 470 | include!("junction_part1.rs"); |
| 471 | include!("junction_part2.rs"); |
| 472 | include!("junction_part3.rs"); |
| 473 | include!("junction_part4.rs"); |