diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 41a36e8f69..c4ada5eb45 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1045,10 +1045,10 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { } _ => (0.0, 0.0, 0.0, None, None, false, None, 0.0), }; - // And its terrain type, likewise. - let cur_terrain = match rl.style.renderer { - RasterRenderer::ShadedRelief { terrain_type, .. } => terrain_type, - _ => 0.0, + // And its terrain type and flat ground's detail, likewise. + let (cur_terrain, cur_flats) = match rl.style.renderer { + RasterRenderer::ShadedRelief { terrain_type, flats, .. } => (terrain_type, flats), + _ => (0.0, None), }; RasterRenderer::ShadedRelief { band: bi, @@ -1085,6 +1085,7 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { Some(Value::Null) => 0.0, Some(_) => relief_terrain_type(f(p, "terrain"))?, }, + flats: cur_flats, } } other => return Err(format!("unknown raster symbology '{other}'")), diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 9f4881b3fb..475b0d7080 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -139,6 +139,7 @@ pub const CAPABILITIES: &[&str] = &[ "shaded-relief-shadow-softness", "shaded-relief-aerial", "shaded-relief-terrain-type", + "shaded-relief-flats", ]; /// 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 853a66410c..dd93c35d92 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1101,6 +1101,13 @@ fn sets_terrain_type(layer: &Layer) -> bool { .is_some_and(|r| matches!(&r.style.renderer, RasterRenderer::ShadedRelief { terrain_type, .. } if *terrain_type != 0.0)) } +/// Whether a layer sets its Shaded Relief's detail on flat ground (#3143): an older reader would +/// draw flat ground even and save the layer again without the setting (even at an amount of 0, +/// which draws none but is saved, with its size). +fn sets_flats(layer: &Layer) -> bool { + layer.raster.as_ref().is_some_and(|r| matches!(&r.style.renderer, RasterRenderer::ShadedRelief { flats: Some(_), .. })) +} + /// Whether a layer is a window of a Zarr variable following the time slider (#1720): an older /// reader would drop the window and read the whole map at each step. fn zarr_window(layer: &Layer) -> bool { @@ -1146,6 +1153,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (sets_shadow_softness(layer), "shaded-relief-shadow-softness"), (sets_aerial(layer), "shaded-relief-aerial"), (sets_terrain_type(layer), "shaded-relief-terrain-type"), + (sets_flats(layer), "shaded-relief-flats"), (layer.size_by.is_some(), super::SIZE_BY_CAPABILITY), (layer.has_picture_markers(), "picture-markers"), (layer.any_picture(svg_picture), "svg-markers"), @@ -1182,7 +1190,8 @@ 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, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type) = (false, false, false, false, false, false); + let (mut crisp, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type, mut flats) = + (false, false, false, false, false, false, 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. @@ -1222,6 +1231,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static soft |= map.layers.iter().any(sets_shadow_softness); aerial |= map.layers.iter().any(sets_aerial); terrain_type |= map.layers.iter().any(sets_terrain_type); + flats |= map.layers.iter().any(sets_flats); sized |= map.layers.iter().any(|layer| layer.size_by.is_some()); pictures |= map.layers.iter().any(Layer::has_picture_markers); svg |= map.layers.iter().any(|layer| layer.any_picture(svg_picture)); @@ -1246,6 +1256,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (soft, "shaded-relief-shadow-softness"), (aerial, "shaded-relief-aerial"), (terrain_type, "shaded-relief-terrain-type"), + (flats, "shaded-relief-flats"), (legends, "normalized-legend-urls"), (sized, super::SIZE_BY_CAPABILITY), (pictures, "picture-markers"), @@ -3501,10 +3512,11 @@ mod tests { })) .unwrap(); let clean = Layer::new_raster(1, "DEM", raster); - for field in ["shadow", "sky", "fill", "rock", "ambient", "balanced", "shadow_softness", "aerial", "terrain_type"] { + for field in ["shadow", "sky", "fill", "rock", "ambient", "balanced", "shadow_softness", "aerial", "terrain_type", "flats"] { let mut value = serde_json::to_value(&clean).unwrap(); value["raster"]["style"]["renderer"]["ShadedRelief"][field] = match field { "rock" => serde_json::to_value(rustgis_map::raster::Rock::DEFAULT).unwrap(), + "flats" => json!({"amount": 0.0, "size": 6}), "balanced" => json!(true), _ => json!(0.4), }; @@ -3521,6 +3533,7 @@ mod tests { "shadow_softness" => "shaded-relief-shadow-softness", "aerial" => "shaded-relief-aerial", "terrain_type" => "shaded-relief-terrain-type", + "flats" => "shaded-relief-flats", _ => "shaded-relief-effects", }; assert_eq!(document["requires"], json!([needs]), "{field}: {document}"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ebca733592..ff3dbe4c1b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8060,6 +8060,31 @@ fn shaded_relief_keeps_its_terrain_type() { assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["shaded-relief-terrain-type"])); } +/// Shaded Relief's detail on flat ground (#3143) reads back from a project, required by name; a +/// new relief has none, and one set is kept when the relief is styled again, and saved. +#[test] +fn shaded_relief_keeps_its_flat_ground_detail() { + let fixture = Project::from_json(include_str!("../../../schema/fixtures/shaded_relief_flats.rgis")).unwrap(); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["shaded-relief-flats"])); + let flats = |s: &Session| match s.map().layers.iter().find_map(|l| l.raster.as_ref()).map(|r| &r.style.renderer) { + Some(rustgis_map::RasterRenderer::ShadedRelief { flats, .. }) => *flats, + other => panic!("{other:?}"), + }; + assert_eq!(flats(&Session::new(fixture)), Some(rustgis_map::raster::Flats::DEFAULT)); + let mut s = with_raster(); + s.run("raster.symbology", &json!({"type": "shadedRelief"})).unwrap(); + assert_eq!(flats(&s), None, "none by default"); + if let Some(rustgis_map::RasterRenderer::ShadedRelief { flats, .. }) = + s.map_mut().layers.iter_mut().find_map(|l| l.raster.as_mut()).map(|r| &mut r.style.renderer) + { + *flats = Some(rustgis_map::raster::Flats::DEFAULT); + } + s.run("raster.symbology", &json!({"type": "shadedRelief", "azimuth": 200, "shadow": 0.5})).unwrap(); + assert_eq!(flats(&s), Some(rustgis_map::raster::Flats::DEFAULT), "kept"); + let text = s.project.saved_text(None).unwrap().0; + assert!(text.contains(r#""flats":{"amount":1.0,"size":6}"#) && text.contains("shaded-relief-flats"), "{text}"); +} + /// Shaded Relief's rock on steep slopes (#1913): an object turns it on, its missing keys from the /// current rock or the defaults; kept when left out; `false` removes it; a `from` not below `to` /// or a bad colour is refused; saved with the project only when set. diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index c690a04fda..96573c789d 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -772,6 +772,7 @@ fn a_balanced_reliefs_colour_bar_is_its_flat_ground() { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let Some(ColorScale::Ramp { lo, hi, colors }) = color_scale(&rl) else { panic!("a ramp") }; let colorizer = Colorizer::new(&rl.style, &r, None); diff --git a/crates/map/src/qgis/raster.rs b/crates/map/src/qgis/raster.rs index 21b552f3ad..42c0447018 100644 --- a/crates/map/src/qgis/raster.rs +++ b/crates/map/src/qgis/raster.rs @@ -103,6 +103,7 @@ fn renderer_style(node: Node, pipe: Node, r: Node, kind: &str, layer: &str, repo shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; (renderer, Stretch::None) } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index c63e562daf..f25ea11c88 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -917,6 +917,7 @@ fn raster_renderers_read_as_rustgis_raster_styles() { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, } ); assert!(report.notes.iter().any(|n| n.text.contains("saturation"))); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 874ef8a408..3a91e31530 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1453,6 +1453,36 @@ impl Rock { } } +/// Shaded Relief's detail on flat ground (#3143): each cell's height above the mean height within +/// `size` cells around it (a square `2 × size + 1` cells a side, without its no data) moves its +/// direct light by [`Flats::shift`], on flat ground only. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Flats { + pub amount: f64, + pub size: u32, +} + +impl Flats { + /// What it is turned on without settings: all of it, over 6 cells, which drew a 90 m DEM's + /// plateau cleanly where 3 was grainy. + pub const DEFAULT: Flats = Flats { amount: 1.0, size: 6 }; + /// The widest neighbourhood, in cells. + pub const MAX_SIZE: u32 = 32; + /// The slope, in degrees, from which ground isn't flat: its light is left as it was. + pub const SLOPE: f64 = 4.0; + + /// How far (0–255) the direct light of a cell on a slope of `degrees` (the ground's own, see + /// [`slope`]) moves when it stands `above` its neighbourhood's mean (in the DEM's units): + /// `amount` (0 to 1) × a weight of 1 on flat ground fading to 0 at [`Flats::SLOPE`] × `40 × + /// above` kept within ±80, so a metre up brightens by 40 and a channel darkens. 0 when that + /// isn't a number. + pub fn shift(&self, degrees: f64, above: f64) -> f64 { + let w = (1.0 - degrees / Self::SLOPE).clamp(0.0, 1.0); + let shift = self.amount.clamp(0.0, 1.0) * w * (40.0 * above).clamp(-80.0, 80.0); + if shift.is_nan() { 0.0 } else { shift } + } +} + /// The share of the colour a Shaded Relief slope turned fully from the sun keeps: its `ambient` /// when set, or else 0.25 (the light of old), and 0.5 with the `balanced` light, which keeps about /// the old light's contrast (#1977). @@ -1751,6 +1781,8 @@ pub enum RasterRenderer { /// [`relief_hillshade`]): above 0 gentle relief shows, below 0 steep ground stands out; 0, the /// default, lights as before. Cast shadows, the sky, the fill light and rock keep the ground's /// own slope. + /// `flats` brings out flat ground's detail (#3143, see [`Flats`]); none, the default, lights it + /// as before. ShadedRelief { band: usize, ramp: Option, @@ -1775,6 +1807,8 @@ pub enum RasterRenderer { aerial: f64, #[serde(default, skip_serializing_if = "is_no_light")] terrain_type: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + flats: Option, }, } @@ -2847,6 +2881,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, } } @@ -3440,6 +3475,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let (mut rocky, mut plain) = (RasterStyle::default_for(&r), RasterStyle::default_for(&r)); (rocky.renderer, plain.renderer) = (relief(Some(rock)), relief(None)); @@ -3498,6 +3534,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let relief = |altitude, ambient, balanced| tinted_relief(None, altitude, ambient, balanced); // Grey relief: white shaded, so a channel is 255 times the light. @@ -3587,6 +3624,7 @@ mod tests { shadow_softness: None, aerial, terrain_type: 0.0, + flats: None, } } @@ -3790,6 +3828,25 @@ mod tests { assert!(hillshade(&wall, 50.0, 50.0, 270.0, 45.0, 2.0) > 0, "lit without a terrain type"); } + /// Flat ground's detail (#3143): a metre above the neighbourhood brightens by 40 at full + /// amount, kept within ±80, scaled by the amount and by a weight fading from flat ground to + /// none at 4°; past that, and for what isn't a number, nothing moves. A project from before it + /// reads as none and saves as it was. + #[test] + fn flat_ground_detail_moves_the_light_by_height_on_flat_ground_only() { + let shift = |amount, degrees, above| Flats { amount, size: 6 }.shift(degrees, above); + let flat = [shift(1.0, 0.0, 1.0), shift(1.0, 0.0, -0.5), shift(1.0, 0.0, 3.0), shift(1.0, 0.0, -9.0), shift(0.5, 0.0, 1.0)]; + assert_eq!(flat, [40.0, -20.0, 80.0, -80.0, 20.0]); + let sloped = [shift(1.0, 1.0, 1.0), shift(1.0, 2.0, -1.0), shift(1.0, 4.0, 1.0), shift(1.0, 30.0, -5.0)]; + assert_eq!(sloped, [30.0, -20.0, 0.0, 0.0]); + let odd = [shift(0.0, 0.0, 1.0), shift(2.0, 0.0, 1.0), shift(1.0, 0.0, f64::NAN), shift(1.0, f64::NAN, 1.0)]; + assert_eq!(odd, [0.0, 40.0, 0.0, 0.0]); + let before = r#"{"ShadedRelief":{"band":0,"ramp":"Terrain","azimuth":315.0,"altitude":45.0,"z_factor":2.0}}"#; + let read: RasterRenderer = serde_json::from_str(before).unwrap(); + assert!(matches!(read, RasterRenderer::ShadedRelief { flats: None, .. })); + assert_eq!(serde_json::to_string(&read).unwrap(), before); + } + /// A tower lit from the east, drawn as Shaded Relief with `shadow`. fn tower(shadow: f64) -> RasterLayer { let gt = GeoTransform { origin_x: 0.0, origin_y: 0.0, pixel_width: 30.0, pixel_height: -30.0 }; diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 235583b1c8..94a5eda078 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -2975,6 +2975,7 @@ fn a_page_says_why_a_frame_drew_no_cast_shadows() { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; for shadow in [0.0, 1.0] { let map = ramp_map(relief(shadow), rustgis_map::raster::Stretch::MinMax); @@ -3075,6 +3076,7 @@ fn page_settles_with_suns(suns: &[f64]) { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let mut m = Map::new(name.clone()); assert_eq!(m.add_raster("dem", copy), 1); @@ -3149,6 +3151,7 @@ fn a_reliefs_shadow_softness_changes_its_page_only_off_the_default() { shadow_softness: softness, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let mut m = Map::new("m"); assert_eq!(m.add_raster("dem", rl), 1); @@ -3205,6 +3208,7 @@ fn a_reliefs_aerial_perspective_lightens_its_page() { shadow_softness: None, aerial, terrain_type: 0.0, + flats: None, }; let map = ramp_map(relief, rustgis_map::raster::Stretch::MinMax); colorbar_page(&map, Orientation::Horizontal, false, "").data().iter().map(|c| u64::from(*c)).sum::() @@ -3241,6 +3245,7 @@ fn a_reliefs_terrain_type_changes_its_frames_contrast_not_its_colour_bar() { shadow_softness: None, aerial: 0.0, terrain_type, + flats: None, }; let mut m = Map::new("m"); assert_eq!(m.add_raster("dem", rl), 1); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 824ea48ccb..7a090bb8d7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -12638,6 +12638,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; }; let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 1200.0, bearing: 0.0, pitch: 0.0 }; @@ -12678,6 +12679,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; // Drawn only zoomed out past a scale between the centre's and the far band's. l.max_scale = Some((centre + farthest) / 2.0); @@ -12729,6 +12731,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; // Drawn only zoomed in past 1:1: or in a group drawn only there. if grouped { diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 663a2feb98..a8f073381c 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -10,7 +10,9 @@ use rustgis_data::raster::{BandStats, ColorHint, Raster, Reprojection}; use rustgis_geom::{Coord, Extent, extent_to_merc, lonlat_to_merc}; use rustgis_map::Globe; use rustgis_map::projection::Flat; -use rustgis_map::raster::{Colorizer, RasterMask, RasterRenderer, RasterStyle, Resampling, Rock, hillshade, relief_hillshade, slope}; +use rustgis_map::raster::{ + Colorizer, Flats, RasterMask, RasterRenderer, RasterStyle, Resampling, Rock, hillshade, relief_hillshade, slope, +}; use tiny_skia::{FilterQuality, Pixmap, PixmapPaint, Transform}; use crate::View; @@ -569,6 +571,12 @@ fn draw_with( rock, terrain_type, water: light.water.filter(|_| relief.is_some()).map(|w| WaterCells::new(w, r, &grid)), + flats: match style.renderer { + RasterRenderer::ShadedRelief { flats: Some(flats), .. } if flats.amount > 0.0 => { + bands.first().map(|&b| FlatMeans::new(flats, r, &style.mask, b, full_turn_width(r), &grid)) + } + _ => None, + }, resampling, alpha_band, alpha_max: rustgis_data::raster::alpha_max(&r.data_type), @@ -742,6 +750,106 @@ impl<'a> WaterCells<'a> { } } +/// The most cells a Shaded Relief's table of sums for its detail on flat ground covers (48 MiB +/// with their counts), about 2000 × 2000 cells in view: past that each mean is summed as it comes, +/// which is slower. +const MAX_FLAT_CELLS: usize = 1 << 22; + +/// The mean heights a Shaded Relief's detail on flat ground (#3143) reads, for one draw: a table +/// of sums over the cells the view reaches, each corner holding the sum and count of the valid +/// heights above and left of it, so a cell's mean takes four reads of each, whatever its size. +struct FlatMeans { + flats: Flats, + /// The first column and row of the table's cells, and how many columns and rows. + origin: (i64, i64), + cols: i64, + rows: i64, + /// `(cols + 1) × (rows + 1)` corners, row by row. + sums: Vec, + counts: Vec, +} + +impl FlatMeans { + /// The table over the cells of `band` of `r` that the source positions in `grid` reach, with + /// a margin of the neighbourhood and a light's neighbours; empty past [`MAX_FLAT_CELLS`]. A + /// whole turn's columns (`wrap_width`) run on past its edges, as its neighbours do. A size + /// past [`Flats::MAX_SIZE`] (a project written by hand) counts as that. + fn new(flats: Flats, r: &Raster, mask: &RasterMask, band: usize, wrap_width: Option, grid: &[Option<(f64, f64)>]) -> FlatMeans { + let flats = Flats { size: flats.size.min(Flats::MAX_SIZE), ..flats }; + let (mut c0, mut r0, mut c1, mut r1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (c, row) in grid.iter().flatten() { + (c0, r0, c1, r1) = (c0.min(*c), r0.min(*row), c1.max(*c), r1.max(*row)); + } + let margin = f64::from(flats.size) + 2.0; + let (w, h) = (i64::from(r.width), i64::from(r.height)); + let edge = |v: f64, lo: i64, hi: i64| if v.is_finite() { (v.floor() as i64).clamp(lo, hi) } else { 0 }; + let (lo, hi) = if wrap_width.is_some() { (-w, 2 * w) } else { (0, w) }; + let (c0, c1) = (edge(c0 - margin, lo, hi), edge(c1 + margin + 1.0, lo, hi)); + let (r0, r1) = (edge(r0 - margin, 0, h), edge(r1 + margin + 1.0, 0, h)); + let (cols, rows) = ((c1 - c0).max(0), (r1 - r0).max(0)); + let corners = usize::try_from((cols + 1).saturating_mul(rows + 1)).unwrap_or(usize::MAX); + let mut means = FlatMeans { flats, origin: (c0, r0), cols: 0, rows: 0, sums: Vec::new(), counts: Vec::new() }; + if corners > MAX_FLAT_CELLS || cols == 0 || rows == 0 { + return means; + } + let stride = cols as usize + 1; + let (mut sums, mut counts) = (vec![0.0; corners], vec![0u32; corners]); + for j in 0..rows as usize { + let (mut sum, mut count) = (0.0, 0); + for i in 0..cols as usize { + if let Some(v) = value(r, mask, band, c0 + i as i64, r0 + j as i64, wrap_width) { + sum += f64::from(v); + count += 1; + } + let (above, at) = (j * stride + i + 1, (j + 1) * stride + i + 1); + sums[at] = sums[above] + sum; + counts[at] = counts[above] + count; + } + } + (means.cols, means.rows, means.sums, means.counts) = (cols, rows, sums, counts); + means + } + + /// The mean of the valid heights of `band` within the neighbourhood of the cell `(ci, ri)`: + /// from the table when it covers it (a whole turn's column a turn either way), or else summed + /// cell by cell. `None` when none is valid. + fn mean(&self, r: &Raster, mask: &RasterMask, band: usize, wrap_width: Option, (ci, ri): (i64, i64)) -> Option { + let s = i64::from(self.flats.size); + let (w, h) = (i64::from(r.width), i64::from(r.height)); + let (y0, y1) = ((ri - s).max(0), (ri + s + 1).min(h)); + let (x0, x1) = if wrap_width.is_some() { (ci - s, ci + s + 1) } else { ((ci - s).max(0), (ci + s + 1).min(w)) }; + let turns: &[i64] = if wrap_width.is_some() { &[0, -w, w] } else { &[0] }; + let (ox, oy) = self.origin; + for turn in turns { + let (x0, x1) = (x0 + turn, x1 + turn); + if x0 >= ox && x1 <= ox + self.cols && y0 >= oy && y1 <= oy + self.rows { + let stride = self.cols + 1; + let at = |x: i64, y: i64| ((y - oy) * stride + (x - ox)) as usize; + let (a, b, c, d) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)); + let sum = self.sums[d] - self.sums[b] - self.sums[c] + self.sums[a]; + let n = self.counts[d] + self.counts[a] - self.counts[b] - self.counts[c]; + return (n > 0).then(|| sum / f64::from(n)); + } + } + mean_by_cells(r, mask, band, wrap_width, (x0, x1), (y0, y1)) + } +} + +/// The mean of the valid heights of `band` of `r` over the columns `x` and rows `y` (half-open), +/// read one by one; `None` when none is valid. +fn mean_by_cells(r: &Raster, mask: &RasterMask, band: usize, wrap_width: Option, x: (i64, i64), y: (i64, i64)) -> Option { + let (mut sum, mut n) = (0.0, 0u32); + for row in y.0..y.1 { + for col in x.0..x.1 { + if let Some(v) = value(r, mask, band, col, row, wrap_width) { + sum += f64::from(v); + n += 1; + } + } + } + (n > 0).then(|| sum / f64::from(n)) +} + /// What pass 1 of [`draw`] reads: where each screen pixel falls in the raster, and how to /// sample it there. struct Pass1<'a> { @@ -780,6 +888,8 @@ struct Pass1<'a> { terrain_type: f64, /// The terrain's water, for Shaded Relief: its cells take its level and flat ground's light. water: Option>, + /// Shaded Relief's detail on flat ground, when it has some. + flats: Option, resampling: Resampling, alpha_band: Option, /// The alpha band's opaque value (its pixel type's: 65535 for 16 bits). @@ -1004,6 +1114,16 @@ impl Pass1<'_> { // The terrain type reshapes the gradient for the sun's light alone (#3142): the fill light // and rock below, like the cast shadows and the sky, keep the ground's own slope. let mut direct = f64::from(relief_hillshade(&z, self.cell.0, self.cell.1, az, alt, zf, self.terrain_type)); + // Flat ground's detail (#3143): its height above its neighbourhood moves its light. Ground + // as steep as `Flats::SLOPE` or more is left as it was. + if let Some(flats) = &self.flats { + let degrees = slope(&z, self.cell.0, self.cell.1); + if degrees < Flats::SLOPE + && let Some(mean) = flats.mean(r, self.mask, band, self.wrap_width, (ci, ri)) + { + direct = (direct + flats.flats.shift(degrees, centre - mean)).clamp(0.0, 255.0); + } + } if let Some(left) = left(self.shadow) { direct *= left; } @@ -1152,6 +1272,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, } } @@ -1251,6 +1372,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); @@ -1429,6 +1551,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; style.resampling = Resampling::Nearest; let view = View { @@ -1488,6 +1611,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type, + flats: None, }; style.resampling = Resampling::Nearest; let view = View { @@ -1856,6 +1980,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; style.resampling = resampling; let view = View { @@ -1870,6 +1995,139 @@ mod tests { (0..600).map(|x| pm.pixel(x, 0).map_or([0; 3], |p| [p.red(), p.green(), p.blue()])).collect() } + /// A plain at 100 m, 48 × 40 cells of 30 m (one pixel each), with low bumps, a levee half a + /// metre high, a channel a metre deep, a hill whose sides are steeper than 4° and no data in a + /// corner. + fn plain_with_landforms() -> Raster { + let (cols, rows) = (48usize, 40usize); + let data = (0..rows * cols) + .map(|i| { + let (c, r) = ((i % cols) as f32, (i / cols) as f32); + let bumps = 0.3 * ((c * 0.9).sin() * (r * 0.7).cos()); + let hill = (40.0 - 6.0 * (c - 36.0).hypot(r - 28.0)).max(0.0); + match (i % cols, i / cols) { + (0..3, 0..3) => -9999.0, + (_, 10) => 100.6 + bumps, + (20, _) => 99.0 + bumps, + _ => 100.0 + bumps + hill, + } + }) + .collect(); + let gt = GeoTransform { origin_x: 0.0, origin_y: rows as f64 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + Raster::new("plain", cols as u32, rows as u32, vec![data], gt, Crs::WebMercator, Some(-9999.0), ColorHint::Gray, "Float32").unwrap() + } + + /// Flat ground's detail (#3143) moves each cell's direct light by its height above the mean of + /// its neighbourhood, by the formula: every pixel against main's light worked out here, the + /// mean summed cell by cell. None, and an amount of 0, draw exactly today's pixels; ground as + /// steep as 4° or more keeps them; a levee brightens, a channel darkens. + #[test] + fn flat_ground_detail_moves_the_light_of_flat_ground_by_its_height() { + let r = plain_with_landforms(); + let (cols, rows) = (r.width as usize, r.height as usize); + let view = View { + width: cols as f64, + height: rows as f64, + pixels_per_point: 1.0, + camera: Camera { center: Coord::new(cols as f64 * 15.0, rows as f64 * 15.0), res: 30.0, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let height = |c: i64, row: i64| r.value(0, c, row); + let paint = |flats: Option| { + let mut style = RasterStyle::default_for(&r); + style.renderer = grey_relief(315.0, 45.0, 1.0, 0.0, 0.0); + if let RasterRenderer::ShadedRelief { flats: f, ramp, .. } = &mut style.renderer { + (*f, *ramp) = (flats, Some(rustgis_map::Ramp::Terrain)); + } + style.resampling = Resampling::Nearest; + let mut pm = Pixmap::new(cols as u32, rows as u32).unwrap(); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Lights::default()); + let px = |i: usize| pm.pixel((i % cols) as u32, (i / cols) as u32).filter(|p| p.alpha() > 0); + let drawn: Vec> = (0..rows * cols).map(|i| px(i).map(|p| [p.red(), p.green(), p.blue(), p.alpha()])).collect(); + (style, drawn) + }; + // Main's light, the detail added as the issue has it. + let (cell_x, cell_y) = r.cell_size_m(); + let want = |style: &RasterStyle, flats: Option, c: i64, row: i64| { + let centre = f64::from(height(c, row)?); + let mut z = [centre; 9]; + for (k, (dx, dy)) in [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)].into_iter().enumerate() { + z[k] = height(c + dx, row + dy).map_or(centre, f64::from); + } + let mut direct = f64::from(hillshade(&z, cell_x, cell_y, 315.0, 45.0, 1.0)); + let degrees = slope(&z, cell_x, cell_y); + if let Some(flats) = flats.filter(|f| f.amount > 0.0 && degrees < 4.0) { + let s = i64::from(flats.size); + let near: Vec = + (row - s..=row + s).flat_map(|y| (c - s..=c + s).filter_map(move |x| height(x, y))).map(f64::from).collect(); + let mean = near.iter().sum::() / near.len() as f64; + direct = (direct + flats.shift(degrees, centre - mean)).clamp(0.0, 255.0); + } + Colorizer::new(style, &r, None).color(&[centre as f32], Some(direct.round() as u8)) + }; + let (_, today) = paint(None); + let some = |amount, size| Some(Flats { amount, size }); + let red = |px: Option<[u8; 4]>| px.map_or(0, |p| i32::from(p[0])); + for flats in [None, some(0.0, 6), some(1.0, 3), Some(Flats::DEFAULT), some(0.5, 9)] { + let (style, drawn) = paint(flats); + let mut moved = 0; + for (i, px) in drawn.iter().enumerate() { + let (c, row) = ((i % cols) as i64, (i / cols) as i64); + assert_eq!(*px, want(&style, flats, c, row), "{flats:?} at {c}, {row}"); + moved += usize::from(*px != today[i]); + } + // The hill's sides keep today's light. + for (c, row) in [(36, 23), (31, 28), (40, 31)] { + assert_eq!(drawn[row * cols + c], today[row * cols + c], "{flats:?}: steep at {c}, {row}"); + } + if flats.is_none_or(|f| f.amount == 0.0) { + assert_eq!(moved, 0, "{flats:?}: today's pixels"); + } else { + assert!(moved > cols * rows / 2, "{flats:?}: {moved}"); + assert!(red(drawn[10 * cols + 10]) > red(today[10 * cols + 10]), "{flats:?}: the levee brightens"); + assert!(red(drawn[30 * cols + 20]) < red(today[30 * cols + 20]), "{flats:?}: the channel darkens"); + } + } + } + + /// A cell's mean from the table of sums is the one summed cell by cell, on a grid with no data + /// and masked heights, at its edges, across a whole turn's seam, and for the cells the table + /// doesn't cover (summed as they come). A size written past the widest is the widest. + #[test] + fn flat_means_from_the_table_are_the_cells_own() { + let (cols, rows) = (24i64, 10i64); + let data: Vec = (0..cols * rows).map(|i| if i % 17 == 5 { -9999.0 } else { ((i * 37) % 23) as f32 * 1.5 }).collect(); + let mask = RasterMask { values: vec![9.0], ..RasterMask::default() }; + for (crs, gt) in [ + (Crs::WebMercator, GeoTransform { origin_x: 0.0, origin_y: 300.0, pixel_width: 30.0, pixel_height: -30.0 }), + (Crs::LonLat, GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 15.0, pixel_height: -18.0 }), + ] { + let r = Raster::new("dem", cols as u32, rows as u32, vec![data.clone()], gt, crs, Some(-9999.0), ColorHint::Gray, "Float32") + .unwrap(); + let wrap = full_turn_width(&r); + assert_eq!(wrap.is_some(), crs == Crs::LonLat); + let all: Vec<_> = (0..cols * rows).map(|i| Some(((i % cols) as f64 + 0.5, (i / cols) as f64 + 0.5))).collect(); + let west: Vec<_> = (0..rows).map(|j| Some((0.5, j as f64 + 0.5))).collect(); + assert_eq!(FlatMeans::new(Flats { amount: 1.0, size: 10_000 }, &r, &mask, 0, wrap, &all).flats.size, Flats::MAX_SIZE); + for size in [1, 3, 6] { + for (grid, covered) in [(&all, true), (&west, false)] { + let means = FlatMeans::new(Flats { amount: 1.0, size }, &r, &mask, 0, wrap, grid); + assert_eq!(means.cols >= cols, covered, "{crs:?} {size}"); + for (c, row) in (0..cols * rows).map(|i| (i % cols, i / cols)) { + let s = i64::from(size); + let x = if wrap.is_some() { (c - s, c + s + 1) } else { ((c - s).max(0), (c + s + 1).min(cols)) }; + let cells = mean_by_cells(&r, &mask, 0, wrap, x, ((row - s).max(0), (row + s + 1).min(rows))); + let mean = means.mean(&r, &mask, 0, wrap, (c, row)); + assert!( + mean.zip(cells).is_some_and(|(a, b)| (a - b).abs() < 1e-9), + "{crs:?} {size} {c}, {row}: {mean:?} {cells:?}" + ); + } + } + } + } + } + /// Rock on steep slopes (#1913) tints by the ground's own slope before the light: the cells /// below `from` keep today's pixels, those past `to` are the rock colour lit, those between /// lean toward it; a Z factor changes the light, not the tint; and Bilinear blends the tint diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index 428e6ac404..a60cf2fcd0 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -271,6 +271,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let e = export(&layer, 2, 2, 1.0).err().unwrap_or_else(|| panic!("an archive without its shadows")); assert!(e.contains("cast shadows") && e.contains("read in place"), "{e}"); @@ -308,6 +309,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let _cancelled = rustgis_data::progress::install(Some(std::sync::Arc::new(Cancelled))); let e = export(&layer, 0, 0, 1.0).err().unwrap_or_else(|| panic!("an archive without its shadows")); diff --git a/crates/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index 87f9823c98..f4685fb78a 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -1395,6 +1395,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; }; let camera = rustgis_map::Camera { center: lonlat_to_merc(Coord::new(0.35, -0.05)), res: 300.0, bearing: 0.0, pitch: 0.0 }; @@ -1453,6 +1454,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; camera.center = lonlat_to_merc(Coord::new(0.35, -0.3)); let view = crate::View { width: 300.0, height: 200.0, pixels_per_point: 1.0, camera, sky: false }; @@ -1507,6 +1509,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let camera = rustgis_map::Camera { center: lonlat_to_merc(Coord::new(0.25, -0.1)), res: 300.0, bearing: 0.0, pitch: 0.0 }; let view = crate::View { width: 200.0, height: 200.0, pixels_per_point: 1.0, camera, sky: false }; @@ -1544,6 +1547,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let camera = rustgis_map::Camera { center: lonlat_to_merc(Coord::new(0.35, -0.05)), res: 300.0, bearing: 0.0, pitch: 0.0 }; let view = crate::View { width: 200.0, height: 200.0, pixels_per_point: 1.0, camera, sky: false }; @@ -1592,6 +1596,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; m.view.terrain.as_mut().unwrap().water.as_mut().unwrap().glint = glint; camera.center = lonlat_to_merc(Coord::new(0.35, -0.3)); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 6b19dcf3d2..eb90a7e364 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -5876,6 +5876,7 @@ mod tests { shadow_softness: None, aerial: 0.0, terrain_type: 0.0, + flats: None, }; let set = |map: &mut Map, shadow: f64, visible: bool| { let l = map.layer_mut(id).unwrap(); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index a915588801..642e226c06 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -7548,6 +7548,8 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { shadow_softness, aerial, terrain_type, + // Not in this pane yet (#3143). + flats: _, } => { use rustgis_engine::map::shadow::{SOFT_EDGE_MAX, SOFT_EDGE_MIN, soft_edge}; let (az, alt, zf, sh, sk, fl) = (*azimuth, *altitude, *z_factor, *shadow, *sky, *fill); diff --git a/docs/maintaining.md b/docs/maintaining.md index c10fe17765..3c056f2e15 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -124,6 +124,7 @@ diagram cut to a circle or to polygons), `terrain-block-polygon` (one cut to pol `null` are none), `shaded-relief-terrain-type` (a Shaded Relief's terrain type, stored as `terrain_type`, left out at 0, or set by a saved step's `"terrain"` on a Shaded Relief, where 0 and `null` light as before), +`shaded-relief-flats` (a Shaded Relief's detail on flat ground), `blank-paper` (a blank basemap's paper colour) and `normalized-legend-urls` for normalized legend addresses. Project requirements include offline map snapshots. `table-export-order` protects saved task commands, diff --git a/schema/fixtures/shaded_relief_flats.rgis b/schema/fixtures/shaded_relief_flats.rgis new file mode 100644 index 0000000000..9455b3655c --- /dev/null +++ b/schema/fixtures/shaded_relief_flats.rgis @@ -0,0 +1 @@ +{"requires":["shaded-relief-flats"],"format":2,"name":"Shaded relief flat ground detail","maps":[{"name":"Map","layers":[{"id":1,"name":"dem","visible":true,"dataset":{"name":"dem","geometry_type":"None","fields":[],"features":[],"source":null},"renderer":{"Single":{"fill":[224,123,57,170],"stroke":[134,74,34,255],"stroke_width":0.7,"size":0.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"","size":10.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto"},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":false,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"raster":{"path":"dem.tif","file_name":null,"style":{"renderer":{"ShadedRelief":{"band":0,"ramp":"Terrain","azimuth":315.0,"altitude":45.0,"z_factor":2.0,"flats":{"amount":1.0,"size":6}}},"stretch":{"PercentClip":{"low":0.5,"high":0.5}},"dra":false,"resampling":"Nearest","brightness":0.0,"contrast":0.0,"gamma":1.0,"rotation":0.0}},"geometry_rev":0}],"basemap":"Paper","camera":{"center":{"x":-4654314.293187932,"y":-2329385.2820357964},"res":64.69445270508425,"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,"terrain":null},"animation":[],"next_layer_id":2}],"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":[]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 1a5f3cd00f..0632be1eb9 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1299,7 +1299,8 @@ "layout-publication-legend", "shaded-relief-shadow-softness", "shaded-relief-aerial", - "shaded-relief-terrain-type" + "shaded-relief-terrain-type", + "shaded-relief-flats" ], "type": "string" }, @@ -1427,7 +1428,8 @@ "layout-publication-legend", "shaded-relief-shadow-softness", "shaded-relief-aerial", - "shaded-relief-terrain-type" + "shaded-relief-terrain-type", + "shaded-relief-flats" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2