Skip to content
Merged
14 changes: 12 additions & 2 deletions crates/engine/examples/held_bench.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Times a large line layer held in longitude/latitude against the same layer held in UTM 32N
//! (#2032 C2): holding it, converting it back for a tool, the first frame, a change of
//! projection, panning and zooming:
//! projection, panning and zooming, and drawing on a map in UTM 32N:
//! `cargo run --release -p rustgis-engine --example held_bench -- [vertices, default 1000000]`.
use rustgis_data::raster::Crs;
use rustgis_data::{Coord, Dataset, Geometry, GeometryType};
Expand Down Expand Up @@ -32,7 +32,7 @@ fn ms(t: Instant) -> f64 {
fn main() -> Result<(), String> {
let vertices: usize = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(1_000_000);
println!("{vertices} vertices; times in ms");
println!("{:<34}{:>12}{:>12}", "", "lon/lat", "UTM 32N");
println!("{:<34}{:>12}{:>12}", "layer held in", "lon/lat", "UTM 32N");
let mut rows: Vec<(&str, [f64; 2])> = Vec::new();
let mut put = |what: &'static str, i: usize, v: f64| match rows.iter_mut().find(|r| r.0 == what) {
Some(r) => r.1[i] = v,
Expand Down Expand Up @@ -75,6 +75,16 @@ fn main() -> Result<(), String> {
let camera = s.map().camera;
put("first frame after projection change", i, frame(&mut s, camera)?);
put("next frame (EPSG:3035)", i, frame(&mut s, camera)?);
// On a map in UTM 32N, the held layer's own system: drawn as it is.
s.run("map.projection", &json!({"type": "epsg:32632"}))?;
s.run("layer.zoomTo", &json!({"layer": "lines"}))?;
let mut camera = s.map().camera;
put("first frame (on a UTM 32N map)", i, frame(&mut s, camera)?);
put("next frame (on a UTM 32N map)", i, frame(&mut s, camera)?);
camera.res /= 4.0;
put("zoom in 4x (on a UTM 32N map)", i, frame(&mut s, camera)?);
// What the map keeps for drawing it there, beside its rows (MB, not ms).
put("drawing copies, MB (UTM 32N map)", i, s.map().layers[0].view_cache_bytes() as f64 / 1e6);
}
for (what, [a, b]) in rows {
println!("{what:<34}{a:>12.1}{b:>12.1}");
Expand Down
42 changes: 14 additions & 28 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,9 @@ pub fn commands() -> Vec<C> {
.params(r#"{"layer"?: name|id | [name|id] (default: the layer selection), "to": position (0 = top; past the end, the bottom). Several keep their order, the topmost landing at "to" as one layer would, and go only to the top or the bottom (one in a group, to its group's): with 4 layers and 2 of them, 2 or more is the bottom, 1 is refused}"#),
C::new("layer.zoomTo", "Zoom To Layer", "Layers", |s, p| {
let ids = layer_ids(s, p)?;
let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.shown_extent()));
if e.is_empty() {
if s.zoom_to_layers(&ids, rustgis_map::ExtentOf::Shown).is_none() {
return Err(if ids.len() > 1 { "the layers have no features" } else { "the layer has no features" }.into());
}
s.zoom_to(&e);
Ok(Value::Null)
}).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"layer"?: name|id | [name|id] (default: the layer selection; zooms to all of them)}"#)
.view()
Expand Down Expand Up @@ -3457,10 +3455,7 @@ fn add_source_read(
}
}
if zoom.unwrap_or(empty_before) {
let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent()));
if !e.is_empty() {
s.zoom_to(&e);
}
s.zoom_to_layers(&ids, rustgis_map::ExtentOf::All);
}
if let Some(note) = attribute_note {
s.notify(format!("{label}: {note}"), false);
Expand Down Expand Up @@ -4259,10 +4254,7 @@ fn add_live(s: &mut Session, p: &Value, db: &rustgis_data::source::duckdb::Datab
return Err(with_left(error, &said));
}
if empty_before {
let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent()));
if !e.is_empty() {
s.zoom_to(&e);
}
s.zoom_to_layers(&ids, rustgis_map::ExtentOf::All);
}
// Empty tables (common in a PostGIS database: its TIGER geocoder's) are left out quietly.
if empty > 0 {
Expand Down Expand Up @@ -4475,10 +4467,7 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: &
s.notify(rustgis_data::source::gdal::in_lonlat_notes(&names), false);
}
if empty_before {
let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent()));
if !e.is_empty() {
s.zoom_to(&e);
}
s.zoom_to_layers(&ids, rustgis_map::ExtentOf::All);
}
if ids.is_empty() {
return Err(format!("{label}: none of its layers could be added"));
Expand Down Expand Up @@ -6839,17 +6828,16 @@ fn added_download(s: &mut Session, p: &Value, mut r: Value, mark_source: bool, u
/// whether the view framed them (not when none had an extent, or the map's projection doesn't
/// reach it).
fn zoom_to_added(s: &mut Session, r: &Value) -> bool {
let ids = r.get("layers").and_then(Value::as_array).into_iter().flatten().chain(r.get("layer"));
let e = ids
let ids: Vec<u32> = r
.get("layers")
.and_then(Value::as_array)
.into_iter()
.flatten()
.chain(r.get("layer"))
.filter_map(Value::as_u64)
.filter_map(|i| u32::try_from(i).ok())
.filter_map(|id| s.map().layer(id).map(|l| l.extent()))
.filter(|e| !e.is_empty())
.fold(rustgis_geom::Extent::EMPTY, |a, e| a.union(&e));
if e.is_empty() {
return false;
}
s.zoom_to(&e)
.collect();
s.zoom_to_layers(&ids, rustgis_map::ExtentOf::All).unwrap_or(false)
}

pub(crate) fn add_data_text(s: &mut Session, p: &Value) -> CmdResult {
Expand Down Expand Up @@ -6907,10 +6895,8 @@ pub(crate) fn add_read(
stand(l, &x);
}
}
if zoom.unwrap_or(empty_before)
&& let Some(e) = s.map().layer(id).map(|l| l.extent())
{
s.zoom_to(&e);
if zoom.unwrap_or(empty_before) {
s.zoom_to_layers(&[id], rustgis_map::ExtentOf::All);
}
Ok(json!({"layer": id, "features": n}))
}
Expand Down
7 changes: 4 additions & 3 deletions crates/engine/src/cmd/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,9 +317,10 @@ pub(crate) fn follow_renamed_map(s: &mut Session, old: &str, new: &str) {
}

fn zoom_full(s: &mut Session, _: &Value) -> CmdResult {
let e = s.map().shown_extent();
let e = if e.is_empty() { Extent::new(-170.0, -58.0, 180.0, 78.0) } else { e };
s.zoom_to(&e);
let ids = s.shown_layer_ids();
if s.zoom_to_layers(&ids, rustgis_map::ExtentOf::Shown).is_none() {
s.zoom_to(&Extent::new(-170.0, -58.0, 180.0, 78.0));
}
Ok(Value::Null)
}

Expand Down
5 changes: 2 additions & 3 deletions crates/engine/src/cmd/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,10 @@ pub fn commands() -> Vec<C> {
}).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"layer"?: name|id (default: the active layer)}"#)
.when(need_layer),
C::new("select.zoomTo", "Zoom To Selection", "Home › Selection", |s, _| {
let e = s.map().selection_extent();
if e.is_empty() {
let ids: Vec<u32> = s.map().layers.iter().filter(|l| !l.selection.is_empty()).map(|l| l.id).collect();
if s.zoom_to_layers(&ids, rustgis_map::ExtentOf::Selected).is_none() {
return Err("nothing with a shape is selected".into());
}
s.zoom_to(&e);
Ok(Value::Null)
}).roles(&[]).effects(crate::policy::Effects::NONE)
.view()
Expand Down
42 changes: 42 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4154,6 +4154,48 @@ impl Session {
true
}

/// Fits the camera to the layers `ids` ([`rustgis_map::ExtentOf`] says which of their
/// features): on a flat map in a coordinate system that holds one of them in its own
/// coordinates ([`rustgis_map::Layer::in_map_units`]), around their places in map coordinates,
/// those layers' exactly as held, with nothing converted; else as [`Session::zoom_to`] does,
/// around their longitude/latitude extent. `None` when they have nothing to zoom to; else
/// whether it did.
pub fn zoom_to_layers(&mut self, ids: &[u32], of: rustgis_map::ExtentOf) -> Option<bool> {
let m = self.map();
let layers: Vec<&rustgis_map::Layer> = ids.iter().filter_map(|id| m.layer(*id)).collect();
// In map coordinates first, where a layer's are its own: its longitude/latitude extent,
// which converts every place, isn't worked out for it then.
if !m.projection.is_globe() {
let flat = m.flat();
if layers.iter().any(|l| l.in_map_units(&flat)) {
let boxed = layers.iter().fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent_on(&flat, of)));
if boxed.is_empty() {
return None;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When every in-map box is empty, this returns None before the longitude/latitude path is tried. Zoom To Layer and Zoom To Selection then report "has no features" or "nothing with a shape is selected" for layers whose other members have places that the map can't draw. Before this change, zoom_to ran and gave the beyond-projection notice. The fix is to fall through to the longitude/latitude path when boxed is empty, and return None only when that path is empty too.

I haven't reproduced this. It needs a set where no in-map layer has geometry and a layer outside the projection's area, so it is narrow.

Category: bug

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 74edf99: when the layers' box on the map is empty (nothing of them on it) or a single point, zoom_to_layers falls through to the longitude/latitude path, which says the map can't show the place. zooming_to_an_empty_layer_in_the_maps_system_and_one_beyond_the_map_says_so covers it (an empty layer held in UTM with a point at 50°E on a UTM 32N map); it fails on the previous head.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
// A single point has no size to fit: framed as one in longitude/latitude is.
if boxed.width() > 0.0 || boxed.height() > 0.0 {
let (w, h) = self.view_size;
if !self.map_mut().fit_map_extent(&boxed, w, h) {
return Some(false);
}
self.record_extent();
return Some(true);
}
}
}
let lonlat = layers.iter().fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent_of(of)));
if lonlat.is_empty() {
return None;
}
Some(self.zoom_to(&lonlat))
}

/// The layers on the active map it shows, by id, top first: what Full Extent zooms to.
pub fn shown_layer_ids(&self) -> Vec<u32> {
let m = self.map();
m.layers.iter().filter(|l| m.shows(l)).map(|l| l.id).collect()
}

pub fn title(&self) -> String {
self.project.name.clone()
}
Expand Down
38 changes: 38 additions & 0 deletions crates/engine/src/tests/held_layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,44 @@ fn a_held_layer_has_the_same_extent_and_zoom() {
assert!((a.x - b.x).abs() < 5.0 && (a.y - b.y).abs() < 5.0, "{a:?} vs {b:?}");
}

/// On a map in a layer's own system, Zoom To Layer, Zoom To Selection and Full Extent frame its
/// features as they are held, in map coordinates, with nothing converted: the view is centred on
/// the middle of their own box exactly (through longitude/latitude it is the centre of the drawn
/// box of their longitude/latitude box, metres away on UTM's turned grid).
#[test]
fn zooming_on_a_map_in_the_layers_system_frames_its_own_box() {
let mut s = session(UTM);
s.view_size = (800.0, 600.0);
s.run("map.projection", &json!({"type": "EPSG:32632"})).unwrap();
let own = |s: &Session, rows: &[usize]| {
let ds = &s.map().layer_by_name("Parcels").unwrap().dataset;
rows.iter().filter_map(|r| ds.features[*r].geometry.as_ref()).fold(rustgis_geom::Extent::EMPTY, |e, g| e.union(&g.extent()))
};
let centred = |s: &Session, e: &rustgis_geom::Extent, what: &str| {
let c = s.map().camera.center;
assert!((c.x - e.center().x).abs() < 1e-6 && (c.y - e.center().y).abs() < 1e-6, "{what}: {c:?} vs {:?}", e.center());
};
s.run("layer.zoomTo", &json!({"layer": "Parcels"})).unwrap();
centred(&s, &own(&s, &(0..9).collect::<Vec<_>>()), "layer");
// The road runs at a slant: the drawn box of its longitude/latitude box is turned against
// UTM's grid and larger than its own, so the way through longitude/latitude centres elsewhere.
s.run("layer.zoomTo", &json!({"layer": "Roads"})).unwrap();
let road = s.map().layer_by_name("Roads").unwrap();
let road_own = road.dataset.extent();
centred(&s, &road_own, "road");
let via = s.map().flat().extent(&road.extent()).center();
assert!((via.x - road_own.center().x).hypot(via.y - road_own.center().y) > 1.0, "{via:?} vs {:?}", road_own.center());
s.run("select.rows", &json!({"layer": "Parcels", "rows": [0, 4]})).unwrap();
s.run("select.zoomTo", &json!({})).unwrap();
centred(&s, &own(&s, &[0, 4]), "selection");
// Full Extent: Wells, Roads and Parcels together, all held in UTM.
s.run("map.zoomFull", &json!({})).unwrap();
let full = ["Wells", "Roads", "Parcels"]
.iter()
.fold(rustgis_geom::Extent::EMPTY, |e, name| e.union(&s.map().layer_by_name(name).unwrap().dataset.extent()));
centred(&s, &full, "full extent");
}

/// Selecting by a box, a point, a radius and a polygon picks the same features.
#[test]
fn a_held_layer_is_selected_alike() {
Expand Down
Loading
Loading