From 1591f234dd2290e44f7742085170e5e0ac10e756 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 19:36:18 +0100 Subject: [PATCH] feat(crs): held layers tested on the remaining commands; whole-layer conversions stop on Cancel; undrawable places counted as the map draws (#2032 C2b) --- crates/data/src/io.rs | 2 +- crates/data/src/lib.rs | 150 ++++++++++--- crates/data/src/progress.rs | 12 +- crates/data/src/publish.rs | 5 +- crates/engine/examples/held_bench.rs | 83 +++++++ crates/engine/src/cmd/exports.rs | 47 +++- crates/engine/src/cmd/workspace.rs | 15 +- crates/engine/src/lib.rs | 16 +- crates/engine/src/tests/held_layers.rs | 292 +++++++++++++++++++++++-- crates/map/src/lib.rs | 147 +++++++++++-- crates/map/src/look.rs | 3 + crates/plugins/src/tools.rs | 38 ++++ crates/render/src/block.rs | 21 ++ crates/render/src/lib.rs | 148 ++++++++++++- crates/render/src/terrain.rs | 6 + crates/render/src/terrain/water.rs | 25 +++ 16 files changed, 924 insertions(+), 86 deletions(-) create mode 100644 crates/engine/examples/held_bench.rs diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index b50e1fd0b7..0eedeccec8 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -4333,7 +4333,7 @@ pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, t Ok(match ext { "csv" => { // Of the longitude/latitude the file is written in. - let ds = ds.in_lonlat().map_err(DataError::Format)?; + let ds = ds.in_lonlat().map_err(DataError::of_conversion)?; let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?; let mut notes = losses.notes(&ds.fields, target); notes.extend(losses.coordinates_note(&ds.fields, target)); diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 36da5cf754..e8299ef729 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -110,6 +110,14 @@ pub enum DataError { pub type Result = std::result::Result; +impl DataError { + /// A coordinate conversion's error ([`Dataset::in_lonlat`], [`Dataset::hold_in`], …, which + /// say it in words): [`DataError::Cancelled`] when it stopped for Cancel, else a format error. + pub fn of_conversion(e: String) -> Self { + if e == DataError::Cancelled.to_string() { DataError::Cancelled } else { DataError::Format(e) } + } +} + /// An I/O error, or [`DataError::Cancelled`] when it carries one: a write that only returns I/O /// errors stops with it for a cancelled run ([`progress`]). impl From for DataError { @@ -448,8 +456,8 @@ impl Dataset { /// Drawing converts geometry from it ([`raster::Crs::to`]), so a dataset that keeps the /// coordinates it was read in can say so here without the map changing. Longitude/latitude /// never fails to convert, and [`Dataset::hold_in`] only holds a dataset where every place - /// converts. A place that can't be converted isn't drawn, and the session says so - /// ([`Dataset::unplaced_in_lonlat`]). + /// converts. A place that can't be converted isn't drawn, and the session says so (the map + /// counts them as it draws, `Layer::unplaced`). pub fn coord_crs(&self) -> raster::Crs { self.held_in } @@ -466,8 +474,11 @@ impl Dataset { let to = self.held_in.to(crs)?; if !to.is_identity() { let lonlat = self.lonlat_conversion()?; + // Before the rows are copied (by the first change), which a cancelled command needn't. + stop_when_asked(0)?; let mut features = self.features.clone(); - for f in &mut features { + for (i, f) in features.iter_mut().enumerate() { + stop_when_asked(i)?; if let Some(g) = &f.geometry { let mut past = false; if crs == raster::Crs::WebMercator { @@ -978,30 +989,6 @@ impl Dataset { } } - /// How many of its features have a place that can't be given in longitude/latitude, which - /// the map, the globe and the drawings made from either leave out: none while its coordinates - /// are longitude/latitude, as every dataset's are today. Refused, naming its system, when the - /// system can't be converted at all (then none of it is drawn). It reads every place through - /// the conversion, on the calling thread, with no Cancel: as long as converting the layer - /// takes. - pub fn unplaced_in_lonlat(&self) -> std::result::Result { - let to = self.lonlat_conversion()?; - if to.is_identity() { - return Ok(0); - } - // Counted, not converted: a place that isn't a number is kept, as a conversion keeps it. - let unplaced = |g: &Geometry| { - let lost = std::cell::Cell::new(false); - g.for_each_coord(|c| { - if !lost.get() && c.is_finite() && to.point(c).is_none() { - lost.set(true); - } - }); - lost.get() - }; - Ok(self.features.rows().filter_map(|r| r.geometry()).filter(|g| unplaced(g)).count()) - } - /// The dataset in longitude/latitude, the space analysis tools work in: borrowed while its /// coordinates are longitude/latitude ([`Dataset::coord_crs`]), as every dataset's are today; /// otherwise a copy with every geometry converted, missing coordinates kept. Refused, naming @@ -1012,9 +999,11 @@ impl Dataset { if to.is_identity() { return Ok(Cow::Borrowed(self)); } + stop_when_asked(0)?; let mut out = self.clone(); out.held_in = raster::Crs::LonLat; - for f in &mut out.features { + for (i, f) in out.features.iter_mut().enumerate() { + stop_when_asked(i)?; if let Some(g) = &mut f.geometry { *g = convert_keeping_missing(&to, g, &HeldPlaces::default()).ok_or_else(|| { format!( @@ -1056,12 +1045,16 @@ impl Dataset { let mut held = HeldPlaces::default(); let edits: Vec<&Geometry> = results.features.rows().filter_map(|r| r.geometry()).collect(); if !edits.is_empty() { - held.want_only(&edits); - for g in self.features.rows().filter_map(|r| r.geometry()) { + held.want_only_checking(&edits, stop_when_asked)?; + for (i, g) in self.features.rows().filter_map(|r| r.geometry()).enumerate() { + stop_when_asked(i)?; self.hold_places(g, None, &mut held); } } - for f in &mut results.features { + // Before the rows are copied out of what shares them. + stop_when_asked(0)?; + for (i, f) in results.features.iter_mut().enumerate() { + stop_when_asked(i)?; if let Some(g) = f.geometry.take() { f.geometry = Some(self.edit_from_lonlat(g, &held).map_err(|e| format!("{}: feature {}: {e}", self.name, f.id))?); } @@ -1093,12 +1086,16 @@ impl Dataset { // edits would bound. let mut held = HeldPlaces::default(); if !edits.is_empty() { - held.want_only(&edits); - for g in self.features.iter().filter_map(|f| f.geometry.as_ref()) { + held.want_only_checking(&edits, stop_when_asked)?; + for (i, g) in self.features.iter().filter_map(|f| f.geometry.as_ref()).enumerate() { + stop_when_asked(i)?; self.hold_places(g, None, &mut held); } } - for f in &mut merged.features { + // Before the rows are copied out of what shares them. + stop_when_asked(0)?; + for (i, f) in merged.features.iter_mut().enumerate() { + stop_when_asked(i)?; if is_changed(f.id) { if let Some(g) = f.geometry.take() { f.geometry = Some(self.edit_from_lonlat(g, &held).map_err(|e| format!("{}: feature {}: {e}", self.name, f.id))?); @@ -1218,8 +1215,19 @@ impl HeldPlaces { /// From now on, holds only places that one of `edited`'s (in longitude/latitude) reads as and /// that isn't held yet: a search of many stored places keeps only those an edit asks for. pub fn want_only(&mut self, edited: &[&Geometry]) { + self.want_only_checking(edited, |_| Ok(())).unwrap_or_default(); + } + + /// [`HeldPlaces::want_only`], stopping when `check` (given each edit's index) says so, the + /// places wanted left as they were. + fn want_only_checking( + &mut self, + edited: &[&Geometry], + mut check: impl FnMut(usize) -> std::result::Result<(), String>, + ) -> std::result::Result<(), String> { let mut wanted = std::collections::HashSet::new(); - for g in edited { + for (i, g) in edited.iter().enumerate() { + check(i)?; g.for_each_coord(|c| { if c.is_finite() && self.get(c).is_none() { wanted.insert(Self::key(c)); @@ -1227,6 +1235,7 @@ impl HeldPlaces { }); } self.wanted = Some(wanted); + Ok(()) } /// The held place that reads exactly as `c` in longitude/latitude. @@ -1243,6 +1252,17 @@ impl HeldPlaces { } } +/// Stops a conversion of a whole layer once the command running it was asked to (looked at every +/// 256 features): a layer's conversion takes as long as the layer is large. A single feature +/// converts whole between looks, however many vertices it has (a long coastline is not stopped +/// partway). +fn stop_when_asked(i: usize) -> std::result::Result<(), String> { + if i.is_multiple_of(256) { + progress::check().map_err(|e| e.to_string())?; + } + Ok(()) +} + /// An edit `g` in longitude/latitude in the target system, as [`convert_keeping_missing`], a held /// place written as held; `None` also when it reaches past 85.05° for Web Mercator, which would /// hold the place at 85.05°, where it ends, rather than refuse it. @@ -1309,6 +1329,66 @@ mod tests { assert_eq!(window.coord_crs(), raster::Crs::LonLat); } + /// A whole layer's conversion stops once its command is cancelled, part-way through as well as + /// before it starts, leaving the dataset as it was; without a cancel it runs to the end. + #[test] + fn a_whole_layer_conversion_stops_when_cancelled() { + use std::sync::atomic::Ordering; + let utm = raster::Crs::Epsg(32632); + let mut ds = Dataset::new("held", GeometryType::Point, vec![]); + for i in 0..600 { + ds.push(Some(Geometry::Point(Coord::new(11.0 + f64::from(i) * 1e-4, 48.7))), vec![]); + } + let plain = ds.clone(); + // Cancelled before it starts, or once asked `n` times. + let before = || { + let probe = std::sync::Arc::new(progress::tests::Counted::default()); + probe.cancel.store(true, Ordering::Relaxed); + progress::install(Some(probe)) + }; + let at = + |n: u64| progress::install(Some(std::sync::Arc::new(progress::tests::Counted { after_checks: Some(n), ..Default::default() }))); + // A conversion checks before its loop, then at features 0, 256 and 512: the third check + // stops it at feature 256, part-way. + let midway = || at(2); + // A write-back first looks over its edits (checks at edits 0, 256 and 512 of 600; at the + // one edit of a merge changing one feature), reads the held places (checks at features + // 0, 256 and 512), then checks before its copy and at features 0 and 256 of it: the copy + // stops at feature 256, part-way. + let results_midway = || at(8); + let merge_midway = || at(6); + for cancel in [&before as &dyn Fn() -> progress::Installed, &midway] { + let _cancelled = cancel(); + assert!(ds.hold_in(utm).is_err()); + assert_eq!(ds, plain, "a cancelled hold leaves the dataset as it was"); + } + ds.hold_in(utm).unwrap(); + let held = ds.clone(); + let merged = ds.in_lonlat().unwrap().into_owned(); + type Cancel<'a> = &'a dyn Fn() -> progress::Installed; + for (cancel, results, merge) in + [(&before as Cancel, &before as Cancel, &before as Cancel), (&midway, &results_midway, &merge_midway)] + { + { + let _cancelled = cancel(); + assert!(ds.in_lonlat().is_err()); + } + { + let _cancelled = results(); + assert!(ds.results_from_lonlat(merged.clone()).is_err()); + } + { + let _cancelled = merge(); + assert!(ds.merged_from_lonlat(merged.clone(), &std::collections::HashSet::from([1])).is_err()); + } + assert_eq!(ds, held); + } + let _cancelled = before(); + // Said in words, read back as a cancel by those that wrap it. + assert!(matches!(ds.in_lonlat().map_err(DataError::of_conversion), Err(DataError::Cancelled))); + assert!(matches!(DataError::of_conversion("no such system".into()), DataError::Format(_))); + } + /// A merge in longitude/latitude written back to a held dataset: what it left as it was stays /// as stored, a changed feature keeps the places it didn't move, and only a moved or new place /// is converted. diff --git a/crates/data/src/progress.rs b/crates/data/src/progress.rs index 23ae6cf46c..63f2f82d5d 100644 --- a/crates/data/src/progress.rs +++ b/crates/data/src/progress.rs @@ -101,14 +101,17 @@ pub(crate) mod tests { use super::*; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; - /// A probe that counts, and is cancelled when told or (with `after`) once that many items - /// were counted. + /// A probe that counts, and is cancelled when told, (with `after`) once that many items + /// were counted, or (with `after_checks`) once asked that many times, for a loop that only + /// checks. #[derive(Default)] pub(crate) struct Counted { pub(crate) cancel: AtomicBool, pub(crate) done: AtomicU64, pub(crate) total: AtomicU64, pub(crate) after: Option, + pub(crate) after_checks: Option, + pub(crate) checks: AtomicU64, } impl Counted { @@ -120,7 +123,10 @@ pub(crate) mod tests { impl Probe for Counted { fn cancelled(&self) -> bool { - self.cancel.load(Ordering::Relaxed) || self.after.is_some_and(|n| self.done.load(Ordering::Relaxed) >= n) + let asked = self.checks.fetch_add(1, Ordering::Relaxed); + self.cancel.load(Ordering::Relaxed) + || self.after.is_some_and(|n| self.done.load(Ordering::Relaxed) >= n) + || self.after_checks.is_some_and(|n| asked >= n) } fn begin(&self, total: u64) { self.total.store(total, Ordering::Relaxed); diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 91ecb4cd73..fcb7da4688 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -302,7 +302,10 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result refused(path, e), + cancelled => cancelled, + })?; if let Some(why) = same_rows(&in_lonlat, &read_back, if crs.is_some() { PROJECTED_TOLERANCE } else { 0.0 }) { return Err(refused(path, format!("the file couldn't hold the layer as it is: {why}"))); } diff --git a/crates/engine/examples/held_bench.rs b/crates/engine/examples/held_bench.rs new file mode 100644 index 0000000000..d953e8cadb --- /dev/null +++ b/crates/engine/examples/held_bench.rs @@ -0,0 +1,83 @@ +//! 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: +//! `cargo run --release -p rustgis-engine --example held_bench -- [vertices, default 1000000]`. +use rustgis_data::raster::Crs; +use rustgis_data::{Coord, Dataset, Geometry, GeometryType}; +use rustgis_engine::render::{View, render}; +use rustgis_engine::{Project, Session}; +use rustgis_geom::extent_to_merc; +use rustgis_map::Camera; +use serde_json::json; +use std::time::Instant; + +/// Lines of 1000 vertices each, zigzagging across a degree around 11.5°E 48.7°N. +fn lines(vertices: usize) -> Dataset { + let mut d = Dataset::new("lines", GeometryType::Polyline, vec![]); + let per = 1000; + for k in 0..vertices.div_ceil(per) { + let y = 48.2 + (k as f64 * 0.618_033).fract(); + // The last line has what is left, so the layer has the vertices asked for. + let n = (vertices - k * per).min(per); + let run = (0..n).map(|i| Coord::new(11.0 + i as f64 / per as f64, y + if i % 2 == 0 { 1e-4 } else { -1e-4 })).collect(); + d.push(Some(Geometry::Line(vec![run])), vec![]); + } + d +} + +fn ms(t: Instant) -> f64 { + t.elapsed().as_secs_f64() * 1000.0 +} + +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"); + 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, + None => { + let mut r = (what, [f64::NAN; 2]); + r.1[i] = v; + rows.push(r); + } + }; + for (i, crs) in [Crs::LonLat, Crs::Epsg(32632)].into_iter().enumerate() { + let mut d = lines(vertices); + let t = Instant::now(); + d.hold_in(crs)?; + put("hold in its system", i, ms(t)); + let t = Instant::now(); + let back = d.in_lonlat()?; + put("in longitude/latitude (a tool)", i, ms(t)); + drop(back); + let mut s = Session::new(Project::default()); + s.map_mut().layers.clear(); + s.map_mut().add_dataset(d); + let e = extent_to_merc(&s.map().full_extent()); + let (w, h) = (1600.0, 1000.0); + let res = (e.width() / w).max(e.height() / h); + let mut camera = Camera { center: Coord::new((e.min_x + e.max_x) / 2.0, (e.min_y + e.max_y) / 2.0), res, bearing: 0.0, pitch: 0.0 }; + let frame = |s: &mut Session, camera: Camera| { + let view = View { width: w, height: h, pixels_per_point: 1.0, camera, sky: false }; + let t = Instant::now(); + render(s.map_mut(), &view).ok_or("no frame")?; + Ok::<_, String>(ms(t)) + }; + put("first frame (Web Mercator)", i, frame(&mut s, camera)?); + put("next frame", i, frame(&mut s, camera)?); + camera.center.x += e.width() / 10.0; + put("pan", i, frame(&mut s, camera)?); + camera.res /= 4.0; + put("zoom in 4x", i, frame(&mut s, camera)?); + s.run("map.projection", &json!({"type": "epsg:3035"}))?; + s.run("layer.zoomTo", &json!({"layer": "lines"}))?; + 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)?); + } + for (what, [a, b]) in rows { + println!("{what:<34}{a:>12.1}{b:>12.1}"); + } + Ok(()) +} diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 25e2af1de5..d9ed8e3489 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -151,13 +151,58 @@ fn said(s: &mut Session, wrote: Wrote) -> CmdResult { /// then that it was written to `path`, or why not. A cancelled one says only that it was cancelled. pub(crate) fn drawn( maps: &[rustgis_map::Map], - notices: Vec<(rustgis_data::diagnostics::Severity, String)>, + mut notices: Vec<(rustgis_data::diagnostics::Severity, String)>, written: Result, path: String, ) -> Result { if let (Err(e), Err(_)) = (&written, rustgis_data::progress::check()) { return Err(e.clone()); } + // Held layers' places the drawing couldn't give in longitude/latitude ([`rustgis_map::Layer::unplaced`]): + // drawn without them, and said of this export, as the screen says them of the map. + let (mut unplaced, mut partly, mut undrawn) = (0usize, Vec::new(), Vec::new()); + for m in maps { + for l in &m.layers { + let named = format!("map '{}', layer '{}'", m.name, l.name); + // Only the layers this export drew: a hidden one, or a map the layout doesn't + // show, keeps a count from an earlier drawing. + match l.unplaced_drawn() { + Some(Ok(n)) if *n > 0 => { + unplaced += n; + partly.push(format!("{named} ({n})")); + } + Some(Err(e)) => undrawn.push(format!("{named}: {e}")), + _ => {} + } + } + } + if written.is_ok() { + let listed = |v: &[String]| { + let more = v.len().saturating_sub(10); + let shown = v.iter().take(10).cloned().collect::>().join("; "); + if more > 0 { format!("{shown}; and {more} more") } else { shown } + }; + let warn = rustgis_data::diagnostics::Severity::Warning; + if unplaced > 0 { + notices.push(( + warn, + format!( + "{path}: {unplaced} feature(s) have a place that can't be given in longitude/latitude, drawn without it ({})", + listed(&partly) + ), + )); + } + if !undrawn.is_empty() { + notices.push(( + warn, + format!( + "{path}: {} layer(s) aren't drawn, as their system can't be given in longitude/latitude: {}", + undrawn.len(), + listed(&undrawn) + ), + )); + } + } // Each by its live layer, with the source it failed on: one the user removed, or opened // afresh meanwhile (`SourceLayer::same_opening`), is left as it is. let failed: Vec<_> = maps diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 2e546c341c..f59fbd8793 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -846,6 +846,12 @@ fn offline_sync(s: &mut Session, p: &Value) -> CmdResult { sync_area(s, ai, &edited) } +/// A layer's conversion error in a sync, named by the layer; a cancel stays a cancel, as the +/// command's other cancels read. +fn sync_error(layer: &str, e: String) -> String { + if e == rustgis_data::DataError::Cancelled.to_string() { e } else { format!("cannot sync layer '{layer}': {e}") } +} + /// Copies the edits `edited` holds of offline area `ai` (its offline map, here or from a field /// package) back to the area's source map, as [`offline_sync`] describes, and refreshes the area. /// @@ -886,9 +892,9 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - // Compared and merged in longitude/latitude, as a package returns its features, whatever // system the source, its last synced copy or the package hold them in; the source is // written back in its own, its unchanged places as stored (`results_from_lonlat`). - let ol_ds = ol.dataset.in_lonlat().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; + let ol_ds = ol.dataset.in_lonlat().map_err(|e| sync_error(&ol.name, e))?; let last_synced = area.data.layers.iter().find(|l| l.id == ol.id).map(|l| &l.dataset); - let baseline = last_synced.map(|d| d.in_lonlat()).transpose().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; + let baseline = last_synced.map(|d| d.in_lonlat()).transpose().map_err(|e| sync_error(&ol.name, e))?; // Whether a feature was edited offline: the returned copy against the last synced one, // as they are when both are held in the same system (as an offline map in the project // and its area are), so a conversion that changed meanwhile (a datum grid downloaded) @@ -919,7 +925,7 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - } let held = (sl.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat).then(|| sl.dataset.clone()); if held.is_some() { - sl.dataset = sl.dataset.in_lonlat().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?.into_owned(); + sl.dataset = sl.dataset.in_lonlat().map_err(|e| sync_error(&ol.name, e))?.into_owned(); } // The ids the area held when it was last synced. let had: std::collections::HashSet = @@ -983,8 +989,7 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - // Its own coordinates back while the merge is converted (and kept, should that fail): // the features it left as they were stay as stored, only those it wrote are converted. let merged = std::mem::replace(&mut sl.dataset, own); - sl.dataset = - sl.dataset.merged_from_lonlat(merged, &written).map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; + sl.dataset = sl.dataset.merged_from_lonlat(merged, &written).map_err(|e| sync_error(&ol.name, e))?; } sl.selection.clear(); sl.touch_geometry(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a5987a2ade..83faf47f6a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3074,10 +3074,10 @@ impl Session { /// has features with a place that can't be given in longitude/latitude, which the map and /// the globe draw from: they draw such a feature without that place (a line broken there, a /// point not at all), and labels' lines, block diagrams and terrain water leave it out. Or - /// that none of the layer is drawn, when its system can't be converted. - /// Layers in longitude/latitude, every layer read today, are passed over at no cost. A held - /// layer's count reads each of its places through the conversion, on the UI thread with no - /// Cancel, once per version of its geometry: as long as converting it for the map takes. + /// that none of the layer is drawn, when its system can't be converted. The map counts them + /// as it converts the layer for drawing ([`rustgis_map::Layer::unplaced`]), so it costs + /// nothing more, and it is said once the layer was drawn. Layers in longitude/latitude, every + /// layer read today, have nothing to say. fn say_unplaced(&mut self) { // One notice per kind, with the count and the layers it is about. let (mut features, mut partly, mut undrawn) = (0usize, Vec::new(), Vec::new()); @@ -3085,17 +3085,19 @@ impl Session { for map in &self.project.maps { for l in map.layers.iter().filter(|l| !l.is_raster() && l.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat) { seen.insert(l.instance_id()); + let Some(count) = l.unplaced() else { continue }; let version = (l.geometry_rev(), l.dataset.coord_crs()); if self.unplaced_checked.insert(l.instance_id(), version) == Some(version) { continue; } - match l.dataset.unplaced_in_lonlat() { + let named = format!("map '{}', layer '{}'", map.name, l.name); + match count { Ok(0) => {} Ok(n) => { features += n; - partly.push(format!("map '{}', layer '{}' ({n})", map.name, l.name)); + partly.push(format!("{named} ({n})")); } - Err(e) => undrawn.push(format!("map '{}', layer '{}': {e}", map.name, l.name)), + Err(e) => undrawn.push(format!("{named}: {e}")), } } } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 750a600549..882164a25e 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -634,21 +634,32 @@ fn a_web_scene_leaves_out_what_it_cannot_place() { } /// A held layer's feature with a place that can't be given in longitude/latitude is drawn without -/// it, and that is said in one notice for every such layer, once for each version of a layer's -/// geometry; layers whose places all convert say nothing. +/// it, and that is said: of the map, once it was drawn, in one notice for every such layer, once +/// for each version of a layer's geometry; and of an export that drew it. Layers whose places +/// all convert say nothing. #[test] fn a_held_layers_undrawable_features_are_said_once() { let mut s = session(UTM); - let said_of = |s: &Session, mark| -> Vec { - s.notices_since(mark) - .iter() - .map(|n| n.text.clone()) - .filter(|t| t.contains("can't be given in longitude/latitude: the map")) - .collect() + let dir = Dir::new("undrawable"); + let said_of = |s: &Session, mark, what: &str| -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains(what)).collect() + }; + let of_map = "can't be given in longitude/latitude: the map"; + let of_export = "can't be given in longitude/latitude, drawn without it"; + // The screen's frame: drawn on the session's map, then looked at after a command. + let frame = |s: &mut Session| { + let view = crate::render::View { width: 160.0, height: 100.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false }; + crate::render::render(s.map_mut(), &view); + let _ = s.run("select.clear", &Value::Null); + }; + let export = |s: &mut Session| { + let path = dir.path().join("map.png"); + s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 160, "height": 100})).unwrap(); }; let mark = s.notice_mark(); - let _ = s.run("select.clear", &Value::Null); - assert!(said_of(&s, mark).is_empty(), "{:?}", said_of(&s, mark)); + frame(&mut s); + export(&mut s); + assert!(said_of(&s, mark, "longitude/latitude").is_empty(), "{:?}", said_of(&s, mark, "longitude/latitude")); // Far beyond any place UTM 32N holds. for name in ["Wells", "Roads"] { let l = s.map_mut().layers.iter_mut().find(|l| l.name == name).unwrap(); @@ -657,14 +668,269 @@ fn a_held_layers_undrawable_features_are_said_once() { l.dataset.push(Some(g), vec![]); l.touch_geometry(); } + // Not drawn yet: nothing found, nothing said. let mark = s.notice_mark(); let _ = s.run("select.clear", &Value::Null); - let _ = s.run("select.clear", &Value::Null); - let said = said_of(&s, mark); + assert!(said_of(&s, mark, of_map).is_empty()); + // An export says what it drew without, of itself. + export(&mut s); + let said = said_of(&s, mark, of_export); + assert_eq!(said.len(), 1, "{said:?}"); + assert!( + said[0].contains(": 2 feature(s)") && said[0].ends_with("(map 'Map', layer 'Roads' (1); map 'Map', layer 'Wells' (1))"), + "{said:?}" + ); + // The map: said after the frame that drew it, once, however often it is drawn again. + frame(&mut s); assert_eq!( - said, + said_of(&s, mark, of_map), [ "2 feature(s) have a place that can't be given in longitude/latitude: the map and the globe draw them without it, and labels' lines, block diagrams and terrain water leave them out (map 'Map', layer 'Roads' (1); map 'Map', layer 'Wells' (1))" ] ); + frame(&mut s); + assert_eq!(said_of(&s, mark, of_map).len(), 1); + // A layer the export doesn't draw (hidden) isn't said of it, though the map's frame counted it and the copy keeps that. + s.map_mut().layers.iter_mut().find(|l| l.name == "Roads").unwrap().visible = false; + let hidden = s.notice_mark(); + export(&mut s); + let said = said_of(&s, hidden, of_export); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains(": 1 feature(s)") && said[0].ends_with("(map 'Map', layer 'Wells' (1))"), "{said:?}"); + s.map_mut().layers.iter_mut().find(|l| l.name == "Roads").unwrap().visible = true; + // An edit makes another version: said again once it is drawn, with its own count. + let wells = s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap(); + wells.dataset.push(Some(Geometry::Point(Coord::new(2e12, 2e12))), vec![]); + wells.touch_geometry(); + let mark = s.notice_mark(); + frame(&mut s); + let said = said_of(&s, mark, of_map); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("2 feature(s)") && said[0].ends_with("(map 'Map', layer 'Wells' (2))"), "{said:?}"); +} + +/// Every cell of a raster layer named in a command's answer. +fn raster_cells(s: &Session, answer: &Value) -> (u32, u32, Vec>) { + let id = answer["layer"].as_u64().unwrap_or_else(|| panic!("no layer in {answer}")) as u32; + let g = s.map().layer(id).unwrap().raster.as_ref().unwrap().data.clone().unwrap(); + let cells = + (0..g.height).flat_map(|y| (0..g.width).map(move |x| (x, y))).map(|(x, y)| g.value(0, i64::from(x), i64::from(y))).collect(); + (g.width, g.height, cells) +} + +/// Rasters read through a held polygon layer read the same pixels: a spectral zone, a clip, and +/// training polygons for a classification. +#[test] +fn a_held_polygon_layer_reads_rasters_alike() { + let mut ss = both(); + run_both(&mut ss, "raster.rasterize", &json!({"layer": "Parcels", "field": "n", "cellSize": 0.0007, "nodata": -1})); + let raster = "Parcels raster"; + let [a, b] = run_both(&mut ss, "raster.spectral", &json!({"layer": raster, "zone": "Parcels"})); + assert_eq!(a["pixels"], b["pixels"], "spectral zone"); + assert!(a["pixels"].as_u64().unwrap() > 0); + assert_numbers_close(&numbers(&a["values"].to_string()), &numbers(&b["values"].to_string()), 1e-6, "spectral zone means"); + let [a, b] = + run_both(&mut ss, "raster.process", &json!({"layer": raster, "operation": "clip", "polygon": "Parcels", "name": "clipped"})); + let (ra, rb) = (raster_cells(&ss[0], &a), raster_cells(&ss[1], &b)); + assert!(ra.2.iter().any(Option::is_some), "the clip keeps cells"); + assert_eq!(ra, rb, "clip"); + let [a, b] = run_both( + &mut ss, + "raster.classifySupervised", + &json!({"layer": raster, "training": "Parcels", "classField": "n", "name": "classes"}), + ); + let (ra, rb) = (raster_cells(&ss[0], &a), raster_cells(&ss[1], &b)); + assert!(ra.2.iter().any(Option::is_some), "the classification fills cells"); + assert_eq!(ra, rb, "supervised classification"); +} + +/// A photo added to a photo layer held in another system is placed there: it reads back at the +/// photo's position, as in a photo layer held in longitude/latitude. +#[test] +fn a_photo_joins_a_held_photo_layer_at_its_place() { + let mut ss = both(); + let photo = |lat: f64, lon: f64| rustgis_data::photo::example(true, (lat, "N"), (lon, "E")); + for s in &mut ss { + let first = photo(48.71, 11.51); + crate::cmd::layer::add_photos_to(s, "Photos", Some(false), |r| r.add("a.jpg", &first)).unwrap(); + } + // The held session's photo layer is held in UTM from here on, as a file's would be. + let held = ss[1].map_mut().layers.iter_mut().find(|l| l.name == "Photos").unwrap(); + held.dataset.hold_in(UTM).unwrap(); + held.touch_geometry(); + for s in &mut ss { + let second = photo(48.72, 11.52); + crate::cmd::layer::add_photos_to(s, "Photos", Some(false), |r| r.add("b.jpg", &second)).unwrap(); + } + assert_eq!(ss[1].map().layer_by_name("Photos").unwrap().dataset.coord_crs(), UTM); + let (a, b) = (lonlat(&ss[0], "Photos"), lonlat(&ss[1], "Photos")); + assert_eq!(a.len(), 2); + assert_close(&a, &b, "photos"); +} + +/// Pixels of two PNGs that differ, and those the first draws (unlike its corner). +fn png_difference(a: &std::path::Path, b: &std::path::Path) -> (usize, usize) { + let (a, b) = (image::open(a).unwrap().to_rgba8(), image::open(b).unwrap().to_rgba8()); + assert_eq!(a.dimensions(), b.dimensions()); + let differ = a.pixels().zip(b.pixels()).filter(|(x, y)| x != y).count(); + let drawn = a.pixels().filter(|p| p.0 != a.get_pixel(0, 0).0).count(); + (differ, drawn) +} + +/// A layer masked by a held polygon layer is drawn alike, on Web Mercator and on the globe. +#[test] +fn a_held_mask_is_drawn_alike() { + let mut ss = both(); + let dir = Dir::new("mask"); + run_both(&mut ss, "layer.mask", &json!({"layer": "Roads", "mask": "Parcels"})); + for (k, projection) in ["mercator", "globe"].into_iter().enumerate() { + let camera = camera_over_parcels(projection); + for s in &mut ss { + s.run("map.projection", &json!({"type": projection})).unwrap(); + s.map_mut().camera = camera; + } + let paths = [0, 1].map(|i| dir.path().join(format!("{k}-{i}.png"))); + for (s, path) in ss.iter_mut().zip(&paths) { + s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 320, "height": 200})).unwrap(); + } + let (differ, drawn) = png_difference(&paths[0], &paths[1]); + assert!(drawn > 1000, "{projection}: little drawn ({drawn} pixels)"); + assert!(differ * 100 < drawn, "{projection}: {differ} of {drawn} drawn pixels differ"); + } +} + +/// A publication layout's globe locator sketches held polygon layers alike. +#[test] +fn a_held_layers_layout_locator_is_drawn_alike() { + let mut ss = both(); + let dir = Dir::new("locator"); + let camera = camera_over_parcels("mercator"); + for s in &mut ss { + s.map_mut().camera = camera; + } + run_both(&mut ss, "layout.publication", &json!({"profile": "a5", "locator": "globe", "title": "Held"})); + let paths = [0, 1].map(|i| dir.path().join(format!("page-{i}.png"))); + for (s, path) in ss.iter_mut().zip(&paths) { + s.run("layout.export", &json!({"layout": 0, "path": path.display().to_string(), "dpi": 36})).unwrap(); + } + let (differ, drawn) = png_difference(&paths[0], &paths[1]); + assert!(drawn > 1000, "little drawn ({drawn} pixels)"); + assert!(differ * 100 < drawn, "{differ} of {drawn} drawn pixels differ"); + // The locator's map keeps a sketch of the polygons, in longitude/latitude: too small on the + // globe to tell apart in the picture, so compared as places. + let sketch = |s: &Session| -> Vec> { + let m = s.project.maps.iter().find(|m| m.name == "Map Locator").expect("the locator's map"); + let l = m.layers.iter().find(|l| l.name == "Parcels").expect("the parcels' sketch"); + assert_eq!(l.dataset.coord_crs(), Crs::LonLat); + l.dataset.features.iter().map(|f| f.geometry.clone()).collect() + }; + let (a, b) = (sketch(&ss[0]), sketch(&ss[1])); + assert!(!a.is_empty()); + assert_close(&a, &b, "locator sketch"); +} + +/// A layout's export says the undrawable places of the maps it shows only: a map it doesn't show +/// keeps its count from the screen's frame, which the export doesn't say. +#[test] +fn a_layout_says_only_the_undrawable_places_of_its_maps() { + let mut s = session(UTM); + let dir = Dir::new("layout"); + let wells = s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap(); + wells.dataset.push(Some(Geometry::Point(Coord::new(1e12, 1e12))), vec![]); + wells.touch_geometry(); + // The screen's frame counts the first map's place. + let view = crate::render::View { width: 160.0, height: 100.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false }; + crate::render::render(s.map_mut(), &view); + let said = |s: &Session, mark| -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("drawn without it")).collect() + }; + let export = |s: &mut Session, name: &str| { + let path = dir.path().join(name); + s.run("layout.export", &json!({"path": path.display().to_string(), "dpi": 36})).unwrap(); + }; + // A layout of another map: nothing said. + s.run("map.new", &json!({"name": "Second"})).unwrap(); + s.run("map.activate", &json!({"name": "Second"})).unwrap(); + s.run("layout.new", &json!({"page": "a5", "template": "map"})).unwrap(); + let mark = s.notice_mark(); + export(&mut s, "second.png"); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + // A layout of the first map: said. + s.run("map.activate", &json!({"name": "Map"})).unwrap(); + s.run("layout.new", &json!({"page": "a5", "template": "map"})).unwrap(); + let mark = s.notice_mark(); + export(&mut s, "first.png"); + let first = said(&s, mark); + assert_eq!(first.len(), 1, "{first:?}"); + assert!(first[0].ends_with("(map 'Map', layer 'Wells' (1))"), "{first:?}"); +} + +/// A held layer a frame reads without drawing it (here the terrain's water, hidden, read by a +/// tilted view) has its undrawable places counted and said, as a drawn layer's are: by an export +/// that read it, and of the map after the screen's frame. A frame that doesn't read it (on a +/// globe, or flat and north up with no shaded relief) says nothing of it. +#[test] +fn a_hidden_held_water_layers_undrawable_places_are_said() { + let mut s = session(UTM); + let dir = Dir::new("water"); + let parcels = s.map_mut().layers.iter_mut().find(|l| l.name == "Parcels").unwrap(); + let far = |x: f64| Coord::new(1e12 + x, 1e12); + parcels.dataset.push(Some(Geometry::Polygon(vec![vec![vec![far(0.0), far(1.0), far(2.0), far(0.0)]]])), vec![]); + parcels.touch_geometry(); + parcels.visible = false; + // Heights in Web Mercator round the parcels, without which terrain water isn't read. + let gt = rustgis_data::raster::GeoTransform { origin_x: 1.2e6, origin_y: 6.2e6, pixel_width: 1e4, pixel_height: -1e4 }; + let dem = rustgis_data::raster::Raster::new( + "dem", + 4, + 4, + vec![vec![10.0; 16]], + gt, + Crs::WebMercator, + None, + rustgis_data::raster::ColorHint::Gray, + "Float32", + ) + .unwrap(); + s.map_mut().add_raster("dem", rustgis_map::raster::RasterLayer::from_path(dem, "dem.tif")); + s.map_mut().view.terrain = Some(rustgis_map::view::Terrain { + source: rustgis_map::view::TerrainSource::Layer("dem".into()), + exaggeration: 1.0, + block: None, + water: Some(rustgis_map::view::TerrainWater { layer: "Parcels".into(), level: None, glint: 0.0, shore: 0.0 }), + }); + let said = |s: &Session, mark, what: &str| -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains(what)).collect() + }; + let export = |s: &mut Session, name: &str| { + let path = dir.path().join(name); + s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 160, "height": 100})).unwrap(); + }; + let frame = |s: &mut Session| { + let view = crate::render::View { width: 160.0, height: 100.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false }; + crate::render::render(s.map_mut(), &view); + let _ = s.run("select.clear", &Value::Null); + }; + // Flat and north up, then on a globe: no terrain water is read, so nothing is said of it. + let mark = s.notice_mark(); + export(&mut s, "flat.png"); + frame(&mut s); + s.map_mut().projection = rustgis_map::Projection::Globe; + export(&mut s, "globe.png"); + frame(&mut s); + assert!(said(&s, mark, "Parcels").is_empty(), "{:?}", said(&s, mark, "Parcels")); + s.map_mut().projection = rustgis_map::Projection::WebMercator; + // Tilted, the ground reads the water: the export says what it left out. + s.map_mut().camera.pitch = 40.0; + let mark = s.notice_mark(); + export(&mut s, "tilted.png"); + let drawn = said(&s, mark, "drawn without it"); + assert_eq!(drawn.len(), 1, "{drawn:?}"); + assert!(drawn[0].ends_with("(map 'Map', layer 'Parcels' (1))"), "{drawn:?}"); + // The screen's frame, then a command: the map's notice names the water layer. + let mark = s.notice_mark(); + frame(&mut s); + let of_map = said(&s, mark, "can't be given in longitude/latitude: the map"); + assert_eq!(of_map.len(), 1, "{of_map:?}"); + assert!(of_map[0].ends_with("(map 'Map', layer 'Parcels' (1))"), "{of_map:?}"); } diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 52eff8a546..aedbb43a09 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -356,6 +356,16 @@ pub struct Layer { /// snapping) don't evict each other. #[serde(skip)] lonlat: LonLatCopy, + /// How many of a held layer's features have a place that can't be given in + /// longitude/latitude, found as it was last converted for drawing ([`Layer::unplaced`]). + #[serde(skip)] + unplaced: Unplaced, + /// Whether its projected or longitude/latitude copy was used since the map was detached for a + /// drawing ([`Map::detach_reads`]): what an export drew, and so can say of itself. + /// Hit-testing and snapping use them too, but on the live map, which no export reads this + /// from. + #[serde(skip)] + drawn: bool, /// Allocation identities and byte totals, shared with render snapshots without retaining rows. #[serde(skip)] view_memory: view_memory::Cache, @@ -562,6 +572,8 @@ impl Layer { projected_for: String::new(), projected_crs: None, lonlat: LonLatCopy::default(), + unplaced: Unplaced::default(), + drawn: false, geometry_rev: 0, view_memory: Default::default(), geometry_kinds: Default::default(), @@ -1093,8 +1105,9 @@ impl Layer { if !matches!(flat, projection::Flat::Mercator) { self.display_levels.clear(); } - self.fill_projected(key, |to_lonlat, g| flat.project_from(to_lonlat, g)); + self.fill_projected(key, |g| flat.project(g)); } + self.drawn = true; &self.projected } @@ -1109,13 +1122,11 @@ impl Layer { return &[]; } if !self.lonlat.fits(self) { - // A system that can't be converted draws nothing, as on a flat map. - let to_lonlat = crs.to(Crs::LonLat).ok(); - let geoms: Vec> = - self.dataset.features.rows().map(|r| Some(to_lonlat.as_ref()?.geometry(r.geometry()?))).collect(); + let geoms = self.convert_counting_unplaced(|g| g); let bytes = lod::cache_bytes(&geoms); self.lonlat = LonLatCopy { geoms: std::sync::Arc::new(geoms), bytes, rev: self.geometry_rev, crs: Some(crs) }; } + self.drawn = true; &self.lonlat.geoms } @@ -1124,16 +1135,87 @@ impl Layer { if self.lonlat.fits(self) { &self.lonlat.geoms } else { &[] } } - /// Fills the projected geometry cache for `key` with `project` of each geometry, given the - /// conversion of the layer's own coordinate system to longitude/latitude. Longitude/latitude, - /// every layer's unless held in another, can't fail; a system that can't be converted draws - /// nothing (a layer read in one is converted as it is read, which says why it can't be). - fn fill_projected(&mut self, key: &str, project: impl Fn(&rustgis_data::raster::Reprojection, &Geometry) -> Option) { + /// Every geometry of a layer held in another system, in longitude/latitude as the map and + /// the globe draw it, passed through `then` one at a time: a place that can't be given there + /// is left out (NaN, which drawing skips), and how many features have one is kept + /// ([`Layer::unplaced`]), counted in the same pass: no second conversion, only a look over + /// each converted geometry and its source for places that are numbers in one and not the + /// other. None of it when its system can't be converted. It doesn't look at Cancel: it + /// converts the whole layer, as drawing always has (about a quarter of a second a million + /// vertices), once per version of its geometry. + fn convert_counting_unplaced(&mut self, then: impl Fn(Geometry) -> T) -> Vec> { + let crs = self.dataset.coord_crs(); + let (geoms, count) = match crs.to(Crs::LonLat) { + Ok(to) => { + let mut lost = 0usize; + let geoms = self + .dataset + .features + .rows() + .map(|r| { + let g = r.geometry()?; + let lonlat = to.geometry(g); + // A place that is a number but isn't once converted couldn't be. + let missing = |g: &Geometry| { + let mut n = 0usize; + g.for_each_coord(|c| n += usize::from(!c.is_finite())); + n + }; + lost += usize::from(missing(&lonlat) > missing(g)); + Some(then(lonlat)) + }) + .collect(); + (geoms, Ok(lost)) + } + Err(e) => ((0..self.dataset.features.len()).map(|_| None).collect(), Err(e)), + }; + self.unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count }; + geoms + } + + /// How many of its features have a place that can't be given in longitude/latitude, which the + /// map and the globe draw without it, as found the last time it was drawn from its current + /// geometry ([`Layer::projected_in`], [`Layer::lonlat_in`]): `None` until then, and for a + /// layer in longitude/latitude, which has none. An error when its system can't be converted, + /// when none of it is drawn. + pub fn unplaced(&self) -> Option<&Result> { + self.unplaced.fits(self).then_some(&self.unplaced.count) + } + + /// Counts its places that can't be given in longitude/latitude ([`Layer::unplaced`]) without + /// keeping a converted copy, unless counted for its geometry as it is, and marks it used by + /// this drawing ([`Layer::unplaced_drawn`]): for a held layer a frame reads beside drawing it + /// (terrain water, block walls, the lines labels square to), so an export that read it says + /// what it left out. Nothing is counted for a layer in longitude/latitude. The count converts + /// the whole layer on the drawing thread without looking at Cancel, once per version of its + /// geometry, as drawing does ([`Layer::projected_in`]). + pub fn count_unplaced(&mut self) { + if self.dataset.coord_crs() != Crs::LonLat && !self.unplaced.fits(self) { + self.convert_counting_unplaced(|_| ()); + } + self.drawn = true; + } + + /// [`Layer::unplaced`] of a layer a drawing used since its map was detached for it + /// ([`Map::detach_reads`]): what an export drawn on a copy can say of itself. `None` for a + /// layer it didn't draw (hidden, out of its scale range, on a map the layout doesn't show). + pub fn unplaced_drawn(&self) -> Option<&Result> { + if self.drawn { self.unplaced() } else { None } + } + + /// Fills the projected geometry cache for `key` with `project` of each geometry in + /// longitude/latitude: a layer's own, or a held layer's converted ([`Layer::convert_counting_unplaced`], + /// which counts what can't be). A system that can't be converted draws nothing. + fn fill_projected(&mut self, key: &str, project: impl Fn(&Geometry) -> Geometry) { self.display = None; let crs = self.dataset.coord_crs(); - let to_lonlat = crs.to(Crs::LonLat).ok(); - let projected: Vec> = - self.dataset.features.iter().map(|ft| project(to_lonlat.as_ref()?, ft.geometry.as_ref()?)).collect(); + let projected: Vec> = if crs == Crs::LonLat { + self.dataset.features.rows().map(|r| r.geometry().map(&project)).collect() + } else { + // Each converted geometry projected as it comes, so no whole copy in + // longitude/latitude is made. + self.convert_counting_unplaced(|g| project(&g)) + }; self.projected_extents = std::sync::Arc::new(projected.iter().map(|g| g.as_ref().map_or(Extent::EMPTY, Geometry::extent)).collect()); self.projected_vertices = projected.iter().flatten().map(lod::thinnable).sum(); @@ -1321,8 +1403,15 @@ impl Layer { pub fn adopt_cache(&mut self, other: &Layer) -> bool { // The globe's copy goes with the rows and geometry alone: a frame drawn only on the globe // has no flat projection to share. - if other.dataset.features.shares(&self.dataset.features) && other.geometry_rev == self.geometry_rev && other.lonlat.fits(other) { - self.lonlat = other.lonlat.clone(); + if other.dataset.features.shares(&self.dataset.features) && other.geometry_rev == self.geometry_rev { + if other.lonlat.fits(other) { + self.lonlat = other.lonlat.clone(); + } + // What a frame drawn on the copy found it can't draw, and that it drew it. + if other.unplaced.fits(other) { + self.unplaced = other.unplaced.clone(); + } + self.drawn |= other.drawn; } let fits = other.dataset.features.shares(&self.dataset.features) && other.geometry_rev == self.geometry_rev @@ -1852,6 +1941,10 @@ impl Map { for source in self.layers.iter_mut().filter_map(|l| l.source.as_mut()) { source.detach_read(); } + // What the copy draws is marked anew ([`Layer::unplaced_drawn`]). + for l in &mut self.layers { + l.drawn = false; + } } /// Identifies this live map, whatever its name or place among the project's maps. @@ -3365,6 +3458,8 @@ impl Layer { projected_for: _, projected_crs: _, lonlat: _, + unplaced: _, + drawn: _, view_memory: _, geometry_kinds: _, geometry_rev: _, @@ -3420,6 +3515,28 @@ impl Layer { } } +/// A held layer's count of features with a place that can't be given in longitude/latitude, at +/// a geometry revision in a coordinate system ([`Layer::unplaced`]). +#[derive(Clone, Debug)] +struct Unplaced { + rev: u64, + crs: Option, + count: Result, +} + +impl Default for Unplaced { + fn default() -> Self { + Unplaced { rev: u64::MAX, crs: None, count: Ok(0) } + } +} + +impl Unplaced { + /// Whether it is of `layer`'s geometry as it is now. + fn fits(&self, layer: &Layer) -> bool { + self.crs == Some(layer.dataset.coord_crs()) && self.rev == layer.geometry_rev + } +} + /// A layer's geometry in longitude/latitude, made from its rows at a geometry revision in a /// coordinate system ([`Layer::lonlat_in`]). #[derive(Clone, Debug, Default)] diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index e2ee7e4a32..91d1a8a2cb 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -136,6 +136,9 @@ impl LayerLook { projected_for: _, projected_crs: _, lonlat: _, + // What the last drawing counted and whether it drew the layer; neither is the look. + unplaced: _, + drawn: _, view_memory: _, geometry_kinds: _, geometry_rev, diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index df0b3cb212..44ddcdea4e 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -432,3 +432,41 @@ fn output(reply: &Value, tool: &str) -> Result { } Ok(ToolResult { losses: Vec::new(), output: Output::Layers(outs), messages }) } + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_data::raster::Crs; + use rustgis_data::{Coord, Dataset, Geometry, GeometryType}; + + /// A plugin tool is given a layer held in another system in longitude/latitude, as GeoJSON is, + /// whole or as its selection. + #[test] + fn a_held_layer_reaches_a_tool_in_longitude_latitude() { + struct Held(Dataset, Vec); + impl Inputs for Held { + fn dataset(&self, l: &str) -> Option<&Dataset> { + (l == "Wells").then_some(&self.0) + } + fn selection(&self, _: &str) -> &[usize] { + &self.1 + } + } + let mut ds = Dataset::new("Wells", GeometryType::Point, vec![]); + ds.push(Some(Geometry::Point(Coord::new(11.5, 48.7))), vec![]); + ds.push(Some(Geometry::Point(Coord::new(11.6, 48.8))), vec![]); + ds.hold_in(Crs::Epsg(32632)).unwrap(); + let near = |v: &Value, lon: f64, lat: f64| { + let c = &v["geometry"]["coordinates"]; + (c[0].as_f64().unwrap() - lon).abs() < 1e-9 && (c[1].as_f64().unwrap() - lat).abs() < 1e-9 + }; + let whole = layer_geojson(&Held(ds.clone(), vec![]), "Wells").unwrap(); + let f = whole["features"].as_array().unwrap(); + assert_eq!(f.len(), 2); + assert!(near(&f[0], 11.5, 48.7) && near(&f[1], 11.6, 48.8), "{whole}"); + let picked = layer_geojson(&Held(ds, vec![1]), "Wells").unwrap(); + let f = picked["features"].as_array().unwrap(); + assert_eq!(f.len(), 1); + assert!(near(&f[0], 11.6, 48.8), "{picked}"); + } +} diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index 13bf1375b9..b096f550bd 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -415,6 +415,7 @@ pub(crate) fn runs(map: &Map, b: &Block, scale: f64, env: &rustgis_data::query:: .and_then(|t| t.walls_layer.as_deref()) .and_then(|n| crate::terrain::walls_layer(map, n)); let Some(layer) = layer else { return (0..b.sides()).map(whole).collect() }; + crate::note_held_read(layer); let cut = layer_cut(layer, b, false, env); let styler = layer.styler_with(env.clone()); let grow = layer.size_factor(scale); @@ -620,6 +621,7 @@ pub(crate) fn water_runs(map: &Map, b: &Block, ground: &Ground, res: f64, scale: return out; }; let Some(layer) = crate::terrain::walls_layer(map, &tw.layer) else { return out }; + crate::note_held_read(layer); let field = bw.field.as_deref().and_then(|f| layer.dataset.field_index(f)); let cut = layer_cut(layer, b, true, env); // Styled at the view centre's drawing scale, as the water layer is drawn on the surface. @@ -1452,6 +1454,25 @@ mod tests { (m, b) } + /// A walls layer held in another system cuts the block's sides where the same layer held in + /// longitude/latitude does (#2032 C2). + #[test] + fn a_held_walls_layer_cuts_the_sides_alike() { + let (mut m, b) = walls_by_units(); + let cuts = |m: &Map| { + let u = units(m.layer_by_name("geo").unwrap(), &b, false, &Default::default()).units; + u.iter() + .map(|side| side.iter().map(|&(lo, hi, row)| ((lo * 1e3).round(), (hi * 1e3).round(), row)).collect::>()) + .collect::>() + }; + let plain = cuts(&m); + let l = m.layers.iter_mut().find(|l| l.name == "geo").unwrap(); + l.dataset.hold_in(rustgis_data::raster::Crs::Epsg(32631)).unwrap(); + l.touch_geometry(); + assert_eq!(cuts(&m), plain); + assert!(plain.iter().flatten().any(|c| c.2.is_some()), "the layer cuts the sides"); + } + #[test] fn walls_take_the_unit_under_the_boxs_edge_with_contacts_straight_down() { let (mut m, b) = walls_by_units(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index aba622fc6f..1c5d26c4d0 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2199,7 +2199,7 @@ fn render_any( env: &Env, ) -> Option { let revisions = archive_revisions([&*map]); - let output = render_pass(map, view, full_res_rasters, backend, record, failed_source, env); + let output = held_reads_counted(map, |map| render_pass(map, view, full_res_rasters, backend, record, failed_source, env)); // A frame stopped part-way (see `cancel`) is no frame. if cancel::requested() { return None; @@ -3252,7 +3252,7 @@ pub fn gpu_may_turn(map: &Map, view: &View) -> bool { || map.view.color_vision != rustgis_map::view::ColorVision::Normal || map.tiles.iter().any(|t| t.draws()) // The GPU draws the ground flat: a view over terrain stays on the CPU. - || terrain::Ground::of(map, &view.camera).is_some() + || terrain::Ground::has_heights(map, &view.camera) { return false; } @@ -4454,7 +4454,9 @@ fn render_frame( // Masks: layers shown only inside another layer's polygons, or left of the swipe divider. let masks = layer_masks(map, &ctx, w, h, &flat, &key, scale, failed_source)?; // The lines point labels are turned square to (#2263), on the screen. - let square_lines = square_lines(map, &ctx, &flat); + // Of those held in another system, the ids, noted read once a label is squared to them. + let mut square_held = std::collections::HashMap::new(); + let square_lines = square_lines(map, &ctx, &flat, &mut square_held); // Bottom first; a higher depth priority draws later (on top) whatever the order. let mut order: Vec = (0..n_layers).rev().collect(); order.sort_by_key(|i| map.layers.get(*i).map_or(0, |l| l.priority)); @@ -5571,7 +5573,12 @@ fn render_frame( .and_then(|to| { // Square to its nearest line, the line's course taken over a text // height; starting at the point, out by its offset. - let runs = square_lines.get(&to.layer.to_ascii_lowercase())?; + let target = to.layer.to_ascii_lowercase(); + // Read, even when it gave no lines (its system can't be converted). + if let Some(&id) = square_held.get(&target) { + note_held_id(id); + } + let runs = square_lines.get(&target)?; let reach = text::block_height(&text, size); let n = square_labels::normal(runs, (x as f32, y as f32), to.within * 1.33, reach, to.side)?; let start = (marker / 2.0 + 2.0 + class.offset[0] * 1.33) * label_factor; @@ -6347,6 +6354,11 @@ pub struct DrapePatch { /// ([`rustgis_map::Globe::drape_mesh`]) while it turns, with no drawing per frame. Labels are /// left out (the view hides them while it moves). pub fn render_globe_drape(map: &mut Map, view: &View, boxes: &[Extent], max_side: u32) -> Vec { + held_reads_counted(map, |map| render_globe_drape_drawn(map, view, boxes, max_side)) +} + +/// [`render_globe_drape`], the held layers it reads beside drawing them not yet counted. +fn render_globe_drape_drawn(map: &mut Map, view: &View, boxes: &[Extent], max_side: u32) -> Vec { let revisions = archive_revisions([&*map]); // A coarse drape may have far fewer pixels than points: it shows the map blurrier, but at // the view's scale. @@ -6405,6 +6417,11 @@ pub struct TiltPatch { /// band, square, over the circle round the view and without the margin: it is laid over the view /// the same way while it turns. pub fn render_tilt_drape(map: &mut Map, view: &View, margin: f64, max_side: u32) -> Vec { + held_reads_counted(map, |map| render_tilt_drape_drawn(map, view, margin, max_side)) +} + +/// [`render_tilt_drape`], the held layers it reads beside drawing them not yet counted. +fn render_tilt_drape_drawn(map: &mut Map, view: &View, margin: f64, max_side: u32) -> Vec { let revisions = archive_revisions([&*map]); let ppp = if view.pixels_per_point.is_finite() { view.pixels_per_point.clamp(0.25, 4.0) } else { 1.0 }; let max_side = f64::from(max_side.clamp(64, 8192)); @@ -6469,15 +6486,73 @@ fn longest_on_screen(ctx: &Ctx<'_>, parts: &[Vec]) -> Option>> = const { std::cell::RefCell::new(None) }; +} + +/// Notes that the drawing on this thread read `layer` beside drawing it (a reader calls it where +/// it reads its layer), for [`held_reads_counted`]. Nothing for a layer in longitude/latitude, +/// nor outside a drawing (a reader asked for its ground alone, say). +pub(crate) fn note_held_read(layer: &rustgis_map::Layer) { + if layer.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat { + note_held_id(layer.id); + } +} + +/// [`note_held_read`] of the layer with this id, known to be held in another system. +fn note_held_id(id: u32) { + HELD_READS.with(|r| { + // One id a layer: few layers are read, many times a frame (a label each). + if let Some(read) = r.borrow_mut().as_mut() + && !read.contains(&id) + { + read.push(id); + } + }); +} + +/// Runs a drawing of `map`, then counts the places of the held layers it read beside drawing them +/// ([`note_held_read`]) that can't be given in longitude/latitude, once for their version and +/// without keeping a copy ([`rustgis_map::Layer::count_unplaced`], which marks them used by this +/// drawing): the session and an export say them as they say those of the layers drawn, and only +/// when a reader read them. A drawing within it (another map's) keeps its own. +fn held_reads_counted(map: &mut Map, draw: impl FnOnce(&mut Map) -> T) -> T { + /// Puts back what was noted before the drawing, also when it panics (a command's panic is + /// caught), so reads outside a drawing aren't noted from then on. + struct Restore(Option>>); + impl Drop for Restore { + fn drop(&mut self) { + if let Some(outer) = self.0.take() { + HELD_READS.with(|r| *r.borrow_mut() = outer); + } + } + } + let restore = Restore(Some(HELD_READS.with(|r| r.borrow_mut().replace(Vec::new())))); + let out = draw(map); + let read = HELD_READS.with(|r| r.borrow_mut().take()).unwrap_or_default(); + drop(restore); + for id in read { + if let Some(l) = map.layer_mut(id) { + l.count_unplaced(); + } + } + out +} + /// The lines of the layers point labels are turned square to ([`LabelPlacement::Perpendicular`], /// #2263), keyed by layer name in ASCII lower case (as [`Map::layer_by_name`] matches names): /// each line's and polygon outline's runs on the screen, a ring closed as it is drawn, broken /// where a place doesn't project (on the globe, cut at the horizon as its stroke is). A layer -/// read in chunks from its source has none to hand. +/// read in chunks from its source has none to hand. `held` gets the ids of those held in another +/// system, by the same names, for a label squared to one to note it read ([`note_held_read`]). fn square_lines( map: &Map, ctx: &Ctx<'_>, flat: &rustgis_map::projection::Flat, + held: &mut std::collections::HashMap, ) -> std::collections::HashMap> { let mut out = std::collections::HashMap::new(); let wanted = map.layers.iter().filter(|l| l.visible && l.labels.enabled).flat_map(|l| l.labels.in_order()).filter_map(|c| { @@ -6488,6 +6563,9 @@ fn square_lines( continue; } let Some(layer) = map.layer_by_name(&name) else { continue }; + if layer.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat { + held.insert(name.clone(), layer.id); + } let mut runs = Vec::new(); // Read in longitude/latitude, whatever system the layer holds its coordinates in; a // feature that can't be given there squares nothing (nor any, in a system that can't be @@ -8576,6 +8654,66 @@ mod tests { assert!(far.angle.is_none() && far.y < fy as f32, "as auto: {:?} {} {fy}", far.angle, far.y); } + /// A drawing that panics (a command's panic is caught) leaves nothing noted: reads outside a + /// drawing are noted nowhere after it, as before it. + #[test] + fn a_panicking_drawing_leaves_no_reads_noted() { + let mut d = Dataset::new("lines", GeometryType::Polyline, vec![]); + d.push(Some(Geometry::Line(vec![vec![Coord::new(-1.0, 0.0), Coord::new(1.0, 0.0)]])), vec![]); + d.hold_in(rustgis_data::raster::Crs::Epsg(32631)).unwrap(); + let mut m = Map::new("Map"); + let id = m.add_dataset(d); + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + held_reads_counted(&mut m, |m| { + note_held_read(m.layer(id).unwrap()); + panic!("a drawing's bug"); + }) + })); + assert!(panicked.is_err()); + assert!(HELD_READS.with(|r| r.borrow().is_none())); + note_held_read(m.layer(id).unwrap()); + assert!(HELD_READS.with(|r| r.borrow().is_none())); + } + + /// A hidden line layer held in another system that point labels square to is counted as read + /// by the frame (its place that can't be given in longitude/latitude, for the session and an + /// export to say) only when a label is squared to it: not when the labelled layer is out of + /// its scale range (#2032 C2). + #[test] + fn a_held_layer_labels_square_to_is_counted_only_when_read() { + let map = |labelled_in_scale: bool| { + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + let mut d = Dataset::new("lines", GeometryType::Polyline, vec![]); + d.push(Some(Geometry::Line(vec![vec![Coord::new(-1.0, 0.0), Coord::new(1.0, 0.0)]])), vec![]); + d.hold_in(rustgis_data::raster::Crs::Epsg(32631)).unwrap(); + d.push(Some(Geometry::Line(vec![vec![Coord::new(1e12, 1e12), Coord::new(1e12 + 1.0, 1e12)]])), vec![]); + let lines = m.add_dataset(d); + m.layer_mut(lines).unwrap().visible = false; + let mut d = Dataset::new("pts", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(-0.05, 0.01))), vec![Value::Text("Near".into())]); + let pts = m.add_dataset(d); + let l = m.layer_mut(pts).unwrap(); + l.labels.enabled = true; + l.labels.default.placement = LabelPlacement::Perpendicular; + l.labels.default.square_to = + Some(rustgis_map::SquareTo { layer: "lines".into(), within: 20.0, side: rustgis_map::SquareSide::Away }); + if !labelled_in_scale { + l.min_scale = Some(1.0); + } + (m, lines) + }; + let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.02)), res: 100.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 300.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }; + let (mut m, lines) = map(true); + let labels = render(&mut m, &view).unwrap().labels; + assert!(labels.iter().find(|l| l.text == "Near").is_some_and(|l| l.angle.is_some()), "squared"); + assert!(matches!(m.layer(lines).unwrap().unplaced_drawn(), Some(Ok(1))), "{:?}", m.layer(lines).unwrap().unplaced_drawn()); + let (mut m, lines) = map(false); + render(&mut m, &view).unwrap(); + assert!(m.layer(lines).unwrap().unplaced_drawn().is_none(), "{:?}", m.layer(lines).unwrap().unplaced_drawn()); + } + /// A label moved by hand into view is drawn whatever its feature's place: a point's, or a /// line's labelled along it, out of view, its callout's line reaching back off the screen. #[test] diff --git a/crates/render/src/terrain.rs b/crates/render/src/terrain.rs index b204f4d912..7bc0acce68 100644 --- a/crates/render/src/terrain.rs +++ b/crates/render/src/terrain.rs @@ -167,6 +167,12 @@ impl Ground { Ground::heights_of(map, camera).map_or(0, |g| water::coarse_shores(map, camera, &g)) } + /// Whether a view of `camera` has terrain on `map` ([`Ground::of`] is `Some`), without reading + /// its water. + pub(crate) fn has_heights(map: &Map, camera: &Camera) -> bool { + Ground::heights_of(map, camera).is_some() + } + /// [`Ground::of`] without its water. fn heights_of(map: &Map, camera: &Camera) -> Option { let t = map.view.terrain.as_ref()?; diff --git a/crates/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index 5e55799dc5..f8d3f07223 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -610,6 +610,7 @@ fn shores(polygons: &[(Vec>, Option)]) -> (f64, usize) { /// of `camera`, when it names a polygon layer there: the polygons that view draws. pub(super) fn of(map: &Map, camera: &Camera, ground: &Ground) -> Option> { let (layer, level) = water_layer(map)?; + crate::note_held_read(layer); let key = Key { rows: layer.dataset.features.allocation_key(), drawn: drawn_rows(map, layer, camera), @@ -825,6 +826,30 @@ pub(crate) fn paint_shore(pm: &mut crate::Canvas, water: &Water, frame: &crate:: mod tests { use super::*; + /// A water layer held in another system holds its water where the same layer held in + /// longitude/latitude does (#2032 C2). + #[test] + fn a_held_water_layer_gives_the_same_polygons() { + use rustgis_data::{Dataset, GeometryType}; + let ring = |x: f64, y: f64| { + vec![Coord::new(x, y), Coord::new(x + 0.01, y), Coord::new(x + 0.01, y + 0.01), Coord::new(x, y + 0.01), Coord::new(x, y)] + }; + let mut d = Dataset::new("lake", GeometryType::Polygon, vec![]); + d.push(Some(Geometry::Polygon(vec![vec![ring(11.5, 48.7)], vec![ring(11.52, 48.71)]])), vec![]); + let plain = rustgis_map::Layer::new(1, d.clone()); + d.hold_in(rustgis_data::raster::Crs::Epsg(32632)).unwrap(); + let held = rustgis_map::Layer::new(2, d); + let (a, b) = (polygons(&plain, None, None), polygons(&held, None, None)); + assert_eq!(a.len(), 2); + assert_eq!(a.len(), b.len()); + for ((ra, _), (rb, _)) in a.iter().zip(&b) { + assert_eq!(ra.len(), rb.len()); + for (x, y) in ra.iter().flatten().zip(rb.iter().flatten()) { + assert!((x.x - y.x).abs() < 1e-3 && (x.y - y.y).abs() < 1e-3, "{x:?} vs {y:?}"); + } + } + } + fn square(x0: f64, y0: f64, side: f64) -> Vec { vec![Coord::new(x0, y0), Coord::new(x0 + side, y0), Coord::new(x0 + side, y0 + side), Coord::new(x0, y0 + side)] }