Modern Apps git

← Modern-Apps.git

maps: carriageway surfaces with painted lane markings

Commit
74a516f03ea1d54aa9425cb7bb5853bb7998ef18
Author
vayun-mathur <[email protected]>
When
2026-09-10 05:54 UTC (2 months ago)
Parents
ff12bb4

Diff

library/map/src/main/rust/shaders/road_surface.frag
diff --git a/library/map/src/main/rust/shaders/road_surface.frag b/library/map/src/main/rust/shaders/road_surface.fragnew file mode 100644index 0000000000..596ed5b0f6--- /dev/null+++ b/library/map/src/main/rust/shaders/road_surface.frag@@ -0,0 +1,147 @@+#version 450+// Road surface fragment: asphalt, then the markings painted onto it.+//+// Everything here is a function of `t` — the across-the-road coordinate, exactly -1 at+// one kerb and +1 at the other — and of the distance along the carriageway. There is no+// marking geometry at all. That is the point of the ribbon: the old `lane_fans` path+// re-stroked a road's entire geometry once per divider, so an eight-lane road paid seven+// extra full strokes to draw seven hairlines. Here they cost arithmetic.+//+// # Which coverage terms are gated by `misc.y`, and which are not+//+// `misc.y` says whether this pass owns edge antialiasing — it is 0 under MSAA, where the+// rasteriser already resolves partial coverage and a second coverage term on top fades a+// diagonal road twice (`line.frag` documents the z6 case that forced this).+//+// That reasoning applies to the **carriageway silhouette** and to nothing else. A marking+// is painted *inside* a fully covered triangle, so the rasteriser sees no edge there and+// resolves nothing: MSAA cannot antialias a lane divider. Its coverage term is therefore+// unconditional. Gating the markings on `misc.y` too would leave every marking hard-edged+// on the MSAA path, and a hard-edged sub-pixel line crawls and flickers as it drifts+// across pixel centres while panning — far more visible than the road edge ever was.+//+// For the same reason every marking edge is derived in **pixels**, never in `t`. A fixed+// width in `t` is a fixed fraction of the road, so it would grow and shrink with zoom and+// go sub-pixel at exactly the zoom where the aliasing is worst.+//+// # Why markings fade out rather than shrink to nothing+//+// Marking widths are proportional to the lane (a real marking is a real width on the+// ground), floored so they stay rasterisable. Left alone, that floor is what a low zoom+// converges to: at a few pixels per lane the floors of the edge lines, the dividers and+// the centre line together are wider than the road, and a motorway renders as a white+// smear. So markings ramp off once a lane is too narrow to read one on, and the asphalt+// is left plain — which is also what the road looked like before any of this existed.+layout(location = 0) in float inT;+layout(location = 1) in float inDistancePx;+layout(location = 0) out vec4 outColor;+layout(push_constant) uniform Push {+    mat4 tileToClip;+    // The carriageway's asphalt colour.+    vec4 color;+    // Repurposed for the ribbon; see the `Push` doc comment in `vulkan/pipeline.rs`,+    // which is the contract the renderer fills in.+    // x: carriageway half-width px, y: lane count, z: centre-line `t`, w: oneway flag.+    vec4 line;+    // x: tile span in px, y: 1 when the pass is single-sampled and this shader owns the+    // carriageway's edge antialiasing, z: 1 when the centre line is yellow,+    // w: the per-frame clock in seconds.+    vec4 misc;+    vec4 morph;+} push;++// Mirrors `style::paint::MIN_HALF_WIDTH_PX`; must match `road_surface.vert`.+const float MIN_HALF_WIDTH_PX = 0.5;++// A painted marking is about 0.15 m in a lane about 3.5 m wide. Held as a fraction of the+// lane rather than an absolute width so it stays a ground measurement across zooms.+const float MARK_WIDTH_LANES = 0.045;+// Below half a pixel a marking falls between pixel centres and stipples, so it is widened+// to something the rasteriser can hit and the fade below takes it away instead.+const float MIN_MARK_HALF_PX = 0.5;+// The lane widths between which markings ramp in. Under the lower bound a lane is a few+// pixels across and its markings would be most of it.+const float MARK_FADE_START_PX = 4.0;+const float MARK_FADE_FULL_PX = 10.0;+// Divider dash and gap, in lane widths: roughly the 3 m line and 9 m gap that is the+// common standard. Tied to the lane so the dash is a ground length, like the widths.+const float DASH_ON_LANES = 0.9;+const float DASH_OFF_LANES = 2.6;+// Markings are painted, not lit, so they are a flat off-white rather than pure white,+// which reads as a blown highlight against the asphalt.+const vec3 MARK_WHITE = vec3(0.92, 0.92, 0.90);+const vec3 MARK_YELLOW = vec3(0.95, 0.76, 0.18);++// The 1px box filter `line.frag` uses, over a signed pixel distance from a band's centre.+// Shared rather than a smoothstep so a marking edge and a road edge fade identically.+float band(float distancePx, float halfPx) {+    return clamp(halfPx - distancePx + 0.5, 0.0, 1.0);+}++void main() {+    float wantHalfPx = push.line.x;+    float halfWidthPx = max(wantHalfPx, MIN_HALF_WIDTH_PX);+    // Hand back the width the vertex shader added to make the quad rasterisable, so a+    // hairline road at low zoom draws faint rather than solid.+    float coverage = clamp(wantHalfPx / halfWidthPx, 0.0, 1.0);+    // `t` interpolates linearly across the ribbon, so this is the same signed+    // one-unit-per-screen-pixel measure `line.frag` calls `inEdgePx`.+    float edgePx = inT * halfWidthPx;+    coverage *= mix(1.0, band(abs(edgePx), halfWidthPx), push.misc.y);+    if (coverage <= 0.0) discard;++    float lanes = max(push.line.y, 1.0);+    float lanePx = 2.0 * halfWidthPx / lanes;+    float legible =+        clamp((lanePx - MARK_FADE_START_PX) / (MARK_FADE_FULL_PX - MARK_FADE_START_PX), 0.0, 1.0);++    vec3 rgb = push.color.rgb;+    if (legible > 0.0) {+        float markHalfPx = max(lanePx * MARK_WIDTH_LANES * 0.5, MIN_MARK_HALF_PX);+        bool oneway = push.line.w >= 0.5;+        float centreT = push.line.z;++        // Lane-index space: 0 at one kerb, `lanes` at the other, so a lane boundary is an+        // integer and the nearest one is a rounding away.+        float lane = (inT * 0.5 + 0.5) * lanes;+        float boundary = round(lane);+        float boundaryT = boundary / lanes * 2.0 - 1.0;+        // Boundary 0 and boundary `lanes` are the kerbs, which carry the solid edge line+        // rather than a divider.+        bool interior = boundary > 0.5 && boundary < lanes - 0.5;+        // The boundary the opposing traffic meets at is the centre line, not a divider —+        // otherwise a white dash is painted straight over the yellow. Half a lane in `t`+        // is `1 / lanes`, so exactly one boundary can match. Identifying the boundary is+        // the one thing done in `t`; its edges are still placed in pixels below.+        bool isCentre = !oneway && abs(boundaryT - centreT) < 1.0 / lanes;++        float dashed = 0.0;+        if (interior && !isCentre) {+            float on = DASH_ON_LANES * lanePx;+            float period = on + DASH_OFF_LANES * lanePx;+            float along = mod(inDistancePx, period);+            // Soft at both ends of the dash for the same reason the sides are soft: a hard+            // dash end is a sub-pixel edge that crawls when the map pans.+            dashed = clamp(min(along, on - along) + 0.5, 0.0, 1.0);+            dashed *= band(abs(lane - boundary) * lanePx, markHalfPx);+        }+        rgb = mix(rgb, MARK_WHITE, dashed * legible);++        // The edge lines sit flush inside the kerb, so their outer side lands on the rim+        // of the carriageway and the road reads as having a painted border rather than a+        // white line floating near one.+        float edgeCentrePx = max(halfWidthPx - markHalfPx, 0.0);+        float edgeLine = band(abs(abs(edgePx) - edgeCentrePx), markHalfPx);+        rgb = mix(rgb, MARK_WHITE, edgeLine * legible);++        // The centre line last, so it wins wherever it overlaps. A one-way carriageway has+        // no opposing traffic and so has no centre line at all — not a white one.+        if (!oneway) {+            float centreLine = band(abs(edgePx - centreT * halfWidthPx), markHalfPx);+            vec3 centreRgb = push.misc.z >= 0.5 ? MARK_YELLOW : MARK_WHITE;+            rgb = mix(rgb, centreRgb, centreLine * legible);+        }+    }++    outColor = vec4(rgb, push.color.a * coverage);+}
library/map/src/main/rust/shaders/road_surface.vert
diff --git a/library/map/src/main/rust/shaders/road_surface.vert b/library/map/src/main/rust/shaders/road_surface.vertnew file mode 100644index 0000000000..862f55ecf3--- /dev/null+++ b/library/map/src/main/rust/shaders/road_surface.vert@@ -0,0 +1,71 @@+#version 450+// Road surface: extrudes the carriageway centreline to its screen-space width and+// hands the fragment stage an across-the-road coordinate.+//+// # Why this is not `line.vert` with another attribute+//+// A stroke has no across-the-road coordinate, so a marking cannot be placed on it —+// which is the whole reason `tess::stroke` cannot draw a lane divider without+// re-stroking the road once per divider. What the ribbon adds is `t`, a genuine+// normalised across-coordinate that is exactly -1 at one kerb and +1 at the other,+// so `road_surface.frag` can paint every marking as a function of `t` alone with no+// extra geometry at all.+//+// It is a separate pipeline rather than a wider shared vertex format because+// `TrafficMesh` and the route overlay both ride the 7-float line format and the line+// pipeline; widening that to serve the roads layer would make every one of them pay+// for four bytes they never read. `tile/geometry.rs` already states this tradeoff.+//+// # Width still lives here, not in the vertices+//+// Same invariant as `line.vert`, and for the same reason: a carriageway's width is a+// screen measurement that ramps continuously with zoom, so baking it into vertices+// would re-tessellate every road in every visible tile on every zoom step, while+// panning, on the critical path. The tessellator emits the centreline point, the+// unit normal of the join and `t`; the half-width arrives as a push constant and the+// offset is+//+//   offset = normal * (t * halfWidth)+//+// `t` doubles as the extrusion multiplier and as the fragment stage's marking+// coordinate, which is what keeps the vertex to six floats.+layout(location = 0) in vec2 inPosition;+layout(location = 1) in vec2 inNormal;+layout(location = 2) in float inT;+layout(location = 3) in float inDistance;+layout(location = 0) out float outT;+layout(location = 1) out float outDistancePx;+layout(push_constant) uniform Push {+    mat4 tileToClip;+    vec4 color;+    // Repurposed for the ribbon; see the `Push` doc comment in `vulkan/pipeline.rs`,+    // which is the contract the renderer fills in.+    // x: carriageway half-width px, y: lane count, z: centre-line `t`, w: oneway flag.+    vec4 line;+    // x: tile span in px, y: 1 when this pass owns edge antialiasing,+    // z: 1 when the centre line is yellow, w: the per-frame clock in seconds.+    vec4 misc;+    vec4 morph;+} push;++// Mirrors `style::paint::MIN_HALF_WIDTH_PX`; must match `road_surface.frag`.+const float MIN_HALF_WIDTH_PX = 0.5;++void main() {+    float wantHalfPx = push.line.x;+    float tilePx = max(push.misc.x, 1.0);+    // A carriageway thinner than a pixel falls between pixel centres and rasterises as+    // stipple, so give it a pixel of geometry to land on and let the fragment stage take+    // the difference back off as alpha. Identical to `line.vert`, so a hairline road at+    // low zoom fades rather than snapping to full strength.+    float halfWidthPx = max(wantHalfPx, MIN_HALF_WIDTH_PX);+    // The offset is a pixel distance and the normal is a unit vector in tile-local+    // space, so dividing by the tile's pixel size converts one to the other.+    vec2 offsetTile = inNormal * (inT * halfWidthPx / tilePx);+    gl_Position = push.tileToClip * vec4(inPosition + offsetTile, 0.0, 1.0);+    outT = inT;+    // Distance along the carriageway in pixels, for the divider dash phase. Scaled here+    // rather than in the tessellator for the same reason the width is: the attribute is+    // tile-local so the geometry stays a function of the tile alone.+    outDistancePx = inDistance * tilePx;+}
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 5bfb2d2283..302e3c469d 100644--- a/library/map/src/main/rust/src/style/mod.rs+++ b/library/map/src/main/rust/src/style/mod.rs@@ -331,6 +331,11 @@ pub struct Layer {     /// z6 where the ramp asks for half.     pub opacity: Ramp,     /// Stroke width in Dp. Zero for a fill.+    ///+    /// On a [`carriageway`](Self::carriageway) layer it is one **lane's** width instead, and the+    /// road's own width is that times the lanes the feature carries. A single number cannot serve+    /// both a two-lane street and an eight-lane motorway, and the lane count is the feature's,+    /// not the style's.     pub width: Ramp,     /// Gap between the two halves of a casing, in Dp.     ///@@ -352,6 +357,17 @@ pub struct Layer {     /// ([`tilecodec::mamaps::body::Feature::transit_ordinal`]) and     /// [`Layer::lane_offset_px`] turns the three into a lateral offset per frame.     pub lanes: Ramp,+    /// Draw this line layer's features as carriageway surfaces rather than strokes.+    ///+    /// A stroke is a band of one colour, so nothing can be painted *within* it — which is why the+    /// divider fan this replaces had to re-stroke a road once per lane boundary. A carriageway+    /// ribbon ([`crate::tess::ribbon`]) carries an across-road coordinate, so every marking is+    /// arithmetic in `road_surface.frag` over one mesh.+    ///+    /// A flag on a line layer rather than a fourth [`LayerKind`], because the kind is what decides+    /// a [`crate::tile::geometry::LayerMesh`]'s stride and pipeline and a carriageway is not one:+    /// it has its own mesh list and its own render pass.+    pub carriageway: bool,     /// Dash and gap lengths in line widths, as `line-dasharray` defines them.     pub dash: (f32, f32),     /// Halo color (ARGB), light and dark. The authored `text-halo-color` per layer;@@ -547,12 +563,9 @@ impl Layer {     /// down each centreline?     ///     /// True when the style gives the layer a [`spread`](Self::spread) — the sideways step between-    /// adjacent lanes. Two layers set it: `transit-rail`, whose features fan by their colour-    /// ordinal, and `roads-lanes`, whose road features fan into one divider line per interior lane-    /// boundary from the feature's `lane_count`. The two never collide: a transit feature carries a-    /// `transit_color` and takes the colour-split path before this is consulted, while a road-    /// carries none. `lanes` defaults to 1 and so cannot be the discriminator; `spread` defaults to-    /// 0 and is only ever set on purpose.+    /// adjacent lanes. Only `transit-rail` sets it, fanning its features by their colour ordinal.+    /// `lanes` defaults to 1 and so cannot be the discriminator; `spread` defaults to 0 and is only+    /// ever set on purpose.     pub fn lane_fan(&self) -> bool {         self.spread.peak() > 0.0     }@@ -678,16 +691,18 @@ pub fn layers() -> &'static [Layer] {     &paint::style().layers } -/// The road lane layer, whose `spread`/`lanes` ramps fan per-lane geometry across a road and-/// whose zoom window gates it.+/// 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 the roads source as well as the fan. [`Layer::lane_fan`] only asks "does this-/// layer have a spread", and `transit-rail` has one for its corridor colours and is declared-/// first, so matching on the fan alone silently answers with the rail layer — whose `minzoom`-/// is 8 against the road lanes' 16. That is what drew turn arrows from z8, offset by the rail-/// corridor's ramp instead of the road's.-pub fn road_lane_layer(layers: &[Layer]) -> Option<&Layer> {-    layers.iter().find(|l| l.lane_fan() && l.source_layer_id == dict::LAYER_ROADS)+/// 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.+pub fn road_carriageway_layer(layers: &[Layer]) -> Option<&Layer> {+    layers.iter().find(|l| l.carriageway) }  #[cfg(test)]@@ -822,19 +837,20 @@ mod tests {     /// Turn arrows are gated by the *road* lane layer, not by whichever layer happens to be the     /// first with a spread.     ///-    /// `transit-rail` carries a spread for its corridor colours and is declared before-    /// `roads-lanes`, so a `find(|l| l.lane_fan())` answers with the rail layer and its-    /// `minzoom: 8`. That shipped: turn arrows drew from z8, four zoom levels of dense per-frame-    /// CPU triangle building for geometry that belongs at z16. Pinned against the real style-    /// because the bug was entirely in the interaction between the predicate and the declaration-    /// order — a hand-built two-layer fixture would have passed.+    /// `transit-rail` carries a spread for its corridor colours and is declared before the road+    /// layer, so a `find(|l| l.lane_fan())` answers with the rail layer and its `minzoom: 8`. That+    /// shipped: turn arrows drew from z8, four zoom levels of dense per-frame CPU triangle building+    /// for geometry that belongs at z16. Pinned against the real style because the bug was entirely+    /// in the interaction between the predicate and the declaration order — a hand-built two-layer+    /// fixture would have passed.     #[test]     fn turn_arrows_are_gated_by_the_road_lane_layer() {-        let gate = road_lane_layer(layers()).expect("the road lane layer");-        assert_eq!(gate.id, "roads-lanes", "not `transit-rail`, which also has a spread");+        let gate = road_carriageway_layer(layers()).expect("the road carriageway layer");+        assert_eq!(gate.id, "roads-carriageway", "not `transit-rail`, which has a spread");          let rail = find("transit-rail");         assert!(rail.lane_fan(), "the rail corridor fan is what made the naive predicate wrong");+        assert!(!rail.carriageway, "and a corridor fan is not a carriageway");         assert!(rail.min_zoom < gate.min_zoom, "and it is the earlier of the two");          assert!(!gate.draws_at(12), "no turn arrows at z12");
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 e7c7dcd821..ba4922593b 100644--- a/library/map/src/main/rust/src/style/paint.rs+++ b/library/map/src/main/rust/src/style/paint.rs@@ -262,6 +262,7 @@ fn layer(json: &Json) -> Result<Layer, String> {         "gap_width",         "spread",         "lanes",+        "carriageway",         "dash",         "text_size",         "text_size_large",@@ -441,6 +442,7 @@ fn layer(json: &Json) -> Result<Layer, String> {         gap_width: Ramp::parse(json.get("gap_width"), &id, "gap_width", 0.0)?,         spread: Ramp::parse(json.get("spread"), &id, "spread", 0.0)?,         lanes: Ramp::parse(json.get("lanes"), &id, "lanes", 1.0)?,+        carriageway: json.get("carriageway").and_then(Json::as_bool).unwrap_or(false),         dash,         text_size: Ramp::parse(json.get("text_size"), &id, "text_size", 0.0)?,         // Optional second arm: present only where the authored style's `text-size` is a@@ -556,8 +558,8 @@ mod tests {         //         // 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-lanes` divider layer (task WS-D) that draws a multi-lane carriageway's-        // individual lanes at z16+: the authored+        // `roads-carriageway` layer that draws a road's surface and its lane markings at+        // z16+: 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@@ -1365,11 +1367,12 @@ mod tests {     fn the_flat_style_agrees_with_basemap_json() {         let root = basemap();         for layer in layers() {-            // `roads-lanes` is an app-only layer: it draws a multi-lane carriageway's individual-            // lane dividers, which the authored `basemap.json` has no concept of. Its width, colour-            // and spread are all deliberately its own, so — like transit's width — it is pinned by-            // its own test (`road_lanes_fan_is_gated_and_spread`) rather than cross-checked here.-            if layer.id == "roads-lanes" {+            // `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" {                 continue;             }             let authored = authored_layer(&root, &layer.authored);@@ -1590,32 +1593,40 @@ mod tests {         assert_eq!(layer.lanes.at(11.0).floor(), 3.0, "three from z11");         assert_eq!(layer.lanes.at(13.0).floor(), 4.0, "four from z13");         assert_eq!(layer.lanes.at(20.0).floor(), 4.0, "and it stays there");-        // Nothing else moves sideways, or every road in the style would — except `roads-lanes`,-        // which fans a multi-lane carriageway into its individual lane dividers by the same-        // mechanism. Its own configuration is pinned by `road_lanes_fan_is_gated_and_spread`.-        for other in layers().iter().filter(|l| l.id != "transit-rail" && l.id != "roads-lanes") {+        // Nothing else moves sideways, or every road in the style would. The road lane fan used to+        // be the one exception; the carriageway that replaced it needs no spread at all, because a+        // marking's place across the road is a coordinate in the mesh rather than an offset of it.+        for other in layers().iter().filter(|l| l.id != "transit-rail") {             assert_eq!(other.spread.peak(), 0.0, "{} must not spread", other.id);             assert_eq!(other.lanes.peak(), 1.0, "{} must not fan out", other.id);         }     } -    /// The road lane fan: `roads-lanes` is the one road layer that spreads, it only appears once-    /// the camera is close enough to make lanes legible, and its lane ramp is high enough to draw-    /// every interior divider of the widest roads. Every other layer is held to no-spread by-    /// `transit_lanes_step_with_zoom_over_a_constant_spacing`.+    /// The road carriageway: `roads-carriageway` is the one layer drawn as a road 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.     #[test]-    fn road_lanes_fan_is_gated_and_spread() {-        let layer = find("roads-lanes");-        assert!(layer.lane_fan(), "roads-lanes must fan into lanes");-        assert_eq!(layer.min_zoom, 16, "the dense lane layer is gated to high zoom");-        assert!(!layer.draws_at(15), "no lanes at z15");-        assert!(layer.draws_at(16), "lanes from z16");-        // The spacing grows with zoom (a lane is a ground distance, unlike a transit corridor's-        // constant screen spacing), and is zero below the gate's reach.-        assert!(layer.spread.at(16.0) > 0.0, "a lane has width at z16");-        assert!(layer.spread.at(20.0) > layer.spread.at(16.0), "and it widens zooming in");-        // High enough that `min(style.lanes, dividers)` never caps a real road's divider count.-        assert!(layer.lanes.at(16.0).floor() >= 7.0, "up to an eight-lane road's dividers");+    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");+        assert_eq!(+            layers().iter().filter(|l| l.carriageway).count(),+            1,+            "exactly one layer draws road surfaces",+        );+        assert_eq!(layer.min_zoom, 16, "the dense lane detail is gated to high zoom");+        assert!(!layer.draws_at(15), "no carriageway at z15");+        assert!(layer.draws_at(16), "a carriageway from z16");+        // A lane is a ground width, so it grows with zoom — roughly the 3.5 m real lane at each of+        // 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");+        // 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");+        assert_ne!(layer.light, road.light);+        assert_ne!(layer.dark, road.dark);     }      /// The `kind` values an authored filter admits, or empty for "any of them".
library/map/src/main/rust/src/tess/mod.rs
diff --git a/library/map/src/main/rust/src/tess/mod.rs b/library/map/src/main/rust/src/tess/mod.rsindex 4e725251bf..80017c9fb2 100644--- a/library/map/src/main/rust/src/tess/mod.rs+++ b/library/map/src/main/rust/src/tess/mod.rs@@ -6,6 +6,7 @@  pub mod earcut; pub mod fill;+pub mod ribbon; pub mod roof; pub mod stroke; pub mod terrain;
library/map/src/main/rust/src/tess/ribbon.rs
diff --git a/library/map/src/main/rust/src/tess/ribbon.rs b/library/map/src/main/rust/src/tess/ribbon.rsnew file mode 100644index 0000000000..0c18684209--- /dev/null+++ b/library/map/src/main/rust/src/tess/ribbon.rs@@ -0,0 +1,308 @@+//! Turns a road centreline into the carriageway surface lane markings are painted on.+//!+//! # Why a ribbon is not just a wide stroke+//!+//! A stroke ([`super::stroke`]) only has to be a band of one colour, so a fragment+//! never needs to know where in that band it landed. A marking does: whether a+//! fragment is inside the centre line, inside a lane divider, or on bare tarmac is+//! entirely a question of how far across the road it is. So every vertex here carries+//! `t`, an across-road coordinate that is exactly `-1` on the left kerb and `+1` on the+//! right and interpolates linearly between them. Each marking in the style then reduces+//! to a comparison against `t`, and one carriageway mesh serves all of them.+//!+//! # Width still lives in the shader+//!+//! Normalising `t` is what makes that possible. A carriageway's half-width is a screen+//! measurement that changes continuously with zoom; baking it into these vertices would+//! re-tessellate every road in the resident set on every zoom step, while panning, on+//! the critical path. It stays a push constant — exactly as `Stroke::half_px` does for+//! the line path — and the vertex shader offsets by+//!+//! ```text+//! position + normal * t * half_width+//! ```+//!+//! Because `t` is a fraction of the road rather than a distance across it, a marking's+//! place on the carriageway is the same number at every zoom. The geometry is a+//! function of the tile alone.+//!+//! # Joins+//!+//! Miter joins and butt caps, computed and clamped exactly as the stroke path does, and+//! sharing its [`MITER_LIMIT`]. A carriageway, its casing and its markings are all+//! drawn from one centreline and have to agree along their edges, so they cannot+//! disagree about where a join is. Lengthening the normal through a miter is also what+//! holds `t = ±1` on the kerb around a bend — with a unit normal the road narrows into+//! the turn and every divider slides sideways with it.++use super::stroke::MITER_LIMIT;++/// Floats per vertex: `x, y, nx, ny, t, distance`.+pub const FLOATS_PER_VERTEX: usize = 6;++/// Tessellate one carriageway part.+///+/// `coords` is flat `[x0, y0, ...]` in tile coordinates; `extent` is the layer's+/// extent, so positions come out in 0..1 and the renderer needs no per-layer scale.+/// Indices are relative to the first vertex already in `vertices`.+pub fn ribbon(coords: &[i32], extent: u32, vertices: &mut Vec<f32>, indices: &mut Vec<u32>) {+    let points = dedupe(coords);+    let n = points.len() / 2;+    if n < 2 {+        return;+    }+    let scale = 1.0 / extent as f32;++    let base = (vertices.len() / FLOATS_PER_VERTEX) as u32;+    let mut distance = 0.0f32;++    for i in 0..n {+        let (nx, ny) = join_normal(&points, n, i);++        if i > 0 {+            // Scaled with the positions: the dash and marking-repeat patterns are+            // measured in pixels, and `line.vert` gets there by multiplying by the+            // tile's pixel span. Leaving this in extent units would make the pattern+            // period depend on the layer that happened to supply the geometry.+            distance += segment_length(&points, i - 1, i) * scale;+        }++        let px = points[i * 2] as f32 * scale;+        let py = points[i * 2 + 1] as f32 * scale;+        // Tile y grows downward, so the perpendicular `(-dy, dx)` points to the right+        // of travel — the `-1` vertex is the left kerb, as a driver would name it.+        vertices.extend_from_slice(&[px, py, nx, ny, -1.0, distance]);+        vertices.extend_from_slice(&[px, py, nx, ny, 1.0, distance]);+    }++    // Two triangles per segment, wound as the stroke path winds them so face culling+    // could be switched on later without the roads disappearing.+    for i in 0..(n - 1) {+        let a = base + (i as u32) * 2;+        indices.extend_from_slice(&[a, a + 1, a + 2, a + 1, a + 3, a + 2]);+    }+}++/// The normal at point `i`: unit at the ends, a clamped miter in between.+fn join_normal(points: &[i32], n: usize, i: usize) -> (f32, f32) {+    let before = if i > 0 { Some(direction(points, i - 1, i)) } else { None };+    let after = if i < n - 1 { Some(direction(points, i, i + 1)) } else { None };++    match (before, after) {+        (None, Some(a)) => (-a.1, a.0),+        (Some(b), None) => (-b.1, b.0),+        (Some(b), Some(a)) => {+            // The bisector, lengthened by 1/cos(theta/2) so both segments' kerbs meet+            // exactly on it.+            let (n1x, n1y) = (-b.1, b.0);+            let (n2x, n2y) = (-a.1, a.0);+            let mut mx = n1x + n2x;+            let mut my = n1y + n2y;+            let len = (mx * mx + my * my).sqrt();+            if len < 1e-6 {+                // A perfect reversal: the bisector is undefined, so fall back to the+                // incoming normal rather than emitting NaN.+                (n1x, n1y)+            } else {+                mx /= len;+                my /= len;+                let cos_half = mx * n1x + my * n1y;+                let miter = if cos_half > 1e-3 { 1.0 / cos_half } else { MITER_LIMIT };+                let clamped = if miter > MITER_LIMIT { MITER_LIMIT } else { miter };+                (mx * clamped, my * clamped)+            }+        }+        (None, None) => unreachable!("a part with fewer than two points was filtered out"),+    }+}++/// Unit direction from point `i` to point `j`.+fn direction(points: &[i32], i: usize, j: usize) -> (f32, f32) {+    let dx = (points[j * 2] - points[i * 2]) as f32;+    let dy = (points[j * 2 + 1] - points[i * 2 + 1]) as f32;+    let len = (dx * dx + dy * dy).sqrt();+    (dx / len, dy / len)+}++fn segment_length(points: &[i32], i: usize, j: usize) -> f32 {+    let dx = (points[j * 2] - points[i * 2]) as f32;+    let dy = (points[j * 2 + 1] - points[i * 2 + 1]) as f32;+    (dx * dx + dy * dy).sqrt()+}++/// Drop consecutive duplicate vertices.+///+/// Simplified tile geometry contains them, and a zero-length segment has no direction+/// — which would put a NaN in the normal and take the whole carriageway off screen,+/// not just that segment.+fn dedupe(coords: &[i32]) -> Vec<i32> {+    let mut out: Vec<i32> = Vec::with_capacity(coords.len());+    let mut i = 0;+    while i + 1 < coords.len() {+        let (x, y) = (coords[i], coords[i + 1]);+        let len = out.len();+        if len == 0 || out[len - 2] != x || out[len - 1] != y {+            out.push(x);+            out.push(y);+        }+        i += 2;+    }+    out+}++#[cfg(test)]+mod tests {+    use super::*;++    fn at(v: &[f32], vertex: usize, field: usize) -> f32 {+        v[vertex * FLOATS_PER_VERTEX + field]+    }+    fn position_x(v: &[f32], i: usize) -> f32 {+        at(v, i, 0)+    }+    fn normal_x(v: &[f32], i: usize) -> f32 {+        at(v, i, 2)+    }+    fn normal_y(v: &[f32], i: usize) -> f32 {+        at(v, i, 3)+    }+    fn across(v: &[f32], i: usize) -> f32 {+        at(v, i, 4)+    }+    fn distance(v: &[f32], i: usize) -> f32 {+        at(v, i, 5)+    }+    fn normal_len(v: &[f32], i: usize) -> f32 {+        (normal_x(v, i).powi(2) + normal_y(v, i).powi(2)).sqrt()+    }++    /// What `line.vert` does with a vertex, so the invariants can be checked on the+    /// host: the whole point of keeping the width out of the buffer is that the shader+    /// is the only place the two are ever combined.+    fn shade(v: &[f32], i: usize, t: f32, half_width: f32) -> (f32, f32) {+        (+            at(v, i, 0) + normal_x(v, i) * t * half_width,+            at(v, i, 1) + normal_y(v, i) * t * half_width,+        )+    }++    #[test]+    fn a_straight_segment_becomes_one_quad() {+        let mut v = Vec::new();+        let mut idx = Vec::new();+        // Extent 100, so tile coordinates and 0..1 positions differ by a round 100.+        ribbon(&[0, 0, 100, 0], 100, &mut v, &mut idx);++        assert_eq!(v.len() / FLOATS_PER_VERTEX, 4, "two points, two vertices each");+        assert_eq!(idx.len(), 6, "two triangles");+        for i in 0..4 {+            assert!((normal_x(&v, i) - 0.0).abs() < 1e-6);+            assert!((normal_y(&v, i) - 1.0).abs() < 1e-6);+        }+        assert!((position_x(&v, 0) - 0.0).abs() < 1e-6);+        assert!((position_x(&v, 2) - 1.0).abs() < 1e-6);+    }++    #[test]+    fn t_reaches_both_kerbs_and_never_leaves_the_carriageway() {+        // A marking is placed by comparing against `t`, so anything outside [-1, +1]+        // would paint kerb markings onto the verge.+        let mut v = Vec::new();+        ribbon(&[0, 0, 100, 0, 100, 100, 250, 40], 4096, &mut v, &mut Vec::new());+        let n = v.len() / FLOATS_PER_VERTEX;+        assert_eq!(n, 8);+        for i in 0..n {+            assert!((-1.0..=1.0).contains(&across(&v, i)), "t {} at {i}", across(&v, i));+        }+        for i in 0..(n / 2) {+            assert_eq!(across(&v, i * 2), -1.0, "left kerb is exactly -1");+            assert_eq!(across(&v, i * 2 + 1), 1.0, "right kerb is exactly +1");+        }+    }++    #[test]+    fn a_markings_place_on_the_road_survives_a_width_change() {+        // The regression this guards is the expensive one: if the half-width were baked+        // in, a zoom step would need a re-tessellation. The same buffer has to serve+        // every width, with the marking staying the same fraction across the road.+        let mut v = Vec::new();+        ribbon(&[0, 0, 100, 0], 100, &mut v, &mut Vec::new());+        let divider = -1.0 / 3.0;++        let fraction = |half_width: f32| {+            let (lx, ly) = shade(&v, 0, -1.0, half_width);+            let (rx, ry) = shade(&v, 1, 1.0, half_width);+            let (mx, my) = shade(&v, 0, divider, half_width);+            let span = ((rx - lx).powi(2) + (ry - ly).powi(2)).sqrt();+            ((mx - lx).powi(2) + (my - ly).powi(2)).sqrt() / span+        };++        let narrow = fraction(2.5);+        let wide = fraction(37.0);+        assert!((narrow - wide).abs() < 1e-6, "{narrow} vs {wide}");+        // And it is where `t` says it is: a third of the way in from the left kerb.+        assert!((narrow - (divider + 1.0) / 2.0).abs() < 1e-6);+    }++    #[test]+    fn a_right_angle_join_gets_a_miter_normal() {+        // (0,0) -> (100,0) -> (100,100). The incoming normal is (0,1) and the outgoing+        // one is (-1,0); their bisector is (-1,1)/sqrt(2) and the miter length is+        // 1/cos(45°) = sqrt(2), so the normal comes out exactly (-1, 1) and the kerb+        // stays on `t = ±1` through the turn.+        let mut v = Vec::new();+        ribbon(&[0, 0, 100, 0, 100, 100], 100, &mut v, &mut Vec::new());+        assert_eq!(v.len() / FLOATS_PER_VERTEX, 6);+        assert!((normal_x(&v, 2) - -1.0).abs() < 1e-5, "join nx {}", normal_x(&v, 2));+        assert!((normal_y(&v, 2) - 1.0).abs() < 1e-5, "join ny {}", normal_y(&v, 2));+        assert!((normal_len(&v, 2) - 2f32.sqrt()).abs() < 1e-5);+        assert!((normal_len(&v, 0) - 1.0).abs() < 1e-5);+        assert!((normal_len(&v, 4) - 1.0).abs() < 1e-5);+    }++    #[test]+    fn a_hairpin_miter_is_clamped_rather_than_throwing_a_spike() {+        let mut v = Vec::new();+        ribbon(&[0, 0, 1000, 0, 0, 10], 4096, &mut v, &mut Vec::new());+        assert!((normal_len(&v, 2) - MITER_LIMIT).abs() < 1e-4, "got {}", normal_len(&v, 2));+    }++    #[test]+    fn a_perfect_reversal_does_not_produce_nan() {+        let mut v = Vec::new();+        ribbon(&[0, 0, 100, 0, 0, 0], 100, &mut v, &mut Vec::new());+        for (i, f) in v.iter().enumerate() {+            assert!(f.is_finite(), "float {i} is {f}");+        }+    }++    #[test]+    fn repeated_vertices_are_dropped() {+        let mut v = Vec::new();+        ribbon(&[0, 0, 0, 0, 0, 0, 50, 0], 100, &mut v, &mut Vec::new());+        assert_eq!(v.len() / FLOATS_PER_VERTEX, 4, "three coincident points became one");+    }++    #[test]+    fn a_part_with_fewer_than_two_distinct_points_emits_nothing() {+        let mut v = Vec::new();+        let mut idx = Vec::new();+        ribbon(&[], 100, &mut v, &mut idx);+        ribbon(&[5, 5], 100, &mut v, &mut idx);+        ribbon(&[5, 5, 5, 5], 100, &mut v, &mut idx);+        assert!(v.is_empty());+        assert!(idx.is_empty());+    }++    #[test]+    fn distance_accumulates_along_the_line_in_tile_local_units() {+        // Mirrors the stroke path's assertion: `line.vert` scales this by the tile's+        // pixel span, so extent units here would stretch every marking pattern by the+        // extent.+        let mut v = Vec::new();+        ribbon(&[0, 0, 300, 0, 300, 400], 100, &mut v, &mut Vec::new());+        assert!((distance(&v, 0) - 0.0).abs() < 1e-6);+        assert!((distance(&v, 2) - 3.0).abs() < 1e-6, "300 tile units at extent 100");+        assert!((distance(&v, 4) - 7.0).abs() < 1e-6, "plus 400 more");+    }+}
library/map/src/main/rust/src/tile/arrow.rs
diff --git a/library/map/src/main/rust/src/tile/arrow.rs b/library/map/src/main/rust/src/tile/arrow.rsindex 2c675188ff..4559aa31fe 100644--- a/library/map/src/main/rust/src/tile/arrow.rs+++ b/library/map/src/main/rust/src/tile/arrow.rs@@ -62,10 +62,10 @@ pub fn arrow_for(mask: u16) -> Option<TurnArrow> { /// One arrow to draw for one lane, in tile-local coordinates. /// /// The anchor sits on the road's centreline a short way back from the junction; the renderer then-/// pushes it sideways into its lane by the same lateral fan the lane dividers use, which is why the-/// instance carries `ordinal` and `count` rather than a baked offset (the offset is a screen-/// measurement that changes with zoom). `angle` is the road's heading at the end, in radians, so-/// the glyph points the way the traffic flows.+/// pushes it sideways onto its lane of the carriageway, which is why the instance carries `ordinal`+/// and `count` rather than a baked offset (the offset is a screen measurement that changes with+/// zoom). `angle` is the road's heading at the end, in radians, so the glyph points the way the+/// traffic flows. #[derive(Debug, Clone, Copy, PartialEq)] pub struct ArrowInstance {     /// Anchor on the centreline, tile-local (extent units).@@ -304,7 +304,7 @@ mod tests {         assert!((max_x - 0.6).abs() < 1e-5, "tip a scale-length ahead of the anchor in +x");         assert!((tip_y - 0.5).abs() < 1e-5, "and level with it, no offset");         // A non-zero lateral offset shifts the whole glyph off the centreline (perpendicular to-        // the heading); the sign of the real offset comes from lane_offset_px per lane.+        // the heading); the sign of the real offset comes from the lane's place across the road.         let mut v2 = Vec::new();         arrow_verts(&through, 0.1, 0.2, &mut v2);         let mean_y2 = v2.chunks(2).map(|p| p[1]).sum::<f32>() / (v2.len() / 2) as f32;
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 6ece4f47e3..c60046ace6 100644--- a/library/map/src/main/rust/src/tile/geometry.rs+++ b/library/map/src/main/rust/src/tile/geometry.rs@@ -11,7 +11,7 @@ //! strokes 7, and the shaders never saw any of it.  use crate::style::{KindFilter, Layer, LayerKind, LayerToggles};-use crate::tess::{fill, roof, stroke, terrain};+use crate::tess::{fill, ribbon, roof, stroke, terrain}; use crate::tile::arrow::{self, ArrowInstance}; use crate::tile::symbol; use crate::tile::select::ANCESTOR_DEPTH;@@ -26,27 +26,14 @@ use tilecodec::mamaps::dict::{LAYER_BUILDINGS, LAYER_EARTH, LAYER_ROADS, LAYER_T /// layer; this is the matching cost gate on the render side. pub const TRAFFIC_MIN_ZOOM: u8 = 12; -/// The shallowest zoom the per-lane road detail (dividers and turn arrows) is built at.+/// The shallowest zoom the per-lane road detail (the carriageway surface and its turn arrows) is+/// built at. ///-/// Matches the `roads-lanes` style layer's `minzoom` in `basemap.flat.json`: the dense lane detail-/// is only legible zoomed right in, so below this the road draws as one line and carries no arrows.+/// Matches the `roads-carriageway` style layer's `minzoom` in `basemap.flat.json`: lane markings+/// are only legible zoomed right in, so below this the road draws as the ordinary stroked layers+/// and carries no arrows. pub const ROAD_LANE_MIN_ZOOM: u8 = 16; -/// How many levels ahead of itself a tile builds per-lane road detail, in place of the general-/// [`ANCESTOR_DEPTH`](crate::tile::select::ANCESTOR_DEPTH).-///-/// The lookahead exists because a tile stands in for the levels below it, and the archive stops at-/// z14 while lanes are drawn from z16 — so the z14 tile *must* build lane geometry it will not draw-/// itself. But the general depth of 4 makes every tile from z12 up build it, and lane detail is the-/// most expensive thing in this file: each divider re-strokes the road's entire geometry, so a-/// six-lane road builds five extra full copies of itself, per tile, three levels before any of it-/// can be drawn.-///-/// Two is the smallest value that still lets the deepest archive tile serve [`ROAD_LANE_MIN_ZOOM`].-/// The cost is that a z12 or z13 ancestor standing in while its z14 child loads shows no lanes or-/// arrows until the child lands — transient, and only at z16+.-const LANE_ANCESTOR_DEPTH: u8 = 2;- /// The height a `buildings` feature with no `height` tag extrudes to, in metres — about three /// storeys, so an unattributed building still reads as a building rather than a flat patch. const DEFAULT_BUILDING_HEIGHT_M: f64 = 9.0;@@ -166,6 +153,35 @@ pub struct ShapedLabel {     pub centreline: Option<Vec<(f32, f32)>>, } +/// One tile's road carriageway surface, for one set of road-shape inputs.+///+/// Kept apart from [`LayerMesh`] because it is neither a stroke nor drawn through the line+/// pipeline: its vertices carry an across-road coordinate ([`crate::tess::ribbon`]) and it draws+/// through the ribbon pipeline, whose push block reads three slots differently. That split is+/// deliberate rather than a wider shared format — [`TrafficMesh`] and the route overlay both ride+/// the 7-float stroke vertex, so widening it to carry a coordinate only roads read would charge+/// every one of them for a layer they do not draw.+///+/// One mesh per distinct ([`lanes`](Self::lanes), [`split`](Self::split), [`oneway`](Self::oneway))+/// 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.+pub struct CarriagewayMesh {+    /// Index into the style's layer list, for the asphalt colour and the lane width ramp.+    pub layer_index: usize,+    /// Lanes across the whole road, both directions together — `Push.line.y`, and the multiplier+    /// that turns the style's per-lane width into this road's own.+    pub lanes: u8,+    /// The across-road coordinate the opposing streams meet at, in -1..=1 — `Push.line.z`.+    /// Meaningless, and zero, when [`oneway`](Self::oneway) is set.+    pub split: f32,+    /// Traffic runs one way, so the carriageway has no centre line at all — `Push.line.w`.+    pub oneway: bool,+    /// Interleaved `x, y, nx, ny, t, distance` per vertex — see [`crate::tess::ribbon`].+    pub vertices: Vec<f32>,+    pub indices: Vec<u32>,+}+ /// One region's shape within one tile, for the selection mask. /// /// Kept apart from [`LayerMesh`] because it is not styled and not drawn in layer order: nothing@@ -236,11 +252,22 @@ pub struct TileMesh {     /// below [`TRAFFIC_MIN_ZOOM`]. Colour is resolved at draw time from a pushed table, so this     /// is built once and survives every recolour.     pub traffic: Vec<TrafficMesh>,+    /// 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.+    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`.+    ///+    /// A property of the tile, not of a road, and `false` on any archive that carries no+    /// convention at all: right-hand traffic with white markings is most of the world by land+    /// area and the safer thing to be wrong about.+    pub yellow_centre: bool,     /// Symbol candidates: shaped once at tessellation time, sized per frame.     pub labels: Vec<ShapedLabel>,     /// Per-lane turn arrows at road junctions, from the archive's turn-lane table. One per marked-    /// lane, placed on the centreline near the junction and pushed into its lane by the same-    /// lateral fan the dividers use. Empty below the lane zoom gate and on any tile with no+    /// lane, placed on the centreline near the junction and pushed sideways onto its lane of the+    /// carriageway. Empty below the lane zoom gate and on any tile with no     /// `turn:lanes`. The renderer draws these as glyphs; the anchors and directions are computed     /// here so the placement is testable off-device.     pub arrows: Vec<ArrowInstance>,@@ -313,6 +340,13 @@ pub fn build_toggled( ) -> TileMesh {     let mut meshes = Vec::with_capacity(layers.len());     let mut labels = Vec::new();+    // The tile's road surfaces, accumulated across every carriageway layer's features. Tile-wide+    // (not per layer) because they draw in their own pass, not the flat layer loop.+    let mut carriageways: Vec<CarriagewayMesh> = Vec::new();+    // Which way traffic drives here, which is what says whether the forward lanes sit on the +1+    // or the -1 side of the road. Absent on every archive that predates the convention byte, and+    // the default — right-hand traffic, white markings — is what most of the world does.+    let left_hand = tile.convention.is_some_and(|c| c.left_hand);     // The tile's 3D buildings, accumulated across the buildings layer's features into one mesh.     // Tile-wide (not per layer) because it draws in its own depth-tested pass, not the layer loop.     let mut building_vertices: Vec<f32> = Vec::new();@@ -328,15 +362,7 @@ pub fn build_toggled(         if !toggles.enabled(layer.toggle) {             continue;         }-        // Per-lane road detail gets its own, much shallower lookahead: see-        // [`LANE_ANCESTOR_DEPTH`]. Scoped to the *roads* fan — `transit-rail` carries a spread-        // too, and narrowing its window would stop coarse ancestors carrying rail corridors.-        let layer_deepest = if layer.lane_fan() && layer.source_layer_id == LAYER_ROADS {-            z.saturating_add(LANE_ANCESTOR_DEPTH)-        } else {-            deepest-        };-        if layer.min_zoom > layer_deepest || layer.max_zoom < z {+        if layer.min_zoom > deepest || layer.max_zoom < z {             continue;         }         let Some(source) = tile.layer(layer.source_layer_id) else { continue };@@ -350,13 +376,6 @@ pub fn build_toggled(         #[allow(clippy::type_complexity)]         let mut coloured: Vec<((u32, u8, u8, u8), Vec<f32>, Vec<u32>)> = Vec::new(); -        // Sub-meshes for a road drawn as its individual lanes: one per (divider ordinal, divider-        // count), so a four-lane and a six-lane road in one tile fan by different amounts and each-        // mesh carries the one lane tuple its offset needs. Stays empty for every layer but a-        // lane-fan road layer, and the `lane_fan()` gate below keeps it off the hot road path.-        #[allow(clippy::type_complexity)]-        let mut lane_fans: Vec<((u8, u8), Vec<f32>, Vec<u32>)> = Vec::new();-         for (feature_index, feature) in source.features.iter().enumerate() {             // Kind, then the road flag/detail filters: one call, so a surface layer never             // draws the ramps, bridges, tunnels and service streets its `kind` alone would@@ -415,7 +434,58 @@ pub fn build_toggled(                         continue;                     }                     let gapped = layer.gapped();-                    if feature.transit_color != 0 {+                    if layer.carriageway {+                        // The road's own surface, with its lane markings painted on by the+                        // fragment shader rather than drawn. A polygon outline has no+                        // carriageway, so only real line features take this path.+                        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+                                }+                            }+                            count => count,+                        };+                        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+                                && m.oneway == oneway+                                && m.split.to_bits() == split.to_bits()+                        }) {+                            Some(at) => at,+                            None => {+                                carriageways.push(CarriagewayMesh {+                                    layer_index: index,+                                    lanes,+                                    split,+                                    oneway,+                                    vertices: Vec::new(),+                                    indices: Vec::new(),+                                });+                                carriageways.len() - 1+                            }+                        };+                        let Some(mesh) = carriageways.get_mut(at) else { continue };+                        for part in parts {+                            let flat = flatten(source.points(part));+                            ribbon::ribbon(+                                &flat,+                                extent,+                                &mut mesh.vertices,+                                &mut mesh.indices,+                            );+                        }+                    } else if feature.transit_color != 0 {                         // A transit line carries its own colour: split into one sub-mesh per                         // distinct (colour, ordinal, lanes, taper), because two routes of one                         // colour on different ordinals draw as two parallel lines and one mesh@@ -438,33 +508,6 @@ pub fn build_toggled(                             let flat = flatten(source.points(part));                             stroke::stroke(&flat, extent, gapped, v, i);                         }-                    } else if layer.lane_fan() {-                        // A road drawn as its individual lanes: one divider line between each-                        // adjacent pair, fanned across the carriageway by `lane_offset_px` at draw-                        // time. A road with fewer than two lanes has no interior divider and so-                        // contributes nothing here — its casing and fill are the ordinary road-                        // layers' job. The geometry is stroked once per divider into a mesh keyed-                        // by (ordinal, divider count), so the offset the shader applies is this-                        // divider's alone.-                        if feature.lane_count < 2 {-                            continue;-                        }-                        let dividers = feature.lane_count - 1;-                        for ordinal in 0..dividers {-                            let key = (ordinal, dividers);-                            let at = match lane_fans.iter().position(|(k, _, _)| *k == key) {-                                Some(at) => at,-                                None => {-                                    lane_fans.push((key, Vec::new(), Vec::new()));-                                    lane_fans.len() - 1-                                }-                            };-                            let Some((_, v, i)) = lane_fans.get_mut(at) else { continue };-                            for part in parts {-                                let flat = flatten(source.points(part));-                                stroke::stroke(&flat, extent, gapped, v, i);-                            }-                        }                     } else {                         // Every ordinary road and boundary: one mesh for the whole layer.                         for part in parts {@@ -550,25 +593,11 @@ pub fn build_toggled(                 lane: (ordinal, lanes, taper),             });         }-        // The road lane dividers: each sub-mesh is one divider drawn the width of the whole road,-        // shifted to its lane boundary by `lane_offset_px` from the (ordinal, count) it carries.-        // The layer's own colour paints them, so no `color_override`; `taper` is full (255) because-        // a lane boundary does not ease in at a corridor end the way a transit route does.-        for ((ordinal, count), vertices, indices) in lane_fans {-            if indices.is_empty() {-                continue;-            }-            meshes.push(LayerMesh {-                layer_index: index,-                kind: layer.kind,-                vertices,-                indices,-                color_override: None,-                lane: (ordinal, count, 255),-            });-        }     } +    // A road whose every part was degenerate would otherwise cost an empty draw.+    carriageways.retain(|m| !m.indices.is_empty());+     TileMesh {         z,         x,@@ -579,6 +608,8 @@ pub fn build_toggled(         labels,         regions: region_meshes(tile, extent, rings_validated),         traffic: traffic_meshes(tile, extent, z, toggles),+        carriageways,+        yellow_centre: tile.convention.is_some_and(|c| c.yellow_centre),         arrows: arrow_meshes(tile, z),         generation,     }@@ -600,15 +631,50 @@ fn terrain_mesh(tile: &Body, ground_width_m: f64) -> TerrainMesh {     TerrainMesh { vertices, indices } } +/// The across-road coordinate the opposing streams of one road feature meet at, in -1..=1.+///+/// The ribbon measures `t` from the left of the geometry's own direction, and the archive's+/// `forward` lanes are the ones running toward the feature's last point — the same direction. So+/// under right-hand traffic the forward lanes take the +1 side and the backward lanes the -1 side,+/// and under left-hand traffic they swap. Expressed as a fraction of the split's own total rather+/// than of [`tilecodec::mamaps::body::Feature::lane_count`], so a table that disagrees with the+/// lane tag still puts the line in the right *place*.+///+/// # It has to land on a lane boundary, not merely near one+///+/// `road_surface.frag` decides which boundary carries the centre line with+/// `abs(boundaryT - centreT) < 1.0 / lanes` — half a lane, and **strictly** less. So a value that+/// sits exactly halfway between two boundaries matches neither: the dividers either side both stay+/// dashed and the centre-line band paints down the middle of a lane. A flat 0.0 does exactly that+/// on any odd lane count, where the middle of the road *is* the middle of the centre lane.+///+/// So the unknown-split case does not push 0.0; it assumes the split a road with an odd lane count+/// actually carries — the extra lane going to the forward direction — and runs it through the same+/// arithmetic as a known one. On an even count that still comes out at 0.0, and it is what real+/// data gives anyway: a three-lane two-way road is tagged 2/1, not "centred".+fn split_t(tile: &Body, layer: &Layer, feature_index: usize, lanes: u8, left_hand: bool) -> f32 {+    let known = tile+        .feature_carriageway(layer.source_layer_id, feature_index)+        .map(|shape| (shape.forward as u16, shape.backward as u16))+        .filter(|(forward, backward)| forward + backward > 0);+    let (forward, backward) = known.unwrap_or_else(|| {+        let lanes = lanes.max(1) as u16;+        (lanes - lanes / 2, lanes / 2)+    });+    let near_kerb = if left_hand { forward } else { backward };+    2.0 * near_kerb as f32 / (forward + backward) as f32 - 1.0+}+ /// The per-lane turn arrows for this tile, from the archive's turn-lane side table. /// /// One arrow per marked lane, at each turn-tagged road's junction end (and start, for backward-/// lanes). Gated to [`ROAD_LANE_MIN_ZOOM`] like the lane dividers — and by the same-/// [`LANE_ANCESTOR_DEPTH`] window the layer loop gives them, so a tile standing in for deeper-/// levels builds them once and coarse ancestors do not build them at all.+/// lanes). Gated to [`ROAD_LANE_MIN_ZOOM`] like the carriageway, over the same+/// [`ANCESTOR_DEPTH`] window the layer loop uses — a tile stands in for the levels below it, and+/// the archive stops at z14 while arrows are drawn from z16, so a z14 tile must build arrows it+/// will not draw itself. /// Empty on any tile with no `turn:lanes` (no turn-lane table), which is nearly all. fn arrow_meshes(tile: &Body, z: u8) -> Vec<ArrowInstance> {-    if z.saturating_add(LANE_ANCESTOR_DEPTH) < ROAD_LANE_MIN_ZOOM {+    if z.saturating_add(ANCESTOR_DEPTH) < ROAD_LANE_MIN_ZOOM {         return Vec::new();     }     let Some(source) = tile.layer(LAYER_ROADS) else { return Vec::new() };@@ -936,6 +1002,7 @@ mod tests {             gap_width: Ramp::constant(0.0),             spread: Ramp::constant(0.0),             lanes: Ramp::constant(1.0),+            carriageway: false,             dash: (0.0, 0.0),             text_size: Ramp::constant(0.0),             text_size_large: None,@@ -1164,30 +1231,28 @@ mod tests {         }     } -    /// A multi-lane road fans into one divider line per interior lane boundary, each in its own-    /// mesh carrying the (ordinal, divider-count) the shader offsets it by; a road with a single-    /// lane draws no divider at all. This is the road half of the lateral-fan the transit tests-    /// above pin — driven by `lane_count` and the layer's own colour rather than a per-route one.-    #[test]-    fn a_multi_lane_road_fans_into_one_divider_per_interior_boundary() {-        use tilecodec::mamaps::body::{Feature, Layer as BodyLayer, Part, NAME_NONE, WINDING_OUTER};+    /// A body of straight roads, one per `(lane_count, oneway)` entry, on the `roads` layer.+    fn carriageway_body(roads: &[(u8, bool)]) -> Body {+        use tilecodec::mamaps::body::{+            Feature, Layer as BodyLayer, Part, FLAG_IS_ONEWAY, NAME_NONE, WINDING_OUTER,+        };         use tilecodec::mamaps::dict;         let mut body = Body::new(4096);         let mut source = BodyLayer::new(dict::LAYER_ROADS);-        // A four-lane road (three interior dividers) and a single-lane road (none).-        for (lane_count, y) in [(4u8, 100i16), (1, 300)] {+        for (i, &(lane_count, oneway)) in roads.iter().enumerate() {             let parts_offset = source.parts.len() as u32;             source.parts.push(Part {                 coord_start: source.coords.len() as u32,                 point_count: 2,                 winding: WINDING_OUTER,             });+            let y = 100 + i as i16 * 100;             source.coords.extend_from_slice(&[(0, y), (1000, y)]);             source.features.push(Feature {                 kind: crate::style::kind_id_for_test("major_road"),                 kind_detail: 0,                 geom_type: GEOM_LINE,-                flags: 0,+                flags: if oneway { FLAG_IS_ONEWAY } else { 0 },                 name_idx: NAME_NONE,                 parts_offset,                 part_count: 1,@@ -1199,31 +1264,191 @@ mod tests {             });         }         body.layers.push(source);+        body+    } +    /// The `roads-carriageway` layer as a one-layer slice, so a test states its own layer set.+    fn carriageway_only() -> &'static [Layer] {         let all = style::layers();-        let at = all.iter().position(|l| l.id == "roads-lanes").expect("the road lanes layer");-        let Some(only) = all.get(at..=at) else { panic!("a one-layer slice") };+        let at = all.iter().position(|l| l.carriageway).expect("the carriageway layer");+        all.get(at..=at).expect("a one-layer slice")+    } -        // Gated to high zoom: nothing while the deepest tile this stands in for is still below-        // the floor (min_zoom 16 against z + ANCESTOR_DEPTH), the whole point of the dense layer.-        assert!(-            build(&body, only, 11, 0, 0, false).meshes.is_empty(),-            "the lane layer is not tessellated below its floor",+    /// **The path every real archive takes today.** The tiler is still wiring the producer side, so+    /// no published tile carries a carriageway table or a marking convention, and the renderer has+    /// to draw a correct road from the lane count alone: the split lands on a lane boundary, the+    /// centre line is white, and a one-way suppresses it entirely.+    #[test]+    fn a_tile_with_no_carriageway_table_still_draws_a_correct_carriageway() {+        let body = carriageway_body(&[(4, false), (3, true)]);+        assert!(body.carriageways.is_empty(), "the fixture is a v7 archive with no table");+        assert!(body.convention.is_none());++        let mesh = build(&body, carriageway_only(), 16, 0, 0, false);+        assert_eq!(+            mesh.carriageways.iter().map(|c| (c.lanes, c.oneway)).collect::<Vec<_>>(),+            vec![(4, false), (3, true)],         );+        assert_eq!(mesh.carriageways[0].split, 0.0, "an even count splits down the middle");+        assert!(!mesh.yellow_centre, "no convention means white, which is most of the world");+        assert!(mesh.meshes.is_empty(), "a carriageway is not a stroked layer mesh");+    } -        let mesh = build(&body, only, 16, 0, 0, false);-        // Three dividers for the four-lane road, none for the one-lane road, and the layer's own-        // colour (no per-feature override).+    /// **The degenerate case the flat 0.0 default hid.** `road_surface.frag` picks the boundary+    /// carrying the centre line with `abs(boundaryT - centreT) < 1.0 / lanes` — half a lane, and+    /// strictly less — so a split that sits exactly halfway between two boundaries matches neither.+    /// On an odd lane count the middle of the road is the middle of the centre *lane*, so a 0.0+    /// default left both neighbouring dividers dashed and painted the centre line down a lane.+    ///+    /// This only ever bit the unknown-split path, which is the only path there is until the tiler+    /// writes a carriageway table — so the invariant is asserted the way the shader tests it,+    /// against every lane count a road can have, both hands of the road.+    #[test]+    fn an_unknown_split_always_lands_on_a_lane_boundary() {+        use tilecodec::mamaps::body::MarkingConvention;+        for left_hand in [false, true] {+            for lanes in 1..=12u8 {+                let mut body = carriageway_body(&[(lanes, false)]);+                body.convention = Some(MarkingConvention { left_hand, yellow_centre: false });+                let mesh = build(&body, carriageway_only(), 16, 0, 0, false);+                let split = mesh.carriageways[0].split;+                assert!((-1.0..=1.0).contains(&split), "{lanes} lanes gave t {split}");+                // Exactly the shader's test, against the nearest boundary it would round to.+                let boundary = (((split + 1.0) / 2.0) * lanes as f32).round();+                let boundary_t = boundary / lanes as f32 * 2.0 - 1.0;+                assert!(+                    (boundary_t - split).abs() < 1.0 / lanes as f32,+                    "{lanes} lanes: t {split} is not within half a lane of boundary {boundary_t}, \+                     so the centre line would paint down the middle of a lane",+                );+            }+        }+    }++    /// The odd lane goes to the forward direction, which is the split real data carries — a+    /// three-lane two-way road is tagged 2/1, not "centred" — and which side of the road that puts+    /// the line on still follows the driving convention.+    #[test]+    fn an_odd_lane_count_gives_the_extra_lane_to_the_forward_direction() {+        use tilecodec::mamaps::body::MarkingConvention;+        let third = 1.0f32 / 3.0;+        for (left_hand, expected) in [(false, -third), (true, third)] {+            let mut body = carriageway_body(&[(3, false)]);+            body.convention = Some(MarkingConvention { left_hand, yellow_centre: false });+            let mesh = build(&body, carriageway_only(), 16, 0, 0, false);+            assert!(+                (mesh.carriageways[0].split - expected).abs() < 1e-6,+                "left_hand {left_hand}: {} is not {expected}",+                mesh.carriageways[0].split,+            );+        }+        // And the same three lanes tagged explicitly agree with the guess, so the fallback is not+        // a second answer that real data will contradict.+        let tagged = split_for(3, tilecodec::mamaps::body::Carriageway {+            forward: 2,+            backward: 1,+            solid_dividers: 0,+        });+        assert!((tagged - -third).abs() < 1e-6, "tagged 2/1 gave {tagged}");+    }++    /// One road with a known carriageway row, tessellated under right-hand traffic.+    fn split_for(lanes: u8, shape: tilecodec::mamaps::body::Carriageway) -> f32 {+        use tilecodec::mamaps::dict;+        let mut body = carriageway_body(&[(lanes, false)]);+        body.carriageways = vec![(dict::LAYER_ROADS, vec![shape])];+        build(&body, carriageway_only(), 16, 0, 0, false).carriageways[0].split+    }++    /// A road with no `lanes` tag — most of OSM — still gets a carriageway, because a zero lane+    /// count would push a zero width and draw nothing at all where a road plainly is.+    #[test]+    fn an_untagged_road_falls_back_to_one_lane_each_way() {+        let mesh = build(&carriageway_body(&[(0, false), (0, true)]), carriageway_only(), 16, 0, 0, false);         assert_eq!(-            mesh.meshes.iter().map(|m| m.lane).collect::<Vec<(u8, u8, u8)>>(),-            vec![(0, 3, 255), (1, 3, 255), (2, 3, 255)],-            "one mesh per interior divider of the four-lane road, in ordinal order",+            mesh.carriageways.iter().map(|c| (c.lanes, c.oneway)).collect::<Vec<_>>(),+            vec![(2, false), (1, true)],+        );+    }++    /// The push inputs are what splits the meshes, so roads that agree on all three share a draw+    /// and roads that disagree cannot — the carriageway equivalent of the transit colour split.+    #[test]+    fn carriageways_split_into_one_mesh_per_distinct_road_shape() {+        // Two four-lane two-ways, a six-lane two-way, and a four-lane one-way.+        let body = carriageway_body(&[(4, false), (6, false), (4, false), (4, true)]);+        let mesh = build(&body, carriageway_only(), 16, 0, 0, false);+        assert_eq!(+            mesh.carriageways.iter().map(|c| (c.lanes, c.oneway)).collect::<Vec<_>>(),+            vec![(4, false), (6, false), (4, true)],+            "one mesh per distinct shape, in first-seen feature order",+        );+        // The two four-lane two-ways really did share a mesh rather than each getting one.+        assert_eq!(mesh.carriageways[0].indices.len(), mesh.carriageways[1].indices.len() * 2);+        for c in &mesh.carriageways {+            assert_eq!(c.vertices.len() % ribbon::FLOATS_PER_VERTEX, 0, "vertices are whole");+            assert_eq!(c.indices.len() % 3, 0, "indices come in threes");+            let vertex_count = (c.vertices.len() / ribbon::FLOATS_PER_VERTEX) as u32;+            assert!(c.indices.iter().all(|&i| i < vertex_count), "an index is out of range");+            assert!(c.vertices.iter().all(|f| f.is_finite()));+        }+    }++    /// Where the archive *does* carry a split, the centre line goes at the boundary between the+    /// directions — and which side that is depends on which side the country drives on, because+    /// `forward` means "toward the feature's last point" and the ribbon measures `t` from the left+    /// of that same direction.+    #[test]+    fn the_centre_line_follows_the_split_and_the_driving_side() {+        use tilecodec::mamaps::body::{Carriageway, MarkingConvention};+        use tilecodec::mamaps::dict;+        // Three forward lanes, one backward.+        let shape = Carriageway { forward: 3, backward: 1, solid_dividers: 0 };++        let mut right = carriageway_body(&[(4, false)]);+        right.carriageways = vec![(dict::LAYER_ROADS, vec![shape])];+        right.convention = Some(MarkingConvention { left_hand: false, yellow_centre: true });+        let mesh = build(&right, carriageway_only(), 16, 0, 0, false);+        assert_eq!(+            mesh.carriageways[0].split, -0.5,+            "right-hand traffic keeps the forward lanes on the +1 side, so the one backward \+             lane takes the quarter of the road nearest the -1 kerb",+        );+        assert!(mesh.yellow_centre, "the Americas paint the line between directions yellow");++        let mut left = carriageway_body(&[(4, false)]);+        left.carriageways = vec![(dict::LAYER_ROADS, vec![shape])];+        left.convention = Some(MarkingConvention { left_hand: true, yellow_centre: false });+        let mesh = build(&left, carriageway_only(), 16, 0, 0, false);+        assert_eq!(mesh.carriageways[0].split, 0.5, "left-hand traffic mirrors it");+        assert!(!mesh.yellow_centre);+    }++    /// A road the archive lists in the table but knows nothing about degrades to the same answer as+    /// a tile with no table at all, rather than dividing by zero.+    #[test]+    fn a_road_with_an_empty_carriageway_row_falls_back_like_an_absent_one() {+        use tilecodec::mamaps::body::Carriageway;+        assert_eq!(split_for(4, Carriageway::default()), 0.0);+        let odd = split_for(3, Carriageway::default());+        assert!((odd - -(1.0f32 / 3.0)).abs() < 1e-6, "three lanes gave {odd}");+    }++    /// The dense lane detail is gated to high zoom, over the same ancestor window every other+    /// layer uses: a tile builds what it will stand in for and no more.+    #[test]+    fn the_carriageway_is_not_built_below_its_zoom_window() {+        let body = carriageway_body(&[(4, false)]);+        assert!(+            build(&body, carriageway_only(), 11, 0, 0, false).carriageways.is_empty(),+            "z11 stands in no deeper than z15, which is below the carriageway floor",         );         assert!(-            mesh.meshes.iter().all(|m| m.color_override.is_none()),-            "a lane divider takes the layer's colour, not a per-feature one",+            !build(&body, carriageway_only(), ROAD_LANE_MIN_ZOOM - ANCESTOR_DEPTH, 0, 0, false)+                .carriageways+                .is_empty(),+            "the deepest archive tile must build what it stands in for at z16",         );-        assert!(mesh.meshes.iter().all(|m| m.kind == LayerKind::Line && !m.indices.is_empty()));     }      /// Turn arrows are produced from the archive's turn-lane table at high zoom and gated off@@ -1359,6 +1584,7 @@ mod tests {             gap_width: Ramp::constant(0.0),             spread: Ramp::constant(0.0),             lanes: Ramp::constant(1.0),+            carriageway: false,             dash: (0.0, 0.0),             text_size: Ramp::constant(1.0),             text_size_large: None,@@ -1792,6 +2018,7 @@ mod tests {             gap_width: Ramp::constant(0.0),             spread: Ramp::constant(0.0),             lanes: Ramp::constant(1.0),+            carriageway: false,             dash: (0.0, 0.0),             text_size: Ramp::constant(12.0),             text_size_large: None,
library/map/src/main/rust/src/tile/symbol.rs
diff --git a/library/map/src/main/rust/src/tile/symbol.rs b/library/map/src/main/rust/src/tile/symbol.rsindex c4ffdef096..e7d63b536e 100644--- a/library/map/src/main/rust/src/tile/symbol.rs+++ b/library/map/src/main/rust/src/tile/symbol.rs@@ -502,6 +502,7 @@ mod tests {             gap_width: crate::style::paint::Ramp::constant(0.0),             spread: crate::style::paint::Ramp::constant(0.0),             lanes: crate::style::paint::Ramp::constant(1.0),+            carriageway: false,             dash: (0.0, 0.0),             text_size: crate::style::paint::Ramp::constant(12.0),             text_size_large: None,@@ -614,6 +615,7 @@ mod tests {             gap_width: crate::style::paint::Ramp::constant(0.0),             spread: crate::style::paint::Ramp::constant(0.0),             lanes: crate::style::paint::Ramp::constant(1.0),+            carriageway: false,             dash: (0.0, 0.0),             text_size: crate::style::paint::Ramp::constant(12.0),             text_size_large: None,
library/map/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/map/src/main/rust/src/vulkan/pipeline.rs b/library/map/src/main/rust/src/vulkan/pipeline.rsindex d256d63013..029748b340 100644--- a/library/map/src/main/rust/src/vulkan/pipeline.rs+++ b/library/map/src/main/rust/src/vulkan/pipeline.rs@@ -46,6 +46,45 @@ pub const MORPH_NONE: [f32; 4] = [1.0, 0.0, 0.0, 0.0]; /// `misc.w` is the per-frame clock (seconds); `morph.x` is the per-tile opacity/morph factor /// (1.0 = fully present) reserved for WS-D. Both default to a value that leaves the flat 2D /// output byte-identical (`clock` is ignored by the current shaders, `morph.x` is 1.0).+///+/// # The ribbon draw reads three of these slots differently+///+/// [`ribbon`](Pipelines::ribbon) is a road carriageway rather than a stroke, so `gap_half_px`,+/// `dash_on`, `dash_off` and `lateral_px` are all meaningless to it: it has no casing bands, its+/// dash pattern is derived from the lane width, and a carriageway is never fanned sideways. Those+/// dead slots carry the markings contract instead, which is why the block does not have to grow+/// past the guaranteed 128 bytes to gain a whole new layer.+///+/// | slot     | line pipeline | ribbon pipeline                                                |+/// |----------|---------------|-----------------------------------------------------------------|+/// | `line.x` | half width px | carriageway half-width px — unchanged meaning                    |+/// | `line.y` | gap half px   | lane count, both directions together                             |+/// | `line.z` | dash on       | `t` of the forward/backward split, the centre line's position     |+/// | `line.w` | dash off      | 1.0 on a one-way, which suppresses the centre line entirely      |+/// | `misc.z` | lateral px    | 1.0 for a yellow centre line, 0.0 for a white one                |+///+/// `line.z` is an across-road coordinate in `[-1, +1]`, not a lane index, so an odd split needs no+/// special case: the shader takes the lane boundary nearest to it. `t` runs -1 at the left kerb to+/// +1 at the right, so with `n` of the `line.y` lanes lying on the -1 side the split is+///+/// ```text+/// line.z = 2.0 * n / lane_count - 1.0+/// ```+///+/// It is ignored when `line.w` is set, so a one-way may push anything there.+///+/// `misc.z` is the driving convention, resolved per tile at archive build time — the Americas paint+/// the line between opposing traffic yellow and most of the rest of the world paints it white. It+/// is a flag rather than a colour because the marking palette belongs to the shader alongside the+/// white it has to match, not to a per-draw push.+///+/// The remaining slots keep their usual meaning and must still be filled: `color` is the asphalt+/// (the markings are the shader's own), `misc.x` the tile's pixel span, `misc.y` the edge-AA flag,+/// and `morph` [`MORPH_NONE`]. `misc.w` is unread by the ribbon — its markings are static, so there+/// is deliberately no dash phase the way the traffic draw has one.+///+/// Both flags are compared against 0.5, so any nonzero-ish float reads as set; push exactly 0.0 or+/// 1.0 rather than relying on that. #[repr(C)] #[derive(Clone, Copy)] pub struct Push {@@ -54,10 +93,12 @@ pub struct Push {     pub tile_to_clip: [f32; 16],     /// Linear RGBA, 0..1.     pub color: [f32; 4],-    /// `half_width_px, gap_half_px, dash_on, dash_off`.+    /// `half_width_px, gap_half_px, dash_on, dash_off`. The ribbon pipeline reads+    /// `half_width_px, lane_count, centre_t, oneway` instead; see the type doc.     pub line: [f32; 4],     /// `tile_px, edge_aa, lateral_px, clock_seconds`. `misc.w` is the per-frame clock forwarded-    /// from the host's `frameTimeNanos` (see `camera::Camera::time_seconds`).+    /// from the host's `frameTimeNanos` (see `camera::Camera::time_seconds`). The ribbon pipeline+    /// reads `misc.z` as the centre-line colour flag rather than a lateral shift.     pub misc: [f32; 4],     /// Per-draw animation slot. `morph.x` is the per-tile opacity/morph factor (1.0 = fully     /// present) reserved for WS-D's LOD cross-fade; `y`/`z`/`w` are reserved. Appended past@@ -82,6 +123,8 @@ const FILL_VERT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/fill.vert.spv const FILL_FRAG: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/fill.frag.spv")); const LINE_VERT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/line.vert.spv")); const LINE_FRAG: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/line.frag.spv"));+const RIBBON_VERT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/road_surface.vert.spv"));+const RIBBON_FRAG: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/road_surface.frag.spv")); const SYMBOL_VERT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/symbol.vert.spv")); const SYMBOL_BILLBOARD_VERT: &[u8] =     include_bytes!(concat!(env!("OUT_DIR"), "/symbol_billboard.vert.spv"));@@ -100,6 +143,18 @@ pub struct Pipelines {     pub symbol_layout: vk::PipelineLayout,     pub fill: vk::Pipeline,     pub line: vk::Pipeline,+    /// Road carriageways: a filled surface with the lane markings painted onto it, from+    /// `road_surface.vert`/`.frag` over the 6-float `tess::ribbon` vertex.+    ///+    /// Deliberately a second pipeline rather than a wider [`line`](Self::line). `TrafficMesh` and+    /// the route overlay both ride the 7-float stroke format and the line pipeline, so widening it+    /// to carry an across-road coordinate would charge every one of them for a layer they do not+    /// draw — the tradeoff `tile/geometry.rs` already states about the lane fans this replaces.+    ///+    /// Same fixed-function state as [`line`](Self::line) — [`Depth::Off`], no culling, straight+    /// src-alpha — because a carriageway is flat basemap drawn in layer order like every other+    /// flat 2D layer. Only the vertex format and the shaders differ.+    pub ribbon: vk::Pipeline,     /// Depth-tested (test + write, `LESS`) variant of [`fill`](Self::fill), for the 3D layers     /// WS-A (buildings) and WS-G (terrain) add. It reuses the position-only fill shaders so the     /// render-pass depth path is exercised today; the 3D workstreams build their own pipelines@@ -176,6 +231,8 @@ impl Pipelines {         let fill_frag = shader_module(device, FILL_FRAG)?;         let line_vert = shader_module(device, LINE_VERT)?;         let line_frag = shader_module(device, LINE_FRAG)?;+        let ribbon_vert = shader_module(device, RIBBON_VERT)?;+        let ribbon_frag = shader_module(device, RIBBON_FRAG)?;         let symbol_vert = shader_module(device, SYMBOL_VERT)?;         let symbol_billboard_vert = shader_module(device, SYMBOL_BILLBOARD_VERT)?;         let symbol_frag = shader_module(device, SYMBOL_FRAG)?;@@ -214,6 +271,32 @@ impl Pipelines {                 .format(vk::Format::R32_SFLOAT)                 .offset(24),         ];+        // Ribbon (road carriageways): position (2 floats), join normal (2 floats), the normalised+        // across-road coordinate `t`, and tile-local distance-along. 24-byte stride. `t` is both the+        // vertex shader's extrusion multiplier and the fragment shader's marking coordinate, which+        // is what keeps this to six floats rather than seven.+        let ribbon_attributes = [+            vk::VertexInputAttributeDescription::default()+                .location(0)+                .binding(0)+                .format(vk::Format::R32G32_SFLOAT)+                .offset(0),+            vk::VertexInputAttributeDescription::default()+                .location(1)+                .binding(0)+                .format(vk::Format::R32G32_SFLOAT)+                .offset(8),+            vk::VertexInputAttributeDescription::default()+                .location(2)+                .binding(0)+                .format(vk::Format::R32_SFLOAT)+                .offset(16),+            vk::VertexInputAttributeDescription::default()+                .location(3)+                .binding(0)+                .format(vk::Format::R32_SFLOAT)+                .offset(20),+        ];         // Sprite (POI icons + app markers): position (tile-local / clip) + uv (atlas), 4 floats.         // The on-ground path — not billboarded — so no per-vertex anchor. Shared with the marker         // path, which pushes 4-float clip-space quads, which is why this format must not grow.@@ -308,6 +391,22 @@ impl Pipelines {             Stencil::Ignore,             Depth::Off,         );+        // Road carriageways. Same fixed-function state as `line` — a carriageway is flat basemap,+        // so depth stays off and layer order does the compositing exactly as it does for a stroke.+        // Only the vertex format and the shaders differ, which is the whole point of splitting it+        // off rather than widening the format every stroked layer shares.+        let ribbon = build(+            device,+            layout,+            render_pass,+            samples,+            ribbon_vert,+            ribbon_frag,+            (crate::tess::ribbon::FLOATS_PER_VERTEX * 4) as u32,+            &ribbon_attributes,+            Stencil::Ignore,+            Depth::Off,+        );         // The depth-tested variant of `fill`: same shaders and vertex format, depth test + write         // on. WS-A/WS-G draw their extruded/relief geometry through pipelines built like this so         // the 3D layers occlude correctly; the flat 2D layers never bind it.@@ -371,6 +470,8 @@ impl Pipelines {                 device.destroy_shader_module(fill_frag, None);                 device.destroy_shader_module(line_vert, None);                 device.destroy_shader_module(line_frag, None);+                device.destroy_shader_module(ribbon_vert, None);+                device.destroy_shader_module(ribbon_frag, None);                 device.destroy_shader_module(symbol_vert, None);                 device.destroy_shader_module(symbol_billboard_vert, None);                 device.destroy_shader_module(symbol_frag, None);@@ -458,6 +559,8 @@ impl Pipelines {         device.destroy_shader_module(fill_frag, None);         device.destroy_shader_module(line_vert, None);         device.destroy_shader_module(line_frag, None);+        device.destroy_shader_module(ribbon_vert, None);+        device.destroy_shader_module(ribbon_frag, None);         device.destroy_shader_module(symbol_vert, None);         device.destroy_shader_module(symbol_billboard_vert, None);         device.destroy_shader_module(symbol_frag, None);@@ -469,10 +572,11 @@ impl Pipelines {         device.destroy_shader_module(terrain_vert, None);         device.destroy_shader_module(terrain_frag, None); -        match (fill, line, depth, building, terrain, symbol, sprite, puck, mask, scrim) {+        match (fill, line, ribbon, depth, building, terrain, symbol, sprite, puck, mask, scrim) {             (                 Ok(fill),                 Ok(line),+                Ok(ribbon),                 Ok(depth),                 Ok(building),                 Ok(terrain),@@ -486,6 +590,7 @@ impl Pipelines {                 symbol_layout,                 fill,                 line,+                ribbon,                 depth,                 building,                 terrain,@@ -495,11 +600,12 @@ impl Pipelines {                 mask,                 scrim,             }),-            (fill, line, depth, building, terrain, symbol, sprite, puck, mask, scrim) => {-                for created in-                    [fill, line, depth, building, terrain, symbol, sprite, puck, mask, scrim]-                        .into_iter()-                        .flatten()+            (fill, line, ribbon, depth, building, terrain, symbol, sprite, puck, mask, scrim) => {+                for created in [+                    fill, line, ribbon, depth, building, terrain, symbol, sprite, puck, mask, scrim,+                ]+                .into_iter()+                .flatten()                 {                     device.destroy_pipeline(created, None);                 }@@ -516,6 +622,7 @@ impl Pipelines {     pub unsafe fn destroy(&self, device: &ash::Device) {         device.destroy_pipeline(self.fill, None);         device.destroy_pipeline(self.line, None);+        device.destroy_pipeline(self.ribbon, None);         device.destroy_pipeline(self.depth, None);         device.destroy_pipeline(self.building, None);         device.destroy_pipeline(self.terrain, None);
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 802f8d2c56..43509d62f8 100644--- a/library/map/src/main/rust/src/vulkan/renderer.rs+++ b/library/map/src/main/rust/src/vulkan/renderer.rs@@ -55,13 +55,22 @@ 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.+    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.+    yellow_centre: bool,     /// Shaped symbol candidates (CPU-side): the renderer emits quads per frame     /// at the frame's text size. Shaped once on the worker thread.     labels: Vec<geometry::ShapedLabel>,     /// Per-lane turn arrows (CPU-side): placed once on the worker thread from the archive's     /// turn-lane table. The renderer builds their triangles per frame — rotated, scaled to a screen-    /// size and offset into their lane — because all three follow the camera, exactly as the lane-    /// dividers' offset does. Empty below the lane zoom gate and on any tile with no `turn:lanes`.+    /// size and offset into their lane — because all three follow the camera, exactly as the+    /// carriageway's own width does. Empty below the lane zoom gate and on any tile with no+    /// `turn:lanes`.     arrows: Vec<crate::tile::arrow::ArrowInstance>,     z: u8,     x: u32,@@ -89,6 +98,21 @@ struct TrafficBuffers {     index_count: u32, } +/// One tile's carriageway surface for one set of road-shape inputs, on the GPU.+///+/// The three shape fields are push constants rather than vertex attributes, which is why they key+/// the mesh split: every road in the tile that agrees on all three shares this draw.+struct CarriagewayBuffers {+    /// Index into the style's layer list, for the asphalt colour and the lane width ramp.+    layer_index: usize,+    lanes: u8,+    split: f32,+    oneway: bool,+    vertices: Buffer,+    indices: Buffer,+    index_count: u32,+}+ /// One tile's extruded 3D buildings, on the GPU. /// /// One combined mesh per tile — every building in the tile, walls and roofs — in the 7-float@@ -918,6 +942,45 @@ impl Renderer {                 });             }         }+        // The tile's road carriageways: one mesh per distinct road shape, uploaded like the+        // traffic segments above.+        let mut carriageways = Vec::with_capacity(mesh.carriageways.len());+        for road in &mesh.carriageways {+            if road.indices.is_empty() {+                continue;+            }+            unsafe {+                let vertices = Buffer::upload(+                    &self.context.instance,+                    self.context.physical_device,+                    &self.context.device,+                    vk::BufferUsageFlags::VERTEX_BUFFER,+                    &road.vertices,+                )?;+                let indices = match Buffer::upload(+                    &self.context.instance,+                    self.context.physical_device,+                    &self.context.device,+                    vk::BufferUsageFlags::INDEX_BUFFER,+                    &road.indices,+                ) {+                    Ok(buffer) => buffer,+                    Err(e) => {+                        vertices.destroy(&self.context.device);+                        return Err(e);+                    }+                };+                carriageways.push(CarriagewayBuffers {+                    layer_index: road.layer_index,+                    lanes: road.lanes,+                    split: road.split,+                    oneway: road.oneway,+                    vertices,+                    indices,+                    index_count: road.indices.len() as u32,+                });+            }+        }         // The tile's 3D buildings, if any: one combined mesh, uploaded like the rest.         let buildings = if mesh.buildings.indices.is_empty() {             None@@ -988,6 +1051,8 @@ impl Renderer {             terrain,             regions,             traffic,+            carriageways,+            yellow_centre: mesh.yellow_centre,             labels: mesh.labels.clone(),             arrows: mesh.arrows.clone(),             z: mesh.z,@@ -1085,6 +1150,10 @@ impl Renderer {                     segment.vertices.destroy(device);                     segment.indices.destroy(device);                 }+                for road in &tile.carriageways {+                    road.vertices.destroy(device);+                    road.indices.destroy(device);+                }                 if let Some(buildings) = &tile.buildings {                     buildings.vertices.destroy(device);                     buildings.indices.destroy(device);@@ -1264,12 +1333,14 @@ impl Renderer {     ///    its flat `earth` fill in step 1; at pitch 0 the grid collapses to the flat footprint.     /// 1. **Basemap layers**, layer-major across tiles, coarsest tile first (fill/line, then     ///    symbols per layer). WS-D scales each tile draw's alpha through `Push.morph.x`.-    /// 2. **`record_traffic`** — basemap detail, so it dims with the region scrim (WS-B animates+    /// 2. **`record_carriageways`** — road surfaces and their lane markings at z16+, over the road+    ///    fills they replace and still under the buildings and the deferred symbols.+    /// 3. **`record_traffic`** — basemap detail, so it dims with the region scrim (WS-B animates     ///    it via `Push.misc.w`).-    /// 3. **`record_arrows`** — lane turn arrows over the roads.-    /// 4. **`record_region_mask`** — stencil + scrim; dims 1–3, not the route/puck.-    /// 5. **`record_route`** — over the scrim (a followed route must not dim), under the puck.-    /// 6. **`record_overlays`** — markers (app pins; WS-F vehicles) billboarded upright under tilt,+    /// 4. **`record_arrows`** — lane turn arrows over the roads.+    /// 5. **`record_region_mask`** — stencil + scrim; dims 1–4, not the route/puck.+    /// 6. **`record_route`** — over the scrim (a followed route must not dim), under the puck.+    /// 7. **`record_overlays`** — markers (app pins; WS-F vehicles) billboarded upright under tilt,     ///    then the puck on top; last.     ///     /// Where a new workstream slots in: **WS-A buildings** and **WS-G terrain** draw with the@@ -1585,6 +1656,10 @@ impl Renderer {         // Traffic sits on the roads it colours, so it draws after the basemap layer loop but         // before the region scrim — it is basemap detail and should dim with everything else         // when a region is selected, unlike the route.+        // Road carriageways: over the flat layer loop, because the surface and its markings+        // replace the road fills at this zoom, and under the buildings and deferred symbols+        // below, because a carriageway is flat basemap like every other road layer.+        self.record_carriageways(command_buffer, camera, layers, palette, &ordered, &mut submitted);         // 3D buildings: after the flat basemap so they paint over it, depth-tested so they occlude         // one another. Gated to z14+; at pitch 0 the building matrix collapses height to the         // footprint, so the flat overhead map is unchanged. Before the deferred symbols, so POI@@ -1614,13 +1689,105 @@ impl Renderer {         device.end_command_buffer(command_buffer).map_err(|e| format!("end_command_buffer {e:?}"))     } +    /// Draw the road carriageways: each resident tile's road surfaces, with the lane markings+    /// painted on by `road_surface.frag` as a function of the across-road coordinate rather than+    /// drawn as geometry.+    ///+    /// 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.+    ///+    /// Coarsest tile first, in `ordered`, for the same reason the layer loop is: a stale ancestor+    /// standing in for a tile that has not arrived must be drawn *under* its descendants, or its+    /// asphalt lands on top of the sharp child as it loads.+    unsafe fn record_carriageways(+        &self,+        command_buffer: vk::CommandBuffer,+        camera: &Camera,+        layers: &[Layer],+        palette: Palette,+        ordered: &[u64],+        submitted: &mut usize,+    ) {+        let device = &self.context.device;+        let floor = camera.zoom.floor().clamp(0.0, 22.0) as u8;+        let edge_aa = f32::from(self.swapchain.samples == vk::SampleCountFlags::TYPE_1);+        let mut bound = false;+        for key in ordered {+            let Some(tile) = self.tiles.get(key) else { continue };+            if tile.carriageways.is_empty() {+                continue;+            }+            let tile_to_clip = camera.tile_to_clip(tile.z, tile.x, tile.y);+            let tile_span_px = camera.tile_span_px(tile.z);+            let yellow = f32::from(tile.yellow_centre);+            for road in &tile.carriageways {+                let Some(layer) = layers.get(road.layer_index) else { continue };+                if !layer.draws_at(floor) {+                    continue;+                }+                // The style ramp is one *lane's* width, so this road's own width is that times+                // the lanes it carries — one number cannot describe both a two-lane street and an+                // eight-lane motorway. Halved because the vertex shader offsets each kerb from+                // the centreline, exactly as `Stroke::half_px` does for a stroke.+                let half_width_px =+                    layer.width.at(camera.zoom) * camera.density * road.lanes as f32 / 2.0;+                if half_width_px <= 0.0 {+                    continue;+                }+                if !bound {+                    device.cmd_bind_pipeline(+                        command_buffer,+                        vk::PipelineBindPoint::GRAPHICS,+                        self.pipelines.ribbon,+                    );+                    bound = true;+                }+                // The asphalt only. The markings are the shader's own palette, because they have+                // to match the white it antialiases them against.+                let asphalt = scale_alpha(layer.color(palette), layer.opacity_at(camera.zoom));+                let push = Push {+                    tile_to_clip,+                    color: argb_to_rgba(asphalt),+                    line: [+                        half_width_px,+                        road.lanes as f32,+                        road.split,+                        f32::from(road.oneway),+                    ],+                    misc: [tile_span_px, edge_aa, yellow, camera.time_seconds],+                    // The markings are static, so unlike the traffic draw there is no phase to+                    // animate and nothing to fade: `MORPH_NONE` is what the ribbon contract asks+                    // for.+                    morph: MORPH_NONE,+                };+                device.cmd_push_constants(+                    command_buffer,+                    self.pipelines.layout,+                    vk::ShaderStageFlags::VERTEX | vk::ShaderStageFlags::FRAGMENT,+                    0,+                    push.as_bytes(),+                );+                device.cmd_bind_vertex_buffers(command_buffer, 0, &[road.vertices.buffer], &[0]);+                device.cmd_bind_index_buffer(+                    command_buffer,+                    road.indices.buffer,+                    0,+                    vk::IndexType::UINT32,+                );+                device.cmd_draw_indexed(command_buffer, road.index_count, 1, 0, 0, 0);+                *submitted += 1;+            }+        }+    }+     /// Draw the per-lane turn arrows: one straight-arrow glyph per marked lane, rotated to point-    /// where the lane leads and pushed into its lane by the same lateral fan the dividers use.+    /// where the lane leads and pushed sideways onto the lane the carriageway painted.     ///     /// Built per frame — rotation, screen size and lane offset all follow the camera, exactly as-    /// the dividers' offset does — and drawn through the **fill** pipeline as plain coloured-    /// triangles, so it needs no glyph atlas and no new pipeline. Gated to the lane layer's zoom-    /// floor (z16), so below it nothing is built or drawn.+    /// the carriageway's width does — and drawn through the **fill** pipeline as plain coloured+    /// triangles, so it needs no glyph atlas and no new pipeline. Gated to the carriageway layer's+    /// zoom floor (z16), so below it nothing is built or drawn.     unsafe fn record_arrows(         &mut self,         command_buffer: vk::CommandBuffer,@@ -1628,16 +1795,19 @@ impl Renderer {         layers: &[Layer],         submitted: &mut usize,     ) {-        // The lane layer whose `spread`/`lanes` ramps decide the sideways offset. Without it there-        // is no fan and every lane's arrow would stack on the centreline. Resolved through-        // [`crate::style::road_lane_layer`], which is careful to pick the *road* lane layer and+        // The carriageway layer, whose zoom window gates the arrows and whose width ramp puts them+        // over the lanes its own markings drew. Resolved through+        // [`crate::style::road_carriageway_layer`], which is careful to pick the *road* layer and         // not the first layer that happens to carry a spread — see its doc comment.-        let Some(lane_layer) = crate::style::road_lane_layer(layers) else { return };+        let Some(carriageway) = crate::style::road_carriageway_layer(layers) else { return };         let floor = camera.zoom.floor().clamp(0.0, 22.0) as u8;-        if !lane_layer.draws_at(floor) {+        if !carriageway.draws_at(floor) {             return;         }         let density = camera.density;+        // One lane of the carriageway, in device px. The lane count is the arrow's own, so a+        // three-lane approach and a five-lane one are each spread across their whole road.+        let lane_px = carriageway.width.at(camera.zoom) * density;         let unit = crate::tile::arrow::unit_arrow_triangles();         // Build each tile's triangles first — this borrows `self.tiles` — then upload and draw,         // which takes `&mut self`. One batch per tile carries its own tile-to-clip matrix.@@ -1653,8 +1823,14 @@ impl Renderer {             let scale = ARROW_DP * density / span; // tile-local 0..1 units per unit-arrow coord             let mut verts: Vec<f32> = Vec::with_capacity(tile.arrows.len() * unit.len() * 2);             for a in &tile.arrows {-                // Sideways into the lane, perpendicular to the road heading (not the glyph's turn).-                let lateral = lane_layer.lane_offset_px(camera.zoom, density, a.ordinal, a.count, 255);+                // Sideways onto the lane, perpendicular to the road heading (not the glyph's+                // turn). Measured from the middle of the road out, so it is the lane's own centre+                // in the same -1..+1 across-road coordinate `tess::ribbon` gives the shader — an+                // arrow that does not sit between the dividers the markings drew is worse than no+                // arrow at all.+                let lanes = a.count.max(1) as f32;+                let centre_t = (2.0 * a.ordinal as f32 + 1.0) / lanes - 1.0;+                let lateral = centre_t * lane_px * lanes / 2.0;                 crate::tile::arrow::arrow_verts(a, scale, lateral / span, &mut verts);             }             if !verts.is_empty() {@@ -2899,6 +3075,10 @@ impl Drop for Renderer {                     region.vertices.destroy(&self.context.device);                     region.indices.destroy(&self.context.device);                 }+                for road in &tile.carriageways {+                    road.vertices.destroy(&self.context.device);+                    road.indices.destroy(&self.context.device);+                }                 if let Some(buildings) = &tile.buildings {                     buildings.vertices.destroy(&self.context.device);                     buildings.indices.destroy(&self.context.device);@@ -2918,6 +3098,10 @@ impl Drop for Renderer {                     region.vertices.destroy(&self.context.device);                     region.indices.destroy(&self.context.device);                 }+                for road in &tile.carriageways {+                    road.vertices.destroy(&self.context.device);+                    road.indices.destroy(&self.context.device);+                }                 if let Some(buildings) = &tile.buildings {                     buildings.vertices.destroy(&self.context.device);                     buildings.indices.destroy(&self.context.device);
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 351d061fd0..10ae8c0c88 100644--- a/library/map/src/main/rust/style/basemap.flat.json+++ b/library/map/src/main/rust/style/basemap.flat.json@@ -595,26 +595,21 @@       "lanes": { "interpolate": "linear", "stops": [[0, 1], [9, 2], [11, 3], [13, 4]] }     },     {-      "id": "roads-lanes",+      "id": "roads-carriageway",       "authored": "roads_major",       "source": "roads",       "type": "line",+      "carriageway": true,       "kinds": ["highway", "major_road", "minor_road"],       "forbid_flags": ["tunnel"],       "minzoom": 16,-      "light": "#b7bcc6",-      "dark": "#5c6270",+      "light": "#c8ccd3",+      "dark": "#3a3f47",       "width": {-        "interpolate": "exponential",-        "base": 1.6,-        "stops": [[16, 0.4], [18, 0.7], [20, 1.2]]-      },-      "spread": {         "interpolate": "exponential",         "base": 2.0,         "stops": [[16, 3.0], [18, 11.0], [20, 40.0]]-      },-      "lanes": { "interpolate": "linear", "stops": [[16, 8]] }+      }     },     {       "id": "poi-outdoor",