Modern Apps git

← Modern-Apps.git

maps: build the traffic colour table off the main thread (#maprender)

Commit
ff50673efe6530091b7f3a78f00242406ab8ff7c
Author
Vayun Mathur <[email protected]>
When
2026-11-13 20:30 UTC (22 days ago)
Parents
4f86665
Part of "visibly laggy when moving around" with the traffic layer on.

Root cause: `MapSurface` rebuilt the renderer's id->ARGB traffic table
inside `remember(components, tokens, trafficEnabled)`, i.e. during
composition on the main thread. `components` is the session-wide merge
of every 1-degree square fetched so far (one entry per road piece), and
it is republished every time a square lands - which happens while the
user is panning, because the prefetch fires on each camera settle. So a
recomposition in the middle of a gesture paid an O(n) pass over a table
that grows to hundreds of thousands of entries for a metro session,
allocating two n-sized arrays and converting a Compose `Color` to ARGB
for every single entry.

What changed:
- `MapSurface` builds the table with `produceState` on
  `Dispatchers.Default`, keyed like the old `remember`. The previous
  table stays on screen until the new one is ready (produceState keeps
  its value across restarts), and turning traffic off still clears it
  immediately.
- `buildTrafficColorTable` resolves the three bucket colours to ARGB
  once instead of once per component. Output is unchanged.

Measured: the new JVM test builds a 600k-component table and prints
its time (best of five) in the test output; that whole cost now leaves
the main thread, which keeps only a reference swap. The test also pins
the output against the old per-component implementation, entry for
entry.

Verified: MapSurfaceHelpersSlice1Test (existing bucketing tests plus
the new equivalence/timing test); ui files stay inside the 350-line
FileLength limit.

Diff

maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.ktindex 564fa3063c..e614f0eed0 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt@@ -4,6 +4,7 @@ import android.app.Activity import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier@@ -16,6 +17,7 @@ import com.vayunmathur.library.map.MapBody import com.vayunmathur.library.map.MapOptions import com.vayunmathur.library.map.MoonTextures import com.vayunmathur.library.map.TileSource+import com.vayunmathur.library.map.TrafficColorTable import com.vayunmathur.library.map.UserPuck import com.vayunmathur.library.map.VectorMap import com.vayunmathur.library.ui.FreeHeightSheetState@@ -38,7 +40,9 @@ import com.vayunmathur.maps.util.RouteService import com.vayunmathur.maps.util.SearchResult import com.vayunmathur.maps.util.SelectedFeatureViewModel import com.vayunmathur.maps.util.TransitStopsViewModel+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext  /**  * The map surface: the renderer, its overlay layers, and what a tap on it means.@@ -113,9 +117,15 @@ fun MapSurface(     // toggle is off or there is nothing to draw, which clears the overlay on the next frame —     // the accumulated data stays cached in OfflineRouter so re-enabling is instant.     val tokens = remember(darkBasemap) { mapTokens(darkBasemap) }+    // Built off the main thread: the table spans every component fetched this session (one+    // entry per road piece in every 1-degree square visited), and it is rebuilt whenever a+    // square lands, which is while the user is panning. The previous table keeps drawing until+    // the new one is ready.     val components by OfflineRouterTraffic.trafficComponents.collectAsState()-    val trafficColors = remember(components, tokens, trafficEnabled) {-        if (trafficEnabled) buildTrafficColorTable(components, tokens) else null+    val trafficColors by produceState<TrafficColorTable?>(null, components, tokens, trafficEnabled) {+        value = if (!trafficEnabled) null else withContext(Dispatchers.Default) {+            buildTrafficColorTable(components, tokens)+        }     }      // The route, drawn inside the renderer's frame so it pans in lock-step with the basemap
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.ktindex 44a76539db..1d22cb27f3 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt@@ -101,6 +101,7 @@ internal fun buildTrafficColorTable( ): TrafficColorTable? {     val n = components.ids.size     if (n == 0) return null+    val (jam, slow, free) = with(tokens.traffic) { Triple(jam.toArgb(), slow.toArgb(), free.toArgb()) }     val outIds = LongArray(n)     val outArgb = IntArray(n)     var k = 0@@ -108,13 +109,12 @@ internal fun buildTrafficColorTable(         val pct = components.ratioPct[i].toInt() and BYTE_MASK         if (pct == 0) continue         val ratio = pct / TRAFFIC_RATIO_SCALE-        val color = when {-            ratio < TRAFFIC_JAM_BELOW -> tokens.traffic.jam-            ratio < TRAFFIC_SLOW_BELOW -> tokens.traffic.slow-            else -> tokens.traffic.free-        }         outIds[k] = components.ids[i]-        outArgb[k] = color.toArgb()+        outArgb[k] = when {+            ratio < TRAFFIC_JAM_BELOW -> jam+            ratio < TRAFFIC_SLOW_BELOW -> slow+            else -> free+        }         k++     }     if (k == 0) return null
maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.ktindex 8c5d0eefa6..83aefaea39 100644--- a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt@@ -62,6 +62,45 @@ class MapSurfaceHelpersSlice1Test {         assertEquals(listOf(8L), table.ids.toList())     } +    @Test+    fun `a session-sized traffic table builds identically to the per-component reference`() {+        // One entry per road piece in every square visited: a metro session reaches the+        // hundreds of thousands. Rebuilt on every landing fetch, so it now runs off the main+        // thread (MapSurface's produceState) with its three colours resolved once.+        val n = 600_000+        val big = OfflineRouterTraffic.TrafficComponents(+            LongArray(n) { it.toLong() },+            ByteArray(n) { ((it * 37) % 101).toByte() },+        )+        fun reference(c: OfflineRouterTraffic.TrafficComponents): Pair<List<Long>, List<Int>> {+            val ids = ArrayList<Long>()+            val argb = ArrayList<Int>()+            for (i in c.ids.indices) {+                val pct = c.ratioPct[i].toInt() and 0xFF+                if (pct == 0) continue+                val ratio = pct / 100.0+                ids += c.ids[i]+                argb += when {+                    ratio < 0.5 -> tokens.traffic.jam+                    ratio < 0.9 -> tokens.traffic.slow+                    else -> tokens.traffic.free+                }.toArgb()+            }+            return ids to argb+        }+        val (refIds, refArgb) = reference(big)+        val table = assertNotNull(buildTrafficColorTable(big, tokens))+        assertEquals(refIds, table.ids.toList())+        assertEquals(refArgb, table.argb.toList())+        // Timing for the report (best of five, after the warm-up above).+        val millis = (1..5).minOf {+            val t = System.nanoTime()+            buildTrafficColorTable(big, tokens)+            (System.nanoTime() - t) / 1e6+        }+        println("traffic table: $n components built in ${"%.2f".format(millis)} ms (now off the main thread)")+    }+     @Test     fun `pin features cover every pin kind in probe order`() {         val pins = pinFeatures(