maps: junction connectors, carriageway v7 wiring, lane guidance
- Commit
3b3a3be8745853a400ec3ed8ed2e5fa56c4673f0- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-10 16:14 UTC (2 months ago)
- Parents
74a516f
Diff
library/map/src/main/rust/src/style/mod.rs
diff --git a/library/map/src/main/rust/src/style/mod.rs b/library/map/src/main/rust/src/style/mod.rsindex 302e3c469d..3b0957de08 100644--- a/library/map/src/main/rust/src/style/mod.rs+++ b/library/map/src/main/rust/src/style/mod.rs@@ -694,15 +694,18 @@ pub fn layers() -> &'static [Layer] { /// The road carriageway layer, whose zoom window gates the per-lane road detail and whose width /// ramp says how wide one lane of it is. ///-/// Matched on [`Layer::carriageway`], which is the flag that makes a layer draw road surfaces and-/// which nothing but a road layer carries. Its predecessor matched [`Layer::lane_fan`] — "does this-/// layer have a spread" — and `transit-rail` has one for its corridor colours and is declared-/// first, so matching that way silently answered with the rail layer, whose `minzoom` is 8 against-/// the road detail's 16. That is what drew turn arrows from z8, offset by the rail corridor's ramp-/// instead of the road's, and is why the predicate here names the thing it wants rather than a-/// property several layers happen to share.+/// Matched on [`Layer::carriageway`] **and** on the roads source, because the flag alone does not+/// name one layer: `junction-connector` draws a surface too, and would answer with a connector's+/// single lane. Its predecessor matched [`Layer::lane_fan`] — "does this layer have a spread" — and+/// `transit-rail` has one for its corridor colours and is declared first, so matching that way+/// silently answered with the rail layer, whose `minzoom` is 8 against the road detail's 16. That+/// is what drew turn arrows from z8, offset by the rail corridor's ramp instead of the road's.+///+/// Naming the source restores what that fix did before the `carriageway` flag replaced it, and is+/// what keeps the answer out of the hands of the declaration order in `basemap.flat.json`: exactly+/// one layer matches, so a reordered style or a third carriageway layer cannot re-point the gate. pub fn road_carriageway_layer(layers: &[Layer]) -> Option<&Layer> {- layers.iter().find(|l| l.carriageway)+ layers.iter().find(|l| l.carriageway && l.source_layer_id == dict::LAYER_ROADS) } #[cfg(test)]@@ -858,6 +861,34 @@ mod tests { assert!(gate.draws_at(16), "turn arrows from z16"); } + /// And the answer does not depend on the order the style lists its layers in.+ ///+ /// `junction-connector` carries `carriageway` too, so a `find` on the flag alone is once again+ /// a predicate several layers share, answering with whichever is declared first — the same+ /// shape as the `lane_fan` bug above, one layer along. `paint`'s+ /// `the_carriageway_is_gated_and_sized_by_the_lane` pins that order, which keeps today's style+ /// honest; this pins that the order is not load-bearing in the first place. Asserted as a+ /// filtered list rather than a `find`, because "one layer matches" is the property that makes+ /// order irrelevant, and a `find` cannot tell one match from the first of several.+ #[test]+ fn the_arrow_gate_does_not_depend_on_the_declaration_order() {+ let matches: Vec<&str> = layers()+ .iter()+ .filter(|l| l.carriageway && l.source_layer_id == dict::LAYER_ROADS)+ .map(|l| l.id.as_str())+ .collect();+ assert_eq!(matches, vec!["roads-carriageway"], "the gate predicate must name one layer");++ // The layer that would answer instead, and the two halves of why it does not.+ let connector = find("junction-connector");+ assert!(connector.carriageway, "a connector draws as a road surface as well");+ assert_ne!(+ connector.source_layer_id,+ dict::LAYER_ROADS,+ "but it reads the junction source, which is what keeps it out of the gate",+ );+ }+ /// A kind the authored `case` gives its own colour has its own layer, and a kind that shares /// a colour with another sits in the same layer rather than adding a draw. #[test]
library/map/src/main/rust/src/style/paint.rs
diff --git a/library/map/src/main/rust/src/style/paint.rs b/library/map/src/main/rust/src/style/paint.rsindex ba4922593b..ce658045d9 100644--- a/library/map/src/main/rust/src/style/paint.rs+++ b/library/map/src/main/rust/src/style/paint.rs@@ -556,10 +556,11 @@ mod tests { // that says what it is, instead of nudging a basemap total that then no longer // states what the basemap is. //- // Basemap: 24 fills, 23 lines and 7 symbols. The 23 lines are the 12- // surface/link layers, 10 bridge layers (5 casings + 5 fills), and the app-only- // `roads-carriageway` layer that draws a road's surface and its lane markings at- // z16+: the authored+ // Basemap: 24 fills, 24 lines and 7 symbols. The 24 lines are the 12+ // surface/link layers, 10 bridge layers (5 casings + 5 fills), and the two app-only+ // carriageway layers that draw a road's surface and its lane markings at z16+ —+ // `roads-carriageway` and `junction-connector`, which continues the same surface+ // through an intersection: the authored // `is_bridge` pass the flat file used to drop entirely, which is what hid the Bay // Bridge and the Golden Gate (task 8). The 7 symbols are the 4-deep places hierarchy // (country/region/locality/subplace) plus the 3 curved line labels WS-E added@@ -582,7 +583,7 @@ mod tests { }; assert_eq!( (count(LayerKind::Fill, false), count(LayerKind::Line, false), count(LayerKind::Symbol, false)),- (24, 23, 7),+ (24, 24, 7), "the basemap layer set", ); assert_eq!(@@ -1367,12 +1368,13 @@ mod tests { fn the_flat_style_agrees_with_basemap_json() { let root = basemap(); for layer in layers() {- // `roads-carriageway` is an app-only layer: it draws a road's surface with its lane- // markings painted on, which the authored `basemap.json` has no concept of. Its width,- // colour and lane semantics are all deliberately its own, so — like transit's width —- // it is pinned by its own test (`the_carriageway_is_gated_and_sized_by_the_lane`)- // rather than cross-checked here.- if layer.id == "roads-carriageway" {+ // A carriageway layer is app-only: it draws a road's surface with its lane markings+ // painted on, which the authored `basemap.json` has no concept of. Its width, colour+ // and lane semantics are all deliberately its own, so — like transit's width — it is+ // pinned by its own test (`the_carriageway_is_gated_and_sized_by_the_lane`) rather+ // than cross-checked here. `junction-connector` is the same surface continued through+ // an intersection and has no authored counterpart either.+ if layer.carriageway { continue; } let authored = authored_layer(&root, &layer.authored);@@ -1602,7 +1604,7 @@ mod tests { } } - /// The road carriageway: `roads-carriageway` is the one layer drawn as a road surface, it only+ /// The road carriageway: `roads-carriageway` is the road layer drawn as a surface, it only /// appears once the camera is close enough to make lane markings legible, and its width ramp is /// **one lane** rather than a whole road — the renderer multiplies by the feature's lane count, /// so a two-lane street and an eight-lane motorway come off the same ramp at their true widths.@@ -1610,10 +1612,21 @@ mod tests { fn the_carriageway_is_gated_and_sized_by_the_lane() { let layer = find("roads-carriageway"); assert!(layer.carriageway, "roads-carriageway must draw as a surface");+ // Two layers draw a surface now. `road_carriageway_layer` no longer picks between them by+ // declaration order — it names the roads source — so this list is pinning *draw order*,+ // not the gate: the connector has to come second, or the road surface paints over the+ // connector at the mouth of the junction and clips its edge lines short of the kerb. assert_eq!(- layers().iter().filter(|l| l.carriageway).count(),- 1,- "exactly one layer draws road surfaces",+ layers().iter().filter(|l| l.carriageway).map(|l| l.id.as_str()).collect::<Vec<_>>(),+ vec!["roads-carriageway", "junction-connector"],+ "the layers drawn as road surfaces, in draw order",+ );+ // And the gate really is order-independent: it still answers the road layer when the+ // connector is put first, which is what `turn_arrows_are_gated_by_the_road_lane_layer`+ // relies on and what the flag alone could not promise.+ assert_eq!(+ super::super::road_carriageway_layer(layers()).map(|l| l.id.as_str()),+ Some("roads-carriageway"), ); assert_eq!(layer.min_zoom, 16, "the dense lane detail is gated to high zoom"); assert!(!layer.draws_at(15), "no carriageway at z15");@@ -1622,6 +1635,21 @@ mod tests { // these, which is what makes the shader's marking widths land where a driver expects them. assert!(layer.width.at(16.0) > 0.0, "a lane has width at z16"); assert!(layer.width.at(20.0) > layer.width.at(16.0), "and it widens zooming in");+ // And it keeps growing to the top of the range, which is the one part of this ramp that is+ // not a styling choice. `Ramp::at` clamps above the last stop, so a ramp ending at z20+ // freezes the lane at 40 dp while the world keeps doubling — the painted lane's *ground*+ // width then halves per zoom, reaching a quarter of a lane by z22, and `MAX_ZOOM` is 22.+ // That put the baked connector offset, which is a fixed projected size, 4x outside the+ // road surface at full zoom. The z22 stop continues the base-2 progression so a lane holds+ // one true ground width from z20 up; drop it and the cliff comes back.+ for zoom in [20.0_f64, 21.0] {+ let (here, next) = (layer.width.at(zoom), layer.width.at(zoom + 1.0));+ assert!(+ (f64::from(next / here) - 2.0).abs() < 1e-6,+ "a lane must double from z{zoom} to z{}: {here} then {next}",+ zoom + 1.0,+ );+ } // The asphalt has to be darker than the off-white the shader paints its markings in, which // is why this is not the white `roads-major` fill it draws over. let road = find("roads-major");@@ -1629,6 +1657,36 @@ mod tests { assert_ne!(layer.dark, road.dark); } + /// A connector is the carriageway continued through a junction, so it has to be the same+ /// asphalt at the same width over the same zoom range.+ ///+ /// Divergence here does not fail anything, it just looks wrong: a connector a shade off the+ /// road it joins draws a visible seam across every intersection, and one off the road's lane+ /// width steps in or out at the kerb. Cheaper to pin than to notice on a screenshot.+ #[test]+ fn a_connector_matches_the_carriageway_it_continues() {+ let (road, connector) = (find("roads-carriageway"), find("junction-connector"));+ assert_eq!(connector.light, road.light, "a connector is the same asphalt");+ assert_eq!(connector.dark, road.dark);+ for zoom in [16.0, 17.5, 18.0, 20.0, 22.0] {+ let (a, b) = (connector.width.at(zoom), road.width.at(zoom));+ assert!(+ (a - b).abs() < 1e-6,+ "a connector is one lane of the road's own width at z{zoom}: {a} vs {b}",+ );+ }+ // The same floor as the road, which is the point: a connector one zoom later than the+ // carriageway it joins would leave every junction as a hole in the road surface for a+ // whole zoom level, and one zoom earlier would hang it in the air with nothing to join.+ // The tiler's junction layer is emitted from this zoom to match.+ assert_eq!(connector.min_zoom, road.min_zoom, "a connector appears with its road");+ assert_eq!(connector.max_zoom, road.max_zoom, "and leaves with it");+ // No kind or flag filter: the junction layer carries connectors and nothing else, so+ // there is nothing to narrow it to.+ assert!(connector.kind_ids.is_empty());+ assert_eq!((connector.require_flags, connector.forbid_flags), (0, 0));+ }+ /// The `kind` values an authored filter admits, or empty for "any of them". /// /// The four shapes `basemap.json` uses on its `fill` layers. A `$type` filter restricts
library/map/src/main/rust/src/tile/geometry.rs
diff --git a/library/map/src/main/rust/src/tile/geometry.rs b/library/map/src/main/rust/src/tile/geometry.rsindex c60046ace6..983bc4fa09 100644--- a/library/map/src/main/rust/src/tile/geometry.rs+++ b/library/map/src/main/rust/src/tile/geometry.rs@@ -16,7 +16,9 @@ use crate::tile::arrow::{self, ArrowInstance}; use crate::tile::symbol; use crate::tile::select::ANCESTOR_DEPTH; use tilecodec::mamaps::body::{Body, GEOM_LINE, GEOM_POINT, GEOM_POLYGON};-use tilecodec::mamaps::dict::{LAYER_BUILDINGS, LAYER_EARTH, LAYER_ROADS, LAYER_TRAFFIC};+use tilecodec::mamaps::dict::{+ LAYER_BUILDINGS, LAYER_EARTH, LAYER_JUNCTION, LAYER_ROADS, LAYER_TRAFFIC,+}; /// The shallowest zoom the traffic overlay is tessellated at. ///@@ -166,6 +168,16 @@ pub struct ShapedLabel { /// rather than one per feature or one per tile: those three are push constants, so features that /// agree on all of them can share a draw, and features that disagree cannot. Most roads in a tile /// are ordinary two-way streets, so the split is usually into very few meshes.+///+/// # Lane connectors ride this too+///+/// A connector through a junction is the same asphalt with the same markings — it is the+/// carriageway continued across the intersection — so it is this type on the same pipeline in the+/// same pass, not a fourth mesh kind with a fourth pass. It differs only in what it pushes:+/// [`lanes`](Self::lanes) 1 and [`oneway`](Self::oneway) set, always, because a connector is one+/// lane of traffic in one direction whatever the feature carries. Its own+/// [`layer_index`](Self::layer_index) keeps it in its own mesh, so a connector never shares a draw+/// with a road. pub struct CarriagewayMesh { /// Index into the style's layer list, for the asphalt colour and the lane width ramp. pub layer_index: usize,@@ -255,6 +267,10 @@ pub struct TileMesh { /// The road carriageways in this tile: the road surfaces the lane markings are painted on, /// one mesh per distinct set of road-shape push inputs. Empty below the carriageway layer's /// zoom window, and on any tile with no roads.+ ///+ /// Also carries the lane connectors through junctions, which are the same surface continued+ /// across an intersection — see [`CarriagewayMesh`]. Empty of those on every tile that has no+ /// junction layer, which today is all of them. pub carriageways: Vec<CarriagewayMesh>, /// The tile's driving convention says the line between opposing streams is yellow (the /// Americas) rather than white — `Push.misc.z`.@@ -441,21 +457,33 @@ pub fn build_toggled( if feature.geom_type != GEOM_LINE { continue; }- let oneway = feature.is_oneway();- // Most roads carry no `lanes` tag at all, and a zero lane count would push- // a zero width and draw nothing. OSM's own reading of an untagged road is- // one lane each way, which is also what makes the centre line appear.- let lanes = match feature.lane_count {- 0 => {- if oneway {- 1- } else {- 2+ // A lane connector is one lane of traffic through a junction, by+ // construction: the tiler emits one feature per connector, already+ // sampled. So its shape is not read off the feature the way a road's is.+ // One-way because a single stream has no opposing direction to be+ // separated from, which is what suppresses the centre line; the split is+ // then meaningless, exactly as it is on a one-way road.+ let (lanes, oneway, split) = if layer.source_layer_id == LAYER_JUNCTION {+ (1, true, 0.0)+ } else {+ let oneway = feature.is_oneway();+ // Most roads carry no `lanes` tag at all, and a zero lane count would+ // push a zero width and draw nothing. OSM's own reading of an untagged+ // road is one lane each way, which is also what makes the centre line+ // appear.+ let lanes = match feature.lane_count {+ 0 => {+ if oneway {+ 1+ } else {+ 2+ } }- }- count => count,+ count => count,+ };+ let split = split_t(tile, layer, feature_index, lanes, left_hand);+ (lanes, oneway, split) };- let split = split_t(tile, layer, feature_index, lanes, left_hand); let at = match carriageways.iter().position(|m| { m.layer_index == index && m.lanes == lanes@@ -1451,6 +1479,151 @@ mod tests { ); } + // --- lane connectors through junctions ---------------------------------++ /// A body of straight lane connectors on the junction layer, each an already-sampled polyline+ /// of three points — the shape the tiler emits, with the bezier sampled on its side.+ ///+ /// The features deliberately carry a lane count of six and no one-way flag, neither of which a+ /// connector can actually be. A connector's shape is fixed by what it *is*, so the tests below+ /// prove the renderer imposes that rather than reading it off the feature.+ fn junction_body(count: usize) -> Body {+ use tilecodec::mamaps::body::{Feature, Layer as BodyLayer, Part, NAME_NONE, WINDING_OUTER};+ let mut body = Body::new(4096);+ let mut source = BodyLayer::new(LAYER_JUNCTION);+ for i in 0..count {+ let parts_offset = source.parts.len() as u32;+ source.parts.push(Part {+ coord_start: source.coords.len() as u32,+ point_count: 3,+ winding: WINDING_OUTER,+ });+ let y = 100 + i as i16 * 100;+ source.coords.extend_from_slice(&[(0, y), (500, y), (1000, y + 200)]);+ source.features.push(Feature {+ kind: 0,+ kind_detail: 0,+ geom_type: GEOM_LINE,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 6,+ });+ }+ body.layers.push(source);+ body+ }++ /// The `junction-connector` layer as a one-layer slice, matching [`carriageway_only`].+ fn connector_only() -> &'static [Layer] {+ let all = style::layers();+ let at = all.iter().position(|l| l.id == "junction-connector").expect("the connector layer");+ all.get(at..=at).expect("a one-layer slice")+ }++ /// A connector goes through the carriageway path as one lane of one-way traffic, whatever the+ /// feature carries.+ ///+ /// Both halves matter to `road_surface.frag`, which reads them straight out of the push block.+ /// One lane leaves no interior lane boundary, so no divider is dashed down the middle of it;+ /// one-way suppresses the centre line, which is the point — a single stream of traffic has no+ /// opposing direction to be separated from, and a connector painted with a centre line reads+ /// as a two-way road through the junction.+ ///+ /// Twelve of them, which is what a plain 4-arm crossroads emits (4 approaches x 3 legal exits,+ /// no U-turn). They must collapse to **one** draw: every connector agrees on all three push+ /// inputs by construction, so the mesh key coalesces them however many there are. That is what+ /// keeps a dense tile to one extra draw call rather than one per connector, and it is the+ /// property that would silently regress if a connector ever gained a per-feature shape.+ #[test]+ fn a_connector_is_one_lane_of_one_way_traffic_whatever_the_feature_carries() {+ let mesh = build(&junction_body(12), connector_only(), 17, 0, 0, false);+ assert_eq!(mesh.carriageways.len(), 1, "a whole crossroads is one draw, not twelve");+ let connector = &mesh.carriageways[0];+ assert_eq!(connector.lanes, 1, "one lane wide, not the six the feature claims");+ assert!(connector.oneway, "and one-way, so no centre line is painted down it");+ assert!(connector.split.abs() < 1e-6, "the split is meaningless on a one-way");+ assert!(mesh.meshes.is_empty(), "a connector is not a stroked layer mesh");++ // The ribbon vertex, so the existing pipeline and shaders draw it with no new format.+ assert_eq!(connector.vertices.len() % ribbon::FLOATS_PER_VERTEX, 0);+ assert_eq!(connector.indices.len() % 3, 0);+ let vertex_count = (connector.vertices.len() / ribbon::FLOATS_PER_VERTEX) as u32;+ assert_eq!(vertex_count, 72, "twelve connectors, three points each, two vertices a point");+ assert!(connector.indices.iter().all(|&i| i < vertex_count), "an index is out of range");+ assert!(connector.vertices.iter().all(|f| f.is_finite()));+ }++ /// Roads and connectors never share a draw, and the connector draws second.+ ///+ /// They disagree on every push input, so they could not share one anyway. The order is the+ /// point: a connector overlaps the road surface at the mouth of the junction, and the road+ /// painting over the connector would leave the connector's edge lines cut off short of where+ /// they meet the kerb.+ #[test]+ fn connectors_and_roads_are_separate_draws_with_the_connector_over_the_road() {+ let layers = style::layers();+ let roads = layers.iter().position(|l| l.id == "roads-carriageway").expect("roads");+ let connectors =+ layers.iter().position(|l| l.id == "junction-connector").expect("connectors");+ assert!(roads < connectors, "layer order is draw order, and the connector goes on top");++ let mut body = carriageway_body(&[(4, false)]);+ body.layers.extend(junction_body(1).layers);+ let mesh = build(&body, layers, 16, 0, 0, false);+ assert_eq!(+ mesh.carriageways+ .iter()+ .map(|c| (c.layer_index, c.lanes, c.oneway))+ .collect::<Vec<_>>(),+ vec![(roads, 4, false), (connectors, 1, true)],+ );+ }++ /// **The only path that exists today.** No archive carries a junction layer, and none will+ /// until the tiler writes one, so the connector layer has to cost exactly nothing on every tile+ /// there is: no mesh, no vertex, no draw, and no road drawn any differently.+ ///+ /// Asserted as a byte-equality against the carriageway layer on its own, rather than as "no+ /// connector mesh appeared". The weaker form would still pass if the connector layer had+ /// quietly changed a road's lane count or split on its way past, which is the failure that+ /// would actually reach a screen.+ #[test]+ fn a_tile_with_no_junction_layer_is_untouched_by_the_connector_layer() {+ let layers = style::layers();+ let connectors =+ layers.iter().position(|l| l.id == "junction-connector").expect("connectors");++ // Ordinary roads at the carriageway zoom, and nothing else — a v7 archive.+ let body = carriageway_body(&[(4, false), (3, true), (0, false)]);+ assert!(body.layer(LAYER_JUNCTION).is_none(), "the fixture has no junction layer");++ let full = build(&body, layers, 16, 0, 0, false);+ let roads_only = build(&body, carriageway_only(), 16, 0, 0, false);+ assert_eq!(full.carriageways.len(), roads_only.carriageways.len(), "an extra draw");+ for (a, b) in full.carriageways.iter().zip(&roads_only.carriageways) {+ assert_ne!(a.layer_index, connectors, "a connector mesh out of thin air");+ assert_eq!(a.lanes, b.lanes);+ assert_eq!(a.oneway, b.oneway);+ assert!((a.split - b.split).abs() < 1e-6, "split {} became {}", b.split, a.split);+ assert_eq!(a.vertices, b.vertices, "the road geometry is byte-identical");+ assert_eq!(a.indices, b.indices);+ }++ // And the published tile, which is the real thing and carries no junction layer either.+ let published = build(&real(), layers, 11, 339, 770, false);+ assert!(published.carriageways.is_empty(), "z11 is below the carriageway floor anyway");+ assert!(+ !published.meshes.iter().any(|m| m.layer_index == connectors),+ "the connector layer must not draw a stroked mesh either",+ );+ }+ /// Turn arrows are produced from the archive's turn-lane table at high zoom and gated off /// below it: a road with `turn:lanes` yields one arrow per marked lane, pointing along the /// road, and none when the tile is too coarse.
library/map/src/main/rust/src/vulkan/renderer.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer.rs b/library/map/src/main/rust/src/vulkan/renderer.rsindex 43509d62f8..00a0f6b3e5 100644--- a/library/map/src/main/rust/src/vulkan/renderer.rs+++ b/library/map/src/main/rust/src/vulkan/renderer.rs@@ -55,10 +55,11 @@ struct ResidentTile { /// Uploaded with the rest of the tile; coloured per frame from the pushed table so a new /// speed reading never re-uploads or re-tessellates them. traffic: Vec<TrafficBuffers>,- /// The road carriageways in this tile, one per distinct set of road-shape push inputs. Drawn- /// in their own pass ([`Renderer::record_carriageways`]) through the ribbon pipeline, not the- /// flat layer loop, because the vertex format and three of the push slots differ. Empty below- /// the carriageway layer's zoom window.+ /// The road carriageways in this tile, one per distinct set of road-shape push inputs, plus+ /// the lane connectors through its junctions. Drawn in their own pass+ /// ([`Renderer::record_carriageways`]) through the ribbon pipeline, not the flat layer loop,+ /// because the vertex format and three of the push slots differ. Empty below the carriageway+ /// layer's zoom window. carriageways: Vec<CarriagewayBuffers>, /// The tile's driving convention paints the line between opposing streams yellow rather than /// white. A property of the tile, not of a road, so it rides here and not on each mesh.@@ -1693,6 +1694,13 @@ impl Renderer { /// painted on by `road_surface.frag` as a function of the across-road coordinate rather than /// drawn as geometry. ///+ /// The lane connectors through junctions draw here too, and are why this loop needs no+ /// connector-specific branch: a connector is the same asphalt on the same pipeline, differing+ /// only in the lane count and one-way flag it pushes, both of which already ride on the mesh.+ /// It belongs in this pass rather than beside it because it is carriageway — it has to sit+ /// under the buildings and the deferred symbols exactly as the roads it joins do, and a second+ /// pass could only get that right by accident.+ /// /// Its own pass rather than a branch of the layer loop because the ribbon is a different vertex /// format on a different pipeline, and because three of its push slots mean something else — /// the `Push` doc comment in [`crate::vulkan::pipeline`] is the contract this fills in.
library/map/src/main/rust/style/basemap.flat.json
diff --git a/library/map/src/main/rust/style/basemap.flat.json b/library/map/src/main/rust/style/basemap.flat.jsonindex 10ae8c0c88..e20731f659 100644--- a/library/map/src/main/rust/style/basemap.flat.json+++ b/library/map/src/main/rust/style/basemap.flat.json@@ -608,7 +608,22 @@ "width": { "interpolate": "exponential", "base": 2.0,- "stops": [[16, 3.0], [18, 11.0], [20, 40.0]]+ "stops": [[16, 3.0], [18, 11.0], [20, 40.0], [22, 160.0]]+ }+ },+ {+ "id": "junction-connector",+ "authored": "roads_major",+ "source": "junction",+ "type": "line",+ "carriageway": true,+ "minzoom": 16,+ "light": "#c8ccd3",+ "dark": "#3a3f47",+ "width": {+ "interpolate": "exponential",+ "base": 2.0,+ "stops": [[16, 3.0], [18, 11.0], [20, 40.0], [22, 160.0]] } }, {
library/tilecodec/src/main/rust/src/mamaps/dict.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/dict.rs b/library/tilecodec/src/main/rust/src/mamaps/dict.rsindex e2176a6195..5d588afb96 100644--- a/library/tilecodec/src/main/rust/src/mamaps/dict.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/dict.rs@@ -22,7 +22,7 @@ //! //! # Size //!-//! Eleven layers, ~108 kinds and 41 details, at a length byte each: under 2 KiB as measured,+//! Twelve layers, ~108 kinds and 41 details, at a length byte each: under 2 KiB as measured, //! which is what lets the header, the dictionary and the root index share one 16 KiB opening //! read. @@ -37,11 +37,12 @@ pub const NONE: u16 = 0; /// The layers this format carries, in draw order. ///-/// A layer's id **is** its index here. Eleven: the seven the style draws, plus `places`-/// (labels), `poi` (icons), `transit` (reserved by v2; populated when transit lands) and+/// A layer's id **is** its index here. Twelve: the seven the style draws, plus `places`+/// (labels), `poi` (icons), `transit` (reserved by v2; populated when transit lands), /// `traffic` (v4: one line per drivable component segment, recoloured live from a pushed-/// id→speed table — geometry from the v6 routing graph, not the basemap). `u8` ids fit with-/// room to spare.+/// id→speed table — geometry from the v6 routing graph, not the basemap) and `junction`+/// (v7: one line per lane connector through an intersection, also from the routing graph).+/// `u8` ids fit with room to spare. pub const LAYERS: &[&str] = &[ "earth", "water",@@ -54,6 +55,7 @@ pub const LAYERS: &[&str] = &[ "poi", "transit", "traffic",+ "junction", ]; pub const LAYER_EARTH: u8 = 0;@@ -71,6 +73,17 @@ pub const LAYER_TRANSIT: u8 = 9; /// recolour it from a live id→speed push. Excluded from the basemap style: it draws only /// when the traffic overlay is enabled. pub const LAYER_TRAFFIC: u8 = 10;+/// v7. One `GEOM_LINE` feature per **lane connector** through an intersection: the sampled+/// centreline a single lane follows from an approach to an exit, built from the same v6+/// routing graph `traffic` reads. Excluded from the basemap style — it draws only where the+/// carriageway surface does, which is why its `min_zoom` is deep.+///+/// Added inside v7 rather than under a version bump of its own. Appending to [`LAYERS`]+/// changes the dictionary every archive carries and [`Dictionary::check_matches_schema`]+/// compares the whole table on open, so this is only safe because v7 was committed but never+/// built or shipped — there is no deployed reader to refuse. Any layer appended after a v7+/// archive exists must bump the format, the way v4 did for `traffic`.+pub const LAYER_JUNCTION: u8 = 11; /// Every `kind` value the schema can emit, id 1 upward. Index 0 is [`NONE`]. ///@@ -465,7 +478,8 @@ mod tests { assert_eq!(d.layer_name(LAYER_POI), Some("poi"), "v2's icon layer"); assert_eq!(d.layer_name(LAYER_TRANSIT), Some("transit"), "v2 reserves transit"); assert_eq!(d.layer_name(LAYER_TRAFFIC), Some("traffic"), "v4's live traffic layer");- assert_eq!(d.layer_name(11), None, "past the table");+ assert_eq!(d.layer_name(LAYER_JUNCTION), Some("junction"), "v7's lane connectors");+ assert_eq!(d.layer_name(12), None, "past the table"); } /// A duplicate would give one value two ids, so half the features carrying it would filter
library/tilecodec/src/main/rust/src/mamaps/header.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header.rs b/library/tilecodec/src/main/rust/src/mamaps/header.rsindex 975a204286..4ca8b7b77f 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header.rs@@ -26,6 +26,15 @@ pub const MAGIC: &[u8; 7] = b"MAMAPS\0"; /// unchanged. The bump is forced twice over: an older reader rejects both an unknown body flag and /// an unknown feature flag bit, so a v7 archive is a clean rejection rather than a wrong map. ///+/// v7 also adds the `junction` layer (id 11) to [`dict::LAYERS`](super::dict::LAYERS): one+/// `GEOM_LINE` feature per lane connector through an intersection, built from the same v6 routing+/// graph `traffic` reads. **That was only free because it landed inside v7's window.** Appending a+/// layer normally forces a bump of its own — v4 did exactly this for `traffic` — because `read`'s+/// `check_matches_schema` compares the whole dictionary on open, so every existing archive stops+/// opening. It cost nothing here only because v7 was committed but never built or shipped, leaving+/// no deployed reader to reject. The window shuts the moment a v7 archive exists: any layer added+/// after that costs v8.+/// /// v6 adds two optional trailing body sections behind new body flags: a per-building **S3DB /// attribute table** (`BODY_FLAG_BUILDING_TABLE`, dense-parallel to the `buildings` layer — /// heights, roof shape/height/direction/orientation and wall/roof colours for 3D extrusion) and a
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 9109b773d6..db5f015e56 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -273,7 +273,13 @@ import androidx.compose.material3.LocalContentColor import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.graphics.vector.PathBuilder+import androidx.compose.ui.graphics.vector.path+import androidx.compose.ui.unit.dp import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey @@ -1050,6 +1056,152 @@ fun IconRoundaboutLeft(modifier: Modifier = Modifier, tint: Color = LocalContent fun IconRoundaboutRight(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.RoundaboutRight, "Roundabout", modifier, tint) +// --- Lane guidance ---+// A real OSM `turn:lanes` lane can permit several movements at once. Road+// signage draws that as one shaft carrying one head per permitted direction,+// so these are built here rather than composed from the single-turn glyphs+// above: stacking two full-size arrows in the same cell reads as a smudge.+// Material has no combined-lane glyphs, so the paths are authored directly.++private const val LANE_SHAFT_X = 12f+private const val LANE_STROKE_WIDTH = 2.2f++/** Where the branches leave the shaft. Every branch starts here so they fan out together. */+private const val LANE_FORK_Y = 15f++private enum class LaneBranch { LEFT, SLIGHT_LEFT, RIGHT, SLIGHT_RIGHT }++private fun ImageVector.Builder.laneStroke(pathBuilder: PathBuilder.() -> Unit) =+ path(+ stroke = SolidColor(Color.Black),+ strokeLineWidth = LANE_STROKE_WIDTH,+ strokeLineCap = StrokeCap.Round,+ strokeLineJoin = StrokeJoin.Round,+ pathBuilder = pathBuilder,+ )++/** Arrowhead as a filled triangle: the tip plus the two base corners. */+private fun ImageVector.Builder.laneHead(+ tipX: Float,+ tipY: Float,+ baseAx: Float,+ baseAy: Float,+ baseBx: Float,+ baseBy: Float,+) = path(fill = SolidColor(Color.Black)) {+ moveTo(tipX, tipY)+ lineTo(baseAx, baseAy)+ lineTo(baseBx, baseBy)+ close()+}++private fun laneVector(+ name: String,+ through: Boolean,+ branches: List<LaneBranch>,+): ImageVector {+ val builder = ImageVector.Builder(+ name = name,+ defaultWidth = 24.dp,+ defaultHeight = 24.dp,+ viewportWidth = 24f,+ viewportHeight = 24f,+ )+ // A through lane runs the shaft up to its own head; otherwise it stops at+ // the fork so the branches are the only thing carrying a head.+ builder.laneStroke {+ moveTo(LANE_SHAFT_X, 21f)+ verticalLineTo(if (through) 7f else LANE_FORK_Y)+ }+ if (through) builder.laneHead(LANE_SHAFT_X, 2f, 15.2f, 7.4f, 8.8f, 7.4f)+ branches.forEach { branch ->+ when (branch) {+ LaneBranch.RIGHT -> {+ builder.laneStroke {+ moveTo(LANE_SHAFT_X, LANE_FORK_Y)+ quadTo(LANE_SHAFT_X, 9.5f, 18f, 9.5f)+ }+ builder.laneHead(22f, 9.5f, 18f, 6.5f, 18f, 12.5f)+ }+ LaneBranch.LEFT -> {+ builder.laneStroke {+ moveTo(LANE_SHAFT_X, LANE_FORK_Y)+ quadTo(LANE_SHAFT_X, 9.5f, 6f, 9.5f)+ }+ builder.laneHead(2f, 9.5f, 6f, 12.5f, 6f, 6.5f)+ }+ LaneBranch.SLIGHT_RIGHT -> {+ builder.laneStroke {+ moveTo(LANE_SHAFT_X, LANE_FORK_Y)+ quadTo(LANE_SHAFT_X, 10.5f, 16.5f, 7.5f)+ }+ builder.laneHead(20.2f, 5f, 18.2f, 10f, 14.8f, 5f)+ }+ LaneBranch.SLIGHT_LEFT -> {+ builder.laneStroke {+ moveTo(LANE_SHAFT_X, LANE_FORK_Y)+ quadTo(LANE_SHAFT_X, 10.5f, 7.5f, 7.5f)+ }+ builder.laneHead(3.8f, 5f, 5.8f, 10f, 9.2f, 5f)+ }+ }+ }+ return builder.build()+}++private val LaneThroughLeft by lazy {+ laneVector("LaneThroughLeft", through = true, branches = listOf(LaneBranch.LEFT))+}+private val LaneThroughRight by lazy {+ laneVector("LaneThroughRight", through = true, branches = listOf(LaneBranch.RIGHT))+}+private val LaneThroughSlightLeft by lazy {+ laneVector("LaneThroughSlightLeft", through = true, branches = listOf(LaneBranch.SLIGHT_LEFT))+}+private val LaneThroughSlightRight by lazy {+ laneVector("LaneThroughSlightRight", through = true, branches = listOf(LaneBranch.SLIGHT_RIGHT))+}+private val LaneLeftRight by lazy {+ laneVector("LaneLeftRight", through = false, branches = listOf(LaneBranch.LEFT, LaneBranch.RIGHT))+}+private val LaneThroughLeftRight by lazy {+ laneVector(+ "LaneThroughLeftRight",+ through = true,+ branches = listOf(LaneBranch.LEFT, LaneBranch.RIGHT),+ )+}++@Composable+fun IconLaneThroughLeft(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(LaneThroughLeft, "Straight or left lane", modifier, tint)++@Composable+fun IconLaneThroughRight(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(LaneThroughRight, "Straight or right lane", modifier, tint)++@Composable+fun IconLaneThroughSlightLeft(+ modifier: Modifier = Modifier,+ tint: Color = LocalContentColor.current,+) = AppIcon(LaneThroughSlightLeft, "Straight or slight left lane", modifier, tint)++@Composable+fun IconLaneThroughSlightRight(+ modifier: Modifier = Modifier,+ tint: Color = LocalContentColor.current,+) = AppIcon(LaneThroughSlightRight, "Straight or slight right lane", modifier, tint)++@Composable+fun IconLaneLeftRight(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(LaneLeftRight, "Left or right lane", modifier, tint)++@Composable+fun IconLaneThroughLeftRight(+ modifier: Modifier = Modifier,+ tint: Color = LocalContentColor.current,+) = AppIcon(LaneThroughLeftRight, "Straight, left or right lane", modifier, tint)+ // --- PDF editor tools --- @Composable fun IconSelect(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =
maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.ktindex 98dcc08d5e..a2765148f2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.kt@@ -6,20 +6,30 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size-import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconLaneLeftRight+import com.vayunmathur.library.ui.IconLaneThroughLeft+import com.vayunmathur.library.ui.IconLaneThroughLeftRight+import com.vayunmathur.library.ui.IconLaneThroughRight+import com.vayunmathur.library.ui.IconLaneThroughSlightLeft+import com.vayunmathur.library.ui.IconLaneThroughSlightRight+import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.maps.ui.iconContent import com.vayunmathur.maps.util.RouteService+import com.vayunmathur.maps.util.RouteService.API.Maneuver /**- * Lane-guidance strip (Vela's `LaneDiagram`). Renders one arrow per available+ * Lane-guidance strip (Vela's `LaneDiagram`). Renders one cell per available * turn lane at the upcoming junction, derived by the Rust router (P5a). Lanes * that lead onto the taken route are highlighted; the rest are dimmed. *+ * A lane permitting several movements gets a single combined glyph — one shaft+ * with a head per direction, the way road signage draws it.+ * * Renders nothing when there is no lane data (single continuation, or a router * that couldn't resolve the junction). */@@ -31,23 +41,61 @@ fun LaneGuidance( inactiveColor: Color = Color.White.copy(alpha = 0.35f), ) { if (lanes.isEmpty()) return+ // One literal drives both the cell and the glyph inside it, so they cannot+ // drift apart.+ val cell = 26.dp Box( modifier- .background(Color.Black.copy(alpha = 0.25f), RoundedCornerShape(8.dp))+ .background(Color.Black.copy(alpha = 0.25f), MaterialTheme.shapes.small) .padding(horizontal = 8.dp, vertical = 4.dp), ) { Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) { lanes.forEach { lane -> val tint = if (lane.active) activeColor else inactiveColor- // A real OSM lane can offer several turns (e.g. through+right):- // overlay each direction's arrow in the lane cell. A single- // direction renders exactly as before.- Box(Modifier.size(26.dp), contentAlignment = Alignment.Center) {- lane.directions.forEach { dir ->- dir.iconContent()?.invoke(Modifier.size(26.dp), tint)- }+ Box(Modifier.size(cell), contentAlignment = Alignment.Center) {+ val glyph = combinedLaneIcon(lane.directions)+ ?: lane.directions.dominant()?.iconContent()+ glyph?.invoke(Modifier.size(cell), tint) } } } } }++/**+ * The single combined glyph for a lane permitting several movements, or null+ * when there is no combined glyph for this set and the caller should fall back+ * to one arrow. Covers the combinations that actually occur in OSM+ * `turn:lanes`.+ */+private fun combinedLaneIcon(+ directions: List<Maneuver>,+): (@Composable (Modifier, Color) -> Unit)? {+ val set = directions.toSet()+ if (set.size < 2) return null+ val through = Maneuver.STRAIGHT in set+ val turns = set - Maneuver.STRAIGHT+ return when {+ through && turns == setOf(Maneuver.TURN_LEFT) ->+ { m, t -> IconLaneThroughLeft(m, t) }+ through && turns == setOf(Maneuver.TURN_RIGHT) ->+ { m, t -> IconLaneThroughRight(m, t) }+ through && turns == setOf(Maneuver.TURN_SLIGHT_LEFT) ->+ { m, t -> IconLaneThroughSlightLeft(m, t) }+ through && turns == setOf(Maneuver.TURN_SLIGHT_RIGHT) ->+ { m, t -> IconLaneThroughSlightRight(m, t) }+ through && turns == setOf(Maneuver.TURN_LEFT, Maneuver.TURN_RIGHT) ->+ { m, t -> IconLaneThroughLeftRight(m, t) }+ !through && turns == setOf(Maneuver.TURN_LEFT, Maneuver.TURN_RIGHT) ->+ { m, t -> IconLaneLeftRight(m, t) }+ else -> null+ }+}++/**+ * The one movement to draw for a lane with no combined glyph. Going straight on+ * dominates when it is offered; otherwise take the leftmost turn, which is the+ * order the router packs them in.+ */+private fun List<Maneuver>.dominant(): Maneuver? =+ firstOrNull { it == Maneuver.STRAIGHT } ?: firstOrNull()
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex 947fd6cb31..a62a7c6068 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -138,6 +138,8 @@ pub struct Stats { pub transit_routes: u64, /// Drivable component segments emitted into the `traffic` layer from the v6 routing graph. pub traffic_segments: u64,+ /// Lane connectors emitted into the `junction` layer from the same graph.+ pub junction_connectors: u64, /// Road ways whose `min_zoom` was pulled shallower to match their corridor. pub corridor_promotions: u64, pub rings: RingStats,@@ -825,6 +827,13 @@ pub fn extract( stats.traffic_segments = schema::traffic::stream_graph(dir, &mut sink)?; stats.features += stats.traffic_segments; println!(" {} drivable component segment(s)", stats.traffic_segments);+ // The `junction` layer rides the same graph: a lane connector is built from the junction+ // node's own incident edges, so there is nothing to read that the traffic pass did not+ // already need. `conventions` decides which side of a road the direction of travel sits+ // on, and is borrowed here because it is moved into the store below.+ stats.junction_connectors = schema::junction::stream_junctions(dir, &conventions, &mut sink)?;+ stats.features += stats.junction_connectors;+ println!(" {} lane connector(s)", stats.junction_connectors); } let store = sink.finish(spill_path)?; let store = store.with_conventions(conventions);
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex a8a10c0e69..52083363e2 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -265,15 +265,18 @@ fn run( "no --transit-routes given, so `transit` is empty; its lines come from GTFS, not the .pbf" ); }- // The same asymmetry once more, for the traffic layer's graph source: the flag without the- // layer is a mistake worth stopping for, the layer without the flag is a legitimate build of- // an archive with no traffic overlay.- if run.graph.is_some() && !layers.traffic {- return Err("--graph was given but the traffic layer is not selected".to_string());+ // The same asymmetry once more, for the two layers the routing graph feeds: the flag without+ // either layer is a mistake worth stopping for, a layer without the flag is a legitimate build+ // of an archive with no traffic overlay and no lane connectors.+ if run.graph.is_some() && !layers.traffic && !layers.junction {+ return Err(+ "--graph was given but neither the traffic nor the junction layer is selected"+ .to_string(),+ ); }- if run.graph.is_none() && layers.traffic {+ if run.graph.is_none() && (layers.traffic || layers.junction) { println!(- "no --graph given, so `traffic` is empty; its lines come from the v6 routing graph, not the .pbf"+ "no --graph given, so `traffic` and `junction` are empty; their lines come from the v6 routing graph, not the .pbf" ); } let provenance = store::Provenance::of(@@ -332,6 +335,12 @@ fn run( stats.traffic_segments, ); }+ if stats.junction_connectors > 0 {+ println!(+ " including {} lane connector(s) for the junction layer",+ stats.junction_connectors,+ );+ } if stats.corridor_promotions > 0 { println!( " {} road way(s) pulled to their corridor's zoom",@@ -535,6 +544,11 @@ fn derive_build_id( h = h.wrapping_mul(0x100_0000_01b3); } };+ // Revision 13: a `junction` layer (id 11) is baked from the same v6 routing graph — one line+ // per lane connector through an intersection. Folded into `.mamaps` v7 rather than bumping the+ // format, because no v7 archive has been built, but the layer set moves and the dictionary+ // every archive carries gains an entry, so a warm cache must miss.+ // // Revision 12: `.mamaps` v4. A `traffic` layer (id 10) is baked from the v6 routing graph — // one line per drivable component segment, each carrying its packed `component_id` in the // body id table — and `FORMAT_VERSION` bumps 3->4. The layer set and the format both move, so@@ -582,7 +596,7 @@ fn derive_build_id( // Revision 3: road `min_zoom` is decided per corridor (`corridor`), and place // `kind_detail` carries the reference basemap's 0-15 population rank rather than a // three-step one (`schema::places::rank_of`).- eat(b"mamaps_build/12");+ eat(b"mamaps_build/13"); eat(input.to_string_lossy().as_bytes()); if let Ok(meta) = std::fs::metadata(input) { eat(&meta.len().to_le_bytes());@@ -604,12 +618,14 @@ fn derive_build_id( u8::from(layers.poi), u8::from(layers.transit), u8::from(layers.traffic),+ u8::from(layers.junction), min_zoom, max_zoom, // A build with a transit-routes file and one without carry different layers from the // same `.pbf`, and readers cache byte ranges under `(url, build_id)`. u8::from(transit_routes),- // Likewise a build with a graph carries the whole traffic layer that one without does not.+ // Likewise a build with a graph carries the whole traffic and junction layers that one+ // without does not. u8::from(graph), ]); eat(&simplification.to_le_bytes());
scripts/maps/mamaps_build/src/schema/junction.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction.rs b/scripts/maps/mamaps_build/src/schema/junction.rsnew file mode 100644index 0000000000..0ad49e1c23--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/junction.rs@@ -0,0 +1,1306 @@+//! `junction`: one line per **lane connector** through an intersection.+//!+//! A lane connector is the path a single lane follows from an approach into an exit — the left-turn+//! lane's arc, the through lane's stripe, the slip road peeling off a motorway. The renderer draws+//! each as a one-lane ribbon and does no curve maths, so every feature here is an already-sampled+//! polyline rather than a control-point set.+//!+//! Geometry comes from the same v6 routing graph [`crate::schema::traffic`] reads —+//! `metadata.bin`, `nodes.bin`, `edges.bin`, `intermediate.bin`, plus `lanes.bin` — and that module+//! is where the on-disk format, the escape tables and the polyline decode are documented. This one+//! only adds what a connector needs on top: which nodes are junctions, which way each incident edge+//! points, and which lane goes where.+//!+//! # What is data and what is inference+//!+//! **Be clear about this, because most of it is inference.** OSM has essentially no lane+//! connectivity data. `connectivity` relations exist but are vanishingly rare and nothing in this+//! tree reads them. So:+//!+//! | Thing | Where it comes from |+//! |---|---|+//! | Which nodes are junctions | **Data.** The generator collapses degree-2 chains, so a surviving node of degree ≥ 3 is a real fork. |+//! | Where each approach and exit runs | **Data.** Node coordinates and edge polylines. |+//! | Approach and exit headings | **Data**, derived: `atan2` over the first geometry step, because the graph stores no headings. |+//! | Which movements are legal | **Inference.** Every exit but the U-turn back where you came from is assumed legal. The graph carries no turn restrictions. |+//! | A lane's turn indication, where `turn:lanes` is tagged | **Data.** `lanes.bin`, keyed by directed edge, ordered left→right. |+//! | A lane's turn indication everywhere else | **Inference**, and this is the overwhelming majority of roads. |+//! | How many lanes an approach has, absent `turn:lanes` | **Inference**, and the weakest link: one lane is assumed per legal exit, because nothing in the graph says otherwise. |+//! | 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. |+//! | The setback the arc starts at | **Neither.** [`SETBACK_M`] is a nominal guess at how big an intersection is. |+//!+//! Motorway exits are the case this should look good on: they are comparatively well tagged, they+//! are geometrically simple, and a slip road's heading separates cleanly from the mainline's.+//! Ordinary urban intersections are a heuristic and will need tuning against screenshots. Nothing+//! here should be read as knowing where the paint is.+//!+//! # Lateral offset is baked in projected units, not ground metres+//!+//! Each connector's polyline already carries its lane's offset across the carriageway. That offset+//! is expressed as a fixed number of **Web Mercator** units — spelled here as the ground metres a+//! lane occupies *at the equator*, which is the same thing — and **not** as ground metres at the+//! junction's own latitude.+//!+//! This is structural rather than cosmetic. The carriageway ribbon's lane width is a screen-space+//! quantity: a dp ramp turned into a half-width in pixels and pushed per draw. Web Mercator's scale+//! carries a `1 / cos φ` term, so a fixed ground distance is a *different* number of pixels at+//! every latitude. Measured against the style's painted lane, 3.5 m of ground comes out at 0.97 of+//! a lane at the equator, 0.76 at 38°N and 0.48 at 60°N — so a naively baked ground offset lands+//! 2.3× too far out in Scandinavia, which is more than two lane widths and puts the connector off+//! the road it is meant to join.+//!+//! No zoom gate can rescue that, because `cos φ` is not a function of zoom. Scaling the offset by+//! `cos φ` before it is converted to degrees cancels the projection's stretch exactly, costs one+//! multiply, and needs no wire field and no shader change. The along-road setback is deliberately+//! *not* scaled: [`SETBACK_M`] is a real distance on the ground, because the intersection it spans+//! and the road geometry it must meet are both real distances on the ground.+//!+//! ## The projection correction is exact; the lane width is not+//!+//! "Exactly" above is a claim about the projection and nothing else: `cos φ` cancels Mercator's+//! `1 / cos φ`, which is pure geometry and leaves nothing over at any latitude. It is *not* a+//! claim that a connector lands on the paint. Read as one it is actively dangerous, because a+//! reader who believes the whole thing is exact has no reason to expect a residual, and on meeting+//! one will look for it in the projection — where it is not — and close it by putting a `cos φ`+//! back somewhere. That is the bug this section exists to prevent.+//!+//! A second and smaller discrepancy does survive, and it is not projection error.+//! [`LANE_WIDTH_MERCATOR_M`] is a single number, while the width the renderer actually paints a+//! lane at comes from the style's dp ramp, which is not linear in ground metres — so the two agree+//! at one zoom and drift either side of it. The ramp is `roads-carriageway`'s `width` in+//! `basemap.flat.json` — exponential, base 2.0, over stops+//! `[[16, 3.0], [18, 11.0], [20, 40.0], [22, 160.0]]`, one lane's width in dp. Read at the+//! equator, where the `cos φ` term is already 1 and the ramp is therefore read cleanly on its+//! own, and against a 512 dp tile, a painted lane is worth about 3.40 m of ground at z17 falling+//! to 2.98 m by z20, against a fixed 3.0 m of connector pitch: roughly 12% narrow at z17,+//! crossing over to about 1% wide by z20. Those figures are reproducible from those stops rather+//! than asserted. The change of sign is the part that matters: no single+//! percentage describes the residual, and anyone who reads "the connector is N% wider" will reach+//! for a correction that is wrong at one end of the zoom range. That the fit crosses zero at all+//! is the point — it is centred across the zoom band rather than biased to one end, which is what+//! fitting on absolute dp instead of relative error buys. The residual is also+//! latitude-independent, which together with the drift in zoom is the signature of a ramp+//! mismatch rather than of a projection.+//!+//! **It cannot be closed by a projection term, because it is not a projection error.** The only+//! two levers on it are [`LANE_WIDTH_MERCATOR_M`] and the style's width ramp; the constant is+//! already fitted against that ramp, and where the residual is deliberately put — in percent+//! rather than in pixels — is argued at the constant. A `cos φ` introduced to chase it would be 1+//! at the equator, which is exactly where the residual was measured, and wrong everywhere else.++use std::collections::BTreeSet;+use std::path::Path;++use osm_ingest::proto::{err, Result};+use tile_build::geom::Geometry;+use tilecodec::mamaps::body::{+ LANE_LEFT, LANE_NONE, LANE_REVERSE, LANE_RIGHT, LANE_SHARP_LEFT, LANE_SHARP_RIGHT,+ LANE_SLIGHT_LEFT, LANE_SLIGHT_RIGHT, LANE_THROUGH,+};+use tilecodec::mamaps::dict::{self, LAYER_JUNCTION};++use super::boundaries::Conventions;+use super::traffic::{Graph, ROAD_TYPE_MASK};+use super::Class;+use crate::store::Sink;++/// The zoom lane connectors first surface at.+///+/// Deeper than [`crate::schema::traffic::MIN_ZOOM`] and for a different reason: a connector is a+/// few tens of metres long and a lane wide, so below the zoom a carriageway is drawn as a surface+/// rather than a stroke there is nothing for it to connect. Matched to where the renderer draws+/// the layer, so no zoom it paints at is left empty.+pub const MIN_ZOOM: u8 = 16;++/// Width of one lane, in **Web Mercator metres** — ground metres at the equator, which at any+/// other latitude is a smaller ground distance and the same projected one. That is what makes it a+/// fixed number of pixels everywhere; see the module docs, where expressing it as ground metres at+/// the junction's own latitude is what puts a connector two lanes off the road at 60°N.+/// [`lane_width_ground_m`] converts it for a given latitude.+///+/// **3.0, not the 3.5 a real lane is designed to, and that is deliberate — do not "correct" it.**+/// This is not a measurement of a road. It is fitted to the width the renderer actually paints a+/// lane at, which is a dp ramp and is not linear in ground metres. Measured against that ramp, a+/// lane is worth about 3.40 m of ground at z17 falling to 2.98 m by z20, so no single constant is+/// right at every zoom and the only question is where to put the residual.+///+/// It is fitted on **absolute misalignment in dp, not relative error**, and the two disagree: a dp+/// is 1.7 per ground metre at z17 and 13.4 at z20, so the same percentage costs eight times the+/// pixels at the deep end. 3.2 minimises worst-case percentage but leaves ~5 dp of visible gap at+/// z20; 3.0 is a worse percentage fit and keeps the gap near a pixel at every zoom, which is the+/// one that cannot be seen. Percentage error is not what a viewer looks at.+pub const LANE_WIDTH_MERCATOR_M: f64 = 3.0;++/// [`LANE_WIDTH_MERCATOR_M`] as ground metres at `lat_degrees`, which is a lane's width shrinking+/// toward the poles exactly as fast as Mercator stretches it. Exact as a statement about the+/// projection — `cos φ` against `1 / cos φ`, with no approximation in it — and only that: it says+/// nothing about whether the result matches the painted lane, which is the ramp residual the+/// module docs describe and is not fixable here.+fn lane_width_ground_m(lat_degrees: f64) -> f64 {+ LANE_WIDTH_MERCATOR_M * lat_degrees.to_radians().cos().abs().max(1e-6)+}++/// How far back from the junction node a connector starts, and how far past it the connector ends.+///+/// The node is a point; a real intersection is a box some tens of metres across. This is the+/// half-width that box is assumed to have, so a connector spans roughly `2 * SETBACK_M` of ground.+/// Clamped per edge to a fraction of that edge's own length, so a short block does not produce a+/// connector running past the next junction.+const SETBACK_M: f64 = 14.0;++/// The most of an incident edge's length a connector may consume at either end.+const SETBACK_EDGE_FRACTION: f64 = 0.4;++/// Below this the connector is shorter than a lane is wide and draws as a blob.+const MIN_SETBACK_M: f64 = 2.0;++/// Bezier handle length as a fraction of the setback.+///+/// 0.55 is the usual circular-arc approximation constant; it makes the curve leave the approach and+/// meet the exit tangentially without bulging past the intersection box.+const HANDLE: f64 = 0.55;++/// Metres per degree of latitude. Spherical, which is the same approximation+/// [`tile_build::geom::project`] makes and is worth centimetres over a connector's length.+const METRES_PER_DEGREE: f64 = 111_320.0;++/// The class every lane connector carries: layer `junction`, no kind and no detail.+///+/// No `kind`/`kind_detail` for the same reason [`crate::schema::traffic::traffic_class`] has none:+/// the basemap style does not draw this layer, the carriageway renderer does, and it selects the+/// whole layer rather than filtering within it. Keeping the name out of [`dict::KINDS`] avoids+/// disturbing the frozen kind table for a value nothing matches by name.+pub fn junction_class() -> Class {+ Class {+ layer: LAYER_JUNCTION,+ kind: dict::NONE,+ kind_detail: dict::NONE,+ flags: 0,+ area: false,+ min_zoom: MIN_ZOOM,+ min_area_px: 0.0,+ }+}++// --- lanes.bin ------------------------------------------------------------------------------++/// `lanes.bin`: `[u32 n][(u32 edge_idx, u32 blob_off) x (n + 1)][u16 mask blob]`.+///+/// **Sparse**: only edges that carry a `turn:lanes` tag appear, ascending by `edge_idx`, so absence+/// from the index is how "this edge has no lane data" is spelled. Mirrors+/// `maps/src/main/rust/src/graph.rs::edge_lane_masks`; the trailing sentinel entry exists only to+/// give the last real edge a length.+///+/// The whole file is read rather than mapped, matching how [`Graph`] reads the rest of the graph.+struct LaneTable {+ raw: Vec<u8>,+ count: u32,+ blob_off: usize,+}++impl LaneTable {+ /// Read `lanes.bin`, or `None` when the graph was built without lane data. A missing file is+ /// not an error — every connector then falls back to the inferred path, which is what happens+ /// for most edges even when the file is present.+ fn load(dir: &Path) -> Result<Option<LaneTable>> {+ let path = dir.join("lanes.bin");+ let raw = match std::fs::read(&path) {+ Ok(raw) => raw,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(e) => return err(format!("cannot read {}: {e}", path.display())),+ };+ if raw.len() < 4 {+ return err("lanes.bin is too short to hold its entry count".to_string());+ }+ let count = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]);+ // n + 1 entries: the trailing sentinel is what gives the last edge an end offset.+ let index_bytes = 4usize+ .checked_add((count as usize + 1).saturating_mul(8))+ .ok_or_else(|| osm_ingest::proto::Error("lanes.bin index size overflows".to_string()))?;+ if raw.len() < index_bytes {+ return err(format!(+ "lanes.bin is {} bytes, too short for its {count}-entry index",+ raw.len(),+ ));+ }+ Ok(Some(LaneTable { raw, count, blob_off: index_bytes }))+ }++ fn entry(&self, i: u32) -> (u32, u32) {+ let at = 4 + (i as usize) * 8;+ let edge = u32::from_le_bytes([self.raw[at], self.raw[at + 1], self.raw[at + 2], self.raw[at + 3]]);+ let off = u32::from_le_bytes([+ self.raw[at + 4],+ self.raw[at + 5],+ self.raw[at + 6],+ self.raw[at + 7],+ ]);+ (edge, off)+ }++ /// The per-lane `LANE_*` masks for directed edge `idx`, ordered left→right, or `None` when it+ /// carries none. Binary search, because the index is sparse.+ fn masks(&self, idx: u32) -> Option<Vec<u16>> {+ let (mut lo, mut hi) = (0u32, self.count);+ while lo < hi {+ let mid = lo + (hi - lo) / 2;+ if self.entry(mid).0 < idx {+ lo = mid + 1;+ } else {+ hi = mid;+ }+ }+ if lo >= self.count || self.entry(lo).0 != idx {+ return None;+ }+ let start = self.blob_off + self.entry(lo).1 as usize;+ let end = self.blob_off + self.entry(lo + 1).1 as usize;+ if end <= start || end > self.raw.len() {+ return None;+ }+ Some(+ self.raw[start..end]+ .chunks_exact(2)+ .map(|c| u16::from_le_bytes([c[0], c[1]]))+ .collect(),+ )+ }+}++// --- turns ----------------------------------------------------------------------------------++/// A movement's turn class, the same vocabulary `turn:lanes` uses.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Turn {+ SharpLeft,+ Left,+ SlightLeft,+ Through,+ SlightRight,+ Right,+ SharpRight,+ /// A reversal back the way the driver came — the `LANE_REVERSE` indication.+ Reverse,+}++impl Turn {+ /// The `LANE_*` bit a lane tagged for this movement sets.+ fn bit(self) -> u16 {+ match self {+ Turn::SharpLeft => LANE_SHARP_LEFT,+ Turn::Left => LANE_LEFT,+ Turn::SlightLeft => LANE_SLIGHT_LEFT,+ Turn::Through => LANE_THROUGH,+ Turn::SlightRight => LANE_SLIGHT_RIGHT,+ Turn::Right => LANE_RIGHT,+ Turn::SharpRight => LANE_SHARP_RIGHT,+ Turn::Reverse => LANE_REVERSE,+ }+ }++ /// The angle, in degrees clockwise, this movement nominally turns through. Used to pick the+ /// closest real exit for a tagged indication that no exit's own bucket matches — a+ /// `turn:lanes=right` onto a road the graph classes as a sharp right, say.+ fn nominal_degrees(self) -> f64 {+ match self {+ Turn::SharpLeft => -155.0,+ Turn::Left => -90.0,+ Turn::SlightLeft => -32.0,+ Turn::Through => 0.0,+ Turn::SlightRight => 32.0,+ Turn::Right => 90.0,+ Turn::SharpRight => 155.0,+ Turn::Reverse => 180.0,+ }+ }++ /// Does this movement go left? Decides which lane of the exit a connector lands in.+ fn is_left(self) -> bool {+ matches!(self, Turn::SharpLeft | Turn::Left | Turn::SlightLeft)+ }++ fn is_right(self) -> bool {+ matches!(self, Turn::SharpRight | Turn::Right | Turn::SlightRight)+ }++ /// Every turn a `LANE_*` mask can name, so a lane's bits can be walked.+ const ALL: [Turn; 8] = [+ Turn::SharpLeft,+ Turn::Left,+ Turn::SlightLeft,+ Turn::Through,+ Turn::SlightRight,+ Turn::Right,+ Turn::SharpRight,+ Turn::Reverse,+ ];+}++/// Bucket a signed turn angle (degrees, positive clockwise/right) into a [`Turn`].+///+/// The thresholds are OSM's own reading of the `turn` vocabulary: `slight` up to 45°, the plain+/// direction out to 135°, `sharp` beyond that, and a reversal past 170°.+fn classify_turn(delta_degrees: f64) -> Turn {+ let magnitude = delta_degrees.abs();+ let right = delta_degrees > 0.0;+ if magnitude <= 20.0 {+ Turn::Through+ } else if magnitude > 170.0 {+ Turn::Reverse+ } else if magnitude <= 45.0 {+ if right {+ Turn::SlightRight+ } else {+ Turn::SlightLeft+ }+ } else if magnitude <= 135.0 {+ if right {+ Turn::Right+ } else {+ Turn::Left+ }+ } else if right {+ Turn::SharpRight+ } else {+ Turn::SharpLeft+ }+}++/// Wrap an angle difference into `(-180, 180]`, so a turn's sign is its direction.+fn normalise_degrees(mut d: f64) -> f64 {+ while d > 180.0 {+ d -= 360.0;+ }+ while d <= -180.0 {+ d += 360.0;+ }+ d+}++// --- local geometry -------------------------------------------------------------------------++/// Bearing from `a` to `b` in degrees clockwise from north, on the local tangent plane.+///+/// The `e7` units cancel in the ratio; only the `cos(lat)` correction on the east component+/// matters, and without it every heading north of the tropics comes out rotated.+fn bearing_degrees(a: (i32, i32), b: (i32, i32)) -> f64 {+ let mid_lat = (f64::from(a.0) + f64::from(b.0)) * 0.5 * 1e-7;+ let north = f64::from(b.0) - f64::from(a.0);+ let east = (f64::from(b.1) - f64::from(a.1)) * mid_lat.to_radians().cos();+ east.atan2(north).to_degrees()+}++/// Ground distance between two `e7` points, in metres.+fn distance_m(a: (i32, i32), b: (i32, i32)) -> f64 {+ let mid_lat = (f64::from(a.0) + f64::from(b.0)) * 0.5 * 1e-7;+ let north = (f64::from(b.0) - f64::from(a.0)) * 1e-7 * METRES_PER_DEGREE;+ let east =+ (f64::from(b.1) - f64::from(a.1)) * 1e-7 * METRES_PER_DEGREE * mid_lat.to_radians().cos();+ (north * north + east * east).sqrt()+}++/// The length of a polyline, in metres.+fn polyline_length_m(verts: &[(i32, i32)]) -> f64 {+ verts.windows(2).map(|w| distance_m(w[0], w[1])).sum()+}++/// A point offset from `origin` by `(east, north)` metres, as `(lon, lat)` degrees.+fn offset_degrees(origin: (i32, i32), east_m: f64, north_m: f64) -> (f64, f64) {+ let lat = f64::from(origin.0) * 1e-7;+ let lon = f64::from(origin.1) * 1e-7;+ let d_lat = north_m / METRES_PER_DEGREE;+ // At the poles this divisor collapses; the Mercator clamp means no tile is drawn there anyway,+ // and a floor keeps a degenerate coordinate from becoming an infinity in the output.+ let d_lon = east_m / (METRES_PER_DEGREE * lat.to_radians().cos().abs().max(1e-6));+ (lon + d_lon, lat + d_lat)+}++/// The unit vector pointing along `heading` (degrees clockwise from north), as `(east, north)`.+fn forward(heading_degrees: f64) -> (f64, f64) {+ let r = heading_degrees.to_radians();+ (r.sin(), r.cos())+}++/// The unit vector 90° clockwise of `heading` — "right of the direction of travel".+fn rightward(heading_degrees: f64) -> (f64, f64) {+ let r = heading_degrees.to_radians();+ (r.cos(), -r.sin())+}++// --- the graph, one junction at a time --------------------------------------------------------++/// Is this road class one a car drives on? The same `1..=9` (motorway..living_street) the traffic+/// layer uses, masked so the reverse-geometry flag cannot trip the range test.+fn is_drivable(type_: u8) -> bool {+ (1..=9).contains(&(type_ & ROAD_TYPE_MASK))+}++/// Incoming drivable edges per node, as a CSR built in one pass over the graph.+///+/// `nodes.bin` is out-edges only and there is no reverse index on disk, so this is the whole reason+/// approaches can be found at all. [`Graph::has_drivable_twin`] is the existing primitive and would+/// do for a two-way street, but it can only find an approach from a node the junction also has an+/// out-edge *to* — which misses every one-way approach, and a one-way approach is exactly the+/// motorway slip road this layer is meant to get right.+///+/// Costs `4 * (node_count + 1)` bytes plus 4 per drivable edge, and stores only the edge index: an+/// in-edge's source node is recovered by [`source_of`], which is a binary search over the same+/// `edge_ptr` array rather than another 4 bytes an edge.+struct InEdges {+ start: Vec<u32>,+ edges: Vec<u32>,+}++impl InEdges {+ fn build(graph: &Graph) -> Result<InEdges> {+ let node_count = graph.node_count;+ let mut start = vec![0u32; node_count as usize + 2];+ let mut total = 0usize;+ for n in 0..node_count {+ for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) {+ if !is_drivable(graph.edge_type(idx)) {+ continue;+ }+ let target = graph.edge_target(idx, n as u32)?;+ if u64::from(target) >= node_count {+ return err(format!(+ "edge {idx} targets node {target}, past the {node_count} in the graph"+ ));+ }+ // Counted one slot high, so the prefix sum below leaves `start[t]` pointing at+ // node `t`'s first slot and `start[t + 1]` one past its last.+ start[target as usize + 1] += 1;+ total += 1;+ }+ }+ for i in 1..start.len() {+ start[i] += start[i - 1];+ }+ let mut fill = start.clone();+ let mut edges = vec![0u32; total];+ for n in 0..node_count {+ for idx in graph.edge_ptr(n)..graph.edge_ptr(n + 1) {+ if !is_drivable(graph.edge_type(idx)) {+ continue;+ }+ let target = graph.edge_target(idx, n as u32)? as usize;+ edges[fill[target] as usize] = idx;+ fill[target] += 1;+ }+ }+ start.truncate(node_count as usize + 1);+ Ok(InEdges { start, edges })+ }++ fn of(&self, n: u64) -> &[u32] {+ let lo = self.start[n as usize] as usize;+ let hi = self.start[n as usize + 1] as usize;+ &self.edges[lo..hi]+ }+}++/// The node edge `idx` leaves from: the last node whose `edge_ptr` is at or below it.+///+/// `edge_ptr` ascends across `nodes.bin` and the sentinel record holds `edge_count`, so the answer+/// is always in `0..node_count` for a valid edge index.+fn source_of(graph: &Graph, idx: u32) -> u64 {+ let (mut lo, mut hi) = (1u64, graph.node_count + 1);+ while lo < hi {+ let mid = lo + (hi - lo) / 2;+ if graph.edge_ptr(mid) > idx {+ hi = mid;+ } else {+ lo = mid + 1;+ }+ }+ lo - 1+}++/// An edge's polyline in the order it is travelled, `from -> to`.+///+/// A reverse-geometry edge stores no shape of its own — its twin running the other way owns it — so+/// the twin's polyline is found and reversed. Without this every curved two-way approach would get+/// its heading from the straight chord instead of the road, which at a bend is a wrong turn angle+/// and therefore a wrong lane pairing.+fn travel_polyline(graph: &Graph, idx: u32, from: u32, to: u32) -> Vec<(i32, i32)> {+ if graph.geom_contains(idx) {+ return graph.polyline(idx, from, to);+ }+ for twin in graph.edge_ptr(u64::from(to))..graph.edge_ptr(u64::from(to) + 1) {+ if !graph.geom_contains(twin) || !is_drivable(graph.edge_type(twin)) {+ continue;+ }+ if graph.edge_target(twin, to).is_ok_and(|t| t == from) {+ let mut verts = graph.polyline(twin, to, from);+ verts.reverse();+ return verts;+ }+ }+ // A genuine straight chord: source and target, and nothing between them.+ graph.polyline(idx, from, to)+}++/// One movement into or out of a junction, resolved into everything a connector needs.+struct Arm {+ /// The node at the far end.+ neighbour: u32,+ /// Degrees clockwise from north, always in the direction of travel — so for an approach this is+ /// the heading traffic *arrives* on, and for an exit the heading it *departs* on.+ heading: f64,+ /// The edge's own length in metres, which caps how far the connector may reach along it.+ length_m: f64,+ /// Lanes running this way, and whether the road carries traffic the other way too. Together+ /// they place a lane across the carriageway.+ lanes: usize,+ two_way: bool,+ /// Per-lane `turn:lanes` masks, left→right, when `lanes.bin` has them. `None` is the common+ /// case and is what sends a movement down the inferred path.+ masks: Option<Vec<u16>>,+}++/// Resolve one incident edge, or `None` when it is not usable as an arm of this junction.+fn arm(+ graph: &Graph,+ lanes: Option<&LaneTable>,+ idx: u32,+ from: u32,+ to: u32,+ outgoing: bool,+) -> Option<Arm> {+ let verts = travel_polyline(graph, idx, from, to);+ // The heading is the first geometry step leaving the junction, or the last arriving at it. A+ // repeated vertex has no direction, so the scan walks past duplicates rather than dividing by+ // zero — the graph does contain them at edges that were split at a coincident point.+ let node = if outgoing { verts.first().copied()? } else { verts.last().copied()? };+ let (heading, ok) = if outgoing {+ match verts.iter().skip(1).find(|v| **v != node) {+ Some(next) => (bearing_degrees(node, *next), true),+ None => (0.0, false),+ }+ } else {+ match verts.iter().rev().skip(1).find(|v| **v != node) {+ Some(prev) => (bearing_degrees(*prev, node), true),+ None => (0.0, false),+ }+ };+ if !ok {+ return None;+ }+ let length_m = polyline_length_m(&verts);+ if length_m < MIN_SETBACK_M {+ return None;+ }+ let masks = lanes.and_then(|table| table.masks(idx)).filter(|m| !m.is_empty());+ // Absent `turn:lanes`, the lane count is filled in by the caller from the junction's own shape;+ // one lane is the floor.+ let lane_count = masks.as_ref().map_or(1, Vec::len);+ let two_way = graph.has_drivable_twin(to, from).unwrap_or(false);+ Some(Arm {+ neighbour: if outgoing { to } else { from },+ heading,+ length_m,+ lanes: lane_count,+ two_way,+ masks,+ })+}++/// A lane's centre, in metres right of the road's centreline as seen by traffic travelling this+/// arm's direction.+///+/// Two offsets stacked. A two-way road's centreline runs between the two directions, so the+/// carriageway a driver is on sits a half-carriageway to their own side of it — right in a+/// right-hand-traffic country, left in a left-hand one. Within that carriageway lane `k` of `count`+/// sits at the usual centred spacing, counted left→right in the direction of travel, which is the+/// order `lanes.bin` stores masks in.+///+/// `width` is the lane width in ground metres at this junction's latitude — see+/// [`lane_width_ground_m`], and the module docs for why it is not simply [`LANE_WIDTH_MERCATOR_M`].+///+/// The opposite direction is assumed to have the same lane count, because the graph gives no way to+/// ask. An asymmetric road — three lanes one way and one the other — puts its connectors half a+/// carriageway off.+fn lane_offset_m(k: usize, count: usize, two_way: bool, left_hand: bool, width: f64) -> f64 {+ let count = count.max(1);+ let side = if left_hand { -1.0 } else { 1.0 };+ let carriageway = if two_way { side * count as f64 * 0.5 * width } else { 0.0 };+ let within = (k as f64 - (count as f64 - 1.0) * 0.5) * width;+ carriageway + within+}++/// Sample the connector from lane `in_lane` of `approach` into lane `out_lane` of `exit`.+///+/// A cubic bezier in a local tangent plane centred on the junction node, with its handles along the+/// two headings so the curve leaves the approach and meets the exit tangentially. Sampled here, in+/// `f64` and once per build, rather than on device once per frame — which is the whole point of+/// carrying a polyline instead of control points.+fn connector(+ node: (i32, i32),+ approach: &Arm,+ in_lane: usize,+ exit: &Arm,+ out_lane: usize,+ turn: Turn,+ left_hand: bool,+) -> Option<Vec<(f64, f64)>> {+ let back = (SETBACK_M).min(approach.length_m * SETBACK_EDGE_FRACTION);+ let ahead = (SETBACK_M).min(exit.length_m * SETBACK_EDGE_FRACTION);+ if back < MIN_SETBACK_M || ahead < MIN_SETBACK_M {+ return None;+ }+ // The setback is real ground distance: the intersection is that big and the roads it joins are+ // where they are. The lateral offset is not — it shrinks with `cos φ` so that it stays a fixed+ // size in projected units, and therefore a fixed size in pixels, at every latitude.+ let width = lane_width_ground_m(f64::from(node.0) * 1e-7);+ let in_off = lane_offset_m(in_lane, approach.lanes, approach.two_way, left_hand, width);+ let out_off = lane_offset_m(out_lane, exit.lanes, exit.two_way, left_hand, width);++ let (fin_e, fin_n) = forward(approach.heading);+ let (rin_e, rin_n) = rightward(approach.heading);+ let (fout_e, fout_n) = forward(exit.heading);+ let (rout_e, rout_n) = rightward(exit.heading);++ // Start: back along the approach from the node, then across to the lane's centre.+ let p0 = (-fin_e * back + rin_e * in_off, -fin_n * back + rin_n * in_off);+ // End: forward along the exit, then across.+ let p3 = (fout_e * ahead + rout_e * out_off, fout_n * ahead + rout_n * out_off);+ let p1 = (p0.0 + fin_e * back * HANDLE, p0.1 + fin_n * back * HANDLE);+ let p2 = (p3.0 - fout_e * ahead * HANDLE, p3.1 - fout_n * ahead * HANDLE);++ // A straight-through movement needs two points; a U-turn needs every one of these. Anything+ // flatter than the sampling would resolve is dropped by the tiler's simplifier anyway.+ let sweep = normalise_degrees(exit.heading - approach.heading).abs();+ let samples = if turn == Turn::Through && sweep < 3.0 && (in_off - out_off).abs() < 0.05 {+ 2+ } else {+ (4.0 + sweep / 18.0).round().clamp(4.0, 14.0) as usize+ };++ let mut out = Vec::with_capacity(samples);+ for i in 0..samples {+ let t = i as f64 / (samples - 1) as f64;+ let u = 1.0 - t;+ let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);+ let east = w0 * p0.0 + w1 * p1.0 + w2 * p2.0 + w3 * p3.0;+ let north = w0 * p0.1 + w1 * p1.1 + w2 * p2.1 + w3 * p3.1;+ out.push(offset_degrees(node, east, north));+ }+ Some(out)+}++/// Which lane of the exit a connector lands in.+///+/// Inference, and the ordinary road convention: a left turn feeds the exit's leftmost lane, a right+/// turn its rightmost, and a through movement holds its position across the junction as closely as+/// the two lane counts allow.+fn exit_lane(turn: Turn, in_lane: usize, in_lanes: usize, out_lanes: usize) -> usize {+ let last = out_lanes.saturating_sub(1);+ if turn.is_left() {+ 0+ } else if turn.is_right() {+ last+ } else {+ (in_lane * out_lanes / in_lanes.max(1)).min(last)+ }+}++/// The exits a lane tagged for `turn` should connect to.+///+/// Exact bucket first: every legal exit the junction's own geometry classes as this movement. When+/// none matches — a `turn:lanes=right` onto a road that leaves at 140°, say — the single closest+/// exit by angle is used instead, because a tagged indication with nowhere to go is far more likely+/// to be a threshold disagreement than a lane that leads nowhere.+fn exits_for(turn: Turn, legal: &[(usize, f64, Turn)]) -> Vec<usize> {+ let exact: Vec<usize> =+ legal.iter().filter(|(_, _, t)| *t == turn).map(|(i, _, _)| *i).collect();+ if !exact.is_empty() {+ return exact;+ }+ let nominal = turn.nominal_degrees();+ legal+ .iter()+ .min_by(|a, b| {+ normalise_degrees(a.1 - nominal)+ .abs()+ .total_cmp(&normalise_degrees(b.1 - nominal).abs())+ })+ .map(|(i, _, _)| vec![*i])+ .unwrap_or_default()+}++/// Spread `lanes` across `exits`, both already in left→right order, as `(lane, exit)` pairs.+///+/// Whichever side is larger drives the pairing, so every lane gets a connector and every exit gets+/// fed. Two left-turn lanes onto one road give two connectors into the same exit, which is right —+/// a dual left turn is two ribbons. One lane onto a two-lane exit gives two connectors out of the+/// same lane, which is also right: the lane fans.+fn distribute(lanes: &[usize], exits: &[usize]) -> Vec<(usize, usize)> {+ if lanes.is_empty() || exits.is_empty() {+ return Vec::new();+ }+ if lanes.len() >= exits.len() {+ lanes+ .iter()+ .enumerate()+ .map(|(i, &lane)| (lane, exits[i * exits.len() / lanes.len()]))+ .collect()+ } else {+ exits+ .iter()+ .enumerate()+ .map(|(j, &exit)| (lanes[j * lanes.len() / exits.len()], exit))+ .collect()+ }+}++/// Read the v6 graph at `dir` and push one line feature per lane connector into `sink`. Returns the+/// number of connectors emitted.+///+/// `conventions` decides which side of a road's centreline the direction of travel sits on, so a+/// left-hand-traffic country's connectors are not mirrored. It is resolved from each junction's own+/// coordinate at [`super::boundaries::COARSE_ZOOM`], which is the granularity the grid holds.+///+/// Not clipped to a bounding box, for the same reason [`crate::schema::traffic::stream_graph`] is+/// not: the graph is already the built region and the tiler clips each connector per tile.+pub fn stream_junctions(dir: &Path, conventions: &Conventions, sink: &mut Sink) -> Result<u64> {+ let graph = Graph::load(dir)?;+ let lanes = LaneTable::load(dir)?;+ let incoming = InEdges::build(&graph)?;+ let class = junction_class();+ let mut emitted = 0u64;++ for n in 0..graph.node_count {+ let node = graph.node(n);+ let in_arms: Vec<Arm> = incoming+ .of(n)+ .iter()+ .filter_map(|&idx| {+ arm(&graph, lanes.as_ref(), idx, source_of(&graph, idx) as u32, n as u32, false)+ })+ .collect();+ let out_arms: Vec<Arm> = (graph.edge_ptr(n)..graph.edge_ptr(n + 1))+ .filter(|&idx| is_drivable(graph.edge_type(idx)))+ .filter_map(|idx| {+ let target = graph.edge_target(idx, n as u32).ok()?;+ arm(&graph, lanes.as_ref(), idx, n as u32, target, true)+ })+ .collect();+ if in_arms.is_empty() || out_arms.len() < 2 {+ continue;+ }+ // A junction is a node three or more distinct roads meet at. Degree-2 chains are collapsed+ // by the generator, so the survivors below this bar are dead ends, attribute breaks and+ // transit stops — none of which anything turns at.+ let degree: BTreeSet<u32> =+ in_arms.iter().chain(&out_arms).map(|a| a.neighbour).collect();+ if degree.len() < 3 {+ continue;+ }++ let (tx, ty) = tile_build::geom::project(+ f64::from(node.1) * 1e-7,+ f64::from(node.0) * 1e-7,+ super::boundaries::COARSE_ZOOM,+ );+ let left_hand = conventions+ .at_tile(+ super::boundaries::COARSE_ZOOM,+ tx.max(0.0) as u64,+ ty.max(0.0) as u64,+ )+ .left_hand;++ for approach in &in_arms {+ // Every exit but the one back the way you came. The graph carries no turn restrictions,+ // so this is the whole legality model: inference, and generous.+ let mut legal: Vec<(usize, f64, Turn)> = out_arms+ .iter()+ .enumerate()+ .filter(|(_, exit)| exit.neighbour != approach.neighbour)+ .map(|(i, exit)| {+ let delta = normalise_degrees(exit.heading - approach.heading);+ (i, delta, classify_turn(delta))+ })+ .collect();+ if legal.is_empty() {+ continue;+ }+ // Left→right as the driver sees them, which is the order lane masks are stored in.+ legal.sort_by(|a, b| a.1.total_cmp(&b.1));++ // `turn:lanes` where it exists, junction shape where it does not. The inferred case is+ // the overwhelming majority of roads: one lane is assumed per legal exit, in the same+ // left→right order, which is the most a junction's own topology can say.+ let pairs: Vec<(usize, usize)> = match &approach.masks {+ Some(masks) => {+ let mut pairs = Vec::new();+ for turn in Turn::ALL {+ let bit = turn.bit();+ let claimants: Vec<usize> = masks+ .iter()+ .enumerate()+ .filter(|(_, m)| {+ // A lane whose only marking is "none" is treated as a through lane,+ // which is what an unmarked lane at a junction means in practice.+ **m & bit != 0+ || (turn == Turn::Through+ && (**m == 0 || **m == LANE_NONE))+ })+ .map(|(k, _)| k)+ .collect();+ if claimants.is_empty() {+ continue;+ }+ pairs.extend(distribute(&claimants, &exits_for(turn, &legal)));+ }+ pairs+ }+ None => (0..legal.len()).map(|i| (i, legal[i].0)).collect(),+ };++ // Under inference the approach's lane count is the number of legal exits, so the+ // connectors span the carriageway instead of stacking on its centreline.+ let inferred_lanes = legal.len();+ let approach_lanes =+ if approach.masks.is_some() { approach.lanes } else { inferred_lanes };++ for (in_lane, exit_index) in pairs {+ let exit = &out_arms[exit_index];+ let Some((_, _, turn)) = legal.iter().find(|(i, _, _)| *i == exit_index) else {+ continue;+ };+ let out_lane = exit_lane(*turn, in_lane, approach_lanes, exit.lanes);+ let sized = Arm {+ lanes: approach_lanes,+ masks: None,+ neighbour: approach.neighbour,+ heading: approach.heading,+ length_m: approach.length_m,+ two_way: approach.two_way,+ };+ let Some(points) = connector(node, &sized, in_lane, exit, out_lane, *turn, left_hand)+ else {+ continue;+ };+ sink.push(&class, &Geometry::Lines(vec![points]))?;+ emitted += 1;+ }+ }+ }+ Ok(emitted)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::schema::traffic::tests::{write_graph, EdgeSpec, GraphFixture};++ /// A four-arm crossroads: node 0 in the middle, nodes 1..4 due north, east, south and west of+ /// it, every arm two-way and residential. Roughly 100 m out on each side, which is a real+ /// intersection's scale and comfortably longer than [`SETBACK_M`].+ ///+ /// Built with the traffic layer's own byte-for-byte v6 writer, so the reader here is exercised+ /// against the same layout the contract specifies rather than a mock.+ fn crossroads(lanes: &[(u32, Vec<u16>)]) -> GraphFixture {+ crossroads_at(350_000_000, 12_000, lanes)+ }++ /// The same crossroads at an arbitrary latitude. `lon_step_e7` is chosen by the caller so the+ /// east and west arms stay roughly 100 m out as `cos φ` shrinks a degree of longitude.+ fn crossroads_at(+ lat_e7: i32,+ lon_step_e7: i32,+ lanes: &[(u32, Vec<u16>)],+ ) -> GraphFixture {+ let coords: [(i32, i32); 5] = [+ (lat_e7, -1_200_000_000), // 0: the junction+ (lat_e7 + 9_000, -1_200_000_000), // 1: north, ~100 m+ (lat_e7, -1_200_000_000 + lon_step_e7), // 2: east+ (lat_e7 - 9_000, -1_200_000_000), // 3: south+ (lat_e7, -1_200_000_000 - lon_step_e7), // 4: west+ ];+ let edge = |source, target| EdgeSpec { source, target, type_: 7, interior: Vec::new() };+ write_graph(+ "junction",+ &coords,+ &[+ // Edges 0..3 leave the junction; edges 4..7 return to it. Grouped by source, which+ // is what makes `nodes.bin`'s edge_ptr a CSR row pointer.+ edge(0, 1),+ edge(0, 2),+ edge(0, 3),+ edge(0, 4),+ edge(1, 0),+ edge(2, 0),+ edge(3, 0),+ edge(4, 0),+ ],+ lanes,+ )+ }++ fn stream(fixture: &GraphFixture) -> (u64, Vec<Vec<(f64, f64)>>) {+ let spill = fixture.dir.join("features.tmp");+ let mut sink = Sink::create(&spill).expect("sink");+ let emitted =+ stream_junctions(&fixture.dir, &Conventions::default(), &mut sink).expect("stream");+ let store = sink.finish(&spill).expect("finish");+ let mut reader = store.reader().expect("reader");+ let mut lines = Vec::new();+ while let Some(feature) = reader.next().expect("read") {+ assert_eq!(feature.class.layer, LAYER_JUNCTION);+ assert_eq!(feature.class.min_zoom, MIN_ZOOM);+ assert!(!feature.class.area, "a connector is a line, not a ring");+ match &feature.geometry {+ Geometry::Lines(parts) => {+ assert_eq!(parts.len(), 1, "one connector is one part");+ lines.push(parts[0].clone());+ }+ other => panic!("a connector came back as {other:?}"),+ }+ }+ let _ = std::fs::remove_file(&spill);+ (emitted, lines)+ }++ /// The angle sign convention the whole layer rests on: positive is a right turn.+ ///+ /// Wrong here and every lane pairing is mirrored, which is the one failure that would look+ /// plausible on a screenshot — connectors that curve smoothly into the wrong road.+ #[test]+ fn a_turn_angle_is_positive_to_the_right() {+ // Heading north, leaving east.+ assert_eq!(classify_turn(normalise_degrees(90.0 - 0.0)), Turn::Right);+ // Heading south, leaving east: east is on the driver's left.+ assert_eq!(classify_turn(normalise_degrees(90.0 - 180.0)), Turn::Left);+ // The wrap is what makes that true rather than a 270-degree right.+ assert_eq!(normalise_degrees(90.0 - 180.0), -90.0);+ assert_eq!(normalise_degrees(350.0), -10.0);+ assert_eq!(normalise_degrees(-350.0), 10.0);+ assert_eq!(classify_turn(0.0), Turn::Through);+ assert_eq!(classify_turn(-15.0), Turn::Through);+ assert_eq!(classify_turn(30.0), Turn::SlightRight);+ assert_eq!(classify_turn(-30.0), Turn::SlightLeft);+ assert_eq!(classify_turn(150.0), Turn::SharpRight);+ assert_eq!(classify_turn(-150.0), Turn::SharpLeft);+ assert_eq!(classify_turn(179.0), Turn::Reverse);+ }++ /// Headings come from `atan2` over a geometry step, because the graph stores none.+ #[test]+ fn a_heading_is_computed_from_the_geometry_and_corrected_for_latitude() {+ let origin = (350_000_000, -1_200_000_000);+ assert!((bearing_degrees(origin, (350_009_000, -1_200_000_000)) - 0.0).abs() < 0.01, "north");+ assert!((bearing_degrees(origin, (349_991_000, -1_200_000_000)) - 180.0).abs() < 0.01, "south");+ assert!((bearing_degrees(origin, (350_000_000, -1_199_988_000)) - 90.0).abs() < 0.01, "east");+ assert!((bearing_degrees(origin, (350_000_000, -1_200_012_000)) + 90.0).abs() < 0.01, "west");+ // Without the cos(lat) correction a due-northeast step at latitude 35 comes out at 45+ // degrees only by accident of the coordinate deltas; with it, equal *ground* distances do.+ let north_m = 1000.0;+ let east_m = 1000.0;+ let (lon, lat) = offset_degrees(origin, east_m, north_m);+ let to = ((lat * 1e7) as i32, (lon * 1e7) as i32);+ assert!((bearing_degrees(origin, to) - 45.0).abs() < 0.05, "{}", bearing_degrees(origin, to));+ }++ /// A node nothing forks at emits nothing. The traffic layer's own square fixture is four nodes+ /// of degree two or less, so it is exactly this case.+ #[test]+ fn a_chain_of_degree_two_nodes_produces_no_connectors() {+ let coords: [(i32, i32); 3] = [+ (350_000_000, -1_200_000_000),+ (350_000_000, -1_199_990_000),+ (350_000_000, -1_199_980_000),+ ];+ let edge = |source, target| EdgeSpec { source, target, type_: 7, interior: Vec::new() };+ let fixture = write_graph(+ "junction_chain",+ &coords,+ &[edge(0, 1), edge(1, 0), edge(1, 2), edge(2, 1)],+ &[],+ );+ let (emitted, lines) = stream(&fixture);+ assert_eq!(emitted, 0, "node 1 has two neighbours, so nothing turns there");+ assert!(lines.is_empty());+ }++ /// The inferred path, which is what the overwhelming majority of roads take.+ ///+ /// Four approaches, three legal exits each (everything but the U-turn back the way you came),+ /// one inferred lane per exit: twelve connectors. The four outer nodes are degree one and+ /// contribute nothing, which is what pins the count to node 0 alone.+ #[test]+ fn a_crossroads_with_no_tagged_lanes_infers_one_connector_per_legal_movement() {+ let fixture = crossroads(&[]);+ let (emitted, lines) = stream(&fixture);+ assert_eq!(emitted, 12, "four approaches x three exits");+ assert_eq!(lines.len(), 12);+ for line in &lines {+ assert!(line.len() >= 2, "a connector needs at least two points");+ assert!(line.len() <= 14, "the sampler is bounded");+ for (lon, lat) in line {+ assert!(lon.is_finite() && lat.is_finite());+ // Every connector stays inside the intersection box, which is two setbacks across.+ assert!((lat - 35.0).abs() < 0.001, "{lat} ran outside the junction");+ assert!((lon + 120.0).abs() < 0.001, "{lon} ran outside the junction");+ }+ }+ // A turning connector is a sampled curve; a straight-through one need not be.+ assert!(+ lines.iter().any(|l| l.len() > 4),+ "no connector was sampled as a curve, so the bezier is not being walked",+ );+ }++ /// The data path: a tagged `turn:lanes` on one approach replaces the inference for that+ /// approach only, and a shared `through;right` lane emits both of its movements.+ #[test]+ fn a_tagged_turn_lanes_approach_pairs_each_lane_with_its_own_exit() {+ // Edge 4 is node1 -> node0, the approach from the north, arriving heading south. Its lanes,+ // left to right: a left-turn lane, a through lane, and a shared through/right lane.+ let masks = vec![+ LANE_LEFT,+ LANE_THROUGH,+ LANE_THROUGH | LANE_RIGHT,+ ];+ let fixture = crossroads(&[(4u32, masks)]);+ let (emitted, _) = stream(&fixture);+ // The tagged approach: one left, two throughs, one right = 4. The other three approaches+ // are untagged and infer three each = 9.+ assert_eq!(emitted, 13, "the tagged approach adds a fourth connector for its shared lane");+ }++ /// Spreading lanes across exits, both ways round. A dual left turn is two ribbons into one+ /// road; a single lane onto a two-lane exit fans into both.+ #[test]+ fn lanes_and_exits_are_distributed_so_neither_side_is_left_unfed() {+ assert_eq!(distribute(&[0, 1], &[7]), vec![(0, 7), (1, 7)], "a dual left turn");+ assert_eq!(distribute(&[3], &[5, 8]), vec![(3, 5), (3, 8)], "one lane fanning");+ assert_eq!(distribute(&[0, 1], &[4, 9]), vec![(0, 4), (1, 9)], "one to one");+ assert!(distribute(&[], &[1]).is_empty());+ assert!(distribute(&[1], &[]).is_empty());+ }++ /// A tagged indication no exit's own bucket matches still connects, to the closest exit by+ /// angle — a threshold disagreement is far likelier than a lane that leads nowhere.+ #[test]+ fn a_tagged_turn_with_no_matching_exit_falls_back_to_the_closest_one() {+ // Exits at a sharp right and straight on; nothing the classifier calls a plain right.+ let legal = vec![(0usize, 150.0, Turn::SharpRight), (1usize, 5.0, Turn::Through)];+ assert_eq!(exits_for(Turn::Right, &legal), vec![0], "90 is nearer 150 than 5");+ assert_eq!(exits_for(Turn::Through, &legal), vec![1], "an exact bucket wins");+ assert!(exits_for(Turn::Left, &[]).is_empty());+ }++ /// Lane offsets, which are what stop every connector from stacking on the road's centreline.+ #[test]+ fn a_lane_sits_on_its_own_side_of_the_centreline() {+ let w = LANE_WIDTH_MERCATOR_M;+ // A one-way, two lanes: centred on the road, half a lane either side.+ assert!((lane_offset_m(0, 2, false, false, w) + w / 2.0).abs() < 1e-9);+ assert!((lane_offset_m(1, 2, false, false, w) - w / 2.0).abs() < 1e-9);+ // Two-way, right-hand traffic: the whole carriageway sits right of the centreline, so both+ // lanes are strictly positive and the inner one is half a lane out.+ assert!((lane_offset_m(0, 2, true, false, w) - w * 0.5).abs() < 1e-9);+ assert!((lane_offset_m(1, 2, true, false, w) - w * 1.5).abs() < 1e-9);+ // Left-hand traffic mirrors it, and only it: lane order within the carriageway does not+ // flip, because `lanes.bin` stores masks left-to-right in the direction of travel.+ assert!((lane_offset_m(0, 2, true, true, w) + w * 1.5).abs() < 1e-9);+ assert!((lane_offset_m(1, 2, true, true, w) + w * 0.5).abs() < 1e-9);+ // A one-way is the same either side of the world: there is no opposing carriageway to sit+ // beside.+ assert_eq!(lane_offset_m(0, 3, false, true, w), lane_offset_m(0, 3, false, false, w));+ }++ /// **The latitude invariant, and the whole reason the offset is not baked in ground metres.**+ ///+ /// The renderer's lane width is a screen-space quantity, and Web Mercator carries a `1 / cos φ`+ /// stretch, so a connector offset by a fixed *ground* distance drifts off the carriageway as+ /// you go north — by 2.3x at 60°N, which is more than two lane widths. Offsetting by a fixed+ /// *projected* distance is what makes it land, at every latitude and with no wire change.+ ///+ /// Measured end to end through the real encoder rather than on the helper, and asserted from+ /// both sides: the projected spread must match, and the ground spread must not — otherwise the+ /// test would still pass if the correction were quietly dropped.+ #[test]+ fn a_connectors_lateral_offset_is_the_same_projected_size_at_every_latitude() {+ // The correction itself: a lane's ground width shrinks toward the poles exactly as fast as+ // Mercator stretches it.+ assert!((lane_width_ground_m(0.0) - LANE_WIDTH_MERCATOR_M).abs() < 1e-9);+ assert!(+ (lane_width_ground_m(60.0) - LANE_WIDTH_MERCATOR_M * 0.5).abs() < 1e-6,+ "cos 60 is a half",+ );++ // The first three connectors are the north approach's, in `incoming.of(0)` order. They+ // share a setback and a heading, so the spread between their start points is purely the+ // lane offset.+ let spread = |lines: &[Vec<(f64, f64)>], project: &dyn Fn((f64, f64)) -> (f64, f64)| {+ let starts: Vec<(f64, f64)> = lines[..3].iter().map(|l| project(l[0])).collect();+ let mut worst: f64 = 0.0;+ for a in &starts {+ for b in &starts {+ worst = worst.max(((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt());+ }+ }+ worst+ };++ // 0.0009 deg of latitude is ~100 m anywhere; a degree of longitude shrinks with cos, so the+ // east/west arms need a wider step at 60 to stay the same distance out.+ let (_, at_equator) = stream(&crossroads_at(0, 9_000, &[]));+ let (_, at_sixty) = stream(&crossroads_at(600_000_000, 18_000, &[]));+ assert_eq!(at_equator.len(), 12);+ assert_eq!(at_sixty.len(), 12);++ // In projected units — what the renderer actually draws — the two must agree. z20 is an+ // arbitrary scale; Mercator is self-similar, so any zoom gives the same ratio.+ let mercator = |(lon, lat): (f64, f64)| tile_build::geom::project(lon, lat, 20);+ let projected_equator = spread(&at_equator, &mercator);+ let projected_sixty = spread(&at_sixty, &mercator);+ assert!(projected_equator > 0.0, "the lanes did not separate at all");+ assert!(+ (projected_sixty / projected_equator - 1.0).abs() < 0.02,+ "a lane must be the same projected width everywhere: {projected_equator} at the \+ equator vs {projected_sixty} at 60N",+ );++ // And in ground units they must differ by cos 60, which is what proves the correction is+ // being applied rather than the assertion above being vacuous. A degree of longitude is+ // `cos φ` shorter on the ground, and the north approach's offset is purely east-west.+ let ground = |(lon, lat): (f64, f64)| {+ (lon * METRES_PER_DEGREE * lat.to_radians().cos(), lat * METRES_PER_DEGREE)+ };+ let ground_ratio = spread(&at_sixty, &ground) / spread(&at_equator, &ground);+ assert!(+ (ground_ratio - 0.5).abs() < 0.02,+ "a lane's ground width should halve by 60N, not stay put: ratio {ground_ratio}",+ );+ }++ /// Which lane of the exit a connector lands in.+ #[test]+ fn a_turn_lands_in_the_exit_lane_its_direction_implies() {+ assert_eq!(exit_lane(Turn::Left, 0, 3, 2), 0, "a left turn takes the exit's left lane");+ assert_eq!(exit_lane(Turn::SharpLeft, 2, 3, 4), 0);+ assert_eq!(exit_lane(Turn::Right, 2, 3, 3), 2, "a right turn takes the rightmost");+ assert_eq!(exit_lane(Turn::Through, 0, 2, 2), 0, "a through movement holds its place");+ assert_eq!(exit_lane(Turn::Through, 1, 2, 2), 1);+ // Narrowing: the outermost lane cannot land past the exit's last.+ assert_eq!(exit_lane(Turn::Through, 3, 4, 2), 1);+ // A zero-lane exit cannot underflow.+ assert_eq!(exit_lane(Turn::Right, 0, 1, 0), 0);+ }++ /// `lanes.bin` is sparse, so absence is the answer for most edges and a missing file is not an+ /// error at all.+ #[test]+ fn a_sparse_lane_table_answers_only_for_the_edges_it_holds() {+ let fixture = crossroads(&[(1u32, vec![LANE_THROUGH]), (4u32, vec![LANE_LEFT, LANE_RIGHT])]);+ let table = LaneTable::load(&fixture.dir).expect("load").expect("a file was written");+ assert_eq!(table.masks(1), Some(vec![LANE_THROUGH]));+ assert_eq!(table.masks(4), Some(vec![LANE_LEFT, LANE_RIGHT]));+ assert_eq!(table.masks(0), None, "edge 0 is not in the index");+ assert_eq!(table.masks(3), None);+ assert_eq!(table.masks(99), None, "past every entry");++ let bare = crossroads(&[]);+ assert!(+ LaneTable::load(&bare.dir).expect("load").is_none(),+ "a graph built without lane data is not an error",+ );+ }++ /// The reverse index, which is the whole reason an approach can be found: `nodes.bin` is+ /// out-edges only.+ #[test]+ fn incoming_edges_are_recovered_from_a_graph_that_stores_only_outgoing_ones() {+ let fixture = crossroads(&[]);+ let graph = Graph::load(&fixture.dir).expect("graph");+ let incoming = InEdges::build(&graph).expect("reverse index");+ // Edges 4..7 all target the junction.+ assert_eq!(incoming.of(0), &[4, 5, 6, 7]);+ // Each outer node is fed by exactly the one edge leaving the junction toward it.+ assert_eq!(incoming.of(1), &[0]);+ assert_eq!(incoming.of(4), &[3]);+ // And every in-edge's source is recoverable from the same `edge_ptr` array.+ assert_eq!(source_of(&graph, 4), 1);+ assert_eq!(source_of(&graph, 7), 4);+ assert_eq!(source_of(&graph, 0), 0);+ assert_eq!(source_of(&graph, 3), 0);+ }++ /// A one-way approach is the case [`InEdges`] exists for: the junction has no out-edge back+ /// toward it, so [`Graph::has_drivable_twin`] could never find it.+ #[test]+ fn a_one_way_approach_is_found_even_though_nothing_leaves_the_junction_toward_it() {+ let coords: [(i32, i32); 4] = [+ (350_000_000, -1_200_000_000), // 0: the junction+ (350_009_000, -1_200_000_000), // 1: north, feeds in one-way+ (350_000_000, -1_199_988_000), // 2: east+ (349_991_000, -1_200_000_000), // 3: south+ ];+ let edge = |source, target| EdgeSpec { source, target, type_: 7, interior: Vec::new() };+ let fixture = write_graph(+ "junction_oneway",+ &coords,+ &[+ // The junction leaves only east and south. Nothing runs back north.+ edge(0, 2),+ edge(0, 3),+ // The one-way approach, plus two-way arms so the node has three neighbours.+ edge(1, 0),+ edge(2, 0),+ edge(3, 0),+ ],+ &[],+ );+ let graph = Graph::load(&fixture.dir).expect("graph");+ assert!(+ !graph.has_drivable_twin(0, 1).expect("twin"),+ "the fixture is only meaningful if nothing leaves the junction northward",+ );+ let (emitted, _) = stream(&fixture);+ // Three approaches. From the north: east and south are both legal (2). From the east: south+ // only, since the U-turn back east is excluded and nothing runs north (1). From the south:+ // east only (1).+ assert_eq!(emitted, 4, "the one-way approach contributes its two movements");+ }++ /// Left-hand traffic mirrors the connectors rather than leaving them on the wrong side.+ #[test]+ fn a_left_hand_traffic_country_gets_its_connectors_on_the_other_side() {+ let fixture = crossroads(&[]);+ let spill = fixture.dir.join("lht.tmp");++ let mut left = Conventions::default();+ // A ring around the fixture's coordinates, so its z6 cell is claimed for a left-hand+ // country. `add` takes lon/lat rings, outer first.+ left.add(+ "GB",+ &[vec![vec![+ (-121.0, 34.0),+ (-119.0, 34.0),+ (-119.0, 36.0),+ (-121.0, 36.0),+ (-121.0, 34.0),+ ]]],+ );++ let mut sink = Sink::create(&spill).expect("sink");+ stream_junctions(&fixture.dir, &left, &mut sink).expect("stream");+ let store = sink.finish(&spill).expect("finish");+ let mut reader = store.reader().expect("reader");+ let mut mirrored = Vec::new();+ while let Some(feature) = reader.next().expect("read") {+ if let Geometry::Lines(parts) = &feature.geometry {+ mirrored.push(parts[0].clone());+ }+ }+ let _ = std::fs::remove_file(&spill);++ let (_, right) = stream(&fixture);+ assert_eq!(mirrored.len(), right.len(), "the same movements exist either side of the world");+ assert_ne!(mirrored, right, "left-hand traffic must not draw the right-hand connectors");+ }+}
scripts/maps/mamaps_build/src/schema/mod.rs
diff --git a/scripts/maps/mamaps_build/src/schema/mod.rs b/scripts/maps/mamaps_build/src/schema/mod.rsindex 7434762290..9bcfc1ccc8 100644--- a/scripts/maps/mamaps_build/src/schema/mod.rs+++ b/scripts/maps/mamaps_build/src/schema/mod.rs@@ -26,6 +26,7 @@ use tilecodec::mamaps::dict; pub mod boundaries; pub mod buildings; pub mod earth;+pub mod junction; pub mod land; pub mod places; pub mod poi;@@ -164,6 +165,7 @@ pub struct Layers { pub poi: bool, pub transit: bool, pub traffic: bool,+ pub junction: bool, } impl Layers {@@ -185,6 +187,9 @@ impl Layers { // its data source (`--graph`) rather than an error: an archive with no traffic layer // is an obvious "no overlay", not the silent disaster an archive with no mainland is. traffic: true,+ // v7's lane connectors, from the same `--graph` and empty without it for the same+ // reason.+ junction: true, } } @@ -201,6 +206,7 @@ impl Layers { poi: false, transit: false, traffic: false,+ junction: false, } } @@ -220,10 +226,12 @@ impl Layers { "poi" => layers.poi = true, "transit" => layers.transit = true, "traffic" => layers.traffic = true,+ "junction" => layers.junction = true, other => { return Err(format!( "unknown layer `{other}`; this generator produces earth, water, buildings, \- roads, boundaries, landcover, landuse, places, poi, transit and traffic"+ roads, boundaries, landcover, landuse, places, poi, transit, traffic and \+ junction" )) } }@@ -248,6 +256,7 @@ impl Layers { dict::LAYER_POI => self.poi, dict::LAYER_TRANSIT => self.transit, dict::LAYER_TRAFFIC => self.traffic,+ dict::LAYER_JUNCTION => self.junction, _ => false, } }@@ -421,7 +430,7 @@ mod tests { Layers { water: true, ..Layers::none() }, ); assert_eq!(- Layers::parse("earth,water,buildings,roads,boundaries,landcover,landuse,places,poi,transit,traffic")+ Layers::parse("earth,water,buildings,roads,boundaries,landcover,landuse,places,poi,transit,traffic,junction") .expect("all"), Layers::all(), );
scripts/maps/mamaps_build/src/schema/traffic.rs
diff --git a/scripts/maps/mamaps_build/src/schema/traffic.rs b/scripts/maps/mamaps_build/src/schema/traffic.rsindex 3ee89a0849..7845a7350f 100644--- a/scripts/maps/mamaps_build/src/schema/traffic.rs+++ b/scripts/maps/mamaps_build/src/schema/traffic.rs@@ -100,7 +100,7 @@ const RANK_BLOCK_BYTES: usize = 64; /// `type_` bit 6: this edge stores no geometry of its own; its twin runs `target -> source`. const REVERSE_GEOMETRY_FLAG: u8 = 0x40; /// The low six bits of `type_` are the road class.-const ROAD_TYPE_MASK: u8 = 0x3F;+pub(crate) const ROAD_TYPE_MASK: u8 = 0x3F; /// A `target_delta` of `i16::MIN` means the true target is in the escape table. const TARGET_DELTA_ESCAPE: i16 = i16::MIN; /// A `dist` u24 of all-ones means the true target and distance are in the escape table.@@ -149,11 +149,14 @@ fn edge_bitmap_bytes(edges: u64) -> usize { /// The subset of the v6 graph reader the traffic layer needs: node coordinates, edge targets and /// types, and big-edge geometry. Names, distances and speed limits are skipped — the server reads /// those; the archive carries only geometry and the id.-struct Graph {+///+/// `pub(crate)` because [`crate::schema::junction`] reads the same four files for the same reason+/// and must not carry a second copy of this byte layout.+pub(crate) struct Graph { nodes: Vec<u8>, edges: Vec<u8>, inter: Vec<u8>,- node_count: u64,+ pub(crate) node_count: u64, escape_first_off: usize, escapes_off: usize, // intermediate.bin sub-table offsets@@ -164,7 +167,7 @@ struct Graph { } impl Graph {- fn load(dir: &Path) -> Result<Graph> {+ pub(crate) fn load(dir: &Path) -> Result<Graph> { let read = |name: &str| -> Result<Vec<u8>> { let path = dir.join(name); std::fs::read(&path)@@ -260,24 +263,24 @@ impl Graph { } /// A node's `(lat_e7, lon_e7)`.- fn node(&self, n: u64) -> (i32, i32) {+ pub(crate) fn node(&self, n: u64) -> (i32, i32) { let base = (n as usize) * 12; (i32_at(&self.nodes, base), i32_at(&self.nodes, base + 4)) } /// A node's first outgoing edge index. The sentinel record (index `node_count`) holds /// `edge_count`, so `edge_ptr(n+1)` is always defined for a real node `n`.- fn edge_ptr(&self, n: u64) -> u32 {+ pub(crate) fn edge_ptr(&self, n: u64) -> u32 { u32_at(&self.nodes, (n as usize) * 12 + 8) } - fn edge_type(&self, idx: u32) -> u8 {+ pub(crate) fn edge_type(&self, idx: u32) -> u8 { self.edges[(idx as usize) * 7 + 5] } /// The target node of edge `idx` whose source is `s`, decoding the escape table when the /// delta or distance is sentinelled.- fn edge_target(&self, idx: u32, s: u32) -> Result<u32> {+ pub(crate) fn edge_target(&self, idx: u32, s: u32) -> Result<u32> { let base = (idx as usize) * 7; let delta = i16_at(&self.edges, base); let dist = (self.edges[base + 2] as u32)@@ -304,7 +307,7 @@ impl Graph { } /// Does edge `idx` store an interior-point blob?- fn geom_contains(&self, idx: u32) -> bool {+ pub(crate) fn geom_contains(&self, idx: u32) -> bool { let byte = self.geom_present_off + (idx as usize) / 8; self.inter[byte] & (1u8 << (idx % 8)) != 0 }@@ -342,7 +345,7 @@ impl Graph { /// The full polyline of edge `idx` in canonical `source -> target` order, as `(lat_e7, lon_e7)` /// vertices: the source node, any stored interior points, then the target node.- fn polyline(&self, idx: u32, s: u32, t: u32) -> Vec<(i32, i32)> {+ pub(crate) fn polyline(&self, idx: u32, s: u32, t: u32) -> Vec<(i32, i32)> { let (slat, slon) = self.node(s as u64); let (tlat, tlon) = self.node(t as u64); let mut out = Vec::with_capacity(4);@@ -370,7 +373,7 @@ impl Graph { /// Is there a drivable edge running `from -> to`? Used to tell a straight two-way chord (which /// has such a twin and is emitted only in the canonical direction) from a one-way (which has /// none and is always emitted).- fn has_drivable_twin(&self, from: u32, to: u32) -> Result<bool> {+ pub(crate) fn has_drivable_twin(&self, from: u32, to: u32) -> Result<bool> { let lo = self.edge_ptr(from as u64); let hi = self.edge_ptr(from as u64 + 1); for e in lo..hi {@@ -444,19 +447,21 @@ pub fn stream_graph(dir: &Path, sink: &mut Sink) -> Result<u64> { } #[cfg(test)]-mod tests {+pub(crate) mod tests { use super::*; - /// Build a minimal but real v6 graph on disk and stream it, so the reader is exercised against- /// the exact byte layout the contract specifies rather than a mock.- ///- /// Four nodes in a square. Edges:- /// * 0: node0 -> node1, one-way, curved (one interior point). Emitted: 2 segments.- /// * 1: node1 -> node2, straight two-way (canonical, `1 < 2`). Emitted: 1 segment.- /// * 2: node2 -> node1, straight two-way (non-canonical twin of edge 1). Skipped.- /// * 3: node2 -> node3, pedestrian (type 10). Skipped (not drivable).- struct GraphFixture {- dir: std::path::PathBuf,+ /// One directed edge of a synthetic graph.+ pub(crate) struct EdgeSpec {+ pub source: u32,+ pub target: u32,+ pub type_: u8,+ /// Interior points as `(d_lat, d_lon)` deltas, chained from the source. An empty list is a+ /// straight chord, which is how the presence bitmap says "this edge stores no geometry".+ pub interior: Vec<(i16, i16)>,+ }++ pub(crate) struct GraphFixture {+ pub dir: std::path::PathBuf, } impl Drop for GraphFixture { fn drop(&mut self) {@@ -464,28 +469,35 @@ mod tests { } } - fn write_fixture() -> GraphFixture {+ /// Write a real v6 graph to a fresh temp directory, byte for byte as the contract specifies.+ ///+ /// `pub(crate)` because [`crate::schema::junction`] reads the same four files and tests against+ /// the same layout; a second writer would be a second chance to disagree with `osm_ingest`.+ ///+ /// `edges` must be grouped by `source` ascending, which is what makes `nodes.bin`'s `edge_ptr`+ /// a CSR row pointer. `lanes` is `(edge_idx, masks)` ascending, and writes no `lanes.bin` at+ /// all when empty — which is the common shape of a real graph.+ pub(crate) fn write_graph(+ tag: &str,+ coords: &[(i32, i32)],+ edges: &[EdgeSpec],+ lanes: &[(u32, Vec<u16>)],+ ) -> GraphFixture { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); let dir = std::env::temp_dir().join(format!(- "mamaps_traffic_{}_{}",+ "mamaps_{tag}_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed), )); std::fs::create_dir_all(&dir).expect("mkdir"); - // Nodes at e7 coordinates. (lat_e7, lon_e7).- let coords: [(i32, i32); 4] = [- (35_000_000, -120_000_000),- (35_000_000, -119_990_000),- (35_010_000, -119_990_000),- (35_010_000, -120_000_000),- ];- // edge_ptr per node, then the sentinel. node0 owns edge 0; node1 owns edge 1; node2 owns- // edges 2,3; node3 owns none.- let edge_ptr: [u32; 5] = [0, 1, 2, 4, 4];- let node_count = 4u64;- let edge_count = 4u64;+ let node_count = coords.len() as u64;+ let edge_count = edges.len() as u64;+ assert!(+ edges.windows(2).all(|w| w[0].source <= w[1].source),+ "a CSR row pointer needs the edges grouped by source",+ ); // metadata.bin (40 bytes). let mut meta = Vec::new();@@ -497,92 +509,128 @@ mod tests { meta.extend_from_slice(&0u64.to_le_bytes()); // named_edges std::fs::write(dir.join("metadata.bin"), &meta).expect("meta"); - // nodes.bin: NodeRec[node_count + 1], 12 bytes each.+ // nodes.bin: NodeRec[node_count + 1], 12 bytes each. `edge_ptr` is the index of the first+ // edge leaving each node, and the sentinel holds `edge_count`. let mut nodes = Vec::new();- for n in 0..node_count as usize {- nodes.extend_from_slice(&coords[n].0.to_le_bytes());- nodes.extend_from_slice(&coords[n].1.to_le_bytes());- nodes.extend_from_slice(&edge_ptr[n].to_le_bytes());+ for (n, (lat, lon)) in coords.iter().enumerate() {+ let first = edges.iter().position(|e| e.source as usize >= n).unwrap_or(edges.len());+ nodes.extend_from_slice(&lat.to_le_bytes());+ nodes.extend_from_slice(&lon.to_le_bytes());+ nodes.extend_from_slice(&(first as u32).to_le_bytes()); }- // Sentinel: coords don't matter, edge_ptr == edge_count. nodes.extend_from_slice(&0i32.to_le_bytes()); nodes.extend_from_slice(&0i32.to_le_bytes());- nodes.extend_from_slice(&edge_ptr[node_count as usize].to_le_bytes());+ nodes.extend_from_slice(&(edge_count as u32).to_le_bytes()); std::fs::write(dir.join("nodes.bin"), &nodes).expect("nodes"); - // edges.bin. EdgeRec[edge_count], 7 bytes: i16 target_delta, u24 dist, u8 type_, u8 speed.- let edge = |source: i64, target: i64, type_: u8| -> [u8; 7] {- let delta = (target - source) as i16;- let mut r = [0u8; 7];- r[0..2].copy_from_slice(&delta.to_le_bytes());+ // edges.bin: EdgeRec[edge_count], 7 bytes: i16 target_delta, u24 dist, u8 type_, u8 speed.+ let mut raw = Vec::new();+ for e in edges {+ let delta = (i64::from(e.target) - i64::from(e.source)) as i16;+ raw.extend_from_slice(&delta.to_le_bytes()); // dist: a plausible non-escape value.- r[2] = 0x10;- r[3] = 0x00;- r[4] = 0x00;- r[5] = type_;- r[6] = 50; // speed_limit- r- };- let mut edges = Vec::new();- edges.extend_from_slice(&edge(0, 1, 1)); // edge 0: 0->1 motorway, curved (geometry set below)- edges.extend_from_slice(&edge(1, 2, 7)); // edge 1: 1->2 residential, straight- edges.extend_from_slice(&edge(2, 1, 7)); // edge 2: 2->1 residential, straight (twin of 1)- edges.extend_from_slice(&edge(2, 3, 10)); // edge 3: 2->3 pedestrian, not drivable- // Pad EdgeRec section to an 8-byte boundary.- while edges.len() % 8 != 0 {- edges.push(0);+ raw.extend_from_slice(&[0x10, 0x00, 0x00]);+ raw.push(e.type_);+ raw.push(50); // speed_limit }- // escape_first: u32[escape_blocks], all zero (no escapes). escape_blocks = ceil(4/1024)+1 = 2.- let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;- for _ in 0..escape_blocks {- edges.extend_from_slice(&0u32.to_le_bytes());+ // Pad the EdgeRec section to an 8-byte boundary, then the all-zero escape block index.+ while raw.len() % 8 != 0 {+ raw.push(0);+ }+ for _ in 0..(edge_count.div_ceil(ESCAPE_BLOCK) + 1) {+ raw.extend_from_slice(&0u32.to_le_bytes()); }- // No escape rows, no names.- std::fs::write(dir.join("edges.bin"), &edges).expect("edges");+ std::fs::write(dir.join("edges.bin"), &raw).expect("edges"); - // intermediate.bin. Only edge 0 carries geometry (one interior point).- // blob: one interior point for edge 0, as (i16 d_lat, i16 d_lon) from node0.+ // intermediate.bin: the interior-point blob, then the presence bitmap, the coarse offsets+ // and the per-geometry-edge within-block offsets, then the geometry-edge count. let mut blob = Vec::new();- // interior point roughly midway, curving off the straight chord.- let d_lat: i16 = 3_000; // +0.0003 deg- let d_lon: i16 = -
Diff truncated.