From 2545fb96fae14349d48e3fb5cb493af0ef55e2bb Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 10:56:03 -0600 Subject: [PATCH 1/9] perf(render): keep the picture under a changed layer, and a see-through layer alone, between frames (#1057) A screen frame keeps its picture as it stood before one layer was drawn, with the label candidates, graphics text and tile output gathered so far, and the looks of what it was drawn from. The next frame of the same view starts from that picture when the layers below still look the same, drawing only from the first changed layer: restyling a layer over a basemap no longer draws the basemap, its tile layers and the layers below again. When that layer is drawn on its own and composited (see-through or blended), its picture alone is kept too. A frame in which it looks the same or only its transparency changed composites that picture at the new opacity instead of drawing the layer, so dragging a layer's transparency slider draws nothing but the layers above it. A layer showing a selection, graphics text or extruded charts isn't kept alone: those are drawn after the composite. Either way the frame is the same, pixel for pixel, as one drawn whole. Only flat, north-up screen frames on the CPU keep pictures, within 66 MB sized by the view. Part 2 of #1057 step 2. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 397 +++++++++++++++++++++++++++++++ crates/render/src/lib.rs | 106 ++++++++- crates/render/src/tiles.rs | 2 +- 3 files changed, 497 insertions(+), 8 deletions(-) create mode 100644 crates/render/src/frame_cache.rs diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs new file mode 100644 index 0000000000..6c4176410e --- /dev/null +++ b/crates/render/src/frame_cache.rs @@ -0,0 +1,397 @@ +//! A screen frame's picture kept up to a layer, so the next frame of the same view draws only +//! from the first layer that changed (#1057): restyling a layer over a basemap, its tile layers +//! and the layers below it draws that layer and those above it, not the whole map again. +//! +//! A kept picture is a [`Checkpoint`]: the pixels of a frame as they stood before one of its +//! layers was drawn, with the label candidates, graphics text and tile output gathered so far. +//! What it was drawn from is kept beside it as looks ([`rustgis_map::look`]): the map's, each +//! layer's, and the frame's own (view, expression environment, tile and source generations). +//! A frame starts from the checkpoint when everything it holds still looks the same, which makes +//! it the same frame, pixel for pixel, as drawing it all again: the layers below draw first in +//! either case, from the same state. +//! +//! The layer the checkpoint stands under is the one being changed, as a slider drags: when it is +//! drawn on its own and composited (see-through or blended), its picture alone is kept too, as an +//! [`Alone`], with what the frame had gathered once it was drawn. A frame in which that layer +//! looks the same or only its transparency changed ([`Change::Transparency`]) composites that +//! picture at the layer's opacity instead of drawing the layer: the same steps a frame drawn +//! whole takes, so again the same pixels. A layer that shows a selection or graphics text isn't +//! kept alone: both are drawn after the composite, the text in the layer's opacity. +//! +//! Only flat, north-up frames for the screen keep pictures: not exports, recordings, the GPU, +//! the globe, turned or tilted views, nor maps whose layers read others while drawing (a mask, +//! labels turned square to another layer's lines, terrain water). A layer read in place from its +//! source or a raster has no look ([`LayerLook::of`]): it counts as changed in every frame, so a +//! picture is kept only from below it. + +use rustgis_data::query::Env; +use rustgis_map::look::{Change, LayerLook, MapLook}; +use tiny_skia::Pixmap; + +use crate::tiles::TileOutput; +use crate::{Candidate, PlacedLabel, View}; + +/// The most pixels the kept pictures hold together, checkpoints and layers alone: two views of +/// 3840 × 2160, about 66 MB; four pictures (two views with their layers alone) at 1920 × 1080. +const MAX_PIXELS: u64 = 2 * 3840 * 2160; + +/// Pictures kept, one per view drawn (a map and its draft, two maps on screen). +const KEPT: usize = 2; + +/// What a frame is drawn from besides its layers. +#[derive(Clone, Debug)] +pub(crate) struct Frame { + pub map: MapLook, + pub view: View, + pub style_env: Env, + pub label_env: Env, + /// [`rustgis_tiles::cache::generation`]: a tile arrived. + pub tiles: u64, + /// [`rustgis_map::source::generation`]: a streamed read finished. + pub sources: u64, + /// The world outline's worldview, and how many shapes it had at hand. + pub worldview: (crate::sample_data::View, usize), + /// Whether the installed font families were indexed ([`crate::families::available`]). + pub fonts: bool, +} + +impl Frame { + /// Whether `other` draws everything but its layers as this frame did. + fn same(&self, other: &Frame) -> bool { + let (a, b) = (&self.view, &other.view); + a.width.to_bits() == b.width.to_bits() + && a.height.to_bits() == b.height.to_bits() + && a.pixels_per_point.to_bits() == b.pixels_per_point.to_bits() + && a.camera == b.camera + && a.sky == b.sky + && self.style_env == other.style_env + && self.label_env == other.label_env + && self.tiles == other.tiles + && self.sources == other.sources + && self.worldview == other.worldview + && self.fonts == other.fonts + && self.map.same(&other.map) + } +} + +/// A frame as it stood before the layer at one place in the drawing order was drawn. +#[derive(Clone)] +pub(crate) struct Checkpoint { + pub pixels: Pixmap, + pub candidates: Vec, + pub fixed: Vec, + pub tiles: TileOutput, +} + +/// A layer's picture alone, drawn opaque, and what the frame had gathered once the layer was drawn +/// and composited, before the tile layers over it. +#[derive(Clone)] +pub(crate) struct Alone { + pub pixels: Pixmap, + pub candidates: Vec, + pub fixed: Vec, + pub tiles: TileOutput, +} + +/// The looks of a frame's layers, bottom first in drawing order, by id; `None` for one with no +/// look. +pub(crate) type Looks = Vec<(u32, Option)>; + +/// A kept picture and what it was drawn from. +struct Kept { + frame: Frame, + looks: Looks, + /// The place in the drawing order the checkpoint stands before. + at: usize, + checkpoint: Checkpoint, + /// The layer at `at` alone. + alone: Option, +} + +impl Kept { + fn pixels(&self) -> u64 { + let size = |p: &Pixmap| u64::from(p.width()) * u64::from(p.height()); + size(&self.checkpoint.pixels) + self.alone.as_ref().map_or(0, |a| size(&a.pixels)) + } +} + +/// The kept pictures, shared by the threads that draw frames (the UI's and the one that draws +/// a view once it settles). +#[cfg(not(test))] +static PICTURES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Runs `f` on the kept pictures. +#[cfg(not(test))] +fn with_pictures(f: impl FnOnce(&mut Vec) -> R) -> R { + // A thread that panicked while holding them left nothing half done: each is replaced whole. + f(&mut PICTURES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)) +} + +// Each test thread keeps its own, so tests running side by side don't take each other's. +#[cfg(test)] +thread_local! { + static PICTURES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// Where the last frame planned started drawing its layers. + static STARTED: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// Whether the last frame planned had a layer alone to composite. + static RECOMBINED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +#[cfg(test)] +fn with_pictures(f: impl FnOnce(&mut Vec) -> R) -> R { + PICTURES.with_borrow_mut(f) +} + +/// How a frame draws, from [`plan`]. +pub(crate) struct Plan { + /// The place in the drawing order the frame starts drawing layers from: 0 draws everything, + /// basemap included. + pub start: usize, + /// What it starts from when `start` is past 0. + pub restored: Option, + /// The place to keep the frame at, if not the one it was restored at. + pub capture_at: Option, + /// The layer at `start` alone, to composite instead of drawing it: it looks the same or only + /// its transparency changed. Kept again when the layer isn't drawn alone this time. + pub recombine: Option, + /// The place in the drawing order of the layer to keep alone, when it is drawn so. + pub alone_at: Option, + frame: Frame, + looks: Looks, +} + +/// The first place in the drawing order where `now` doesn't look as `then` did. +fn first_change(then: &Looks, now: &Looks) -> usize { + then.iter() + .zip(now) + .position(|((a, la), (b, lb))| { + a != b + || match (la, lb) { + (Some(la), Some(lb)) => la.change(lb) != Change::Same, + _ => true, + } + }) + .unwrap_or(then.len().min(now.len())) +} + +/// How the layer at place `at` in the drawing order differs between `then` and `now`. +fn change_at(then: &Looks, now: &Looks, at: usize) -> Change { + match (then.get(at), now.get(at)) { + (Some((a, Some(la))), Some((b, Some(lb)))) if a == b => la.change(lb), + _ => Change::Drawn, + } +} + +/// The place at which a frame keeping its picture at `at` keeps a layer alone: one with a look, +/// when a view's checkpoint and layer fit within [`MAX_PIXELS`] together. +fn alone_at(looks: &Looks, at: usize, pixels: u64) -> Option { + (pixels.saturating_mul(2) <= MAX_PIXELS && looks.get(at).is_some_and(|(_, l)| l.is_some())).then_some(at) +} + +/// How to draw `frame` with layers `looks` of `pixels` pixels: from a kept picture when one still +/// shows its bottom layers, and where to keep this one. The kept picture is taken out meanwhile; +/// [`keep`] puts the frame's back. +pub(crate) fn plan(frame: Frame, looks: Looks, pixels: u64) -> Plan { + let plan = plan_with(frame, looks, pixels); + #[cfg(test)] + STARTED.set(Some(plan.start)); + #[cfg(test)] + RECOMBINED.set(plan.recombine.is_some()); + plan +} + +/// [`plan`]. +fn plan_with(frame: Frame, looks: Looks, pixels: u64) -> Plan { + if pixels.saturating_mul(KEPT as u64) > MAX_PIXELS { + return Plan { start: 0, restored: None, capture_at: None, recombine: None, alone_at: None, frame, looks }; + } + let found = with_pictures(|kept| kept.iter().position(|k| k.frame.same(&frame)).map(|i| kept.remove(i))); + let Some(k) = found else { + // Nothing to start from: keep what lies under the first layer (the basemap, the tile + // layers below every layer), or the frame under its first changed layer next time. + let alone_at = alone_at(&looks, 0, pixels); + return Plan { start: 0, restored: None, capture_at: Some(0), recombine: None, alone_at, frame, looks }; + }; + let changed = first_change(&k.looks, &looks); + if k.at <= changed { + let capture_at = (changed > k.at && changed < looks.len()).then_some(changed); + let recombine = k.alone.filter(|_| matches!(change_at(&k.looks, &looks, k.at), Change::Same | Change::Transparency)); + let alone_at = alone_at(&looks, capture_at.unwrap_or(k.at), pixels); + Plan { start: k.at, restored: Some(k.checkpoint), capture_at, recombine, alone_at, frame, looks } + } else { + let alone_at = alone_at(&looks, changed, pixels); + Plan { start: 0, restored: None, capture_at: Some(changed), recombine: None, alone_at, frame, looks } + } +} + +/// Keeps the picture a frame drawn by `plan` ends with: `captured` when it took one, else the one +/// it started from, with the layer over it alone: `alone` when the frame drew it so, else the one +/// it was composited from. Called only for a frame drawn to the end. +pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Option<(usize, Alone)>) { + let Plan { start, restored, recombine, frame, looks, .. } = plan; + let Some((at, checkpoint)) = captured.or(restored.map(|c| (start, c))) else { return }; + let alone = match alone { + Some((a, alone)) if a == at => Some(alone), + _ => recombine.filter(|_| at == start), + }; + with_pictures(|kept| { + kept.retain(|k| !k.frame.same(&frame)); + if kept.len() >= KEPT { + kept.remove(0); + } + kept.push(Kept { frame, looks, at, checkpoint, alone }); + // Within the budget: the older views' layers alone go first, then the older views. + while kept.iter().map(Kept::pixels).sum::() > MAX_PIXELS { + if let Some(k) = kept.iter_mut().find(|k| k.alone.is_some()) { + k.alone = None; + } else if kept.len() > 1 { + kept.remove(0); + } else { + break; + } + } + }); +} + +#[cfg(test)] +mod tests { + use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value}; + use rustgis_map::{Basemap, Camera, Map, Renderer, Rgba}; + + use super::*; + use crate::render; + + /// A map of a grid of labelled squares under a layer of points, and a view of it. + fn map() -> (Map, View, u32, u32) { + let mut squares = Dataset::new("squares", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + for i in 0..40 { + let (x, y) = (f64::from(i % 8) * 0.01, f64::from(i / 8) * 0.01); + let ring = vec![ + Coord::new(x, y), + Coord::new(x + 0.008, y), + Coord::new(x + 0.008, y + 0.008), + Coord::new(x, y + 0.008), + Coord::new(x, y), + ]; + let pos = rustgis_geom::lonlat_to_merc; + squares.push(Some(Geometry::Polygon(vec![vec![ring.into_iter().map(pos).collect()]])), vec![Value::Text(format!("S{i}"))]); + } + let mut points = Dataset::new("points", GeometryType::Point, Vec::new()); + for i in 0..30 { + let c = rustgis_geom::lonlat_to_merc(Coord::new(f64::from(i % 6) * 0.013, f64::from(i / 6) * 0.009)); + points.push(Some(Geometry::Point(c)), Vec::new()); + } + let mut map = Map::new("Map"); + map.basemap = Basemap::Blank; + map.graticule = false; + let below = map.add_dataset(squares); + let above = map.add_dataset(points); + if let Some(l) = map.layer_mut(below) { + l.labels.enabled = true; + l.labels.default.field = "name".into(); + } + let camera = Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(0.04, 0.025)), res: 12.0, bearing: 0.0, pitch: 0.0 }; + (map, View { width: 200.0, height: 160.0, pixels_per_point: 1.0, camera, sky: false }, below, above) + } + + /// Draws `map` twice: as it comes after the frames before it, and again from nothing. They + /// must be the same frame; gives where the first started drawing its layers. + fn draw(map: &mut Map, view: &View) -> Option { + let kept = render(map, view).expect("drawn"); + let (started, recombined) = (STARTED.get(), RECOMBINED.get()); + let pictures = PICTURES.take(); + let fresh = render(map, view).expect("drawn"); + PICTURES.set(pictures); + RECOMBINED.set(recombined); + assert!(kept.pixmap.data() == fresh.pixmap.data(), "a frame from a kept picture differs from one drawn whole"); + let texts = |r: &crate::Rendered| r.labels.iter().map(|l| (l.text.clone(), l.x.to_bits(), l.y.to_bits())).collect::>(); + assert_eq!(texts(&kept), texts(&fresh), "its labels differ"); + started + } + + #[test] + fn a_frame_draws_from_its_first_changed_layer() { + let (mut map, view, below, above) = map(); + assert_eq!(draw(&mut map, &view), Some(0), "the first frame draws everything"); + // Restyling the layer on top draws only it, the labels of the one below still placed. + let restyle = |map: &mut Map, id: u32, rgb: (u8, u8, u8)| { + if let Some(l) = map.layer_mut(id) { + l.renderer = Renderer::Single(rustgis_map::Symbol { fill: Rgba::rgb(rgb.0, rgb.1, rgb.2), ..l.symbol(0) }); + } + }; + // The first change after a new view starts from the picture under every layer, and keeps + // one under the changed layer for the next. + restyle(&mut map, above, (200, 30, 30)); + assert_eq!(draw(&mut map, &view), Some(0)); + restyle(&mut map, above, (30, 200, 30)); + assert_eq!(draw(&mut map, &view), Some(1), "each step of a drag draws from the picture under the layer"); + restyle(&mut map, above, (30, 30, 200)); + assert_eq!(draw(&mut map, &view), Some(1)); + // Nothing changed: still from the kept picture. + assert_eq!(draw(&mut map, &view), Some(1)); + // The layer below changed: everything again. + restyle(&mut map, below, (10, 10, 120)); + assert_eq!(draw(&mut map, &view), Some(0)); + if let Some(l) = map.layer_mut(below) { + l.dataset.features.truncate(20); + } + assert_eq!(draw(&mut map, &view), Some(0), "an edit to the rows draws the layer again"); + // Moving the view draws everything. + let mut moved = view; + moved.camera.center.x += 50.0; + assert_eq!(draw(&mut map, &moved), Some(0)); + } + + #[test] + fn a_see_through_layer_is_composited_again_at_its_new_transparency() { + let (mut map, view, _, above) = map(); + let set = |map: &mut Map, t: f32| map.layer_mut(above).map(|l| l.transparency = t); + set(&mut map, 20.0); + assert_eq!(draw(&mut map, &view), Some(0)); + // The first change keeps the frame under the layer, and the layer alone. + set(&mut map, 30.0); + assert_eq!(draw(&mut map, &view), Some(0)); + assert!(!RECOMBINED.get()); + // Each further step of the drag composites that picture: the same frame as one drawn whole. + for t in [40.0, 75.0, 5.0] { + set(&mut map, t); + assert_eq!(draw(&mut map, &view), Some(1)); + assert!(RECOMBINED.get(), "{t}"); + } + // Nothing changed: composited again. + assert_eq!(draw(&mut map, &view), Some(1)); + assert!(RECOMBINED.get()); + // Opaque, it is drawn straight onto the map, which composites nothing. + set(&mut map, 0.0); + draw(&mut map, &view); + set(&mut map, 50.0); + draw(&mut map, &view); + // A colour drawn differently: the layer is drawn again, and kept alone again. + if let Some(l) = map.layer_mut(above) { + l.renderer = Renderer::Single(rustgis_map::Symbol { fill: Rgba::rgb(10, 200, 90), ..l.symbol(0) }); + } + assert_eq!(draw(&mut map, &view), Some(1)); + assert!(!RECOMBINED.get()); + set(&mut map, 60.0); + assert_eq!(draw(&mut map, &view), Some(1)); + assert!(RECOMBINED.get()); + // A selection is drawn over the composite: the layer isn't kept alone while it shows one. + if let Some(l) = map.layer_mut(above) { + l.selection = vec![0, 3]; + } + draw(&mut map, &view); + set(&mut map, 70.0); + draw(&mut map, &view); + assert!(!RECOMBINED.get(), "a layer showing a selection is drawn"); + } + + #[test] + fn a_layer_with_no_look_draws_in_every_frame() { + let (mut map, view, below, _) = map(); + if let Some(l) = map.layer_mut(below) { + l.source = Some(Default::default()); + } + draw(&mut map, &view); + assert_eq!(draw(&mut map, &view), Some(0)); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index aba622fc6f..54861b0fb2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -41,6 +41,7 @@ pub mod svg; pub mod terrain; mod text; pub use text::CALLOUT_WIDTH; +mod frame_cache; pub mod tile_mesh; mod tiles; pub mod vector; @@ -4145,6 +4146,18 @@ fn holds_picture(cmds: &[gpu_scene::DrawCmd]) -> bool { cmds.iter().any(|c| matches!(c, gpu_scene::DrawCmd::Image { .. })) } +/// Whether a frame of `map` for `view` can start from a kept picture and keep its own +/// ([`frame_cache`]): flat and north-up, with no layer drawing from another (a mask, the swipe, +/// labels turned square to another layer's lines, terrain water). +fn keeps_pictures(map: &Map, view: &View) -> bool { + view.camera.bearing == 0.0 + && view.camera.pitch == 0.0 + && !map.projection.is_globe() + && map.swipe.is_none() + && map.view.terrain.as_ref().is_none_or(|t| t.water.is_none()) + && map.layers.iter().all(|l| l.mask.is_none() && l.labels.in_order().all(|c| c.square_to.is_none())) +} + /// Draws one north-up frame. `labels_to` says where its labels go: a turned or tilted view the /// frame stands in for places them itself (and draws their icons). `full_res_rasters` marks an /// export, which draws everything as it will stay: rasters at full resolution, and labels in @@ -4228,6 +4241,33 @@ fn render_frame( Some(g) => g.may_see(e), None => e.intersects(&mesh_cull), }; + // Bottom first; a higher depth priority draws later (on top) whatever the order. + let mut order: Vec = (0..map.layers.len()).rev().collect(); + order.sort_by_key(|i| map.layers.get(*i).map_or(0, |l| l.priority)); + // A screen frame starts from the picture kept of the last one, under its first changed layer + // (see `frame_cache`), and keeps its own. + let mut cached = (!pm.is_recording() && !gpu && !full_res_rasters && matches!(labels_to, Labels::Own) && keeps_pictures(map, view)) + .then(|| { + let frame = frame_cache::Frame { + map: rustgis_map::look::MapLook::of(map), + view: *view, + style_env: style_env.clone(), + label_env: label_env.clone(), + tiles: rustgis_tiles::cache::generation(), + sources: rustgis_map::source::generation(), + worldview: (sample_data::view(), world_of(sample_data::view()).len()), + fonts: families::available().is_some(), + }; + let looks = order.iter().filter_map(|i| map.layers.get(*i)).map(|l| (l.id, rustgis_map::look::LayerLook::of(l))).collect(); + frame_cache::plan(frame, looks, u64::from(w) * u64::from(h)) + }); + let start = cached.as_ref().map_or(0, |p| p.start); + let mut captured: Option<(usize, frame_cache::Checkpoint)> = None; + // The layer kept alone (`frame_cache::Alone`): its picture once composited, and the rest once + // it is done. + let alone_at = cached.as_ref().and_then(|p| p.alone_at); + let mut drawn_alone: Option<(usize, Pixmap)> = None; + let mut captured_alone: Option<(usize, frame_cache::Alone)> = None; // Basemap. let (water, land, outline, grat) = map.palette(); @@ -4247,7 +4287,8 @@ fn render_frame( let pictureless = backend.is_gpu() && matches!(labels_to, Labels::Turned(_) | Labels::Tilted(..)); // Set when such a frame stops that way. let mut declined = false; - if map.draws_world_outline() { + // A frame started from a kept picture has its basemap and the tile layers under its layers. + if start == 0 && map.draws_world_outline() { let fill = paint(land, 1.0); let stroke = (outline.a() > 0).then(|| (paint(outline, 1.0), 0.6)); // The worldview read once: the outline and its level must be of the same one, though @@ -4314,7 +4355,7 @@ fn render_frame( } } } - if map.graticule && grat.a() > 0 { + if start == 0 && map.graticule && grat.a() > 0 { let p = paint(grat, 1.0); // A measured or UTM graticule's lines (#1042), else latitudes and longitudes. let grid = mapgrid::lines(map, view); @@ -4432,7 +4473,9 @@ fn render_frame( } }}; } - draw_tiles!(None); + if start == 0 { + draw_tiles!(None); + } // Layers, bottom first. let mut label_candidates: Vec = Vec::new(); @@ -4449,15 +4492,18 @@ fn render_frame( let distance = viewing_distance(map.ground_res_at(&view.camera), view.height); // Graphics text: always drawn, and other labels keep clear of it. let mut fixed_labels: Vec = Vec::new(); + if let Some(c) = cached.as_ref().and_then(|p| p.restored.as_ref()) { + pm = Canvas::from_pixmap(c.pixels.clone()); + label_candidates.clone_from(&c.candidates); + fixed_labels.clone_from(&c.fixed); + tile_out = c.tiles.clone(); + } let tokens = rustgis_map::graphics::TokenValues::of(map, scale); let n_layers = map.layers.len(); // Masks: layers shown only inside another layer's polygons, or left of the swipe divider. let masks = layer_masks(map, &ctx, w, h, &flat, &key, scale, failed_source)?; // The lines point labels are turned square to (#2263), on the screen. let square_lines = square_lines(map, &ctx, &flat); - // Bottom first; a higher depth priority draws later (on top) whatever the order. - let mut order: Vec = (0..n_layers).rev().collect(); - order.sort_by_key(|i| map.layers.get(*i).map_or(0, |l| l.priority)); let clip = map.view.clip_distance.map(|d| (view.camera.center_lonlat(), d)); // Each layer group's visibility, scale range and transparency apply to its layers, its // subgroups' too (#413, #836). @@ -4485,21 +4531,40 @@ fn render_frame( .and_then(|w| Some((map.layer_by_name(&w.layer)?.id, w.shore))); // The layer drawn last, whose tile layers go over it before the next. let mut below: Option = None; - for li in order { + for (at, li) in order.into_iter().enumerate() { // Each layer drawn is a layer of the recording (#1815); what comes between them isn't. pm.layer(None); // A frame no longer wanted stops between layers (see `cancel`). if cancel::requested() { break; } + if let Some((a, pixels)) = drawn_alone.take() { + let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); + captured_alone = Some((a, frame_cache::Alone { pixels, candidates, fixed, tiles })); + } // What is drawn so far already leaves a picture, waiting or in the scene (see // `pictureless`). if pictureless && (cpu_dirty || holds_picture(&cmds)) { return None; } + // Already in the picture the frame started from, with the tile layers over them. + if at < start { + continue; + } if let Some(id) = below.take() { draw_tiles!(Some(id)); } + if cached.as_ref().is_some_and(|p| p.capture_at == Some(at)) { + captured = Some(( + at, + frame_cache::Checkpoint { + pixels: pm.pixels().clone(), + candidates: label_candidates.clone(), + fixed: fixed_labels.clone(), + tiles: tile_out.clone(), + }, + )); + } below = map.layers.get(li).map(|l| l.id); // The water under the shore band, read only when its layer is drawn; shore tiles on // their way leave the frame pending, for the band to be drawn once they land. @@ -4541,6 +4606,18 @@ fn render_frame( mask, ); }; + // The layer the frame started under, kept alone: composited at its opacity now, which is + // what drawing it would end with (see `frame_cache`). + if at == start + && offscreen + && let Some(a) = cached.as_ref().and_then(|p| p.recombine.as_ref()) + { + composite(&mut pm, &a.pixels); + label_candidates.clone_from(&a.candidates); + fixed_labels.clone_from(&a.fixed); + tile_out = a.tiles.clone(); + continue; + } if let Some(rl) = &layer.raster { if let Some(data) = &rl.data { let place = match &globe { @@ -4613,6 +4690,9 @@ fn render_frame( let mut target = Pixmap::new(w, h)?; draw_it(&mut target, 1.0); composite(&mut pm, &target); + if alone_at == Some(at) { + drawn_alone = Some((at, target)); + } } else { draw_it(pm.pixels(), opacity); } @@ -5094,6 +5174,11 @@ fn render_frame( } } else { composite(&mut pm, target.pixmap()); + // Not with a selection or graphics text, drawn over the composite, nor + // with extruded charts, placed after it. + if alone_at == Some(at) && layer.selection.is_empty() && !layer.graphics && layer.extrusion.is_none() { + drawn_alone = Some((at, target.pixmap().clone())); + } } } } @@ -5795,9 +5880,16 @@ fn render_frame( if cancel::requested() || (pictureless && (cpu_dirty || holds_picture(&cmds))) { return None; } + if let Some((a, pixels)) = drawn_alone.take() { + let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); + captured_alone = Some((a, frame_cache::Alone { pixels, candidates, fixed, tiles })); + } if let Some(id) = below { draw_tiles!(Some(id)); } + if let Some(plan) = cached.take() { + frame_cache::keep(plan, captured, captured_alone); + } // A band of a tilted view: the sun's glint on the terrain's water, over the water's own fill. if matches!(labels_to, Labels::Tilted(..) | Labels::Shared) && let Some(g) = TILT_GLINT.with(|g| g.borrow().clone()) diff --git a/crates/render/src/tiles.rs b/crates/render/src/tiles.rs index 7ab591d0e0..1840ca9b22 100644 --- a/crates/render/src/tiles.rs +++ b/crates/render/src/tiles.rs @@ -21,7 +21,7 @@ use crate::{PlacedIcon, PlacedLabel, View}; const MOSAIC: f64 = 2048.0; /// What drawing the tile layers found. -#[derive(Default)] +#[derive(Clone, Default)] pub(crate) struct TileOutput { pub labels: Vec<(PlacedLabel, f64)>, pub attribution: Vec, From 73bcd990c98699cb703cb00b55afc3e8399826a4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 19:45:10 -0600 Subject: [PATCH 2/9] fix(render): a frame from a kept picture carries what the layers below left (#1057) A frame started from a kept picture now restores what the skipped layers left for those above, as a frame drawn whole has it: the marker sprites drawn so far (a marker past the sprite limit is drawn straight) and the shapeburst budget spent. Its layers are compared by their place in the list too, which labels take their priority from, so reordering layers whose drawing order holds draws the frame whole. The worldview is read once a frame, for its key, its outline and the outline in a custom projection, so another thread switching it mid-frame can't keep one view's outline under another's key. The key reads the outline only when it is drawn, and the font index only as it stands, without indexing fonts for a map with no text. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 53 ++++++++++++++++++++++++++------ crates/render/src/lib.rs | 51 ++++++++++++++++++------------ 2 files changed, 76 insertions(+), 28 deletions(-) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 6c4176410e..7bb626cc3d 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -29,7 +29,7 @@ use rustgis_map::look::{Change, LayerLook, MapLook}; use tiny_skia::Pixmap; use crate::tiles::TileOutput; -use crate::{Candidate, PlacedLabel, View}; +use crate::{Candidate, PlacedLabel, Sprites, View}; /// The most pixels the kept pictures hold together, checkpoints and layers alone: two views of /// 3840 × 2160, about 66 MB; four pictures (two views with their layers alone) at 1920 × 1080. @@ -49,9 +49,9 @@ pub(crate) struct Frame { pub tiles: u64, /// [`rustgis_map::source::generation`]: a streamed read finished. pub sources: u64, - /// The world outline's worldview, and how many shapes it had at hand. - pub worldview: (crate::sample_data::View, usize), - /// Whether the installed font families were indexed ([`crate::families::available`]). + /// The world outline's worldview, and how many shapes it had at hand, when it is drawn. + pub worldview: Option<(crate::sample_data::View, usize)>, + /// Whether the installed font families were indexed ([`crate::families::installed_now`]). pub fonts: bool, } @@ -78,6 +78,11 @@ impl Frame { #[derive(Clone)] pub(crate) struct Checkpoint { pub pixels: Pixmap, + /// The marker sprites drawn so far: a layer above draws a marker from one, or straight once + /// there are as many as a frame keeps, as it would in a frame drawn whole. + pub sprites: Sprites, + /// The shapeburst budget spent so far (`gradient_fill::FRAME_BURST_PX`). + pub bursts: f32, pub candidates: Vec, pub fixed: Vec, pub tiles: TileOutput, @@ -88,14 +93,16 @@ pub(crate) struct Checkpoint { #[derive(Clone)] pub(crate) struct Alone { pub pixels: Pixmap, + pub sprites: Sprites, + pub bursts: f32, pub candidates: Vec, pub fixed: Vec, pub tiles: TileOutput, } -/// The looks of a frame's layers, bottom first in drawing order, by id; `None` for one with no -/// look. -pub(crate) type Looks = Vec<(u32, Option)>; +/// The looks of a frame's layers, bottom first in drawing order, by id and place in the map's list +/// (which labels take their priority from); `None` for one with no look. +pub(crate) type Looks = Vec<((u32, usize), Option)>; /// A kept picture and what it was drawn from. struct Kept { @@ -263,6 +270,9 @@ mod tests { /// A map of a grid of labelled squares under a layer of points, and a view of it. fn map() -> (Map, View, u32, u32) { + // The installed fonts indexed now: another test indexing them partway would change every + // frame's key (`Frame::fonts`), and the next frame would draw whole. + crate::families::installed(); let mut squares = Dataset::new("squares", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); for i in 0..40 { let (x, y) = (f64::from(i % 8) * 0.01, f64::from(i / 8) * 0.01); @@ -276,10 +286,10 @@ mod tests { let pos = rustgis_geom::lonlat_to_merc; squares.push(Some(Geometry::Polygon(vec![vec![ring.into_iter().map(pos).collect()]])), vec![Value::Text(format!("S{i}"))]); } - let mut points = Dataset::new("points", GeometryType::Point, Vec::new()); + let mut points = Dataset::new("points", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); for i in 0..30 { let c = rustgis_geom::lonlat_to_merc(Coord::new(f64::from(i % 6) * 0.013, f64::from(i / 6) * 0.009)); - points.push(Some(Geometry::Point(c)), Vec::new()); + points.push(Some(Geometry::Point(c)), vec![Value::Text(format!("P{i}"))]); } let mut map = Map::new("Map"); map.basemap = Basemap::Blank; @@ -385,6 +395,31 @@ mod tests { assert!(!RECOMBINED.get(), "a layer showing a selection is drawn"); } + #[test] + fn a_layer_moved_in_the_list_draws_whole_though_its_drawing_order_holds() { + let (mut map, view, below, above) = map(); + // Labels on both, which take their priority from the layers' places in the list; the + // drawing order is held by the layers' depth priorities whatever the list says. + for (id, priority) in [(below, 0), (above, 1)] { + if let Some(l) = map.layer_mut(id) { + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.priority = priority; + } + } + draw(&mut map, &view); + // Changes to the layer on top keep the picture under it. + for size in [9.0, 11.0] { + if let Some(l) = map.layer_mut(above) { + l.renderer = Renderer::Single(rustgis_map::Symbol { size, ..l.symbol(0) }); + } + draw(&mut map, &view); + } + assert_eq!(draw(&mut map, &view), Some(1)); + map.layers.reverse(); + assert_eq!(draw(&mut map, &view), Some(0), "the labels below place differently"); + } + #[test] fn a_layer_with_no_look_draws_in_every_frame() { let (mut map, view, below, _) = map(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 54861b0fb2..6dcb05a7e5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -762,11 +762,6 @@ fn outline_level_for(map_per_px: f64) -> usize { } } -/// The built-in world outline in longitude/latitude, for the globe. -fn world_lonlat() -> &'static Vec { - world_lonlat_of(sample_data::view()) -} - /// The world outline in view `wv`, in longitude/latitude. fn world_lonlat_of(wv: sample_data::View) -> &'static Vec { static W: [OnceLock>; sample_data::VIEW_COUNT] = [const { OnceLock::new() }; sample_data::VIEW_COUNT]; @@ -786,15 +781,15 @@ thread_local! { } /// The built-in world outline in a custom projection's coordinates (kept per projection). -fn world_in(flat: &rustgis_map::projection::Flat, key: &str) -> std::rc::Rc> { +fn world_in(wv: sample_data::View, flat: &rustgis_map::projection::Flat, key: &str) -> std::rc::Rc> { WORLD_IN.with(|cell| { - let lonlat = world_lonlat(); + let lonlat = world_lonlat_of(wv); // An outline not at hand yet is drawn empty, not kept. if lonlat.is_empty() { return std::rc::Rc::new(Vec::new()); } cell.borrow_mut() - .entry(format!("{}:{key}", sample_data::view().index())) + .entry(format!("{}:{key}", wv.index())) .or_insert_with(|| std::rc::Rc::new(lonlat.iter().map(|g| flat.project(g)).collect())) .clone() }) @@ -883,7 +878,7 @@ struct Ctx<'a> { /// Set when drawing the globe; coordinates are then longitude/latitude, not Web Mercator. globe: Option, /// Point marker sprites drawn so far, by symbol and quarter-pixel offset. - sprites: std::cell::RefCell>>>, + sprites: std::cell::RefCell, /// The pixels the frame's shapeburst fills have worked on (`gradient_fill::FRAME_BURST_PX`), /// shared by a layer's scaled context (a reference scale's) with the frame's. bursts: std::rc::Rc>, @@ -892,6 +887,9 @@ struct Ctx<'a> { /// A marker sprite's symbol and quarter-pixel offset. type SpriteKey = (Rgba, Rgba, u32, u32, Marker, u8, u8); +/// The marker sprites a frame has drawn ([`Ctx::sprites`]). +type Sprites = std::collections::HashMap>>; + impl Ctx<'_> { /// Logical screen position of a coordinate, `None` when it is behind the globe. fn screen(&self, c: Coord) -> Option<(f64, f64)> { @@ -4244,6 +4242,9 @@ fn render_frame( // Bottom first; a higher depth priority draws later (on top) whatever the order. let mut order: Vec = (0..map.layers.len()).rev().collect(); order.sort_by_key(|i| map.layers.get(*i).map_or(0, |l| l.priority)); + // The worldview read once: the frame's key, the outline and its level must be of the same + // one, though another thread may switch it mid-frame. + let worldview = sample_data::view(); // A screen frame starts from the picture kept of the last one, under its first changed layer // (see `frame_cache`), and keeps its own. let mut cached = (!pm.is_recording() && !gpu && !full_res_rasters && matches!(labels_to, Labels::Own) && keeps_pictures(map, view)) @@ -4255,10 +4256,16 @@ fn render_frame( label_env: label_env.clone(), tiles: rustgis_tiles::cache::generation(), sources: rustgis_map::source::generation(), - worldview: (sample_data::view(), world_of(sample_data::view()).len()), - fonts: families::available().is_some(), + // Only when drawn: asking for an outline not at hand says so in the log. + worldview: map.draws_world_outline().then(|| (worldview, world_of(worldview).len())), + // Whether they were indexed so far, without indexing them for a map with no text. + fonts: families::installed_now().is_some(), }; - let looks = order.iter().filter_map(|i| map.layers.get(*i)).map(|l| (l.id, rustgis_map::look::LayerLook::of(l))).collect(); + // By id and place in the list, which labels take their priority from. + let looks = order + .iter() + .filter_map(|i| Some(((map.layers.get(*i)?.id, *i), rustgis_map::look::LayerLook::of(map.layers.get(*i)?)))) + .collect(); frame_cache::plan(frame, looks, u64::from(w) * u64::from(h)) }); let start = cached.as_ref().map_or(0, |p| p.start); @@ -4291,12 +4298,9 @@ fn render_frame( if start == 0 && map.draws_world_outline() { let fill = paint(land, 1.0); let stroke = (outline.a() > 0).then(|| (paint(outline, 1.0), 0.6)); - // The worldview read once: the outline and its level must be of the same one, though - // another thread may switch it mid-frame. - let worldview = sample_data::view(); - let custom_world = custom.then(|| world_in(&flat, &key)); + let custom_world = custom.then(|| world_in(worldview, &flat, &key)); let outlines: &Vec = match (&globe, &custom_world) { - (Some(_), _) => world_lonlat(), + (Some(_), _) => world_lonlat_of(worldview), (None, Some(w)) => w, (None, None) => world_of(worldview), }; @@ -4494,6 +4498,9 @@ fn render_frame( let mut fixed_labels: Vec = Vec::new(); if let Some(c) = cached.as_ref().and_then(|p| p.restored.as_ref()) { pm = Canvas::from_pixmap(c.pixels.clone()); + // What the layers below left for those above: the sprites drawn, the shapeburst budget. + ctx.sprites.borrow_mut().clone_from(&c.sprites); + ctx.bursts.set(c.bursts); label_candidates.clone_from(&c.candidates); fixed_labels.clone_from(&c.fixed); tile_out = c.tiles.clone(); @@ -4540,7 +4547,8 @@ fn render_frame( } if let Some((a, pixels)) = drawn_alone.take() { let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); - captured_alone = Some((a, frame_cache::Alone { pixels, candidates, fixed, tiles })); + let (sprites, bursts) = (ctx.sprites.borrow().clone(), ctx.bursts.get()); + captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, fixed, tiles })); } // What is drawn so far already leaves a picture, waiting or in the scene (see // `pictureless`). @@ -4559,6 +4567,8 @@ fn render_frame( at, frame_cache::Checkpoint { pixels: pm.pixels().clone(), + sprites: ctx.sprites.borrow().clone(), + bursts: ctx.bursts.get(), candidates: label_candidates.clone(), fixed: fixed_labels.clone(), tiles: tile_out.clone(), @@ -4613,6 +4623,8 @@ fn render_frame( && let Some(a) = cached.as_ref().and_then(|p| p.recombine.as_ref()) { composite(&mut pm, &a.pixels); + ctx.sprites.borrow_mut().clone_from(&a.sprites); + ctx.bursts.set(a.bursts); label_candidates.clone_from(&a.candidates); fixed_labels.clone_from(&a.fixed); tile_out = a.tiles.clone(); @@ -5882,7 +5894,8 @@ fn render_frame( } if let Some((a, pixels)) = drawn_alone.take() { let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); - captured_alone = Some((a, frame_cache::Alone { pixels, candidates, fixed, tiles })); + let (sprites, bursts) = (ctx.sprites.borrow().clone(), ctx.bursts.get()); + captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, fixed, tiles })); } if let Some(id) = below { draw_tiles!(Some(id)); From bd23e91ecb7bdd475c952ae5966e6ceb8fc57f2f Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 20:23:42 -0600 Subject: [PATCH 3/9] fix(render): a layer's look copies none of what it leaves out; the kept pictures' budget counts their sprites (#1057) A layer's look is now built field by field rather than from a whole copy pared down, so a frame no longer copies a layer's edit archive (whole features for every edit) only to drop it. The budget for kept pictures counts their marker sprites too, each once, and lets go of the older views' layers alone, then the older views, before the newest view's layer alone. A kept picture is keyed by the downloaded-font generation, so text drawn with a font that arrived since is drawn again, and by the number of layers, which label priorities count: a layer added on top by its depth priority, leaving the others in place, draws the frame whole. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/look.rs | 158 +++++++++++++++++++++++++++---- crates/render/src/frame_cache.rs | 43 ++++++++- crates/render/src/lib.rs | 2 + 3 files changed, 183 insertions(+), 20 deletions(-) diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index e2ee7e4a32..1746c0d1e6 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -37,6 +37,147 @@ pub struct LayerLook { raster: Option, } +/// `layer` without its rows, raster, caches and what else a look leaves out (see the module), +/// copied field by field: a whole copy taken first and pared down would copy, in every frame, what +/// grows with the data, such as an edit archive's whole features for every edit. +fn bare(layer: &Layer) -> Layer { + let Layer { + id, + name, + visible, + dataset, + renderer, + labels, + transparency, + min_scale, + max_scale, + definition_query, + time, + selection, + expanded, + selectable, + graphics, + blend, + mask, + display_filters, + aggregation, + extrusion, + line_strokes, + fill_layers, + no_fill, + hidden_fills, + stroke_levels, + marker_rotation, + diagram, + symbol_by, + size_by, + reference_scale, + priority, + design, + // Compared by its own look. + raster: _, + source, + // Saving back to a database or GeoPackage keeps per-row versions, which aren't drawn. + postgis: _, + gpkg: _, + synced: _, + connection, + anonymous, + instance_id, + replacement_rev, + // Caches, emptied below. + projected, + display, + display_rejected: _, + display_levels, + projected_extents, + projected_vertices, + thinned, + projected_rev, + projected_for, + projected_crs, + lonlat, + view_memory: _, + geometry_kinds: _, + geometry_rev, + } = layer; + let crate::design::Design { domains, subtypes, rules, contingent, archive, templates } = design; + let mut kept = Layer { + id: *id, + name: name.clone(), + visible: *visible, + // Its rows are shared, so the copy costs a pointer; dropped below. + dataset: dataset.clone(), + renderer: renderer.clone(), + labels: labels.clone(), + transparency: *transparency, + min_scale: *min_scale, + max_scale: *max_scale, + definition_query: definition_query.clone(), + // A time binding keeps the rows its dates were read from: only what it draws by. + time: time.as_ref().map(|t| { + let mut bare = crate::time::TimeBinding::new(t.field.clone()); + bare.window = t.window; + bare + }), + selection: selection.clone(), + expanded: *expanded, + selectable: *selectable, + graphics: *graphics, + blend: *blend, + mask: mask.clone(), + display_filters: display_filters.clone(), + aggregation: *aggregation, + extrusion: extrusion.clone(), + line_strokes: line_strokes.clone(), + fill_layers: fill_layers.clone(), + no_fill: *no_fill, + hidden_fills: hidden_fills.clone(), + stroke_levels: *stroke_levels, + marker_rotation: marker_rotation.clone(), + diagram: diagram.clone(), + symbol_by: symbol_by.clone(), + size_by: size_by.clone(), + reference_scale: *reference_scale, + priority: *priority, + design: crate::design::Design { + domains: domains.clone(), + subtypes: subtypes.clone(), + rules: rules.clone(), + contingent: contingent.clone(), + // Whether edits are archived, not the whole features from before and after each. + archive: archive.as_ref().map(|_| Vec::new()), + templates: templates.clone(), + }, + raster: None, + source: source.clone(), + postgis: None, + gpkg: None, + synced: None, + connection: connection.clone(), + anonymous: *anonymous, + instance_id: *instance_id, + replacement_rev: *replacement_rev, + projected: projected.clone(), + display: display.clone(), + display_rejected: Vec::new(), + display_levels: display_levels.clone(), + projected_extents: projected_extents.clone(), + projected_vertices: *projected_vertices, + thinned: thinned.clone(), + projected_rev: *projected_rev, + projected_for: projected_for.clone(), + projected_crs: *projected_crs, + lonlat: lonlat.clone(), + view_memory: Default::default(), + geometry_kinds: Default::default(), + geometry_rev: *geometry_rev, + }; + kept.dataset.features = Default::default(); + kept.clear_cache(); + kept +} + impl LayerLook { /// The look of `layer`; `None` for one whose drawing reads more than the layer holds, which no /// look can vouch for: a source read in place (its file is read again for each frame) or a @@ -51,22 +192,7 @@ impl LayerLook { None => None, }; let rows = layer.dataset.features.allocation_key(); - // Saving back to a database or GeoPackage keeps per-row versions, which aren't drawn. - let mut kept = Layer { raster: None, postgis: None, gpkg: None, synced: None, ..layer.clone() }; - kept.dataset.features = Default::default(); - kept.clear_cache(); - // What these share with the layer could hold its rows: a time binding keeps the rows its - // dates were read from. - kept.time = layer.time.as_ref().map(|t| { - let mut bare = crate::time::TimeBinding::new(t.field.clone()); - bare.window = t.window; - bare - }); - kept.view_memory = Default::default(); - // Edit archiving keeps whole features from before and after each edit, which aren't drawn. - kept.design.archive = layer.design.archive.as_ref().map(|_| Vec::new()); - kept.geometry_kinds = Default::default(); - Some(LayerLook { layer: kept, rows, raster }) + Some(LayerLook { layer: bare(layer), rows, raster }) } /// How the layer `now` was taken of differs from the one this look was taken of. diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 7bb626cc3d..d074eff9fc 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -53,6 +53,10 @@ pub(crate) struct Frame { pub worldview: Option<(crate::sample_data::View, usize)>, /// Whether the installed font families were indexed ([`crate::families::installed_now`]). pub fonts: bool, + /// [`crate::fonts::font_generation`]: a downloaded font now draws some text. + pub font_generation: u32, + /// How many layers the map has, which labels take their priority from. + pub layers: usize, } impl Frame { @@ -70,6 +74,8 @@ impl Frame { && self.sources == other.sources && self.worldview == other.worldview && self.fonts == other.fonts + && self.font_generation == other.font_generation + && self.layers == other.layers && self.map.same(&other.map) } } @@ -116,9 +122,19 @@ struct Kept { } impl Kept { + /// The pixels it holds: its pictures and their marker sprites, each sprite counted once + /// though the checkpoint and the layer alone share it. fn pixels(&self) -> u64 { let size = |p: &Pixmap| u64::from(p.width()) * u64::from(p.height()); - size(&self.checkpoint.pixels) + self.alone.as_ref().map_or(0, |a| size(&a.pixels)) + let mut seen = std::collections::HashSet::new(); + let alone = self.alone.as_ref(); + let sprites = std::iter::once(&self.checkpoint.sprites) + .chain(alone.map(|a| &a.sprites)) + .flat_map(|s| s.values().flatten()) + .filter(|p| seen.insert(std::sync::Arc::as_ptr(p))) + .map(|p| size(p)) + .sum::(); + size(&self.checkpoint.pixels) + alone.map_or(0, |a| size(&a.pixels)) + sprites } } @@ -247,14 +263,19 @@ pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Opt kept.remove(0); } kept.push(Kept { frame, looks, at, checkpoint, alone }); - // Within the budget: the older views' layers alone go first, then the older views. + // Within the budget: the older views' layers alone go first, then the older views, then + // this view's layer alone. while kept.iter().map(Kept::pixels).sum::() > MAX_PIXELS { - if let Some(k) = kept.iter_mut().find(|k| k.alone.is_some()) { + let older = kept.len().saturating_sub(1); + if let Some(k) = kept.iter_mut().take(older).find(|k| k.alone.is_some()) { k.alone = None; } else if kept.len() > 1 { kept.remove(0); + } else if let Some(k) = kept.first_mut().filter(|k| k.alone.is_some()) { + k.alone = None; } else { - break; + // A view whose picture and sprites alone are past the budget keeps nothing. + kept.clear(); } } }); @@ -418,6 +439,20 @@ mod tests { assert_eq!(draw(&mut map, &view), Some(1)); map.layers.reverse(); assert_eq!(draw(&mut map, &view), Some(0), "the labels below place differently"); + // A layer added to the end of the list, drawn on top by its depth priority, leaves the + // others at their places, but the label priorities of all of them count the layers. + for size in [9.0, 11.0] { + if let Some(l) = map.layer_mut(above) { + l.renderer = Renderer::Single(rustgis_map::Symbol { size, ..l.symbol(0) }); + } + draw(&mut map, &view); + } + assert_eq!(draw(&mut map, &view), Some(1)); + let Some(mut added) = map.layer(above).cloned() else { panic!("the layer above") }; + added.id = 99; + added.priority = 2; + map.layers.push(added); + assert_eq!(draw(&mut map, &view), Some(0), "the labels below rank differently"); } #[test] diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6dcb05a7e5..5a92c6f47f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4260,6 +4260,8 @@ fn render_frame( worldview: map.draws_world_outline().then(|| (worldview, world_of(worldview).len())), // Whether they were indexed so far, without indexing them for a map with no text. fonts: families::installed_now().is_some(), + font_generation: fonts::font_generation(), + layers: map.layers.len(), }; // By id and place in the list, which labels take their priority from. let looks = order From a2f34e1fe17cc0af7d62c56c641deeedec664096 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 21:12:14 -0600 Subject: [PATCH 4/9] fix(render): a kept picture under graphics text is keyed by the minute it shows (#1057) Graphics text expands {date} and {time} from the clock, to the minute. A frame of a map with graphics layers now keys its kept pictures by that minute, so a picture whose graphics text showed an earlier time isn't restored under a changed layer above it. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 4 ++++ crates/render/src/lib.rs | 1 + 2 files changed, 5 insertions(+) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index d074eff9fc..96b122742b 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -57,6 +57,9 @@ pub(crate) struct Frame { pub font_generation: u32, /// How many layers the map has, which labels take their priority from. pub layers: usize, + /// The minute graphics text shows for `{date}` and `{time}` + /// ([`rustgis_map::graphics::TokenValues`]), on a map with graphics. + pub clock: Option, } impl Frame { @@ -76,6 +79,7 @@ impl Frame { && self.fonts == other.fonts && self.font_generation == other.font_generation && self.layers == other.layers + && self.clock == other.clock && self.map.same(&other.map) } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d600e531e5..f0cdcdc584 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4262,6 +4262,7 @@ fn render_frame( fonts: families::installed_now().is_some(), font_generation: fonts::font_generation(), layers: map.layers.len(), + clock: map.layers.iter().any(|l| l.graphics).then(|| rustgis_map::graphics::TokenValues::of(map, scale).now / 60), }; // By id and place in the list, which labels take their priority from. let looks = order From 898c1c6bd09744a479b8d870c8e04c3e654e3e12 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 21:53:23 -0600 Subject: [PATCH 5/9] perf(render): a frame past the kept pictures' budget takes no looks (#1057) A frame too large to keep pictures within the budget (a 2560 x 1440 window at 2x, say) now skips building the looks of its layers and the map, which it would only throw away. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 6 ++++ crates/render/src/lib.rs | 53 +++++++++++++++++--------------- 2 files changed, 35 insertions(+), 24 deletions(-) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 96b122742b..a21d4253f3 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -201,6 +201,12 @@ fn first_change(then: &Looks, now: &Looks) -> usize { .unwrap_or(then.len().min(now.len())) } +/// Whether a frame of `w` × `h` pixels can keep pictures: [`plan`] refuses one past the budget, +/// so a frame checks first rather than take the looks of its layers for nothing. +pub(crate) fn fits(w: u32, h: u32) -> bool { + (u64::from(w) * u64::from(h)).saturating_mul(KEPT as u64) <= MAX_PIXELS +} + /// How the layer at place `at` in the drawing order differs between `then` and `now`. fn change_at(then: &Looks, now: &Looks, at: usize) -> Change { match (then.get(at), now.get(at)) { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f0cdcdc584..82fd84edf4 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4247,30 +4247,35 @@ fn render_frame( let worldview = sample_data::view(); // A screen frame starts from the picture kept of the last one, under its first changed layer // (see `frame_cache`), and keeps its own. - let mut cached = (!pm.is_recording() && !gpu && !full_res_rasters && matches!(labels_to, Labels::Own) && keeps_pictures(map, view)) - .then(|| { - let frame = frame_cache::Frame { - map: rustgis_map::look::MapLook::of(map), - view: *view, - style_env: style_env.clone(), - label_env: label_env.clone(), - tiles: rustgis_tiles::cache::generation(), - sources: rustgis_map::source::generation(), - // Only when drawn: asking for an outline not at hand says so in the log. - worldview: map.draws_world_outline().then(|| (worldview, world_of(worldview).len())), - // Whether they were indexed so far, without indexing them for a map with no text. - fonts: families::installed_now().is_some(), - font_generation: fonts::font_generation(), - layers: map.layers.len(), - clock: map.layers.iter().any(|l| l.graphics).then(|| rustgis_map::graphics::TokenValues::of(map, scale).now / 60), - }; - // By id and place in the list, which labels take their priority from. - let looks = order - .iter() - .filter_map(|i| Some(((map.layers.get(*i)?.id, *i), rustgis_map::look::LayerLook::of(map.layers.get(*i)?)))) - .collect(); - frame_cache::plan(frame, looks, u64::from(w) * u64::from(h)) - }); + let mut cached = (!pm.is_recording() + && !gpu + && !full_res_rasters + && matches!(labels_to, Labels::Own) + && frame_cache::fits(w, h) + && keeps_pictures(map, view)) + .then(|| { + let frame = frame_cache::Frame { + map: rustgis_map::look::MapLook::of(map), + view: *view, + style_env: style_env.clone(), + label_env: label_env.clone(), + tiles: rustgis_tiles::cache::generation(), + sources: rustgis_map::source::generation(), + // Only when drawn: asking for an outline not at hand says so in the log. + worldview: map.draws_world_outline().then(|| (worldview, world_of(worldview).len())), + // Whether they were indexed so far, without indexing them for a map with no text. + fonts: families::installed_now().is_some(), + font_generation: fonts::font_generation(), + layers: map.layers.len(), + clock: map.layers.iter().any(|l| l.graphics).then(|| rustgis_map::graphics::TokenValues::of(map, scale).now / 60), + }; + // By id and place in the list, which labels take their priority from. + let looks = order + .iter() + .filter_map(|i| Some(((map.layers.get(*i)?.id, *i), rustgis_map::look::LayerLook::of(map.layers.get(*i)?)))) + .collect(); + frame_cache::plan(frame, looks, u64::from(w) * u64::from(h)) + }); let start = cached.as_ref().map_or(0, |p| p.start); let mut captured: Option<(usize, frame_cache::Checkpoint)> = None; // The layer kept alone (`frame_cache::Alone`): its picture once composited, and the rest once From c53cd52520246c67652e518ef498eb33fcdea1b3 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 21:58:29 -0600 Subject: [PATCH 6/9] fix(render): kept pictures follow the tile layers' places and the layer count graphics text shows (#1057) A kept picture is keyed by where each tile layer is drawn (Map::tile_slots), which follows the layers present: a tile layer whose layer was replaced by another, now drawn under every layer, is no longer lost from a picture restored above that place. Graphics text's {layers}, the layers not of graphics, is keyed with its minute. A frame restored from a picture under its first layer no longer draws the world outline, graticule and tile layers under every layer first, only to replace them. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 12 ++++++++---- crates/render/src/lib.rs | 14 ++++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index a21d4253f3..a0e1c58861 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -57,9 +57,12 @@ pub(crate) struct Frame { pub font_generation: u32, /// How many layers the map has, which labels take their priority from. pub layers: usize, - /// The minute graphics text shows for `{date}` and `{time}` - /// ([`rustgis_map::graphics::TokenValues`]), on a map with graphics. - pub clock: Option, + /// What graphics text shows for `{date}` and `{time}` (the minute) and for `{layers}` (the + /// layers not of graphics), on a map with graphics ([`rustgis_map::graphics::TokenValues`]). + pub tokens: Option<(u64, usize)>, + /// The layer each tile layer is drawn over ([`rustgis_map::Map::tile_slots`]), which follows + /// the layers present as well as the tile layers' settings. + pub tile_slots: Vec>, } impl Frame { @@ -79,7 +82,8 @@ impl Frame { && self.fonts == other.fonts && self.font_generation == other.font_generation && self.layers == other.layers - && self.clock == other.clock + && self.tokens == other.tokens + && self.tile_slots == other.tile_slots && self.map.same(&other.map) } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 82fd84edf4..80be30a99a 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4267,7 +4267,11 @@ fn render_frame( fonts: families::installed_now().is_some(), font_generation: fonts::font_generation(), layers: map.layers.len(), - clock: map.layers.iter().any(|l| l.graphics).then(|| rustgis_map::graphics::TokenValues::of(map, scale).now / 60), + tokens: map.layers.iter().any(|l| l.graphics).then(|| { + let t = rustgis_map::graphics::TokenValues::of(map, scale); + (t.now / 60, t.layers) + }), + tile_slots: map.tile_slots(), }; // By id and place in the list, which labels take their priority from. let looks = order @@ -4277,6 +4281,8 @@ fn render_frame( frame_cache::plan(frame, looks, u64::from(w) * u64::from(h)) }); let start = cached.as_ref().map_or(0, |p| p.start); + // A frame with no kept picture to start from draws what lies under its layers. + let cold = cached.as_ref().is_none_or(|p| p.restored.is_none()); let mut captured: Option<(usize, frame_cache::Checkpoint)> = None; // The layer kept alone (`frame_cache::Alone`): its picture once composited, and the rest once // it is done. @@ -4303,7 +4309,7 @@ fn render_frame( // Set when such a frame stops that way. let mut declined = false; // A frame started from a kept picture has its basemap and the tile layers under its layers. - if start == 0 && map.draws_world_outline() { + if cold && map.draws_world_outline() { let fill = paint(land, 1.0); let stroke = (outline.a() > 0).then(|| (paint(outline, 1.0), 0.6)); let custom_world = custom.then(|| world_in(worldview, &flat, &key)); @@ -4367,7 +4373,7 @@ fn render_frame( } } } - if start == 0 && map.graticule && grat.a() > 0 { + if cold && map.graticule && grat.a() > 0 { let p = paint(grat, 1.0); // A measured or UTM graticule's lines (#1042), else latitudes and longitudes. let grid = mapgrid::lines(map, view); @@ -4485,7 +4491,7 @@ fn render_frame( } }}; } - if start == 0 { + if cold { draw_tiles!(None); } From ed1e8f7ff8dd9cef8fa76581b19dd4211c8180a4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 22:47:06 -0600 Subject: [PATCH 7/9] fix(render): a kept picture is complete, and a 4K view keeps its layer alone beside its sprites (#1057) A frame keeps a picture only while what it has drawn so far is complete: no tiles on their way or failed (to be asked for again), no layer read in place drawn from less than the view needs, and no tile pictures it left for the next frame (rustgis_tiles::lacking, new). A frame restored from a picture never skips work an unfinished frame would have done again. The kept pictures' budget now allows each kept view its marker sprites (at most 1024 sprites of 49 x 49 pixels, about 9.8 MB) beside its pictures, so at 3840 x 2160 the sprites no longer cost the view its layer alone: within about 86 MB in all. A kept picture is keyed by the tile and streamed-read generations only on a map that reads them (tile layers or terrain; a layer read from its source), so a tile arriving for another map's view no longer throws away this one's pictures. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 37 ++++++++++++++++++++++++++------ crates/render/src/lib.rs | 15 ++++++++----- crates/tiles/src/lib.rs | 2 +- crates/tiles/src/picture.rs | 6 ++++++ 4 files changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index a0e1c58861..cee150e44b 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -31,10 +31,17 @@ use tiny_skia::Pixmap; use crate::tiles::TileOutput; use crate::{Candidate, PlacedLabel, Sprites, View}; -/// The most pixels the kept pictures hold together, checkpoints and layers alone: two views of -/// 3840 × 2160, about 66 MB; four pictures (two views with their layers alone) at 1920 × 1080. +/// The most pixels the kept pictures hold together, checkpoints and layers alone, about 66 MB: +/// two views of 3840 × 2160, or one with its layer alone; two views with their layers alone at +/// 1920 × 1080. const MAX_PIXELS: u64 = 2 * 3840 * 2160; +/// The most pixels one frame's marker sprites can hold ([`crate::MAX_SPRITES`] of at most +/// [`crate::MAX_SPRITE_REACH`] around their centre): about 2.5 million, 9.8 MB. Each kept view +/// may hold that beside its pictures, so the sprites never cost a view its layer alone: with them +/// the kept pictures stay within about 86 MB. +const SPRITE_PIXELS: u64 = crate::MAX_SPRITES as u64 * (2 * crate::MAX_SPRITE_REACH as u64 + 1).pow(2); + /// Pictures kept, one per view drawn (a map and its draft, two maps on screen). const KEPT: usize = 2; @@ -45,10 +52,12 @@ pub(crate) struct Frame { pub view: View, pub style_env: Env, pub label_env: Env, - /// [`rustgis_tiles::cache::generation`]: a tile arrived. - pub tiles: u64, - /// [`rustgis_map::source::generation`]: a streamed read finished. - pub sources: u64, + /// [`rustgis_tiles::cache::generation`]: a tile arrived, on a map with tile layers or terrain + /// (a tile for another map's view leaves this one's pictures). + pub tiles: Option, + /// [`rustgis_map::source::generation`]: a streamed read finished, on a map with a layer read + /// from its source. + pub sources: Option, /// The world outline's worldview, and how many shapes it had at hand, when it is drawn. pub worldview: Option<(crate::sample_data::View, usize)>, /// Whether the installed font families were indexed ([`crate::families::installed_now`]). @@ -279,7 +288,7 @@ pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Opt kept.push(Kept { frame, looks, at, checkpoint, alone }); // Within the budget: the older views' layers alone go first, then the older views, then // this view's layer alone. - while kept.iter().map(Kept::pixels).sum::() > MAX_PIXELS { + while kept.iter().map(Kept::pixels).sum::() > MAX_PIXELS + KEPT as u64 * SPRITE_PIXELS { let older = kept.len().saturating_sub(1); if let Some(k) = kept.iter_mut().take(older).find(|k| k.alone.is_some()) { k.alone = None; @@ -469,6 +478,20 @@ mod tests { assert_eq!(draw(&mut map, &view), Some(0), "the labels below rank differently"); } + #[test] + fn a_view_of_3840_by_2160_keeps_its_layer_alone_beside_the_marker_sprites() { + let (mut map, mut view, _, above) = map(); + (view.width, view.height) = (3840.0, 2160.0); + // The layer dragged is of point markers, drawn from sprites. + for t in [20.0, 30.0, 40.0] { + if let Some(l) = map.layer_mut(above) { + l.transparency = t; + } + draw(&mut map, &view); + } + assert!(RECOMBINED.get(), "the layer alone was kept"); + } + #[test] fn a_layer_with_no_look_draws_in_every_frame() { let (mut map, view, below, _) = map(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 80be30a99a..fd72a1ef6c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4259,8 +4259,8 @@ fn render_frame( view: *view, style_env: style_env.clone(), label_env: label_env.clone(), - tiles: rustgis_tiles::cache::generation(), - sources: rustgis_map::source::generation(), + tiles: (!map.tiles.is_empty() || map.view.terrain.is_some()).then(rustgis_tiles::cache::generation), + sources: map.layers.iter().any(|l| l.source.is_some()).then(rustgis_map::source::generation), // Only when drawn: asking for an outline not at hand says so in the log. worldview: map.draws_world_outline().then(|| (worldview, world_of(worldview).len())), // Whether they were indexed so far, without indexing them for a map with no text. @@ -4289,6 +4289,11 @@ fn render_frame( let alone_at = cached.as_ref().and_then(|p| p.alone_at); let mut drawn_alone: Option<(usize, Pixmap)> = None; let mut captured_alone: Option<(usize, frame_cache::Alone)> = None; + // Kept only as drawn in full so far: tiles still to come, to draw, or to ask for again after + // a failure are drawn again rather than restored as they stood. + let complete = |t: &tiles::TileOutput| { + !t.pending && t.errors.is_empty() && t.partial.is_empty() && t.pending_in_place.is_empty() && rustgis_tiles::lacking().is_none() + }; // Basemap. let (water, land, outline, grat) = map.palette(); @@ -4561,7 +4566,7 @@ fn render_frame( if cancel::requested() { break; } - if let Some((a, pixels)) = drawn_alone.take() { + if let Some((a, pixels)) = drawn_alone.take().filter(|_| complete(&tile_out)) { let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); let (sprites, bursts) = (ctx.sprites.borrow().clone(), ctx.bursts.get()); captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, fixed, tiles })); @@ -4578,7 +4583,7 @@ fn render_frame( if let Some(id) = below.take() { draw_tiles!(Some(id)); } - if cached.as_ref().is_some_and(|p| p.capture_at == Some(at)) { + if cached.as_ref().is_some_and(|p| p.capture_at == Some(at)) && complete(&tile_out) { captured = Some(( at, frame_cache::Checkpoint { @@ -5913,7 +5918,7 @@ fn render_frame( if cancel::requested() || (pictureless && (cpu_dirty || holds_picture(&cmds))) { return None; } - if let Some((a, pixels)) = drawn_alone.take() { + if let Some((a, pixels)) = drawn_alone.take().filter(|_| complete(&tile_out)) { let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); let (sprites, bursts) = (ctx.sprites.borrow().clone(), ctx.bursts.get()); captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, fixed, tiles })); diff --git a/crates/tiles/src/lib.rs b/crates/tiles/src/lib.rs index 61e877feea..28954fb61a 100644 --- a/crates/tiles/src/lib.rs +++ b/crates/tiles/src/lib.rs @@ -48,6 +48,6 @@ pub mod vector_export; pub mod warp; pub use draw::{Drawn, Frame, PlacedTiles, Placement, draw, place, place_raster}; -pub use picture::{Pace, Unfinished, pace, paced, unfinished}; +pub use picture::{Pace, Unfinished, lacking, pace, paced, unfinished}; pub use source::{Kind, Spec}; pub use symbols::{Collide, Label, LabelIcon}; diff --git a/crates/tiles/src/picture.rs b/crates/tiles/src/picture.rs index 7e3489cdd5..190ed01a2a 100644 --- a/crates/tiles/src/picture.rs +++ b/crates/tiles/src/picture.rs @@ -171,6 +171,12 @@ pub fn pace() -> Option<(Pace, Instant)> { PACE.with(|p| p.get()).map(|p| (p.pace, p.until)) } +/// What the map being drawn on this thread lacks so far (inside [`paced`]): a picture of it kept +/// partway is unfinished too. +pub fn lacking() -> Option { + PACE.with(|p| p.get()).and_then(|p| p.lacks) +} + /// Notes, for [`paced`], what the map being drawn on this thread still lacks: a renderer drawing /// at its pace calls it when it left something out or stood something in, so the map is drawn /// again (`Next`: the next frame; `Later`: once it stops moving). Outside `paced`, nothing. From 7c3a5c318f07d9c94a16ae90881f2f4a10a6bed2 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 23:34:07 -0600 Subject: [PATCH 8/9] fix(render): a kept picture over tile layers lasts until a failed tile may be asked for again (#1057) A server that refuses a tile without saying when to come back is asked again by the next draw after a minute (rustgis_tiles::cache::RETRY). A picture kept of a map with tile layers or terrain now lasts that long from when it was drawn, so the next frame after it draws the tile layers and asks for the tile again. Pictures of maps with routine missing tiles are still reused in the meantime. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 11 ++++++++++- crates/render/src/lib.rs | 1 + 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index cee150e44b..41b3a839b8 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -106,6 +106,9 @@ pub(crate) struct Checkpoint { pub sprites: Sprites, /// The shapeburst budget spent so far (`gradient_fill::FRAME_BURST_PX`). pub bursts: f32, + /// When it was drawn: one of a map with tile layers is drawn again once a failed tile may be + /// asked for again ([`rustgis_tiles::cache::RETRY`]), as the next frame drawn whole would. + pub taken: web_time::Instant, pub candidates: Vec, pub fixed: Vec, pub tiles: TileOutput, @@ -251,7 +254,13 @@ fn plan_with(frame: Frame, looks: Looks, pixels: u64) -> Plan { if pixels.saturating_mul(KEPT as u64) > MAX_PIXELS { return Plan { start: 0, restored: None, capture_at: None, recombine: None, alone_at: None, frame, looks }; } - let found = with_pictures(|kept| kept.iter().position(|k| k.frame.same(&frame)).map(|i| kept.remove(i))); + // A picture over tile layers lasts until a tile that failed in it may be asked for again: a + // server that gave no time to come back is asked by the next draw after a minute. + let fresh = |k: &Kept| k.frame.tiles.is_none() || k.checkpoint.taken.elapsed() < rustgis_tiles::cache::RETRY; + let found = with_pictures(|kept| { + kept.retain(fresh); + kept.iter().position(|k| k.frame.same(&frame)).map(|i| kept.remove(i)) + }); let Some(k) = found else { // Nothing to start from: keep what lies under the first layer (the basemap, the tile // layers below every layer), or the frame under its first changed layer next time. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index fd72a1ef6c..26f8e861ea 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4590,6 +4590,7 @@ fn render_frame( pixels: pm.pixels().clone(), sprites: ctx.sprites.borrow().clone(), bursts: ctx.bursts.get(), + taken: web_time::Instant::now(), candidates: label_candidates.clone(), fixed: fixed_labels.clone(), tiles: tile_out.clone(), From 87bd93909f7086dd6bcf5c5ccc47d42e9bb7e161 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 00:10:03 -0600 Subject: [PATCH 9/9] fix(render): a picture kept over a restored one is as old as its tiles (#1057) A checkpoint taken by a frame that started from a kept picture holds that picture's tile layers, so it now keeps the time that picture was drawn: a failed tile in it is asked for again when its retry is due, not a minute after the newer checkpoint. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 26f8e861ea..b0044b49f6 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4590,7 +4590,8 @@ fn render_frame( pixels: pm.pixels().clone(), sprites: ctx.sprites.borrow().clone(), bursts: ctx.bursts.get(), - taken: web_time::Instant::now(), + // Over a restored picture, its tiles are as old as that picture. + taken: cached.as_ref().and_then(|p| p.restored.as_ref()).map_or_else(web_time::Instant::now, |c| c.taken), candidates: label_candidates.clone(), fixed: fixed_labels.clone(), tiles: tile_out.clone(),