From c2a58c8c8c9951f1991b5b5481c1d48633294bce Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 10:15:41 -0600 Subject: [PATCH 1/4] feat(tiles): a tile layer can draw its pictures with nearest-neighbour resampling (#2804) Web tile layers (WMS, WMTS, XYZ, COG, picture archives) always blended their pictures when drawn at a size other than their own, which softens imagery zoomed past its resolution. They now take the Resampling choice raster layers have, Nearest Neighbor or Bilinear (the default, unchanged). It applies on every path a tile picture is drawn: the tiles crate's raster draw (which now also honours a style's raster-resampling: nearest), the reprojected and single-picture paths in render, and the GPU map's tile and live-tile samplers. map.addTiles and map.setTiles take `resampling`, map.tiles reports it, the layer's menu has a Resampling submenu, and the setting is saved only when it isn't the default. --- crates/engine/command-surface.txt | 4 +- crates/engine/src/cmd/geolibre.rs | 1 + crates/engine/src/cmd/tiles.rs | 73 +++++++++++++++++++- crates/map/src/tiles.rs | 14 ++++ crates/render/examples/tile_mesh_bench.rs | 1 + crates/render/src/gpu_scene.rs | 3 + crates/render/src/native_tiles.rs | 20 ++++-- crates/render/src/single_image.rs | 45 ++++++++++--- crates/render/src/tiles.rs | 2 + crates/tiles/src/cache.rs | 2 + crates/tiles/src/draw.rs | 44 ++++++++++-- crates/tiles/src/picture.rs | 2 + crates/tiles/src/pmtiles.rs | 1 + crates/tiles/src/shapes.rs | 1 + crates/tiles/src/source.rs | 22 ++++-- crates/tiles/src/style.rs | 6 ++ crates/ui-egui/src/mapgpu.rs | 82 ++++++++++++++++++----- crates/ui-egui/src/panes.rs | 14 ++++ crates/ui-egui/src/tilelayer.rs | 52 ++++++++------ 19 files changed, 325 insertions(+), 64 deletions(-) diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index a2d195a995..2a3dd53584 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -306,7 +306,7 @@ layout.seriesRefresh layout? layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? columns? textSize? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? map? scale? center? bearing? pitch? grid? extentIndicator? border? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? rows? background? locator.find locator? text limit? zoom? map.activate name -map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? +map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? map.basemap name keepTiles? color? map.bodies map.body name? basemap? @@ -352,7 +352,7 @@ map.selectTiles name? index? id? map.setBearing bearing by map.setPitch pitch by map.setScale scale -map.setTiles name? index? id? visible? opacity? blend? move? to? rename? bands? range? dequantize? legend? hiddenLayers? singleImage? tileSize? +map.setTiles name? index? id? visible? opacity? blend? resampling? move? to? rename? bands? range? dequantize? legend? hiddenLayers? singleImage? tileSize? map.terrain layer? tiles? encoding? exaggeration? block? water? off? map.thumbnail create? image? path? clear? map.tiles diff --git a/crates/engine/src/cmd/geolibre.rs b/crates/engine/src/cmd/geolibre.rs index 28034852c3..2bb29af13d 100644 --- a/crates/engine/src/cmd/geolibre.rs +++ b/crates/engine/src/cmd/geolibre.rs @@ -537,6 +537,7 @@ fn finish_archive(s: &mut Session, p: &Value, bytes: Vec) -> CmdResult { loaded.visible = t.visible; loaded.opacity = t.opacity; loaded.blend = t.blend; + loaded.resampling = t.resampling; loaded.name = t.name.clone(); *t = loaded; } diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index 1689e8ad16..febed28701 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -14,12 +14,12 @@ use crate::{CmdResult, CommandSpec as C, Session}; pub fn commands() -> Vec { vec![ C::new("map.addTiles", "Add Tile Layer", "Home › Add", add).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login"}"#, + r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "resampling"?: "nearest"|"bilinear" (picture tiles drawn at a size other than their own: each pixel a block, or blended, the default), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login"}"#, ), C::new("map.removeTiles", "Remove Tile Layer", "Home › Add", remove).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name"?: text, "index"?: number, "id"?: catalog id} (removes every tile layer when none is given)"#), C::new("map.setTiles", "Tile Layer Properties", "Home › Add", set).inputs(set_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"name"?: text | "index"?: number (0 = top) | "id"?: catalog id, "visible"?: bool, "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference", "move"?: "up"|"down"|"top"|"bottom" (past the next layer in the drawing order of all the map's layers, a feature or raster layer too), "to"?: number (its place in that order among the other layers, 0 = top; the Layers pane lists it), "rename"?: text, "bands"?: [red, green, blue] | [band] (a cloud-optimised GeoTIFF's bands shown, from 1; [] for its own), "range"?: [low, high] (the values shown from black to full colour; null: each band's 2nd–98th percentile), "dequantize"?: "aef" (AlphaEarth's quantised embeddings) | "none", "legend"?: as map.addTiles's, or null for none, "hiddenLayers"?: [source layer name] (vector tiles' source layers not drawn or identified, as map.tiles's sourceLayers names them; replaces the list, [] or null for none), "singleImage"?: bool (as map.addTiles's), "tileSize"?: 256|512|1024 (a WMS or map service asked for in Web Mercator: its tiles' size)}"#, + r#"{"name"?: text | "index"?: number (0 = top) | "id"?: catalog id, "visible"?: bool, "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference", "resampling"?: "nearest"|"bilinear" (how picture tiles are drawn at a size other than their own: each pixel a block, or blended, the default), "move"?: "up"|"down"|"top"|"bottom" (past the next layer in the drawing order of all the map's layers, a feature or raster layer too), "to"?: number (its place in that order among the other layers, 0 = top; the Layers pane lists it), "rename"?: text, "bands"?: [red, green, blue] | [band] (a cloud-optimised GeoTIFF's bands shown, from 1; [] for its own), "range"?: [low, high] (the values shown from black to full colour; null: each band's 2nd–98th percentile), "dequantize"?: "aef" (AlphaEarth's quantised embeddings) | "none", "legend"?: as map.addTiles's, or null for none, "hiddenLayers"?: [source layer name] (vector tiles' source layers not drawn or identified, as map.tiles's sourceLayers names them; replaces the list, [] or null for none), "singleImage"?: bool (as map.addTiles's), "tileSize"?: 256|512|1024 (a WMS or map service asked for in Web Mercator: its tiles' size)}"#, ), C::new("map.tiles", "Tile Layers", "Home › Add", |s, _| Ok(list(s, !s.policy_user()))).inputs(listing_inputs).roles(&[]).effects(crate::policy::Effects::NONE).view(), // As `layer.expand` for a layer's classes: what the pane shows, not an edit to undo. @@ -109,7 +109,7 @@ pub(crate) fn list(s: &Session, redact: bool) -> Value { .map(|(i, t)| { let url = shown(&t.url); let mut o = json!({"index": i, "name": t.name, "id": t.id, "kind": t.kind.code(), "url": url, "visible": t.visible, "error": t.error, - "opacity": t.opacity, "blend": t.blend.code(), "overlay": t.overlay, "attribution": t.attribution, "minZoom": t.min_zoom, "maxZoom": t.max_zoom}); + "opacity": t.opacity, "blend": t.blend.code(), "resampling": sampling_code(t.resampling), "overlay": t.overlay, "attribution": t.attribution, "minZoom": t.min_zoom, "maxZoom": t.max_zoom}); // Its place in the drawing order: over this map layer, or (none) under them all. o["over"] = json!(s.map().tile_slot(t).and_then(|id| s.map().layer(id)).map(|l| l.name.clone())); // A layer its service draws on request: one picture of the view, or tiles of a @@ -227,6 +227,12 @@ pub(crate) fn add_with_metadata_wait(s: &mut Session, p: &Value, metadata_wait: if let Some(m) = blend(p)? { t.blend = m; } + if let Some(r) = resampling(p)? { + if matches!(kind, TileKind::Vector | TileKind::Style) { + return Err(NOT_PICTURES.into()); + } + t.resampling = r; + } // Vector tiles' layer names (an OGC API collection's), each drawn in a colour of its own. if let Some(names) = p.get("layers").and_then(Value::as_array) { t.layers = names.iter().filter_map(Value::as_str).map(str::to_string).collect(); @@ -874,9 +880,34 @@ fn hidden_layers(p: &Value) -> Result>, String> { } } +/// A resampling as the `resampling` parameter names it. +fn sampling_code(r: rustgis_map::raster::Resampling) -> &'static str { + match r { + rustgis_map::raster::Resampling::Nearest => "nearest", + rustgis_map::raster::Resampling::Bilinear => "bilinear", + } +} + +/// Refused for a layer that draws vector shapes: there are no pictures to resample. +const NOT_PICTURES: &str = "resampling is for a layer of picture tiles, not vector tiles or a style"; + +/// The `resampling` parameter: how the layer's pictures are drawn at a size other than their own. +fn resampling(p: &Value) -> Result, String> { + match p.get("resampling") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(name)) => Some(name.trim()) + .filter(|n| !n.is_empty()) + .and_then(rustgis_map::raster::Resampling::from_name) + .map(Some) + .ok_or_else(|| format!("unknown resampling '{name}': nearest or bilinear")), + Some(_) => Err("resampling is \"nearest\" or \"bilinear\"".into()), + } +} + fn set(s: &mut Session, p: &Value) -> CmdResult { let i = find(s, p)?.ok_or("name or index is required")?; let mode = blend(p)?; + let sampling = resampling(p)?; let look = cog_look(p)?; // Before the legends are prepared: a refused name must leave no login activated. let rename = ps(p, "rename") @@ -907,6 +938,9 @@ fn set(s: &mut Session, p: &Value) -> CmdResult { if hidden.as_ref().is_some_and(|h| !h.is_empty()) && matches!(t.kind, TileKind::Raster | TileKind::Cog) { return Err("hiddenLayers is for vector tiles' source layers".into()); } + if sampling.is_some() && matches!(t.kind, TileKind::Vector | TileKind::Style) { + return Err(NOT_PICTURES.into()); + } let single = b(p, "singleImage"); if single == Some(true) && !t.on_request() { return Err(NOT_ON_REQUEST.into()); @@ -954,6 +988,9 @@ fn set(s: &mut Session, p: &Value) -> CmdResult { if let Some(m) = mode { t.blend = m; } + if let Some(r) = sampling { + t.resampling = r; + } if let Some(r) = rename { t.name = r; } @@ -1062,6 +1099,36 @@ mod tests { assert_eq!(text.matches("\"blend\"").count(), 1, "{text}"); } + #[test] + fn picture_tiles_can_be_drawn_crisp_and_vector_tiles_refuse_it() { + use rustgis_map::raster::Resampling; + let mut s = Session::new(Project::default()); + let wms = json!({"url": "https://wms.example.com/{z}/{x}/{y}.png", "name": "Imagery", "resampling": "nearest"}); + assert!(s.run("map.addTiles", &wms).is_ok()); + assert!(s.run("map.addTiles", &json!({"url": "https://b.example.com/{z}/{x}/{y}.png", "name": "Base"})).is_ok()); + let of = |s: &Session, name: &str| s.map().tiles.iter().find(|t| t.name == name).map(|t| t.resampling); + assert_eq!(of(&s, "Imagery"), Some(Resampling::Nearest)); + // Blended as before unless asked. + assert_eq!(of(&s, "Base"), Some(Resampling::Bilinear)); + let listed = s.run("map.tiles", &json!({})).unwrap(); + let base = listed.as_array().and_then(|l| l.iter().find(|t| t["name"] == "Base")).cloned().unwrap_or_default(); + assert_eq!(base["resampling"], "bilinear"); + assert!(s.run("map.setTiles", &json!({"name": "Base", "resampling": "nearest"})).is_ok()); + assert_eq!(of(&s, "Base"), Some(Resampling::Nearest)); + assert!(s.run("edit.undo", &json!({})).is_ok()); + assert_eq!(of(&s, "Base"), Some(Resampling::Bilinear)); + assert!(s.run("map.setTiles", &json!({"name": "Base", "resampling": "cubic"})).is_err()); + assert!(s.run("map.setTiles", &json!({"name": "Base", "resampling": " "})).is_err()); + let vector = json!({"url": "https://v.example.com/{z}/{x}/{y}.pbf", "kind": "vector", "name": "Roads"}); + assert!(s.run("map.addTiles", &vector).is_ok()); + assert!(s.run("map.setTiles", &json!({"name": "Roads", "resampling": "nearest"})).is_err()); + // Saved with the project; a blended layer saves none. + let text = serde_json::to_string(&s.project).unwrap(); + let p = Project::from_json(&text).unwrap(); + assert_eq!(p.map().tiles.iter().find(|t| t.name == "Imagery").map(|t| t.resampling), Some(Resampling::Nearest)); + assert_eq!(text.matches("\"resampling\"").count(), 1, "{text}"); + } + /// A refused legend's address is shortened for the error without cutting its omission /// marker in half: the address before it is cut instead, and the query stays out. #[test] diff --git a/crates/map/src/tiles.rs b/crates/map/src/tiles.rs index 47f26e899e..5dc39d8391 100644 --- a/crates/map/src/tiles.rs +++ b/crates/map/src/tiles.rs @@ -134,6 +134,10 @@ pub struct TileLayer { /// hillshade). #[serde(default, skip_serializing_if = "is_normal")] pub blend: crate::effects::Blend, + /// How its pictures are drawn at a size other than their own: smooth (bilinear), as every + /// tile layer was before, or crisp, each of the picture's pixels a block (#2804). + #[serde(default = "smooth", skip_serializing_if = "is_smooth")] + pub resampling: crate::raster::Resampling, /// The catalog entry it came from (`osm`, `esri-imagery`), when it came from one. #[serde(default, skip_serializing_if = "String::is_empty")] pub id: String, @@ -335,6 +339,14 @@ fn one() -> f32 { fn is_false(b: &bool) -> bool { !*b } +fn smooth() -> crate::raster::Resampling { + crate::raster::Resampling::Bilinear +} + +fn is_smooth(r: &crate::raster::Resampling) -> bool { + *r == smooth() +} + fn is_normal(b: &crate::effects::Blend) -> bool { *b == crate::effects::Blend::Normal } @@ -407,6 +419,7 @@ impl TileLayer { overlay: false, over: None, blend: crate::effects::Blend::Normal, + resampling: smooth(), id: String::new(), layers: Vec::new(), style_layers: String::new(), @@ -702,6 +715,7 @@ impl TileLayer { overlay: _, over: _, blend: _, + resampling: _, id: _, layers: _, style_layers: _, diff --git a/crates/render/examples/tile_mesh_bench.rs b/crates/render/examples/tile_mesh_bench.rs index a75f3c1f5a..f11f1adf02 100644 --- a/crates/render/examples/tile_mesh_bench.rs +++ b/crates/render/examples/tile_mesh_bench.rs @@ -20,6 +20,7 @@ fn main() { layers: Vec::new(), style_layers: String::new(), hidden_layers: Vec::new(), + nearest: false, }; for (name, lon, lat, zoom) in [("Manhattan z14.3", -73.98, 40.75, 14.3f64), ("Manhattan z12.3", -73.98, 40.75, 12.3), ("Paris z15.3", 2.35, 48.86, 15.3)] diff --git a/crates/render/src/gpu_scene.rs b/crates/render/src/gpu_scene.rs index 967846462a..722754338d 100644 --- a/crates/render/src/gpu_scene.rs +++ b/crates/render/src/gpu_scene.rs @@ -177,6 +177,9 @@ pub struct TileQuad { /// The part of the picture in that square: left, top, right, bottom (0..1, top down). pub uv: [f32; 4], pub opacity: f32, + /// Each of the picture's pixels a block where it's drawn larger or smaller than its own size, + /// rather than blended (the layer's resampling, #2804). + pub nearest: bool, } impl TileQuad { diff --git a/crates/render/src/native_tiles.rs b/crates/render/src/native_tiles.rs index e514469823..576c4b350a 100644 --- a/crates/render/src/native_tiles.rs +++ b/crates/render/src/native_tiles.rs @@ -189,6 +189,7 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat Some(((x * k) as f32, (y * k) as f32)) }; let opacity = t.opacity.clamp(0.0, 1.0); + let quality = filter(t); let (mut pending, mut error) = (false, None); for p in pictures { // A WMTS tile past the service's coverage is routine; a WMS picture (any area asked) isn't. @@ -196,7 +197,7 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat match state { State::Ready(payload) => { if let Payload::Image(img) = &*payload { - paint(pm, img, p.area, p.area, opacity, &place); + paint(pm, img, p.area, p.area, opacity, quality, &place); } } State::Pending => { @@ -209,7 +210,7 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat if let Some((payload, at)) = stand_in && let Payload::Image(img) = &*payload { - paint(pm, img, at, p.area, opacity, &place); + paint(pm, img, at, p.area, opacity, quality, &place); } } // A WMTS tile the service doesn't have (past its coverage) is left clear, as the warped @@ -292,9 +293,19 @@ pub(crate) fn paint( area: [f64; 4], clip: [f64; 4], opacity: f32, + quality: FilterQuality, place: &dyn Fn(Coord) -> Option<(f32, f32)>, ) { - paint_blended(pm, img, area, clip, opacity, tiny_skia::BlendMode::SourceOver, place); + paint_blended(pm, img, area, clip, opacity, tiny_skia::BlendMode::SourceOver, quality, place); +} + +/// How a tile layer's pictures are sampled where they're drawn at another size: blended, or +/// each pixel a block (#2804). +pub(crate) fn filter(t: &rustgis_map::TileLayer) -> FilterQuality { + match t.resampling { + rustgis_map::raster::Resampling::Nearest => FilterQuality::Nearest, + rustgis_map::raster::Resampling::Bilinear => FilterQuality::Bilinear, + } } /// [`paint`], combined with what is beneath by `blend`. @@ -305,6 +316,7 @@ pub(crate) fn paint_blended( clip: [f64; 4], opacity: f32, blend: tiny_skia::BlendMode, + quality: FilterQuality, place: &dyn Fn(Coord) -> Option<(f32, f32)>, ) { let corner = |x: f64, y: f64| place(Coord::new(x, y)); @@ -322,7 +334,7 @@ pub(crate) fn paint_blended( } path.close(); let Some(path) = path.finish() else { return }; - let shader = Pattern::new(img.as_ref(), SpreadMode::Pad, FilterQuality::Bilinear, opacity, transform); + let shader = Pattern::new(img.as_ref(), SpreadMode::Pad, quality, opacity, transform); // Without anti-aliasing, neighbouring pictures meet without a seam. let paint = Paint { shader, anti_alias: false, blend_mode: blend, ..Paint::default() }; pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None); diff --git a/crates/render/src/single_image.rs b/crates/render/src/single_image.rs index 64de99558f..5de9305e34 100644 --- a/crates/render/src/single_image.rs +++ b/crates/render/src/single_image.rs @@ -359,14 +359,15 @@ pub(crate) fn draw(pm: &mut Pixmap, req: &Request, t: &TileLayer, view: &View, f let key = format!("{} {}", req.system.epsg, req.base); let opacity = t.opacity.clamp(0.0, 1.0); let blend = crate::blend_mode(t.blend); + let quality = crate::native_tiles::filter(t); // In another system than the map's, warped into place piece by piece (one affine placing // would leave it off where the systems bend apart). let warped = req.warp; let paint = |pm: &mut Pixmap, img: &Pixmap, at: [f64; 4]| { if warped { - paint_warped(pm, img, at, opacity, blend, &place); + paint_warped(pm, img, at, opacity, blend, quality, &place); } else { - crate::native_tiles::paint_blended(pm, img, at, at, opacity, blend, &place); + crate::native_tiles::paint_blended(pm, img, at, at, opacity, blend, quality, &place); } }; // The units a pixel of a picture at a logical pixel's detail, as on a standard screen. @@ -562,9 +563,10 @@ fn paint_warped( at: [f64; 4], opacity: f32, blend: tiny_skia::BlendMode, + quality: tiny_skia::FilterQuality, place: &dyn Fn(Coord) -> Option<(f32, f32)>, ) { - use tiny_skia::{FillRule, FilterQuality, Paint, PathBuilder, Pattern, SpreadMode, Transform}; + use tiny_skia::{FillRule, Paint, PathBuilder, Pattern, SpreadMode, Transform}; let (iw, ih) = (img.width() as f32, img.height() as f32); if iw <= 0.0 || ih <= 0.0 { return; @@ -618,7 +620,7 @@ fn paint_warped( path.line_to(d[2].0, d[2].1); path.close(); let Some(path) = path.finish() else { return }; - let shader = Pattern::new(img.as_ref(), SpreadMode::Pad, FilterQuality::Bilinear, opacity, transform); + let shader = Pattern::new(img.as_ref(), SpreadMode::Pad, quality, opacity, transform); // Without anti-aliasing, neighbouring triangles meet without a seam. let paint = Paint { shader, anti_alias: false, blend_mode: blend, ..Paint::default() }; pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None); @@ -654,8 +656,17 @@ mod tests { let at = [0.0, 0.0, 64.0, 64.0]; let shift = |c: Coord| Some(((c.x + 10.0) as f32, (74.0 - c.y) as f32)); let (mut a, mut b) = (Pixmap::new(100, 100).unwrap(), Pixmap::new(100, 100).unwrap()); - paint_warped(&mut a, &img, at, 1.0, tiny_skia::BlendMode::SourceOver, &shift); - crate::native_tiles::paint_blended(&mut b, &img, at, at, 1.0, tiny_skia::BlendMode::SourceOver, &shift); + paint_warped(&mut a, &img, at, 1.0, tiny_skia::BlendMode::SourceOver, tiny_skia::FilterQuality::Bilinear, &shift); + crate::native_tiles::paint_blended( + &mut b, + &img, + at, + at, + 1.0, + tiny_skia::BlendMode::SourceOver, + tiny_skia::FilterQuality::Bilinear, + &shift, + ); let differ = a.pixels().iter().zip(b.pixels()).filter(|(p, q)| p != q).count(); assert!(differ < 64, "{differ} pixels differ from one quad"); // Bent with a cross term (x pushed right by x × y), so a cell's fourth corner is off any @@ -668,7 +679,15 @@ mod tests { } let bend = |c: Coord| Some(((c.x + 10.0 + c.x * c.y / 64.0) as f32, (266.0 - c.y) as f32)); let mut pm = Pixmap::new(1300, 280).unwrap(); - paint_warped(&mut pm, &ramp, [0.0, 0.0, 256.0, 256.0], 1.0, tiny_skia::BlendMode::SourceOver, &bend); + paint_warped( + &mut pm, + &ramp, + [0.0, 0.0, 256.0, 256.0], + 1.0, + tiny_skia::BlendMode::SourceOver, + tiny_skia::FilterQuality::Bilinear, + &bend, + ); let (mut worst, mut seen) = (0.0f64, 0); for py in 0..pm.height() { for px in 0..pm.width() { @@ -689,12 +708,20 @@ mod tests { // straddling it aren't drawn, so nothing is smeared between the two parts. let wrap = |c: Coord| Some(((if c.x > 200.0 { c.x + 1000.0 } else { c.x }) as f32, (256.0 - c.y) as f32)); let mut pm = Pixmap::new(1400, 256).unwrap(); - paint_warped(&mut pm, &ramp, [0.0, 0.0, 256.0, 256.0], 1.0, tiny_skia::BlendMode::SourceOver, &wrap); + paint_warped( + &mut pm, + &ramp, + [0.0, 0.0, 256.0, 256.0], + 1.0, + tiny_skia::BlendMode::SourceOver, + tiny_skia::FilterQuality::Bilinear, + &wrap, + ); assert!((0..256).all(|y| pm.pixel(600, y).unwrap().alpha() == 0), "smeared across the wrap"); assert!(pm.pixel(100, 128).unwrap().alpha() == 255 && pm.pixel(1240, 128).unwrap().alpha() == 255); // Nothing drawn where `place` can't put the picture. let mut none = Pixmap::new(10, 10).unwrap(); - paint_warped(&mut none, &img, at, 1.0, tiny_skia::BlendMode::SourceOver, &|_| None); + paint_warped(&mut none, &img, at, 1.0, tiny_skia::BlendMode::SourceOver, tiny_skia::FilterQuality::Bilinear, &|_| None); assert!(none.pixels().iter().all(|p| p.alpha() == 0)); } diff --git a/crates/render/src/tiles.rs b/crates/render/src/tiles.rs index 5f5fc24dae..b16101de35 100644 --- a/crates/render/src/tiles.rs +++ b/crates/render/src/tiles.rs @@ -168,6 +168,7 @@ pub fn spec(t: &TileLayer) -> Spec { layers: t.layers.clone(), style_layers: t.style_layers.clone(), hidden_layers: t.hidden_layers.clone(), + nearest: t.resampling == rustgis_map::raster::Resampling::Nearest, } } @@ -628,6 +629,7 @@ fn quad(p: &rustgis_tiles::Placement, origin: [f64; 2]) -> TileQuad { ((p.at.max_y - c.min_y) / h) as f32, ], opacity: p.opacity, + nearest: p.nearest, } } diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index c83f7551be..28d7e8ff51 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -6203,6 +6203,7 @@ Connection: close layers: vec![], style_layers: String::new(), hidden_layers: vec![], + nearest: false, }; let mut resolved = None; for _ in 0..200 { @@ -6432,6 +6433,7 @@ Connection: close layers: Vec::new(), style_layers: String::new(), hidden_layers: Vec::new(), + nearest: false, }; let Resolve::Ready(resolved) = crate::source::resolve(&spec) else { panic!("the cached document must resolve") }; if kind == Kind::Style { diff --git a/crates/tiles/src/draw.rs b/crates/tiles/src/draw.rs index ca80ad0c3c..22bf3a39d2 100644 --- a/crates/tiles/src/draw.rs +++ b/crates/tiles/src/draw.rs @@ -174,7 +174,7 @@ pub fn draw(pm: &mut Pixmap, spec: &Spec, opacity: f32, frame: &Frame, labels: b // a map moving across them only puts them in place. if let Some(pictures) = crate::picture::cover(&r, frame, &frame.extent(w, h), None, &mut out.pending, &mut out.error) { for it in &pictures { - draw_raster(pm, it, frame, opacity); + draw_raster(pm, it, frame, opacity, false); } if labels { draw_layers(None, (w, h), &frame.extent(w, h), &r, frame, Pass::Labels, &mut out); @@ -300,8 +300,9 @@ pub(crate) fn draw_layers( LayerKind::Raster => { let Some(t) = target.as_deref_mut() else { continue }; let o = layer.raster_opacity(zoom); + let nearest = layer.raster_resampling_nearest(zoom); for it in list { - draw_raster(t, it, frame, o); + draw_raster(t, it, frame, o, nearest); } } LayerKind::Fill | LayerKind::FillExtrusion | LayerKind::Line | LayerKind::Circle => { @@ -355,6 +356,8 @@ pub struct Placement { /// for. pub clip: Extent, pub opacity: f32, + /// Each of its pixels a block where drawn at another size (`raster-resampling: nearest`). + pub nearest: bool, } /// A tile layer as placed tiles, bottom first, rather than drawn into a pixmap. @@ -419,7 +422,8 @@ fn place_as( pictures.then(|| crate::picture::cover(&r, frame, view, Some(reach), &mut out.pending, &mut out.error)).flatten() { let opacity = opacity.clamp(0.0, 1.0); - out.tiles = pictures.into_iter().map(|it| Placement { picture: it.payload, at: it.at, clip: it.clip, opacity }).collect(); + out.tiles = + pictures.into_iter().map(|it| Placement { picture: it.payload, at: it.at, clip: it.clip, opacity, nearest: false }).collect(); if let Some(size) = labels { let mut d = Drawn::default(); draw_layers(None, size, &frame.extent(size.0, size.1), &r, frame, Pass::Labels, &mut d); @@ -447,9 +451,10 @@ fn place_as( items.insert(src_id, list.items); } let o = (layer.raster_opacity(zoom) * opacity).clamp(0.0, 1.0); + let nearest = layer.raster_resampling_nearest(zoom); for it in items.get(src_id).into_iter().flatten() { if matches!(*it.payload, Payload::Image(_)) { - out.tiles.push(Placement { picture: it.payload.clone(), at: it.at, clip: it.clip, opacity: o }); + out.tiles.push(Placement { picture: it.payload.clone(), at: it.at, clip: it.clip, opacity: o, nearest }); } } } @@ -808,7 +813,9 @@ pub(crate) fn clip_rect(it: &Item, frame: &Frame) -> Option { Rect::from_ltrb(x0.round(), y0.round(), x1.round(), y1.round()) } -fn draw_raster(pm: &mut Pixmap, it: &Item, frame: &Frame, opacity: f32) { +/// Draws a picture tile in place: its pixels blended where it is drawn at another size, or each +/// a block when `nearest`. +fn draw_raster(pm: &mut Pixmap, it: &Item, frame: &Frame, opacity: f32, nearest: bool) { let Payload::Image(img) = &*it.payload else { return }; let Some(clip) = clip_rect(it, frame) else { return }; let (x0, y0) = frame.px(it.at.min_x, it.at.max_y); @@ -821,7 +828,7 @@ fn draw_raster(pm: &mut Pixmap, it: &Item, frame: &Frame, opacity: f32) { copy_over(pm, img, clip, (x0, y0), k, opacity); return; } - let quality = FilterQuality::Bilinear; + let quality = if nearest { FilterQuality::Nearest } else { FilterQuality::Bilinear }; let shader = Pattern::new(img.as_ref(), SpreadMode::Pad, quality, opacity.clamp(0.0, 1.0), Transform::from_row(k, 0.0, 0.0, k, x0, y0)); // Without anti-aliasing, neighbouring tiles meet without a seam. let paint = Paint { shader, anti_alias: false, ..Paint::default() }; @@ -1583,6 +1590,7 @@ pub(crate) mod tests { layers: Vec::new(), style_layers: String::new(), hidden_layers: Vec::new(), + nearest: false, }; // Zoom 0: one tile over the world, 4096 units across it. let half = 20_037_508.342_789_244; @@ -1700,6 +1708,7 @@ pub(crate) mod tests { layers: Vec::new(), style_layers: String::new(), hidden_layers: Vec::new(), + nearest: false, }; let half = 20_037_508.342_789_244; // Just inside zoom 1 (the archive has no other). @@ -1822,6 +1831,27 @@ pub(crate) mod tests { assert!(clip_line_along(&[(f32::NAN, 0.0), (1.0, 1.0)], [0.0, 0.0, 10.0, 10.0]).len() <= 1); } + #[test] + fn a_picture_drawn_larger_is_blended_unless_asked_for_its_pixels() { + // Two pixels, black and white, drawn 16 times their size. + let mut img = Pixmap::new(2, 1).unwrap(); + img.pixels_mut()[0] = tiny_skia::ColorU8::from_rgba(0, 0, 0, 255).premultiply(); + img.pixels_mut()[1] = tiny_skia::ColorU8::from_rgba(255, 255, 255, 255).premultiply(); + let id = TileId { z: 0, x: 0, y: 0 }; + let it = Item { payload: Arc::new(Payload::Image(img)), at: id.extent(), z: 0, clip: id.extent() }; + let half = crate::template::HALF_WORLD; + let frame = Frame { left: -half, top: half, m_per_px: 2.0 * half / 32.0, ppp: 1.0 }; + // Each pixel's shades along the middle row: two, or a ramp between them. + let shades = |nearest: bool| { + let mut pm = Pixmap::new(32, 16).unwrap(); + draw_raster(&mut pm, &it, &frame, 1.0, nearest); + let row: std::collections::BTreeSet = (0..32).filter_map(|x| pm.pixel(x, 8)).map(|p| p.red()).collect(); + row.len() + }; + assert_eq!(shades(true), 2); + assert!(shades(false) > 2); + } + #[test] fn copies_pictures_as_a_pattern_draws_them() { let mut img = Pixmap::new(8, 8).unwrap(); @@ -1843,7 +1873,7 @@ pub(crate) mod tests { let mut copied = Pixmap::new(12, 12).unwrap(); copied.fill(tiny_skia::Color::from_rgba8(10, 200, 30, 255)); let mut painted = copied.clone(); - draw_raster(&mut copied, &it, &frame, opacity); + draw_raster(&mut copied, &it, &frame, opacity, false); // As a pattern fill would. let paint = Paint { shader: Pattern::new(img.as_ref(), SpreadMode::Pad, FilterQuality::Nearest, opacity, Transform::from_translate(2.4, 1.6)), diff --git a/crates/tiles/src/picture.rs b/crates/tiles/src/picture.rs index 190ed01a2a..441a0b3987 100644 --- a/crates/tiles/src/picture.rs +++ b/crates/tiles/src/picture.rs @@ -571,6 +571,7 @@ mod tests { layers: Vec::new(), style_layers: String::new(), hidden_layers: Vec::new(), + nearest: false, }; let f = frame(2.999, 1.0); let view = f.extent(64, 64); @@ -946,6 +947,7 @@ mod tests { layers: Vec::new(), style_layers: style.into(), hidden_layers: Vec::new(), + nearest: false, }; (spec, dir) } diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index 7de3a9ca0d..f058827d3e 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -2039,6 +2039,7 @@ pub(crate) mod tests { layers: Vec::new(), style_layers: String::new(), hidden_layers: Vec::new(), + nearest: false, }; let mut resolved = crate::source::resolve(&spec); for _ in 0..200 { diff --git a/crates/tiles/src/shapes.rs b/crates/tiles/src/shapes.rs index ff779608e9..fb5eefa7d1 100644 --- a/crates/tiles/src/shapes.rs +++ b/crates/tiles/src/shapes.rs @@ -468,6 +468,7 @@ mod tests { layers: Vec::new(), style_layers: style.into(), hidden_layers: Vec::new(), + nearest: false, }; (spec, dir) } diff --git a/crates/tiles/src/source.rs b/crates/tiles/src/source.rs index 611d2643eb..8af8e6282c 100644 --- a/crates/tiles/src/source.rs +++ b/crates/tiles/src/source.rs @@ -50,12 +50,15 @@ pub struct Spec { /// Source layers left out (`roads`, `pois`): the style layers drawing them are dropped, so /// they neither draw nor are picked. pub hidden_layers: Vec, + /// Picture tiles drawn at a size other than their own keep each pixel a block + /// (`raster-resampling: nearest`) instead of blending them (#2804). + pub nearest: bool, } impl Spec { fn key(&self) -> String { format!( - "{:?}|{}:{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", + "{:?}|{}:{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", self.kind, self.url.len(), self.url, @@ -68,7 +71,8 @@ impl Spec { // Each name with its length, so ["a,b"] and ["a", "b"] differ. self.layers.iter().map(|l| format!("{}:{l}", l.len())).collect::(), self.style_layers, - self.hidden_layers.iter().map(|l| format!("{}:{l}", l.len())).collect::() + self.hidden_layers.iter().map(|l| format!("{}:{l}", l.len())).collect::(), + self.nearest ) } } @@ -609,10 +613,19 @@ fn raster_style(spec: &Spec) -> Value { "type": "raster", "tiles": templates(spec), "tileSize": spec.tile_size, "minzoom": spec.min_zoom, "maxzoom": spec.max_zoom, }}, - "layers": [{"id": "raster", "type": "raster", "source": "raster"}], + "layers": [raster_layer(spec)], }) } +/// The one layer of a style drawing picture tiles, crisp when the spec asks. +fn raster_layer(spec: &Spec) -> Value { + let mut layer = json!({"id": "raster", "type": "raster", "source": "raster"}); + if spec.nearest { + layer["paint"] = json!({"raster-resampling": "nearest"}); + } + layer +} + /// A tile archive (PMTiles or MBTiles), as far as styling it goes. struct Archive { /// The template of its tile addresses. @@ -639,7 +652,7 @@ fn archive_style(spec: &Spec, info: Archive) -> Option { "type": "raster", "tiles": tiles, "tileSize": spec.tile_size, "minzoom": minzoom, "maxzoom": maxzoom, "attribution": attribution, }}, - "layers": [{"id": "raster", "type": "raster", "source": "raster"}], + "layers": [raster_layer(spec)], })); } let source = json!({"type": "vector", "tiles": tiles, "minzoom": minzoom, "maxzoom": maxzoom, "attribution": attribution}); @@ -852,6 +865,7 @@ mod tests { layers: Vec::new(), style_layers: String::new(), hidden_layers: Vec::new(), + nearest: false, } } diff --git a/crates/tiles/src/style.rs b/crates/tiles/src/style.rs index 6089a6bd4c..32679cfd67 100644 --- a/crates/tiles/src/style.rs +++ b/crates/tiles/src/style.rs @@ -1865,6 +1865,12 @@ impl StyleLayer { [lo, MAX_STYLE_ZOOM].into_iter().chain(grid).chain(named).filter(shown).any(|z| expr.elevation_ramp(z).is_none()) } + /// Whether `raster-resampling` is `nearest` (default `linear`): a raster layer's tile pictures + /// drawn at a size other than their own keep each pixel a block rather than blending them. + pub fn raster_resampling_nearest(&self, zoom: f32) -> bool { + self.pval("raster-resampling", &FeatureCtx::zoom_only(zoom)).as_str() == Some("nearest") + } + /// `color-relief-opacity` (default 1). pub fn color_relief_opacity(&self, zoom: f32) -> f32 { self.opacity("color-relief-opacity", &FeatureCtx::zoom_only(zoom)) diff --git a/crates/ui-egui/src/mapgpu.rs b/crates/ui-egui/src/mapgpu.rs index 420900e882..f4afba7528 100644 --- a/crates/ui-egui/src/mapgpu.rs +++ b/crates/ui-egui/src/mapgpu.rs @@ -260,6 +260,8 @@ pub(crate) struct GpuMapRenderer { blit_layout: wgpu::BindGroupLayout, templates: wgpu::Buffer, sampler: wgpu::Sampler, + /// Each pixel a block, for tile layers set to nearest-neighbour resampling (#2804). + nearest_sampler: wgpu::Sampler, /// MSAA sample count of the offscreen scene target. samples: u32, /// The tile pictures uploaded so far, kept across scenes. @@ -353,6 +355,12 @@ impl GpuMapRenderer { min_filter: wgpu::FilterMode::Linear, ..Default::default() }); + let nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("mapgpu_image_nearest"), + mag_filter: wgpu::FilterMode::Nearest, + min_filter: wgpu::FilterMode::Nearest, + ..Default::default() + }); let pipeline = |label: &str, vs: &str, fs: &str, @@ -555,6 +563,7 @@ impl GpuMapRenderer { blit_layout, templates, sampler, + nearest_sampler, samples, tile_textures: Default::default(), tile_meshes: Default::default(), @@ -671,8 +680,8 @@ const KEPT_TILE_BYTES: u64 = 64 << 20; struct TileTextures { /// By the picture's address, with the picture itself held weakly: the tile cache keeps the /// picture alive, and once it lets go the texture goes too (the weak reference keeps the - /// address from being reused until then). - by_picture: std::collections::HashMap, + /// address from being reused until then), and whether it's sampled nearest. + by_picture: std::collections::HashMap<(usize, bool), TileTexture>, /// Counts scenes: when each texture was last drawn. scene: u64, } @@ -695,7 +704,7 @@ impl TileTextures { r: &GpuMapRenderer, q: &TileQuad, ) -> Option<(wgpu::BindGroup, Arc>)> { - let key = Arc::as_ptr(&q.picture) as usize; + let key = (Arc::as_ptr(&q.picture) as usize, q.nearest); if let Some(t) = self.by_picture.get_mut(&key) && t.picture.upgrade().is_some_and(|p| Arc::ptr_eq(&p, &q.picture)) { @@ -734,7 +743,10 @@ impl TileTextures { layout: &r.image_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&r.sampler) }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(if q.nearest { &r.nearest_sampler } else { &r.sampler }), + }, ], }); let texture = Arc::new(texture); @@ -753,7 +765,7 @@ impl TileTextures { /// [`KEPT_TILE_BYTES`] those unused longest, but never one the scene just drew. fn end_scene(&mut self) { self.by_picture.retain(|_, t| t.picture.strong_count() > 0); - let mut old: Vec<(u64, u64, usize)> = + let mut old: Vec<(u64, u64, (usize, bool))> = self.by_picture.iter().filter(|(_, t)| t.used != self.scene).map(|(k, t)| (t.used, t.bytes, *k)).collect(); if old.iter().map(|o| o.1).sum::() > KEPT_TILE_BYTES { old.sort_unstable_by_key(|o| std::cmp::Reverse(o.0)); @@ -2587,25 +2599,39 @@ mod tests { return; } let mut png = std::io::Cursor::new(Vec::new()); - let tile = image::RgbaImage::from_fn(256, 256, |x, y| image::Rgba([40 + (x / 2) as u8, 60 + (y / 2) as u8, 140, 255])); + // Blocks of 8 pixels, light and dark: drawn larger, sharp edges or blended ones. + let blocks = url.contains("/blocks/"); + let tile = image::RgbaImage::from_fn(256, 256, |x, y| match blocks { + true if (x / 8 + y / 8) % 2 == 0 => image::Rgba([230, 220, 90, 255]), + true => image::Rgba([30, 60, 140, 255]), + false => image::Rgba([40 + (x / 2) as u8, 60 + (y / 2) as u8, 140, 255]), + }); match tile.write_to(&mut png, image::ImageFormat::Png) { Ok(()) => done(Ok(png.into_inner())), Err(e) => done(Err(e.to_string())), } }); - let build = |opacity: f32| { + // `nearest`: tiles of blocks no finer than zoom 2, drawn about three times their size, + // each pixel a block (#2804). + let build = |opacity: f32, nearest: bool| { move || { let mut m = Map::new("Map"); m.graticule = false; - let mut t = TileLayer::new("Tiles", TileKind::Raster, "https://parity.test/{z}/{x}/{y}.png"); + let url = if nearest { "https://parity.test/blocks/{z}/{x}/{y}.png" } else { "https://parity.test/{z}/{x}/{y}.png" }; + let mut t = TileLayer::new("Tiles", TileKind::Raster, url); t.opacity = opacity; + if nearest { + t.max_zoom = 2; + t.resampling = rustgis_engine::map::raster::Resampling::Nearest; + } m.tiles.push(t); m } }; let center = lonlat_to_merc(Coord::new(12.3, 45.6)); // Zoom 4 at its own size, and zoom 3 drawn between levels. - for (res, opacity) in [(9783.939620500, 1.0), (13_000.0, 1.0), (13_000.0, 0.6)] { + for (res, opacity, nearest) in [(9783.939620500, 1.0, false), (13_000.0, 1.0, false), (13_000.0, 0.6, false), (13_000.0, 1.0, true)] + { let view = View { width: 320.0, height: 200.0, @@ -2613,8 +2639,13 @@ mod tests { camera: Camera { center, res, bearing: 0.0, pitch: 0.0 }, sky: false, }; - let mut m = build(opacity)(); - render::render_png(&mut m, &view).expect("tiles fetched"); + let mut m = build(opacity, nearest)(); + let png = render::render_png(&mut m, &view).expect("tiles fetched"); + if nearest { + let mut smooth = build(opacity, nearest)(); + smooth.tiles[0].resampling = rustgis_engine::map::raster::Resampling::Bilinear; + assert_ne!(png, render::render_png(&mut smooth, &view).expect("tiles fetched"), "nearest draws as bilinear"); + } let Some(RenderOutput::Gpu(scene)) = render::render_backend(&mut m, &view, Backend::Gpu) else { panic!("gpu scene") }; assert!(!scene.cmds.iter().any(|c| matches!(c, DrawCmd::Image { .. })), "no picture of the view at {res}"); assert!(scene.cmds.iter().any(|c| matches!(c, DrawCmd::Tiles { .. })), "tiles at {res}"); @@ -2622,7 +2653,7 @@ mod tests { let Some(RenderOutput::Gpu(scene)) = render::render_backend(&mut m, &view, Backend::GpuLive) else { panic!("gpu scene") }; assert!(scene.cmds.iter().any(|c| matches!(c, DrawCmd::LiveTiles { .. })), "live tiles at {res}"); assert!(!scene.cmds.iter().any(|c| matches!(c, DrawCmd::Tiles { .. } | DrawCmd::Image { .. })), "only live tiles at {res}"); - assert_parity(&format!("raster tiles {res} {opacity}"), build(opacity), &view); + assert_parity(&format!("raster tiles {res} {opacity} {nearest}"), build(opacity, nearest), &view); } } @@ -2656,7 +2687,8 @@ mod tests { let mut pm = rustgis_engine::render::Pixmap::new(4, 4).expect("pixmap"); pm.data_mut().chunks_mut(4).for_each(|p| p.copy_from_slice(&[200, 30, 30, 255])); let picture = Arc::new(Payload::Image(pm)); - let quad = TileQuad { picture: picture.clone(), rect: [0.0, 0.0, 100.0, 100.0], uv: [0.0, 0.0, 1.0, 1.0], opacity: 1.0 }; + let quad = + TileQuad { picture: picture.clone(), rect: [0.0, 0.0, 100.0, 100.0], uv: [0.0, 0.0, 1.0, 1.0], opacity: 1.0, nearest: false }; let scene = |q: &TileQuad| GpuScene { clear: [0.0; 4], cmds: vec![DrawCmd::Tiles { origin: [0.0, 0.0], tiles: vec![q.clone()] }], @@ -2681,7 +2713,13 @@ mod tests { // Once the tile cache lets the picture go, so does the GPU. drop((quad, picture, first, _second)); let other = rustgis_engine::render::Pixmap::new(4, 4).expect("pixmap"); - let q = TileQuad { picture: Arc::new(Payload::Image(other)), rect: [0.0, 0.0, 1.0, 1.0], uv: [0.0, 0.0, 1.0, 1.0], opacity: 1.0 }; + let q = TileQuad { + picture: Arc::new(Payload::Image(other)), + rect: [0.0, 0.0, 1.0, 1.0], + uv: [0.0, 0.0, 1.0, 1.0], + opacity: 1.0, + nearest: false, + }; let _third = upload(&scene(&q)).expect("fits"); assert_eq!(r.tile_textures.lock().expect("textures").by_picture.len(), 1); } @@ -2698,7 +2736,13 @@ mod tests { pm.data_mut().chunks_mut(4).for_each(|p| p.copy_from_slice(&[c, 30, 30, 255])); Arc::new(Payload::Image(pm)) }; - let quad = |p: &Arc| TileQuad { picture: p.clone(), rect: [0.0, 0.0, 10.0, 10.0], uv: [0.0, 0.0, 1.0, 1.0], opacity: 1.0 }; + let quad = |p: &Arc| TileQuad { + picture: p.clone(), + rect: [0.0, 0.0, 10.0, 10.0], + uv: [0.0, 0.0, 1.0, 1.0], + opacity: 1.0, + nearest: false, + }; // Two chunks of 64 pictures of 256 pixels. let chunk = 64 * 256 * 256 * 4; let mut live = @@ -2752,7 +2796,13 @@ mod tests { pm.data_mut().chunks_mut(4).for_each(|p| p.copy_from_slice(&[c, 30, 30, 255])); Arc::new(Payload::Image(pm)) }; - let quad = |p: &Arc| TileQuad { picture: p.clone(), rect: [0.0, 0.0, 10.0, 10.0], uv: [0.0, 0.0, 1.0, 1.0], opacity: 1.0 }; + let quad = |p: &Arc| TileQuad { + picture: p.clone(), + rect: [0.0, 0.0, 10.0, 10.0], + uv: [0.0, 0.0, 1.0, 1.0], + opacity: 1.0, + nearest: false, + }; let chunk = 16u64 << 20; let mut live = crate::tilelayer::LiveTiles::new(&rs.device, wgpu::TextureFormat::Rgba8Unorm, 4, DEPTH_FORMAT).with_budget(2 * chunk); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 7a9313f7f1..655b0f2ab0 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -1770,6 +1770,20 @@ fn tile_row(app: &mut RustGisApp, ui: &mut Ui, i: usize, moves: [bool; 2], reord } }) .on_hover_text(tl!("How the layer's colours combine with the tile layers and basemap beneath.")); + // Picture tiles drawn larger or smaller than their own pixels: blended, or each a block (#2804). + if !matches!(tile.kind, TileKind::Vector | TileKind::Style) { + use rustgis_engine::map::raster::Resampling; + crate::widgets::submenu(ui, &crate::i18n::fmt("Resampling: {how}", &[("how", tl_raw!(tile.resampling.label()))]), |ui| { + for r in Resampling::ALL { + if ui.radio(tile.resampling == r, tl!(r.label())).clicked() { + let code = if r == Resampling::Nearest { "nearest" } else { "bilinear" }; + action = Some(("map.setTiles", json!({"index": i, "resampling": code}))); + ui.close(); + } + } + }) + .on_hover_text(tl!("How the layer's pictures are drawn when zoomed past or short of their own pixels: each pixel a crisp block, or blended smooth.")); + } // A layer its service draws on request: one picture of the view, or tiles (#1162). if tile.on_request() { let shown = if tile.single_image { diff --git a/crates/ui-egui/src/tilelayer.rs b/crates/ui-egui/src/tilelayer.rs index a5b4f2b93f..24a9d72f51 100644 --- a/crates/ui-egui/src/tilelayer.rs +++ b/crates/ui-egui/src/tilelayer.rs @@ -50,14 +50,16 @@ struct Instance { opacity: f32, } -/// What a live layer draws in one frame: per chunk, its instances. +/// What a live layer draws in one frame: per chunk and sampling (nearest or not), its instances. #[derive(Default, Clone)] -struct Runs(Vec<(usize, Range)>); +struct Runs(Vec<(usize, bool, Range)>); /// One texture array of a pool. struct Chunk { texture: wgpu::Texture, bind: wgpu::BindGroup, + /// The same, sampled nearest: a layer set to nearest-neighbour resampling (#2804). + nearest_bind: wgpu::BindGroup, #[cfg_attr(not(test), expect(dead_code, reason = "read by the tests only"))] layers: u32, /// Its pictures' side, and its bytes. @@ -96,6 +98,7 @@ pub(crate) struct LiveTiles { pipeline: wgpu::RenderPipeline, layout: wgpu::BindGroupLayout, sampler: wgpu::Sampler, + nearest_sampler: wgpu::Sampler, uniforms: wgpu::Buffer, /// Every chunk, by the index an [`At`] names; `None` once given back to the budget. chunks: Vec>, @@ -215,6 +218,12 @@ impl LiveTiles { min_filter: wgpu::FilterMode::Linear, ..Default::default() }); + let nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("live_tiles_nearest"), + mag_filter: wgpu::FilterMode::Nearest, + min_filter: wgpu::FilterMode::Nearest, + ..Default::default() + }); let uniforms = device.create_buffer(&wgpu::BufferDescriptor { label: Some("live_tiles_uniforms"), size: 16, @@ -226,6 +235,7 @@ impl LiveTiles { pipeline, layout, sampler, + nearest_sampler, uniforms, chunks: Vec::new(), pools: HashMap::new(), @@ -267,20 +277,21 @@ impl LiveTiles { } } for quads in layers { - let mut by_chunk: Vec<(usize, Vec)> = Vec::new(); + let mut by_chunk: Vec<((usize, bool), Vec)> = Vec::new(); for q in quads { let Some(at) = self.slot(device, queue, q, &mut uploads, &mut backlog) else { continue }; let i = Instance { rect: q.rect, uv: q.uv, layer: at.layer, opacity: q.opacity }; - match by_chunk.iter_mut().find(|(c, _)| *c == at.chunk) { + let run = (at.chunk, q.nearest); + match by_chunk.iter_mut().find(|(c, _)| *c == run) { Some((_, v)) => v.push(i), - None => by_chunk.push((at.chunk, vec![i])), + None => by_chunk.push((run, vec![i])), } } let mut runs = Runs::default(); - for (chunk, v) in by_chunk { + for ((chunk, nearest), v) in by_chunk { let first = instances.len() as u32; instances.extend(v); - runs.0.push((chunk, first..instances.len() as u32)); + runs.0.push((chunk, nearest, first..instances.len() as u32)); } self.runs.push(runs); } @@ -405,16 +416,19 @@ impl LiveTiles { }); let view = texture .create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("live_tiles_chunk"), - layout: &self.layout, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: self.uniforms.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&view) }, - wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, - ], - }); - let c = Chunk { texture, bind, layers, side, bytes: chunk_bytes }; + let bind_with = |sampler: &wgpu::Sampler| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("live_tiles_chunk"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: self.uniforms.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(sampler) }, + ], + }) + }; + let (bind, nearest_bind) = (bind_with(&self.sampler), bind_with(&self.nearest_sampler)); + let c = Chunk { texture, bind, nearest_bind, layers, side, bytes: chunk_bytes }; // A slot given back earlier is reused, so the list doesn't grow with every exchange. let chunk = match self.chunks.iter().position(Option::is_none) { Some(i) => { @@ -473,9 +487,9 @@ impl LiveTiles { } rp.set_pipeline(&self.pipeline); rp.set_vertex_buffer(0, instances.slice(..)); - for (chunk, range) in &runs.0 { + for (chunk, nearest, range) in &runs.0 { if let Some(Some(c)) = self.chunks.get(*chunk) { - rp.set_bind_group(0, &c.bind, &[]); + rp.set_bind_group(0, if *nearest { &c.nearest_bind } else { &c.bind }, &[]); rp.draw(0..6, range.clone()); } } From d4ffa27ff777a0ab1e599ea854496c5d84d98b5d Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 11:04:57 -0600 Subject: [PATCH 2/4] fix(tiles): refuse resampling for a vector archive, one GPU texture per picture A PMTiles or MBTiles archive read as holding vector tiles draws shapes, so map.setTiles refuses a resampling it would ignore and the layer's menu leaves the Resampling submenu out. The GPU map keeps one texture per tile picture with a nearest bind group beside it, instead of a texture per sampling. The helper choosing the filter is named for what it picks. --- crates/engine/src/cmd/tiles.rs | 10 ++++++-- crates/engine/src/tests.rs | 33 ++++++++++++++++++++++++ crates/render/src/native_tiles.rs | 4 +-- crates/render/src/single_image.rs | 2 +- crates/tiles/src/draw.rs | 3 +++ crates/ui-egui/src/mapgpu.rs | 42 ++++++++++++++++++------------- crates/ui-egui/src/panes.rs | 5 +++- 7 files changed, 75 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index febed28701..e76aba9ec5 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -228,7 +228,7 @@ pub(crate) fn add_with_metadata_wait(s: &mut Session, p: &Value, metadata_wait: t.blend = m; } if let Some(r) = resampling(p)? { - if matches!(kind, TileKind::Vector | TileKind::Style) { + if draws_shapes(&t) { return Err(NOT_PICTURES.into()); } t.resampling = r; @@ -891,6 +891,12 @@ fn sampling_code(r: rustgis_map::raster::Resampling) -> &'static str { /// Refused for a layer that draws vector shapes: there are no pictures to resample. const NOT_PICTURES: &str = "resampling is for a layer of picture tiles, not vector tiles or a style"; +/// Whether `t` draws vector shapes rather than pictures: vector tiles, a style, or an archive +/// read as holding vector tiles (one still on its way isn't known yet). +fn draws_shapes(t: &TileLayer) -> bool { + matches!(t.kind, TileKind::Vector | TileKind::Style) || rustgis_render::tile_source_layers(t).is_some() +} + /// The `resampling` parameter: how the layer's pictures are drawn at a size other than their own. fn resampling(p: &Value) -> Result, String> { match p.get("resampling") { @@ -938,7 +944,7 @@ fn set(s: &mut Session, p: &Value) -> CmdResult { if hidden.as_ref().is_some_and(|h| !h.is_empty()) && matches!(t.kind, TileKind::Raster | TileKind::Cog) { return Err("hiddenLayers is for vector tiles' source layers".into()); } - if sampling.is_some() && matches!(t.kind, TileKind::Vector | TileKind::Style) { + if sampling.is_some() && draws_shapes(t) { return Err(NOT_PICTURES.into()); } let single = b(p, "singleImage"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 30bdc16be1..8268bdca6e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -23226,6 +23226,39 @@ fn identify_reports_vector_tile_features() { let _ = std::fs::remove_dir_all(dir); } +/// A vector tile archive draws shapes, not pictures: once it's read, `map.setTiles` refuses a +/// resampling it would ignore (#2804). +#[test] +fn a_vector_archive_refuses_resampling() { + use crate::render::rustgis_tiles::{mvt, pmtiles}; + let road = + mvt::Feature { id: None, kind: mvt::GeomKind::LineString, geometry: vec![vec![[0.0, 2048.0], [4096.0, 2048.0]]], props: vec![] }; + let tile = mvt::encode(&mvt::Tile { layers: vec![mvt::Layer { name: "roads".into(), extent: 4096, features: vec![road] }] }); + let new = pmtiles::NewArchive { + tile_type: pmtiles::TileType::Mvt, + gzipped_tiles: false, + bounds: [-180.0, -85.0, 180.0, 85.0], + metadata: json!({"vector_layers": [{"id": "roads"}]}), + }; + let dir = std::env::temp_dir().join(format!("rustgis-vector-resampling-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("roads.pmtiles"); + std::fs::write(&path, pmtiles::write(vec![(0, 0, 0, tile)], &new).unwrap()).unwrap(); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + // The archive's header arrives in the background. + for _ in 0..500 { + if s.run("map.tiles", &json!({})).unwrap()[0].get("sourceLayers").is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); // test-wait: the archive's header is read on another thread + } + let err = s.run("map.setTiles", &json!({"index": 0, "resampling": "nearest"})).unwrap_err(); + assert!(err.contains("picture tiles"), "{err}"); + assert_eq!(s.map().tiles[0].resampling, rustgis_map::raster::Resampling::Bilinear); + let _ = std::fs::remove_dir_all(&dir); +} + /// A vector archive's source layers are listed by `map.tiles`; one switched off with /// `map.setTiles {hiddenLayers}` isn't identified, the setting undoes and is kept with the project, /// and a bad list is refused without changing anything. diff --git a/crates/render/src/native_tiles.rs b/crates/render/src/native_tiles.rs index 576c4b350a..a30e1318eb 100644 --- a/crates/render/src/native_tiles.rs +++ b/crates/render/src/native_tiles.rs @@ -189,7 +189,7 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat Some(((x * k) as f32, (y * k) as f32)) }; let opacity = t.opacity.clamp(0.0, 1.0); - let quality = filter(t); + let quality = sampling(t); let (mut pending, mut error) = (false, None); for p in pictures { // A WMTS tile past the service's coverage is routine; a WMS picture (any area asked) isn't. @@ -301,7 +301,7 @@ pub(crate) fn paint( /// How a tile layer's pictures are sampled where they're drawn at another size: blended, or /// each pixel a block (#2804). -pub(crate) fn filter(t: &rustgis_map::TileLayer) -> FilterQuality { +pub(crate) fn sampling(t: &rustgis_map::TileLayer) -> FilterQuality { match t.resampling { rustgis_map::raster::Resampling::Nearest => FilterQuality::Nearest, rustgis_map::raster::Resampling::Bilinear => FilterQuality::Bilinear, diff --git a/crates/render/src/single_image.rs b/crates/render/src/single_image.rs index 5de9305e34..b090899041 100644 --- a/crates/render/src/single_image.rs +++ b/crates/render/src/single_image.rs @@ -359,7 +359,7 @@ pub(crate) fn draw(pm: &mut Pixmap, req: &Request, t: &TileLayer, view: &View, f let key = format!("{} {}", req.system.epsg, req.base); let opacity = t.opacity.clamp(0.0, 1.0); let blend = crate::blend_mode(t.blend); - let quality = crate::native_tiles::filter(t); + let quality = crate::native_tiles::sampling(t); // In another system than the map's, warped into place piece by piece (one affine placing // would leave it off where the systems bend apart). let warped = req.warp; diff --git a/crates/tiles/src/draw.rs b/crates/tiles/src/draw.rs index 22bf3a39d2..6de12bcc25 100644 --- a/crates/tiles/src/draw.rs +++ b/crates/tiles/src/draw.rs @@ -174,6 +174,9 @@ pub fn draw(pm: &mut Pixmap, spec: &Spec, opacity: f32, frame: &Frame, labels: b // a map moving across them only puts them in place. if let Some(pictures) = crate::picture::cover(&r, frame, &frame.extent(w, h), None, &mut out.pending, &mut out.error) { for it in &pictures { + // A picture already holds its raster layers as their `raster-resampling` drew them + // (crisp blocks for `nearest`): placed between its zoom levels it is blended as the + // style's shapes in it are, a picture of the map rather than of the source's pixels. draw_raster(pm, it, frame, opacity, false); } if labels { diff --git a/crates/ui-egui/src/mapgpu.rs b/crates/ui-egui/src/mapgpu.rs index f4afba7528..007758e061 100644 --- a/crates/ui-egui/src/mapgpu.rs +++ b/crates/ui-egui/src/mapgpu.rs @@ -680,8 +680,8 @@ const KEPT_TILE_BYTES: u64 = 64 << 20; struct TileTextures { /// By the picture's address, with the picture itself held weakly: the tile cache keeps the /// picture alive, and once it lets go the texture goes too (the weak reference keeps the - /// address from being reused until then), and whether it's sampled nearest. - by_picture: std::collections::HashMap<(usize, bool), TileTexture>, + /// address from being reused until then). + by_picture: std::collections::HashMap, /// Counts scenes: when each texture was last drawn. scene: u64, } @@ -689,6 +689,9 @@ struct TileTextures { struct TileTexture { picture: std::sync::Weak, bind: wgpu::BindGroup, + /// The same texture sampled nearest, for a layer set to nearest-neighbour resampling + /// (#2804): one upload whichever way the layers that draw it sample it. + nearest_bind: wgpu::BindGroup, texture: Arc>, used: u64, bytes: u64, @@ -704,12 +707,13 @@ impl TileTextures { r: &GpuMapRenderer, q: &TileQuad, ) -> Option<(wgpu::BindGroup, Arc>)> { - let key = (Arc::as_ptr(&q.picture) as usize, q.nearest); + let key = Arc::as_ptr(&q.picture) as usize; if let Some(t) = self.by_picture.get_mut(&key) && t.picture.upgrade().is_some_and(|p| Arc::ptr_eq(&p, &q.picture)) { t.used = self.scene; - return Some((t.bind.clone(), t.texture.clone())); + let bind = if q.nearest { &t.nearest_bind } else { &t.bind }; + return Some((bind.clone(), t.texture.clone())); } let pm = q.pixmap()?; let (w, h) = (pm.width(), pm.height()); @@ -738,34 +742,36 @@ impl TileTextures { size, ); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("mapgpu_tile_bind"), - layout: &r.image_layout, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Sampler(if q.nearest { &r.nearest_sampler } else { &r.sampler }), - }, - ], - }); + let bind_with = |sampler: &wgpu::Sampler| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("mapgpu_tile_bind"), + layout: &r.image_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) }, + ], + }) + }; + let (bind, nearest_bind) = (bind_with(&r.sampler), bind_with(&r.nearest_sampler)); + let chosen = if q.nearest { nearest_bind.clone() } else { bind.clone() }; let texture = Arc::new(texture); let t = TileTexture { picture: Arc::downgrade(&q.picture), - bind: bind.clone(), + bind, + nearest_bind, texture: texture.clone(), used: self.scene, bytes: u64::from(w) * u64::from(h) * 4, }; self.by_picture.insert(key, t); - Some((bind, texture)) + Some((chosen, texture)) } /// Ends a scene: drops the textures of pictures the tile cache let go, and past /// [`KEPT_TILE_BYTES`] those unused longest, but never one the scene just drew. fn end_scene(&mut self) { self.by_picture.retain(|_, t| t.picture.strong_count() > 0); - let mut old: Vec<(u64, u64, (usize, bool))> = + let mut old: Vec<(u64, u64, usize)> = self.by_picture.iter().filter(|(_, t)| t.used != self.scene).map(|(k, t)| (t.used, t.bytes, *k)).collect(); if old.iter().map(|o| o.1).sum::() > KEPT_TILE_BYTES { old.sort_unstable_by_key(|o| std::cmp::Reverse(o.0)); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 655b0f2ab0..da67f7f4ed 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -1771,7 +1771,10 @@ fn tile_row(app: &mut RustGisApp, ui: &mut Ui, i: usize, moves: [bool; 2], reord }) .on_hover_text(tl!("How the layer's colours combine with the tile layers and basemap beneath.")); // Picture tiles drawn larger or smaller than their own pixels: blended, or each a block (#2804). - if !matches!(tile.kind, TileKind::Vector | TileKind::Style) { + // Not for one drawing shapes: vector tiles, a style, or an archive read as holding vector + // tiles. + let vector_archive = rustgis_engine::render::tile_source_layers(tile).is_some(); + if !matches!(tile.kind, TileKind::Vector | TileKind::Style) && !vector_archive { use rustgis_engine::map::raster::Resampling; crate::widgets::submenu(ui, &crate::i18n::fmt("Resampling: {how}", &[("how", tl_raw!(tile.resampling.label()))]), |ui| { for r in Resampling::ALL { From 5f4031440b70f35533ae1119f9acdcfb1b09fd23 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 12:08:24 -0600 Subject: [PATCH 3/4] fix(tiles): refuse resampling until an archive is known to hold pictures; require tile-resampling An archive still being read may hold vector tiles, so map.addTiles and map.setTiles refuse a resampling for it until its header shows pictures, and the layer's menu offers the choice only then: a stored setting is always one that is drawn. A tile layer drawn nearest, or a saved map.addTiles/map.setTiles step setting it, requires the new tile-resampling capability, so an older RustGIS refuses the project instead of drawing it blended and saving it again without the setting. Adds the tile_resampling fixture and its test, the schema's capability list and the maintaining guide's paragraph. The GPU texture test checks one texture serves both samplings. --- crates/engine/src/cmd/tiles.rs | 25 +++--- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 36 ++++++++ crates/engine/src/tests.rs | 6 +- crates/render/src/lib.rs | 2 +- crates/render/src/tiles.rs | 12 +++ crates/tiles/src/source.rs | 10 +++ crates/ui-egui/src/mapgpu.rs | 4 +- crates/ui-egui/src/panes.rs | 7 +- docs/maintaining.md | 6 ++ schema/fixtures/tile_resampling.rgis | 101 ++++++++++++++++++++++ schema/project.schema.json | 6 +- 12 files changed, 197 insertions(+), 19 deletions(-) create mode 100644 schema/fixtures/tile_resampling.rgis diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index e76aba9ec5..213b4264b7 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -228,9 +228,7 @@ pub(crate) fn add_with_metadata_wait(s: &mut Session, p: &Value, metadata_wait: t.blend = m; } if let Some(r) = resampling(p)? { - if draws_shapes(&t) { - return Err(NOT_PICTURES.into()); - } + takes_resampling(&t)?; t.resampling = r; } // Vector tiles' layer names (an OGC API collection's), each drawn in a colour of its own. @@ -891,14 +889,21 @@ fn sampling_code(r: rustgis_map::raster::Resampling) -> &'static str { /// Refused for a layer that draws vector shapes: there are no pictures to resample. const NOT_PICTURES: &str = "resampling is for a layer of picture tiles, not vector tiles or a style"; -/// Whether `t` draws vector shapes rather than pictures: vector tiles, a style, or an archive -/// read as holding vector tiles (one still on its way isn't known yet). -fn draws_shapes(t: &TileLayer) -> bool { - matches!(t.kind, TileKind::Vector | TileKind::Style) || rustgis_render::tile_source_layers(t).is_some() +/// Refused for an archive whose header isn't read yet: it may hold vector tiles. +const NOT_KNOWN_YET: &str = "this archive is still being read: set its resampling once it shows on the map"; + +/// Refused unless `t` is known to draw pictures: a vector layer, style or archive draws shapes, +/// and an archive not read yet might (a setting it would ignore isn't kept). +fn takes_resampling(t: &TileLayer) -> Result<(), String> { + match rustgis_render::tile_draws_pictures(t) { + Some(true) => Ok(()), + Some(false) => Err(NOT_PICTURES.into()), + None => Err(NOT_KNOWN_YET.into()), + } } /// The `resampling` parameter: how the layer's pictures are drawn at a size other than their own. -fn resampling(p: &Value) -> Result, String> { +pub(crate) fn resampling(p: &Value) -> Result, String> { match p.get("resampling") { None | Some(Value::Null) => Ok(None), Some(Value::String(name)) => Some(name.trim()) @@ -944,8 +949,8 @@ fn set(s: &mut Session, p: &Value) -> CmdResult { if hidden.as_ref().is_some_and(|h| !h.is_empty()) && matches!(t.kind, TileKind::Raster | TileKind::Cog) { return Err("hiddenLayers is for vector tiles' source layers".into()); } - if sampling.is_some() && draws_shapes(t) { - return Err(NOT_PICTURES.into()); + if sampling.is_some() { + takes_resampling(t)?; } let single = b(p, "singleImage"); if single == Some(true) && !t.on_request() { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 90993f023d..a3d9db02b8 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -115,6 +115,7 @@ pub const CAPABILITIES: &[&str] = &[ PROJECT_CRS, "dggs-system", "label-clearance", + "tile-resampling", ]; /// An offline area keeping the versions that lost a sync or a Bring Back /// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 5b3590e0ed..ee8011461f 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -149,8 +149,22 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("dggs-system", command_uses_dggs_system), ("label-weight", command_weighs_labels), ("label-clearance", command_clears_labels), + ("tile-resampling", command_resamples_tiles), ]; +/// A saved `map.addTiles` or `map.setTiles` drawing a tile layer's pictures nearest (#2804), read as +/// the command reads it: an older reader runs it without the key, saying nothing, so the layer would +/// stay blended. `bilinear` is what an older reader keeps. +fn command_resamples_tiles(id: &str, params: &Value) -> bool { + match id { + "map.addTiles" | "map.setTiles" => { + crate::cmd::tiles::resampling(params).ok().flatten() == Some(rustgis_map::raster::Resampling::Nearest) + } + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_resamples_tiles)), + _ => false, + } +} + /// A saved `labels.placement` that gives a class a clearance other than 2, read as the command /// reads it (#2828): an older reader runs it without the key, saying nothing, so the labels would /// keep 2 points apart as before. 2 or null is what an older reader keeps. @@ -638,6 +652,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static ) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false, false); let mut polygon = false; let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared) = (false, false, false, false, false, false); + let mut crisp = false; for map in maps { offline_area_id |= map.offline_area_id.is_some(); // A blank basemap's paper colour (#2532), which an older reader would draw and save white. @@ -645,6 +660,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static guided |= map.layers.iter().any(label_guide); weighed |= map.layers.iter().any(label_weight); cleared |= map.layers.iter().any(label_clearance); + // A tile layer drawn nearest (#2804), which an older reader would draw and save blended. + crisp |= map.tiles.iter().any(|t| t.resampling != rustgis_map::raster::Resampling::Bilinear); // An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the // project by name rather than failing to read the type. mgrs |= map.graticule_type == rustgis_map::graticule::GraticuleType::Mgrs; @@ -692,6 +709,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (guided, "label-guide"), (weighed, "label-weight"), (cleared, "label-clearance"), + (crisp, "tile-resampling"), (offline_area_id, "offline-map-area-id"), (paper, "blank-paper"), (native, super::NATIVE_COORDINATES), @@ -809,6 +827,24 @@ mod tests { serde_json::from_slice(bytes).unwrap() } + /// A tile layer drawn nearest (#2804) reads back as it was and saving names `tile-resampling`; + /// one drawn blended, as an older reader would, names nothing. So does a saved step setting it. + #[test] + fn tile_resampling_fixture_reads_its_setting() { + use rustgis_map::raster::Resampling; + let fixture = Project::from_json(include_str!("../../../schema/fixtures/tile_resampling.rgis")).unwrap(); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["tile-resampling"])); + assert_eq!(fixture.maps[0].tiles[0].resampling, Resampling::Nearest); + let reopened = Project::from_json(&saved.to_string()).unwrap(); + assert_eq!(serde_json::to_value(&reopened).unwrap(), saved); + let mut plain = fixture; + plain.maps[0].tiles[0].resampling = Resampling::Bilinear; + assert!(serde_json::to_value(&plain).unwrap().get("requires").is_none()); + assert!(command_resamples_tiles("map.setTiles", &json!({"index": 0, "resampling": "nearest"}))); + assert!(!command_resamples_tiles("map.setTiles", &json!({"index": 0, "resampling": "bilinear"}))); + } + /// A saved MGRS graticule drawn on top in a color of its own (#1042 piece 8) reads back as it /// was, and saving names all three again; a map without them names none. #[test] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8268bdca6e..e6aa6bcfc2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -23227,7 +23227,7 @@ fn identify_reports_vector_tile_features() { } /// A vector tile archive draws shapes, not pictures: once it's read, `map.setTiles` refuses a -/// resampling it would ignore (#2804). +/// resampling it would ignore, and before then it's refused as not known yet (#2804). #[test] fn a_vector_archive_refuses_resampling() { use crate::render::rustgis_tiles::{mvt, pmtiles}; @@ -23255,6 +23255,10 @@ fn a_vector_archive_refuses_resampling() { } let err = s.run("map.setTiles", &json!({"index": 0, "resampling": "nearest"})).unwrap_err(); assert!(err.contains("picture tiles"), "{err}"); + // One not read (here never: it isn't there) might hold vector tiles: refused too. + let missing = dir.join("missing.pmtiles").display().to_string(); + let err = s.run("map.addTiles", &json!({"url": missing, "kind": "pmtiles", "resampling": "nearest"})).unwrap_err(); + assert!(err.contains("still being read"), "{err}"); assert_eq!(s.map().tiles[0].resampling, rustgis_map::raster::Resampling::Bilinear); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 62bc2ceb97..fe58a2de20 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -51,7 +51,7 @@ pub mod vector; pub use tiles::{Live, live as live_tiles}; pub use rustgis_tiles; -pub use tiles::{source_layers as tile_source_layers, spec as tile_spec, style_view}; +pub use tiles::{draws_pictures as tile_draws_pictures, source_layers as tile_source_layers, spec as tile_spec, style_view}; /// Natural Earth 1:110m sample data (public domain), fetched by `build.rs` from rustgis-assets. /// The countries in another worldview are downloaded when one is chosen, never built in. diff --git a/crates/render/src/tiles.rs b/crates/render/src/tiles.rs index b16101de35..906264c47e 100644 --- a/crates/render/src/tiles.rs +++ b/crates/render/src/tiles.rs @@ -184,6 +184,18 @@ pub fn source_layers(t: &TileLayer) -> Option> { rustgis_tiles::source::source_layers(kind, &t.url) } +/// Whether a tile layer draws pictures (`Some(true)`) rather than vector shapes (`Some(false)`): +/// raster tiles and a cloud-optimised GeoTIFF do, vector tiles and a style don't, and an archive +/// is known once its header is read (`None` until then). +pub fn draws_pictures(t: &TileLayer) -> Option { + match t.kind { + TileKind::Raster | TileKind::Cog => Some(true), + TileKind::Vector | TileKind::Style => Some(false), + TileKind::PmTiles => rustgis_tiles::source::archive_holds_vectors(Kind::PmTiles, &t.url).map(|v| !v), + TileKind::MbTiles => rustgis_tiles::source::archive_holds_vectors(Kind::MbTiles, &t.url).map(|v| !v), + } +} + /// Where a MapLibre style layer's root properties place the map; `Ok(None)` while the style is /// still loading (asking starts loading it). Other tile layers have no view of their own. pub fn style_view(t: &TileLayer) -> Result, String> { diff --git a/crates/tiles/src/source.rs b/crates/tiles/src/source.rs index 8af8e6282c..c4d47fedbd 100644 --- a/crates/tiles/src/source.rs +++ b/crates/tiles/src/source.rs @@ -577,6 +577,16 @@ pub fn source_layers(kind: Kind, url: &str) -> Option> { } } +/// Whether a tile archive holds vector tiles (`Some(true)`) or pictures (`Some(false)`); `None` +/// while its header is on its way or can't be read. Other kinds aren't archives: `None`. +pub fn archive_holds_vectors(kind: Kind, url: &str) -> Option { + match kind { + Kind::PmTiles => pmtiles::info(url).ok().flatten().map(|i| i.tile_type.is_vector()), + Kind::MbTiles => mbtiles::info_ready(url, web_time::Duration::ZERO).ok().flatten().map(|i| i.format.is_vector()), + _ => None, + } +} + /// The document at `url`: `Ok(None)` while it is on its way. fn fetch_json(url: &str, from: Option<&address::Origin>) -> Result, String> { match cache::document(url, from) { diff --git a/crates/ui-egui/src/mapgpu.rs b/crates/ui-egui/src/mapgpu.rs index 007758e061..210ed01802 100644 --- a/crates/ui-egui/src/mapgpu.rs +++ b/crates/ui-egui/src/mapgpu.rs @@ -2713,8 +2713,10 @@ mod tests { let first = upload(&scene(&quad)).expect("fits"); assert!(first.has_tiles && !first.has_images, "tiles move with the camera"); let _second = upload(&scene(&quad)).expect("fits"); + // Drawn nearest by another layer (#2804): the same texture, sampled another way. + let _nearest = upload(&scene(&TileQuad { nearest: true, ..quad.clone() })).expect("fits"); let textures = r.tile_textures.lock().expect("textures"); - assert_eq!(textures.by_picture.len(), 1, "one texture for the picture"); + assert_eq!(textures.by_picture.len(), 1, "one texture for the picture, however it's sampled"); drop(textures); // Once the tile cache lets the picture go, so does the GPU. drop((quad, picture, first, _second)); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index da67f7f4ed..56fce723c1 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -1771,10 +1771,9 @@ fn tile_row(app: &mut RustGisApp, ui: &mut Ui, i: usize, moves: [bool; 2], reord }) .on_hover_text(tl!("How the layer's colours combine with the tile layers and basemap beneath.")); // Picture tiles drawn larger or smaller than their own pixels: blended, or each a block (#2804). - // Not for one drawing shapes: vector tiles, a style, or an archive read as holding vector - // tiles. - let vector_archive = rustgis_engine::render::tile_source_layers(tile).is_some(); - if !matches!(tile.kind, TileKind::Vector | TileKind::Style) && !vector_archive { + // Only for pictures: not vector tiles, a style, or an archive holding vector tiles or not + // read yet. + if rustgis_engine::render::tile_draws_pictures(tile) == Some(true) { use rustgis_engine::map::raster::Resampling; crate::widgets::submenu(ui, &crate::i18n::fmt("Resampling: {how}", &[("how", tl_raw!(tile.resampling.label()))]), |ui| { for r in Resampling::ALL { diff --git a/docs/maintaining.md b/docs/maintaining.md index 316d103338..25fd56640e 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -174,6 +174,12 @@ Likewise a label class keeping other than 2 points free round its labels (`label step: an older reader would place the labels 2 points apart and save them again without the clearances, or run the step without it. +Projects and map files with a tile layer drawn nearest (`map.setTiles` with `"resampling": +"nearest"`) require `tile-resampling`, so an older reader refuses them instead of drawing the layer +blended and saving it again without the setting. So do projects with a saved `map.addTiles` or +`map.setTiles` step (in a task, a model or a script) that sets it: an older reader would run the +step without it, saying nothing. + Projects with an ink on a legend, colorbar, table or chart (`color` on those elements) require `layout-element-ink`, so an older reader refuses them instead of drawing those elements in dark grey and saving them again without it. Saved `layout.addElement` and `layout.update` commands diff --git a/schema/fixtures/tile_resampling.rgis b/schema/fixtures/tile_resampling.rgis new file mode 100644 index 0000000000..f8ddf9ad14 --- /dev/null +++ b/schema/fixtures/tile_resampling.rgis @@ -0,0 +1,101 @@ +{ + "format": 2, + "name": "Crisp tiles", + "maps": [ + { + "name": "Map", + "layers": [], + "basemap": "Paper", + "camera": { + "center": { + "x": 0.0, + "y": 2000000.0 + }, + "res": 30000.0, + "bearing": 0.0, + "pitch": 0.0 + }, + "bookmarks": [], + "graticule": true, + "projection": "WebMercator", + "popup_mode": "Topmost", + "label_display": { + "paused": false, + "locked": false, + "show_unplaced": false + }, + "editing": { + "relationships": [], + "snapping": { + "enabled": false, + "tolerance_px": 10.0, + "vertex": true, + "edge": true, + "end": true + }, + "topology": [], + "settings": { + "enabled": true, + "show_vertices": true, + "elevation": "None", + "ground_to_grid": null + } + }, + "swipe": null, + "view": { + "effects": { + "stars": true, + "sun_time": null, + "weather": "None", + "vignette": false, + "edges": false, + "tilt_shift": false, + "grain": false, + "brightness": 0.0, + "contrast": 0.0, + "saturation": 0.0, + "sepia": 0.0 + }, + "wireframe": false, + "clip_distance": null + }, + "animation": [], + "next_layer_id": 1, + "tiles": [ + { + "name": "Imagery", + "kind": "raster", + "url": "https://tiles.example/{z}/{x}/{y}.png", + "resampling": "Nearest" + } + ] + } + ], + "active_map": 0, + "tables": [], + "next_table_id": 1, + "gp_history": [], + "layouts": [], + "folders": [], + "styles": [], + "ramps": [], + "tasks": [], + "gp_env": { + "extent": null, + "cell_size": null + }, + "models": [], + "workspaces": [], + "link_views": false, + "jobs": [], + "offline_areas": [], + "reports": [], + "presentations": [], + "notebooks": [], + "dl_models": [], + "shared": [], + "data_stores": [], + "requires": [ + "tile-resampling" + ] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 69ecfcd3a9..877fdd7be8 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1278,7 +1278,8 @@ "label-weight", "project-crs", "dggs-system", - "label-clearance" + "label-clearance", + "tile-resampling" ], "type": "string" }, @@ -1385,7 +1386,8 @@ "label-weight", "project-crs", "dggs-system", - "label-clearance" + "label-clearance", + "tile-resampling" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2 From eb8c4f81b59baa5ed7f81704683b42f53bca9599 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 14:02:43 -0600 Subject: [PATCH 4/4] fix(tiles): a resampling name of separators alone is refused, not read as nearest --- crates/engine/src/cmd/tiles.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index 8d29157e09..4539de577a 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -927,8 +927,9 @@ fn read_local_header(t: &TileLayer, wait: web_time::Duration) { pub(crate) fn resampling(p: &Value) -> Result, String> { match p.get("resampling") { None | Some(Value::Null) => Ok(None), + // A name with no letters (blank, or separators alone, which `from_name` drops) names none. Some(Value::String(name)) => Some(name.trim()) - .filter(|n| !n.is_empty()) + .filter(|n| n.chars().any(char::is_alphanumeric)) .and_then(rustgis_map::raster::Resampling::from_name) .map(Some) .ok_or_else(|| format!("unknown resampling '{name}': nearest or bilinear")), @@ -1150,7 +1151,9 @@ mod tests { assert!(s.run("edit.undo", &json!({})).is_ok()); assert_eq!(of(&s, "Base"), Some(Resampling::Bilinear)); assert!(s.run("map.setTiles", &json!({"name": "Base", "resampling": "cubic"})).is_err()); - assert!(s.run("map.setTiles", &json!({"name": "Base", "resampling": " "})).is_err()); + for blank in [" ", "-", "_"] { + assert!(s.run("map.setTiles", &json!({"name": "Base", "resampling": blank})).is_err(), "{blank:?}"); + } let vector = json!({"url": "https://v.example.com/{z}/{x}/{y}.pbf", "kind": "vector", "name": "Roads"}); assert!(s.run("map.addTiles", &vector).is_ok()); assert!(s.run("map.setTiles", &json!({"name": "Roads", "resampling": "nearest"})).is_err());