Modern Apps git

← Modern-Apps.git

library: draw the map on a render thread, not the main thread (#maprender)

Commit
ca8dfe28f91174a0aafd500e1a7091d277da214b
Author
Vayun Mathur <[email protected]>
When
2026-11-13 20:16 UTC (22 days ago)
Parents
57b0e93
Owner report: "visibly laggy when moving around and I sometimes get
'Maps isn't responding'".

Root cause: every MapNative call ran on the main thread. The whole
frame (upload drain, tile selection, label placement, symbol emission,
command recording, the fence wait, the swapchain acquire and the
present) ran inside the Choreographer callback, so each frame's native
time was taken straight out of Compose's budget for layout, drawing and
input. That is the visible lag while panning: the UI thread alternates
between recording Vulkan and running Compose, and both miss vsync.
Worse, the slow, blocking native calls ran there too:
- `create`: Vulkan bring-up, every pipeline compiled, and the SDF glyph
  atlas built from the bundled fonts. Measured on the host
  (tests/frame_cpu_bench.rs, create_time_cpu_work): the atlas alone is
  1350 ms on a Genoa core, so 3-5 s on a phone core - a near-ANR on
  every cold map open, before Vulkan work is even counted.
- `detach`/`trimMemory`: vkDeviceWaitIdle.
- swapchain rebuild: vkDeviceWaitIdle plus a recompile of every
  pipeline, inside a frame.
- `setMoonTextures`: a ~36 MB upload.
- tap picks: a one-shot id-buffer render plus vkQueueWaitIdle.
- the legacy-cache cleanup (recursive delete) in `cacheDir`.
Any of those stretching (thermal throttling, a slow driver, a busy GPU)
was a multi-second main-thread stall.

What changed:
- `MapRenderThread`: one process-wide, display-priority thread (lazily
  started, so JVM tests never start it). Tasks run in submission order,
  which keeps the native single-threaded contract (`handle_mut` hands
  out an unlocked &mut) exactly as before, on a thread that may block.
  `call` gives bounded synchronous answers and runs inline when
  re-entered.
- `MapNativeLink`: the only code that crosses threads. The render
  thread owns the native handle and the region-mask retry; the main
  thread owns `attached` plus a generation counter so a frame or create
  result that outlives its surface is dropped.
- `SurfaceMapRenderer`: public API and the on-demand Choreographer loop
  are unchanged and still main-thread. A vsync now reads the camera
  snapshot (Compose state stays on the main thread) and posts one frame;
  the render thread draws it, refreshes the tilt pivot, retries the
  region mask and asks `nextFrameDelayMillis`, and posts one result
  back. A vsync while a frame is still drawing marks it owed and the
  newest camera is drawn the moment the frame lands, so a slow frame
  costs latency, never a backlog. Setters pack their arrays on main
  and post the native call; picks wait at most 250 ms (past it the tap
  is a miss and maps' CPU hit-test runs); `renderFrame()` waits at most
  500 ms; `detachSurface` waits at most 1 s (the native side holds its
  own ANativeWindow reference, so returning early can only fail the
  late teardown's frame, never crash).
- `attachSurface` queues `create` and then the deferred-state replay
  behind it; `renderState` flips to Rendering/Unavailable when create
  lands. VulkanMapSurface releases its Surface on a late failure via
  the new internal `onStartFailed`. A throwing create counts as failed.
- The frame-stats overlay reads step times through the render thread.

Measured effect (main thread per frame): before, the full native frame
(every step on the overlay, plus any fence/acquire wait); after, one
camera-snapshot read and one queue post (microseconds), independent of
scene complexity. Main-thread stalls removed: cold create (>=1.35 s CPU
on host, before Vulkan), device-idle waits in detach/trim/rebuild, the
Moon upload, and the pick's queue-idle wait (now bounded at 250 ms).
On-device frame times can be read with the existing FrameStatsOverlay.

Verified: new MapRenderThreadTest (order, single thread, bounded call,
re-entrancy, survives a throwing task, no thread use without a
surface); existing FrameLoopWakeTest/RendererStateTest contracts are
kept (no surface means no native call and no thread). Rust bridge docs
updated for the new threading. Full gradle checks run in the container.

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 596b27df6b..0c85f89d4e 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@@ -42,7 +42,7 @@ private val COUNT_STEPS = setOf("eout", "phit", "cull", "bind", "fcan", "uall")  * last frame's ms, polled from [MapNative.lastFrameStepTimesNanos].  *  * Off by default ([enabled]) so release pays nothing: no poll, no composition, no JNI. The- * poll runs at ~3 Hz through [renderer]'s live handle and never touches the frame loop — it+ * poll runs at ~3 Hz through [renderer]'s render thread and never touches the frame loop — it  * reads the native copy rather than asking for a frame, so the overlay cannot keep the map  * awake or change its pacing.  *@@ -58,16 +58,8 @@ fun FrameStatsOverlay(     var times by remember { mutableStateOf(LongArray(0)) }     LaunchedEffect(renderer) {         while (isActive) {-            val handle = renderer.handle-            times = if (handle != 0L) {-                try {-                    MapNative.lastFrameStepTimesNanos(handle)-                } catch (_: Throwable) {-                    LongArray(0)-                }-            } else {-                LongArray(0)-            }+            // Native state is read on the render thread; the answer lands back on main.+            renderer.queryStepTimes { times = it }             delay(POLL_MILLIS)         }     }
library/map/src/main/java/com/vayunmathur/library/map/MapNativeLink.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNativeLink.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNativeLink.ktnew file mode 100644index 0000000000..b1a762613d--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNativeLink.kt@@ -0,0 +1,210 @@+package com.vayunmathur.library.map++import android.view.Surface+import com.vayunmathur.library.log.Log++/**+ * The link from one [SurfaceMapRenderer] to its native renderer on [MapRenderThread].+ *+ * Owns the two halves of "is there a native renderer": the main thread's view ([attached],+ * [generation]) and the render thread's ([nativeHandle], [region]), and is the only code that+ * crosses between them. Every native call goes through [post], [query] or one of the+ * lifecycle tasks here, so all of them run on the render thread in submission order — the+ * native side's single-threaded contract — and every result that comes back is checked+ * against [generation] so a frame or create that outlived its surface is dropped.+ *+ * Split from SurfaceMapRenderer.kt (FileLength) along the thread boundary.+ */+internal class MapNativeLink {++    /**+     * The native handle, **render thread only**: written by the create/destroy tasks and read+     * by every task after them. Never read on the main thread, which is what keeps the native+     * single-threaded contract without a lock.+     */+    private var nativeHandle = 0L++    /** The selected region mask as the render thread tracks it (render thread only). */+    private val region = NativeRegionMask()++    /**+     * Whether a native renderer exists or is being created, on the main thread's view: set by+     * [create], cleared by [destroy] and by a failed create ([createFailed]). Native calls are+     * gated on this rather than on a handle, so a setter issued between [create] and the+     * create finishing is queued behind it, not dropped.+     */+    var attached = false+        private set++    /**+     * Bumped on every create and destroy (main thread), so a result that crosses back after+     * the surface it belonged to is gone is recognised and ignored.+     */+    var generation = 0+        private set++    /**+     * Run [block] with the live native handle on the render thread, after every call issued+     * before it. Dropped when not [attached]; skipped on the render thread after a failed create.+     */+    fun post(block: (Long) -> Unit) {+        if (!attached) return+        MapRenderThread.post {+            val h = nativeHandle+            if (h != 0L) block(h)+        }+    }++    /** As [post], but waits for the answer, at most [timeoutMillis]; [fallback] otherwise. */+    fun <T> query(timeoutMillis: Long, fallback: T, block: (Long) -> T): T {+        if (!attached) return fallback+        return MapRenderThread.call(timeoutMillis, fallback) {+            val h = nativeHandle+            if (h != 0L) block(h) else fallback+        }+    }++    /**+     * Queue `MapNative.create` on [surface]; [onCreated] gets the handle (0 on failure) back on+     * the main thread, unless a [destroy] overtook it. [cacheDir] and [localPath] are resolved+     * on the render thread because both touch the disk.+     */+    @Suppress("LongParameterList")+    fun create(+        surface: Surface,+        cacheDir: () -> String,+        localPath: () -> String?,+        widthPx: Int,+        heightPx: Int,+        dark: Boolean,+        muted: Boolean,+        onCreated: (Long) -> Unit,+    ) {+        attached = true+        val created = ++generation+        MapRenderThread.post {+            // A throw (an unlinked symbol, a disk error resolving the paths) is a failed start,+            // not a lost answer: without a reply the loop would keep dispatching empty frames.+            val h = try {+                MapNative.create(surface, cacheDir(), localPath(), widthPx, heightPx, dark, muted)+            } catch (t: Throwable) {+                Log.error("MapNativeLink", "native create threw", t)+                0L+            }+            nativeHandle = h+            MapRenderThread.toMain { if (created == generation) onCreated(h) }+        }+    }++    /** The create answered 0: nothing will draw, so stop queueing native calls. */+    fun createFailed() {+        attached = false+    }++    /**+     * Destroy the native renderer on the render thread and wait for it, at most [waitMillis].+     * Past the bound it returns anyway: the native side holds its own reference on the window,+     * so a caller releasing its `Surface` then can only make the late teardown's last frame+     * fail, never crash — while an unbounded wait could hold the main thread hostage.+     */+    fun destroy(waitMillis: Long) {+        if (!attached) return+        attached = false+        generation+++        MapRenderThread.call(waitMillis, Unit) {+            val h = nativeHandle+            nativeHandle = 0L+            region.reset()+            if (h != 0L) MapNative.destroy(h)+        }+    }++    /** Select the region mask on the render thread (see [NativeRegionMask]). */+    fun selectRegion(regionId: Long?) = post { h -> region.select(h, regionId) }++    /**+     * Draw one frame on the render thread from a snapshot read on the main thread; [onDone]+     * gets the result back on the main thread, unless a [destroy] overtook it.+     */+    fun frame(+        snapshot: FrameSnapshot,+        density: Float,+        frameTimeNanos: Long,+        pivotWanted: Boolean,+        onDone: (FrameResult) -> Unit,+    ) {+        val issued = generation+        MapRenderThread.post {+            val h = nativeHandle+            val result = if (h == 0L) FrameResult.NONE else drawFrame(h, snapshot, density, frameTimeNanos, pivotWanted, region)+            MapRenderThread.toMain { if (issued == generation) onDone(result) }+        }+    }++    /** One frame drawn synchronously, for a host driving its own loop; bounded by [timeoutMillis]. */+    fun frameNow(+        snapshot: FrameSnapshot,+        density: Float,+        frameTimeNanos: Long,+        pivotWanted: Boolean,+        timeoutMillis: Long,+    ): FrameResult = query(timeoutMillis, FrameResult.NONE) { h ->+        drawFrame(h, snapshot, density, frameTimeNanos, pivotWanted, region)+    }++    /** The native per-step frame times, delivered on the main thread; empty with no renderer. */+    fun stepTimes(onResult: (LongArray) -> Unit) {+        if (!attached) {+            onResult(LongArray(0))+            return+        }+        MapRenderThread.post {+            val h = nativeHandle+            val times = if (h != 0L) MapNative.lastFrameStepTimesNanos(h) else LongArray(0)+            MapRenderThread.toMain { onResult(times) }+        }+    }+}++/**+ * The selected region mask as the render thread sees it: the id to mask and whether it has+ * been matched to resident tiles yet.+ *+ * The match needs the region's tiles to be resident, and a selection usually arrives before+ * they are — tapping a city label recentres the map, so the tiles under the new camera are+ * still in flight. So an unresolved id is retried after every frame until it lands rather than+ * being dropped. Owned by the render thread, so the retry runs right after the frame that may+ * have landed the tiles, with no main-thread hop.+ */+internal class NativeRegionMask {+    private var id: Long? = null++    /** True while a nonzero id is selected and no resident tile carries it yet. */+    var pending = false+        private set++    /** Select [regionId] (`null`/`0` clears) and try to apply it at once. */+    fun select(handle: Long, regionId: Long?) {+        id = regionId+        pending = true+        apply(handle)+    }++    /** Apply the selected mask; leaves [pending] set while its tiles have not landed. */+    fun apply(handle: Long) {+        val selected = id+        if (selected == null || selected == 0L) {+            MapNative.clearRegionMask(handle)+            pending = false+            return+        }+        // A nonzero answer once a resident tile carries the id; `0` means not yet.+        pending = MapNative.setRegionMask(handle, selected) == 0L+    }++    /** Forget the selection, for a renderer that has been destroyed. */+    fun reset() {+        id = null+        pending = false+    }+}
library/map/src/main/java/com/vayunmathur/library/map/MapRenderThread.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapRenderThread.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapRenderThread.ktnew file mode 100644index 0000000000..0b2029a79e--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapRenderThread.kt@@ -0,0 +1,121 @@+package com.vayunmathur.library.map++import android.os.Handler+import android.os.Looper+import android.os.Process+import com.vayunmathur.library.log.Log+import java.util.concurrent.CountDownLatch+import java.util.concurrent.ExecutorService+import java.util.concurrent.Executors+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference++/**+ * The one thread every [MapNative] call runs on.+ *+ * The native renderer is single-threaded by contract — `bridge::handle_mut` hands out a plain+ * `&mut` with no lock behind it — so every call into it must come from one thread. That thread+ * used to be the main thread: the whole frame (upload drain, tile selection, label placement,+ * command recording, the fence wait, the swapchain acquire and the present) ran on the+ * Choreographer callback, and so did `create` (Vulkan bring-up, pipeline compile, the glyph+ * atlas), `destroy` and `trimMemory` (`vkDeviceWaitIdle`), a swapchain rebuild+ * (`vkDeviceWaitIdle` plus a recompile of every pipeline), the 36 MB Moon upload and the tap+ * pick (a one-shot render plus `vkQueueWaitIdle`). Every millisecond of that was a millisecond+ * Compose could not lay out, draw or take input in, which is what "visibly laggy when moving+ * around" was made of, and any of the waits stretching was a "Maps isn't responding" dialog.+ *+ * Now the main thread only decides *when* to draw (the on-demand Choreographer loop in+ * [SurfaceMapRenderer] is unchanged) and *what* to draw (it reads the camera snapshot), and+ * hands the work here. Calls are serialised in submission order on one dedicated thread at+ * display priority, so the single-threaded contract holds exactly as before, only on a thread+ * that is allowed to block.+ *+ * One thread for the process rather than one per renderer: renderers come and go with+ * navigation, a shared queue needs no lifetime management, and a car surface and a phone+ * surface drawing at once simply take turns. Created lazily, so a process that never attaches+ * a surface — every JVM unit test — never starts it.+ */+internal object MapRenderThread {++    private const val TAG = "MapRenderThread"++    private val executor: ExecutorService by lazy {+        Executors.newSingleThreadExecutor { task ->+            Thread(+                {+                    // Display priority, like the platform's own RenderThread: frame work must+                    // not queue behind background tile decode or image loading.+                    try {+                        Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY)+                    } catch (_: Throwable) {+                        // Not fatal: the thread still runs at default priority.+                    }+                    task.run()+                },+                "MapRender",+            ).apply { isDaemon = true }+        }+    }++    private val main: Handler by lazy { Handler(Looper.getMainLooper()) }++    /** The executor's thread once it has run anything; used to make [call] re-entrant. */+    @Volatile+    private var thread: Thread? = null++    /** Run [task] on the render thread after everything already queued. Never blocks. */+    fun post(task: () -> Unit) {+        executor.execute {+            thread = Thread.currentThread()+            try {+                task()+            } catch (t: Throwable) {+                // A throwing task must not kill the only thread the renderer has.+                Log.error(TAG, "render-thread task failed", t)+            }+        }+    }++    /** Run [task] on the main thread, for results that feed main-thread state. */+    fun toMain(task: () -> Unit) {+        main.post(task)+    }++    /**+     * Run [task] on the render thread and wait for its result, at most [timeoutMillis].+     *+     * For the few calls whose callers need an answer synchronously (a tap pick, a host that+     * drives its own frame loop, a detach that must not return before the native renderer is+     * gone). The wait is bounded: past it the caller gets [fallback] and the task still runs+     * later, so the main thread can be delayed by at most the bound, never frozen. Called on+     * the render thread itself it runs [task] inline rather than deadlocking on its own queue.+     */+    fun <T> call(timeoutMillis: Long, fallback: T, task: () -> T): T {+        if (Thread.currentThread() === thread) return task()+        val result = AtomicReference<Any?>(Unset)+        val done = CountDownLatch(1)+        post {+            try {+                result.set(task())+            } finally {+                done.countDown()+            }+        }+        val finished = try {+            done.await(timeoutMillis, TimeUnit.MILLISECONDS)+        } catch (_: InterruptedException) {+            Thread.currentThread().interrupt()+            false+        }+        if (!finished) {+            Log.error(TAG, "render thread did not answer within ${timeoutMillis}ms; using the fallback")+            return fallback+        }+        val value = result.get()+        @Suppress("UNCHECKED_CAST")+        return if (value === Unset) fallback else value as T+    }++    /** Marker for "the task threw before producing a value". */+    private object Unset+}
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapFrame.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapFrame.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapFrame.ktnew file mode 100644index 0000000000..4a4914f6d8--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapFrame.kt@@ -0,0 +1,125 @@+package com.vayunmathur.library.map++/*+ * The frame half of [SurfaceMapRenderer] that runs on [MapRenderThread]: the camera snapshot+ * the main thread hands over, the one native frame drawn from it, and what comes back.+ *+ * Split out so SurfaceMapRenderer.kt stays under the FileLength limit, and so the boundary is+ * visible in one place: everything in [FrameSnapshot] is read on the main thread (the Compose+ * camera is main-thread state), everything in [drawFrame] runs on the render thread (the+ * native renderer is single-threaded), and [FrameResult] is all that crosses back.+ */++/** Camera + viewport + globe state for one frame, read on the main thread. */+internal data class FrameSnapshot(+    val position: CameraPosition,+    val widthDp: Float,+    val heightDp: Float,+    val globe: Boolean,+    val moon: Boolean,+) {+    /** True when this frame would draw anything different from [previous]. */+    fun hasChangedSince(previous: FrameSnapshot?): Boolean = previous == null || this != previous++    /**+     * Whether the Compose camera's tilt pivot must be refreshed from the resident heightmaps+     * after this frame: only under pitch on the flat path, the renderer's own gate+     * (`Renderer::render` resolves its pivot exactly when `pitch > 0` off-globe).+     */+    val wantsPivot: Boolean get() = position.pitch > 0.0 && !globe+}++/**+ * What one render-thread frame reports back to the main thread's loop.+ *+ * @property drawn the frame presented (false: no renderer, swapchain rebuilt, or no image).+ * @property pivotDp the refreshed tilt pivot, or NaN when not asked for.+ * @property regionPending a region mask is selected but its tiles have not landed yet.+ * @property nextDelayMillis [MapNative.nextFrameDelayMillis] after the frame.+ */+internal data class FrameResult(+    val drawn: Boolean,+    val pivotDp: Double,+    val regionPending: Boolean,+    val nextDelayMillis: Long,+) {+    companion object {+        /** No native renderer behind the frame (create failed, or a detach overtook it). */+        val NONE = FrameResult(drawn = false, pivotDp = Double.NaN, regionPending = false, nextDelayMillis = -1L)+    }+}++/**+ * Draw one frame on the render thread: the frame itself, then the tilt pivot and region-mask+ * retry that used to run on the main thread right after it, then the native "when next"+ * answer, so the main thread gets everything it schedules on in one hop.+ */+internal fun drawFrame(+    handle: Long,+    snapshot: FrameSnapshot,+    density: Float,+    frameTimeNanos: Long,+    pivotWanted: Boolean,+    region: NativeRegionMask,+): FrameResult {+    val position = snapshot.position+    val drawn = MapNative.render(+        handle,+        position.target.longitude.toFloat(),+        position.target.latitude.toFloat(),+        position.zoom.toFloat(),+        position.bearing.toFloat(),+        position.pitch.toFloat(),+        snapshot.widthDp,+        snapshot.heightDp,+        density,+        frameTimeNanos,+        snapshot.globe,+        snapshot.moon,+    )+    val pivot = if (pivotWanted) {+        MapNative.tiltPivotDp(+            handle,+            position.target.longitude.toFloat(),+            position.target.latitude.toFloat(),+            position.zoom.toFloat(),+        )+    } else {+        Double.NaN+    }+    if (region.pending) region.apply(handle)+    return FrameResult(drawn, pivot, region.pending, MapNative.nextFrameDelayMillis(handle))+}++/**+ * The Moon raster pair the host pushes for the lunar globe: converted LROC+ * color (RGBA8) + converted LDEM (RG8 packed uint16). Plain holder so the+ * renderer can remember and replay it across re-attach like every other+ * deferred state.+ */+data class MoonTextures(+    val colorRgba: ByteArray,+    val width: Int,+    val height: Int,+    val demRg: ByteArray,+    val demWidth: Int,+    val demHeight: Int,+) {+    override fun equals(other: Any?): Boolean {+        if (this === other) return true+        if (other !is MoonTextures) return false+        return width == other.width && height == other.height &&+            demWidth == other.demWidth && demHeight == other.demHeight &&+            colorRgba.contentEquals(other.colorRgba) && demRg.contentEquals(other.demRg)+    }++    override fun hashCode(): Int {+        var result = width+        result = 31 * result + height+        result = 31 * result + demWidth+        result = 31 * result + demHeight+        result = 31 * result + colorRgba.contentHashCode()+        result = 31 * result + demRg.contentHashCode()+        return result+    }+}
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.ktindex 7ef353fb99..40549971a3 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt@@ -78,8 +78,9 @@ private const val RGB_MASK = 0x00FFFFFF  * cleared. The convenience path for a host that wants one line in one colour — Android  * Auto, which has no view hierarchy to hang a Compose overlay in.  *- * Main thread, like everything else here. Not free, but paid once per route rather- * than once per frame: the native side tessellates the polyline and uploads it here,+ * Main thread, like everything else here (the stroke and upload run on the render thread).+ * Not free, but paid once per route rather than once per frame: the native side tessellates+ * the polyline and uploads it,  * and never rebuilds it — the mesh is zoom-independent, so a navigation session costs  * one tessellation however long the drive or however much the driver zooms. Setting  * the same route again does re-tessellate, so drive this from a state change rather@@ -153,15 +154,17 @@ internal fun SurfaceMapRenderer.dropTraffic() {  * own feature. `internal` because it is wired through [Projection.pickMarker] like the label  * pick, so a caller without a live renderer gets `0` rather than a dead handle.  */-internal fun SurfaceMapRenderer.tapMarkerAt(xDp: Float, yDp: Float): Long {-    val h = handle-    if (h == 0L) return 0L-    return try {-        MapNative.pickAt(h, xDp, yDp)-    } catch (_: Throwable) {-        0L+internal fun SurfaceMapRenderer.tapMarkerAt(xDp: Float, yDp: Float): Long =+    // The native pick renders the id buffer and waits for the GPU, so it runs on the render+    // thread; the tap handler waits for it, bounded, and falls back to "no pin" past the bound+    // (the host's CPU hit-test then takes over) rather than freezing the main thread.+    queryRenderThread(PICK_TIMEOUT_MILLIS, 0L) { h ->+        try {+            MapNative.pickAt(h, xDp, yDp)+        } catch (_: Throwable) {+            0L+        }     }-}  /**  * One native pick row as a [PlacedLabel], or null when the row is malformed.@@ -191,10 +194,17 @@ private const val LABEL_FIELDS = 7 private const val LABEL_FIELDS_LEGACY = 6 private const val LABEL_REGION_INDEX = 6 internal fun SurfaceMapRenderer.tapLabelsIn(box: DpRect, layerIds: Set<String>): List<PlacedLabel> {-    val h = handle-    if (h == 0L) return emptyList()+    // The placed-label snapshot is native state the frame rewrites, so it is read on the+    // render thread; parsing the rows happens back here.+    val rows = queryRenderThread(PICK_TIMEOUT_MILLIS, emptyArray<String>()) { h ->+        try {+            MapNative.pickLabels(h, box.left.value, box.top.value, box.right.value, box.bottom.value)+        } catch (_: Throwable) {+            emptyArray()+        }+    }     return try {-        MapNative.pickLabels(h, box.left.value, box.top.value, box.right.value, box.bottom.value)+        rows             .asSequence()             .map { row -> parseLabelRow(row.split('')) }             .filter { label -> label != null && (layerIds.isEmpty() || label.layerId in layerIds) }@@ -206,12 +216,11 @@ internal fun SurfaceMapRenderer.tapLabelsIn(box: DpRect, layerIds: Set<String>): }  internal fun SurfaceMapRenderer.applyRoute() {-    if (handle == 0L) return     // Drawable segments only: fewer than two points strokes nothing, and dropping them     // here keeps the native side's per-segment ranges aligned with the colours.     val drawable = routeSegments?.filter { it.points.size >= 2 }     if (drawable.isNullOrEmpty()) {-        MapNative.clearRoute(handle)+        onRenderThread { h -> MapNative.clearRoute(h) }         return     }     // Flat lon/lat pairs across every segment, plus a point count and colour per@@ -231,24 +240,19 @@ internal fun SurfaceMapRenderer.applyRoute() {             at++         }     }-    MapNative.setRoute(-        handle,-        flat,-        lengths,-        colors,-        routeStyle.width.value,-        routeStyle.casingWidth.value,-        routeStyle.casingColor.toArgb(),-    )+    val width = routeStyle.width.value+    val casingWidth = routeStyle.casingWidth.value+    val casingColor = routeStyle.casingColor.toArgb()+    // Packed here, stroked and uploaded on the render thread.+    onRenderThread { h -> MapNative.setRoute(h, flat, lengths, colors, width, casingWidth, casingColor) } }  internal fun SurfaceMapRenderer.applyRailLines() {-    if (handle == 0L) return     // Drawable segments only, like the route: fewer than two points strokes     // nothing, and dropping them keeps the native per-segment ranges aligned.     val drawable = railSegments?.filter { it.points.size >= 2 }     if (drawable.isNullOrEmpty()) {-        MapNative.clearRailLines(handle)+        onRenderThread { h -> MapNative.clearRailLines(h) }         return     }     val flat = FloatArray(drawable.sumOf { it.points.size } * 2)@@ -264,27 +268,66 @@ internal fun SurfaceMapRenderer.applyRailLines() {             at++         }     }-    MapNative.setRailLines(-        handle,-        flat,-        lengths,-        colors,-        railStyle.width.value,-        railStyle.casingWidth.value,-        railStyle.casingColor.toArgb(),-    )+    val width = railStyle.width.value+    val casingWidth = railStyle.casingWidth.value+    val casingColor = railStyle.casingColor.toArgb()+    onRenderThread { h -> MapNative.setRailLines(h, flat, lengths, colors, width, casingWidth, casingColor) } }  internal fun SurfaceMapRenderer.applyTraffic() {-    if (handle == 0L) return     val speeds = trafficSpeeds-    if (speeds == null) {-        MapNative.clearTraffic(handle)-    } else {-        MapNative.setTrafficSpeeds(handle, speeds.first, speeds.second)+    onRenderThread { h ->+        if (speeds == null) {+            MapNative.clearTraffic(h)+        } else {+            MapNative.setTrafficSpeeds(h, speeds.first, speeds.second)+        }+    }+}++internal fun SurfaceMapRenderer.applyUserPuck() {+    val puck = userPuck+    onRenderThread { h ->+        if (puck == null) {+            MapNative.clearUserPuck(h)+        } else {+            MapNative.setUserPuck(+                h,+                puck.position.longitude.toFloat(),+                puck.position.latitude.toFloat(),+                puck.bearing ?: 0f,+                puck.bearing != null,+            )+        }+    }+}++internal fun SurfaceMapRenderer.applyMarkers() {+    val pins = markers+    if (pins.isEmpty()) {+        onRenderThread { h -> MapNative.clearMarkers(h) }+        return+    }+    val packed = packMapMarkers(pins)+    onRenderThread { h -> MapNative.setMarkers(h, packed.ids, packed.lonLat, packed.icons, packed.labels) }+}++internal fun SurfaceMapRenderer.applyVehicles() {+    val vs = vehicles+    if (vs.isEmpty()) {+        onRenderThread { h -> MapNative.clearVehicles(h) }+        return     }+    val packed = packVehicles(vs)+    onRenderThread { h -> MapNative.setVehicles(h, packed.ids, packed.lonLat, packed.icons, packed.colors) } } +/**+ * How long a tap waits for the render thread's pick: one in-flight frame plus the pick's own+ * one-shot render. Past it the tap resolves as a miss and the host's fallbacks run.+ */+internal const val PICK_TIMEOUT_MILLIS = 250L+ /**  * The fill the single-colour [setSingleRoute] convenience paints: the car's `#1A73E8`,  * the one route colour in this app authored against a real rendering (see
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 7d0a59ff3d..73a3837c57 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@@ -8,8 +8,6 @@ import android.view.Surface import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.DpRect import java.io.File @@ -24,16 +22,16 @@ import java.io.File  * ## Threading  *  * **Every method on this class, and every property set on it, must be called on the main- * thread**, including construction. The renderer is not safe to drive from two threads at- * once, and the frame loop runs on the main thread's [Choreographer], so a call from- * anywhere else races the frame currently being recorded. This is a hard requirement, not a- * convention — there is no lock behind it.+ * thread**, including construction. The class itself has no lock: its state, the on-demand+ * frame loop on the main thread's [Choreographer] and the camera read are all main-thread.  *- * That costs less than it sounds like: the expensive work (range fetch, inflate, MVT decode,- * tessellation) happens on worker threads inside the native side, so a frame on this side- * only uploads finished meshes and records a command buffer. Android Auto's- * `SurfaceCallback` is dispatched on the main thread, so the car path satisfies this without- * doing anything.+ * The *native* renderer, though, never runs on the main thread. Every [MapNative] call — the+ * frame, `create`/`destroy`, every setter, picks — is handed to [MapRenderThread] in call order,+ * so the main thread only decides when to draw and what camera to draw from, and is never+ * blocked by a frame, a GPU wait or a swapchain rebuild. Results that feed main-thread state+ * (the render state, the tilt pivot, "draw again when") come back through a main-thread post.+ * Android Auto's `SurfaceCallback` is dispatched on the main thread, so the car path satisfies+ * this without doing anything.  *  * ## Lifecycle  *@@ -52,19 +50,18 @@ import java.io.File  *  * The surface is deliberately not owned here: [detachSurface] destroys the native renderer  * (which waits for the GPU to go idle and drops the `ANativeWindow`) but never calls- * [Surface.release]. Whoever created the `Surface` releases it, and only after- * [detachSurface] has returned.+ * [Surface.release]. Whoever created the `Surface` releases it, after [detachSurface] returns.  *  * ## State set before the surface exists  *  * [MapNative.create] deliberately takes no layer, puck or connectivity arguments, so  * everything set through [setPalette], [setLayers], [setOnline], [setUserPuck],  * [setRoute] and [setRegionMask] is remembered and replayed into the native renderer- * inside [attachSurface], **before the first frame**. Without that the first resident set- * is tessellated with the wrong layers and immediately thrown away, the puck is missing- * until the next fix arrives a second later, the route is missing until the host happens- * to set it again, and a surface created while offline stays pinned to cache. Setting any- * of them while a surface is attached applies immediately.+ * right after it is created, **before the first frame** — the render thread runs them in+ * order behind `create`. Without that the first resident set is tessellated with the wrong+ * layers and immediately thrown away, the puck is missing until the next fix, the route is+ * missing until the host happens to set it again, and a surface created while offline stays+ * pinned to cache. Setting any of them while a surface is attached applies immediately.  *  * @param context any [Context]; only the application context is retained.  * @param density pixels per dp for [surface][attachSurface]'s display — `dpi / 160f` on@@ -75,8 +72,9 @@ import java.io.File  *  * Public setters mirror the render-state surface one-for-one (palette, layers, puck,  * markers, vehicles, route, rail, traffic, region, connectivity, Moon textures); the- * route/traffic/picking halves live as extensions in SurfaceMapOverlays.kt, so this- * file holds only frame-loop, surface-lifecycle and attach-replay logic.+ * route/traffic/picking halves live as extensions in SurfaceMapOverlays.kt and the+ * render-thread frame in SurfaceMapFrame.kt, so this file holds only frame-loop,+ * surface-lifecycle and attach-replay logic.  */ @Suppress("TooManyFunctions") class SurfaceMapRenderer(@@ -87,8 +85,7 @@ class SurfaceMapRenderer(      /**      * Convenience for a host whose surface already exists at construction time: identical to-     * building the renderer and immediately calling [attachSurface]. Check [renderState]-     * afterwards — creation is synchronous, so it is already final when this returns.+     * building the renderer and immediately calling [attachSurface].      *      * The frame loop is *not* started; call [start].      */@@ -104,7 +101,27 @@ class SurfaceMapRenderer(     }      private val appContext = context.applicationContext++    /**+     * The native handle as last reported to the main thread: nonzero once `create` succeeded,+     * zero before, after a failure and after [detachSurface]. Informational on this side;+     * native calls go through [link], which owns the render thread's own copy.+     */     internal var handle = 0L+        private set++    /** The native renderer on [MapRenderThread]: every native call goes through it. */+    private val link = MapNativeLink()++    /** Whether a native renderer exists or is being created (see [MapNativeLink.attached]). */+    private val attached: Boolean get() = link.attached++    /** A frame is on the render thread; the loop does not queue a second behind it. */+    private var frameInFlight = false++    /** A vsync arrived while [frameInFlight]: draw again the moment the current frame lands. */+    private var frameOwed = false+     private var widthPx = 0     private var heightPx = 0 @@ -130,7 +147,7 @@ class SurfaceMapRenderer(     /**      * The camera and viewport the last frame was actually drawn from, so a change that reaches      * the renderer without passing through a setter is still noticed. The Compose path *pulls*-     * its camera out of [composeCamera] inside [renderFrame] and nothing tells us when a+     * its camera out of [composeCamera] when a frame is dispatched and nothing tells us when a      * gesture or animation moves it, so this is the backstop under the push channel      * `VulkanMapSurface` installs.      */@@ -155,7 +172,7 @@ class SurfaceMapRenderer(         }      /**-     * Compose reads its camera out of a [CameraState] inside the frame callback, so that a+     * Compose reads its camera out of a [CameraState] when each frame is dispatched, so that a      * gesture or animation lands in the very next frame rather than a snapshot-propagation      * later. Setting this makes the loop take both the camera and the dp viewport from that      * state (skipping any frame whose viewport is not measured yet) instead of from [camera]@@ -175,20 +192,26 @@ class SurfaceMapRenderer(     /**      * Whether this surface is drawing, or why it is not.      *-     * Backed by Compose state so [VulkanMapSurface] can show a fallback without polling;-     * non-Compose hosts can just read it after [attachSurface] returns, since the native-     * renderer is created synchronously there. Written only on the main thread, so it needs-     * no synchronisation.+     * Backed by Compose state so [VulkanMapSurface] can show a fallback without polling.+     * Native creation runs on the render thread, so after [attachSurface] this reads+     * [MapRenderState.Initialising] until the create lands a moment later and flips it to+     * [MapRenderState.Rendering] or [MapRenderState.Unavailable]; only a missing renderer+     * library is reported synchronously. Written only on the main thread.      */     var renderState: MapRenderState by mutableStateOf(MapRenderState.Initialising)         private set +    /**+     * Called on the main thread when native creation fails after [attachSurface] returned, so+     * a host holding the [Surface] only for this renderer can release it (nothing will draw+     * into it). Internal: [VulkanMapSurface] is the one host that needs it.+     */+    internal var onStartFailed: (() -> Unit)? = null+     /**      * Whether the host wants frames. Owned here rather than split across a `pause()`/      * `resume()` pair so there is exactly one writer per input and one reconciler-     * ([syncFrameLoop]) deciding whether the callback should be posted. The orderings that-     * pair gets wrong — stopped before the surface arrives, surface destroyed while stopped,-     * [start] before the handle exists — all collapse into "recompute the predicate" here.+     * ([syncFrameLoop]) deciding whether the callback should be posted.      */     private var started = false @@ -203,83 +226,64 @@ class SurfaceMapRenderer(     private var online = true      /** Remembered so a fix taken before the surface existed is drawn in the first frame. */-    private var userPuck: UserPuck? = null+    internal var userPuck: UserPuck? = null+        private set      /**      * The app pins to draw, remembered so a set pushed before the surface existed — or one that-     * outlives a surface being recreated — is still there in the first frame, the same way-     * [userPuck] and [routeSegments] are.+     * outlives a surface being recreated — is still there in the first frame.      */-    private var markers: List<MapMarker> = emptyList()+    internal var markers: List<MapMarker> = emptyList()+        private set      /**-     * The simulated transit vehicles to draw, remembered on the same terms as [markers] so a set-     * pushed before the surface existed — or one that outlives a surface being recreated — is still-     * there in the first frame. Kept apart from [markers] because the host pushes the two on-     * different cadences (vehicles at ~1 Hz, pins on a tap/search).+     * The simulated transit vehicles to draw, remembered on the same terms as [markers]. Kept+     * apart from [markers] because the host pushes the two on different cadences (vehicles at+     * ~1 Hz, pins on a tap/search).      */-    private var vehicles: List<MapMarker> = emptyList()+    internal var vehicles: List<MapMarker> = emptyList()+        private set      /**      * The route to draw, and how, remembered so a route set before the surface existed —      * or one that outlives a surface being recreated — is still there in the first frame.-     *-     * Kept as the coloured segments rather than as anything native, because the native mesh-     * dies with the renderer and this has to be able to rebuild it.      */     internal var routeSegments: List<RouteSegment>? = null     internal var routeStyle = RouteStyle()      /**-     * The pack-driven rail-lines network to draw, and how — a second coloured-     * overlay beside the navigation route so the network and a selected route-     * coexist. Remembered on the same terms as [routeSegments] so a push that-     * arrived before the surface existed is re-applied in the first frame.+     * The pack-driven rail-lines network to draw, and how — a second coloured overlay beside+     * the navigation route. Remembered on the same terms as [routeSegments].      */     internal var railSegments: List<RouteSegment>? = null     internal var railStyle = RouteStyle() -    /**-     * The Moon raster pair, remembered so a surface attached after the push —-     * or re-attached after a recreate — still starts with the Moon available,-     * the same way [userPuck] and [routeSegments] are.-     */-    private var moonTextures: MoonTextures? = null+    /** The Moon raster pair, remembered so a surface attached after the push still has it. */+    internal var moonTextures: MoonTextures? = null+        private set      /**      * The last-pushed live-traffic colour table (`component_id`s and their ARGB), remembered so-     * a push that arrived before the surface existed — or that has to outlive the surface being-     * recreated — is re-applied in the first frame, the same way [route] is. `null` means the-     * overlay has nothing to draw (never pushed, or cleared).+     * a push that arrived before the surface existed is re-applied in the first frame. `null`+     * means the overlay has nothing to draw (never pushed, or cleared).      */     internal var trafficSpeeds: Pair<LongArray, IntArray>? = null      /**-     * Whether to draw the orthographic-sphere globe rather than the flat map.-     *-     * Pulled per frame out of the Compose `CameraState` (see [composeCamera]), like-     * the camera itself — a `LaunchedEffect` in `VulkanMapSurface` invalidates on-     * change, so flipping the toggle while idle still redraws. Read alongside the-     * camera in [renderFrame] and handed to the native frame as its `globe` flag.-     * Plain `var` (not Compose state): only ever written from effects, read on the-     * frame callback. Default-off; the car path never sets it.+     * Whether to draw the orthographic-sphere globe rather than the flat map. Read alongside+     * [camera] when a frame is dispatched (the Compose path reads `CameraState.globeEnabled`+     * instead). Default-off; the car path never sets it.      */     var globeEnabled: Boolean = false -    /**-     * Which body the globe draws. Earth (default) is the vector basemap; Moon is-     * the maps-pushed raster pair (see [SurfaceMapRenderer.setMoonTextures]).-     * Plain `var` like [globeEnabled]: written from effects, read on the frame-     * callback. Only read while the globe is active.-     */+    /** Which body the globe draws: Earth (default) or the maps-pushed Moon raster pair. */     var body: MapBody = MapBody.Earth      /**-     * Upload the Moon raster pair after attach (and after any re-attach — the-     * native textures die with the renderer like every other GPU state, so this-     * must be replayed; see `attachSurface`). [colorRgba] is `width x height`-     * RGBA8, [demRg] is `demWidth x demHeight` RG8 packed uint16. Remembered so-     * a surface attached after the push still starts with the Moon available.+     * Upload the Moon raster pair after attach (and after any re-attach — the native textures+     * die with the renderer like every other GPU state). [colorRgba] is `width x height`+     * RGBA8, [demRg] is `demWidth x demHeight` RG8 packed uint16. The ~36 MB upload runs on+     * the render thread.      */     fun setMoonTextures(         colorRgba: ByteArray,@@ -290,9 +294,7 @@ class SurfaceMapRenderer(         demHeight: Int,     ) {         moonTextures = MoonTextures(colorRgba, width, height, demRg, demWidth, demHeight)-        if (handle != 0L) {-            MapNative.setMoonTextures(handle, colorRgba, width, height, demRg, demWidth, demHeight)-        }+        applyMoonTextures()         invalidate()     } @@ -300,18 +302,20 @@ class SurfaceMapRenderer(     fun clearMoonTextures() {         if (moonTextures == null) return         moonTextures = null-        if (handle != 0L) MapNative.clearMoonTextures(handle)+        onRenderThread { h -> MapNative.clearMoonTextures(h) }         invalidate()     }      /**      * Release memory for [ComponentCallbacks2.onTrimMemory]. From      * [ComponentCallbacks2.TRIM_MEMORY_BACKGROUND] up every resident tile goes (the next frame-     * refetches what it needs); below it only off-screen tiles do.+     * refetches what it needs); below it only off-screen tiles do. The native trim waits for+     * the GPU to go idle, which is why it runs on the render thread.      */     fun trimMemory(level: Int) {-        if (handle == 0L) return-        MapNative.trimMemory(handle, keepVisible = level < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND)+        if (!attached) return+        val keepVisible = level < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND+        onRenderThread { h -> MapNative.trimMemory(h, keepVisible) }         invalidate()     } @@ -319,23 +323,16 @@ class SurfaceMapRenderer(     private var selectedRegionId: Long? = null      /**-     * Whether [selectedRegionId] has been matched to resident tiles yet.-     *-     * The match needs the region's tiles to be resident, and a selection usually arrives before-     * they are - tapping a city label recentres the map, so the tiles under the new camera are-     * still in flight. So an unresolved id is retried each frame until it lands rather than-     * being dropped, which is the difference between the mask appearing and the mask silently-     * never appearing.+     * Whether [selectedRegionId] has been matched to resident tiles yet, as last reported by a+     * frame. Only the loop's retry cadence reads it; the retry itself runs on the render thread+     * right after each frame (see [NativeRegionMask]).      */     private var regionResolved = true      /**-     * Where cached byte ranges live: the app cache dir, so "Clear cache" in-     * system settings reclaims them like any other cache. Previously external-     * files, where only "Clear storage" could reach them.-     *-     * The platform may evict this first under storage pressure, which is fine:-     * every entry re-streams on demand, and offline areas simply re-download.+     * Where cached byte ranges live: the app cache dir, so "Clear cache" in system settings+     * reclaims them like any other cache. Resolved on the render thread (first use deletes a+     * stale legacy directory recursively, which is disk work the main thread must not do).      */     private val cacheDir: File by lazy {         deleteStaleExternalCache()@@ -343,10 +340,9 @@ class SurfaceMapRenderer(     }      /**-     * One-time reclaim: older builds kept the range cache at-     * externalFilesDir/vectortilecache/, invisible to "Clear cache". The-     * entries are keyed by URL + range, so nothing here can be confused for-     * the new location's — delete the whole stale directory.+     * One-time reclaim: older builds kept the range cache at externalFilesDir/vectortilecache/,+     * invisible to "Clear cache". The entries are keyed by URL + range, so nothing here can be+     * confused for the new location's — delete the whole stale directory.      */     private fun deleteStaleExternalCache() {         val external = appContext.getExternalFilesDir(null) ?: return@@ -363,30 +359,44 @@ class SurfaceMapRenderer(     var tileSource: TileSource = TileSource.Server      /**-     * A `.mamaps` archive pushed to the device's external files dir, if present and-     * [tileSource] is [TileSource.LocalFile]. When it exists the renderer opens it-     * directly and does no networking; otherwise this is `null` and the renderer uses-     * the built-in URL and its range cache unchanged (including the LocalFile fallback-     * when no archive was pushed).+     * A `.mamaps` archive pushed to the device's external files dir, if present and [source]+     * is [TileSource.LocalFile]; otherwise `null` and the renderer uses the built-in URL and+     * its range cache. Disk work, so called on the render thread.      */-    private val localArchivePath: String?-        get() {-            if (tileSource != TileSource.LocalFile) return null-            val root = appContext.getExternalFilesDir(null) ?: appContext.filesDir-            val local = File(root, LOCAL_ARCHIVE_NAME)-            return if (local.exists()) local.absolutePath else null-        }+    private fun localArchivePath(source: TileSource): String? {+        if (source != TileSource.LocalFile) return null+        val root = appContext.getExternalFilesDir(null) ?: appContext.filesDir+        val local = File(root, LOCAL_ARCHIVE_NAME)+        return if (local.exists()) local.absolutePath else null+    }++    /**+     * Run [block] with the live native handle on the render thread, after every native call+     * issued before it. Dropped when no surface is attached (the state it would apply is+     * remembered and replayed on the next attach) and skipped on the render thread when the+     * create failed. The single funnel for native calls from this class and its extensions.+     */+    internal fun onRenderThread(block: (Long) -> Unit) = link.post(block)++    /**+     * Run [block] on the render thread and wait for its answer, at most [timeoutMillis]; [fallback]+     * with no surface, after a failed create, or past the bound. For the synchronous queries+     * (picks) only — everything else posts.+     */+    internal fun <T> queryRenderThread(timeoutMillis: Long, fallback: T, block: (Long) -> T): T =+        link.query(timeoutMillis, fallback, block)      /**      * Bring the native renderer up on [surface] at [widthPx] x [heightPx] pixels, replaying      * the deferred theme, layers, connectivity, puck and region mask before any frame is-     * drawn. [renderState] is final when this returns.+     * drawn. Creation runs on the render thread: [renderState] reads+     * [MapRenderState.Initialising] until it lands (see [renderState], [onStartFailed]).      *      * Any previously attached surface is torn down first. The caller keeps ownership of      * [surface] and must not release it until after [detachSurface] or [destroy].      */     fun attachSurface(surface: Surface, widthPx: Int, heightPx: Int) {-        if (handle != 0L) detachSurface()+        if (attached) detachSurface()         this.widthPx = widthPx         this.heightPx = heightPx         // A new native renderer has drawn nothing, so the previous surface's snapshot must not@@ -397,18 +407,29 @@ class SurfaceMapRenderer(             renderState = MapRenderState.Unavailable(MapRenderState.Reason.RendererLibraryMissing)             return         }-        handle = MapNative.create(surface, cacheDir.absolutePath, localArchivePath, widthPx, heightPx, dark, muted)-        if (handle == 0L) {-            Log.error(TAG, "the Vulkan renderer failed to start; see MapRenderer in logcat")-            renderState = MapRenderState.Unavailable(MapRenderState.Reason.RendererStartFailed)-            return+        val source = tileSource+        link.create(+            surface, { cacheDir.absolutePath }, { localArchivePath(source) }, widthPx, heightPx, dark, muted,+            ::onCreated,+        )+        // Queued behind `create`, so the very first resident set is tessellated with the+        // layers the host asked for instead of being built and then invalidated.+        replayDeferredState()+        syncFrameLoop()+        // The whole deferred set was just replayed into a brand-new native renderer, and the+        // resident set is empty, so this surface owes a frame whatever the loop was doing.+        invalidate()+    }++    private fun replayDeferredState() {+        val online = online+        val layers = layers+        onRenderThread { h ->+            MapNative.setOnline(h, online)+            MapNative.setLayers(h, layers.poi, layers.transit, layers.poiKinds.joinToString(","))+            MapNative.setTrafficEnabled(h, layers.traffic)+            MapNative.setSafetyEnabled(h, layers.safety)         }-        MapNative.setOnline(handle, online)-        // Before the first frame, so the very first resident set is tessellated with-        // the layers the host asked for instead of being built and then invalidated.-        MapNative.setLayers(handle, layers.poi, layers.transit, layers.poiKinds.joinToString(","))-        MapNative.setTrafficEnabled(handle, layers.traffic)-        MapNative.setSafetyEnabled(handle, layers.safety)         applyUserPuck()         applyRoute()         applyRailLines()@@ -417,10 +438,20 @@ class SurfaceMapRenderer(         applyMarkers()         applyVehicles()         applyMoonTextures()+    }++    /** The create result, back on the main thread. Ignored when the surface already moved on. */+    private fun onCreated(nativeHandle: Long) {+        if (nativeHandle == 0L) {+            Log.error(TAG, "the Vulkan renderer failed to start; see MapRenderer in logcat")+            link.createFailed()+            renderState = MapRenderState.Unavailable(MapRenderState.Reason.RendererStartFailed)+            syncFrameLoop()+            onStartFailed?.invoke()+            return+        }+        handle = nativeHandle         renderState = MapRenderState.Rendering-        syncFrameLoop()-        // The whole deferred set was just replayed into a brand-new native renderer, and the-        // resident set is empty, so this surface owes a frame whatever the loop was doing.         invalidate()     } @@ -428,7 +459,7 @@ class SurfaceMapRenderer(     fun resize(widthPx: Int, heightPx: Int) {         this.widthPx = widthPx         this.heightPx = heightPx-        if (handle != 0L) MapNative.resize(handle, widthPx, heightPx)+        onRenderThread { h -> MapNative.resize(h, widthPx, heightPx) }         invalidate()     } @@ -436,18 +467,18 @@ class SurfaceMapRenderer(      * Destroy the native renderer and stop drawing, leaving this instance reusable: a later      * [attachSurface] brings it back up with all the deferred state intact.      *-     * Does not release the [Surface] — that is the caller's, and releasing it before this-     * returns would pull the window out from under a GPU that has not gone idle yet.+     * Waits (bounded, [DETACH_WAIT_MILLIS]) for the render thread to destroy the native side,+     * which waits for the GPU and drops the `ANativeWindow` (see [MapNativeLink.destroy]).      */     fun detachSurface() {-        if (handle != 0L) {-            MapNative.destroy(handle)-            handle = 0L-        }+        link.destroy(DETACH_WAIT_MILLIS)+        handle = 0L+        frameInFlight = false+        frameOwed = false         // Back to Initialising, not sticky-Unavailable: the surface is gone, and a surface         // that is recreated (navigation, backgrounding) gets a fresh attempt.         renderState = MapRenderState.Initialising-        // handle is now 0, so this is what removes the callback.+        // Not attached any more, so this is what removes the callback.         syncFrameLoop()     } @@ -462,10 +493,7 @@ class SurfaceMapRenderer(      /**      * Stop driving frames without tearing the renderer down, for a host that is off screen.-     * Idempotent.-     *-     * This stops *rendering* only. In-flight tile fetches on the native side are not paused,-     * and that is where the data cost is, so this does not fully quiesce the map.+     * Idempotent. In-flight tile fetches on the native side are not paused.      */     fun stop() {         started = false@@ -481,70 +509,31 @@ class SurfaceMapRenderer(     /**      * Draw exactly one frame, for a host driving its own loop instead of using      * [start]/[stop]. Returns whether a frame was actually presented — false when there is-     * no renderer, no measured viewport, or the swapchain needed rebuilding.+     * no renderer, no measured viewport, the swapchain needed rebuilding, or the render thread+     * did not answer within [FRAME_CALL_TIMEOUT_MILLIS].      *-     * Uses `System.nanoTime()` as the animation clock; the Choreographer loop passes its own-     * `frameTimeNanos` through the [renderFrame]`(Long)` overload instead.+     * Uses `System.nanoTime()` as the animation clock; see the overload for a supplied clock.      */     fun renderFrame(): Boolean = renderFrame(System.nanoTime())      /**-     * As [renderFrame], but with the frame clock supplied by the caller — the Choreographer's-     * `frameTimeNanos`, which the renderer forwards to shaders so animation is tied to the+     * As [renderFrame], but with the frame clock supplied by the caller (a Choreographer+     * `frameTimeNanos`), which the renderer forwards to shaders so animation is tied to the      * presented frame rather than to wall-clock jitter.      */     fun renderFrame(frameTimeNanos: Long): Boolean {         val snapshot = readFrameSnapshot() ?: return false         trackFrameChange(snapshot)-        refreshTiltPivot(snapshot)-        val drawn = renderSnapshot(snapshot, frameTimeNanos)-        if (drawn) onFrame()-        if (!regionResolved) applyRegionMask()-        return drawn-    }--    /**-     * Refresh the Compose camera's tilt pivot from the resident heightmaps, so overlays-     * positioned through [Projection] pivot on the same terrain the basemap draws with.-     *-     * Only under pitch on the flat path — the renderer's own gate (`Renderer::render`-     * resolves its pivot exactly when `pitch > 0` off-globe) — and only on the Compose-     * path, which is the sole reader of the pivot state. Writes only on change, so a-     * settled pivot costs no recomposition; while tiles stream in the pivot converges and-     * overlays track it a frame behind the basemap. A dead handle cannot reach here-     * (`readFrameSnapshot` returns null first), and the native side answers 0.0 — the-     * legacy sea-level pivot — wherever no resident tile has DEM.-     */-    private fun refreshTiltPivot(snapshot: FrameSnapshot) {-        val state = composeCamera ?: return-        val position = snapshot.position-        if (position.pitch <= 0.0 || snapshot.globe) {-            if (state.pivotDp != 0.0) state.pivotDp = 0.0-            return-        }-        val pivot = MapNative.tiltPivotDp(-            handle,-            position.target.longitude.toFloat(),-            position.target.latitude.toFloat(),-            position.zoom.toFloat(),-        )-        if (pivot != state.pivotDp) state.pivotDp = pivot+        val result = link.frameNow(snapshot, density, frameTimeNanos, wantsPivot(snapshot), FRAME_CALL_TIMEOUT_MILLIS)+        applyFrameResult(result, snapshot)+        if (result.drawn) onFrame()+        return result.drawn     } -    /** Camera + viewport + globe state for one frame, or null when nothing can draw. */-    private data class FrameSnapshot(-        val position: CameraPosition,-        val widthDp: Float,-        val heightDp: Float,-        val globe: Boolean,-        val moon: Boolean-    ) {-        /** True when this frame would draw anything different from [previous]. */-        fun hasChangedSince(previous: FrameSnapshot?): Boolean = previous == null || this != previous-    }+    private fun wantsPivot(snapshot: FrameSnapshot): Boolean = composeCamera != null && snapshot.wantsPivot      private fun readFrameSnapshot(): FrameSnapshot? {-        if (handle == 0L) return null+        if (!attached) return null         val state = composeCamera         if (state != null) {             val viewport = state.viewportDp ?: return null@@ -555,7 +544,7 @@ class SurfaceMapRenderer(                 widthDp = viewport.width,                 heightDp = viewport.height,                 globe = globe,-                moon = globe && state.body == MapBody.Moon+                moon = globe && state.body == MapBody.Moon,             )         }         if (widthPx <= 0 || heightPx <= 0 || density <= 0f) return null@@ -565,7 +554,7 @@ class SurfaceMapRenderer(             widthDp = widthPx / density,             heightDp = heightPx / density,             globe = globe,-            moon = globe && body == MapBody.Moon+            moon = globe && body == MapBody.Moon,         )     } @@ -578,41 +567,31 @@ class SurfaceMapRenderer(         lastChangeNanos = System.nanoTime()     } -    private fun renderSnapshot(snapshot: FrameSnapshot, frameTimeNanos: Long): Boolean {-        // The Compose path carries the twist-gesture bearing end to end: `CameraState`-        // holds it, `Projection` rotates overlays with it, and the native frame below draws-        // the basemap with it — so the basemap and everything positioned through the-        // projection turn together. Tilt is honoured the same way on both paths.-        val position = snapshot.position-        return MapNative.render(-            handle,-            position.target.longitude.toFloat(),-            position.target.latitude.toFloat(),-            position.zoom.toFloat(),-            position.bearing.toFloat(),-            position.pitch.toFloat(),-            snapshot.widthDp,-            snapshot.heightDp,-            density,-            frameTimeNanos,-            snapshot.globe,-            snapshot.moon,-        )+    /**+     * Fold a frame's main-thread-visible results back in: the region retry state and the+     * Compose camera's tilt pivot, so overlays positioned through [Projection] pivot on the+     * same terrain the basemap draws with. Writes the pivot only on change, so a settled pivot+     * costs no recomposition; off the tilted flat path it resets to the sea-level 0.0.+     */+    private fun applyFrameResult(result: FrameResult, snapshot: FrameSnapshot) {+        regionResolved = !result.regionPending+        val state = composeCamera ?: return+        val pivot = if (snapshot.wantsPivot) result.pivotDp else 0.0+        if (!pivot.isNaN() && pivot != state.pivotDp) state.pivotDp = pivot     }      private fun syncFrameLoop() {-        if (started && handle != 0L) requestFrame() else cancelFrame()+        if (started && attached) requestFrame() else cancelFrame()     }      /**      * Ask for a frame because something changed, and re-arm the idle grace.      *      * The renderer draws **on demand**, not every vsync: rendering a still map at 60 Hz did-     * full Vulkan work on the main thread for an identical picture, which is what made the-     * device hot. Every setter here calls this, and so must anything outside that mutates what-     * the renderer would draw. It is public and cheap for that reason — a host that is unsure-     * whether a change is already covered should call it, because the cost of a wasted frame-     * is one frame and the cost of a missed one is a map that has silently stopped updating.+     * full Vulkan work for an identical picture, which is what made the device hot. Every+     * setter here calls this, and so must anything outside that mutates what the renderer+     * would draw. It is public and cheap for that reason — the cost of a wasted frame is one+     * frame and the cost of a missed one is a map that has silently stopped updating.      *      * Main thread, like everything else here. Idempotent within a frame.      *@@ -627,14 +606,13 @@ class SurfaceMapRenderer(      /**      * How many times the loop has been woken. Test seam for the on-demand contract: every-     * public mutator must wake the loop, and [FrameLoopWakeTest] asserts each one does. A-     * setter that stops calling [invalidate] fails there instead of freezing the map on device.+     * public mutator must wake the loop, and [FrameLoopWakeTest] asserts each one does.      */     internal var wakeCount = 0         private set      private fun requestFrame() {-        if (!started || handle == 0L) return+        if (!started || !attached) return         if (posted) {             // Already scheduled for the next vsync — nothing to do.             if (!postedDelayed) return@@ -650,14 +628,10 @@ class SurfaceMapRenderer(      /**      * Ask for one frame [delayMillis] from now, for work that is pending but not yet due —-     * today, a failed tile waiting out its retry backoff.-     *-     * Posting it immediately would spin through the whole backoff at 60fps, and not posting it-     * at all would leave the tile missing until the user happened to move the camera. Any-     * [invalidate] in the meantime supersedes it.+     * today, a failed tile waiting out its retry backoff. Any [invalidate] supersedes it.      */     private fun requestFrameDelayed(delayMillis: Long) {-        if (posted || !started || handle == 0L) return+        if (posted || !started || !attached) return         posted = true         postedDelayed = true         Choreographer.getInstance().postFrameCallbackDelayed(frameCallback, delayMillis)@@ -677,11 +651,49 @@ class SurfaceMapRenderer(         postedDelayed = false         // stop() and detachSurface() cannot un-post a callback Choreographer has already         // dispatched for this frame, so the predicate is re-checked here rather than trusted.-        if (!started || handle == 0L) return-        val drawn = renderFrame(frameTimeNanos)+        if (!started || !attached) return+        // The render thread is still on the previous frame. Queueing a second behind it would+        // draw a stale camera late; instead the current frame's completion draws the newest+        // camera immediately (see onFrameDone), so a slow frame costs latency, never a backlog.+        if (frameInFlight) {+            frameOwed = true+            return+        }+        dispatchFrame(frameTimeNanos)+    }++    /**+     * Read this frame's camera on the main thread and hand the frame to the render thread.+     * The main thread's share of a frame is this read plus one queue post.+     */+    private fun dispatchFrame(frameTimeNanos: Long) {+        val snapshot = readFrameSnapshot()+        if (snapshot == null) {+            // No measured viewport yet: try again next vsync, as a frame that did not draw.+            requestFrame()+            return+        }+        trackFrameChange(snapshot)+        frameInFlight = true+        link.frame(snapshot, density, frameTimeNanos, wantsPivot(snapshot)) { result -> onFrameDone(snapshot, result) }+    }++    /** A render-thread frame landed: apply its results and decide when the next one runs. */+    private fun onFrameDone(snapshot: FrameSnapshot, result: FrameResult) {+        frameInFlight = false+        applyFrameResult(result, snapshot)+        if (result.drawn) onFrame()+        if (!started || !attached) return+        // A vsync came and went while this frame was drawing: the camera has likely moved+        // again, so draw the newest one now rather than waiting out another vsync.+        if (frameOwed) {+            frameOwed = false+            dispatchFrame(System.nanoTime())+            return+        }         // A frame that did not present has not shown the change that asked for it: the-        // swapchain was rebuilt, or the viewport is not measured yet. Either way, try again.-        if (!drawn) {+        // swapchain was rebuilt, no image was free, or the viewport is not measured yet.+        if (!result.drawn) {             requestFrame()             return         }@@ -693,7 +705,7 @@ class SurfaceMapRenderer(         // An unresolved region mask retries once its tiles land, which is a frame the native         // side already asks for; with nothing pending (offline, say) it polls on a slow cadence         // rather than spinning the loop at 60 fps.-        val delay = MapNative.nextFrameDelayMillis(handle)+        val delay = result.nextDelayMillis         when {             delay == 0L -> requestFrame()             delay > 0L -> requestFrameDelayed(if (regionResolved) delay else minOf(delay, REGION_RETRY_MILLIS))@@ -705,7 +717,7 @@ class SurfaceMapRenderer(     fun setPalette(dark: Boolean, muted: Boolean) {         this.dark = dark         this.muted = muted-        if (handle != 0L) MapNative.setPalette(handle, dark, muted)+        onRenderThread { h -> MapNative.setPalette(h, dark, muted) }         invalidate()     } @@ -715,10 +727,11 @@ class SurfaceMapRenderer(      */     fun setLayers(options: LayerOptions) {         this.layers = options-        if (handle != 0L) {-            MapNative.setLayers(handle, options.poi, options.transit, options.poiKinds.joinToString(","))-            MapNative.setTrafficEnabled(handle, options.traffic)-            MapNative.setSafetyEnabled(handle, options.safety)+        val kinds = options.poiKinds.joinToString(",")+        onRenderThread { h ->+            MapNative.setLayers(h, options.poi, options.transit, kinds)+            MapNative.setTrafficEnabled(h, options.traffic)+            MapNative.setSafetyEnabled(h, options.safety)         }         invalidate()     }@@ -736,7 +749,7 @@ class SurfaceMapRenderer(      */     fun setOnline(online: Boolean) {         this.online = online-        if (handle != 0L) MapNative.setOnline(handle, online)+        onRenderThread { h -> MapNative.setOnline(h, online) }         invalidate()     } @@ -752,9 +765,8 @@ class SurfaceMapRenderer(      /**      * Replace the app's pins with [markers], drawn by the renderer as billboarded sprites so they-     * pan and tilt in lock-step with the basemap instead of trailing it the way a Compose overlay-     * does. An empty list clears them. Cheap: the geometry is the shared unit quad, so this is a-     * pure state push, no tessellation.+     * pan and tilt in lock-step with the basemap. An empty list clears them. Cheap: the geometry+     * is the shared unit quad, so this is a pure state push, no tessellation.      */     fun setMarkers(markers: List<MapMarker>) {         this.markers = markers@@ -763,13 +775,9 @@ class SurfaceMapRenderer(     }      /**-     * Replace the simulated transit vehicles with [vehicles], drawn by the renderer as billboarded-     * sprites through the same path as [setMarkers]. An empty list clears them. Cheap: the geometry-     * is the shared unit quad, so this is a pure state push, no tessellation.-     *-     * Separate from [setMarkers] so the host's ~1 Hz vehicle recompute replaces only the vehicles-     * and leaves the app pins untouched; drive it from the vehicle ticker rather than merging it-     * into the pin set.+     * Replace the simulated transit vehicles with [vehicles], drawn through the same path as+     * [setMarkers]. An empty list clears them. Separate from [setMarkers] so the host's ~1 Hz+     * vehicle recompute replaces only the vehicles and leaves the app pins untouched.      */     fun setVehicles(vehicles: List<MapMarker>) {         this.vehicles = vehicles@@ -783,7 +791,7 @@ class SurfaceMapRenderer(     fun setRegionMask(mask: Long?) {         Log.dev("RegionDbg", "setRegionMask mask=$mask")         this.selectedRegionId = mask-        this.regionResolved = false+        this.regionResolved = mask == null || mask == 0L         applyRegionMask()         invalidate()     }@@ -796,103 +804,25 @@ class SurfaceMapRenderer(     internal fun pickLabels(box: DpRect, layerIds: Set<String>): List<PlacedLabel> =         tapLabelsIn(box, layerIds) -    private fun applyRegionMask() {-        if (handle == 0L) return-        val id = selectedRegionId-        if (id == null || id == 0L) {-            MapNative.clearRegionMask(handle)-            regionResolved = true-            return-        }-        // `0` clears above; a nonzero id returns nonzero once a resident tile carries it.-        // `0` back means the tiles have not landed yet — retried next frame, not a miss.-        val resolved = MapNative.setRegionMask(handle, id) != 0L-        // Logged on the transition only: this runs every retry frame while unresolved.-        if (resolved) Log.dev("RegionDbg", "applyRegionMask id=$id resolved")-        regionResolved = resolved-    }--    private fun applyUserPuck() {-        if (handle == 0L) return-        val puck = userPuck-        if (puck == null) {-            MapNative.clearUserPuck(handle)-        } else {-            MapNative.setUserPuck(-                handle,-                puck.position.longitude.toFloat(),-                puck.position.latitude.toFloat(),-                puck.bearing ?: 0f,-                puck.bearing != null,-            )-        }-    }+    /**+     * The native per-step frame times (see [MapNative.lastFrameStepTimesNanos]), delivered to+     * [onResult] on the main thread; empty with no live renderer. For the debug overlay, which+     * must not read native state from the main thread.+     */+    internal fun queryStepTimes(onResult: (LongArray) -> Unit) = link.stepTimes(onResult) -    private fun applyMarkers() {-        if (handle == 0L) return-        val pins = markers-        if (pins.isEmpty()) {-            MapNative.clearMarkers(handle)-            return-        }-        val packed = packMapMarkers(pins)-        MapNative.setMarkers(handle, packed.ids, packed.lonLat, packed.icons, packed.labels)-    }--    private fun applyVehicles() {-        if (handle == 0L) return-        val vs = vehicles-        if (vs.isEmpty()) {-            MapNative.clearVehicles(handle)-            return-        }-        val packed = packVehicles(vs)-        MapNative.setVehicles(handle, packed.ids, packed.lonLat, packed.icons, packed.colors)-    }+    private fun applyRegionMask() = link.selectRegion(selectedRegionId)      private fun applyMoonTextures() {-        if (handle == 0L) return         val moon = moonTextures ?: return-        MapNative.setMoonTextures(-            handle,-            moon.colorRgba, moon.width, moon.height,-            moon.demRg, moon.demWidth, moon.demHeight,-        )-    }--/**- * The Moon raster pair the host pushes for the lunar globe: converted LROC- * color (RGBA8) + converted LDEM (RG8 packed uint16). Plain holder so the- * renderer can remember and replay it across re-attach like every other- * deferred state.- */-data class MoonTextures(-    val colorRgba: ByteArray,-    val width: Int,-    val height: Int,-    val demRg: ByteArray,-    val demWidth: Int,-    val demHeight: Int,-) {-    override fun equals(other: Any?): Boolean {-        if (this === other) return true-        if (other !is MoonTextures) return false-        return width == other.width && height == other.height &&-            demWidth == other.demWidth && demHeight == other.demHeight &&-            colorRgba.contentEquals(other.colorRgba) && demRg.contentEquals(other.demRg)-    }--    override fun hashCode(): Int {-        var result = width-        result = 31 * result + height-        result = 31 * result + demWidth-        result = 31 * result + demHeight-        result = 31 * result + colorRgba.contentHashCode()-        result = 31 * result + demRg.contentHashCode()-        return result+        onRenderThread { h ->+            MapNative.setMoonTextures(+                h,+                moon.colorRgba, moon.width, moon.height,+                moon.demRg, moon.demWidth, moon.demHeight,+            )+        }     }-}-      // `internal` (not `private`) so the frame-loop contract is testable: `IDLE_GRACE_NANOS`     // is pinned by `FrameLoopWakeTest`.@@ -909,53 +839,25 @@ data class MoonTextures(          *          * The renderer stops drawing when nothing is changing, so the cost of failing to          * notice a change is a map that has frozen — far worse than the frames this wastes.-         * A quarter of a second is long enough to cover an invalidation that arrives a frame-         * or two late (the `snapshotFlow` push channel is one such) and short enough that an-         * idle map settles to zero frames while the user is still looking at it. It costs-         * nothing during an interaction, where every frame re-arms it.-         *-         * `internal` rather than `private` so [FrameLoopWakeTest] can pin the quarter-second:-         * a grace of zero freezes the map whenever the push channel is one frame late, and an-         * unbounded one re-heats the phone this loop exists to cool.+         * A quarter of a second covers an invalidation that arrives a frame or two late (the+         * `snapshotFlow` push channel is one such) and is short enough that an idle map+         * settles to zero frames while the user is still looking at it.          */         internal val IDLE_GRACE_NANOS = java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(250)          /** Retry cadence for an unresolved region mask while no tile work is pending. */         const val REGION_RETRY_MILLIS = 500L -        // DEFAULT_ROUTE_COLOR lives in SurfaceMapOverlays.kt.-    }-}+        /**+         * Upper bound on [detachSurface]'s wait for the native teardown. A frame on the render+         * thread is bounded by the 100 ms swapchain-acquire cap plus its own few ms, and the+         * teardown by one GPU idle; a second is far past both and still well inside an ANR.+         */+        const val DETACH_WAIT_MILLIS = 1_000L -/**- * The Moon raster pair the host pushes for the lunar globe: converted LROC- * color (RGBA8) + converted LDEM (RG8 packed uint16). Plain holder so the- * renderer can remember and replay it across re-attach like every other- * deferred state.- */-data class MoonTextures(-    val colorRgba: ByteArray,-    val width: Int,-    val height: Int,-    val demRg: ByteArray,-    val demWidth: Int,-    val demHeight: Int,-) {-    override fun equals(other: Any?): Boolean {-        if (this === other) return true-        if (other !is MoonTextures) return false-        return width == other.width && height == other.height &&-            demWidth == other.demWidth && demHeight == other.demHeight &&-            colorRgba.contentEquals(other.colorRgba) && demRg.contentEquals(other.demRg)-    }--    override fun hashCode(): Int {-        var result = width-        result = 31 * result + height-        result = 31 * result + demWidth-        result = 31 * result + demHeight-        result = 31 * result + colorRgba.contentHashCode()-        result = 31 * result + demRg.contentHashCode()-        return result+        /** Upper bound on [renderFrame]'s synchronous wait for one render-thread frame. */+        const val FRAME_CALL_TIMEOUT_MILLIS = 500L++        // DEFAULT_ROUTE_COLOR and the pick timeout live in SurfaceMapOverlays.kt.     } }
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 9d7a6e69e1..57806736df 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@@ -51,6 +51,10 @@ import kotlinx.coroutines.flow.StateFlow  * [TextureView.SurfaceTextureListener.onSurfaceTextureDestroyed] means we release it, so  * the renderer is torn down — device idle, buffers freed, `ANativeWindow` released —  * exactly when the window goes away.+ *+ * Drawing into a TextureView from a thread other than the UI thread is the supported+ * configuration (the view only consumes the `SurfaceTexture`'s buffers), which is what lets+ * every frame run on the renderer's own render thread rather than the main thread.  */ @Composable @Suppress("LongMethod")@@ -178,7 +182,8 @@ internal fun VulkanMapSurface(     }      // The renderer holds tens of MB of GPU tile buffers; hand them back when the system asks.-    // Callbacks arrive on the main thread, which is the renderer's thread.+    // Callbacks arrive on the main thread, the renderer's API thread; the trim itself (a GPU+    // idle wait) runs on its render thread.     DisposableEffect(context, host) {         val callbacks = object : ComponentCallbacks2 {             override fun onTrimMemory(level: Int) = renderer.trimMemory(level)@@ -354,6 +359,9 @@ private class MapSurfaceHost(     val renderer = SurfaceMapRenderer(context, density, onFrame).apply {         composeCamera = cameraState         this.tileSource = tileSource+        // Native creation runs on the render thread, so a failure is reported after+        // attachSurface returned: give the Surface back then, as the synchronous path does.+        onStartFailed = { releaseSurface() }     }      private var surface: Surface? = null
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..13539ea838 100644--- a/library/map/src/main/rust/src/bridge/mod.rs+++ b/library/map/src/main/rust/src/bridge/mod.rs@@ -8,8 +8,11 @@ //! //! # Threading //!-//! `render` is called from Kotlin's `Choreographer` callback, so on the main thread; every-//! Vulkan call happens there and the renderer is never driven from two threads at once.+//! Every entry point is called from one Kotlin thread, `MapRenderThread` — a dedicated+//! display-priority thread, never the main thread (the Kotlin side's Choreographer loop only+//! schedules frames and hands them over). Every Vulkan call happens there and the renderer is+//! never driven from two threads at once, which is what lets `handle_mut` hand out a plain+//! `&mut` with no lock. //! Tile work — the range fetch, the gzip inflate, the MVT decode and the tessellation — //! runs on a worker thread and hands finished meshes back through a channel, which //! `render` drains. That is the split the plan asks for: the expensive half off the
library/map/src/main/rust/tests/frame_cpu_bench.rs
diff --git a/library/map/src/main/rust/tests/frame_cpu_bench.rs b/library/map/src/main/rust/tests/frame_cpu_bench.rsnew file mode 100644index 0000000000..d235282994--- /dev/null+++ b/library/map/src/main/rust/tests/frame_cpu_bench.rs@@ -0,0 +1,143 @@+//! Host timings for the work the map used to do on the Android main thread.+//!+//! Not a correctness test: ignored by default and run on demand to put numbers on the+//! render-thread move and on the hot paths it carries. Everything here is the CPU half of the+//! native renderer (the Vulkan half has no host build), timed on the host with the same code+//! the device runs. A phone core is roughly 2-4x slower than a desktop core, so read these as+//! lower bounds for the device.+//!+//! ```text+//! cargo test -p map_renderer --release --test frame_cpu_bench -- --ignored --nocapture --test-threads=1+//! MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps cargo test ... (adds the archive half)+//! ```++use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::time::{Duration, Instant};++use map_renderer::camera::Camera;+use map_renderer::style::{self, KindFilter, LayerToggles};+use map_renderer::tile::geometry;+use map_renderer::tile::glyph::atlas::GlyphAtlas;+use map_renderer::tile::select;+use map_renderer::tile::source::FileRangeReader;+use map_renderer::tile::sprite::SpriteAtlas;+use tilecodec::mamaps::read::{LeafCache, MamapsArchive};++fn ms(d: Duration) -> f64 {+    d.as_secs_f64() * 1e3+}++fn camera(lon: f64, lat: f64, zoom: f64) -> Camera {+    Camera {+        center_lon: lon,+        center_lat: lat,+        zoom,+        // A Pixel-class portrait viewport.+        width_dp: 412.0,+        height_dp: 915.0,+        density: 2.625,+        bearing_deg: 0.0,+        pitch_deg: 0.0,+        pivot_dp: 0.0,+        globe: false,+        moon: false,+        time_seconds: 0.0,+    }+}++/// What `MapNative.create` computed on the calling thread before any Vulkan object existed:+/// the parsed style, the SDF glyph atlas and the decoded POI sprite sheet. All three are+/// process-wide lazies, so this is a first-surface cost (each process pays it once).+#[test]+#[ignore = "timing harness; run with --ignored --nocapture"]+fn create_time_cpu_work() {+    let t = Instant::now();+    let layers = style::layers().len();+    let style_ms = ms(t.elapsed());+    let t = Instant::now();+    let glyphs = GlyphAtlas::build();+    let atlas_ms = ms(t.elapsed());+    let t = Instant::now();+    let sprites = SpriteAtlas::build().expect("sprite sheet");+    let sprite_ms = ms(t.elapsed());+    std::hint::black_box((&glyphs, &sprites));+    println!(+        "create CPU work: style parse {style_ms:.1} ms ({layers} layers), glyph atlas {atlas_ms:.1} ms, \+         sprite decode {sprite_ms:.1} ms, total {:.1} ms",+        style_ms + atlas_ms + sprite_ms+    );+}++/// Per-frame tile selection (`select::visible` + `select::resident_set`), which `render` runs+/// on every frame while the camera moves.+#[test]+#[ignore = "timing harness; run with --ignored --nocapture"]+fn per_frame_selection() {+    for zoom in [4.0, 10.0, 14.0, 17.0] {+        let mut cam = camera(-122.4194, 37.7749, zoom);+        let frames = 2_000;+        let t = Instant::now();+        let mut n = 0usize;+        for i in 0..frames {+            // A pan: a little east every frame, as a drag does.+            cam.center_lon = -122.4194 + i as f64 * 1e-5 * 2f64.powf(14.0 - zoom);+            n += select::visible(&cam, 0, 15).len();+            n += select::resident_set(&cam, 0, 15).len();+        }+        println!(+            "selection z{zoom}: {:.3} ms/frame ({} tiles/frame)",+            ms(t.elapsed()) / frames as f64,+            n / frames+        );+    }+}++fn archive_path() -> Option<PathBuf> {+    match std::env::var("MAMAPS_REAL_ARCHIVE") {+        Ok(p) if Path::new(&p).is_file() => Some(PathBuf::from(p)),+        _ => {+            eprintln!("MAMAPS_REAL_ARCHIVE not set: archive half skipped");+            None+        }+    }+}++/// Worker-side cost of one viewport: archive read (memory-mapped, cold pages are random+/// reads) plus decode and tessellation per tile. Runs on the tile workers, never on the+/// render or main thread; reported so the frame numbers have their background counterpart.+#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE; timing harness"]+fn viewport_tile_build() {+    let Some(path) = archive_path() else { return };+    let archive = MamapsArchive::open_with_cache(+        FileRangeReader::open(&path).expect("open"),+        Arc::new(LeafCache::new()),+    )+    .expect("archive");+    let layers = style::layers();+    let toggles = LayerToggles { poi: true, transit: true, traffic: true, safety: true };+    for (name, lon, lat, zoom) in [("SF", -122.4194, 37.7749, 14.0), ("London", -0.1278, 51.5074, 11.0)] {+        let cam = camera(lon, lat, zoom);+        let tiles = select::visible(&cam, archive.header.min_zoom, archive.header.max_zoom);+        let (mut read, mut build, mut labels) = (Duration::ZERO, Duration::ZERO, 0usize);+        for tile in &tiles {+            let t = Instant::now();+            let Ok(Some(body)) = archive.tile(tile.z, tile.x, tile.y) else { continue };+            read += t.elapsed();+            let t = Instant::now();+            let mesh = geometry::build_toggled(+                &body, layers, tile.z, tile.x, tile.y, false, toggles, &KindFilter::all(), 1,+            );+            build += t.elapsed();+            labels += mesh.labels.len();+        }+        println!(+            "{name} z{zoom}: {} tiles, read {:.1} ms, decode+tessellate {:.1} ms ({:.1} ms/tile), {labels} labels",+            tiles.len(),+            ms(read),+            ms(build),+            ms(build) / tiles.len().max(1) as f64+        );+    }+}
library/map/src/test/java/com/vayunmathur/library/map/MapRenderThreadTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/MapRenderThreadTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/MapRenderThreadTest.ktnew file mode 100644index 0000000000..73c463baca--- /dev/null+++ b/library/map/src/test/java/com/vayunmathur/library/map/MapRenderThreadTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.library.map++import android.app.Application+import java.util.Collections+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotSame+import kotlin.test.assertTrue++/**+ * The render-thread contract every native call now relies on.+ *+ * The native renderer is single-threaded (`bridge::handle_mut` hands out an unlocked `&mut`),+ * and it no longer runs on the main thread, so [MapRenderThread] must give exactly three+ * guarantees: one thread, submission order, and a caller that is never blocked past its bound.+ * Plain JVM: the executor is java.util.concurrent, and `Process.setThreadPriority` is a stub+ * that returns (this module sets `isReturnDefaultValues`).+ */+class MapRenderThreadTest {++    @Test+    fun posts_run_in_order_on_one_thread_that_is_not_the_caller() {+        val order = Collections.synchronizedList(mutableListOf<Int>())+        val threads = Collections.synchronizedSet(mutableSetOf<Thread>())+        val done = CountDownLatch(1)+        repeat(200) { i ->+            MapRenderThread.post {+                order += i+                threads += Thread.currentThread()+            }+        }+        MapRenderThread.post { done.countDown() }+        assertTrue(done.await(5, TimeUnit.SECONDS), "render thread never drained")+        assertEquals((0 until 200).toList(), order.toList(), "native calls must keep submission order")+        assertEquals(1, threads.size, "every native call must land on the same thread")+        assertNotSame(Thread.currentThread(), threads.single(), "native work must leave the calling thread")+    }++    @Test+    fun call_returns_the_answer_and_runs_inline_when_reentered() {+        assertEquals(42, MapRenderThread.call(5_000, -1) { 42 })+        // A synchronous query issued from a render-thread task must not wait on its own queue.+        val nested = MapRenderThread.call(5_000, -1) { MapRenderThread.call(5_000, -2) { 7 } }+        assertEquals(7, nested)+    }++    @Test+    fun a_slow_render_thread_costs_the_caller_its_bound_not_its_duration() {+        val release = CountDownLatch(1)+        MapRenderThread.post { release.await(5, TimeUnit.SECONDS) }+        val started = System.nanoTime()+        val answer = MapRenderThread.call(50, "fallback") { "late" }+        val waitedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)+        release.countDown()+        assertEquals("fallback", answer)+        assertTrue(waitedMillis < 1_000, "caller waited ${waitedMillis}ms past a 50 ms bound")+    }++    @Test+    fun a_throwing_task_does_not_kill_the_thread() {+        MapRenderThread.post { error("boom") }+        assertEquals("alive", MapRenderThread.call(5_000, "dead") { "alive" })+        assertEquals("fallback", MapRenderThread.call(5_000, "fallback") { error("boom") })+    }++    @Test+    fun a_renderer_without_a_surface_never_touches_the_render_thread() {+        // No surface: every native call is dropped (remembered for the attach replay), and+        // the synchronous queries answer their fallback without waiting on anything.+        val r = SurfaceMapRenderer(Application(), density = 3f)+        var ran = false+        r.onRenderThread { ran = true }+        assertEquals(-1L, r.queryRenderThread(5_000, -1L) { 1L })+        r.trimMemory(80)+        r.detachSurface()+        MapRenderThread.call(5_000, Unit) {}+        assertFalse(ran)+        assertEquals(MapRenderState.Initialising, r.renderState)+    }+}