Modern Apps git

← Modern-Apps.git

map: tile byte budget, arena reuse, R8 glyph atlas, trim hook, drop moon

Commit
5e4a04263410c0b970136c960911dc439ab5defa
Author
vayun-mathur <[email protected]>
When
2026-10-26 21:02 UTC (1 month ago)
Parents
f00a518

Diff

library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex 3067511349..c242acc474 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -122,6 +122,9 @@ internal object MapNative {         demHeight: Int,     ) +    /** Drop the Moon raster pair from the GPU; a Moon frame draws the clear colour until the next push. */+    external fun clearMoonTextures(handle: Long)+     external fun resize(handle: Long, width: Int, height: Int)      /**@@ -438,6 +441,13 @@ internal object MapNative {      */     external fun lastFrameStepTimesNanos(handle: Long): LongArray +    /**+     * Give memory back under system pressure: evict every resident tile except the visible ones+     * (or all of them when [keepVisible] is false), wait for the GPU, and free the evicted+     * buffers, empty upload arenas and scratch high-water blocks at once.+     */+    external fun trimMemory(handle: Long, keepVisible: Boolean)+     /**      * Destroy the renderer, wait for the GPU to go idle, and release the window.      *
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 cfeb93a745..566df88ac3 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@@ -1,5 +1,6 @@ package com.vayunmathur.library.map +import android.content.ComponentCallbacks2 import android.content.Context import com.vayunmathur.library.log.Log import android.view.Choreographer@@ -295,6 +296,25 @@ class SurfaceMapRenderer(         invalidate()     } +    /** Forget the Moon raster pair and free its GPU images, e.g. once the host leaves the Moon. */+    fun clearMoonTextures() {+        if (moonTextures == null) return+        moonTextures = null+        if (handle != 0L) MapNative.clearMoonTextures(handle)+        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.+     */+    fun trimMemory(level: Int) {+        if (handle == 0L) return+        MapNative.trimMemory(handle, keepVisible = level < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND)+        invalidate()+    }+     /** The baked `regionId` to mask, or `null` for no mask. */     private var selectedRegionId: Long? = null 
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 3dc689fbf1..7396d95e95 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@@ -1,6 +1,8 @@ package com.vayunmathur.library.map +import android.content.ComponentCallbacks2 import android.content.Context+import android.content.res.Configuration import android.graphics.SurfaceTexture import android.view.Surface import android.view.TextureView@@ -182,6 +184,19 @@ 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.+    DisposableEffect(context, host) {+        val callbacks = object : ComponentCallbacks2 {+            override fun onTrimMemory(level: Int) = renderer.trimMemory(level)+            override fun onConfigurationChanged(newConfig: Configuration) = Unit+            @Deprecated("Deprecated in Java")+            override fun onLowMemory() = renderer.trimMemory(ComponentCallbacks2.TRIM_MEMORY_BACKGROUND)+        }+        context.registerComponentCallbacks(callbacks)+        onDispose { context.unregisterComponentCallbacks(callbacks) }+    }+     // The renderer draws on demand rather than every vsync, and it *pulls* its camera out of     // the CameraState inside its frame callback — so nothing would otherwise tell it that a     // gesture, a fling, `animateTo` or a layout pass has moved the camera while the loop is@@ -315,16 +330,19 @@ internal fun VulkanMapSurface(      // The Moon textures: pushed like the route, out of band from the frame loop.     // Keyed on value equality so an identical push on recomposition does not-    // re-upload 36MB. `null` keeps whatever is there (upload-once asset).+    // re-upload 36MB. `null` frees them (the host left the Moon).     LaunchedEffect(moonTextures, host) {-        moonTextures?.let {+        val moon = moonTextures+        if (moon == null) {+            renderer.clearMoonTextures()+        } else {             renderer.setMoonTextures(-                it.colorRgba,-                it.width,-                it.height,-                it.demRg,-                it.demWidth,-                it.demHeight+                moon.colorRgba,+                moon.width,+                moon.height,+                moon.demRg,+                moon.demWidth,+                moon.demHeight             )         }     }
library/map/src/main/rust/src/bridge/frame.rs
diff --git a/library/map/src/main/rust/src/bridge/frame.rs b/library/map/src/main/rust/src/bridge/frame.rsindex 24aa931ac6..d58248e215 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -1,7 +1,7 @@ //! One frame from a camera snapshot. //! //! Pure move out of `bridge.rs`; no logic changes.-use super::handle::{handle_mut, TileResult, RESIDENT_TILE_CAP, UPLOADS_PER_FRAME, WASH_MAX_ZOOM};+use super::handle::{handle_mut, TileResult, RESIDENT_BYTE_BUDGET, RESIDENT_TILE_CAP, UPLOADS_PER_FRAME, WASH_MAX_ZOOM}; use super::log::{log, log_info}; use crate::camera::Camera; use crate::style;@@ -129,7 +129,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(                 // It arrived, so whatever was failing has stopped. Anything else would leave a                 // tile that recovered still carrying a ten-second backoff for the session.                 map.retry.remove(&key);-                if let Err(e) = map.renderer.upload(key, &mesh) {+                if let Err(e) = map.renderer.upload(key, mesh) {                     log(&format!("uploading a tile failed: {e}"));                 }             }@@ -343,7 +343,8 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // resumes against.     if !moon {         map.retry.retain_visible(&visible);-        map.renderer.retain(&keep, &visible, RESIDENT_TILE_CAP);+        map.renderer+            .retain(&keep, &visible, RESIDENT_TILE_CAP, RESIDENT_BYTE_BUDGET);         map.last_visible = wanted_keys;     }     // `fetch_held` (the hold count from the live-set diff above) plus the drain count
library/map/src/main/rust/src/bridge/handle.rs
diff --git a/library/map/src/main/rust/src/bridge/handle.rs b/library/map/src/main/rust/src/bridge/handle.rsindex b4b3d11851..04ed5ff2c9 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -8,7 +8,7 @@ use crate::tile::select::TileId; /// Re-exported so `bridge::frame` keeps its `super::handle::RESIDENT_TILE_CAP` path: the /// constant lives in `tile::select` (with the retention policy and its measurement pin), /// but the frame reads it through the handle.-pub(crate) use crate::tile::select::RESIDENT_TILE_CAP;+pub(crate) use crate::tile::select::{RESIDENT_BYTE_BUDGET, RESIDENT_TILE_CAP}; use crate::vulkan::renderer::Renderer; use jni::sys::jlong; use std::collections::{HashMap, HashSet};
library/map/src/main/rust/src/bridge/lifecycle.rs
diff --git a/library/map/src/main/rust/src/bridge/lifecycle.rs b/library/map/src/main/rust/src/bridge/lifecycle.rsindex fb3d4f6ffe..e7878ce46f 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -283,3 +283,22 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_destroy<'l>(     // the renderer, which waits for the device to go idle before freeing anything.     unsafe { drop(Box::from_raw(handle as *mut MapHandle)) }; }++/// Give memory back under system pressure (`onTrimMemory`). With `keep_visible` the tiles on+/// screen stay; without it every tile goes and the next frame refetches what it needs.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_trimMemory<'l>(+    _env: EnvUnowned<'l>,+    _class: JClass<'l>,+    handle: jlong,+    keep_visible: bool,+) {+    if let Some(map) = handle_mut(handle) {+        let keep = if keep_visible {+            map.last_visible.clone()+        } else {+            HashSet::new()+        };+        map.renderer.trim(&keep);+    }+}
library/map/src/main/rust/src/bridge/moon.rs
diff --git a/library/map/src/main/rust/src/bridge/moon.rs b/library/map/src/main/rust/src/bridge/moon.rsindex 929bcd86f3..e5d3418b54 100644--- a/library/map/src/main/rust/src/bridge/moon.rs+++ b/library/map/src/main/rust/src/bridge/moon.rs@@ -94,3 +94,17 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setMoonTexture fn bytemuck_cast(bytes: &mut [u8]) -> &mut [i8] {     unsafe { std::slice::from_raw_parts_mut(bytes.as_mut_ptr() as *mut i8, bytes.len()) } }++/// Drop the Moon raster pair (~40 MB of GPU images) when the host leaves the Moon; a later+/// [`setMoonTextures`](Java_com_vayunmathur_library_map_MapNative_setMoonTextures) uploads it+/// again.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearMoonTextures<'l>(+    _env: EnvUnowned<'l>,+    _class: JClass<'l>,+    handle: jlong,+) {+    if let Some(map) = handle_mut(handle) {+        map.renderer.clear_moon_textures();+    }+}
library/map/src/main/rust/src/lib.rs
diff --git a/library/map/src/main/rust/src/lib.rs b/library/map/src/main/rust/src/lib.rsindex 1e2b5b6065..04f295c91b 100644--- a/library/map/src/main/rust/src/lib.rs+++ b/library/map/src/main/rust/src/lib.rs@@ -45,6 +45,7 @@ pub mod marker; pub mod overlay; pub mod overlay_parts; pub mod pipeline_cache;+pub mod range_alloc; pub mod style; pub mod tess; pub mod tile;
library/map/src/main/rust/src/range_alloc.rs
diff --git a/library/map/src/main/rust/src/range_alloc.rs b/library/map/src/main/rust/src/range_alloc.rsnew file mode 100644index 0000000000..c5b0584205--- /dev/null+++ b/library/map/src/main/rust/src/range_alloc.rs@@ -0,0 +1,121 @@+//! First-fit free list over one fixed-size byte range, for the tile-upload arenas.+//!+//! Host-compiled (unlike `vulkan`) so the bookkeeping the arenas rely on is pinned by tests.+//! Every range handed out and every free span is a multiple of [`ALIGN`], so a released range+//! always merges cleanly with its neighbours.++pub const ALIGN: u64 = 64;++pub fn align_up(v: u64) -> u64 {+    (v + ALIGN - 1) & !(ALIGN - 1)+}++/// Free spans as `(offset, len)`, sorted by offset and never adjacent (adjacent spans merge).+#[derive(Debug, Clone)]+pub struct RangeAlloc {+    capacity: u64,+    free: Vec<(u64, u64)>,+}++impl RangeAlloc {+    pub fn new(capacity: u64) -> RangeAlloc {+        let capacity = capacity & !(ALIGN - 1);+        RangeAlloc {+            capacity,+            free: vec![(0, capacity)],+        }+    }++    /// Reserve `len` bytes (rounded up to [`ALIGN`]); the offset, or `None` when no span fits.+    pub fn alloc(&mut self, len: u64) -> Option<u64> {+        let len = align_up(len.max(1));+        let at = self.free.iter().position(|&(_, span)| span >= len)?;+        let (offset, span) = self.free[at];+        if span == len {+            self.free.remove(at);+        } else {+            self.free[at] = (offset + len, span - len);+        }+        Some(offset)+    }++    /// Whether a span of `len` bytes is free, without reserving it.+    pub fn fits(&self, len: u64) -> bool {+        let len = align_up(len.max(1));+        self.free.iter().any(|&(_, span)| span >= len)+    }++    /// Return a range previously handed out by [`alloc`](Self::alloc) with the same `len`.+    pub fn release(&mut self, offset: u64, len: u64) {+        let len = align_up(len.max(1));+        let at = self.free.partition_point(|&(o, _)| o < offset);+        self.free.insert(at, (offset, len));+        if at + 1 < self.free.len() && offset + len == self.free[at + 1].0 {+            self.free[at].1 += self.free[at + 1].1;+            self.free.remove(at + 1);+        }+        if at > 0 && self.free[at - 1].0 + self.free[at - 1].1 == offset {+            self.free[at - 1].1 += self.free[at].1;+            self.free.remove(at);+        }+    }++    pub fn is_empty(&self) -> bool {+        self.free.len() == 1 && self.free[0] == (0, self.capacity)+    }++    pub fn used(&self) -> u64 {+        self.capacity - self.free.iter().map(|&(_, span)| span).sum::<u64>()+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn a_released_range_is_handed_out_again() {+        let mut a = RangeAlloc::new(1024);+        let first = a.alloc(100).unwrap();+        let second = a.alloc(100).unwrap();+        assert_eq!((first, second), (0, 128));+        a.release(first, 100);+        assert_eq!(a.alloc(64), Some(0));+    }++    #[test]+    fn neighbours_merge_back_into_one_span() {+        let mut a = RangeAlloc::new(1024);+        let r: Vec<u64> = (0..4).map(|_| a.alloc(256).unwrap()).collect();+        assert_eq!(a.alloc(1), None);+        a.release(r[1], 256);+        a.release(r[3], 256);+        a.release(r[2], 256);+        assert_eq!(a.alloc(768), Some(256));+        a.release(256, 768);+        a.release(r[0], 256);+        assert!(a.is_empty());+        assert_eq!(a.used(), 0);+    }++    #[test]+    fn fits_does_not_reserve() {+        let mut a = RangeAlloc::new(256);+        assert!(a.fits(256));+        assert!(a.fits(256));+        assert_eq!(a.alloc(256), Some(0));+        assert!(!a.fits(1));+    }++    #[test]+    fn fragmentation_falls_through_to_a_later_span() {+        let mut a = RangeAlloc::new(1024);+        let r: Vec<u64> = (0..4).map(|_| a.alloc(256).unwrap()).collect();+        a.release(r[0], 256);+        a.release(r[2], 256);+        assert_eq!(a.alloc(512), None);+        assert_eq!(a.alloc(200), Some(0));+        assert_eq!(a.alloc(256), Some(512));+        assert_eq!(a.used(), 1024);+    }+}
library/map/src/main/rust/src/tile/select/mod.rs
diff --git a/library/map/src/main/rust/src/tile/select/mod.rs b/library/map/src/main/rust/src/tile/select/mod.rsindex 520e416de6..f79d2e0a78 100644--- a/library/map/src/main/rust/src/tile/select/mod.rs+++ b/library/map/src/main/rust/src/tile/select/mod.rs@@ -37,5 +37,5 @@ pub use cover::{relevant_keys, redundant_tiles, COVER_MAX_DEPTH}; pub use fade::{     fade_in_progress, has_resident_ancestor, lod_fade_alpha, tile_lod_alpha, LOD_FADE_SECONDS, };-pub use resident::{resident_set, stands_in_for_visible, zoom_out_burst, ANCESTOR_DEPTH, DESCENDANT_DEPTH, RESIDENT_TILE_CAP};+pub use resident::{evict, resident_set, stands_in_for_visible, zoom_out_burst, ANCESTOR_DEPTH, DESCENDANT_DEPTH, RESIDENT_BYTE_BUDGET, RESIDENT_TILE_CAP}; pub use tile_id::TileId;
library/map/src/main/rust/src/tile/select/resident.rs
diff --git a/library/map/src/main/rust/src/tile/select/resident.rs b/library/map/src/main/rust/src/tile/select/resident.rsindex cb7d3fe491..0b260536e0 100644--- a/library/map/src/main/rust/src/tile/select/resident.rs+++ b/library/map/src/main/rust/src/tile/select/resident.rs@@ -18,8 +18,8 @@ pub fn zoom_out_burst(last_zoom: Option<f64>, zoom: f64) -> bool {  /// The most tiles allowed resident on the GPU at once. ///-/// Eviction is the only thing bounding tile memory — there is no separate budget — so this is a-/// real limit rather than a safety net. It matters more now that descendants are kept: an+/// Together with [`RESIDENT_BYTE_BUDGET`] this bounds tile memory, so it is a real limit rather+/// than a safety net. It matters more now that descendants are kept: an /// ancestor set is linear in depth, but a descendant set is not, and without a cap every deep /// tile visited would stay resident for as long as the camera sat above it. ///@@ -46,6 +46,38 @@ pub fn zoom_out_burst(last_zoom: Option<f64>, zoom: f64) -> bool { /// structural demand against it. pub const RESIDENT_TILE_CAP: usize = 64; +/// GPU bytes (vertex + index) the non-visible resident tiles may add on top of what is on+/// screen.+///+/// The count cap alone let 64 dense city tiles stay resident, hundreds of megabytes. Visible+/// tiles are never evicted and ancestors are coarse and few, so only descendants and unrelated+/// tiles answer to this budget: past it they go first, which costs a briefly coarser zoom-out.+pub const RESIDENT_BYTE_BUDGET: u64 = 48 * 1024 * 1024;++/// Which resident tiles to evict, given each as `(rank, key, gpu_bytes)`.+///+/// Rank 0 is visible, 1 an ancestor, 2 a descendant stand-in, 3 unrelated. Rank 3 always goes;+/// past `cap` tiles anything but rank 0 goes; and once the running byte total (in rank order)+/// passes `byte_budget`, ranks 2 and 3 go. Visible tiles are never evicted: evicting one only+/// refetches it next frame.+pub fn evict(ranked: &mut [(u8, u64, u64)], cap: usize, byte_budget: u64) -> Vec<u64> {+    ranked.sort_unstable_by_key(|&(rank, key, _)| (rank, key));+    let mut bytes = 0u64;+    let mut kept = 0usize;+    let mut doomed = Vec::new();+    for &(rank, key, size) in ranked.iter() {+        let over_cap = kept >= cap && rank != 0;+        let over_budget = bytes.saturating_add(size) > byte_budget && rank >= 2;+        if rank == 3 || over_cap || over_budget {+            doomed.push(key);+        } else {+            kept += 1;+            bytes = bytes.saturating_add(size);+        }+    }+    doomed+}+ /// How many levels of descendant to *keep* when they are already resident. /// /// The mirror of [`ANCESTOR_DEPTH`], and the reason zooming out no longer blanks the map. An
library/map/src/main/rust/src/tile/select/tests_part3.rs
diff --git a/library/map/src/main/rust/src/tile/select/tests_part3.rs b/library/map/src/main/rust/src/tile/select/tests_part3.rsindex c2e62efcbb..ee677bd5a0 100644--- a/library/map/src/main/rust/src/tile/select/tests_part3.rs+++ b/library/map/src/main/rust/src/tile/select/tests_part3.rs@@ -152,3 +152,31 @@ fn resident_demand_fits_the_cap_with_headroom() {         worst_globe.1,     ); }++const MIB: u64 = 1024 * 1024;++#[test]+fn eviction_drops_unrelated_and_never_visible() {+    let mut ranked = vec![(0, 1, 500 * MIB), (0, 2, 500 * MIB), (3, 9, 1)];+    assert_eq!(evict(&mut ranked, 1, 0), vec![9]);+}++#[test]+fn eviction_spends_the_byte_budget_on_descendants_last() {+    // Visible + ancestors already fill the budget: descendants go, ancestors stay.+    let mut ranked = vec![+        (2, 30, 8 * MIB),+        (1, 20, 4 * MIB),+        (0, 10, 40 * MIB),+        (2, 31, 1 * MIB),+    ];+    let doomed = evict(&mut ranked, 64, 48 * MIB);+    assert_eq!(doomed, vec![30]);+}++#[test]+fn eviction_counts_the_cap_over_kept_tiles_only() {+    let mut ranked = vec![(0, 1, 0), (2, 2, 100 * MIB), (2, 3, 0), (1, 4, 0)];+    // Tile 2 is over the byte budget; it must not use up a cap slot that tile 3 needs.+    assert_eq!(evict(&mut ranked, 3, 50 * MIB), vec![2]);+}
library/map/src/main/rust/src/vulkan/buffers.rs
diff --git a/library/map/src/main/rust/src/vulkan/buffers.rs b/library/map/src/main/rust/src/vulkan/buffers.rsindex 2ef4ef9c96..17fbff1d80 100644--- a/library/map/src/main/rust/src/vulkan/buffers.rs+++ b/library/map/src/main/rust/src/vulkan/buffers.rs@@ -264,6 +264,23 @@ impl ScratchRing {         }     } +    /// Free every block past the first, dropping a dense frame's high-water mark.+    ///+    /// # Safety+    ///+    /// The device must be idle, or no command buffer may still reference the ring.+    pub unsafe fn shrink(&mut self, device: &ash::Device) {+        for block in self.blocks.drain(1.min(self.blocks.len())..) {+            device.unmap_memory(block.memory);+            device.destroy_buffer(block.buffer, None);+            device.free_memory(block.memory, None);+        }+        if let Some(first) = self.blocks.first_mut() {+            first.used = 0;+        }+        self.cursor = 0;+    }+     /// # Safety     ///     /// The device must be idle, or no command buffer may still reference the ring.
library/map/src/main/rust/src/vulkan/images.rs
diff --git a/library/map/src/main/rust/src/vulkan/images.rs b/library/map/src/main/rust/src/vulkan/images.rsindex 66f4c35f6b..298ecdcbfe 100644--- a/library/map/src/main/rust/src/vulkan/images.rs+++ b/library/map/src/main/rust/src/vulkan/images.rs@@ -142,20 +142,29 @@ impl SampledImage {                 pixels.len()             ));         }-        // SwiftShader (the emulator's Vulkan) advertises sampled R8 but its-        // optimal-tiling R8 path is less exercised than RGBA8; expand R8 → RGBA8-        // so the image, view and sampler all take the universally-supported-        // path. Costs 4x atlas bytes (4 MB, one-time). The byte order is the-        // shader contract — see `glyph::expand_sdf_r8_to_rgba8`, which owns it-        // so a host test pins it.+        // SwiftShader (the emulator's Vulkan) advertises sampled R8 but its optimal-tiling R8+        // path is less exercised than RGBA8, so there (or on a device without linear-filtered+        // R8) the atlas is expanded R8 → RGBA8 at 4x the bytes. Everywhere else it stays R8 and+        // the view swizzles R into all four channels, which samples exactly like the expansion:+        // `glyph::expand_sdf_r8_to_rgba8` owns that byte-order contract and a host test pins it.         let rgba;         let (upload_pixels, upload_format) = match format {-            vk::Format::R8_UNORM => {+            vk::Format::R8_UNORM if !r8_sampling_ok(instance, physical_device) => {                 rgba = crate::tile::glyph::expand_sdf_r8_to_rgba8(pixels);                 (rgba.as_slice(), vk::Format::R8G8B8A8_UNORM)             }             _ => (pixels, format),         };+        let components = if upload_format == vk::Format::R8_UNORM {+            vk::ComponentMapping {+                r: vk::ComponentSwizzle::R,+                g: vk::ComponentSwizzle::R,+                b: vk::ComponentSwizzle::R,+                a: vk::ComponentSwizzle::R,+            }+        } else {+            vk::ComponentMapping::default()+        };         let _ = bpp;         // Device-local image, host-visible staging buffer (the Buffer helper is         // vertex/index-shaped; staging wants TRANSFER_SRC so do it inline).@@ -312,6 +321,7 @@ impl SampledImage {             .image(image)             .view_type(vk::ImageViewType::TYPE_2D)             .format(upload_format)+            .components(components)             .subresource_range(vk::ImageSubresourceRange {                 aspect_mask: vk::ImageAspectFlags::COLOR,                 base_mip_level: 0,@@ -357,3 +367,19 @@ impl SampledImage {         device.destroy_image(self.image, None);     } }++/// Whether R8 atlases can stay R8 on this device: not SwiftShader, and R8 supports linear+/// sampling with optimal tiling.+unsafe fn r8_sampling_ok(instance: &ash::Instance, physical_device: vk::PhysicalDevice) -> bool {+    let props = instance.get_physical_device_properties(physical_device);+    let name = std::ffi::CStr::from_ptr(props.device_name.as_ptr()).to_string_lossy();+    if name.contains("SwiftShader") {+        return false;+    }+    instance+        .get_physical_device_format_properties(physical_device, vk::Format::R8_UNORM)+        .optimal_tiling_features+        .contains(+            vk::FormatFeatureFlags::SAMPLED_IMAGE | vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR,+        )+}
library/map/src/main/rust/src/vulkan/renderer/mod.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod.rs b/library/map/src/main/rust/src/vulkan/renderer/mod.rsindex 84fcf1d6b7..9d824e3f97 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -76,9 +76,8 @@ struct LayerBuffers { /// who owns the memory — which is why the draw path binds `(buffer, offset)` pairs plus a /// per-draw `firstIndex` and never asks which path produced them. ///-/// Ownership on retire: fresh pools are destroyed with the tile; arena ranges belong to-/// the pool and are never freed (see `collect_retired`, which tells them apart by buffer-/// handle, not by offset — offset 0 is a valid arena start).+/// Ownership on retire: fresh pools are destroyed with the tile; arena ranges go back to the+/// pool's free lists ([`arena_ranges`](Self::arena_ranges)) once the grace period is over. /// /// `pub(crate)`: the pick-snapshot split (`placement_refresh`) resolves one /// label against a tile, so it names this type.@@ -98,9 +97,10 @@ pub(crate) struct ResidentTile {     /// Same `(handle, offset, handle, offset)` shape as [`flat`](Self::flat).     ribbons: Option<(vk::Buffer, vk::DeviceSize, vk::Buffer, vk::DeviceSize)>,     /// Fresh-path owned buffers (up to 6: flat/lines/ribbons × vertices/indices), destroyed-    /// with the tile. Empty on the pooled path — arena ranges belong to the pool and are-    /// never freed (see `upload_pool`).+    /// with the tile. Empty on the pooled path.     fresh_owned: Vec<Buffer>,+    /// Pooled-path arena ranges, released to the pool when the tile leaves the retiring queue.+    arena_ranges: Vec<upload_pool::ArenaRange>,     layers: Vec<LayerBuffers>,     /// The tile's extruded 3D buildings, or `None` below z14 / where the tile has none. Drawn in     /// its own depth-tested pass ([`Renderer::record_buildings`]), not the flat layer loop.
library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rsindex 60060a22ba..7deceb20b1 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs@@ -196,8 +196,8 @@ pub struct Renderer {     /// before the first submit and after anything that invalidates unconditionally     /// (swapchain rebuild), forcing the next frame through.     pub(crate) last_frame_version: Option<FrameVersion>,-    /// Tile-upload staging arenas (see `upload_pool`): bump-allocated once, never freed-    /// until the renderer dies, so a tile upload costs copies but no `vkAllocateMemory`.+    /// Tile-upload staging arenas (see `upload_pool`): sub-allocated per tile and recycled on+    /// retire, so a tile upload costs copies but no `vkAllocateMemory`.     pub(crate) upload_pool: UploadPool,     /// Which resident tiles are fully covered by settled finer tiles     /// ([`cover`](crate::tile::select::cover)), per draw group: the
library/map/src/main/rust/src/vulkan/renderer/upload.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload.rs b/library/map/src/main/rust/src/vulkan/renderer/upload.rsindex a50a65d507..4f7791d71f 100644--- a/library/map/src/main/rust/src/vulkan/renderer/upload.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/upload.rs@@ -18,7 +18,10 @@ impl Renderer {     /// ribbon carriageways in [`ribbons`](ResidentTile::ribbons). Buildings and terrain are     /// already one mesh per tile and keep their own pair. A dense tile costs ~5 allocations     /// instead of ~60-100, on the same Choreographer callback as before.-    pub fn upload(&mut self, key: u64, mesh: &TileMesh) -> Result<(), String> {+    ///+    /// Takes the mesh by value so its CPU-side parts (labels, arrows, heightmap, region rings)+    /// move onto the resident tile instead of being cloned beside a copy that is then dropped.+    pub fn upload(&mut self, key: u64, mut mesh: TileMesh) -> Result<(), String> {         use crate::style::LayerKind;         use crate::tess::{fill, ribbon, stroke};         use crate::vulkan::buffers::upload_packed;@@ -78,9 +81,9 @@ impl Renderer {         // through to fresh buffers below, counting the allocation — so `Step::UploadAllocs`         // reads zero in the steady state and names every fallback.         //-        // SAFETY: arena ranges are bump-allocated and never reused for another tile, so no-        // live draw can reference the ranges this commit writes; draws bind the committed-        // offsets below, which outlive the tile like every other resident buffer.+        // SAFETY: a pooled range is only handed out again after the tile that held it has+        // left the retiring queue (frames-in-flight grace), so no live draw can reference+        // the ranges this commit writes.         //         // The pooled path needs the same `first_index` bookkeeping the fresh path does         // below (layer slices, region/traffic/carriageway lookups), so both paths funnel@@ -173,7 +176,7 @@ impl Renderer {         let (flat_first_src, line_first_src, ribbon_first_src) =             upload_tail::first_index_lists(&pooled_buffers, &flat, &lines, &ribbons);         let layers = upload_tail::build_layers(-            mesh,+            &mesh,             &flat_layer_at,             &line_layer_at,             &flat_first_src,@@ -181,10 +184,10 @@ impl Renderer {         );         let flat_first: Vec<u32> = flat_first_src;         let line_first: Vec<u32> = line_first_src;-        let regions = upload_tail::build_regions(mesh, &flat_region_at, &flat_first);-        let traffic = upload_tail::build_traffic(mesh, &line_traffic_at, &line_first);+        let regions = upload_tail::build_regions(&mut mesh, &flat_region_at, &flat_first);+        let traffic = upload_tail::build_traffic(&mesh, &line_traffic_at, &line_first);         let ribbon_first: Vec<u32> = ribbon_first_src;-        let carriageways = upload_tail::build_carriageways(mesh, &ribbon_first);+        let carriageways = upload_tail::build_carriageways(&mesh, &ribbon_first);         // The tile's 3D buildings, if any: one combined mesh, uploaded fresh — 2 allocs         // when present, counted below. Buildings and terrain stay on the fresh path         // deliberately: they are single meshes per tile (not packed groups), rare (z14+@@ -267,7 +270,7 @@ impl Renderer {             .get(&key)             .map(|previous| previous.uploaded_at)             .unwrap_or_else(|| self.last_camera.map(|c| c.time_seconds).unwrap_or(0.0));-        let tile = upload_tail::assemble_tile(+        let mut tile = upload_tail::assemble_tile(             &pooled_buffers,             (flat, lines, ribbons),             layers,@@ -276,9 +279,10 @@ impl Renderer {             carriageways,             buildings,             terrain,-            mesh,+            &mut mesh,             uploaded_at,         );+        tile.arena_ranges = pooled.as_ref().map(|s| s.ranges()).unwrap_or_default();         if let Some(previous) = self.tiles.insert(key, tile) {             self.retire(previous);         }@@ -297,26 +301,79 @@ impl Renderer {     }      /// Drop resident tiles that are neither wanted nor useful as a stand-in, and enforce-    /// the residency cap. Split into `upload_tail` (file-length limit); see it for the-    /// ranking contract — this only forwards, so the call sites are unchanged.-    pub fn retain(&mut self, keep: &[u64], visible: &[select::TileId], cap: usize) {-        upload_tail::retain(self, keep, visible, cap);+    /// the residency cap and byte budget. Split into `upload_tail` (file-length limit).+    pub fn retain(+        &mut self,+        keep: &[u64],+        visible: &[select::TileId],+        cap: usize,+        byte_budget: u64,+    ) {+        upload_tail::retain(self, keep, visible, cap, byte_budget);+    }++    /// Give memory back under system pressure: evict every resident tile not in `visible`+    /// (all of them when it is empty), wait for the GPU, then free retired tiles, empty+    /// arenas and the scratch rings' high-water blocks at once rather than over the next+    /// frames, which may never come while the app is in the background.+    pub fn trim(&mut self, visible: &std::collections::HashSet<u64>) {+        let doomed: Vec<u64> = self+            .tiles+            .keys()+            .filter(|key| !visible.contains(key))+            .copied()+            .collect();+        if !doomed.is_empty() {+            self.bump_residency();+        }+        for key in doomed {+            if let Some(tile) = self.tiles.remove(&key) {+                self.retire(tile);+            }+        }+        // SAFETY: after `device_wait_idle` no command buffer references anything retired.+        unsafe {+            if self.context.device.device_wait_idle().is_err() {+                return;+            }+            for (remaining, _) in &mut self.retiring {+                *remaining = 0;+            }+            for transient in &mut self.transients {+                transient.frames = 0;+            }+            for (remaining, _) in &mut self.moon_retiring {+                *remaining = 0;+            }+            self.collect_retired();+            let keep_first = !self.tiles.is_empty();+            self.upload_pool+                .release_empty_arenas(&self.context.device, keep_first);+            for ring in &mut self.scratch {+                ring.shrink(&self.context.device);+            }+        }     } -    /// Free anything whose grace period has expired. Split into `upload_tail`-    /// (file-length limit): `fresh_owned` destroys, arena ranges free nothing — see-    /// `free_retired_tile` for the ownership rule.+    /// Free anything whose grace period has expired. `fresh_owned` buffers are destroyed;+    /// arena ranges go back to the pool, and arenas past the first that empty out are freed.     pub(super) fn collect_retired(&mut self) {         self.collect_moon_retired();         let device = self.context.device.clone();+        let pool = &mut self.upload_pool;         self.retiring.retain_mut(|(remaining, tile)| {             if *remaining > 0 {                 *remaining -= 1;                 return true;             }+            for range in &tile.arena_ranges {+                pool.release(range);+            }             upload_tail::free_retired_tile_owned(tile, &device);             false         });+        // SAFETY: ranges were released only after their grace period (above).+        unsafe { self.upload_pool.release_empty_arenas(&device, true) };         // Transient per-frame symbol buffers retire on the same grace count, in         // their own queue — no device_wait_idle stall on the frame path.         // `device` is the owned clone above, so borrows are explicit: `destroy`
library/map/src/main/rust/src/vulkan/renderer/upload_moon.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload_moon.rs b/library/map/src/main/rust/src/vulkan/renderer/upload_moon.rsindex 12c84588da..825175e69c 100644--- a/library/map/src/main/rust/src/vulkan/renderer/upload_moon.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/upload_moon.rs@@ -146,6 +146,25 @@ impl Renderer {         Ok(())     } +    /// Retire the Moon pair and its descriptor pool; a Moon frame then draws the clear colour+    /// until the next [`set_moon_textures`](Self::set_moon_textures).+    pub fn clear_moon_textures(&mut self) {+        let had = self.moon_color.is_some() || self.moon_dem.is_some() || self.moon_pool.is_some();+        if let Some(color) = self.moon_color.take() {+            self.retire_moon_image(color);+        }+        if let Some(dem) = self.moon_dem.take() {+            self.retire_moon_image(dem);+        }+        if let Some(pool) = self.moon_pool.take() {+            self.retire_moon_pool(pool);+        }+        self.moon_set = None;+        if had {+            self.bump_state();+        }+    }+     fn retire_moon_image(&mut self, image: SampledImage) {         // Images are not buffers: hold them aside with the same frame count and         // destroy on drain (see `collect_retired`).
library/map/src/main/rust/src/vulkan/renderer/upload_pool.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload_pool.rs b/library/map/src/main/rust/src/vulkan/renderer/upload_pool.rsindex 2e00641e66..6c28756b03 100644--- a/library/map/src/main/rust/src/vulkan/renderer/upload_pool.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/upload_pool.rs@@ -6,24 +6,24 @@ //! burst of finished tiles landing in one frame is the frame-time tail P0 measured. //! //! [`UploadPool`] fixes the remaining per-tile allocation: one persistent 8 MiB vertex arena-//! and one 4 MiB index arena, bump-allocated per upload and never freed until the renderer-//! dies. A tile's meshes pack into the arenas exactly as [`upload_packed`] packs them into-//! fresh buffers — same slices, same `first_index` rebasing — except the slices name+//! and one 4 MiB index arena, sub-allocated per upload from a first-fit free list+//! ([`RangeAlloc`]). A tile's meshes pack into the arenas exactly as [`upload_packed`] packs+//! them into fresh buffers — same slices, same `first_index` rebasing — except the slices name //! (arena, byte offset) ranges instead of whole buffers, and draws bind those offsets. //!-//! Lifetime is the whole point, so it is stated plainly: arena memory is never reused for a-//! *different* tile. When an arena fills, the pool allocates the next arena (up to-//! [`MAX_ARENAS`]); a tile larger than one arena falls back to fresh buffers. Retired tiles-//! free nothing — their ranges simply leak until the renderer dies — which bounds the waste-//! to the residency cap (64 tiles × one upload each, amortised across arenas) instead of-//! paying an allocator round-trip per tile per upload. Tiles re-upload rarely (only on-//! generation changes), so the leak is cold, while the per-frame win is hot.+//! Lifetime: a tile's ranges ([`ArenaRange`]) go back to the free list only when the tile+//! leaves the retiring queue, i.e. after the frames-in-flight grace, so no in-flight draw can+//! read a range that a later upload overwrites. When an arena fills, the pool allocates the+//! next (up to [`MAX_ARENAS`]); a tile larger than one arena falls back to fresh buffers. An+//! arena past the first that empties out is destroyed, so a burst does not pin its high-water+//! mark for the session. //! //! Every fresh allocation the drain still issues (fallback path, first-fill growth) is //! counted into `Step::UploadAllocs`: the overlay row reads zero in the steady state, and //! any nonzero names the path to fix. Pooled uploads record nothing. //! //! Split out (file-length limit); `upload.rs` calls in, never the reverse.+use crate::range_alloc::{align_up, RangeAlloc}; use crate::vulkan::buffers::Buffer; use crate::timing::Step; use super::Renderer;@@ -36,25 +36,38 @@ const VERTEX_ARENA_BYTES: vk::DeviceSize = 8 * 1024 * 1024; /// cold-start burst, few enough that a pathological session cannot eat the device. const MAX_ARENAS: usize = 4; -/// One persistent upload arena pair, bump-allocated and never compacted.+/// One upload arena pair and the free lists over it. /// /// `vertices`/`indices` are whole-arena buffers: tiles own *ranges* of them, never the-/// buffers, so `Drop`/`collect_retired` must never destroy these through a tile — only-/// [`destroy_pool`] destroys arenas, once, at renderer teardown.+/// buffers, so nothing destroys these through a tile — only [`destroy_pool`] and+/// [`UploadPool::release_empty_arenas`] do. struct Arena {     vertices: Buffer,     indices: Buffer,-    used_verts: vk::DeviceSize,-    used_indices: vk::DeviceSize,+    vert_alloc: RangeAlloc,+    index_alloc: RangeAlloc, } -/// The renderer's tile-upload pool: arena pairs plus the fresh-allocation counter.-///-/// Arena buffers are owned here and ONLY here: `upload.rs` borrows their handles for-/// draws and `collect_retired`/`Drop` consult them by handle comparison, but neither-/// ever destroys them — only [`destroy_pool`] does, once, at renderer teardown.+/// A tile's claim on one arena, handed back by [`UploadPool::release`] once the tile retires.+#[derive(Clone, Copy)]+pub(super) struct ArenaRange {+    arena: usize,+    vert_offset: vk::DeviceSize,+    vert_len: vk::DeviceSize,+    index_offset: vk::DeviceSize,+    index_len: vk::DeviceSize,+}++impl ArenaRange {+    pub(super) fn bytes(&self) -> u64 {+        self.vert_len + self.index_len+    }+}++/// The renderer's tile-upload pool. Slots stay put (a destroyed arena leaves `None`) so the+/// arena index in an [`ArenaRange`] never shifts under a live tile. pub(super) struct UploadPool {-    pub(super) arenas: Vec<Arena>,+    arenas: Vec<Option<Arena>>, }  impl UploadPool {@@ -66,12 +79,52 @@ impl UploadPool {     /// Null handles when the index names no arena — never panics on a stale slice.     /// A null bind draws nothing, exactly as a missing pool did on the fresh path.     pub(super) fn arena_buffers(&self, index: usize) -> (vk::Buffer, vk::Buffer) {-        self.arenas.get(index).map_or_else(+        self.arenas.get(index).and_then(Option::as_ref).map_or_else(             || (vk::Buffer::null(), vk::Buffer::null()),             |a| (a.vertices.buffer, a.indices.buffer),         )     } +    /// Hand a retired tile's range back to its arena's free lists.+    ///+    /// Only after the tile's grace period: the range may be overwritten by the next upload.+    pub(super) fn release(&mut self, range: &ArenaRange) {+        let Some(Some(arena)) = self.arenas.get_mut(range.arena) else {+            return;+        };+        if range.vert_len > 0 {+            arena.vert_alloc.release(range.vert_offset, range.vert_len);+        }+        if range.index_len > 0 {+            arena.index_alloc.release(range.index_offset, range.index_len);+        }+    }++    /// Destroy arenas no tile holds a range in. The first is kept while `keep_first`, since+    /// an empty mesh group's placeholder names arena 0's handle.+    ///+    /// # Safety+    ///+    /// Ranges are only released after the grace period, so an empty arena has no in-flight+    /// reader; the caller must uphold that by releasing through [`release`](Self::release).+    pub(super) unsafe fn release_empty_arenas(&mut self, device: &ash::Device, keep_first: bool) {+        let skip = usize::from(keep_first);+        for slot in self.arenas.iter_mut().skip(skip) {+            if slot+                .as_ref()+                .is_some_and(|a| a.vert_alloc.is_empty() && a.index_alloc.is_empty())+            {+                if let Some(arena) = slot.take() {+                    arena.vertices.destroy(device);+                    arena.indices.destroy(device);+                }+            }+        }+        while matches!(self.arenas.last(), Some(None)) {+            self.arenas.pop();+        }+    }+     /// Whether `buffer` is an arena buffer owned by this pool (never destroyed through     /// a tile) rather than a fresh per-tile buffer.     ///@@ -81,6 +134,7 @@ impl UploadPool {     pub(super) fn owns_buffer(&self, b: vk::Buffer) -> bool {         self.arenas             .iter()+            .flatten()             .any(|a| a.vertices.buffer == b || a.indices.buffer == b)     } @@ -106,10 +160,36 @@ pub(super) struct PooledPacked {     pub index_offset: vk::DeviceSize,     /// Arena index holding this group.     pub arena: usize,+    /// Reserved (aligned) byte lengths; zero for an empty group's placeholder.+    pub vert_len: vk::DeviceSize,+    pub index_len: vk::DeviceSize,     /// Per-mesh `firstIndex` values, rebased to absolute like [`upload_packed`].     pub first_index: Vec<u32>, } +impl PooledPacked {+    fn placeholder() -> PooledPacked {+        PooledPacked {+            vert_offset: 0,+            index_offset: 0,+            arena: 0,+            vert_len: 0,+            index_len: 0,+            first_index: Vec::new(),+        }+    }++    fn range(&self) -> ArenaRange {+        ArenaRange {+            arena: self.arena,+            vert_offset: self.vert_offset,+            vert_len: self.vert_len,+            index_offset: self.index_offset,+            index_len: self.index_len,+        }+    }+}+ /// Arena-backed slices for one tile's three packed groups. pub(super) struct TileArenaSlices {     pub flat: PooledPacked,@@ -117,6 +197,17 @@ pub(super) struct TileArenaSlices {     pub ribbons: PooledPacked, } +impl TileArenaSlices {+    /// The ranges the tile must hand back on retire (placeholders hold none).+    pub(super) fn ranges(&self) -> Vec<ArenaRange> {+        [&self.flat, &self.lines, &self.ribbons]+            .into_iter()+            .filter(|p| p.vert_len > 0 || p.index_len > 0)+            .map(PooledPacked::range)+            .collect()+    }+}+ /// The per-tile mesh groups `upload` packs, in arena-commit order. pub(super) struct UploadGroups<'a> {     pub flat: &'a [(&'a [f32], &'a [u32])],@@ -172,13 +263,10 @@ fn pack_group(stride_floats: usize, meshes: &[(&[f32], &[u32])]) -> (Vec<f32>, V     (packed_verts, packed_indices) } -fn align64(v: vk::DeviceSize) -> vk::DeviceSize {-    (v + 63) & !63-}--/// Fit one packed group into an existing arena; `None` when none fits.-fn try_fit(-    pool: &UploadPool,+/// Reserve one packed group's ranges in the first arena with room for both; `None` when+/// none has.+fn try_reserve(+    pool: &mut UploadPool,     meshes: &[(&[f32], &[u32])],     vert_bytes: vk::DeviceSize,     index_bytes: vk::DeviceSize,@@ -186,17 +274,24 @@ fn try_fit(     if vert_bytes == 0 || index_bytes == 0 {         return None;     }-    for (n, arena) in pool.arenas.iter().enumerate() {-        let vo = align64(arena.used_verts);-        let io = align64(arena.used_indices);-        if vo + vert_bytes <= arena.vertices.size && io + index_bytes <= arena.indices.size {-            return Some(PooledPacked {-                vert_offset: vo,-                index_offset: io,-                arena: n,-                first_index: rebase_first_index(meshes),-            });+    for (n, slot) in pool.arenas.iter_mut().enumerate() {+        let Some(arena) = slot else { continue };+        if !arena.vert_alloc.fits(vert_bytes) || !arena.index_alloc.fits(index_bytes) {+            continue;         }+        let vert_offset = arena.vert_alloc.alloc(vert_bytes)?;+        let Some(index_offset) = arena.index_alloc.alloc(index_bytes) else {+            arena.vert_alloc.release(vert_offset, vert_bytes);+            return None;+        };+        return Some(PooledPacked {+            vert_offset,+            index_offset,+            arena: n,+            vert_len: align_up(vert_bytes),+            index_len: align_up(index_bytes),+            first_index: rebase_first_index(meshes),+        });     }     None }@@ -228,19 +323,23 @@ fn grow_arenas(renderer: &mut Renderer) -> Result<(), String> {                 return Err(e);             }         };-        renderer.upload_pool.arenas.push(Arena {+        let arena = Arena {+            vert_alloc: RangeAlloc::new(vertices.size),+            index_alloc: RangeAlloc::new(indices.size),             vertices,             indices,-            used_verts: 0,-            used_indices: 0,-        });+        };+        let pool = &mut renderer.upload_pool;+        match pool.arenas.iter_mut().find(|slot| slot.is_none()) {+            Some(slot) => *slot = Some(arena),+            None => pool.arenas.push(Some(arena)),+        }     }     Ok(()) } -/// Copy packed bytes into a reserved arena range. The cursors advance even if a map-/// fails: the range is abandoned, never reused, so a failed copy cannot corrupt a later-/// tile — but the caller must then fall back rather than draw the range.+/// Copy packed bytes into a reserved arena range. On failure the caller releases the+/// range and falls back rather than drawing it. unsafe fn commit_bytes(     renderer: &Renderer,     packed: &PooledPacked,@@ -248,7 +347,7 @@ unsafe fn commit_bytes(     packed_indices: &[u32], ) -> bool {     let device = &renderer.context.device;-    let Some(arena) = renderer.upload_pool.arenas.get(packed.arena) else {+    let Some(Some(arena)) = renderer.upload_pool.arenas.get(packed.arena) else {         return false;     };     let vert_bytes = std::mem::size_of_val(packed_verts) as vk::DeviceSize;@@ -292,33 +391,15 @@ unsafe fn commit_bytes(     ok_v && ok_i } -fn advance_arena(pool: &mut UploadPool, packed: &PooledPacked, vert_bytes: u64, index_bytes: u64) {-    // Empty groups reserve nothing — their slice is a placeholder naming arena 0 at-    // offset 0. Advancing one would reset a live arena's cursor to zero and hand its-    // ranges back out to the next tile, stomping live draws. Only committed bytes-    // move a cursor.-    if vert_bytes == 0 && index_bytes == 0 {-        return;-    }-    let Some(arena) = pool.arenas.get_mut(packed.arena) else {-        return;-    };-    arena.used_verts = packed.vert_offset + vert_bytes;-    arena.used_indices = packed.index_offset + index_bytes;-}- /// Reserve one group's arena space, growing the pool once on a miss. /// /// Returns `None` for an empty group (no reservation, no slices) and when the group /// fits nowhere even after growth — the caller falls back for the whole tile. Growth /// counts 2 into `Step::UploadAllocs` (one vertex + one index arena). ///-/// The cursor moves when the range is handed out, not after its bytes land: the three-/// groups reserve in turn against one pool, so a later group must see the earlier-/// group's range as taken even though nothing is committed yet. Reserving without-/// advancing would hand every group the same range and each commit would stomp the-/// previous group's bytes. A later commit failure abandons the range (never reused,-/// never drawn — the tile falls back to fresh), exactly as `commit_bytes` documents.+/// The range comes off the free list at reserve time, not after its bytes land: the three+/// groups reserve in turn against one pool, so a later group must see the earlier group's+/// range as taken. A later commit failure releases it again (see `commit_tile_groups`). fn reserve_group(     renderer: &mut Renderer,     meshes: &[(&[f32], &[u32])],@@ -333,101 +414,76 @@ fn reserve_group(     if bytes.0 > VERTEX_ARENA_BYTES || bytes.1 > VERTEX_ARENA_BYTES / 2 {         return None;     }-    if let Some(reserved) = try_fit(&renderer.upload_pool, meshes, bytes.0, bytes.1) {-        advance_arena(&mut renderer.upload_pool, &reserved, bytes.0, bytes.1);+    if let Some(reserved) = try_reserve(&mut renderer.upload_pool, meshes, bytes.0, bytes.1) {         return Some(reserved);     }-    if renderer.upload_pool.arenas.len() >= MAX_ARENAS {+    if renderer.upload_pool.arenas.iter().flatten().count() >= MAX_ARENAS {         return None;     }     grow_arenas(renderer).ok()?;     UploadPool::record_allocs(renderer, 2);-    // The new arena is empty, so the size check above guarantees the fit; no earlier-    // arena fit, so this names the new one.-    let reserved = try_fit(&renderer.upload_pool, meshes, bytes.0, bytes.1)?;-    advance_arena(&mut renderer.upload_pool, &reserved, bytes.0, bytes.1);-    Some(reserved)+    // The new arena is empty, so the size check above guarantees the fit.+    try_reserve(&mut renderer.upload_pool, meshes, bytes.0, bytes.1) }  /// Commit one tile's three packed groups into the pool. /// /// Reserves all three groups first (growing the pool if an empty arena is needed), then /// packs and copies each group. Returns the arena slices, or `None` when any group did-/// not fit or any copy failed — the caller falls back to fresh buffers for the whole-/// tile. Mixing pooled and fresh slices per group would double the slice bookkeeping-/// for no steady-state gain, since the common case fits entirely.+/// not fit or any copy failed — every range reserved for the tile is released and the+/// caller falls back to fresh buffers for the whole tile. Mixing pooled and fresh slices+/// per group would double the slice bookkeeping for no steady-state gain, since the+/// common case fits entirely. /// /// Growth counts 2 into `Step::UploadAllocs` (one vertex + one index arena); a fully /// pooled tile counts nothing.-///-/// Takes `&mut Renderer` (not `&Renderer`) because reserving may grow the pool: the-/// caller is `upload()`, which already holds `&mut self`. pub(super) unsafe fn commit_tile_groups(     renderer: &mut Renderer,     groups: UploadGroups<'_>, ) -> Option<TileArenaSlices> {     use crate::tess::{fill, ribbon, stroke};-    let flat_bytes = group_bytes(groups.flat);-    let line_bytes = group_bytes(groups.lines);-    let ribbon_bytes = group_bytes(groups.ribbons);-    // Reserve each group in turn; grow once on the first miss and retry that group; fail-    // the tile if it still misses. A group with no bytes reserves nothing.-    let flat = reserve_group(renderer, groups.flat, flat_bytes);-    let lines = reserve_group(renderer, groups.lines, line_bytes);-    let ribbons = reserve_group(renderer, groups.ribbons, ribbon_bytes);-    // Groups with no bytes reserved nothing: build their empty slices explicitly so the-    // tile below still carries all three groups. A group WITH bytes that reserved-    // nothing means the tile does not fit: fall back for the whole tile.-    let flat = match (flat_bytes, flat) {-        ((0, 0), _) => Some(PooledPacked {-            vert_offset: 0,-            index_offset: 0,-            arena: 0,-            first_index: Vec::new(),-        }),-        (_, r) => r,-    }?;-    let lines = match (line_bytes, lines) {-        ((0, 0), _) => Some(PooledPacked {-            vert_offset: 0,-            index_offset: 0,-            arena: 0,-            first_index: Vec::new(),-        }),-        (_, r) => r,-    }?;-    let ribbons = match (ribbon_bytes, ribbons) {-        ((0, 0), _) => Some(PooledPacked {-            vert_offset: 0,-            index_offset: 0,-            arena: 0,-            first_index: Vec::new(),-        }),-        (_, r) => r,-    }?;-    // Pack the bytes exactly as `upload_packed` does, then commit each non-empty-    // group into its reserved range. The cursors already moved at reserve time, so-    // there is nothing to advance here — a failed commit abandons its range (the-    // tile falls back to fresh) exactly as `commit_bytes` documents.+    let sized = [+        (groups.flat, group_bytes(groups.flat)),+        (groups.lines, group_bytes(groups.lines)),+        (groups.ribbons, group_bytes(groups.ribbons)),+    ];+    // A group with no bytes gets a placeholder slice so the tile still carries all three; a+    // group WITH bytes that reserved nothing means the tile does not fit.+    let reserved = sized.map(|(meshes, bytes)| {+        if bytes == (0, 0) {+            Some(PooledPacked::placeholder())+        } else {+            reserve_group(renderer, meshes, bytes)+        }+    });+    let slices = match reserved {+        [Some(flat), Some(lines), Some(ribbons)] => TileArenaSlices { flat, lines, ribbons },+        partial => {+            for packed in partial.iter().flatten() {+                renderer.upload_pool.release(&packed.range());+            }+            return None;+        }+    };     let (fv, fi) = pack_group(fill::FLOATS_PER_VERTEX, groups.flat);     let (lv, li) = pack_group(stroke::FLOATS_PER_VERTEX, groups.lines);     let (rv, ri) = pack_group(ribbon::FLOATS_PER_VERTEX, groups.ribbons);-    if !fv.is_empty() && !commit_bytes(renderer, &flat, &fv, &fi) {-        return None;-    }-    if !lv.is_empty() && !commit_bytes(renderer, &lines, &lv, &li) {-        return None;-    }-    if !rv.is_empty() && !commit_bytes(renderer, &ribbons, &rv, &ri) {+    let committed = (fv.is_empty() || commit_bytes(renderer, &slices.flat, &fv, &fi))+        && (lv.is_empty() || commit_bytes(renderer, &slices.lines, &lv, &li))+        && (rv.is_empty() || commit_bytes(renderer, &slices.ribbons, &rv, &ri));+    if !committed {+        for range in slices.ranges() {+            renderer.upload_pool.release(&range);+        }         return None;     }-    Some(TileArenaSlices { flat, lines, ribbons })+    Some(slices) }  /// Destroy every arena. Called from the renderer's `Drop`, after the device goes idle — /// the same contract as every other buffer the renderer owns. pub(super) unsafe fn destroy_pool(pool: &mut UploadPool, device: &ash::Device) {-    for arena in pool.arenas.drain(..) {+    for arena in pool.arenas.drain(..).flatten() {         arena.vertices.destroy(device);         arena.indices.destroy(device);     }
library/map/src/main/rust/src/vulkan/renderer/upload_tail.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload_tail.rs b/library/map/src/main/rust/src/vulkan/renderer/upload_tail.rsindex 157c8cc9ad..f52f94bd3d 100644--- a/library/map/src/main/rust/src/vulkan/renderer/upload_tail.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/upload_tail.rs@@ -129,13 +129,13 @@ pub(super) fn build_layers( /// FindFamily SIGABRT: the first empty segment made `*_at` shorter than the mesh list /// and `[0]` landed on an empty vec. pub(super) fn build_regions(-    mesh: &TileMesh,+    mesh: &mut TileMesh,     flat_region_at: &[usize],     flat_first: &[u32], ) -> Vec<RegionBuffers> {     let mut regions = Vec::with_capacity(mesh.regions.len());     let mut ri = 0usize;-    for region in &mesh.regions {+    for region in &mut mesh.regions {         if region.indices.is_empty() {             continue;         }@@ -150,7 +150,7 @@ pub(super) fn build_regions(             id: region.id,             first_index,             index_count: region.indices.len() as u32,-            rings: region.rings.clone(),+            rings: std::mem::take(&mut region.rings),             area: region.area,             level: region.level,         });@@ -233,7 +233,7 @@ pub(super) fn assemble_tile(     carriageways: Vec<CarriagewayBuffers>,     buildings: Option<BuildingBuffers>,     terrain: Option<TerrainBuffers>,-    mesh: &TileMesh,+    mesh: &mut TileMesh,     uploaded_at: f32, ) -> ResidentTile {     // Owned buffers follow the fresh triples out (fresh path only; the pooled path@@ -273,6 +273,7 @@ pub(super) fn assemble_tile(         lines: lines_handles,         ribbons: ribbons_handles,         fresh_owned,+        arena_ranges: Vec::new(),         layers,         buildings,         terrain,@@ -280,9 +281,9 @@ pub(super) fn assemble_tile(         traffic,         carriageways,         yellow_centre: mesh.yellow_centre,-        labels: mesh.labels.clone(),-        arrows: mesh.arrows.clone(),-        heightmap: mesh.heightmap.clone(),+        labels: std::mem::take(&mut mesh.labels),+        arrows: std::mem::take(&mut mesh.arrows),+        heightmap: mesh.heightmap.take(),         z: mesh.z,         x: mesh.x,         y: mesh.y,@@ -308,14 +309,9 @@ pub(super) fn is_arena_buffer(pool: &super::upload_pool::UploadPool, b: vk::Buff  /// Free a resident tile's owned GPU buffers after its grace period. ///-/// `fresh_owned` destroys its buffers; arena ranges free nothing (they belong to the-/// pool). Buildings/terrain are always fresh. The CPU-side clones drop with the tile-/// either way. Takes only the tile + device (never the renderer), so the `retain_mut`-/// in `upload.rs` borrows just the retiring queue — no `self` inside the closure.-///-/// Retirement still gates the grace count for both, so a replaced tile's draws stop-/// referencing its ranges before anything reuses them (nothing ever does — but the-/// fence discipline stays uniform).+/// `fresh_owned` destroys its buffers; arena ranges are released by the caller, which holds+/// the pool. Buildings/terrain are always fresh. Takes only the tile + device (never the+/// renderer), so the `retain_mut` in `upload.rs` borrows just the retiring queue. pub(super) fn free_retired_tile_owned(tile: &ResidentTile, device: &ash::Device) {     // SAFETY: the device is idle past the grace count (see `collect_retired`).     unsafe {@@ -359,28 +355,43 @@ pub(super) fn free_tile_set(     } } +/// GPU bytes a resident tile holds: its arena ranges plus every buffer it owns.+pub(super) fn tile_gpu_bytes(tile: &ResidentTile) -> u64 {+    let ranges: u64 = tile.arena_ranges.iter().map(|r| r.bytes()).sum();+    let fresh: u64 = tile.fresh_owned.iter().map(|b| b.size).sum();+    let buildings = tile+        .buildings+        .as_ref()+        .map_or(0, |b| b.vertices.size + b.indices.size);+    let terrain = tile+        .terrain+        .as_ref()+        .map_or(0, |t| t.vertices.size + t.indices.size);+    ranges + fresh + buildings + terrain+}+ /// Drop resident tiles that are neither wanted nor useful as a stand-in, and enforce the-/// residency cap.+/// residency cap and byte budget (see [`select::evict`]). /// /// `keep` is the visible tiles and their ancestors, in the order [`select::resident_set`] /// produced them — coarsest first. `visible` is needed separately because descendants cannot /// be enumerated into a keep list without naming tiles that were never fetched; they are /// recognised here, against what is actually resident.-///-/// This is also the **only** bound on GPU memory. Tiles live until they fall out of this, so-/// the cap is not belt-and-braces: without it, retaining descendants would mean every deep-/// tile visited during a session stays resident for as long as the camera sits above it.-pub fn retain(renderer: &mut Renderer, keep: &[u64], visible: &[select::TileId], cap: usize) {+pub fn retain(+    renderer: &mut Renderer,+    keep: &[u64],+    visible: &[select::TileId],+    cap: usize,+    byte_budget: u64,+) {     use std::collections::HashSet;     let visible_keys: HashSet<u64> = visible.iter().map(|t| t.key()).collect();     let wanted: HashSet<u64> = keep.iter().copied().collect(); -    // Rank by how much is lost if it goes, because the cap has to evict *something* and the-    // stand-ins are what it should reach for first.-    let mut ranked: Vec<(u8, u64)> = renderer+    let mut ranked: Vec<(u8, u64, u64)> = renderer         .tiles-        .keys()-        .map(|&key| {+        .iter()+        .map(|(&key, tile)| {             let rank = if visible_keys.contains(&key) {                 0 // on screen at its own zoom; evicting this is the blank frame itself             } else if wanted.contains(&key) {@@ -390,19 +401,10 @@ pub fn retain(renderer: &mut Renderer, keep: &[u64], visible: &[select::TileId],             } else {                 3 // unrelated to anything on screen             };-            (rank, key)+            (rank, key, tile_gpu_bytes(tile))         })         .collect();-    ranked.sort_unstable();--    // Over the cap, stand-ins go first and on-screen tiles never: evicting a visible tile-    // only refetches it next frame, and a tilted view can need more tiles than the cap holds.-    let doomed: Vec<u64> = ranked-        .iter()-        .enumerate()-        .filter(|(at, (rank, _))| *rank == 3 || (*at >= cap && *rank != 0))-        .map(|(_, (_, key))| *key)-        .collect();+    let doomed = select::evict(&mut ranked, cap, byte_budget);     if doomed.is_empty() {         return;     }
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex e61d87c246..f9b8bef3f3 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -173,14 +173,12 @@ fun MapPage(         }     } -    // The Moon raster pair, loaded lazily on first Moon select (never for Earth-    // sessions): 37MB of assets read once, cached for the session. `body` lives-    // on the chrome (session-only); the textures ride the scope to the surface.+    // The Moon raster pair, loaded on Moon select (never for Earth sessions) and dropped+    // again when the body goes back to Earth, so ~37MB of heap and ~40MB of GPU images are+    // only held while the Moon is actually shown.     var moonTextures by remember { mutableStateOf<MoonTextures?>(null) }     LaunchedEffect(chrome.body) {-        if (chrome.body == MapBody.Moon && moonTextures == null) {-            moonTextures = MoonAssetLoader.load(context)-        }+        moonTextures = if (chrome.body == MapBody.Moon) MoonAssetLoader.load(context) else null     }      // Resolve the P6 map-theme setting against the OS the same way DynamicTheme does, so the map
maps/src/main/java/com/vayunmathur/maps/util/MoonAssetLoader.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MoonAssetLoader.kt b/maps/src/main/java/com/vayunmathur/maps/util/MoonAssetLoader.ktindex f038c955e7..3e6e1cc0d2 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MoonAssetLoader.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MoonAssetLoader.kt@@ -11,9 +11,9 @@ import kotlinx.coroutines.withContext  *  * The assets (`assets/moon/moon_color_4096.rgba` + `moon_dem_2048.rg`,  * converted offline from NASA SVS 4720 by `analysis/convert_moon.py`) total- * ~37MB, so this runs on IO and only on first Moon select — Earth sessions- * never pay the read. The result is cached in memory for the session (the- * native side re-uploads from it on every re-attach).+ * ~37MB, so this runs on IO and only on Moon select — Earth sessions never pay+ * the read. Nothing is cached here: the caller holds the result only while the+ * Moon is shown, and a re-select reads the assets again.  *  * Null when the assets are missing or unreadable: the Moon frame then draws  * the clear colour rather than crashing (see the native `record_moon`).@@ -28,25 +28,18 @@ object MoonAssetLoader {     private const val DEM_W = 2048     private const val DEM_H = 1024 -    @Volatile-    private var cached: MoonTextures? = null--    suspend fun load(context: Context): MoonTextures? {-        cached?.let { return it }-        return withContext(Dispatchers.IO) {-            cached?.let { return@withContext it }-            try {-                val color = context.assets.open(COLOR_ASSET).use { it.readBytes() }-                val dem = context.assets.open(DEM_ASSET).use { it.readBytes() }-                if (color.size != COLOR_W * COLOR_H * COLOR_BYTES_PER_PX ||-                    dem.size != DEM_W * DEM_H * DEM_BYTES_PER_PX-                ) {-                    return@withContext null-                }-                MoonTextures(color, COLOR_W, COLOR_H, dem, DEM_W, DEM_H).also { cached = it }-            } catch (_: IOException) {-                null+    suspend fun load(context: Context): MoonTextures? = withContext(Dispatchers.IO) {+        try {+            val color = context.assets.open(COLOR_ASSET).use { it.readBytes() }+            val dem = context.assets.open(DEM_ASSET).use { it.readBytes() }+            if (color.size != COLOR_W * COLOR_H * COLOR_BYTES_PER_PX ||+                dem.size != DEM_W * DEM_H * DEM_BYTES_PER_PX+            ) {+                return@withContext null             }+            MoonTextures(color, COLOR_W, COLOR_H, dem, DEM_W, DEM_H)+        } catch (_: IOException) {+            null         }     } }