From cd2d6c7879662434e63c96263f7e7915bf6a751e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 01:46:49 -0300 Subject: [PATCH 1/2] feat(render): a generalised Shaded Relief lights its heights smoothed over a size in metres (#3145, part 1) A new Shaded Relief setting, `generalize` (metres, 0 = off by default): the lights read from its slopes (the sun's, the fill light and rock) are worked out from its heights smoothed with a Gaussian of that size, three box passes each way with no data left out. The colour ramp keeps each cell's own height. The smoothing is done for each draw over the cells the view reaches and the filter's reach past them, so a part of the view is lit as the whole grid is. With more than 2^22 cells in view it smooths the mean heights of blocks of cells and reads between their centres. A geographic grid's cells are sized on the ground row by row. Saved with the layer and kept when the relief is styled again. The file capability, the read-in-place margin and the command key follow in part 2. Part of #3145. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/raster.rs | 9 +- crates/map/src/layout/tests.rs | 1 + crates/map/src/qgis/raster.rs | 1 + crates/map/src/qgis/tests.rs | 1 + crates/map/src/raster.rs | 26 +- crates/render/src/layout/tests.rs | 5 + crates/render/src/lib.rs | 3 + crates/render/src/raster.rs | 407 ++++++++++++++++++++++++++++- crates/render/src/raster_export.rs | 2 + crates/render/src/terrain/water.rs | 5 + crates/ui-egui/src/mapview.rs | 1 + crates/ui-egui/src/panes.rs | 2 + 12 files changed, 446 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 1809ce207e..70a2724858 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 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), + // And its terrain type, flat ground's detail and generalisation, likewise. + let (cur_terrain, cur_flats, cur_generalize) = match rl.style.renderer { + RasterRenderer::ShadedRelief { terrain_type, flats, generalize, .. } => (terrain_type, flats, generalize), + _ => (0.0, None, 0.0), }; RasterRenderer::ShadedRelief { band: bi, @@ -1089,6 +1089,7 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { None => cur_flats, Some(v) => relief_flats(v, cur_flats)?, }, + generalize: cur_generalize, } } other => return Err(format!("unknown raster symbology '{other}'")), diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index 2ecc9dadd4..cb294cc0aa 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -773,6 +773,7 @@ fn a_balanced_reliefs_colour_bar_is_its_flat_ground() { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; 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 42c0447018..342756eec8 100644 --- a/crates/map/src/qgis/raster.rs +++ b/crates/map/src/qgis/raster.rs @@ -104,6 +104,7 @@ fn renderer_style(node: Node, pipe: Node, r: Node, kind: &str, layer: &str, repo aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; (renderer, Stretch::None) } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 47550b3f57..3f0ff15e0a 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -918,6 +918,7 @@ fn raster_renderers_read_as_rustgis_raster_styles() { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, } ); 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 824b173953..36505db885 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1814,7 +1814,11 @@ pub enum RasterRenderer { /// 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. + /// as before. `generalize` (metres, 0 or more) generalises the relief (#3145): every light read + /// from its slopes (the sun's, the fill light and rock) is worked out from its heights smoothed + /// with a Gaussian of that size, so small landforms fade and large ones stay. The colour ramp + /// keeps each cell's own height, and so does flat ground's detail (on the smoothed slope); cast + /// shadows and the sky read the heights as they are. 0, the default, lights as before. ShadedRelief { band: usize, ramp: Option, @@ -1841,6 +1845,8 @@ pub enum RasterRenderer { terrain_type: f64, #[serde(default, skip_serializing_if = "Option::is_none")] flats: Option, + #[serde(default, skip_serializing_if = "is_no_light")] + generalize: f64, }, } @@ -2915,6 +2921,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, } } @@ -3509,6 +3516,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; let (mut rocky, mut plain) = (RasterStyle::default_for(&r), RasterStyle::default_for(&r)); (rocky.renderer, plain.renderer) = (relief(Some(rock)), relief(None)); @@ -3568,6 +3576,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; let relief = |altitude, ambient, balanced| tinted_relief(None, altitude, ambient, balanced); // Grey relief: white shaded, so a channel is 255 times the light. @@ -3658,6 +3667,7 @@ mod tests { aerial, terrain_type: 0.0, flats: None, + generalize: 0.0, } } @@ -3880,6 +3890,20 @@ mod tests { assert_eq!(serde_json::to_string(&read).unwrap(), before); } + /// A Shaded Relief's generalisation (#3145): a project from before it reads as 0 (off) and + /// saves as it was; one set is saved in metres and reads back. + #[test] + fn a_reliefs_generalisation_is_saved_only_when_set() { + 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 { generalize: 0.0, .. })); + assert_eq!(serde_json::to_string(&read).unwrap(), before); + let set = r#"{"ShadedRelief":{"band":0,"ramp":"Terrain","azimuth":315.0,"altitude":45.0,"z_factor":2.0,"generalize":120.0}}"#; + let read: RasterRenderer = serde_json::from_str(set).unwrap(); + assert!(matches!(read, RasterRenderer::ShadedRelief { generalize: 120.0, .. })); + assert_eq!(serde_json::to_string(&read).unwrap(), set); + } + /// 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 1a50e73b57..f7f80b451c 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -3035,6 +3035,7 @@ fn a_page_says_why_a_frame_drew_no_cast_shadows() { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; for shadow in [0.0, 1.0] { let map = ramp_map(relief(shadow), rustgis_map::raster::Stretch::MinMax); @@ -3136,6 +3137,7 @@ fn page_settles_with_suns(suns: &[f64]) { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; let mut m = Map::new(name.clone()); assert_eq!(m.add_raster("dem", copy), 1); @@ -3211,6 +3213,7 @@ fn a_reliefs_shadow_softness_changes_its_page_only_off_the_default() { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; let mut m = Map::new("m"); assert_eq!(m.add_raster("dem", rl), 1); @@ -3268,6 +3271,7 @@ fn a_reliefs_aerial_perspective_lightens_its_page() { aerial, terrain_type: 0.0, flats: None, + generalize: 0.0, }; let map = ramp_map(relief, rustgis_map::raster::Stretch::MinMax); colorbar_page(&map, Orientation::Horizontal, false, "").data().iter().map(|c| u64::from(*c)).sum::() @@ -3305,6 +3309,7 @@ fn a_reliefs_terrain_type_changes_its_frames_contrast_not_its_colour_bar() { aerial: 0.0, terrain_type, flats: None, + generalize: 0.0, }; 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 8fd38fabc5..77eb7c4596 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -12762,6 +12762,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; }; let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 1200.0, bearing: 0.0, pitch: 0.0 }; @@ -12803,6 +12804,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; // Drawn only zoomed out past a scale between the centre's and the far band's. l.max_scale = Some((centre + farthest) / 2.0); @@ -12855,6 +12857,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; // 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 37a96e3bcb..852e312866 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -584,6 +584,12 @@ fn draw_with( } _ => None, }, + smoothed: match style.renderer { + RasterRenderer::ShadedRelief { generalize, .. } if generalize > 0.0 => { + bands.first().map(|&b| Smoothed::new(generalize, r, &style.mask, b, full_turn_width(r), &grid)) + } + _ => None, + }, resampling, alpha_band, alpha_max: rustgis_data::raster::alpha_max(&r.data_type), @@ -783,16 +789,8 @@ impl FlatMeans { /// 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 margin = i64::from(flats.size) + 2; + let ((c0, c1), (r0, r1)) = cells_reached(r, grid, wrap_width, (margin, margin)); 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() }; @@ -842,6 +840,203 @@ impl FlatMeans { } } +/// The columns and rows (half-open) of `r` that the source positions in `grid` reach, `margin` +/// cells (columns, rows) past them, within the grid; a whole turn's columns (`wrap_width`) run on +/// a turn past either edge. +fn cells_reached(r: &Raster, grid: &[Option<(f64, f64)>], wrap_width: Option, margin: (i64, i64)) -> ((i64, i64), (i64, i64)) { + 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 (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 (mx, my) = (margin.0 as f64, margin.1 as f64); + ((edge(c0 - mx, lo, hi), edge(c1 + mx + 1.0, lo, hi)), (edge(r0 - my, 0, h), edge(r1 + my + 1.0, 0, h))) +} + +/// The most cells a generalised Shaded Relief (#3145) smooths for one draw, about 2000 × 2000 in +/// view with the filter's reach (64 MiB while it works, 32 MiB kept for the draw): past that it +/// smooths the mean heights of square blocks of cells, as few to a block as fit. +const MAX_SMOOTH_CELLS: usize = 1 << 22; + +/// The widest Gaussian a generalised Shaded Relief smooths with, in the cells it smooths. +const MAX_SIGMA_CELLS: f64 = 256.0; + +/// The radii of three box filters that, passed one after another, are about a Gaussian of +/// `sigma` cells: boxes of two neighbouring odd widths, as many of each as bring their variance +/// nearest `sigma²` (the Fast Almost Gaussian Filter's method). Under about half a cell, none. +fn box_radii(sigma: f64) -> [usize; 3] { + let s2 = if sigma.is_finite() { sigma.clamp(0.0, MAX_SIGMA_CELLS).powi(2) } else { 0.0 }; + let mut low = (4.0 * s2 + 1.0).sqrt().floor() as usize; + if low.is_multiple_of(2) { + low -= 1; + } + let l = low as f64; + let wide = ((12.0 * s2 - 3.0 * l * l - 12.0 * l - 9.0) / (-4.0 * l - 4.0)).round(); + [0.0, 1.0, 2.0].map(|i| if i < wide { (low - 1) / 2 } else { low.div_ceil(2) }) +} + +/// A generalisation's Gaussian (#3145) over `metres`, in cells of `r`, each way: along the row +/// `row` (a geographic grid's cells narrow toward the poles), and down the columns. +fn generalise_sigma(metres: f64, r: &Raster, row: f64) -> (f64, f64) { + let (x, y) = if r.crs.is_geographic() { + let (x, y) = r.cell_size(); + let lat = r.transform.to_world(0.0, row).y.to_radians().cos().abs().max(0.01); + (x.abs() * 111_320.0 * lat, y.abs() * 110_574.0) + } else { + r.cell_size_ground_m() + }; + let sigma = |cell: f64| if cell.abs() > 0.0 && metres.is_finite() { metres / cell.abs() } else { 0.0 }; + (sigma(x), sigma(y)) +} + +/// How many cells past those it lights a smoothing of `sigma` cells, in blocks of `step`, reads: +/// its boxes' reach, and a light's neighbours. +fn smoothing_reach(sigma: f64, step: i64) -> i64 { + (box_radii(sigma / step as f64).iter().sum::() as i64 + 1) * step + 2 +} + +/// Box filters of `radii` passed one after another along `line`, the cells past its ends counting +/// as 0: each pass makes every value the mean of the `2 × rad + 1` around it. What a pass spreads +/// past the ends is kept for the next one, so the line ends up as one filter of the three boxes' +/// kernel. `buf` and `tmp` are work space. +fn box_passes(line: &mut [f64], radii: [usize; 3], buf: &mut Vec, tmp: &mut Vec) { + let reach: usize = radii.iter().sum(); + if reach == 0 || line.is_empty() { + return; + } + buf.clear(); + buf.resize(reach, 0.0); + buf.extend_from_slice(line); + buf.resize(line.len() + 2 * reach, 0.0); + for rad in radii.into_iter().filter(|r| *r > 0) { + tmp.clear(); + tmp.extend_from_slice(buf); + let width = (2 * rad + 1) as f64; + let mut sum: f64 = tmp.iter().take(rad).sum(); + for (i, out) in buf.iter_mut().enumerate() { + sum += tmp.get(i + rad).copied().unwrap_or(0.0); + if i > rad { + sum -= tmp.get(i - rad - 1).copied().unwrap_or(0.0); + } + *out = sum / width; + } + } + line.copy_from_slice(&buf[reach..reach + line.len()]); +} + +/// The heights a generalised Shaded Relief (#3145) lights, for one draw: over the cells the view +/// reaches, and the filter's reach past them, the valid heights smoothed with a Gaussian of a +/// size in metres (three box passes each way), no data left out (each height is the filter's +/// weighted mean of the valid ones). With more cells than [`MAX_SMOOTH_CELLS`], it smooths the +/// mean heights of square blocks of them and reads between the blocks' centres. +struct Smoothed { + /// The first column and row of the cells it covers, and how many columns and rows of them. + origin: (i64, i64), + span: (i64, i64), + /// Cells to a block's side: 1 unless the view holds too many. + step: i64, + /// How many blocks a row. + cols: i64, + /// Each block's smoothed height, row by row, NaN where no valid height is near. + heights: Vec, +} + +impl Smoothed { + fn new(metres: f64, r: &Raster, mask: &RasterMask, band: usize, wrap_width: Option, grid: &[Option<(f64, f64)>]) -> Smoothed { + Smoothed::within(metres, r, mask, band, wrap_width, grid, MAX_SMOOTH_CELLS) + } + + /// [`Smoothed::new`] in at most `max_cells` blocks. + fn within( + metres: f64, + r: &Raster, + mask: &RasterMask, + band: usize, + wrap_width: Option, + grid: &[Option<(f64, f64)>], + max_cells: usize, + ) -> Smoothed { + let (sy, max_cells) = (generalise_sigma(metres, r, 0.0).1, max_cells.max(1)); + let mut step = 1i64; + loop { + // The filter's reach: along the rows, as far as it is widest, at the rows nearest a pole. + let reach_y = smoothing_reach(sy, step); + let (_, (r0, r1)) = cells_reached(r, grid, wrap_width, (0, reach_y)); + let sx = |row: f64| generalise_sigma(metres, r, row).0; + let reach_x = smoothing_reach(sx(r0 as f64).max(sx(r1 as f64)), step); + let ((c0, c1), (r0, r1)) = cells_reached(r, grid, wrap_width, (reach_x, reach_y)); + let span = ((c1 - c0).max(0), (r1 - r0).max(0)); + let (cols, rows) = ((span.0 + step - 1) / step, (span.1 + step - 1) / step); + let blocks = usize::try_from(cols.saturating_mul(rows)).unwrap_or(usize::MAX); + if blocks > max_cells { + step *= ((blocks as f64 / max_cells as f64).sqrt().ceil() as i64).max(2); + continue; + } + // Each block's sum of valid heights and their count, then both smoothed alike. + let (mut sums, mut counts) = (vec![0.0; blocks], vec![0.0; blocks]); + for j in 0..span.1 { + for i in 0..span.0 { + if let Some(v) = value(r, mask, band, c0 + i, r0 + j, wrap_width) { + let at = ((j / step) * cols + i / step) as usize; + sums[at] += f64::from(v); + counts[at] += 1.0; + } + } + } + let (mut line, mut buf, mut tmp) = (Vec::new(), Vec::new(), Vec::new()); + for grid in [&mut sums, &mut counts] { + for (j, row) in grid.chunks_mut(cols.max(1) as usize).enumerate() { + let centre = (r0 + j as i64 * step) as f64 + step as f64 / 2.0; + box_passes(row, box_radii(sx(centre) / step as f64), &mut buf, &mut tmp); + } + for c in 0..cols as usize { + line.clear(); + line.extend(grid.iter().skip(c).step_by(cols as usize).copied()); + box_passes(&mut line, box_radii(sy / step as f64), &mut buf, &mut tmp); + for (k, v) in line.iter().enumerate() { + grid[k * cols as usize + c] = *v; + } + } + } + // Each height in its sum's place. A weight this small is what the passes leave of none. + for (s, n) in sums.iter_mut().zip(&counts) { + *s = if *n > 1e-9 { *s / n } else { f64::NAN }; + } + return Smoothed { origin: (c0, r0), span, step, cols, heights: sums }; + } + } + + /// The smoothed height at the cell `(ci, ri)`'s centre (a whole turn's column a turn either + /// way), read between the blocks' centres when they are larger than a cell; `None` outside the + /// cells covered or where no valid height is near. + fn height(&self, (ci, ri): (i64, i64), wrap_width: Option) -> Option { + let turns: &[i64] = match wrap_width { + Some(w) => &[0, -w, w], + None => &[0], + }; + let inside = |&(dc, dr): &(i64, i64)| (0..self.span.0).contains(&dc) && (0..self.span.1).contains(&dr); + let (dc, dr) = turns.iter().map(|t| (ci + t - self.origin.0, ri - self.origin.1)).find(inside)?; + let rows = (self.span.1 + self.step - 1) / self.step; + let at = |i: i64, j: i64| self.heights.get((j.clamp(0, rows - 1) * self.cols + i.clamp(0, self.cols - 1)) as usize).copied(); + if self.step == 1 { + return at(dc, dr).filter(|h| h.is_finite()); + } + // Between the centres of the four blocks around it, those with a height. + let step = self.step as f64; + let (x, y) = ((dc as f64 + 0.5) / step - 0.5, (dr as f64 + 0.5) / step - 0.5); + let (i, j, fx, fy) = (x.floor() as i64, y.floor() as i64, x - x.floor(), y - y.floor()); + let (mut sum, mut weight) = (0.0, 0.0); + for (di, dj, w) in [(0, 0, (1.0 - fx) * (1.0 - fy)), (1, 0, fx * (1.0 - fy)), (0, 1, (1.0 - fx) * fy), (1, 1, fx * fy)] { + if let Some(h) = at(i + di, j + dj).filter(|h| h.is_finite()) { + (sum, weight) = (sum + h * w, weight + w); + } + } + (weight > 0.0).then(|| sum / weight) + } +} + /// 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 { @@ -897,6 +1092,8 @@ struct Pass1<'a> { water: Option>, /// Shaded Relief's detail on flat ground, when it has some. flats: Option, + /// A generalised Shaded Relief's smoothed heights, which its slopes' lights read. + smoothed: Option, resampling: Resampling, alpha_band: Option, /// The alpha band's opaque value (its pixel type's: 65535 for 16 bits). @@ -1108,10 +1305,19 @@ impl Pass1<'_> { let direct = f64::from(hillshade(&[0.0; 9], self.cell.0, self.cell.1, az, alt, zf)); return Lit { direct, ambient: 255.0, fill: 0.0, rock: 0.0 }; } - let mut z = [centre; 9]; + // Generalised (#3145), the window's heights are the smoothed ones, where the ground has one. + let height = |c: i64, row: i64| { + let own = value(r, self.mask, band, c, row, self.wrap_width).map(f64::from); + match &self.smoothed { + Some(smoothed) => own.and_then(|_| smoothed.height((c, row), self.wrap_width)), + None => own, + } + }; + let mid = if self.smoothed.is_some() { height(ci, ri).unwrap_or(centre) } else { centre }; + let mut z = [mid; 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() { let (dx, dy) = (dx * self.east_north.0, dy * self.east_north.1); - z[k] = value(r, self.mask, band, ci + dx, ri + dy, self.wrap_width).map(f64::from).unwrap_or(centre); + z[k] = height(ci + dx, ri + dy).unwrap_or(mid); } let at = ri as usize * r.width as usize + ci as usize; // What a grid of 0 (none) to 255 (all) leaves of a light, at `strength`. @@ -1280,6 +1486,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, } } @@ -1380,6 +1587,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); @@ -1559,6 +1767,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; style.resampling = Resampling::Nearest; let view = View { @@ -1619,6 +1828,7 @@ mod tests { aerial: 0.0, terrain_type, flats: None, + generalize: 0.0, }; style.resampling = Resampling::Nearest; let view = View { @@ -1988,6 +2198,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; style.resampling = resampling; let view = View { @@ -2135,6 +2346,178 @@ mod tests { } } + /// A valley of 30 m cells, 18° at its sides, cut by gullies 3 cells apart and up to 4 m deep, + /// with no data in a corner. + fn gullied_valley(crs: Crs, gt: GeoTransform) -> Raster { + let (cols, rows) = (64usize, 48usize); + let data = (0..rows * cols) + .map(|i| { + let (c, r) = ((i % cols) as f32, (i / cols) as f32); + match (i % cols, i / cols) { + (0..4, 0..4) => -9999.0, + _ => 500.0 + 0.15 * (c - 32.0).powi(2) + 4.0 * (c * 1.9).sin() * (r * 1.3).cos(), + } + }) + .collect(); + Raster::new("valley", cols as u32, rows as u32, vec![data], gt, crs, Some(-9999.0), ColorHint::Gray, "Float32").unwrap() + } + + fn valley_in_metres() -> Raster { + gullied_valley(Crs::WebMercator, GeoTransform { origin_x: 0.0, origin_y: 48.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }) + } + + /// The heights of `r` smoothed as a generalised relief's are (#3145), worked out the slow way: + /// each the mean of the valid heights around it weighted by the three boxes' kernel. + fn smoothed_by_kernel(r: &Raster, sigma: f64) -> impl Fn(i64, i64) -> Option + '_ { + let mut kernel = vec![1.0]; + for rad in box_radii(sigma) { + let width = 2 * rad + 1; + let mut next = vec![0.0; kernel.len() + width - 1]; + for (i, k) in kernel.iter().enumerate() { + for slot in next.iter_mut().skip(i).take(width) { + *slot += k / width as f64; + } + } + kernel = next; + } + let reach = (kernel.len() / 2) as i64; + move |c, row| { + r.value(0, c, row)?; + let (mut sum, mut weight) = (0.0, 0.0); + for dy in -reach..=reach { + for dx in -reach..=reach { + if let Some(v) = r.value(0, c + dx, row + dy) { + let w = kernel[(dx + reach) as usize] * kernel[(dy + reach) as usize]; + (sum, weight) = (sum + w * f64::from(v), weight + w); + } + } + } + Some(sum / weight) + } + } + + /// A generalised Shaded Relief (#3145) lights each cell from the heights smoothed with a + /// Gaussian of its size in metres and colours it by its own: every pixel against the light + /// worked out here from heights smoothed the slow way. 0 draws as before; 90 m on 30 m cells + /// smooths away the gullies and keeps the valley. + #[test] + fn a_generalised_relief_lights_its_smoothed_heights_and_colours_its_own() { + let r = valley_in_metres(); + 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 paint = |generalize: f64, ramp: 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 { generalize: g, ramp: tint, .. } = &mut style.renderer { + (*g, *tint) = (generalize, ramp.clone()); + } + 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) + }; + let own = |c: i64, row: i64| r.value(0, c, row).map(f64::from); + let smooth = smoothed_by_kernel(&r, 3.0); + let want = |style: &RasterStyle, height: &dyn Fn(i64, i64) -> Option, c: i64, row: i64| { + let centre = own(c, row)?; + let mid = height(c, row)?; + let mut z = [mid; 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).unwrap_or(mid); + } + let direct = hillshade(&z, 30.0, 30.0, 315.0, 45.0, 1.0); + Colorizer::new(style, &r, None).color(&[centre as f32], Some(direct)) + }; + let red = |px: Option<[u8; 4]>| px.map_or(0.0, |p| f64::from(p[0])); + // How much the light changes from one pixel to the next along the rows: the gullies. + let rough = |drawn: &[Option<[u8; 4]>]| { + let steps: Vec = (0..rows) + .flat_map(|j| (4..cols - 1).map(move |i| (j, i))) + .map(|(j, i)| (red(drawn[j * cols + i + 1]) - red(drawn[j * cols + i])).abs()) + .collect(); + steps.iter().sum::() / steps.len() as f64 + }; + let terrain = Some(rustgis_map::Ramp::Terrain); + let (style, today) = paint(0.0, terrain.clone()); + for (i, px) in today.iter().enumerate() { + let (c, row) = ((i % cols) as i64, (i / cols) as i64); + assert_eq!(*px, want(&style, &own, c, row), "0 at {c}, {row}"); + } + let (style, drawn) = paint(90.0, terrain); + for (i, px) in drawn.iter().enumerate() { + let (c, row) = ((i % cols) as i64, (i / cols) as i64); + assert_eq!(*px, want(&style, &smooth, c, row), "90 m at {c}, {row}"); + } + // In grey, the light alone. + let ((_, today), (_, drawn)) = (paint(0.0, None), paint(90.0, None)); + assert!(rough(&drawn) < rough(&today) / 3.0, "gullies: {} against {}", rough(&drawn), rough(&today)); + // The valley stays: its east side, facing the sun in the north-west, lit more than its west. + let side = |drawn: &[Option<[u8; 4]>], from: usize| { + (0..rows).map(|j| (from..from + 12).map(|i| red(drawn[j * cols + i])).sum::()).sum::() + }; + assert!(side(&drawn, 44) > side(&drawn, 8) * 1.1, "{} {}", side(&drawn, 44), side(&drawn, 8)); + } + + /// The smoothed heights over a part of the view are the whole grid's (the filter's reach past + /// it is read), across a whole turn's seam too; in blocks, when too many cells are in view, + /// they stay close to them; outside the cells covered there are none. + #[test] + fn smoothed_heights_in_part_of_the_view_are_the_whole_grids() { + let mask = RasterMask::default(); + for r in [ + valley_in_metres(), + gullied_valley(Crs::LonLat, GeoTransform { origin_x: -180.0, origin_y: 0.0, pixel_width: 5.625, pixel_height: -0.01 }), + ] { + let (cols, rows, wrap) = (i64::from(r.width), i64::from(r.height), full_turn_width(&r)); + let at = |c: i64, row: i64| Some((c as f64 + 0.5, row as f64 + 0.5)); + let all: Vec<_> = (0..cols * rows).map(|i| at(i % cols, i / cols)).collect(); + let west: Vec<_> = (0..rows).flat_map(|row| [at(0, row), at(1, row)]).collect(); + let metres = 3.0 * r.cell_size_ground_m().0; + let whole = Smoothed::new(metres, &r, &mask, 0, wrap, &all); + let part = Smoothed::new(metres, &r, &mask, 0, wrap, &west); + assert!(part.span.0 < cols + 2 * wrap.unwrap_or(0), "{:?}: a part", r.crs); + for (c, row) in (0..rows).flat_map(|row| (0..2).map(move |c| (c, row))) { + let (a, b) = (whole.height((c, row), wrap), part.height((c, row), wrap)); + assert!(a.zip(b).is_some_and(|(a, b)| (a - b).abs() < 1e-9) || (a.is_none() && b.is_none()), "{c}, {row}: {a:?} {b:?}"); + assert!(a.is_some() || r.value(0, c, row).is_none(), "{c}, {row}: a valid cell has one"); + } + assert_eq!(part.height((cols / 2, rows / 2), wrap), None, "outside the part"); + if wrap.is_some() { + let (a, b) = (part.height((cols - 1, 5), wrap), whole.height((cols - 1, 5), wrap)); + assert!(a.zip(b).is_some_and(|(a, b)| (a - b).abs() < 1e-9), "the seam's other side: {a:?} {b:?}"); + } + // In blocks of two cells or more, with the size of the Gaussian twice as wide. + let blocks = Smoothed::within(2.0 * metres, &r, &mask, 0, wrap, &all, (cols * rows / 3) as usize); + let fine = Smoothed::new(2.0 * metres, &r, &mask, 0, wrap, &all); + assert!(blocks.step >= 2 && blocks.heights.len() <= (cols * rows / 3) as usize, "{}", blocks.step); + for (c, row) in (8..rows - 8).flat_map(|row| (8..cols - 8).map(move |c| (c, row))) { + let (a, b) = (fine.height((c, row), wrap).unwrap(), blocks.height((c, row), wrap).unwrap()); + assert!((a - b).abs() < 1.0, "{c}, {row}: {a} {b}"); + } + } + } + + /// Three box passes add up to about the Gaussian's spread (within a fifth of a cell from one + /// cell up to the widest), none under half a cell or for a size that isn't one. + #[test] + fn box_radii_spread_as_far_as_the_gaussian() { + for sigma in (0..=2600).map(|i| 1.0 + f64::from(i) * 0.098) { + let variance: f64 = box_radii(sigma).iter().map(|r| ((2 * r + 1).pow(2) - 1) as f64 / 12.0).sum(); + assert!((variance.sqrt() - sigma.min(MAX_SIGMA_CELLS)).abs() < 0.2, "{sigma}: {}", variance.sqrt()); + } + for sigma in [0.0, 0.3, 0.45, -2.0, f64::NAN, f64::INFINITY] { + assert_eq!(box_radii(sigma), [0, 0, 0], "{sigma}"); + } + } + /// 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 a9f2c8eea1..e7340077b0 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -288,6 +288,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; 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}"); @@ -326,6 +327,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; 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 f4685fb78a..a8e7ca3e52 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -1396,6 +1396,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; }; let camera = rustgis_map::Camera { center: lonlat_to_merc(Coord::new(0.35, -0.05)), res: 300.0, bearing: 0.0, pitch: 0.0 }; @@ -1455,6 +1456,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; 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 }; @@ -1510,6 +1512,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; 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 }; @@ -1548,6 +1551,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; 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 }; @@ -1597,6 +1601,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; 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 eb90a7e364..0a6ef9d536 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -5877,6 +5877,7 @@ mod tests { aerial: 0.0, terrain_type: 0.0, flats: None, + generalize: 0.0, }; 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 cd80a89420..66393e7be5 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -7670,6 +7670,8 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { aerial, terrain_type, flats, + // Its pane field comes with #3145's last part. + generalize: _, } => { 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); From e298ce21331cefbe774bdffe7fc5a8ac2f244386 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 03:14:13 -0300 Subject: [PATCH 2/2] fix(render): a generalised relief keeps its size past 256 cells, round a narrow whole turn and on a turned raster (#3145, part 1) From review: - A Gaussian wider than 256 cells is smoothed in blocks wide enough to hold it, not cut to 256 cells (30 km on 30 m cells was 7.68 km). - A whole turn narrower than the filter's reach reads every repeated column the filter needs, round the turn. - A turned raster's smoothing covers where its pixels fall once turned back, not the unturned box (part of the view was lit flat). - The fixture schema/fixtures/shaded_relief_generalize.rgis and the file capability shaded-relief-generalize it requires come forward from part 2. - The docs of the relief's light and of the renderer say the fill light and rock read the smoothed slope when it is generalised. Part of #3145. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 21 +++- crates/engine/src/tests.rs | 25 ++++ crates/map/src/raster.rs | 2 +- crates/render/src/raster.rs | 117 ++++++++++++++++-- docs/maintaining.md | 2 + schema/fixtures/shaded_relief_generalize.rgis | 1 + schema/project.schema.json | 6 +- 8 files changed, 159 insertions(+), 16 deletions(-) create mode 100644 schema/fixtures/shaded_relief_generalize.rgis diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 4672136783..56b30843c5 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -149,6 +149,7 @@ pub const CAPABILITIES: &[&str] = &[ "shaded-relief-terrain-type", "shaded-relief-flats", "layout-publication-crs", + "shaded-relief-generalize", ]; /// 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 c0bedff106..41b4ae8a3b 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1248,6 +1248,15 @@ 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 generalises its Shaded Relief (#3145): an older reader would light every +/// landform and save the layer again without the setting. +fn sets_generalize(layer: &Layer) -> bool { + layer + .raster + .as_ref() + .is_some_and(|r| matches!(&r.style.renderer, RasterRenderer::ShadedRelief { generalize, .. } if *generalize != 0.0)) +} + /// 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 { @@ -1318,6 +1327,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (sets_aerial(layer), "shaded-relief-aerial"), (sets_terrain_type(layer), "shaded-relief-terrain-type"), (sets_flats(layer), "shaded-relief-flats"), + (sets_generalize(layer), "shaded-relief-generalize"), (layer.size_by.is_some(), super::SIZE_BY_CAPABILITY), (layer.has_picture_markers(), "picture-markers"), (layer.any_picture(svg_picture), "svg-markers"), @@ -1357,8 +1367,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static let (mut polygon, mut svg, mut raster_mask, mut class_order) = (false, false, 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, mut flats) = - (false, false, false, false, false, false, false); + let (mut crisp, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type, mut flats, mut generalize) = + (false, 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. @@ -1399,6 +1409,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static aerial |= map.layers.iter().any(sets_aerial); terrain_type |= map.layers.iter().any(sets_terrain_type); flats |= map.layers.iter().any(sets_flats); + generalize |= map.layers.iter().any(sets_generalize); 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)); @@ -1426,6 +1437,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (aerial, "shaded-relief-aerial"), (terrain_type, "shaded-relief-terrain-type"), (flats, "shaded-relief-flats"), + (generalize, "shaded-relief-generalize"), (legends, "normalized-legend-urls"), (sized, super::SIZE_BY_CAPABILITY), (pictures, "picture-markers"), @@ -3883,7 +3895,9 @@ 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", "flats"] { + for field in + ["shadow", "sky", "fill", "rock", "ambient", "balanced", "shadow_softness", "aerial", "terrain_type", "flats", "generalize"] + { 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(), @@ -3905,6 +3919,7 @@ mod tests { "aerial" => "shaded-relief-aerial", "terrain_type" => "shaded-relief-terrain-type", "flats" => "shaded-relief-flats", + "generalize" => "shaded-relief-generalize", _ => "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 13d763f9ca..e394634092 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8132,6 +8132,31 @@ fn shaded_relief_keeps_its_flat_ground_detail() { assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["shaded-relief-flats"])); } +/// A Shaded Relief's generalisation (#3145) 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_generalisation() { + let generalize = |s: &Session| match s.map().layers.iter().find_map(|l| l.raster.as_ref()).map(|r| &r.style.renderer) { + Some(rustgis_map::RasterRenderer::ShadedRelief { generalize, .. }) => *generalize, + other => panic!("{other:?}"), + }; + let fixture = Project::from_json(include_str!("../../../schema/fixtures/shaded_relief_generalize.rgis")).unwrap(); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["shaded-relief-generalize"])); + assert_eq!(generalize(&Session::new(fixture)), 90.0); + let mut s = with_raster(); + s.run("raster.symbology", &json!({"type": "shadedRelief"})).unwrap(); + assert_eq!(generalize(&s), 0.0, "none by default"); + if let Some(rustgis_map::RasterRenderer::ShadedRelief { generalize, .. }) = + s.map_mut().layers.iter_mut().find_map(|l| l.raster.as_mut()).map(|r| &mut r.style.renderer) + { + *generalize = 120.0; + } + s.run("raster.symbology", &json!({"type": "shadedRelief", "azimuth": 200, "shadow": 0.5})).unwrap(); + assert_eq!(generalize(&s), 120.0, "kept"); + let text = s.project.saved_text(None).unwrap().0; + assert!(text.contains(r#""generalize":120.0"#) && text.contains("shaded-relief-generalize"), "{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/raster.rs b/crates/map/src/raster.rs index 36505db885..dc0de810f1 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1812,7 +1812,7 @@ pub enum RasterRenderer { /// (−1 to 1) reshapes each cell's gradient for the sun's light only (#3142, see /// [`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. + /// own slope (the smoothed one for the fill light and rock when it is generalised). /// `flats` brings out flat ground's detail (#3143, see [`Flats`]); none, the default, lights it /// as before. `generalize` (metres, 0 or more) generalises the relief (#3145): every light read /// from its slopes (the sun's, the fill light and rock) is worked out from its heights smoothed diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 852e312866..2dbb3c35d3 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -586,7 +586,19 @@ fn draw_with( }, smoothed: match style.renderer { RasterRenderer::ShadedRelief { generalize, .. } if generalize > 0.0 => { - bands.first().map(|&b| Smoothed::new(generalize, r, &style.mask, b, full_turn_width(r), &grid)) + // A turned raster's pixels are found turned back about its centre: the smoothing + // covers where they fall, not the unturned box. + let turned: Vec<_> = if rotated { + let back = |(x, y): (f64, f64)| { + let (dx, dy) = (x - centre.0, y - centre.1); + source(r, view, place, direct.as_ref(), k, centre.0 + dx * cos - dy * sin, centre.1 + dx * sin + dy * cos) + }; + (0..gw * gh).map(|i| back(((x0 + i % gw * STEP) as f64, (y0 + i / gw * STEP) as f64))).collect() + } else { + Vec::new() + }; + let reached = if rotated { &turned } else { &grid }; + bands.first().map(|&b| Smoothed::new(generalize, r, &style.mask, b, full_turn_width(r), reached)) } _ => None, }, @@ -842,7 +854,7 @@ impl FlatMeans { /// The columns and rows (half-open) of `r` that the source positions in `grid` reach, `margin` /// cells (columns, rows) past them, within the grid; a whole turn's columns (`wrap_width`) run on -/// a turn past either edge. +/// past either edge, round the turn as often as the margin reaches. fn cells_reached(r: &Raster, grid: &[Option<(f64, f64)>], wrap_width: Option, margin: (i64, i64)) -> ((i64, i64), (i64, i64)) { 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() { @@ -850,7 +862,7 @@ fn cells_reached(r: &Raster, grid: &[Option<(f64, f64)>], wrap_width: Option, tmp: &mut /// The heights a generalised Shaded Relief (#3145) lights, for one draw: over the cells the view /// reaches, and the filter's reach past them, the valid heights smoothed with a Gaussian of a /// size in metres (three box passes each way), no data left out (each height is the filter's -/// weighted mean of the valid ones). With more cells than [`MAX_SMOOTH_CELLS`], it smooths the -/// mean heights of square blocks of them and reads between the blocks' centres. +/// weighted mean of the valid ones). With more cells than [`MAX_SMOOTH_CELLS`], or a Gaussian +/// wider than [`MAX_SIGMA_CELLS`] cells, it smooths the mean heights of square blocks of them and +/// reads between the blocks' centres. struct Smoothed { /// The first column and row of the cells it covers, and how many columns and rows of them. origin: (i64, i64), span: (i64, i64), - /// Cells to a block's side: 1 unless the view holds too many. + /// Cells to a block's side: 1 unless the view holds too many or the Gaussian is too wide. step: i64, /// How many blocks a row. cols: i64, @@ -965,7 +978,14 @@ impl Smoothed { let reach_y = smoothing_reach(sy, step); let (_, (r0, r1)) = cells_reached(r, grid, wrap_width, (0, reach_y)); let sx = |row: f64| generalise_sigma(metres, r, row).0; - let reach_x = smoothing_reach(sx(r0 as f64).max(sx(r1 as f64)), step); + let widest = sx(r0 as f64).max(sx(r1 as f64)); + // Blocks wide enough that the Gaussian fits the widest kernel. + let fits = (widest.max(sy) / MAX_SIGMA_CELLS).ceil(); + if fits.is_finite() && fits > step as f64 { + step = fits as i64; + continue; + } + let reach_x = smoothing_reach(widest, step); let ((c0, c1), (r0, r1)) = cells_reached(r, grid, wrap_width, (reach_x, reach_y)); let span = ((c1 - c0).max(0), (r1 - r0).max(0)); let (cols, rows) = ((span.0 + step - 1) / step, (span.1 + step - 1) / step); @@ -1294,8 +1314,9 @@ impl Pass1<'_> { /// [`relief_hillshade`]) times what the cast shadows leave on it; and the /// ambient light, scaled by the sky the cell sees; the fill light (see [`FILL_ALTITUDE`]), which /// nothing shadows; and its share of rock (see [`Rock::share`]), from the ground's own slope in - /// the same window. `centre` is the cell's height, and stands in for a neighbour that is no - /// data, masked or outside the grid. Every light a cell gets is worked out here, so that + /// the same window. Generalised (#3145), the window holds the smoothed heights (see + /// [`Smoothed`]). `centre` is the cell's height, and stands in for a neighbour that is no data, + /// masked or outside the grid. Every light a cell gets is worked out here, so that /// [`blend`] smooths each of them. fn light(&self, band: usize, (az, alt, zf): (f64, f64, f64), (ci, ri): (i64, i64), centre: f64) -> Lit { let r = self.r; @@ -2474,7 +2495,7 @@ mod tests { let mask = RasterMask::default(); for r in [ valley_in_metres(), - gullied_valley(Crs::LonLat, GeoTransform { origin_x: -180.0, origin_y: 0.0, pixel_width: 5.625, pixel_height: -0.01 }), + gullied_valley(Crs::LonLat, GeoTransform { origin_x: -180.0, origin_y: 2.4, pixel_width: 5.625, pixel_height: -0.1 }), ] { let (cols, rows, wrap) = (i64::from(r.width), i64::from(r.height), full_turn_width(&r)); let at = |c: i64, row: i64| Some((c as f64 + 0.5, row as f64 + 0.5)); @@ -2505,6 +2526,82 @@ mod tests { } } + /// A turned raster is lit from smoothed heights wherever its pixels fall, not only where the + /// view's unturned box does: a tilted plane, which smoothing leaves as it is, drawn turned a + /// quarter in a long, low view is lit as it is without the generalisation. + #[test] + fn a_turned_generalised_relief_is_smoothed_wherever_its_pixels_fall() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 400.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let plane = (0..400 * 400).map(|i| 100.0 + 9.0 * (i % 400) as f32 + 4.0 * (i / 400) as f32).collect(); + let r = Raster::new("plane", 400, 400, vec![plane], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let view = View { + width: 200.0, + height: 20.0, + pixels_per_point: 1.0, + camera: Camera { center: Coord::new(6000.0, 6000.0), res: 30.0, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let paint = |generalize: f64| { + 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 { generalize: g, .. } = &mut style.renderer { + *g = generalize; + } + (style.resampling, style.rotation) = (Resampling::Nearest, 90.0); + let mut pm = Pixmap::new(200, 20).unwrap(); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Lights::default()); + pm.data().to_vec() + }; + let (today, generalised) = (paint(0.0), paint(60.0)); + let differ = today.chunks(4).zip(generalised.chunks(4)).filter(|(a, b)| a != b).count(); + assert_eq!(differ, 0, "pixels lit otherwise"); + } + + /// A generalisation wider than [`MAX_SIGMA_CELLS`] cells is smoothed in blocks wide enough to + /// hold it, not cut to the widest: 30 km on 30 m cells isn't 7.68 km. + #[test] + fn a_generalisation_past_the_widest_kernel_is_smoothed_in_blocks() { + let r = valley_in_metres(); + let all: Vec<_> = (0..64 * 48).map(|i| Some(((i % 64) as f64 + 0.5, (i / 64) as f64 + 0.5))).collect(); + let at = |metres| Smoothed::new(metres, &r, &RasterMask::default(), 0, None, &all); + let (widest, past) = (at(MAX_SIGMA_CELLS * 30.0), at(30_000.0)); + assert_eq!(widest.step, 1); + assert!(past.step >= 4, "{}", past.step); + assert_ne!(past.height((32, 24), None), widest.height((32, 24), None)); + } + + /// On a whole turn narrower than the filter's reach, a height takes in every column the + /// filter reaches, round the turn as often as it does: as filtering the turn periodically. + #[test] + fn a_whole_turn_narrower_than_the_filter_is_smoothed_round_it() { + let gt = GeoTransform { origin_x: -180.0, origin_y: 1.35, pixel_width: 90.0, pixel_height: -0.9 }; + let r = + Raster::new("turn", 4, 3, vec![[0.0, 0.0, 0.0, 100.0].repeat(3)], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let wrap = full_turn_width(&r); + assert_eq!(wrap, Some(4)); + let metres = 2.5 * generalise_sigma(1.0, &r, 1.5).0.recip(); + let all: Vec<_> = (0..12).map(|i| Some(((i % 4) as f64 + 0.5, (i / 4) as f64 + 0.5))).collect(); + let smoothed = Smoothed::new(metres, &r, &RasterMask::default(), 0, wrap, &all); + // The three boxes' kernel, wrapped round the four columns. + let mut kernel = vec![1.0]; + for rad in box_radii(2.5) { + let mut next = vec![0.0; kernel.len() + 2 * rad]; + for (i, k) in kernel.iter().enumerate() { + for slot in next.iter_mut().skip(i).take(2 * rad + 1) { + *slot += k / (2 * rad + 1) as f64; + } + } + kernel = next; + } + let reach = (kernel.len() / 2) as i64; + for c in 0..4 { + let want: f64 = + kernel.iter().enumerate().map(|(k, w)| w * if (c + k as i64 - reach).rem_euclid(4) == 3 { 100.0 } else { 0.0 }).sum(); + let got = smoothed.height((c, 1), wrap).unwrap(); + assert!((got - want).abs() < 1e-9, "{c}: {got} {want}"); + } + } + /// Three box passes add up to about the Gaussian's spread (within a fifth of a cell from one /// cell up to the widest), none under half a cell or for a size that isn't one. #[test] diff --git a/docs/maintaining.md b/docs/maintaining.md index f328d8f255..4b406c9036 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -131,6 +131,8 @@ diagram cut to a circle or to polygons), `terrain-block-polygon` (one cut to pol 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, stored at any amount, or set by a saved step, where `false`, `null` and an amount of 0 are none), +`shaded-relief-generalize` (a Shaded Relief generalised, its lights read from its heights smoothed +over `generalize` metres, left out at 0), `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_generalize.rgis b/schema/fixtures/shaded_relief_generalize.rgis new file mode 100644 index 0000000000..dc02b1a456 --- /dev/null +++ b/schema/fixtures/shaded_relief_generalize.rgis @@ -0,0 +1 @@ +{"requires":["shaded-relief-generalize"],"format":2,"name":"Shaded relief generalised","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,"generalize":90.0}},"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 bc495cbbb6..85ab384148 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1307,7 +1307,8 @@ "shaded-relief-aerial", "shaded-relief-terrain-type", "shaded-relief-flats", - "layout-publication-crs" + "layout-publication-crs", + "shaded-relief-generalize" ], "type": "string" }, @@ -1443,7 +1444,8 @@ "shaded-relief-aerial", "shaded-relief-terrain-type", "shaded-relief-flats", - "layout-publication-crs" + "layout-publication-crs", + "shaded-relief-generalize" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2