From 5656fc48c59f30bb2e67ac65d26ac1fdde335a82 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 16:32:26 +0100 Subject: [PATCH 1/2] feat(crs): held layers: the globe's longitude/latitude copy in a cache of its own, undrawable features said, a sync compares same-system copies as held (#2032 C2b) --- crates/data/src/lib.rs | 22 +++++++ crates/engine/src/cmd/workspace.rs | 37 ++++++++--- crates/engine/src/lib.rs | 40 +++++++++++ crates/engine/src/tests/held_layers.rs | 55 ++++++++++++++++ crates/map/src/lib.rs | 91 +++++++++++++++++++++++--- crates/render/src/lib.rs | 4 +- 6 files changed, 227 insertions(+), 22 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index bacb62ad3b..3acca359f0 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -973,6 +973,28 @@ 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). + 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 diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 0995315c1f..69b913760b 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -884,16 +884,33 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - // 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 baseline = area - .data - .layers - .iter() - .find(|l| l.id == ol.id) - .map(|l| l.dataset.in_lonlat()) - .transpose() - .map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; + 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))?; + // 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) + // can't make an unedited feature look edited; else both in longitude/latitude. + type ById<'a> = std::collections::HashMap>; + fn by_id(d: &rustgis_data::Dataset) -> ById<'_> { + d.features.rows().map(|r| (r.id(), r)).collect() + } + let raw: Option<(ById<'_>, ById<'_>)> = + last_synced.filter(|b| b.coord_crs() == ol.dataset.coord_crs()).map(|b| (by_id(b), by_id(&ol.dataset))); + let same_row = |a: rustgis_data::RowRef, b: rustgis_data::RowRef| a.geometry() == b.geometry() && a.values().eq(b.values()); + // `lonlat_base` and `lonlat_now`, the copies in longitude/latitude, are used only when + // the two aren't held in the same system. + let unchanged_offline = |fid: u64, lonlat_base: Option<&&rustgis_data::Feature>, lonlat_now: &rustgis_data::Feature| match &raw + { + Some((base, now)) => base.get(&fid).is_some_and(|b| now.get(&fid).is_some_and(|n| same_row(*b, *n))), + None => lonlat_base.is_some_and(|b| *b == lonlat_now), + }; + let same_as_last = match (&raw, &baseline) { + (Some(_), Some(_)) => last_synced.is_some_and(|b| b.features == ol.dataset.features), + (None, Some(b)) => b.features == ol_ds.features, + _ => false, + }; if !offline_fields_match(&sl.dataset.fields, &ol_ds.fields) - && baseline.as_ref().is_none_or(|b| !offline_fields_match(&b.fields, &ol_ds.fields) || b.features != ol_ds.features) + && baseline.as_ref().is_none_or(|b| !offline_fields_match(&b.fields, &ol_ds.fields) || !same_as_last) { return Err(format!("cannot sync layer '{}': source and offline fields differ; align the fields before syncing", ol.name)); } @@ -926,7 +943,7 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - for f in &ol_ds.features { let fid = f.id; if had.contains(&fid) { - let changed_offline = base.get(&fid).is_none_or(|b| *b != f); + let changed_offline = !unchanged_offline(fid, base.get(&fid), f); match sl.dataset.features.iter_mut().find(|x| x.id == fid) { Some(x) if changed_offline && x != f => { if base.get(&fid).is_some_and(|b| *b != x) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5ead80e880..977aed3147 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -852,6 +852,10 @@ pub struct Session { pub(crate) crs_used_elsewhere: Vec<(String, String)>, /// When the frame path last looked for missing datum grids ([`Session::say_grid_notes`]). grid_notes_checked: Option, + /// Each layer held in another system (by instance) and the geometry revision and system whose + /// places were last counted for [`Session::say_unplaced`], so a version of a layer is looked at + /// once. + unplaced_checked: std::collections::HashMap, /// The datum grids the map's layers were last projected with /// ([`rustgis_data::raster::crs::grid_generation`]). grid_generation: u64, @@ -1337,6 +1341,7 @@ impl Session { grid_pairs: Vec::new(), crs_used_elsewhere: Vec::new(), grid_notes_checked: None, + unplaced_checked: Default::default(), grid_generation: rustgis_data::raster::crs::grid_generation(), grid_downloads_said: Default::default(), grid_turns: 0, @@ -1767,6 +1772,7 @@ impl Session { self.undo_memory.publish(&self.project, &self.undo, &self.redo); // And the coordinate systems that needed a missing datum grid, after every command. self.say_grid_notes(); + self.say_unplaced(); // A plugin's command waiting for its fetches answers `pending` and runs again when they // land: logged then, once. (Another command's `pending`, a download the web app makes, is // logged as it is asked for: nothing runs it again.) @@ -3060,6 +3066,40 @@ impl Session { if due { self.grid_notes_checked = Some(web_time::Instant::now()); self.say_grid_notes(); + self.say_unplaced(); + } + } + + /// Says, once for each version of a layer's geometry, that a layer held in another system + /// 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. + fn say_unplaced(&mut self) { + let mut said = Vec::new(); + let mut seen = std::collections::HashSet::new(); + 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 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() { + Ok(0) => {} + Ok(n) => said.push(format!( + "Map '{}', layer '{}': {n} 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.name, l.name + )), + Err(e) => said.push(format!("Map '{}', layer '{}' isn't drawn: {e}", map.name, l.name)), + } + } + } + // Layers gone are forgotten, so the map stays as small as the project. + self.unplaced_checked.retain(|id, _| seen.contains(id)); + for text in said { + self.notice(text, rustgis_data::diagnostics::Severity::Warning); } } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 5988950179..813abd0124 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -583,6 +583,29 @@ fn a_held_layers_offline_edits_sync_alike() { assert_eq!(after[1..], before[1..]); } +/// An offline map held in the source's own system, as the project keeps it, is compared with its +/// area's last synced copy as it is held: a feature not edited offline leaves a source edit made +/// since in place, and one edited offline replaces the source's. +#[test] +fn a_held_offline_map_keeps_the_sources_later_edits() { + let mut s = session(UTM); + s.run("offline.download", &json!({"name": "Field", "extent": [11.4, 48.6, 11.6, 48.8]})).unwrap(); + s.run("offline.open", &json!({"name": "Field"})).unwrap(); + s.run("edit.setValue", &json!({"layer": "Wells", "row": 1, "field": "n", "value": 99})).unwrap(); + s.run("map.activate", &json!({"name": "Map"})).unwrap(); + // The source's own edit, made after the download, of a feature the offline map left alone. + s.run("edit.setValue", &json!({"layer": "Wells", "row": 0, "field": "n", "value": 7})).unwrap(); + let returned = s.project.maps.iter().find(|m| m.name == "Field (offline)").unwrap().clone(); + assert_eq!(returned.layers.iter().find(|l| l.name == "Wells").unwrap().dataset.coord_crs(), UTM); + let ai = s.project.offline_areas.iter().position(|a| a.name == "Field").unwrap(); + crate::cmd::workspace::sync_area(&mut s, ai, &returned).unwrap(); + let wells = &s.map().layer_by_name("Wells").unwrap().dataset; + let n = wells.field_index("n").unwrap(); + assert_eq!(wells.value(0, n), &Cell::Int(7), "an unedited offline copy replaced the source's edit"); + assert_eq!(wells.value(1, n), &Cell::Int(99)); + assert_eq!(wells.coord_crs(), UTM); +} + /// A web scene leaves out, and says, a feature of a held layer with a place that can't be given /// in longitude/latitude, rather than failing the whole scene. #[test] @@ -609,3 +632,35 @@ fn a_web_scene_leaves_out_what_it_cannot_place() { "{said:?}" ); } + +/// A held layer's feature with a place that can't be given in longitude/latitude is drawn without +/// it, and that is said, once for each version of the layer's geometry; a layer whose places all convert +/// says 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 mark = s.notice_mark(); + let _ = s.run("select.clear", &Value::Null); + assert!(said_of(&s, mark).is_empty(), "{:?}", said_of(&s, mark)); + // Far beyond any place UTM 32N holds. + 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(); + 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_eq!( + said, + [ + "Map 'Map', layer 'Wells': 1 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" + ] + ); +} diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 2174b10ce6..1ef2f7b088 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -350,6 +350,11 @@ pub struct Layer { /// The coordinate system the cache was projected from ([`Dataset::coord_crs`]). #[serde(skip)] projected_crs: Option, + /// Its geometry in longitude/latitude for the globe, when held in another system + /// ([`Layer::lonlat_in`]): a slot of its own, so the globe and a flat projection (hit-testing, + /// snapping) don't evict each other. + #[serde(skip)] + lonlat: LonLatCopy, /// Allocation identities and byte totals, shared with render snapshots without retaining rows. #[serde(skip)] view_memory: view_memory::Cache, @@ -555,6 +560,7 @@ impl Layer { projected_rev: u64::MAX, projected_for: String::new(), projected_crs: None, + lonlat: LonLatCopy::default(), geometry_rev: 0, view_memory: Default::default(), geometry_kinds: Default::default(), @@ -747,6 +753,8 @@ impl Layer { self.view_memory .total(&self.dataset.features, &self.projected, &self.projected_extents, &self.thinned) .saturating_add(self.display_levels.iter().map(|d| d.bytes).sum::()) + // The globe's copy of a held layer, kept beside the flat projection. + .saturating_add(if self.lonlat.fits(self) { lod::cache_bytes(&self.lonlat.geoms) } else { 0 }) } /// Every feature of a streamed layer's source (up to the read limit), for tools and for @@ -1089,20 +1097,28 @@ impl Layer { &self.projected } - /// Its geometry in longitude/latitude, for the globe, which draws there: kept in the - /// projected geometry cache ([`Layer::projected_cache`]) under its own key, so it is converted - /// once, not every frame. Empty while its coordinates are longitude/latitude, as every layer's - /// are unless held in another system: the geometry is then drawn as it is. + /// Its geometry in longitude/latitude, for the globe, which draws there: kept in a cache of + /// its own beside the projected one ([`Layer::projected_cache`]), so it is converted once, not + /// every frame, and a flat projection made meanwhile (hit-testing, snapping) doesn't evict it. + /// Empty while its coordinates are longitude/latitude, as every layer's are unless held in + /// another system: the geometry is then drawn as it is. pub fn lonlat_in(&mut self) -> &[Option] { - const KEY: &str = "longitude/latitude"; - if self.dataset.coord_crs() == Crs::LonLat { + let crs = self.dataset.coord_crs(); + if crs == Crs::LonLat { return &[]; } - if !self.is_cached(KEY) { - self.display_levels.clear(); - self.fill_projected(KEY, |to_lonlat, g| Some(to_lonlat.geometry(g))); + 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 = self.dataset.features.rows().map(|r| Some(to_lonlat.as_ref()?.geometry(r.geometry()?))).collect(); + self.lonlat = LonLatCopy { geoms: std::sync::Arc::new(geoms), rev: self.geometry_rev, crs: Some(crs) }; } - &self.projected + &self.lonlat.geoms + } + + /// Its copy in longitude/latitude as [`Layer::lonlat_in`] last made it: empty when none is. + pub fn lonlat_cache(&self) -> &[Option] { + if self.lonlat.fits(self) { &self.lonlat.geoms } else { &[] } } /// Fills the projected geometry cache for `key` with `project` of each geometry, given the @@ -1292,6 +1308,7 @@ impl Layer { self.projected_rev = u64::MAX; self.projected_for.clear(); self.projected_crs = None; + self.lonlat = LonLatCopy::default(); } /// Takes the projected geometry cache `other` (a copy of this layer, such as one drawn off @@ -1321,6 +1338,9 @@ impl Layer { self.projected_for.clone_from(&other.projected_for); self.projected_crs = other.projected_crs; } + if other.lonlat.fits(other) { + self.lonlat = other.lonlat.clone(); + } let budget = self.lod_budget(); self.trim_thinned_levels(budget); let used: usize = self.thinned.iter().filter_map(|(_, c)| c.as_ref()).map(|c| lod::cache_bytes(c)).sum(); @@ -1339,6 +1359,12 @@ impl Layer { && self.projected_crs == Some(self.dataset.coord_crs()) } + /// Its geometry's revision, bumped by [`Layer::touch_geometry`]: what a check made once per + /// version of the geometry is keyed by. + pub fn geometry_rev(&self) -> u64 { + self.geometry_rev + } + /// Marks geometry as changed. pub fn touch_geometry(&mut self) { self.geometry_rev = self.geometry_rev.wrapping_add(1); @@ -3316,6 +3342,7 @@ impl Layer { projected_rev: _, projected_for: _, projected_crs: _, + lonlat: _, view_memory: _, geometry_kinds: _, geometry_rev: _, @@ -3371,6 +3398,22 @@ impl Layer { } } +/// 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)] +struct LonLatCopy { + geoms: std::sync::Arc>>, + rev: u64, + crs: Option, +} + +impl LonLatCopy { + /// Whether it is of `layer`'s rows as they are now. + fn fits(&self, layer: &Layer) -> bool { + self.crs == Some(layer.dataset.coord_crs()) && self.rev == layer.geometry_rev && self.geoms.len() == layer.dataset.features.len() + } +} + #[cfg(test)] mod tests { use super::*; @@ -4203,6 +4246,34 @@ mod tests { assert_eq!(lod::DISPLAY_BUILDS.get(), before + 4); } + /// A layer held in another system keeps its globe copy in longitude/latitude beside a flat + /// projection: hit-testing or snapping in Web Mercator doesn't make the globe convert it again. + #[test] + fn a_held_layers_globe_copy_and_flat_projection_are_kept_apart() { + let mut d = Dataset::new("held", GeometryType::Point, vec![]); + d.push(Some(Geometry::Point(Coord::new(11.5, 48.7))), vec![]); + d.hold_in(Crs::Epsg(32632)).unwrap(); + let mut l = Layer::new(1, d); + let before = l.view_cache_bytes(); + let globe = l.lonlat_in().as_ptr(); + assert!(l.view_cache_bytes() > before, "the globe copy is counted in the layer's cache memory"); + let Some(Geometry::Point(c)) = &l.lonlat_cache()[0] else { panic!("a point") }; + assert!((c.x - 11.5).abs() < 1e-9 && (c.y - 48.7).abs() < 1e-9, "{c:?}"); + l.projected(); + assert!(l.is_cached("mercator")); + assert_eq!(l.lonlat_in().as_ptr(), globe, "the flat projection evicted the globe copy"); + assert!(l.is_cached("mercator"), "the globe copy evicted the flat projection"); + // An edit makes both again; clearing the caches drops both. + l.touch_geometry(); + assert!(l.lonlat_cache().is_empty()); + assert!(!l.lonlat_in().is_empty()); + l.clear_cache(); + assert!(l.lonlat_cache().is_empty()); + // A layer in longitude/latitude has none: the globe draws its rows. + let mut plain = long_line(10); + assert!(plain.lonlat_in().is_empty()); + } + #[test] fn rejected_display_levels_are_not_rebuilt_on_unchanged_frames() { let flat = projection::Flat::Mercator; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 64968202d2..a1381ee1eb 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4736,7 +4736,7 @@ fn render_frame( // The globe draws the lon/lat geometry itself (a layer held in another system, its // copy in longitude/latitude); the flat map its Web Mercator copy. let geoms: Vec> = if globe.is_some() && ds_ptr.coord_crs() != rustgis_data::raster::Crs::LonLat { - layer.projected_cache().iter().map(Option::as_ref).collect() + layer.lonlat_cache().iter().map(Option::as_ref).collect() } else if globe.is_some() { ds_ptr.features.iter().map(|f| f.geometry.as_ref()).collect() } else if display_only { @@ -5996,7 +5996,7 @@ fn layer_masks( if ml.lonlat_in().is_empty() { ml.dataset.features.iter().filter_map(|f| f.geometry.as_ref()).for_each(&mut add); } else { - ml.projected_cache().iter().flatten().for_each(&mut add); + ml.lonlat_cache().iter().flatten().for_each(&mut add); } } else { ml.projected_in(flat, key).iter().flatten().for_each(&mut add); From bafe9e26de0f18d1e23f64e6d4ca495244ce42df Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 18:08:28 +0100 Subject: [PATCH 2/2] fix(crs): review: fewer conversions on held layers, one notice per kind, the globe copy adopted and counted once --- crates/data/src/lib.rs | 39 +++++++++++++++++--------- crates/engine/src/cmd/items.rs | 3 +- crates/engine/src/cmd/labels.rs | 3 +- crates/engine/src/cmd/sharing.rs | 3 +- crates/engine/src/cmd/stac_area.rs | 3 +- crates/engine/src/cmd/workspace.rs | 7 +++-- crates/engine/src/lib.rs | 36 ++++++++++++++++++------ crates/engine/src/tests/held_layers.rs | 16 +++++++---- crates/map/src/lib.rs | 23 +++++++++++---- 9 files changed, 93 insertions(+), 40 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 3acca359f0..36da5cf754 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -448,9 +448,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. The map draws none of a layer whose conversion fails (`Layer::projected_in`) and - /// doesn't say so yet: before a reader holds a file's own system (#2032 C2b), that needs a - /// notice, as AGENTS.md's "Never silent" asks. + /// converts. A place that can't be converted isn't drawn, and the session says so + /// ([`Dataset::unplaced_in_lonlat`]). pub fn coord_crs(&self) -> raster::Crs { self.held_in } @@ -492,8 +491,14 @@ impl Dataset { /// coordinate (NaN, infinite) stays as it is, for the edit to judge as it does today; refused, /// naming its system, when its system can't be converted or one of its places can't be. pub fn geometry_to_lonlat<'a>(&self, g: &'a Geometry) -> std::result::Result, String> { - let to = self.coord_crs().to(raster::Crs::LonLat)?; - Self::converted_to_lonlat(&to, g) + Self::geometry_to_lonlat_by(&self.lonlat_conversion()?, g) + } + + /// [`Dataset::geometry_to_lonlat`] by `to`, its [`Dataset::lonlat_conversion`] made once for + /// many geometries: refused, naming its system, when one of the geometry's places can't be + /// converted. + pub fn geometry_to_lonlat_by<'a>(to: &raster::Reprojection, g: &'a Geometry) -> std::result::Result, String> { + Self::converted_to_lonlat(to, g) .ok_or_else(|| format!("a place of this feature in {} can't be given in longitude/latitude", to.source().label())) } @@ -976,7 +981,9 @@ 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). + /// 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() { @@ -1039,15 +1046,20 @@ impl Dataset { /// `results`, a dataset in longitude/latitude made from this one (a tool's update of it), in /// its own coordinates: as it is while they are longitude/latitude, as every dataset's are /// today; otherwise each geometry written back as an edit is ([`Dataset::edit_from_lonlat`]), - /// its stored places kept as stored. Refused, naming the first feature, when one of its places - /// can't be held in its system. + /// its stored places kept as stored. Every stored place is read, but only those the results + /// read as are held, so what is held is as large as the results, not the layer. Refused, naming + /// the first feature, when one of its places can't be held in its system. pub fn results_from_lonlat(&self, mut results: Dataset) -> std::result::Result { if self.edits_in_lonlat() { return Ok(results); } let mut held = HeldPlaces::default(); - for g in self.features.iter().filter_map(|f| f.geometry.as_ref()) { - self.hold_places(g, None, &mut held); + 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()) { + self.hold_places(g, None, &mut held); + } } for f in &mut results.features { if let Some(g) = f.geometry.take() { @@ -1061,10 +1073,9 @@ impl Dataset { /// `merged`, its features in longitude/latitude as [`Dataset::in_lonlat`] gives them with some /// updated, added or left out (an offline area's sync), in its own coordinates: a feature whose /// id isn't in `changed` is taken as it holds it, not converted back; a changed one is written - /// back as [`Dataset::results_from_lonlat`] writes it: every stored place is read, but only - /// those the changes read as are held, so what is held is as large as the changes, not the - /// layer. As it is while its - /// coordinates are longitude/latitude, as every dataset's are today. + /// back as [`Dataset::results_from_lonlat`] writes it, holding only the stored places the + /// changes read as. As it is while its coordinates are longitude/latitude, as every dataset's + /// are today. pub fn merged_from_lonlat( &self, mut merged: Dataset, diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index c9a24a9b66..433062ed9f 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -1280,6 +1280,7 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result }; let mut mesh = Mesh { keep_lines, ..Mesh::default() }; let rows = l.visible_rows(); + let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; for (row, ft) in l.dataset.features.iter().enumerate() { if row.is_multiple_of(256) { rustgis_data::progress::check().map_err(|e| e.to_string())?; @@ -1287,7 +1288,7 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result // A feature with no geometry draws nothing, so its height is neither used nor reported. let Some(g) = ft.geometry.as_ref().filter(|_| rows.get(row) == Some(&true)) else { continue }; // Placed from longitude/latitude, whatever system the layer holds its coordinates in. - let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id))?; + let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id))?; // A height that isn't a finite number takes the default, and is counted. let height = match hf { Some(fi) => match l.dataset.value(row, fi).as_f64().filter(|h| h.is_finite()) { diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 707551d8b6..fa6e7e9434 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -867,13 +867,14 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { out_fields, ); let mut moved = Vec::new(); + let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; for (row, ft) in l.dataset.features.rows().enumerate() { if rows.get(row) != Some(&true) { continue; } // In longitude/latitude, as the annotation layer holds its points and moved labels are. let Some(g) = ft.geometry() else { continue }; - let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?; + let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?; let Some(at) = g.label_point() else { continue }; for (i, class) in matcher.classes_of(&l.dataset, row).filter(|(_, c)| c.visible) { let text = match by_text(i).and_then(|e| e.text_cut(&l.dataset, row)) { diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index d8f9241fd8..78d598baa2 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -515,6 +515,7 @@ fn styled_features(l: &Layer, budget: &mut usize) -> Result, String> let mut out = Vec::new(); // Its symbol by expression (no map scale: the page zooms on its own). let styler = l.styler(None); + let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; for (row, ft) in l.dataset.features.rows().enumerate() { if *budget == 0 { break; @@ -523,7 +524,7 @@ fn styled_features(l: &Layer, budget: &mut usize) -> Result, String> continue; } let Some(g) = ft.geometry() else { continue }; - let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?; + let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?; let sym = styler.symbol(row); let props: serde_json::Map = l.dataset.fields.iter().enumerate().map(|(i, f)| (f.name.clone(), json!(l.dataset.value(row, i).to_string()))).collect(); diff --git a/crates/engine/src/cmd/stac_area.rs b/crates/engine/src/cmd/stac_area.rs index 9c98b092da..ff14550dc4 100644 --- a/crates/engine/src/cmd/stac_area.rs +++ b/crates/engine/src/cmd/stac_area.rs @@ -159,9 +159,10 @@ fn selected(s: &Session, p: &Value) -> Result<(Vec, Vec), Stri } // In longitude/latitude, as a search area is, whatever system the layer holds them in. let mut geometries: Vec = Vec::new(); + let to = layer.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", layer.name))?; for f in layer.selection.iter().filter_map(|row| layer.dataset.features.row(*row)) { if let Some(g) = f.geometry() { - let g = layer.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", layer.name, f.id()))?; + let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", layer.name, f.id()))?; geometries.push(g.into_owned()); } } diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 69b913760b..2e546c341c 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -498,9 +498,12 @@ fn selected_lines(s: &Session, p: &Value, all: bool) -> Result>, }; // Sampled in longitude/latitude, whatever system the layer holds its coordinates in. let mut out: Vec> = Vec::new(); + let to = l.dataset.lonlat_conversion().map_err(|e| format!("{n}: {e}"))?; for f in rows.iter().filter_map(|r| l.dataset.features.row(*r)) { let Some(g) = f.geometry().filter(|g| matches!(g, Geometry::Line(_))) else { continue }; - if let Geometry::Line(parts) = &*l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{n}: feature {}: {e}", f.id()))? { + if let Geometry::Line(parts) = + &*rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{n}: feature {}: {e}", f.id()))? + { let v: Vec = parts.iter().flatten().copied().collect(); if v.len() >= 2 { out.push(v); @@ -901,7 +904,7 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - // the two aren't held in the same system. let unchanged_offline = |fid: u64, lonlat_base: Option<&&rustgis_data::Feature>, lonlat_now: &rustgis_data::Feature| match &raw { - Some((base, now)) => base.get(&fid).is_some_and(|b| now.get(&fid).is_some_and(|n| same_row(*b, *n))), + Some((raw_base, raw_now)) => raw_base.get(&fid).is_some_and(|b| raw_now.get(&fid).is_some_and(|n| same_row(*b, *n))), None => lonlat_base.is_some_and(|b| *b == lonlat_now), }; let same_as_last = match (&raw, &baseline) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 977aed3147..f3bfe5377d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3075,9 +3075,12 @@ impl Session { /// 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. + /// 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. fn say_unplaced(&mut self) { - let mut said = Vec::new(); + // 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()); let mut seen = std::collections::HashSet::new(); 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) { @@ -3088,17 +3091,34 @@ impl Session { } match l.dataset.unplaced_in_lonlat() { Ok(0) => {} - Ok(n) => said.push(format!( - "Map '{}', layer '{}': {n} 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.name, l.name - )), - Err(e) => said.push(format!("Map '{}', layer '{}' isn't drawn: {e}", map.name, l.name)), + Ok(n) => { + features += n; + partly.push(format!("map '{}', layer '{}' ({n})", map.name, l.name)); + } + Err(e) => undrawn.push(format!("map '{}', layer '{}': {e}", map.name, l.name)), } } } // Layers gone are forgotten, so the map stays as small as the project. self.unplaced_checked.retain(|id, _| seen.contains(id)); - for text in said { + 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 } + }; + if features > 0 { + let text = format!( + "{features} 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 ({})", + listed(&partly) + ); + self.notice(text, rustgis_data::diagnostics::Severity::Warning); + } + if !undrawn.is_empty() { + let text = format!( + "{} layer(s) aren't drawn, as their system can't be given in longitude/latitude: {}", + undrawn.len(), + listed(&undrawn) + ); self.notice(text, rustgis_data::diagnostics::Severity::Warning); } } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 813abd0124..750a600549 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -634,8 +634,8 @@ 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, once for each version of the layer's geometry; a layer whose places all convert -/// says nothing. +/// 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. #[test] fn a_held_layers_undrawable_features_are_said_once() { let mut s = session(UTM); @@ -650,9 +650,13 @@ fn a_held_layers_undrawable_features_are_said_once() { let _ = s.run("select.clear", &Value::Null); assert!(said_of(&s, mark).is_empty(), "{:?}", said_of(&s, mark)); // Far beyond any place UTM 32N holds. - 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(); + for name in ["Wells", "Roads"] { + let l = s.map_mut().layers.iter_mut().find(|l| l.name == name).unwrap(); + let far = Coord::new(1e12, 1e12); + let g = if name == "Wells" { Geometry::Point(far) } else { Geometry::Line(vec![vec![far, Coord::new(far.x + 1.0, far.y)]]) }; + l.dataset.push(Some(g), vec![]); + l.touch_geometry(); + } let mark = s.notice_mark(); let _ = s.run("select.clear", &Value::Null); let _ = s.run("select.clear", &Value::Null); @@ -660,7 +664,7 @@ fn a_held_layers_undrawable_features_are_said_once() { assert_eq!( said, [ - "Map 'Map', layer 'Wells': 1 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" + "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))" ] ); } diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 1ef2f7b088..5a3b9c32d7 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -754,7 +754,7 @@ impl Layer { .total(&self.dataset.features, &self.projected, &self.projected_extents, &self.thinned) .saturating_add(self.display_levels.iter().map(|d| d.bytes).sum::()) // The globe's copy of a held layer, kept beside the flat projection. - .saturating_add(if self.lonlat.fits(self) { lod::cache_bytes(&self.lonlat.geoms) } else { 0 }) + .saturating_add(if self.lonlat.fits(self) { self.lonlat.bytes } else { 0 }) } /// Every feature of a streamed layer's source (up to the read limit), for tools and for @@ -1110,8 +1110,10 @@ impl Layer { 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 = self.dataset.features.rows().map(|r| Some(to_lonlat.as_ref()?.geometry(r.geometry()?))).collect(); - self.lonlat = LonLatCopy { geoms: std::sync::Arc::new(geoms), rev: self.geometry_rev, crs: Some(crs) }; + let geoms: Vec> = + self.dataset.features.rows().map(|r| Some(to_lonlat.as_ref()?.geometry(r.geometry()?))).collect(); + let bytes = lod::cache_bytes(&geoms); + self.lonlat = LonLatCopy { geoms: std::sync::Arc::new(geoms), bytes, rev: self.geometry_rev, crs: Some(crs) }; } &self.lonlat.geoms } @@ -1316,6 +1318,11 @@ impl Layer { /// a pointer. Display-only results preserve this layer's exact cache; optional copies are /// trimmed to its remaining budget. False when the rows or source settings don't match. 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(); + } let fits = other.dataset.features.shares(&self.dataset.features) && other.geometry_rev == self.geometry_rev && (other.is_cached(&other.projected_for) || other.display_cache().is_some()) @@ -1338,9 +1345,6 @@ impl Layer { self.projected_for.clone_from(&other.projected_for); self.projected_crs = other.projected_crs; } - if other.lonlat.fits(other) { - self.lonlat = other.lonlat.clone(); - } let budget = self.lod_budget(); self.trim_thinned_levels(budget); let used: usize = self.thinned.iter().filter_map(|(_, c)| c.as_ref()).map(|c| lod::cache_bytes(c)).sum(); @@ -3403,6 +3407,8 @@ impl Layer { #[derive(Clone, Debug, Default)] struct LonLatCopy { geoms: std::sync::Arc>>, + /// Its size, counted once when it is made ([`Layer::view_cache_bytes`]). + bytes: usize, rev: u64, crs: Option, } @@ -4257,6 +4263,11 @@ mod tests { let before = l.view_cache_bytes(); let globe = l.lonlat_in().as_ptr(); assert!(l.view_cache_bytes() > before, "the globe copy is counted in the layer's cache memory"); + // A copy drawn only on the globe hands its copy back, with no flat projection to share. + let mut receiver = l.clone(); + receiver.clear_cache(); + receiver.adopt_cache(&l); + assert_eq!(receiver.lonlat_cache().as_ptr(), globe, "the globe copy wasn't adopted"); let Some(Geometry::Point(c)) = &l.lonlat_cache()[0] else { panic!("a point") }; assert!((c.x - 11.5).abs() < 1e-9 && (c.y - 48.7).abs() < 1e-9, "{c:?}"); l.projected();