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
1 change: 1 addition & 0 deletions crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,7 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult {
// What the imported maps' block diagrams can't draw their walls, top band or water bed
// from, as when a project opens.
super::project::say_block_layers(s, first_map..s.project.maps.len());
super::raster::say_generalize_out_of_range(s, first_map..s.project.maps.len(), |_| true);
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
super::connections::note_waiting(s);
if let Some(n) = names.last()
&& let Some(i) = s.project.maps.iter().position(|m| &m.name == n)
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4794,6 +4794,8 @@ pub(crate) fn settle_added(s: &mut Session, ids: &[u32]) {
super::connections::restore_active(s);
s.wait_in_place_reads();
super::project::say_conversion_fallbacks(s);
let active = s.project.active_map;
super::raster::say_generalize_out_of_range(s, active..active + 1, |l| ids.contains(&l.id));
// Only the databases the added layers read can change here.
let m = s.map();
let keys: Vec<_> = ids.iter().filter_map(|id| m.layer(*id)?.source.as_ref()).flat_map(super::connections::layer_keys).collect();
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,7 @@ fn reset(s: &mut Session, p: Project) {
super::terrain_blocks::told_uncut(s);
}
say_block_layers(s, 0..s.project.maps.len());
super::raster::say_generalize_out_of_range(s, 0..s.project.maps.len(), |_| true);
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
// Water on a layer read a view at a time (#2305), which `map.terrain` refuses, would come
// from the rows the view holds (the map draws none from it): dropped and said, as the project
// opens.
Expand Down
37 changes: 37 additions & 0 deletions crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1177,6 +1177,43 @@ fn relief_aerial(v: Option<f64>) -> Result<f64, String> {
}
}

/// A Shaded Relief's generalisation outside 0 to [`GENERALIZE_MAX`] in the layers `which` picks of
/// the maps `range` (a file written by hand, #3434 review) set to the nearest `raster.symbology`
/// takes, as it is drawn: past the widest, the widest; below 0 or not a number, none. Said, with
/// the layers, their maps and how many, as a project opens, maps are imported, layer files are
/// added and an offline area's map opens.
pub(crate) fn say_generalize_out_of_range(s: &mut Session, range: std::ops::Range<usize>, which: impl Fn(&rustgis_map::Layer) -> bool) {
let mut set = Vec::new();
for m in s.project.maps.get_mut(range).unwrap_or_default() {
let map = m.name.clone();
for l in m.layers.iter_mut().filter(|l| which(l)) {
let name = l.name.clone();
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
if let Some(RasterRenderer::ShadedRelief { generalize, .. }) = l.raster.as_mut().map(|r| &mut r.style.renderer)
&& !(0.0..=GENERALIZE_MAX).contains(generalize)
{
let to = if *generalize > GENERALIZE_MAX { GENERALIZE_MAX } else { 0.0 };
set.push(format!("{name} in {map} ({generalize} m, now {to} m)"));
*generalize = to;
}
}
}
match set.as_slice() {
[] => {}
[one] => s.notify(
format!("{one}: its Shaded Relief's generalisation was outside 0 to {GENERALIZE_MAX} m, so it is set to the nearest it can be"),
false,
),
_ => s.notify(
format!(
"{} Shaded Reliefs had a generalisation outside 0 to {GENERALIZE_MAX} m, so each is set to the nearest it can be: {}",
set.len(),
set.join(", ")
),
false,
),
}
}

/// A Shaded Relief's `"generalize"` (see `raster.symbology`), `v` being the number of metres given,
/// if it is one: refused by name outside 0 to [`GENERALIZE_MAX`], never brought into it.
pub(crate) fn relief_generalize(v: Option<f64>) -> Result<f64, String> {
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,9 @@ pub fn commands() -> Vec<C> {
}
s.project.maps.push(m);
s.project.active_map = s.project.maps.len() - 1;
// Nor their generalisations out of range (#3145), which are set and said here.
let opened = s.project.active_map;
super::raster::say_generalize_out_of_range(s, opened..opened + 1, |_| true);
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
}
s.active_layer = s.map().layers.first().map(|l| l.id);
s.zoom_to(&extent);
Expand Down
107 changes: 107 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8231,6 +8231,89 @@ fn shaded_relief_keeps_its_generalisation() {
assert!(text.contains(r#""generalize":120.0"#) && text.contains("shaded-relief-generalize"), "{text}");
}

/// A Shaded Relief's generalisation outside 0 to 10 km in a file (written by hand) is set to the
/// nearest the command takes, past 10 km to 10 km and below 0 to none, as the project opens, as
/// maps are imported and as a layer file is added, and said with how many (#3434 review). One
/// inside the range is left as it is, unsaid.
#[test]
fn a_generalisation_out_of_range_in_a_file_is_set_within_it_and_said() {
use rustgis_map::RasterRenderer;
let text = include_str!("../../../schema/fixtures/shaded_relief_generalize.rgis");
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let generalize = |l: &rustgis_map::Layer| match l.raster.as_ref().map(|r| &r.style.renderer) {
Some(RasterRenderer::ShadedRelief { generalize, .. }) => *generalize,
other => panic!("{other:?}"),
};
let mut p = Project::from_json(text).unwrap();
let mut second = p.maps[0].layers[0].clone();
(second.id, second.name) = (2, "dem2".into());
p.maps[0].layers.push(second);
let said = |s: &Session| s.notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("generalisation")).collect::<Vec<_>>();
// In range, nothing.
let mut quiet = Session::new(Project::default());
crate::cmd::project::reset_to(&mut quiet, p.clone());
assert!(said(&quiet).is_empty(), "{:?}", said(&quiet));
// Opened from a file holding 1e20 and -5, as written by hand.
let p = Project::from_json(include_str!("../../../schema/fixtures/shaded_relief_generalize_out_of_range.rgis")).unwrap();
let mut s = Session::new(Project::default());
crate::cmd::project::reset_to(&mut s, p.clone());
let layers = &s.project.maps[0].layers;
assert_eq!((generalize(&layers[0]), generalize(&layers[1])), (10_000.0, 0.0));
let notes = said(&s);
// Each layer with its map, the file's values and what they are now.
let one = |name: &str, map: &str, was: &str, now: &str| format!("{name} in {map} ({was} m, now {now} m)");
assert!(
notes.len() == 1
&& notes[0].starts_with("2 Shaded Reliefs")
&& notes[0].contains(&one("dem", "Map", "100000000000000000000", "10000"))
&& notes[0].contains(&one("dem2", "Map", "-5", "0")),
"{notes:?}"
);
// A style file takes no raster's style, so none reaches a layer from it (#3443 review).
let e = s.run("style.import", &json!({"text": include_str!("../../../schema/fixtures/shaded_relief_generalize_out_of_range.rgis")}));
assert!(e.is_err_and(|e| e.to_string().contains("no feature layers")), "rasters' styles aren't imported");
// An offline area's snapshot, which a project's read doesn't check, is set and said as its map
// opens (#3443 review).
let mut snapshot = p.maps[0].clone();
snapshot.layers.truncate(1);
s.project.offline_areas.push(crate::project::OfflineArea {
id: String::new(),
name: "Field".into(),
map: "Map".into(),
extent: rustgis_geom::Extent::new(10.0, 45.0, 11.0, 46.0),
created: 0.0,
synced: 0.0,
generation: String::new(),
returned: Vec::new(),
ids: Default::default(),
conflicts: Default::default(),
data: snapshot,
});
let mark = s.notice_mark();
s.run("offline.open", &json!({"name": "Field"})).unwrap();
let notes: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("generalisation")).collect();
assert!(notes.len() == 1 && notes[0].starts_with(&one("dem", &s.map().name, "100000000000000000000", "10000")), "{notes:?}");
assert_eq!(generalize(&s.map().layers[0]), 10_000.0);
// Imported in a map: said again for that map.
let mut map = p.maps[0].clone();
map.name = "Imported".into();
map.layers.truncate(1);
let mark = s.notice_mark();
s.run("map.import", &json!({"text": serde_json::to_string(&map).unwrap()})).unwrap();
let notes: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("generalisation")).collect();
assert_eq!(notes.len(), 1, "{notes:?}");
let imported = s.project.maps.iter().find(|m| m.name == "Imported").unwrap();
assert_eq!(generalize(&imported.layers[0]), 10_000.0);
// A layer file added.
let mut layer = p.maps[0].layers[1].clone();
layer.name = "dem3".into();
let file = String::from_utf8(crate::project::layer_file_bytes(&layer).unwrap()).unwrap();
let mark = s.notice_mark();
s.run("layer.addLayerFile", &json!({"text": file})).unwrap();
let notes: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("generalisation")).collect();
assert!(notes.len() == 1 && notes[0].contains("dem3"), "{notes:?}");
assert_eq!(s.map().layers.iter().find(|l| l.name == "dem3").map(generalize), Some(0.0));
}

/// 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 Expand Up @@ -35739,6 +35822,30 @@ fn flat_ground_detail_read_in_place_has_no_step_at_the_views_edges() {
let _ = std::fs::remove_file(&tif);
}

/// A generalised relief (#3145) whose reach past the view is more than the tiles kept can read at
/// the level the view needs is read there with as much of its reach as fits, rather than from a
/// coarser level, and says so by its generalisation, not as a view too large (#3434 review). One
/// whose reach fits draws as before.
#[test]
fn a_generalisation_reaching_past_what_fits_is_cut_at_the_level_needed_and_said() {
use rustgis_data::raster::cog::{Example, example_with};
let (base, _) = serve_ranges(example_with(&Example { size: 4096, tile: 256, bands: 3, ..Example::default() }));
let mut s = Session::new(Project::default());
s.run("layer.addUrl", &json!({"url": format!("{base}/scene.tif")})).unwrap();
s.map_mut().camera.center = rustgis_geom::lonlat_to_merc(rustgis_geom::Coord::new(10.5, 45.5));
s.map_mut().camera.res = 25.0;
s.view_size = (768.0, 768.0);
let png = std::env::temp_dir().join(format!("rustgis-generalize-cut-{}.png", std::process::id()));
let export = |s: &mut Session, metres: f64| {
s.run("raster.symbology", &json!({"type": "shadedRelief", "generalize": metres})).unwrap();
s.run("share.exportMap", &json!({"path": png.to_string_lossy(), "width": 768, "height": 768}))
};
assert!(export(&mut s, 1000.0).is_ok());
let e = export(&mut s, 10_000.0).unwrap_err().to_string();
assert!(e.contains("generalisation") && !e.contains("too large a part"), "{e}");
let _ = std::fs::remove_file(&png);
}

/// A generalised relief (#3145) read in place smooths the cells past the part in view too: a
/// small view's pixels are the middle of a view twice as large, with no step at its edges.
#[test]
Expand Down
46 changes: 34 additions & 12 deletions crates/render/src/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ pub(crate) fn draw(
const WINDOW_GRID: usize = 17;
/// Why a part in view was drawn from a coarser level than it needs.
const TOO_LARGE: &str = "the view is too large a part of the image to read at the resolution it needs";
/// Why a generalised relief's part in view was read with less of its reach than it smooths.
const GENERALISE_CUT: &str = "its generalisation reaches farther past the view than can be read at the resolution it needs, so \
near the view's edges it is smoothed from fewer cells: a smaller generalisation or a smaller view draws it whole";
/// Why a turned layer is drawn from its overview.
const TURNED: &str = "turned, it is drawn from its overview, not at the resolution the view needs";

Expand Down Expand Up @@ -232,32 +235,50 @@ pub(crate) fn draw_in_place(
// A pixel past each side for bilinear sampling, or the cells flat ground's detail averages
// (#3143), or a generalised relief smooths (#3145), so the part's edge is drawn as the whole
// image's.
let least = match style.renderer {
RasterRenderer::ShadedRelief { flats: Some(f), .. } if f.amount > 0.0 => f.size.min(Flats::MAX_SIZE) + 1,
_ => 1,
};
let pad = |l: &rustgis_data::raster::cog::Level| {
let flats = match style.renderer {
RasterRenderer::ShadedRelief { flats: Some(f), .. } if f.amount > 0.0 => f.size.min(Flats::MAX_SIZE) + 1,
_ => 1,
};
let Some(generalize) = generalisation(&style.renderer) else { return flats };
let Some(generalize) = generalisation(&style.renderer) else { return least };
let scale = (f64::from(r.width) / f64::from(l.width.max(1)), f64::from(r.height) / f64::from(l.height.max(1)));
let sy = generalise_sigma(generalize, r, scale, 0.0).1;
// Along the rows, at the rows nearest a pole the part reaches, as the smoothing reads them.
let sx = |row: f64| generalise_sigma(generalize, r, scale, row.clamp(0.0, f64::from(r.height))).0;
let past = generalised_reach(sx(want.rows.0).max(sx(want.rows.1)), sy).1 as f64 * scale.1;
let (reach_x, reach_y) = generalised_reach(sx(want.rows.0 - past).max(sx(want.rows.1 + past)), sy);
flats.max(u32::try_from(reach_x.max(reach_y)).unwrap_or(u32::MAX))
least.max(u32::try_from(reach_x.max(reach_y)).unwrap_or(u32::MAX))
};
let mut window = None;
let (mut window, mut cut) = (None, false);
while let Some(l) = levels.get(level) {
let pad = pad(l);
// The part in view, in the level's pixels, `pad` past each side.
// The part in view, in the level's pixels, `pad` past each side, when it fits.
let (sx, sy) = (f64::from(l.width) / f64::from(r.width.max(1)), f64::from(l.height) / f64::from(r.height.max(1)));
let edge = |v: f64, k: f64, max: u32| ((v * k).floor() as i64).clamp(0, i64::from(max)) as u32;
let cols: Vec<(u32, u32)> = strips.iter().map(|c| padded((edge(c.0, sx, l.width), edge(c.1, sx, l.width)), pad, l.width)).collect();
let rows = padded((edge(want.rows.0, sy, l.height), edge(want.rows.1, sy, l.height)), pad, l.height);
if cols.iter().all(|cols| rustgis_tiles::cog::raster::fits(address, level, *cols, rows, &read)) {
let part = |pad: u32| {
let cols: Vec<(u32, u32)> =
strips.iter().map(|c| padded((edge(c.0, sx, l.width), edge(c.1, sx, l.width)), pad, l.width)).collect();
let rows = padded((edge(want.rows.0, sy, l.height), edge(want.rows.1, sy, l.height)), pad, l.height);
cols.iter().all(|cols| rustgis_tiles::cog::raster::fits(address, level, *cols, rows, &read)).then_some((cols, rows))
};
let full = pad(l);
if let Some((cols, rows)) = part(full) {
window = Some((level, cols, rows));
break;
}
// A generalisation reaching farther past the view than the tiles kept hold at the level
// the view needs (#3145) is read there with as much of its reach as fits, the most that
// does, rather than the view from a coarser level: said.
if level == needed && full > least && part(least).is_some() {
let (mut fits, mut over) = (least, full);
while over - fits > 1 {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let mid = fits + (over - fits) / 2;
if part(mid).is_some() { fits = mid } else { over = mid }
}
if let Some((cols, rows)) = part(fits) {
(window, cut) = (Some((level, cols, rows)), true);
break;
}
}
// Too large a part for the tiles kept (a view far wider than the screen, a file of many
// bands stored together): a coarser level.
level += 1;
Expand Down Expand Up @@ -332,6 +353,7 @@ pub(crate) fn draw_in_place(
// Read coarser than the view needs (too large a part for the tiles kept): the map shows
// it, an export refuses it.
(false, false) if level > needed => Err(TOO_LARGE.into()),
(false, false) if cut => Err(GENERALISE_CUT.into()),
(false, false) => Ok(false),
}
}
Expand Down
1 change: 1 addition & 0 deletions schema/fixtures/shaded_relief_generalize_out_of_range.rgis
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"requires":["shaded-relief-generalize"],"format":2,"name":"Shaded relief generalised out of range","maps":[{"name":"Map","layers":[{"id":1,"name":"dem","visible":true,"dataset":{"name":"dem","geometry_type":"None","fields":[],"features":[],"source":null},"renderer":{"Single":{"fill":[224,123,57,170],"stroke":[134,74,34,255],"stroke_width":0.7,"size":0.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"","size":10.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto"},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":false,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"raster":{"path":"dem.tif","file_name":null,"style":{"renderer":{"ShadedRelief":{"band":0,"ramp":"Terrain","azimuth":315.0,"altitude":45.0,"z_factor":2.0,"generalize":1e+20}},"stretch":{"PercentClip":{"low":0.5,"high":0.5}},"dra":false,"resampling":"Nearest","brightness":0.0,"contrast":0.0,"gamma":1.0,"rotation":0.0}},"geometry_rev":0},{"id":2,"name":"dem2","visible":true,"dataset":{"name":"dem","geometry_type":"None","fields":[],"features":[],"source":null},"renderer":{"Single":{"fill":[224,123,57,170],"stroke":[134,74,34,255],"stroke_width":0.7,"size":0.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"","size":10.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto"},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":false,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"raster":{"path":"dem.tif","file_name":null,"style":{"renderer":{"ShadedRelief":{"band":0,"ramp":"Terrain","azimuth":315.0,"altitude":45.0,"z_factor":2.0,"generalize":-5.0}},"stretch":{"PercentClip":{"low":0.5,"high":0.5}},"dra":false,"resampling":"Nearest","brightness":0.0,"contrast":0.0,"gamma":1.0,"rotation":0.0}},"geometry_rev":0}],"basemap":"Paper","camera":{"center":{"x":-4654314.293187932,"y":-2329385.2820357964},"res":64.69445270508425,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":2}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]}
Loading