Repository navigation
feat(map): a generalised relief casts its shadows and sees its sky from its smoothed heights (#3145, part 3) #3448
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
elpidioassinaturas
merged 4 commits into
opengeos:main
from
elpidioassinaturas:feat/3145-shadows-smoothed
Nov 30, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
3cec3e1
feat(map): a generalised relief casts its shadows and sees its sky fr…
elpidiofilho 98b1b26
fix(map): a generalised relief's whole-grid smoothing plans its memor…
elpidiofilho 05c4253
fix(map): a generalised relief's smoothing plans for its whole work s…
elpidiofilho ea440b0
fix(map): a generalised relief's block past 2^24 cells keeps its mean…
elpidiofilho File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,328 @@ | ||
| //! 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; | ||
| 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; | ||
|
|
||
| /// 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<f64>, tmp: &mut Vec<f64>) { | ||
| 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()]); | ||
| } | ||
|
|
||
| /// 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 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`]). | ||
| pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool, together: usize) -> Result<Raster, Unlit> { | ||
| let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 1); | ||
| smoothed_within(r, band, mask, metres, stop, limit, together) | ||
| } | ||
|
|
||
| /// 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), 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(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<f32>, | ||
| 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. | ||
| fn smoothed_within( | ||
| r: &Raster, | ||
| band: usize, | ||
| mask: &RasterMask, | ||
| metres: f64, | ||
| stop: &AtomicBool, | ||
| limit: usize, | ||
| together: usize, | ||
| ) -> Result<Raster, Unlit> { | ||
| 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)?; | ||
| 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 (cols, rows, step) = blocks_of(r, metres); | ||
| let blocks = (cols * rows) as usize; | ||
| fn reserve<T>(v: &mut Vec<T>, 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()); | ||
| let (mut line, mut buf, mut tmp) = (Vec::new(), Vec::new(), Vec::new()); | ||
| let longest = line_cells(cols, rows); | ||
| 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)); | ||
| 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() { | ||
| return Err(Unlit::Stopped); | ||
| } | ||
| line.clear(); | ||
|
elpidioassinaturas marked this conversation as resolved.
Resolved
|
||
| line.extend(block_row.iter().map(|v| f64::from(*v))); | ||
|
elpidioassinaturas marked this conversation as resolved.
Resolved
|
||
| 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 { | ||
| 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 (v, l) in grid.iter_mut().skip(c).step_by(cols as usize).zip(&line) { | ||
| *v = *l 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, 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(); | ||
| 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 { | ||
| 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)); | ||
| } | ||
| } | ||
| // 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)] | ||
| mod tests { | ||
| use super::*; | ||
| use rustgis_data::raster::{Crs, GeoTransform}; | ||
|
elpidioassinaturas marked this conversation as resolved.
Resolved
|
||
|
|
||
| /// 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), 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}"); | ||
| } else { | ||
| assert!((v - 250.0).abs() < 1e-3, "{i}: {v}"); | ||
| } | ||
| } | ||
| let stopped = smoothed(&r, 0, &RasterMask::default(), 10_000.0, &AtomicBool::new(true), 1); | ||
| 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, | ||
| /// 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 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()); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.