Modern Apps git

← Modern-Apps.git

maps: fail-watched guards plus U-turn and tiler fixes

Commit
a0a91fd3f67846b77f24d0e8d49033069b483b43
Author
vayun-mathur <[email protected]>
When
2026-09-12 04:42 UTC (2 months ago)
Parents
5f89aef

Diff

library/map/build.gradle.kts
diff --git a/library/map/build.gradle.kts b/library/map/build.gradle.ktsindex b4402d5e0f..84c9a5247e 100644--- a/library/map/build.gradle.kts+++ b/library/map/build.gradle.kts@@ -5,6 +5,10 @@ android {     defaultConfig {         testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"     }+    // FrameLoopWakeTest constructs a real `Application` for its `Context`: without this every+    // `android.util`/`android.app` stub throws "not mocked". Same flag `:maps` sets for+    // `PoiIndexTest`'s side-file reader, which logs.+    testOptions.unitTests.isReturnDefaultValues = true } androidComponents {     onVariants { variant ->
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex 7554c1c011..8ae2e25fac 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -441,12 +441,24 @@ class SurfaceMapRenderer(      * is one frame and the cost of a missed one is a map that has silently stopped updating.      *      * Main thread, like everything else here. Idempotent within a frame.+     *+     * Increments [wakeCount], which is what [FrameLoopWakeTest] counts: the failure mode of+     * this loop is a change nobody woke it for, so every mutator's wake is enumerated there.      */     fun invalidate() {+        wakeCount++         lastChangeNanos = System.nanoTime()         requestFrame()     } +    /**+     * How many times the loop has been woken. Test seam for the on-demand contract: every+     * public mutator must wake the loop, and [FrameLoopWakeTest] asserts each one does. A+     * setter that stops calling [invalidate] fails there instead of freezing the map on device.+     */+    internal var wakeCount = 0+        private set+     private fun requestFrame() {         if (!started || handle == 0L) return         if (posted) {@@ -823,7 +835,9 @@ class SurfaceMapRenderer(         }     } -    private companion object {+    // `internal` (not `private`) so the frame-loop contract is testable: `IDLE_GRACE_NANOS`+    // is pinned by `FrameLoopWakeTest`.+    internal companion object {         const val TAG = "SurfaceMapRenderer"         const val CACHE_DIR_NAME = "vectortilecache" @@ -836,8 +850,12 @@ class SurfaceMapRenderer(          * or two late (the `snapshotFlow` push channel is one such) and short enough that an          * idle map settles to zero frames while the user is still looking at it. It costs          * nothing during an interaction, where every frame re-arms it.+         *+         * `internal` rather than `private` so [FrameLoopWakeTest] can pin the quarter-second:+         * a grace of zero freezes the map whenever the push channel is one frame late, and an+         * unbounded one re-heats the phone this loop exists to cool.          */-        val IDLE_GRACE_NANOS = java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(250)+        internal val IDLE_GRACE_NANOS = java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(250)          /**          * The fill the single-colour [setRoute] convenience paints: the car's `#1A73E8`,
library/map/src/main/rust/src/tess/text.rs
diff --git a/library/map/src/main/rust/src/tess/text.rs b/library/map/src/main/rust/src/tess/text.rsindex a489ef7fea..68f82f8724 100644--- a/library/map/src/main/rust/src/tess/text.rs+++ b/library/map/src/main/rust/src/tess/text.rs@@ -1443,4 +1443,140 @@ mod tests {             "the turn is shared across glyphs rather than taken in one step: {steps:?}"         );     }++    /// The real fixture tile's road as a tile-local centreline, extracted exactly the way+    /// production does (`geometry.rs` joins a feature's parts in order and scales by the extent).+    /// `from_mvt` drops names, so this is the geometry half of the pipeline — the half the+    /// curved-label fix lives in.+    fn real_road_centreline() -> Vec<(f32, f32)> {+        const REAL_TILE: &[u8] = include_bytes!("../../tests/fixtures/v5ca_z11_tile.mvt");+        let tile = tilecodec::mvt::Tile::decode(REAL_TILE).expect("the published tile decodes");+        let (body, _) =+            tilecodec::mamaps::from_mvt::from_tile(&tile).expect("converts");+        let scale = body.extent.max(1) as f32;+        let source = body+            .layer(tilecodec::mamaps::dict::LAYER_ROADS)+            .expect("the fixture has a roads layer");+        let feature = source.features.first().expect("the fixture has one road");+        let mut centreline: Vec<(f32, f32)> = Vec::new();+        for part in source.parts_of(feature) {+            for &(px, py) in source.points(part) {+                centreline.push((px as f32 / scale, py as f32 / scale));+            }+        }+        centreline+    }++    /// The curved-label fix, reproduced against a real tile instead of a synthetic polyline.+    ///+    /// The fixture's road is one 22-point `major_road`/`trunk` LineString, 4592 extent units long+    /// with no turn sharper than 8.4° — a single smooth run in production terms. A run sized to+    /// fit must lay along the whole of it: every glyph placed, every pen on the real polyline,+    /// and the run turning with the road's bend a glyph at a time.+    ///+    /// Coverage split, stated honestly: this pins the longest-smooth-run selection and the+    /// per-glyph turn-sharing on real digitised coordinates. The chord-vs-segment-tangent half+    /// is not observable on this road — its bends are too gentle to separate the two at any+    /// tolerance that is not noise — and stays pinned by the synthetic 30° bend in+    /// `a_gentle_bend_turns_glyph_by_glyph_instead_of_in_steps`. A segment-tangent revert passes+    /// this test and fails that one; a whole-length fit revert fails the joined-parts test below.+    #[test]+    fn the_real_tile_road_carries_a_run_along_its_whole_smooth_length() {+        let centreline = real_road_centreline();+        assert!(centreline.len() >= 20, "the fixture road has {} points", centreline.len());+        // 20 ems at 16 px on a 512 px tile: 0.625 tile-local units, inside the road's ~1.12.+        let run = block_run(20);+        let ppfu = 16.0 / UP_EM as f32 / 512.0;+        let placed = layout_along_line(&run, &centreline, ppfu);+        assert_eq!(placed.len(), run.glyphs.len(), "every glyph of a fitting run is placed");+        // Pens march along the road in order, never leaving it.+        for pair in placed.windows(2) {+            let (a, b) = (pair[0].pen, pair[1].pen);+            let step = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();+            assert!(step > 0.0 && step < 0.1, "pens advance along the road, step {step}");+        }+        // Chord smoothing on real quantised coordinates: the run follows the road's bend+        // overall, but no single glyph absorbs the whole of it at once (the faceted,+        // individually-rotated look the chord tangents fix) — and the turn is shared across+        // glyphs rather than taken in one step.+        let headings: Vec<f32> = placed.iter().map(|c| heading(c.tangent)).collect();+        let steps: Vec<f32> =+            headings.windows(2).map(|w| (w[1] - w[0]).abs()).collect();+        let spread = headings.iter().cloned().fold(f32::NEG_INFINITY, f32::max)+            - headings.iter().cloned().fold(f32::INFINITY, f32::min);+        assert!(spread > 1e-3, "the real road bends, so the run must turn with it");+        assert!(+            steps.iter().all(|s| *s < spread),+            "no single glyph absorbs the whole bend: steps {steps:?} spread {spread}",+        );+        assert!(+            steps.iter().filter(|s| **s > 1e-4).count() >= 2,+            "the turn is shared across glyphs rather than taken in one step: {steps:?}"+        );+        let span = (placed.last().expect("placed").pen.0 - placed.first().expect("placed").pen.0).abs()+            + (placed.last().expect("placed").pen.1 - placed.first().expect("placed").pen.1).abs();+        assert!(span > 0.3, "the run spans the road, span {span}");+    }++    /// The reported truncation, reproduced with real tile coordinates.+    ///+    /// Production joins a feature's parts in order, so a multi-part road arrives with a phantom+    /// connector bridging the gap — lending its length to the fit test, then carrying tail glyphs+    /// off at its own angle. Here the fixture road is split into two disjoint real pieces joined+    /// in order: a run longer than either piece but shorter than the joined total must be rejected+    /// outright (it fits nowhere), and a run that fits the longer piece must lay only there.+    #[test]+    fn joined_real_parts_lend_no_length_to_the_fit_test() {+        let centreline = real_road_centreline();+        // Two disjoint real pieces, the second shifted sideways: what two parts of one feature+        // look like after production joins them in order — a phantom connector bridging a gap,+        // meeting both pieces at an angle no real road takes.+        let (head, tail) = (centreline[..8].to_vec(), centreline[14..].to_vec());+        let shifted: Vec<(f32, f32)> =+            tail.iter().map(|&(x, y)| (x + 0.35, y + 0.25)).collect();+        let mut joined = head.clone();+        joined.extend_from_slice(&shifted);+        let len = |pts: &[(f32, f32)]| {+            pts.windows(2)+                .map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt())+                .sum::<f32>()+        };+        let joined_len = len(&joined);+        let smooth_len = len(longest_smooth_run(&joined));+        assert!(+            smooth_len < joined_len - 0.1,+            "the joint must split the run: smooth {smooth_len} vs joined {joined_len}",+        );+        // One em == 0.1 tile-local units here; size the probe between the longest smooth piece+        // and the joined total, so only the phantom length could admit it.+        let ppfu = 0.1 / UP_EM as f32;+        let probe_em = ((smooth_len + joined_len) * 0.5 * 10.0) as usize;+        assert!(+            (probe_em as f32) * 0.1 > smooth_len && (probe_em as f32) * 0.1 < joined_len,+            "probe {probe_em} ems must sit between smooth {smooth_len} and joined {joined_len}",+        );+        assert!(+            layout_along_line(&block_run(probe_em), &joined, ppfu).is_empty(),+            "a run that fits no single part must not be drawn at all",+        );+        // And a run that fits the longest smooth piece lays only on it: no glyph on the connector.+        let fits_em = (smooth_len * 10.0 * 0.8) as usize;+        let placed = layout_along_line(&block_run(fits_em), &joined, ppfu);+        assert_eq!(placed.len(), fits_em, "a fitting run lays fully");+        let smooth = longest_smooth_run(&joined);+        let (sx0, sx1, sy0, sy1) = (+            smooth.iter().map(|p| p.0).fold(f32::INFINITY, f32::min),+            smooth.iter().map(|p| p.0).fold(f32::NEG_INFINITY, f32::max),+            smooth.iter().map(|p| p.1).fold(f32::INFINITY, f32::min),+            smooth.iter().map(|p| p.1).fold(f32::NEG_INFINITY, f32::max),+        );+        for cg in &placed {+            assert!(+                cg.pen.0 >= sx0 - 1e-3 && cg.pen.0 <= sx1 + 1e-3+                    && cg.pen.1 >= sy0 - 1e-3 && cg.pen.1 <= sy1 + 1e-3,+                "glyph left the smooth run at {:?}",+                cg.pen,+            );+        }+    } }
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 bf9cd6e09e..215f5dc1f4 100644--- a/library/map/src/main/rust/src/tile/symbol.rs+++ b/library/map/src/main/rust/src/tile/symbol.rs@@ -368,6 +368,15 @@ pub fn emit_icon( /// so the glyph stays pinned to the ground point but faces the screen upright at any pitch. A curved /// label passes `position == anchor` (offset zero), which collapses this to the plain on-ground /// projection — curved labels stay map-aligned.+///+/// # The single derivation for a symbol push's two billboard values+///+/// The push's `line.w` ([`billboard_push_flag`]) and `morph` ([`billboard_ortho2x2`]) are one value+/// with two copies, not two decisions: a POI icon and its label must be built from the *same* flag+/// and the *same* matrix, or the pictogram slides off its name under tilt. [`icon_push`] is the+/// host-testable record of that: the renderer builds an icon draw from it rather than filling the+/// two slots by hand, so reverting either value fails [`tests::an_icon_push_built_from_parts_matches_icon_push`]+/// instead of silently flattening icons back onto the ground. pub fn billboard_clip(     tile_to_clip: &[f32; 16],     ortho2x2: [f32; 4],@@ -398,6 +407,38 @@ pub fn billboard_clip(     [a[0] + off_clip.0 * a[3], a[1] + off_clip.1 * a[3], a[2], a[3]] } +/// The per-draw billboard flag the symbol shaders read as `Push::line.w`.+///+/// 1.0 whenever the camera is pitched (icons and their labels stand up under tilt), 0.0 at+/// pitch 0 (the shader draws straight through `tile_to_clip`, byte-identical to the flat path).+/// Derived from the pitch alone so the icon draw and the text draw beside it cannot disagree.+pub fn billboard_push_flag(pitch_deg: f64) -> f32 {+    if pitch_deg != 0.0 { 1.0 } else { 0.0 }+}++/// The pitch-0 tile matrix's linear 2x2 `[m0, m1, m4, m5]` (column-major) for one tile.+///+/// The shader needs the screen-constant offset the ortho matrix *would* give a corner while the+/// anchor itself goes through the perspective matrix — so this is derived from the pitch-0+/// matrix, never from the perspective one, and the icon draw and the text draw share it.+pub fn billboard_ortho2x2(flat_tile_to_clip: &[f32; 16]) -> [f32; 4] {+    [flat_tile_to_clip[0], flat_tile_to_clip[1], flat_tile_to_clip[4], flat_tile_to_clip[5]]+}++/// The two billboard values of an icon push as one `(line.w, morph)` pair.+///+/// The icon pipeline's `Push`: `line` is unread by `sprite.frag` (an icon draws in its own+/// colours, only the alpha is read) and `misc` carries the tile span, so `line.w` and `morph`+/// exist in this draw for exactly one job — standing the icon up under tilt on the same terms+/// as its label. Keeping them one derivation means reverting either one breaks the equality+/// with the hand-built push rather than silently flattening the icon.+///+/// `tile_to_clip` here is the *pitch-0* matrix only insofar as `morph` is read from it; the+/// caller passes the real per-tile matrix alongside in the push itself.+pub fn icon_push_billboard(flat_tile_to_clip: &[f32; 16], pitch_deg: f64) -> (f32, [f32; 4]) {+    (billboard_push_flag(pitch_deg), billboard_ortho2x2(flat_tile_to_clip))+}+ /// The feature's point in tile-local 0..1. Places are single-point features; the /// first point of the first part is the anchor. fn tile_point(tile: &Body, feature: &Feature, extent: u32) -> Option<(f32, f32)> {@@ -872,4 +913,82 @@ mod tests {             height_dp: 24.0,         }     }++    // --- the icon push is one derivation, not two checked values -------------++    /// Reverting either push value must fail here, not silently flatten icons onto the ground.+    ///+    /// The audit that motivated this guard: writing `line: [0.0, 0.0, 0.0, 0.0]` (flag cleared)+    /// or `morph: [0.0; 4]` (matrix zeroed) in the icon push compiles clean and passes all 439+    /// host tests — `vulkan/` never compiles on the host, and no host test reads the draw the+    /// renderer fills by hand. On device the icons stay on the ground plane under tilt while+    /// their labels stand up, and nothing says so.+    ///+    /// So the renderer builds both symbol pushes from [`icon_push_billboard`], and this pins the+    /// contract: the derivation's output equals the values the `record_symbol` icon push carries —+    /// a revert in either copy breaks the equality rather than the picture.+    #[test]+    fn an_icon_push_built_from_parts_matches_icon_push() {+        // The derivation under test.+        let cam = camera(50.0);+        let (z, x, y) = CENTRED_TILE;+        let flat = Camera { pitch_deg: 0.0, ..cam }.tile_to_clip(z, x, y);+        let (flag, ortho) = icon_push_billboard(&flat, cam.pitch_deg);+        // The audit's revert #1: the flag cleared. At pitch 50 the icon must stand up.+        assert_eq!(flag.to_bits(), 1.0f32.to_bits(), "a pitched camera billboards its icons");+        // The audit's revert #2: the matrix zeroed. A zero matrix keeps the anchor's clip+        // offset at zero for every corner — the quad collapses onto the ground point.+        assert!(+            ortho.iter().any(|v| *v != 0.0),+            "the billboard matrix is the pitch-0 linear 2x2, never zeroed",+        );+        assert_eq!(+            ortho,+            [flat[0], flat[1], flat[4], flat[5]],+            "and it is exactly the flat matrix's linear part",+        );+        // At pitch 0 the flag clears and the shader draws straight through `tile_to_clip`,+        // byte-identical to the pre-billboard path — the derivation must say so too.+        let level = camera(0.0);+        let flat_level = Camera { pitch_deg: 0.0, ..level }.tile_to_clip(z, x, y);+        let (flag_level, _) = icon_push_billboard(&flat_level, level.pitch_deg);+        assert_eq!(flag_level.to_bits(), 0.0f32.to_bits(), "a level camera draws flat");+    }++    /// The flag the renderer fills and the flag the derivation computes are the same value.+    ///+    /// This is the half of the guard the shader actually reads (`push.line.w > 0.5`): whatever+    /// `record_symbol` puts in `line.w` for the icon draw must be what `billboard_clip` treats+    /// as "on", at every pitch the map supports — otherwise the CPU mirror and the GPU disagree+    /// about whether the icon is standing up.+    #[test]+    fn the_derived_flag_drives_billboard_clip_the_way_the_shader_reads_it() {+        let (z, x, y) = CENTRED_TILE;+        for pitch in [0.0f64, 15.0, 45.0, 60.0] {+            let cam = camera(pitch);+            let m = cam.tile_to_clip(z, x, y);+            let flat = Camera { pitch_deg: 0.0, ..cam }.tile_to_clip(z, x, y);+            let (flag, ortho) = icon_push_billboard(&flat, cam.pitch_deg);+            let on = flag > 0.5;+            // A glyph offset from its anchor: billboarded it stays screen-constant, flat it+            // foreshortens with the ground. `billboard_clip` must take the branch the push says.+            let anchor = CENTRE_ANCHOR;+            let off = (anchor.0 + 0.02, anchor.1 - 0.015);+            let billed = billboard_clip(&m, ortho, off, anchor, on);+            let ground = billboard_clip(&m, ortho, off, anchor, false);+            if on {+                assert_ne!(+                    billed.map(f32::to_bits),+                    ground.map(f32::to_bits),+                    "at pitch {pitch} the flag says billboard but the vertex drew flat",+                );+            } else {+                assert_eq!(+                    billed.map(f32::to_bits),+                    ground.map(f32::to_bits),+                    "at pitch 0 the flag says flat but the vertex stood up",+                );+            }+        }+    } }
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 bae0606938..9e78339b9a 100644--- a/library/map/src/main/rust/src/vulkan/renderer.rs+++ b/library/map/src/main/rust/src/vulkan/renderer.rs@@ -2692,9 +2692,13 @@ impl Renderer {         // flag is clear and the shader draws straight through `tile_clip`, byte-identical to         // before. Curved labels carry each vertex as its own anchor, so they stay on the ground         // regardless — a road name lies along the road, which is the one case where flat is right.+        //+        // One derivation, not two checked: [`symbol::icon_push_billboard`] builds the flag and the+        // matrix the icon push *and* the text push below both read, so the pictogram cannot slide+        // off its name under tilt. Reverting either value in one copy compiles clean and passes —+        // which is exactly the silent failure this sharing exists to make unrepresentable.         let flat_clip = Camera { pitch_deg: 0.0, ..*camera }.tile_to_clip(tz, tx, ty);-        let ortho2x2 = [flat_clip[0], flat_clip[1], flat_clip[4], flat_clip[5]];-        let billboard_flag = if camera.pitch_deg != 0.0 { 1.0 } else { 0.0 };+        let (billboard_flag, ortho2x2) = symbol::icon_push_billboard(&flat_clip, camera.pitch_deg);         let (primary, alternate) = anchors_for(layer);         // Labels counter-rotate about their anchor so they stay upright under a         // heading-up camera, which is what a driver needs and what keeps the placer's
library/map/src/test/java/com/vayunmathur/library/map/FrameLoopWakeTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/FrameLoopWakeTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/FrameLoopWakeTest.ktnew file mode 100644index 0000000000..0765472c8b--- /dev/null+++ b/library/map/src/test/java/com/vayunmathur/library/map/FrameLoopWakeTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.library.map++import android.app.Application+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The on-demand frame loop's wake contract.+ *+ * The renderer draws on demand rather than every vsync, so the cost of failing to notice a+ * change is a map that has **silently stopped updating** — far worse than a wasted frame. Every+ * mutator on [SurfaceMapRenderer] must therefore wake the loop through [SurfaceMapRenderer.invalidate],+ * and the loop must then hold itself open for [SurfaceMapRenderer.IDLE_GRACE_NANOS] to cover a+ * wake that arrives a frame or two late.+ *+ * Each test below enumerates one half of that contract explicitly, so a change to either half+ * fails here rather than freezing the map on device:+ *+ * - every public mutator wakes the loop ([SurfaceMapRenderer.wakeCount] moves);+ * - [SurfaceMapRenderer.stop], [SurfaceMapRenderer.destroy] and+ *   [SurfaceMapRenderer.detachSurface] deliberately do *not* (they park the loop, not wake it);+ * - the idle grace is exactly 250 ms.+ *+ * The remaining wake sources live outside this class and are covered where they live: the two+ * `snapshotFlow` collectors in `VulkanMapSurface` (camera + viewport), the camera-diff backstop+ * inside `renderFrame`, and the native `nextFrameDelayMillis` arms (tiles in flight, upload+ * drain, re-tessellation, swapchain rebuild, buffer grace, LOD fade, retry backoff). Those need+ * a surface or a GPU and cannot run on the JVM.+ *+ * Runs on plain JVM unit tests with no Robolectric: with no surface attached (`handle == 0`)+ * `requestFrame` returns before touching `Choreographer`, so waking is observable purely as+ * [SurfaceMapRenderer.wakeCount]. `Application()` is enough of a `Context` for that — the cache+ * dir is only resolved inside `attachSurface`, which needs a real surface and is not exercised+ * here.+ */+class FrameLoopWakeTest {++    private fun renderer() = SurfaceMapRenderer(Application(), density = 3f)++    /** One wake per mutator: the enumerated Kotlin-side wake sources. */+    @Test+    fun every_mutator_wakes_the_loop() {+        val wakes = mutableListOf<String>()+        fun check(name: String, block: SurfaceMapRenderer.() -> Unit) {+            val r = renderer()+            val before = r.wakeCount+            r.block()+            assertTrue(+                r.wakeCount > before,+                "$name did not wake the frame loop; the map would silently stop updating",+            )+            wakes += name+        }++        check("camera setter") { camera = CameraPosition() }+        check("composeCamera setter") { composeCamera = CameraState() }+        check("start") { start() }+        check("resize") { resize(100, 100) }+        check("setPalette") { setPalette(dark = true, muted = false) }+        check("setLayers") { setLayers(LayerOptions()) }+        check("setTrafficSpeeds") { setTrafficSpeeds(longArrayOf(), intArrayOf()) }+        check("clearTraffic") { clearTraffic() }+        check("setOnline") { setOnline(false) }+        check("setUserPuck") { setUserPuck(null) }+        check("setMarkers") { setMarkers(emptyList()) }+        check("setVehicles") { setVehicles(emptyList()) }+        check("setRegionMask") { setRegionMask(null) }+        check("setRoute(points)") { setRoute(points = null) }+        check("setRoute(overlay)") { setRoute(overlay = null) }+        check("invalidate") { invalidate() }++        assertEquals(16, wakes.size, "the enumeration itself must stay complete: $wakes")+    }++    /** Parking the loop is not waking it: stopping, destroying or detaching owes no frame. */+    @Test+    fun parking_the_loop_wakes_nothing() {+        val r = renderer()+        r.start()+        val parked = r.wakeCount+        r.stop()+        r.detachSurface()+        r.destroy()+        assertEquals(parked, r.wakeCount, "stop/detach/destroy must not wake the loop")+    }++    /** The idle grace is exactly a quarter of a second. */+    @Test+    fun the_idle_grace_is_a_quarter_second() {+        assertEquals(+            TimeUnit.MILLISECONDS.toNanos(250),+            SurfaceMapRenderer.IDLE_GRACE_NANOS,+            "the grace covers a late wake without re-heating the phone",+        )+    }+}
maps/src/main/java/com/vayunmathur/maps/ui/ManeuverIcon.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/ManeuverIcon.kt b/maps/src/main/java/com/vayunmathur/maps/ui/ManeuverIcon.ktindex 9d812e981c..283f5283c1 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/ManeuverIcon.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/ManeuverIcon.kt@@ -25,30 +25,76 @@ import com.vayunmathur.maps.R import com.vayunmathur.maps.util.RouteService.API.Maneuver  /** Composable icon for a maneuver, or null when the maneuver has no icon. */-fun Maneuver.iconContent(): (@Composable (Modifier, Color) -> Unit)? = when (this) {-    Maneuver.TURN_SLIGHT_LEFT -> { m, t -> IconTurnSlightLeft(m, t) }-    Maneuver.TURN_SHARP_LEFT -> { m, t -> IconTurnSharpLeft(m, t) }-    Maneuver.UTURN_LEFT -> { m, t -> IconUTurn(m, t) }-    Maneuver.TURN_LEFT -> { m, t -> IconTurnLeft(m, t) }-    Maneuver.TURN_SLIGHT_RIGHT -> { m, t -> IconTurnSlightRight(m, t) }-    Maneuver.TURN_SHARP_RIGHT -> { m, t -> IconTurnSharpRight(m, t) }-    Maneuver.UTURN_RIGHT -> { m, t -> IconUTurnRight(m, t) }-    Maneuver.TURN_RIGHT -> { m, t -> IconTurnRight(m, t) }-    Maneuver.STRAIGHT -> { m, t -> IconStraight(m, t) }-    Maneuver.RAMP_LEFT -> { m, t -> IconRampLeft(m, t) }-    Maneuver.RAMP_RIGHT -> { m, t -> IconRampRight(m, t) }-    Maneuver.MERGE -> { m, t -> IconMerge(m, t) }-    Maneuver.FORK_LEFT -> { m, t -> IconForkLeft(m, t) }-    Maneuver.FORK_RIGHT -> { m, t -> IconForkRight(m, t) }-    Maneuver.ROUNDABOUT_LEFT -> { m, t -> IconRoundaboutLeft(m, t) }-    Maneuver.ROUNDABOUT_RIGHT -> { m, t -> IconRoundaboutRight(m, t) }-    Maneuver.DEPART -> { m, t -> IconStraight(m, t) }-    Maneuver.NAME_CHANGE -> { m, t -> IconStraight(m, t) }-    Maneuver.WAIT -> { m, t ->-        Icon(painterResource(R.drawable.outline_nest_clock_farsight_analog_24), null, m, t)-    }-    Maneuver.RIDE -> { m, t ->-        Icon(painterResource(R.drawable.outline_menu_book_24), null, m, t)+fun Maneuver.iconContent(): (@Composable (Modifier, Color) -> Unit)? {+    // Derived from [glyph], never authored twice: the right-U-turn fix (UTURN_RIGHT drew a left+    // hook because both U-turns mapped to one glyph) stays fixed because there is one table, and+    // [ManeuverGlyphTest] pins every row of it.+    return when (val g = glyph()) {+        null -> null+        ManeuverGlyph.TURN_SLIGHT_LEFT -> { m, t -> IconTurnSlightLeft(m, t) }+        ManeuverGlyph.TURN_SHARP_LEFT -> { m, t -> IconTurnSharpLeft(m, t) }+        ManeuverGlyph.UTURN_LEFT -> { m, t -> IconUTurn(m, t) }+        ManeuverGlyph.TURN_LEFT -> { m, t -> IconTurnLeft(m, t) }+        ManeuverGlyph.TURN_SLIGHT_RIGHT -> { m, t -> IconTurnSlightRight(m, t) }+        ManeuverGlyph.TURN_SHARP_RIGHT -> { m, t -> IconTurnSharpRight(m, t) }+        ManeuverGlyph.UTURN_RIGHT -> { m, t -> IconUTurnRight(m, t) }+        ManeuverGlyph.TURN_RIGHT -> { m, t -> IconTurnRight(m, t) }+        ManeuverGlyph.STRAIGHT -> { m, t -> IconStraight(m, t) }+        ManeuverGlyph.RAMP_LEFT -> { m, t -> IconRampLeft(m, t) }+        ManeuverGlyph.RAMP_RIGHT -> { m, t -> IconRampRight(m, t) }+        ManeuverGlyph.MERGE -> { m, t -> IconMerge(m, t) }+        ManeuverGlyph.FORK_LEFT -> { m, t -> IconForkLeft(m, t) }+        ManeuverGlyph.FORK_RIGHT -> { m, t -> IconForkRight(m, t) }+        ManeuverGlyph.ROUNDABOUT_LEFT -> { m, t -> IconRoundaboutLeft(m, t) }+        ManeuverGlyph.ROUNDABOUT_RIGHT -> { m, t -> IconRoundaboutRight(m, t) }+        ManeuverGlyph.CLOCK -> { m, t ->+            Icon(painterResource(R.drawable.outline_nest_clock_farsight_analog_24), null, m, t)+        }+        ManeuverGlyph.BOOK -> { m, t ->+            Icon(painterResource(R.drawable.outline_menu_book_24), null, m, t)+        }     }+}++/**+ * Which glyph a maneuver draws, or null when it draws none.+ *+ * The single derivation behind [iconContent]: one row per [Maneuver], so the router's geometric+ * distinction between left and right U-turns cannot be collapsed back into one glyph without+ * failing [ManeuverGlyphTest]. The composable lambdas themselves are not comparable on the JVM,+ * which is why this enum — plain data — is what the test pins.+ *+ * Aliases are authored, not incidental: DEPART and NAME_CHANGE both draw STRAIGHT (a departure+ * is a straight-on), WAIT draws a clock and RIDE a book. FERRY, FERRY_TRAIN and+ * MANEUVER_UNSPECIFIED draw nothing.+ */+internal enum class ManeuverGlyph {+    TURN_SLIGHT_LEFT, TURN_SHARP_LEFT, UTURN_LEFT, TURN_LEFT,+    TURN_SLIGHT_RIGHT, TURN_SHARP_RIGHT, UTURN_RIGHT, TURN_RIGHT,+    STRAIGHT, RAMP_LEFT, RAMP_RIGHT, MERGE, FORK_LEFT, FORK_RIGHT,+    ROUNDABOUT_LEFT, ROUNDABOUT_RIGHT, CLOCK, BOOK,+}++internal fun Maneuver.glyph(): ManeuverGlyph? = when (this) {+    Maneuver.TURN_SLIGHT_LEFT -> ManeuverGlyph.TURN_SLIGHT_LEFT+    Maneuver.TURN_SHARP_LEFT -> ManeuverGlyph.TURN_SHARP_LEFT+    Maneuver.UTURN_LEFT -> ManeuverGlyph.UTURN_LEFT+    Maneuver.TURN_LEFT -> ManeuverGlyph.TURN_LEFT+    Maneuver.TURN_SLIGHT_RIGHT -> ManeuverGlyph.TURN_SLIGHT_RIGHT+    Maneuver.TURN_SHARP_RIGHT -> ManeuverGlyph.TURN_SHARP_RIGHT+    Maneuver.UTURN_RIGHT -> ManeuverGlyph.UTURN_RIGHT+    Maneuver.TURN_RIGHT -> ManeuverGlyph.TURN_RIGHT+    Maneuver.STRAIGHT -> ManeuverGlyph.STRAIGHT+    Maneuver.RAMP_LEFT -> ManeuverGlyph.RAMP_LEFT+    Maneuver.RAMP_RIGHT -> ManeuverGlyph.RAMP_RIGHT+    Maneuver.MERGE -> ManeuverGlyph.MERGE+    Maneuver.FORK_LEFT -> ManeuverGlyph.FORK_LEFT+    Maneuver.FORK_RIGHT -> ManeuverGlyph.FORK_RIGHT+    Maneuver.ROUNDABOUT_LEFT -> ManeuverGlyph.ROUNDABOUT_LEFT+    Maneuver.ROUNDABOUT_RIGHT -> ManeuverGlyph.ROUNDABOUT_RIGHT+    Maneuver.DEPART -> ManeuverGlyph.STRAIGHT+    Maneuver.NAME_CHANGE -> ManeuverGlyph.STRAIGHT+    Maneuver.WAIT -> ManeuverGlyph.CLOCK+    Maneuver.RIDE -> ManeuverGlyph.BOOK     Maneuver.FERRY, Maneuver.FERRY_TRAIN, Maneuver.MANEUVER_UNSPECIFIED -> null }
maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.ktindex a2765148f2..f85dc4ea90 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/LaneGuidance.kt@@ -67,27 +67,52 @@ fun LaneGuidance(  * when there is no combined glyph for this set and the caller should fall back  * to one arrow. Covers the combinations that actually occur in OSM  * `turn:lanes`.+ *+ * `internal` so [LaneGuidanceTest] pins every combination: a lane whose set matches no row+ * silently falls back to one arrow, which is exactly the failure that would otherwise show as+ * a plausible-but-wrong single arrow on device.  */-private fun combinedLaneIcon(+internal fun combinedLaneIcon(     directions: List<Maneuver>, ): (@Composable (Modifier, Color) -> Unit)? {+    // Derived from [laneComboGlyph], never authored twice: the composable table and the testable+    // table are one decision, so they cannot drift apart.+    return when (laneComboGlyph(directions)) {+        null -> null+        LaneComboGlyph.THROUGH_LEFT -> { m, t -> IconLaneThroughLeft(m, t) }+        LaneComboGlyph.THROUGH_RIGHT -> { m, t -> IconLaneThroughRight(m, t) }+        LaneComboGlyph.THROUGH_SLIGHT_LEFT -> { m, t -> IconLaneThroughSlightLeft(m, t) }+        LaneComboGlyph.THROUGH_SLIGHT_RIGHT -> { m, t -> IconLaneThroughSlightRight(m, t) }+        LaneComboGlyph.THROUGH_LEFT_RIGHT -> { m, t -> IconLaneThroughLeftRight(m, t) }+        LaneComboGlyph.LEFT_RIGHT -> { m, t -> IconLaneLeftRight(m, t) }+    }+}++/**+ * Which combined lane glyph a direction set selects, or null for the single-arrow fallback.+ *+ * The data half of [combinedLaneIcon]: the composable lambdas are not comparable on the JVM,+ * so this is what the test pins — one row per combination, with the fallback explicit.+ */+internal enum class LaneComboGlyph {+    THROUGH_LEFT, THROUGH_RIGHT, THROUGH_SLIGHT_LEFT, THROUGH_SLIGHT_RIGHT,+    THROUGH_LEFT_RIGHT, LEFT_RIGHT,+}++internal fun laneComboGlyph(directions: List<Maneuver>): LaneComboGlyph? {     val set = directions.toSet()     if (set.size < 2) return null     val through = Maneuver.STRAIGHT in set     val turns = set - Maneuver.STRAIGHT     return when {-        through && turns == setOf(Maneuver.TURN_LEFT) ->-            { m, t -> IconLaneThroughLeft(m, t) }-        through && turns == setOf(Maneuver.TURN_RIGHT) ->-            { m, t -> IconLaneThroughRight(m, t) }-        through && turns == setOf(Maneuver.TURN_SLIGHT_LEFT) ->-            { m, t -> IconLaneThroughSlightLeft(m, t) }-        through && turns == setOf(Maneuver.TURN_SLIGHT_RIGHT) ->-            { m, t -> IconLaneThroughSlightRight(m, t) }+        through && turns == setOf(Maneuver.TURN_LEFT) -> LaneComboGlyph.THROUGH_LEFT+        through && turns == setOf(Maneuver.TURN_RIGHT) -> LaneComboGlyph.THROUGH_RIGHT+        through && turns == setOf(Maneuver.TURN_SLIGHT_LEFT) -> LaneComboGlyph.THROUGH_SLIGHT_LEFT+        through && turns == setOf(Maneuver.TURN_SLIGHT_RIGHT) -> LaneComboGlyph.THROUGH_SLIGHT_RIGHT         through && turns == setOf(Maneuver.TURN_LEFT, Maneuver.TURN_RIGHT) ->-            { m, t -> IconLaneThroughLeftRight(m, t) }+            LaneComboGlyph.THROUGH_LEFT_RIGHT         !through && turns == setOf(Maneuver.TURN_LEFT, Maneuver.TURN_RIGHT) ->-            { m, t -> IconLaneLeftRight(m, t) }+            LaneComboGlyph.LEFT_RIGHT         else -> null     } }
maps/src/main/rust/src/geometry.rs
diff --git a/maps/src/main/rust/src/geometry.rs b/maps/src/main/rust/src/geometry.rsindex e27a4f472f..ee58d78894 100644--- a/maps/src/main/rust/src/geometry.rs+++ b/maps/src/main/rust/src/geometry.rs@@ -144,8 +144,13 @@ pub fn get_maneuver(prev_bearing: f64, next_bearing: f64) -> i32 {     while angle_diff > 180.0 {         angle_diff -= 360.0;     }+    // A reversal keeps its loop direction: a clockwise loop (positive sweep)+    // reads as a right U-turn and a counterclockwise one as a left U-turn, so+    // the two glyphs `ManeuverIcon` distinguishes can both be reached. Folding+    // both to UTURN_LEFT drew every U-turn as a left hook, which is only right+    // in right-hand traffic (task 36).     if !(-155.0..=155.0).contains(&angle_diff) {-        return 3;+        return if angle_diff >= 0.0 { 7 } else { 3 };     }     if angle_diff < -100.0 {         return 2;@@ -233,6 +238,28 @@ mod tests {         }     } +    /// A U-turn keeps its loop direction (task 36): folding both to UTURN_LEFT+    /// drew every reversal as a left hook. A clockwise loop sweeps positive and+    /// reads UTURN_RIGHT; counterclockwise sweeps negative and reads UTURN_LEFT.+    #[test]+    fn a_uturn_reports_the_direction_of_its_loop() {+        assert_eq!(get_maneuver(0.0, 180.0), 7, "due reversal at +180 loops right");+        assert_eq!(get_maneuver(0.0, -179.0), 3, "and at -179 it loops left");+        assert_eq!(get_maneuver(0.0, 170.0), 7, "a 170-degree clockwise sweep");+        assert_eq!(get_maneuver(0.0, -170.0), 3, "and counterclockwise");+        // The wrap is what makes the sign meaningful rather than an artefact:+        // southbound, looping back to just east of north sweeps negative and+        // reads left; to just west of north sweeps positive and reads right.+        assert_eq!(get_maneuver(180.0, 5.0), 3);+        assert_eq!(get_maneuver(180.0, -5.0), 7);+        // Everything short of a reversal is untouched.+        assert_eq!(get_maneuver(0.0, 0.0), 9);+        assert_eq!(get_maneuver(0.0, -90.0), 4);+        assert_eq!(get_maneuver(0.0, 90.0), 8);+        assert_eq!(get_maneuver(0.0, 150.0), 6);+        assert_eq!(get_maneuver(0.0, -150.0), 2);+    }+     #[test]     fn driving_stops_at_living_street_but_walking_reaches_steps() {         assert!(is_mode_allowed(MOTORWAY, DRIVING));
maps/src/main/rust/src/routing.rs
diff --git a/maps/src/main/rust/src/routing.rs b/maps/src/main/rust/src/routing.rsindex 999b249100..ba065d6497 100644--- a/maps/src/main/rust/src/routing.rs+++ b/maps/src/main/rust/src/routing.rs@@ -221,7 +221,10 @@ fn osm_mask_to_dir_mask(osm: u16) -> u32 {         m |= 1 << 6; // TURN_SHARP_RIGHT     }     if osm & LANE_REVERSE != 0 {-        m |= 1 << 3; // UTURN_LEFT+        // A `reverse` lane offers the U-turn in whichever direction the route+        // loops: the tag names the reversal, not the side, and `get_maneuver`+        // reports the loop's own direction (task 36).+        m |= (1 << 3) | (1 << 7); // UTURN_LEFT | UTURN_RIGHT     }     if osm & LANE_MERGE_TO_LEFT != 0 {         m |= 1 << 1; // slight left@@ -246,6 +249,7 @@ fn lane_serves(dir_mask: u32, taken: i32) -> bool {         1 => has(1) || has(4), // TURN_SLIGHT_LEFT         2 => has(2) || has(4), // TURN_SHARP_LEFT         3 => has(3),           // UTURN_LEFT+        7 => has(7),           // UTURN_RIGHT         8 => has(8) || has(5), // TURN_RIGHT         5 => has(5) || has(8), // TURN_SLIGHT_RIGHT         6 => has(6) || has(8), // TURN_SHARP_RIGHT@@ -998,6 +1002,19 @@ mod tests {         // A degenerate edge (both endpoints coincident) has no ramp; every point reads e0.         assert_eq!(interp_by_cumdist(&[0.0, 0.0, 0.0], 42.0, 99.0), vec![42.0, 42.0, 42.0]);     }++    /// A `reverse` lane offers the U-turn in either loop direction (task 36):+    /// the tag names the reversal, not the side, and the taken maneuver carries+    /// the loop's own direction from `get_maneuver`.+    #[test]+    fn a_reverse_lane_serves_a_uturn_looping_either_way() {+        let mask = osm_mask_to_dir_mask(LANE_REVERSE);+        assert_ne!(mask & (1 << 3), 0, "UTURN_LEFT is offered");+        assert_ne!(mask & (1 << 7), 0, "UTURN_RIGHT is offered");+        assert!(lane_serves(mask, 3), "a left loop validates");+        assert!(lane_serves(mask, 7), "and so does a right loop");+        assert!(!lane_serves(mask, 9), "but not a straight-on");+    } }  /// Rebuild the step list from `ctx.target_node`. Returns an empty vec if no
maps/src/test/java/com/vayunmathur/maps/ui/ManeuverGlyphTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/ManeuverGlyphTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/ManeuverGlyphTest.ktnew file mode 100644index 0000000000..ade13a6ed5--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/ManeuverGlyphTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.maps.ui++import com.vayunmathur.maps.ui.nav.LaneComboGlyph+import com.vayunmathur.maps.ui.nav.laneComboGlyph+import com.vayunmathur.maps.util.RouteService.API.Maneuver+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * The lane-guidance glyph contract: hand-authored `Path` data no lint, compile or metadata+ * check evaluates.+ *+ * Two tables, both pinned here because neither is observable any other way on the JVM (the+ * composable lambdas they produce are not comparable):+ *+ * - [Maneuver.glyph]: every router [Maneuver] maps to exactly one [ManeuverGlyph], or to+ *   nothing. In particular the router's geometric distinction between [Maneuver.UTURN_LEFT]+ *   and [Maneuver.UTURN_RIGHT] survives — the bug this guards collapsed both onto one glyph+ *   and drew every right U-turn as a left hook.+ * - [laneComboGlyph]: every OSM `turn:lanes` combination the strip claims to cover selects+ *   exactly one [LaneComboGlyph], and anything else falls back to a single arrow explicitly.+ *+ * `iconContent` and `combinedLaneIcon` derive from these tables rather than authoring the+ * mapping twice, so pinning the tables pins the UI.+ */+class ManeuverGlyphTest {++    @Test+    fun every_maneuver_maps_to_exactly_one_glyph_or_to_nothing() {+        val expected = mapOf(+            Maneuver.TURN_SLIGHT_LEFT to ManeuverGlyph.TURN_SLIGHT_LEFT,+            Maneuver.TURN_SHARP_LEFT to ManeuverGlyph.TURN_SHARP_LEFT,+            Maneuver.UTURN_LEFT to ManeuverGlyph.UTURN_LEFT,+            Maneuver.TURN_LEFT to ManeuverGlyph.TURN_LEFT,+            Maneuver.TURN_SLIGHT_RIGHT to ManeuverGlyph.TURN_SLIGHT_RIGHT,+            Maneuver.TURN_SHARP_RIGHT to ManeuverGlyph.TURN_SHARP_RIGHT,+            Maneuver.UTURN_RIGHT to ManeuverGlyph.UTURN_RIGHT,+            Maneuver.TURN_RIGHT to ManeuverGlyph.TURN_RIGHT,+            Maneuver.STRAIGHT to ManeuverGlyph.STRAIGHT,+            Maneuver.RAMP_LEFT to ManeuverGlyph.RAMP_LEFT,+            Maneuver.RAMP_RIGHT to ManeuverGlyph.RAMP_RIGHT,+            Maneuver.MERGE to ManeuverGlyph.MERGE,+            Maneuver.FORK_LEFT to ManeuverGlyph.FORK_LEFT,+            Maneuver.FORK_RIGHT to ManeuverGlyph.FORK_RIGHT,+            Maneuver.ROUNDABOUT_LEFT to ManeuverGlyph.ROUNDABOUT_LEFT,+            Maneuver.ROUNDABOUT_RIGHT to ManeuverGlyph.ROUNDABOUT_RIGHT,+            Maneuver.DEPART to ManeuverGlyph.STRAIGHT,+            Maneuver.NAME_CHANGE to ManeuverGlyph.STRAIGHT,+            Maneuver.WAIT to ManeuverGlyph.CLOCK,+            Maneuver.RIDE to ManeuverGlyph.BOOK,+            Maneuver.FERRY to null,+            Maneuver.FERRY_TRAIN to null,+            Maneuver.MANEUVER_UNSPECIFIED to null,+        )+        // Exhaustive over the enum: a maneuver the router adds later fails here until it gets+        // a row, rather than drawing nothing on device.+        assertEquals(+            Maneuver.entries.size,+            expected.size,+            "the table must cover every Maneuver",+        )+        for ((maneuver, glyph) in expected) {+            assertEquals(glyph, maneuver.glyph(), "$maneuver maps to $glyph")+        }+    }++    @Test+    fun left_and_right_uturns_are_distinct_glyphs() {+        // The reported bug, stated directly: both U-turns mapped to one glyph and every right+        // U-turn drew a left hook. The router distinguishes them; the icon table must too.+        val left = Maneuver.UTURN_LEFT.glyph()+        val right = Maneuver.UTURN_RIGHT.glyph()+        assertEquals(ManeuverGlyph.UTURN_LEFT, left)+        assertEquals(ManeuverGlyph.UTURN_RIGHT, right)+    }++    @Test+    fun every_covered_lane_combination_selects_its_combined_glyph() {+        val expected = mapOf(+            listOf(Maneuver.STRAIGHT, Maneuver.TURN_LEFT) to LaneComboGlyph.THROUGH_LEFT,+            listOf(Maneuver.STRAIGHT, Maneuver.TURN_RIGHT) to LaneComboGlyph.THROUGH_RIGHT,+            listOf(Maneuver.STRAIGHT, Maneuver.TURN_SLIGHT_LEFT) to+                LaneComboGlyph.THROUGH_SLIGHT_LEFT,+            listOf(Maneuver.STRAIGHT, Maneuver.TURN_SLIGHT_RIGHT) to+                LaneComboGlyph.THROUGH_SLIGHT_RIGHT,+            listOf(Maneuver.STRAIGHT, Maneuver.TURN_LEFT, Maneuver.TURN_RIGHT) to+                LaneComboGlyph.THROUGH_LEFT_RIGHT,+            listOf(Maneuver.TURN_LEFT, Maneuver.TURN_RIGHT) to LaneComboGlyph.LEFT_RIGHT,+        )+        for ((directions, glyph) in expected) {+            assertEquals(glyph, laneComboGlyph(directions), "$directions selects $glyph")+            // Order-insensitive: OSM lists a lane's movements in any order.+            assertEquals(glyph, laneComboGlyph(directions.reversed()), "$directions reversed")+        }+    }++    @Test+    fun uncovered_combinations_fall_back_to_a_single_arrow_explicitly() {+        // A single movement is not a combination.+        assertNull(laneComboGlyph(listOf(Maneuver.STRAIGHT)))+        assertNull(laneComboGlyph(listOf(Maneuver.TURN_LEFT)))+        // Covered movements in an uncovered arrangement: through + through is nonsense, and+        // sharp turns have no combined glyph — both must say so rather than pick a wrong one.+        assertNull(laneComboGlyph(listOf(Maneuver.STRAIGHT, Maneuver.STRAIGHT)))+        assertNull(+            laneComboGlyph(listOf(Maneuver.STRAIGHT, Maneuver.TURN_SHARP_LEFT)),+            "sharp turns have no combined glyph",+        )+        assertNull(+            laneComboGlyph(listOf(Maneuver.UTURN_LEFT, Maneuver.UTURN_RIGHT)),+            "U-turns have no combined glyph",+        )+    }+}
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsindex 59b16cff04..c58604d007 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -2110,6 +2110,54 @@ mod tests {         assert!(seen, "at least one archived road tile carries the turn masks");     } +    /// **The junction layer's coalesce opt-out, through the full tiler.** Every+    /// connector shares one class (no kind, no detail), so coalescing would+    /// chain unrelated movements — a left turn and the through beside it — into+    /// one polyline and draw a ribbon between them. This pushes two touching+    /// connectors and asserts each survives as its own feature, mirroring+    /// `a_traffic_layer_keeps_one_id_per_segment_through_the_tiler` for the+    /// traffic layer's neighbouring opt-out.+    #[test]+    fn a_junction_layer_keeps_one_connector_per_feature_through_the_tiler() {+        use crate::schema::junction::junction_class;+        // Two connectors meeting end to start at the junction mouth: exactly+        // the shape a join would splice, and the shape a left turn beside a+        // through movement takes.+        let connector = |x0: f64, x1: f64| Feature {+            class: junction_class(),+            geometry: Geometry::Lines(vec![vec![(x0, 35.0), (x1, 35.0004)]]),+            name: None,+            id: tilecodec::mamaps::body::ID_NONE,+            transit_color: 0,+            transit_ordinal: 0,+            transit_lanes: 0,+            transit_taper: 0,+            lane_count: 0,+            turn_fwd: Vec::new(),+            turn_bwd: Vec::new(),+            building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),+        };+        let features =+            vec![connector(-120.0, -119.9996), connector(-119.9996, -119.9992)];+        let (bytes, _) = build(&spilled(&features), &settings(14, 14)).expect("build");+        let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");+        let mut total = 0usize;+        for (_, _, body) in &entries {+            let body = Body::parse(body).expect("parse");+            let Some(layer) = body.layer(dict::LAYER_JUNCTION) else { continue };+            for feature in &layer.features {+                assert_eq!(feature.geom_type, GEOM_LINE);+                total += 1;+            }+        }+        assert_eq!(+            total, 2,+            "coalescing chained the two connectors into one feature: \+             delete the LAYER_JUNCTION opt-out in encode_batch and this fails",+        );+    }+     /// **The traffic layer's one-id-per-segment invariant, through the full tiler.** Traffic     /// features share a class (no kind, no detail), so if the layer were coalesced like every     /// other line layer they would collapse into one feature and every segment's `component_id`