diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index c86b9a321a..efc71bcdc3 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use rustgis_data::raster::{self, Raster}; use rustgis_geom::Extent; use rustgis_map::raster::{ - Normalizer, RasterLayer, RasterMask, RasterRenderer, RasterStyle, Resampling, Stretch, classify_masked, unique_values, + Normalizer, RasterLayer, RasterMask, RasterRenderer, RasterStyle, Resampling, Rock, Stretch, classify_masked, unique_values, }; use rustgis_map::{ClassMethod, Ramp, RasterDefaults}; use serde_json::{Value, json}; @@ -36,7 +36,7 @@ pub fn commands() -> Vec { C::new("layer.addDataBytes", "Add Data (from file contents)", "Home › Add", add_bytes).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"fileName": "name.tif|.tiff|.asc|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf (JPEG 2000: desktop, through GDAL)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData)}"#), C::new("raster.symbology", "Symbology", "Style › Rendering", symbology).when(need_raster).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer"?, "type": "stretch"|"rgb"|"classify"|"unique"|"colormap"|"shadedRelief", "band"?: 1.., "ramp"?, "invert"?: bool, "classes"?: 1..32, "method"?, "azimuth"?, "altitude"?, "zFactor"?, "shadow"?: 0..1 (shadedRelief: how dark the shadows the terrain casts are; left out, kept; 0 casts none), "sky"?: 0..1 (shadedRelief: how much the share of the sky each cell sees dims its ambient light; left out, kept; 0 leaves it whole), "fill"?: 0..1 (shadedRelief: a fill light from the side opposite the sun that lightens the slopes turned toward it; left out, kept; 0 has none), "grey"?: bool (shadedRelief without its colour ramp)}"#, + r#"{"layer"?, "type": "stretch"|"rgb"|"classify"|"unique"|"colormap"|"shadedRelief", "band"?: 1.., "ramp"?, "invert"?: bool, "classes"?: 1..32, "method"?, "azimuth"?, "altitude"?, "zFactor"?, "shadow"?: 0..1 (shadedRelief: how dark the shadows the terrain casts are; left out, kept; 0 casts none), "sky"?: 0..1 (shadedRelief: how much the share of the sky each cell sees dims its ambient light; left out, kept; 0 leaves it whole), "fill"?: 0..1 (shadedRelief: a fill light from the side opposite the sun that lightens the slopes turned toward it; left out, kept; 0 has none), "rock"?: {"from"?: 0..90, "to"?: 0..90, "color"?: #RRGGBB} | false (shadedRelief: steep slopes tinted toward a rock colour before the light, from the ground's own slope in degrees, without the Z factor: the ramp below from, the colour above to, blended between; left out, kept; an object's missing keys keep the current rock's, or 25, 40 and #B2ACA4; false or null removes it), "grey"?: bool (shadedRelief without its colour ramp)}"#, ), C::new("raster.stretch", "Stretch Type", "Style › Rendering", stretch).inputs(stretch_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_raster) @@ -791,10 +791,10 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { RasterRenderer::Colormap } "shadedrelief" | "hillshade" => { - // Left out, a Shaded Relief keeps its own shadows, sky and fill light; a new one has none. - let (cur_shadow, cur_sky, cur_fill) = match rl.style.renderer { - RasterRenderer::ShadedRelief { shadow, sky, fill, .. } => (shadow, sky, fill), - _ => (0.0, 0.0, 0.0), + // Left out, a Shaded Relief keeps its own shadows, sky, fill light and rock; a new one has none. + let (cur_shadow, cur_sky, cur_fill, cur_rock) = match rl.style.renderer { + RasterRenderer::ShadedRelief { shadow, sky, fill, rock, .. } => (shadow, sky, fill, rock), + _ => (0.0, 0.0, 0.0, None), }; RasterRenderer::ShadedRelief { band: bi, @@ -805,6 +805,10 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { shadow: f(p, "shadow").unwrap_or(cur_shadow).clamp(0.0, 1.0), sky: f(p, "sky").unwrap_or(cur_sky).clamp(0.0, 1.0), fill: f(p, "fill").unwrap_or(cur_fill).clamp(0.0, 1.0), + rock: match p.get("rock") { + None => cur_rock, + Some(v) => relief_rock(v, cur_rock)?, + }, } } other => return Err(format!("unknown raster symbology '{other}'")), @@ -818,6 +822,31 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { }) } +/// The rock of a Shaded Relief's `"rock"` (see `raster.symbology`): `false` or null for none, or +/// an object whose missing keys keep `cur`'s, or else [`Rock::DEFAULT`]'s. +fn relief_rock(v: &Value, cur: Option) -> Result, String> { + if v.is_null() || *v == Value::Bool(false) { + return Ok(None); + } + if !v.is_object() { + return Err("rock must be an object with from, to and color, or false".into()); + } + let was = cur.unwrap_or(Rock::DEFAULT); + let angle = |k: &str, d: f64| match v.get(k).filter(|x| !x.is_null()) { + None => Ok(d), + Some(x) => x.as_f64().filter(|a| a.is_finite()).map(|a| a.clamp(0.0, 90.0)).ok_or_else(|| format!("rock's {k} must be degrees")), + }; + let (from, to) = (angle("from", was.from)?, angle("to", was.to)?); + if from >= to { + return Err(format!("rock's from ({from}°) must be below its to ({to}°)")); + } + let color = super::layout::color(v, "color", was.color)?; + if color.a() != 255 { + return Err("rock's color must be #RRGGBB: the rock is opaque".into()); + } + Ok(Some(Rock { from, to, color })) +} + /// Most values a mask lists. const MAX_MASK_VALUES: usize = 256; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a13f3bb374..9c591af191 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4361,6 +4361,67 @@ fn shaded_relief_keeps_its_fill_light() { assert_eq!(fill(&t), 0.45, "back when opened"); } +/// 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. +#[test] +fn shaded_relief_keeps_its_rock_on_steep_slopes() { + use rustgis_map::raster::Rock; + let mut s = with_raster(); + let rock = |s: &Session| match s.map().layers.first().and_then(|l| l.raster.as_ref()).map(|r| &r.style.renderer) { + Some(rustgis_map::RasterRenderer::ShadedRelief { rock, .. }) => *rock, + other => panic!("{other:?}"), + }; + let rocks_saved = |s: &mut Session| s.project.saved_text(None).unwrap().0.matches("\"rock\"").count(); + s.run("raster.symbology", &json!({"type": "shadedRelief"})).unwrap(); + assert_eq!(rock(&s), None, "off by default"); + let before = rocks_saved(&mut s); + s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": {}})).unwrap(); + assert_eq!(rock(&s), Some(Rock::DEFAULT)); + s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": {"to": 50, "color": "#806040"}})).unwrap(); + s.run("raster.symbology", &json!({"type": "shadedRelief", "azimuth": 200})).unwrap(); + let want = Rock { from: 25.0, to: 50.0, color: rustgis_map::Rgba::rgb(0x80, 0x60, 0x40) }; + assert_eq!(rock(&s), Some(want), "left out, kept; its missing keys too"); + assert_eq!(rocks_saved(&mut s), before + 1, "saved when set"); + for bad in + [json!({"from": 40, "to": 30}), json!({"from": 30, "to": 30}), json!({"color": "rock"}), json!({"color": "#B2ACA480"}), json!(3)] + { + assert!(s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": bad})).is_err(), "{bad}"); + assert_eq!(rock(&s), Some(want), "{bad}: refused, the rock kept"); + } + s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": false})).unwrap(); + assert_eq!(rock(&s), None); + assert_eq!(rocks_saved(&mut s), before, "not saved once removed"); +} + +/// An export draws the rock on steep slopes: a grey relief whose east half is a 63° wall turns +/// red there with a red rock, and keeps the same pixels on the flat west half. +#[test] +fn an_export_draws_the_rock_on_steep_slopes() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let mut s = world(); + // 41 cells of 30 m a side: flat to column 20, then rising 60 m a cell eastward. + let wall: Vec = (0..41 * 41).map(|i| ((i % 41 - 20).max(0) * 60) as f32).collect(); + let gt = GeoTransform { origin_x: 500_000.0, origin_y: 7_000_000.0, pixel_width: 30.0, pixel_height: -30.0 }; + let r = Raster::new("wall", 41, 41, vec![wall], gt, Crs::from_epsg(31983).unwrap(), None, ColorHint::Gray, "Float32").unwrap(); + let bytes = geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "wall", rustgis_map::RasterLayer::from_bytes(r, "wall.tif".to_string(), bytes)).unwrap(); + s.run("layer.zoomTo", &json!({"layer": "wall"})).unwrap(); + let drawn = |s: &mut Session, rock: Value| { + s.run("raster.symbology", &json!({"layer": "wall", "type": "shadedRelief", "grey": true, "azimuth": 270, "rock": rock})).unwrap(); + let png = crate::cmd::share::map_png(s, Some(200.0), Some(200.0), None).unwrap(); + crate::render::decode_png(&png).unwrap() + }; + let plain = drawn(&mut s, json!(false)); + let rocky = drawn(&mut s, json!({"from": 10, "to": 20, "color": "#FF0000"})); + let px = |p: &tiny_skia::Pixmap, x: u32| p.pixel(x, 100).map(|c| [c.red(), c.green(), c.blue()]).unwrap(); + // The flat west half: the same grey. The wall: grey without the rock, red with it. + assert_eq!(px(&rocky, 70), px(&plain, 70)); + let ([r0, g0, b0], [r1, g1, b1]) = (px(&plain, 130), px(&rocky, 130)); + assert!(r0 == g0 && g0 == b0 && r0 > 0, "a grey wall: {:?}", [r0, g0, b0]); + assert!(r1 > 0 && g1 == 0 && b1 == 0, "a red wall: {:?}", [r1, g1, b1]); +} + /// An export draws the sky a pit hides: its floor darker with `sky` 1 than with 0, the ground /// around it (which sees the whole sky) the same. The first export with the sky, from a cold /// cache, waits for the grid: it is the same image as one drawn once the grid is kept. diff --git a/crates/map/src/qgis/raster.rs b/crates/map/src/qgis/raster.rs index 53b735e41f..22095aadb5 100644 --- a/crates/map/src/qgis/raster.rs +++ b/crates/map/src/qgis/raster.rs @@ -97,6 +97,7 @@ fn renderer_style(node: Node, pipe: Node, r: Node, kind: &str, layer: &str, repo shadow: 0.0, sky: 0.0, fill: 0.0, + rock: None, }; (renderer, Stretch::None) } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 3d1f1f5c14..b0fb6c515d 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -875,7 +875,8 @@ fn raster_renderers_read_as_rustgis_raster_styles() { z_factor: 2.0, shadow: 0.0, sky: 0.0, - fill: 0.0 + fill: 0.0, + rock: None } ); assert!(report.notes.iter().any(|n| n.text.contains("saturation"))); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index fa43afb2b2..a0c5a2c1d7 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1150,6 +1150,32 @@ impl Default for ZarrTime { } } +/// Shaded Relief's rock colour on steep slopes (#1913): below `from` degrees of slope the ramp's +/// colour is kept, above `to` it is `color`, and between them the two are blended on a smooth +/// step. The slope is the ground's own, without the Z factor (see [`slope`]). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Rock { + pub from: f64, + pub to: f64, + pub color: Rgba, +} + +impl Rock { + /// What a rock turned on without settings is: a light warm grey from 25° to 40°, which a 30 m + /// DEM reaches on its real scarps (it averages a cliff with its foot). + pub const DEFAULT: Rock = Rock { from: 25.0, to: 40.0, color: Rgba::rgb(0xB2, 0xAC, 0xA4) }; + + /// The share of rock (0 to 1) on a slope of `degrees`: 0 up to `from`, 1 from `to` on, and a + /// smooth step between them, so no hard outline follows a contour of slope. + pub fn share(&self, degrees: f64) -> f64 { + if self.to - self.from <= 0.0 { + return if degrees >= self.to { 1.0 } else { 0.0 }; + } + let t = ((degrees - self.from) / (self.to - self.from)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + } +} + fn is_no_light(v: &f64) -> bool { *v == 0.0 } @@ -1358,7 +1384,8 @@ pub enum RasterRenderer { /// is how much the share of the sky each cell sees scales its ambient light /// ([`crate::shadow::sky`]); 0, the default, leaves it whole. `fill` (0 to 1) is a fill light /// from the side opposite the sun, 55° up, that lightens only the slopes turned toward it; 0, - /// the default, has none. + /// the default, has none. `rock` tints steep slopes toward a rock colour before the lights + /// shade them (see [`Rock`]); none, the default, keeps the ramp. ShadedRelief { band: usize, ramp: Option, @@ -1371,6 +1398,8 @@ pub enum RasterRenderer { sky: f64, #[serde(default, skip_serializing_if = "is_no_light")] fill: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + rock: Option, }, } @@ -1929,17 +1958,25 @@ impl<'a> Colorizer<'a> { /// The colour of a pixel from its renderer band values (`NaN` = no data), or `None` for /// transparent. `hillshade` (0–255) is used by Shaded Relief. pub fn color(&self, vals: &[f32], hillshade: Option) -> Option<[u8; 4]> { - self.color_lit(vals, hillshade, None, None) + self.color_lit(vals, hillshade, None, None, None) } /// [`Colorizer::color`], with Shaded Relief's ambient light scaled by `ambient` (0–255, the - /// share of it the sky a cell sees leaves, see [`RasterRenderer::ShadedRelief`]'s `sky`), and - /// `fill` (0–255, a share of the colour) added for its fill light (its `fill`). - pub fn color_lit(&self, vals: &[f32], hillshade: Option, ambient: Option, fill: Option) -> Option<[u8; 4]> { + /// share of it the sky a cell sees leaves, see [`RasterRenderer::ShadedRelief`]'s `sky`), + /// `fill` (0–255, a share of the colour) added for its fill light (its `fill`), and its colour + /// moved `rock` (0–255) of the way to its rock colour (its `rock`, see [`Rock::share`]). + pub fn color_lit( + &self, + vals: &[f32], + hillshade: Option, + ambient: Option, + fill: Option, + rock: Option, + ) -> Option<[u8; 4]> { // The renderer masks values as it samples them (they arrive as NaN); this is for other callers. let mask = &self.style.mask; if mask.is_empty() || !vals.iter().any(|v| mask.hides(*v)) { - return self.paint(vals, hillshade, ambient, fill); + return self.paint(vals, hillshade, ambient, fill, rock); } // Masked values are no data. The renderer bands are at most three. let mut kept = [f32::NAN; 3]; @@ -1948,10 +1985,10 @@ impl<'a> Colorizer<'a> { *k = *v; } } - self.paint(kept.get(..vals.len().min(3)).unwrap_or(&kept), hillshade, ambient, fill) + self.paint(kept.get(..vals.len().min(3)).unwrap_or(&kept), hillshade, ambient, fill, rock) } - fn paint(&self, vals: &[f32], hillshade: Option, ambient: Option, fill: Option) -> Option<[u8; 4]> { + fn paint(&self, vals: &[f32], hillshade: Option, ambient: Option, fill: Option, rock: Option) -> Option<[u8; 4]> { let v0 = *vals.first()?; let c = match &self.style.renderer { RasterRenderer::Rgb { .. } => { @@ -1978,9 +2015,14 @@ impl<'a> Colorizer<'a> { } *self.palette.get(i as usize)? } - RasterRenderer::ShadedRelief { ramp, .. } => { + RasterRenderer::ShadedRelief { ramp, rock: steep, .. } => { let h = hillshade.unwrap_or(180) as f64 / 255.0; let base = if ramp.is_some() { *self.ramp_lut.get(self.byte(0, v0) as usize)? } else { [255, 255, 255, 255] }; + // Steep ground first takes on the rock colour; the light then shades either. + let base = match (steep, rock) { + (Some(steep), Some(share)) if share > 0 => Rgba(base).lerp(steep.color.with_alpha(255), f64::from(share) / 255.0).0, + _ => base, + }; // Multiply the tint by the hillshade, keeping some ambient light (less of it where // the terrain hides part of the sky), and adding the fill light on its own. let a = 0.25 * ambient.map_or(1.0, |a| f64::from(a) / 255.0); @@ -1993,16 +2035,29 @@ impl<'a> Colorizer<'a> { } } -/// Hillshade (0–255) from a 3×3 window of elevations (row by row), Horn's method. -pub fn hillshade(z: &[f64; 9], cell_x: f64, cell_y: f64, azimuth: f64, altitude: f64, z_factor: f64) -> u8 { +/// The slope (degrees) of a 3×3 window of elevations (row by row), from the gradient +/// [`hillshade`] uses: the ground's own, with no Z factor. +pub fn slope(z: &[f64; 9], cell_x: f64, cell_y: f64) -> f64 { + let (dzdx, dzdy) = horn(z, cell_x, cell_y); + dzdx.hypot(dzdy).atan().to_degrees() +} + +/// The east and south gradients of a 3×3 window of elevations, Horn's method. +fn horn(z: &[f64; 9], cell_x: f64, cell_y: f64) -> (f64, f64) { let [a, b, c, d, _, f, g, h, i] = *z; let dzdx = ((c + 2.0 * f + i) - (a + 2.0 * d + g)) / (8.0 * cell_x.max(1e-9)); let dzdy = ((g + 2.0 * h + i) - (a + 2.0 * b + c)) / (8.0 * cell_y.max(1e-9)); - let slope = (z_factor * (dzdx * dzdx + dzdy * dzdy).sqrt()).atan(); + (dzdx, dzdy) +} + +/// Hillshade (0–255) from a 3×3 window of elevations (row by row), Horn's method. +pub fn hillshade(z: &[f64; 9], cell_x: f64, cell_y: f64, azimuth: f64, altitude: f64, z_factor: f64) -> u8 { + let (dzdx, dzdy) = horn(z, cell_x, cell_y); + let tilt = (z_factor * (dzdx * dzdx + dzdy * dzdy).sqrt()).atan(); let aspect = if dzdx != 0.0 || dzdy != 0.0 { dzdy.atan2(-dzdx) } else { 0.0 }; let zenith = (90.0 - altitude.clamp(0.0, 90.0)).to_radians(); let az = (360.0 - azimuth + 90.0).rem_euclid(360.0).to_radians(); - let v = zenith.cos() * slope.cos() + zenith.sin() * slope.sin() * (az - aspect).cos(); + let v = zenith.cos() * tilt.cos() + zenith.sin() * tilt.sin() * (az - aspect).cos(); (v.max(0.0) * 255.0).round().clamp(0.0, 255.0) as u8 } @@ -2301,6 +2356,11 @@ mod tests { use super::*; + /// A Shaded Relief without a ramp or rock, lit from `azimuth` and `altitude`. + fn grey_relief(azimuth: f64, altitude: f64, z_factor: f64, shadow: f64, sky: f64) -> RasterRenderer { + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude, z_factor, shadow, sky, fill: 0.0, rock: None } + } + /// The legend names a class as the file does (#889), and gives the value of one it doesn't. #[test] fn legend_labels_classes_with_their_names() { @@ -2787,14 +2847,76 @@ mod tests { assert!(plain.opening.is_none(), "an anonymous web raster is not fetched whole"); } + /// Rock on steep slopes (#1913): the ramp's colour up to `from`, the rock's from `to` on, and a + /// smooth step between them; the slope is the ground's own, which no Z factor changes; and the + /// rock is saved only when set. + #[test] + fn rock_tints_steep_slopes_by_the_grounds_own_slope() { + let rock = Rock { from: 20.0, to: 40.0, color: Rgba::rgb(200, 100, 50) }; + assert_eq!((rock.share(0.0), rock.share(20.0), rock.share(40.0), rock.share(70.0)), (0.0, 0.0, 1.0, 1.0)); + assert!((rock.share(30.0) - 0.5).abs() < 1e-12); + let (a, b) = (rock.share(22.0), rock.share(25.0)); + assert!(0.0 < a && a < b && b < 0.5, "a smooth step, slow at its ends: {a}, {b}"); + // A plane rising one metre a metre eastward is 45 degrees, whatever the light's Z factor. + let z = [0.0, 10.0, 20.0, 0.0, 10.0, 20.0, 0.0, 10.0, 20.0]; + assert!((slope(&z, 10.0, 10.0) - 45.0).abs() < 1e-9); + assert_ne!(hillshade(&z, 10.0, 10.0, 270.0, 45.0, 1.0), hillshade(&z, 10.0, 10.0, 270.0, 45.0, 3.0)); + + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = + Raster::new("dem", 10, 10, vec![(0..100).map(|v| v as f32).collect()], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32") + .unwrap(); + let relief = |rock| RasterRenderer::ShadedRelief { + band: 0, + ramp: Some(Ramp::Terrain), + azimuth: 315.0, + altitude: 45.0, + z_factor: 1.0, + shadow: 0.0, + sky: 0.0, + fill: 0.0, + rock, + }; + let (mut rocky, mut plain) = (RasterStyle::default_for(&r), RasterStyle::default_for(&r)); + (rocky.renderer, plain.renderer) = (relief(Some(rock)), relief(None)); + let (with, without) = (Colorizer::new(&rocky, &r, None), Colorizer::new(&plain, &r, None)); + for (v, h) in [(10.0, 0), (50.0, 128), (90.0, 255)] { + let plain = without.color_lit(&[v], Some(h), None, None, None); + assert_eq!(with.color_lit(&[v], Some(h), None, None, None), plain, "no share of rock: the ramp"); + assert_eq!(with.color_lit(&[v], Some(h), None, None, Some(0)), plain, "flat ground: the ramp"); + assert_eq!(without.color_lit(&[v], Some(h), None, None, Some(255)), plain, "no rock set: the ramp"); + // All rock: the rock colour, lit as the ramp is (a quarter ambient, the rest the sun). + let lit = |c: u8| (f64::from(c) * (0.25 + 0.75 * f64::from(h) / 255.0)).round() as u8; + assert_eq!(with.color_lit(&[v], Some(h), None, None, Some(255)), Some([lit(200), lit(100), lit(50), 255])); + // Half way: half way between the two colours. + let half = with.color_lit(&[v], Some(255), None, None, Some(128)).unwrap(); + let ramp = without.color_lit(&[v], Some(255), None, None, None).unwrap(); + for (k, end) in [200u8, 100, 50].into_iter().enumerate() { + let mid = (f64::from(ramp[k]) + f64::from(end)) / 2.0; + assert!((f64::from(half[k]) - mid).abs() <= 1.5, "{v}: channel {k} {} not near {mid}", half[k]); + } + // With the sky and the fill light (#1912) too: the rock colour first, then every light + // shades it, as they shade the ramp. + let all = |c: u8| (f64::from(c) * (0.25 * 128.0 / 255.0 + 0.75 * f64::from(h) / 255.0 + 40.0 / 255.0)).round() as u8; + assert_eq!(with.color_lit(&[v], Some(h), Some(128), Some(40), Some(255)), Some([all(200), all(100), all(50), 255])); + let filled = without.color_lit(&[v], Some(h), Some(128), Some(40), None); + assert_eq!(with.color_lit(&[v], Some(h), Some(128), Some(40), Some(0)), filled, "flat ground: the filled ramp"); + } + + // Saved only when set, and read back as it was. + let saved = serde_json::to_string(&relief(None)).unwrap(); + assert!(!saved.contains("rock"), "{saved}"); + let saved = serde_json::to_string(&relief(Some(rock))).unwrap(); + assert_eq!(serde_json::from_str::(&saved).unwrap(), relief(Some(rock))); + } + /// 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 }; let data: Vec = (0..400).map(|i| if i == 10 * 20 + 10 { 900.0 } else { 0.0 }).collect(); let r = Raster::new("tower", 20, 20, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut rl = RasterLayer::from_path(r, "tower.tif"); - rl.style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 90.0, altitude: 30.0, z_factor: 1.0, shadow, sky: 0.0, fill: 0.0 }; + rl.style.renderer = grey_relief(90.0, 30.0, 1.0, shadow, 0.0); rl } @@ -2852,16 +2974,7 @@ mod tests { let r = Raster::new("hills", 1200, 1200, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut rl = RasterLayer::from_path(r, "hills.tif"); let lit = |rl: &mut RasterLayer, az: f64| { - rl.style.renderer = RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: az, - altitude: 10.0, - z_factor: 1.0, - shadow: 1.0, - sky: 0.0, - fill: 0.0, - }; + rl.style.renderer = grey_relief(az, 10.0, 1.0, 1.0, 0.0); }; let other = |az: f64, rl: &RasterLayer| { let mut c = rl.clone(); @@ -2920,16 +3033,7 @@ mod tests { let data: Vec = (0..2000 * 2000).map(|i| ((i % 2000) as f32 * 0.01) + ((i / 2000) as f32 * 0.01)).collect(); let r = Raster::new("plain", 2000, 2000, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut rl = RasterLayer::from_path(r, "plain.tif"); - rl.style.renderer = RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: 135.0, - altitude: 2.0, - z_factor: 1.0, - shadow: 1.0, - sky: 0.0, - fill: 0.0, - }; + rl.style.renderer = grey_relief(135.0, 2.0, 1.0, 1.0, 0.0); let (sent, landings) = std::sync::mpsc::channel::<()>(); { let _cancelled = rustgis_data::progress::install(Some(std::sync::Arc::new(Cancelled))); @@ -2957,16 +3061,7 @@ mod tests { let data: Vec = (0..800 * 800).map(|i| ((i % 800) as f32 * 0.01) + ((i / 800) as f32 * 0.01)).collect(); let r = Raster::new("plain", 800, 800, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut rl = RasterLayer::from_path(r, "plain.tif"); - rl.style.renderer = RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: 135.0, - altitude: 3.0, - z_factor: 1.0, - shadow: 1.0, - sky: 0.0, - fill: 0.0, - }; + rl.style.renderer = grey_relief(135.0, 3.0, 1.0, 1.0, 0.0); let (sent, landings) = std::sync::mpsc::channel::<&'static str>(); let told = |who: &'static str| { let tx = sent.clone(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 04f264aa95..d3832f3c21 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -3682,6 +3682,7 @@ mod tests { shadow, sky: 0.0, fill: 0.0, + rock: None, }; for shadow in [0.0, 1.0] { let map = ramp_map(relief(shadow), rustgis_map::raster::Stretch::MinMax); @@ -3732,6 +3733,7 @@ mod tests { shadow: 1.0, sky: 0.0, fill: 0.0, + rock: None, }; let mut m = Map::new(name.clone()); assert_eq!(m.add_raster("dem", copy), 1); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 47a5629c7c..30343c099c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8864,6 +8864,7 @@ mod tests { shadow, sky: 0.0, fill: 0.0, + rock: None, }; }; let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 1200.0, bearing: 0.0, pitch: 0.0 }; @@ -8898,6 +8899,7 @@ mod tests { shadow: 1.0, sky: 0.0, fill: 0.0, + rock: None, }; // Drawn only zoomed out past a scale between the centre's and the far band's. l.max_scale = Some((centre + farthest) / 2.0); @@ -8942,6 +8944,7 @@ mod tests { shadow: 1.0, sky: 0.0, fill: 0.0, + rock: None, }; // Drawn only zoomed in past 1:1: or in a group drawn only there. if grouped { diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 0db44290df..dbd4dc9d15 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -10,7 +10,7 @@ use rustgis_data::raster::{BandStats, ColorHint, Raster}; use rustgis_geom::{Coord, Extent, extent_to_merc}; use rustgis_map::Globe; use rustgis_map::projection::Flat; -use rustgis_map::raster::{Colorizer, RasterMask, RasterRenderer, RasterStyle, Resampling, hillshade}; +use rustgis_map::raster::{Colorizer, RasterMask, RasterRenderer, RasterStyle, Resampling, Rock, hillshade, slope}; use tiny_skia::{FilterQuality, Pixmap, PixmapPaint, Transform}; use crate::View; @@ -496,6 +496,11 @@ fn draw_with( RasterRenderer::ShadedRelief { fill, .. } if fill > 0.0 => fill.min(1.0), _ => 0.0, }; + // Steep slopes tinted toward rock, before the light. + let rock = match style.renderer { + RasterRenderer::ShadedRelief { rock, .. } => rock, + _ => None, + }; // Blending neighbours would invent values that aren't classes or palette entries. let resampling = match style.renderer { RasterRenderer::UniqueValues { .. } | RasterRenderer::Colormap => Resampling::Nearest, @@ -527,6 +532,7 @@ fn draw_with( shadow, sky, fill, + rock, resampling, alpha_band, alpha_max: rustgis_data::raster::alpha_max(&r.data_type), @@ -539,6 +545,7 @@ fn draw_with( let mut alpha = if alpha_band.is_some() { vec![0u8; bw * bh] } else { Vec::new() }; let mut ambient = if sky.is_some() { vec![255u8; bw * bh] } else { Vec::new() }; let mut filled = if relief.is_some() && fill > 0.0 { vec![0u8; bw * bh] } else { Vec::new() }; + let mut rocky = if relief.is_some() && rock.is_some() { vec![0u8; bw * bh] } else { Vec::new() }; let threads = threads.clamp(1, bh); let rows = bh.div_ceil(threads.max(1)); each_chunk( @@ -548,8 +555,9 @@ fn draw_with( .zip(chunks_or_empty(&mut alpha, rows * bw)) .zip(chunks_or_empty(&mut ambient, rows * bw)) .zip(chunks_or_empty(&mut filled, rows * bw)) + .zip(chunks_or_empty(&mut rocky, rows * bw)) .enumerate(), - |(i, ((((v, sh), al), am), fl))| pass1.rows(y0 + i * rows, v, sh, al, am, fl), + |(i, (((((v, sh), al), am), fl), ro))| pass1.rows(y0 + i * rows, v, sh, al, am, fl, ro), ); // Dynamic range adjustment: statistics of the values in view. @@ -559,19 +567,20 @@ fn draw_with( // Pass 2: colours, premultiplied, into a pixmap the size of the raster's screen box. let Some(mut lay) = Pixmap::new(bw as u32, bh as u32) else { return }; - let (vals, shade, alpha, ambient, filled) = (&vals, &shade, &alpha, &ambient, &filled); + let (vals, shade, alpha, ambient, filled, rocky) = (&vals, &shade, &alpha, &ambient, &filled, &rocky); each_chunk(threads, lay.data_mut().chunks_mut(rows * bw * 4).enumerate(), |(ci, out)| { let first = ci * rows * bw; // Neighbouring pixels often share their values (zoomed in, or classes): colour once. - let mut last: Option<(&[f32], [Option; 4], Option<[u8; 4]>)> = None; + let mut last: Option<(&[f32], [Option; 5], Option<[u8; 4]>)> = None; for (j, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { let i = first + j; let Some(v) = vals.get(i * nb..(i + 1) * nb) else { continue }; - let (sh, al, am, fl) = (shade.get(i).copied(), alpha.get(i).copied(), ambient.get(i).copied(), filled.get(i).copied()); + let (sh, al, am) = (shade.get(i).copied(), alpha.get(i).copied(), ambient.get(i).copied()); + let (fl, ro) = (filled.get(i).copied(), rocky.get(i).copied()); let c = match last { - Some((lv, l, c)) if l == [sh, al, am, fl] && same(lv, v) => c, + Some((lv, l, c)) if l == [sh, al, am, fl, ro] && same(lv, v) => c, _ => { - let c = colorizer.color_lit(v, sh, am, fl).map(|mut c| { + let c = colorizer.color_lit(v, sh, am, fl, ro).map(|mut c| { if let Some(a) = al { c[3] = ((c[3] as u16 * a as u16 + 127) / 255) as u8; } @@ -579,7 +588,7 @@ fn draw_with( let pm = |x: u8| ((x as u16 * a + 127) / 255) as u8; [pm(c[0]), pm(c[1]), pm(c[2]), c[3]] }); - last = Some((v, [sh, al, am, fl], c)); + last = Some((v, [sh, al, am, fl, ro], c)); c } }; @@ -667,6 +676,8 @@ struct Pass1<'a> { sky: Option<(&'a [u8], f64)>, /// The fill light's strength (0 to 1; 0, none), see [`FILL_ALTITUDE`]. fill: f64, + /// Shaded Relief's rock on steep slopes, when it has one. + rock: Option, resampling: Resampling, alpha_band: Option, /// The alpha band's opaque value (its pixel type's: 65535 for 16 bits). @@ -680,9 +691,18 @@ struct Pass1<'a> { } impl Pass1<'_> { - /// Fills the band values (and hillshade, alpha, ambient and fill light, when kept) of the screen - /// rows from `py0` on, as many as `vals` holds. - fn rows(&self, py0: usize, vals: &mut [f32], shade: &mut [u8], alpha: &mut [u8], ambient: &mut [u8], filled: &mut [u8]) { + /// Fills the band values (and hillshade, alpha, ambient and fill light and share of rock, when + /// kept) of the screen rows from `py0` on, as many as `vals` holds. + fn rows( + &self, + py0: usize, + vals: &mut [f32], + shade: &mut [u8], + alpha: &mut [u8], + ambient: &mut [u8], + filled: &mut [u8], + rocky: &mut [u8], + ) { let (r, bw, nb) = (self.r, self.bw, self.bands.len().max(1)); let lerp = |p: f64, q: f64, t: f64| p + (q - p) * t; // Each grid column's source position at this row, interpolated down the grid. @@ -823,6 +843,9 @@ impl Pass1<'_> { if let Some(f) = filled.get_mut(i) { *f = light.fill.round().clamp(0.0, 255.0) as u8; } + if let Some(ro) = rocky.get_mut(i) { + *ro = light.rock.round().clamp(0.0, 255.0) as u8; + } } } } @@ -830,9 +853,10 @@ impl Pass1<'_> { /// 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; and the fill light (see [`FILL_ALTITUDE`]), - /// which nothing shadows. `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 + /// 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 /// [`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; @@ -858,7 +882,8 @@ impl Pass1<'_> { } else { 0.0 }; - Lit { direct, ambient: left(self.sky).map_or(255.0, |left| left * 255.0), fill } + let rock = self.rock.map_or(0.0, |rock| rock.share(slope(&z, self.cell.0, self.cell.1)) * 255.0); + Lit { direct, ambient: left(self.sky).map_or(255.0, |left| left * 255.0), fill, rock } } /// The lights of the cell `(i, j)`, or none when it is no data, masked or outside the grid; a @@ -893,6 +918,8 @@ struct Lit { direct: f64, ambient: f64, fill: f64, + /// Its share of rock, 0 to 255: not a light, but blended as the lights are. + rock: f64, } /// The four cells' lights of [`Pass1::quad_lights`] blended bilinearly at `(fx, fy)` (0 to 1) @@ -902,16 +929,17 @@ struct Lit { /// 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 fill, mut total) = (0.0, 0.0, 0.0, 0.0); + let (mut direct, mut ambient, mut fill, mut rock, mut total) = (0.0, 0.0, 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; fill += w * light.fill; + rock += w * light.rock; total += w; } } - (total > 0.0).then(|| Lit { direct: direct / total, ambient: ambient / total, fill: fill / total }) + (total > 0.0).then(|| Lit { direct: direct / total, ambient: ambient / total, fill: fill / total, rock: rock / total }) } /// Whether two pixels' band values are the same (NaN, no data, equal to itself). @@ -974,6 +1002,11 @@ mod tests { use super::*; + /// A Shaded Relief without a ramp or rock, lit from `azimuth` and `altitude`. + fn grey_relief(azimuth: f64, altitude: f64, z_factor: f64, shadow: f64, sky: f64) -> RasterRenderer { + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude, z_factor, shadow, sky, fill: 0.0, rock: None } + } + /// A raster turned by a hair either side of none isn't turned: it is drawn at the view's /// resolution, not from its overview. #[test] @@ -1064,6 +1097,7 @@ mod tests { shadow: 0.0, sky: 0.0, fill: 0.0, + rock: None, }; style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); @@ -1097,16 +1131,7 @@ mod tests { let data = [0.0, 1_000_000.0, 2_000_000.0, 3_000_000.0].repeat(18); let r = Raster::new("regional relief", 4, 18, vec![data], gt, Crs::LonLat, 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, - fill: 0.0, - }; + style.renderer = grey_relief(270.0, 45.0, 1.0, 0.0, 0.0); style.resampling = Resampling::Nearest; let view = View { width: 1.0, @@ -1145,16 +1170,7 @@ mod tests { let dark = vec![0u8; 4 * 18]; let drawn = |shadow: f64, light: Option<&[u8]>| { 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, - sky: 0.0, - fill: 0.0, - }; + style.renderer = grey_relief(270.0, 45.0, 1.0, shadow, 0.0); style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); draw( @@ -1206,8 +1222,7 @@ mod tests { let (none, dark) = (vec![0u8; 4 * 18], vec![0u8; 4 * 18]); let drawn = |shadow: f64, sky: f64, light: Lights| { 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, sky, fill: 0.0 }; + style.renderer = grey_relief(270.0, 45.0, 1.0, shadow, sky); style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), light); @@ -1220,17 +1235,8 @@ mod tests { assert_eq!(drawn(0.0, 1.0, Lights::default()), today, "no grid"); // No sky at all: the direct light alone. 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: 1.0, - fill: 0.0, - }; - let want = Colorizer::new(&style, &r, None).color_lit(&[0.0], Some(lit), Some(0), None).unwrap(); + style.renderer = grey_relief(270.0, 45.0, 1.0, 0.0, 1.0); + let want = Colorizer::new(&style, &r, None).color_lit(&[0.0], Some(lit), Some(0), None, None).unwrap(); assert_eq!(drawn(0.0, 1.0, hidden), want); assert!(want[0] < today[0]); // In full shadow only the ambient light is left: a quarter of the colour, scaled by the @@ -1255,8 +1261,17 @@ mod tests { let r = Raster::new("relief", 3, 3, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); let (azimuth, altitude) = (270.0, 45.0); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude, z_factor: 1.0, shadow: 0.0, sky: 0.0, fill }; + style.renderer = RasterRenderer::ShadedRelief { + band: 0, + ramp: None, + azimuth, + altitude, + z_factor: 1.0, + shadow: 0.0, + sky: 0.0, + fill, + rock: None, + }; style.resampling = Resampling::Nearest; let view = View { width: 1.0, @@ -1326,16 +1341,7 @@ mod tests { let data: Vec = (0..36 * 18).map(|i| elevations[(i % 36 + shift) % 36]).collect(); let r = Raster::new("relief", 36, 18, vec![data], gt, Crs::LonLat, 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, - fill: 0.0, - }; + style.renderer = grey_relief(270.0, 45.0, 1.0, 0.0, 0.0); style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(80, 40).unwrap(); draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Lights::default()); @@ -1421,16 +1427,7 @@ mod tests { "rgb" => RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }, "classify" => rustgis_map::raster::classify(&r, 0, 5, Default::default(), Default::default()), "unique" => rustgis_map::raster::unique_values(&r, 0, Default::default()), - _ => RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: 315.0, - altitude: 45.0, - z_factor: 1.0, - shadow: 0.0, - sky: 0.0, - fill: 0.0, - }, + _ => grey_relief(315.0, 45.0, 1.0, 0.0, 0.0), }; s.dra = true; s.resampling = Resampling::Bilinear; @@ -1448,16 +1445,7 @@ mod tests { let mut s = style.clone(); s.renderer = match kind { "rgb" => RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }, - "shadedRelief" => RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: 315.0, - altitude: 45.0, - z_factor: 1.0, - shadow: 0.0, - sky: 0.0, - fill: 0.0, - }, + "shadedRelief" => grey_relief(315.0, 45.0, 1.0, 0.0, 0.0), _ => s.renderer, }; let mut one = Pixmap::new(420, 300).unwrap(); @@ -1592,8 +1580,7 @@ mod tests { 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, fill: 0.0 }; + style.renderer = grey_relief(270.0, 45.0, 1.0, shadow, sky); style.resampling = resampling; style.mask = RasterMask { values: mask.to_vec(), ..RasterMask::default() }; let view = View { @@ -1608,6 +1595,89 @@ mod tests { (0..600).map(|x| pm.pixel(x, 0).filter(|p| p.alpha() > 0).map(|p| p.red())).collect() } + /// The middle row of a white relief rising eastward (cells 100 m, slopes of 0, 5.7, 16.7, 26.6, + /// 35 and 21.8 degrees), lit from `azimuth` with `rock`, `z_factor` and `fill`, as each pixel's + /// colour. + fn rock_row(resampling: Resampling, rock: Option, z_factor: f64, (azimuth, fill): (f64, f64)) -> Vec<[u8; 3]> { + let gt = GeoTransform { origin_x: 0.0, origin_y: 300.0, pixel_width: 100.0, pixel_height: -100.0 }; + let data = [0.0, 0.0, 20.0, 60.0, 120.0, 200.0].repeat(3); + let r = Raster::new("relief", 6, 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, altitude: 45.0, z_factor, shadow: 0.0, sky: 0.0, fill, rock }; + style.resampling = resampling; + 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"), Lights::default()); + (0..600).map(|x| pm.pixel(x, 0).map_or([0; 3], |p| [p.red(), p.green(), p.blue()])).collect() + } + + /// 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 + /// between cell centres as it blends the light. + #[test] + fn rock_tints_steep_slopes_before_the_light() { + const WEST: (f64, f64) = (270.0, 0.0); + let rock = Rock { from: 10.0, to: 30.0, color: rustgis_map::Rgba::rgb(200, 100, 50) }; + let plain = rock_row(Resampling::Nearest, None, 1.0, WEST); + let rocky = rock_row(Resampling::Nearest, Some(rock), 1.0, WEST); + let centre = |row: &[[u8; 3]], k: usize| row[100 * k + 49]; + // Green over red: 1 on the white relief, 0.5 on the rock, whatever the light. + let tint = |c: [u8; 3]| f64::from(c[1]) / f64::from(c[0]); + for k in [0, 1] { + assert_eq!(centre(&rocky, k), centre(&plain, k), "cell {k} is below from"); + } + assert!((tint(centre(&rocky, 4)) - 0.5).abs() < 0.02, "cell 4 is past to: {:?}", centre(&rocky, 4)); + for k in [2, 3, 5] { + let t = tint(centre(&rocky, k)); + assert!(0.52 < t && t < 0.98, "cell {k} leans toward rock: {t}"); + } + assert!(tint(centre(&rocky, 2)) > tint(centre(&rocky, 3)), "steeper, more rock"); + // Three times the Z factor: other lights, the same tints. + let steeper = rock_row(Resampling::Nearest, Some(rock), 3.0, WEST); + for k in 1..6 { + assert_ne!(centre(&steeper, k), centre(&rocky, k), "cell {k}: the light changes"); + assert!((tint(centre(&steeper, k)) - tint(centre(&rocky, k))).abs() < 0.02, "cell {k}: the tint doesn't"); + } + // Bilinear: the tint runs from cell 2's centre to cell 3's, not in a step. + let bilinear = rock_row(Resampling::Bilinear, Some(rock), 1.0, WEST); + let tints = |row: &[[u8; 3]]| row[249..=349].iter().map(|c| (tint(*c) * 1000.0).round() as i64).collect::>(); + let mut seen = tints(&bilinear); + // (Each colour channel is rounded to a byte: a tint can step back by a hundredth.) + assert!(seen.windows(2).all(|w| w[1] <= w[0] + 10), "toward more rock all the way: {seen:?}"); + seen.dedup(); + let mut stepped = tints(&rocky); + stepped.dedup(); + assert!(seen.len() > 20 && stepped.len() == 2, "{} tints blended, {} nearest", seen.len(), stepped.len()); + } + + /// Rock and the fill light (#1912) together: the slopes turned from the sun take the rock + /// colour, and the fill lightens it as it lightens the ramp, keeping its tint; flat ground + /// gets neither. + #[test] + fn the_fill_light_lightens_the_rock_too() { + let rock = Rock { from: 10.0, to: 30.0, color: rustgis_map::Rgba::rgb(200, 100, 50) }; + // The sun from the east: the slopes rising eastward face away from it, toward the fill. + let unfilled = rock_row(Resampling::Nearest, Some(rock), 1.0, (90.0, 0.0)); + let filled = rock_row(Resampling::Nearest, Some(rock), 1.0, (90.0, 1.0)); + let plain = rock_row(Resampling::Nearest, None, 1.0, (90.0, 1.0)); + let centre = |row: &[[u8; 3]], k: usize| row[100 * k + 49]; + let tint = |c: [u8; 3]| f64::from(c[1]) / f64::from(c[0]); + let (dim, lit) = (centre(&unfilled, 4), centre(&filled, 4)); + assert!(lit.iter().zip(dim).all(|(l, d)| *l > d), "cell 4 (35 degrees) lightened: {dim:?} to {lit:?}"); + assert!((tint(lit) - 0.5).abs() < 0.02 && (tint(dim) - 0.5).abs() < 0.02, "the rock's tint kept: {dim:?} {lit:?}"); + assert!(tint(centre(&plain, 4)) > 0.98, "no rock: the white relief, filled"); + assert_eq!(centre(&filled, 0), centre(&unfilled, 0), "flat: no fill"); + assert_eq!(centre(&filled, 0), centre(&plain, 0), "flat: no rock"); + } + /// 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. @@ -1689,16 +1759,7 @@ mod tests { 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, - fill: 0.0, - }; + style.renderer = grey_relief(270.0, 45.0, 1.0, 0.0, 0.0); style.resampling = resampling; let view = View { width: 24.0, @@ -1738,16 +1799,7 @@ mod tests { }; 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, - fill: 0.0, - }; + style.renderer = grey_relief(315.0, 45.0, 1.0, 1.0, 0.0); style.resampling = resampling; let mut pm = Pixmap::new(80, 1).unwrap(); draw( diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index 5d270b5e32..aa9f1bf3f9 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -199,6 +199,7 @@ mod tests { shadow: 1.0, sky: 0.0, fill: 0.0, + rock: None, }; let e = export(&layer, 2, 2, 1.0).err().unwrap_or_else(|| panic!("an archive without its shadows")); assert!(e.contains("cast shadows") && e.contains("read in place"), "{e}"); @@ -231,6 +232,7 @@ mod tests { shadow: 1.0, sky: 0.0, fill: 0.0, + rock: None, }; let _cancelled = rustgis_data::progress::install(Some(std::sync::Arc::new(Cancelled))); let e = export(&layer, 0, 0, 1.0).err().unwrap_or_else(|| panic!("an archive without its shadows")); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index b0188ece7b..2887084a6e 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -5128,6 +5128,7 @@ mod tests { shadow, sky: 0.0, fill: 0.0, + rock: None, }; let set = |map: &mut Map, shadow: f64, visible: bool| { let l = map.layer_mut(id).unwrap(); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 7466eea54c..04c29fac5a 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -7,7 +7,7 @@ use egui::{Align2, CornerRadius, Rect, Sense, Stroke, Ui, pos2, vec2}; use rustgis_engine::Session; use rustgis_engine::analysis::{ParamKind, tools}; use rustgis_engine::data::GeometryType; -use rustgis_engine::map::raster::{Normalizer, RasterLegend, RasterStyle}; +use rustgis_engine::map::raster::{Normalizer, RasterLegend, RasterStyle, Rock}; use rustgis_engine::map::symbology::{ ClassRef, ClassStyle, Dash, LineCap, LineJoin, LineMark, LineMarkers, LineStroke, MAX_EXPRESSION_CLASSES, MAX_LABEL, MAX_LINE_MARKER_SIZE, MAX_MARKER_INTERVAL, MAX_STROKE_OFFSET, MAX_STROKE_WIDTH, MAX_STROKES, MIN_MARKER_INTERVAL, OTHER_VALUES, @@ -6756,7 +6756,7 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { RasterRenderer::Colormap => { ui.label(egui::RichText::new(tl!("Colors from the raster's own color table.")).size(11.5).color(t.text_dim)); } - RasterRenderer::ShadedRelief { band, ramp, azimuth, altitude, z_factor, shadow, sky, fill } => { + RasterRenderer::ShadedRelief { band, ramp, azimuth, altitude, z_factor, shadow, sky, fill, rock } => { let (az, alt, zf, sh, sk, fl) = (*azimuth, *altitude, *z_factor, *shadow, *sky, *fill); let rp = ramp.as_ref().map(|r| r.name().to_string()); let relief = move |band: usize, az: f64, alt: f64, zf: f64, sh: f64| { @@ -6815,6 +6815,7 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { ui.end_row(); } }); + rock_on_slopes(app, ui, l.id, *rock, relief(*band, az, alt, zf, sh)); let mut tint = ramp.is_some(); if ui.checkbox(&mut tint, tl!("Tint by elevation")).changed() { let mut p = relief(*band, az, alt, zf, sh); @@ -6970,6 +6971,50 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { transparency_row(app, ui, l); } +/// Shaded Relief's Rock on steep slopes (#1913): a check box and, when it is on, the slopes in +/// degrees the rock colour starts and ends at and the colour. `relief` is the layer's Shaded +/// Relief as `raster.symbology` takes it, to which the rock is added. +fn rock_on_slopes(app: &mut RustGisApp, ui: &mut Ui, layer: u32, rock: Option, relief: Value) { + let send = |app: &mut RustGisApp, rock: Value| { + let mut p = relief.clone(); + p["rock"] = rock; + let _ = app.run("raster.symbology", p); + }; + let mut on = rock.is_some(); + if ui + .checkbox(&mut on, tl!("Rock on steep slopes")) + .on_hover_text(tl!("Tints steep ground toward a rock colour before the light shades it, by the ground's own slope")) + .changed() + { + send(app, if on { json!({}) } else { json!(false) }); + } + let Some(rock) = rock else { return }; + egui::Grid::new(("relief_rock", layer)).num_columns(2).spacing(vec2(10.0, 4.0)).show(ui, |ui| { + for (label, v, which) in [("From", rock.from, 0), ("To", rock.to, 1)] { + let input_label = ui.label(tl!(label)); + let mut x = v; + // Kept across a drag until it is let go (#607). + let drag = Dragged::lend(ui, egui::Id::unique(("relief_rock_drag", layer, which)), &mut x); + let r = ui + .add(egui::DragValue::new(&mut x).update_while_editing(false).range(0.0..=90.0).speed(0.5).max_decimals(1).suffix("°")) + .labelled_by(input_label.id); + if drag.settled(ui, &r, &mut x) && x != v { + // The other end moves along rather than cross it. + let (from, to) = + if which == 0 { (x.min(89.0), rock.to.max(x.min(89.0) + 1.0)) } else { (rock.from.min(x.max(1.0) - 1.0), x.max(1.0)) }; + send(app, json!({"from": from, "to": to})); + } + ui.end_row(); + } + let input_label = ui.label(tl!("Color")); + let mut c = egui::Color32::from_rgb(rock.color.r(), rock.color.g(), rock.color.b()); + if crate::widgets::color_button(ui, &mut c).labelled_by(input_label.id).changed() { + send(app, json!({"color": rustgis_engine::map::Rgba::rgb(c.r(), c.g(), c.b()).hex()})); + } + ui.end_row(); + }); +} + /// The Masking section of a raster's symbology (#348): values drawn as no data, and a range of /// values shown. fn raster_masking(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, d: &rustgis_engine::data::raster::Raster, style: &RasterStyle, t: &Tokens) { diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 54c82b3757..6d1e17637c 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1339,11 +1339,23 @@ to the sun; the more a slope turns toward the fill, the more it gains, up to 0.1 with a fill of 1. Nothing shadows it, and it is drawn at once (nothing to work out). 0, the default, draws the relief as before, and it is saved with the project only when it isn't 0. +**Rock on steep slopes**, on a Shaded Relief layer (`raster.symbology` +`"rock": {"from": 25, "to": 40, "color": "#B2ACA4"}`), tints steep ground toward a rock colour, +so cliffs and scarps stand out from the gentle slopes of the same height. Below **From** degrees +of slope the ramp's colour is kept, above **To** the rock colour is used, and between them the two +are blended on a smooth step. The lights (hillshade, cast shadows, sky visibility and fill light) +then shade that colour as they shade the ramp. The slope is the ground's own, worked out from the +same 3 × 3 window as the hillshade but without the Z factor, so 35° means 35° whatever the +exaggeration (metres at the cell's latitude for a geographic raster). A 30 m DEM averages a cliff +with its foot, so its walls come out gentler than they are: 25° to 40° suits it, and a finer DEM +can start higher. Missing keys keep the current rock's (or those defaults), and `"rock": false` +removes it; it is off by default and saved with the project only when set. + With **Resampling** set to bilinear, a Shaded Relief layer's light (its hillshade, cast shadows, -sky visibility and fill light) 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. +sky visibility and fill light) and its rock tint are 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