From 1bcd9b41e14bdf7945026e8a1a6fd52e5db86427 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 19:10:14 -0600 Subject: [PATCH] perf(render): keep a GPU scene's pictures between scenes of the same view (#1057) A GPU scene for the screen now starts from the frame kept of the last scene of the same view under its first changed layer, as a CPU frame does (frame_cache): the checkpoint holds the scene's commands so far, shared with the scene that made them (the pictures drawn on the CPU and the layers' meshes), and the picture it was drawing then. A picture drawn again with the same pixels is that same picture, and the GPU map keeps the texture of a picture it has uploaded by its address while a scene draws it, so the pictures under a restyled layer are neither drawn nor uploaded again. On a map with no blended layer, the first two see-through layers of a scene are pictures of their own, which the GPU places at the layer's opacity (a uniform of the image pipeline). A transparency change alone places the layer kept alone again at its new opacity: nothing is drawn or uploaded. The CPU fallback for scenes of many pictures counts them as before, as though those layers were composited. The kept pictures stay within frame_cache's budget, now counting the pictures and tiles a GPU checkpoint's commands hold, and the meshes they hold within the kept meshes' budget again. vector_layers_bench takes BENCH_RASTER (a raster under the layers), a transparency sequence, and BENCH_ONLY=restyle. --- crates/render/examples/vector_layers_bench.rs | 76 +++-- crates/render/src/frame_cache.rs | 298 +++++++++++++++++- crates/render/src/gpu_scene.rs | 31 +- crates/render/src/layer_meshes.rs | 7 +- crates/render/src/lib.rs | 237 ++++++++++++-- crates/render/src/tiles.rs | 8 +- crates/ui-egui/src/mapgpu.rs | 223 ++++++++----- crates/ui-egui/src/mapgpu.wgsl | 5 +- 8 files changed, 739 insertions(+), 146 deletions(-) diff --git a/crates/render/examples/vector_layers_bench.rs b/crates/render/examples/vector_layers_bench.rs index 435cfd0c03..78a068cfc2 100644 --- a/crates/render/examples/vector_layers_bench.rs +++ b/crates/render/examples/vector_layers_bench.rs @@ -11,9 +11,13 @@ //! quarter of the view a step, so every frame brings new features in; //! - **tilt 10 m:** the same pan at 10 m, tilted 60°; //! - **restyle:** the top layer's fill colour changed in each of 8 frames of one view, over the -//! whole map and at 10 m a point (#1057), then the same with every layer renamed in each frame -//! too, so that none looks as it did: what each frame drew before a frame kept what still -//! stands (the picture under the changed layer on the CPU, each layer's mesh on the GPU). +//! whole map and at 10 m a point (#1057), then its transparency instead, then the fill with +//! every layer renamed in each frame too, so that none looks as it did: what each frame drew +//! before a frame kept what still stands (the picture under the changed layer, and the layer +//! alone while only its transparency changes; on the GPU each layer's mesh too). +//! +//! `BENCH_RASTER=dem.tif` reads a raster into memory and draws it under the layers, as a basemap +//! (the views are still fitted to the layers). //! //! `BENCH_BACKEND=gpu` times the GPU scene instead (`Backend::Gpu`): what the CPU does for a GPU //! frame, tessellating the layers the GPU draws and drawing the rest into pictures, not the @@ -24,7 +28,8 @@ //! //! Made for swisstopo's swiss-map-vector25 (`SMV25_CHLV95LN02.gpkg`, 336,000 features in LV95, //! from data.geo.admin.ch, one map sheet). For a profiler, `BENCH_ONLY=2,zoom` (a pixel scale and a sequence) runs -//! that sequence three times on the whole map and nothing else; `BENCH_THREADS=1` draws on one thread. +//! that sequence three times on the whole map and nothing else, `BENCH_ONLY=restyle` the restyle +//! sequences alone; `BENCH_THREADS=1` draws on one thread. use rustgis_geom::{Coord, lonlat_to_merc}; use rustgis_map::{Basemap, Camera, Map}; use rustgis_render::gpu_scene::DrawCmd; @@ -51,7 +56,7 @@ impl Drawn { let mut d = Drawn::default(); for c in &scene.cmds { match c { - DrawCmd::Image { pixmap } => { + DrawCmd::Image { pixmap, .. } => { d.images += 1; d.image_px += u64::from(pixmap.width()) * u64::from(pixmap.height()); } @@ -110,6 +115,13 @@ fn main() { } } println!("read {} layers in {:.1} s", read.len(), t.elapsed().as_secs_f64()); + let raster = std::env::var_os("BENCH_RASTER").map(|path| { + let path = std::path::PathBuf::from(path); + match rustgis_data::raster::read_path(&path) { + Ok(r) => (r, path.display().to_string()), + Err(e) => fail(format!("{}: {e}", path.display())), + } + }); // The highest-numbered tables (land cover) at the bottom, as a topographic map stacks them. let mut datasets: Vec<_> = read.into_iter().filter(|d| !d.features.is_empty()).collect(); datasets.sort_by(|a, b| b.name.cmp(&a.name)); @@ -124,6 +136,13 @@ fn main() { let (name, rows) = (d.name.clone(), d.features.len()); layers.push((m.add_dataset(d), name, rows, vertices)); } + if let Some((r, path)) = raster { + println!("under them, the raster {path} ({} × {})", r.width, r.height); + m.add_raster("raster", rustgis_map::RasterLayer::from_path(r, path)); + // Added on top; drawn at the bottom. + let r = m.layers.remove(0); + m.layers.push(r); + } let total: (usize, usize) = layers.iter().fold((0, 0), |(r, v), l| (r + l.2, v + l.3)); println!("{} layers, {} features, {} vertices", layers.len(), total.0, total.1); if !(extent.min_x.is_finite() && extent.max_x.is_finite() && extent.min_y.is_finite() && extent.max_y.is_finite()) @@ -171,11 +190,10 @@ fn main() { ("tilt 10 m", tilt), ]; let ids: Vec = layers.iter().map(|l| l.0).collect(); + // One layer alone hides the raster too. let show = |m: &mut Map, only: Option| { - for id in &ids { - if let Some(l) = m.layer_mut(*id) { - l.visible = only.is_none_or(|o| o == *id); - } + for l in &mut m.layers { + l.visible = only.is_none_or(|o| o == l.id); } }; let view = |camera: Camera, ppp: f64| View { width: 1920.0, height: 1080.0, pixels_per_point: ppp, camera, sky: false }; @@ -226,20 +244,24 @@ fn main() { let max = s.last().copied().unwrap_or(0.0); format!("{:>3} frames, median {median:6.0} ms, slowest {max:6.0} ms, total {:7.0} ms", s.len(), s.iter().sum::()) }; - // The top layer's fill changed in each frame; with `all`, every layer renamed too. - let restyle = |m: &mut Map, cam: Camera, ppp: f64, all: bool| -> Vec<(f64, Drawn)> { + // The top layer's fill changed in each frame, or its transparency (`see_through`); with + // `all`, every layer renamed too. + let restyle = |m: &mut Map, cam: Camera, ppp: f64, see_through: bool, all: bool| -> Vec<(f64, Drawn)> { let Some(top) = ids.last().copied() else { return Vec::new() }; (0..8u8) .map(|i| { if let Some(l) = m.layer_mut(top) { - let fill = rustgis_map::Rgba::rgb(40 + i * 20, 120, 200 - i * 20); - l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill, ..l.symbol(0) }); + if see_through { + l.transparency = 20.0 + f32::from(i) * 5.0; + } else { + let fill = rustgis_map::Rgba::rgb(40 + i * 20, 120, 200 - i * 20); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill, ..l.symbol(0) }); + } } + // The raster too, when there is one. if all { - for id in &ids { - if let Some(l) = m.layer_mut(*id) { - l.name = format!("{} {i}", l.name.trim_end_matches(|c: char| c.is_ascii_digit() || c == ' ')); - } + for l in &mut m.layers { + l.name = format!("{} {i}", l.name.trim_end_matches(|c: char| c.is_ascii_digit() || c == ' ')); } } run_drawn(m, &[cam], ppp).remove(0) @@ -247,8 +269,12 @@ fn main() { .collect() }; show(&mut m, None); + // `BENCH_ONLY=restyle` runs the restyle sequences alone. + let restyle_only = std::env::var("BENCH_ONLY").is_ok_and(|o| o == "restyle"); // `BENCH_ONLY` that names no pixel scale and sequence stops the run, not runs everything. - if let Ok(only) = std::env::var("BENCH_ONLY") { + if let Ok(only) = std::env::var("BENCH_ONLY") + && !restyle_only + { let Some((ppp, name, cams)) = only.split_once(',').and_then(|(p, n)| { let cams = &sequences.iter().find(|s| s.0 == n)?.1; Some((p.parse::().ok().filter(|p| p.is_finite() && *p > 0.0)?, n, cams)) @@ -266,7 +292,7 @@ fn main() { // The first frame projects every layer and builds the whole map's level of detail. let first = run(&mut m, &[camera(centre, whole)], 1.0); println!("first frame (projects every layer): {:.0} ms", first.first().copied().unwrap_or(0.0)); - for ppp in [1.0f64, 2.0] { + for ppp in [1.0f64, 2.0].into_iter().filter(|_| !restyle_only) { for (name, cams) in &sequences { show(&mut m, None); let drawn = run_drawn(&mut m, cams, ppp); @@ -293,18 +319,22 @@ fn main() { show(&mut m, None); for ppp in [1.0f64, 2.0] { for res in [whole, 10.0] { - for all in [false, true] { - let drawn = restyle(&mut m, camera(centre, res), ppp, all); + for (see_through, all, what) in + [(false, false, "the top layer restyled"), (true, false, "its transparency"), (false, true, "every layer changed")] + { + let drawn = restyle(&mut m, camera(centre, res), ppp, see_through, all); // The first frame of a view keeps; the next seven take what still stands. let times: Vec = drawn.iter().skip(1).map(|d| d.0).collect(); - let what = if all { "every layer changed" } else { "the top layer restyled" }; println!("{ppp}x restyle at {res:.1} m, {what}: {}{}", summary(×), scenes(&drawn)); + if let Some(l) = ids.last().and_then(|top| m.layer_mut(*top)) { + l.transparency = 0.0; + } } } } // The layers a GPU scene draws on the CPU: each alone, over the whole map and at 3 m, flat; // after the sequences, so it warms no cache they time. - if backend.is_gpu() { + if backend.is_gpu() && !restyle_only { let mut on_cpu = Vec::new(); for (id, name, rows, v) in &layers { show(&mut m, Some(*id)); diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 3795c0c2db..3af62a3a6d 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -18,11 +18,20 @@ //! 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. +//! Only flat, north-up frames for the screen keep pictures: not exports, recordings, 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. +//! +//! A GPU scene keeps its pictures the same way: its checkpoint holds the scene's commands so far +//! ([`GpuPart`]), sharing their data (the pictures drawn on the CPU, the layers' meshes) with the +//! scene that made them, and the CPU picture it was drawing then. The GPU keeps the texture of a +//! picture it has uploaded while the picture lives, so a scene started from a checkpoint uploads +//! none of the pictures under its first changed layer again. On the GPU a see-through layer of +//! normal blend is a picture of its own, which the GPU places at the layer's opacity +//! ([`crate::gpu_scene::DrawCmd::Image`]): the layer alone composited again at a new transparency +//! is that same picture, drawn and uploaded once. //! //! Each layer's label candidates are kept beside the picture too ([`LayerLabels`]): a layer drawn //! again over a restored picture, or in a frame of the same view drawn whole, that looks the same @@ -33,12 +42,15 @@ use rustgis_data::query::Env; use rustgis_map::look::{Change, LayerLook, MapLook}; use tiny_skia::Pixmap; +use crate::gpu_scene::DrawCmd; use crate::tiles::TileOutput; -use crate::{Candidate, PlacedLabel, Sprites, View}; +use crate::{Backend, Candidate, PlacedLabel, Sprites, View}; /// 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. +/// 1920 × 1080. A GPU checkpoint counts the pictures and raster tiles its commands hold too +/// (each shared one once), though it shares them with the scene on screen: at 1920 × 1080, +/// eight pictures of the view in all. const MAX_PIXELS: u64 = 2 * 3840 * 2160; /// The most pixels one frame's marker sprites can hold ([`crate::MAX_SPRITES`] of at most @@ -57,9 +69,20 @@ pub(crate) const MAX_LABEL_BYTES: usize = 16 << 20; /// Pictures kept, one per view drawn (a map and its draft, two maps on screen). const KEPT: usize = 2; +/// The most bytes of meshes the kept GPU checkpoints hold together ([`GpuPart`]), as +/// [`crate::layer_meshes`] counts them: they share them with the scenes on screen and the meshes +/// that module keeps, so what they hold beside those is at most this, the same budget again. +const MAX_MESH_BYTES: usize = crate::layer_meshes::MAX_BYTES; + /// What a frame is drawn from besides its layers. #[derive(Clone, Debug)] pub(crate) struct Frame { + /// A CPU frame or a GPU scene (whose raster tile layers are placed live or as tiles). + pub backend: Backend, + /// On the GPU, whether see-through layers may be pictures of their own (`GPU_ALONE`), which + /// a change to any layer's blend can turn: a scene kept with them or without them is no + /// start for one drawn the other way. + pub alone: bool, pub map: MapLook, pub view: View, pub style_env: Env, @@ -90,7 +113,9 @@ 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() + self.backend == other.backend + && self.alone == other.alone + && 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 @@ -110,9 +135,12 @@ impl Frame { } /// 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, + /// Its pixels; for a GPU scene, those of the CPU picture it was drawing, `None` when that + /// held nothing yet. + pub pixels: Option>, + /// A GPU scene's commands so far. + pub gpu: Option, /// 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, @@ -126,11 +154,35 @@ pub(crate) struct Checkpoint { pub tiles: TileOutput, } +/// What a GPU scene had made when a [`Checkpoint`] was taken. +pub(crate) struct GpuPart { + /// Its commands, sharing their data with the scene's ([`DrawCmd::share`]). + pub cmds: Vec, + /// The see-through layers it had drawn as pictures of their own (`gpu_alone`). + pub alone: usize, + /// The pictures flushed so far, as the CPU fallback counts them. + pub runs: crate::Runs, +} + +impl GpuPart { + /// `cmds` shared, with `alone` layers drawn as pictures of their own and `runs`; `None` when + /// one can't be shared (an extrusion, which only a tilted view's scenes have). + pub(crate) fn of(cmds: &[DrawCmd], alone: usize, runs: crate::Runs) -> Option { + Some(GpuPart { cmds: cmds.iter().map(DrawCmd::share).collect::>()?, alone, runs }) + } + + /// Its commands, shared again for a scene starting from it. + pub(crate) fn cmds(&self) -> Vec { + self.cmds.iter().filter_map(DrawCmd::share).collect() + } +} + /// 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. +/// and composited, before the tile layers over it. Shared: on the GPU it is the picture the scene +/// draws. #[derive(Clone)] pub(crate) struct Alone { - pub pixels: Pixmap, + pub pixels: std::sync::Arc, pub sprites: Sprites, pub bursts: f32, pub candidates: Vec, @@ -160,8 +212,9 @@ 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. + /// The pixels it holds: its pictures, those of a GPU scene's commands (its pictures and + /// raster tiles) and their marker sprites, each shared one counted once (the checkpoint and + /// the layer alone share sprites; on the GPU a scene's command shares the layer alone). fn pixels(&self) -> u64 { let size = |p: &Pixmap| u64::from(p.width()) * u64::from(p.height()); let mut seen = std::collections::HashSet::new(); @@ -169,10 +222,38 @@ impl Kept { 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))) + .filter(|p| seen.insert(std::sync::Arc::as_ptr(p) as usize)) .map(|p| size(p)) .sum::(); - size(&self.checkpoint.pixels) + alone.map_or(0, |a| size(&a.pixels)) + sprites + let own = self.checkpoint.pixels.as_ref().filter(|p| seen.insert(std::sync::Arc::as_ptr(p) as usize)).map_or(0, |p| size(p)); + let alone_px = alone.filter(|a| seen.insert(std::sync::Arc::as_ptr(&a.pixels) as usize)).map_or(0, |a| size(&a.pixels)); + let cmds = self.checkpoint.gpu.iter().flat_map(|g| &g.cmds); + let mut scene = 0u64; + for c in cmds { + match c { + DrawCmd::Image { pixmap, .. } if seen.insert(std::sync::Arc::as_ptr(pixmap) as usize) => scene += size(pixmap), + DrawCmd::Tiles { tiles, .. } => { + for t in tiles { + if let Some(p) = t.pixmap().filter(|_| seen.insert(std::sync::Arc::as_ptr(&t.picture) as usize)) { + scene += size(p); + } + } + } + _ => {} + } + } + own + alone_px + sprites + scene + } + + /// The bytes of meshes a GPU scene's commands hold, as allocated. + fn mesh_bytes(&self) -> usize { + let cmds = self.checkpoint.gpu.iter().flat_map(|g| &g.cmds); + cmds.map(|c| match c { + DrawCmd::Mesh { .. } | DrawCmd::Points { .. } => crate::layer_meshes::bytes_of(std::slice::from_ref(c)), + DrawCmd::TileMeshes { tiles } => tiles.iter().map(|t| t.mesh.bytes()).sum(), + _ => 0, + }) + .sum() } } @@ -205,6 +286,12 @@ fn with_pictures(f: impl FnOnce(&mut Vec) -> R) -> R { PICTURES.with_borrow_mut(f) } +/// Forgets the pictures kept on this test thread, for a test of what else a frame keeps. +#[cfg(test)] +pub(crate) fn clear() { + PICTURES.take(); +} + /// 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, @@ -385,6 +472,14 @@ pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Opt kept.remove(0); } kept.push(Kept { frame, looks, labels, at, checkpoint, alone }); + // The meshes within theirs: the older views go first, then this one. + while kept.iter().map(Kept::mesh_bytes).sum::() > MAX_MESH_BYTES { + if kept.len() > 1 { + kept.remove(0); + } else { + kept.clear(); + } + } // 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 + KEPT as u64 * SPRITE_PIXELS { @@ -645,6 +740,177 @@ mod tests { assert!(RECOMBINED.get(), "the layer alone was kept"); } + /// `map()` over a raster read into memory, at the bottom: on the GPU a picture drawn on the + /// CPU, the squares and points meshes over it. + fn over_a_raster() -> (Map, View, u32, u32) { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let (mut map, view, below, above) = map(); + let n = 32usize; + let values: Vec = (0..n * n).map(|i| (i % n + i / n) as f32).collect(); + let gt = GeoTransform { origin_x: -0.1, origin_y: 0.15, pixel_width: 0.3 / n as f64, pixel_height: -0.25 / n as f64 }; + let r = Raster::new("r", n as u32, n as u32, vec![values], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").expect("a raster"); + map.add_raster("r", rustgis_map::RasterLayer::from_path(r, "r.tif")); + // Added on top; moved to the bottom. + let r = map.layers.remove(0); + map.layers.push(r); + (map, view, below, above) + } + + /// A GPU scene's commands, the pictures' pixels, opacities and the meshes' data among them. + fn commands(scene: &crate::gpu_scene::GpuScene) -> Vec<(&'static str, Vec)> { + scene + .cmds + .iter() + .map(|c| match c { + DrawCmd::Image { pixmap, opacity } => ("image", [&opacity.to_bits().to_le_bytes()[..], pixmap.data()].concat()), + DrawCmd::Mesh { vertices, indices, .. } => { + ("mesh", [bytemuck::cast_slice::<_, u8>(vertices.as_slice()), bytemuck::cast_slice(indices.as_slice())].concat()) + } + DrawCmd::Points { instances, .. } => ("points", bytemuck::cast_slice(instances.as_slice()).to_vec()), + _ => ("other", Vec::new()), + }) + .collect() + } + + /// The pictures of a GPU scene, by address. + fn pictures(scene: &crate::gpu_scene::GpuScene) -> Vec<*const Pixmap> { + scene + .cmds + .iter() + .filter_map(|c| match c { + DrawCmd::Image { pixmap, .. } => Some(std::sync::Arc::as_ptr(pixmap)), + _ => None, + }) + .collect() + } + + /// [`draw`] for a GPU scene: it must be the same scene as one drawn from nothing, command for + /// command. Gives where it started drawing its layers, and the scene. + fn draw_gpu(map: &mut Map, view: &View) -> (Option, crate::gpu_scene::GpuScene) { + let Some(crate::RenderOutput::Gpu(kept)) = crate::render_backend(map, view, Backend::Gpu) else { panic!("a GPU scene") }; + let (started, recombined) = (STARTED.get(), RECOMBINED.get()); + let pictures = PICTURES.take(); + let Some(crate::RenderOutput::Gpu(fresh)) = crate::render_backend(map, view, Backend::Gpu) else { panic!("a GPU scene") }; + PICTURES.set(pictures); + RECOMBINED.set(recombined); + let (k, f) = (commands(&kept), commands(&fresh)); + let shape = |c: &[(&'static str, Vec)]| { + c.iter().map(|(n, d)| (*n, d.len(), d.iter().map(|b| u64::from(*b)).sum::())).collect::>() + }; + assert!(k == f, "a scene from a kept picture differs from one drawn whole: {:?} vs {:?}", shape(&k), shape(&f)); + let texts = + |s: &crate::gpu_scene::GpuScene| s.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, kept) + } + + #[test] + fn a_gpu_scene_takes_the_pictures_under_its_first_changed_layer() { + let (mut map, view, below, above) = over_a_raster(); + let (started, first) = draw_gpu(&mut map, &view); + assert_eq!(started, Some(0)); + let images: Vec = first.cmds.iter().map(|c| matches!(c, DrawCmd::Image { .. })).collect(); + assert!(images.first() == Some(&true) && images.iter().skip(1).all(|i| !i), "the raster's picture, then meshes: {images:?}"); + 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) }); + } + }; + restyle(&mut map, above, (200, 30, 30)); + let (_, mut last) = draw_gpu(&mut map, &view); + for rgb in [(30, 200, 30), (30, 30, 200)] { + restyle(&mut map, above, rgb); + let (started, scene) = draw_gpu(&mut map, &view); + assert_eq!(started, Some(2), "from the picture under the points"); + assert_eq!(pictures(&scene), pictures(&last), "the raster's picture is the last scene's, its texture uploaded already"); + last = scene; + } + // The squares restyled: the first change under the kept picture draws everything again, + // the next from under them, the raster's picture the last scene's. + restyle(&mut map, below, (10, 10, 120)); + let (started, last) = draw_gpu(&mut map, &view); + assert_eq!(started, Some(0)); + restyle(&mut map, below, (10, 120, 10)); + let (started, scene) = draw_gpu(&mut map, &view); + assert_eq!(started, Some(1)); + assert_eq!(pictures(&scene), pictures(&last)); + // A CPU frame of the same view takes nothing of the GPU's, nor a GPU scene the CPU's. + let _ = render(&mut map, &view); + assert_eq!(STARTED.get(), Some(0)); + let _ = crate::render_backend(&mut map, &view, Backend::Gpu); + assert!( + PICTURES + .with_borrow(|k| k.iter().any(|k| k.frame.backend == Backend::Gpu) && k.iter().any(|k| k.frame.backend == Backend::Cpu)) + ); + // The raster restyled: everything again, a new picture. + if let Some(r) = map.layers.last_mut().and_then(|l| l.raster.as_mut()) { + r.style.brightness += 10.0; + } + let (started, scene) = draw_gpu(&mut map, &view); + assert_eq!(started, Some(0)); + assert_ne!(pictures(&scene), pictures(&last)); + } + + #[test] + fn a_see_through_layer_on_the_gpu_is_placed_again_at_its_new_transparency() { + let (mut map, view, below, above) = over_a_raster(); + let set = |map: &mut Map, t: f32| map.layer_mut(below).map(|l| l.transparency = t); + let opacities = |s: &crate::gpu_scene::GpuScene| { + s.cmds + .iter() + .filter_map(|c| match c { + DrawCmd::Image { opacity, .. } => Some((opacity * 100.0).round() as i32), + _ => None, + }) + .collect::>() + }; + set(&mut map, 20.0); + let (_, scene) = draw_gpu(&mut map, &view); + // The squares, see-through, are a picture of their own over the raster's, placed at their opacity. + assert_eq!(opacities(&scene), vec![100, 80]); + set(&mut map, 30.0); + let (_, mut last) = draw_gpu(&mut map, &view); + assert!(!RECOMBINED.get()); + for t in [40.0, 75.0, 5.0] { + set(&mut map, t); + let (started, scene) = draw_gpu(&mut map, &view); + assert_eq!(started, Some(1)); + assert!(RECOMBINED.get(), "{t}"); + assert_eq!(pictures(&scene), pictures(&last), "the same pictures, the squares' not drawn again"); + assert_eq!(opacities(&scene), vec![100, 100 - t as i32]); + last = scene; + } + // Restyled: drawn again, a new picture. + if let Some(l) = map.layer_mut(below) { + l.renderer = Renderer::Single(rustgis_map::Symbol { fill: Rgba::rgb(10, 200, 90), ..l.symbol(0) }); + } + let (_, scene) = draw_gpu(&mut map, &view); + assert!(!RECOMBINED.get()); + let (was, now) = (pictures(&last), pictures(&scene)); + assert!(was.first() == now.first() && was.get(1) != now.get(1), "the raster's kept, the squares' drawn again"); + // Blended, the layer is composited into the picture under it on the CPU, as before; its + // transparency changed alone still composites the layer kept, not drawn again. + if let Some(l) = map.layer_mut(below) { + l.blend = rustgis_map::effects::Blend::Multiply; + } + for t in [50.0, 60.0, 70.0] { + set(&mut map, t); + let (_, scene) = draw_gpu(&mut map, &view); + assert_eq!(opacities(&scene), vec![100], "one picture"); + } + assert!(RECOMBINED.get()); + // Of normal blend under a blended layer, which blends with the picture under it: still + // composited into it, so the blended layer sees what the see-through one drew. + if let Some(l) = map.layer_mut(below) { + l.blend = rustgis_map::effects::Blend::Normal; + } + if let Some(l) = map.layer_mut(above) { + l.blend = rustgis_map::effects::Blend::Multiply; + } + let (_, scene) = draw_gpu(&mut map, &view); + assert_eq!(opacities(&scene), vec![100], "the raster, the squares and the points in one picture"); + } + #[test] fn a_layer_with_no_look_draws_in_every_frame() { let (mut map, view, below, _) = map(); diff --git a/crates/render/src/gpu_scene.rs b/crates/render/src/gpu_scene.rs index 180e570023..967846462a 100644 --- a/crates/render/src/gpu_scene.rs +++ b/crates/render/src/gpu_scene.rs @@ -101,9 +101,14 @@ impl CmdClip { /// that need tiny-skia: masks, blend modes, transparency, aggregation, extrusion) at its /// exact z-position; `Mesh`/`Points` are lyon-tessellated vector layers. pub enum DrawCmd { - /// Screen-sized premultiplied RGBA, drawn covering the whole map view. The pixmap is - /// moved in, not copied — flushing the CPU accumulator doesn't pay a full-screen `to_vec`. - Image { pixmap: tiny_skia::Pixmap }, + /// Screen-sized premultiplied RGBA, drawn covering the whole map view at `opacity` (the + /// picture's every channel times it, placed over what is under it). The pixmap is moved in, + /// not copied — flushing the CPU accumulator doesn't pay a full-screen `to_vec`. Shared: a + /// picture of layers that look as they did is kept from one scene to the next + /// (`frame_cache`), and the GPU keeps the texture of a picture it has uploaded while the + /// picture lives. A see-through layer drawn alone is one at the layer's opacity, so a change + /// of transparency alone draws nothing again. + Image { pixmap: Arc, opacity: f32 }, /// Tessellated polygon fills and line/ring strokes of one layer run. Shared: a layer that looks /// as it did keeps its mesh from one scene to the next (`layer_meshes`), and the GPU keeps the /// buffers of a mesh it has uploaded while the mesh lives. @@ -130,6 +135,26 @@ pub enum DrawCmd { TileMeshes { tiles: Vec }, } +impl DrawCmd { + /// A command sharing this one's data, for a scene to draw again; `None` for an extrusion, + /// whose data isn't shared (only a tilted view's scenes have them, and those keep nothing). + pub fn share(&self) -> Option { + Some(match self { + DrawCmd::Image { pixmap, opacity } => DrawCmd::Image { pixmap: Arc::clone(pixmap), opacity: *opacity }, + DrawCmd::Mesh { origin, vertices, indices } => { + DrawCmd::Mesh { origin: *origin, vertices: Arc::clone(vertices), indices: Arc::clone(indices) } + } + DrawCmd::Points { origin, instances } => DrawCmd::Points { origin: *origin, instances: Arc::clone(instances) }, + DrawCmd::Extrusion { .. } => return None, + DrawCmd::Tiles { origin, tiles } => DrawCmd::Tiles { origin: *origin, tiles: tiles.clone() }, + DrawCmd::LiveTiles { name, spec, opacity, archive_revision } => { + DrawCmd::LiveTiles { name: name.clone(), spec: spec.clone(), opacity: *opacity, archive_revision: *archive_revision } + } + DrawCmd::TileMeshes { tiles } => DrawCmd::TileMeshes { tiles: tiles.clone() }, + }) + } +} + /// One tile of a [`DrawCmd::TileMeshes`]. #[derive(Clone)] pub struct MeshTile { diff --git a/crates/render/src/layer_meshes.rs b/crates/render/src/layer_meshes.rs index 1374c204ba..bf7f60389d 100644 --- a/crates/render/src/layer_meshes.rs +++ b/crates/render/src/layer_meshes.rs @@ -132,7 +132,7 @@ fn share(cmd: &DrawCmd) -> Option { } /// The bytes `cmds` hold, as allocated. -fn bytes_of(cmds: &[DrawCmd]) -> usize { +pub(crate) fn bytes_of(cmds: &[DrawCmd]) -> usize { cmds.iter() .map(|c| match c { DrawCmd::Mesh { vertices, indices, .. } => { @@ -351,8 +351,11 @@ mod tests { (m, a, b, View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }) } - /// The GPU scene of `view`; a frame drawn on the CPU instead fails the test. + /// The GPU scene of `view`, drawn whole: a scene started from a kept picture + /// (`frame_cache`) doesn't draw the layers under it. A frame drawn on the CPU instead fails + /// the test. fn scene(m: &mut Map, view: &View) -> GpuScene { + crate::frame_cache::clear(); match render_backend(m, view, Backend::Gpu) { Some(RenderOutput::Gpu(s)) => s, _ => panic!("no GPU scene"), diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6df81f793d..171bb1a23f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2165,20 +2165,53 @@ fn render_cpu( } } +/// How many pictures a GPU scene would hold with its see-through layers composited into the +/// picture being drawn rather than drawn alone ([`GPU_ALONE`]), as they were before they could +/// be: what the CPU fallback counts, so the same scenes stay on the GPU. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Runs { + pub count: usize, + /// A layer drawn alone since the last flush: composited, it would have left the picture + /// being drawn something to flush. + pub pending: bool, +} + /// Flushes the GPU pass's CPU accumulator pixmap as an Image draw command and resets it to /// transparent. Basemap, tiles, rasters and tiny-skia-only layers draw into the accumulator -/// between GPU mesh commands, preserving the exact painter's-algorithm order. -pub(crate) fn flush_acc(pm: &mut Pixmap, cmds: &mut Vec, dirty: &mut bool) -> Option<()> { +/// between GPU mesh commands, preserving the exact painter's-algorithm order. Counts in `runs` +/// what the flush would have flushed with the layers alone composited instead. +pub(crate) fn flush_acc(pm: &mut Pixmap, cmds: &mut Vec, dirty: &mut bool, runs: &mut Runs) -> Option<()> { + if *dirty || runs.pending { + runs.count += 1; + runs.pending = false; + } if *dirty { // Move the pixmap into the command (no full-screen copy) and start a fresh transparent // accumulator. let old = std::mem::replace(pm, Pixmap::new(pm.width(), pm.height())?); - cmds.push(gpu_scene::DrawCmd::Image { pixmap: old }); + cmds.push(gpu_scene::DrawCmd::Image { pixmap: std::sync::Arc::new(old), opacity: 1.0 }); *dirty = false; } Some(()) } +/// Places a see-through layer's own picture over what is drawn so far, at its `opacity` +/// ([`GPU_ALONE`]): the accumulator flushed first, which `runs` doesn't count, as the layer would +/// have been composited into it. +fn place_alone( + pm: &mut Pixmap, + cmds: &mut Vec, + dirty: &mut bool, + runs: &mut Runs, + picture: std::sync::Arc, + opacity: f32, +) -> Option<()> { + flush_acc(pm, cmds, dirty, &mut Runs::default())?; + cmds.push(gpu_scene::DrawCmd::Image { pixmap: picture, opacity }); + runs.pending = true; + Some(()) +} + /// The shared render body behind [`render`], [`render_backend`] and the export paths. /// `full_res_rasters` renders rasters at full resolution (exports); `backend` selects the CPU /// pixmap or a GPU scene (see [`Backend`]). @@ -4242,6 +4275,34 @@ fn frame_water(map: &Map, view: &View, labels_to: &Labels) -> Option<(std::sync: ground.water().cloned().map(|w| (w, pending)) } +/// The see-through layers a GPU scene draws as pictures of their own, which the GPU places at +/// the layer's opacity: those of normal blend and no mask, the first this many in the drawing +/// order, on a map with no layer or tile layer of another blend (which blends with the picture +/// being drawn under it). The others are composited into the picture being drawn, as a blended +/// or masked layer is. A layer of its own is drawn once while only its transparency changes (`frame_cache`), but +/// each is a picture of the whole view to upload and keep on the GPU, and it can split the +/// picture under and over it in two; so a few, not every one. +const GPU_ALONE: usize = 2; + +/// Gives the pictures among `cmds` at the places `kept` names that hold the same pixels as the +/// picture kept for that place (a checkpoint's, drawn on by nothing since) that very picture, +/// shared, and forgets the places `cmds` has reached: a scene started from a checkpoint draws +/// its picture from the texture uploaded for it, and a scene kept draws the one its checkpoint +/// holds. The pictures are compared only once each, when the scene's next picture comes. +fn share_kept_pictures(cmds: &mut [gpu_scene::DrawCmd], kept: &mut Vec<(usize, std::sync::Arc)>) { + kept.retain(|(at, p)| { + let Some(c) = cmds.get_mut(*at) else { return true }; + if let gpu_scene::DrawCmd::Image { pixmap, opacity } = c + && *opacity == 1.0 + && !std::sync::Arc::ptr_eq(pixmap, p) + && pixmap.data() == p.data() + { + *pixmap = std::sync::Arc::clone(p); + } + false + }); +} + /// Whether a GPU scene's commands hold a picture drawn on the CPU. fn holds_picture(cmds: &[gpu_scene::DrawCmd]) -> bool { cmds.iter().any(|c| matches!(c, gpu_scene::DrawCmd::Image { .. })) @@ -4354,16 +4415,22 @@ fn render_frame( // 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(); + // Whether see-through layers may be drawn as pictures of their own (see `GPU_ALONE`): not on a + // map with a layer or tile layer of another blend, which blends with the picture under it, + // which must then hold what a see-through layer drew there. + let normal = rustgis_map::effects::Blend::Normal; + let alone_allowed = gpu && !map.layers.iter().any(|l| l.blend != normal) && !map.tiles.iter().any(|t| t.blend != normal); // A screen frame starts from the picture kept of the last one, under its first changed layer - // (see `frame_cache`), and keeps its own. + // (see `frame_cache`), and keeps its own: a GPU scene's, with its commands so far. 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 { + backend, + alone: alone_allowed, map: rustgis_map::look::MapLook::of(map), view: *view, style_env: style_env.clone(), @@ -4396,7 +4463,7 @@ fn render_frame( // 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 drawn_alone: Option<(usize, std::sync::Arc)> = None; let mut captured_alone: Option<(usize, frame_cache::Alone)> = None; // The label candidates each layer drawn gives the frame, kept for the next (see `frame_cache`). let mut layer_labels: frame_cache::LayerLabels = Vec::new(); @@ -4420,6 +4487,11 @@ fn render_frame( } // Set when tiny-skia actually rasterizes into the accumulator. let mut cpu_dirty = false; + // The pictures flushed so far, as the CPU fallback counts them (see `Runs`). + let mut runs = Runs::default(); + // The see-through layers drawn as pictures of their own so far (see `GPU_ALONE`); none unless + // `alone_allowed`. + let mut gpu_alone = if alone_allowed { 0 } else { GPU_ALONE }; // A GPU frame standing in for a turned or tilted view ([`gpu_turned`]) is of no use with a // picture in it: that view is then drawn on the CPU whole. So it stops at the first layer // that would leave one, rather than draw the rest (#2540). @@ -4453,7 +4525,7 @@ fn render_frame( // The GPU backend tessellates a country in view whole (its mesh moves with the camera, // `GPU_CULL_MARGIN`): the level's fewer vertices help it, the per-part culling doesn't. if gpu { - flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; + flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs)?; if mesh::collect_basemap(&mut cmds, polys, &c.extent, land, outline, ctx.ppp, map_per_px).is_ok() { continue; } @@ -4478,7 +4550,7 @@ fn render_frame( { let mut tessellated = false; if gpu { - flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; + flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs)?; tessellated = mesh::collect_basemap(&mut cmds, polys, &g.extent(), land, outline, ctx.ppp, map_per_px).is_ok(); } if gpu && !tessellated { @@ -4555,7 +4627,7 @@ fn render_frame( e.expand(*c); } } - flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; + flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs)?; let tessellated = !e.is_empty() && mesh::collect_graticule(&mut cmds, &lines, &e, grat, width, ctx.ppp, map_per_px).is_ok(); if !tessellated { @@ -4598,6 +4670,7 @@ fn render_frame( let tile_gpu = (gpu && shown).then_some(tiles::Gpu { cmds: &mut cmds, dirty: &mut cpu_dirty, + runs: &mut runs, // A tilted view's bands are drawn at their own densities: their tiles as pictures. meshes: !matches!(labels_to, Labels::Tilted(..)), // Only a frame for the view itself (not a turned or tilted view's north-up stand-in). @@ -4654,8 +4727,24 @@ 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(); + // The pictures a GPU scene was drawing when its checkpoints were taken, by the place among + // its commands the next picture comes: when that is the same picture, it is the one kept + // (`share_kept_pictures`), whose texture is on the GPU already. + let mut kept_pictures: Vec<(usize, std::sync::Arc)> = Vec::new(); if let Some(c) = cached.as_ref().and_then(|p| p.restored.as_ref()) { - pm = Canvas::from_pixmap(c.pixels.clone()); + pm = match &c.pixels { + Some(p) => Canvas::from_pixmap(Pixmap::clone(p)), + None => Canvas::new(w, h)?, + }; + // A GPU scene's commands so far, sharing their data (and so the GPU's textures and + // buffers) with the scene kept, and the picture it was drawing then. + if let Some(g) = &c.gpu { + cmds = g.cmds(); + gpu_alone = g.alone; + runs = g.runs; + cpu_dirty = c.pixels.is_some(); + kept_pictures.extend(c.pixels.iter().map(|p| (cmds.len(), std::sync::Arc::clone(p)))); + } // 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); @@ -4724,11 +4813,26 @@ 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)) && complete(&tile_out) { + // A GPU scene's commands are kept with the picture it is drawing (none while that holds + // nothing), when they can all be shared. + if cached.as_ref().is_some_and(|p| p.capture_at == Some(at)) + && complete(&tile_out) + && let Some(gpu_part) = if gpu { + share_kept_pictures(&mut cmds, &mut kept_pictures); + frame_cache::GpuPart::of(&cmds, gpu_alone, runs).map(Some) + } else { + Some(None) + } + { + let pixels = (!gpu || cpu_dirty).then(|| std::sync::Arc::new(pm.pixels().clone())); + if gpu && let Some(p) = &pixels { + kept_pictures.push((cmds.len(), std::sync::Arc::clone(p))); + } captured = Some(( at, frame_cache::Checkpoint { - pixels: pm.pixels().clone(), + pixels, + gpu: gpu_part, sprites: ctx.sprites.borrow().clone(), bursts: ctx.bursts.get(), // Over a restored picture, its tiles are as old as that picture. @@ -4759,6 +4863,8 @@ fn render_frame( let (blend, layer_blend) = (blend_mode(layer.blend), layer.blend); // Drawn on its own and composited when it is see-through, masked or blended. let offscreen = opacity < 0.999 || mask.is_some() || layer.blend != rustgis_map::effects::Blend::Normal; + // On the GPU, a picture of its own placed at its opacity (see `GPU_ALONE`). + let gpu_own = gpu && offscreen && mask.is_none() && layer.blend == rustgis_map::effects::Blend::Normal && gpu_alone < GPU_ALONE; let composite = |pm: &mut Canvas, target: &Pixmap| { // A recording keeps the masked layer as a picture cut by its mask, placed with its // opacity and blend over the vectors beneath. @@ -4786,7 +4892,14 @@ fn render_frame( && offscreen && let Some(a) = cached.as_ref().and_then(|p| p.recombine.as_ref()) { - composite(&mut pm, &a.pixels); + if gpu_own { + // The same picture as last time, its texture already on the GPU. + place_alone(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs, std::sync::Arc::clone(&a.pixels), opacity)?; + gpu_alone += 1; + } else { + composite(&mut pm, &a.pixels); + cpu_dirty = true; + } ctx.sprites.borrow_mut().clone_from(&a.sprites); ctx.bursts.set(a.bursts); label_candidates.clone_from(&a.candidates); @@ -4865,14 +4978,21 @@ fn render_frame( if offscreen { let mut target = Pixmap::new(w, h)?; draw_it(&mut target, 1.0); - composite(&mut pm, &target); + let target = std::sync::Arc::new(target); + if gpu_own { + place_alone(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs, std::sync::Arc::clone(&target), opacity)?; + gpu_alone += 1; + } else { + composite(&mut pm, &target); + cpu_dirty = true; + } if alone_at == Some(at) { drawn_alone = Some((at, target)); } } else { draw_it(pm.pixels(), opacity); + cpu_dirty = true; } - cpu_dirty = true; } continue; } @@ -4992,6 +5112,11 @@ fn render_frame( // Copied only while the frame's copies stay within what a view keeps. let room = frame_cache::MAX_LABEL_BYTES.saturating_sub(layer_label_bytes); let mut gave_labels: Option> = None; + // Whether the picture being drawn held anything before this layer: a layer drawn as a + // picture of its own (`gpu_own`) leaves it so. + let dirty_before = cpu_dirty; + // Whether the layer drew anything (`gpu_own`: a picture of its own only then). + let mut layer_drew = false; let mut draw_chunk = |layer: &mut rustgis_map::Layer| -> rustgis_data::Result<()> { // A stopped frame draws no more of a layer or a streamed chunk (see `cancel`). if cancel::requested() { @@ -5113,7 +5238,7 @@ fn render_frame( // just itself. let mut gpu_done = false; if gpu_layer { - flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty) + flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs) .ok_or_else(|| rustgis_data::DataError::Format("cannot allocate render target".into()))?; // Kept from the last scene of this view when the layer looks as it did (a layer read // from its source has no look, and draws in batches). @@ -5384,6 +5509,7 @@ fn render_frame( dest.end_bands(); } cpu_dirty |= drawn_here; + layer_drew |= drawn_here; } if !complete_source { if let (Some(a), Some(base)) = (layer.aggregation, aggregate_symbol) { @@ -5393,6 +5519,7 @@ fn render_frame( if let Some((water, darkness)) = &shore { terrain::paint_shore(if direct { &mut pm } else { &mut target }, water, view, *darkness); cpu_dirty = true; + layer_drew = true; } if !direct { if target.is_recording() { @@ -5400,11 +5527,26 @@ fn render_frame( pm.place(std::mem::replace(&mut target, empty), Transform::identity(), opacity, layer_blend, None); } } 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())); + let keep_alone = alone_at == Some(at) && layer.selection.is_empty() && !layer.graphics && layer.extrusion.is_none(); + if gpu_own && !layer_drew { + // Nothing drawn: nothing to place. + cpu_dirty = dirty_before; + } else if gpu_own && let Some(empty) = Canvas::new(1, 1) { + let picture = std::sync::Arc::new(std::mem::replace(&mut target, empty).into_pixmap()); + cpu_dirty = dirty_before; + place_alone(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs, std::sync::Arc::clone(&picture), opacity) + .ok_or_else(|| rustgis_data::DataError::Format("cannot allocate render target".into()))?; + gpu_alone += 1; + if keep_alone { + drawn_alone = Some((at, picture)); + } + } else { + composite(&mut pm, target.pixmap()); + if keep_alone { + drawn_alone = Some((at, std::sync::Arc::new(target.pixmap().clone()))); + } } } } @@ -6108,10 +6250,18 @@ fn render_frame( if let Some((water, darkness)) = &shore { terrain::paint_shore(if direct { &mut pm } else { &mut target }, water, view, *darkness); cpu_dirty = true; + layer_drew = true; } if !direct { if target.is_recording() { pm.place(target, Transform::identity(), opacity, layer_blend, None); + } else if gpu_own { + // Nothing drawn (a source that gave no rows): nothing to place. + cpu_dirty = dirty_before; + if layer_drew { + place_alone(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs, std::sync::Arc::new(target.into_pixmap()), opacity)?; + gpu_alone += 1; + } } else { composite(&mut pm, target.pixmap()); } @@ -6145,9 +6295,8 @@ fn render_frame( return None; } } - if let Some(plan) = cached.take() { - frame_cache::keep(plan, captured, captured_alone, layer_labels); - } + // Kept once the frame is done: not a GPU scene that the CPU draws whole instead. + let keep = cached.take().map(|plan| move || frame_cache::keep(plan, captured, captured_alone, layer_labels)); // 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()) @@ -6307,6 +6456,9 @@ fn render_frame( let pending_in_place = tile_out.pending_in_place; match backend { Backend::Cpu => { + if let Some(keep) = keep { + keep(); + } let (pixmap, recorded) = if pm.is_recording() { (Pixmap::new(1, 1)?, Some(pm)) } else { (pm.into_pixmap(), None) }; Some(RenderOutput::Cpu(Rendered { pixmap, @@ -6323,13 +6475,19 @@ fn render_frame( })) } Backend::Gpu | Backend::GpuLive => { - flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; + flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty, &mut runs)?; + share_kept_pictures(&mut cmds, &mut kept_pictures); // Pathological CPU/GPU alternation (rasters, masks, blends between every vector - // layer) costs more full-screen uploads than a plain CPU rasterization. - let images = cmds.iter().filter(|c| matches!(c, gpu_scene::DrawCmd::Image { .. })).count(); - if images > 4 { + // layer) costs more full-screen uploads than a plain CPU rasterization. Counted as + // though the see-through layers drawn alone were composited into the pictures around + // them, as they were before they could be (`GPU_ALONE`), so the same scenes stay on + // the GPU. + if runs.count > 4 { return render_frame(map, view, full_res_rasters, Backend::Cpu, labels_to, record, failed_source, env); } + if let Some(keep) = keep { + keep(); + } Some(RenderOutput::Gpu(gpu_scene::GpuScene { clear: mesh::premul(water), cmds, @@ -10097,6 +10255,31 @@ mod tests { assert!(!scene.cmds.iter().any(|c| matches!(c, gpu_scene::DrawCmd::Image { .. })), "hidden tiles must not emit an empty image"); } + /// The pictures a scene would hold with its see-through layers composited into the picture + /// being drawn instead of drawn alone, as `Runs` counts them. + #[test] + fn runs_count_the_pictures_of_a_scene_without_layers_alone() { + let alone = || std::sync::Arc::new(Pixmap::new(1, 1).expect("pixmap")); + let (mut pm, mut cmds) = (Pixmap::new(1, 1).expect("pixmap"), Vec::new()); + // A picture, then two layers alone over it and a picture over them: one, as composited. + let (mut dirty, mut runs) = (true, Runs::default()); + place_alone(&mut pm, &mut cmds, &mut dirty, &mut runs, alone(), 0.5); + place_alone(&mut pm, &mut cmds, &mut dirty, &mut runs, alone(), 0.5); + dirty = true; + flush_acc(&mut pm, &mut cmds, &mut dirty, &mut runs); + assert_eq!((cmds.len(), runs.count), (4, 1)); + // Ended by a layer that adds nothing (a mesh with nothing in view): a layer alone, then a + // picture, are two. + place_alone(&mut pm, &mut cmds, &mut dirty, &mut runs, alone(), 0.5); + flush_acc(&mut pm, &mut cmds, &mut dirty, &mut runs); + dirty = true; + flush_acc(&mut pm, &mut cmds, &mut dirty, &mut runs); + assert_eq!(runs.count, 3); + // A flush with nothing drawn since counts nothing. + flush_acc(&mut pm, &mut cmds, &mut dirty, &mut runs); + assert_eq!(runs.count, 3); + } + #[test] fn gpu_backend_caps_image_commands_to_a_cpu_frame() { // More than four alternating CPU-only layers costs more full-screen uploads than a @@ -10154,7 +10337,7 @@ mod tests { let kinds = cmd_kinds(&scene); assert!(!kinds.contains(&"mesh"), "no mesh f32 would misplace: {kinds:?}"); let Some(pixmap) = scene.cmds.iter().find_map(|c| match c { - gpu_scene::DrawCmd::Image { pixmap } => Some(pixmap), + gpu_scene::DrawCmd::Image { pixmap, .. } => Some(pixmap), _ => None, }) else { panic!("the square is drawn on the CPU: {kinds:?}") diff --git a/crates/render/src/tiles.rs b/crates/render/src/tiles.rs index 4a88492b83..33efd80b81 100644 --- a/crates/render/src/tiles.rs +++ b/crates/render/src/tiles.rs @@ -265,6 +265,8 @@ fn mesh_tiles(v: &rustgis_tiles::shapes::VectorTiles, centre: [f64; 2]) -> (Vec< pub(crate) struct Gpu<'a> { pub cmds: &'a mut Vec, pub dirty: &'a mut bool, + /// The pictures flushed so far, as the CPU fallback counts them ([`crate::Runs`]). + pub runs: &'a mut crate::Runs, /// Vector tile styles may be drawn as meshes ([`DrawCmd::TileMeshes`]). pub meshes: bool, /// Raster tile layers are left for the GPU map to place for each frame ([`DrawCmd::LiveTiles`]). @@ -374,7 +376,7 @@ pub(crate) fn draw( && t.opacity >= 0.999 && let Some(v) = rustgis_tiles::shapes::vector_tiles(&spec(t), &frame, &fetch, Some(&reach), labels.then_some((pm.width(), pm.height()))) - && crate::flush_acc(pm, g.cmds, g.dirty).is_some() + && crate::flush_acc(pm, g.cmds, g.dirty, g.runs).is_some() { let (tiles, waiting) = mesh_tiles(&v, origin); if !tiles.is_empty() { @@ -394,7 +396,7 @@ pub(crate) fn draw( && north_up && t.blend == Blend::Normal && let Some(p) = rustgis_tiles::place_raster(&s, t.opacity, &frame, &fetch, &reach) - && crate::flush_acc(pm, g.cmds, g.dirty).is_some() + && crate::flush_acc(pm, g.cmds, g.dirty, g.runs).is_some() { let archive_revision = if matches!(s.kind, Kind::PmTiles | Kind::MbTiles) { rustgis_tiles::cache::archive_revision([s.url.as_str()]) @@ -413,7 +415,7 @@ pub(crate) fn draw( { // What the accumulator holds goes first, under the tiles; with no room for a new // accumulator the layer is drawn into this one instead. - let flushed = p.tiles.is_empty() || crate::flush_acc(pm, g.cmds, g.dirty).is_some(); + let flushed = p.tiles.is_empty() || crate::flush_acc(pm, g.cmds, g.dirty, g.runs).is_some(); if flushed { if !p.tiles.is_empty() { g.cmds.push(DrawCmd::Tiles { origin, tiles: p.tiles.iter().map(|q| quad(q, origin)).collect() }); diff --git a/crates/ui-egui/src/mapgpu.rs b/crates/ui-egui/src/mapgpu.rs index 2480586252..53ac864aa8 100644 --- a/crates/ui-egui/src/mapgpu.rs +++ b/crates/ui-egui/src/mapgpu.rs @@ -255,6 +255,8 @@ pub(crate) struct GpuMapRenderer { tile_mesh_layout: wgpu::BindGroupLayout, backdrop_layout: wgpu::BindGroupLayout, image_layout: wgpu::BindGroupLayout, + /// A picture's opacity, beside its texture. + opacity_layout: wgpu::BindGroupLayout, blit_layout: wgpu::BindGroupLayout, templates: wgpu::Buffer, sampler: wgpu::Sampler, @@ -266,6 +268,8 @@ pub(crate) struct GpuMapRenderer { tile_meshes: std::sync::Mutex, /// The layers' meshes and markers the latest scene uploaded, for the next to share. layer_buffers: std::sync::Mutex, + /// The pictures drawn on the CPU the latest scene uploaded, for the next to share. + pictures: std::sync::Mutex, /// The live raster tile layers' pictures and per-frame instances (#635). pub(crate) live: std::sync::Mutex, /// The last frame left live tile pictures to upload: draw again. @@ -331,6 +335,10 @@ impl GpuMapRenderer { label: Some("mapgpu_blit_uv"), entries: &[uniform_buf(wgpu::ShaderStages::VERTEX, 0, 16)], }); + let opacity_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("mapgpu_image_opacity"), + entries: &[uniform_buf(wgpu::ShaderStages::FRAGMENT, 1, 16)], + }); let templates = buffer_init( device, &wgpu::util::BufferInitDescriptor { @@ -508,7 +516,8 @@ impl GpuMapRenderer { samples, flat.clone(), ); - let image_pipeline = pipeline("mapgpu_image", "vs_image", "fs_image", &[], &[&image_layout], scene_format, samples, flat.clone()); + let image_pipeline = + pipeline("mapgpu_image", "vs_image", "fs_image", &[], &[&image_layout, &opacity_layout], scene_format, samples, flat.clone()); let backdrop_pipeline = pipeline("mapgpu_backdrop", "vs_backdrop", "fs_backdrop", &[], &[&backdrop_layout], scene_format, samples, flat.clone()); let shadow_pipeline = @@ -542,6 +551,7 @@ impl GpuMapRenderer { tile_mesh_layout, backdrop_layout, image_layout, + opacity_layout, blit_layout, templates, sampler, @@ -549,6 +559,7 @@ impl GpuMapRenderer { tile_textures: Default::default(), tile_meshes: Default::default(), layer_buffers: Default::default(), + pictures: Default::default(), live: std::sync::Mutex::new(crate::tilelayer::LiveTiles::new(device, scene_format, samples, DEPTH_FORMAT)), live_backlog: std::sync::atomic::AtomicBool::new(false), } @@ -877,6 +888,80 @@ impl LayerBuffers { } } +/// A picture drawn on the CPU, on the GPU. +pub(crate) struct PictureTexture { + bind: wgpu::BindGroup, + _texture: Owned, +} + +/// The pictures drawn on the CPU on the GPU, by the address of their pixels, which the renderer +/// shares from scene to scene while the layers in them look as they did (`render::frame_cache`): +/// a scene draws those from the textures an earlier one uploaded, as [`LayerBuffers`] keeps the +/// layers' meshes. Both are held weakly: a texture lives as long as a scene that draws it, so these +/// cost no GPU memory beside the scenes on screen. +#[derive(Default)] +struct PictureTextures { + by_picture: std::collections::HashMap, std::sync::Weak)>, +} + +impl PictureTextures { + /// The texture of `pixmap`, uploaded the first time a scene draws it. + fn texture( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + r: &GpuMapRenderer, + pixmap: &Arc, + ) -> Arc { + let key = Arc::as_ptr(pixmap) as usize; + // While the picture lives its address is its own: the weak reference keeps another from it. + if let Some((picture, texture)) = self.by_picture.get(&key) + && picture.upgrade().is_some_and(|p| Arc::ptr_eq(&p, pixmap)) + && let Some(texture) = texture.upgrade() + { + return texture; + } + let size = wgpu::Extent3d { width: pixmap.width(), height: pixmap.height(), depth_or_array_layers: 1 }; + let texture = owned_texture( + device, + &wgpu::TextureDescriptor { + label: Some("mapgpu_image"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + // Linear, like every egui texture: values pass through unconverted. + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }, + ); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + pixmap.data(), + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(pixmap.width() * 4), rows_per_image: Some(pixmap.height()) }, + size, + ); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("mapgpu_image_bind"), + layout: &r.image_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&r.sampler) }, + ], + }); + let texture = Arc::new(PictureTexture { bind, _texture: texture }); + self.by_picture.insert(key, (Arc::downgrade(pixmap), Arc::downgrade(&texture))); + texture + } + + /// Ends a scene: forgets the textures no scene draws any longer, and those of pictures gone. + fn end_scene(&mut self) { + self.by_picture.retain(|_, (picture, texture)| picture.strong_count() > 0 && texture.strong_count() > 0); + } +} + /// One tile of an uploaded vector tile layer. pub(crate) struct MeshTileDraw { mesh: Arc, @@ -1043,23 +1128,13 @@ pub(crate) enum SceneDraw { }, /// A vector tile layer's meshes: what shows of them depends on the camera's zoom (its bits, /// rewritten by `set_camera`). - TileMeshes { - tiles: Vec, - zoom: std::sync::atomic::AtomicU32, - }, + TileMeshes { tiles: Vec, zoom: std::sync::atomic::AtomicU32 }, /// A tilted view's water, fog and sky, under everything. - Backdrop { - uniforms: Owned, - bind: wgpu::BindGroup, - }, - Image { - bind: wgpu::BindGroup, - _texture: Owned, - }, + Backdrop { uniforms: Owned, bind: wgpu::BindGroup }, + /// A picture drawn on the CPU, shared with the scenes that draw it, and its opacity. + Image { texture: Arc, opacity: wgpu::BindGroup, _opacity: Owned }, /// The `n`th live raster tile layer of the scene, placed for each frame shown (#635). - LiveTiles { - n: usize, - }, + LiveTiles { n: usize }, /// A raster tile layer: its tiles' corners in one buffer, six per tile, and each tile's /// texture (from [`TileTextures`]) with the first of its corners. Tiles { @@ -1205,7 +1280,7 @@ fn cmd_fits(limits: &wgpu::Limits, cmd: &DrawCmd) -> bool { && fits(std::mem::size_of_val(indices.as_slice())) && u32::try_from(indices.len()).is_ok() } - DrawCmd::Image { pixmap } => { + DrawCmd::Image { pixmap, .. } => { let (w, h) = (pixmap.width(), pixmap.height()); (1..=max_dim).contains(&w) && (1..=max_dim).contains(&h) && pixmap.data().len() as u64 == w as u64 * h as u64 * 4 } @@ -1247,6 +1322,7 @@ impl SceneBuffers { let mut tile_textures = r.tile_textures.lock().unwrap_or_else(|e| e.into_inner()); let mut tile_meshes = r.tile_meshes.lock().unwrap_or_else(|e| e.into_inner()); let mut layer_buffers = r.layer_buffers.lock().unwrap_or_else(|e| e.into_inner()); + let mut pictures = r.pictures.lock().unwrap_or_else(|e| e.into_inner()); if let Some(t) = tilt.filter(|t| t.camera.pitch != 0.0) { let u = BackdropUniforms::new(&camera, size, ppp, scene.clear, t); let uniforms = owned_buffer( @@ -1374,46 +1450,27 @@ impl SceneBuffers { shadows: *shadows, }); } - DrawCmd::Image { pixmap } => { - let texture = owned_texture( + DrawCmd::Image { pixmap, opacity } => { + let texture = pictures.texture(device, queue, r, pixmap); + let uniform = owned_buffer( device, - &wgpu::TextureDescriptor { - label: Some("mapgpu_image"), - size: wgpu::Extent3d { width: pixmap.width(), height: pixmap.height(), depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - // Linear, like every egui texture: values pass through unconverted. - format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }, - ); - queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &texture, - mip_level: 0, - origin: wgpu::Origin3d::ZERO, - aspect: wgpu::TextureAspect::All, - }, - pixmap.data(), - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(pixmap.width() * 4), - rows_per_image: Some(pixmap.height()), + &wgpu::util::BufferInitDescriptor { + label: Some("mapgpu_image_opacity"), + contents: bytemuck::cast_slice(&[ + if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 }, + 0.0, + 0.0, + 0.0, + ]), + usage: wgpu::BufferUsages::UNIFORM, }, - wgpu::Extent3d { width: pixmap.width(), height: pixmap.height(), depth_or_array_layers: 1 }, ); - let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("mapgpu_image_bind"), - layout: &r.image_layout, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&r.sampler) }, - ], + label: Some("mapgpu_image_opacity"), + layout: &r.opacity_layout, + entries: &[wgpu::BindGroupEntry { binding: 1, resource: uniform.as_entire_binding() }], }); - draws.push(SceneDraw::Image { bind, _texture: texture }); + draws.push(SceneDraw::Image { texture, opacity: bind, _opacity: uniform }); has_images = true; } DrawCmd::LiveTiles { name, spec, opacity, archive_revision } => { @@ -1499,6 +1556,7 @@ impl SceneBuffers { tile_textures.end_scene(); tile_meshes.end_scene(); layer_buffers.end_scene(); + pictures.end_scene(); let tiles_live = !live.is_empty() && !has_images && !has_tiles && !scene.cmds.iter().any(|c| matches!(c, DrawCmd::TileMeshes { .. })); let reach = gpu_scene::reach(&scene.cmds); @@ -1595,9 +1653,10 @@ fn paint_draws(renderer: &GpuMapRenderer, draws: &[SceneDraw], rp: &mut wgpu::Re rp.set_bind_group(0, bind, &[]); rp.draw(0..6, 0..1); } - SceneDraw::Image { bind, .. } => { + SceneDraw::Image { texture, opacity, .. } => { rp.set_pipeline(&renderer.image_pipeline); - rp.set_bind_group(0, bind, &[]); + rp.set_bind_group(0, &texture.bind, &[]); + rp.set_bind_group(1, opacity, &[]); rp.draw(0..6, 0..1); } SceneDraw::TileMeshes { tiles, zoom, .. } => { @@ -1818,13 +1877,19 @@ mod tests { assert!(!cmd_fits(&limits, &mesh(100, 6)), "a vertex buffer over max_buffer_size declines"); assert!(!cmd_fits(&limits, &mesh(4, 300)), "an index buffer over max_buffer_size declines"); assert!( - !cmd_fits(&limits, &DrawCmd::Image { pixmap: rustgis_engine::render::Pixmap::new(2049, 2).expect("pixmap") }), + !cmd_fits( + &limits, + &DrawCmd::Image { pixmap: Arc::new(rustgis_engine::render::Pixmap::new(2049, 2).expect("pixmap")), opacity: 1.0 } + ), "an image over max_texture_dimension_2d declines" ); // 0x0 and size-mismatched images are now unconstructible (Pixmap always holds w*h*4): // the type does the work. assert!( - cmd_fits(&limits, &DrawCmd::Image { pixmap: rustgis_engine::render::Pixmap::new(2, 2).expect("pixmap") }), + cmd_fits( + &limits, + &DrawCmd::Image { pixmap: Arc::new(rustgis_engine::render::Pixmap::new(2, 2).expect("pixmap")), opacity: 1.0 } + ), "a valid 2x2 image fits" ); } @@ -1890,7 +1955,7 @@ mod tests { shape: 0, }]), }, - DrawCmd::Image { pixmap: rustgis_engine::render::Pixmap::new(1, 1).expect("pixmap") }, + DrawCmd::Image { pixmap: Arc::new(rustgis_engine::render::Pixmap::new(1, 1).expect("pixmap")), opacity: 1.0 }, ], labels: vec![], unplaced: vec![], @@ -1906,14 +1971,16 @@ mod tests { let sb = SceneBuffers::from_scene(&rs.device, &rs.queue, &r, &scene, Camera::world(), [400.0, 300.0], 1.0).expect("fits the device"); assert_eq!(sb.draws.len(), 3); - // The next scene sharing the layers' data (a layer that looks as it did) draws from the - // buffers this one uploaded; new data, as a restyled layer's, is uploaded again. - let buffers = |sb: &SceneBuffers| -> Vec<*const Owned> { + // The next scene sharing the layers' data and pictures (layers that look as they did) + // draws from the buffers and textures this one uploaded; new data, as a restyled layer's, + // is uploaded again. + let buffers = |sb: &SceneBuffers| -> Vec { sb.draws .iter() .flat_map(|d| match d { - SceneDraw::Mesh { vertices, indices, .. } => vec![Arc::as_ptr(vertices), Arc::as_ptr(indices)], - SceneDraw::Points { instances, .. } => vec![Arc::as_ptr(instances)], + SceneDraw::Mesh { vertices, indices, .. } => vec![Arc::as_ptr(vertices) as usize, Arc::as_ptr(indices) as usize], + SceneDraw::Points { instances, .. } => vec![Arc::as_ptr(instances) as usize], + SceneDraw::Image { texture, .. } => vec![Arc::as_ptr(texture) as usize], _ => vec![], }) .collect() @@ -1936,18 +2003,32 @@ mod tests { }; let last = SceneBuffers::from_scene(&rs.device, &rs.queue, &r, &copied, Camera::world(), [400.0, 300.0], 1.0).expect("fits"); let (was, now) = (buffers(&next), buffers(&last)); - assert!(was[0] != now[0] && was[1] != now[1] && was[2] == now[2], "only the mesh is uploaded again"); + assert!(was[0] != now[0] && was[1] != now[1] && was[2] == now[2] && was[3] == now[3], "only the mesh is uploaded again"); + // A picture placed at another opacity is the same texture; a new picture is uploaded. + let placed = GpuScene { + cmds: copied + .cmds + .iter() + .filter_map(|c| match c { + DrawCmd::Image { pixmap, .. } => Some(DrawCmd::Image { pixmap: pixmap.clone(), opacity: 0.4 }), + _ => None, + }) + .chain(std::iter::once(DrawCmd::Image { + pixmap: Arc::new(rustgis_engine::render::Pixmap::new(1, 1).expect("pixmap")), + opacity: 1.0, + })) + .collect(), + ..copied + }; + let again = SceneBuffers::from_scene(&rs.device, &rs.queue, &r, &placed, Camera::world(), [400.0, 300.0], 1.0).expect("fits"); + let now = buffers(&again); + assert_eq!(now.first(), was.get(3), "the same texture at another opacity"); + assert_ne!(now.get(1), was.get(3), "a new picture uploaded"); } - /// A command sharing `cmd`'s data, for a mesh or markers. + /// A command sharing `cmd`'s data. fn share(cmd: &DrawCmd) -> Option { - match cmd { - DrawCmd::Mesh { origin, vertices, indices } => { - Some(DrawCmd::Mesh { origin: *origin, vertices: vertices.clone(), indices: indices.clone() }) - } - DrawCmd::Points { origin, instances } => Some(DrawCmd::Points { origin: *origin, instances: instances.clone() }), - _ => None, - } + cmd.share() } // ---- CPU↔GPU pixel parity: render the same map through both backends and compare ---- diff --git a/crates/ui-egui/src/mapgpu.wgsl b/crates/ui-egui/src/mapgpu.wgsl index c4d7af0e6f..11ccaf0c75 100644 --- a/crates/ui-egui/src/mapgpu.wgsl +++ b/crates/ui-egui/src/mapgpu.wgsl @@ -246,9 +246,12 @@ fn vs_image(@builtin(vertex_index) vi: u32) -> ImgOut { @group(0) @binding(0) var t_img: texture_2d; @group(0) @binding(1) var s_img: sampler; +// The picture's opacity (x): a see-through layer drawn alone is placed at its own (#1057). +@group(1) @binding(1) var image_opacity: vec4f; + @fragment fn fs_image(in: ImgOut) -> @location(0) vec4f { - return textureSample(t_img, s_img, in.uv); + return textureSample(t_img, s_img, in.uv) * image_opacity.x; } // A cached image scene's pan/zoom changes only the sampled rectangle. The viewport stays