diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index a05a407960..5954d7e354 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -691,7 +691,13 @@ impl Pass1<'_> { } // Nearest sampling: the last cell read, and the pixel it was read for. let mut last: Option<((i64, i64), usize)> = None; - for dx in 0..bw { + // Bilinear relief: the last four cells' lights, by the first's column and row; and the + // last pixel that fell in the grid, with its source position. + let mut quad: Option<((i64, i64), [Option; 4])> = None; + let mut prev: Option<(usize, f64, f64)> = None; + // The source position of the pixel in column `dx` of this row, its column wrapped here, + // not in `source`: the grid's columns run on across a 0..360° seam. + let pos_at = |dx: usize| { let px = self.x0 + dx; let pos = match self.rotated { // Back-rotate the screen pixel about the centre, then find its source exactly. @@ -711,13 +717,26 @@ impl Pass1<'_> { } } }; - let Some((c, row)) = pos else { continue }; - // Wrapped here, not in `source`: the grid's columns run on across a 0..360° seam. - let c = r.wrap_col(c); + pos.map(|(c, row)| (r.wrap_col(c), row)) + }; + for dx in 0..bw { + let Some((c, row)) = pos_at(dx) else { continue }; if c < 0.0 || row < 0.0 || c >= r.width as f64 || row >= r.height as f64 { continue; } let i = dy * bw + dx; + // How many cells one screen pixel spans here, along the row: from the last pixel in + // the grid, or the next one on the row's first. Across a whole turn's seam the columns + // are counted the short way round: 35.95 to 0.05 is a tenth of a cell, not 35.9. + let last_drawn = prev.replace((dx, c, row)); + let cols_apart = |other: f64| { + let d = (c - other).abs(); + self.wrap_width.map_or(d, |w| d.min(w as f64 - d)) + }; + let span = || match last_drawn { + Some((pdx, pc, pr)) => cols_apart(pc).hypot(row - pr) / (dx - pdx) as f64, + None => pos_at(dx + 1).map_or(0.0, |(nc, nr)| cols_apart(nc).hypot(nr - row)), + }; // Truncating is flooring here (both are at least 0), and much cheaper. let cell = (c as i64, row as i64); // The same cell as the last pixel, sampled nearest: the same values. @@ -756,35 +775,111 @@ impl Pass1<'_> { } } } - if let (Some((az, alt, zf)), Some(b)) = (self.relief, self.bands.first()) { - let (ci, ri) = cell; - let centre = value(r, self.mask, *b, ci, ri, self.wrap_width).unwrap_or(0.0) as f64; - let mut z = [centre; 9]; - for (k, (dx, dy)) in - [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)].into_iter().enumerate() - { - let (dx, dy) = (dx * self.east_north.0, dy * self.east_north.1); - z[k] = value(r, self.mask, *b, ci + dx, ri + dy, self.wrap_width).map(f64::from).unwrap_or(centre); - } + if let (Some(relief), Some(&b)) = (self.relief, self.bands.first()) { + // Bilinear: the light blended between the four cells around the point, as the + // band values are (#1880). Nearest, or no cell around it lit: its own cell's. + // So too where a cell is a pixel across or less: the blend can't be seen there, + // and each pixel would work out four new lights. + let blended = (self.resampling == Resampling::Bilinear && span() < 1.0).then(|| { + let (x, y) = (c - 0.5, row - 0.5); + let at = (x.floor() as i64, y.floor() as i64); + let cell_light = |i, j| self.cell_light(b, relief, (i, j)); + let lights = match quad { + Some((q, lights)) if q == at => lights, + // One cell east or west: two of the lights are the last four's. + Some(((qi, qj), [_, ne, _, se])) if qj == at.1 && qi + 1 == at.0 => { + [ne, cell_light(at.0 + 1, at.1), se, cell_light(at.0 + 1, at.1 + 1)] + } + Some(((qi, qj), [nw, _, sw, _])) if qj == at.1 && qi - 1 == at.0 => { + [cell_light(at.0, at.1), nw, cell_light(at.0, at.1 + 1), sw] + } + _ => self.quad_lights(b, relief, at), + }; + quad = Some((at, lights)); + blend(lights, x - x.floor(), y - y.floor()) + }); + let light = blended.flatten().unwrap_or_else(|| { + let centre = value(r, self.mask, b, cell.0, cell.1, self.wrap_width).unwrap_or(0.0); + self.light(b, relief, cell, f64::from(centre)) + }); if let Some(s) = shade.get_mut(i) { - *s = hillshade(&z, self.cell.0, self.cell.1, az, alt, zf); - if let Some((grid, strength)) = self.shadow - && let Some(lit) = grid.get(ri as usize * r.width as usize + ci as usize) - { - let left = 1.0 - strength * (1.0 - f64::from(*lit) / 255.0); - *s = (f64::from(*s) * left).round().clamp(0.0, 255.0) as u8; - } + *s = light.direct.round().clamp(0.0, 255.0) as u8; } - if let Some((grid, strength)) = self.sky - && let Some(seen) = grid.get(ri as usize * r.width as usize + ci as usize) + if self.sky.is_some() && let Some(a) = ambient.get_mut(i) { - *a = ((1.0 - strength * (1.0 - f64::from(*seen) / 255.0)) * 255.0).round().clamp(0.0, 255.0) as u8; + *a = light.ambient.round().clamp(0.0, 255.0) as u8; } } } } } + + /// The lights on the relief's cell `(ci, ri)`, from 0 to 255 and not rounded: the direct + /// light, the hillshade of its 3 × 3 window times what the cast shadows leave on it; and the + /// ambient light, scaled by the sky the cell sees. `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; + let mut z = [centre; 9]; + for (k, (dx, dy)) in [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)].into_iter().enumerate() { + 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); + } + 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`. + let left = |grid: Option<(&[u8], f64)>| { + grid.and_then(|(grid, strength)| grid.get(at).map(|v| 1.0 - strength * (1.0 - f64::from(*v) / 255.0))) + }; + let mut direct = f64::from(hillshade(&z, self.cell.0, self.cell.1, az, alt, zf)); + if let Some(left) = left(self.shadow) { + direct *= left; + } + Lit { direct, ambient: left(self.sky).map_or(255.0, |left| left * 255.0) } + } + + /// The lights of the cell `(i, j)`, or none when it is no data, masked or outside the grid; a + /// column past a whole turn's edge wraps. + fn cell_light(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> Option { + let ci = self.wrap_width.map_or(i, |w| i.rem_euclid(w)); + if ci < 0 || j < 0 || ci >= i64::from(self.r.width) || j >= i64::from(self.r.height) { + return None; + } + let centre = value(self.r, self.mask, band, ci, j, self.wrap_width)?; + Some(self.light(band, relief, (ci, j), f64::from(centre))) + } + + /// The lights of the four cells whose centres are around a point, from the cell `(i, j)` at + /// its top left: `(i, j)`, `(i + 1, j)`, `(i, j + 1)` and `(i + 1, j + 1)`. + fn quad_lights(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> [Option; 4] { + [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(di, dj)| self.cell_light(band, relief, (i + di, j + dj))) + } +} + +/// A relief cell's lights, from 0 to 255 and not rounded (see [`Pass1::light`]). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Lit { + direct: f64, + ambient: f64, +} + +/// The four cells' lights of [`Pass1::quad_lights`] blended bilinearly at `(fx, fy)` (0 to 1) +/// from the first, each light on its own. A cell without lights is left out and the others' +/// weights scaled up: the light is clamped at the grid's edge, and a clipped or masked edge isn't +/// darkened. At a cell's centre this is that cell's lights exactly. `None` when none of the four +/// with a weight has lights. +fn blend(lights: [Option; 4], fx: f64, fy: f64) -> Option { + let weights = [(1.0 - fx) * (1.0 - fy), fx * (1.0 - fy), (1.0 - fx) * fy, fx * fy]; + let (mut direct, mut ambient, mut total) = (0.0, 0.0, 0.0); + for (light, w) in lights.into_iter().zip(weights) { + if let Some(light) = light { + direct += w * light.direct; + ambient += w * light.ambient; + total += w; + } + } + (total > 0.0).then(|| Lit { direct: direct / total, ambient: ambient / total }) } /// Whether two pixels' band values are the same (NaN, no data, equal to itself). @@ -1361,4 +1456,187 @@ mod tests { } } } + + /// A row of 600 screen pixels across a relief of 6 × 3 cells of 100 m whose slope grows + /// eastward, lit from the west, its middle row drawn: cell `k` covers pixels `100 k - 1` to + /// `100 k + 98`, its centre on `100 k + 49`, and the last pixel is past the raster. The red + /// channel of each pixel, or `None` where it isn't drawn. The cast shadows and sky of `light`, + /// when given, are drawn at full strength; a `mirrored` grid is stored right to left. + fn relief_row(resampling: Resampling, nodata: Option, mask: &[f64], light: Lights, mirrored: bool) -> Vec> { + let (origin_x, pixel_width) = if mirrored { (600.0, -100.0) } else { (0.0, 100.0) }; + let gt = GeoTransform { origin_x, origin_y: 300.0, pixel_width, pixel_height: -100.0 }; + let mut heights = [0.0, 0.0, 20.0, 60.0, 120.0, 200.0]; + if mirrored { + heights.reverse(); + } + let data = heights.repeat(3); + let r = Raster::new("relief", 6, 3, vec![data], gt, Crs::WebMercator, nodata, ColorHint::Gray, "Float32").unwrap(); + let mut style = RasterStyle::default_for(&r); + let full = |grid: Option<&[u8]>| if grid.is_some() { 1.0 } else { 0.0 }; + let (shadow, sky) = (full(light.shadow), full(light.sky)); + style.renderer = RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow, sky }; + style.resampling = resampling; + style.mask = RasterMask { values: mask.to_vec(), ..RasterMask::default() }; + let view = View { + width: 600.0, + height: 1.0, + pixels_per_point: 1.0, + camera: Camera { center: Coord::new(300.5, 150.0), res: 1.0, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let mut pm = Pixmap::new(600, 1).unwrap(); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), light); + (0..600).map(|x| pm.pixel(x, 0).filter(|p| p.alpha() > 0).map(|p| p.red())).collect() + } + + /// Bilinear relief blends the four cells' light (#1880): the same as Nearest at each cell's + /// centre and in the outer half of the edge cells, and in between from one centre's light to + /// the next, not in steps. Nearest keeps one light per cell. + #[test] + fn bilinear_relief_blends_the_light_between_cell_centres() { + let nearest = relief_row(Resampling::Nearest, None, &[], Lights::default(), false); + let bilinear = relief_row(Resampling::Bilinear, None, &[], Lights::default(), false); + // Stored right to left, the cells are read westward: the same pixels (the last one, on + // the raster's edge, falls on the other side of it). + assert_eq!(relief_row(Resampling::Bilinear, None, &[], Lights::default(), true)[..599], bilinear[..599]); + let centre = |k: usize| nearest[100 * k + 49].unwrap(); + for k in 0..6 { + assert!(nearest[100 * k..100 * k + 98].iter().all(|v| *v == Some(centre(k))), "nearest, cell {k}"); + assert_eq!(bilinear[100 * k + 49], Some(centre(k)), "bilinear at the centre of cell {k}"); + } + assert!(bilinear[..49].iter().all(|v| *v == Some(centre(0))) && bilinear[550..599].iter().all(|v| *v == Some(centre(5)))); + for k in 1..4 { + let (a, b) = (centre(k), centre(k + 1)); + assert!(b > a + 5, "the slope grows toward the sun: {a} to {b}"); + let between: Vec = bilinear[100 * k + 49..=100 * k + 149].iter().map(|v| v.unwrap()).collect(); + assert!(between.windows(2).all(|w| w[0] <= w[1] && w[1] - w[0] <= 2), "cells {k} to {}: {between:?}", k + 1); + let middle = between[50]; + assert!(a < middle && middle < b, "cells {k} to {}: {middle} between {a} and {b}", k + 1); + } + } + + /// A no-data or masked cell is left out of the blend, the others' weights scaled up: next to + /// it the relief keeps its own cell's light, rather than darkening toward the hole. + #[test] + fn bilinear_relief_leaves_a_hidden_cell_out_of_the_blend() { + for (nodata, mask) in [(Some(120.0), &[][..]), (None, &[120.0][..])] { + let nearest = relief_row(Resampling::Nearest, nodata, mask, Lights::default(), false); + let bilinear = relief_row(Resampling::Bilinear, nodata, mask, Lights::default(), false); + // Cell 4 is hidden; cell 3's light runs on to its edge, and cell 5's from its own. + assert!(bilinear[399..499].iter().all(Option::is_none), "{nodata:?} {mask:?}"); + assert!(bilinear[349..399].iter().all(|v| v.is_some() && *v == nearest[349]), "{nodata:?} {mask:?}"); + assert!(bilinear[499..599].iter().all(|v| v.is_some() && *v == nearest[549]), "{nodata:?} {mask:?}"); + } + } + + /// The light cast shadows leave is blended with the hillshade: from a lit cell to a shadowed + /// one, Bilinear dims gradually where Nearest steps. + #[test] + fn bilinear_relief_blends_the_cast_shadows_too() { + // Cell 2 in full shadow in every row, the others lit. + let light: Vec = [255, 255, 0, 255, 255, 255].repeat(3); + let nearest = relief_row(Resampling::Nearest, None, &[], Lights { shadow: Some(&light), sky: None }, false); + let bilinear = relief_row(Resampling::Bilinear, None, &[], Lights { shadow: Some(&light), sky: None }, false); + let (lit, dark) = (nearest[149].unwrap(), nearest[249].unwrap()); + assert!(dark < lit && nearest[198] == Some(lit) && nearest[199] == Some(dark), "{lit} {dark}"); + assert_eq!((bilinear[149], bilinear[249]), (Some(lit), Some(dark))); + let middle = bilinear[199].unwrap(); + assert!(dark < middle && middle < lit, "{middle} between {dark} and {lit}"); + } + + /// The ambient light the sky leaves is blended too: from a cell that sees the whole sky to one + /// that sees none of it, Bilinear dims gradually where Nearest steps. + #[test] + fn bilinear_relief_blends_the_sky_too() { + // Cell 2 sees no sky in every row, the others all of it. + let sky: Vec = [255, 255, 0, 255, 255, 255].repeat(3); + let light = Lights { shadow: None, sky: Some(&sky) }; + let nearest = relief_row(Resampling::Nearest, None, &[], light, false); + let bilinear = relief_row(Resampling::Bilinear, None, &[], light, false); + let (open, hidden) = (nearest[149].unwrap(), nearest[249].unwrap()); + assert!(hidden < open && nearest[198] == Some(open) && nearest[199] == Some(hidden), "{open} {hidden}"); + assert_eq!((bilinear[149], bilinear[249]), (Some(open), Some(hidden))); + let middle = bilinear[199].unwrap(); + assert!(hidden < middle && middle < open, "{middle} between {hidden} and {open}"); + } + + /// Where a cell is a pixel across or less, Bilinear relief draws each cell's own light, as + /// before #1880: the blend couldn't be seen, and would work out four lights for each pixel. + #[test] + fn bilinear_relief_keeps_the_cells_light_when_a_cell_is_a_pixel_or_less() { + // 40 x 3 cells of 100 m with uneven heights, seen 24 pixels wide at `res` m a pixel. + let row = |resampling: Resampling, res: f64| { + let gt = GeoTransform { origin_x: 0.0, origin_y: 300.0, pixel_width: 100.0, pixel_height: -100.0 }; + let data = (0..120).map(|k| (k * 37 % 11) as f32 * 10.0).collect(); + let r = Raster::new("relief", 40, 3, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let mut style = RasterStyle::default_for(&r); + style.renderer = + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow: 0.0, sky: 0.0 }; + style.resampling = resampling; + let view = View { + width: 24.0, + height: 1.0, + pixels_per_point: 1.0, + camera: Camera { center: Coord::new(2000.0, 150.0), res, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let mut pm = Pixmap::new(24, 1).unwrap(); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Lights::default()); + (0..24).map(|x| pm.pixel(x, 0).map(|p| p.red())).collect::>() + }; + for res in [100.0, 150.0] { + assert_eq!(row(Resampling::Bilinear, res), row(Resampling::Nearest, res), "{res} m a pixel"); + } + // Two pixels to a cell: blended. + assert_ne!(row(Resampling::Bilinear, 50.0), row(Resampling::Nearest, 50.0)); + } + + /// A grid spanning one whole turn blends its light across the 0°/360° seam as anywhere else: + /// the cells on either side of it are neighbours, and a pixel just across it is a fraction of + /// a cell from the last one, not a whole turn. + #[test] + fn bilinear_relief_blends_across_a_whole_turns_seam() { + // 36 x 18 cells of 10 degrees, flat; the cast shadows leave no light on column 0 (0 to + // 10 degrees east) and all of it on the others. + let gt = GeoTransform { origin_x: 0.0, origin_y: 90.0, pixel_width: 10.0, pixel_height: -10.0 }; + let r = Raster::new("turn", 36, 18, vec![vec![0.0; 36 * 18]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let light: Vec = (0..36 * 18).map(|k| if k % 36 == 0 { 0 } else { 255 }).collect(); + // 80 pixels of half a degree across the seam, on row 8's centre (5 degrees north). + let view = View { + width: 80.0, + height: 1.0, + pixels_per_point: 1.0, + camera: Camera { center: lonlat_to_merc(Coord::new(0.0, 5.0)), res: 1_113_194.9 / 20.0, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let row = |resampling: Resampling| { + let mut style = RasterStyle::default_for(&r); + style.renderer = + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 315.0, altitude: 45.0, z_factor: 1.0, shadow: 1.0, sky: 0.0 }; + style.resampling = resampling; + let mut pm = Pixmap::new(80, 1).unwrap(); + draw( + &mut pm, + &r, + &style, + None, + &view, + 1.0, + false, + Place::Flat(&Flat::Mercator, "mercator"), + Lights { shadow: Some(&light), sky: None }, + ); + (0..80).map(|x| pm.pixel(x, 0).unwrap().red()).collect::>() + }; + let (nearest, bilinear) = (row(Resampling::Nearest), row(Resampling::Bilinear)); + // Column 35's centre (5 degrees west) is on pixel 29.5, column 0's on 49.5; the seam lies + // between pixels 39 and 40. + let (lit, dark) = (nearest[29], nearest[50]); + assert!(dark + 20 < lit && nearest[39] == lit && nearest[40] == dark, "{nearest:?}"); + let across = &bilinear[30..=49]; + assert!(across.windows(2).all(|w| w[0] >= w[1]), "darkens steadily across the seam: {across:?}"); + for x in [39, 40] { + assert!(dark + 10 < bilinear[x] && bilinear[x] + 10 < lit, "pixel {x} blends: {across:?}"); + } + } } diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index c5d8b761ae..04375c2166 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1298,6 +1298,11 @@ exports, and said when it can't be drawn (in the browser over 500,000 cells, or GeoTIFF read in place) as cast shadows are. Terrain outside the raster, or farther than 100 cells, hides none of its sky. +With **Resampling** set to bilinear, a Shaded Relief layer's light (its hillshade, cast shadows and +sky visibility) is blended between the cells' centres, as its values are, so a cell drawn over many +pixels shades smoothly instead of in squares; nearest keeps one light per cell, as before. A cell +with no data, or masked, is left out of the blend, so it doesn't darken the relief next to it. + **Masking**, at the foot of the Symbology pane (`raster.mask`), hides pixel values from view without changing the data: values to draw as no data (a background of 0 or −9999 the file doesn't flag, QA flags, land cover classes such as `0, 254, 255`), and values outside, or inside, a range. The