Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 35 additions & 6 deletions crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -36,7 +36,7 @@ pub fn commands() -> Vec<C> {
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)
Expand Down Expand Up @@ -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,
Expand All @@ -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") {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
None => cur_rock,
Some(v) => relief_rock(v, cur_rock)?,
},
}
}
other => return Err(format!("unknown raster symbology '{other}'")),
Expand All @@ -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<Rock>) -> Result<Option<Rock>, 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()) {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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;

Expand Down
61 changes: 61 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f32> = (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.
Expand Down
1 change: 1 addition & 0 deletions crates/map/src/qgis/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
3 changes: 2 additions & 1 deletion crates/map/src/qgis/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")));
Expand Down
Loading
Loading