From 3cec3e1d804a1d3d311c5ca140252f04421eaa9e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 09:42:42 -0300 Subject: [PATCH 1/4] feat(map): a generalised relief casts its shadows and sees its sky from its smoothed heights (#3145, part 3) Cast shadows and the sky of a Shaded Relief with a generalisation are now traced over its whole grid smoothed with the same Gaussian as its light, in blocks past 256 cells as the renderer smooths them, so their shapes match the light. The size is part of the light grid's key, so a new size is a grid of its own; at 0 they are traced over the heights as they are. The smoothing (box radii and passes, the Gaussian in cells, the block size) moves from the renderer to rustgis_map::generalize, which both use. Part of #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 185 +++++++++++++++++++++++++++++++++++ crates/map/src/lib.rs | 1 + crates/map/src/raster.rs | 107 ++++++++++++++++++-- crates/render/src/raster.rs | 73 +------------- 4 files changed, 290 insertions(+), 76 deletions(-) create mode 100644 crates/map/src/generalize.rs diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs new file mode 100644 index 0000000000..817700032d --- /dev/null +++ b/crates/map/src/generalize.rs @@ -0,0 +1,185 @@ +//! A generalised Shaded Relief's smoothing (#3145): a Gaussian of a size in metres, made of three +//! box passes each way (the Fast Almost Gaussian Filter's method). The renderer smooths the cells +//! a view reaches with it; cast shadows and the sky are traced over the whole grid smoothed here. + +use std::sync::atomic::{AtomicBool, Ordering}; + +use rustgis_data::raster::{ColorHint, Raster}; + +use crate::raster::RasterMask; + +/// The widest Gaussian a generalised Shaded Relief smooths with, in the cells it smooths. +pub 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. +pub 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 over `metres`, in cells of `r` made `scale` times larger (a coarser +/// level's), each way: along the row `row` of `r` (a geographic grid's cells narrow toward the +/// poles), and down the columns. +pub fn generalise_sigma(metres: f64, r: &Raster, scale: (f64, f64), 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 * scale.0), sigma(y * scale.1)) +} + +/// Cells to a block's side for a Gaussian of `sigma` cells at its widest: as many as make it fit +/// [`MAX_SIGMA_CELLS`], at least 1. +pub fn block_step(sigma: f64) -> i64 { + // At most a block of 2³² cells a side, larger than any grid, so the sums stay in range. + let fits = (sigma / MAX_SIGMA_CELLS).ceil(); + if fits > 1.0 { fits.min(4_294_967_296.0) as i64 } else { 1 } +} + +/// 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. +pub 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 of `band` of `r` smoothed with a Gaussian of `metres` as a whole grid, for the +/// traces of cast shadows and the sky: a raster of one band, each valid cell the filter's weighted +/// mean of the valid heights around it (no data and masked heights left out), the others NaN. +/// Past [`MAX_SIGMA_CELLS`] cells it smooths the mean heights of square blocks of cells, as the +/// renderer does, and reads between the blocks' centres. The grid's edges stop the filter, a +/// whole turn's too. `None` when `stop` is set, or there isn't the memory for it (8 bytes a cell +/// while it works, then 4). +pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool) -> Option { + let (w, h) = (i64::from(r.width), i64::from(r.height)); + let sy = generalise_sigma(metres, r, (1.0, 1.0), 0.0).1; + let sx = |row: f64| generalise_sigma(metres, r, (1.0, 1.0), row).0; + let step = block_step(sx(0.0).max(sx(h as f64)).max(sy)).min(w.max(h).max(1)); + let (cols, rows) = ((w + step - 1) / step, (h + step - 1) / step); + let blocks = usize::try_from(cols.checked_mul(rows)?).ok()?; + // Each block's sum of valid heights and their count, in `f32`: each pass keeps them means. + let (mut sums, mut counts) = (Vec::new(), Vec::new()); + sums.try_reserve_exact(blocks).ok()?; + counts.try_reserve_exact(blocks).ok()?; + sums.resize(blocks, 0.0f32); + counts.resize(blocks, 0.0f32); + let height = |c: i64, row: i64| r.value(band, c, row).filter(|v| !mask.hides(*v)); + for row in 0..h { + for c in 0..w { + if let Some(v) = height(c, row) { + let at = ((row / step) * cols + c / step) as usize; + (sums[at], counts[at]) = (sums[at] + 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, block_row) in grid.chunks_mut(cols as usize).enumerate() { + if stop.load(Ordering::Relaxed) { + return None; + } + line.clear(); + line.extend(block_row.iter().map(|v| f64::from(*v))); + let radii = box_radii(sx((j as i64 * step) as f64 + step as f64 / 2.0) / step as f64); + box_passes(&mut line, radii, &mut buf, &mut tmp); + block_row.iter_mut().zip(&line).for_each(|(v, l)| *v = *l as f32); + } + for c in 0..cols as usize { + line.clear(); + line.extend(grid.iter().skip(c).step_by(cols as usize).map(|v| f64::from(*v))); + 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 as f32; + } + } + } + // Each block's 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 { f32::NAN }; + } + drop(counts); + let block = |i: i64, j: i64| sums.get((j.clamp(0, rows - 1) * cols + i.clamp(0, cols - 1)) as usize).copied().filter(|v| v.is_finite()); + let mut heights = Vec::new(); + heights.try_reserve_exact(usize::try_from(w * h).ok()?).ok()?; + for row in 0..h { + for c in 0..w { + let v = height(c, row).and_then(|_| { + if step == 1 { + return block(c, row); + } + // Between the centres of the four blocks around it, those with a height. + let step = step as f64; + let (x, y) = ((c as f64 + 0.5) / step - 0.5, (row 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, k) 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(b) = block(i + di, j + dj) { + (sum, weight) = (sum + f64::from(b) * k, weight + k); + } + } + (weight > 0.0).then(|| (sum / weight) as f32) + }); + heights.push(v.unwrap_or(f32::NAN)); + } + } + Raster::new(&r.name, r.width, r.height, vec![heights], r.transform, r.crs, None, ColorHint::Gray, "Float32").ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_data::raster::{Crs, GeoTransform}; + + /// The whole grid smoothed in blocks (a Gaussian past the widest kernel) keeps an even + /// height even, its no data NaN; stopped, it gives nothing. + #[test] + fn a_whole_grid_is_smoothed_in_blocks_past_the_widest_kernel_and_stops() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 600.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let data = (0..600 * 600).map(|i| if i % 600 < 3 && i / 600 < 3 { -9999.0 } else { 250.0 }).collect(); + let r = Raster::new("even", 600, 600, vec![data], gt, Crs::WebMercator, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); + assert!(block_step(generalise_sigma(10_000.0, &r, (1.0, 1.0), 0.0).0) >= 2); + let s = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(false)).unwrap(); + for (i, v) in s.bands[0].data.iter().enumerate() { + if i % 600 < 3 && i / 600 < 3 { + assert!(v.is_nan(), "{i}"); + } else { + assert!((v - 250.0).abs() < 1e-3, "{i}: {v}"); + } + } + assert!(smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(true)).is_none()); + } +} diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 1a18af2a96..9ffb0bd656 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -10,6 +10,7 @@ pub mod design; pub mod diagram; pub mod effects; pub mod fills; +pub mod generalize; pub mod geolibre; mod geometry_kinds; pub mod globe; diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index f94b29ca6c..72a6bf0312 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1053,7 +1053,12 @@ impl RasterLayer { crate::shadow::MAX_BROWSER_CELLS )); } - let key = LightKey { band, grid, z_factor, mask: self.style.mask.clone() }; + // Traced over the heights smoothed as the relief's light is (#3145), at the size drawn. + let generalize = match self.style.renderer { + RasterRenderer::ShadedRelief { generalize, .. } if generalize > 0.0 => generalize.min(GENERALIZE_MAX), + _ => 0.0, + }; + let key = LightKey { band, grid, z_factor, mask: self.style.mask.clone(), generalize }; let mut start = None; let work = { let Ok(mut jobs) = self.cast.0.lock() else { return CastShadows::None }; @@ -1133,6 +1138,8 @@ struct LightKey { grid: Grid, z_factor: f64, mask: RasterMask, + /// The generalisation it is traced over the heights smoothed by, in metres (#3145); 0, none. + generalize: f64, } /// Which grid: the light cast shadows leave for a sun, or the sky seen. @@ -1303,11 +1310,28 @@ fn start_light(r: Arc, key: LightKey, work: Arc) { let run = move || { drop(LIGHT_HOLD.read().unwrap_or_else(|e| e.into_inner())); let threads = rustgis_data::threads::max(); - let traced = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match key.grid { - Grid::Shadows { azimuth, altitude, soft_edge } => { - crate::shadow::light(&r, key.band, &key.mask, azimuth, altitude, soft_edge, key.z_factor, threads, &work.stop) + let traced = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + // A generalised relief's are traced over its smoothed heights, one band with no mask. + let smoothed = if key.generalize > 0.0 { + match crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop) { + Some(smoothed) => Some(smoothed), + None if work.stop.load(std::sync::atomic::Ordering::Relaxed) => return Err(crate::shadow::Unlit::Stopped), + None => return Err(crate::shadow::Unlit::NoMemory), + } + } else { + None + }; + let unmasked = RasterMask::default(); + let (heights, band, mask) = match &smoothed { + Some(smoothed) => (smoothed, 0, &unmasked), + None => (r.as_ref(), key.band, &key.mask), + }; + match key.grid { + Grid::Shadows { azimuth, altitude, soft_edge } => { + crate::shadow::light(heights, band, mask, azimuth, altitude, soft_edge, key.z_factor, threads, &work.stop) + } + Grid::Sky => crate::shadow::sky(heights, band, mask, key.z_factor, threads, &work.stop), } - Grid::Sky => crate::shadow::sky(&r, key.band, &key.mask, key.z_factor, threads, &work.stop), })); let not_drawn = key.grid.not_drawn(); match traced { @@ -1822,7 +1846,8 @@ pub enum RasterRenderer { /// 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. + /// shadows and the sky are traced over the whole grid smoothed alike (see + /// [`crate::generalize::smoothed`]). 0, the default, lights as before. ShadedRelief { band: usize, ramp: Option, @@ -3908,6 +3933,76 @@ mod tests { assert_eq!(serde_json::to_string(&read).unwrap(), set); } + /// `r`'s heights smoothed the slow way, as a generalised relief's are (#3145): each the mean of + /// the valid heights around it weighted by the three boxes' kernel of `sigma` cells. + fn smoothed_by_kernel(r: &Raster, sigma: f64) -> Raster { + let mut kernel = vec![1.0]; + for rad in crate::generalize::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; + let (w, h) = (i64::from(r.width), i64::from(r.height)); + let data = (0..w * h) + .map(|i| { + let (c, row) = (i % w, i / w); + r.value(0, c, row).map_or(f32::NAN, |_| { + 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 k = kernel[(dx + reach) as usize] * kernel[(dy + reach) as usize]; + (sum, weight) = (sum + k * f64::from(v), weight + k); + } + } + } + (sum / weight) as f32 + }) + }) + .collect(); + Raster::new("smoothed", r.width, r.height, vec![data], r.transform, r.crs, None, ColorHint::Gray, "Float32").unwrap() + } + + /// A generalised relief (#3145) casts its shadows and sees its sky from its heights smoothed as + /// its light is: each grid is the one traced over the heights smoothed the slow way (within a + /// level, for the rounding of the heights kept); at 0, over the heights as they are; a tower's + /// sharp shadow becomes a hill's soft one. + #[test] + fn a_generalised_relief_casts_shadows_and_sees_its_sky_from_its_smoothed_heights() { + use std::sync::atomic::AtomicBool; + let grids = |metres: f64| { + let mut rl = tower(1.0); + if let RasterRenderer::ShadedRelief { generalize, sky, .. } = &mut rl.style.renderer { + (*generalize, *sky) = (metres, 1.0); + } + let CastShadows::Ready(shadow) = rl.cast_shadows(true, (0, 1), || {}) else { panic!("{metres}: shadows") }; + let CastShadows::Ready(sky) = rl.sky_view(true, (0, 1), || {}) else { panic!("{metres}: sky") }; + (shadow, sky) + }; + let raw = tower(0.0).data.as_deref().cloned().unwrap(); + let mask = RasterMask::default(); + let traced = |r: &Raster| { + let stop = AtomicBool::new(false); + let shadow = crate::shadow::light(r, 0, &mask, 90.0, 30.0, crate::shadow::soft_edge(None), 1.0, 1, &stop).unwrap(); + (shadow, crate::shadow::sky(r, 0, &mask, 1.0, 1, &stop).unwrap()) + }; + let near = |a: &[u8], b: &[u8]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1); + let (shadow, sky) = grids(0.0); + let (want_shadow, want_sky) = traced(&raw); + assert!(*shadow == want_shadow && *sky == want_sky, "as they are"); + let (shadow, sky) = grids(90.0); + let (want_shadow, want_sky) = traced(&smoothed_by_kernel(&raw, 3.0)); + assert!(near(&shadow, &want_shadow), "shadows"); + assert!(near(&sky, &want_sky), "sky"); + assert_ne!(*shadow, traced(&raw).0, "the tower's shadow is softened"); + } + /// 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/raster.rs b/crates/render/src/raster.rs index 195acba326..6967b2c629 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -9,6 +9,7 @@ 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::generalize::{block_step, box_passes, box_radii, generalise_sigma}; use rustgis_map::projection::Flat; use rustgis_map::raster::{ Colorizer, Flats, GENERALIZE_MAX, RasterMask, RasterRenderer, RasterStyle, Resampling, Rock, hillshade, relief_hillshade, slope, @@ -893,38 +894,6 @@ struct SmoothLimits { reads: usize, } -/// 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` made `scale` times larger (a -/// coarser level's), each way: along the row `row` of `r` (a geographic grid's cells narrow toward -/// the poles), and down the columns. -fn generalise_sigma(metres: f64, r: &Raster, scale: (f64, f64), 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 * scale.0), sigma(y * scale.1)) -} - /// 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 { @@ -946,14 +915,6 @@ fn padded((from, to): (u32, u32), pad: u32, len: u32) -> (u32, u32) { (from.saturating_sub(pad), to.saturating_add(pad).saturating_add(1).min(len)) } -/// Cells to a block's side for a Gaussian of `sigma` cells at its widest: as many as make it fit -/// [`MAX_SIGMA_CELLS`], at least 1. -fn block_step(sigma: f64) -> i64 { - // At most a block of 2³² cells a side, larger than any grid, so the sums stay in range. - let fits = (sigma / MAX_SIGMA_CELLS).ceil(); - if fits > 1.0 { fits.min(4_294_967_296.0) as i64 } else { 1 } -} - /// [`smoothing_reach`] along the rows and down the columns, for a Gaussian of `sx` and `sy` cells, /// in the blocks it is smoothed in ([`block_step`]). fn generalised_reach(sx: f64, sy: f64) -> (i64, i64) { @@ -961,35 +922,6 @@ fn generalised_reach(sx: f64, sy: f64) -> (i64, i64) { (smoothing_reach(sx, step), smoothing_reach(sy, step)) } -/// 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()]); -} - /// How sparse the sample of a block of `step` cells a side is: every `every`-th cell each way, from /// `every / 2`, as dense as keeps `blocks` such blocks within `reads` cells read, the cells counted /// as the sample reads them; every cell when they fit, one a block at the sparsest. @@ -1012,7 +944,7 @@ fn sample_every(step: i64, blocks: usize, reads: usize) -> i64 { /// 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`] (its work space -/// counted), or a Gaussian wider than [`MAX_SIGMA_CELLS`] cells, it smooths square blocks of cells +/// counted), or a Gaussian wider than [`rustgis_map::generalize::MAX_SIGMA_CELLS`] cells, it smooths square blocks of cells /// and reads between the blocks' centres. A block is the mean height of its cells, or, past /// [`MAX_SMOOTH_READS`] cells, of a regular sample of them. Blocks sit on the grid, at multiples of /// their size, so where the view is doesn't move them. @@ -1599,6 +1531,7 @@ mod tests { use rustgis_data::raster::{ColorHint, Crs, GeoTransform}; use rustgis_geom::lonlat_to_merc; use rustgis_map::Camera; + use rustgis_map::generalize::MAX_SIGMA_CELLS; use rustgis_map::raster::RasterStyle; use super::*; From 98b1b26c4bdc8d6bed9c74599fd78c6e7f4a484e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 11:10:12 -0300 Subject: [PATCH 2/4] fix(map): a generalised relief's whole-grid smoothing plans its memory, reserves all it holds and stops at each row and column (#3145, part 3) From review: - The smoothing sizes its limit with memory::planned (12 bytes a cell) and refuses a larger grid with a way out (Unlit::TooLarge: clip the raster first), rather than run out of memory partway. - Its filter lines are reserved fallibly with the blocks, so a failed reservation is said, not an abort. - It looks at stop before it holds anything and at each row and column. Part of #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 91 +++++++++++++++++++++++++++++------- crates/map/src/raster.rs | 10 ++-- crates/map/src/shadow.rs | 3 ++ 3 files changed, 81 insertions(+), 23 deletions(-) diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs index 817700032d..59ce57bfdf 100644 --- a/crates/map/src/generalize.rs +++ b/crates/map/src/generalize.rs @@ -7,6 +7,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use rustgis_data::raster::{ColorHint, Raster}; use crate::raster::RasterMask; +use crate::shadow::Unlit; /// The widest Gaussian a generalised Shaded Relief smooths with, in the cells it smooths. pub const MAX_SIGMA_CELLS: f64 = 256.0; @@ -77,40 +78,73 @@ pub fn box_passes(line: &mut [f64], radii: [usize; 3], buf: &mut Vec, tmp: line.copy_from_slice(&buf[reach..reach + line.len()]); } +/// The most cells a whole grid is smoothed for when the memory isn't known (12 bytes a cell: 768 +/// MiB). +const SMOOTHED_FLOOR: usize = 1 << 26; + /// The heights of `band` of `r` smoothed with a Gaussian of `metres` as a whole grid, for the /// traces of cast shadows and the sky: a raster of one band, each valid cell the filter's weighted /// mean of the valid heights around it (no data and masked heights left out), the others NaN. /// Past [`MAX_SIGMA_CELLS`] cells it smooths the mean heights of square blocks of cells, as the /// renderer does, and reads between the blocks' centres. The grid's edges stop the filter, a -/// whole turn's too. `None` when `stop` is set, or there isn't the memory for it (8 bytes a cell -/// while it works, then 4). -pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool) -> Option { +/// whole turn's too. It holds 8 bytes a block and the smoothed band's 4 a cell while it works (3 +/// times a `Float32` layer's band at most), then the band: a grid past what +/// [`rustgis_data::memory::planned`] gives for that is refused ([`Unlit::TooLarge`]). It looks at +/// `stop` before it holds anything and at each row and column ([`Unlit::Stopped`]). +pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool) -> Result { + let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 12); + smoothed_within(r, band, mask, metres, stop, limit) +} + +/// [`smoothed`] for a grid of at most `limit` cells. +fn smoothed_within(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool, limit: usize) -> Result { + let stopped = || stop.load(Ordering::Relaxed); let (w, h) = (i64::from(r.width), i64::from(r.height)); + let cells = usize::try_from(w * h).map_err(|_| Unlit::NoMemory)?; + if cells > limit { + return Err(Unlit::TooLarge { cells, limit }); + } + if stopped() { + return Err(Unlit::Stopped); + } let sy = generalise_sigma(metres, r, (1.0, 1.0), 0.0).1; let sx = |row: f64| generalise_sigma(metres, r, (1.0, 1.0), row).0; let step = block_step(sx(0.0).max(sx(h as f64)).max(sy)).min(w.max(h).max(1)); let (cols, rows) = ((w + step - 1) / step, (h + step - 1) / step); - let blocks = usize::try_from(cols.checked_mul(rows)?).ok()?; - // Each block's sum of valid heights and their count, in `f32`: each pass keeps them means. + let blocks = (cols * rows) as usize; + fn reserve(v: &mut Vec, n: usize) -> Result<(), Unlit> { + v.try_reserve_exact(n).map_err(|_| Unlit::NoMemory) + } + // Each block's sum of valid heights and their count, in `f32`: each pass keeps them means. The + // passes' line and its two copies: the longest row or column, with the widest boxes' reach. let (mut sums, mut counts) = (Vec::new(), Vec::new()); - sums.try_reserve_exact(blocks).ok()?; - counts.try_reserve_exact(blocks).ok()?; + let (mut line, mut buf, mut tmp) = (Vec::new(), Vec::new(), Vec::new()); + let longest = cols.max(rows) as usize + 6 * MAX_SIGMA_CELLS as usize + 6; + reserve(&mut sums, blocks)?; + reserve(&mut counts, blocks)?; + reserve(&mut line, longest)?; + reserve(&mut buf, longest)?; + reserve(&mut tmp, longest)?; sums.resize(blocks, 0.0f32); counts.resize(blocks, 0.0f32); let height = |c: i64, row: i64| r.value(band, c, row).filter(|v| !mask.hides(*v)); for row in 0..h { + if stopped() { + return Err(Unlit::Stopped); + } for c in 0..w { if let Some(v) = height(c, row) { let at = ((row / step) * cols + c / step) as usize; - (sums[at], counts[at]) = (sums[at] + v, counts[at] + 1.0); + if let (Some(sum), Some(count)) = (sums.get_mut(at), counts.get_mut(at)) { + (*sum, *count) = (*sum + v, *count + 1.0); + } } } } - let (mut line, mut buf, mut tmp) = (Vec::new(), Vec::new(), Vec::new()); for grid in [&mut sums, &mut counts] { for (j, block_row) in grid.chunks_mut(cols as usize).enumerate() { - if stop.load(Ordering::Relaxed) { - return None; + if stopped() { + return Err(Unlit::Stopped); } line.clear(); line.extend(block_row.iter().map(|v| f64::from(*v))); @@ -119,11 +153,14 @@ pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: & block_row.iter_mut().zip(&line).for_each(|(v, l)| *v = *l as f32); } for c in 0..cols as usize { + if stopped() { + return Err(Unlit::Stopped); + } line.clear(); line.extend(grid.iter().skip(c).step_by(cols as usize).map(|v| f64::from(*v))); 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 as f32; + for (v, l) in grid.iter_mut().skip(c).step_by(cols as usize).zip(&line) { + *v = *l as f32; } } } @@ -131,11 +168,14 @@ pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: & for (s, n) in sums.iter_mut().zip(&counts) { *s = if *n > 1e-9 { *s / n } else { f32::NAN }; } - drop(counts); + drop((counts, line, buf, tmp)); let block = |i: i64, j: i64| sums.get((j.clamp(0, rows - 1) * cols + i.clamp(0, cols - 1)) as usize).copied().filter(|v| v.is_finite()); let mut heights = Vec::new(); - heights.try_reserve_exact(usize::try_from(w * h).ok()?).ok()?; + reserve(&mut heights, cells)?; for row in 0..h { + if stopped() { + return Err(Unlit::Stopped); + } for c in 0..w { let v = height(c, row).and_then(|_| { if step == 1 { @@ -156,7 +196,10 @@ pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: & heights.push(v.unwrap_or(f32::NAN)); } } - Raster::new(&r.name, r.width, r.height, vec![heights], r.transform, r.crs, None, ColorHint::Gray, "Float32").ok() + // The transform and size are the layer's own, so this only fails as a raster's band can't be + // held. + Raster::new(&r.name, r.width, r.height, vec![heights], r.transform, r.crs, None, ColorHint::Gray, "Float32") + .map_err(|_| Unlit::NoMemory) } #[cfg(test)] @@ -172,7 +215,7 @@ mod tests { let data = (0..600 * 600).map(|i| if i % 600 < 3 && i / 600 < 3 { -9999.0 } else { 250.0 }).collect(); let r = Raster::new("even", 600, 600, vec![data], gt, Crs::WebMercator, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); assert!(block_step(generalise_sigma(10_000.0, &r, (1.0, 1.0), 0.0).0) >= 2); - let s = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(false)).unwrap(); + let s = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(false)).ok().unwrap(); for (i, v) in s.bands[0].data.iter().enumerate() { if i % 600 < 3 && i / 600 < 3 { assert!(v.is_nan(), "{i}"); @@ -180,6 +223,18 @@ mod tests { assert!((v - 250.0).abs() < 1e-3, "{i}: {v}"); } } - assert!(smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(true)).is_none()); + let stopped = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(true)); + assert_eq!(stopped.err(), Some(Unlit::Stopped)); + } + + /// A grid whose smoothing would hold more than the memory planned for it is refused, saying + /// how many cells it has and how many fit, rather than run out of memory partway (AGENTS.md). + #[test] + fn a_grid_past_the_memory_planned_is_refused() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 100.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let r = Raster::new("even", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let at = |limit| smoothed_within(&r, 0, &RasterMask::default(), 90.0, &AtomicBool::new(false), limit); + assert_eq!(at(9_999).err(), Some(Unlit::TooLarge { cells: 10_000, limit: 9_999 })); + assert!(at(10_000).is_ok()); } } diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 72a6bf0312..268c96439c 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1313,11 +1313,7 @@ fn start_light(r: Arc, key: LightKey, work: Arc) { let traced = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { // A generalised relief's are traced over its smoothed heights, one band with no mask. let smoothed = if key.generalize > 0.0 { - match crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop) { - Some(smoothed) => Some(smoothed), - None if work.stop.load(std::sync::atomic::Ordering::Relaxed) => return Err(crate::shadow::Unlit::Stopped), - None => return Err(crate::shadow::Unlit::NoMemory), - } + Some(crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop)?) } else { None }; @@ -1344,6 +1340,10 @@ fn start_light(r: Arc, key: LightKey, work: Arc) { Ok(out) => { work.finish(out.map(Arc::new).map_err(|e| match e { crate::shadow::Unlit::Failed => format!("{not_drawn}: working it out failed"), + crate::shadow::Unlit::TooLarge { cells, limit } => format!( + "{not_drawn}: smoothing its {cells} cells for its generalisation needs more memory than is planned for \ + ({limit} cells): clip the raster to the area drawn first" + ), _ => format!("{not_drawn}: there isn't the memory for it"), })); work.land(); diff --git a/crates/map/src/shadow.rs b/crates/map/src/shadow.rs index 31bcf3ad8f..a01f79d8ee 100644 --- a/crates/map/src/shadow.rs +++ b/crates/map/src/shadow.rs @@ -54,6 +54,9 @@ pub enum Unlit { NoMemory, /// A thread working it out failed (panicked). Failed, + /// A generalised relief's grid of `cells` cells is more than the `limit` its smoothing plans + /// for (#3145, see [`crate::generalize::smoothed`]). + TooLarge { cells: usize, limit: usize }, } /// The light left by cast shadows on each cell of `band` (`0` in shadow to `255` lit), row by row From 05c4253afc866ec5ece991c5df0a11443476ae7e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 11:41:30 -0300 Subject: [PATCH 3/4] fix(map): a generalised relief's smoothing plans for its whole work space, its filter lines and its shadows' and sky's smoothing together (#3145, part 3) From review: - The memory plan counts bytes: each block's sum and count, the smoothed band and the filter's three lines (a grid one row tall makes them as long as itself), not 12 bytes a cell. - A relief whose cast shadows and sky are both asked for smooths its grid for each at once: each plans for both. Sharing one smoothed grid between them is left for the next part. Part of #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 94 ++++++++++++++++++++++++++---------- crates/map/src/raster.rs | 20 +++++--- crates/map/src/shadow.rs | 6 +-- 3 files changed, 86 insertions(+), 34 deletions(-) diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs index 59ce57bfdf..db48e8396c 100644 --- a/crates/map/src/generalize.rs +++ b/crates/map/src/generalize.rs @@ -78,39 +78,70 @@ pub fn box_passes(line: &mut [f64], radii: [usize; 3], buf: &mut Vec, tmp: line.copy_from_slice(&buf[reach..reach + line.len()]); } -/// The most cells a whole grid is smoothed for when the memory isn't known (12 bytes a cell: 768 -/// MiB). -const SMOOTHED_FLOOR: usize = 1 << 26; +/// What a whole grid's smoothing plans for when the memory isn't known: 768 MiB. +const SMOOTHED_FLOOR: usize = 768 << 20; /// The heights of `band` of `r` smoothed with a Gaussian of `metres` as a whole grid, for the /// traces of cast shadows and the sky: a raster of one band, each valid cell the filter's weighted /// mean of the valid heights around it (no data and masked heights left out), the others NaN. /// Past [`MAX_SIGMA_CELLS`] cells it smooths the mean heights of square blocks of cells, as the /// renderer does, and reads between the blocks' centres. The grid's edges stop the filter, a -/// whole turn's too. It holds 8 bytes a block and the smoothed band's 4 a cell while it works (3 -/// times a `Float32` layer's band at most), then the band: a grid past what -/// [`rustgis_data::memory::planned`] gives for that is refused ([`Unlit::TooLarge`]). It looks at -/// `stop` before it holds anything and at each row and column ([`Unlit::Stopped`]). -pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool) -> Result { - let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 12); - smoothed_within(r, band, mask, metres, stop, limit) +/// whole turn's too. It holds what [`smoothing_bytes`] counts (3 times a `Float32` layer's band at +/// most, but for a grid a few cells across), then the band, `together` times when that many +/// smoothings run at once (a relief's cast shadows and its sky): past what +/// [`rustgis_data::memory::planned`] gives, it is refused ([`Unlit::TooLarge`]). It looks at `stop` +/// before it holds anything and at each row and column ([`Unlit::Stopped`]). +pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool, together: usize) -> Result { + let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 1); + smoothed_within(r, band, mask, metres, stop, limit, together) } -/// [`smoothed`] for a grid of at most `limit` cells. -fn smoothed_within(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool, limit: usize) -> Result { +/// The blocks, rows and cells to a block's side of `r` smoothed over `metres`. +fn blocks_of(r: &Raster, metres: f64) -> (i64, i64, i64) { + let (w, h) = (i64::from(r.width), i64::from(r.height)); + let sy = generalise_sigma(metres, r, (1.0, 1.0), 0.0).1; + let sx = |row: f64| generalise_sigma(metres, r, (1.0, 1.0), row).0; + let step = block_step(sx(0.0).max(sx(h as f64)).max(sy)).min(w.max(h).max(1)); + ((w + step - 1) / step, (h + step - 1) / step, step) +} + +/// The cells of the filter's lines: the longest row or column of blocks, with the widest boxes' +/// reach either side. +fn line_cells(cols: i64, rows: i64) -> usize { + cols.max(rows) as usize + 6 * MAX_SIGMA_CELLS as usize + 6 +} + +/// The bytes [`smoothed`] holds for `r` over `metres` while it works: each block's sum and count +/// (8), the smoothed band (4 a cell), and the filter's line with its two copies (24 a cell of it). +pub fn smoothing_bytes(r: &Raster, metres: f64) -> usize { + let (cols, rows, _) = blocks_of(r, metres); + let cells = r.width as usize * r.height as usize; + (8 * (cols * rows) as usize).saturating_add(4 * cells).saturating_add(24 * line_cells(cols, rows)) +} + +/// [`smoothed`] within `limit` bytes for `together` smoothings at once. +fn smoothed_within( + r: &Raster, + band: usize, + mask: &RasterMask, + metres: f64, + stop: &AtomicBool, + limit: usize, + together: usize, +) -> Result { let stopped = || stop.load(Ordering::Relaxed); let (w, h) = (i64::from(r.width), i64::from(r.height)); let cells = usize::try_from(w * h).map_err(|_| Unlit::NoMemory)?; - if cells > limit { - return Err(Unlit::TooLarge { cells, limit }); + let bytes = smoothing_bytes(r, metres).saturating_mul(together.max(1)); + if bytes > limit { + return Err(Unlit::TooLarge { bytes, limit }); } if stopped() { return Err(Unlit::Stopped); } let sy = generalise_sigma(metres, r, (1.0, 1.0), 0.0).1; let sx = |row: f64| generalise_sigma(metres, r, (1.0, 1.0), row).0; - let step = block_step(sx(0.0).max(sx(h as f64)).max(sy)).min(w.max(h).max(1)); - let (cols, rows) = ((w + step - 1) / step, (h + step - 1) / step); + let (cols, rows, step) = blocks_of(r, metres); let blocks = (cols * rows) as usize; fn reserve(v: &mut Vec, n: usize) -> Result<(), Unlit> { v.try_reserve_exact(n).map_err(|_| Unlit::NoMemory) @@ -119,7 +150,7 @@ fn smoothed_within(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop // passes' line and its two copies: the longest row or column, with the widest boxes' reach. let (mut sums, mut counts) = (Vec::new(), Vec::new()); let (mut line, mut buf, mut tmp) = (Vec::new(), Vec::new(), Vec::new()); - let longest = cols.max(rows) as usize + 6 * MAX_SIGMA_CELLS as usize + 6; + let longest = line_cells(cols, rows); reserve(&mut sums, blocks)?; reserve(&mut counts, blocks)?; reserve(&mut line, longest)?; @@ -215,7 +246,7 @@ mod tests { let data = (0..600 * 600).map(|i| if i % 600 < 3 && i / 600 < 3 { -9999.0 } else { 250.0 }).collect(); let r = Raster::new("even", 600, 600, vec![data], gt, Crs::WebMercator, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); assert!(block_step(generalise_sigma(10_000.0, &r, (1.0, 1.0), 0.0).0) >= 2); - let s = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(false)).ok().unwrap(); + let s = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(false), 1).ok().unwrap(); for (i, v) in s.bands[0].data.iter().enumerate() { if i % 600 < 3 && i / 600 < 3 { assert!(v.is_nan(), "{i}"); @@ -223,18 +254,31 @@ mod tests { assert!((v - 250.0).abs() < 1e-3, "{i}: {v}"); } } - let stopped = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(true)); + let stopped = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(true), 1); assert_eq!(stopped.err(), Some(Unlit::Stopped)); } /// A grid whose smoothing would hold more than the memory planned for it is refused, saying - /// how many cells it has and how many fit, rather than run out of memory partway (AGENTS.md). + /// how much it needs and how much is planned, rather than run out of memory partway + /// (AGENTS.md). All it holds is counted: the blocks, the band, and the filter's three lines, + /// which a grid one row tall makes as long as itself; and as many times as smoothings run + /// together, a relief's cast shadows and its sky each smoothing its grid (#3448 review). #[test] fn a_grid_past_the_memory_planned_is_refused() { - let gt = GeoTransform { origin_x: 0.0, origin_y: 100.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; - let r = Raster::new("even", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); - let at = |limit| smoothed_within(&r, 0, &RasterMask::default(), 90.0, &AtomicBool::new(false), limit); - assert_eq!(at(9_999).err(), Some(Unlit::TooLarge { cells: 10_000, limit: 9_999 })); - assert!(at(10_000).is_ok()); + let even = |w: u32, h: u32| { + let gt = GeoTransform { origin_x: 0.0, origin_y: f64::from(h) * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + Raster::new("even", w, h, vec![vec![250.0; (w * h) as usize]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap() + }; + let at = + |r: &Raster, limit, together| smoothed_within(r, 0, &RasterMask::default(), 90.0, &AtomicBool::new(false), limit, together); + let square = even(100, 100); + let need = smoothing_bytes(&square, 90.0); + assert_eq!(at(&square, need - 1, 1).err(), Some(Unlit::TooLarge { bytes: need, limit: need - 1 })); + assert!(at(&square, need, 1).is_ok()); + assert_eq!(at(&square, need, 2).err(), Some(Unlit::TooLarge { bytes: 2 * need, limit: need })); + // A row 4000 cells long: its lines are 24 bytes a cell, past the 12 a cell of the rest. + let row = even(4000, 1); + assert!(smoothing_bytes(&row, 90.0) >= 36 * 4000, "{}", smoothing_bytes(&row, 90.0)); + assert!(at(&row, 12 * 4000, 1).is_err()); } } diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 268c96439c..cfbfa0ad80 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1111,7 +1111,13 @@ impl RasterLayer { }; // Started without holding the lock: a thread the system refuses runs it here. if let Some((r, key)) = start { - start_light(r, key, work.clone()); + // A generalised relief's shadows and sky each smooth its grid, at once when both are + // asked for: each plans for both. + let together = match self.style.renderer { + RasterRenderer::ShadedRelief { shadow, sky, .. } if shadow > 0.0 && sky > 0.0 => 2, + _ => 1, + }; + start_light(r, key, work.clone(), together); } work.result(wait) } @@ -1306,14 +1312,14 @@ pub fn hold_cast_shadows() -> std::sync::RwLockWriteGuard<'static, ()> { /// Works out a light grid: natively on a thread of its own (here if the system refuses one), /// in the browser here. -fn start_light(r: Arc, key: LightKey, work: Arc) { +fn start_light(r: Arc, key: LightKey, work: Arc, together: usize) { let run = move || { drop(LIGHT_HOLD.read().unwrap_or_else(|e| e.into_inner())); let threads = rustgis_data::threads::max(); let traced = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { // A generalised relief's are traced over its smoothed heights, one band with no mask. let smoothed = if key.generalize > 0.0 { - Some(crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop)?) + Some(crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together)?) } else { None }; @@ -1340,9 +1346,11 @@ fn start_light(r: Arc, key: LightKey, work: Arc) { Ok(out) => { work.finish(out.map(Arc::new).map_err(|e| match e { crate::shadow::Unlit::Failed => format!("{not_drawn}: working it out failed"), - crate::shadow::Unlit::TooLarge { cells, limit } => format!( - "{not_drawn}: smoothing its {cells} cells for its generalisation needs more memory than is planned for \ - ({limit} cells): clip the raster to the area drawn first" + crate::shadow::Unlit::TooLarge { bytes, limit } => format!( + "{not_drawn}: smoothing its heights for its generalisation needs {} MiB, more than the {} MiB planned \ + for it: clip the raster to the area drawn first", + bytes >> 20, + limit >> 20 ), _ => format!("{not_drawn}: there isn't the memory for it"), })); diff --git a/crates/map/src/shadow.rs b/crates/map/src/shadow.rs index a01f79d8ee..58dc63ac55 100644 --- a/crates/map/src/shadow.rs +++ b/crates/map/src/shadow.rs @@ -54,9 +54,9 @@ pub enum Unlit { NoMemory, /// A thread working it out failed (panicked). Failed, - /// A generalised relief's grid of `cells` cells is more than the `limit` its smoothing plans - /// for (#3145, see [`crate::generalize::smoothed`]). - TooLarge { cells: usize, limit: usize }, + /// A generalised relief's smoothing would hold `bytes`, past the `limit` it plans for (#3145, + /// see [`crate::generalize::smoothed`]). + TooLarge { bytes: usize, limit: usize }, } /// The light left by cast shadows on each cell of `band` (`0` in shadow to `255` lit), row by row From ea440b0f13a91292f6b9cec5f0a350be3beadeb2 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 11:58:58 -0300 Subject: [PATCH 4/4] fix(map): a generalised relief's block past 2^24 cells keeps its mean (#3145, part 3) From review: the blocks' sums and counts were added up in f32, so past 2^24 cells a block's count stopped while its sum grew, and its height came out half as high again, unsaid. A row of blocks is now summed in f64 with whole counts, then kept as f32. The memory plan counts the row's 16 bytes a block, and the doc says the multiple of the layer for a grid a row or a column wide. Part of #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 78 ++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 17 deletions(-) diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs index db48e8396c..89fc56ac0a 100644 --- a/crates/map/src/generalize.rs +++ b/crates/map/src/generalize.rs @@ -86,8 +86,9 @@ const SMOOTHED_FLOOR: usize = 768 << 20; /// mean of the valid heights around it (no data and masked heights left out), the others NaN. /// Past [`MAX_SIGMA_CELLS`] cells it smooths the mean heights of square blocks of cells, as the /// renderer does, and reads between the blocks' centres. The grid's edges stop the filter, a -/// whole turn's too. It holds what [`smoothing_bytes`] counts (3 times a `Float32` layer's band at -/// most, but for a grid a few cells across), then the band, `together` times when that many +/// whole turn's too. It holds what [`smoothing_bytes`] counts (about 3 times a `Float32` layer's +/// band for a grid many cells across both ways, up to about 9 times for one a row or a column +/// wide, whose filter lines are as long as itself), then the band, `together` times when that many /// smoothings run at once (a relief's cast shadows and its sky): past what /// [`rustgis_data::memory::planned`] gives, it is refused ([`Unlit::TooLarge`]). It looks at `stop` /// before it holds anything and at each row and column ([`Unlit::Stopped`]). @@ -112,11 +113,54 @@ fn line_cells(cols: i64, rows: i64) -> usize { } /// The bytes [`smoothed`] holds for `r` over `metres` while it works: each block's sum and count -/// (8), the smoothed band (4 a cell), and the filter's line with its two copies (24 a cell of it). +/// (8), a row of blocks' `f64` sums and whole counts while they are read (16 a block of the row), +/// the smoothed band (4 a cell), and the filter's line with its two copies (24 a cell of it). pub fn smoothing_bytes(r: &Raster, metres: f64) -> usize { let (cols, rows, _) = blocks_of(r, metres); let cells = r.width as usize * r.height as usize; - (8 * (cols * rows) as usize).saturating_add(4 * cells).saturating_add(24 * line_cells(cols, rows)) + (8 * (cols * rows) as usize).saturating_add(16 * cols as usize).saturating_add(4 * cells).saturating_add(24 * line_cells(cols, rows)) +} + +/// Each block's sum of the `height`s of the cells of a `size` grid in it and their count, into +/// `sums` and `counts`, the blocks `step` cells a side, row by row. Looks at `stopped` at each row. +fn block_sums( + (w, h): (i64, i64), + step: i64, + height: &impl Fn(i64, i64) -> Option, + stopped: &impl Fn() -> bool, + sums: &mut [f32], + counts: &mut [f32], +) -> Result<(), Unlit> { + // A row of blocks at a time in `f64` sums and whole counts, so a block of more cells than an + // `f32` counts one by one (2²⁴) still sums them all; then kept as `f32`, a relative error of + // about 6e-8 in each. + let cols = (w + step - 1) / step; + let (mut row_sums, mut row_counts) = (Vec::new(), Vec::new()); + row_sums.try_reserve_exact(cols as usize).map_err(|_| Unlit::NoMemory)?; + row_counts.try_reserve_exact(cols as usize).map_err(|_| Unlit::NoMemory)?; + for (j, (sums, counts)) in sums.chunks_mut(cols.max(1) as usize).zip(counts.chunks_mut(cols.max(1) as usize)).enumerate() { + row_sums.clear(); + row_counts.clear(); + row_sums.resize(cols as usize, 0.0f64); + row_counts.resize(cols as usize, 0u64); + for row in (j as i64 * step..(j as i64 + 1) * step).take_while(|row| *row < h) { + if stopped() { + return Err(Unlit::Stopped); + } + for c in 0..w { + if let Some(v) = height(c, row) { + let at = (c / step) as usize; + if let (Some(sum), Some(count)) = (row_sums.get_mut(at), row_counts.get_mut(at)) { + (*sum, *count) = (*sum + f64::from(v), *count + 1); + } + } + } + } + for (out, (sum, count)) in sums.iter_mut().zip(counts.iter_mut()).zip(row_sums.iter().zip(&row_counts)) { + (*out.0, *out.1) = (*sum as f32, *count as f32); + } + } + Ok(()) } /// [`smoothed`] within `limit` bytes for `together` smoothings at once. @@ -159,19 +203,7 @@ fn smoothed_within( sums.resize(blocks, 0.0f32); counts.resize(blocks, 0.0f32); let height = |c: i64, row: i64| r.value(band, c, row).filter(|v| !mask.hides(*v)); - for row in 0..h { - if stopped() { - return Err(Unlit::Stopped); - } - for c in 0..w { - if let Some(v) = height(c, row) { - let at = ((row / step) * cols + c / step) as usize; - if let (Some(sum), Some(count)) = (sums.get_mut(at), counts.get_mut(at)) { - (*sum, *count) = (*sum + v, *count + 1.0); - } - } - } - } + block_sums((w, h), step, &height, &stopped, &mut sums, &mut counts)?; for grid in [&mut sums, &mut counts] { for (j, block_row) in grid.chunks_mut(cols as usize).enumerate() { if stopped() { @@ -258,6 +290,18 @@ mod tests { assert_eq!(stopped.err(), Some(Unlit::Stopped)); } + /// A block of more cells than an `f32` counts one by one (2²⁴) sums and counts them all: an + /// even height stays that height (#3448 review: it came out half as high again). + #[test] + fn a_block_past_two_to_the_twenty_four_cells_keeps_its_mean() { + let side = 4100; + let (mut sums, mut counts) = (vec![0.0f32], vec![0.0f32]); + block_sums((side, side), side, &|_, _| Some(812.5), &|| false, &mut sums, &mut counts).unwrap(); + let mean = sums[0] / counts[0]; + assert!((mean - 812.5).abs() < 1e-3, "{mean}"); + assert_eq!(counts[0], (side * side) as f32); + } + /// A grid whose smoothing would hold more than the memory planned for it is refused, saying /// how much it needs and how much is planned, rather than run out of memory partway /// (AGENTS.md). All it holds is counted: the blocks, the band, and the filter's three lines,