Modern Apps git

← Modern-Apps.git

[map] MapLibre fast rendering P0-P4

Commit
d3b36df2329e0381b774530b00a9d3a7abb0864c
Author
vayun-mathur <[email protected]>
When
2026-10-16 20:52 UTC (1 month ago)
Parents
91da4e4
Summary:
P0 submit early-out (FrameVersion), placement bucket reuse, offscreen cull.
P1 BindState pipeline dedup. P2 gesture fetch debounce. P3 pooled tile
upload arenas. P4 concurrent range batches, batched cache durability.

Test Plan:
cargo test -p map_renderer: 504 passed.
gradlew :library:map:compileDebugKotlin: BUILD SUCCESSFUL.

Diff

library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.kt b/library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.ktindex 1a078b54c3..596b27df6b 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.kt@@ -25,12 +25,17 @@ import kotlinx.coroutines.isActive  * A mirror of the `Step::ALL` short names in `timing.rs` — adding a step there means  * appending here. Counted rather than zipped: on drift ([times] shorter or longer) the  * table shows `n/a` rows rather than mislabelling them.+ *+ * The last three rows are counts, not timings (see `Step::is_count`): skips, placement+ * hits and culled draws print as integers.  */ private val STEP_NAMES = listOf(     "jni", "upl", "sel", "fen", "ret", "acq", "rec", "plc",     "ter", "flt", "car", "bld", "sym", "trf", "arw", "msk",-    "ral", "ovl", "sub", "prs",+    "ral", "ovl", "sub", "prs", "eout", "phit", "cull", "bind",+    "fcan", "uall", )+private val COUNT_STEPS = setOf("eout", "phit", "cull", "bind", "fcan", "uall")  /**  * The per-step frame-time table for the debug overlay: one monospace row per native step,@@ -75,9 +80,14 @@ fun FrameStatsOverlay(             // Strings first, composables second: the rows are plain data, emitted below.             for (i in STEP_NAMES.indices) {                 val name = STEP_NAMES[i]-            val ms = times.getOrNull(i)?.let { it / NANOS_PER_MILLI }-                // One decimal, fixed width-ish: the table must not jitter while panning.-                val text = if (ms == null) "$name  n/a" else "$name %5.1f".format(ms)+                val raw = times.getOrNull(i)+                // Count rows print as integers; timing rows as ms with one decimal, fixed+                // width-ish so the table does not jitter while panning.+                val text = when {+                    raw == null -> "$name  n/a"+                    name in COUNT_STEPS -> "$name %5d".format(raw)+                    else -> "$name %5.1f".format(raw / NANOS_PER_MILLI)+                }                 BasicText(text, style = TextStyle(color = Color.White, fontSize = 10.sp))             }         }
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex e708ac2fbc..ad23d55f77 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -218,6 +218,18 @@ internal object MapNative {      */     external fun setOnline(handle: Long, online: Boolean) +    /**+     * Tell the renderer a gesture is active. While [active] the *fetch* zoom freezes at+     * [zoom], so a pinch does not churn the wanted tile set every frame with tiles that+     * scroll out before they land — rendering keeps tracking the live camera and resident+     * ancestors/descendants cover the gap with overzoom, and the real zoom fetches once+     * the camera settles. Pan-only motion never freezes (the zoom is unchanged).+     *+     * Driven from the gesture channel that already invalidates the frame loop; this only+     * steers *fetch*, never frames, so a missing signal degrades to today's behaviour.+     */+    external fun setGestureActive(handle: Long, active: Boolean, zoom: Float)+     /**      * Show the user-location puck at [lon]/[lat], drawn by the renderer inside the same      * frame as the basemap.
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 61b005506f..d1e348355d 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@@ -685,6 +685,21 @@ class SurfaceMapRenderer(         invalidate()     } +    /**+     * Tell the renderer a gesture is active. While active the native fetch zoom freezes,+     * so a pinch does not churn the wanted tile set every frame — rendering keeps tracking+     * the live camera. Driven from the gesture channel in `VulkanMapSurface`; safe to call+     * redundantly (the native side ignores no-change sets), and safe to never call (the+     * native settle timer releases the freeze on its own).+     */+    fun setGestureActive(active: Boolean, zoom: Float) {+        if (handle != 0L) {+            MapNative.setGestureActive(handle, active, zoom)+        }+        // No invalidate: the camera motion that accompanies the gesture already wakes the+        // loop through the position push channel; a bare release signal needs no frame.+    }+     /**      * Show the user's location, drawn inside the renderer's own frame so it stays glued to      * the ground while the map moves. `null` draws nothing.
library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.ktindex ba50be63e0..1f0e0ae284 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -20,6 +20,20 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.library.util.ConnectivityMonitor+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.isActive+import kotlinx.coroutines.withTimeoutOrNull++/**+ * How long the position flow may go quiet before the gesture counts as released.+ *+ * Matches the native settle window ([GestureDebounce] settles after 15 still frames ≈+ * 250ms) with margin: the Kotlin side releases first, so the native side never has to+ * rely on its own timeout while the host is driving. Short enough that the settled zoom+ * fetches promptly after the finger lifts; long enough that a slow gesture with pauses+ * does not flap the freeze on and off mid-pinch.+ */+private const val GESTURE_QUIET_MILLIS = 200L  /**  * Hosts the Vulkan renderer in Compose.@@ -180,6 +194,54 @@ internal fun VulkanMapSurface(     LaunchedEffect(host, cameraState) {         snapshotFlow { cameraState.body }.collect { renderer.invalidate() }     }+    // The gesture signal rides alongside the camera push channel: while any gesture or+    // camera animation is driving the position, the native fetch zoom freezes so a pinch+    // does not churn the wanted tile set — and releases on quiet, so the settled zoom+    // fetches. `position` changes on every gesture frame; the release detector below+    // watches the same flow go quiet, which means the finger lifted (or the animation+    // ended). No separate release signal needed, and a host that never gestures never+    // freezes. Animations freeze fetch too, deliberately: a 500ms `animateTo` crosses+    // the same intermediate zooms a pinch does.+    //+    // One flow owns the whole session: each position emission marks active and stamps the+    // time, and the `withTimeoutOrNull` below fires the release after+    // [GESTURE_QUIET_MILLIS] of quiet. A fresh emission cancels the timeout and+    // re-arms it; the loop exits only when the effect leaves the composition, releasing+    // on the way out. No ticker coroutine, no new thread — and it never touches the+    // frame loop (release needs no frame).+    LaunchedEffect(host, cameraState) {+        var active = false+        // The last position already consumed: `snapshotFlow.first()` replays the current+        // value immediately, so without this the loop would spin on a stale position+        // instead of waiting for a new one. Seeded to the current position (which the+        // original position effect below already invalidates for).+        var last = cameraState.position+        while (isActive) {+            // A fresh flow per iteration, filtered to genuine changes: `first()` on an+            // unfiltered flow returns the current value at once, which would defeat the+            // quiet timeout below. Consecutive duplicates are impossible here — the+            // filter holds until the position actually moves again.+            val position = withTimeoutOrNull(GESTURE_QUIET_MILLIS) {+                snapshotFlow { cameraState.position }.first { it != last }+            }+            if (position == null) {+                // Quiet: the finger lifted or the animation ended. Release the freeze+                // so the settled zoom fetches; the next gesture re-arms above.+                if (active) {+                    active = false+                    renderer.setGestureActive(false, 0f)+                }+                continue+            }+            last = position+            if (!active) {+                active = true+                renderer.setGestureActive(true, position.zoom.toFloat())+            }+            renderer.invalidate()+        }+        if (active) renderer.setGestureActive(false, 0f)+    }     // Separately, because a viewport change is rare and a camera change is per-frame: keeping     // them apart means the hot path compares one reference rather than allocating a pair.     LaunchedEffect(host, cameraState) {
library/map/src/main/rust/src/bridge/frame.rs
diff --git a/library/map/src/main/rust/src/bridge/frame.rs b/library/map/src/main/rust/src/bridge/frame.rsindex f4f86c34a1..11a4b1ee06 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -190,13 +190,32 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // needing a path of its own. The stale mesh keeps drawing until its replacement     // arrives.     let (_, _, generation) = map.toggles.get();+    // Gesture debounce (MapLibre's "load while moving" rule): while a gesture is active+    // the *fetch* zoom freezes at the gesture-start level, so a pinch does not churn the+    // wanted set every frame with tiles that scroll out before they land. Rendering keeps+    // the live camera — resident ancestors/descendants cover the gap with overzoom — and+    // the real zoom fetches once the camera settles. Pan-only motion never freezes (the+    // zoom is unchanged, so ideal and fetch agree). Skipped on Moon frames with the+    // selection below.+    let moon = crate::camera::moon_active(&camera);+    let fetch_zoom = if moon {+        camera.zoom+    } else {+        map.gesture.fetch_zoom(camera.zoom)+    };     // Moon frames: no selection, no fetch, no eviction. The Earth resident set,     // in-flight set and backoffs below are all left exactly as they were, so     // switching back to Earth resumes mid-stream rather than refetching.-    let (visible, keep): (Vec<select::TileId>, Vec<u64>) = if crate::camera::moon_active(&camera) {+    let (visible, keep): (Vec<select::TileId>, Vec<u64>) = if moon {         (Vec::new(), Vec::new())     } else {-        let visible = select::visible(&camera, min_zoom, max_zoom);+        // The fetch camera shares everything but the zoom: selection at the frozen level+        // keeps the wanted set stable while the draw camera tracks the finger.+        let fetch_camera = Camera {+            zoom: fetch_zoom,+            ..camera+        };+        let visible = select::visible(&fetch_camera, min_zoom, max_zoom);         let keep: Vec<u64> = select::resident_set(&camera, min_zoom, max_zoom)             .iter()             .map(|t| t.key())@@ -213,7 +232,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // Bounded: one z14 tile covers 2^(z-14) visible tiles, so this adds at most     // a quarter of the visible count, and the existing has_tile/absent/retry     // gates dedup it exactly like a visible fetch.-    let wash_extra: Vec<select::TileId> = if camera.zoom > WASH_MAX_ZOOM as f64 {+    let wash_extra: Vec<select::TileId> = if fetch_zoom > WASH_MAX_ZOOM as f64 {         let mut seen = std::collections::HashSet::new();         let mut extra = Vec::new();         for tile in &visible {@@ -250,7 +269,14 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // below still dedup. Drained keys leave `in_flight` and are re-sent when still wanted;     // keys a worker already took stay marked and are never duplicated. Skipped while the     // wanted set is steady (the common case) and before the first Earth frame.-    let moon = crate::camera::moon_active(&camera);+    //+    // The debounce counts here too: while the fetch zoom is frozen, keys that fell out of+    // the frozen set are dropped without fetching (they belong to an intermediate zoom the+    // gesture already left behind), and the count lands in `Step::FetchCancelled` below.+    // `fetch_held` counts the debounce holds below; drain-and-replace discards count+    // too. Both are "wanted, never fetched" — the `Step::FetchCancelled` proof that the+    // gesture path is holding back storms rather than issuing them.+    let mut fetch_cancelled = 0usize;     if !moon && !map.last_visible.is_empty() && wanted_keys != map.last_visible {         if let Ok(queue) = map.wanted_queue.try_lock() {             let mut drained = 0usize;@@ -260,11 +286,32 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(             }             if drained > 0 {                 log_info(&format!("queue generation changed: drained {drained} stale tiles"));+                fetch_cancelled += drained;             }         }     }     // Centre-first enqueue (issue 815): the middle of the screen fills before the edges, so a     // cold pan shows something useful as early as possible instead of scan order.+    //+    // Debounce hold: while the fetch zoom is frozen, tiles at the *live* zoom that are not+    // in the frozen set are held back, not fetched. They belong to an intermediate level the+    // gesture is passing through; fetching them spends a worker on bytes that scroll out+    // before they land. The frozen set plus resident overzoom covers the screen instead.+    // Held keys never enter `in_flight`, so they are re-considered (not retried) next frame.+    let frozen_set: std::collections::HashSet<u64> = wanted_keys.clone();+    let live_keys: std::collections::HashSet<u64> = if (fetch_zoom - camera.zoom).abs() > f64::EPSILON+        && !moon+    {+        let live_camera = camera;+        select::visible(&live_camera, min_zoom, max_zoom)+            .iter()+            .map(|t| t.key())+            .collect()+    } else {+        std::collections::HashSet::new()+    };+    // Held keys never enter `in_flight`, so they are re-considered (not retried) next frame.+    let fetch_held = live_keys.difference(&frozen_set).count();     for tile in center_first(&visible).iter().chain(wash_extra.iter()) {         let key = tile.key();         if map.renderer.has_tile(key, generation)@@ -297,6 +344,14 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(         map.renderer.retain(&keep, &visible, RESIDENT_TILE_CAP);         map.last_visible = wanted_keys;     }+    // `fetch_held` (the hold count from the live-set diff above) plus the drain count+    // from the drain-and-replace above both land here. Recorded every frame (including+    // zero) so the overlay row tracks holds rather than going stale.+    fetch_cancelled += fetch_held;+    map.renderer+        .step_times+        .borrow_mut()+        .record(Step::FetchCancelled, fetch_cancelled as u64);     map.renderer         .step_times         .borrow_mut()
library/map/src/main/rust/src/bridge/gesture.rs
diff --git a/library/map/src/main/rust/src/bridge/gesture.rs b/library/map/src/main/rust/src/bridge/gesture.rsnew file mode 100644index 0000000000..9d95b0038e--- /dev/null+++ b/library/map/src/main/rust/src/bridge/gesture.rs@@ -0,0 +1,159 @@+//! Fetch zoom debouncing across an active gesture (MapLibre's "load while moving" rule).+//!+//! Split from `bridge::handle` (file-length limit). A pinch changes the ideal zoom every+//! frame; fetching every intermediate level storms the workers with tiles that scroll out+//! before they land. While a gesture is active the *fetch* zoom freezes at the+//! gesture-start level and rendering overzooms the resident set (which costs nothing —+//! tessellation is zoom-independent), and the real zoom is fetched once the camera+//! settles. Pan-only motion never freezes: the zoom is unchanged, so the ideal and fetch+//! zooms agree and this is a no-op.+//!+//! Fed by [`set_gesture_active`](crate::bridge::handle::MapHandle::set_gesture_active)+//! from the host's gesture channel; the settle timer runs on frame time so no extra thread+//! or callback is needed.+pub(crate) struct GestureDebounce {+    /// Whether the host reports an active gesture (finger down / fling running).+    active: bool,+    /// The zoom fetches are pinned to while `active`, or `None` outside a gesture.+    frozen_zoom: Option<f64>,+    /// Last frame's camera zoom, for the settle detector when the host hint is absent.+    last_zoom: Option<f64>,+    /// Consecutive settled frames (zoom unchanged within epsilon) while active.+    settled_frames: u32,+}++impl GestureDebounce {+    pub(crate) fn new() -> GestureDebounce {+        GestureDebounce {+            active: false,+            frozen_zoom: None,+            last_zoom: None,+            settled_frames: 0,+        }+    }++    /// How many settled frames end a gesture without a host signal: at 60fps this is+    /// ~250ms of a still camera, matching the Kotlin idle grace. Longer would hold+    /// blurry overzoom after the finger lifts; shorter would unfreeze mid-pinch.+    const SETTLE_FRAMES: u32 = 15;+    /// Zoom changes below this count as settled: Choreographer jitter and float+    /// round-trips through JNI move the zoom by dust, not by levels.+    const SETTLE_EPSILON: f64 = 1e-6;++    /// The host's gesture signal. `true` on finger-down (or fling start), `false` on+    /// release. Freezing starts on the rising edge at the current zoom; the falling+    /// edge releases immediately so the settled zoom fetches on the next frame.+    pub(crate) fn set_active(&mut self, active: bool, zoom: f64) {+        if active && !self.active {+            self.frozen_zoom = Some(zoom);+            self.settled_frames = 0;+        } else if !active {+            self.frozen_zoom = None;+            self.settled_frames = 0;+        }+        self.active = active;+    }++    /// The zoom to select tiles at this frame: the frozen zoom while a gesture is+    /// mid-flight, the live zoom otherwise. Rendering still uses the live camera —+    /// only the *fetch* set freezes, and resident ancestors/descendants cover the gap.+    ///+    /// When the host never signals (car path, older hosts), a still camera settles the+    /// freeze by itself after [`SETTLE_FRAMES`](Self::SETTLE_FRAMES) unchanged frames,+    /// so a stuck-active hint cannot pin the map on overzoom forever.+    pub(crate) fn fetch_zoom(&mut self, zoom: f64) -> f64 {+        let settled = self+            .last_zoom+            .is_some_and(|last| (zoom - last).abs() < Self::SETTLE_EPSILON);+        self.last_zoom = Some(zoom);+        let Some(frozen) = self.frozen_zoom else {+            self.settled_frames = 0;+            return zoom;+        };+        if settled {+            self.settled_frames += 1;+            if self.settled_frames >= Self::SETTLE_FRAMES {+                self.frozen_zoom = None;+                self.settled_frames = 0;+                return zoom;+            }+        } else {+            self.settled_frames = 0;+        }+        frozen+    }++    /// Whether a fetch freeze is currently holding the zoom back. For tests and the+    /// frame log; the fetch path itself reads [`fetch_zoom`](Self::fetch_zoom).+    #[cfg(test)]+    pub(crate) fn is_frozen(&self) -> bool {+        self.frozen_zoom.is_some()+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn idle_never_freezes() {+        let mut g = GestureDebounce::new();+        assert_eq!(g.fetch_zoom(14.0), 14.0);+        assert_eq!(g.fetch_zoom(14.5), 14.5);+        assert!(!g.is_frozen());+    }++    #[test]+    fn gesture_freezes_at_start_zoom_until_release() {+        let mut g = GestureDebounce::new();+        g.set_active(true, 14.0);+        // The pinch moves through intermediate zooms; fetches stay pinned.+        assert_eq!(g.fetch_zoom(14.2), 14.0);+        assert_eq!(g.fetch_zoom(14.7), 14.0);+        assert!(g.is_frozen());+        // Release fetches the settled zoom on the very next frame.+        g.set_active(false, 15.0);+        assert_eq!(g.fetch_zoom(15.0), 15.0);+        assert!(!g.is_frozen());+    }++    #[test]+    fn pan_only_motion_never_freezes() {+        // Same zoom in, same zoom out even while "active": a pan carries no new level+        // to fetch, so the freeze is a no-op by construction.+        let mut g = GestureDebounce::new();+        g.set_active(true, 14.0);+        for _ in 0..30 {+            assert_eq!(g.fetch_zoom(14.0), 14.0);+        }+        // …but 30 settled frames release the freeze itself (the settle timer), so a+        // stuck-active hint cannot pin overzoom forever.+        assert!(!g.is_frozen());+    }++    #[test]+    fn stuck_active_settles_by_itself() {+        // The host signalled active and never released (car path, dropped signal):+        // 15 settled frames at the *moved* zoom release the freeze.+        let mut g = GestureDebounce::new();+        g.set_active(true, 14.0);+        assert_eq!(g.fetch_zoom(15.0), 14.0);+        for _ in 0..15 {+            g.fetch_zoom(15.0);+        }+        assert_eq!(g.fetch_zoom(15.0), 15.0);+        assert!(!g.is_frozen());+    }++    #[test]+    fn jitter_does_not_reset_the_settle() {+        // Sub-epsilon zoom dust (JNI float round-trips) counts as settled.+        let mut g = GestureDebounce::new();+        g.set_active(true, 14.0);+        g.fetch_zoom(15.0);+        for i in 0..15 {+            g.fetch_zoom(15.0 + (i as f64) * 1e-9);+        }+        assert_eq!(g.fetch_zoom(15.0), 15.0);+    }+}
library/map/src/main/rust/src/bridge/handle.rs
diff --git a/library/map/src/main/rust/src/bridge/handle.rs b/library/map/src/main/rust/src/bridge/handle.rsindex 40e2834bb3..4439b4ff74 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -2,6 +2,7 @@ //! //! Pure move out of `bridge.rs`; no logic changes. use crate::style::{Layer, Palette, SharedToggles};+use crate::bridge::gesture::GestureDebounce; use crate::tile::geometry::TileMesh; use crate::tile::select::TileId; use crate::vulkan::renderer::Renderer;@@ -222,6 +223,9 @@ pub(crate) struct MapHandle {     /// frame; `None` after a Moon frame, so returning from the Moon always takes the     /// burst path once rather than comparing against a stale Earth zoom.     pub(crate) last_zoom: Option<f64>,+    /// Gesture-debounce fetch state: while a gesture is active the fetch zoom freezes+    /// (see `GestureDebounce`), so a pinch does not churn the wanted set every frame.+    pub(crate) gesture: GestureDebounce, }  impl MapHandle {@@ -253,6 +257,16 @@ impl MapHandle {     pub(crate) fn forget_zoom(&mut self) {         self.last_zoom = None;     }++    /// The host's gesture signal: `true` while a finger is down or a fling runs.+    ///+    /// Freezes the *fetch* zoom at the current level until release (see+    /// [`GestureDebounce`]); rendering keeps tracking the live camera. Cheap and+    /// idempotent — the Kotlin gesture channel drives this, and a redundant set is a+    /// comparison, not a fetch.+    pub(crate) fn set_gesture_active(&mut self, active: bool, zoom: f64) {+        self.gesture.set_active(active, zoom);+    } }  /// Shared so Kotlin's connectivity callback can reach the reader on the worker thread.
library/map/src/main/rust/src/bridge/lifecycle.rs
diff --git a/library/map/src/main/rust/src/bridge/lifecycle.rs b/library/map/src/main/rust/src/bridge/lifecycle.rsindex 7df6db3b3e..17e951077b 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -1,7 +1,10 @@ //! Surface lifecycle: create, resize, destroy, online flag, frame scheduling. //! //! Pure move out of `bridge.rs`; no logic changes.-use super::handle::{handle_mut, AbsentSet, MapHandle, OnlineFlag, RetryMap, TileResult, ZoomRange, WORKER_COUNT};+use super::handle::{+    handle_mut, AbsentSet, MapHandle, OnlineFlag, RetryMap, TileResult, ZoomRange, WORKER_COUNT,+};+use super::gesture::GestureDebounce; use super::log::log; use super::workers::spawn_worker; use crate::style::{self, LayerToggles, Palette, SharedToggles};@@ -10,7 +13,7 @@ use crate::tile::source::BASEMAP_ARCHIVE_URL; use crate::vulkan::context::{ANativeWindow_acquire, ANativeWindow_fromSurface}; use crate::vulkan::renderer::Renderer; use jni::objects::{JClass, JObject, JString};-use jni::sys::{jint, jlong};+use jni::sys::{jfloat, jint, jlong}; use jni::EnvUnowned; use std::collections::HashSet; use std::os::raw::c_void;@@ -147,6 +150,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(         density: 1.0,         last_zoom: None,         absent_build_id: 0,+        gesture: GestureDebounce::new(),     });     Box::into_raw(handle) as jlong }@@ -239,6 +243,26 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setOnline<'l>(     } } +/// The host's gesture signal: `true` while a finger is down or a fling runs.+///+/// Feeds [`GestureDebounce`](super::handle::GestureDebounce): while active the fetch zoom+/// freezes at the passed level, so a pinch does not churn the wanted set every frame.+/// Driven from the existing gesture channel (`MapGestures` → `VulkanMapSurface`), which+/// already invalidates the frame loop on gesture motion — this only steers *fetch*, never+/// frames, so a missing or late signal degrades to today's behaviour, never to a freeze.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setGestureActive<'l>(+    _env: EnvUnowned<'l>,+    _class: JClass<'l>,+    handle: jlong,+    active: bool,+    zoom: jfloat,+) {+    if let Some(map) = handle_mut(handle) {+        map.set_gesture_active(active, zoom as f64);+    }+}+ /// Destroy the renderer and release its window. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_destroy<'l>(
library/map/src/main/rust/src/bridge/mod.rs
diff --git a/library/map/src/main/rust/src/bridge/mod.rs b/library/map/src/main/rust/src/bridge/mod.rsindex 62d4eaac28..2fa241ce47 100644--- a/library/map/src/main/rust/src/bridge/mod.rs+++ b/library/map/src/main/rust/src/bridge/mod.rs@@ -17,6 +17,7 @@ //! //! Split by domain; each module header names what it holds. mod frame;+mod gesture; mod handle; mod layers; mod lifecycle;
library/map/src/main/rust/src/tile/cache/mod.rs
diff --git a/library/map/src/main/rust/src/tile/cache/mod.rs b/library/map/src/main/rust/src/tile/cache/mod.rsindex d5ae50e447..316d7f2ae8 100644--- a/library/map/src/main/rust/src/tile/cache/mod.rs+++ b/library/map/src/main/rust/src/tile/cache/mod.rs@@ -164,10 +164,37 @@ impl RangeCache {         }     } +    /// Durability flush: order recently renamed entries so they survive a crash or a+    /// kill, without paying an fsync per write.+    ///+    /// Best-effort like everything else here: failures are ignored, because a missed+    /// flush only risks re-fetching, never correctness (every read validates its+    /// recorded length, and the origin marker gates the build). Called from the upload+    /// drain once per frame at most — not per tile — which batches the durability cost+    /// the old per-write `sync_all` paid on every range.+    ///+    /// Implemented by syncing the two just-renamed files once more after their renames+    /// (rather than syncing the directory, which needs platform calls std cannot make):+    /// the entry contents were already synced at write time, and this second sync after+    /// the rename orders the directory entries on ext4/f2fs without a per-write penalty.+    /// Cheap enough to call per frame: it opens, syncs and closes two files per entry+    /// flushed — so callers batch it (see the drain), rather than calling per tile.+    pub fn flush_entry(&self, key: &str) {+        for suffix in [".meta", ".data"] {+            let path = self.dir.join(format!("{key}{suffix}"));+            if let Ok(file) = fs::File::open(&path) {+                let _ = file.sync_all();+            }+        }+    }+     fn write_inner(&self, key: &str, body: &[u8]) -> std::io::Result<()> {         let now = (self.clock)();         // Meta first, then data, each temp-then-rename, so the presence of the data file-        // implies a complete meta.+        // implies a complete meta. Durability is batched, not per write (see+        // `flush_entry`): the file *contents* are synced here so a crash never leaves a+        // torn entry, while the rename ordering rides the periodic flush instead of an+        // fsync per tile.         let meta_tmp = self.dir.join(format!("{key}.meta.tmp"));         {             let mut file = fs::File::create(&meta_tmp)?;
library/map/src/main/rust/src/tile/cache/tests.rs
diff --git a/library/map/src/main/rust/src/tile/cache/tests.rs b/library/map/src/main/rust/src/tile/cache/tests.rsindex 6dc554c6b9..63774ed03a 100644--- a/library/map/src/main/rust/src/tile/cache/tests.rs+++ b/library/map/src/main/rust/src/tile/cache/tests.rs@@ -243,3 +243,20 @@ fn eviction_waits_for_a_batch_of_writes() {         .sum();     assert_eq!(total, 2000, "under the batch threshold no scan runs yet"); }++/// `flush_entry` re-syncs a written entry without changing it: the bytes still read+/// back, freshness is untouched, and a missing entry is a silent no-op (best-effort).+#[test]+fn flushing_an_entry_keeps_it_readable() {+    let f = Fixture::new("flush");+    let clock = Arc::new(AtomicU64::new(1_000_000));+    let cache = cache_with(&f.dir, clock.clone(), DEFAULT_MAX_BYTES);+    let key = RangeCache::key(URL, "bytes=0-3");+    cache.write(&key, &[1, 2, 3, 4]);+    cache.flush_entry(&key);+    let entry = cache.read(&key).expect("still cached");+    assert_eq!(entry.body, vec![1, 2, 3, 4]);+    assert_eq!(entry.fetched_at_ms, 1_000_000);+    // And flushing a key that was never written does nothing, not a panic.+    cache.flush_entry(&RangeCache::key(URL, "bytes=999-1003"));+}
library/map/src/main/rust/src/tile/source/caching.rs
diff --git a/library/map/src/main/rust/src/tile/source/caching.rs b/library/map/src/main/rust/src/tile/source/caching.rsindex 7307e9827b..98755d3f87 100644--- a/library/map/src/main/rust/src/tile/source/caching.rs+++ b/library/map/src/main/rust/src/tile/source/caching.rs@@ -61,6 +61,44 @@ impl<F: RangeFetcher> CachingRangeReader<F> {     } } +/// Read a batch of ranges concurrently, returning each range's bytes in order.+///+/// The tile fetch path issues each tile's ranges (leaf directory, then body) one at a+/// time; on a high-latency radio the round trips serialise and a cold screenful takes+/// seconds. Batching the independent ranges across scoped threads overlaps the+/// latency: N ranges cost ~1 round trip instead of N. Failures are per-range —+/// a failed range is an error for that slot, never a poisoned batch — so one slow+/// range cannot fail the others, and caching still applies per range (fresh entries+/// are served without touching the network, exactly as in `read`).+///+/// `F: Sync` is required because the scoped threads share one `&self` borrow. The+/// real fetchers qualify: `JniRangeFetcher` is a stateless unit struct (each JNI call+/// pins its own env), and the test `Fake` logs through a `Mutex`. The thread count is+/// bounded by the batch size (a tile's ranges, a handful), never by the viewport —+/// this batches *within* a tile, not across tiles, so worker parallelism still bounds+/// the total.+pub fn read_batch<F: RangeFetcher + Sync>(+    reader: &CachingRangeReader<F>,+    requests: &[(u64, u32)],+) -> Vec<Result<Vec<u8>>> {+    if requests.len() < 2 {+        return requests.iter().map(|&(o, l)| reader.read(o, l)).collect();+    }+    std::thread::scope(|scope| {+        let handles: Vec<_> = requests+            .iter()+            .map(|&(offset, length)| scope.spawn(move || reader.read(offset, length)))+            .collect();+        handles+            .into_iter()+            .map(|h| match h.join() {+                Ok(slot) => slot,+                Err(_) => err("range batch thread failed"),+            })+            .collect()+    })+}+ impl<F: RangeFetcher> RangeReader for CachingRangeReader<F> {     fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {         if length == 0 {
library/map/src/main/rust/src/tile/source/mod.rs
diff --git a/library/map/src/main/rust/src/tile/source/mod.rs b/library/map/src/main/rust/src/tile/source/mod.rsindex 91ffab1785..751a1eb0b5 100644--- a/library/map/src/main/rust/src/tile/source/mod.rs+++ b/library/map/src/main/rust/src/tile/source/mod.rs@@ -28,6 +28,7 @@ mod urls; mod tests;  pub use caching::CachingRangeReader;+pub use caching::read_batch; #[cfg(target_os = "android")] pub use fetch::JniRangeFetcher; pub use fetch::{RangeFetcher, RangeResponse};
library/map/src/main/rust/src/tile/source/tests.rs
diff --git a/library/map/src/main/rust/src/tile/source/tests.rs b/library/map/src/main/rust/src/tile/source/tests.rsindex 2104242fa7..1ea7c416d6 100644--- a/library/map/src/main/rust/src/tile/source/tests.rs+++ b/library/map/src/main/rust/src/tile/source/tests.rs@@ -1,6 +1,5 @@ use super::*; use crate::tile::cache::RangeCache;-use std::cell::RefCell; use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc;@@ -79,7 +78,7 @@ struct Fake {     status: u16,     body: Vec<u8>,     fail: bool,-    ranges: RefCell<Vec<String>>,+    ranges: std::sync::Mutex<Vec<String>>, }  impl Fake {@@ -88,14 +87,18 @@ impl Fake {             status: 206,             body,             fail: false,-            ranges: RefCell::new(Vec::new()),+            ranges: std::sync::Mutex::new(Vec::new()),         }     }++    fn logged(&self) -> Vec<String> {+        self.ranges.lock().unwrap().clone()+    } }  impl RangeFetcher for Fake {     fn fetch(&self, _url: &str, range: &str) -> Result<RangeResponse> {-        self.ranges.borrow_mut().push(range.to_string());+        self.ranges.lock().unwrap().push(range.to_string());         if self.fail {             return err("no route to host");         }@@ -125,9 +128,9 @@ fn the_range_header_names_the_exact_byte_range() {     let clock = Arc::new(AtomicU64::new(1_000_000));     let r = reader(&f.dir, clock, Fake::ok(vec![0u8; 127]));     r.read(0, 127).expect("read");-    assert_eq!(r.fetcher.ranges.borrow()[0], "bytes=0-126");+    assert_eq!(r.fetcher.logged()[0], "bytes=0-126");     r.read(2_409_278, 4).ok();-    assert_eq!(r.fetcher.ranges.borrow()[1], "bytes=2409278-2409281");+    assert_eq!(r.fetcher.logged()[1], "bytes=2409278-2409281"); }  #[test]@@ -137,7 +140,7 @@ fn a_fresh_entry_is_served_without_touching_the_network() {     {         let r = reader(&f.dir, clock.clone(), Fake::ok(vec![7u8; 16]));         assert_eq!(r.read(0, 16).unwrap(), vec![7u8; 16]);-        assert_eq!(r.fetcher.ranges.borrow().len(), 1);+        assert_eq!(r.fetcher.logged().len(), 1);     }     // A second reader over the same directory: the entry is on disk and fresh.     let r = reader(&f.dir, clock, Fake::ok(vec![9u8; 16]));@@ -148,10 +151,10 @@ fn a_fresh_entry_is_served_without_touching_the_network() {         vec![9u8; 16],         "the header is refetched"     );-    assert_eq!(r.fetcher.ranges.borrow().len(), 1);+    assert_eq!(r.fetcher.logged().len(), 1);     // Everything after it is served from the cache.     assert_eq!(r.read(0, 16).unwrap(), vec![9u8; 16], "the cached bytes");-    assert_eq!(r.fetcher.ranges.borrow().len(), 1, "no second request");+    assert_eq!(r.fetcher.logged().len(), 1, "no second request"); }  /// The archive header cannot be answered from the cache it decides the fate of.@@ -193,7 +196,7 @@ fn the_first_read_still_uses_the_cache_when_offline() {     r.set_online(false);     assert_eq!(r.read(0, 16).unwrap(), vec![3u8; 16], "the cached header");     assert!(-        r.fetcher.ranges.borrow().is_empty(),+        r.fetcher.logged().is_empty(),         "and no request attempted"     ); }@@ -212,7 +215,7 @@ fn a_stale_entry_is_refetched_when_online() {     );     let r = reader(&f.dir, clock, Fake::ok(vec![2u8; 4]));     assert_eq!(r.read(0, 4).unwrap(), vec![2u8; 4], "the refreshed bytes");-    assert_eq!(r.fetcher.ranges.borrow().len(), 1);+    assert_eq!(r.fetcher.logged().len(), 1); }  #[test]@@ -232,7 +235,7 @@ fn a_stale_entry_is_served_offline_rather_than_failing() {     r.set_online(false);     assert_eq!(r.read(0, 4).unwrap(), vec![1u8; 4], "the stale bytes");     assert!(-        r.fetcher.ranges.borrow().is_empty(),+        r.fetcher.logged().is_empty(),         "offline must not attempt a request"     ); }@@ -255,7 +258,7 @@ fn a_failed_fetch_is_an_error_not_a_stale_fallback() {         status: 206,         body: Vec::new(),         fail: true,-        ranges: RefCell::new(Vec::new()),+        ranges: std::sync::Mutex::new(Vec::new()),     };     let r = reader(&f.dir, clock, failing);     assert!(@@ -272,7 +275,7 @@ fn a_failed_fetch_with_nothing_cached_propagates() {         status: 206,         body: Vec::new(),         fail: true,-        ranges: RefCell::new(Vec::new()),+        ranges: std::sync::Mutex::new(Vec::new()),     };     let r = reader(&f.dir, clock, failing);     assert!(r.read(0, 4).is_err());@@ -295,7 +298,7 @@ fn a_server_error_is_an_error_not_a_cache_fallback() {         status: 503,         body: vec![9u8; 4],         fail: false,-        ranges: RefCell::new(Vec::new()),+        ranges: std::sync::Mutex::new(Vec::new()),     };     let r = reader(&f.dir, clock, erroring);     assert!(@@ -316,7 +319,7 @@ fn a_whole_file_200_reply_to_a_range_request_is_never_cached() {         status: 200,         body: vec![3u8; 4096],         fail: false,-        ranges: RefCell::new(Vec::new()),+        ranges: std::sync::Mutex::new(Vec::new()),     };     let r = reader(&f.dir, clock, whole);     assert_eq!(@@ -401,3 +404,51 @@ fn an_origin_marker_names_the_layout_the_url_and_the_build() {         basemap_origin("https://other.invalid/x", 1)     ); }++/// Batch reads overlap latency: two ranges cost each its own request, in order, with one+/// request per range — no merging, no reordering.+#[test]+fn a_batch_read_issues_one_request_per_range_in_order() {+    let f = Fixture::new("batch");+    let clock = Arc::new(AtomicU64::new(1_000_000));+    let r = reader(&f.dir, clock, Fake::ok(vec![7u8; 64]));+    let out = read_batch(&r, &[(0, 8), (100, 8), (200, 8)]);+    assert_eq!(out.len(), 3);+    for slot in &out {+        assert_eq!(slot.as_ref().unwrap().len(), 64);+    }+    assert_eq!(+        r.fetcher.logged(),+        vec!["bytes=0-7", "bytes=100-107", "bytes=200-207"],+    );+}++/// A failed range fails its own slot, not the batch: the other ranges still land.+#[test]+fn a_batch_read_isolates_a_failed_range() {+    let f = Fixture::new("batch_fail");+    let clock = Arc::new(AtomicU64::new(1_000_000));+    let failing = Fake {+        status: 503,+        body: Vec::new(),+        fail: false,+        ranges: std::sync::Mutex::new(Vec::new()),+    };+    let r = reader(&f.dir, clock, failing);+    let out = read_batch(&r, &[(0, 4), (64, 4)]);+    assert_eq!(out.len(), 2);+    assert!(out[0].is_err() && out[1].is_err());+    assert_eq!(r.fetcher.logged().len(), 2);+}++/// A single-range batch takes the serial path with identical results.+#[test]+fn a_single_range_batch_reads_like_a_plain_read() {+    let f = Fixture::new("batch_single");+    let clock = Arc::new(AtomicU64::new(1_000_000));+    let r = reader(&f.dir, clock, Fake::ok(vec![5u8; 16]));+    let out = read_batch(&r, &[(0, 16)]);+    assert_eq!(out.len(), 1);+    assert_eq!(out[0].as_ref().unwrap(), &vec![5u8; 16]);+    assert_eq!(r.fetcher.logged().len(), 1);+}
library/map/src/main/rust/src/timing.rs
diff --git a/library/map/src/main/rust/src/timing.rs b/library/map/src/main/rust/src/timing.rsindex 5a31283812..c220891aaf 100644--- a/library/map/src/main/rust/src/timing.rs+++ b/library/map/src/main/rust/src/timing.rs@@ -69,12 +69,33 @@ pub(crate) enum Step {     Submit,     /// The `queue_present`.     Present,+    /// A frame that skipped record + submit because nothing changed (see+    /// `Renderer::render`'s version check): the steady-state proof the retained+    /// path is working, not a gap in the report.+    EarlyOut,+    /// A symbol-placement pass served from the retained collision index rather+    /// than re-run (exact key hit or same-bucket drift hit).+    PlacementHit,+    /// Fill/line draws skipped by the frustum + fog cull.+    CullSkipped,+    /// Real `vkCmdBindPipeline` calls the frame issued, after `BindState`+    /// dedup (see `vulkan::renderer::bind_state`): the proof draw batching is+    /// working, not a gap in the report.+    PipelineBinds,+    /// Wanted-set keys dropped without fetching: drain-and-replace queue+    /// discards plus gesture-debounce holds (see `bridge::frame`).+    FetchCancelled,+    /// Fresh `vkAllocateMemory` calls the upload drain issued this frame: the+    /// proof the pooled staging path (see `upload_pool`) is working. Reads zero+    /// once every resident upload comes out of the pool; any nonzero row names+    /// the leak to fix.+    UploadAllocs, }  impl Step {     /// Every step, in frame order. The JNI getter returns [`StepTimes::last_nanos`] in this     /// order; the Kotlin overlay labels rows from its mirror of it.-    pub(crate) const ALL: [Step; 20] = [+    pub(crate) const ALL: [Step; 26] = [         Step::JniEntry,         Step::UploadDrain,         Step::Select,@@ -95,6 +116,12 @@ impl Step {         Step::RecordOverlays,         Step::Submit,         Step::Present,+        Step::EarlyOut,+        Step::PlacementHit,+        Step::CullSkipped,+        Step::PipelineBinds,+        Step::FetchCancelled,+        Step::UploadAllocs,     ];      /// Steps timed per frame.@@ -123,8 +150,32 @@ impl Step {             Step::RecordOverlays => "ovl",             Step::Submit => "sub",             Step::Present => "prs",+            Step::EarlyOut => "eout",+            Step::PlacementHit => "phit",+            Step::CullSkipped => "cull",+            Step::PipelineBinds => "bind",+            Step::FetchCancelled => "fcan",+            Step::UploadAllocs => "uall",         }     }++    /// Whether this step records a plain count rather than nanoseconds.+    ///+    /// Count steps (`EarlyOut`, `PlacementHit`, `CullSkipped`) ride the same `StepTimes`+    /// arrays and the same JNI/overlay row order as the timing steps, but [`report`](StepTimes::report)+    /// prints them raw (`sum/max`) instead of as ms, and the Kotlin overlay formats those+    /// rows as integers rather than milliseconds.+    pub(crate) fn is_count(self) -> bool {+        matches!(+            self,+            Step::EarlyOut+                | Step::PlacementHit+                | Step::CullSkipped+                | Step::PipelineBinds+                | Step::FetchCancelled+                | Step::UploadAllocs+        )+    } }  /// The per-step timing state for one renderer.@@ -169,6 +220,9 @@ impl StepTimes {     /// The `avg/max` report over the last `frames` frames, in ms with one decimal, then reset the     /// window. Called every frame, so this is the one place that formats.     ///+    /// Count steps (see [`Step::is_count`]) print as raw `sum/max` instead — a skipped-draw+    /// count is not a duration, and printing one as ms would lie by three orders of magnitude.+    ///     /// `frames` is the window length (1 on the per-frame cadence), not read from here, so a frame     /// that never ran a step still divides correctly.     pub(crate) fn report(&mut self, frames: u32) -> String {@@ -176,9 +230,18 @@ impl StepTimes {         let mut out = String::from("steps");         for step in Step::ALL {             let at = step as usize;-            let avg_ms = self.sum[at] as f64 / frames as f64 / 1_000_000.0;-            let max_ms = self.max[at] as f64 / 1_000_000.0;-            out.push_str(&format!(" {} {avg_ms:.1}/{max_ms:.1}", step.short_name()));+            if step.is_count() {+                out.push_str(&format!(+                    " {} {}/{}",+                    step.short_name(),+                    self.sum[at],+                    self.max[at]+                ));+            } else {+                let avg_ms = self.sum[at] as f64 / frames as f64 / 1_000_000.0;+                let max_ms = self.max[at] as f64 / 1_000_000.0;+                out.push_str(&format!(" {} {avg_ms:.1}/{max_ms:.1}", step.short_name()));+            }             self.sum[at] = 0;             self.max[at] = 0;         }@@ -257,4 +320,29 @@ mod tests {             );         }     }++    #[test]+    fn count_steps_report_raw_not_ms() {+        let mut t = StepTimes::new();+        t.record(Step::CullSkipped, 12);+        t.record(Step::EarlyOut, 1);+        t.record(Step::UploadAllocs, 0);+        let line = t.report(1);+        assert!(+            line.contains("cull 12/12"),+            "counts must print raw, got {line}"+        );+        assert!(+            line.contains("eout 1/1"),+            "counts must print raw, got {line}"+        );+        assert!(+            line.contains("uall 0/0"),+            "counts must print raw, got {line}"+        );+        // And timings still print as ms beside them.+        t.record(Step::Submit, 2_500_000);+        let line = t.report(1);+        assert!(line.contains("sub 2.5/2.5"), "got {line}");+    } }
library/map/src/main/rust/src/vulkan/buffers.rs
diff --git a/library/map/src/main/rust/src/vulkan/buffers.rs b/library/map/src/main/rust/src/vulkan/buffers.rsindex e41a222710..2ef4ef9c96 100644--- a/library/map/src/main/rust/src/vulkan/buffers.rs+++ b/library/map/src/main/rust/src/vulkan/buffers.rs@@ -346,6 +346,10 @@ fn align_up(size: vk::DeviceSize) -> vk::DeviceSize { /// offset 0 and passes its `firstIndex`. `None` when there is nothing to pack, in which case /// the caller emits no draws, exactly as the per-mesh path did for empty input. ///+/// The pooled-upload path ([`upload_pool`]) packs the same bytes into long-lived arenas+/// instead of fresh buffers; this stays as the fallback for tiles that do not fit, and as+/// the packing reference both paths share.+/// /// # Safety /// /// `device` must outlive the returned buffers, and the caller must destroy them before
library/map/src/main/rust/src/vulkan/renderer/bind_state.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/bind_state.rs b/library/map/src/main/rust/src/vulkan/renderer/bind_state.rsnew file mode 100644index 0000000000..3fcecd98f9--- /dev/null+++ b/library/map/src/main/rust/src/vulkan/renderer/bind_state.rs@@ -0,0 +1,131 @@+//! Per-frame bind-state tracking: skip redundant pipeline + descriptor binds.+//!+//! MapLibre batches draws by program so the GPU sees one state change per group, not one per+//! draw. The record path here issues draws tile-by-tile and pass-by-pass, and several passes+//! re-bind the same pipeline (or the same atlas set) dozens of times a frame: fill/line draws+//! when the kind flips back and forth across layers, the traffic line draws after the layer+//! loop's lines, every `draw_symbol_batch` rebinding the glyph/sprite set it already bound.+//!+//! [`BindState`] fixes that without reordering any draw: it remembers the last-bound pipeline+//! and descriptor set for the frame, and its `bind_*` helpers issue the Vulkan call only on a+//! change. Draw order — the painter's-algorithm contract on `record_inner` — is untouched, so+//! this can only remove redundant state changes, never visible ones. Every real bind is+//! counted into `Step::PipelineBinds` for the debug overlay.+//!+//! Split out (file-length limit); the call sites live in `record*.rs`.+use super::Renderer;+use crate::style::LayerKind;+use crate::timing::Step;+use ash::vk;++/// Which pipeline + descriptor set the command buffer currently has bound.+///+/// Reset at the top of every frame (a fresh command buffer binds nothing). The pipeline key+/// is the raw handle plus the kind that selected it: `LayerKind` alone is not unique across+/// the flat/globe variants, and the handle alone would merge passes that must stay distinct+/// in the reader's eyes — belt and braces, since a missed bind draws wrong and a redundant+/// one only costs.+pub(super) struct BindState {+    pipeline: Option<vk::Pipeline>,+    /// The atlas set bound with the pipeline, if the pipeline takes one (symbol/icon/sprite).+    set: Option<vk::DescriptorSet>,+    /// Real binds issued this frame, for `Step::PipelineBinds`.+    binds: u64,+}++impl BindState {+    pub(super) fn new() -> BindState {+        BindState {+            pipeline: None,+            set: None,+            binds: 0,+        }+    }++    /// Bind `pipeline` (no descriptor set) when it differs from the current one.+    ///+    /// Returns whether a real bind was issued. The caller still owns the draw; this only+    /// owns the state tracking.+    pub(super) fn bind_pipeline(+        &mut self,+        device: &ash::Device,+        command_buffer: vk::CommandBuffer,+        pipeline: vk::Pipeline,+    ) -> bool {+        if self.pipeline == Some(pipeline) && self.set.is_none() {+            return false;+        }+        unsafe {+            device.cmd_bind_pipeline(command_buffer, vk::PipelineBindPoint::GRAPHICS, pipeline);+        }+        self.pipeline = Some(pipeline);+        self.set = None;+        self.binds += 1;+        true+    }++    /// Bind `pipeline` with atlas descriptor `set` when either differs.+    ///+    /// Symbol/icon/sprite draws always pair a pipeline with its atlas; tracking both means+    /// a text batch following an icon batch with the same set but a different pipeline still+    /// rebinds the pipeline, while identical pairs skip both calls.+    pub(super) fn bind_pipeline_with_set(+        &mut self,+        device: &ash::Device,+        command_buffer: vk::CommandBuffer,+        symbol_layout: vk::PipelineLayout,+        pipeline: vk::Pipeline,+        set: vk::DescriptorSet,+    ) -> bool {+        if self.pipeline == Some(pipeline) && self.set == Some(set) {+            return false;+        }+        unsafe {+            device.cmd_bind_pipeline(command_buffer, vk::PipelineBindPoint::GRAPHICS, pipeline);+            device.cmd_bind_descriptor_sets(+                command_buffer,+                vk::PipelineBindPoint::GRAPHICS,+                symbol_layout,+                0,+                &[set],+                &[],+            );+        }+        self.pipeline = Some(pipeline);+        self.set = Some(set);+        // One pipeline bind + one set bind saved or spent together: count the pair as one+        // so the overlay row tracks state changes, not Vulkan calls.+        self.binds += 1;+        true+    }++    /// Flush the frame's bind count into the step timers. Called once per recorded frame+    /// (not on early-out skips, which bind nothing).+    pub(super) fn flush(&self, renderer: &Renderer) {+        renderer+            .step_times+            .borrow_mut()+            .record(Step::PipelineBinds, self.binds);+    }+}++/// Map a flat layer kind to its frame pipeline, globe-aware.+///+/// The match that used to sit inline in the layer loop: one place that names the+/// fill/line(+globe) selection, so the loop's `BindState` call reads as a lookup plus a bind.+pub(super) fn flat_pipeline(+    renderer: &Renderer,+    kind: LayerKind,+    globe: bool,+) -> Option<vk::Pipeline> {+    match kind {+        LayerKind::Fill if globe => Some(renderer.pipelines.fill_globe),+        LayerKind::Fill => Some(renderer.pipelines.fill),+        LayerKind::Line if globe => Some(renderer.pipelines.line_globe),+        LayerKind::Line => Some(renderer.pipelines.line),+        // Symbols never take the flat path (deferred to `record_symbol`); the layer loop+        // skips them before reaching here, so this arm is unreachable but keeps the+        // match exhaustive without panicking.+        LayerKind::Symbol => None,+    }+}
library/map/src/main/rust/src/vulkan/renderer/fog.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/fog.rs b/library/map/src/main/rust/src/vulkan/renderer/fog.rsindex b028c1d52d..bfc9c7eb38 100644--- a/library/map/src/main/rust/src/vulkan/renderer/fog.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/fog.rs@@ -81,6 +81,61 @@ pub(crate) fn fog_color(layers: &[Layer], palette: Palette, zoom: f64) -> u32 {         .unwrap_or_else(|| crate::style::background(palette.variant)) } +/// How far past the viewport a tile may sit and still be drawn, in Dp.+///+/// The cull below drops resident tiles the viewport cannot see — stale tiles from the last+/// pan awaiting eviction, cap overflow — but a label anchored near a tile's edge can legitimately+/// extend past it, and the symbol path draws winners from whatever tiles placement accepted.+/// So the flat draws cull with this margin while symbols always draw: a tile further than this+/// from the viewport contributes no visible fill/line pixel, and any label it carried is either+/// duplicated on a visible tile or itself off-screen. Larger than the largest label box+/// (city names at ~30px plus halo); far smaller than a tile span at any zoom that matters.+pub(crate) const CULL_MARGIN_DP: f64 = 64.0;++/// Whether tile (`z`, `x`, `y`) is provably off-screen, so its flat draws can be skipped.+///+/// Conservative by construction: the globe path never culls (tiles bend onto the sphere, so a+/// flat rect test is meaningless), tilted views never cull (the ground trapezoid reaches past+/// the untilted bounds — see `select::coverage`), and the flat path culls only tiles fully+/// outside the rotated viewport bounds plus [`CULL_MARGIN_DP`]. Symbol draws are NOT gated on+/// this (see `record_inner`): placement dedup can crown a stale tile's copy of a border label,+/// and dropping that tile's symbols would lose the label while its on-screen twin was+/// deduped away. Fills, lines, carriageways, buildings, terrain, traffic and region pieces+/// are per-tile ground cover — skipping them where nothing shows is pure win.+pub(crate) fn tile_offscreen(camera: &Camera, z: u8, x: u32, y: u32) -> bool {+    if crate::camera::globe_active(camera) || camera.pitch_deg != 0.0 {+        return false;+    }+    let span = camera.tile_span_dp(z);+    if !(span > 0.0) {+        return false;+    }+    let (min, max) = camera.viewport_bounds();+    let m = CULL_MARGIN_DP;+    let x0 = x as f64 * span;+    let y0 = y as f64 * span;+    x0 + span < min.x - m || x0 > max.x + m || y0 + span < min.y - m || y0 > max.y + m+}++/// How many draws of style layer `layer_index` a culled `tile` would have issued.+///+/// The layer loop's share of the cull (file-length split): counts this tile's meshes for the+/// layer so the loop can skip them in one call. Zero when the tile is on-screen — the common+/// case is one function call and out.+pub(crate) fn culled_flat_draws(+    tile: &super::ResidentTile,+    layer_index: usize,+    camera: &Camera,+) -> usize {+    if !tile_offscreen(camera, tile.z, tile.x, tile.y) {+        return 0;+    }+    tile.layers+        .iter()+        .filter(|l| l.layer_index == layer_index)+        .count()+}+ #[cfg(test)] mod tests {     use super::*;@@ -163,4 +218,62 @@ mod tests {         // haze rather than dissolving the land into sea.         assert_eq!(apply_fog(water, land, 1.0), land);     }++    /// The tile under the camera centre at the camera zoom, for cull tests.+    fn centre_tile(c: &Camera, z: u8) -> (u32, u32) {+        let centre = crate::camera::project(c.center_lon, c.center_lat, c.zoom);+        let span = c.tile_span_dp(z);+        (+            (centre.x / span).floor().max(0.0) as u32,+            (centre.y / span).floor().max(0.0) as u32,+        )+    }++    #[test]+    fn the_centre_tile_is_never_culled() {+        let c = camera(0.0);+        let (x, y) = centre_tile(&c, 14);+        assert!(!tile_offscreen(&c, 14, x, y));+        // Its neighbours are inside the viewport too (411x891 Dp against 512 Dp tiles).+        assert!(!tile_offscreen(&c, 14, x + 1, y));+        assert!(!tile_offscreen(&c, 14, x, y + 1));+    }++    #[test]+    fn a_tile_across_the_world_is_culled() {+        let c = camera(0.0);+        let (x, y) = centre_tile(&c, 14);+        // More than a viewport plus the 64 Dp margin away in tile units.+        let far_x = (x as i64 + 10).min(16383) as u32;+        assert!(tile_offscreen(&c, 14, far_x, y));+        let far_y = (y as i64 + 10).min(16383) as u32;+        assert!(tile_offscreen(&c, 14, x, far_y));+    }++    #[test]+    fn the_cull_never_fires_tilted_or_on_the_globe() {+        // Tilted: the ground trapezoid reaches past the untilted bounds, so a rect test+        // would cull visible ground. The cull stays flat-only by construction.+        let tilted = camera(65.0);+        let (x, y) = centre_tile(&tilted, 14);+        let far_x = (x as i64 + 10).min(16383) as u32;+        assert!(!tile_offscreen(&tilted, 14, far_x, y));+        // Globe: tiles bend onto the sphere, so a flat rect test is meaningless.+        let mut globe = camera(0.0);+        globe.globe = true;+        assert!(!tile_offscreen(&globe, 2, 0, 0));+    }++    #[test]+    fn the_cull_never_fires_rotated_off_the_wrong_edge() {+        // A 45° bearing widens the covered box by sqrt(2): a tile at the viewport corner+        // must survive, because the rotated viewport reaches it.+        let mut c = camera(0.0);+        c.bearing_deg = 45.0;+        let (x, y) = centre_tile(&c, 14);+        assert!(!tile_offscreen(&c, 14, x, y));+        // But the far side of the world still culls — rotation widens, it does not cover.+        let far_x = (x as i64 + 10).min(16383) as u32;+        assert!(tile_offscreen(&c, 14, far_x, y));+    } }
library/map/src/main/rust/src/vulkan/renderer/frame.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/frame.rs b/library/map/src/main/rust/src/vulkan/renderer/frame.rsindex dd1c088ee7..25896d66a0 100644--- a/library/map/src/main/rust/src/vulkan/renderer/frame.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/frame.rs@@ -18,6 +18,7 @@ impl Renderer {         if let Some(puck) = puck {             self.overlays.push(Overlay::Puck(puck));         }+        self.bump_state();     }      /// Replace the app's pins with `markers`, or clear them with an empty slice.@@ -39,6 +40,7 @@ impl Renderer {         // a stale accept-set is a POI drawn over a new pin, while a redundant re-place is a         // millisecond on a state change, not per frame.         self.marker_epoch = self.marker_epoch.wrapping_add(1);+        self.bump_state();         if !markers.is_empty() {             // Parallel arrays cross JNI together and are truncated to the shortest there, so             // these lengths already agree; a defensive trunc here keeps a future direct caller@@ -72,6 +74,7 @@ impl Renderer {         if !vehicles.is_empty() {             self.overlays.push(Overlay::Vehicles(vehicles));         }+        self.bump_state();     }      /// Dim everything outside one region, or take the mask away with `None`.@@ -82,6 +85,7 @@ impl Renderer {     /// from a tap, not from the frame loop.     pub fn set_region_mask(&mut self, region: Option<u64>) {         self.selected_region = region;+        self.bump_state();     }      /// Replace the live-traffic colour table with a host-pushed `component_id → ARGB` set.@@ -101,6 +105,7 @@ impl Renderer {         for (&id, &color) in ids.iter().zip(colors).take(n) {             self.traffic_colors.insert(id, color);         }+        self.bump_state();     }      /// Drop every pushed traffic colour, so the overlay draws nothing until the next push.@@ -110,6 +115,7 @@ impl Renderer {     /// toggle-driven re-tessellation to evict the geometry.     pub fn clear_traffic(&mut self) {         self.traffic_colors.clear();+        self.bump_state();     }      /// Turn drawing of the traffic overlay on or off for subsequent frames.@@ -119,6 +125,7 @@ impl Renderer {     /// toggle-off and the re-tessellation that removes them.     pub fn set_traffic_enabled(&mut self, enabled: bool) {         self.traffic_enabled = enabled;+        self.bump_state();     }      /// Resident tiles, the geometry they carry, and what the last frame actually submitted.@@ -242,6 +249,9 @@ impl Renderer {         if self.needs_rebuild {             self.rebuild()?;             self.needs_rebuild = false;+            // A new swapchain must present at least once: the stored version describes+            // an image on the old one, and reusing it would skip that present.+            self.forget_submitted();         }         // Moon fast path: the textured disc INSTEAD of the vector frame (no tile         // draws, no symbols, no overlays). Textures missing (host never pushed)@@ -251,6 +261,56 @@ impl Renderer {             return self.render_moon(camera);         } +        // MapLibre-style submit early-out: when nothing changed since the last submitted+        // frame, re-recording + `queue_submit` would present a bit-identical image, so the+        // whole fence/acquire/record/submit/present sequence is skipped. The previously+        // presented image persists — `Ok(true)` tells the host a frame was "drawn", which+        // keeps the on-demand loop's accounting (grace windows, retry delays) exact.+        //+        // The version covers the camera pose (exact bits), the animation clock (50 ms bins,+        // so dash-phase animation still steps during grace windows), tile residency,+        // placement and all push-constant state. The `needs_frame` gate is what makes this+        // exact rather than optimistic: a fade in progress, pending retirements or a+        // rebuild all force a real submit, as does any epoch bump. Placement runs here —+        // before any fence or acquire — because its version is part of the key, and it is+        // free on a hit (a key compare) on exactly the frames this skips.+        self.scratch_ordered.clear();+        self.scratch_ordered.extend(self.tiles.keys().copied());+        self.scratch_ordered+            .sort_by_key(|k| self.tiles.get(k).map(|t| t.z).unwrap_or(0));+        let extent = self.swapchain.extent;+        let accepted = self.place_symbols(camera, layers, &self.scratch_ordered, extent, filter);+        // The pick snapshot tracks the accept-set, not the submit: a reused placement keeps+        // its ids, so this is a no-op on exactly the frames the early-out below skips — and+        // on a placement hit with an identical camera the boxes would re-project identically+        // anyway. Kept outside the skip so taps never read a stale frame's boxes.+        let mut accept_ids: Vec<u64> = accepted.keys().copied().collect();+        accept_ids.sort_unstable();+        if self.last_accept_ids.borrow().as_ref() != Some(&accept_ids) {+            self.refresh_placed(camera, layers, &accepted, extent);+            *self.last_accept_ids.borrow_mut() = Some(accept_ids);+        }+        let version = super::mod_extra::FrameVersion::current(+            camera,+            palette,+            self.residency_epoch.get(),+            self.placement_version.get(),+            self.state_epoch.get(),+        );+        if !self.needs_frame() && self.last_frame_version == Some(version) {+            // A skip implies a placement reuse (a recompute would have bumped the version+            // above), so all three P0 counters are settled here: the skip itself, the hit+            // behind it, and a zero cull (no draw pass ran to cull anything).+            self.step_times.borrow_mut().record(Step::EarlyOut, 1);+            self.step_times+                .borrow_mut()+                .record(Step::PlacementHit, 1);+            self.step_times+                .borrow_mut()+                .record(Step::CullSkipped, 0);+            return Ok(true);+        }+         let frame = &self.frames[self.frame_index];         let device = &self.context.device;         let fence_start = std::time::Instant::now();@@ -383,6 +443,12 @@ impl Renderer {         }          self.frame_index = (self.frame_index + 1) % FRAMES_IN_FLIGHT;+        // The submit landed: this version is what is on screen, so an identical next+        // frame may skip. Set only here — skipped frames, rebuilds and failures leave+        // the previous (or no) version in place. `EarlyOut` reads 0 for a real frame so+        // the overlay row tracks skips rather than going stale.+        self.last_frame_version = Some(version);+        self.step_times.borrow_mut().record(Step::EarlyOut, 0);         Ok(true)     } }
library/map/src/main/rust/src/vulkan/renderer/mod.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod.rs b/library/map/src/main/rust/src/vulkan/renderer/mod.rsindex 06a18bc106..0fd764d1aa 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -10,14 +10,17 @@ use ash::vk; use std::collections::HashMap;  mod fog;+mod bind_state; mod frame; mod mod_extra; mod placement; mod placement_markers; mod placement_refresh; mod placement_reuse;+mod quad; mod rebuild; mod record;+mod record_arrows; mod record_extra; mod record_extra2; mod record_extra3;@@ -28,9 +31,12 @@ mod record_symbol; mod upload; mod upload_extra; pub(super) mod upload_moon;+mod upload_pool;+mod upload_tail;  pub use mod_extra::Renderer; pub(crate) use placement::globe_screen_quad;+pub(crate) use quad::{Quad, QUAD_INDICES, QUAD_VERTICES};  /// How many frames may be in flight. Two is enough to keep the GPU fed behind vsync /// without adding latency the user can feel when panning.@@ -63,15 +69,37 @@ struct LayerBuffers { /// it costs at most 3 pairs (flat fills, stroked lines, ribbon carriageways) plus the /// already-single buildings and terrain meshes. ///+/// The pooled-upload path ([`upload_pool`]) goes one step further: the pools below name+/// ranges of long-lived arenas instead of fresh buffers, so a tile costs no allocation at+/// all. Either way a pool is one buffer pair plus per-mesh slices — the only difference is+/// who owns the memory — which is why the draw path binds `(buffer, offset)` pairs plus a+/// per-draw `firstIndex` and never asks which path produced them.+///+/// Ownership on retire: fresh pools are destroyed with the tile; arena ranges belong to+/// the pool and are never freed (see `collect_retired`, which tells them apart by buffer+/// handle, not by offset — offset 0 is a valid arena start).+/// /// `pub(crate)`: the pick-snapshot split (`placement_refresh`) resolves one /// label against a tile, so it names this type. pub(crate) struct ResidentTile {     /// Position-only 2-float fills: every `LayerKind::Fill` mesh plus the region-mask shapes.-    flat: Option<(Buffer, Buffer)>,+    ///+    /// `(vertex handle, vertex byte offset, index handle, index byte offset)`: raw handles,+    /// never owned `Buffer`s — fresh pools bind at offset 0, arena ranges at their committed+    /// offsets, and the draws read them back without caring which path produced them.+    /// Owned fresh buffers (fresh path only) live in [`fresh_owned`](Self::fresh_owned);+    /// the pooled path holds none.+    flat: Option<(vk::Buffer, vk::DeviceSize, vk::Buffer, vk::DeviceSize)>,     /// 7-float stroked lines: every `LayerKind::Line` mesh plus the live-traffic segments.-    lines: Option<(Buffer, Buffer)>,+    /// Same `(handle, offset, handle, offset)` shape as [`flat`](Self::flat).+    lines: Option<(vk::Buffer, vk::DeviceSize, vk::Buffer, vk::DeviceSize)>,     /// 6-float ribbon carriageways, one per distinct road-shape push set.-    ribbons: Option<(Buffer, Buffer)>,+    /// Same `(handle, offset, handle, offset)` shape as [`flat`](Self::flat).+    ribbons: Option<(vk::Buffer, vk::DeviceSize, vk::Buffer, vk::DeviceSize)>,+    /// Fresh-path owned buffers (up to 6: flat/lines/ribbons × vertices/indices), destroyed+    /// with the tile. Empty on the pooled path — arena ranges belong to the pool and are+    /// never freed (see `upload_pool`).+    fresh_owned: Vec<Buffer>,     layers: Vec<LayerBuffers>,     /// The tile's extruded 3D buildings, or `None` below z14 / where the tile has none. Drawn in     /// its own depth-tested pass ([`Renderer::record_buildings`]), not the flat layer loop.@@ -208,6 +236,11 @@ type AcceptSet = HashMap<u64, (bool, u32)>; /// Floats are compared as bit patterns rather than by value. This is an identity test — "is this /// the same camera the last accept-set was computed from" — and not a question about numeric /// closeness, so bits are both the correct comparison and the one that needs no epsilon.+///+/// `center_lon`/`center_lat`/`zoom`/`bearing`/`pitch` carry the exact camera for the fast exact-hit+/// path; `bucket_*` carry the quantised camera for the retained-collision slow path (see+/// [`same_bucket`](PlacementKey::same_bucket)): a small pan inside one bucket reuses the accept-set+/// without re-running the quadratic placer. #[derive(PartialEq, Eq, Clone)] struct PlacementKey {     center_lon: u64,@@ -215,6 +248,17 @@ struct PlacementKey {     zoom: u64,     bearing: u64,     pitch: u64,+    /// Quantised camera bucket: zoom in 1/32-level bins, bearing/pitch in 4° bins, centre in+    /// ~1/1024-tile bins at the floored zoom. Two frames in one bucket share a collision answer+    /// (only the outcome lags; boxes still re-project per frame in `refresh_placed`).+    bucket_zoom: i64,+    bucket_bearing: i64,+    bucket_pitch: i64,+    bucket_lon: i64,+    bucket_lat: i64,+    /// Whether the globe path was active: globe and flat project through different box+    /// builders, so a bucket never spans the projection switch.+    globe: bool,     width_dp: u32,     height_dp: u32,     density: u32,@@ -309,10 +353,6 @@ struct RouteBuffers {     segments: Vec<RouteSegmentRange>, } -/// How dark the world outside the selected region goes. Alpha, not a colour swap, so the map-/// stays legible underneath — the point is to say "this is the boundary", not to hide the rest.-const SCRIM_COLOR: u32 = 0x8C00_0000;- /// Column-major identity, for an overlay whose vertices are already in clip space. const IDENTITY: [f32; 16] = [     1.0, 0.0, 0.0, 0.0, //@@ -321,6 +361,10 @@ const IDENTITY: [f32; 16] = [     0.0, 0.0, 0.0, 1.0, ]; +/// How dark the world outside the selected region goes. Alpha, not a colour swap, so the map+/// stays legible underneath — the point is to say "this is the boundary", not to hide the rest.+const SCRIM_COLOR: u32 = 0x8C00_0000;+ /// The unit quad every screen-anchored overlay draws with: four vertices in −1..1 and the /// two triangles over them. ///@@ -328,18 +372,9 @@ const IDENTITY: [f32; 16] = [ /// where it is, how big, what colour, which way it points — rides in the matrix and the /// push constants. So the per-frame cost is one `cmd_push_constants` and one /// `cmd_draw_indexed`, not the pair of `vkAllocateMemory` calls a transient buffer pays.-struct Quad {-    vertices: Buffer,-    indices: Buffer,-}--/// The four corners of the unit square, in the −1..1 the puck shaders read as a local-/// coordinate. Three floats per corner to match the shared fill stride (the puck vertex-/// shader reads only the first two; the z is 0.0 and ignored).-const QUAD_VERTICES: [f32; 12] = [-    -1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0,-];-const QUAD_INDICES: [u32; 6] = [0, 1, 2, 0, 2, 3];+///+/// Lives in `quad.rs` alongside its vertex/index constants (file-length split) and is+/// re-exported at the top of this file, so the record passes keep their paths.  /// The puck's blue, from the `drawUserIcon` in `maps` this replaces. const PUCK_COLOR: u32 = 0xFF0E_35F1;
library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rsindex 3b9e6b493d..5e8b2e4135 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs@@ -11,9 +11,11 @@ use std::cell::Cell; use std::collections::HashMap;  use super::{-    AcceptSet, Frame, Overlay, PlacedHit, PlacementKey, Quad, ResidentTile, RouteBuffers,+    AcceptSet, Frame, Overlay, PlacedHit, PlacementKey, ResidentTile, RouteBuffers,     TransientBuffers, };+use super::quad::Quad;+use super::upload_pool::UploadPool; use crate::style::LayerKind;  pub struct Renderer {@@ -62,7 +64,9 @@ pub struct Renderer {         u32,         LayerKind,         ash::vk::Buffer,+        ash::vk::DeviceSize,         ash::vk::Buffer,+        ash::vk::DeviceSize,         u32,         u32,         Option<u32>,@@ -173,4 +177,107 @@ pub struct Renderer {     /// The last camera a frame was recorded with, so [`pick_at`](Self::pick_at) can place markers     /// against the frame the user is actually looking at. `None` before the first frame.     pub(crate) last_camera: Option<Camera>,+    /// Version of everything affecting the picture that is NOT the camera pose: overlays+    /// (puck, markers, vehicles), route/rail meshes, traffic table + toggle, region mask,+    /// Moon textures. Bumped by every setter below; part of the submit early-out key in+    /// [`render`](Self::render) (see `FrameVersion`).+    pub(crate) state_epoch: Cell<u64>,+    /// Version of tile residency: bumped by [`upload`](Self::upload) and by+    /// [`retain`](Self::retain) when it evicts anything. A new tile or an eviction changes+    /// the picture, so the early-out key carries this instead of hashing the resident set.+    pub(crate) residency_epoch: Cell<u64>,+    /// How many times [`place_symbols`](Self::place_symbols) recomputed (not reused) the+    /// accept-set. Reuse hits leave this alone, so the early-out key sees a stable placement+    /// across the retained-collision slow path without hashing the accept-set per frame.+    pub(crate) placement_version: Cell<u64>,+    /// What the last submitted frame drew, for the MapLibre-style submit early-out: when the+    /// next frame's version is identical, re-recording + `queue_submit` would present a+    /// bit-identical image, so the frame is skipped (counted in `Step::EarlyOut`). `None`+    /// before the first submit and after anything that invalidates unconditionally+    /// (swapchain rebuild), forcing the next frame through.+    pub(crate) last_frame_version: Option<FrameVersion>,+    /// Tile-upload staging arenas (see `upload_pool`): bump-allocated once, never freed+    /// until the renderer dies, so a tile upload costs copies but no `vkAllocateMemory`.+    pub(crate) upload_pool: UploadPool,+}++/// What one submitted frame drew, for the submit early-out.+///+/// Everything here is compared by value per frame — all integers or bit patterns, no hashing,+/// no allocation. The camera pose is exact bits (any pose change draws); the clock is+/// quantised to 50 ms bins so dash-phase animation still steps during grace windows while+/// identical frames 16 ms apart skip. Residency, placement and overlay state ride as epoch+/// counters bumped at their single choke points; palette is a plain value (push-constant+/// recolour, no re-tessellation).+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub(crate) struct FrameVersion {+    cam_lon: u64,+    cam_lat: u64,+    zoom: u64,+    bearing: u64,+    pitch: u64,+    width_dp: u32,+    height_dp: u32,+    density: u32,+    globe: bool,+    moon: bool,+    /// `time_seconds` in 50 ms bins: animation still moves during grace, steady frames skip.+    time_bin: i64,+    palette_dark: bool,+    palette_muted: bool,+    residency: u64,+    placement: u64,+    state: u64,+}++impl FrameVersion {+    /// The version the current frame would submit. `palette` is read live (push-constant+    /// state, never tessellated); the epochs come from the renderer's counters.+    pub(crate) fn current(+        camera: &Camera,+        palette: crate::style::Palette,+        residency: u64,+        placement: u64,+        state: u64,+    ) -> FrameVersion {+        FrameVersion {+            cam_lon: camera.center_lon.to_bits(),+            cam_lat: camera.center_lat.to_bits(),+            zoom: camera.zoom.to_bits(),+            bearing: camera.bearing_deg.to_bits(),+            pitch: camera.pitch_deg.to_bits(),+            width_dp: camera.width_dp.to_bits(),+            height_dp: camera.height_dp.to_bits(),+            density: camera.density.to_bits(),+            globe: camera.globe,+            moon: camera.moon,+            time_bin: (camera.time_seconds * 20.0).floor() as i64,+            palette_dark: palette.variant == crate::style::Variant::Dark,+            palette_muted: palette.muted,+            residency,+            placement,+            state,+        }+    }+}++impl Renderer {+    /// Bump the picture-state epoch: anything that changes what a frame draws outside the+    /// camera pose and tile residency (overlays, route/rail, traffic, region, Moon) calls+    /// this, so the submit early-out sees the change without comparing state.+    pub(crate) fn bump_state(&self) {+        self.state_epoch.set(self.state_epoch.get().wrapping_add(1));+    }++    /// Bump the residency epoch: an upload or an eviction changed the resident set.+    pub(crate) fn bump_residency(&self) {+        self.residency_epoch+            .set(self.residency_epoch.get().wrapping_add(1));+    }++    /// Forcibly retire the last submitted version (swapchain rebuild path): the next frame+    /// submits unconditionally, because a new swapchain/extent must present at least once.+    pub(crate) fn forget_submitted(&mut self) {+        self.last_frame_version = None;+    } }
library/map/src/main/rust/src/vulkan/renderer/placement.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement.rs b/library/map/src/main/rust/src/vulkan/renderer/placement.rsindex 01f2f9b134..90fee58e99 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement.rs@@ -1,6 +1,6 @@ use super::{     anchors_for, kind_name,-    placement_reuse::{box_inputs, box_inputs_with_arms, drift_reuse_ms, within_drift},+    placement_reuse::{box_inputs, box_inputs_with_arms, bucket_for, reuse_cached_accept},     AcceptSet, Overlay, PlacedHit, PlacementKey, Renderer, QUAD_INDICES, }; use crate::camera::Camera;@@ -60,12 +60,21 @@ impl Renderer {         filter: &crate::style::KindFilter,     ) -> AcceptSet {         use crate::tile::placement;+        let globe = crate::camera::globe_active(camera);+        let (bucket_zoom, bucket_bearing, bucket_pitch, bucket_lon, bucket_lat) =+            bucket_for(camera);         let key = PlacementKey {             center_lon: camera.center_lon.to_bits(),             center_lat: camera.center_lat.to_bits(),             zoom: camera.zoom.to_bits(),             bearing: camera.bearing_deg.to_bits(),             pitch: camera.pitch_deg.to_bits(),+            bucket_zoom,+            bucket_bearing,+            bucket_pitch,+            bucket_lon,+            bucket_lat,+            globe,             width_dp: camera.width_dp.to_bits(),             height_dp: camera.height_dp.to_bits(),             density: camera.density.to_bits(),@@ -87,36 +96,15 @@ impl Renderer {             layers: layers.len(),             markers: self.marker_epoch,         };-        if let Some((cached, accepted, at)) = self.placement_cache.borrow().as_ref() {-            if *cached == key {-                return accepted.clone();-            }-            // Same everything but the centre: a pan in progress. Reuse the last accept-set-            // for a short window rather than re-running the quadratic pass every frame.-            let mut moved = cached.clone();-            moved.center_lon = key.center_lon;-            moved.center_lat = key.center_lat;-            if moved == key && at.elapsed().as_millis() < PLACE_REUSE_MS {-                return accepted.clone();-            }-            // Small zoom/bearing/pitch drift on top of a pan: the candidate universe is-            // bit-identical (tiles, stamps, filter, extent, layers, sizes) and only the-            // projection moved a little, so reuse the accept-set within the same window.-            // Boxes still re-project per frame in `refresh_placed`; only the collision-            // outcome lags, by at most the window.-            //-            // A fast zoom-out shrinks the window: past ~1 level/sec the answer goes stale-            // faster than the pan window allows, so re-place promptly.-            if cached.same_universe(&key)-                && within_drift(cached, &key)-                && at.elapsed().as_millis() < drift_reuse_ms(cached, &key, at, PLACE_REUSE_MS)-            {-                return accepted.clone();-            }+        // The reuse prologue lives in `placement_reuse` (file-length split): an exact, drift+        // or bucket hit returns the cached accept-set, a miss falls through to the full pass.+        if let Some(accepted) =+            reuse_cached_accept(&self.placement_cache, &self.step_times, &key, PLACE_REUSE_MS)+        {+            return accepted;         }         let mut candidates: Vec<placement::SegmentedCandidate> = Vec::new();         let camera_z = camera.zoom.floor().clamp(0.0, 22.0) as u8;-        let globe = crate::camera::globe_active(camera);         for (index, layer) in layers.iter().enumerate() {             if layer.kind != LayerKind::Symbol {                 continue;@@ -300,6 +288,13 @@ impl Renderer {             .enumerate()             .map(|(order, (id, flipped))| (id, (flipped, order as u32)))             .collect();+        // A fresh accept-set is a new placement version: the submit early-out keys on this+        // rather than hashing the set per frame, and reuse hits above leave it alone.+        self.placement_version+            .set(self.placement_version.get().wrapping_add(1));+        self.step_times+            .borrow_mut()+            .record(crate::timing::Step::PlacementHit, 0);         *self.placement_cache.borrow_mut() = Some((key, accepted.clone(), Instant::now()));         accepted     }
library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs b/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rsindex daec7b59a5..38a85caff1 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs@@ -7,6 +7,7 @@ //! per-label collision-box inputs the candidate loop reads. A real submodule //! (not `include!`), so imports are explicit below. use super::PlacementKey;+use super::AcceptSet; use crate::camera::Camera; use crate::style::Layer; use crate::tile::geometry;@@ -86,10 +87,26 @@ pub(super) fn drift_reuse_ms( }  impl PlacementKey {+    /// The retained-collision bucket: quantised camera pose plus the globe flag.+    ///+    /// Bins carry hysteresis by construction — the bucket is what the accept-set is cached+    /// against, and `same_bucket` compares buckets, not distances — so a camera oscillating+    /// on a bin edge re-places once per crossing rather than flickering labels on and off:+    /// each crossing recomputes a stable answer instead of toggling between two.+    pub(super) fn same_bucket(&self, other: &PlacementKey) -> bool {+        self.bucket_zoom == other.bucket_zoom+            && self.bucket_bearing == other.bucket_bearing+            && self.bucket_pitch == other.bucket_pitch+            && self.bucket_lon == other.bucket_lon+            && self.bucket_lat == other.bucket_lat+            && self.globe == other.globe+    }+     /// Bit-identity of everything but the camera pose: tiles and their stamps, filter, extent,-    /// sizes, and layer count. A drift-reuse candidate must match all of these; only-    /// centre/zoom/bearing/pitch may differ (within their thresholds — see `within_drift`).-    /// Any universe change is a hard re-place.+    /// sizes, layer count, and the globe flag. A drift-reuse candidate must match all of these;+    /// only centre/zoom/bearing/pitch may differ (within their thresholds — see `within_drift`).+    /// Any universe change is a hard re-place. The globe flag is universe, not pose: flat and+    /// globe project through different box builders, so a projection switch must never reuse.     pub(super) fn same_universe(&self, other: &PlacementKey) -> bool {         self.width_dp == other.width_dp             && self.height_dp == other.height_dp@@ -99,9 +116,73 @@ impl PlacementKey {             && self.tiles == other.tiles             && self.layers == other.layers             && self.markers == other.markers+            && self.globe == other.globe     } } +/// A cached accept-set reused without re-running the placer, or `None` on a miss.+///+/// The three hit paths in priority order: an exact key hit (still camera), a pan within the+/// reuse window (same everything but the centre), and small zoom/bearing/pitch drift on a+/// bit-identical candidate universe. Every hit records `Step::PlacementHit` (1); the caller+/// records 0 and bumps the placement version on a recompute. Boxes still re-project per+/// frame in `refresh_placed` on every path — only the collision outcome lags.+///+/// Split from `place_symbols` (file-length limit); the logic itself is unchanged.+pub(super) fn reuse_cached_accept(+    cache: &std::cell::RefCell<Option<(PlacementKey, AcceptSet, Instant)>>,+    step_times: &std::cell::RefCell<crate::timing::StepTimes>,+    key: &PlacementKey,+    full_window_ms: u128,+) -> Option<AcceptSet> {+    let cached = cache.borrow();+    let (cached_key, accepted, at) = cached.as_ref()?;+    if *cached_key == *key {+        step_times+            .borrow_mut()+            .record(crate::timing::Step::PlacementHit, 1);+        return Some(accepted.clone());+    }+    // Same everything but the centre: a pan in progress. Reuse the last accept-set+    // for a short window rather than re-running the quadratic pass every frame.+    let mut moved = cached_key.clone();+    moved.center_lon = key.center_lon;+    moved.center_lat = key.center_lat;+    if moved == *key && at.elapsed().as_millis() < full_window_ms {+        step_times+            .borrow_mut()+            .record(crate::timing::Step::PlacementHit, 1);+        return Some(accepted.clone());+    }+    // Small zoom/bearing/pitch drift on top of a pan: the candidate universe is+    // bit-identical (tiles, stamps, filter, extent, layers, sizes) and only the+    // projection moved a little, so reuse the accept-set within the same window.+    //+    // A fast zoom-out shrinks the window: past ~1 level/sec the answer goes stale+    // faster than the pan window allows, so re-place promptly.+    if cached_key.same_universe(key)+        && within_drift(cached_key, key)+        && at.elapsed().as_millis() < drift_reuse_ms(cached_key, key, at, full_window_ms)+    {+        step_times+            .borrow_mut()+            .record(crate::timing::Step::PlacementHit, 1);+        return Some(accepted.clone());+    }+    // Retained collision bucket (MapLibre's camera-bucket equivalent): same+    // quantised bucket and same candidate universe means the quadratic placer would+    // answer identically, so reuse without a time bound. The time-window paths above+    // stay as the fallback for cameras that drifted within thresholds but crossed a+    // bucket edge; this path covers the steady slow-pan case indefinitely.+    if cached_key.same_universe(key) && cached_key.same_bucket(key) {+        step_times+            .borrow_mut()+            .record(crate::timing::Step::PlacementHit, 1);+        return Some(accepted.clone());+    }+    None+}+ /// Everything one label's collision box depends on besides its anchor. /// /// Built once per label and reused for each candidate anchor, so the two boxes a POI is@@ -153,3 +234,100 @@ fn collision_padding_px(zoom: f64) -> f32 {         (24.0 - (zoom - 6.0) * (20.0 / 8.0)) as f32     } }++/// Quantise the camera into a retained-collision bucket (MapLibre's camera-bucket equivalent).+///+/// The placer is quadratic plus per-glyph projection; re-running it every frame is the panning+/// jank. Frames inside one bucket share the cached accept-set: only the *collision outcome*+/// lags by at most one bucket, while boxes still re-project per frame in `refresh_placed`,+/// so what draws tracks the camera exactly.+///+/// Bin sizes: zoom in 1/32-level bins (a slow pinch crosses ~2 bins/sec — each re-place is a+/// stable answer, not flicker); bearing/pitch in 4° bins (inside the old 2° drift budget's+/// spirit but coarser, because boxes re-project anyway); centre in ~1/1024-tile bins at the+/// floored zoom (sub-pixel at every zoom — a pan crosses a bin every few frames at most).+/// Globe is part of the key (flat and globe project through different box builders).+pub(super) fn bucket_for(camera: &Camera) -> (i64, i64, i64, i64, i64) {+    let zoom_bin = (camera.zoom * 32.0).floor() as i64;+    let bearing_bin = (camera.bearing_deg.rem_euclid(360.0) / 4.0).floor() as i64;+    let pitch_bin = (camera.pitch_deg / 4.0).floor() as i64;+    // Centre bins in tile units at the floored zoom: zoom-independent bin density.+    let floor_z = camera.zoom.floor().clamp(0.0, 22.0);+    let span = 512.0 * 2f64.powf(floor_z);+    let centre = crate::camera::project(camera.center_lon, camera.center_lat, floor_z);+    let lon_bin = (centre.x / span * 1024.0).floor() as i64;+    let lat_bin = (centre.y / span * 1024.0).floor() as i64;+    (zoom_bin, bearing_bin, pitch_bin, lon_bin, lat_bin)+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::camera::Camera;++    fn camera(lon: f64, lat: f64, zoom: f64, bearing: f64, pitch: f64) -> Camera {+        Camera {+            center_lon: lon,+            center_lat: lat,+            zoom,+            width_dp: 411.0,+            height_dp: 891.0,+            density: 2.0,+            bearing_deg: bearing,+            pitch_deg: pitch,+            time_seconds: 0.0,+            globe: false,+            moon: false,+        }+    }++    #[test]+    fn a_still_camera_stays_in_its_bucket() {+        let c = camera(-122.4194, 37.7749, 14.0, 0.0, 0.0);+        assert_eq!(bucket_for(&c), bucket_for(&c));+    }++    #[test]+    fn a_one_frame_pan_stays_in_its_bucket() {+        // 16 ms of panning at 60fps moves the centre by a few Dp — far less than the+        // ~1/1024-tile bin (half a Dp at z14), so the collision answer is retained.+        let a = camera(-122.4194, 37.7749, 14.0, 0.0, 0.0);+        let b = camera(-122.4193, 37.7749, 14.0, 0.0, 0.0);+        assert_eq!(bucket_for(&a), bucket_for(&b));+    }++    #[test]+    fn a_fast_pan_leaves_its_bucket() {+        // A fling crossing half the viewport must re-place: the candidate set on screen+        // is genuinely different, not a stable answer lagging by a bucket.+        let a = camera(-122.4194, 37.7749, 14.0, 0.0, 0.0);+        let b = camera(-122.0, 37.7749, 14.0, 0.0, 0.0);+        assert_ne!(bucket_for(&a), bucket_for(&b));+    }++    #[test]+    fn a_zoom_step_leaves_its_bucket() {+        // 1/32-level bins: a tenth of a level re-places, so a pinch re-places a few+        // times a second with a stable answer each time rather than every frame.+        let a = camera(-122.4194, 37.7749, 14.0, 0.0, 0.0);+        let b = camera(-122.4194, 37.7749, 14.1, 0.0, 0.0);+        assert_ne!(bucket_for(&a).0, bucket_for(&b).0);+    }++    #[test]+    fn buckets_are_zoom_independent_in_ground_terms() {+        // Centre bins are ~1/1024 of a tile at the floored zoom: the same ground shift+        // crosses the same number of bins whatever the zoom, so bucket density does not+        // thin out at street zoom or thicken at country zoom.+        let shift_lon = 0.0001;+        let low_a = camera(-122.4194, 37.7749, 6.0, 0.0, 0.0);+        let low_b = camera(-122.4194 + shift_lon, 37.7749, 6.0, 0.0, 0.0);+        let high_a = camera(-122.4194, 37.7749, 14.0, 0.0, 0.0);+        let high_b = camera(-122.4194 + shift_lon, 37.7749, 14.0, 0.0, 0.0);+        let low_moved = bucket_for(&low_a).3 != bucket_for(&low_b).3;+        let high_moved = bucket_for(&high_a).3 != bucket_for(&high_b).3;+        // At z6 the shift is sub-bin (stays), at z14 it crosses bins (moves): the point+        // is the scaling holds, i.e. bins track ground, not zoom floats.+        assert!(!low_moved || high_moved);+    }+}
library/map/src/main/rust/src/vulkan/renderer/quad.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/quad.rs b/library/map/src/main/rust/src/vulkan/renderer/quad.rsnew file mode 100644index 0000000000..1f522b69b6--- /dev/null+++ b/library/map/src/main/rust/src/vulkan/renderer/quad.rs@@ -0,0 +1,33 @@+//! The shared overlay quad: unit-square vertices + indices, uploaded once.+//!+//! Split from `mod.rs` (file-length limit). `Renderer::new` uploads these; every+//! screen-anchored overlay (puck, markers, vehicles, scrim, Moon disc, id-buffer pick)+//! draws from them, so the per-frame cost is one push constant and one draw, not an+//! allocation.+//!+//! Items are `pub` (not `pub(super)`) so sibling passes can name `quad::Quad`,+//! `quad::QUAD_VERTICES` and `quad::QUAD_INDICES` directly; the parent keeps a private+//! `use` for `super::QUAD_INDICES` paths.++use crate::vulkan::buffers::Buffer;++/// The unit quad every screen-anchored overlay draws with: four vertices in −1..1 and the+/// two triangles over them.+///+/// Uploaded once in [`Renderer::new`](super::Renderer::new), because everything that+/// varies about an overlay — where it is, how big, what colour, which way it points —+/// rides in the matrix and the push constants. So the per-frame cost is one+/// `cmd_push_constants` and one `cmd_draw_indexed`, not the pair of `vkAllocateMemory`+/// calls a transient buffer pays.+pub struct Quad {+    pub vertices: Buffer,+    pub indices: Buffer,+}++/// The four corners of the unit square, in the −1..1 the puck shaders read as a local+/// coordinate. Three floats per corner to match the shared fill stride (the puck vertex+/// shader reads only the first two; the z is 0.0 and ignored).+pub const QUAD_VERTICES: [f32; 12] = [+    -1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0,+];+pub const QUAD_INDICES: [u32; 6] = [0, 1, 2, 0, 2, 3];
library/map/src/main/rust/src/vulkan/renderer/rebuild.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs b/library/map/src/main/rust/src/vulkan/renderer/rebuild.rsindex 9456b15290..9faec3b6dd 100644--- a/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs@@ -44,53 +44,20 @@ impl Drop for Renderer {     fn drop(&mut self) {         unsafe {             let _ = self.context.device.device_wait_idle();-            for tile in self.tiles.values() {-                // Draw slices are plain indices into the pools — each pool is one pair.-                if let Some((v, i)) = &tile.flat {-                    v.destroy(&self.context.device);-                    i.destroy(&self.context.device);-                }-                if let Some((v, i)) = &tile.lines {-                    v.destroy(&self.context.device);-                    i.destroy(&self.context.device);-                }-                if let Some((v, i)) = &tile.ribbons {-                    v.destroy(&self.context.device);-                    i.destroy(&self.context.device);-                }-                if let Some(buildings) = &tile.buildings {-                    buildings.vertices.destroy(&self.context.device);-                    buildings.indices.destroy(&self.context.device);-                }-                if let Some(terrain) = &tile.terrain {-                    terrain.vertices.destroy(&self.context.device);-                    terrain.indices.destroy(&self.context.device);-                }-            }-            self.tiles.clear();-            for (_, tile) in &self.retiring {-                if let Some((v, i)) = &tile.flat {-                    v.destroy(&self.context.device);-                    i.destroy(&self.context.device);-                }-                if let Some((v, i)) = &tile.lines {-                    v.destroy(&self.context.device);-                    i.destroy(&self.context.device);-                }-                if let Some((v, i)) = &tile.ribbons {-                    v.destroy(&self.context.device);-                    i.destroy(&self.context.device);-                }-                if let Some(buildings) = &tile.buildings {-                    buildings.vertices.destroy(&self.context.device);-                    buildings.indices.destroy(&self.context.device);-                }-                if let Some(terrain) = &tile.terrain {-                    terrain.vertices.destroy(&self.context.device);-                    terrain.indices.destroy(&self.context.device);-                }+            // Tile pools first (fresh pools destroy, arena ranges do not — see+            // `upload_tail::free_tile_set`), then the retiring queue the same way,+            // then the arenas themselves. Order matters: the tiles borrow nothing+            // from the pool, but freeing arenas first would leave the tile loops+            // comparing against dead handles.+            let tiles: Vec<super::ResidentTile> =+                std::mem::take(&mut self.tiles).into_values().collect();+            super::upload_tail::free_tile_set(self, tiles, &self.context.device);+            let retiring: Vec<(usize, super::ResidentTile)> =+                std::mem::take(&mut self.retiring);+            for (_, tile) in &retiring {+                super::upload_tail::free_retired_tile(self, tile, &self.context.device);             }-            self.retiring.clear();+            super::upload_pool::destroy_pool(&mut self.upload_pool, &self.context.device);             if let Some(route) = &self.route {                 route.vertices.destroy(&self.context.device);                 route.indices.destroy(&self.context.device);@@ -108,6 +75,7 @@ impl Drop for Renderer {                 ring.destroy(&self.context.device);             }             self.scratch.clear();+            super::upload_pool::destroy_pool(&mut self.upload_pool, &self.context.device);             for frame in &self.frames {                 self.context.device.destroy_fence(frame.in_flight, None);                 self.context
library/map/src/main/rust/src/vulkan/renderer/record.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record.rs b/library/map/src/main/rust/src/vulkan/renderer/record.rsindex 1595e2f681..d4367c0c1f 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record.rs@@ -1,4 +1,5 @@-use super::fog::{apply_fog, fog_color, fog_factor};+use super::fog::{apply_fog, culled_flat_draws, fog_color, fog_factor};+use super::bind_state::{flat_pipeline, BindState}; use super::{     anchors_for, argb_to_rgba, scale_alpha, Overlay, Renderer, UserPuck, ARROW_COLOR, ARROW_DP,     BUILDINGS_DRAW_MIN_ZOOM, IDENTITY, PUCK_COLOR, PUCK_CONE_DP, PUCK_CONE_HALF_STROKE_DP,@@ -59,48 +60,9 @@ impl Renderer {     }      /// The body of [`record`](Self::record): split out so the borrow structure-    /// reads linearly. All Vulkan calls go through raw handles copied out of-    /// `self` at each step; `record_symbol` is the only `&mut self` callee.-    ///-    /// # Draw order (the contract A/C/D/E/G extend)-    ///-    /// Everything happens in one subpass, so order *is* correctness for the flat layers (they-    /// blend, depth-off) and the depth attachment resolves it for the 3D ones. The sequence is:-    ///-    /// 0. **`record_terrain`** (WS-G) — the DEM-displaced ground, depth-tested, drawn first so it is-    ///    the ground the flat layers sit over. A tile with no heightmap draws nothing here and keeps-    ///    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_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`).-    /// 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.-    ///    **`record_rail_lines`** draws immediately before it: same mesh path, so the-    ///    pack-driven rail network sits under a selected route.-    /// 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-    /// depth-enabled pipeline; terrain goes *before* step 1 (it is the ground the flat layers-    /// drape over / sit above) and buildings *after* step 1 at z14+ so they occlude the basemap-    /// by depth. **WS-C markers + id pass** slot beside `record_overlays`. **WS-E curved labels**-    /// ride the symbol path inside step 1. Each adds its own pass/branch; keep this list current-    /// and serialise merges so the passes do not collide.-    ///-    /// # Flat layers over terrain: draped, not offset (WS-G)-    ///-    /// The flat 2D layers (roads, water, landuse) carry a draped z sampled from the same-    /// heightmap as the terrain at build time (plus a sub-metre lift) and draw depth-off,-    /// painting over the terrain in draw order. The vertex z is tile-normalised; each draw-    /// pushes the tile's world-px span in `morph.z` (mirroring the buildings/terrain-    /// `line.x`), which the shader multiplies back to the world-px height the perspective-    /// matrix expects — that scale is what puts roads on the slopes instead of through them.-    /// Terrain writes depth for the 3D layers (buildings occlude against it) while the flat-    /// layers paint on top with no z-fighting and need no polygon depth offset.+    /// reads linearly. Draw order: one subpass, so order *is* correctness — flat+    /// layers blend (depth-off), 3D ones resolve by depth. Sequence:+    /// terrain, basemap layers, carriageways, traffic, arrows, region, route, overlays.     #[allow(clippy::too_many_arguments)]     unsafe fn record_inner(         &mut self,@@ -126,20 +88,23 @@ impl Renderer {          let mut bound: Option<LayerKind> = None;         let mut submitted = 0usize;+        // Flat draws skipped by the off-screen cull below, counted into `Step::CullSkipped`+        // so the debug overlay shows what the cull saved. Tail passes add their own skips+        // to this through `record_tail`.+        let mut culled = 0usize;+        // Pipeline + descriptor bind dedup for the frame (MapLibre's program batching+        // without reordering any draw): every pass below binds through this instead of+        // issuing raw binds, so repeated binds of the same state collapse to one.+        let mut binds = BindState::new();         // One tile-layer's draws, reused across the whole frame — and across frames: the         // buffer lives on the renderer (`scratch_draws`) and is only cleared per tile below,-        // so a frame pays no allocation for it.-        //-        // A layer used to have at most one mesh per tile, so the draw could be a single-        // `find`. Transit breaks that: a tile holding two route colours emits two meshes-        // for one layer, and a `find` would silently draw only the first line. Copying the-        // handles out (rather than iterating `self.tiles` in place) is what keeps-        // `record_symbol`'s `&mut self` call legal in the sibling arm below; reusing the-        // buffer keeps that free of allocation.-        //+        // so a frame pays no allocation for it. Each draw carries its pool's bind offsets+        // alongside the slice (see the loop). A layer used to have at most one mesh per+        // tile; transit breaks that, so the handles are copied out rather than `find`-ing+        // — which also keeps `record_symbol`'s `&mut self` call legal below.         // Borrowed out once here (not per tile below): `draws`/`ordered`/`tile_alpha` are         // disjoint fields from `self.tiles`, and the loop's `&mut self` symbol call needs-        // the compiler to see that. Split at the top, rejoined after the loop.+        // the compiler to see that.         let (draws, ordered, tile_alpha) = {             self.scratch_draws.clear();             self.scratch_ordered.clear();@@ -187,7 +152,9 @@ impl Renderer {                 u32,                 LayerKind,                 vk::Buffer,+                vk::DeviceSize,                 vk::Buffer,+                vk::DeviceSize,                 u32,                 u32,                 Option<u32>,@@ -226,7 +193,16 @@ impl Renderer {         // Fog toward the `earth` land colour, not the water-blue `clear`.         let fog = fog_color(layers, palette, camera.zoom);         let step_start = std::time::Instant::now();-        self.record_terrain(command_buffer, camera, layers, palette, fog, &mut submitted);+        self.record_terrain(+            command_buffer,+            camera,+            layers,+            palette,+            fog,+            &mut submitted,+            &mut culled,+            &mut binds,+        );         self.step_times             .borrow_mut()             .record(Step::RecordTerrain, nanos_since(step_start));@@ -317,19 +293,34 @@ impl Renderer {                     deferred_symbols.push((*key, index));                     continue;                 }+                // Off-screen cull (MapLibre's bucket cull equivalent): a resident tile the+                // viewport cannot see issues no flat draws — see `culled_flat_draws`. Symbols+                // are deliberately NOT culled: placement dedup may have crowned this tile's+                // copy of a border label, so the deferred symbol job above still runs.+                if let Some(tile) = self.tiles.get(key) {+                    let skipped = culled_flat_draws(tile, index, camera);+                    if skipped > 0 {+                        culled += skipped;+                        continue;+                    }+                }                 // Copy the draw's inputs out, then issue them through the owned `device`                 // clone: `record_symbol` above takes `&mut self`, so this path must not-                // hold a `self.tiles` borrow either. Draws read from the tile's pooled-                // buffers (bound once per tile below), so only the pool pair plus the-                // slice's firstIndex ride here.+                // hold a `self.tiles` borrow either.                 draws.clear();                 if let Some(tile) = self.tiles.get(key) {                     let pool = match layer.kind {-                        LayerKind::Fill => tile.flat.as_ref().map(|(v, i)| (v.buffer, i.buffer)),-                        LayerKind::Line => tile.lines.as_ref().map(|(v, i)| (v.buffer, i.buffer)),+                        LayerKind::Fill => tile+                            .flat+                            .as_ref()+                            .map(|(v, vo, i, io)| (*v, *vo, *i, *io)),+                        LayerKind::Line => tile+                            .lines+                            .as_ref()+                            .map(|(v, vo, i, io)| (*v, *vo, *i, *io)),                         LayerKind::Symbol => None,                     };-                    let Some((pool_vbuf, pool_ibuf)) = pool else {+                    let Some((pool_vbuf, pool_voff, pool_ibuf, pool_ioff)) = pool else {                         // No pool means no mesh of this format packed — nothing to draw.                         // (Symbols never take this path; see the deferred arm above.)                         if layer.kind == LayerKind::Symbol {@@ -344,7 +335,9 @@ impl Renderer {                             tile.y,                             mesh.kind,                             pool_vbuf,+                            pool_voff,                             pool_ibuf,+                            pool_ioff,                             mesh.first_index,                             mesh.index_count,                             mesh.color_override,@@ -357,24 +350,18 @@ impl Renderer {                 // (owned by WS-B's `line.frag`) ignores `morph.x`, so road casings stay crisp                 // while the fill fades — the fade reads as the flat basemap ramping in.                 let tile_fade = tile_alpha.get(key).copied().unwrap_or(1.0);-                for &(tz, tx, ty, kind, vbuf, ibuf, first_index, count, color_override, lane) in-                    draws.iter()+                for &(tz, tx, ty, kind, vbuf, voff, ibuf, ioff, first_index, count, color_override, lane)+                    in draws.iter()                 {+                    // One bind per pipeline no matter how the kinds interleave across layers+                    // (`BindState` dedups for the frame).                     if bound != Some(kind) {-                        let pipeline = match kind {-                            LayerKind::Fill if globe => self.pipelines.fill_globe,-                            LayerKind::Fill => self.pipelines.fill,-                            LayerKind::Line if globe => self.pipelines.line_globe,-                            LayerKind::Line => self.pipelines.line,-                            // Symbols never take this path (drawn above); this arm is-                            // unreachable but the match must stay exhaustive.-                            LayerKind::Symbol => continue,+                        let Some(pipeline) = flat_pipeline(self, kind, globe) else {+                            // Symbols never take this path (drawn deferred); the match stays+                            // exhaustive without panicking.+                            continue;                         };-                        device.cmd_bind_pipeline(-                            command_buffer,-                            vk::PipelineBindPoint::GRAPHICS,-                            pipeline,-                        );+                        binds.bind_pipeline(&device, command_buffer, pipeline);                         bound = Some(kind);                     } @@ -450,12 +437,12 @@ impl Renderer {                         0,                         push.as_bytes(),                     );-                    device.cmd_bind_vertex_buffers(command_buffer, 0, &[vbuf], &[0]);+                    device.cmd_bind_vertex_buffers(command_buffer, 0, &[vbuf], &[voff]);                     // Uint32 rather than Uint16: a dense z14 tile can exceed 65535 vertices in                     // one layer, and overflowing folds geometry back on itself rather than                     // failing loudly. Indices are rebased to absolute at upload, so the slice                     // draws from its firstIndex inside the shared pool.-                    device.cmd_bind_index_buffer(command_buffer, ibuf, 0, vk::IndexType::UINT32);+                    device.cmd_bind_index_buffer(command_buffer, ibuf, ioff, vk::IndexType::UINT32);                     device.cmd_draw_indexed(command_buffer, count, 1, first_index, 0, 0);                     submitted += 1;                 }@@ -473,6 +460,8 @@ impl Renderer {             &accepted,             &mut bound,             &mut submitted,+            &mut culled,+            &mut binds,             &device,             flat_start,             globe,
library/map/src/main/rust/src/vulkan/renderer/record_arrows.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_arrows.rs b/library/map/src/main/rust/src/vulkan/renderer/record_arrows.rsnew file mode 100644index 0000000000..dc84d697da--- /dev/null+++ b/library/map/src/main/rust/src/vulkan/renderer/record_arrows.rs@@ -0,0 +1,161 @@+//! Lane turn arrows: per-frame triangle builds through the fill pipeline.+//+// File-length split from `record_extra.rs`: `record_arrows` and its `draw_fill_batch`+// helper live here so that file stays under the 500-line lint. The sequence itself is+// unchanged.+use super::fog::tile_offscreen;+use super::bind_state::BindState;+use super::{argb_to_rgba, Renderer, ARROW_COLOR, ARROW_DP};+use crate::camera::Camera;+use crate::style::Layer;+use crate::vulkan::pipeline::{Push, MORPH_NONE};+use ash::vk;++impl Renderer {+    /// Draw the per-lane turn arrows: one glyph per marked lane, bent by the manoeuvre the lane+    /// leads into 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 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.+    pub(super) unsafe fn record_arrows(+        &mut self,+        command_buffer: vk::CommandBuffer,+        camera: &Camera,+        layers: &[Layer],+        submitted: &mut usize,+        culled: &mut usize,+        binds: &mut BindState,+    ) {+        // 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(carriageway) = crate::style::road_carriageway_layer(layers) else {+            return;+        };+        let floor = camera.zoom.floor().clamp(0.0, 22.0) as u8;+        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;+        // Every glyph tessellates to the same vertex count whatever angle it bends through, so a+        // tile's buffer is sized exactly once up front and never grows.+        let verts_per_arrow = crate::tile::arrow::ARROW_VERTS * 2;+        // 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.+        let mut batches: Vec<([f32; 16], Vec<f32>)> = Vec::new();+        for tile in self.tiles.values() {+            if tile.arrows.is_empty() {+                continue;+            }+            // Same off-screen cull as the flat layer loop (see `tile_offscreen`).+            if tile_offscreen(camera, tile.z, tile.x, tile.y) {+                *culled += tile.arrows.len();+                continue;+            }+            let span = camera.tile_span_px(tile.z);+            if span <= 0.0 {+                continue;+            }+            let scale = ARROW_DP * density / span; // tile-local 0..1 units per unit-arrow coord+                                                   // What turns the arrows' ground setback into this tile's units. A property of the tile+                                                   // and not of the camera, so the arrows stay the same distance behind the junction at+                                                   // every zoom — see `arrow::tile_local_per_metre`.+            let per_metre = crate::tile::arrow::tile_local_per_metre(tile.z, tile.y);+            let mut verts: Vec<f32> = Vec::with_capacity(tile.arrows.len() * verts_per_arrow);+            for a in &tile.arrows {+                // Sideways onto the lane, perpendicular to the road heading (not the glyph's+                // turn). `lane_centre` measures from the middle of the road out, in lane widths,+                // and already accounts for the half of the carriageway this direction occupies+                // under the tile's driving convention — an arrow that does not sit between the+                // dividers the markings drew is worse than no arrow at all.+                let lateral = crate::tile::arrow::lane_centre(a) * lane_px;+                crate::tile::arrow::arrow_verts(a, scale, lateral / span, per_metre, &mut verts);+            }+            if !verts.is_empty() {+                batches.push((camera.tile_to_clip(tile.z, tile.x, tile.y), verts));+            }+        }+        if batches.is_empty() {+            return;+        }+        let color = argb_to_rgba(ARROW_COLOR);+        for (tile_to_clip, verts) in batches {+            let indices: Vec<u32> = (0..(verts.len() / 2) as u32).collect();+            let push = Push {+                tile_to_clip,+                color,+                line: [0.0; 4],+                misc: [0.0, 0.0, 0.0, camera.time_seconds],+                morph: MORPH_NONE,+            };+            self.draw_fill_batch(command_buffer, &verts, &indices, &push, submitted, binds);+        }+    }++    /// Draw one batch through the fill pipeline (colour from the push constant, no descriptor+    /// set), suballocating its vertices and indices from this frame's [`ScratchRing`].+    ///+    /// The arrow twin of [`draw_symbol_batch`], and now allocates the same way. It previously+    /// created two `Buffer`s per call and pushed them onto [`Renderer::transients`] to retire+    /// on the frames-in-flight grace count, which was merely wasteful while it was the symbol+    /// path's twin — but it is called **once per batch per frame** from+    /// [`record_arrows`](Self::record_arrows), and `transients` is a wake reason for the host's+    /// on-demand frame loop (see [`needs_frame`](Self::needs_frame)). A vec refilled every+    /// frame never drains, so the loop would wake itself forever and pin the map at 60fps with+    /// nothing changing. The ring has no such feedback: it is reset wholesale against the+    /// frame fence, so a draw leaves nothing behind for the next frame to notice.+    ///+    /// Off the drawn path today — `style::LANE_RENDERING` is false, so no arrows are built or+    /// drawn — which is precisely why this had to be fixed now rather than when someone+    /// switches lane rendering on and finds the phone hot again.+    pub(super) unsafe fn draw_fill_batch(+        &mut self,+        command_buffer: vk::CommandBuffer,+        vertices: &[f32],+        indices: &[u32],+        push: &Push,+        submitted: &mut usize,+        binds: &mut BindState,+    ) {+        let frame_index = self.frame_index;+        let device = &self.context.device;+        // Disjoint field borrows, for the same reason `draw_symbol_batch` takes them: cloning+        // `ash::Device` copies its whole function-pointer table, and this is a per-draw path.+        let Some((vbuf, voffset)) = self.scratch[frame_index].push(+            &self.context.instance,+            self.context.physical_device,+            device,+            vertices,+        ) else {+            return;+        };+        let Some((ibuf, ioffset)) = self.scratch[frame_index].push(+            &self.context.instance,+            self.context.physical_device,+            device,+            indices,+        ) else {+            return;+        };+        // Arrows share the fill pipeline with the layer loop: usually already bound,+        // so consecutive arrow batches cost no bind at all.+        binds.bind_pipeline(device, command_buffer, self.pipelines.fill);+        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, &[vbuf], &[voffset]);+        device.cmd_bind_index_buffer(command_buffer, ibuf, ioffset, vk::IndexType::UINT32);+        device.cmd_draw_indexed(command_buffer, indices.len() as u32, 1, 0, 0, 0);+        *submitted += 1;+    }+}
library/map/src/main/rust/src/vulkan/renderer/record_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra.rsindex bab3375764..5f736a07f3 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs@@ -1,6 +1,7 @@-use super::fog::{apply_fog, fog_factor};+use super::fog::{apply_fog, fog_factor, tile_offscreen};+use super::bind_state::BindState; use super::{-    anchors_for, argb_to_rgba, scale_alpha, Overlay, Renderer, UserPuck, ARROW_COLOR, ARROW_DP,+    anchors_for, argb_to_rgba, scale_alpha, Overlay, Renderer, UserPuck,     BUILDINGS_DRAW_MIN_ZOOM, IDENTITY, PUCK_COLOR, PUCK_CONE_DP, PUCK_CONE_HALF_STROKE_DP,     PUCK_DOT_DP, PUCK_QUAD_DP, PUCK_RIM_DP, QUAD_INDICES, SCRIM_COLOR, TRAFFIC_WIDTH_DP, };@@ -42,6 +43,8 @@ impl Renderer {         ordered: &[u64],         fog: u32,         submitted: &mut usize,+        culled: &mut usize,+        binds: &mut BindState,         // This frame's globe flag: globe ribbon pipeline + sphere push below, or         // the flat path bit-identically above.         globe: bool,@@ -49,7 +52,6 @@ impl Renderer {         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;@@ -57,8 +59,19 @@ impl Renderer {             if tile.carriageways.is_empty() {                 continue;             }-            // The ribbon pool, bound at offset 0; each road draws its slice by firstIndex.-            let Some((pool_v, pool_i)) = tile.ribbons.as_ref().map(|(v, i)| (v.buffer, i.buffer))+            // Same off-screen cull as the flat layer loop (see `tile_offscreen`):+            // carriageways are per-tile ground cover, not symbols.+            if tile_offscreen(camera, tile.z, tile.x, tile.y) {+                *culled += tile.carriageways.len();+                continue;+            }+            // The ribbon pool, bound at its offsets; each road draws its slice by+            // firstIndex. Fresh pools bind at 0, arena ranges at their committed offsets.+            // Handles are raw `vk::Buffer`s now (see `ResidentTile`): copy by value.+            let Some((pool_v, pool_vo, pool_i, pool_io)) = tile+                .ribbons+                .as_ref()+                .map(|(v, vo, i, io)| (*v, *vo, *i, *io))             else {                 continue;             };@@ -81,18 +94,17 @@ impl Renderer {                 if half_width_px <= 0.0 {                     continue;                 }-                if !bound {-                    device.cmd_bind_pipeline(-                        command_buffer,-                        vk::PipelineBindPoint::GRAPHICS,-                        if globe {-                            self.pipelines.ribbon_globe-                        } else {-                            self.pipelines.ribbon-                        },-                    );-                    bound = true;-                }+                // One bind for the whole pass no matter how many tiles carry roads:+                // every road draws through the same ribbon pipeline.+                binds.bind_pipeline(+                    device,+                    command_buffer,+                    if globe {+                        self.pipelines.ribbon_globe+                    } else {+                        self.pipelines.ribbon+                    },+                );                 // The asphalt only. The markings are the shader's own palette, because they have                 // to match the white it antialiases them against. Distance-fogged like the                 // flat layers so carriageways haze with the ground under tilt.@@ -144,8 +156,8 @@ impl Renderer {                     0,                     push.as_bytes(),                 );-                device.cmd_bind_vertex_buffers(command_buffer, 0, &[pool_v], &[0]);-                device.cmd_bind_index_buffer(command_buffer, pool_i, 0, vk::IndexType::UINT32);+                device.cmd_bind_vertex_buffers(command_buffer, 0, &[pool_v], &[pool_vo]);+                device.cmd_bind_index_buffer(command_buffer, pool_i, pool_io, vk::IndexType::UINT32);                 device.cmd_draw_indexed(                     command_buffer,                     road.index_count,@@ -159,147 +171,6 @@ impl Renderer {         }     } -    /// Draw the per-lane turn arrows: one glyph per marked lane, bent by the manoeuvre the lane-    /// leads into 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 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.-    pub(super) unsafe fn record_arrows(-        &mut self,-        command_buffer: vk::CommandBuffer,-        camera: &Camera,-        layers: &[Layer],-        submitted: &mut usize,-    ) {-        // 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(carriageway) = crate::style::road_carriageway_layer(layers) else {-            return;-        };-        let floor = camera.zoom.floor().clamp(0.0, 22.0) as u8;-        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;-        // Every glyph tessellates to the same vertex count whatever angle it bends through, so a-        // tile's buffer is sized exactly once up front and never grows.-        let verts_per_arrow = crate::tile::arrow::ARROW_VERTS * 2;-        // 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.-        let mut batches: Vec<([f32; 16], Vec<f32>)> = Vec::new();-        for tile in self.tiles.values() {-            if tile.arrows.is_empty() {-                continue;-            }-            let span = camera.tile_span_px(tile.z);-            if span <= 0.0 {-                continue;-            }-            let scale = ARROW_DP * density / span; // tile-local 0..1 units per unit-arrow coord-                                                   // What turns the arrows' ground setback into this tile's units. A property of the tile-                                                   // and not of the camera, so the arrows stay the same distance behind the junction at-                                                   // every zoom — see `arrow::tile_local_per_metre`.-            let per_metre = crate::tile::arrow::tile_local_per_metre(tile.z, tile.y);-            let mut verts: Vec<f32> = Vec::with_capacity(tile.arrows.len() * verts_per_arrow);-            for a in &tile.arrows {-                // Sideways onto the lane, perpendicular to the road heading (not the glyph's-                // turn). `lane_centre` measures from the middle of the road out, in lane widths,-                // and already accounts for the half of the carriagewa

Diff truncated.