diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index ffa75cb59a..d3c9eed8b8 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 7f454f4a90..463bc71cad 100644 --- a/crates/engine/src/cmd/geolibre.rs +++ b/crates/engine/src/cmd/geolibre.rs @@ -581,6 +581,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..4539de577a 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)? { + // A local archive is read first (as it is below anyway), so a picture one takes it at once. + read_local_header(&t, metadata_wait); + takes_resampling(&t)?; + 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,67 @@ 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"; + +/// 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) { + Ok(Some(true)) => Ok(()), + Ok(Some(false)) => Err(NOT_PICTURES.into()), + Ok(None) => Err(NOT_KNOWN_YET.into()), + Err(e) => Err(format!("resampling can't be set: the archive couldn't be read ({e})")), + } +} + +/// Reads a local archive's header, waiting up to `wait`, so what it holds is known (natively; a +/// web address and the browser's files are read as they draw). +fn read_local_header(t: &TileLayer, wait: web_time::Duration) { + #[cfg(not(target_arch = "wasm32"))] + match t.kind { + TileKind::PmTiles if rustgis_render::rustgis_tiles::pmtiles::is_local(&t.url) => { + // Its error, if any, is reported when the setting is refused or the layer draws. + let _ = rustgis_render::rustgis_tiles::pmtiles::info_blocking(&t.url, wait); + } + TileKind::MbTiles => { + let _ = rustgis_render::rustgis_tiles::mbtiles::info_ready(&t.url, wait); + } + _ => {} + } + #[cfg(target_arch = "wasm32")] + let _ = (t, wait); +} + +/// The `resampling` parameter: how the layer's pictures are drawn at a size other than their own. +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.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")), + 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 +971,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() { + takes_resampling(t)?; + } let single = b(p, "singleImage"); if single == Some(true) && !t.on_request() { return Err(NOT_ON_REQUEST.into()); @@ -954,6 +1021,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 +1132,38 @@ 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()); + 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()); + // 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/engine/src/project.rs b/crates/engine/src/project.rs index 63ad885e28..1f28a53fd0 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -119,6 +119,7 @@ pub const CAPABILITIES: &[&str] = &[ "label-clearance", "svg-markers", "label-duplicates", + "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 c63f8c8ca9..3f4a1f365b 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -159,6 +159,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("label-weight", command_weighs_labels), ("label-clearance", command_clears_labels), ("label-duplicates", command_removes_duplicate_labels), + ("tile-resampling", command_resamples_tiles), ]; /// A saved `labels.placement` that has a class remove duplicates, read as the command reads it @@ -172,6 +173,19 @@ fn command_removes_duplicate_labels(id: &str, params: &Value) -> bool { } } +/// 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. @@ -687,6 +701,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static let (mut polygon, mut svg) = (false, false); let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) = (false, 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. @@ -695,6 +710,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static weighed |= map.layers.iter().any(label_weight); cleared |= map.layers.iter().any(label_clearance); deduped |= map.layers.iter().any(removes_duplicate_labels); + // 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; @@ -745,6 +762,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (weighed, "label-weight"), (cleared, "label-clearance"), (deduped, "label-duplicates"), + (crisp, "tile-resampling"), (offline_area_id, "offline-map-area-id"), (paper, "blank-paper"), (native, super::NATIVE_COORDINATES), @@ -862,6 +880,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 fdddcbb010..fe1bedaa77 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -23559,6 +23559,61 @@ 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; one that can't be read says so, and a local picture archive takes +/// it as it's added (#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); + // One that can't be read says so. + 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("couldn't be read"), "{err}"); + // A local archive of pictures takes it as it's added: its header is read first. + let png = { + let mut out = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(4, 4, image::Rgba([90, 120, 60, 255])).write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let pictures = pmtiles::NewArchive { + tile_type: pmtiles::TileType::Png, + gzipped_tiles: false, + bounds: [-180.0, -85.0, 180.0, 85.0], + metadata: json!({}), + }; + let imagery = dir.join("imagery.pmtiles"); + std::fs::write(&imagery, pmtiles::write(vec![(0, 0, 0, png)], &pictures).unwrap()).unwrap(); + let url = imagery.display().to_string(); + s.run("map.addTiles", &json!({"url": url, "kind": "pmtiles", "resampling": "nearest"})).unwrap(); + assert_eq!(s.map().tiles[0].resampling, rustgis_map::raster::Resampling::Nearest); + 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/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/lib.rs b/crates/render/src/lib.rs index 4d3288ccac..3744c7b871 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/native_tiles.rs b/crates/render/src/native_tiles.rs index e514469823..a30e1318eb 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 = 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. @@ -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 sampling(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..b090899041 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::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; 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..987eafcb38 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, } } @@ -183,6 +184,19 @@ 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; its error when it can't be). +pub fn draws_pictures(t: &TileLayer) -> Result, String> { + let archive = |kind| rustgis_tiles::source::archive_holds_vectors(kind, &t.url).map(|v| v.map(|vectors| !vectors)); + match t.kind { + TileKind::Raster | TileKind::Cog => Ok(Some(true)), + TileKind::Vector | TileKind::Style => Ok(Some(false)), + TileKind::PmTiles => archive(Kind::PmTiles), + TileKind::MbTiles => archive(Kind::MbTiles), + } +} + /// 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> { @@ -628,6 +642,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 61079ed663..0eab06da51 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -6261,6 +6261,7 @@ Connection: close layers: vec![], style_layers: String::new(), hidden_layers: vec![], + nearest: false, }; let mut resolved = None; for _ in 0..200 { @@ -6490,6 +6491,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..6de12bcc25 100644 --- a/crates/tiles/src/draw.rs +++ b/crates/tiles/src/draw.rs @@ -174,7 +174,10 @@ 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); + // 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 { draw_layers(None, (w, h), &frame.extent(w, h), &r, frame, Pass::Labels, &mut out); @@ -300,8 +303,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 +359,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 +425,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 +454,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 +816,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 +831,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 +1593,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 +1711,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 +1834,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 +1876,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..b68155366e 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 ) } } @@ -573,6 +577,30 @@ 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, and an error when it can't be read or its tiles are of a type +/// RustGIS doesn't know. Other kinds aren't archives: `None`. +pub fn archive_holds_vectors(kind: Kind, url: &str) -> Result, String> { + use pmtiles::TileType; + use rustgis_data::mbtiles::Format; + const UNKNOWN: &str = "its tiles are of a type RustGIS doesn't know"; + match kind { + Kind::PmTiles => match pmtiles::info(url)?.map(|i| i.tile_type) { + None => Ok(None), + Some(TileType::Mvt) => Ok(Some(true)), + Some(TileType::Png | TileType::Jpeg | TileType::Webp | TileType::Avif) => Ok(Some(false)), + Some(TileType::Unknown) => Err(UNKNOWN.into()), + }, + Kind::MbTiles => match mbtiles::info_ready(url, web_time::Duration::ZERO)?.map(|i| i.format) { + None => Ok(None), + Some(Format::Pbf) => Ok(Some(true)), + Some(Format::Png | Format::Jpeg | Format::Webp) => Ok(Some(false)), + Some(Format::Unknown) => Err(UNKNOWN.into()), + }, + _ => Ok(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) { @@ -609,10 +637,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 +676,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 +889,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..210ed01802 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(), @@ -680,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, @@ -700,7 +712,8 @@ impl TileTextures { && 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()); @@ -729,24 +742,29 @@ 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(&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 @@ -2587,25 +2605,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 +2645,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 +2659,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 +2693,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()] }], @@ -2675,13 +2713,21 @@ 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)); 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 +2744,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 +2804,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..3cef055f76 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -1770,6 +1770,22 @@ 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). + // 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) == Ok(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 { + 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()); } } diff --git a/docs/maintaining.md b/docs/maintaining.md index 941b0feb98..53740ca73c 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -181,6 +181,12 @@ A label class removing duplicates (`labels.placement` with a `removeDuplicates` `label-duplicates`, in a layer, a saved style or a saved `labels.placement` step: an older reader would place and save every label, 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 2895f16c09..8513be0323 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1280,7 +1280,8 @@ "dggs-system", "label-clearance", "svg-markers", - "label-duplicates" + "label-duplicates", + "tile-resampling" ], "type": "string" }, @@ -1389,7 +1390,8 @@ "dggs-system", "label-clearance", "svg-markers", - "label-duplicates" + "label-duplicates", + "tile-resampling" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2