library-map: fix zoom-dependent ocean, island and border rendering
- Commit
2d36f5de63da46b7682cd09d075af028cebec801- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-27 04:05 UTC (2 months ago)
- Parents
6802332
Diff
library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.ktindex 53f2c22e18..adb3856bec 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -356,13 +356,15 @@ private val POI_LAYER_IDS = setOf( ) /**- * Shown before any tile has loaded. Matches the renderer's own backdrop, so the surface- * appearing does not flash a different colour.+ * Shown before any tile has loaded. Matches the renderer's own clear colour (the water-blue+ * `background` in `style/basemap.flat.json`: `#80deea` light, `#0d1b2a` dark), so the surface+ * appearing does not flash a different colour — and so an unloaded ocean viewport reads as+ * ocean in both layers rather than beige-grey behind blue. */-private const val LIGHT_BACKGROUND = 0xFFE9E7E2+private const val LIGHT_BACKGROUND = 0xFF80DEEA -/** `BasemapPalette.Fill.Background`, so this and `maps` agree in the dark. */-private const val DARK_BACKGROUND = 0xFF1B1D22+/** The renderer's dark clear, so this and the surface agree in the dark. */+private const val DARK_BACKGROUND = 0xFF0D1B2A /** * The attribution text the overlay used to draw: "© OpenStreetMap contributors · Protomaps".
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 ea54b5d86f..6e77e0b04b 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};+use super::handle::{handle_mut, TileResult, RESIDENT_TILE_CAP, UPLOADS_PER_FRAME, WASH_MAX_ZOOM}; use super::log::{log, log_info}; use crate::camera::Camera; use crate::style;@@ -71,7 +71,8 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // Task-17 pick needs the frame's density for Dp→device-px; remember it. map.density = density; - // Upload whatever the workers finished, up to `UPLOADS_PER_FRAME`. Doing it here rather than+ // Upload whatever the workers finished, up to the frame's budget (see+ // `upload_budget`: a zoom-out drains faster). Doing it here rather than // on a worker keeps every Vulkan call on one thread; bounding it keeps a burst of finished // tiles from landing in a single frame. //@@ -83,9 +84,14 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // The drain sample below still records (zero elapsed on Moon frames) so the // frame-time rollup keeps its shape. let drain_start = std::time::Instant::now();- if !crate::camera::moon_active(&camera) {+ if crate::camera::moon_active(&camera) {+ // No selection runs for the Moon, so no zoom is recorded — and the Earth set+ // resumes mid-stream when the body switches back, which deserves the burst path.+ map.forget_zoom();+ } else {+ let budget = map.upload_budget(camera.zoom); let mut uploads = 0usize;- while uploads < UPLOADS_PER_FRAME {+ while uploads < budget { let Ok((key, result)) = map.finished.try_recv() else { break; };@@ -141,6 +147,17 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( .record(Step::UploadDrain, nanos_since(drain_start)); let select_start = std::time::Instant::now(); let (min_zoom, max_zoom) = map.zoom_range.get();+ // A republish under the stable URL moves every byte offset: absences and backoffs+ // recorded against the previous build would refuse or delay tiles that exist now.+ // The worker publishes the real build id with the range; a change clears both sets.+ // (0 is "header not yet fetched" — nothing is cleared until the first real id lands,+ // so cold-start absences recorded under the guessed range survive the header.)+ let build_id = map.zoom_range.build_id();+ if build_id != 0 && build_id != map.absent_build_id {+ map.absent.clear();+ map.retry.clear();+ map.absent_build_id = build_id;+ } // A tile is "had" only if it was tessellated at the current toggle generation, so a // toggle change re-requests the resident set through this same loop rather than // needing a path of its own. The stale mesh keeps drawing until its replacement@@ -160,25 +177,25 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( (visible, keep) }; let now = std::time::Instant::now();- // Wash overzoom: the four fill layers stop at z12 (`MAX_ZOOM_PER_LAYER`),- // so past z12 nothing `visible` carries them. Their z12 ancestors are kept+ // Wash overzoom: the `landtype` wash tiles to z14 (`mamaps_build::DEFAULT_MAX_ZOOM`),+ // so past z14 nothing `visible` carries it. Its z14 ancestors are kept // resident by `resident_set` — but kept is not fetched, so a cold start at- // z13+ would show no wash until the user zooms through z12. Fetch the z12+ // z15+ would show no wash until the user zooms through z14. Fetch the z14 // covering tiles alongside the visible ones; the draw loop already draws- // every resident tile, so the wash shows through where z13+ have none.- // Bounded: one z12 tile covers 2^(z-12) visible tiles, so this adds at most+ // every resident tile, so the wash shows through where z15+ have none.+ // Bounded: one z14 tile covers 2^(z-14) visible tiles, so this adds at most // a quarter of the visible count, and the existing has_tile/absent/retry // gates dedup it exactly like a visible fetch.- let wash_extra: Vec<select::TileId> = if camera.zoom > 12.0 {+ let wash_extra: Vec<select::TileId> = if camera.zoom > WASH_MAX_ZOOM as f64 { let mut seen = std::collections::HashSet::new(); let mut extra = Vec::new(); for tile in &visible {- if tile.z <= 12 {+ if tile.z <= WASH_MAX_ZOOM { continue; }- let shift = tile.z - 12;+ let shift = tile.z - WASH_MAX_ZOOM; let ancestor = select::TileId {- z: 12,+ z: WASH_MAX_ZOOM, x: tile.x >> shift, y: tile.y >> shift, };@@ -202,27 +219,23 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( continue; } // A closed channel means every worker died; the map keeps drawing what it has.- let _ = map.wanted.send(*tile);+ // The key is removed again on failure: it is only taken out of `in_flight` when a+ // result is drained, so a dropped send would otherwise stick the tile there for+ // the rest of the session and it would never be re-requested.+ if map.wanted.send(*tile).is_err() {+ map.in_flight.remove(&key);+ } }- // Drop backoffs for tiles that are no longer visible. Not just housekeeping: an entry whose- // deadline has passed but which nothing re-requests would make `nextFrameDelayMillis`- // answer "draw now" forever, spinning the on-demand loop at 60fps for a tile that is off- // screen. Only the visible set is ever fetched, so only the visible set may hold a backoff.+ // Drop backoffs for tiles that are no longer visible (see+ // `RetryMap::retain_visible` for why this is load-bearing, not housekeeping). // // Skipped on Moon frames along with the fetch above: `visible` is empty, and // retaining against it would drop every Earth backoff (harmless but wasteful) // — worse, `retain` below with an empty keep would EVICT the Earth set. The // Moon guard keeps both calls out.- //- // Linear rather than a `HashSet` of the visible keys, deliberately: this runs per frame,- // `retry` is empty in the ordinary case (so the closure never runs), and a viewport is a- // couple of dozen tiles. Building a set here would allocate every frame to save nothing. let moon = crate::camera::moon_active(&camera); if !moon {- if !map.retry.is_empty() {- map.retry- .retain(|key, _| visible.iter().any(|t| t.key() == *key));- }+ map.retry.retain_visible(&visible); map.renderer.retain(&keep, &visible, RESIDENT_TILE_CAP); } map.renderer
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 4366c24894..c9a31a3f18 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -19,6 +19,12 @@ use std::sync::Arc; pub(crate) struct ZoomRange { min: std::sync::atomic::AtomicU8, max: std::sync::atomic::AtomicU8,+ /// The archive `build_id` the range came with, or 0 before the header lands.+ ///+ /// Read live every frame: when it changes, the archive was republished under its stable+ /// URL and every cached absence/backoff addresses the previous build's byte offsets —+ /// so the frame clears both rather than serving a map made of mismatched tiles.+ build_id: std::sync::atomic::AtomicU64, } impl ZoomRange {@@ -28,12 +34,18 @@ impl ZoomRange { ZoomRange { min: std::sync::atomic::AtomicU8::new(0), max: std::sync::atomic::AtomicU8::new(15),+ build_id: std::sync::atomic::AtomicU64::new(0), } } - pub(crate) fn set(&self, min: u8, max: u8) {+ pub(crate) fn set(&self, min: u8, max: u8, build_id: u64) { self.min.store(min, std::sync::atomic::Ordering::Relaxed); self.max.store(max, std::sync::atomic::Ordering::Relaxed);+ // Last: a reader that sees the new build id is guaranteed to also see the new+ // range (same ordering on both sides), so the frame below never clears the+ // absent set against a range it has not adopted yet.+ self.build_id+ .store(build_id, std::sync::atomic::Ordering::Relaxed); } pub(crate) fn get(&self) -> (u8, u8) {@@ -42,6 +54,10 @@ impl ZoomRange { self.max.load(std::sync::atomic::Ordering::Relaxed), ) }++ pub(crate) fn build_id(&self) -> u64 {+ self.build_id.load(std::sync::atomic::Ordering::Relaxed)+ } } /// How many tile workers run in parallel.@@ -81,8 +97,33 @@ pub(crate) const RESIDENT_TILE_CAP: usize = 64; /// Four is a deliberate middle: a screenful is a couple of dozen tiles, so a cold pan fills in /// over roughly ten frames, which is a fraction of the fetch and decode latency that preceded it /// and so is not visible. Lower would start to look like a trickle; higher gives the tail back.+///+/// Raised after a zoom-out (see [`upload_budget`]): a zoom-out invalidates a screenful at once,+/// and draining it at four per frame leaves the map coarse for seconds while the ancestors it+/// needs are already finished and waiting in the channel. pub(crate) const UPLOADS_PER_FRAME: usize = 4; +/// Uploads per frame while the camera is zooming out: the burst rate that drains a screenful+/// of newly-visible ancestors in a frame or two rather than ten.+///+/// Zoom-out is the one gesture that invalidates the whole viewport at once — every visible+/// key changes — while the replacements are usually already finished (ancestors fetched+/// ahead, or resident descendants standing in). The steady-state cap exists to smooth a+/// burst of *finished* tiles across frames; after a zoom-out the burst is the whole frame,+/// and smoothing it only stretches the coarse interval. Detected by comparing the camera+/// zoom against the last frame's: any decrease takes the burst path for that frame.+pub(crate) const UPLOADS_PER_FRAME_ZOOM_OUT: usize = 16;++/// The deepest zoom the `landtype` wash tiles to.+///+/// The archive stops at z14 (`mamaps_build::DEFAULT_MAX_ZOOM`); past it the renderer+/// overzooms, and the wash a z15+ viewport shows comes from its z14 ancestors — which the+/// fetch loop has to ask for explicitly (see `wash_extra` in `frame.rs`), because keeping+/// an ancestor resident is not the same as fetching it. One table for what used to be five+/// disagreeing caps (`z0-15` guess, z16 doc, 22 style max, hardcoded z12 wash, z14 tiler):+/// the tiler's z14 is the truth and this names it.+pub(crate) const WASH_MAX_ZOOM: u8 = 14;+ /// What a worker reports back about a tile. pub(crate) enum TileResult { /// Tessellated and ready to upload.@@ -109,7 +150,11 @@ pub(crate) struct MapHandle { pub(crate) in_flight: HashSet<u64>, /// Tiles the archive does not contain. Remembered so they are not re-requested every /// frame forever — most of a coastal viewport is ocean.- pub(crate) absent: HashSet<u64>,+ ///+ /// Bounded (see [`ABSENT_CAP`]): without a cap a pan-heavy session accumulates one entry+ /// per distinct empty tile it ever visited. Eviction re-requests at most one tile that+ /// is still absent — a single fetch, not a storm.+ pub(crate) absent: AbsentSet, /// Tiles whose fetch or decode failed, as `key -> (consecutive failures, earliest retry)`. /// /// [`TileResult::Failed`] deliberately does not mark a tile [`TileResult::Absent`], so it@@ -121,9 +166,10 @@ pub(crate) struct MapHandle { /// `Instant`, not the camera's `time_seconds`, because that clock wraps hourly and a /// deadline across a wrap would either fire an hour early or an hour late. ///- /// Cleared per tile on success. Bounded in practice the same way [`absent`](Self::absent)- /// is: it holds one small entry per distinct tile that has actually failed this session.- pub(crate) retry: HashMap<u64, (u32, std::time::Instant)>,+ /// Cleared per tile on success. Bounded like [`absent`](Self::absent): it holds one small+ /// entry per distinct tile that has actually failed recently, not per tile that ever+ /// failed this session.+ pub(crate) retry: RetryMap, pub(crate) online: Arc<OnlineFlag>, /// Light or dark. Switching costs nothing: colour is a push constant and the layer set /// is identical, so no tile is re-tessellated or re-uploaded.@@ -136,9 +182,50 @@ pub(crate) struct MapHandle { pub(crate) toggles: Arc<SharedToggles>, /// Read live every frame, because the worker only learns it after fetching the header. pub(crate) zoom_range: Arc<ZoomRange>,+ /// The archive `build_id` the absent/backoff sets were recorded against, or 0 before the+ /// header lands. When the worker publishes a new build id the archive was republished+ /// under its stable URL: cached absences address the previous build's byte offsets, so+ /// both sets are cleared rather than serving a map made of mismatched tiles.+ pub(crate) absent_build_id: u64, /// Last frame's density (device px per Dp), for the task-17 pick path's /// Dp→device-px conversion. Written every render call. pub(crate) density: f32,+ /// The camera zoom of the last frame that ran the upload drain, for the zoom-out+ /// burst (see [`upload_budget`](Self::upload_budget)). `None` before the first+ /// frame; `None` after a Moon frame, so returning from the Moon always takes the+ /// burst path once rather than comparing against a stale Earth zoom.+ pub(crate) last_zoom: Option<f64>,+}++impl MapHandle {+ /// How many finished tiles this frame may upload: the burst rate while zooming out,+ /// the steady rate otherwise — and the burst rate once after the Moon, when the Earth+ /// set resumes mid-stream.+ ///+ /// Zoom-out invalidates the whole viewport at once while its replacements are usually+ /// already finished (ancestors fetched ahead, resident descendants standing in), so+ /// the steady-state smoothing only stretches the coarse interval. Records the zoom it+ /// saw, so the next frame compares against this one (see+ /// [`zoom_out_burst`](crate::tile::select::zoom_out_burst)).+ pub(crate) fn upload_budget(&mut self, zoom: f64) -> usize {+ let burst = crate::tile::select::zoom_out_burst(self.last_zoom, zoom);+ self.last_zoom = Some(zoom);+ if burst {+ UPLOADS_PER_FRAME_ZOOM_OUT+ } else {+ UPLOADS_PER_FRAME+ }+ }++ /// Forget the zoom history, so the next frame takes the burst path.+ ///+ /// Called on the Moon guard's behalf: Moon frames skip the drain without recording a+ /// zoom, and the Earth set underneath kept changing (or the camera moved while the+ /// Moon drew), so resuming at the steady rate would trickle tiles the user is already+ /// looking at.+ pub(crate) fn forget_zoom(&mut self) {+ self.last_zoom = None;+ } } /// Shared so Kotlin's connectivity callback can reach the reader on the worker thread.@@ -161,3 +248,155 @@ pub(crate) fn handle_mut(handle: jlong) -> Option<&'static mut MapHandle> { // these from one thread. unsafe { Some(&mut *(handle as *mut MapHandle)) } }++/// How many absent tiles are remembered before the oldest is forgotten.+///+/// A viewport is a couple of dozen tiles; 512 holds a long pan trail while keeping the+/// worst case at hundreds of entries rather than the tens of thousands an unbounded set+/// reaches on a pan-heavy session. Forgetting one only costs a single re-request if that+/// tile is still absent — never a storm, because a re-probed absent tile lands right back+/// here.+pub(crate) const ABSENT_CAP: usize = 512;++/// How many failed tiles hold a backoff at once. Same shape and same reasoning as+/// [`ABSENT_CAP`]: forgetting one only costs a re-request, and an unbounded map is a+/// slow leak on a flaky network.+pub(crate) const RETRY_CAP: usize = 512;++/// The tiles the archive does not contain: an insertion-ordered set capped at+/// [`ABSENT_CAP`].+///+/// `HashSet` for the per-frame membership test plus a `VecDeque` for the insertion order,+/// so evicting the oldest is O(1) amortised. All mutation goes through [`insert`] and+/// [`clear`]; there is deliberately no `remove` — nothing but eviction and a full clear+/// takes a tile out.+pub(crate) struct AbsentSet {+ set: HashSet<u64>,+ order: std::collections::VecDeque<u64>,+}++impl AbsentSet {+ pub(crate) fn new() -> AbsentSet {+ AbsentSet {+ set: HashSet::new(),+ order: std::collections::VecDeque::new(),+ }+ }++ pub(crate) fn contains(&self, key: &u64) -> bool {+ self.set.contains(key)+ }++ pub(crate) fn insert(&mut self, key: u64) {+ if !self.set.insert(key) {+ return;+ }+ self.order.push_back(key);+ while self.order.len() > ABSENT_CAP {+ if let Some(oldest) = self.order.pop_front() {+ self.set.remove(&oldest);+ } else {+ break;+ }+ }+ }++ pub(crate) fn clear(&mut self) {+ self.set.clear();+ self.order.clear();+ }++ pub(crate) fn len(&self) -> usize {+ self.set.len()+ }++ pub(crate) fn is_empty(&self) -> bool {+ self.set.is_empty()+ }+}++/// The failed-tile backoffs: `key -> (consecutive failures, earliest retry)`, capped at+/// [`RETRY_CAP`] by evicting the oldest insertion.+///+/// Same insertion-ordered shape as [`AbsentSet`]. Re-inserting a key that is already+/// present updates its value in place without moving it: the attempt count keeps climbing+/// while the tile keeps failing, and the eviction order stays first-failed-first-out.+pub(crate) struct RetryMap {+ map: HashMap<u64, (u32, std::time::Instant)>,+ order: std::collections::VecDeque<u64>,+}++impl RetryMap {+ pub(crate) fn new() -> RetryMap {+ RetryMap {+ map: HashMap::new(),+ order: std::collections::VecDeque::new(),+ }+ }++ pub(crate) fn get(&self, key: &u64) -> Option<&(u32, std::time::Instant)> {+ self.map.get(key)+ }++ pub(crate) fn insert(&mut self, key: u64, value: (u32, std::time::Instant)) {+ if self.map.insert(key, value).is_none() {+ self.order.push_back(key);+ }+ while self.order.len() > RETRY_CAP {+ if let Some(oldest) = self.order.pop_front() {+ self.map.remove(&oldest);+ } else {+ break;+ }+ }+ }++ pub(crate) fn remove(&mut self, key: &u64) -> Option<(u32, std::time::Instant)> {+ self.map.remove(key)+ }++ pub(crate) fn is_empty(&self) -> bool {+ self.map.is_empty()+ }++ pub(crate) fn values(&self) -> impl Iterator<Item = &(u32, std::time::Instant)> {+ self.map.values()+ }++ pub(crate) fn retain(&mut self, mut keep: impl FnMut(&u64, &mut (u32, std::time::Instant)) -> bool) {+ self.map.retain(|k, v| keep(k, v));+ if self.map.len() < self.order.len() {+ self.order.retain(|k| self.map.contains_key(k));+ }+ }++ pub(crate) fn clear(&mut self) {+ self.map.clear();+ self.order.clear();+ }++ #[cfg(test)]+ pub(crate) fn len(&self) -> usize {+ self.map.len()+ }++ /// Forget every backoff for a tile that is no longer visible.+ ///+ /// Not just housekeeping: an entry whose deadline has passed but which nothing+ /// re-requests would make `nextFrameDelayMillis` answer "draw now" forever, spinning+ /// the on-demand loop at 60fps for a tile that is off screen. Only the visible set is+ /// ever fetched, so only the visible set may hold a backoff.+ ///+ /// Skipped on Moon frames along with the fetch that feeds it: `visible` is empty, and+ /// retaining against it would drop every Earth backoff (harmless but wasteful).+ ///+ /// Linear rather than a `HashSet` of the visible keys, deliberately: this runs per frame,+ /// `retry` is empty in the ordinary case (so the closure never runs), and a viewport is a+ /// couple of dozen tiles. Building a set here would allocate every frame to save nothing.+ pub(crate) fn retain_visible(&mut self, visible: &[crate::tile::select::TileId]) {+ if self.map.is_empty() {+ return;+ }+ self.retain(|key, _| visible.iter().any(|t| t.key() == *key));+ }+}
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 4c69ba6ffd..d827e41d2c 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -1,7 +1,7 @@ //! Surface lifecycle: create, resize, destroy, online flag, frame scheduling. //! //! Pure move out of `bridge.rs`; no logic changes.-use super::handle::{handle_mut, MapHandle, OnlineFlag, TileResult, ZoomRange, WORKER_COUNT};+use super::handle::{handle_mut, AbsentSet, MapHandle, OnlineFlag, RetryMap, TileResult, ZoomRange, WORKER_COUNT}; use super::log::log; use super::workers::spawn_worker; use crate::style::{self, LayerToggles, Palette, SharedToggles};@@ -12,7 +12,7 @@ use crate::vulkan::renderer::Renderer; use jni::objects::{JClass, JObject, JString}; use jni::sys::{jboolean, jint, jlong}; use jni::JNIEnv;-use std::collections::{HashMap, HashSet};+use std::collections::HashSet; use std::os::raw::c_void; use std::sync::{Arc, Mutex}; /// Create the renderer for `surface`. Returns 0 on failure, having logged why.@@ -130,13 +130,15 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( finished: finished_rx, wanted: wanted_tx, in_flight: HashSet::new(),- absent: HashSet::new(),- retry: HashMap::new(),+ absent: AbsentSet::new(),+ retry: RetryMap::new(), online, palette: Palette::new(dark != 0, muted != 0), toggles, zoom_range, density: 1.0,+ last_zoom: None,+ absent_build_id: 0, }); Box::into_raw(handle) as jlong }
library/map/src/main/rust/src/bridge/workers.rs
diff --git a/library/map/src/main/rust/src/bridge/workers.rs b/library/map/src/main/rust/src/bridge/workers.rsindex 1e2c706d94..a7e3569318 100644--- a/library/map/src/main/rust/src/bridge/workers.rs+++ b/library/map/src/main/rust/src/bridge/workers.rs@@ -77,36 +77,14 @@ pub(crate) fn spawn_worker( // Single open: the header prefix is fetched *once per surface* (the first worker // fetches, the rest block on `header`), then the `build_id` is read out of it and the // cache opens once per worker with the full origin marker — wiping on mismatch up- // front. No two-step reset. A failed fetch poisons the lock for every worker, so one- // dead network kills the surface's workers once instead of logging four times.- let build_id =- *header.get_or_init(- || match JniRangeFetcher.fetch(&archive_url, "bytes=0-127") {- Ok(r)- if r.status == 206- && r.body.len() == tilecodec::mamaps::header::HEADER_LEN =>- {- match Header::parse(&r.body) {- Ok(h) => Some(h.build_id),- Err(e) => {- log(&format!("cannot parse the mamaps header: {e}"));- None- }- }- }- Ok(r) => {- log(&format!(- "cannot fetch the mamaps header: HTTP {}",- r.status- ));- None- }- Err(e) => {- log(&format!("cannot fetch the mamaps header: {e}"));- None- }- },- );+ // front. No two-step reset.+ //+ // Retried with backoff, not once: a single failed fetch used to poison the lock for+ // every worker, so one transient network blip at startup killed the surface's workers+ // and stuck every in-flight tile for the session. A header that keeps failing past+ // `HEADER_RETRIES` still kills them once instead of logging four times — but only+ // after the network has had its chance to come back.+ let build_id = *header.get_or_init(|| fetch_header_with_retry(&archive_url)); let Some(build_id) = build_id else { return }; let cache = RangeCache::open( cache_dir,@@ -138,7 +116,67 @@ pub(crate) fn spawn_worker( } } -/// Serve tile requests from `archive` until the queue closes.+/// How many times the cold-start header fetch is retried before the workers give up.+///+/// The fetch runs once per surface (not once per worker), so these retries are the surface's+/// whole startup budget: a few seconds of tunnel against giving up for the session. Past this+/// the lock holds `None` and every worker returns, as before.+#[cfg(target_os = "android")]+const HEADER_RETRIES: u32 = 5;++/// One attempt at the archive header's `build_id`: `Some` on a parsed 128-byte 206,+/// `None` on any transport failure, unexpected status or unparseable body.+#[cfg(target_os = "android")]+fn fetch_header_once(archive_url: &str) -> Option<u64> {+ use crate::tile::source::JniRangeFetcher;+ use crate::tile::source::RangeFetcher;+ match JniRangeFetcher.fetch(archive_url, "bytes=0-127") {+ Ok(r)+ if r.status == 206 && r.body.len() == tilecodec::mamaps::header::HEADER_LEN =>+ {+ match Header::parse(&r.body) {+ Ok(h) => Some(h.build_id),+ Err(e) => {+ log(&format!("cannot parse the mamaps header: {e}"));+ None+ }+ }+ }+ Ok(r) => {+ log(&format!(+ "cannot fetch the mamaps header: HTTP {}",+ r.status+ ));+ None+ }+ Err(e) => {+ log(&format!("cannot fetch the mamaps header: {e}"));+ None+ }+ }+}++/// Fetch the archive header's `build_id`, retrying transient failures with backoff.+///+/// A `Some` is the build id; `None` means the header never arrived and the caller returns.+/// Parse failures are not retried — a body that will not parse now will not parse in a+/// second — but transport failures and non-206 statuses are, because those are what a+/// tunnel, a captive portal and a cold radio look like.+#[cfg(target_os = "android")]+fn fetch_header_with_retry(archive_url: &str) -> Option<u64> {+ use crate::tile::source::retry_delay_ms;+ let mut attempt = 0u32;+ loop {+ match fetch_header_once(archive_url) {+ Some(id) => return Some(id),+ None if attempt >= HEADER_RETRIES => return None,+ None => {+ attempt += 1;+ std::thread::sleep(std::time::Duration::from_millis(retry_delay_ms(attempt)));+ }+ }+ }+} /// /// Generic over the reader so the same loop drives both the URL-backed /// [`CachingRangeReader`] and the disk-backed [`FileRangeReader`]: only how the archive@@ -153,8 +191,9 @@ fn serve<R: RangeReader>( ) { // Publish the real range. Until this lands the renderer works from a guess, and // a guess that is too high asks for a zoom the archive does not contain and- // silently gets nothing back.- zoom_range.set(archive.header.min_zoom, archive.header.max_zoom);+ // silently gets nothing back. The build id rides with it so the frame can clear+ // absences recorded against a previous publish (see `absent_build_id`).+ zoom_range.set(archive.header.min_zoom, archive.header.max_zoom, archive.header.build_id); let layers = style::layers(); // Read once from the header rather than per tile: it is a property of the archive. let rings_validated = archive.header.rings_validated();
library/map/src/main/rust/src/style/paint_extra3.rs
diff --git a/library/map/src/main/rust/src/style/paint_extra3.rs b/library/map/src/main/rust/src/style/paint_extra3.rsindex 91551404a0..931cb3569d 100644--- a/library/map/src/main/rust/src/style/paint_extra3.rs+++ b/library/map/src/main/rust/src/style/paint_extra3.rs@@ -20,7 +20,7 @@ fn the_vendored_flat_style_parses() { // that says what it is, instead of nudging a basemap total that then no longer // states what the basemap is. //- // Basemap: 24 fills, 24 lines and 7 symbols. The 24 lines are the 12+ // Basemap: 30 fills, 24 lines and 7 symbols. The 24 lines are the 12 // surface/link layers, 10 bridge layers (5 casings + 5 fills), and the two app-only // carriageway layers that draw a road's surface and its lane markings at z16+ — // `roads-carriageway` and `junction-connector`, which continues the same surface@@ -45,13 +45,17 @@ fn the_vendored_flat_style_parses() { .filter(|l| l.kind == kind && l.toggle.is_some() == optional) .count() };+ // The 30 fills are `earth`, `landcover` + 5 covers, 11 `landuse_*` greens,+ // `water`, 6 v8 landuse arms (pedestrian/orchard/vineyard/quarry/+ // swimming_pool/residential/commercial), pier, and buildings. Six more than+ // the v7 count: the v8 `landtype` merge carries what the wash used to drop. assert_eq!( ( count(LayerKind::Fill, false), count(LayerKind::Line, false), count(LayerKind::Symbol, false) ),- (24, 24, 7),+ (30, 24, 7), "the basemap layer set", ); assert_eq!(
library/map/src/main/rust/src/style/paint_extra5.rs
diff --git a/library/map/src/main/rust/src/style/paint_extra5.rs b/library/map/src/main/rust/src/style/paint_extra5.rsindex 32dd19211c..dd8dfd9a20 100644--- a/library/map/src/main/rust/src/style/paint_extra5.rs+++ b/library/map/src/main/rust/src/style/paint_extra5.rs@@ -34,6 +34,11 @@ fn the_flat_style_agrees_with_basemap_json() { // reference style has no orchard/vineyard/quarry/pool/residential/commercial arms, // so there is nothing to cross-check their colours or ramps against. Their sources // and kind whitelists are pinned by `the_interned_whitelist_is_the_authored_one`.+ //+ // `landuse_pier` is app-only for its colour alone: commit f3ee7d62 deliberately+ // paints piers with the industrial fill (`#d1dde1`, water-adjacent — a pier sits+ // over water) rather than the authored neutral `#e0e0e0`. Its source, kinds and+ // ramps are still cross-checked below; only the fill-colour arm is skipped. if layer.carriageway || matches!( layer.id.as_str(),@@ -87,26 +92,30 @@ fn the_flat_style_agrees_with_basemap_json() { } match layer.kind { LayerKind::Fill => {- // The light colour has to be one the authored `fill-color` can produce.- let mut colors = Vec::new();- colors_in(- authored- .get("paint")- .and_then(|p| p.get("fill-color"))- .expect("a colour"),- &mut colors,- );- assert!(- colors.contains(&layer.light),- "`{}`'s {:#010X} is not a colour `{}`'s fill-color paints: {:?}",- layer.id,- layer.light,- layer.authored,- colors- .iter()- .map(|c| format!("{c:#010X}"))- .collect::<Vec<_>>(),- );+ // The light colour has to be one the authored `fill-color` can produce —+ // except `landuse_pier`, whose industrial-fill colour is a deliberate+ // divergence (see the skip-list comment above).+ if layer.id != "landuse_pier" {+ let mut colors = Vec::new();+ colors_in(+ authored+ .get("paint")+ .and_then(|p| p.get("fill-color"))+ .expect("a colour"),+ &mut colors,+ );+ assert!(+ colors.contains(&layer.light),+ "`{}`'s {:#010X} is not a colour `{}`'s fill-color paints: {:?}",+ layer.id,+ layer.light,+ layer.authored,+ colors+ .iter()+ .map(|c| format!("{c:#010X}"))+ .collect::<Vec<_>>(),+ );+ } let authored_opacity = authored_property(&authored, "fill-opacity") .unwrap_or_else(|| Ramp::constant(1.0)); assert_ramps_agree(&layer.id, "opacity", &layer.opacity, &authored_opacity);
library/map/src/main/rust/src/style/paint_extra7.rs
diff --git a/library/map/src/main/rust/src/style/paint_extra7.rs b/library/map/src/main/rust/src/style/paint_extra7.rsindex 6f0dd48882..d7b6c86e0b 100644--- a/library/map/src/main/rust/src/style/paint_extra7.rs+++ b/library/map/src/main/rust/src/style/paint_extra7.rs@@ -22,7 +22,21 @@ fn the_kinds_each_authored_layer_admits_are_all_drawn_and_no_others() { families.push(&layer.authored); } }+ // App-only v8 families with no authored counterpart (see+ // `every_authored_layer_a_flat_layer_names_exists`): their kind whitelists+ // are pinned by `the_interned_whitelist_is_the_authored_one`, not here.+ const APP_ONLY_FAMILIES: &[&str] = &[+ "landuse_orchard",+ "landuse_vineyard",+ "landuse_quarry",+ "landuse_swimming_pool",+ "landuse_residential",+ "landuse_commercial",+ ]; for family in families {+ if APP_ONLY_FAMILIES.contains(&family) {+ continue;+ } let authored = authored_layer(&root, family); let mut admitted = authored_filter_kinds(authored.get("filter")); let mut drawn: Vec<String> = layers()@@ -33,10 +47,22 @@ fn the_kinds_each_authored_layer_admits_are_all_drawn_and_no_others() { if admitted.is_empty() { // An unrestricted authored layer needs an unfiltered flat layer, or the kinds // its colour expression does not name would stop being drawn at all.+ //+ // v8 merges the wash sources: authored `earth` and `water` are both type-only+ // filters over their own sources, while every flat arm reads merged+ // `landtype`. Flat `earth` (empty whitelist — matches every kind) is the+ // unfiltered member for both families: it draws the mainland and every+ // water kind, and flat `water` repaints the water kinds over it. So family+ // `water` is covered without its own unfiltered arm.+ let covered = layers().iter().any(|l| {+ l.kinds.is_empty()+ && (l.authored == family+ || (family == "water"+ && l.authored == "earth"+ && l.source_layer == "landtype"))+ }); assert!(- layers()- .iter()- .any(|l| l.authored == family && l.kinds.is_empty()),+ covered, "`{family}` admits every kind but no flat layer draws them", ); continue;@@ -76,6 +102,10 @@ fn the_kinds_each_authored_layer_admits_are_all_drawn_and_no_others() { /// Every authored layer a flat layer names has to exist, or the cross-check silently stops /// checking that layer.+///+/// The six v8 landtype arms (`landuse_orchard` … `landuse_commercial`) are exempt: the+/// reference style has no such arms, so there is nothing to name. Their sources and kind+/// whitelists are pinned by `the_interned_whitelist_is_the_authored_one` instead. #[test] fn every_authored_layer_a_flat_layer_names_exists() { let root = basemap();@@ -86,7 +116,19 @@ fn every_authored_layer_a_flat_layer_names_exists() { .iter() .filter_map(|layer| layer.get("id").and_then(Json::as_str)) .collect();+ // App-only flat layers with no authored counterpart (see above).+ const APP_ONLY: &[&str] = &[+ "landuse_orchard",+ "landuse_vineyard",+ "landuse_quarry",+ "landuse_swimming_pool",+ "landuse_residential",+ "landuse_commercial",+ ]; for layer in layers() {+ if APP_ONLY.contains(&layer.authored.as_str()) {+ continue;+ } assert!( ids.contains(&layer.authored.as_str()), "`{}` names authored layer `{}`, which is not in basemap.json",
library/map/src/main/rust/src/tile/geometry/terrain.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/terrain.rs b/library/map/src/main/rust/src/tile/geometry/terrain.rsindex 9faed22c16..f426b1eca7 100644--- a/library/map/src/main/rust/src/tile/geometry/terrain.rs+++ b/library/map/src/main/rust/src/tile/geometry/terrain.rs@@ -104,6 +104,36 @@ fn land_mask(tile: &Body, dim: usize) -> Vec<bool> { point_in_rings(u, v, &land_rings) && !point_in_rings(u, v, &water_rings); } }+ // Erode one DEM cell: a sample stays land only when its 4-neighbours are land too.+ // Coarse tiles simplify the coastline aggressively, so a cell that is mostly ocean can+ // still test inside — and relief drawn there paints shaded earth over open sea, which in+ // the dark palette reads as a black ocean. Eroding the shore back by half a DEM cell+ // errs toward water, which is the safe direction: the flat `earth` fill still draws+ // underneath (so no hole opens), only the relief withholds, and at worst a shoreline+ // loses its shading for half a cell rather than the sea gaining a continent.+ //+ // Off-grid neighbours read as land, so a land-only tile keeps its full grid (its edge+ // ring would otherwise erode against nothing) and the erosion only ever bites where+ // in-tile water was actually seen.+ let raw = mask.clone();+ let at = |row: usize, col: usize| -> bool {+ if row >= dim || col >= dim {+ return true;+ }+ raw[row * dim + col]+ };+ for row in 0..dim {+ for col in 0..dim {+ if raw[row * dim + col]+ && !(at(row.saturating_sub(1), col)+ && at(row + 1, col)+ && at(row, col.saturating_sub(1))+ && at(row, col + 1))+ {+ mask[row * dim + col] = false;+ }+ }+ } mask }
library/map/src/main/rust/src/tile/geometry/tests.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests.rs b/library/map/src/main/rust/src/tile/geometry/tests.rsindex 57cea9d0a4..98c244b03a 100644--- a/library/map/src/main/rust/src/tile/geometry/tests.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests.rs@@ -9,20 +9,26 @@ use tilecodec::mamaps::body::{ }; use tilecodec::mamaps::dict; -/// A representative v7 body: one `earth` polygon, one `major_road` LineString-/// (kind 45) and two `water` polygons — the same layers the old MVT fixture-/// carried, built directly as a body so the tests no longer depend on the-/// MVT→body converter.+/// A representative v8 body: one `landtype` layer holding a kind-less mainland+/// polygon, one `major_road` LineString (kind 45) and two `lake` polygons — the+/// same shapes the old MVT fixture carried, built directly as a body so the+/// tests no longer depend on the MVT→body converter.+///+/// v8 merges the four wash layers into one `landtype` source: the mainland+/// carries kind [`NONE`](dict::NONE) (what the `earth` style arm matches — its+/// whitelist is empty) and the lakes carry `lake`, which the `water` arm names. /// /// The road is named, so the curved-label tests in `tess::text` share this /// fixture's shape: their own centreline below is this road's coordinates. fn real() -> Body {+ use tilecodec::mamaps::dict::NONE; let mut body = Body::new(4096); body.names.push("Old Madrone Road".to_string());- let mut earth = BodyLayer::new(dict::LAYER_EARTH);- earth.features.push(Feature {- kind: 1,- kind_detail: dict::NONE,+ let mut landtype = BodyLayer::new(dict::LAYER_LANDTYPE);+ // Mainland first: the exterior every hole is contained in.+ landtype.features.push(Feature {+ kind: NONE,+ kind_detail: NONE, geom_type: GEOM_POLYGON, flags: 0, name_idx: NAME_NONE,@@ -34,13 +40,40 @@ fn real() -> Body { transit_taper: 0, lane_count: 0, });- earth.parts.push(Part {+ landtype.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER, });- earth.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];- body.layers.push(earth);+ landtype.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ for (i, base) in [(500i16, 3000i16), (2500, 500)].iter().enumerate() {+ landtype.features.push(Feature {+ kind: crate::style::kind_id_for_test("lake"),+ kind_detail: NONE,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 1 + i as u32,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ landtype.parts.push(Part {+ coord_start: landtype.coords.len() as u32,+ point_count: 4,+ winding: WINDING_OUTER,+ });+ landtype.coords.extend_from_slice(&[+ *base,+ (base.0 + 600, base.1),+ (base.0 + 600, base.1 + 400),+ (base.0, base.1 + 400),+ ]);+ }+ body.layers.push(landtype); let mut roads = BodyLayer::new(dict::LAYER_ROADS); roads.features.push(Feature { kind: crate::style::kind_id_for_test("major_road"),@@ -63,35 +96,6 @@ fn real() -> Body { }); roads.coords = vec![(100, 100), (1500, 900), (2600, 1800), (3900, 2700)]; body.layers.push(roads);- let mut water = BodyLayer::new(dict::LAYER_WATER);- for (i, base) in [(500i16, 3000i16), (2500, 500)].iter().enumerate() {- water.features.push(Feature {- kind: 4,- kind_detail: dict::NONE,- geom_type: GEOM_POLYGON,- flags: 0,- name_idx: NAME_NONE,- parts_offset: i as u32,- part_count: 1,- transit_color: 0,- transit_ordinal: 0,- transit_lanes: 0,- transit_taper: 0,- lane_count: 0,- });- water.parts.push(Part {- coord_start: water.coords.len() as u32,- point_count: 4,- winding: WINDING_OUTER,- });- water.coords.extend_from_slice(&[- *base,- (base.0 + 600, base.1),- (base.0 + 600, base.1 + 400),- (base.0, base.1 + 400),- ]);- }- body.layers.push(water); body } @@ -101,8 +105,8 @@ fn mesh_for<'a>(mesh: &'a TileMesh, layers: &[Layer], id: &str) -> Option<&'a La #[test] fn the_real_tile_produces_geometry_for_the_layers_it_has_data_in() {- // The fixture body carries one `earth` polygon, one `roads` LineString of- // kind = major_road, and two `water` polygons.+ // The fixture body carries one kind-less `landtype` mainland, one `roads`+ // LineString of kind = major_road, and two `lake` polygons on `landtype`. let layers = style::layers(); let mesh = build(&real(), &layers, 14, 339, 770, false);
library/map/src/main/rust/src/tile/geometry/tests_drape.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_drape.rs b/library/map/src/main/rust/src/tile/geometry/tests_drape.rsindex fc944841cc..f693bed608 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_drape.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_drape.rs@@ -196,9 +196,9 @@ fn a_degenerate_heightmap_keeps_the_flat_earth_fill() { use tilecodec::mamaps::body::{NAME_NONE, WINDING_OUTER}; let layers = crate::style::layers(); let mut body = Body::new(4096);- let mut earth = BodyLayer::new(tilecodec::mamaps::dict::LAYER_EARTH);- earth.features.push(Feature {- kind: 1,+ let mut landtype = BodyLayer::new(tilecodec::mamaps::dict::LAYER_LANDTYPE);+ landtype.features.push(Feature {+ kind: tilecodec::mamaps::dict::NONE, kind_detail: tilecodec::mamaps::dict::NONE, geom_type: GEOM_POLYGON, flags: 0,@@ -211,13 +211,13 @@ fn a_degenerate_heightmap_keeps_the_flat_earth_fill() { transit_taper: 0, lane_count: 0, });- earth.parts.push(tilecodec::mamaps::body::Part {+ landtype.parts.push(tilecodec::mamaps::body::Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER, });- earth.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];- body.layers.push(earth);+ landtype.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ body.layers.push(landtype); body.heightmap = Some(Heightmap { dim: 1, samples: vec![32768],
library/map/src/main/rust/src/tile/geometry/tests_extra2.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra2.rsindex 52f0c6f2bc..6a39fadb24 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs@@ -10,16 +10,17 @@ use tilecodec::mamaps::body::{ use tilecodec::mamaps::dict; use tilecodec::mamaps::dict::LAYER_JUNCTION; -/// A representative v7 body: one `earth` polygon, one `major_road` LineString-/// (kind 45) and one `water` polygon — the same layers the old MVT fixture-/// carried, built directly as a body so the tests no longer depend on the-/// MVT→body converter.+/// A representative v8 body: one `landtype` layer holding a kind-less mainland+/// polygon, one `major_road` LineString (kind 45) and one `lake` polygon — the+/// same shapes the old MVT fixture carried, built directly as a body so the+/// tests no longer depend on the MVT→body converter. fn real() -> Body {+ use tilecodec::mamaps::dict::NONE; let mut body = Body::new(4096);- let mut earth = BodyLayer::new(dict::LAYER_EARTH);- earth.features.push(Feature {- kind: 1,- kind_detail: dict::NONE,+ let mut landtype = BodyLayer::new(dict::LAYER_LANDTYPE);+ landtype.features.push(Feature {+ kind: NONE,+ kind_detail: NONE, geom_type: GEOM_POLYGON, flags: 0, name_idx: NAME_NONE,@@ -31,40 +32,38 @@ fn real() -> Body { transit_taper: 0, lane_count: 0, });- earth.parts.push(Part {+ landtype.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER, });- earth.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];- body.layers.push(earth);- let mut roads = BodyLayer::new(dict::LAYER_ROADS);- roads.features.push(Feature {- kind: crate::style::kind_id_for_test("major_road"),- kind_detail: dict::NONE,- geom_type: GEOM_LINE,+ landtype.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ landtype.features.push(Feature {+ kind: crate::style::kind_id_for_test("lake"),+ kind_detail: NONE,+ geom_type: GEOM_POLYGON, flags: 0, name_idx: NAME_NONE,- parts_offset: 0,+ parts_offset: 1, part_count: 1, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,- lane_count: 1,+ lane_count: 0, });- roads.parts.push(Part {- coord_start: 0,+ landtype.parts.push(Part {+ coord_start: 4, point_count: 4, winding: WINDING_OUTER, });- roads.coords = vec![(100, 100), (1500, 900), (2600, 1800), (3900, 2700)];- body.layers.push(roads);- let mut water = BodyLayer::new(dict::LAYER_WATER);- water.features.push(Feature {- kind: 4,+ landtype.coords.extend_from_slice(&[(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)]);+ body.layers.push(landtype);+ let mut roads = BodyLayer::new(dict::LAYER_ROADS);+ roads.features.push(Feature {+ kind: crate::style::kind_id_for_test("major_road"), kind_detail: dict::NONE,- geom_type: GEOM_POLYGON,+ geom_type: GEOM_LINE, flags: 0, name_idx: NAME_NONE, parts_offset: 0,@@ -73,15 +72,15 @@ fn real() -> Body { transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,- lane_count: 0,+ lane_count: 1, });- water.parts.push(Part {+ roads.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER, });- water.coords = vec![(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)];- body.layers.push(water);+ roads.coords = vec![(100, 100), (1500, 900), (2600, 1800), (3900, 2700)];+ body.layers.push(roads); body }
library/map/src/main/rust/src/tile/geometry/tests_extra3.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra3.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra3.rsindex cd2a23f6e6..d207ca9d24 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra3.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra3.rs@@ -65,6 +65,7 @@ fn traffic_body(ids: &[Option<u64>], id_table: bool) -> Body { heightmap: None, carriageways: Vec::new(), convention: None,+ region_links: Vec::new(), } } @@ -290,6 +291,7 @@ fn building_body(attrs: Option<tilecodec::mamaps::body::BuildingAttrs>) -> Body heightmap: None, carriageways: Vec::new(), convention: None,+ region_links: Vec::new(), } }
library/map/src/main/rust/src/tile/geometry/tests_extra4.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra4.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra4.rsindex 0dd15db19e..d771b6fd96 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra4.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra4.rs@@ -87,6 +87,7 @@ fn named_road_body(name: &str, pts: &[(i16, i16)]) -> Body { heightmap: None, carriageways: Vec::new(), convention: None,+ region_links: Vec::new(), } } @@ -190,6 +191,7 @@ fn hill_building_body( heightmap, carriageways: Vec::new(), convention: None,+ region_links: Vec::new(), } }
library/map/src/main/rust/src/tile/geometry/tests_extra6.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra6.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra6.rsindex 98a962086f..a8685b1a83 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra6.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra6.rs@@ -8,16 +8,17 @@ use tilecodec::mamaps::body::{ }; use tilecodec::mamaps::dict; -/// A representative v7 body: one `earth` polygon, one `major_road` LineString-/// (kind 45) and one `water` polygon — the same layers the old MVT fixture-/// carried, built directly as a body so the tests no longer depend on the-/// MVT→body converter.+/// A representative v8 body: one `landtype` layer holding a kind-less mainland+/// polygon, one `major_road` LineString (kind 45) and one `lake` polygon — the+/// same shapes the old MVT fixture carried, built directly as a body so the+/// tests no longer depend on the MVT→body converter. fn real() -> Body {+ use tilecodec::mamaps::dict::NONE; let mut body = Body::new(4096);- let mut earth = BodyLayer::new(dict::LAYER_EARTH);- earth.features.push(Feature {- kind: 1,- kind_detail: dict::NONE,+ let mut landtype = BodyLayer::new(dict::LAYER_LANDTYPE);+ landtype.features.push(Feature {+ kind: NONE,+ kind_detail: NONE, geom_type: GEOM_POLYGON, flags: 0, name_idx: NAME_NONE,@@ -29,40 +30,40 @@ fn real() -> Body { transit_taper: 0, lane_count: 0, });- earth.parts.push(Part {+ landtype.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER, });- earth.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];- body.layers.push(earth);- let mut roads = BodyLayer::new(dict::LAYER_ROADS);- roads.features.push(Feature {- kind: crate::style::kind_id_for_test("major_road"),- kind_detail: dict::NONE,- geom_type: GEOM_LINE,+ landtype.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ landtype.features.push(Feature {+ kind: crate::style::kind_id_for_test("lake"),+ kind_detail: NONE,+ geom_type: GEOM_POLYGON, flags: 0, name_idx: NAME_NONE,- parts_offset: 0,+ parts_offset: 1, part_count: 1, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,- lane_count: 1,+ lane_count: 0, });- roads.parts.push(Part {- coord_start: 0,+ landtype.parts.push(Part {+ coord_start: 4, point_count: 4, winding: WINDING_OUTER, });- roads.coords = vec![(100, 100), (1500, 900), (2600, 1800), (3900, 2700)];- body.layers.push(roads);- let mut water = BodyLayer::new(dict::LAYER_WATER);- water.features.push(Feature {- kind: 4,+ landtype+ .coords+ .extend_from_slice(&[(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)]);+ body.layers.push(landtype);+ let mut roads = BodyLayer::new(dict::LAYER_ROADS);+ roads.features.push(Feature {+ kind: crate::style::kind_id_for_test("major_road"), kind_detail: dict::NONE,- geom_type: GEOM_POLYGON,+ geom_type: GEOM_LINE, flags: 0, name_idx: NAME_NONE, parts_offset: 0,@@ -71,15 +72,15 @@ fn real() -> Body { transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,- lane_count: 0,+ lane_count: 1, });- water.parts.push(Part {+ roads.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER, });- water.coords = vec![(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)];- body.layers.push(water);+ roads.coords = vec![(100, 100), (1500, 900), (2600, 1800), (3900, 2700)];+ body.layers.push(roads); body } @@ -92,8 +93,8 @@ fn a_line_layer_also_strokes_polygon_outlines() { // A lake shoreline and an administrative boundary are lines over area features. let outline = vec![Layer { id: "water-edge".to_string(),- source_layer: "water".to_string(),- source_layer_id: tilecodec::mamaps::dict::LAYER_WATER,+ source_layer: "landtype".to_string(),+ source_layer_id: tilecodec::mamaps::dict::LAYER_LANDTYPE, kind: LayerKind::Line, kinds: Vec::new(), kind_ids: Vec::new(),@@ -129,7 +130,7 @@ fn a_line_layer_also_strokes_polygon_outlines() { authored: "water".to_string(), }]; let mesh = build(&real(), &outline, 11, 339, 770, false);- assert_eq!(mesh.meshes.len(), 1, "the water polygons' outlines stroke");+ assert_eq!(mesh.meshes.len(), 1, "the landtype polygons' outlines stroke"); assert!(!mesh.meshes[0].indices.is_empty()); } /// **The Phase 4 milestone, end to end inside this crate.** A `.mamaps` archive is built,
library/map/src/main/rust/src/tile/geometry/tests_extra7.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra7.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra7.rsindex 2c621dabad..d18da5262a 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra7.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra7.rs@@ -9,17 +9,19 @@ use tilecodec::mamaps::body::{ }; use tilecodec::mamaps::dict; -/// A representative v7 body: one `earth` polygon and one `water` polygon —-/// the same layers the old MVT fixture carried, built directly as a body so-/// the tests no longer depend on the MVT→body converter.+/// A representative v8 body: one `landtype` layer holding a kind-less mainland+/// polygon and one `lake` polygon — the same shapes the old MVT fixture+/// carried, built directly as a body so the tests no longer depend on the+/// MVT→body converter. /// (Duplicated from `tests_extra3`: sibling `#[cfg(test)]` modules cannot /// see each other's private items.) fn real() -> Body {+ use tilecodec::mamaps::dict::NONE; let mut body = Body::new(4096);- let mut earth = BodyLayer::new(dict::LAYER_EARTH);- earth.features.push(Feature {- kind: 1,- kind_detail: dict::NONE,+ let mut landtype = BodyLayer::new(dict::LAYER_LANDTYPE);+ landtype.features.push(Feature {+ kind: NONE,+ kind_detail: NONE, geom_type: GEOM_POLYGON, flags: 0, name_idx: NAME_NONE,@@ -31,21 +33,19 @@ fn real() -> Body { transit_taper: 0, lane_count: 0, });- earth.parts.push(Part {+ landtype.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER, });- earth.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];- body.layers.push(earth);- let mut water = BodyLayer::new(dict::LAYER_WATER);- water.features.push(Feature {- kind: 4,- kind_detail: dict::NONE,+ landtype.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ landtype.features.push(Feature {+ kind: crate::style::kind_id_for_test("lake"),+ kind_detail: NONE, geom_type: GEOM_POLYGON, flags: 0, name_idx: NAME_NONE,- parts_offset: 0,+ parts_offset: 1, part_count: 1, transit_color: 0, transit_ordinal: 0,@@ -53,13 +53,15 @@ fn real() -> Body { transit_taper: 0, lane_count: 0, });- water.parts.push(Part {- coord_start: 0,+ landtype.parts.push(Part {+ coord_start: 4, point_count: 4, winding: WINDING_OUTER, });- water.coords = vec![(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)];- body.layers.push(water);+ landtype+ .coords+ .extend_from_slice(&[(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)]);+ body.layers.push(landtype); body } @@ -132,6 +134,51 @@ fn a_tile_without_a_heightmap_stays_flat() { ); } +/// Open sea builds no relief even when a DEM is attached: a tile with no kind-less land+/// base is water (or off the land product), so the land mask is all-false and the grid+/// drops out completely. Relief drawn there would paint shaded earth over the ocean —+/// the dark-palette black sea.+#[test]+fn open_sea_with_a_heightmap_builds_no_terrain() {+ use tilecodec::mamaps::dict::NONE;+ let layers = style::layers();+ let mut body = Body::new(4096);+ // Water only: no NONE-kind mainland, so this tile is sea.+ let mut water = BodyLayer::new(dict::LAYER_LANDTYPE);+ water.features.push(Feature {+ kind: crate::style::kind_id_for_test("ocean"),+ kind_detail: NONE,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ water.parts.push(Part {+ coord_start: 0,+ point_count: 4,+ winding: WINDING_OUTER,+ });+ water.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ body.layers.push(water);+ // A flat sea-level DEM, exactly what coastal tiles carry over their water half.+ body.heightmap = Some(heightmap(9, |_, _| 0));+ let mesh = build(&body, &layers, 4, 2, 5, false);+ assert!(+ mesh.terrain.indices.is_empty(),+ "open sea builds no relief grid, or shaded earth covers the ocean"+ );+ assert!(+ mesh_for(&mesh, &layers, "water").is_some(),+ "the water fill still draws flat over the clear"+ );+}+ #[test] fn terrain_height_is_normalised_from_the_dem() { // The displaced z is metres / the tile's ground width — the same tile-local unit buildings
library/map/src/main/rust/src/tile/select/fade.rs
diff --git a/library/map/src/main/rust/src/tile/select/fade.rs b/library/map/src/main/rust/src/tile/select/fade.rsindex 1cb654344b..d6742c5865 100644--- a/library/map/src/main/rust/src/tile/select/fade.rs+++ b/library/map/src/main/rust/src/tile/select/fade.rs@@ -11,11 +11,18 @@ pub const LOD_FADE_SECONDS: f32 = 0.3; /// The per-tile opacity of a tile `now - uploaded_at` seconds after its GPU buffers landed: 0 at /// upload, ramping linearly to 1 over `duration` (WS-D LOD cross-fade). Both times share the /// `Camera::time_seconds` epoch. A non-positive `duration` disables the fade (opaque at once).+///+/// The elapsed time is taken **modulo [`CLOCK_WRAP_SECONDS`]** like+/// [`fade_in_progress`]: the shared clock wraps hourly, and a plain subtraction across a wrap+/// is wrong by an entire period — a tile stamped at 3599.9 against a clock just wrapped to 0.1+/// would read as −3599.8 s, clamp to 0, and sit transparent for the remaining hour whenever a+/// coarse ancestor is resident. The wrap is exact here (not an approximation): both stamps+/// come from the same bounded clock. pub fn lod_fade_alpha(now: f32, uploaded_at: f32, duration: f32) -> f32 { if duration <= 0.0 { return 1.0; }- ((now - uploaded_at) / duration).clamp(0.0, 1.0)+ ((now - uploaded_at).rem_euclid(crate::camera::CLOCK_WRAP_SECONDS) / duration).clamp(0.0, 1.0) } /// Whether a tile stamped `uploaded_at` is still inside its cross-fade, and so would draw
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 be4498d0fd..5bebc3ea68 100644--- a/library/map/src/main/rust/src/tile/select/mod.rs+++ b/library/map/src/main/rust/src/tile/select/mod.rs@@ -31,5 +31,5 @@ pub use coverage::{bound, visible}; 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, ANCESTOR_DEPTH, DESCENDANT_DEPTH};+pub use resident::{resident_set, stands_in_for_visible, zoom_out_burst, ANCESTOR_DEPTH, DESCENDANT_DEPTH}; 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 753b9b1230..e307299254 100644--- a/library/map/src/main/rust/src/tile/select/resident.rs+++ b/library/map/src/main/rust/src/tile/select/resident.rs@@ -4,6 +4,18 @@ use super::coverage::visible; use super::tile_id::TileId; +/// Whether this frame deserves the zoom-out upload burst: the first frame, or any frame+/// whose camera zoom decreased since the last.+///+/// Zoom-out invalidates the whole viewport at once while its replacements are usually+/// already finished (ancestors fetched ahead, resident descendants standing in), so the+/// steady-state smoothing only stretches the coarse interval. A pure function of the two+/// zooms so the drain policy is host-testable; the render thread threads its `last_zoom`+/// through it (see `MapHandle::upload_budget`).+pub fn zoom_out_burst(last_zoom: Option<f64>, zoom: f64) -> bool {+ last_zoom.is_none_or(|last| zoom < last)+}+ /// 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.rs
diff --git a/library/map/src/main/rust/src/tile/select/tests.rs b/library/map/src/main/rust/src/tile/select/tests.rsindex 702300d0ab..31deedb00c 100644--- a/library/map/src/main/rust/src/tile/select/tests.rs+++ b/library/map/src/main/rust/src/tile/select/tests.rs@@ -37,8 +37,11 @@ fn a_fresh_tile_ramps_zero_to_one_over_the_duration() { 1.0, "opaque at the end" );- // Before upload (clock races the stamp) and long after both clamp.- assert_eq!(lod_fade_alpha(uploaded_at - 1.0, uploaded_at, d), 0.0);+ // Before upload (clock races the stamp) reads as long-resident: the elapsed time is+ // modulo the hourly wrap, so a `now` behind the stamp is indistinguishable from a stamp+ // nearly an hour old. Opaque is the safe direction — a race must never make a tile+ // transparent — and it agrees with `fade_in_progress`, which already wraps.+ assert_eq!(lod_fade_alpha(uploaded_at - 1.0, uploaded_at, d), 1.0); assert_eq!(lod_fade_alpha(uploaded_at + 10.0, uploaded_at, d), 1.0); } @@ -50,6 +53,26 @@ fn a_long_resident_tile_is_fully_opaque() { assert_eq!(lod_fade_alpha(now, uploaded_at, LOD_FADE_SECONDS), 1.0); } +/// Across the hourly clock wrap a young tile stays young: a tile stamped at 3599.9 against a+/// clock just wrapped to 0.1 is 0.2 s old, ramping — never stuck transparent for the hour.+/// The plain subtraction read −3599.8 s, clamped to 0, and pinned the tile invisible while a+/// coarse ancestor was resident. `fade_in_progress` already wrapped; this makes the alpha+/// agree with it.+#[test]+fn the_fade_survives_the_hourly_clock_wrap() {+ use crate::camera::CLOCK_WRAP_SECONDS;+ let d = LOD_FADE_SECONDS;+ let uploaded_at = CLOCK_WRAP_SECONDS - 0.1;+ let now = 0.1;+ let alpha = lod_fade_alpha(now, uploaded_at, d);+ assert!(+ (alpha - 0.2 / d).abs() < 1e-3,+ "0.2 s into the fade, not stuck at 0: got {alpha}",+ );+ // And the progress gate agrees it is mid-fade, so the frame loop keeps running.+ assert!(fade_in_progress(now, uploaded_at, d));+}+ /// The coarse ancestor stays fully opaque underneath a fading finer child: the child ramps /// (an ancestor is resident to cover the gap) while the ancestor, having nothing resident /// above it, draws at full opacity.@@ -115,6 +138,22 @@ fn a_lone_fresh_tile_does_not_fade() { ); } +/// The zoom-out upload burst: the first frame and any frame whose zoom decreased drain+/// finished tiles faster, so a zoom-out that invalidates the whole viewport refills in a+/// frame or two instead of trickling at the steady rate while the east half of the map+/// waits lineless.+#[test]+fn the_first_frame_and_any_zoom_out_take_the_burst_path() {+ assert!(zoom_out_burst(None, 10.0), "the first frame bursts");+ assert!(zoom_out_burst(Some(10.0), 4.0), "a zoom-out bursts");+ assert!(+ zoom_out_burst(Some(10.0), 9.99),+ "even a fractional step out bursts",+ );+ assert!(!zoom_out_burst(Some(4.0), 10.0), "a zoom-in keeps the steady rate");+ assert!(!zoom_out_burst(Some(10.0), 10.0), "a pan at the same zoom keeps it");+}+ /// The fade window is open for exactly as long as the fade runs, so the on-demand frame /// loop keeps drawing across it and stops once the tile has settled. A tile frozen at /// half opacity is what this prevents.
library/map/src/main/rust/src/tile/symbol/tests.rs
diff --git a/library/map/src/main/rust/src/tile/symbol/tests.rs b/library/map/src/main/rust/src/tile/symbol/tests.rsindex bde1f822ce..127108ee92 100644--- a/library/map/src/main/rust/src/tile/symbol/tests.rs+++ b/library/map/src/main/rust/src/tile/symbol/tests.rs@@ -212,6 +212,7 @@ fn a_label_carries_its_own_kind_and_id_not_its_layers() { heightmap: None, carriageways: Vec::new(), convention: None,+ region_links: Vec::new(), }; // A layer whose whitelist lists `restaurant` first, exactly as `poi-food` does. let layer = food_layer();
library/map/src/main/rust/src/vulkan/renderer/record_flat.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_flat.rs b/library/map/src/main/rust/src/vulkan/renderer/record_flat.rsdeleted file mode 100644index b00f8d561e..0000000000--- a/library/map/src/main/rust/src/vulkan/renderer/record_flat.rs+++ /dev/null@@ -1,276 +0,0 @@-use super::fog::{apply_fog, fog_factor};-use super::{- argb_to_rgba, scale_alpha, Renderer, ResidentTile, ARROW_COLOR, ARROW_DP,- BUILDINGS_DRAW_MIN_ZOOM, IDENTITY, PUCK_COLOR, PUCK_CONE_DP, PUCK_CONE_HALF_STROKE_DP,- PUCK_DOT_DP, PUCK_QUAD_DP, PUCK_RIM_DP, QUAD_INDICES, SCRIM_COLOR, TRAFFIC_WIDTH_DP,-};-use crate::camera::Camera;-use crate::marker::{Marker, MARKER_SIZE_DP};-use crate::style::paint::Stroke;-use crate::style::{Layer, LayerKind, Palette};-use crate::tile::select;-use crate::timing::{nanos_since, Step};-use crate::vulkan::pipeline::{Push, MORPH_NONE, NO_MARKINGS};-use ash::vk;-use std::collections::HashMap;-use tilecodec::mamaps::dict::LAYER_JUNCTION;--impl Renderer {- /// The flat-layer pass of `record_inner`: basemap fills, lines and deferred symbols,- /// layer-major across tiles, coarsest tile first.- ///- /// Split from `record_inner` so `record.rs` stays under the file-length limit; the pass- /// itself is unchanged. Takes every draw input by parameter (no `&mut self`) because the- /// caller holds the scratch buffers as raw pointers across the `&mut self` symbol calls- /// that follow this pass.- #[allow(clippy::too_many_arguments)]- unsafe fn record_flat_layers(- command_buffer: vk::CommandBuffer,- camera: &Camera,- layers: &[Layer],- palette: Palette,- filter: &crate::style::KindFilter,- fog: u32,- camera_z: u8,- ordered: &[u64],- tile_alpha: &HashMap<u64, f32>,- tiles: &HashMap<u64, super::ResidentTile>,- draws: &mut Vec<(- u8,- u32,- u32,- LayerKind,- vk::Buffer,- vk::Buffer,- u32,- u32,- Option<u32>,- (u8, u8, u8),- )>,- deferred_symbols: &mut Vec<(u64, usize)>,- device: &ash::Device,- fill: vk::Pipeline,- line: vk::Pipeline,- fill_globe: vk::Pipeline,- line_globe: vk::Pipeline,- layout: vk::PipelineLayout,- edge_aa: f32,- bound: &mut Option<LayerKind>,- submitted: &mut usize,- ) {- // The globe flag for this frame: the globe matrices + shaders + depth path- // below, or the flat path bit-identically above. Read once (not per tile)- // so a frame cannot mix the two.- let globe = crate::camera::globe_active(camera);- for (index, layer) in layers.iter().enumerate() {- // `min_zoom`/`max_zoom` are a data-and-cost gate, not paint: they say which zooms- // the archive is worth asking for this layer at. Paint is the ramp below.- if !layer.draws_at_focused(camera_z, layer.focused_by(filter)) {- continue;- }- // Width and opacity come from the flat style, evaluated against the *camera's*- // fractional zoom rather than the tile's, so a stroke grows and a fill fades- // smoothly while zooming instead of jumping a step at every level. Both are push- // constants, so this re-tessellates nothing, and neither varies per tile.- // Symbols are the exception: label quads are sized per frame (see- // tile::symbol), so the text size is evaluated here and the mesh lookup- // below re-tessellates the tile's symbol layers every frame. Cheap —- // dozens of quads — and placement stays frame-correct.- let (stroke, opacity) = match layer.kind {- // The ramp is what makes a fill visible, and it is the *only* thing: gating a- // fill on an integer zoom drew `landcover` at full strength at z6 where the- // ramp asks for half, and popped `landuse_park` on at full strength at z7- // where it asks for a fifth.- LayerKind::Fill => {- let opacity = layer.opacity_at(camera.zoom);- if opacity <= 0.0 {- continue;- }- (Stroke::NONE, opacity)- }- LayerKind::Line => {- let stroke = layer.stroke(camera.zoom);- // The ramps reach zero outside the zooms a layer is meant for, and that is- // the style's own gate: several road layers carry no `min_zoom` and rely on- // it.- if !stroke.visible() {- continue;- }- // A line's own opacity ramp (today only rail's 0.5): the authored style- // paints some lines translucent, and folding it into the colour column- // would bake a constant while the ramp stays per-frame like a fill's.- (stroke, layer.opacity_at(camera.zoom))- }- LayerKind::Symbol => {- if !layer.text_visible_at(camera.zoom) {- continue;- }- (Stroke::NONE, layer.opacity_at(camera.zoom))- }- };- for key in ordered.iter() {- // Symbol layers emit per frame at the frame's text size from the- // tile's shaped candidates (see above): deferred to after the buildings- // pass so labels are not painted over, then drawn with `&mut self` for- // their transient uploads.- if layer.kind == LayerKind::Symbol {- // Deeper tiles contribute no candidates (see `place_symbols`), so their- // labels are already suppressed by the accept set. Skipping the job here- // only avoids scanning their labels to emit nothing.- if tiles.get(key).is_some_and(|tile| tile.z > camera_z) {- continue;- }- deferred_symbols.push((*key, index));- continue;- }- // Copy the draw's inputs out, then issue them through the owned `device`- // clone: `record_symbol` above takes `&mut self`, so this path must not- // hold a `self.tiles` borrow either. Draws read from the tile's pooled- // buffers (bound once per tile below), so only the pool pair plus the- // slice's firstIndex ride here.- draws.clear();- if let Some(tile) = tiles.get(key) {- let pool = match layer.kind {- LayerKind::Fill => tile.flat.as_ref().map(|(v, i)| (v.buffer, i.buffer)),- LayerKind::Line => tile.lines.as_ref().map(|(v, i)| (v.buffer, i.buffer)),- LayerKind::Symbol => None,- };- let Some((pool_vbuf, pool_ibuf)) = pool else {- // No pool means no mesh of this format packed — nothing to draw.- // (Symbols never take this path; see the deferred arm above.)- if layer.kind == LayerKind::Symbol {- continue;- }- continue;- };- for mesh in tile.layers.iter().filter(|l| l.layer_index == index) {- draws.push((- tile.z,- tile.x,- tile.y,- mesh.kind,- pool_vbuf,- pool_ibuf,- mesh.first_index,- mesh.index_count,- mesh.color_override,- mesh.lane,- ));- }- }- // This tile's LOD cross-fade opacity for the frame (WS-D), applied through- // `Push.morph.x`. The fill fragment multiplies output alpha by it; the line path- // (owned by WS-B's `line.frag`) ignores `morph.x`, so road casings stay crisp- // while the fill fades — the fade reads as the flat basemap ramping in.- let tile_fade = tile_alpha.get(key).copied().unwrap_or(1.0);- for &(tz, tx, ty, kind, vbuf, ibuf, first_index, count, color_override, lane) in- draws.iter()- {- if *bound != Some(kind) {- // The bound cache is per kind: globe and flat share the kind key- // but never mix in one frame (`globe` is read once above), so the- // first bind of the frame wins and stays for the frame.- let pipeline = match kind {- LayerKind::Fill if globe => fill_globe,- LayerKind::Fill => fill,- LayerKind::Line if globe => line_globe,- LayerKind::Line => line,- // Symbols never take this path (drawn above); this arm is- // unreachable but the match must stay exhaustive.- LayerKind::Symbol => continue,- };- device.cmd_bind_pipeline(- command_buffer,- vk::PipelineBindPoint::GRAPHICS,- pipeline,- );- *bound = Some(kind);- }-- let (half_width_px, half_gap_px) = stroke.half_px(camera.density);- // `misc.y` tells the fragment shader whether it has to antialias the edge- // itself. With MSAA the rasteriser already resolves partial coverage, and- // applying a second coverage term on top fades a diagonal road twice — at- // z6 a 2.9px highway crossing the screen at an angle lost all but one- // pixel of its strength, while the near-vertical stretches of the same- // road kept three.- // A mesh that carries its own colour keeps it **unshifted**: transit- // colours are operator brand colours, and the reference draws them- // literally. Every other layer goes through `color(palette)`, which- // swaps in the dark column and blends toward the background when muted;- // doing that to a route colour would turn a network's own red into- // whatever the dark basemap thinks red should be. The opacity ramp still- // applies, because that is per-frame paint rather than palette.- let base = color_override.unwrap_or_else(|| layer.color(palette));- // Distance fog: haze the draw toward the land colour with its tile's- // distance, so tilted far tiles dissolve instead of ending at a hard- // ground edge. Zero at pitch 0 — the flat map is unchanged.- let base = apply_fog(base, fog, fog_factor(camera, tz, tx, ty));- // How far this mesh's whole band shifts sideways, in device pixels. The- // feature carries its colour's ordinal and its corridor's colour count,- // not an offset: how many lanes the corridor actually draws is a step- // function of the camera zoom, so the lane is chosen here rather than- // baked into the mesh. Zero for every layer but transit, where the count- // is absent and reads one.- let (ordinal, count_of_colours, taper) = lane;- let lateral_px = layer.lane_offset_px(- camera.zoom,- camera.density,- ordinal,- count_of_colours,- taper,- );- let push = Push {- tile_to_clip: camera.tile_to_clip(tz, tx, ty),- color: argb_to_rgba(scale_alpha(base, opacity)),- line: [half_width_px, half_gap_px, layer.dash.0, layer.dash.1],- misc: if globe {- // Globe: centre lon/lat (degrees) for the sphere basis.- [- camera.center_lon as f32,- camera.center_lat as f32,- lateral_px,- camera.time_seconds,- ]- } else {- [- camera.tile_span_px(tz),- edge_aa,- lateral_px,- camera.time_seconds,- ]- },- // `morph.z` is the tile's world-px span (Dp): the draped-`z` scale.- // On the globe it is the globe radius (Dp) instead, and morph.xy- // the half-viewport (Dp) — see the `*_globe.vert` headers.- morph: if globe {- let r = crate::camera::globe_radius(camera.zoom) as f32;- [- tile_fade,- camera.width_dp / 2.0,- r,- camera.height_dp / 2.0,- ]- } else {- [tile_fade, 0.0, camera.tile_span_dp(tz) as f32, 0.0]- },- };- device.cmd_push_constants(- command_buffer,- layout,- vk::ShaderStageFlags::VERTEX | vk::ShaderStageFlags::FRAGMENT,- 0,- push.as_bytes(),- );- device.cmd_bind_vertex_buffers(command_buffer, 0, &[vbuf], &[0]);- // Uint32 rather than Uint16: a dense z14 tile can exceed 65535 vertices in- // one layer, and overflowing folds geometry back on itself rather than- // failing loudly. Indices are rebased to absolute at upload, so the slice- // draws from its firstIndex inside the shared pool.- device.cmd_bind_index_buffer(command_buffer, ibuf, 0, vk::IndexType::UINT32);- device.cmd_draw_indexed(command_buffer, count, 1, first_index, 0, 0);- *submitted += 1;- }- }- }- }
library/map/src/main/rust/src/vulkan/renderer/tail.tmp
diff --git a/library/map/src/main/rust/src/vulkan/renderer/tail.tmp b/library/map/src/main/rust/src/vulkan/renderer/tail.tmpdeleted file mode 100644index f9f3e1a6c7..0000000000--- a/library/map/src/main/rust/src/vulkan/renderer/tail.tmp+++ /dev/null@@ -1,463 +0,0 @@- /// Draw `mesh` as the navigation route, or take the route away with `None`.- ///- /// Pure state like [`set_user_puck`](Self::set_user_puck), and for a stronger reason:- /// a route arrives once when the driver starts navigating and then does not change- /// for the rest of the trip, so it has no business being an argument on- /// [`render`](Self::render).- ///- /// The old buffers go through the same frames-in-flight grace queue the transient- /// symbol buffers use — a command buffer submitted last frame may still be reading- /// them, and freeing a live vertex buffer is the classic Vulkan use-after-free.- ///- /// On upload failure the route is left cleared rather than half-set, so a device that- /// cannot allocate draws no route instead of a route with no indices.- pub fn set_route(&mut self, mesh: Option<&RouteMesh>) -> Result<(), String> {- if let Some(previous) = self.route.take() {- self.transients.push(TransientBuffers {- vbuf: previous.vertices,- ibuf: previous.indices,- frames: FRAMES_IN_FLIGHT,- });- }- let Some(mesh) = mesh else { return Ok(()) };- if mesh.indices.is_empty() {- return Ok(());- }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &mesh.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &mesh.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- self.route = Some(RouteBuffers {- placement: mesh.placement,- vertices,- indices,- index_count: mesh.indices.len() as u32,- segments: mesh.segments.clone(),- });- }- Ok(())- }-- /// Upload a tile's geometry, replacing anything already resident for it.- pub fn upload(&mut self, key: u64, mesh: &TileMesh) -> Result<(), String> {- let mut layers = Vec::with_capacity(mesh.meshes.len());- for layer_mesh in &mesh.meshes {- if layer_mesh.indices.is_empty() {- continue;- }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &layer_mesh.vertices,- )?;- let indices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &layer_mesh.indices,- )?;- layers.push(LayerBuffers {- layer_index: layer_mesh.layer_index,- kind: layer_mesh.kind,- vertices,- indices,- index_count: layer_mesh.indices.len() as u32,- color_override: layer_mesh.color_override,- lane: layer_mesh.lane,- });- }- }- let mut regions = Vec::with_capacity(mesh.regions.len());- for region in &mesh.regions {- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- ®ion.vertices,- )?;- let indices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- ®ion.indices,- )?;- regions.push(RegionBuffers {- id: region.id,- vertices,- indices,- index_count: region.indices.len() as u32,- rings: region.rings.clone(),- area: region.area,- level: region.level,- });- }- }- let mut traffic = Vec::with_capacity(mesh.traffic.len());- for segment in &mesh.traffic {- if segment.indices.is_empty() {- continue;- }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &segment.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &segment.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- traffic.push(TrafficBuffers {- id: segment.id,- vertices,- indices,- index_count: segment.indices.len() as u32,- });- }- }- // The tile's road carriageways: one mesh per distinct road shape, uploaded like the- // traffic segments above.- let mut carriageways = Vec::with_capacity(mesh.carriageways.len());- for road in &mesh.carriageways {- if road.indices.is_empty() {- continue;- }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &road.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &road.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- carriageways.push(CarriagewayBuffers {- layer_index: road.layer_index,- lanes: road.lanes,- split: road.split,- oneway: road.oneway,- vertices,- indices,- index_count: road.indices.len() as u32,- });- }- }- // The tile's 3D buildings, if any: one combined mesh, uploaded like the rest.- let buildings = if mesh.buildings.indices.is_empty() {- None- } else {- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &mesh.buildings.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &mesh.buildings.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- Some(BuildingBuffers {- vertices,- indices,- index_count: mesh.buildings.indices.len() as u32,- })- }- };- // The tile's terrain grid, if any: one combined mesh, uploaded like the buildings above.- let terrain = if mesh.terrain.indices.is_empty() {- None- } else {- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &mesh.terrain.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &mesh.terrain.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- Some(TerrainBuffers {- vertices,- indices,- index_count: mesh.terrain.indices.len() as u32,- })- }- };- let tile = ResidentTile {- layers,- buildings,- terrain,- regions,- traffic,- carriageways,- yellow_centre: mesh.yellow_centre,- labels: mesh.labels.clone(),- arrows: mesh.arrows.clone(),- z: mesh.z,- x: mesh.x,- y: mesh.y,- // Stamp the tile with the latest frame clock so the fade below measures from the- // moment its GPU buffers landed. Before the first frame there is no clock yet;- // 0.0 makes `now - uploaded_at` large, so a startup tile is fully opaque at once- // (nothing is under it to fade over anyway).- uploaded_at: self.last_camera.map(|c| c.time_seconds).unwrap_or(0.0),- generation: mesh.generation,- };- if let Some(previous) = self.tiles.insert(key, tile) {- self.retire(previous);- }- Ok(())- }-- /// Drop resident tiles that are neither wanted nor useful as a stand-in, and enforce the- /// residency cap.- ///- /// `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(&mut self, keep: &[u64], visible: &[select::TileId], cap: usize) {- 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)> = self- .tiles- .keys()- .map(|&key| {- 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) {- 1 // an ancestor: one coarse tile covers many fine ones, so cheap to hold- } else if select::stands_in_for_visible(key, visible, select::DESCENDANT_DEPTH) {- 2 // a descendant: only covers a fraction of the screen, so the first to go- } else {- 3 // unrelated to anything on screen- };- (rank, key)- })- .collect();- ranked.sort_unstable();-- let doomed: Vec<u64> = ranked- .iter()- .enumerate()- .filter(|(at, (rank, _))| *rank == 3 || *at >= cap)- .map(|(_, (_, key))| *key)- .collect();- for key in doomed {- if let Some(tile) = self.tiles.remove(&key) {- self.retire(tile);- }- }- }-- /// Hold a tile's buffers until every in-flight frame that might reference them has- /// finished.- ///- /// Freeing them immediately is the classic Vulkan use-after-free: a command buffer- /// submitted last frame can still be executing, and destroying its vertex buffer is- /// undefined behaviour that usually looks like corrupted geometry rather than a crash.- fn retire(&mut self, tile: ResidentTile) {- self.retiring.push((FRAMES_IN_FLIGHT, tile));- }-- /// Free anything whose grace period has expired.- pub(super) fn collect_retired(&mut self) {- let device = &self.context.device;- self.retiring.retain_mut(|(remaining, tile)| {- if *remaining > 0 {- *remaining -= 1;- return true;- }- unsafe {- for layer in &tile.layers {- layer.vertices.destroy(device);- layer.indices.destroy(device);- }- for region in &tile.regions {- region.vertices.destroy(device);- region.indices.destroy(device);- }- for segment in &tile.traffic {- segment.vertices.destroy(device);- segment.indices.destroy(device);- }- for road in &tile.carriageways {- road.vertices.destroy(device);- road.indices.destroy(device);- }- if let Some(buildings) = &tile.buildings {- buildings.vertices.destroy(device);- buildings.indices.destroy(device);- }- if let Some(terrain) = &tile.terrain {- terrain.vertices.destroy(device);- terrain.indices.destroy(device);- }- }- false- });- // Transient per-frame symbol buffers retire on the same grace count, in- // their own queue — no device_wait_idle stall on the frame path.- self.transients.retain_mut(|t| {- if t.frames > 0 {- t.frames -= 1;- return true;- }- unsafe {- t.vbuf.destroy(device);- t.ibuf.destroy(device);- }- false- });- }-}--/// Upload the process-global glyph atlas and allocate its descriptor set.-///-/// Separate from [`Renderer::new`] so the error paths read linearly. Called once-/// at startup; the bytes come from `tile::glyph::atlas()` (SDF R8 built from the-/// bundled Noto Sans at first use).-///-/// # Safety-///-/// Same rules as the surrounding constructors: live device, idle queue.-unsafe fn try_upload_glyph_atlas(- context: &Context,- atlas_set: &AtlasSet,- command_pool: vk::CommandPool,-) -> Result<(SampledImage, vk::DescriptorSet), String> {- use crate::tile::glyph;- if !glyph::fonts_staged() {- return Err("bundled fonts are not valid TTFs".into());- }- let atlas = glyph::atlas();- let image = SampledImage::upload(- &context.instance,- context.physical_device,- &context.device,- context.queue,- context.queue_family_index,- command_pool,- &atlas.pixels,- glyph::ATLAS_PX,- glyph::ATLAS_PX,- vk::Format::R8_UNORM,- )?;- let set = atlas_set.allocate(&context.device, &image)?;- Ok((image, set))-}--/// Upload the process-global POI sprite sheet and allocate its descriptor set.-///-/// [`try_upload_glyph_atlas`]'s counterpart, and the second of the two sets-/// [`AtlasSet`]'s pool is sized for. The sheet is already RGBA8, so-/// [`SampledImage::upload`] takes it unchanged — no expansion step like the glyph-/// atlas's R8 one.-///-/// # Safety-///-/// Same rules as the surrounding constructors: live device, idle queue.-unsafe fn try_upload_sprite_atlas(- context: &Context,- atlas_set: &AtlasSet,- command_pool: vk::CommandPool,-) -> Result<(SampledImage, vk::DescriptorSet), String> {- use crate::tile::sprite;- let atlas = sprite::atlas();- // An empty atlas is what `sprite::atlas()` leaves behind when the sheet will not- // decode; uploading a zero-sized image would fail in the driver instead of here.- if atlas.is_empty() {- return Err("the sprite sheet carries no icons".into());- }- let image = SampledImage::upload(- &context.instance,- context.physical_device,- &context.device,- context.queue,- context.queue_family_index,- command_pool,- &atlas.pixels,- atlas.width,- atlas.height,- vk::Format::R8G8B8A8_UNORM,- )?;- let set = atlas_set.allocate(&context.device, &image)?;- Ok((image, set))-}
library/map/src/main/rust/src/vulkan/renderer/upload.rs.bak
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload.rs.bak b/library/map/src/main/rust/src/vulkan/renderer/upload.rs.bakdeleted file mode 100644index 78cd15fc35..0000000000--- a/library/map/src/main/rust/src/vulkan/renderer/upload.rs.bak+++ /dev/null@@ -1,652 +0,0 @@-use super::{- BuildingBuffers, CarriagewayBuffers, FRAMES_IN_FLIGHT, Frame, LayerBuffers, QUAD_INDICES,- QUAD_VERTICES, Quad, RegionBuffers, Renderer, ResidentTile, RouteBuffers, TerrainBuffers,- TrafficBuffers, TransientBuffers,-};-use crate::overlay::RouteMesh;-use crate::tile::geometry::TileMesh;-use crate::tile::select;-use crate::vulkan::buffers::{Buffer, ScratchRing};-use crate::vulkan::cache::ShaderCache;-use crate::vulkan::context::{ANativeWindow, Context};-use crate::vulkan::images::{AtlasSet, SampledImage};-use crate::vulkan::pick::Pick;-use crate::vulkan::pipeline::Pipelines;-use crate::vulkan::swapchain::Swapchain;-use ash::vk;-use std::cell::Cell;-use std::collections::{HashMap, HashSet};--impl Renderer {- /// # Safety- ///- /// `window` must be an acquired `ANativeWindow`; the renderer releases it on drop.- pub unsafe fn new(- window: *mut ANativeWindow,- width: u32,- height: u32,- cache_dir: &std::path::Path,- ) -> Result<Renderer, String> {- let context = Context::new(window)?;- let swapchain = Swapchain::new(&context, width, height)?;- let atlas_set = AtlasSet::new(&context.device)?;- // Before any pipeline is created, so the very first launch's twelve compiles are the ones- // that get recorded. Its own subdirectory of `cache_dir`, not `cache_dir` itself: the tile- // range cache deletes every *file* in its directory when the archive origin changes- // (`tile::cache::RangeCache::invalidate_on_origin_change`), so a blob there would be wiped- // by an unrelated archive republish and read as a random cold start. That deletion is- // `remove_file`, which does not recurse into a subdirectory.- let cache_path = cache_dir.join("pipeline");- let mut pipeline_cache = ShaderCache::open(- &context.instance,- context.physical_device,- &context.device,- Some(&cache_path),- );- let pipelines = Pipelines::new(- &context.device,- swapchain.render_pass,- swapchain.samples,- Some(atlas_set.layout),- pipeline_cache.handle(),- )?;-- let pool_info = vk::CommandPoolCreateInfo::default()- .queue_family_index(context.queue_family_index)- // Each frame's buffer is re-recorded every frame, so it must be individually- // resettable rather than requiring a whole-pool reset.- .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER);- let command_pool = context- .device- .create_command_pool(&pool_info, None)- .map_err(|e| format!("create_command_pool {e:?}"))?;- // The glyph atlas is a process-global built from the bundled fonts; upload- // it now so every symbol draw can bind it. Failure is non-fatal: labels- // simply don't draw until a build with working fonts (see fonts_staged).- // Logging goes through eprintln: bridge::log needs `__android_log_write`,- // which links on device but not on the host test binary.- let (glyph_atlas, glyph_set) = unsafe {- match try_upload_glyph_atlas(&context, &atlas_set, command_pool) {- Ok((image, set)) => (Some(image), Some(set)),- Err(e) => {- eprintln!("glyph atlas upload skipped: {e}");- (None, None)- }- }- };- // The POI sprite sheet, on the same terms: a failure costs icons, not the map.- // It takes the second of the two sets `AtlasSet` sizes its pool for.- let (sprite_atlas, sprite_set) = unsafe {- match try_upload_sprite_atlas(&context, &atlas_set, command_pool) {- Ok((image, set)) => (Some(image), Some(set)),- Err(e) => {- eprintln!("sprite atlas upload skipped: {e}");- (None, None)- }- }- };-- let allocate = vk::CommandBufferAllocateInfo::default()- .command_pool(command_pool)- .level(vk::CommandBufferLevel::PRIMARY)- .command_buffer_count(FRAMES_IN_FLIGHT as u32);- let command_buffers = context- .device- .allocate_command_buffers(&allocate)- .map_err(|e| format!("allocate_command_buffers {e:?}"))?;-- let mut frames = Vec::with_capacity(FRAMES_IN_FLIGHT);- for &command_buffer in &command_buffers {- // Created signalled, so the first frame does not wait on a fence nothing has- // submitted to.- let fence_info =- vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::SIGNALED);- let semaphore_info = vk::SemaphoreCreateInfo::default();- frames.push(Frame {- command_buffer,- in_flight: context- .device- .create_fence(&fence_info, None)- .map_err(|e| format!("create_fence {e:?}"))?,- image_available: context- .device- .create_semaphore(&semaphore_info, None)- .map_err(|e| format!("create_semaphore {e:?}"))?,- render_finished: context- .device- .create_semaphore(&semaphore_info, None)- .map_err(|e| format!("create_semaphore {e:?}"))?,- });- }-- // Read the extent before the swapchain moves into the struct: the surface may have- // given us a different size than we asked for.- let width = swapchain.extent.width;- let height = swapchain.extent.height;-- // The overlay geometry, uploaded once and never touched again. Unlike the- // atlases this is not optional: it is 32 bytes of vertices, and a device that- // cannot allocate that cannot draw a tile either.- let quad = Quad {- vertices: Buffer::upload(- &context.instance,- context.physical_device,- &context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &QUAD_VERTICES,- )?,- indices: Buffer::upload(- &context.instance,- context.physical_device,- &context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &QUAD_INDICES,- )?,- };-- // The offscreen id-buffer pass for tap picking. Self-contained and format-stable, so it is- // built once here and survives swapchain rebuilds (only its target is resized).- let pick = Pick::new(&context, pipeline_cache.handle())?;- // Everything that compiles a shader has now run once. On a cold cache this is the write- // that makes every later launch cheap; on a warm one the blob has not grown and this does- // nothing.- pipeline_cache.persist(&context.device);-- Ok(Renderer {- context,- swapchain,- pipelines,- atlas_set,- glyph_atlas,- glyph_set,- sprite_atlas,- sprite_set,- command_pool,- frames,- frame_index: 0,- tiles: HashMap::new(),- retiring: Vec::new(),- pipeline_cache,- transients: Vec::new(),- scratch: (0..FRAMES_IN_FLIGHT).map(|_| ScratchRing::default()).collect(),- window,- width,- height,- needs_rebuild: false,- submitted_draws: Cell::new(0),- placed: std::cell::RefCell::new(Vec::new()),- placement_cache: std::cell::RefCell::new(None),- overlays: Vec::new(),- quad,- selected_region: None,- route: None,- traffic_colors: HashMap::new(),- traffic_enabled: false,- pick,- last_camera: None,- })- }-- /// Draw `mesh` as the navigation route, or take the route away with `None`.- ///- /// Pure state like [`set_user_puck`](Self::set_user_puck), and for a stronger reason:- /// a route arrives once when the driver starts navigating and then does not change- /// for the rest of the trip, so it has no business being an argument on- /// [`render`](Self::render).- ///- /// The old buffers go through the same frames-in-flight grace queue the transient- /// symbol buffers use — a command buffer submitted last frame may still be reading- /// them, and freeing a live vertex buffer is the classic Vulkan use-after-free.- ///- /// On upload failure the route is left cleared rather than half-set, so a device that- /// cannot allocate draws no route instead of a route with no indices.- pub fn set_route(&mut self, mesh: Option<&RouteMesh>) -> Result<(), String> {- if let Some(previous) = self.route.take() {- self.transients.push(TransientBuffers {- vbuf: previous.vertices,- ibuf: previous.indices,- frames: FRAMES_IN_FLIGHT,- });- }- let Some(mesh) = mesh else { return Ok(()) };- if mesh.indices.is_empty() {- return Ok(());- }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &mesh.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &mesh.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- self.route = Some(RouteBuffers {- placement: mesh.placement,- vertices,- indices,- index_count: mesh.indices.len() as u32,- segments: mesh.segments.clone(),- });- }- Ok(())- }-- /// Upload a tile's geometry, replacing anything already resident for it.- pub fn upload(&mut self, key: u64, mesh: &TileMesh) -> Result<(), String> {- let mut layers = Vec::with_capacity(mesh.meshes.len());- for layer_mesh in &mesh.meshes {- if layer_mesh.indices.is_empty() {- continue;- }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &layer_mesh.vertices,- )?;- let indices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &layer_mesh.indices,- )?;- layers.push(LayerBuffers {- layer_index: layer_mesh.layer_index,- kind: layer_mesh.kind,- vertices,- indices,- index_count: layer_mesh.indices.len() as u32,- color_override: layer_mesh.color_override,- lane: layer_mesh.lane,- });- }- }- let mut regions = Vec::with_capacity(mesh.regions.len());- for region in &mesh.regions {- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- ®ion.vertices,- )?;- let indices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- ®ion.indices,- )?;- regions.push(RegionBuffers {- id: region.id,- vertices,- indices,- index_count: region.indices.len() as u32,- rings: region.rings.clone(),- area: region.area,- level: region.level,- });- }- }- let mut traffic = Vec::with_capacity(mesh.traffic.len());- for segment in &mesh.traffic {- if segment.indices.is_empty() {- continue;- }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &segment.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &segment.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- traffic.push(TrafficBuffers {- id: segment.id,- vertices,- indices,- index_count: segment.indices.len() as u32,- });- }- }- // The tile's road carriageways: one mesh per distinct road shape, uploaded like the- // traffic segments above.- let mut carriageways = Vec::with_capacity(mesh.carriageways.len());- for road in &mesh.carriageways {- if road.indices.is_empty() {- continue;- }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &road.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &road.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- carriageways.push(CarriagewayBuffers {- layer_index: road.layer_index,- lanes: road.lanes,- split: road.split,- oneway: road.oneway,- vertices,- indices,- index_count: road.indices.len() as u32,- });- }- }- // The tile's 3D buildings, if any: one combined mesh, uploaded like the rest.- let buildings = if mesh.buildings.indices.is_empty() {- None- } else {- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &mesh.buildings.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &mesh.buildings.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- Some(BuildingBuffers {- vertices,- indices,- index_count: mesh.buildings.indices.len() as u32,- })- }- };- // The tile's terrain grid, if any: one combined mesh, uploaded like the buildings above.- let terrain = if mesh.terrain.indices.is_empty() {- None- } else {- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &mesh.terrain.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &mesh.terrain.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- Some(TerrainBuffers {- vertices,- indices,- index_count: mesh.terrain.indices.len() as u32,- })- }- };- let tile = ResidentTile {- layers,- buildings,- terrain,- regions,- traffic,- carriageways,- yellow_centre: mesh.yellow_centre,- labels: mesh.labels.clone(),- arrows: mesh.arrows.clone(),- z: mesh.z,- x: mesh.x,- y: mesh.y,- // Stamp the tile with the latest frame clock so the fade below measures from the- // moment its GPU buffers landed. Before the first frame there is no clock yet;- // 0.0 makes `now - uploaded_at` large, so a startup tile is fully opaque at once- // (nothing is under it to fade over anyway).- uploaded_at: self.last_camera.map(|c| c.time_seconds).unwrap_or(0.0),- generation: mesh.generation,- };- if let Some(previous) = self.tiles.insert(key, tile) {- self.retire(previous);- }- Ok(())- }-- /// Drop resident tiles that are neither wanted nor useful as a stand-in, and enforce the- /// residency cap.- ///- /// `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(&mut self, keep: &[u64], visible: &[select::TileId], cap: usize) {- 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)> = self- .tiles- .keys()- .map(|&key| {- 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) {- 1 // an ancestor: one coarse tile covers many fine ones, so cheap to hold- } else if select::stands_in_for_visible(key, visible, select::DESCENDANT_DEPTH) {- 2 // a descendant: only covers a fraction of the screen, so the first to go- } else {- 3 // unrelated to anything on screen- };- (rank, key)- })- .collect();- ranked.sort_unstable();-- let doomed: Vec<u64> = ranked- .iter()- .enumerate()- .filter(|(at, (rank, _))| *rank == 3 || *at >= cap)- .map(|(_, (_, key))| *key)- .collect();- for key in doomed {- if let Some(tile) = self.tiles.remove(&key) {- self.retire(tile);- }- }- }-- /// Hold a tile's buffers until every in-flight frame that might reference them has- /// finished.- ///- /// Freeing them immediately is the classic Vulkan use-after-free: a command buffer- /// submitted last frame can still be executing, and destroying its vertex buffer is- /// undefined behaviour that usually looks like corrupted geometry rather than a crash.- fn retire(&mut self, tile: ResidentTile) {- self.retiring.push((FRAMES_IN_FLIGHT, tile));- }-- /// Free anything whose grace period has expired.- pub(super) fn collect_retired(&mut self) {- let device = &self.context.device;- self.retiring.retain_mut(|(remaining, tile)| {- if *remaining > 0 {- *remaining -= 1;- return true;- }- unsafe {- for layer in &tile.layers {- layer.vertices.destroy(device);- layer.indices.destroy(device);- }- for region in &tile.regions {- region.vertices.destroy(device);- region.indices.destroy(device);- }- for segment in &tile.traffic {- segment.vertices.destroy(device);- segment.indices.destroy(device);- }- for road in &tile.carriageways {- road.vertices.destroy(device);- road.indices.destroy(device);- }- if let Some(buildings) = &tile.buildings {- buildings.vertices.destroy(device);- buildings.indices.destroy(device);- }- if let Some(terrain) = &tile.terrain {- terrain.vertices.destroy(device);- terrain.indices.destroy(device);- }- }- false- });- // Transient per-frame symbol buffers retire on the same grace count, in- // their own queue — no device_wait_idle stall on the frame path.- self.transients.retain_mut(|t| {- if t.frames > 0 {- t.frames -= 1;- return true;- }- unsafe {- t.vbuf.destroy(device);- t.ibuf.destroy(device);- }- false- });- }-}--/// Upload the process-global glyph atlas and allocate its descriptor set.-///-/// Separate from [`Renderer::new`] so the error paths read linearly. Called once-/// at startup; the bytes come from `tile::glyph::atlas()` (SDF R8 built from the-/// bundled Noto Sans at first use).-///-/// # Safety-///-/// Same rules as the surrounding constructors: live device, idle queue.-unsafe fn try_upload_glyph_atlas(- context: &Context,- atlas_set: &AtlasSet,- command_pool: vk::CommandPool,-) -> Result<(SampledImage, vk::DescriptorSet), String> {- use crate::tile::glyph;- if !glyph::fonts_staged() {- return Err("bundled fonts are not valid TTFs".into());- }- let atlas = glyph::atlas();- let image = SampledImage::upload(- &context.instance,- context.physical_device,- &context.device,- context.queue,- context.queue_family_index,- command_pool,- &atlas.pixels,- glyph::ATLAS_PX,- glyph::ATLAS_PX,
Diff truncated.