Skip to content
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ raster.rotation layer? angle
raster.setDefaultStyle fromLayer? layer? ramp? invert? stretch? low? high? n? resampling? reset?
raster.spectral layer lon? lat? points? zone?
raster.stretch layer? type low? high? n? min? max? like?
raster.symbology layer? type band? ramp? invert? classes? method? azimuth? altitude? zFactor? shadow? sky? fill? ambient? balanced? rock? grey?
raster.symbology layer? type band? ramp? invert? classes? method? azimuth? altitude? zFactor? shadow? sky? fill? ambient? balanced? shadowSoftness? rock? grey?
raster.zarrInfo path url bbox? variable?
report.activate report
report.attachments report? field
Expand Down
32 changes: 25 additions & 7 deletions crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub fn commands() -> Vec<C> {
C::new("layer.addDataBytes", "Add Data (from file contents)", "Home › Add", add_bytes::<MAX_UPLOAD_BYTES>).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"fileName": "name.tif|.tiff|.asc|.grb|.grib|.grb2|.grib2 (GRIB)|.hgt|.dt0|.dt1|.dt2|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "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), "ambient"?: 0..1|null (shadedRelief: the share of the colour a slope turned fully from the sun keeps; left out, kept; null, the default: 0.25, or 0.5 balanced), "balanced"?: bool (shadedRelief: flat ground keeps the ramp's colour and slopes facing the sun brighten, up to 1.3; left out, kept; false, the default, lights as before), "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)}"#,
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), "ambient"?: 0..1|null (shadedRelief: the share of the colour a slope turned fully from the sun keeps; left out, kept; null, the default: 0.25, or 0.5 balanced), "balanced"?: bool (shadedRelief: flat ground keeps the ramp's colour and slopes facing the sun brighten, up to 1.3; left out, kept; false, the default, lights as before), "shadowSoftness"?: 0.5..15|null (shadedRelief: how soft the edges of its cast shadows are, as half the sun's apparent size in degrees; left out, kept; outside 0.5 to 15, refused; null, the default: 5), "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 @@ -1034,13 +1034,13 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult {
RasterRenderer::Colormap
}
"shadedrelief" | "hillshade" => {
// Left out, a Shaded Relief keeps its own shadows, sky, fill light, rock, ambient
// and balanced light; a new one has none (and the default ambient).
let (cur_shadow, cur_sky, cur_fill, cur_rock, cur_ambient, cur_balanced) = match rl.style.renderer {
RasterRenderer::ShadedRelief { shadow, sky, fill, rock, ambient, balanced, .. } => {
(shadow, sky, fill, rock, ambient, balanced)
// Left out, a Shaded Relief keeps its own shadows (and their softness), sky, fill
// light, rock, ambient and balanced light; a new one has none (and the defaults).
let (cur_shadow, cur_sky, cur_fill, cur_rock, cur_ambient, cur_balanced, cur_softness) = match rl.style.renderer {
RasterRenderer::ShadedRelief { shadow, sky, fill, rock, ambient, balanced, shadow_softness, .. } => {
(shadow, sky, fill, rock, ambient, balanced, shadow_softness)
}
_ => (0.0, 0.0, 0.0, None, None, false),
_ => (0.0, 0.0, 0.0, None, None, false, None),
};
RasterRenderer::ShadedRelief {
band: bi,
Expand All @@ -1062,6 +1062,11 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult {
Some(_) => Some(f(p, "ambient").ok_or("\"ambient\" must be a number from 0 to 1, or null")?.clamp(0.0, 1.0)),
},
balanced: b(p, "balanced").unwrap_or(cur_balanced),
shadow_softness: match p.get("shadowSoftness") {
None => cur_softness,
Some(Value::Null) => None,
Some(_) => relief_shadow_softness(f(p, "shadowSoftness"))?,
},
}
}
other => return Err(format!("unknown raster symbology '{other}'")),
Expand All @@ -1075,6 +1080,19 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult {
})
}

/// A Shaded Relief's `"shadowSoftness"` (see `raster.symbology`), `v` being the number given, if
/// it is one: refused by name outside the range, never brought into it. The default's own value
/// is kept as none, so a project that sets nothing new saves as it did.
fn relief_shadow_softness(v: Option<f64>) -> Result<Option<f64>, String> {
use rustgis_map::shadow::{SOFT_EDGE, SOFT_EDGE_MAX, SOFT_EDGE_MIN};
match v {
Some(v) if (SOFT_EDGE_MIN..=SOFT_EDGE_MAX).contains(&v) => Ok(Some(v).filter(|v| *v != SOFT_EDGE)),
_ => Err(format!(
"\"shadowSoftness\" must be a number of degrees from {SOFT_EDGE_MIN} to {SOFT_EDGE_MAX}, or null for the default ({SOFT_EDGE})"
)),
}
}

/// 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> {
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ pub const CAPABILITIES: &[&str] = &[
"layout-text-statistics",
"layout-publication-parts",
"layout-publication-legend",
"shaded-relief-shadow-softness",
];
/// An offline area keeping the versions that lost a sync or a Bring Back
/// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them.
Expand Down
37 changes: 34 additions & 3 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("layout-text-statistics", command_uses_text_statistics),
("layout-publication-parts", command_sets_publication_parts),
("layout-publication-legend", command_sets_publication_legend),
("shaded-relief-shadow-softness", command_sets_shadow_softness),
];

/// A saved `layout.publication` that leaves out or sets up its grid, scale bar or north arrow
Expand Down Expand Up @@ -213,6 +214,17 @@ fn command_sets_publication_legend(id: &str, params: &Value) -> bool {
}
}

/// A saved `raster.symbology` that sets a Shaded Relief's shadow softness (#3144): an older reader
/// runs it without the key, saying nothing, so the shadows would be traced at the default disc.
/// `null` asks for that default.
fn command_sets_shadow_softness(id: &str, params: &Value) -> bool {
match id {
"raster.symbology" => params.get("shadowSoftness").is_some_and(|v| !v.is_null()),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_shadow_softness)),
_ => false,
}
}

/// A saved `labels.placement` that has a class remove duplicates, read as the command reads it
/// (#2847): an older reader runs it without the key, saying nothing, so every label would show.
/// False or null is what an older reader keeps.
Expand Down Expand Up @@ -953,6 +965,15 @@ fn relief_light(layer: &Layer) -> bool {
)
}

/// Whether a layer sets how soft its Shaded Relief's cast shadows are (#3144): an older reader
/// would trace them at the default and save the layer again without the setting.
fn sets_shadow_softness(layer: &Layer) -> bool {
layer
.raster
.as_ref()
.is_some_and(|r| matches!(&r.style.renderer, RasterRenderer::ShadedRelief { shadow_softness, .. } if shadow_softness.is_some()))
}

/// Whether a layer is a window of a Zarr variable following the time slider (#1720): an older
/// reader would drop the window and read the whole map at each step.
fn zarr_window(layer: &Layer) -> bool {
Expand Down Expand Up @@ -995,6 +1016,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> {
[
(relief_effects(layer), "shaded-relief-effects"),
(relief_light(layer), "shaded-relief-light"),
(sets_shadow_softness(layer), "shaded-relief-shadow-softness"),
(layer.size_by.is_some(), super::SIZE_BY_CAPABILITY),
(layer.has_picture_markers(), "picture-markers"),
(layer.any_picture(svg_picture), "svg-markers"),
Expand Down Expand Up @@ -1031,7 +1053,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
let (mut polygon, mut svg) = (false, false);
let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) =
(false, false, false, false, false, false, false);
let (mut crisp, mut bed) = (false, false);
let (mut crisp, mut bed, mut soft) = (false, false, false);
for map in maps {
offline_area_id |= map.offline_area_id.is_some();
// A blank basemap's paper colour (#2532), which an older reader would draw and save white.
Expand Down Expand Up @@ -1066,6 +1088,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
}
relief |= map.layers.iter().any(relief_effects);
light |= map.layers.iter().any(relief_light);
soft |= map.layers.iter().any(sets_shadow_softness);
sized |= map.layers.iter().any(|layer| layer.size_by.is_some());
pictures |= map.layers.iter().any(Layer::has_picture_markers);
svg |= map.layers.iter().any(|layer| layer.any_picture(svg_picture));
Expand All @@ -1086,6 +1109,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
(walls_layer, "terrain-block-walls-layer"),
(relief, "shaded-relief-effects"),
(light, "shaded-relief-light"),
(soft, "shaded-relief-shadow-softness"),
(legends, "normalized-legend-urls"),
(sized, super::SIZE_BY_CAPABILITY),
(pictures, "picture-markers"),
Expand Down Expand Up @@ -1548,6 +1572,9 @@ mod tests {
(&["layout-text-statistics"], "layout.addElement", json!({"kind": "text", "text": "{count:Cities}"})),
(&["layout-publication-parts"], "layout.publication", json!({"grid": "none"})),
(&["layout-publication-legend"], "layout.publication", json!({"legend": "none"})),
(&["shaded-relief-shadow-softness"], "raster.symbology", json!({"type": "shadedRelief", "shadowSoftness": 1.5})),
// `null` is the default an older reader draws.
(&[], "raster.symbology", json!({"type": "shadedRelief", "shadowSoftness": null})),
// An SVG image is a picture marker as well, in a node as in a saved command.
(&["picture-markers", "svg-markers"], "layer.marker", json!({"image": svg})),
(&[], "buffer", json!({"input": "Cities", "distance": 1})),
Expand Down Expand Up @@ -3167,7 +3194,7 @@ mod tests {
}))
.unwrap();
let clean = Layer::new_raster(1, "DEM", raster);
for field in ["shadow", "sky", "fill", "rock", "ambient", "balanced"] {
for field in ["shadow", "sky", "fill", "rock", "ambient", "balanced", "shadow_softness"] {
let mut value = serde_json::to_value(&clean).unwrap();
value["raster"]["style"]["renderer"]["ShadedRelief"][field] = match field {
"rock" => serde_json::to_value(rustgis_map::raster::Rock::DEFAULT).unwrap(),
Expand All @@ -3182,7 +3209,11 @@ mod tests {
json_bytes(&map_file_bytes(p.map()).unwrap()),
json_bytes(&layer_file_bytes(&layer).unwrap()),
] {
let needs = if matches!(field, "ambient" | "balanced") { "shaded-relief-light" } else { "shaded-relief-effects" };
let needs = match field {
"ambient" | "balanced" => "shaded-relief-light",
"shadow_softness" => "shaded-relief-shadow-softness",
_ => "shaded-relief-effects",
};
assert_eq!(document["requires"], json!([needs]), "{field}: {document}");
}
}
Expand Down
52 changes: 52 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7804,6 +7804,58 @@ fn shaded_relief_keeps_its_ambient_and_balanced_light() {
assert_eq!(light(&t), (Some(0.35), true), "back when opened");
}

/// Shaded Relief's shadow softness (#3144) is set, kept when left out, refused by name outside its
/// range (never brought into it), saved only when set, and back when the project is opened again;
/// null, or the default's own value, is the default again, which saves nothing new.
#[test]
fn shaded_relief_keeps_its_shadow_softness() {
let mut s = with_raster();
let softness = |s: &Session| match s.map().layers.iter().find_map(|l| l.raster.as_ref()).map(|r| &r.style.renderer) {
Some(rustgis_map::RasterRenderer::ShadedRelief { shadow_softness, .. }) => *shadow_softness,
other => panic!("{other:?}"),
};
let saved = |s: &mut Session| s.project.saved_text(None).unwrap().0;
s.run("raster.symbology", &json!({"type": "shadedRelief", "shadow": 0.8})).unwrap();
assert_eq!(softness(&s), None);
assert!(!saved(&mut s).contains("shadow_softness") && !saved(&mut s).contains("shaded-relief-shadow-softness"));
s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": 1.5})).unwrap();
s.run("raster.symbology", &json!({"type": "shadedRelief", "azimuth": 200})).unwrap();
assert_eq!(softness(&s), Some(1.5), "left out, kept");
for refused in [json!(0.4), json!(15.5), json!(-1), json!("soft"), json!(true)] {
let e = s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": refused})).unwrap_err();
assert!(e.contains("\"shadowSoftness\"") && e.contains("0.5 to 15"), "{refused}: {e}");
assert_eq!(softness(&s), Some(1.5), "{refused}: refused, nothing changed");
}
for bound in [0.5, 15.0] {
s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": bound})).unwrap();
assert_eq!(softness(&s), Some(bound));
}
let text = saved(&mut s);
assert!(text.contains("\"shadow_softness\":15.0") && text.contains("shaded-relief-shadow-softness"), "saved, and required by name");
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
let dir = std::env::temp_dir().join(format!("rustgis-softness-{}-{nanos}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("softness.rgis");
s.run("project.saveAs", &json!({"path": path.display().to_string()})).unwrap();
let mut t = Session::new(Project::default());
t.run("project.open", &json!({"path": path.display().to_string()})).unwrap();
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(softness(&t), Some(15.0), "back when opened");
for default in [json!(null), json!(5)] {
s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": 2})).unwrap();
s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": default})).unwrap();
assert_eq!(softness(&s), None, "{default}: the default");
}
s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": 2})).unwrap();
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(softness(&s), None, "undone");
assert!(!saved(&mut s).contains("shadow_softness"), "the default saves nothing new");
// The fixture reads back as saved, requiring what it sets by name.
let fixture = Project::from_json(include_str!("../../../schema/fixtures/shaded_relief_shadow_softness.rgis")).unwrap();
assert_eq!(softness(&Session::new(fixture.clone())), Some(1.5));
assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["shaded-relief-effects", "shaded-relief-shadow-softness"]));
}

/// 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.
Expand Down
1 change: 1 addition & 0 deletions crates/map/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,7 @@ fn a_balanced_reliefs_colour_bar_is_its_flat_ground() {
rock: None,
ambient: None,
balanced,
shadow_softness: None,
};
let Some(ColorScale::Ramp { lo, hi, colors }) = color_scale(&rl) else { panic!("a ramp") };
let colorizer = Colorizer::new(&rl.style, &r, None);
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 @@ -100,6 +100,7 @@ fn renderer_style(node: Node, pipe: Node, r: Node, kind: &str, layer: &str, repo
rock: None,
ambient: None,
balanced: false,
shadow_softness: None,
};
(renderer, Stretch::None)
}
Expand Down
1 change: 1 addition & 0 deletions crates/map/src/qgis/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,7 @@ fn raster_renderers_read_as_rustgis_raster_styles() {
rock: None,
ambient: None,
balanced: false,
shadow_softness: None,
}
);
assert!(report.notes.iter().any(|n| n.text.contains("saturation")));
Expand Down
Loading
Loading