From 813a5bb3f1636832cc0a5e820e4b745c31549a33 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 11:05:42 +0100 Subject: [PATCH 01/15] Keep layers in their own coordinate system and draw them directly (#2032 C2c) --- apps/rustgis-python/src/lib.rs | 22 +- crates/analysis/src/network.rs | 58 +++- crates/data/src/citygml/tests.rs | 4 +- crates/data/src/cityjson/tests.rs | 3 +- crates/data/src/citymodel.rs | 5 +- crates/data/src/dxf.rs | 13 +- crates/data/src/esripbf.rs | 12 +- crates/data/src/esripbf/tests.rs | 5 +- crates/data/src/export.rs | 7 +- crates/data/src/export/tests.rs | 5 +- crates/data/src/filegdb.rs | 19 +- crates/data/src/filegdb/tests.rs | 1 + crates/data/src/gml.rs | 34 +- crates/data/src/io.rs | 119 ++++--- crates/data/src/landxml.rs | 14 +- crates/data/src/lib.rs | 298 +++++++++++++----- crates/data/src/mapinfo.rs | 14 +- crates/data/src/publish.rs | 74 +++-- crates/data/src/raster/reproject.rs | 98 +++++- crates/data/src/sheets.rs | 2 +- crates/data/src/source/chunk_memory.rs | 19 +- crates/data/src/source/fgb.rs | 23 +- crates/data/src/source/geojson.rs | 25 +- crates/data/src/source/gpkg.rs | 13 +- crates/data/src/source/gpkg/edit.rs | 2 +- crates/data/src/source/gpkg_mem.rs | 18 +- crates/data/src/source/mod.rs | 56 +++- crates/data/src/source/mysql.rs | 2 +- crates/data/src/source/parquet.rs | 17 +- crates/data/src/source/shp.rs | 21 +- crates/data/src/source/sqlserver.rs | 2 +- crates/data/src/source/tests.rs | 53 +++- crates/data/src/sync.rs | 10 +- crates/data/tests/planetary_crs.rs | 4 +- crates/data/tests/projection_methods.rs | 4 + crates/engine/src/cmd/clipboard.rs | 64 ++-- crates/engine/src/cmd/design.rs | 105 +++--- crates/engine/src/cmd/field.rs | 7 +- crates/engine/src/cmd/gp.rs | 2 +- crates/engine/src/cmd/imagery.rs | 7 +- crates/engine/src/cmd/labels.rs | 5 + crates/engine/src/cmd/layer.rs | 11 +- crates/engine/src/cmd/plugins.rs | 8 +- crates/engine/src/cmd/qgis.rs | 9 +- crates/engine/src/cmd/select.rs | 5 +- crates/engine/src/cmd/stac_area.rs | 2 + crates/engine/src/cmd/workflows.rs | 26 +- crates/engine/src/geometry_calc.rs | 6 +- crates/engine/src/lib.rs | 16 + crates/engine/src/project.rs | 2 + crates/engine/src/tests.rs | 27 +- crates/engine/src/tests/held_layers.rs | 245 ++++++++++++++ crates/engine/tests/define_projection.rs | 7 +- .../engine/tests/portable_projects/reload.rs | 2 + crates/geolibre/src/lib.rs | 15 +- crates/geolibre/src/tests.rs | 23 +- crates/map/src/lib.rs | 204 ++++++++++-- crates/map/src/look.rs | 7 +- crates/map/src/projection.rs | 97 +++++- crates/map/src/source.rs | 27 +- crates/map/src/source/window.rs | 60 +++- crates/plugins/src/tools.rs | 1 + crates/render/src/block.rs | 4 +- crates/render/src/layout.rs | 2 + crates/render/src/lib.rs | 54 +++- crates/render/src/terrain/water.rs | 2 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/mapview.rs | 8 +- crates/ui-egui/src/vertexedit.rs | 2 +- crates/ui-egui/tests/define_projection.rs | 24 +- docs/comparison/index.md | 4 +- docs/user-guide/analysis.md | 5 +- docs/user-guide/data-formats.md | 8 +- docs/user-guide/maps.md | 7 +- 74 files changed, 1749 insertions(+), 439 deletions(-) diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index 91d4e51c8f..28372e9887 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -201,13 +201,23 @@ impl Engine { } let mut ds = rustgis_engine::data::Dataset::new(found.name.clone(), found.geometry_type(), found.dataset.fields.clone()); ds.zm_dropped = found.dataset.zm_dropped; - // Copied in longitude/latitude, the system a new dataset holds its coordinates in. + // Copied in longitude/latitude, the system a new dataset holds its coordinates in: + // exactly through WGS 84, as the whole layer's GeoJSON is, whatever map it is shown on. + // A layer whose system can't be converted fails only with a geometry to convert, as + // it did when each geometry was converted on its own. + let to = found.dataset.lonlat_conversion(); for r in found.selection.iter().filter_map(|&i| found.dataset.features.row(i)) { - let g = r - .geometry() - .map(|g| found.dataset.geometry_to_lonlat(g).map(std::borrow::Cow::into_owned)) - .transpose() - .map_err(|e| format!("{}: feature {}: {e}", found.name, r.id()))?; + let g = match r.geometry() { + Some(g) => { + let to = to.as_ref().map_err(|e| format!("{}: {e}", found.name))?; + Some( + rustgis_engine::data::Dataset::geometry_to_lonlat_by(to, g) + .map_err(|e| format!("{}: feature {}: {e}", found.name, r.id()))? + .into_owned(), + ) + } + None => None, + }; ds.push(g, r.values().cloned().collect()); } let text = rustgis_engine::data::io::to_geojson(&ds).to_string(); diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 16a2fe50a8..7a3679cc89 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -127,6 +127,10 @@ const GRAPH_CACHE_BYTES: usize = 256 << 20; struct CachedNetwork { features: Weak>, + /// The system the rows held their coordinates in, and the datum grids there were, when the + /// graph was built: a relabel (Define Projection keeps the rows) or a grid downloaded since + /// gives another graph from the same rows. + held: (rustgis_data::raster::Crs, u64), rows: Vec, cost_field: Option, graph: Arc, @@ -141,21 +145,37 @@ fn network_for( ds: &Dataset, rows: &[usize], cost_field: Option, +) -> Result, String> { + network_keyed(cache, ds, rows, cost_field, || Network::build(ds, rows, cost_field)) +} + +/// [`network_for`] kept under `ds`'s rows as it holds them (its system, and the datum grids +/// there are), the rows the graph stands for, and built by `build` only when the one kept isn't +/// theirs. +fn network_keyed( + cache: &Mutex>, + ds: &Dataset, + rows: &[usize], + cost_field: Option, + build: impl FnOnce() -> Result, ) -> Result, String> { crate::control::check()?; let features = ds.features.allocation_key(); + let held = (ds.coord_crs(), rustgis_data::raster::crs::grid_generation()); { let cached = cache.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(cached) = cached.as_ref().filter(|c| c.features.ptr_eq(&features) && c.rows == rows && c.cost_field == cost_field) { + if let Some(cached) = + cached.as_ref().filter(|c| c.features.ptr_eq(&features) && c.held == held && c.rows == rows && c.cost_field == cost_field) + { return Ok(cached.graph.clone()); } } // Build outside the lock: another run can check Cancel while this one builds its graph. - let graph = Arc::new(Network::build(ds, rows, cost_field)?); + let graph = Arc::new(build()?); let bytes = graph.bytes().saturating_add(rows.len().saturating_mul(size_of::())); crate::control::check()?; let mut cached = cache.lock().unwrap_or_else(|e| e.into_inner()); - *cached = (bytes <= GRAPH_CACHE_BYTES).then(|| CachedNetwork { features, rows: rows.to_vec(), cost_field, graph: graph.clone() }); + *cached = (bytes <= GRAPH_CACHE_BYTES).then(|| CachedNetwork { features, held, rows: rows.to_vec(), cost_field, graph: graph.clone() }); Ok(graph) } @@ -185,22 +205,46 @@ pub fn shortest_route( shortest_route_with(&NETWORK, ds, rows, from, to, cost_field, snap_m) } -/// Keeps endpoint validation, graph reuse and search on the same path for any cache owner. -fn shortest_route_with( - cache: &Mutex>, - ds: &Dataset, +/// [`shortest_route`] over `held`, a layer held in another system than longitude/latitude: the +/// graph is built from `lonlat`, the layer in longitude/latitude, only when the one kept isn't +/// for `held`'s rows as they are, and is kept under them. Later routes over the same layer then +/// reuse it without converting the layer again; the converted copy isn't kept. +pub fn shortest_route_held<'a>( + held: &Dataset, + lonlat: impl FnOnce() -> Result, String>, rows: &[usize], from: Coord, to: Coord, cost_field: Option, snap_m: f64, ) -> Result { + check_route_ends(from, to, snap_m)?; + let graph = network_keyed(&NETWORK, held, rows, cost_field, || Network::build(&*lonlat()?, rows, cost_field))?; + route_on(&graph, held, from, to, snap_m) +} + +/// Refuses a snap distance or route end a route can't be found from. +fn check_route_ends(from: Coord, to: Coord, snap_m: f64) -> Result<(), String> { if !snap_m.is_finite() { return Err("the snap distance must be finite".into()); } if [from, to].iter().any(|c| !c.is_finite() || c.y.abs() > 90.0) { return Err("a route end has invalid coordinates".into()); } + Ok(()) +} + +/// Keeps endpoint validation, graph reuse and search on the same path for any cache owner. +fn shortest_route_with( + cache: &Mutex>, + ds: &Dataset, + rows: &[usize], + from: Coord, + to: Coord, + cost_field: Option, + snap_m: f64, +) -> Result { + check_route_ends(from, to, snap_m)?; let graph = network_for(cache, ds, rows, cost_field)?; route_on(&graph, ds, from, to, snap_m) } diff --git a/crates/data/src/citygml/tests.rs b/crates/data/src/citygml/tests.rs index 51bdab95c4..4d2ea0dcdd 100644 --- a/crates/data/src/citygml/tests.rs +++ b/crates/data/src/citygml/tests.rs @@ -204,7 +204,7 @@ fn a_compound_system_is_read_by_its_horizontal_part() { let out = read("model.gml", &bytes, None).unwrap(); let ds = &out[0].0; assert_eq!(ds.crs, Some(Crs::Epsg(25832))); - let e = ds.extent(); + let e = ds.lonlat_extent(); assert!((e.min_x - 9.0).abs() < 0.01 && (e.min_y - 49.6).abs() < 0.1, "{e:?}"); // One naming another system is refused. let other = inner.replace("EPSG:25832", "EPSG:25833"); @@ -1055,7 +1055,7 @@ fn a_system_given_reads_the_coordinates_as_written() { let ground = square(500_000.0, 5_500_000.0, 10.0, 0.0); let bytes = model("urn:ogc:def:crs:EPSG::4258", &building("b1", &surface("GroundSurface", &[polygon("g", &ground)]))); let out = read("model.gml", &bytes, Some(Crs::Epsg(25832))).unwrap(); - let e = out[0].0.extent(); + let e = out[0].0.lonlat_extent(); assert!((e.min_x - 9.0).abs() < 0.01 && (e.min_y - 49.6).abs() < 0.1, "{e:?}"); // Latitude 10 to 12, longitude 0 to 4, given as the system the file names. let inner = surface("GroundSurface", &[polygon("g", "10 0 0 10 4 0 12 4 0 12 0 0 10 0 0")]); diff --git a/crates/data/src/cityjson/tests.rs b/crates/data/src/cityjson/tests.rs index 486d382ea0..1ca36f1d49 100644 --- a/crates/data/src/cityjson/tests.rs +++ b/crates/data/src/cityjson/tests.rs @@ -311,7 +311,8 @@ fn a_compound_system_is_read_by_its_horizontal_part() { for urn in ["https://www.opengis.net/def/crs/EPSG/0/7415", "urn:ogc:def:crs:EPSG::7415"] { v["metadata"]["referenceSystem"] = json!(urn); let out = read("m.city.json", v.to_string().as_bytes(), None).unwrap(); - let ds = &out[0].0; + // Held in its horizontal system; placed in longitude/latitude. + let ds = &out[0].0.in_lonlat().unwrap().into_owned(); let Some(Geometry::Polygon(p)) = geometry(ds, 0) else { panic!("{:?}", geometry(ds, 0)) }; let c = p[0][0][0]; assert!((c.x - 4.32).abs() < 0.05 && (c.y - 52.0).abs() < 0.05, "{urn}: {c:?}"); diff --git a/crates/data/src/citymodel.rs b/crates/data/src/citymodel.rs index 2a39f6b798..6506b046c5 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -566,8 +566,10 @@ pub(crate) fn finish( let to_lonlat = crs.transformer().map_err(|e| DataError::Format(format!("{file_name}: {e}")))?; let mut objects = HashSet::new(); for row in &mut rows { + // Kept as the file holds it, in its system, when it has a place in longitude/latitude + // (as `geometry_to_lonlat` would give it). if let Some(g) = row.geometry.take() { - row.geometry = crate::io::geometry_to_lonlat(&g, &to_lonlat); + row.geometry = crate::io::lonlat_box(&g, &to_lonlat).map(|_| g); if row.geometry.is_none() { (row.unconverted, row.draws) = (true, false); objects.insert(row.object); @@ -1060,6 +1062,7 @@ fn layers(stem: &str, rows: Vec, built: &[Built], crs: Crs, counts: &mut Co report.extrusion = Some(crate::SuggestedExtrusion { height_field: HEIGHT.into(), base_field: BASE_HEIGHT.into() }); } ds.crs = (crs != Crs::LonLat).then_some(crs); + ds.held_in = crs; ds.drop_zm(&mut report, z_dropped); out.push((ds, report)); } diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index c3f11dcb44..b5f8845a32 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1529,15 +1529,15 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result })?; any_geometry |= geometry.is_some(); with_zm += usize::from(geometry.is_some() && (has_z || has_m)); + // Kept as the answer holds it, in its own system, when it has a place in longitude/latitude + // (as `geometry_to_lonlat` would give it). let geometry = match (geometry, &to_lonlat) { (Some(g), Some(t)) => { - let g = crate::io::geometry_to_lonlat(&g, t); - unprojected += usize::from(g.is_none()); - g + let ok = crate::io::lonlat_box(&g, t).is_some(); + unprojected += usize::from(!ok); + ok.then_some(g) } (g, _) => g, }; @@ -361,6 +363,10 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result ds.geometry_type = layer_type; } ds.crs = crs; + // Held as the answer gives its coordinates, in its own system, when RustGIS converts it. + if let Some(c) = crs.filter(|_| to_lonlat.is_some()) { + ds.held_in = c; + } // What couldn't be converted can't come back by defining the projection again. ds.crs_incomplete = unprojected > 0; let losses = Losses { diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 05e9e61d53..2a7cc14fec 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -221,7 +221,8 @@ fn web_mercator_answers_are_turned_to_longitude_latitude() { feature(&[geometry(&[], &[1_113_195, 0])]), ]); let (ds, report) = read(&bytes, "t").unwrap(); - let Some(Geometry::Point(p)) = ds.features[0].geometry else { panic!("not a point") }; + assert_eq!(ds.held_in, Crs::WebMercator, "held as the answer gives it"); + let Some(Geometry::Point(p)) = ds.in_lonlat().unwrap().features[0].geometry else { panic!("not a point") }; assert!((p.x - 10.0).abs() < 1e-4 && p.y.abs() < 1e-9, "{p:?}"); assert_eq!(ds.crs, Some(Crs::WebMercator)); assert!(report.messages.is_empty()); @@ -458,7 +459,7 @@ fn a_wkts_own_shift_wins_over_its_wkid() { |reference: Vec| answer(&[message(8, &reference), transform(false, 1.0, xy.x, xy.y), feature(&[geometry(&[], &[0, 0])])]); let at = |bytes: &[u8]| { let (ds, report) = read(bytes, "t").unwrap(); - match &ds.features[0].geometry { + match &ds.in_lonlat().unwrap().features[0].geometry { Some(Geometry::Point(p)) => (*p, report.messages), g => panic!("{g:?}"), } diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 824ca311a9..520470dfa4 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -257,7 +257,12 @@ fn write_chunks_as( let mut utc_dates = Vec::new(); let mut fine_dates = Vec::new(); let mut written_values = Vec::new(); - let mut scratch = query.map(|expr| (expr, Cow::::Owned(layer.clone()))); + // Measured ($area, $length) in the system the source gives its features in. + let mut scratch = query.map(|expr| { + let mut input = layer.clone(); + input.held_in = held; + (expr, Cow::::Owned(input)) + }); let mut feed = |add: &mut dyn FnMut(&[Feature]) -> Result<()>| -> Result<()> { // A GeoPackage export that starts again feeds the features again, and counts them again. total = 0; diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 112a2eca04..2cd9d14752 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -173,7 +173,8 @@ fn a_streamed_web_mercator_export_counts_what_it_writes_at_85_degrees() { assert_eq!(e.beyond_web_mercator, n, ".{ext} in {}", crs.label()); // As many as the file holds at 85.05°. let mut at_edge = 0; - for g in read_back(&path).features.iter().filter_map(|f| f.geometry.as_ref()) { + let back = read_back(&path); + for g in back.in_lonlat().unwrap().features.iter().filter_map(|f| f.geometry.as_ref()) { g.for_each_coord(|c| at_edge += usize::from((c.y.abs() - rustgis_geom::MAX_LAT).abs() < 1e-6)); } assert_eq!(at_edge, n, ".{ext} in {}", crs.label()); @@ -687,7 +688,7 @@ fn a_streamed_export_is_written_from_the_system_its_source_gives() { assert_eq!(e.written, 302, "{name}"); // Northings in the millions: only the square at 86° N is past 85.05°. assert_eq!(e.beyond_web_mercator, beyond, "{name}"); - let p = first(&read_back(&d.join(name))); + let p = first(&read_back(&d.join(name)).in_lonlat().unwrap()); assert!((p.x - want.x).abs() < 1e-7 && (p.y - want.y).abs() < 1e-7, "{name}: {p:?} {want:?}"); } } diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 45999071af..f14b9aad65 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -354,6 +354,10 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result) -> Result report.skipped += 1, } } + // Kept as the file holds it, in its own system, when it has a place in longitude/latitude. let geometry = match (geometry, &to_lonlat) { (Some(g), Some(t)) => { - let g = to_lonlat_geometry(g, t); - unprojected += usize::from(g.is_none()); - g + let ok = crate::io::places_in_lonlat(&g, t); + unprojected += usize::from(!ok); + ok.then_some(g) } (g, _) => g, }; @@ -458,14 +463,6 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result Option { - let mut ok = true; - let out = g.map_coords(&|c| t.to_lonlat(c).unwrap_or(Coord::new(f64::NAN, f64::NAN))); - out.for_each_coord(|c: Coord| ok &= c.is_finite()); - ok.then_some(out) -} - // --------------------------------------------------------------------------------------------- // Bytes diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index d76b45126f..6845338e55 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -895,6 +895,7 @@ fn placement_cases_are_placed() { let layers = read_files(&files).unwrap(); let (ds, report) = &layers[0]; assert!(report.messages.is_empty(), "{what}: {:?}", report.messages); + let ds = ds.in_lonlat().unwrap().into_owned(); let Some(Geometry::Polygon(p)) = &ds.features[0].geometry else { panic!("{what}: {:?}", ds.features[0].geometry) }; // The corner at the point (stored to the millimetre) is within a centimetre of it. let off = p[0][0].iter().map(|c| metres_apart(*c, lonlat)).fold(f64::INFINITY, f64::min); diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 083cdc37cc..6a857c9d88 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -650,19 +650,33 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> let (zm, unread, parts) = (kind.zm, kind.unread, kind.parts_lost); let unread_names = kind.unread_names.said(); let (mut outside, mut null_text) = (false, Vec::new()); + // Held as the file holds its coordinates, in its own system (in the axis order RustGIS + // gives every system's), when RustGIS converts it. + if let Some((Some(_), _)) = &transform + && let Some((c, _)) = file_srs + { + ds.held_in = c; + } for (g, attrs) in kind.rows { let g = g.map(|g| match &transform { - Some((t, swap)) => g.map_coords(&|c| { - let c = if *swap { Coord::new(c.y, c.x) } else { c }; - match t { - Some(t) => t.to_lonlat(c).unwrap_or(Coord::new(f64::NAN, f64::NAN)), - None => c, - } - }), - None => g, + Some((_, true)) => g.map_coords(&|c| Coord::new(c.y, c.x)), + _ => g, }); if let Some(g) = &g { - let e = g.extent(); + // Its box in longitude/latitude: a place that can't be given there isn't drawn + // (the map counts it), as one converted to NaN wasn't. + let e = match &transform { + Some((Some(t), _)) => { + let mut e = rustgis_geom::Extent::EMPTY; + g.for_each_coord(|c| { + if let Some(l) = t.to_lonlat(c) { + e.expand(l); + } + }); + e + } + _ => g.extent(), + }; outside |= e.min_x < -180.0 || e.max_x > 180.0 || e.min_y < -90.0 || e.max_y > 90.0; } let row = ds @@ -848,6 +862,8 @@ mod tests { assert_eq!(layers.len(), 1); let (ds, rep) = &layers[0]; assert_eq!(ds.name, "s"); + // Held in its own system; placed in longitude/latitude. + let ds = ds.in_lonlat().unwrap().into_owned(); let Some(Geometry::Point(c)) = &ds.features[0].geometry else { panic!() }; assert!((c.x - 15.0).abs() < 1e-6 && (c.y - 42.0).abs() < 0.01, "{c:?}"); assert_eq!(rep.skipped, 1); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index bf550d1226..0edb2d94c7 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -617,10 +617,9 @@ pub fn default_export_note(ds: &Dataset, path: &str) -> Option { }) } -/// The dataset in `crs`'s coordinates, from the system it holds them in ([`Dataset::coord_crs`]: -/// longitude/latitude, as every dataset's are today), by the direct operation between the two -/// ([`Crs::to`]). A copy as it is when it holds them in `crs`. Fails on a coordinate the system -/// can't hold, naming its feature. +/// The dataset in `crs`'s coordinates, from the system it holds them in ([`Dataset::coord_crs`]), +/// by the direct operation between the two ([`Crs::to`]). A copy as it is when it holds them in +/// `crs`. Fails on a coordinate the system can't hold, naming its feature. pub fn project(ds: &Dataset, crs: Crs) -> Result { let from = ds.coord_crs(); if crs == from { @@ -659,23 +658,31 @@ pub(crate) fn project_each(features: &mut [crate::Feature], to: &crate::raster:: Ok(()) } -/// Defines the CRS of the dataset's native coordinates without changing those numeric values. -/// Geometry stored in longitude/latitude is converted back through the previous CRS, then -/// interpreted in the new one. Builds a copy so failed transformations leave the input intact. +/// Defines the CRS of the dataset's native coordinates without changing those numeric values: a +/// relabel. Its coordinates as the file held them (in the system it is held in, else the one it was +/// read in, [`Dataset::crs`], or longitude/latitude without one) are held in `crs` as they are; a +/// dataset held in longitude/latitude while it says another system (a project saved by an older +/// release) has its coordinates brought back to that system first. Refused when a place can't be +/// given in longitude/latitude from `crs`. Builds a copy so a refusal leaves the input intact. /// Source geometry discarded during import cannot be recovered this way. pub fn define_projection(ds: &Dataset, crs: Crs) -> Result { if ds.crs_incomplete { return Err(DataError::Format("geometry was lost during import; import the original file again with a crs override".into())); } - let from = ds.crs.unwrap_or(Crs::LonLat); - let native = project(ds, from)?; + // The system its numbers are in: the one it is held in, or, for a layer held in + // longitude/latitude, the one it was read in (a project saved by an older release). + let from = match ds.coord_crs() { + Crs::LonLat => ds.crs.unwrap_or(Crs::LonLat), + held => held, + }; + // As they are while held in the system it was read in, as a file read now is. + let mut out = project(ds, from)?; let to = crs.to(Crs::LonLat).map_err(DataError::Format)?; - let mut out = native; - for f in &mut out.features { - if let Some(g) = f.geometry.take() { - let g = to.geometry(&g); + for f in &out.features { + if let Some(g) = &f.geometry { + let lonlat = to.geometry(g); let mut valid = true; - g.for_each_coord(|c| valid &= c.is_finite() && c.x.abs() <= 180.0 && c.y.abs() <= 90.0); + lonlat.for_each_coord(|c| valid &= c.is_finite() && c.x.abs() <= 180.0 && c.y.abs() <= 90.0); if !valid { return Err(DataError::Format(format!( "feature {} can't be interpreted in {}; import the original file with a crs override", @@ -683,12 +690,9 @@ pub fn define_projection(ds: &Dataset, crs: Crs) -> Result { crs.label() ))); } - f.geometry = Some(g); } } - // Its coordinates read in `crs` and are held in longitude/latitude, as every dataset's are - // until #2032 C2 lets a layer hold its own system (defining one then only relabels it). - out.held_in = Crs::LonLat; + out.held_in = crs; out.crs = Some(crs); Ok(out) } @@ -1417,6 +1421,30 @@ pub(crate) fn geometry_to_lonlat(g: &Geometry, t: &crate::raster::Transformer) - ok.then_some(out) } +/// Whether every coordinate of `g`, in the system `t` converts, has a place in longitude/latitude +/// (a finite one): a reader keeps the geometry as the file holds it, held in its system +/// ([`Dataset::held_in`]), when it does, and leaves the feature's geometry out when it doesn't, +/// as one it couldn't convert. Each coordinate is converted to be checked, none is kept. +pub(crate) fn places_in_lonlat(g: &Geometry, t: &crate::raster::Transformer) -> bool { + let mut ok = true; + g.for_each_coord(|c: Coord| ok &= t.to_lonlat(c).is_some_and(|l| l.is_finite())); + ok +} + +/// The box in longitude/latitude of a geometry in the coordinates `t` converts, for a reader that +/// keeps the geometry as the file holds it: `None` where [`geometry_to_lonlat`] refuses it (a +/// coordinate that can't be converted, or comes out beyond longitude/latitude). Each coordinate +/// is converted to be checked, none is kept. +pub(crate) fn lonlat_box(g: &Geometry, t: &crate::raster::Transformer) -> Option { + let mut ok = true; + let mut out = rustgis_geom::Extent::EMPTY; + g.for_each_coord(|c: Coord| match t.to_lonlat(c) { + Some(l) if l.is_finite() && l.x.abs() <= 180.5 && l.y.abs() <= 90.5 => out.expand(l), + _ => ok = false, + }); + ok.then_some(out) +} + /// What takes a FeatureCollection's features as they're read. pub(crate) trait FeatureSink { /// The `"features"` member starts (again, when a document repeats it: the last one wins). @@ -1664,9 +1692,11 @@ impl Collector { for (n, (geom, values, had_z)) in self.features.into_iter().enumerate() { // A feature that can't be converted is dropped, and its id is not reused, as when the // file is read in place. + // Kept as the file holds it, in its declared system, when it has a place in + // longitude/latitude (as [`geometry_to_lonlat`] would give it). let geom = match (&declared, geom) { - (Some((_, t)), Some(g)) => match geometry_to_lonlat(&g, t) { - Some(g) => Some(g), + (Some((_, t)), Some(g)) => match lonlat_box(&g, t) { + Some(_) => Some(g), None => { unconverted += 1; continue; @@ -1689,6 +1719,7 @@ impl Collector { ds.geometry_type = dominant_type(&ds); if let Some((crs, _)) = &declared { ds.crs = Some(*crs); + ds.held_in = *crs; if unconverted > 0 { report.skipped += unconverted; report.messages.push(format!( @@ -2672,14 +2703,13 @@ pub(crate) fn read_rows( if let Some(c) = crs.filter(|c| *c != crate::raster::Crs::LonLat) { let t = c.transformer().map_err(DataError::Format)?; ds.crs = Some(c); + // Kept as the file holds them, in its system, where they have a place in longitude/latitude. + ds.held_in = c; let mut lost = 0usize; for f in &mut ds.features { if let Some(g) = f.geometry.take() { - let out = g.map_coords(&|p| t.to_lonlat(p).unwrap_or(Coord::new(f64::NAN, f64::NAN))); - let mut ok = true; - out.for_each_coord(|c| ok &= c.is_finite()); - if ok { - f.geometry = Some(out); + if places_in_lonlat(&g, &t) { + f.geometry = Some(g); } else { lost += 1; } @@ -3639,14 +3669,13 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio } g => g, }; + // Kept as the file holds it, in its own system, when it has a place in longitude/latitude. let geom = match (&to_lonlat, geom) { (Some(t), Some(g)) => { - let mut ok = true; - let out = g.map_coords(&|c| t.to_lonlat(c).unwrap_or(Coord::new(f64::NAN, f64::NAN))); - out.for_each_coord(|c| ok &= c.is_finite()); + let ok = places_in_lonlat(&g, t); converted += usize::from(ok); unconverted += usize::from(!ok); - ok.then_some(out) + ok.then_some(g) } (_, g) => g, }; @@ -3662,8 +3691,13 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio ds.geometry_type = source_kind; } integral_numeric_to_integer(&mut ds, &decimals); + // Held in its own system when it has one RustGIS converts; only coordinates read as + // longitude/latitude are checked for being so. + if let Some(c) = ds.crs.filter(|_| to_lonlat.is_some()) { + ds.held_in = c; + } let e = ds.extent(); - if !e.is_empty() && (e.min_x < -180.5 || e.max_x > 180.5 || e.min_y < -90.5 || e.max_y > 90.5) { + if to_lonlat.is_none() && !e.is_empty() && (e.min_x < -180.5 || e.max_x > 180.5 || e.min_y < -90.5 || e.max_y > 90.5) { report.messages.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place".into()); } if report.skipped > 0 { @@ -4553,7 +4587,7 @@ fn shapefile_geometry_losses(g: Option<&Geometry>, gt: GeometryType, drawable: f /// notice per kind with a count, or none: vertices with a missing (NaN) or infinite coordinate, /// and the line parts or polygon rings without enough vertices to draw. Features left out whole /// are [`left_out_note`]'s. In another system than the one the layer holds its coordinates in -/// ([`Dataset::coord_crs`], longitude/latitude today), the export writes the projected copy and +/// ([`Dataset::coord_crs`]), the export writes the projected copy and /// refuses a coordinate that doesn't project to a finite one ([`project`]), so every vertex it /// writes is drawable (an infinite latitude in Web Mercator is written at 85.05°), and only parts /// too short to draw are left out. `target` names what was written; line @@ -5619,6 +5653,9 @@ mod tests { CsvOptions { x: Some("e".into()), y: Some("N".into()), crs: Some(Crs::parse("EPSG:2263").unwrap()), ..CsvOptions::default() }; let (ds, rep) = read_csv_with(text, "t", &opts).unwrap(); assert_eq!(ds.geometry_type, GeometryType::Point); + // Held in the file's system; placed in longitude/latitude. + assert_eq!(ds.held_in, Crs::parse("EPSG:2263").unwrap()); + let ds = ds.in_lonlat().unwrap().into_owned(); let Some(Geometry::Point(c)) = &ds.features[0].geometry else { panic!() }; assert!((c.x + 73.96).abs() < 0.05 && (c.y - 40.78).abs() < 0.05, "{c:?}"); assert_eq!(rep.messages, ["1 rows had no usable coordinates"]); @@ -5639,7 +5676,7 @@ mod tests { let (ds, rep) = read_csv(text, "t").unwrap(); assert_eq!(ds.geometry_type, GeometryType::Polyline); assert_eq!(ds.fields.len(), 1); - let e = ds.features[0].geometry.as_ref().unwrap().extent(); + let e = ds.in_lonlat().unwrap().features[0].geometry.as_ref().unwrap().extent(); assert!((e.min_x - 15.0).abs() < 0.01 && (e.min_y - 42.0).abs() < 0.05, "{e:?}"); assert!(ds.features[3].geometry.is_none()); assert_eq!( @@ -5949,6 +5986,7 @@ mod tests { let (zip, _) = write_bytes_in(ds, "shp", Crs::WebMercator).unwrap(); let mut at_edge = 0; for (back, _) in read_zip(&format!("{name}.zip"), &zip).unwrap() { + let back = back.in_lonlat().unwrap(); for g in back.features.iter().filter_map(|f| f.geometry.as_ref()) { g.for_each_coord(|c| at_edge += usize::from((c.y.abs() - MAX_LAT).abs() < 1e-6)); } @@ -6090,7 +6128,7 @@ mod tests { let text = "X,Y,Longitude,Latitude\n1000,2000,-89.9,35.1\n"; let opts = CsvOptions { crs: Some(Crs::WebMercator), ..Default::default() }; let (ds, report) = read_csv_with(text, "projected", &opts).unwrap(); - let Some(Geometry::Point(p)) = ds.features[0].geometry else { panic!("point") }; + let Some(Geometry::Point(p)) = ds.in_lonlat().unwrap().features[0].geometry else { panic!("point") }; assert!((p.x - 0.00898315).abs() < 1e-7 && (p.y - 0.0179663).abs() < 1e-7); assert!(report.messages.is_empty()); for crs in [Crs::WebMercator, Crs::parse("EPSG:2263").unwrap(), Crs::parse("+proj=merc +datum=WGS84 +units=m").unwrap()] { @@ -6278,13 +6316,13 @@ mod tests { assert_eq!((columns.x.as_deref(), columns.y.as_deref()), (Some(x), Some(y))); let opts = CsvOptions { crs: Some(Crs::WebMercator), ..Default::default() }; let (dataset, report) = read_csv_with(&text, "projected", &opts).unwrap(); - let Some(Geometry::Point(point)) = dataset.features[0].geometry else { panic!("point") }; + let Some(Geometry::Point(point)) = dataset.in_lonlat().unwrap().features[0].geometry else { panic!("point") }; assert!((point.x - 1.0).abs() < 1e-10 && (point.y - 2.0).abs() < 1e-10, "{point:?}"); assert_eq!(report.skipped, 0); assert!(report.messages.is_empty(), "{:?}", report.messages); let opts = CsvOptions { x: Some("Longitude".into()), y: Some("Latitude".into()), ..opts }; let (explicit, _) = read_csv_with(&text, "explicit", &opts).unwrap(); - let Some(Geometry::Point(point)) = explicit.features[0].geometry else { panic!("point") }; + let Some(Geometry::Point(point)) = explicit.in_lonlat().unwrap().features[0].geometry else { panic!("point") }; assert!(point.x.abs() < 0.001 && point.y.abs() < 0.001, "explicit selection must win: {point:?}"); } } @@ -6940,7 +6978,8 @@ mod tests { // Paris in UTM zone 31N. w.write_shape_and_record(&shapefile::Point::new(451_219.33, 5_411_550.20), &r).unwrap(); } - let at = |ds: &Dataset| ds.features[0].geometry.as_ref().and_then(Geometry::label_point).unwrap(); + // In longitude/latitude, from the system the read holds it in. + let at = |ds: &Dataset| ds.in_lonlat().unwrap().features[0].geometry.as_ref().and_then(Geometry::label_point).unwrap(); // As ArcGIS and GDAL write it: Esri WKT with no EPSG authority. let prj = r#"PROJCS["WGS_1984_UTM_Zone_31N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",3.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]"#; @@ -7039,7 +7078,7 @@ mod tests { } std::fs::write(shp.with_extension("prj"), f[5]).unwrap(); let (ds, report) = read_path(&shp).unwrap(); - let c = ds.features[0].geometry.as_ref().and_then(Geometry::label_point).unwrap(); + let c = ds.in_lonlat().unwrap().features[0].geometry.as_ref().and_then(Geometry::label_point).unwrap(); assert!((c.x - lon).abs() < 1e-7 && (c.y - lat).abs() < 1e-7, "EPSG:{code}: {c:?}"); assert!(report.messages.is_empty(), "EPSG:{code}: {:?}", report.messages); } @@ -7228,7 +7267,7 @@ mod tests { let layers = read_zip_in("projected.zip", &zip, Some(crs)).unwrap(); assert_eq!(layers.len(), 2); for (table, report) in layers { - let point = table.features[0].geometry.as_ref().unwrap().label_point().unwrap(); + let point = table.in_lonlat().unwrap().features[0].geometry.as_ref().unwrap().label_point().unwrap(); assert!((point.x - 15.0).abs() < 1e-6 && (point.y - 42.0).abs() < 1e-6, "{point:?}"); assert_eq!(table.crs, Some(crs)); assert!(report.messages.is_empty(), "{:?}", report.messages); @@ -7466,7 +7505,7 @@ mod tests { assert_eq!(layers.len(), 2); let (ds, rep) = &layers[0]; assert_eq!(ds.name, "Paris"); - let c = ds.features[0].geometry.as_ref().and_then(Geometry::label_point).unwrap(); + let c = ds.in_lonlat().unwrap().features[0].geometry.as_ref().and_then(Geometry::label_point).unwrap(); assert!((c.x - 2.335).abs() < 1e-6 && (c.y - 48.855).abs() < 1e-6, "{c:?}"); assert!(rep.messages.iter().any(|m| m.contains("ne_VERSION.txt")), "{:?}", rep.messages); assert_eq!(ds.value(0, 0), &Value::Text("paris".into())); @@ -7969,7 +8008,7 @@ mod tests { write_path_in(&ds, &d.join("own.fgb"), utm).unwrap(); write_path_in(&ds, &d.join("lonlat.csv"), Crs::LonLat).unwrap(); for name in ["own.fgb", "lonlat.csv"] { - let read = read_path(&d.join(name)).unwrap().0; + let read = read_path(&d.join(name)).unwrap().0.in_lonlat().unwrap().into_owned(); let Some(Geometry::Point(p)) = read.features[0].geometry.clone() else { panic!("{name}: a point") }; assert!((p.x - lonlat.x).abs() < 1e-9 && (p.y - lonlat.y).abs() < 1e-9, "{name}: {p:?}"); } diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 78c106ab98..ebaf8786ff 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -227,14 +227,14 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result Deserialize<'de> for Features { } /// A feature class: a named table of features sharing a schema and geometry type. -/// Its geometry is in the system it holds its coordinates in ([`Dataset::held_in`]): WGS 84 -/// longitude/latitude for every dataset read or made today, including those of tools and -/// plugins (#2032 C2 lets readers hold a file's own system). +/// Its geometry is in the system it holds its coordinates in ([`Dataset::held_in`]): a file's +/// own system for a file read in one, WGS 84 longitude/latitude for one without, for features +/// drawn or made by tools and plugins, and for a saved project's. #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct Dataset { pub name: String, @@ -423,7 +423,8 @@ pub struct Dataset { #[serde(default)] pub source: Option, /// The coordinate system it was read in, when that isn't longitude/latitude: what an export - /// writes by default. Its geometry is in [`Dataset::held_in`], longitude/latitude today. + /// writes by default. Its geometry is in [`Dataset::held_in`], which is this system for a file + /// read now and longitude/latitude for one a saved project holds. #[serde(default, skip_serializing_if = "Option::is_none")] pub crs: Option, /// Import lost geometry while interpreting source coordinates. Defining a projection cannot @@ -443,6 +444,13 @@ pub struct Dataset { /// longitude/latitude, as older releases read them, so a saved dataset reads back held there. #[serde(skip, default = "held_in_lonlat")] pub held_in: raster::Crs, + /// The system of the map it is shown on, when that map draws it straight into its own system + /// (the map's `direct_system`, set by the map): its places are then given in + /// longitude/latitude for edits and drawing as that map shows them ([`Dataset::shown_conversion`]), + /// so a vertex handle or a new vertex lands on the line the map draws. `None` when it is shown + /// on no such map. + #[serde(skip)] + pub shown_in: Option, } /// What a dataset read from a project holds its coordinates in ([`Dataset::held_in`]). @@ -451,10 +459,9 @@ fn held_in_lonlat() -> raster::Crs { } impl Dataset { - /// The coordinate system its geometry is in ([`Dataset::held_in`]): longitude/latitude (WGS 84) - /// for every dataset read or made today, whatever system it was read in ([`Dataset::crs`]). - /// 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 + /// The coordinate system its geometry is in ([`Dataset::held_in`]): the system a file was read + /// in, else longitude/latitude (WGS 84). Drawing converts geometry from it + /// ([`raster::Crs::to`]). 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 (the map /// counts them as it draws, `Layer::unplaced`). @@ -462,6 +469,18 @@ impl Dataset { self.held_in } + /// Holds a dataset made in longitude/latitude from another (a command's output: a route, + /// simulated points, annotation) as that one is: in `held`, the system it holds its + /// coordinates in ([`Dataset::coord_crs`]), with `crs`, the one it was read in, which exports + /// use by default. Refused as [`Dataset::hold_in`] is, leaving it as it was: in + /// longitude/latitude with no system of its own, so Define Projection never takes its numbers + /// for another system's. + pub fn hold_as(&mut self, held: raster::Crs, crs: Option) -> std::result::Result<(), String> { + self.hold_in(held)?; + self.crs = crs; + Ok(()) + } + /// Converts its geometry into `crs` and holds it there ([`Dataset::held_in`]); a missing /// coordinate (NaN, infinite) stays as it is. Refused, naming the first feature, when its /// system can't be converted to `crs` or one of its places can't be held there (in Web @@ -498,11 +517,13 @@ impl Dataset { /// One of its geometries in longitude/latitude, the space edits work in (a vertex dragged to a /// place, a move on the ground): borrowed as it is while its coordinates are - /// longitude/latitude ([`Dataset::coord_crs`]), as every dataset's are today. A missing - /// coordinate (NaN, infinite) stays as it is, for the edit to judge as it does today; refused, + /// longitude/latitude ([`Dataset::coord_crs`]). A missing coordinate (NaN, infinite) stays as + /// it is, for the edit to judge; refused, /// naming its system, when its system can't be converted or one of its places can't be. + /// On a map that draws it straight into its own system ([`Dataset::shown_in`]), as that map + /// shows it ([`Dataset::shown_conversion`]). pub fn geometry_to_lonlat<'a>(&self, g: &'a Geometry) -> std::result::Result, String> { - Self::geometry_to_lonlat_by(&self.lonlat_conversion()?, g) + Self::geometry_to_lonlat_by(&self.shown_conversion()?, g) } /// [`Dataset::geometry_to_lonlat`] by `to`, its [`Dataset::lonlat_conversion`] made once for @@ -525,35 +546,33 @@ impl Dataset { } /// An edited geometry in longitude/latitude, written back in its own coordinates - /// ([`Dataset::coord_crs`]): as it is while they are longitude/latitude, as every dataset's are - /// today. A missing coordinate stays as it is; refused, naming its system, when one of its - /// places can't be held there. - pub fn geometry_from_lonlat(&self, g: Geometry) -> std::result::Result { - let to = raster::Crs::LonLat.to(self.coord_crs())?; - if to.is_identity() { - return Ok(g); - } - edit_into_own(&to, &g, &HeldPlaces::default()).ok_or_else(|| format!("the edit reaches a place {} can't hold", to.target().label())) - } - - /// An edit of its own places, as [`Dataset::geometry_from_lonlat`] writes it, except that a - /// place reading exactly as a held one in longitude/latitude ([`Dataset::hold_places`]) is - /// written as it is held, not converted back. An edit then moves only what it moved: the places + /// ([`Dataset::coord_crs`]): as it is while they are longitude/latitude. A missing coordinate + /// stays as it is; refused, naming its system, when one of its places can't be held there. On + /// a map that draws it straight into its own system ([`Dataset::shown_in`]), from + /// longitude/latitude as that map shows them ([`Dataset::shown_conversion`]). A place reading + /// exactly as a held one in longitude/latitude ([`Dataset::hold_places`]) is written as it is + /// held, not converted back. An edit then moves only what it moved: the places /// it left, or snapped to, stay exactly as stored, whatever a round trip through /// longitude/latitude would do to them (about a nanometre in UTM, but up to metres where a - /// projection's inverse is approximate, as Robinson's is). As it is while its coordinates are - /// longitude/latitude, as every dataset's are today. + /// projection's inverse is approximate, as Robinson's is). pub fn edit_from_lonlat(&self, g: Geometry, held: &HeldPlaces) -> std::result::Result { - let to = raster::Crs::LonLat.to(self.coord_crs())?; + Self::edit_from_lonlat_by(&self.shown_from_lonlat()?, g, held) + } + + /// [`Dataset::edit_from_lonlat`] by `to`, a conversion into its own coordinates: exact through + /// WGS 84 (`Crs::LonLat.to(coord_crs)`) for places that come from data rather than a map, such + /// as a tool's results ([`Dataset::results_from_lonlat`]) or a photo's position, or from + /// another system for pasted features. A place past 85.05° is refused when `to` is from + /// longitude/latitude into Web Mercator. + pub fn edit_from_lonlat_by(to: &raster::Reprojection, g: Geometry, held: &HeldPlaces) -> std::result::Result { if to.is_identity() { return Ok(g); } - edit_into_own(&to, &g, held).ok_or_else(|| format!("the edit reaches a place {} can't hold", to.target().label())) + edit_into_own(to, &g, held).ok_or_else(|| format!("the edit reaches a place {} can't hold", to.target().label())) } /// Whether an edit's places, given in longitude/latitude, are written as they are, with - /// nothing to hold ([`Dataset::hold_places`]): its coordinates are longitude/latitude, as every - /// dataset's are today. + /// nothing to hold ([`Dataset::hold_places`]): its coordinates are longitude/latitude. pub fn edits_in_lonlat(&self) -> bool { self.lonlat_conversion().is_ok_and(|to| to.is_identity()) } @@ -563,10 +582,45 @@ impl Dataset { /// ([`Dataset::edit_from_lonlat`]): those `within` a box in its coordinates, or all. Nothing /// while its coordinates are longitude/latitude; a place that can't be converted adds nothing. pub fn hold_places(&self, g: &Geometry, within: Option<&Extent>, held: &mut HeldPlaces) { - if let Ok(to) = self.lonlat_conversion() - && !to.is_identity() - { - held.add(&to, g, within); + if let Ok(to) = self.shown_conversion() { + Self::hold_places_by(&to, g, within, held); + } + } + + /// [`Dataset::hold_places`], each place read in longitude/latitude by `to`. + fn hold_places_by(to: &raster::Reprojection, g: &Geometry, within: Option<&Extent>, held: &mut HeldPlaces) { + if !to.is_identity() { + held.add(to, g, within); + } + } + + /// The map system its places are shown through ([`Dataset::shown_in`]), when the map draws it + /// there by a direct operation: `None` when it is shown on no such map, is in that system + /// itself or in longitude/latitude, or there is no direct operation between the two (the way + /// through WGS 84 then gives what the map draws). + fn shown_through(&self) -> Option { + let (own, map) = (self.coord_crs(), self.shown_in?); + let plain = |c: raster::Crs| matches!(c, raster::Crs::LonLat | raster::Crs::WebMercator); + (own != map && !plain(own) && !plain(map) && own.to(map).is_ok_and(|t| t.is_direct())).then_some(map) + } + + /// The conversion of its own coordinates to longitude/latitude for edits and drawing: as the + /// map it is shown on gives them ([`Dataset::shown_in`]: into the map's system by the direct + /// operation the map draws it with, then by the map's own inverse), else + /// [`Dataset::lonlat_conversion`]. Analysis and exports take [`Dataset::lonlat_conversion`], + /// which doesn't depend on a map. + pub fn shown_conversion(&self) -> std::result::Result { + match self.shown_through() { + Some(map) => self.coord_crs().to_via(map, raster::Crs::LonLat), + None => self.lonlat_conversion(), + } + } + + /// [`Dataset::shown_conversion`] the other way: longitude/latitude into its own coordinates. + pub fn shown_from_lonlat(&self) -> std::result::Result { + match self.shown_through() { + Some(map) => raster::Crs::LonLat.to_via(map, self.coord_crs()), + None => raster::Crs::LonLat.to(self.coord_crs()), } } @@ -600,11 +654,20 @@ impl Serialize for Dataset { st.serialize_field("geometry_type", &self.geometry_type)?; st.serialize_field("fields", &self.fields)?; let none: &[Feature] = &[]; - // In longitude/latitude, as every release reads a saved dataset's features. A place that - // can't be given there fails the save, naming its feature, rather than being saved - // wrong; `hold_in` only holds a dataset whose places all convert. - let lonlat = if self.windowed { None } else { Some(self.in_lonlat().map_err(serde::ser::Error::custom)?) }; - st.serialize_field("features", lonlat.as_ref().map_or(none, |d| d.features.as_slice()))?; + // In longitude/latitude, as every release reads a saved dataset's features: converted a + // row at a time as it is written, so a large layer held in another system isn't copied + // whole. A place that can't be given there fails the save, naming its feature, rather + // than being saved wrong; `hold_in` only holds a dataset whose places all convert. + if self.windowed { + st.serialize_field("features", none)?; + } else { + let to = self.lonlat_conversion().map_err(serde::ser::Error::custom)?; + if to.is_identity() { + st.serialize_field("features", self.features.as_slice())?; + } else { + st.serialize_field("features", &SavedInLonLat { ds: self, to })?; + } + } st.serialize_field("source", &self.source)?; if let Some(crs) = &self.crs { st.serialize_field("crs", crs)?; @@ -625,6 +688,52 @@ impl Serialize for Dataset { } } +/// A dataset's rows in longitude/latitude as [`Dataset::in_lonlat`] gives them, each converted as +/// it is written ([`Dataset`]'s `Serialize`), written as [`Feature`] writes itself. +struct SavedInLonLat<'a> { + ds: &'a Dataset, + to: raster::Reprojection, +} + +impl Serialize for SavedInLonLat<'_> { + fn serialize(&self, s: S) -> std::result::Result { + use serde::ser::{Error, SerializeSeq, SerializeStruct}; + struct Values<'a>(RowRef<'a>); + impl Serialize for Values<'_> { + fn serialize(&self, s: S) -> std::result::Result { + s.collect_seq(self.0.values()) + } + } + struct Row<'a>(RowRef<'a>, Option); + impl Serialize for Row<'_> { + fn serialize(&self, s: S) -> std::result::Result { + let mut st = s.serialize_struct("Feature", 3)?; + st.serialize_field("id", &self.0.id())?; + st.serialize_field("geometry", &self.1)?; + st.serialize_field("attrs", &Values(self.0))?; + st.end() + } + } + let mut seq = s.serialize_seq(Some(self.ds.features.len()))?; + for (i, r) in self.ds.features.rows().enumerate() { + stop_when_asked(i).map_err(S::Error::custom)?; + let geometry = match r.geometry() { + Some(g) => Some(convert_keeping_missing(&self.to, g, &HeldPlaces::default()).ok_or_else(|| { + S::Error::custom(format!( + "{}: feature {} has a place in {} that can't be given in longitude/latitude", + self.ds.name, + r.id(), + self.to.source().label() + )) + })?), + None => None, + }; + seq.serialize_element(&Row(r, geometry))?; + } + seq.end() + } +} + /// What a reader skipped. #[derive(Clone, Debug, Default, PartialEq)] pub struct ReadReport { @@ -916,6 +1025,7 @@ impl Dataset { zm_dropped: false, windowed: false, held_in: raster::Crs::LonLat, + shown_in: None, } } @@ -939,14 +1049,34 @@ impl Dataset { /// The box around its features' geometry in longitude/latitude: [`Dataset::extent`] through /// [`Dataset::extent_to_lonlat`]. pub fn lonlat_extent(&self) -> Extent { - self.extent_to_lonlat(&self.extent()) + self.lonlat_extent_of(self.features.rows().filter_map(RowRef::geometry)) + } + + /// The box in longitude/latitude around `geometries` (its own): exactly that of their places + /// there, each converted, as the readers of every release before #2032 C2 converted them, + /// not the converted box of their box (which a projection's grid, turned and curved against + /// longitude/latitude, makes larger). Their box itself while they are longitude/latitude; + /// a place that can't be converted is left out; empty when its system can't be converted. + pub fn lonlat_extent_of<'a>(&self, geometries: impl Iterator) -> Extent { + let Ok(to) = self.lonlat_conversion() else { return Extent::EMPTY }; + if to.is_identity() { + return geometries.fold(Extent::EMPTY, |e, g| e.union(&g.extent())); + } + let mut out = Extent::EMPTY; + for g in geometries { + g.for_each_coord(|c| { + if let Some(l) = to.point(c) { + out.expand(l); + } + }); + } + out } /// A box in its own coordinates ([`Dataset::coord_crs`]) in longitude/latitude, as - /// [`raster::Reprojection::extent`] converts it. The box itself while they are longitude/latitude, - /// as every dataset's are today. Empty when its system can't be converted. Longitude/latitude - /// never fails to; before [`Dataset::coord_crs`] returns another system, that case needs a - /// notice, as it says. + /// [`raster::Reprojection::extent`] converts it. The box itself while they are + /// longitude/latitude. Empty when its system can't be converted (the map then draws none of + /// it, and the session says so). pub fn extent_to_lonlat(&self, e: &Extent) -> Extent { match self.coord_crs().to(raster::Crs::LonLat) { Ok(to) => to.extent(e), @@ -955,8 +1085,9 @@ impl Dataset { } /// The conversion of its own coordinates ([`Dataset::coord_crs`]) to longitude/latitude, for - /// places taken from its geometry one by one: the identity today. Fails as - /// [`raster::Crs::to`] does, which longitude/latitude never does. + /// places taken from its geometry one by one, exact through WGS 84 whatever map it is shown + /// on: the identity while they are longitude/latitude. Fails as [`raster::Crs::to`] does, + /// which longitude/latitude never does. pub fn lonlat_conversion(&self) -> std::result::Result { self.coord_crs().to(raster::Crs::LonLat) } @@ -965,7 +1096,7 @@ impl Dataset { /// ([`Geometry::wgs84_measure`]) from its own coordinates; refused as /// [`Dataset::geometry_to_lonlat`] refuses. pub fn wgs84_measure(&self, g: &Geometry, m: Measure) -> std::result::Result, String> { - Ok(self.geometry_to_lonlat(g)?.wgs84_measure(m)) + Ok(Self::geometry_to_lonlat_by(&self.lonlat_conversion()?, g)?.wgs84_measure(m)) } /// [`ambiguous_area_message`] for these of its geometries, read in longitude/latitude, where a @@ -973,11 +1104,14 @@ impl Dataset { /// can't be measured either. pub fn ambiguous_area_message<'a>(&self, geometries: impl Iterator) -> Option { let unplaced = std::cell::Cell::new(0usize); - let ambiguous = ambiguous_area_message(geometries.filter_map(|g| match self.geometry_to_lonlat(g) { - Ok(g) => Some(g), - Err(_) => { - unplaced.set(unplaced.get() + 1); - None + let to = self.lonlat_conversion(); + let ambiguous = ambiguous_area_message(geometries.filter_map(|g| { + match to.as_ref().map_err(String::clone).and_then(|to| Self::geometry_to_lonlat_by(to, g)) { + Ok(g) => Some(g), + Err(_) => { + unplaced.set(unplaced.get() + 1); + None + } } })); let unplaced = (unplaced.get() > 0).then(|| { @@ -990,10 +1124,10 @@ impl Dataset { } /// 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 - /// the first feature that can't be, when one of its places can't be converted. The copy is - /// held in longitude/latitude ([`Dataset::held_in`]), so it isn't converted again. + /// coordinates are longitude/latitude ([`Dataset::coord_crs`]); otherwise a copy with every + /// geometry converted, missing coordinates kept. Refused, naming the first feature that can't + /// be, when one of its places can't be converted. The copy is held in longitude/latitude + /// ([`Dataset::held_in`]), so it isn't converted again. pub fn in_lonlat(&self) -> std::result::Result, String> { let to = self.lonlat_conversion()?; if to.is_identity() { @@ -1020,8 +1154,8 @@ impl Dataset { /// A longitude/latitude box in its own coordinates ([`Dataset::coord_crs`]), as /// [`raster::Reprojection::extent`] converts it: for asking which features a box reaches, once - /// for the box rather than once a feature. The box itself while they are longitude/latitude, - /// as every dataset's are today. A box partly outside what its system holds gives the box of + /// for the box rather than once a feature. The box itself while they are + /// longitude/latitude. A box partly outside what its system holds gives the box of /// the part that converts, as [`raster::Reprojection::extent`] does; unlike a streamed source's /// `extent_from_lonlat`, it isn't refused. Empty when its system can't be converted, which /// longitude/latitude never fails to be (see [`Dataset::extent_to_lonlat`]). @@ -1033,13 +1167,16 @@ 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. 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. + /// its own coordinates: as it is while they are longitude/latitude; otherwise each geometry + /// written back as an edit is ([`Dataset::edit_from_lonlat`]), 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() { + // Exact through WGS 84 both ways, as the results were read (`in_lonlat`), whatever map + // the layer is shown on. + let (read, write) = (self.lonlat_conversion()?, raster::Crs::LonLat.to(self.coord_crs())?); + if read.is_identity() { return Ok(results); } let mut held = HeldPlaces::default(); @@ -1048,7 +1185,7 @@ impl Dataset { 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); + Self::hold_places_by(&read, g, None, &mut held); } } // Before the rows are copied out of what shares them. @@ -1056,7 +1193,8 @@ impl Dataset { 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))?); + f.geometry = + Some(Self::edit_from_lonlat_by(&write, g, &held).map_err(|e| format!("{}: feature {}: {e}", self.name, f.id))?); } } results.held_in = self.held_in; @@ -1067,14 +1205,14 @@ impl Dataset { /// 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, holding only the stored places the - /// changes read as. As it is while its coordinates are longitude/latitude, as every dataset's - /// are today. + /// changes read as. As it is while its coordinates are longitude/latitude. pub fn merged_from_lonlat( &self, mut merged: Dataset, changed: &std::collections::HashSet, ) -> std::result::Result { - if self.edits_in_lonlat() { + let (read, write) = (self.lonlat_conversion()?, raster::Crs::LonLat.to(self.coord_crs())?); + if read.is_identity() { return Ok(merged); } let own: std::collections::HashMap = self.features.iter().map(|f| (f.id, f)).collect(); @@ -1089,7 +1227,7 @@ impl Dataset { 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); + Self::hold_places_by(&read, g, None, &mut held); } } // Before the rows are copied out of what shares them. @@ -1098,7 +1236,8 @@ impl Dataset { 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))?); + f.geometry = + Some(Self::edit_from_lonlat_by(&write, g, &held).map_err(|e| format!("{}: feature {}: {e}", self.name, f.id))?); } } else if let Some(o) = own.get(&f.id) { f.geometry = o.geometry.clone(); @@ -1297,6 +1436,21 @@ fn convert_keeping_missing(to: &raster::Reprojection, g: &Geometry, held: &HeldP mod tests { use super::*; + /// A layer made from another is held as that one is, with its system for exports; one with a + /// place the system can't hold stays in longitude/latitude with no system of its own. + #[test] + fn a_layer_made_from_another_is_held_as_it_is() { + let utm = raster::Crs::Epsg(32632); + let mut ds = Dataset::new("made", GeometryType::Point, vec![]); + ds.push(Some(Geometry::Point(Coord::new(11.5, 48.7))), vec![]); + ds.hold_as(utm, Some(utm)).unwrap(); + assert_eq!((ds.coord_crs(), ds.crs), (utm, Some(utm))); + let mut polar = Dataset::new("polar", GeometryType::Point, vec![]); + polar.push(Some(Geometry::Point(Coord::new(11.5, 89.0))), vec![]); + assert!(polar.hold_as(raster::Crs::WebMercator, Some(raster::Crs::WebMercator)).is_err()); + assert_eq!((polar.coord_crs(), polar.crs), (raster::Crs::LonLat, None)); + } + /// A dataset held in another system converts into it, and back, at the same places; one /// reaching past where Web Mercator ends, or a window onto a source read in place, is refused /// and left as it was. diff --git a/crates/data/src/mapinfo.rs b/crates/data/src/mapinfo.rs index 3913f23778..cddb2cdf0b 100644 --- a/crates/data/src/mapinfo.rs +++ b/crates/data/src/mapinfo.rs @@ -382,15 +382,18 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe } }, }; + // Held as the file holds its coordinates, in its own system, when RustGIS converts it. + if let (Some(_), Some(c)) = (&t, crs) { + ds.held_in = c; + } let (mut lost, mut null_text) = (0usize, Vec::new()); for (k, g) in geoms.into_iter().enumerate() { + // Kept as the file holds it when it has a place in longitude/latitude. let g = match (&t, g) { (Some(t), Some(g)) => { - let out = g.map_coords(&|c| t.to_lonlat(c).unwrap_or(Coord::new(f64::NAN, f64::NAN))); - let mut ok = true; - out.for_each_coord(|c| ok &= c.is_finite()); + let ok = crate::io::places_in_lonlat(&g, t); lost += usize::from(!ok); - ok.then_some(out) + ok.then_some(g) } (_, g) => g, }; @@ -504,6 +507,8 @@ mod tests { fn projected_and_broken() { let utm = "Version 300\nCoordSys Earth Projection 8, 104, \"m\", 15, 0, 0.9996, 500000, 0\nColumns 1\n id Integer\nData\nPoint 500000 4649776\nPoint 500100 x\n"; let (ds, rep) = read(utm, None, "u").unwrap(); + // Held in its own system; placed in longitude/latitude. + let ds = ds.in_lonlat().unwrap().into_owned(); let Some(Geometry::Point(c)) = &ds.features[0].geometry else { panic!() }; assert!((c.x - 15.0).abs() < 1e-6 && (c.y - 42.0).abs() < 0.01, "{c:?}"); assert_eq!(ds.features.len(), 1); @@ -524,6 +529,7 @@ mod tests { // The same point in feet: the false easting is in feet too, and PROJ wants metres. let ft = "CoordSys Earth Projection 8, 104, \"ft\", 15, 0, 0.9996, 1640416.6667, 0\nData\nPoint 1640416.6667 15255170.6\n"; let (ds, rep) = read(ft, None, "f").unwrap(); + let ds = ds.in_lonlat().unwrap().into_owned(); let Some(Geometry::Point(c)) = &ds.features[0].geometry else { panic!("{rep:?}") }; assert!((c.x - 15.0).abs() < 1e-6 && (c.y - 42.0).abs() < 0.01, "{c:?}"); // A datum not read keeps the coordinates as they are, and says so. diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index fcb7da4688..2cf0dcbc84 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -300,19 +300,27 @@ 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 }) { + // Compared as they are when the layer holds its coordinates in the system the file is read + // back in (its own): written unconverted, they read back exactly. Otherwise both in + // longitude/latitude, so compared alike whatever systems the two hold them in. + fn lonlat<'d>(d: &'d Dataset, path: &Path) -> Result> { + d.in_lonlat().map_err(|e| match DataError::of_conversion(e) { + DataError::Format(e) => refused(path, e), + cancelled => cancelled, + }) + } + let systems_differ = ds.coord_crs() != read_back.coord_crs(); + let (layer, back) = if systems_differ { + (lonlat(ds, path)?, lonlat(&read_back, path)?) + } else { + (std::borrow::Cow::Borrowed(ds), std::borrow::Cow::Borrowed(&read_back)) + }; + let projected = crs.is_some() && systems_differ; + if let Some(why) = same_rows(&layer, &back, if projected { PROJECTED_TOLERANCE } else { 0.0 }) { return Err(refused(path, format!("the file couldn't hold the layer as it is: {why}"))); } - if crs.is_some() - && let Some(note) = projection_note(&in_lonlat, &read_back)? - { + if projected && let Some(note) = projection_note(&layer, &back)? { notes.push(format!("{}: {note}", path.display())); } @@ -413,6 +421,19 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result(ds: &'a Dataset, crs: Option, as_held: Option<(&Dataset, &Dataset)>) -> Result> { + // A native shape the read couldn't place (left without geometry) can't be told apart from a + // feature without one, whatever system the layer holds its coordinates in. + if let Some((read, raw)) = as_held { + for (i, (f, r)) in read.features.iter().zip(raw.features.iter()).enumerate() { + crate::progress::check()?; + if f.geometry.is_none() && r.geometry.is_some() { + return Err(DataError::Format(format!( + "source shape {} couldn't be converted to longitude/latitude, so its native geometry can't be matched safely; check the source projection and add the file again; nothing was written", + i + 1 + ))); + } + } + } // From the system the layer holds its coordinates in: as they are when that is the file's. let (c, from) = (crs.unwrap_or(Crs::LonLat), ds.coord_crs()); if c == from { @@ -421,9 +442,15 @@ fn in_file<'a>(ds: &'a Dataset, crs: Option, as_held: Option<(&Dataset, &Da let t = from.to(c).map_err(DataError::Format)?; // The file as read is matched by its longitude/latitude: only a layer held in them is. let as_held = as_held.filter(|_| from == Crs::LonLat); - let (read, raw): (Vec<&Feature>, Vec<&Feature>) = match as_held { - Some((read, raw)) => (read.features.iter().collect(), raw.features.iter().collect()), - None => (Vec::new(), Vec::new()), + // The file as read, in longitude/latitude as the layer reads it (converted from the file's + // own system by the conversion that gave the layer its copy). + let read_in_lonlat = match as_held { + Some((read, _)) => Some(read.in_lonlat().map_err(DataError::of_conversion)?), + None => None, + }; + let (read, raw): (Vec<&Feature>, Vec<&Feature>) = match (&read_in_lonlat, as_held) { + (Some(read), Some((_, raw))) => (read.features.iter().collect(), raw.features.iter().collect()), + _ => (Vec::new(), Vec::new()), }; // File reads number rows anew; persistent layer ids can have gaps after a deletion. // Exact geometry keys retain correspondence without trusting those regenerated ids. @@ -431,12 +458,6 @@ fn in_file<'a>(ds: &'a Dataset, crs: Option, as_held: Option<(&Dataset, &Da let mut at: std::collections::HashMap, (usize, bool)> = std::collections::HashMap::new(); for (i, f) in read.iter().enumerate() { crate::progress::check()?; - if f.geometry.is_none() && raw.get(i).is_some_and(|f| f.geometry.is_some()) { - return Err(DataError::Format(format!( - "source shape {} couldn't be converted to longitude/latitude, so its native geometry can't be matched safely; check the source projection and add the file again; nothing was written", - i + 1 - ))); - } at.entry(key(f)?) .and_modify(|(first, ambiguous)| *ambiguous |= raw.get(*first).zip(raw.get(i)).is_some_and(|(a, b)| a.geometry != b.geometry)) .or_insert((i, false)); @@ -1703,9 +1724,12 @@ mod tests { } /// A publish whose read-back has projection round-off says so through `shapefile()`, on any - /// platform. Whether a given move's round trip is exact is up to the libm, so several are - /// tried in each system: each gives the note exactly when its read-back differs, and at least - /// one must, or the noted publish went untested. + /// platform: a layer held in longitude/latitude (as a project saved by an older release keeps + /// its copy), whose moves are converted into the file's system. Whether a given move's round + /// trip is exact is up to the libm, so several are tried in each system: each gives the note + /// exactly when its read-back differs, and at least one must, or the noted publish went + /// untested. A layer held in the file's system, as one read now is, writes its coordinates as + /// they are. #[test] fn a_publish_with_projection_round_off_says_so() { let dir = tempfile::tempdir().unwrap(); @@ -1717,7 +1741,9 @@ mod tests { let mut ds = parcels(); ds.crs = Some(crs); crate::io::write_path_in(&ds, &path, crs).unwrap(); - let (mut ds, sync) = read(&path); + let (native, sync) = read(&path); + assert_eq!(native.held_in, crs, "{code}: read in the file's own system"); + let mut ds = native.in_lonlat().unwrap().into_owned(); let mut rows: Vec<_> = ds.features.iter().cloned().collect(); if let Some(Geometry::Polygon(polys)) = &mut rows[1].geometry { polys[0][0][1].y += dy; @@ -1725,7 +1751,7 @@ mod tests { ds.features = rows.into(); let published = shapefile(&ds, &path, &sync).unwrap(); let (back, _) = read(&path); - let off = differing(&ds, &back); + let off = differing(&ds, &back.in_lonlat().unwrap()); assert!(off.is_empty() || off == [2], "{code} {dy}: unedited shapes changed: {off:?}"); assert_eq!(published.notes.len(), usize::from(!off.is_empty()), "{code} {dy}: {:?}", published.notes); if let Some(note) = published.notes.first() { diff --git a/crates/data/src/raster/reproject.rs b/crates/data/src/raster/reproject.rs index 53f5d46d1c..5e477e797e 100644 --- a/crates/data/src/raster/reproject.rs +++ b/crates/data/src/raster/reproject.rs @@ -31,6 +31,9 @@ pub struct Reprojection { /// The direct operation between the two, when neither is longitude/latitude or Web Mercator /// and terrio-crs has one. direct: Option>, + /// Two conversions one after the other, through a system between ([`Crs::to_via`]); the + /// fields above are then unused. + through: Option>, } impl Crs { @@ -51,7 +54,28 @@ impl Crs { (Some(a), Some(b)) => DirectPair::new(self, other, a, b).map(std::sync::Arc::new), _ => None, }; - Ok(Reprojection { source: self, target: other, unproject, project, direct }) + Ok(Reprojection { source: self, target: other, unproject, project, direct, through: None }) + } + + /// The conversion of coordinates in this system to `other`'s through `via`: this system's to + /// `via` ([`Crs::to`], the direct operation where there is one), then `via`'s to `other`. A + /// map in `via` shows a layer in this system by the first, and gives its places in + /// longitude/latitude by the second, so a place converted this way and drawn on that map + /// lands where the layer's own place is drawn. Where `via` is either end, or the two ends are + /// the same system, it is [`Crs::to`]. + pub fn to_via(self, via: Crs, other: Crs) -> Result { + if via == self || via == other || self == other { + return self.to(other); + } + let (first, second) = (self.to(via)?, via.to(other)?); + Ok(Reprojection { + source: self, + target: other, + unproject: None, + project: None, + direct: None, + through: Some(std::sync::Arc::new((first, second))), + }) } } @@ -71,6 +95,12 @@ impl Reprojection { self.source == self.target } + /// Whether it takes the direct operation between its two systems where it can (see the + /// module's notes), not only the way through WGS 84. + pub fn is_direct(&self) -> bool { + self.direct.is_some() + } + /// A place in the target system, or `None` where the source system has no such place or the /// target can't hold it. Each system's transformer judges what it is given, as a call of its /// own did: Web Mercator takes a latitude past 85.05° (an infinite one too) as 85.05°, where @@ -78,6 +108,9 @@ impl Reprojection { /// is finite. Between two other systems, the direct operation's coordinates of a place the way /// through WGS 84 converts, else those through WGS 84 (see the module's notes). pub fn point(&self, c: Coord) -> Option { + if let Some(through) = &self.through { + return through.1.point(through.0.point(c)?); + } let lonlat = match &self.unproject { Some(t) => t.to_lonlat(c)?, None => c, @@ -92,6 +125,13 @@ impl Reprojection { Some(self.direct.as_ref().and_then(|d| d.point(c, out)).unwrap_or(out)) } + /// The place `c` in the target system when `via` is where the way through WGS 84 puts it in + /// the target, as a caller with its own checks there found it (the map's projection): the + /// direct operation's coordinates where it has one that lands near `via`, else `via`. + pub fn point_near(&self, c: Coord, via: Coord) -> Coord { + self.direct.as_ref().and_then(|d| d.point(c, via)).unwrap_or(via) + } + /// A copy of `g` in the target system, its places that can't be converted NaN (which drawing /// skips; [`Reprojection::whole_geometry`] refuses them). Between the same system, `g` exactly /// as it is, a coordinate that isn't finite included. @@ -125,8 +165,34 @@ impl Reprojection { } out } + + /// [`Reprojection::extent`] for a feature's box, as a frame tests each feature's against the + /// view distance: a point's box by its one place, a small box by its corners and edges' + /// middles (3 by 3 places, not 17 by 17). A box whose converted size is more than + /// [`FEATURE_EXTENT_FINE`] in either axis (about 10 km in degrees), where edges bend enough to + /// matter, is converted as [`Reprojection::extent`] converts it. Empty where none of the + /// places converts. + pub fn feature_extent(&self, e: &Extent) -> Extent { + if self.is_identity() || e.is_empty() { + return *e; + } + let corner = Coord::new(e.min_x, e.min_y); + if e.max_x == e.min_x && e.max_y == e.min_y { + return self.point(corner).map_or(Extent::EMPTY, |m| Extent::from_points(m, m)); + } + let mut out = Extent::EMPTY; + for m in e.samples(2).filter_map(|c| self.point(c)) { + out.expand(m); + } + if out.width() > FEATURE_EXTENT_FINE || out.height() > FEATURE_EXTENT_FINE { self.extent(e) } else { out } + } } +/// The converted size above which [`Reprojection::feature_extent`] samples a box as finely as +/// [`Reprojection::extent`]: 0.1, about 10 km in degrees. Below it, a box's edges bend by well +/// under a millimetre between 3 places a side (a 10 km box in UTM: within 1e-8°). +pub const FEATURE_EXTENT_FINE: f64 = 0.1; + #[cfg(test)] mod tests { use super::*; @@ -149,11 +215,30 @@ mod tests { assert!((back.x - bern.x).abs() < 1e-7 && (back.y - bern.y).abs() < 1e-7, "{back:?}"); } - /// Every dataset is held in longitude/latitude, whatever system it was read in, so the map's - /// conversion of its geometry is the identity and can't fail (the map draws none of a layer - /// whose conversion fails: [`crate::Dataset::coord_crs`]). + /// A feature's box converted from 3 by 3 places is the 17 by 17 one's within a millimetre for + /// a 10 km box in UTM 32N (in degrees, about 1e-8); a point's is its one place. + #[test] + fn a_features_box_converts_from_few_places() { + let to = Crs::Epsg(32632).to(Crs::LonLat).unwrap(); + let e = Extent::new(690_000.0, 5_390_000.0, 700_000.0, 5_400_000.0); + let (fine, rough) = (to.extent(&e), to.feature_extent(&e)); + for (a, b) in [(fine.min_x, rough.min_x), (fine.min_y, rough.min_y), (fine.max_x, rough.max_x), (fine.max_y, rough.max_y)] { + assert!((a - b).abs() < 1e-8, "{fine:?} vs {rough:?}"); + } + // A 500 km box is sampled finely. + let large = Extent::new(300_000.0, 5_000_000.0, 800_000.0, 5_500_000.0); + assert_eq!(to.feature_extent(&large), to.extent(&large)); + let p = Coord::new(695_000.0, 5_395_000.0); + let at = to.point(p).unwrap(); + assert_eq!(to.feature_extent(&Extent::from_points(p, p)), Extent::from_points(at, at)); + assert!(to.feature_extent(&Extent::EMPTY).is_empty()); + } + + /// A dataset made in code is held in longitude/latitude, whatever system it says it was read + /// in, until held in another ([`crate::Dataset::hold_in`]), so the map's conversion of its + /// geometry is the identity and can't fail. #[test] - fn every_dataset_is_held_in_lonlat() { + fn a_dataset_made_in_code_is_held_in_lonlat() { let mut ds = crate::Dataset::new("lv95", crate::GeometryType::Point, vec![]); ds.crs = Some(Crs::Epsg(2056)); assert_eq!(ds.coord_crs(), Crs::LonLat); @@ -163,7 +248,8 @@ mod tests { let g = Geometry::Line(vec![vec![Coord::new(7.0, 46.0), Coord::new(f64::NAN, 47.0)]]); let read = ds.geometry_to_lonlat(&g).unwrap(); assert!(matches!(read, std::borrow::Cow::Borrowed(_))); - assert_eq!(format!("{:?}", ds.geometry_from_lonlat(read.into_owned()).unwrap()), format!("{g:?}")); + let held = crate::HeldPlaces::default(); + assert_eq!(format!("{:?}", ds.edit_from_lonlat(read.into_owned(), &held).unwrap()), format!("{g:?}")); // So its longitude/latitude box is its geometry's. ds.push(Some(Geometry::Point(Coord::new(2_600_000.0, 1_200_000.0))), vec![]); ds.push(Some(Geometry::Point(Coord::new(7.0, 46.0))), vec![]); diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 95c787261f..c47adab587 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -772,7 +772,7 @@ mod tests { // The header row comes after a blank one; the coordinates are UTM 33N. let opts = CsvOptions { crs: crate::raster::Crs::from_epsg(32633), ..CsvOptions::default() }; let (ds, _) = read(&book, "book", Some("utm"), &opts).unwrap(); - let e = ds.features[0].geometry.as_ref().unwrap().extent(); + let e = ds.in_lonlat().unwrap().features[0].geometry.as_ref().unwrap().extent(); assert!((e.min_x - 15.0).abs() < 0.01 && (e.min_y - 42.0).abs() < 0.05, "{e:?}"); let (ds, _) = read(&book, "book", Some("Notes"), &CsvOptions::default()).unwrap(); assert_eq!(ds.geometry_type, crate::GeometryType::None); diff --git a/crates/data/src/source/chunk_memory.rs b/crates/data/src/source/chunk_memory.rs index ffbb3694d3..fd4f56d2b0 100644 --- a/crates/data/src/source/chunk_memory.rs +++ b/crates/data/src/source/chunk_memory.rs @@ -81,11 +81,20 @@ impl<'a> Chunker<'a> { } } -/// A streamed row kept for a copy clipped to `extent`: `None` when it has no shape or its shape's -/// extent misses `extent`, else the row with exactly `width` values (cut, or padded with nulls) -/// and the heap bytes it holds. Fails, rather than aborting, when the values can't be allocated. -pub fn clip_row(mut row: Feature, extent: &Extent, width: usize) -> Result, DataError> { - if row.geometry.as_ref().is_none_or(|g| !g.extent().intersects(extent)) { +/// A streamed row kept for a copy clipped to `extent` (in longitude/latitude): `None` when it has +/// no shape or its shape's extent there misses `extent`, else the row with exactly `width` values +/// (cut, or padded with nulls) and the heap bytes it holds. `to_lonlat` takes the row's shape from +/// the system its source gives it in ([`super::FeatureSource::coord_crs`]) to longitude/latitude, +/// where its extent is compared; the row is kept in its own. Fails, rather than aborting, when the +/// values can't be allocated. +pub fn clip_row( + mut row: Feature, + extent: &Extent, + width: usize, + to_lonlat: &crate::raster::Reprojection, +) -> Result, DataError> { + let lonlat = |g: &crate::Geometry| if to_lonlat.is_identity() { g.extent() } else { to_lonlat.geometry(g).extent() }; + if row.geometry.as_ref().is_none_or(|g| !lonlat(g).intersects(extent)) { return Ok(None); } row.attrs.truncate(width); diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 402e00939e..8e96cd3803 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -8,7 +8,7 @@ //! sample are passed over without being fetched. use super::remote::{self, Remote}; -use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit, in_request, stride}; +use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit, stride}; use crate::raster::Crs; use crate::{DataError, Feature, Field, FieldType, GeometryType, Result, Value, wkb}; use flatgeobuf::geozero::{ColumnValue, CoordDimensions, PropertyProcessor, ToWkb}; @@ -380,14 +380,15 @@ impl FgbSource { if !late && !sample.wants() { continue; } - let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.geometry(g)); + let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !in_request(&geometry, req) || (late && !sample.wants()) { + if !geometry.in_request(req) || (late && !sample.wants()) { continue; } + let geometry = geometry.geometry; let mut props = Props { fields: &self.info.fields, slots: &self.slots, @@ -445,14 +446,15 @@ impl FgbSource { crate::progress::step(1)?; n += 1; let id = numbers.as_ref().and_then(|v| v.get(usize::try_from(n - 1).unwrap_or(usize::MAX)).copied()).unwrap_or(n); - let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.geometry(g)); + let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !in_request(&geometry, &req) { + if !geometry.in_request(&req) { continue; } + let geometry = geometry.geometry; let mut props = Props { fields: &self.info.fields, slots: &self.slots, @@ -757,15 +759,15 @@ impl FgbSource { continue; } let id = hits.items.get(this).map(|(_, i)| i + 1).unwrap_or(this as u64 + 1); - let geometry = - feat.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.geometry(g)); + let geometry = feat.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !in_request(&geometry, req) || (late && !sample.wants()) { + if !geometry.in_request(req) || (late && !sample.wants()) { continue; } + let geometry = geometry.geometry; let mut props = Props { fields: &self.info.fields, slots: &self.slots, @@ -806,6 +808,11 @@ impl FeatureSource for FgbSource { &self.info } + /// Its own system, in which it gives its features as the file holds them. + fn coord_crs(&self) -> crate::raster::Crs { + self.reproject.crs() + } + fn read(&self, req: &Request) -> Result { match &self.input { Input::Path(p, original) => self.read_with(&|| Ok(BufReader::new(open_input_file(p, original.as_deref())?)), req, false), diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 43fb694783..dc88b980be 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -11,9 +11,9 @@ use std::fs::{File, Metadata}; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; -use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit, in_request, stride}; +use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit, stride}; use crate::io::{ - FeatureSink, Schema, declared_crs, geojson_attrs, geojson_geometry, geojson_has_z, geometry_to_lonlat, latitude_past_poles, + FeatureSink, Schema, declared_crs, geojson_attrs, geojson_geometry, geojson_has_z, geometry_to_lonlat, latitude_past_poles, lonlat_box, swapped_latitude_note, }; use crate::{DataError, Feature, GeometryType, Result}; @@ -316,6 +316,11 @@ impl FeatureSource for GeoJsonSource { &self.info } + /// Its own system, in which it gives its features as the file holds them. + fn coord_crs(&self) -> crate::raster::Crs { + self.reproject.crs() + } + fn lost_to_crs(&self) -> bool { !self.failed.is_empty() } @@ -439,11 +444,19 @@ impl GeoJsonSource { let place = self.places.get(i as usize).ok_or(())?; let json = read_place(f, pos, buf, place).ok_or(())?; let geometry = geojson_geometry(&json).map_err(|_| ())?; - let geometry = match (self.reproject.transformer(), geometry) { - (Some(t), Some(g)) => Some(geometry_to_lonlat(&g, t).ok_or(())?), - (_, g) => g, + // Kept as the file holds it, in its own system; its box in longitude/latitude answers the + // request. + let lonlat = match (self.reproject.transformer(), &geometry) { + (Some(t), Some(g)) => Some(lonlat_box(g, t).ok_or(())?), + (_, g) => g.as_ref().map(crate::Geometry::extent), + }; + // One without geometry doesn't match an extent. + let outside = match (&lonlat, &req.extent) { + (_, None) => false, + (None, Some(_)) => true, + (Some(e), Some(r)) => !e.intersects(r), }; - if geometry.as_ref().map_or(req.extent.is_some(), |g| !in_request(g, req)) || !wanted() { + if outside || !wanted() { return Ok(None); } Ok(Some(Feature { id: u64::from(i) + 1, geometry, attrs: geojson_attrs(&json, &self.info.fields) })) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 180fcd0860..ac2c7b3987 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -4,7 +4,7 @@ //! and otherwise scan, testing the envelope in each geometry's header before decoding it. use super::gpkg_blob::{field_type, is_empty_blob, is_whole_empty_blob, split_blob}; -use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit, in_request, stride}; +use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit, stride}; use crate::raster::Crs; use crate::{DataError, Feature, Field, FieldType, GeometryType, Result, Value, wkb}; use rusqlite::types::ValueRef; @@ -416,11 +416,11 @@ impl GpkgSource { { return Ok(Row::Skip); } - let Some(geometry) = wkb::decode(body).and_then(|g| self.reproject.geometry(g)) else { return Ok(Row::Bad) }; - if !in_request(&geometry, req) { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { return Ok(Row::Bad) }; + if !placed.in_request(req) { return Ok(Row::Skip); } - Ok(Row::Feature(Feature { id, geometry: Some(geometry), attrs: attrs() })) + Ok(Row::Feature(Feature { id, geometry: Some(placed.geometry), attrs: attrs() })) } } @@ -437,6 +437,11 @@ impl FeatureSource for GpkgSource { &self.info } + /// Its own system, in which it gives its features as the file holds them. + fn coord_crs(&self) -> crate::raster::Crs { + self.reproject.crs() + } + /// Samples native-envelope matches, or decoded view matches when the native box is refused. /// Scans count records and check Cancel between them. fn read(&self, req: &Request) -> Result { diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 807f5cd2d2..6bce8da806 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -521,7 +521,7 @@ impl EditTable { ValueRef::Blob(b) if is_empty_blob(b) => Some(None), ValueRef::Blob(b) => { let (_, body) = split_blob(b)?; - self.src.reproject.geometry(wkb::decode(body)?).map(Some) + self.src.reproject.to_lonlat_geometry(wkb::decode(body)?).map(Some) } _ => None, } diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 1672275ef7..35615bbb00 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -3,7 +3,7 @@ //! SQLite (`gpkg`), which uses the R-tree index; here a read scans the table, testing the envelope //! in each geometry's header before decoding it. -use super::{Batch, FeatureSource, Reproject, Request, Sampler, Shared, SourceInfo, clamp_limit, in_request}; +use super::{Batch, FeatureSource, Reproject, Request, Sampler, Shared, SourceInfo, clamp_limit}; use crate::sqlite::{Db, Table, Val}; use crate::{DataError, Feature, Field, FieldType, GeometryType, Result, Value, wkb}; use rustgis_geom::Extent; @@ -335,6 +335,11 @@ impl FeatureSource for GpkgMemSource { &self.info } + /// Its own system, in which it gives its features as the file holds them. + fn coord_crs(&self) -> crate::raster::Crs { + self.reproject.crs() + } + /// Keeps rows without geometry in whole reads; they have no location to match an extent. /// Counts scanned records and checks Cancel between them. fn read(&self, req: &Request) -> Result { @@ -389,13 +394,14 @@ impl FeatureSource for GpkgMemSource { if known && !sample.wants() { return ControlFlow::Continue(()); } - let Some(geometry) = wkb::decode(body).and_then(|g| self.reproject.geometry(g)) else { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { skipped += 1; return ControlFlow::Continue(()); }; - if !in_request(&geometry, req) || (!known && !sample.wants()) { + if !placed.in_request(req) || (!known && !sample.wants()) { return ControlFlow::Continue(()); } + let geometry = placed.geometry; // Integer keys, negative ones too, map to distinct ids. sample.keep(Feature { id: rowid as u64, @@ -452,14 +458,14 @@ impl FeatureSource for GpkgMemSource { { return ControlFlow::Continue(()); } - let Some(geometry) = wkb::decode(body).and_then(|g| self.reproject.geometry(g)) else { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { out.skipped += 1; return ControlFlow::Continue(()); }; - if !in_request(&geometry, &req) { + if !placed.in_request(&req) { return ControlFlow::Continue(()); } - Some(geometry) + Some(placed.geometry) } // Without geometry (NULL, or an empty one): kept unless an extent is asked for. Some(Val::Null | Val::Blob(_)) | None if req.extent.is_none() => None, diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index d677f2eb72..dd1cf2cf52 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -372,9 +372,11 @@ pub trait FeatureSource: Send + Sync { Err(DataError::Unsupported("a source that can't be read a chunk at a time".into())) } fn info(&self) -> &SourceInfo; - /// The coordinate system of the features it gives: longitude/latitude, which every source - /// converts its own to today. Once sources hand over their own coordinates (#2032 C2), a - /// source says its system here, and one that wraps another says the other's. + /// The coordinate system of the features it gives: a file read in place gives them as the file + /// holds them, in its own system (Shapefile, GeoPackage, FlatGeobuf, GeoParquet, GeoJSON); a + /// source that converts them (a database or service that answers in longitude/latitude) says + /// longitude/latitude, the default. One that wraps another says the other's. A request's + /// extent is in longitude/latitude whatever this is. fn coord_crs(&self) -> crate::raster::Crs { crate::raster::Crs::LonLat } @@ -676,6 +678,8 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, ds.crs_incomplete = (info.format == "Shapefile" && skipped > 0) || src.lost_to_crs(); ds.zm_dropped = info.zm_dropped; ds.features = features.into(); + // Held as the source gives its features, in its own system. + ds.held_in = src.coord_crs(); let rounded = rounded_dates_note(&info.fields, &rounded_dates); let unread_dates = unread_dates_note(&info.fields, &unread_dates); let mut report = ReadReport { @@ -888,8 +892,16 @@ impl Reproject { self.crs.definition_text() } - /// The geometry in longitude/latitude; `None` when a coordinate can't be converted. - pub(crate) fn geometry(&self, g: Geometry) -> Option { + /// The system the source's features are given in ([`FeatureSource::coord_crs`]): its own, as + /// the file holds them (longitude/latitude for one read as such). + pub(crate) fn crs(&self) -> Crs { + self.crs + } + + /// The geometry converted to longitude/latitude; `None` when a coordinate can't be converted: + /// for a source that gives its features there (a database, a GeoPackage table loaded for + /// editing), unlike [`Reproject::read`]. + pub(crate) fn to_lonlat_geometry(&self, g: Geometry) -> Option { let Some(t) = &self.t else { return Some(g) }; let mut ok = true; let out = g.map_coords(&|c| t.to_lonlat(c).unwrap_or(Coord::new(f64::NAN, f64::NAN))); @@ -897,6 +909,25 @@ impl Reproject { ok.then_some(out) } + /// A geometry as the file holds it, kept in the source's own coordinates + /// ([`Reproject::crs`]), with its box in longitude/latitude for a request's extent to test + /// ([`Placed::in_request`]); `None` when a coordinate can't be converted to longitude/latitude, + /// as a feature that can't be placed is left out. Each coordinate is converted to be checked, + /// none is kept converted. + pub(crate) fn read(&self, g: Geometry) -> Option { + let Some(t) = &self.t else { + let lonlat = g.extent(); + return Some(Placed { geometry: g, lonlat }); + }; + let mut ok = true; + let mut lonlat = Extent::EMPTY; + g.for_each_coord(|c| match t.to_lonlat(c).filter(|l| l.is_finite()) { + Some(l) => lonlat.expand(l), + None => ok = false, + }); + ok.then_some(Placed { geometry: g, lonlat }) + } + /// A longitude/latitude geometry in the source's coordinates. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn to_native(&self, g: &Geometry) -> Option { @@ -1234,6 +1265,21 @@ pub(crate) fn in_request(g: &Geometry, req: &Request) -> bool { } } +/// A geometry a source read, in its own coordinates, and its box in longitude/latitude +/// ([`Reproject::read`]). +pub(crate) struct Placed { + pub(crate) geometry: Geometry, + pub(crate) lonlat: Extent, +} + +impl Placed { + /// Whether it is within a request's extent (in longitude/latitude), as [`in_request`] asks + /// of a geometry there. + pub(crate) fn in_request(&self, req: &Request) -> bool { + req.extent.is_none_or(|e| self.lonlat.intersects(&e)) + } +} + /// Makes ring rustls's process-wide crypto provider. SQL Server's client also builds aws-lc-rs /// into rustls, and with two providers built in rustls picks neither by itself (the MySQL /// client's `ClientConfig::builder()` would panic). diff --git a/crates/data/src/source/mysql.rs b/crates/data/src/source/mysql.rs index dd7f520fb2..628251007d 100644 --- a/crates/data/src/source/mysql.rs +++ b/crates/data/src/source/mysql.rs @@ -938,7 +938,7 @@ impl MysqlSource { mysql::Value::Bytes(b) => wkb::decode(b), _ => None, }?; - let geometry: Geometry = self.reproject.geometry(geometry)?; + let geometry: Geometry = self.reproject.to_lonlat_geometry(geometry)?; let attrs = self .info .fields diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 0093bbbd07..d0cc4c3fd9 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -12,7 +12,7 @@ //! downloaded whole instead. use super::remote::{self, Remote}; -use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit, in_request}; +use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit}; use crate::{DataError, Feature, Field, FieldType, GeometryType, Result, Value, wkb}; use bytes::Bytes; use parquet::basic::{ConvertedType, Encoding, LogicalType, Type as Physical}; @@ -470,6 +470,11 @@ impl FeatureSource for ParquetSource { &self.info } + /// Its own system, in which it gives its features as the file holds them. + fn coord_crs(&self) -> crate::raster::Crs { + self.reproject.crs() + } + /// Keeps rows with null geometry in whole reads; they have no location to match an extent. /// Unbounded spatial scans bound retained row masks and refuse groups over the decoded-column /// budget before decoding, count rows and check Cancel between them. They decode every selected group's geometry @@ -646,7 +651,7 @@ impl FeatureSource for ParquetSource { // Null geometry is valid; malformed non-null WKB is skipped and counted. let geometry = match geoms.get(k).and_then(|b| b.as_deref()) { Some(bytes) => { - let Some(geometry) = wkb::decode(bytes).and_then(|g| self.reproject.geometry(g)) else { + let Some(geometry) = wkb::decode(bytes).and_then(|g| self.reproject.read(g)) else { skipped += 1; continue; }; @@ -654,10 +659,11 @@ impl FeatureSource for ParquetSource { } None => None, }; - let matches_extent = geometry.as_ref().map_or(req.extent.is_none(), |g| in_request(g, req)); + let matches_extent = geometry.as_ref().map_or(req.extent.is_none(), |g| g.in_request(req)); if !matches_extent || (late && !sample.wants()) { continue; } + let geometry = geometry.map(|p| p.geometry); let values = attrs.iter().enumerate().map(|(field, col)| col.value(k, field, &mut unread_dates, &mut rounded_dates)).collect(); sample.keep(Feature { id: base.saturating_add(r as u64 + 1), geometry, attrs: values }); @@ -755,7 +761,7 @@ impl FeatureSource for ParquetSource { crate::progress::step(1)?; let geometry = match geoms.get(k).and_then(|b| b.as_deref()) { Some(bytes) => { - let Some(geometry) = wkb::decode(bytes).and_then(|geom| self.reproject.geometry(geom)) else { + let Some(geometry) = wkb::decode(bytes).and_then(|geom| self.reproject.read(geom)) else { out.skipped += 1; continue; }; @@ -763,9 +769,10 @@ impl FeatureSource for ParquetSource { } None => None, }; - if !geometry.as_ref().map_or(req.extent.is_none(), |g| in_request(g, &req)) { + if !geometry.as_ref().map_or(req.extent.is_none(), |g| g.in_request(&req)) { continue; } + let geometry = geometry.map(|p| p.geometry); let values = attrs .iter() .enumerate() diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 14719db53f..4acdecde8f 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -19,7 +19,7 @@ mod index; pub use cache::use_temporary_index_dir; pub use cache::{Emptied, empty_index_cache}; -use super::{Batch, FeatureSource, Reproject, Request, SourceInfo, clamp_limit, in_request}; +use super::{Batch, FeatureSource, Reproject, Request, SourceInfo, clamp_limit}; use crate::io::group_rings; use crate::{DataError, Feature, Field, FieldType, Geometry, GeometryType, Result, Value}; use rustgis_geom::{Coord, Extent}; @@ -220,6 +220,11 @@ impl FeatureSource for ShpSource { &self.info } + /// Its own system, in which it gives its features as the file holds them. + fn coord_crs(&self) -> crate::raster::Crs { + self.reproject.crs() + } + /// Samples indexed records, falling back to geometry matches when the native view is refused. /// The fallback counts records and checks Cancel before reading each one. fn read(&self, req: &Request) -> Result { @@ -267,8 +272,8 @@ impl FeatureSource for ShpSource { skipped += 1; return Ok(()); } - Ok(Some(g)) => match self.reproject.geometry(g) { - Some(g) => Some(g), + Ok(Some(g)) => match self.reproject.read(g) { + Some(placed) => Some(placed), None => { skipped += 1; return Ok(()); @@ -282,9 +287,10 @@ impl FeatureSource for ShpSource { }; // The index's boxes are rounded outward to f32, so it can match a shape just outside. A // shape without geometry doesn't match an extent, bounded natively or not. - if geometry.as_ref().map_or(req.extent.is_some(), |g| !in_request(g, req)) { + if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.in_request(req)) { return Ok(()); } + let geometry = geometry.map(|p| p.geometry); let attrs = if u64::from(i) < self.table.rows { let at = self.table.header_len + u64::from(i) * self.table.row_len as u64; if dbf.read_at(at, &mut row).is_err() { @@ -365,8 +371,8 @@ impl FeatureSource for ShpSource { skipped += 1; return Ok(()); } - Ok(Some(g)) => match self.reproject.geometry(g) { - Some(g) => Some(g), + Ok(Some(g)) => match self.reproject.read(g) { + Some(placed) => Some(placed), None => { skipped += 1; return Ok(()); @@ -379,9 +385,10 @@ impl FeatureSource for ShpSource { } }; // As in `read`, the shape itself is checked. - if geometry.as_ref().map_or(req.extent.is_some(), |g| !in_request(g, &req)) { + if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.in_request(&req)) { return Ok(()); } + let geometry = geometry.map(|p| p.geometry); let attrs = if u64::from(i) < self.table.rows { let at = self.table.header_len + u64::from(i) * self.table.row_len as u64; if dbf.read_at(at, &mut row).is_err() { diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index b49a02009c..48c67ed06e 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -971,7 +971,7 @@ impl SqlServerSource { /// RustGIS holds is null, counted in `unread` ([`Batch::unread_dates`]). fn row_feature(&self, r: &Row, unread: &mut Vec) -> Option { let id = id_of(at(r, 0))?; - let geometry: Geometry = self.reproject.geometry(wkb::decode(bytes_of(at(r, 1))?)?)?; + let geometry: Geometry = self.reproject.to_lonlat_geometry(wkb::decode(bytes_of(at(r, 1))?)?)?; let attrs = self.info.fields.iter().enumerate().map(|(k, f)| attr_of(f.ty, at(r, k + 2), unread, k)).collect(); Some(Feature { id, geometry: Some(geometry), attrs }) } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 8af93fdf43..8ad2b79d78 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::raster::Crs; use crate::raster::wkt::tests::{PlacementCase, metres_apart, placement_cases}; use crate::{Dataset, Field, FieldType, Geometry, Value, wkb}; use rustgis_geom::{Coord, lonlat_to_merc}; @@ -75,7 +76,7 @@ fn explicit_method_1028_warns_for_known_geopackage_authorities() { "{notes:?}" ); let point = Geometry::Point(Coord::new(0.0, 4_984_944.377_977_743)); - let Geometry::Point(at) = read.geometry(point).unwrap() else { panic!("not a point") }; + let Geometry::Point(at) = read.to_lonlat_geometry(point).unwrap() else { panic!("not a point") }; assert!(at.x.abs() < 1e-9 && (at.y - 45.0).abs() < 1e-9, "{at:?}"); } } @@ -132,7 +133,7 @@ fn a_geopackage_row_read_by_its_code_says_its_definitions_grid() { }; let read = gpkg_reproject(100001, Some(row), &mut notes).unwrap(); assert_eq!(notes, if notice { vec![said] } else { vec![] }, "{definition}"); - let Geometry::Point(at) = read.geometry(Geometry::Point(xy)).unwrap() else { panic!("not a point") }; + let Geometry::Point(at) = read.to_lonlat_geometry(Geometry::Point(xy)).unwrap() else { panic!("not a point") }; assert!((at.x - by_code.x).abs() < 1e-9 && (at.y - by_code.y).abs() < 1e-9, "{at:?} {by_code:?}"); } } @@ -162,7 +163,7 @@ fn a_geopackage_rows_code_gives_way_to_its_definitions_shift() { (read, notes) }; // Where a reading puts `xy`, and where a `.prj` of `wkt` would. - let at = |r: &Reproject, xy: Coord| match r.geometry(Geometry::Point(xy)) { + let at = |r: &Reproject, xy: Coord| match r.to_lonlat_geometry(Geometry::Point(xy)) { Some(Geometry::Point(c)) => c, g => panic!("{g:?}"), }; @@ -590,6 +591,21 @@ fn write_gpkg(path: &Path, rtree: bool) { tx.commit().unwrap(); } +/// A read's features in longitude/latitude, from the system the source gives them in +/// ([`FeatureSource::coord_crs`]), for a test to say where they are. +fn in_lonlat(src: &dyn FeatureSource, mut batch: Batch) -> Batch { + for f in &mut batch.features { + f.geometry = lonlat_of(src, f.geometry.take()); + } + batch +} + +/// A geometry a source gave, in longitude/latitude ([`in_lonlat`]). +fn lonlat_of(src: &dyn FeatureSource, g: Option) -> Option { + let to = src.coord_crs().to(Crs::LonLat).unwrap(); + g.map(|g| to.geometry(&g)) +} + /// The same checks for every provider. fn check(src: &dyn FeatureSource, expect_indexed: bool) { let info = src.info(); @@ -601,7 +617,7 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { assert_eq!(info.fields[vi].ty, FieldType::Integer); // Everything. - let all = src.read(&Request::all()).unwrap(); + let all = in_lonlat(src, src.read(&Request::all()).unwrap()); assert_eq!(all.features.len(), 600, "{}", info.format); assert!(all.complete); let f = all.features.iter().find(|f| f.attrs.contains(&Value::Text("p3_4".into()))).unwrap(); @@ -612,13 +628,13 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { assert!((c.x - (-138.0)).abs() < 1e-4 && (c.y - (-44.0)).abs() < 1e-4, "{c:?} in {}", info.format); assert_eq!(f.attrs[vi], Value::Int(64)); // Ids stay put between reads. - let near = src.read(&Request { extent: Some(Extent::new(-140.0, -46.0, -130.0, -40.0)), limit: 100 }).unwrap(); + let near = in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-140.0, -46.0, -130.0, -40.0)), limit: 100 }).unwrap()); let g = near.features.iter().find(|g| g.attrs.contains(&Value::Text("p3_4".into()))).unwrap(); assert_eq!(g.id, f.id, "{}", info.format); // An extent: exactly the points in it. let e = Extent::new(-60.0, -10.0, 40.0, 50.0); - let got = src.read(&Request { extent: Some(e), limit: 10_000 }).unwrap(); + let got = in_lonlat(src, src.read(&Request { extent: Some(e), limit: 10_000 }).unwrap()); assert_eq!(got.features.len(), in_box(&e), "{}", info.format); assert!(got.complete); assert!(got.features.iter().all(|f| f.geometry.as_ref().is_some_and(|g| e.contains(g.extent().center())))); @@ -630,7 +646,7 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { } // A limit: a sample spread over the whole extent, not the first rows. - let s = src.read(&Request { extent: None, limit: 60 }).unwrap(); + let s = in_lonlat(src, src.read(&Request { extent: None, limit: 60 }).unwrap()); assert!(!s.complete); assert!(s.features.len() <= 60 && s.features.len() >= 50, "{} of {}", s.features.len(), info.format); let xs: Vec = s.features.iter().filter_map(|f| f.geometry.as_ref()).map(|g| g.extent().min_x).collect(); @@ -638,7 +654,7 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { assert!(s.matched >= 600); // An extent outside the data. - let none = src.read(&Request { extent: Some(Extent::new(-179.9, 80.0, -179.0, 84.0)), limit: 100 }).unwrap(); + let none = in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-179.9, 80.0, -179.0, 84.0)), limit: 100 }).unwrap()); assert!(none.features.is_empty()); // A whole read into a dataset. @@ -1140,7 +1156,7 @@ fn custom_srs_reads(path: &Path) -> Vec<(Option, Vec)> { .into_iter() .map(|src| { let batch = src.read(&Request::all()).unwrap(); - (batch.features.first().and_then(|f| f.geometry.clone()), src.info().notes.clone()) + (lonlat_of(src, batch.features.first().and_then(|f| f.geometry.clone())), src.info().notes.clone()) }) .collect() } @@ -1315,10 +1331,12 @@ fn placement_cases_are_placed_from_a_prj_a_geopackage_and_a_flatgeobuf() { write_shapefile(&ds, &p); std::fs::write(p.with_extension("prj"), &wkt).unwrap(); let src = open_path(&p, None).unwrap(); - let read = src.read(&Request::all()).unwrap(); + let read = in_lonlat(src.as_ref(), src.read(&Request::all()).unwrap()); assert_placed(what, read.features.first().and_then(|f| f.geometry.as_ref()), lonlat); assert!(src.info().notes.is_empty(), "{what}: {:?}", src.info().notes); let (whole, report) = crate::io::read_path(&p).unwrap(); + // Held as the file holds it, in the system its `.prj` gives. + let whole = whole.in_lonlat().unwrap(); assert_placed(what, whole.features.first().and_then(|f| f.geometry.as_ref()), lonlat); assert!(report.messages.is_empty(), "{what}: {:?}", report.messages); @@ -1361,7 +1379,7 @@ fn fgb_reads(path: &Path) -> Vec<(Option, Vec)> { .into_iter() .map(|src| { let batch = src.read(&Request::all()).unwrap(); - (batch.features.first().and_then(|f| f.geometry.clone()), src.info().notes.clone()) + (lonlat_of(src.as_ref(), batch.features.first().and_then(|f| f.geometry.clone())), src.info().notes.clone()) }) .collect() } @@ -1530,7 +1548,7 @@ fn a_geopackage_definitions_shift_places_points_as_a_prj_does() { std::fs::write(p.with_extension("prj"), prj).unwrap(); let src = open_path(&p, None).unwrap(); assert!(src.info().notes.is_empty(), "{name}: {:?}", src.info().notes); - match src.read(&Request::all()).unwrap().features.first().and_then(|f| f.geometry.clone()) { + match lonlat_of(src.as_ref(), src.read(&Request::all()).unwrap().features.first().and_then(|f| f.geometry.clone())) { Some(Geometry::Point(c)) => c, g => panic!("{name}: {g:?}"), } @@ -2442,7 +2460,7 @@ fn shapefile_in_place_reprojects_from_its_prj() { assert!((e.min_x - 2.335).abs() < 1e-6 && (e.min_y - 48.855).abs() < 1e-6, "{e:?}"); assert!(src.info().notes.is_empty(), "{:?}", src.info().notes); // A longitude/latitude extent finds it; one beside it doesn't. - let near = src.read(&Request { extent: Some(Extent::new(2.0, 48.5, 2.5, 49.0)), limit: 10 }).unwrap(); + let near = in_lonlat(src.as_ref(), src.read(&Request { extent: Some(Extent::new(2.0, 48.5, 2.5, 49.0)), limit: 10 }).unwrap()); let c = near.features.first().and_then(|f| f.geometry.as_ref()).and_then(Geometry::label_point).unwrap(); assert!((c.x - 2.335).abs() < 1e-6 && (c.y - 48.855).abs() < 1e-6, "{c:?}"); assert!(src.read(&Request { extent: Some(Extent::new(3.0, 48.5, 3.5, 49.0)), limit: 10 }).unwrap().features.is_empty()); @@ -2696,12 +2714,15 @@ fn geojson_paths(file: &str, text: &str) -> (Dataset, Vec, String) { let strip = |m: &Vec| m.iter().map(|m| m.trim_start_matches("x: ").to_string()).collect::>(); assert_eq!(strip(&report.messages), strip(&in_report.messages), "{file}"); // The extent a source says is that of the features it reads (those that convert). - assert_eq!(src.info().extent, whole.extent(), "{file}"); + assert_eq!(src.info().extent, whole.lonlat_extent(), "{file}"); + assert_eq!(inplace.held_in, whole.held_in, "{file}"); assert_eq!(src.info().count, Some(whole.features.len() as u64), "{file}"); assert_eq!(src.info().coordinate_system(), whole.crs, "{file}"); } let src = geojson::GeoJsonSource::open_with(&p, "x", crate::io::BYTES_FLOOR).unwrap(); - (whole, report.messages, src.info().crs.clone()) + // In longitude/latitude, for the tests to say where its features are: it holds them in its + // declared system, as the file does. + (whole.in_lonlat().unwrap().into_owned(), report.messages, src.info().crs.clone()) } fn in_arnhem(e: &Extent) -> bool { @@ -4478,7 +4499,7 @@ fn a_view_its_system_cant_bound_reads_what_is_in_view() { assert_eq!(probe.done.load(std::sync::atomic::Ordering::Relaxed), 0, "{ext}"); } for limit in [10, 2201] { - let read = source.read(&Request { extent: Some(view), limit }).unwrap(); + let read = in_lonlat(source, source.read(&Request { extent: Some(view), limit }).unwrap()); assert_eq!(read.matched, 200, "{ext}: count only view matches before sampling"); if limit == 10 { // Adaptive sampling keeps between half the limit and the limit. diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index eb67279ac2..e676e5e41f 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -68,9 +68,17 @@ pub fn rows_digest(ds: &crate::Dataset) -> crate::Result { field.alias = None; } put(&mut h, &(&fields, &ds.crs)); + // Its geometry in longitude/latitude, as every release before #2032 C2 held a file's rows + // (converted by the same transformer the readers converted them with), so a digest saved + // then still matches the file read now in its own coordinates. + let to = ds.lonlat_conversion().map_err(crate::DataError::Format)?; crate::progress::begin(ds.features.len()); for f in ds.features.iter() { - put(&mut h, &(&f.geometry, &f.attrs)); + if to.is_identity() { + put(&mut h, &(&f.geometry, &f.attrs)); + } else { + put(&mut h, &(&f.geometry.as_ref().map(|g| to.geometry(g)), &f.attrs)); + } for (index, value) in f.attrs.iter().enumerate() { if let crate::Value::Float(number) = value && !number.is_finite() diff --git a/crates/data/tests/planetary_crs.rs b/crates/data/tests/planetary_crs.rs index d2d34cd1e4..4aa50033a6 100644 --- a/crates/data/tests/planetary_crs.rs +++ b/crates/data/tests/planetary_crs.rs @@ -54,6 +54,8 @@ fn craters(points: [(f64, f64); 2]) -> Dataset { const LONLAT: [(f64, f64); 2] = [(-133.8, 18.65), (77.45, 18.44)]; fn points(ds: &Dataset) -> Vec { + // Held in the file's system; placed in longitude/latitude (the body's). + let ds = ds.in_lonlat().unwrap(); ds.features.iter().filter_map(|f| f.geometry.as_ref()?.label_point()).collect() } @@ -1099,7 +1101,7 @@ fn exports_say_what_they_write_instead_of_another_body_s_system() { assert!(rustgis_data::export_error(&craters(LONLAT), eqc).is_none()); // Written to a Mars projection, the numbers are Mars metres. let projected = io::project(&layer, eqc).unwrap(); - let x = points(&projected)[0].x; + let x = projected.features[0].geometry.as_ref().and_then(|g| g.label_point()).unwrap().x; assert!((x - 3_396_190.0 * (-133.8f64).to_radians()).abs() < 1e-3, "{x}"); } diff --git a/crates/data/tests/projection_methods.rs b/crates/data/tests/projection_methods.rs index d883cd4895..9052ae0a98 100644 --- a/crates/data/tests/projection_methods.rs +++ b/crates/data/tests/projection_methods.rs @@ -41,6 +41,8 @@ fn explicit_method_1028_warns_in_full_and_streamed_shapefiles() { } let path = dir.path().join("p.shp"); let (read, report) = io::read_path(&path).unwrap(); + // Held in the file's system; placed in longitude/latitude. + let read = read.in_lonlat().unwrap(); near(read.features.first().and_then(|f| f.geometry.as_ref()?.label_point()), 0.0, 45.0, 1e-9); let streamed = rustgis_data::source::open_path(&path, None).unwrap(); for notes in [&report.messages, &streamed.info().notes] { @@ -63,6 +65,8 @@ fn read_prj(prj: &str, x: f64, y: f64) -> (Option, Vec) { std::fs::write(dir.path().join(format!("p.{ext}")), bytes).unwrap(); } let (read, report) = io::read_path(&dir.path().join("p.shp")).unwrap(); + // Held in the file's system; placed in longitude/latitude. + let read = read.in_lonlat().unwrap(); let at = match read.features.first().and_then(|f| f.geometry.clone()) { Some(Geometry::Point(c)) => Some(c), _ => None, diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 95fae7f86a..7ba97c10c3 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -3,6 +3,7 @@ //! Copied features are held by the session (with their schema) and also returned as GeoJSON, which //! the app puts on the system clipboard; paste takes either. +use rustgis_data::raster::Crs; use rustgis_data::{Dataset, Feature, FieldType, GeometryType, Value as Attr}; use serde_json::{Value, json}; @@ -66,16 +67,13 @@ fn copy(s: &mut Session) -> CmdResult { let id = source(s).ok_or("nothing is selected")?; let l = s.map().layer(id).ok_or("no such layer")?; let mut data = Dataset::new(l.name.clone(), l.geometry_type(), l.dataset.fields.clone()); - // In longitude/latitude, from the layer's own coordinates: the clipboard's, and its GeoJSON's. - let mut features = Vec::with_capacity(l.selection.len()); - for r in &l.selection { - let Some(f) = l.dataset.features.get(*r) else { continue }; - let geometry = f.geometry.as_ref().map(|g| l.dataset.geometry_to_lonlat(g).map(std::borrow::Cow::into_owned)).transpose()?; - features.push(rustgis_data::Feature { id: f.id, geometry, attrs: f.attrs.clone() }); - } - data.features = features.into(); + // The clipboard holds them as the layer does, in its system; its GeoJSON is in + // longitude/latitude, converted exactly through WGS 84, whatever map they were copied from. + data.held_in = l.dataset.coord_crs(); + data.crs = l.dataset.crs; + data.features = l.selection.iter().filter_map(|r| l.dataset.features.get(*r).cloned()).collect::>().into(); let n = data.features.len(); - let text = rustgis_data::io::to_geojson(&data).to_string(); + let text = rustgis_data::io::to_geojson(&*data.in_lonlat()?).to_string(); let layer = l.name.clone(); s.clipboard = Some(Clipboard { data }); s.notify(format!("Copied {n} features from {layer}"), false); @@ -98,23 +96,27 @@ fn cut(s: &mut Session, _: &Value) -> CmdResult { } l.touch_geometry(); // The archive gets the removed features in the order they were copied, as stored, in the - // layer's own coordinates (the clipboard holds them in longitude/latitude). + // layer's own coordinates, as the clipboard holds them. let removed: Vec = copied.iter().filter_map(|r| gone.get(r)).map(|f| super::design::Change { before: Some(f.clone()), row: None }).collect(); super::design::apply(s, id, removed)?; Ok(out) } -/// The features to paste: GeoJSON text when given, else the clipboard. -fn clip(s: &Session, p: &Value) -> Result { +/// The features to paste: GeoJSON text when given, with what its reader says it left out, else +/// the clipboard. +fn clip(s: &Session, p: &Value) -> Result<(Dataset, Vec), String> { match ps(p, "text").map(str::trim).filter(|t| !t.is_empty()) { Some(t) if t.len() > MAX_TEXT => Err("the pasted text is too large".into()), Some(t) => { - let (ds, _) = + // Held as the text gives them: in the system a legacy `crs` member names, else in + // longitude/latitude. + let (ds, report) = rustgis_data::io::read_geojson(t, "Pasted").map_err(|e| format!("the pasted text isn't GeoJSON features: {e}"))?; - if ds.features.is_empty() { Err("the pasted text has no features".into()) } else { Ok(ds) } + let said = report.into_messages().map(|m| format!("Pasted text: {m}")).collect(); + if ds.features.is_empty() { Err("the pasted text has no features".into()) } else { Ok((ds, said)) } } - None => s.clipboard.as_ref().map(|c| c.data.clone()).ok_or_else(|| "nothing has been copied".to_string()), + None => s.clipboard.as_ref().map(|c| (c.data.clone(), Vec::new())).ok_or_else(|| "nothing has been copied".to_string()), } } @@ -130,11 +132,8 @@ fn coerce(v: &Attr, ty: FieldType) -> (Attr, Cut) { } fn paste(s: &mut Session, p: &Value) -> CmdResult { - let src = clip(s, p)?; + let (src, said) = clip(s, p)?; let id = s.layer_id(p)?; - // Pasted where they were copied from, in a layer of the same system, their places stay as - // stored there. - let held = super::design::held_places(s, id, &[], &src.features.iter().filter_map(|f| f.geometry.as_ref()).collect::>()); let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; if l.is_raster() { return Err("features can't be pasted into a raster layer".into()); @@ -167,15 +166,29 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult { // Per field, what converting the pasted values cut, and the values that aren't null but that // the field can't hold. let mut unfit = vec![(Cuts::default(), 0usize); l.dataset.fields.len()]; - // The features the layer takes, their shapes in longitude/latitude written in its own - // coordinates: all converted before any is added. + // The features the layer takes, their shapes written in its own coordinates from the system + // the clipboard holds them in: as they are in a layer of that system (pasted where they were + // copied from, nothing moves), else converted by the operation between the two, which + // doesn't depend on the map. All converted before any is added. + let (from, own) = (src.coord_crs(), l.dataset.coord_crs()); let mut taken: Vec = src .features .into_iter() .filter(|ft| !ft.geometry.as_ref().is_some_and(|g| want != GeometryType::None && g.kind() != want)) .collect(); + // Into Web Mercator by way of longitude/latitude, where the latitudes it can't hold are found. + let steps = if from == own { + vec![] + } else if own == Crs::WebMercator && from != Crs::LonLat { + vec![from.to(Crs::LonLat)?, Crs::LonLat.to(own)?] + } else { + vec![from.to(own)?] + }; + let none = rustgis_data::HeldPlaces::default(); for ft in &mut taken { - ft.geometry = ft.geometry.take().map(|g| l.dataset.edit_from_lonlat(g, &held)).transpose()?; + for to in &steps { + ft.geometry = ft.geometry.take().map(|g| Dataset::edit_from_lonlat_by(to, g, &none)).transpose()?; + } } for ft in taken { next = next.saturating_add(1); @@ -212,7 +225,7 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult { super::design::apply(s, id, (first..first + n).map(|r| super::design::Change { before: None, row: Some(r) }).collect())?; s.map_mut().layers.iter_mut().filter(|o| o.id != id).for_each(|o| o.selection.clear()); s.notify(format!("Pasted {n} features into {name}"), false); - for notice in notices { + for notice in said.into_iter().chain(notices) { s.notify(notice, false); } Ok(json!({"pasted": n, "layer": id})) @@ -221,11 +234,14 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult { fn paste_special(s: &mut Session, p: &Value) -> CmdResult { // The name given, checked before the clipboard is read. let name = super::name_given(p, "a layer's name", 200)?; - let mut ds = clip(s, p)?; + let (mut ds, said) = clip(s, p)?; ds.name = name.unwrap_or_else(|| format!("{} (pasted)", ds.name)); ds.source = None; let n = ds.features.len(); let id = super::layer::add_dataset(s, ds); + for m in said { + s.notify(m, false); + } Ok(json!({"pasted": n, "layer": id})) } diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index bf31d41e10..baf946155f 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -70,11 +70,10 @@ pub(crate) fn display_area_messages<'a>(layers: impl Iterator before { @@ -1178,8 +1177,7 @@ fn edit_vertex(s: &mut Session, p: &Json) -> CmdResult { /// one of them reads as are held. The search reads the box of every feature of the layers in its /// system, each from its vertices, once a command (an added feature, a paste): work that grows /// with those layers, which C2 is to take to a spatial index. -/// Empty while the layer is in longitude/latitude, as every layer is today: its edits are written -/// as they are. +/// Empty while the layer is in longitude/latitude: its edits are written as they are. pub(crate) fn held_places(s: &Session, id: u32, originals: &[&Geometry], edited: &[&Geometry]) -> rustgis_data::HeldPlaces { let mut held = rustgis_data::HeldPlaces::default(); let Some(l) = s.map().layer(id).filter(|l| !l.dataset.edits_in_lonlat()) else { return held }; @@ -2209,8 +2207,10 @@ fn stored_place(s: &Session, id: u32, row: usize, at: Coord) -> Option { let own = l.dataset.features.get(row)?.geometry.as_ref()?; // Only its places within a millionth of where the map shows the hit, in its own coordinates, // are read and projected: a snap asks on every pointer move. - let to_lonlat = l.dataset.lonlat_conversion().ok()?; - let shown = rustgis_data::raster::Crs::LonLat.to(l.dataset.coord_crs()).ok()?.point(s.map().to_lonlat(at)?)?; + // As the map shows its places ([`rustgis_data::Dataset::shown_conversion`]), so a vertex + // drawn straight into the map's system is the one it projects to. + let to_lonlat = l.dataset.shown_conversion().ok()?; + let shown = l.dataset.shown_from_lonlat().ok()?.point(s.map().to_lonlat(at)?)?; let reach = round_trip_reach(shown); // A world projection draws a longitude past ±180° (a shape drawn across the antimeridian) one // turn round; Web Mercator draws it past its edge. A place matched as read wins over one @@ -2294,13 +2294,12 @@ fn topology_rules(s: &mut Session, p: &Json) -> CmdResult { struct TopologyInput { rule: TopologyRule, layer: String, - /// The layer in longitude/latitude, where the rules are checked, and its covering layer's. + /// The layer as it holds its coordinates, and its covering layer: rows shared with the map's, + /// so a check read ahead is known to have read what the rules read now. Each is converted to + /// longitude/latitude, where the rules are checked, as the check runs. data: rustgis_data::Dataset, rows: Vec, by: Option, - /// Why the layer, or its covering layer, can't be given in longitude/latitude: the check is - /// refused rather than run on coordinates of another system. - unreadable: Option, } /// The rules as the map has them now, each with what it reads; a rule whose layer is gone is left @@ -2312,21 +2311,11 @@ fn topology_checks(s: &Session) -> Vec { let rows: Vec = l.visible_rows().iter().enumerate().filter(|(_, v)| **v).map(|(i, _)| i).collect(); // A covering layer that is gone leaves the rule with nothing to check (its layer's // latitudes are still checked). - // Both in longitude/latitude: a copy only of a layer in another system. - let lonlat = |d: &rustgis_data::Dataset| d.in_lonlat().map(std::borrow::Cow::into_owned); - let (by, by_unreadable) = match &rule { - TopologyRule::MustBeCoveredBy { by, .. } => match s.map().layer_by_name(by).map(|b| lonlat(&b.dataset)) { - Some(Ok(d)) => (Some(d), None), - Some(Err(e)) => (None, Some(e)), - None => (None, None), - }, - _ => (None, None), - }; - let (data, unreadable) = match lonlat(&l.dataset) { - Ok(d) => (d, by_unreadable), - Err(e) => (l.dataset.clone(), Some(e)), + let by = match &rule { + TopologyRule::MustBeCoveredBy { by, .. } => s.map().layer_by_name(by).map(|b| b.dataset.clone()), + _ => None, }; - inputs.push(TopologyInput { rule, layer: l.name.clone(), data, rows, by, unreadable }); + inputs.push(TopologyInput { rule, layer: l.name.clone(), data: l.dataset.clone(), rows, by }); } inputs } @@ -2364,18 +2353,27 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result t::overlaps(&i.data, &i.rows), - (TopologyRule::MustNotHaveGaps { .. }, _) => t::gaps(&i.data, &i.rows), - (TopologyRule::MustNotSelfIntersect { .. }, _) => t::self_intersections(&i.data, &i.rows), - (TopologyRule::MustNotHaveDangles { .. }, _) => t::dangles(&i.data, &i.rows, tol), + // In longitude/latitude, a copy only of a layer held in another system; refused, naming + // the layer, rather than checked on coordinates of another system. + // A cancel while converting is the check's cancel, said as the rules' is. + let named = |e: String| { + if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) { + "the topology check was cancelled".to_string() + } else { + format!("{}: {e}", i.layer) + } + }; + let data = i.data.in_lonlat().map_err(named)?; + let by = i.by.as_ref().map(|b| b.in_lonlat().map_err(named)).transpose()?; + rustgis_analysis::validate_latitudes(&data, i.rows.iter().copied())?; + found.push(match (&i.rule, &by) { + (TopologyRule::MustNotOverlap { .. }, _) => t::overlaps(&data, &i.rows), + (TopologyRule::MustNotHaveGaps { .. }, _) => t::gaps(&data, &i.rows), + (TopologyRule::MustNotSelfIntersect { .. }, _) => t::self_intersections(&data, &i.rows), + (TopologyRule::MustNotHaveDangles { .. }, _) => t::dangles(&data, &i.rows, tol), (TopologyRule::MustBeCoveredBy { .. }, Some(by)) => { rustgis_analysis::validate_latitudes(by, 0..by.features.len())?; - t::not_covered(&i.data, &i.rows, by) + t::not_covered(&data, &i.rows, by) } // Its covering layer is gone: nothing checked, nothing said, as it always was. (TopologyRule::MustBeCoveredBy { .. }, None) => t::Checked { errors: Vec::new(), complete: true, skipped: 0 }, @@ -2596,6 +2594,39 @@ pub(crate) fn new_feature_inputs(input: &super::InputContext<'_>, p: &Json) -> R mod tests { use super::*; + /// A check of a layer held in another system, read ahead, is known to have read what the + /// rules read now: both share the layer's rows (each check converts its own copy as it runs), + /// and its errors are those of the same layer in longitude/latitude. + #[test] + fn a_held_layers_topology_read_ahead_is_still_current() { + let ring = |x: f64| { + vec![vec![ + Coord::new(x, 48.7), + Coord::new(x + 0.01, 48.7), + Coord::new(x + 0.01, 48.71), + Coord::new(x, 48.71), + Coord::new(x, 48.7), + ]] + }; + let mut errors = Vec::new(); + for crs in [rustgis_data::raster::Crs::LonLat, rustgis_data::raster::Crs::Epsg(32632)] { + let mut ds = rustgis_data::Dataset::new("Parcels", GeometryType::Polygon, vec![]); + // Two overlapping squares. + ds.push(Some(Geometry::Polygon(vec![ring(11.5)])), vec![]); + ds.push(Some(Geometry::Polygon(vec![ring(11.505)])), vec![]); + ds.hold_in(crs).unwrap(); + let mut s = Session::new(crate::Project::default()); + s.map_mut().add_dataset(ds); + s.run("topology.rules", &json!({"add": {"rule": "mustNotOverlap", "layer": "Parcels"}})).unwrap(); + let (ahead, now) = (topology_checks(&s), topology_checks(&s)); + assert!(same_topology(&ahead, &now), "{crs:?}"); + let found = check_topology(&ahead, 1.0).unwrap(); + errors.push(found[0].errors.len()); + } + assert_eq!(errors[0], errors[1]); + assert!(errors[0] > 0, "the overlap is found"); + } + #[test] fn a_center_is_found_within_the_commands_budget() { // A line at 89.9°N whose ten edges each span 170° of longitude: 340 half-degree stretches diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 6940580998..ea8a454ca7 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -588,15 +588,18 @@ fn copy_stream( let (mut used, mut inside, mut outside) = (0usize, 0usize, 0usize); let mut fits = true; let info = src.info(); + // Its rows come in the source's own system, held there in the copy; the area is compared in + // longitude/latitude. + let to_lonlat = src.coord_crs().to(rustgis_data::raster::Crs::LonLat).map_err(|e| format!("{}: {e}", layer.name))?; let batch = src .visit_chunks(Some(extent), 1 << 20, &mut |chunk| { progress::check()?; for row in chunk { // Only a row the copy keeps is reshaped; one past the budget is just counted. let Some((row, bytes)) = (if fits { - source::chunk_memory::clip_row(row, &extent, dataset.fields.len())? + source::chunk_memory::clip_row(row, &extent, dataset.fields.len(), &to_lonlat)? } else { - source::chunk_memory::clip_row(row, &extent, 0)? + source::chunk_memory::clip_row(row, &extent, 0, &to_lonlat)? }) else { outside += 1; continue; diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 0640b9cb3f..11fc457cc9 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1397,7 +1397,7 @@ fn streamed_inputs( /// The layers a tool reads, in longitude/latitude, the space analysis tools work in /// ([`Inputs::dataset`]): those read whole (streamed layers, files) converted where they are, and /// a converted copy of each other layer it names whose coordinates are in another system. Nothing -/// is copied while every dataset is in longitude/latitude, as every one is today. +/// is copied for a layer held in longitude/latitude. fn lonlat_inputs( map: &rustgis_map::Map, spec: Option<&rustgis_analysis::ToolSpec>, diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 27fc27121a..71aa948f85 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1054,7 +1054,12 @@ fn zone_rings(s: &Session, z: &str) -> Result>, String> { return Err("the zone has no polygon".into()); }; // In longitude/latitude, whatever system the layer holds its coordinates in. - let Geometry::Polygon(polys) = &*l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{z}: {e}"))? else { + let Geometry::Polygon(polys) = &*l + .dataset + .lonlat_conversion() + .and_then(|to| rustgis_data::Dataset::geometry_to_lonlat_by(&to, g)) + .map_err(|e| format!("{z}: {e}"))? + else { return Err("the zone has no polygon".into()); }; polys.first().cloned().ok_or_else(|| "the zone has no polygon".into()) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index fa6e7e9434..bf24051560 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -866,6 +866,8 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { GeometryType::Point, out_fields, ); + // Made in longitude/latitude, then held as the labelled layer is (Dataset::hold_as). + let system = (l.dataset.coord_crs(), l.dataset.crs); 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() { @@ -979,6 +981,9 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { if let Some(src) = s.map_mut().layer_mut(id) { src.labels.enabled = false; } + if let Err(e) = ds.hold_as(system.0, system.1) { + s.notify(format!("{}: kept in longitude/latitude, as it was made, not in {}: {e}", ds.name, system.0.label()), false); + } let new_id = super::layer::add_dataset(s, ds); if let Some(a) = s.map_mut().layer_mut(new_id) { // The annotation is all text: the points themselves are invisible. diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index eb6c1d732d..feba20f271 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1831,10 +1831,17 @@ pub(crate) fn add_photos_to(s: &mut Session, name: &str, zoom: Option, fee let id = match existing { Some(id) => { let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; - // Read in longitude/latitude, held in the layer's system. + // Read in longitude/latitude, held in the layer's system: through WGS 84, as a photo's + // position is data, not a place on the map. let mut photos = Vec::new(); + let to = rustgis_data::raster::Crs::LonLat.to(l.dataset.coord_crs()).map_err(|e| format!("{}: {e}", l.name))?; + let none = rustgis_data::HeldPlaces::default(); for f in ds.features.into_iter().take(added) { - let g = f.geometry.map(|g| l.dataset.geometry_from_lonlat(g)).transpose().map_err(|e| format!("{}: {e}", l.name))?; + let g = f + .geometry + .map(|g| rustgis_data::Dataset::edit_from_lonlat_by(&to, g, &none)) + .transpose() + .map_err(|e| format!("{}: {e}", l.name))?; photos.push((g, f.attrs)); } for (g, attrs) in photos { diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 94742a503a..f67886cc0d 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -594,8 +594,11 @@ impl Bridge<'_> { let n = features.len(); features.push_row(r.to_feature()); if let Some(g) = r.geometry() - && let std::borrow::Cow::Owned(g) = - l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, r.id()))? + && let std::borrow::Cow::Owned(g) = l + .dataset + .lonlat_conversion() + .and_then(|to| rustgis_data::Dataset::geometry_to_lonlat_by(&to, g)) + .map_err(|e| format!("{}: feature {}: {e}", l.name, r.id()))? { features.set_geometry(n, Some(g)); } @@ -613,6 +616,7 @@ impl Bridge<'_> { zm_dropped: false, windowed: false, held_in: rustgis_data::raster::Crs::LonLat, + shown_in: None, }; let mut ds = ds; let mut member = None; diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 85f62d74e8..6b5803743e 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -460,7 +460,14 @@ fn add_layer( let mut ds = rustgis_data::Dataset::new(name, *geometry, fields.clone()); if let Some(c) = layer.crs.as_deref().or(crs.as_deref()) { match rustgis_data::raster::crs::Crs::parse(c) { - Ok(c) => ds.crs = Some(c), + // Empty, so held in its system at no cost: features drawn into it are kept + // there, as in a layer read from a file in it. + Ok(c) => { + // Refused, it stays in longitude/latitude with no system of its own. + if let Err(e) = ds.hold_as(c, Some(c)) { + report.approximated(name, format!("held in longitude/latitude, not in {} ({e})", c.label())); + } + } Err(e) => report.skipped(name, format!("its coordinate system {c}, which RustGIS can't read ({e})")), } } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 4df9aae2f0..ba8c158180 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -75,8 +75,11 @@ pub fn commands() -> Vec { return Err("nothing is selected in this layer".into()); } let mut ds = rustgis_data::Dataset::new(format!("{} selection", l.name), l.geometry_type(), l.dataset.fields.clone()); - // Its coordinates as they are, held in the layer's system. + // Its coordinates as they are, held in the layer's system, which it exports in. ds.held_in = l.dataset.held_in; + ds.crs = l.dataset.crs; + // What the import lost, Define Projection can't recover in the copy either. + ds.crs_incomplete = l.dataset.crs_incomplete; for r in &l.selection { if let Some(f) = l.dataset.features.get(*r) { ds.push(f.geometry.clone(), f.attrs.clone()); diff --git a/crates/engine/src/cmd/stac_area.rs b/crates/engine/src/cmd/stac_area.rs index ff14550dc4..a4c6f58125 100644 --- a/crates/engine/src/cmd/stac_area.rs +++ b/crates/engine/src/cmd/stac_area.rs @@ -45,6 +45,8 @@ fn read_geometries(path: &str) -> Result<(Vec, Vec), String> { return Err(format!("{path} has more than {} features: simplify it or use a bounding box", area::MAX_FEATURES)); } let mut messages: Vec = report.into_messages().map(|m| format!("{path}: {m}")).collect(); + // The search area is in longitude/latitude; a file in another system is read in its own. + let ds = ds.in_lonlat().map_err(|e| format!("{path}: {e}"))?; let geometries: Vec = ds.features.iter().filter_map(|f| f.geometry.clone()).collect(); if geometries.len() < ds.features.len() { messages.push(format!( diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 647854bfd7..430fdfbe53 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1718,10 +1718,12 @@ fn route(s: &mut Session, p: &Value) -> CmdResult { rustgis_map::rows::Rows::Subset(rows) => rows, }; // The network in longitude/latitude, as `from` and `to` are, whatever system the layer holds - // its coordinates in. - let lines = l.dataset.in_lonlat()?; - let r = network::shortest_route( - &lines, + // its coordinates in: converted only when its graph is built, which is kept for the layer's + // rows, so routes over a held network reuse it as they do over one in longitude/latitude. + let system = (l.dataset.coord_crs(), l.dataset.crs); + let r = network::shortest_route_held( + &l.dataset, + || l.dataset.in_lonlat(), &rows, point(p, "from")?, point(p, "to")?, @@ -1732,6 +1734,7 @@ fn route(s: &mut Session, p: &Value) -> CmdResult { let mut ds = Dataset::new(name, GeometryType::Polyline, vec![Field::new("length_km", FieldType::Double), Field::new("cost", FieldType::Double)]); ds.push(Some(Geometry::Line(vec![r.path.clone()])), vec![Attr::Float(r.length_m / 1000.0), Attr::Float(r.cost)]); + hold_as(s, &mut ds, system); let nid = super::layer::add_dataset(s, ds); if let Some(notice) = query_notice { s.notify_text(notice, false); @@ -1846,9 +1849,10 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { rustgis_map::rows::Rows::All => (0..l.dataset.features.len()).collect(), rustgis_map::rows::Rows::Subset(rows) => rows, }; - // Placed in longitude/latitude, as the points' layer holds them, whatever system the polygons' - // layer holds its coordinates in. + // Placed in longitude/latitude, whatever system the polygons' layer holds its coordinates in, + // then held in that system, as the polygons are. let polygons = l.dataset.in_lonlat()?; + let system = (l.dataset.coord_crs(), l.dataset.crs); let seed = f(p, "seed").map_or(42, |v| v.max(0.0) as u64); let pts: Vec<(usize, Coord)> = match ps(p, "field") { Some(fname) => { @@ -1878,6 +1882,7 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { ds.push(Some(Geometry::Point(*c)), vec![Attr::Int(*r as i64)]); } let n = ds.features.len(); + hold_as(s, &mut ds, system); if let Some(notice) = query_notice { s.notify_text(notice, false); } @@ -1885,6 +1890,15 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"layer": nid, "points": n})) } +/// Holds `ds`, a layer made in longitude/latitude from another, as that layer is +/// ([`Dataset::hold_as`]; `system` is its [`Dataset::coord_crs`] and [`Dataset::crs`]), and says +/// so when it can't be: it stays in longitude/latitude then, as it was made. +fn hold_as(s: &mut Session, ds: &mut Dataset, (held, crs): (rustgis_data::raster::Crs, Option)) { + if let Err(e) = ds.hold_as(held, crs) { + s.notify(format!("{}: kept in longitude/latitude, as it was made, not in {}: {e}", ds.name, held.label()), false); + } +} + fn numeric_fields(ds: &Dataset, p: &Value) -> Result, String> { match p.get("fields").and_then(Value::as_array) { Some(a) => a diff --git a/crates/engine/src/geometry_calc.rs b/crates/engine/src/geometry_calc.rs index adc4dba797..5433779a88 100644 --- a/crates/engine/src/geometry_calc.rs +++ b/crates/engine/src/geometry_calc.rs @@ -101,8 +101,10 @@ pub fn run(s: &mut Session, p: &Json) -> CmdResult { if g.kind() != l.geometry_type() { return Err("feature geometry does not match the layer".into()); } - // Measured and placed in longitude/latitude, from the layer's own coordinates. - let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("feature {}: {e}", f.id))?; + // Measured and placed in longitude/latitude, from the layer's own coordinates through + // WGS 84, whatever map it is shown on. + let to = l.dataset.lonlat_conversion().map_err(|e| format!("feature {}: {e}", f.id))?; + let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("feature {}: {e}", f.id))?; let g = g.as_ref(); // Lengths and areas use longitude differences, so a shape drawn or buffered across the // antimeridian may run past ±180°; a coordinate has to be a real longitude. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 83faf47f6a..a04ad5a66e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1705,7 +1705,14 @@ impl Session { pub fn run(&mut self, id: &str, params: &Value) -> CmdResult { self.command_epilogue(id, params, |s| { let native_maintenance = s.depth == 0 && s.policy_ingress_idle(); + if s.depth == 0 { + s.note_shown_systems(); + } let result = s.run_command(id, params); + // A command may change a map's projection, or add layers to it. + if s.depth == 0 { + s.note_shown_systems(); + } // Native sessions without a drawing loop recover their own failed overviews. // Named callers and sealed completions do not initiate unrelated maintenance. if native_maintenance && s.read_in_place_again() { @@ -3070,6 +3077,15 @@ impl Session { } } + /// Tells every map's layers the system their map draws them straight into + /// ([`rustgis_map::Map::note_shown_system`]): before and after each command, and each frame + /// of the app, which also covers layers landing from a background read. + pub fn note_shown_systems(&mut self) { + for m in &mut self.project.maps { + m.note_shown_system(); + } + } + /// 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 diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 946b333147..266bf2645b 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -536,6 +536,7 @@ impl From for Table { windowed: false, // Saved in longitude/latitude, as `Dataset`'s own saving writes them. held_in: rustgis_data::raster::Crs::LonLat, + shown_in: None, }, } } @@ -2469,6 +2470,7 @@ impl Durable for Table { zm_dropped: _, windowed: _, held_in: _, + shown_in: _, } = dataset; if let Some(v) = provenance { p.string(Leaf::Table, v, true, rustgis_map::paths::is_local(v)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fd60d9b549..96a9e65edf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -21441,7 +21441,7 @@ fn citygml_layers_and_the_coordinate_system_given() { }; // Placed in the Netherlands, as EPSG:28992 puts (85000, 447000). let placed = |s: &Session, name: &str| { - let e = s.map().layer_by_name(name).map(|l| l.dataset.extent()).unwrap(); + let e = s.map().layer_by_name(name).map(|l| l.dataset.lonlat_extent()).unwrap(); assert!((4.0..5.0).contains(&e.min_x) && (51.5..52.5).contains(&e.min_y), "{name}: {e:?}"); }; @@ -26149,7 +26149,8 @@ fn projection_review_typed_layer_inputs_report_the_formula_choice() { std::fs::write(&path, "e,n\n0,4984944.377977743\n").unwrap(); let result = session.run("layer.addData", &json!({"path":path,"x":"e","y":"n","crs":definition})).unwrap(); let layer = session.map().layer(result["layer"].as_u64().unwrap() as u32).unwrap(); - assert!((layer.dataset.features[0].geometry.as_ref().unwrap().label_point().unwrap().y - 45.0).abs() < 1e-9); + let lonlat = layer.dataset.in_lonlat().unwrap(); + assert!((lonlat.features[0].geometry.as_ref().unwrap().label_point().unwrap().y - 45.0).abs() < 1e-9); } _ => { session @@ -26196,7 +26197,7 @@ fn a_typed_crs_says_its_grid_isnt_applied() { let added = s.run("layer.addData", &json!({"path": csv, "x": "e", "y": "n", "crs": definition})).unwrap(); let id = added["layer"].as_u64().unwrap() as u32; // On UTM zone 17N's central meridian, 81°W. - let at = s.map().layer(id).unwrap().dataset.features[0].geometry.as_ref().unwrap().label_point().unwrap(); + let at = s.map().layer(id).unwrap().dataset.in_lonlat().unwrap().features[0].geometry.as_ref().unwrap().label_point().unwrap(); assert!((at.x + 81.0).abs() < 1e-3, "{at:?}"); assert_eq!(count(&s, mark), (expected, expected), "csv {definition}: {:?}", s.notices_since(mark)); let mark = s.notice_mark(); @@ -26419,7 +26420,7 @@ fn layers_export_in_the_system_they_were_read_in() { let l = s.map().layer(r["layer"].as_u64().unwrap() as u32).unwrap(); let ds = if l.is_streamed() { l.load_all().unwrap() } else { l.dataset.clone() }; assert_eq!(ds.crs.map(|c| c.label()).unwrap_or_else(|| "EPSG:4326".into()), want, "{file}"); - let e = ds.extent(); + let e = ds.lonlat_extent(); assert!((e.min_x - 9.0).abs() < 1e-6 && (e.min_y - 51.451_18).abs() < 1e-5 && e.width() > 0.0139, "{file}: {e:?}"); } // The .prj says the system, by its parameters and its code. @@ -26461,7 +26462,7 @@ fn a_system_without_an_epsg_code_is_exported_in_its_own_system() { let l = s.map().layer(r["layer"].as_u64().unwrap() as u32).unwrap(); let ds = if l.is_streamed() { l.load_all().unwrap() } else { l.dataset.clone() }; assert_eq!(ds.crs.map(|c| c.label()), Some(own.label()), "{file}"); - let at = ds.features[0].geometry.as_ref().unwrap().extent(); + let at = ds.in_lonlat().unwrap().features[0].geometry.as_ref().unwrap().extent(); assert!((at.min_x + 90.049).abs() < 1e-6 && (at.min_y - 35.1495).abs() < 1e-6, "{file}: {at:?}"); } // A system WKT1 has no name for can't be written into either: WGS 84, and the notice says so. @@ -41468,7 +41469,10 @@ fn geopackage_edits_save_back() { let batch = source.read(&Request::all()).unwrap(); assert_eq!(batch.features.len(), 3); let f = batch.features.iter().find(|f| f.id == 2).unwrap(); - let Some(Geometry::Line(parts)) = &f.geometry else { panic!("reopened line: {:?}", f.geometry) }; + // Given in the file's system (Web Mercator); placed in longitude/latitude. + let to = source.coord_crs().to(Crs::LonLat).unwrap(); + let geometry = f.geometry.as_ref().map(|g| to.geometry(g)); + let Some(Geometry::Line(parts)) = &geometry else { panic!("reopened line: {geometry:?}") }; assert_eq!(parts.len(), 1); assert_eq!(parts[0].len(), moved.len()); for (a, b) in parts[0].iter().zip(&moved) { @@ -42572,7 +42576,11 @@ fn raster_tools_read_projected_zone_files_without_reprojecting_twice() { let loaded = s.run("layer.addData", &json!({"path": path, "name": "loaded_zones"})).unwrap()["layer"].clone(); let input = s.map().layer(loaded.as_u64().unwrap() as u32).unwrap().dataset.clone(); assert_eq!(input.crs.map(|c| c.label()).unwrap_or_else(|| "EPSG:4326".into()), format!("EPSG:{epsg}"), "{ext}"); - assert!(input.extent().contains(tr.to_lonlat(gt.to_world(2.0, 2.0)).unwrap()), "{epsg}, {ext}: {:?}", input.extent()); + assert!( + input.lonlat_extent().contains(tr.to_lonlat(gt.to_world(2.0, 2.0)).unwrap()), + "{epsg}, {ext}: {:?}", + input.lonlat_extent() + ); for raster in ["utm", "geographic"] { let depth = s.undo_depth(); s.run( @@ -42585,7 +42593,8 @@ fn raster_tools_read_projected_zone_files_without_reprojecting_twice() { let field = out.field_index(&format!("{raster}_{stat}")).unwrap(); assert_eq!(out.value(0, field), &expected, "EPSG:{epsg}, {ext}, {raster}, {stat}"); } - assert_eq!(out.features[0].geometry, input.features[0].geometry); + // In longitude/latitude, where the tool works (the input is held in its file's system). + assert_eq!(out.in_lonlat().unwrap().features[0].geometry, input.in_lonlat().unwrap().features[0].geometry); assert_eq!(out.crs, input.crs); assert_eq!(s.undo_depth(), depth + 1); assert!(s.undo()); @@ -45876,7 +45885,7 @@ fn web_mercator_exports_say_what_they_write_at_85_degrees() { let said = |s: &Session, mark| -> Vec { s.notices_since(mark).iter().filter(|n| n.text.contains("where Web Mercator ends")).map(|n| n.text.clone()).collect() }; - let south = |s: &Session, id: u32| s.map().layer(id).unwrap().dataset.extent().min_y; + let south = |s: &Session, id: u32| s.map().layer(id).unwrap().dataset.lonlat_extent().min_y; let mut beyond = 0; for g in s.map().layers.iter().filter(|l| l.name == "Countries").flat_map(|l| l.dataset.features.iter()).filter_map(|f| f.geometry.as_ref()) diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 882164a25e..8aa577659c 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -288,6 +288,109 @@ fn features_are_copied_between_systems() { assert_close(&wells[9..], &wells[1..3], "into UTM"); } +/// The clipboard holds features in the system of the layer they were copied from. Its GeoJSON is +/// their places in longitude/latitude through WGS 84 whatever map they were copied on, also one +/// in another datum's system that draws them by a direct operation; pasted back into the layer +/// they keep its numbers exactly. GeoJSON text naming its system (a legacy `crs` member) is +/// pasted from that system: by the operation between the two into a layer held in another. +#[test] +fn the_clipboard_holds_features_in_their_own_system() { + let gk = Crs::Epsg(31467); + let mut s = session(gk); + s.run("map.projection", &json!({"type": "EPSG:25832"})).unwrap(); + assert_eq!(s.map().flat().direct_system(), Some(Crs::Epsg(25832))); + s.run("select.rows", &json!({"layer": "Wells", "rows": [1, 2]})).unwrap(); + let text = s.run("edit.copy", &Value::Null).unwrap()["text"].as_str().unwrap().to_string(); + let places = |text: &str| -> Vec { + let gj: Value = serde_json::from_str(text).unwrap(); + gj["features"] + .as_array() + .unwrap() + .iter() + .map(|f| Coord::new(f["geometry"]["coordinates"][0].as_f64().unwrap(), f["geometry"]["coordinates"][1].as_f64().unwrap())) + .collect() + }; + let exact: Vec = lonlat(&s, "Wells")[1..3] + .iter() + .map(|g| match g { + Some(Geometry::Point(c)) => *c, + g => panic!("a point: {g:?}"), + }) + .collect(); + // Within 0.1 mm of WGS 84's, where the map's way is some decimetres off. + for (p, q) in places(&text).iter().zip(&exact) { + assert!((p.x - q.x).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9, "{p:?} vs {q:?}"); + } + s.run("map.projection", &json!({"type": "mercator"})).unwrap(); + assert_eq!(s.run("edit.copy", &Value::Null).unwrap()["text"].as_str().unwrap(), text, "the same on Web Mercator"); + let native = |s: &Session, layer: &str| -> Vec> { + s.map().layer_by_name(layer).unwrap().dataset.features.iter().map(|f| f.geometry.clone()).collect() + }; + s.run("edit.paste", &json!({"layer": "Wells"})).unwrap(); + let wells = native(&s, "Wells"); + assert_eq!(wells[9..], wells[1..3], "pasted where copied from, exactly"); + + // UTM 32N text into a layer in longitude/latitude and into the DHDN one. + let at = Coord::new(11.5, 48.7); + let in_utm = Crs::LonLat.to(UTM).unwrap().point(at).unwrap(); + let pasted = json!({ + "type": "FeatureCollection", + "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::32632"}}, + "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [in_utm.x, in_utm.y]}}] + }) + .to_string(); + s.map_mut().add_dataset(Dataset::new("Plain", GeometryType::Point, vec![])); + s.run("edit.paste", &json!({"layer": "Plain", "text": pasted})).unwrap(); + assert_close(&lonlat(&s, "Plain"), &[Some(Geometry::Point(at))], "UTM text into longitude/latitude"); + s.run("edit.paste", &json!({"layer": "Wells", "text": pasted})).unwrap(); + let want = UTM.to(gk).unwrap().point(in_utm).unwrap(); + let Some(Geometry::Point(got)) = native(&s, "Wells")[11] else { panic!("a point") }; + assert!((got.x - want.x).abs() < 1e-6 && (got.y - want.y).abs() < 1e-6, "UTM text into DHDN: {got:?} vs {want:?}"); +} + +/// A route over a held network after Define Projection runs on the network as it now reads, not +/// on a graph kept from before: the relabel keeps the rows, so the graph is kept under its system +/// too. Here the UTM 32N numbers relabelled DHDN zone 3 lie about 2,800 km west, away from the +/// route's ends. +#[test] +fn a_route_follows_a_relabelled_network() { + let mut s = session(UTM); + let route = json!({"layer": "Roads", "from": [11.4951, 48.6925], "to": [11.5295, 48.7290], "snapDistance": 100}); + let first = s.run("analysis.route", &route).unwrap(); + assert_eq!(s.run("analysis.route", &route).unwrap()["lengthKm"], first["lengthKm"], "the kept graph"); + s.run("layer.defineProjection", &json!({"layer": "Roads", "crs": "EPSG:31467"})).unwrap(); + let after = s.run("analysis.route", &route); + assert!(after.as_ref().is_err_and(|e| e.contains("from the network")), "a graph kept from before: {after:?}"); +} + +/// Define Projection on a layer made from a held layer's selection relabels it: its numbers stay +/// as they are, now in the system given. The layer made keeps the system it was read in. +#[test] +fn a_selection_layer_of_a_held_layer_is_relabelled_as_it_is() { + let mut s = session(UTM); + s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().dataset.crs = Some(UTM); + s.run("select.rows", &json!({"layer": "Wells", "rows": [0, 4]})).unwrap(); + let made = s.run("select.layerFromSelection", &json!({"layer": "Wells"})).unwrap(); + let id = made["layer"].as_u64().unwrap() as u32; + let l = s.map().layer(id).unwrap(); + assert_eq!((l.dataset.coord_crs(), l.dataset.crs), (UTM, Some(UTM))); + let name = l.name.clone(); + let before: Vec> = l.dataset.features.iter().map(|f| f.geometry.clone()).collect(); + s.run("layer.defineProjection", &json!({"layer": name, "crs": "EPSG:25832"})).unwrap(); + let l = s.map().layer(id).unwrap(); + assert_eq!(l.dataset.coord_crs(), Crs::Epsg(25832)); + let after: Vec> = l.dataset.features.iter().map(|f| f.geometry.clone()).collect(); + assert_eq!(after, before, "relabelled, not converted"); + // One without a recorded system too. + s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().dataset.crs = None; + let made = s.run("select.layerFromSelection", &json!({"layer": "Wells"})).unwrap(); + let id = made["layer"].as_u64().unwrap() as u32; + let name = s.map().layer(id).unwrap().name.clone(); + s.run("layer.defineProjection", &json!({"layer": name, "crs": "EPSG:25832"})).unwrap(); + let after: Vec> = s.map().layer(id).unwrap().dataset.features.iter().map(|f| f.geometry.clone()).collect(); + assert_eq!(after, before, "relabelled, not converted, without a recorded system"); +} + /// A project saves a held layer in longitude/latitude, as older releases read it, and opens it /// back held there, at the same places. #[test] @@ -934,3 +1037,145 @@ fn a_hidden_held_water_layers_undrawable_places_are_said() { assert_eq!(of_map.len(), 1, "{of_map:?}"); assert!(of_map[0].ends_with("(map 'Map', layer 'Parcels' (1))"), "{of_map:?}"); } + +/// On a map drawn in another system than the layer's, on another datum (DHDN 3-degree Gauss-Krüger +/// zone 3 on ETRS89 UTM 32N, whose direct operation is some decimetres from the way through WGS 84: +/// 0.37 m at Stuttgart in PROJ 9.9.0, see the map's +/// `a_held_layer_is_drawn_straight_into_a_map_in_a_coordinate_system`), the places edits give and +/// take are those the map draws: a vertex's handle is where the map draws the vertex, and a vertex +/// moved to where the map draws it stays where it was stored. Calculate Geometry's coordinates are +/// the layer's own through WGS 84, whatever map. +#[test] +fn edits_on_a_map_in_another_datums_system_land_on_what_it_draws() { + let gk = Crs::Epsg(31467); + let mut s = session(gk); + s.run("map.projection", &json!({"type": "EPSG:25832"})).unwrap(); + let flat = s.map().flat(); + assert_eq!(flat.direct_system(), Some(Crs::Epsg(25832))); + let id = s.map().layer_by_name("Roads").unwrap().id; + let stored = s.map().layer(id).unwrap().dataset.features[0].geometry.clone().unwrap(); + let drawn = s.map_mut().layer_mut(id).unwrap().projected_in(&flat, "test")[0].clone().unwrap(); + let (Geometry::Line(stored_parts), Geometry::Line(drawn_parts)) = (&stored, &drawn) else { panic!("a line") }; + let l = s.map().layer(id).unwrap(); + assert_eq!(l.dataset.shown_in, Some(Crs::Epsg(25832)), "the map told its layer its system"); + let Geometry::Line(handles) = &*l.dataset.geometry_to_lonlat(&stored).unwrap() else { panic!("a line") }; + let exact = l.dataset.lonlat_conversion().unwrap(); + for ((h, d), c) in handles[0].iter().zip(&drawn_parts[0]).zip(&stored_parts[0]) { + let at = flat.forward_checked(*h).unwrap(); + assert!((at.x - d.x).hypot(at.y - d.y) < 1e-6, "handle at {at:?}, vertex drawn at {d:?}"); + // Through WGS 84 the handle would be off the line. + let via = flat.forward_checked(exact.point(*c).unwrap()).unwrap(); + assert!((via.x - d.x).hypot(via.y - d.y) > 0.1, "{via:?} vs {d:?}"); + } + // A vertex moved to where the map draws it, as a drag there gives it, keeps its place. + let at = flat.inverse(drawn_parts[0][1]).unwrap(); + s.run("edit.vertex", &json!({"layer": "Roads", "row": 0, "action": "move", "index": 1, "lon": at.x, "lat": at.y})).unwrap(); + let Some(Geometry::Line(after)) = &s.map().layer(id).unwrap().dataset.features[0].geometry else { panic!("a line") }; + let (a, b) = (after[0][1], stored_parts[0][1]); + assert!((a.x - b.x).hypot(a.y - b.y) < 1e-6, "moved to {a:?} from {b:?}"); + // Analysis reads the layer through WGS 84, as on any map. + let g = rustgis_data::Dataset::geometry_to_lonlat_by(&exact, &stored).unwrap(); + s.run("map.projection", &json!({"type": "mercator"})).unwrap(); + let l = s.map().layer(id).unwrap(); + assert_eq!(l.dataset.shown_in, None); + assert_eq!(*l.dataset.geometry_to_lonlat(&stored).unwrap(), *g, "on Web Mercator, edits go through WGS 84"); +} + +/// A project saved by an older release opens as it did (#2032 C2): a layer it kept in the +/// project holds its features in longitude/latitude, as they were saved, and a layer read in +/// place from a UTM 32N Shapefile is read again in the file's own system, at the same places. +/// Both export the file's own numbers to UTM 32N (the kept one within a micrometre, its round +/// trip through longitude/latitude), +/// draw alike on Web Mercator and on a UTM map, and saving the project again writes the kept +/// layer's features as they were saved. +#[test] +fn a_project_saved_by_an_older_release_opens_as_it_did() { + let dir = Dir::new("older-project"); + let shp = dir.path().join("parcels.shp"); + let mut file = layers().remove(2); + file.hold_in(UTM).unwrap(); + rustgis_data::io::write_path_in(&file, &shp, UTM).unwrap(); + let numbers = |ds: &Dataset| ds.features.iter().map(|f| f.geometry.clone()).collect::>(); + // As the file holds them (its rings in the Shapefile's order). + let read = rustgis_data::io::read_path(&shp).unwrap().0; + assert_eq!(read.coord_crs(), UTM, "read in the file's own system"); + let in_file = numbers(&read); + + // As an older release saved it: the kept layer's features in longitude/latitude (every release + // held them there), and the layer read in place by its file's path. + let mut older = Session::new(Project::default()); + let kept = older.run("layer.addData", &json!({"path": shp.display().to_string(), "name": "Kept"})).unwrap(); + let kept = kept["layer"].as_u64().unwrap() as u32; + let lonlat = older.map().layer(kept).unwrap().dataset.in_lonlat().unwrap().into_owned(); + older.map_mut().layer_mut(kept).unwrap().dataset = lonlat.clone(); + older.run("layer.addData", &json!({"path": shp.display().to_string(), "name": "Streamed", "stream": true})).unwrap(); + let project = dir.path().join("older.rgis"); + older.run("project.saveAs", &json!({"path": project.display().to_string()})).unwrap(); + let saved: Value = serde_json::from_str(&std::fs::read_to_string(&project).unwrap()).unwrap(); + let saved_kept = saved["maps"][0]["layers"].as_array().unwrap().iter().find(|l| l["name"] == "Kept").unwrap(); + let ring = &saved_kept["dataset"]["features"][0]["geometry"]["Polygon"][0][0][0]; + let x = ring["x"].as_f64().unwrap(); + assert!((11.0..12.0).contains(&x), "saved in longitude/latitude: {ring}"); + + let mut s = Session::new(Project::default()); + s.run("project.open", &json!({"path": project.display().to_string()})).unwrap(); + s.wait_in_place_reads(); + let kept = s.map().layer_by_name("Kept").unwrap().id; + let streamed = s.map().layer_by_name("Streamed").unwrap().id; + // Kept: as saved, in longitude/latitude, its system remembered for exports. + let k = &s.map().layer(kept).unwrap().dataset; + assert_eq!(k.coord_crs(), Crs::LonLat); + assert_eq!(k.crs, Some(UTM)); + assert_eq!(numbers(k), numbers(&lonlat)); + // Read in place: the file's own numbers, at the same places. + let whole = s.map().layer(streamed).unwrap().load_all().unwrap(); + assert_eq!(whole.coord_crs(), UTM); + assert_eq!(numbers(&whole), in_file); + assert_close(&numbers(&whole.in_lonlat().unwrap()), &numbers(&lonlat), "read in place"); + let (ek, es) = (k.lonlat_extent(), whole.lonlat_extent()); + for (a, b) in [(ek.min_x, es.min_x), (ek.min_y, es.min_y), (ek.max_x, es.max_x), (ek.max_y, es.max_y)] { + assert!((a - b).abs() < CLOSE, "extents {ek:?} {es:?}"); + } + + // Both export the file's numbers. + for name in ["Kept", "Streamed"] { + let out = dir.path().join(format!("{name}.shp")); + s.run("share.exportLayer", &json!({"layer": name, "path": out.display().to_string(), "crs": "EPSG:32632"})).unwrap(); + let back = rustgis_data::io::read_path(&out).unwrap().0; + assert_eq!(back.coord_crs(), UTM, "{name}"); + let (mut a, mut b) = (Vec::new(), Vec::new()); + numbers(&back).iter().flatten().for_each(|g| g.for_each_coord(|c| a.push(c))); + in_file.iter().flatten().for_each(|g| g.for_each_coord(|c| b.push(c))); + assert_eq!(a.len(), b.len(), "{name}"); + for (p, q) in a.iter().zip(&b) { + assert!((p.x - q.x).hypot(p.y - q.y) < 1e-6, "{name}: {p:?} {q:?}"); + } + } + + // Both draw alike, on Web Mercator and on a map in the file's system. + for (k, projection) in ["mercator", "EPSG:32632"].into_iter().enumerate() { + s.run("map.projection", &json!({"type": projection})).unwrap(); + s.run("layer.zoomTo", &json!({"layer": "Kept"})).unwrap(); + let paths = [0, 1].map(|i| dir.path().join(format!("{k}-{i}.png"))); + for (shown, path) in [(kept, &paths[0]), (streamed, &paths[1])] { + let hidden = if shown == kept { streamed } else { kept }; + s.run("layer.visibility", &json!({"layer": hidden, "visible": false})).unwrap(); + s.run("layer.visibility", &json!({"layer": shown, "visible": true})).unwrap(); + s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 320, "height": 200})).unwrap(); + } + // Where each draws (the two layers have colours of their own). + let [a, b] = paths.map(|p| image::open(p).unwrap().to_rgba8()); + let (bg_a, bg_b) = (*a.get_pixel(0, 0), *b.get_pixel(0, 0)); + let drawn = a.pixels().filter(|p| **p != bg_a).count(); + let differ = a.pixels().zip(b.pixels()).filter(|(p, q)| (**p != bg_a) != (**q != bg_b)).count(); + assert!(drawn > 1000, "{projection}: little drawn ({drawn} pixels)"); + assert!(differ * 100 < drawn, "{projection}: {differ} of {drawn} drawn pixels differ"); + } + + // Saved again, the kept layer's features are written as they were saved. + let again = dir.path().join("again.rgis"); + s.run("project.saveAs", &json!({"path": again.display().to_string()})).unwrap(); + let saved_again: Value = serde_json::from_str(&std::fs::read_to_string(&again).unwrap()).unwrap(); + let again_kept = saved_again["maps"][0]["layers"].as_array().unwrap().iter().find(|l| l["name"] == "Kept").unwrap(); + assert_eq!(again_kept["dataset"]["features"], saved_kept["dataset"]["features"]); +} diff --git a/crates/engine/tests/define_projection.rs b/crates/engine/tests/define_projection.rs index af008c6a17..8b56587a86 100644 --- a/crates/engine/tests/define_projection.rs +++ b/crates/engine/tests/define_projection.rs @@ -36,7 +36,9 @@ fn upload(s: &mut Session, bytes: &[u8], crs: Option<&str>) -> u32 { /// Reads the first fixture point without deriving an expected result through a transformer. fn point(ds: &Dataset) -> Coord { - ds.features[0].geometry.as_ref().unwrap().label_point().unwrap() + // In longitude/latitude, from the system the layer holds its coordinates in (the file's own + // as it is read, the numbers as they are until a system is defined). + ds.in_lonlat().unwrap().features[0].geometry.as_ref().unwrap().label_point().unwrap() } /// Checks the known surveyed coordinate and its attribute survived the public workflow. @@ -60,7 +62,8 @@ fn missing_prj_layer_command_preserves_native_numbers_and_undoes_as_one_step() { assert!(layer.dataset.features[1].geometry.is_none()); assert!(layer.geometry_rev > before.geometry_rev); let exported = io::project(&layer.dataset, Crs::parse("EPSG:32631").unwrap()).unwrap(); - let c = point(&exported); + // The numbers written: the layer's own, held in the system defined. + let c = exported.features[0].geometry.as_ref().unwrap().label_point().unwrap(); assert!((c.x - 451_219.33).abs() < 1e-5 && (c.y - 5_411_550.20).abs() < 1e-5, "{c:?}"); assert_eq!(io::default_export_crs(&layer.dataset, "shp"), Crs::parse("EPSG:32631").unwrap()); let saved = s.project.saved_text(None).unwrap().0; diff --git a/crates/engine/tests/portable_projects/reload.rs b/crates/engine/tests/portable_projects/reload.rs index ac13bb536b..941c6c8d2d 100644 --- a/crates/engine/tests/portable_projects/reload.rs +++ b/crates/engine/tests/portable_projects/reload.rs @@ -37,6 +37,8 @@ fn loaded(s: &Session, id: u32) -> Dataset { } fn first_point(ds: &Dataset) -> Coord { + // In longitude/latitude, from the system the layer holds its coordinates in. + let ds = ds.in_lonlat().unwrap(); match ds.features[0].geometry.as_ref().unwrap() { Geometry::Point(at) => *at, other => panic!("expected fixture point, got {other:?}"), diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 5b4934e657..6b9df62908 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -771,16 +771,11 @@ fn load(file_name: &str, bytes: &[u8], layer_name: &str, job: &Job, dir: Option< match read { Ok((mut ds, _)) => { ds.name = layer_name.to_string(); - if job.crs != Crs::LonLat - && looks_projected(&ds) - && let Ok(tf) = job.crs.transformer() - { - let lost = convert_features(&mut ds, |c| tf.to_lonlat(c)); - if lost > 0 { - messages.push(format!( - "{layer_name}: {lost} features couldn't be converted to longitude/latitude and have no geometry" - )); - } + // An output that says its system (a .prj, a GeoJSON `crs`) is held in it as + // read; one in the working system that doesn't is relabelled to it. + if job.crs != Crs::LonLat && ds.coord_crs() == Crs::LonLat && looks_projected(&ds) { + ds.held_in = job.crs; + ds.crs = Some(job.crs); } Some(if ds.features.iter().all(|f| f.geometry.is_none()) { OutputLayer::Table(ds) } else { OutputLayer::Vector(ds) }) } diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index 1db227c7f0..2ead485ca3 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -364,6 +364,7 @@ fn vector_tools_work_in_metres_and_return_lonlat() { let r = rustgis_analysis::run("geolibre:buffer_vector", &f, &json!({"input": "pts", "distance": "1000"})).unwrap(); let Output::Layers(layers) = r.output else { panic!("layers") }; let Some(OutputLayer::Vector(ds)) = layers.first() else { panic!("a vector layer: {layers:?}") }; + let ds = ds.in_lonlat().unwrap(); let Some(Some(Geometry::Polygon(polys))) = ds.features.first().map(|f| f.geometry.clone()) else { panic!("a polygon") }; let area = rustgis_geom::geodesic_ring_area_m2(&polys[0][0]).abs(); let circle = std::f64::consts::PI * 1000.0 * 1000.0; @@ -376,6 +377,7 @@ fn rasters_and_points_meet_in_one_coordinate_system() { let r = rustgis_analysis::run("geolibre:extract_raster_values_at_points", &f, &json!({"rasters": "dem", "points": "pts"})).unwrap(); let Output::Layers(layers) = r.output else { panic!("layers") }; let Some(OutputLayer::Vector(ds)) = layers.first() else { panic!("points: {layers:?}") }; + let ds = ds.in_lonlat().unwrap(); let p: Option = ds.features.first().and_then(|f| f.geometry.as_ref()).map(|g| g.extent().center()); let centre = f.points.extent().center(); assert!(p.is_some_and(|c| (c.x - centre.x).abs() < 1e-6 && (c.y - centre.y).abs() < 1e-6), "back in lon/lat: {p:?}"); @@ -456,13 +458,28 @@ fn prepare_and_finish_without_a_runner() { c.x, c.y ); let lines = vec!["working…".to_string(), r#"{"output":"/work/output.geojson","log":"/work/my_output.geojson","count":1}"#.to_string()]; - let r = finish(&job, &[("output.geojson".into(), out.into_bytes())], &lines, None); + let r = finish(&job, &[("output.geojson".into(), out.clone().into_bytes())], &lines, None); let Output::Layers(layers) = r.output else { panic!("layers") }; let Some(OutputLayer::Vector(ds)) = layers.first() else { panic!("a vector: {layers:?}") }; assert_eq!(ds.name, "Test Buffer"); - let p = ds.extent().center(); + // Held in the working system, its numbers as the runner wrote them. + assert_eq!(ds.coord_crs(), Crs::Epsg(32617)); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(c))); + let p = ds.in_lonlat().unwrap().extent().center(); let want = f.points.extent().center(); - assert!((p.x - want.x).abs() < 1e-6 && (p.y - want.y).abs() < 1e-6, "back in lon/lat: {p:?}"); + assert!((p.x - want.x).abs() < 1e-6 && (p.y - want.y).abs() < 1e-6, "at the input's place: {p:?}"); + // An output that names its system (the legacy GeoJSON `crs` member) is held in it as read, + // not converted a second time. + let named = out.replacen( + r#"{"type":"FeatureCollection","#, + r#"{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::32617"}},"#, + 1, + ); + let again = finish(&job, &[("output.geojson".into(), named.into_bytes())], &[], None); + let Output::Layers(layers) = again.output else { panic!("layers") }; + let Some(OutputLayer::Vector(ds)) = layers.first() else { panic!("a vector: {layers:?}") }; + assert_eq!(ds.coord_crs(), Crs::Epsg(32617)); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(c))); assert!(r.messages.contains(&"working…".to_string())); assert!(r.messages.iter().any(|m| m == "Count: 1"), "results, without the output path: {:?}", r.messages); assert!(!r.messages.iter().any(|m| m.contains("/work/output.geojson")), "the output came back as a layer"); diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 85e54f9663..d597d02196 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -360,6 +360,10 @@ pub struct Layer { /// longitude/latitude, found as it was last converted for drawing ([`Layer::unplaced`]). #[serde(skip)] unplaced: Unplaced, + /// Its extent in longitude/latitude as last worked out ([`Layer::extent`]): converting every + /// place of a layer held in another system takes long enough not to do it each frame. + #[serde(skip)] + extent_cache: ExtentCache, /// 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 @@ -573,6 +577,7 @@ impl Layer { projected_crs: None, lonlat: LonLatCopy::default(), unplaced: Unplaced::default(), + extent_cache: ExtentCache::default(), drawn: false, geometry_rev: 0, view_memory: Default::default(), @@ -731,6 +736,10 @@ impl Layer { } } self.dataset.windowed = true; + // Held as the source gives them, in its own system. + if let Some(src) = &self.source { + self.dataset.held_in = src.coord_crs(); + } if let Some(src) = &mut self.source { src.reads = src.reads.wrapping_add(1); } @@ -745,8 +754,8 @@ impl Layer { self.projected_extents = cache.extents; self.projected_vertices = cache.vertices; self.projected_for = cache.key; - // A source reads its window in longitude/latitude, and its read projects from there. - self.projected_crs = Some(Crs::LonLat); + // Projected from the system the source gives its window in. + self.projected_crs = Some(cache.crs); self.projected_rev = self.geometry_rev; let feature_bytes = if padded { rustgis_data::source::memory::features_bytes(&self.dataset.features) } else { cache.feature_bytes }; @@ -940,6 +949,8 @@ impl Layer { }; let mut ds = Dataset::new(self.dataset.name.clone(), geometry_type, info.fields.clone()); ds.crs = info.coordinate_system(); + // Rows copied into it come in the source's own system. + ds.held_in = src.coord_crs(); // What reading the source drops, the export lacks (see `Dataset::zm_dropped`). ds.zm_dropped = info.zm_dropped || self.dataset.zm_dropped; if !self.dataset.fields.is_empty() { @@ -1120,7 +1131,7 @@ impl Layer { if !matches!(flat, projection::Flat::Mercator) { self.display_levels.clear(); } - self.fill_projected(key, |g| flat.project(g)); + self.fill_projected(key, flat); } self.drawn = true; &self.projected @@ -1218,18 +1229,41 @@ impl Layer { 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) { + /// Fills the projected geometry cache for `key` with each geometry on `flat`: a layer's own + /// in longitude/latitude projected ([`projection::Flat::project`]); a held layer's as the map + /// draws its system ([`projection::Flat::held`]: as it is on a map in that system, by the + /// direct operation on one in another, else through longitude/latitude), counting the + /// features with a place that can't be given in longitude/latitude ([`Layer::unplaced`]). A + /// system that can't be converted draws nothing. + fn fill_projected(&mut self, key: &str, flat: &projection::Flat) { self.display = None; let crs = self.dataset.coord_crs(); let projected: Vec> = if crs == Crs::LonLat { - self.dataset.features.rows().map(|r| r.geometry().map(&project)).collect() + self.dataset.features.rows().map(|r| r.geometry().map(|g| flat.project(g))).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)) + match flat.held(crs) { + // Nothing to count: every place is drawn as it is. + Ok(held) if held.is_identity() => self.dataset.features.rows().map(|r| r.geometry().cloned()).collect(), + Ok(held) => { + let mut lost = 0usize; + let geoms = self + .dataset + .features + .rows() + .map(|r| { + let (g, lost_here) = held.geometry(r.geometry()?); + lost += usize::from(lost_here); + Some(g) + }) + .collect(); + self.unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Ok(lost) }; + geoms + } + Err(e) => { + self.unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Err(e) }; + (0..self.dataset.features.len()).map(|_| None).collect() + } + } }; self.projected_extents = std::sync::Arc::new(projected.iter().map(|g| g.as_ref().map_or(Extent::EMPTY, Geometry::extent)).collect()); @@ -1587,7 +1621,7 @@ impl Layer { (Some(r), _) => r.data.as_ref().map(|d| d.extent()).unwrap_or(Extent::EMPTY), // A streamed layer's whole extent, not just the part read. (None, Some(s)) => s.info().map(|i| i.extent).filter(|e| !e.is_empty()).unwrap_or_else(|| self.dataset.lonlat_extent()), - (None, None) => self.dataset.lonlat_extent(), + (None, None) => self.extent_cache.get(&self.dataset, self.geometry_rev), } } @@ -1611,12 +1645,7 @@ impl Layer { /// without geometry left out): the box around them in the dataset's own coordinates, converted /// ([`Dataset::extent_to_lonlat`]). pub fn rows_extent(&self, rows: impl IntoIterator) -> Extent { - let own = rows - .into_iter() - .filter_map(|r| self.dataset.features.get(r)) - .filter_map(|f| f.geometry.as_ref()) - .fold(Extent::EMPTY, |e, g| e.union(&g.extent())); - self.dataset.extent_to_lonlat(&own) + self.dataset.lonlat_extent_of(rows.into_iter().filter_map(|r| self.dataset.features.get(r)).filter_map(|f| f.geometry.as_ref())) } pub fn opacity(&self) -> f32 { @@ -3050,6 +3079,20 @@ impl Map { projection::Flat::of(&self.projection) } + /// Tells each of its layers the system it draws them straight into + /// ([`projection::Flat::direct_system`], `None` for most maps), so a layer held in another + /// gives its places for edits and drawing as this map shows them + /// ([`rustgis_data::Dataset::shown_in`]): a vertex handle or a new vertex lands on the line the + /// map draws, not half a metre off it where the two systems' datums differ. + pub fn note_shown_system(&mut self) { + let system = self.flat().direct_system(); + for l in &mut self.layers { + if l.dataset.shown_in != system { + l.dataset.shown_in = system; + } + } + } + /// Longitude/latitude to the camera's coordinates; `None` outside the projection's area of /// use or where it folds. pub fn to_map(&self, c: Coord) -> Option { @@ -3474,6 +3517,7 @@ impl Layer { projected_crs: _, lonlat: _, unplaced: _, + extent_cache: _, drawn: _, view_memory: _, geometry_kinds: _, @@ -3493,6 +3537,7 @@ impl Layer { zm_dropped: _, windowed: _, held_in: _, + shown_in: _, } = dataset; if let Some(v) = provenance { out.push((LayerRole::Dataset, v.as_str(), true, paths::is_local(v))); @@ -3530,6 +3575,47 @@ impl Layer { } } +/// A layer's extent in longitude/latitude for its rows at a geometry revision in a coordinate +/// system ([`Layer::extent`]), behind a lock, as it is worked out through `&self`. +#[derive(Debug, Default)] +struct ExtentCache(std::sync::Mutex>); + +#[derive(Clone, Copy, Debug)] +struct ExtentKept { + rev: u64, + rows: usize, + len: usize, + crs: Crs, + extent: Extent, +} + +impl Clone for ExtentCache { + fn clone(&self) -> Self { + ExtentCache(std::sync::Mutex::new(*self.0.lock().unwrap_or_else(|e| e.into_inner()))) + } +} + +impl ExtentCache { + /// [`Dataset::lonlat_extent`] of `ds` at revision `rev`, kept until its rows, revision or + /// system change. Longitude/latitude rows are boxed as they are, which needs no keeping. + fn get(&self, ds: &Dataset, rev: u64) -> Extent { + let crs = ds.coord_crs(); + if crs == Crs::LonLat { + return ds.extent(); + } + let (rows, len) = (ds.features.allocation_key().as_ptr() as usize, ds.features.len()); + let mut kept = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(k) = *kept + && (k.rev, k.rows, k.len, k.crs) == (rev, rows, len, crs) + { + return k.extent; + } + let extent = ds.lonlat_extent(); + *kept = Some(ExtentKept { rev, rows, len, crs, extent }); + extent + } +} + /// 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)] @@ -4435,6 +4521,82 @@ mod tests { assert!(plain.lonlat_in().is_empty()); } + /// A held layer is drawn straight into a map whose projection is a coordinate system: as it + /// is on a map in its own system, by the direct operation between the two on a map in another + /// (DHDN 3-degree Gauss-Krüger zone 3 on ETRS89 UTM 32N, whose datums differ: the way through + /// WGS 84 is 0.44 m off it, see `reproject.rs`), and through longitude/latitude on Web Mercator + /// and a world projection. A place outside the map's area isn't drawn on it, as before, and + /// isn't counted as one that can't be given in longitude/latitude. + #[test] + fn a_held_layer_is_drawn_straight_into_a_map_in_a_coordinate_system() { + let line = Geometry::Line(vec![vec![Coord::new(9.18, 48.78), Coord::new(9.2, 48.8)]]); + let held = |crs: Crs| { + let mut d = Dataset::new("held", GeometryType::Polyline, vec![]); + d.push(Some(line.clone()), vec![]); + d.hold_in(crs).unwrap(); + Layer::new(1, d) + }; + let flat = |code: &str| projection::Flat::of(&Projection::Custom(code.into())); + let coords = |g: &Geometry| { + let mut v = Vec::new(); + g.for_each_coord(|c| v.push(c)); + v + }; + // On a map in its own system, its coordinates exactly. + let mut gk = held(Crs::Epsg(31467)); + let stored = gk.dataset.features[0].geometry.clone().unwrap(); + // PROJ 9.9.0 (northing first in EPSG:31467's own axis order): + // echo "48.78 9.18" | cs2cs -f %.6f EPSG:4326 EPSG:31467 -> 5404737.597295 3513304.512454 + // echo "48.8 9.2" | cs2cs -f %.6f EPSG:4326 EPSG:31467 -> 5406965.390660 3514768.524742 + // echo "5404737.597295 3513304.512454" | cs2cs -f %.6f EPSG:31467 EPSG:25832 -> 513223.740371 5403015.206314 + // echo "5406965.390660 3514768.524742" | cs2cs -f %.6f EPSG:31467 EPSG:25832 -> 514687.172659 5405242.103035 + // ("DHDN to ETRS89 (2)"; through EPSG:4326 the first is 513223.539572 5403015.518478, + // 0.37 m away). Within a millimetre. + let near = |got: &[Coord], want: &[(f64, f64)]| { + assert_eq!(got.len(), want.len()); + for (g, w) in got.iter().zip(want) { + assert!((g.x - w.0).abs() < 1e-3 && (g.y - w.1).abs() < 1e-3, "{g:?} vs PROJ {w:?}"); + } + }; + near(&coords(&stored), &[(3513304.512454, 5404737.597295), (3514768.524742, 5406965.390660)]); + let on_own = gk.projected_in(&flat("EPSG:31467"), "gk")[0].clone().unwrap(); + assert_eq!(coords(&on_own), coords(&stored)); + assert!(gk.unplaced().is_none(), "nothing is converted, so nothing is counted"); + // On ETRS89 UTM 32N, the direct operation's result, not the way through WGS 84. + let utm = flat("EPSG:25832"); + assert_eq!(utm.direct_system(), Some(Crs::Epsg(25832))); + let direct = Crs::Epsg(31467).to(Crs::Epsg(25832)).unwrap(); + let to_lonlat = Crs::Epsg(31467).to(Crs::LonLat).unwrap(); + let drawn = gk.projected_in(&utm, "utm")[0].clone().unwrap(); + for (d, s) in coords(&drawn).into_iter().zip(coords(&stored)) { + let want = direct.point(s).unwrap(); + assert!((d.x - want.x).abs() < 1e-6 && (d.y - want.y).abs() < 1e-6, "{d:?} vs {want:?}"); + let via = utm.forward_checked(to_lonlat.point(s).unwrap()).unwrap(); + assert!((d.x - via.x).hypot(d.y - via.y) > 0.1, "drawn through WGS 84: {d:?} vs {via:?}"); + } + near(&coords(&drawn), &[(513223.740371, 5403015.206314), (514687.172659, 5405242.103035)]); + assert_eq!(gk.unplaced(), Some(&Ok(0))); + // Web Mercator and a world projection draw it from longitude/latitude, as before. + for (map, key) in [(projection::Flat::Mercator, "mercator"), (flat("ESRI:54030"), "robinson")] { + assert_eq!(map.direct_system(), None, "{key}"); + let want = map.project(&to_lonlat.geometry(&stored)); + assert_eq!(gk.projected_in(&map, key)[0].as_ref(), Some(&want), "{key}"); + } + // A layer held in Web Mercator is drawn on the Web Mercator map as it is. + let mut merc = held(Crs::WebMercator); + let stored_merc = merc.dataset.features[0].geometry.clone().unwrap(); + let on_merc = merc.projected_in(&projection::Flat::Mercator, "mercator")[0].clone().unwrap(); + assert_eq!(coords(&on_merc), coords(&stored_merc)); + // A place far outside UTM 32N isn't drawn there, and isn't one longitude/latitude lacks. + let mut d = Dataset::new("far", GeometryType::Point, vec![]); + d.push(Some(Geometry::Point(Coord::new(50.0, 48.8))), vec![]); + d.hold_in(Crs::Epsg(31467)).unwrap(); + let mut far = Layer::new(2, d); + let drawn = far.projected_in(&utm, "utm")[0].clone().unwrap(); + assert!(coords(&drawn).iter().all(|c| !c.is_finite()), "{drawn:?}"); + assert_eq!(far.unplaced(), Some(&Ok(0))); + } + #[test] fn rejected_display_levels_are_not_rebuilt_on_unchanged_frames() { let flat = projection::Flat::Mercator; @@ -4606,9 +4768,9 @@ mod tests { } /// A layer's extents are in longitude/latitude, converted from its dataset's own coordinates - /// (`Dataset::coord_crs`). That is longitude/latitude for every dataset today, whatever system - /// it records, so this covers the identity: the boxes are its geometry's. Rows past the last - /// are left out. + /// (`Dataset::coord_crs`). A dataset made in code is in longitude/latitude, whatever system it + /// records, so this covers the identity: the boxes are its geometry's. Rows past the last are + /// left out. #[test] fn a_layers_extents_are_identity_converted_to_lonlat() { let mut m = Map::new("Map"); diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index bab0c3b59c..5c4ca9f4f9 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -98,6 +98,7 @@ fn bare(layer: &Layer) -> Layer { projected_crs, lonlat, unplaced: _, + extent_cache: _, drawn: _, view_memory: _, geometry_kinds: _, @@ -172,6 +173,7 @@ fn bare(layer: &Layer) -> Layer { projected_crs: *projected_crs, lonlat: lonlat.clone(), unplaced: Default::default(), + extent_cache: Default::default(), drawn: false, view_memory: Default::default(), geometry_kinds: Default::default(), @@ -268,6 +270,7 @@ impl LayerLook { lonlat: _, // What the last drawing counted and whether it drew the layer; neither is the look. unplaced: _, + extent_cache: _, drawn: _, view_memory: _, geometry_kinds: _, @@ -329,7 +332,7 @@ fn same_time(a: Option<&crate::time::TimeBinding>, b: Option<&crate::time::TimeB /// Whether two datasets hold what a frame draws alike, their rows aside (compared by allocation). fn same_dataset(a: &Dataset, b: &Dataset) -> bool { - let Dataset { name, geometry_type, fields, features: _, source, crs, crs_incomplete, zm_dropped, windowed, held_in } = a; + let Dataset { name, geometry_type, fields, features: _, source, crs, crs_incomplete, zm_dropped, windowed, held_in, shown_in } = a; *name == b.name && *geometry_type == b.geometry_type && *fields == b.fields @@ -339,6 +342,8 @@ fn same_dataset(a: &Dataset, b: &Dataset) -> bool { && *zm_dropped == b.zm_dropped && *windowed == b.windowed && *held_in == b.held_in + // Labels' lines, terrain water and block walls read its places as its map shows them. + && *shown_in == b.shown_in } /// Whether two layer groups apply alike to their layers: whether the Layers pane shows a group diff --git a/crates/map/src/projection.rs b/crates/map/src/projection.rs index 791b9d9ce0..e87833a28e 100644 --- a/crates/map/src/projection.rs +++ b/crates/map/src/projection.rs @@ -498,6 +498,10 @@ pub struct Projector { lon0: f64, /// Where the map's edge runs in WGS84 longitudes, worked out on first use (see [`Projector::edge`]). edge: std::sync::OnceLock, + /// The system it projects to as data names it, when that system's transformer is the one it + /// projects with: an EPSG or ESRI code. `None` for a preset, a `local:` view or a PROJ + /// definition. + crs: Option, } /// The edge is sampled every `EDGE_STEP`° of latitude from 90°S to 90°N: `EDGE_SAMPLES` latitudes, @@ -604,6 +608,13 @@ impl Projector { // Noted as used, so a background export of a map drawn in it says its missing grid: under // the key its transformer is kept by ([`transformer_key`]). rustgis_data::raster::crs::note_used(&transformer_key(&def, &label), || label.to_string()); + let crs = match (epsg, esri) { + (Some(c), _) => Some(Crs::Epsg(c)), + (None, Some(_)) => { + label.strip_prefix("ESRI:").and_then(|n| n.parse::().ok()).and_then(rustgis_data::raster::crs::esri_crs) + } + (None, None) => None, + }; let t = match (epsg, esri) { // Without the code its error already starts with. (Some(c), _) => rustgis_data::raster::Crs::Epsg(c) @@ -624,7 +635,7 @@ impl Projector { let domain = Domain::of(preset, &def, (lon0, lat0), pm); let engine = t; let to_meter = if to_meter.is_finite() && to_meter > 0.0 { to_meter } else { 1.0 }; - Ok(Projector { engine, to_meter, domain, lon0, edge: std::sync::OnceLock::new() }) + Ok(Projector { engine, to_meter, domain, lon0, edge: std::sync::OnceLock::new(), crs }) } /// The central meridian, in WGS84 longitudes, of a projection that shows the whole world: the @@ -746,6 +757,12 @@ impl Projector { pub fn domain(&self) -> Domain { self.domain } + + /// The system it projects to, as data in it names it: an EPSG or ESRI code; `None` for a + /// preset, a `local:` view or a PROJ definition. + pub fn crs(&self) -> Option { + self.crs + } } /// The flat map's projection, ready to convert coordinates. @@ -845,6 +862,35 @@ impl Flat { Some(if to_lonlat.is_identity() { self.project(g) } else { self.project(&to_lonlat.geometry(g)) }) } + /// The map's own coordinate system, when geometry in another can be drawn straight into it + /// ([`Flat::held`]): an EPSG or ESRI code whose map has no edge to cut along (a system limited + /// to an area of use; a world projection's cut needs longitude/latitude). `None` for Web + /// Mercator, which draws from longitude/latitude as before, and every other map. + pub fn direct_system(&self) -> Option { + match self { + Flat::Custom(p) if p.edge().is_none() => p.crs(), + _ => None, + } + } + + /// How geometry in `crs` (a layer's own system) is drawn on this map: as it is on a map in that + /// system (Web Mercator's too, whose map coordinates are its metres); on another a + /// [`Flat::direct_system`] names, by the direct operation between the two ([`Crs::to`]: the + /// datum transformation PROJ picks for the pair) where its place through longitude/latitude is + /// one the map shows, so what the map leaves out (a place past its area of use, or one it + /// folds) stays left out; on every other map, through longitude/latitude ([`Flat::project`]). + /// An error when `crs` can't be converted to longitude/latitude, when none of it can be drawn. + pub fn held(&self, crs: Crs) -> Result, String> { + let map = self.direct_system(); + if map == Some(crs) || (matches!(self, Flat::Mercator) && crs == Crs::WebMercator) { + return Ok(HeldDrawing { flat: self, to_lonlat: None, to_map: None }); + } + let to_lonlat = crs.to(Crs::LonLat)?; + // A pair with no conversion between them is drawn through longitude/latitude. + let to_map = map.and_then(|m| crs.to(m).ok()); + Ok(HeldDrawing { flat: self, to_lonlat: Some(to_lonlat), to_map }) + } + /// Map coordinates to longitude/latitude. pub fn inverse(&self, m: Coord) -> Option { match self { @@ -875,6 +921,55 @@ impl Flat { } } +/// Geometry in a layer's own system drawn on a map ([`Flat::held`]). +pub struct HeldDrawing<'a> { + flat: &'a Flat, + /// `None` on a map in the layer's own system, which draws it as it is. + to_lonlat: Option, + /// The direct operation to the map's system, when the map has one ([`Flat::direct_system`]). + to_map: Option, +} + +impl HeldDrawing<'_> { + /// Whether it draws geometry as it is (a map in the layer's own system). + pub fn is_identity(&self) -> bool { + self.to_lonlat.is_none() + } + + /// `g` in map coordinates, and whether a place of it that is a number couldn't be given in + /// longitude/latitude (what [`crate::Layer::unplaced`] counts: such a place isn't drawn). + /// Places the map can't show are NaN, which drawing skips. On a map in its own system, `g` + /// exactly as it is, with nothing lost. + pub fn geometry(&self, g: &rustgis_data::Geometry) -> (rustgis_data::Geometry, bool) { + let Some(to_lonlat) = &self.to_lonlat else { return (g.clone(), false) }; + let Some(to_map) = &self.to_map else { + let lonlat = to_lonlat.geometry(g); + let lost = missing(&lonlat) > missing(g); + return (self.flat.project(&lonlat), lost); + }; + let lost = std::cell::Cell::new(false); + let nan = Coord::new(f64::NAN, f64::NAN); + let out = g.map_coords(&|c| { + if !c.is_finite() { + return nan; + } + let Some(lonlat) = to_lonlat.point(c) else { + lost.set(true); + return nan; + }; + self.flat.forward_checked(lonlat).map_or(nan, |m| to_map.point_near(c, m)) + }); + (out, lost.get()) + } +} + +/// How many of a geometry's coordinates aren't numbers. +fn missing(g: &rustgis_data::Geometry) -> usize { + let mut n = 0usize; + g.for_each_coord(|c| n += usize::from(!c.is_finite())); + n +} + thread_local! { static PROJECTORS: std::cell::RefCell>>> = std::cell::RefCell::new(std::collections::HashMap::new()); diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index 665dd00902..28bc641f17 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -49,8 +49,27 @@ pub struct AmbiguousAreas { impl AmbiguousAreas { /// Count each affected feature once and all of its ambiguous rings. pub fn from_features(features: &[rustgis_data::Feature]) -> Self { + Self::from_geometries(features.iter().filter_map(|feature| feature.geometry.as_ref())) + } + + /// [`AmbiguousAreas::from_features`] of features given in `crs`, read in longitude/latitude + /// (a place that can't be given there is left out of its ring). + pub fn from_features_in(features: &[rustgis_data::Feature], crs: rustgis_data::raster::Crs) -> Self { + if crs == rustgis_data::raster::Crs::LonLat { + return Self::from_features(features); + } + let Ok(to) = crs.to(rustgis_data::raster::Crs::LonLat) else { return Self::default() }; + // One converted geometry at a time, not a copy of the layer. + let mut counts = Self::default(); + for g in features.iter().filter_map(|f| f.geometry.as_ref()) { + counts.include(Self::from_geometries(std::iter::once(&to.geometry(g)))); + } + counts + } + + fn from_geometries<'a>(geometries: impl Iterator) -> Self { let mut counts = Self::default(); - for geometry in features.iter().filter_map(|feature| feature.geometry.as_ref()) { + for geometry in geometries { let rings = geometry.ambiguous_area_rings(); if rings > 0 { counts.rings = counts.rings.saturating_add(rings); @@ -962,6 +981,12 @@ impl SourceLayer { Ok(new) } + /// The system its features are given in ([`FeatureSource::coord_crs`]): the file's own for a + /// file read in place; longitude/latitude until it is open. + pub fn coord_crs(&self) -> rustgis_data::raster::Crs { + self.handle.as_ref().map_or(rustgis_data::raster::Crs::LonLat, |h| h.coord_crs()) + } + /// A source that can be read whole a chunk at a time, for an export. pub fn visit_source(&self) -> Option> { self.handle.as_ref().filter(|h| h.visits_chunks()).cloned() diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index 9d3c080000..c7eee8b141 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -1,5 +1,6 @@ //! A view is decoded and projected on the source worker. The UI installs Arc-backed caches. use rustgis_data::query::Expr; +use rustgis_data::raster::Crs; use rustgis_data::source::{Batch, FeatureSource, Request, memory}; use rustgis_data::{DataError, Dataset, Field, Geometry, Result}; use rustgis_geom::Extent; @@ -17,6 +18,8 @@ pub(crate) struct Cache { pub projected_bytes: usize, /// The read kept the definition query's matches (its `matched` counts them). pub filtered: bool, + /// The system its rows are given in, the source's own ([`FeatureSource::coord_crs`]). + pub crs: Crs, } fn base_bytes(batch: &Batch, projected: &Vec>) -> usize { @@ -64,7 +67,11 @@ pub(super) fn read_mode( query: Option<&Query>, ) -> Result<(Batch, Cache)> { let read = |source: &dyn FeatureSource| -> Result<(Batch, Cache)> { - if full { Ok(whole(source.read(req)?, projection)) } else { read_with_fields(source, req, bytes, projection, estimate, fields) } + if full { + Ok(whole(source.read(req)?, projection, source.coord_crs())) + } else { + read_with_fields(source, req, bytes, projection, estimate, fields) + } }; // A query that doesn't parse draws every feature, so the view is read as without one. let Some(query) = query else { return read(source) }; @@ -81,7 +88,8 @@ pub(super) fn read_mode( } drop(first); let (batch, areas) = read_filtered(source, req, if full { usize::MAX } else { bytes / 2 }, scratch, &expr, full, &query.env)?; - let (batch, mut cache) = if full { whole(batch, projection) } else { fit(batch, bytes, projection, fields)? }; + let crs = source.coord_crs(); + let (batch, mut cache) = if full { whole(batch, projection, crs) } else { fit(batch, bytes, projection, fields, crs)? }; cache.filtered = true; if rustgis_data::query::uses_area(&expr) { cache.areas = areas; @@ -104,7 +112,9 @@ pub(super) fn walked(source: &dyn FeatureSource, query: &Query) -> Option<(Datas /// validation before a geometry measurement expression is evaluated by the layer. fn parsed_query(source: &dyn FeatureSource, query: &Query) -> Option<(Dataset, Expr)> { let info = source.info(); - let scratch = Dataset::new(info.name.clone(), info.geometry_type, query.fields.clone()); + let mut scratch = Dataset::new(info.name.clone(), info.geometry_type, query.fields.clone()); + // Its chunks come in the source's own system, which `$area` and `$length` measure from. + scratch.held_in = source.coord_crs(); let expr = rustgis_data::query::parse(&query.text, &scratch).ok()?; Some((scratch, expr)) } @@ -159,7 +169,7 @@ fn read_filtered( ))); } if measures_area && !strict { - areas.include(super::AmbiguousAreas::from_features(&scratch.features)); + areas.include(super::AmbiguousAreas::from_features_in(&scratch.features, scratch.held_in)); } let keep: Vec = (0..scratch.features.len()).map(|r| rustgis_data::query::matches(expr, &scratch, r, env)).collect(); for (feature, _) in std::mem::take(&mut scratch.features).into_iter().zip(keep).filter(|(_, k)| *k) { @@ -209,11 +219,11 @@ fn check_areas(expr: &Expr, features: &[rustgis_data::Feature], name: &str, comp } /// A whole read's cache: every feature projected, without a byte budget. -fn whole(batch: Batch, projection: &crate::Projection) -> (Batch, Cache) { +fn whole(batch: Batch, projection: &crate::Projection, crs: Crs) -> (Batch, Cache) { let flat = crate::projection::Flat::of(projection); - let projected: Vec<_> = batch.features.iter().map(|f| f.geometry.as_ref().map(|g| flat.project(g))).collect(); + let projected = projected_rows(&flat, crs, &batch.features); let cache = Cache { - areas: super::AmbiguousAreas::from_features(&batch.features), + areas: super::AmbiguousAreas::from_features_in(&batch.features, crs), extents: Arc::new(projected.iter().map(|g| g.as_ref().map_or(Extent::EMPTY, Geometry::extent)).collect()), vertices: projected.iter().flatten().map(crate::lod::thinnable).sum(), mean_bytes: 0, @@ -222,10 +232,24 @@ fn whole(batch: Batch, projection: &crate::Projection) -> (Batch, Cache) { projected: Arc::new(projected), key: projection.code(), filtered: false, + crs, }; (batch, cache) } +/// Each feature's geometry, given in `crs` (the source's own system), in the map's coordinates on +/// `flat`, as the map draws a layer held there ([`crate::projection::Flat::held`]): none when the +/// system can't be converted, as the map draws none of such a layer. +fn projected_rows(flat: &crate::projection::Flat, crs: Crs, features: &[rustgis_data::Feature]) -> Vec> { + if crs == Crs::LonLat { + return features.iter().map(|f| f.geometry.as_ref().map(|g| flat.project(g))).collect(); + } + match flat.held(crs) { + Ok(held) => features.iter().map(|f| f.geometry.as_ref().map(|g| held.geometry(g).0)).collect(), + Err(_) => features.iter().map(|_| None).collect(), + } +} + #[cfg(test)] fn read( source: &dyn FeatureSource, @@ -248,6 +272,7 @@ fn read_with_fields( fields: Option, ) -> Result<(Batch, Cache)> { let flat = crate::projection::Flat::of(projection); + let crs = source.coord_crs(); let base_budget = bytes.saturating_mul(3) / 4; let count_for = |cost: usize| req.limit.min(base_budget.saturating_mul(9) / 10 / cost.max(1)).max(usize::from(req.limit > 0)); let mut request = Request { limit: if estimate == 0 { req.limit.min(64) } else { count_for(estimate) }, ..*req }; @@ -255,7 +280,7 @@ fn read_with_fields( // Trusted row sizes avoid a second probe, but never exempt a newly oversized row. refuse_oversized(&batch, bytes)?; pad(&mut batch, bytes, fields)?; - let project = |batch: &Batch| batch.features.iter().map(|f| f.geometry.as_ref().map(|g| flat.project(g))).collect::>(); + let project = |batch: &Batch| projected_rows(&flat, crs, &batch.features); let mut projected = project(&batch); // The first small uniform sample measures real geometry and trimmed attributes rather // than padded DBF widths. Later windows reuse the measured bytes per row, avoiding a @@ -278,16 +303,16 @@ fn read_with_fields( projected = project(&batch); } } - trim(batch, projected, bytes, projection) + trim(batch, projected, bytes, projection, crs) } /// A view read some other way (a filtered walk) fitted to the view's `bytes` as a read is. -fn fit(mut batch: Batch, bytes: usize, projection: &crate::Projection, fields: Option) -> Result<(Batch, Cache)> { +fn fit(mut batch: Batch, bytes: usize, projection: &crate::Projection, fields: Option, crs: Crs) -> Result<(Batch, Cache)> { refuse_oversized(&batch, bytes)?; pad(&mut batch, bytes, fields)?; let flat = crate::projection::Flat::of(projection); - let projected = batch.features.iter().map(|f| f.geometry.as_ref().map(|g| flat.project(g))).collect(); - trim(batch, projected, bytes, projection) + let projected = projected_rows(&flat, crs, &batch.features); + trim(batch, projected, bytes, projection, crs) } /// Refuses a read holding a feature larger than the whole view budget. @@ -323,7 +348,13 @@ fn pad(batch: &mut Batch, bytes: usize, fields: Option) -> Result<()> { /// Thins the rows and their projection evenly until they fit three quarters of `bytes`, and /// builds the window's cache. -fn trim(mut batch: Batch, mut projected: Vec>, bytes: usize, projection: &crate::Projection) -> Result<(Batch, Cache)> { +fn trim( + mut batch: Batch, + mut projected: Vec>, + bytes: usize, + projection: &crate::Projection, + crs: Crs, +) -> Result<(Batch, Cache)> { let base_budget = bytes.saturating_mul(3) / 4; // Keep room for display levels. Actual allocation accounting also handles projections // that split at a world seam and create more parts than the original geometry. @@ -350,7 +381,7 @@ fn trim(mut batch: Batch, mut projected: Vec>, bytes: usize, pr let mean_bytes = base_bytes(&batch, &projected).div_ceil(batch.features.len().max(1)); let feature_bytes = memory::features_bytes(&batch.features); let projected_bytes = crate::lod::cache_bytes(&projected); - let areas = super::AmbiguousAreas::from_features(&batch.features); + let areas = super::AmbiguousAreas::from_features_in(&batch.features, crs); Ok(( batch, Cache { @@ -363,6 +394,7 @@ fn trim(mut batch: Batch, mut projected: Vec>, bytes: usize, pr feature_bytes, projected_bytes, filtered: false, + crs, }, )) } diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index 44ddcdea4e..98cb993f27 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -211,6 +211,7 @@ fn layer_geojson(inputs: &dyn Inputs, name: &str) -> Result { zm_dropped: false, windowed: false, held_in: ds.held_in, + shown_in: None, }; Ok(rustgis_data::io::to_geojson(&*sub.in_lonlat()?)) } diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index b096f550bd..561fddbb2a 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -496,7 +496,7 @@ fn units(layer: &rustgis_map::Layer, b: &Block, water: bool, env: &rustgis_data: let (mut parts, mut ids): (Vec, Vec<(usize, usize)>) = (Vec::new(), Vec::new()); // Its conversion to longitude/latitude, made once for its polygons (none: a system that can't // be converted, of which the map draws nothing either). - let to = layer.dataset.lonlat_conversion().ok(); + let to = layer.dataset.shown_conversion().ok(); for (row, ft) in layer.dataset.features.iter().enumerate() { if keep.as_ref().is_some_and(|k| !k.get(row).copied().unwrap_or(false)) { continue; @@ -632,7 +632,7 @@ pub(crate) fn water_runs(map: &Map, b: &Block, ground: &Ground, res: f64, scale: // each crossing few of them). let mut near_box: std::collections::HashMap> = std::collections::HashMap::new(); // The layer's conversion to longitude/latitude, as the cut's parts were read (`units`). - let to = layer.dataset.lonlat_conversion().ok(); + let to = layer.dataset.shown_conversion().ok(); for (i, runs) in out.iter_mut().enumerate() { let (side, _, _) = b.side(i); let Some(units) = cut.units.get(i) else { continue }; diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index dac8bfb345..3cdc883660 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2255,6 +2255,8 @@ fn complete_shown_legends( let mut no_data = None; let mut chunk = layer.clone(); chunk.source = None; + // Its chunks come in the source's own system. + chunk.dataset.held_in = source.coord_crs(); chunk.clear_cache(); let result = crate::visit_complete(source.as_ref(), &mut |features| { chunk.dataset.features = features.into(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b0044b49f6..47b68864eb 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2314,6 +2314,8 @@ fn render_pass( layer.selection = features.iter().enumerate().filter_map(|(r, f)| ids.contains(&f.id).then_some(r)).collect(); layer.source = None; layer.dataset.features = features.into(); + // Held as the source gives them, in its own system. + layer.dataset.held_in = source.coord_crs(); layer.clear_cache(); layer.touch_geometry(); } @@ -3681,7 +3683,9 @@ fn upright_markers_with(map: &mut Map, view: &View, margin: f64, env: &Env) -> V let scale = map.ground_res_at(&view.camera) / rustgis_geom::PIXEL_M; let (flat, key) = (map.flat(), map.projection.code()); let cull = view.camera.extent(view.width, view.height).padded(margin.clamp(CULL_MARGIN, 4.0), 0.0); - let clip = map.view.clip_distance.map(|d| (view.camera.center_lonlat(), d)); + // The view's centre in longitude/latitude from the map's own coordinates (Web Mercator or + // the map's system); none, so nothing is clipped, where the projection has no place there. + let clip = map.view.clip_distance.and_then(|d| Some((map.to_lonlat(view.camera.center)?, d))); let held = map.held_by_group(scale); let group_opacity = map.group_opacities(); let upright: std::collections::HashSet = map.layers.iter().filter(|l| stands_up(map, l)).map(|l| l.id).collect(); @@ -3718,7 +3722,7 @@ fn upright_markers_with(map: &mut Map, view: &View, margin: f64, env: &Env) -> V }; let lonlat = clip.and_then(|_| { let own = layer.dataset.features.get(row).and_then(|f| f.geometry.as_ref())?.extent(); - Some(to_lonlat.as_ref().map_or(rustgis_geom::Extent::EMPTY, |t| t.extent(&own))) + Some(to_lonlat.as_ref().map_or(rustgis_geom::Extent::EMPTY, |t| t.feature_extent(&own))) }); if let (Some((centre, d)), Some(e)) = (clip, lonlat) { let near = Coord::new(centre.x.clamp(e.min_x, e.max_x), centre.y.clamp(e.min_y, e.max_y)); @@ -4093,7 +4097,7 @@ pub(crate) fn within_view_distance(rows: &mut [bool], dataset: &rustgis_data::Da .features .get(r) .and_then(|f| f.geometry.as_ref()) - .and_then(|g| to.as_ref().map(|t| t.extent(&g.extent()))) + .and_then(|g| to.as_ref().map(|t| t.feature_extent(&g.extent()))) .filter(|e| !e.is_empty()); *keep = e.is_some_and(|e| { let near = Coord::new(centre.x.clamp(e.min_x, e.max_x), centre.y.clamp(e.min_y, e.max_y)); @@ -4532,7 +4536,9 @@ fn render_frame( // 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); - let clip = map.view.clip_distance.map(|d| (view.camera.center_lonlat(), d)); + // The view's centre in longitude/latitude from the map's own coordinates (Web Mercator or + // the map's system); none, so nothing is clipped, where the projection has no place there. + let clip = map.view.clip_distance.and_then(|d| Some((map.to_lonlat(view.camera.center)?, d))); // Each layer group's visibility, scale range and transparency apply to its layers, its // subgroups' too (#413, #836). let held = map.held_by_group(scale); @@ -4747,11 +4753,20 @@ fn render_frame( { let result = owner.cached_thinning(&key, level, || { let (mut eligible, mut all, mut kept) = (0usize, 0usize, 0usize); + // Its features come in the source's own system: drawn as the map draws a layer + // held there. + let crs = source.coord_crs(); + let held = (crs != rustgis_data::raster::Crs::LonLat).then(|| flat.held(crs).ok()).flatten(); visit_complete(source.as_ref(), &mut |features| { for feature in features { if let Some(g) = feature.geometry { let tolerance = rustgis_map::lod::tolerance(level); - let (counted, thinned) = if matches!(flat, rustgis_map::projection::Flat::Mercator) { + let (counted, thinned) = if crs != rustgis_data::raster::Crs::LonLat { + let Some(held) = &held else { continue }; + let projected = held.geometry(&g).0; + let thinned = rustgis_map::lod::thin(&projected, tolerance); + (projected, thinned) + } else if matches!(flat, rustgis_map::projection::Flat::Mercator) { let thinned = rustgis_map::lod::project_thinned(&g, &flat, tolerance); (g, thinned) } else { @@ -4899,7 +4914,9 @@ fn render_frame( // extrusion keep `geoms`, the full geometry, for their exact positions. let chunk_thinned: Vec> = if thin_complete && !display_only { let tolerance = rustgis_map::lod::level(thin_tol).map_or(thin_tol, rustgis_map::lod::tolerance); - if matches!(flat, rustgis_map::projection::Flat::Mercator) { + // Projected and thinned at once from longitude/latitude rows; from any other + // system, the projected geometry is thinned. + if matches!(flat, rustgis_map::projection::Flat::Mercator) && ds_ptr.coord_crs() == rustgis_data::raster::Crs::LonLat { ds_ptr .features .iter() @@ -5835,6 +5852,8 @@ fn render_frame( if let Some(source) = source { let mut chunk = layer.clone(); chunk.source = None; + // Its chunks come in the source's own system. + chunk.dataset.held_in = source.coord_crs(); chunk.clear_cache(); chunk.dataset.features = Vec::new().into(); // All coordinates are read here: filtering only to the viewport can change labels, @@ -6159,10 +6178,26 @@ fn layer_masks( } }; if let Some(source) = map.layers.get(mi).and_then(|l| l.source.as_ref()).and_then(|s| s.chunk_source()) { + // Its features come in the source's own system: in longitude/latitude for + // the globe, as the map draws them on a flat map. + let crs = source.coord_crs(); + let to_lonlat = crs.to(rustgis_data::raster::Crs::LonLat).ok(); + let held = flat.held(crs).ok(); let result = visit_complete(source.as_ref(), &mut |features| { for feature in features { if let Some(g) = feature.geometry { - let g = if ctx.globe.is_some() { g } else { flat.project(&g) }; + let g = match (ctx.globe.is_some(), crs == rustgis_data::raster::Crs::LonLat) { + (true, true) => g, + (true, false) => match &to_lonlat { + Some(to) => to.geometry(&g), + None => continue, + }, + (false, true) => flat.project(&g), + (false, false) => match &held { + Some(held) => held.geometry(&g).0, + None => continue, + }, + }; add(&g); } } @@ -6495,6 +6530,8 @@ fn render_globe_drape_drawn(map: &mut Map, view: &View, boxes: &[Extent], max_si } let max_side = f64::from(max_side.clamp(64, 8192)); let projection = std::mem::replace(&mut map.projection, rustgis_map::Projection::WebMercator); + // Edits' and labels' places shown as these patches draw them, through longitude/latitude. + map.note_shown_system(); let (display, lock) = (map.label_display, map.label_lock.take()); let anchors = std::mem::take(&mut map.label_lock_line_anchors); map.label_display.paused = true; @@ -6522,6 +6559,7 @@ fn render_globe_drape_drawn(map: &mut Map, view: &View, boxes: &[Extent], max_si } } map.projection = projection; + map.note_shown_system(); map.label_display = display; map.label_lock = lock; map.label_lock_line_anchors = anchors; @@ -6696,7 +6734,7 @@ fn square_lines( // 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 // converted), as the map draws none of it. - let Ok(to) = layer.dataset.lonlat_conversion() else { continue }; + let Ok(to) = layer.dataset.shown_conversion() else { continue }; for g in layer.dataset.features.iter().filter_map(|f| rustgis_data::Dataset::converted_to_lonlat(&to, f.geometry.as_ref()?)) { let (parts, rings): (Vec<&Vec>, bool) = match &*g { Geometry::Line(parts) => (parts.iter().collect(), false), diff --git a/crates/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index f8d3f07223..6fc3a1533e 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -487,7 +487,7 @@ fn polygons(layer: &rustgis_map::Layer, level: Option<&str>, drawn: Option<&[boo let mut polygons = Vec::new(); // Its conversion to longitude/latitude, made once for its polygons (none: a system that can't // be converted, of which the map draws nothing either). - let to = layer.dataset.lonlat_conversion().ok(); + let to = layer.dataset.shown_conversion().ok(); for (row, ft) in layer.dataset.features.iter().enumerate() { if drawn.is_some_and(|d| !d.get(row).copied().unwrap_or(false)) { continue; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6e613c2fe6..9fca4d6d72 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -6413,6 +6413,8 @@ impl RustGisApp { // never waits for cast shadows still being worked out: it says they were (Never hold the // window). Exports drawn off it wait for them. rustgis_engine::render::on_the_interface_thread(); + // Layers landed from a background read meanwhile learn their map's system too. + self.session.note_shown_systems(); // A pass egui asks to repeat is the same frame: `ui` sets the delay once, from the first pass. if ctx.current_pass_index() == 0 { self.frame_start = Some(web_time::Instant::now()); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 1addb76e63..8135fb6670 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -2291,7 +2291,7 @@ pub(crate) fn text_graphic_at(app: &RustGisApp, ctx: &egui::Context, rect: Rect, let tokens = graphics::TokenValues::of(map, scale); // Only what is drawn, as render_frame draws it: the first layer on top, and in a layer the // last row. Fully transparent layers and rows beyond the view clipping distance are not drawn. - let clip = map.view.clip_distance.map(|d| (map.camera.center_lonlat(), d)); + let clip = map.view.clip_distance.and_then(|d| Some((map.to_lonlat(map.camera.center)?, d))); map.layers.iter().filter(|l| l.graphics && l.selectable && map.draws_at(l, scale) && map.layer_opacity(l) > 0.0).find_map(|l| { let drawn = l.drawn_rows(scale); // Boxes in longitude/latitude, as the view distance is measured there: none when the @@ -2302,7 +2302,7 @@ pub(crate) fn text_graphic_at(app: &RustGisApp, ctx: &egui::Context, rect: Rect, if let Some((centre, d)) = clip { // No extent (an empty geometry, or one whose conversion isn't a number): nothing // of it is drawn, and clamping to its extent would panic. - let e = to_lonlat.extent(&g.extent()); + let e = to_lonlat.feature_extent(&g.extent()); if e.is_empty() { return None; } @@ -2330,9 +2330,9 @@ fn text_shown( use rustgis_engine::map::graphics; let ds = &l.dataset; let text = graphics::expand(graphics::label(ds, row)?, tokens); - // Its place in longitude/latitude, from the layer's own coordinates (the identity today). + // Its place in longitude/latitude, from the layer's own coordinates, as the map shows them. let place = ds.features.get(row)?.geometry.as_ref()?.label_point()?; - let to_lonlat = ds.lonlat_conversion().ok()?; + let to_lonlat = ds.shown_conversion().ok()?; let place = if to_lonlat.is_identity() { place } else { to_lonlat.point(place)? }; let at = lonlat_to_screen(app, rect, place)?; let job = label_job( diff --git a/crates/ui-egui/src/vertexedit.rs b/crates/ui-egui/src/vertexedit.rs index d9cf7ec4a6..b53c8007cb 100644 --- a/crates/ui-egui/src/vertexedit.rs +++ b/crates/ui-egui/src/vertexedit.rs @@ -102,7 +102,7 @@ impl DragOwner { preview: shared_origin(app, d).and_then(|original| { // Matched in the layer's own coordinates, where shared vertices are equal, and // drawn in longitude/latitude, as the handles are. - let to = layer.dataset.lonlat_conversion().ok()?; + let to = layer.dataset.shown_conversion().ok()?; let lonlat = |c: Coord| if to.is_identity() { Some(c) } else { to.point(c) }; let edges = shared_edges(layer.dataset.features.iter(), original); Some(SharedPreview { diff --git a/crates/ui-egui/tests/define_projection.rs b/crates/ui-egui/tests/define_projection.rs index 0d23c31c19..0c6a99ccc4 100644 --- a/crates/ui-egui/tests/define_projection.rs +++ b/crates/ui-egui/tests/define_projection.rs @@ -52,7 +52,12 @@ fn dialog_applies_to_captured_layer_and_undo_restores_native_coordinates() { h.step(); assert!(h.state().dialogs.open.is_none()); let point = |app: &RustGisApp, name: &str| { - app.session.map().layer_by_name(name).unwrap().dataset.features[0].geometry.as_ref().unwrap().label_point().unwrap() + app.session.map().layer_by_name(name).unwrap().dataset.in_lonlat().unwrap().features[0] + .geometry + .as_ref() + .unwrap() + .label_point() + .unwrap() }; assert!((point(h.state(), "Parcels").x - 2.335).abs() < 1e-6); assert_eq!(point(h.state(), "Other").x, 451_219.33); @@ -83,12 +88,23 @@ fn import_dialog_passes_crs_to_browser_upload_before_wrong_prj_is_read() { let ordinary = h.state_mut().open_picked("ordinary.zip", &bytes).unwrap(); let ordinary_id = ordinary["layer"].as_u64().unwrap() as u32; assert_eq!( - h.state().session.map().layer(ordinary_id).unwrap().dataset.features[0].geometry.as_ref().unwrap().label_point().unwrap().x, + h.state().session.map().layer(ordinary_id).unwrap().dataset.in_lonlat().unwrap().features[0] + .geometry + .as_ref() + .unwrap() + .label_point() + .unwrap() + .x, 451_219.33 ); let result = h.state_mut().open_picked(&format!("{}parcels.zip", rustgis_ui_egui::SHAPEFILE_PICK), &bytes).unwrap(); let id = result["layer"].as_u64().unwrap() as u32; - let point = h.state().session.map().layer(id).unwrap().dataset.features[0].geometry.as_ref().unwrap().label_point().unwrap(); + let point = h.state().session.map().layer(id).unwrap().dataset.in_lonlat().unwrap().features[0] + .geometry + .as_ref() + .unwrap() + .label_point() + .unwrap(); assert!((point.x - 2.335).abs() < 1e-6, "{point:?}"); // The browser can return several grouped Shapefiles from one pick. let second = h.state_mut().open_picked(&format!("{}another.zip", rustgis_ui_egui::SHAPEFILE_PICK), &bytes).unwrap(); @@ -193,7 +209,7 @@ fn downloaded_shapefile_keeps_the_requested_source_crs() { std::thread::sleep(std::time::Duration::from_millis(20)); // test-wait: legacy polling for the downloaded layer } let layer = h.state().session.map().layer_by_name("Downloaded").unwrap(); - let point = layer.dataset.features[0].geometry.as_ref().unwrap().label_point().unwrap(); + let point = layer.dataset.in_lonlat().unwrap().features[0].geometry.as_ref().unwrap().label_point().unwrap(); assert!((point.x - 2.335).abs() < 1e-6 && (point.y - 48.855).abs() < 1e-6, "{point:?}"); assert_eq!(layer.dataset.crs, Some(rustgis_engine::data::raster::Crs::parse("EPSG:32631").unwrap())); } diff --git a/docs/comparison/index.md b/docs/comparison/index.md index 1e8da16e7b..0c35536a87 100644 --- a/docs/comparison/index.md +++ b/docs/comparison/index.md @@ -141,7 +141,9 @@ Stated plainly, so the tables above are worth trusting: The native File Geodatabase reader is 2D and does not read compressed tables, raster fields or sparse row layouts; GDAL can fill these gaps on desktop. DWG and rasters such as JPEG 2000, NetCDF and HDF also need GDAL. SQL queries need DuckDB; both are external programs. -- **Coordinate systems.** Vector data is stored in longitude/latitude; there is no full PROJ. +- **Coordinate systems.** A file's vector data keeps the file's own coordinates and is drawn + in the map's projection on the fly; databases and point clouds are read in longitude/latitude, + and analysis tools still work there. There is no full PROJ. - **Editing depth.** Vertex move, insert and delete are supported, but not versioned multi-user database editing. Desktop GeoPackage and PostGIS layers loaded for editing can save back to their source tables with row-conflict checks; other edits stay in the project diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index ddf2c79358..3add116bf9 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -803,7 +803,7 @@ gp.run={"tool":"near","params":{"input":"addresses","near":"hydrants","units":"F **Spatial Join** (`spatialJoin`, also `gp.spatialJoin`) copies attributes from `join` features to `target` features. Layers may have different source coordinate systems: their geometry is -stored in longitude/latitude before the join. `match` is one of: +converted to longitude/latitude for the join. `match` is one of: - **Intersects** (default), **Contains** (target contains join) or **Within** (target lies within join). @@ -1207,7 +1207,8 @@ CRS metadata. Coordinates are used directly, without projection or snapping. output memory, including repeated text attributes, before building the segments; unavailable memory returns an error. - **Feature Envelope To Polygon** (`featureEnvelopeToPolygon`) writes one axis-aligned rectangle - around all coordinates of each feature in stored longitude/latitude axes. Point features and + around all coordinates of each feature in longitude/latitude axes (converted from the layer's + own system). Point features and horizontal or vertical lines have zero-area envelopes and are skipped with a count. Longitude bounds are literal, including for features spanning the antimeridian. - **Unsplit Line** (`unsplitLine`) joins line parts at exactly equal endpoints where precisely diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 7c24596b67..069240da11 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -18,7 +18,7 @@ export names its feature. | Format | Extensions or source | How to add it | Notes | | --- | --- | --- | --- | -| GeoJSON | `.geojson`, `.json` | Home › Add › Add Data, or drop the file | Features with typed attributes; a single-member `GeometryCollection` is unwrapped (including nested single-member collections). Empty or multi-member collections are unsupported: the whole feature, including its attributes, is skipped and counted in an unreadable-geometry notice. A FeatureCollection's legacy `crs` member (`{"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::28992"}}`) is honoured for EPSG codes (`EPSG:28992`, `urn:ogc:def:crs:EPSG::28992`, `urn:ogc:def:crs:EPSG:6.6:28992`) and for `CRS84`: a projected or other non-WGS 84 system converts the coordinates to longitude/latitude and the layer keeps it as its coordinate system (Layer properties, export in it, Define Projection); `CRS84` and `EPSG:4326` are longitude/latitude already, so the coordinates stay as they are and the layer has no other coordinate system. Coordinates are x/y (easting/northing, or longitude/latitude) whatever the EPSG axis order. A `crs` that isn't understood (a `link`, WKT or PROJ text, any other name, an unknown code) is named in a notice and the coordinates are read as longitude/latitude. A feature whose coordinates can't be converted, or convert to beyond ±180.5° longitude or ±90.5° latitude (the declared system doesn't fit the numbers), is left out and counted in a notice, and Define Projection then asks for the file to be added again. A feature read as longitude/latitude (no `crs`, `CRS84` or `EPSG:4326`, or a `crs` that isn't understood) with a position whose longitude is within ±180.5° but whose latitude is past ±90.5° is kept, and one notice counts them: longitude and latitude may be swapped. A `crs` on a feature, a geometry or a lone Feature is ignored. GeoJSON is always written in WGS 84 without a `crs`. Desktop FeatureCollections larger than 32 MiB use an in-place reader (which honours `crs` too, reading the file once more to check the features convert); layers with more than 100,000 features stream a view at a time. Other GeoJSON files load whole: a FeatureCollection up to 32 MiB, or any with `"stream": false`, up to the size read into memory (256 MiB in the web app; on the desktop about 512 MiB for every 16 GiB of memory, up to 4 GiB: `fileBytes` in [Environments](analysis.md)); another GeoJSON document larger than 32 MiB up to 256 MiB, as it is read as it is added. A GeoJSON read whole whose attribute table (a cell for every field in every feature) would take more than 8 times that size is refused, saying the table's size: many features with properties spread over many fields. | +| GeoJSON | `.geojson`, `.json` | Home › Add › Add Data, or drop the file | Features with typed attributes; a single-member `GeometryCollection` is unwrapped (including nested single-member collections). Empty or multi-member collections are unsupported: the whole feature, including its attributes, is skipped and counted in an unreadable-geometry notice. A FeatureCollection's legacy `crs` member (`{"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::28992"}}`) is honoured for EPSG codes (`EPSG:28992`, `urn:ogc:def:crs:EPSG::28992`, `urn:ogc:def:crs:EPSG:6.6:28992`) and for `CRS84`: a projected or other non-WGS 84 system is the layer's own: its coordinates are kept as the file holds them and drawn in the map's projection (Layer properties, export in it, Define Projection); `CRS84` and `EPSG:4326` are longitude/latitude already, so the coordinates stay as they are and the layer has no other coordinate system. Coordinates are x/y (easting/northing, or longitude/latitude) whatever the EPSG axis order. A `crs` that isn't understood (a `link`, WKT or PROJ text, any other name, an unknown code) is named in a notice and the coordinates are read as longitude/latitude. A feature whose coordinates can't be converted, or convert to beyond ±180.5° longitude or ±90.5° latitude (the declared system doesn't fit the numbers), is left out and counted in a notice, and Define Projection then asks for the file to be added again. A feature read as longitude/latitude (no `crs`, `CRS84` or `EPSG:4326`, or a `crs` that isn't understood) with a position whose longitude is within ±180.5° but whose latitude is past ±90.5° is kept, and one notice counts them: longitude and latitude may be swapped. A `crs` on a feature, a geometry or a lone Feature is ignored. GeoJSON is always written in WGS 84 without a `crs`. Desktop FeatureCollections larger than 32 MiB use an in-place reader (which honours `crs` too, reading the file once more to check the features convert); layers with more than 100,000 features stream a view at a time. Other GeoJSON files load whole: a FeatureCollection up to 32 MiB, or any with `"stream": false`, up to the size read into memory (256 MiB in the web app; on the desktop about 512 MiB for every 16 GiB of memory, up to 4 GiB: `fileBytes` in [Environments](analysis.md)); another GeoJSON document larger than 32 MiB up to 256 MiB, as it is read as it is added. A GeoJSON read whole whose attribute table (a cell for every field in every feature) would take more than 8 times that size is refused, saying the table's size: many features with properties spread over many fields. | | Delimited text | `.csv`, `.tsv`, `.txt`, recognised `.dat`; UTF-8 `.csv.gz`, `.tsv.gz`, `.txt.gz`, `.dat.gz` | Add Data, or Home › Add › Add Data › Delimited Text… to choose the columns from the file's header | Comma, semicolon, tab or pipe separated (found from the header, or `"delimiter"`); `info.fileColumns` lists the columns and the ones found. Points from x/y columns (named like longitude/latitude, in English or another language such as `經度`/`緯度`, GTFS `stop_lon`/`stop_lat` or easting/northing, or chosen with `"x"` and `"y"`), or any geometry from a WKT/EWKT column (named like `wkt` or `geometry`, or `"wkt"`). When an inferred pair exceeds degree ranges, a recognised longitude/latitude pair is preferred only if its in-range, non-0,0 points cover at least as many rows as the first pair can place, unless a projected `"crs"` is given (see [Delimited Text](data.md) for aliases and sampling). Coordinates in another system are converted from `"crs"` (`EPSG:2263`, or WKT) or an EWKT `SRID=`; rows still read outside longitude/latitude are counted in a notice. Points placed at exactly 0,0 are kept and counted in a notice, as they may represent missing coordinates. Uncompressed text is UTF-8, or UTF-16 with its byte-order mark; other uncompressed files are read as Windows-1252 (Latin-1, as many public sources still publish CSV), with a notice saying so. Gzip input is UTF-8 only, streamed within the size read into memory of expanded text (256 MiB in the web app); decompress other encodings and add as `.txt`. Retained CSV rows and cells have a separate estimated memory budget (256 MiB in the browser; a quarter of physical memory between 256 MiB and 4 GiB on desktop). A file without coordinates opens as a standalone table. | | Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer or standalone table, at most 32 layers and tables together for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) opens as a standalone table, with its `.cpg` when present. An orphan MapInfo `.mid` without its `.mif` is skipped and named in the archive's notice. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | | dBASE table | `.dbf`, with `.cpg` when present | Add Data or drop the file; in the browser, pick or drop the `.dbf` and `.cpg` together, or zip them | Without a `.shp` beside it, opens as an editable standalone table. Uses the same code page, field types and loss notices as Shapefile attributes (including integer, double, Boolean and date fields). On the desktop, picking a `.dbf` with a `.shp` beside it opens that Shapefile instead; in the browser pick its parts together. ZIP tables share the archive's 32-layer/table budget. | @@ -766,8 +766,10 @@ it by default (see [Writing](#writing)). This differs from changing the map's coordinate system, which only changes the display, or exporting to another CRS, which converts coordinate numbers while preserving locations. -RustGIS stores geometry in longitude/latitude, so Define Projection first reconstructs native -numbers through the previous CRS; small floating-point rounding differences are possible. +A layer read from a file keeps the file's own numbers, so Define Projection only relabels them. A +layer kept in a project saved by an older release holds its geometry in longitude/latitude: its +native numbers are first reconstructed through the previous CRS, where small floating-point +rounding differences are possible. Edits already made to the layer are reinterpreted too. If the wrong CRS already discarded or clamped coordinates, import the original file again to recover them accurately. diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 828dadccac..d52c154523 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -787,7 +787,12 @@ both sides of the map. Each projection has an area of use: polar projections sho their hemisphere poleward of 30°, regional ones their region, transverse Mercator (UTM) zones 30° either side of their meridian, and data outside it isn't drawn. Switching keeps the centre and scale, and the choice is saved with the map (`map.projection` from the command line). A -raster already in the map's coordinate system draws without being reprojected. To open every new +raster already in the map's coordinate system draws without being reprojected, and so does a +vector layer read from a file in it. On a map in another EPSG or ESRI system limited to an area of +use, a layer is drawn into it by the direct transformation between the two systems (the datum +shift PROJ picks for the pair, not one through WGS 84), and its vertices are edited and snapped +where they are drawn; Web Mercator, the globe and world projections draw through +longitude/latitude. To open every new session in a projection, set it in **Settings › Start-up › Projection**. Robinson, Equal Earth, Natural Earth, Winkel Tripel and Eckert IV are computed by RustGIS itself on a sphere, so EPSG:8857 (Equal Earth) works too. So is the sinusoidal projection, on a sphere or an From 26212f594389f32f19d7ac145af2d41e5027b546 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 11:54:00 +0100 Subject: [PATCH 02/15] Review round 1: wasm dead code gated, GML keeps unconvertible places missing, identity draw counts none, Paste Special keeps crs_incomplete, topology read-ahead compares systems, cancel stops hold_as, shown systems before nested commands, copy-free clip extent, docs --- crates/data/src/gml.rs | 59 ++++++++++++++++++++------ crates/data/src/io.rs | 2 + crates/data/src/lib.rs | 7 ++- crates/data/src/source/chunk_memory.rs | 15 ++++++- crates/data/src/source/mod.rs | 4 ++ crates/engine/src/cmd/clipboard.rs | 2 + crates/engine/src/cmd/design.rs | 6 +-- crates/engine/src/cmd/labels.rs | 7 ++- crates/engine/src/cmd/workflows.rs | 22 +++++++--- crates/engine/src/lib.rs | 6 +-- crates/engine/src/tests/held_layers.rs | 12 +++++- crates/map/src/lib.rs | 18 +++++++- crates/map/src/source/window.rs | 8 ++-- docs/user-guide/data-formats.md | 7 +-- 14 files changed, 133 insertions(+), 42 deletions(-) diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 6a857c9d88..51968853ca 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -662,21 +662,34 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> Some((_, true)) => g.map_coords(&|c| Coord::new(c.y, c.x)), _ => g, }); - if let Some(g) = &g { - // Its box in longitude/latitude: a place that can't be given there isn't drawn - // (the map counts it), as one converted to NaN wasn't. - let e = match &transform { - Some((Some(t), _)) => { - let mut e = rustgis_geom::Extent::EMPTY; - g.for_each_coord(|c| { - if let Some(l) = t.to_lonlat(c) { - e.expand(l); - } - }); - e + // A place that can't be given in longitude/latitude is kept as a missing coordinate + // (NaN), as it was when the reader converted the file: the layer is drawn, saved and + // measured without it, as before. Its box in longitude/latitude from the rest. + let mut e = rustgis_geom::Extent::EMPTY; + let g = match (&transform, g) { + (Some((Some(t), _)), Some(g)) => { + let lonlat = std::cell::Cell::new(rustgis_geom::Extent::EMPTY); + let kept = g.map_coords(&|c| match t.to_lonlat(c) { + Some(l) if l.is_finite() => { + let mut b = lonlat.get(); + b.expand(l); + lonlat.set(b); + c + } + _ if !c.is_finite() => c, + _ => Coord::new(f64::NAN, f64::NAN), + }); + e = lonlat.get(); + Some(kept) + } + (_, g) => { + if let Some(g) = &g { + e = g.extent(); } - _ => g.extent(), - }; + g + } + }; + if !e.is_empty() { outside |= e.min_x < -180.0 || e.max_x > 180.0 || e.min_y < -90.0 || e.max_y > 90.0; } let row = ds @@ -850,6 +863,24 @@ mod tests { assert!(layers[0].1.messages.iter().all(|m| !m.contains("written as Null")), "no marker, no notice: {:?}", layers[0].1.messages); } + /// A place a file's system can't give in longitude/latitude is kept missing (NaN), as when the + /// reader converted the file, so the layer still saves and is read in longitude/latitude; its + /// other places keep the file's numbers. + #[test] + fn a_place_with_no_longitude_latitude_is_kept_missing() { + let gml = r#" +500000,4649776 1e15,4649776 +"#; + let layers = read("r.gml", gml.as_bytes()).unwrap(); + let (ds, _) = &layers[0]; + assert_eq!(ds.coord_crs(), Crs::Epsg(32633)); + let Some(Geometry::Line(parts)) = &ds.features[0].geometry else { panic!("a line") }; + assert_eq!(parts[0][0], Coord::new(500000.0, 4649776.0), "the file's numbers"); + assert!(parts[0][1].x.is_nan() && parts[0][1].y.is_nan(), "{:?}", parts[0][1]); + assert!(serde_json::to_string(ds).is_ok(), "saves"); + assert!(ds.in_lonlat().is_ok()); + } + #[test] fn reads_gml2_and_projected() { // OGR-style GML 2: gml:coordinates, EPSG:32633 (easting/northing), a MultiPolygon. diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 0edb2d94c7..4e0104b91b 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1414,6 +1414,8 @@ fn is_epsg_or_crs84_name(name: &str) -> bool { /// A geometry in longitude/latitude from the coordinates `t` converts: `None` when a coordinate /// can't be converted or comes out beyond longitude/latitude (a declared system that doesn't match /// the coordinates). +// Used by the in-place readers and databases, which the web app hasn't. +#[cfg(not(target_arch = "wasm32"))] pub(crate) fn geometry_to_lonlat(g: &Geometry, t: &crate::raster::Transformer) -> Option { let mut ok = true; let out = g.map_coords(&|c| t.to_lonlat(c).unwrap_or(Coord::new(f64::NAN, f64::NAN))); diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 3b510bace7..b8c7aa0624 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -461,10 +461,9 @@ fn held_in_lonlat() -> raster::Crs { impl Dataset { /// The coordinate system its geometry is in ([`Dataset::held_in`]): the system a file was read /// in, else longitude/latitude (WGS 84). Drawing converts geometry from it - /// ([`raster::Crs::to`]). 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 (the map - /// counts them as it draws, `Layer::unplaced`). + /// ([`raster::Crs::to`]). 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 (the map counts them as it draws, `Layer::unplaced`). pub fn coord_crs(&self) -> raster::Crs { self.held_in } diff --git a/crates/data/src/source/chunk_memory.rs b/crates/data/src/source/chunk_memory.rs index fd4f56d2b0..cc4fd8ee66 100644 --- a/crates/data/src/source/chunk_memory.rs +++ b/crates/data/src/source/chunk_memory.rs @@ -93,7 +93,20 @@ pub fn clip_row( width: usize, to_lonlat: &crate::raster::Reprojection, ) -> Result, DataError> { - let lonlat = |g: &crate::Geometry| if to_lonlat.is_identity() { g.extent() } else { to_lonlat.geometry(g).extent() }; + // A place at a time, without a converted copy of the shape; one that can't be converted is + // left out of the extent, as a converted copy's missing place is. + let lonlat = |g: &crate::Geometry| { + if to_lonlat.is_identity() { + return g.extent(); + } + let mut e = Extent::EMPTY; + g.for_each_coord(|c| { + if let Some(m) = to_lonlat.point(c) { + e.expand(m); + } + }); + e + }; if row.geometry.as_ref().is_none_or(|g| !lonlat(g).intersects(extent)) { return Ok(None); } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index dd1cf2cf52..f56bef72e6 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -901,6 +901,8 @@ impl Reproject { /// The geometry converted to longitude/latitude; `None` when a coordinate can't be converted: /// for a source that gives its features there (a database, a GeoPackage table loaded for /// editing), unlike [`Reproject::read`]. + // Databases and GeoPackage editing, which the web app hasn't. + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn to_lonlat_geometry(&self, g: Geometry) -> Option { let Some(t) = &self.t else { return Some(g) }; let mut ok = true; @@ -1258,6 +1260,8 @@ pub(crate) fn clamp_limit(limit: usize) -> usize { } /// Whether a feature's geometry falls in a request's extent (always true without one). +// Databases, which the web app hasn't. +#[cfg(not(target_arch = "wasm32"))] pub(crate) fn in_request(g: &Geometry, req: &Request) -> bool { match &req.extent { Some(e) => g.extent().intersects(e), diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 7ba97c10c3..7744b945f5 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -71,6 +71,8 @@ fn copy(s: &mut Session) -> CmdResult { // longitude/latitude, converted exactly through WGS 84, whatever map they were copied from. data.held_in = l.dataset.coord_crs(); data.crs = l.dataset.crs; + // What the import lost, Define Projection can't recover in a layer pasted from it either. + data.crs_incomplete = l.dataset.crs_incomplete; data.features = l.selection.iter().filter_map(|r| l.dataset.features.get(*r).cloned()).collect::>().into(); let n = data.features.len(); let text = rustgis_data::io::to_geojson(&*data.in_lonlat()?).to_string(); diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index baf946155f..71f7424771 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2320,10 +2320,10 @@ fn topology_checks(s: &Session) -> Vec { inputs } -/// Whether two layers' data are the same: the same rows (shared, not compared one by one), fields -/// and geometry type. +/// Whether two layers' data are the same: the same system they hold coordinates in (a relabel +/// keeps the rows), the same rows (shared, not compared one by one), fields and geometry type. fn same_data(a: &rustgis_data::Dataset, b: &rustgis_data::Dataset) -> bool { - a.features.shares(&b.features) && a.fields == b.fields && a.geometry_type == b.geometry_type + a.coord_crs() == b.coord_crs() && a.features.shares(&b.features) && a.fields == b.fields && a.geometry_type == b.geometry_type } /// Whether `was` (what a check read on another thread) is what the rules read now. diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index bf24051560..ea0a8e0b31 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -981,8 +981,11 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { if let Some(src) = s.map_mut().layer_mut(id) { src.labels.enabled = false; } - if let Err(e) = ds.hold_as(system.0, system.1) { - s.notify(format!("{}: kept in longitude/latitude, as it was made, not in {}: {e}", ds.name, system.0.label()), false); + match ds.hold_as(system.0, system.1) { + // A cancel stops the command, which adds nothing. + Err(e) if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) => return Err(e), + Err(e) => s.notify(format!("{}: kept in longitude/latitude, as it was made, not in {}: {e}", ds.name, system.0.label()), false), + Ok(()) => {} } let new_id = super::layer::add_dataset(s, ds); if let Some(a) = s.map_mut().layer_mut(new_id) { diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 430fdfbe53..cee198e971 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1734,7 +1734,7 @@ fn route(s: &mut Session, p: &Value) -> CmdResult { let mut ds = Dataset::new(name, GeometryType::Polyline, vec![Field::new("length_km", FieldType::Double), Field::new("cost", FieldType::Double)]); ds.push(Some(Geometry::Line(vec![r.path.clone()])), vec![Attr::Float(r.length_m / 1000.0), Attr::Float(r.cost)]); - hold_as(s, &mut ds, system); + hold_as(s, &mut ds, system)?; let nid = super::layer::add_dataset(s, ds); if let Some(notice) = query_notice { s.notify_text(notice, false); @@ -1882,7 +1882,7 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { ds.push(Some(Geometry::Point(*c)), vec![Attr::Int(*r as i64)]); } let n = ds.features.len(); - hold_as(s, &mut ds, system); + hold_as(s, &mut ds, system)?; if let Some(notice) = query_notice { s.notify_text(notice, false); } @@ -1892,10 +1892,20 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { /// Holds `ds`, a layer made in longitude/latitude from another, as that layer is /// ([`Dataset::hold_as`]; `system` is its [`Dataset::coord_crs`] and [`Dataset::crs`]), and says -/// so when it can't be: it stays in longitude/latitude then, as it was made. -fn hold_as(s: &mut Session, ds: &mut Dataset, (held, crs): (rustgis_data::raster::Crs, Option)) { - if let Err(e) = ds.hold_as(held, crs) { - s.notify(format!("{}: kept in longitude/latitude, as it was made, not in {}: {e}", ds.name, held.label()), false); +/// so when it can't be: it stays in longitude/latitude then, as it was made. A cancel stops the +/// command, which adds nothing. +fn hold_as( + s: &mut Session, + ds: &mut Dataset, + (held, crs): (rustgis_data::raster::Crs, Option), +) -> Result<(), String> { + match ds.hold_as(held, crs) { + Err(e) if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) => Err(e), + Err(e) => { + s.notify(format!("{}: kept in longitude/latitude, as it was made, not in {}: {e}", ds.name, held.label()), false); + Ok(()) + } + Ok(()) => Ok(()), } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a04ad5a66e..303347715c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1705,9 +1705,9 @@ impl Session { pub fn run(&mut self, id: &str, params: &Value) -> CmdResult { self.command_epilogue(id, params, |s| { let native_maintenance = s.depth == 0 && s.policy_ingress_idle(); - if s.depth == 0 { - s.note_shown_systems(); - } + // Before every command, a script's or task's too: one before it in the same script may + // have changed a map's projection. + s.note_shown_systems(); let result = s.run_command(id, params); // A command may change a map's projection, or add layers to it. if s.depth == 0 { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 8aa577659c..d90ea417e1 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -318,7 +318,9 @@ fn the_clipboard_holds_features_in_their_own_system() { }) .collect(); // Within 0.1 mm of WGS 84's, where the map's way is some decimetres off. - for (p, q) in places(&text).iter().zip(&exact) { + let copied = places(&text); + assert_eq!(copied.len(), exact.len(), "every copied feature in the text"); + for (p, q) in copied.iter().zip(&exact) { assert!((p.x - q.x).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9, "{p:?} vs {q:?}"); } s.run("map.projection", &json!({"type": "mercator"})).unwrap(); @@ -346,6 +348,14 @@ fn the_clipboard_holds_features_in_their_own_system() { let want = UTM.to(gk).unwrap().point(in_utm).unwrap(); let Some(Geometry::Point(got)) = native(&s, "Wells")[11] else { panic!("a point") }; assert!((got.x - want.x).abs() < 1e-6 && (got.y - want.y).abs() < 1e-6, "UTM text into DHDN: {got:?} vs {want:?}"); + // A layer pasted from a copy keeps what its import lost, so Define Projection still refuses it. + s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().dataset.crs_incomplete = true; + s.run("select.rows", &json!({"layer": "Wells", "rows": [1]})).unwrap(); + s.run("edit.copy", &Value::Null).unwrap(); + let made = s.run("edit.pasteSpecial", &json!({"name": "Copied"})).unwrap(); + let l = s.map().layer(made["layer"].as_u64().unwrap() as u32).unwrap(); + assert!(l.dataset.crs_incomplete); + assert_eq!(l.dataset.coord_crs(), gk); } /// A route over a held network after Define Projection runs on the network as it now reads, not diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index d597d02196..8791c7d925 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1242,8 +1242,12 @@ impl Layer { self.dataset.features.rows().map(|r| r.geometry().map(|g| flat.project(g))).collect() } else { match flat.held(crs) { - // Nothing to count: every place is drawn as it is. - Ok(held) if held.is_identity() => self.dataset.features.rows().map(|r| r.geometry().cloned()).collect(), + // Every place is drawn as it is, those longitude/latitude can't give too, so none + // is left out of this drawing. + Ok(held) if held.is_identity() => { + self.unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Ok(0) }; + self.dataset.features.rows().map(|r| r.geometry().cloned()).collect() + } Ok(held) => { let mut lost = 0usize; let geoms = self @@ -4582,6 +4586,16 @@ mod tests { let want = map.project(&to_lonlat.geometry(&stored)); assert_eq!(gk.projected_in(&map, key)[0].as_ref(), Some(&want), "{key}"); } + // A place longitude/latitude can't give is counted where drawing goes through it (Web + // Mercator), and not on a map in the layer's own system, which draws it as it is. + let mut d = Dataset::new("wild", GeometryType::Point, vec![]); + d.push(Some(Geometry::Point(Coord::new(1e15, 5_400_000.0))), vec![]); + d.held_in = Crs::Epsg(31467); + let mut wild = Layer::new(3, d); + wild.projected_in(&projection::Flat::Mercator, "mercator"); + assert_eq!(wild.unplaced(), Some(&Ok(1))); + wild.projected_in(&flat("EPSG:31467"), "gk"); + assert_eq!(wild.unplaced(), Some(&Ok(0)), "drawn as it is"); // A layer held in Web Mercator is drawn on the Web Mercator map as it is. let mut merc = held(Crs::WebMercator); let stored_merc = merc.dataset.features[0].geometry.clone().unwrap(); diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index c7eee8b141..3fb020baef 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -81,7 +81,7 @@ pub(super) fn read_mode( // Half the budget holds them; their projection and display levels take the rest. let first = read(source)?; if full { - check_areas(&expr, &first.0.features, &source.info().name, first.0.complete)?; + check_areas(&expr, &scratch, &first.0.features, &source.info().name, first.0.complete)?; } if first.0.complete || !source.visits_chunks() || numbers_rows(&expr) { return Ok(first); @@ -208,9 +208,11 @@ fn read_filtered( } /// An expression parsed against source metadata still needs validation against decoded geometry. -fn check_areas(expr: &Expr, features: &[rustgis_data::Feature], name: &str, complete: bool) -> Result<()> { +/// `held`, the query's scratch dataset, holds its coordinates as the source gives them, so the +/// features' places are read in longitude/latitude from that system. +fn check_areas(expr: &Expr, held: &Dataset, features: &[rustgis_data::Feature], name: &str, complete: bool) -> Result<()> { if rustgis_data::query::uses_area(expr) - && let Some(message) = rustgis_data::ambiguous_area_message(features.iter().filter_map(|f| f.geometry.as_ref())) + && let Some(message) = held.ambiguous_area_message(features.iter().filter_map(|f| f.geometry.as_ref())) { let scope = if complete { String::new() } else { format!("; count covers the {} feature(s) read for this view", features.len()) }; return Err(DataError::Format(format!("Definition query: {name}: {message}{scope}"))); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 069240da11..fa149ea650 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -767,9 +767,10 @@ it by default (see [Writing](#writing)). This differs from changing the map's coordinate system, which only changes the display, or exporting to another CRS, which converts coordinate numbers while preserving locations. A layer read from a file keeps the file's own numbers, so Define Projection only relabels them. A -layer kept in a project saved by an older release holds its geometry in longitude/latitude: its -native numbers are first reconstructed through the previous CRS, where small floating-point -rounding differences are possible. +layer kept in a saved project (by this release or an older one) and opened again holds its +geometry in longitude/latitude, as projects save it: its native numbers are first reconstructed +through the previous CRS, where small floating-point rounding differences are possible. A layer +read from its file again when the project opens keeps the file's numbers. Edits already made to the layer are reinterpreted too. If the wrong CRS already discarded or clamped coordinates, import the original file again to recover them accurately. From f2a2698bda75cf59d787b2deedb8375bb0252881 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 12:11:23 +0100 Subject: [PATCH 03/15] Review: GML says places kept missing, identity test expects a zero count, comments --- crates/data/src/gml.rs | 19 ++++++++++++++++++- crates/data/src/io.rs | 2 +- crates/map/src/lib.rs | 6 +++--- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 51968853ca..1626fb6059 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -650,6 +650,8 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> let (zm, unread, parts) = (kind.zm, kind.unread, kind.parts_lost); let unread_names = kind.unread_names.said(); let (mut outside, mut null_text) = (false, Vec::new()); + // Features with a place the file's system can't give in longitude/latitude, kept missing. + let mut unplaced = 0usize; // Held as the file holds its coordinates, in its own system (in the axis order RustGIS // gives every system's), when RustGIS converts it. if let Some((Some(_), _)) = &transform @@ -669,6 +671,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> let g = match (&transform, g) { (Some((Some(t), _)), Some(g)) => { let lonlat = std::cell::Cell::new(rustgis_geom::Extent::EMPTY); + let missing = std::cell::Cell::new(false); let kept = g.map_coords(&|c| match t.to_lonlat(c) { Some(l) if l.is_finite() => { let mut b = lonlat.get(); @@ -677,8 +680,12 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> c } _ if !c.is_finite() => c, - _ => Coord::new(f64::NAN, f64::NAN), + _ => { + missing.set(true); + Coord::new(f64::NAN, f64::NAN) + } }); + unplaced += usize::from(missing.get()); e = lonlat.get(); Some(kept) } @@ -716,6 +723,14 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> let what = if kind.skipped == 1 { "feature" } else { "features" }; rep.messages.push(format!("{}: {} {what} had geometry that couldn't be read", ds.name, kind.skipped)); } + if unplaced > 0 { + let what = if unplaced == 1 { "feature has" } else { "features have" }; + let system = file_srs.map_or_else(String::new, |(c, _)| format!(" in {}", c.label())); + rep.messages.push(format!( + "{}: {unplaced} {what} places{system} that can't be given in longitude/latitude; they are left out of the shapes", + ds.name + )); + } if file_srs.is_none() && outside { rep.messages.push("the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude".into()); } @@ -878,6 +893,7 @@ mod tests { assert_eq!(parts[0][0], Coord::new(500000.0, 4649776.0), "the file's numbers"); assert!(parts[0][1].x.is_nan() && parts[0][1].y.is_nan(), "{:?}", parts[0][1]); assert!(serde_json::to_string(ds).is_ok(), "saves"); + assert!(layers[0].1.messages.iter().any(|m| m.contains("1 feature has places")), "{:?}", layers[0].1.messages); assert!(ds.in_lonlat().is_ok()); } @@ -898,6 +914,7 @@ mod tests { let Some(Geometry::Point(c)) = &ds.features[0].geometry else { panic!() }; assert!((c.x - 15.0).abs() < 1e-6 && (c.y - 42.0).abs() < 0.01, "{c:?}"); assert_eq!(rep.skipped, 1); + assert!(!rep.messages.iter().any(|m| m.contains("can't be given")), "every place converts: {:?}", rep.messages); assert_eq!(srs("EPSG:4326").map(|s| s.1), Some(false)); assert_eq!(srs("http://www.opengis.net/def/crs/EPSG/0/4326").map(|s| s.1), Some(true)); assert_eq!(srs("urn:ogc:def:crs:EPSG::32633").map(|s| s.1), Some(false), "projected: easting first"); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 4e0104b91b..79ff823081 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1414,7 +1414,7 @@ fn is_epsg_or_crs84_name(name: &str) -> bool { /// A geometry in longitude/latitude from the coordinates `t` converts: `None` when a coordinate /// can't be converted or comes out beyond longitude/latitude (a declared system that doesn't match /// the coordinates). -// Used by the in-place readers and databases, which the web app hasn't. +// Used by the in-place GeoJSON reader, which the web app hasn't. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn geometry_to_lonlat(g: &Geometry, t: &crate::raster::Transformer) -> Option { let mut ok = true; diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 8791c7d925..ee9fcf93ac 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1242,8 +1242,8 @@ impl Layer { self.dataset.features.rows().map(|r| r.geometry().map(|g| flat.project(g))).collect() } else { match flat.held(crs) { - // Every place is drawn as it is, those longitude/latitude can't give too, so none - // is left out of this drawing. + // Every place is drawn as it is, those longitude/latitude can't give too: the + // conversion leaves none out (a place a reader kept missing is said by the reader). Ok(held) if held.is_identity() => { self.unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Ok(0) }; self.dataset.features.rows().map(|r| r.geometry().cloned()).collect() @@ -4565,7 +4565,7 @@ mod tests { near(&coords(&stored), &[(3513304.512454, 5404737.597295), (3514768.524742, 5406965.390660)]); let on_own = gk.projected_in(&flat("EPSG:31467"), "gk")[0].clone().unwrap(); assert_eq!(coords(&on_own), coords(&stored)); - assert!(gk.unplaced().is_none(), "nothing is converted, so nothing is counted"); + assert_eq!(gk.unplaced(), Some(&Ok(0)), "drawn as it is: none left out"); // On ETRS89 UTM 32N, the direct operation's result, not the way through WGS 84. let utm = flat("EPSG:25832"); assert_eq!(utm.direct_system(), Some(Crs::Epsg(25832))); From e6543f7ab15331c82f5c0f144d99f16b2270b03a Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 12:44:18 +0100 Subject: [PATCH 04/15] Review round 2: per-drawing unplaced counts, GeoLibre relabel checks places, Shapefile out-of-range notice for held layers, extent cache keyed on a weak reference, shared hold_as --- crates/data/src/io.rs | 36 +++++++++++++++------ crates/data/src/source/mod.rs | 2 -- crates/engine/src/cmd/labels.rs | 7 +---- crates/engine/src/cmd/workflows.rs | 2 +- crates/geolibre/src/lib.rs | 12 +++++++ crates/map/src/lib.rs | 50 +++++++++++++++++++++++------- crates/map/src/look.rs | 3 ++ 7 files changed, 83 insertions(+), 29 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 79ff823081..abee130284 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1414,7 +1414,6 @@ fn is_epsg_or_crs84_name(name: &str) -> bool { /// A geometry in longitude/latitude from the coordinates `t` converts: `None` when a coordinate /// can't be converted or comes out beyond longitude/latitude (a declared system that doesn't match /// the coordinates). -// Used by the in-place GeoJSON reader, which the web app hasn't. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn geometry_to_lonlat(g: &Geometry, t: &crate::raster::Transformer) -> Option { let mut ok = true; @@ -1428,9 +1427,20 @@ pub(crate) fn geometry_to_lonlat(g: &Geometry, t: &crate::raster::Transformer) - /// ([`Dataset::held_in`]), when it does, and leaves the feature's geometry out when it doesn't, /// as one it couldn't convert. Each coordinate is converted to be checked, none is kept. pub(crate) fn places_in_lonlat(g: &Geometry, t: &crate::raster::Transformer) -> bool { + places_lonlat_extent(g, t).is_some() +} + +/// [`places_in_lonlat`] with the box of the places in longitude/latitude, for a reader that says +/// when they come out beyond it (a `.prj` that doesn't match the coordinates): `None` when one of +/// them has no place there. +pub(crate) fn places_lonlat_extent(g: &Geometry, t: &crate::raster::Transformer) -> Option { let mut ok = true; - g.for_each_coord(|c: Coord| ok &= t.to_lonlat(c).is_some_and(|l| l.is_finite())); - ok + let mut e = rustgis_geom::Extent::EMPTY; + g.for_each_coord(|c: Coord| match t.to_lonlat(c).filter(|l| l.is_finite()) { + Some(l) => e.expand(l), + None => ok = false, + }); + ok.then_some(e) } /// The box in longitude/latitude of a geometry in the coordinates `t` converts, for a reader that @@ -3619,6 +3629,9 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio }), }; let (mut converted, mut unconverted, mut zm_shapes, mut not_numbers) = (0usize, 0usize, 0usize, 0usize); + // The box of the converted places in longitude/latitude, for the notice of a `.prj` that + // doesn't match the coordinates. + let mut lonlat_extent = rustgis_geom::Extent::EMPTY; let mut counts = DbfCounts::new(ds.fields.len()); let mut source_kind = GeometryType::None; let pt = |x: f64, y: f64| Coord::new(x, y); @@ -3674,10 +3687,13 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // Kept as the file holds it, in its own system, when it has a place in longitude/latitude. let geom = match (&to_lonlat, geom) { (Some(t), Some(g)) => { - let ok = places_in_lonlat(&g, t); - converted += usize::from(ok); - unconverted += usize::from(!ok); - ok.then_some(g) + let placed = places_lonlat_extent(&g, t); + if let Some(e) = &placed { + lonlat_extent = lonlat_extent.union(e); + } + converted += usize::from(placed.is_some()); + unconverted += usize::from(placed.is_none()); + placed.map(|_| g) } (_, g) => g, }; @@ -3698,8 +3714,10 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio if let Some(c) = ds.crs.filter(|_| to_lonlat.is_some()) { ds.held_in = c; } - let e = ds.extent(); - if to_lonlat.is_none() && !e.is_empty() && (e.min_x < -180.5 || e.max_x > 180.5 || e.min_y < -90.5 || e.max_y > 90.5) { + // In longitude/latitude, as the file's places come out there (beyond it: a `.prj` that + // doesn't match the coordinates), or as they are without a system to convert from. + let e = if to_lonlat.is_some() { lonlat_extent } else { ds.extent() }; + if !e.is_empty() && (e.min_x < -180.5 || e.max_x > 180.5 || e.min_y < -90.5 || e.max_y > 90.5) { report.messages.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place".into()); } if report.skipped > 0 { diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index f56bef72e6..73030a491a 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -901,7 +901,6 @@ impl Reproject { /// The geometry converted to longitude/latitude; `None` when a coordinate can't be converted: /// for a source that gives its features there (a database, a GeoPackage table loaded for /// editing), unlike [`Reproject::read`]. - // Databases and GeoPackage editing, which the web app hasn't. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn to_lonlat_geometry(&self, g: Geometry) -> Option { let Some(t) = &self.t else { return Some(g) }; @@ -1260,7 +1259,6 @@ pub(crate) fn clamp_limit(limit: usize) -> usize { } /// Whether a feature's geometry falls in a request's extent (always true without one). -// Databases, which the web app hasn't. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn in_request(g: &Geometry, req: &Request) -> bool { match &req.extent { diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index ea0a8e0b31..7beec09a92 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -981,12 +981,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { if let Some(src) = s.map_mut().layer_mut(id) { src.labels.enabled = false; } - match ds.hold_as(system.0, system.1) { - // A cancel stops the command, which adds nothing. - Err(e) if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) => return Err(e), - Err(e) => s.notify(format!("{}: kept in longitude/latitude, as it was made, not in {}: {e}", ds.name, system.0.label()), false), - Ok(()) => {} - } + super::workflows::hold_as(s, &mut ds, system)?; let new_id = super::layer::add_dataset(s, ds); if let Some(a) = s.map_mut().layer_mut(new_id) { // The annotation is all text: the points themselves are invisible. diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index cee198e971..6a1be86bd5 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1894,7 +1894,7 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { /// ([`Dataset::hold_as`]; `system` is its [`Dataset::coord_crs`] and [`Dataset::crs`]), and says /// so when it can't be: it stays in longitude/latitude then, as it was made. A cancel stops the /// command, which adds nothing. -fn hold_as( +pub(crate) fn hold_as( s: &mut Session, ds: &mut Dataset, (held, crs): (rustgis_data::raster::Crs, Option), diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 6b9df62908..5823f522c0 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -776,6 +776,18 @@ fn load(file_name: &str, bytes: &[u8], layer_name: &str, job: &Job, dir: Option< if job.crs != Crs::LonLat && ds.coord_crs() == Crs::LonLat && looks_projected(&ds) { ds.held_in = job.crs; ds.crs = Some(job.crs); + // Every place the layer keeps has one in longitude/latitude, as when it was + // converted there: a feature with one that hasn't is kept without geometry. + // Each place is converted to be checked; the layer keeps its own. + let lost = match ds.lonlat_conversion() { + Ok(to) => convert_features(&mut ds, |c| to.point(c).filter(|l| l.is_finite()).map(|_| c)), + Err(_) => convert_features(&mut ds, |_| None), + }; + if lost > 0 { + messages.push(format!( + "{layer_name}: {lost} features couldn't be converted to longitude/latitude and have no geometry" + )); + } } Some(if ds.features.iter().all(|f| f.geometry.is_none()) { OutputLayer::Table(ds) } else { OutputLayer::Vector(ds) }) } diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index ee9fcf93ac..9eb20e4b19 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -357,9 +357,15 @@ pub struct Layer { #[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`]). + /// longitude/latitude, found as it was last converted there (the globe's copy, frames that + /// read it there: [`Layer::unplaced`]). #[serde(skip)] unplaced: Unplaced, + /// How many its flat projection's drawing left out ([`Layer::projected_in`]): none on a map + /// in its own system, which draws every place as it is. Kept apart from `unplaced`, so the + /// globe and the flat map each say what they leave out, whichever drew last. + #[serde(skip)] + flat_unplaced: Unplaced, /// Its extent in longitude/latitude as last worked out ([`Layer::extent`]): converting every /// place of a layer held in another system takes long enough not to do it each frame. #[serde(skip)] @@ -577,6 +583,7 @@ impl Layer { projected_crs: None, lonlat: LonLatCopy::default(), unplaced: Unplaced::default(), + flat_unplaced: Unplaced::default(), extent_cache: ExtentCache::default(), drawn: false, geometry_rev: 0, @@ -1205,7 +1212,14 @@ impl Layer { /// 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) + // The larger of the counts of drawings made from its geometry as it is: what one drawing + // left out is said, though another drew it. + let fit = |u: &Unplaced| u.fits(self); + match (fit(&self.unplaced).then_some(&self.unplaced.count), fit(&self.flat_unplaced).then_some(&self.flat_unplaced.count)) { + (Some(a @ Err(_)), _) | (_, Some(a @ Err(_))) => Some(a), + (Some(a @ Ok(x)), Some(b @ Ok(y))) => Some(if x >= y { a } else { b }), + (a, b) => a.or(b), + } } /// Counts its places that can't be given in longitude/latitude ([`Layer::unplaced`]) without @@ -1245,7 +1259,7 @@ impl Layer { // Every place is drawn as it is, those longitude/latitude can't give too: the // conversion leaves none out (a place a reader kept missing is said by the reader). Ok(held) if held.is_identity() => { - self.unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Ok(0) }; + self.flat_unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Ok(0) }; self.dataset.features.rows().map(|r| r.geometry().cloned()).collect() } Ok(held) => { @@ -1260,11 +1274,11 @@ impl Layer { Some(g) }) .collect(); - self.unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Ok(lost) }; + self.flat_unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Ok(lost) }; geoms } Err(e) => { - self.unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Err(e) }; + self.flat_unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Err(e) }; (0..self.dataset.features.len()).map(|_| None).collect() } } @@ -1464,6 +1478,9 @@ impl Layer { if other.unplaced.fits(other) { self.unplaced = other.unplaced.clone(); } + if other.flat_unplaced.fits(other) { + self.flat_unplaced = other.flat_unplaced.clone(); + } self.drawn |= other.drawn; } let fits = other.dataset.features.shares(&self.dataset.features) @@ -3521,6 +3538,7 @@ impl Layer { projected_crs: _, lonlat: _, unplaced: _, + flat_unplaced: _, extent_cache: _, drawn: _, view_memory: _, @@ -3584,10 +3602,13 @@ impl Layer { #[derive(Debug, Default)] struct ExtentCache(std::sync::Mutex>); -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] struct ExtentKept { rev: u64, - rows: usize, + /// The rows it was worked out from, without keeping them: a change through a copy, or in + /// place (which moves the rows out from under a weak reference), makes them other rows, and + /// an allocation freed and reused is never taken for them. + rows: std::sync::Weak>, len: usize, crs: Crs, extent: Extent, @@ -3595,7 +3616,7 @@ struct ExtentKept { impl Clone for ExtentCache { fn clone(&self) -> Self { - ExtentCache(std::sync::Mutex::new(*self.0.lock().unwrap_or_else(|e| e.into_inner()))) + ExtentCache(std::sync::Mutex::new(self.0.lock().unwrap_or_else(|e| e.into_inner()).clone())) } } @@ -3607,10 +3628,11 @@ impl ExtentCache { if crs == Crs::LonLat { return ds.extent(); } - let (rows, len) = (ds.features.allocation_key().as_ptr() as usize, ds.features.len()); + let (rows, len) = (ds.features.allocation_key(), ds.features.len()); let mut kept = self.0.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(k) = *kept - && (k.rev, k.rows, k.len, k.crs) == (rev, rows, len, crs) + if let Some(k) = kept.as_ref() + && k.rows.ptr_eq(&rows) + && (k.rev, k.len, k.crs) == (rev, len, crs) { return k.extent; } @@ -4596,6 +4618,12 @@ mod tests { assert_eq!(wild.unplaced(), Some(&Ok(1))); wild.projected_in(&flat("EPSG:31467"), "gk"); assert_eq!(wild.unplaced(), Some(&Ok(0)), "drawn as it is"); + // The globe, drawn from its longitude/latitude copy, leaves it out, and says so whatever + // the flat map drew since; a flat drawing of its own system adds nothing to it. + wild.lonlat_in(); + assert_eq!(wild.unplaced(), Some(&Ok(1)), "the globe's"); + wild.projected_in(&flat("EPSG:31467"), "gk"); + assert_eq!(wild.unplaced(), Some(&Ok(1)), "still the globe's"); // A layer held in Web Mercator is drawn on the Web Mercator map as it is. let mut merc = held(Crs::WebMercator); let stored_merc = merc.dataset.features[0].geometry.clone().unwrap(); diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index 5c4ca9f4f9..856ce956e4 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -98,6 +98,7 @@ fn bare(layer: &Layer) -> Layer { projected_crs, lonlat, unplaced: _, + flat_unplaced: _, extent_cache: _, drawn: _, view_memory: _, @@ -173,6 +174,7 @@ fn bare(layer: &Layer) -> Layer { projected_crs: *projected_crs, lonlat: lonlat.clone(), unplaced: Default::default(), + flat_unplaced: Default::default(), extent_cache: Default::default(), drawn: false, view_memory: Default::default(), @@ -270,6 +272,7 @@ impl LayerLook { lonlat: _, // What the last drawing counted and whether it drew the layer; neither is the look. unplaced: _, + flat_unplaced: _, extent_cache: _, drawn: _, view_memory: _, From de5fe63c7df8309bc58eec84b67459d674a4b351 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 12:48:47 +0100 Subject: [PATCH 05/15] Review round 2 follow-up: notices said when a count rises, GeoLibre keeps geometry when the system can't convert, Shapefile notice wording, tests --- crates/data/src/io.rs | 32 +++++++++++++++++++++++++- crates/engine/src/lib.rs | 8 ++++--- crates/engine/src/tests/held_layers.rs | 11 +++++++++ crates/geolibre/src/lib.rs | 3 ++- 4 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index abee130284..c070588523 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3718,7 +3718,11 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // doesn't match the coordinates), or as they are without a system to convert from. let e = if to_lonlat.is_some() { lonlat_extent } else { ds.extent() }; if !e.is_empty() && (e.min_x < -180.5 || e.max_x > 180.5 || e.min_y < -90.5 || e.max_y > 90.5) { - report.messages.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place".into()); + report.messages.push(if to_lonlat.is_some() { + "coordinates are not longitude/latitude once converted from the .prj's coordinate system; the .prj may not match them, and they may draw out of place".into() + } else { + "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place".into() + }); } if report.skipped > 0 { report.messages.push(format!("{} shapes were unreadable or unsupported", report.skipped)); @@ -6983,6 +6987,32 @@ mod tests { assert!(rep.messages.iter().any(|m| m.contains("1 number isn't finite") && m.contains("'lat'")), "{:?}", rep.messages); } + /// A `.prj` that doesn't match the coordinates (a geographic system for numbers past 180°) is + /// said, though the file is held in its system as it is, as it was when it was converted. + #[test] + fn a_shapefile_whose_prj_doesnt_fit_is_said() { + use shapefile::dbase::{FieldValue, Record, TableWriterBuilder}; + let dir = std::env::temp_dir().join(format!("rustgis-shp-prj-misfit-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let shp = dir.join("misfit.shp"); + { + let table = TableWriterBuilder::new().add_character_field("name".try_into().unwrap(), 10); + let mut w = shapefile::Writer::from_path(&shp, table).unwrap(); + let mut r = Record::default(); + r.insert("name".into(), FieldValue::Character(Some("far".into()))); + w.write_shape_and_record(&shapefile::Point::new(500.0, 10.0), &r).unwrap(); + } + let prj = r#"GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]"#; + std::fs::write(dir.join("misfit.prj"), prj).unwrap(); + let (_, rep) = read_path(&shp).unwrap(); + assert!( + rep.messages.iter().any(|m| m.contains("not longitude/latitude") || m.contains("couldn't be converted")), + "{:?}", + rep.messages + ); + let _ = std::fs::remove_dir_all(&dir); + } + /// A projected Shapefile is converted to longitude/latitude by its `.prj` (issue #84). #[test] fn shapefile_prj_reprojects() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 303347715c..fb517d1c1d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -855,7 +855,7 @@ pub struct Session { /// 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, + 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, @@ -3102,8 +3102,10 @@ impl Session { 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) { + // Said again when the count changes at the same version: a drawing that leaves out + // what an earlier one drew (the globe after the layer's own system). + let version = (l.geometry_rev(), l.dataset.coord_crs(), count.clone()); + if self.unplaced_checked.insert(l.instance_id(), version.clone()).as_ref() == Some(&version) { continue; } let named = format!("map '{}', layer '{}'", map.name, l.name); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index d90ea417e1..688cccbe0b 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -820,6 +820,17 @@ fn a_held_layers_undrawable_features_are_said_once() { 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:?}"); + // On a map in the layers' own system every place is drawn, so nothing is said; the globe's + // copy, which leaves them out, says so at the same version of the geometry. + s.run("map.projection", &json!({"type": "EPSG:32632"})).unwrap(); + let mark = s.notice_mark(); + frame(&mut s); + assert!(said_of(&s, mark, of_map).is_empty(), "{:?}", said_of(&s, mark, of_map)); + s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().lonlat_in(); + let _ = s.run("select.clear", &Value::Null); + let said = said_of(&s, mark, of_map); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].ends_with("(map 'Map', layer 'Wells' (2))"), "{said:?}"); } /// Every cell of a raster layer named in a command's answer. diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 5823f522c0..a3c24d04cc 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -779,9 +779,10 @@ fn load(file_name: &str, bytes: &[u8], layer_name: &str, job: &Job, dir: Option< // Every place the layer keeps has one in longitude/latitude, as when it was // converted there: a feature with one that hasn't is kept without geometry. // Each place is converted to be checked; the layer keeps its own. + // A system with no conversion at all keeps the geometry: drawing says it. let lost = match ds.lonlat_conversion() { Ok(to) => convert_features(&mut ds, |c| to.point(c).filter(|l| l.is_finite()).map(|_| c)), - Err(_) => convert_features(&mut ds, |_| None), + Err(_) => 0, }; if lost > 0 { messages.push(format!( From 6fd08400085ecf89ff2f43171f6c6204e0a5d9a9 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 13:06:35 +0100 Subject: [PATCH 06/15] Review: unplaced notice said again only for a larger count at a version; docs; test --- crates/engine/src/lib.rs | 42 ++++++++++++++++---------- crates/engine/src/tests/held_layers.rs | 11 +++++-- 2 files changed, 35 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fb517d1c1d..4aec7b7d97 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -852,9 +852,9 @@ 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. + /// Each layer held in another system (by instance): the geometry revision and system whose + /// places were last counted for [`Session::say_unplaced`], and the most it said of them, so a + /// version of a layer is said once, and again only for a count above it. unplaced_checked: std::collections::HashMap)>, /// The datum grids the map's layers were last projected with /// ([`rustgis_data::raster::crs::grid_generation`]). @@ -3086,14 +3086,15 @@ impl Session { } } - /// 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. 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. + /// Says, once for each version of a layer's geometry (and again for a larger count, as when the + /// globe leaves out what a map in the layer's own system drew), 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. 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()); @@ -3102,11 +3103,20 @@ impl Session { 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 }; - // Said again when the count changes at the same version: a drawing that leaves out - // what an earlier one drew (the globe after the layer's own system). - let version = (l.geometry_rev(), l.dataset.coord_crs(), count.clone()); - if self.unplaced_checked.insert(l.instance_id(), version.clone()).as_ref() == Some(&version) { - continue; + // Said again at the same version only for a larger count: a drawing that leaves out + // what an earlier one drew (the globe after the layer's own system), not each time + // a map's projection goes back to one already said. + let (rev, crs) = (l.geometry_rev(), l.dataset.coord_crs()); + let above = |said: &Result| match (count, said) { + (Err(_), Ok(_)) => true, + (Ok(n), Ok(m)) => n > m, + _ => false, + }; + match self.unplaced_checked.get(&l.instance_id()) { + Some((r, c, said)) if (*r, *c) == (rev, crs) && !above(said) => continue, + _ => { + self.unplaced_checked.insert(l.instance_id(), (rev, crs, count.clone())); + } } let named = format!("map '{}', layer '{}'", map.name, l.name); match count { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 688cccbe0b..c50d8026c6 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -820,9 +820,11 @@ fn a_held_layers_undrawable_features_are_said_once() { 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:?}"); - // On a map in the layers' own system every place is drawn, so nothing is said; the globe's - // copy, which leaves them out, says so at the same version of the geometry. + // A version drawn first on a map in the layers' own system, which draws every place, says + // nothing; the globe's copy, which leaves them out, says so at the same version; going back + // to Web Mercator, which leaves out as many, says nothing more. s.run("map.projection", &json!({"type": "EPSG:32632"})).unwrap(); + s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().touch_geometry(); let mark = s.notice_mark(); frame(&mut s); assert!(said_of(&s, mark, of_map).is_empty(), "{:?}", said_of(&s, mark, of_map)); @@ -831,6 +833,11 @@ fn a_held_layers_undrawable_features_are_said_once() { let said = said_of(&s, mark, of_map); assert_eq!(said.len(), 1, "{said:?}"); assert!(said[0].ends_with("(map 'Map', layer 'Wells' (2))"), "{said:?}"); + s.run("map.projection", &json!({"type": "mercator"})).unwrap(); + frame(&mut s); + s.run("map.projection", &json!({"type": "EPSG:32632"})).unwrap(); + frame(&mut s); + assert_eq!(said_of(&s, mark, of_map).len(), 1, "{:?}", said_of(&s, mark, of_map)); } /// Every cell of a raster layer named in a command's answer. From 15653f869b8ebbdb748e984eb85a2027bbd3de86 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 13:17:29 +0100 Subject: [PATCH 07/15] Review: a topology check read ahead is dropped when the datum grids changed --- crates/engine/src/cmd/design.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 71f7424771..c6a5cf34b3 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2394,6 +2394,9 @@ const TOPOLOGY_AHEAD: &str = "topology.validate"; struct TopologyAhead { inputs: Vec, tol: f64, + /// The datum grids there were when it was made ([`rustgis_data::raster::crs::grid_generation`]): + /// a grid that arrives meanwhile changes how a layer held in another system converts. + grids: u64, found: Result, String>, } @@ -2405,9 +2408,10 @@ pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option CmdResult { let tol = topology_tolerance(p); let inputs = topology_checks(s); let found = match super::reads::take::(s, TOPOLOGY_AHEAD) { - Some(ahead) if ahead.tol == tol && same_topology(&ahead.inputs, &inputs) => ahead.found?, + Some(ahead) + if ahead.tol == tol && ahead.grids == rustgis_data::raster::crs::grid_generation() && same_topology(&ahead.inputs, &inputs) => + { + ahead.found? + } // Checking again here would hold the window: the check made on its thread is dropped. - Some(_) => return Err("the topology rules or their layers changed while they were checked: validate again".into()), + Some(_) => { + return Err("the topology rules, their layers or the datum grids changed while they were checked: validate again".into()); + } None => check_topology(&inputs, tol)?, }; // Rules whose layer, or covering layer, isn't on the map are checked for nothing: said. From 264841acc7ca557919f2e6a7cc25a7a084591589 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 13:42:53 +0100 Subject: [PATCH 08/15] Review round 3: export says only its own drawings' omissions, labels change the source after the fallible step, Source tab shows a held extent in its system, to_geojson converts held datasets --- crates/data/src/io.rs | 42 +++++++++++++++++++++++++-- crates/engine/src/cmd/labels.rs | 3 +- crates/map/src/lib.rs | 50 +++++++++++++++++++++++++-------- crates/map/src/look.rs | 2 +- crates/ui-egui/src/panes.rs | 16 +++++++---- 5 files changed, 91 insertions(+), 22 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index c070588523..e27f7949db 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1820,13 +1820,30 @@ pub(crate) fn dominant_type(ds: &Dataset) -> GeometryType { } } -/// A dataset as a GeoJSON FeatureCollection value, in longitude/latitude. +/// A dataset as a GeoJSON FeatureCollection value, in longitude/latitude: a dataset held in +/// another system has each geometry converted through WGS 84 ([`Dataset::lonlat_conversion`]), +/// a place that can't be given there written as missing (`null`), and every geometry without +/// one when its system can't be converted. Callers that must refuse such a place convert first +/// ([`Dataset::in_lonlat`]), which leaves nothing to convert here. pub fn to_geojson(ds: &Dataset) -> Json { - let features: Vec = ds.features.iter().map(|f| feature_to_geojson(&ds.fields, f)).collect(); + let to = ds.lonlat_conversion().ok(); + let features: Vec = ds + .features + .iter() + .map(|f| match &to { + Some(t) if t.is_identity() => feature_to_geojson(&ds.fields, f), + Some(t) => { + let g = f.geometry.as_ref().map(|g| t.geometry(g)); + feature_to_geojson(&ds.fields, &crate::Feature { id: f.id, geometry: g, attrs: f.attrs.clone() }) + } + None => feature_to_geojson(&ds.fields, &crate::Feature { id: f.id, geometry: None, attrs: f.attrs.clone() }), + }) + .collect(); json!({"type": "FeatureCollection", "name": ds.name, "features": features}) } -/// A GeoJSON text conversion with per-feature progress and cancellation. +/// A GeoJSON text conversion with per-feature progress and cancellation, of `ds`'s coordinates as +/// they are: the caller converts a dataset held in another system first ([`Dataset::in_lonlat`]). pub fn to_geojson_text(ds: &Dataset) -> Result { let mut writer = GeoJsonWriter::new(Vec::new(), &ds.name, &ds.fields)?; writer.write(&ds.features)?; @@ -6987,6 +7004,25 @@ mod tests { assert!(rep.messages.iter().any(|m| m.contains("1 number isn't finite") && m.contains("'lat'")), "{:?}", rep.messages); } + /// A GeoJSON read in the system its legacy `crs` member names is written back in + /// longitude/latitude, through WGS 84, as the format is: UTM 32N, Ingolstadt. + #[test] + fn a_held_geojson_is_written_in_lonlat() { + let at = Coord::new(11.5, 48.7); + let utm = Crs::Epsg(32632).transformer().unwrap().from_lonlat(at).unwrap(); + let text = format!( + r#"{{"type":"FeatureCollection","crs":{{"type":"name","properties":{{"name":"urn:ogc:def:crs:EPSG::32632"}}}},"features":[{{"type":"Feature","properties":{{}},"geometry":{{"type":"Point","coordinates":[{},{}]}}}}]}}"#, + utm.x, utm.y + ); + let (ds, _) = read_geojson(&text, "held").unwrap(); + assert_eq!(ds.coord_crs(), Crs::Epsg(32632)); + let out = to_geojson(&ds); + let c = &out["features"][0]["geometry"]["coordinates"]; + let (x, y) = (c[0].as_f64().unwrap(), c[1].as_f64().unwrap()); + assert!((x - at.x).abs() < 1e-9 && (y - at.y).abs() < 1e-9, "{c}"); + assert!(out.get("crs").is_none()); + } + /// A `.prj` that doesn't match the coordinates (a geographic system for numbers past 180°) is /// said, though the file is held in its system as it is, as it was when it was converted. #[test] diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 7beec09a92..bf71d06f36 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -978,10 +978,11 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { labels.classes.get_mut(class).unwrap_or(&mut labels.default).move_label(id, Some(at)); } let (min_scale, max_scale) = (l.min_scale, l.max_scale); + // Before the labelled layer changes, so a cancel leaves it as it was. + super::workflows::hold_as(s, &mut ds, system)?; if let Some(src) = s.map_mut().layer_mut(id) { src.labels.enabled = false; } - super::workflows::hold_as(s, &mut ds, system)?; let new_id = super::layer::add_dataset(s, ds); if let Some(a) = s.map_mut().layer_mut(new_id) { // The annotation is all text: the points themselves are invisible. diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 9eb20e4b19..54be92e144 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -375,7 +375,7 @@ pub struct Layer { /// Hit-testing and snapping use them too, but on the live map, which no export reads this /// from. #[serde(skip)] - drawn: bool, + drawn: Drawn, /// Allocation identities and byte totals, shared with render snapshots without retaining rows. #[serde(skip)] view_memory: view_memory::Cache, @@ -585,7 +585,7 @@ impl Layer { unplaced: Unplaced::default(), flat_unplaced: Unplaced::default(), extent_cache: ExtentCache::default(), - drawn: false, + drawn: Drawn::default(), geometry_rev: 0, view_memory: Default::default(), geometry_kinds: Default::default(), @@ -1140,7 +1140,7 @@ impl Layer { } self.fill_projected(key, flat); } - self.drawn = true; + self.drawn.flat = true; &self.projected } @@ -1159,7 +1159,7 @@ impl Layer { 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.drawn.lonlat = true; &self.lonlat.geoms } @@ -1212,10 +1212,17 @@ impl Layer { /// 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> { - // The larger of the counts of drawings made from its geometry as it is: what one drawing - // left out is said, though another drew it. - let fit = |u: &Unplaced| u.fits(self); - match (fit(&self.unplaced).then_some(&self.unplaced.count), fit(&self.flat_unplaced).then_some(&self.flat_unplaced.count)) { + self.unplaced_of(Drawn { flat: true, lonlat: true }) + } + + /// [`Layer::unplaced`] of the drawings `of` names: the larger of their counts made from its + /// geometry as it is, so what one drawing left out is said, though another drew it. + fn unplaced_of(&self, of: Drawn) -> Option<&Result> { + let fit = |u: &Unplaced, used: bool| used && u.fits(self); + match ( + fit(&self.unplaced, of.lonlat).then_some(&self.unplaced.count), + fit(&self.flat_unplaced, of.flat).then_some(&self.flat_unplaced.count), + ) { (Some(a @ Err(_)), _) | (_, Some(a @ Err(_))) => Some(a), (Some(a @ Ok(x)), Some(b @ Ok(y))) => Some(if x >= y { a } else { b }), (a, b) => a.or(b), @@ -1233,14 +1240,16 @@ impl Layer { if self.dataset.coord_crs() != Crs::LonLat && !self.unplaced.fits(self) { self.convert_counting_unplaced(|_| ()); } - self.drawn = true; + self.drawn.lonlat = 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). + /// Only the drawings it made count: one in the layer's own system, which leaves none out, + /// doesn't say what a globe drawn on the live map left out. pub fn unplaced_drawn(&self) -> Option<&Result> { - if self.drawn { self.unplaced() } else { None } + self.unplaced_of(self.drawn) } /// Fills the projected geometry cache for `key` with each geometry on `flat`: a layer's own @@ -1481,7 +1490,8 @@ impl Layer { if other.flat_unplaced.fits(other) { self.flat_unplaced = other.flat_unplaced.clone(); } - self.drawn |= other.drawn; + self.drawn.flat |= other.drawn.flat; + self.drawn.lonlat |= other.drawn.lonlat; } let fits = other.dataset.features.shares(&self.dataset.features) && other.geometry_rev == self.geometry_rev @@ -2008,7 +2018,7 @@ impl Map { } // What the copy draws is marked anew ([`Layer::unplaced_drawn`]). for l in &mut self.layers { - l.drawn = false; + l.drawn = Drawn::default(); } } @@ -3666,6 +3676,14 @@ impl Unplaced { /// A layer's geometry in longitude/latitude, made from its rows at a geometry revision in a /// coordinate system ([`Layer::lonlat_in`]). +/// Which of a layer's drawings a frame made: its flat projection ([`Layer::projected_in`]) or its +/// longitude/latitude copy ([`Layer::lonlat_in`], [`Layer::count_unplaced`]). +#[derive(Clone, Copy, Debug, Default)] +struct Drawn { + flat: bool, + lonlat: bool, +} + #[derive(Clone, Debug, Default)] struct LonLatCopy { geoms: std::sync::Arc>>, @@ -4624,6 +4642,14 @@ mod tests { assert_eq!(wild.unplaced(), Some(&Ok(1)), "the globe's"); wild.projected_in(&flat("EPSG:31467"), "gk"); assert_eq!(wild.unplaced(), Some(&Ok(1)), "still the globe's"); + // A drawing made since its map was detached (an export) says only what it left out: one + // in the layer's own system, none, though the live map's globe left one out. + wild.drawn = Drawn::default(); + assert!(wild.unplaced_drawn().is_none(), "not drawn"); + wild.projected_in(&flat("EPSG:31467"), "gk"); + assert_eq!(wild.unplaced_drawn(), Some(&Ok(0))); + wild.lonlat_in(); + assert_eq!(wild.unplaced_drawn(), Some(&Ok(1)), "and the globe's when it draws it too"); // A layer held in Web Mercator is drawn on the Web Mercator map as it is. let mut merc = held(Crs::WebMercator); let stored_merc = merc.dataset.features[0].geometry.clone().unwrap(); diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index 856ce956e4..a5595b33a9 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -176,7 +176,7 @@ fn bare(layer: &Layer) -> Layer { unplaced: Default::default(), flat_unplaced: Default::default(), extent_cache: Default::default(), - drawn: false, + drawn: Default::default(), view_memory: Default::default(), geometry_kinds: Default::default(), geometry_rev: *geometry_rev, diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 8fcfb0a9cd..c5b6d59039 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -6968,7 +6968,12 @@ fn save_history_script(app: &mut RustGisApp) { /// What the Layer Properties pane's Source tab (#1803) shows of a layer: its geometry, counts, /// source, coordinate system, extent and fields, or a raster's own details. pub(crate) fn source_details(ui: &mut Ui, l: &Layer, t: &Tokens) { - let e = l.extent(); + // A layer held in another system shows its extent there, as its coordinates are: no + // conversion of every place on the interface thread, which this pane is drawn on each frame. + let held = l.dataset.coord_crs(); + let lonlat = held == rustgis_engine::data::raster::Crs::LonLat; + let e = if lonlat { l.extent() } else { l.dataset.extent() }; + let edge = |v: f64| if lonlat { format!("{v:.4}°") } else { format!("{v:.2}") }; if let Some(rl) = &l.raster { raster_details(ui, rl, t); return; @@ -6983,10 +6988,11 @@ pub(crate) fn source_details(ui: &mut Ui, l: &Layer, t: &Tokens) { // A web or database address without its keys, tokens or password. ("Source", l.dataset.source.as_deref().map_or_else(|| tl!("In project").into(), rustgis_engine::sources::redact)), ("Source coordinate system", l.dataset.crs.map(|c| c.label()).unwrap_or_else(|| "EPSG:4326".into())), - ("West", format!("{:.4}°", e.min_x)), - ("East", format!("{:.4}°", e.max_x)), - ("South", format!("{:.4}°", e.min_y)), - ("North", format!("{:.4}°", e.max_y)), + ("Held in", held.label()), + (if lonlat { "West" } else { "Min X" }, edge(e.min_x)), + (if lonlat { "East" } else { "Max X" }, edge(e.max_x)), + (if lonlat { "South" } else { "Min Y" }, edge(e.min_y)), + (if lonlat { "North" } else { "Max Y" }, edge(e.max_y)), ("Definition query", l.definition_query.clone().unwrap_or_else(|| "—".into())), ]; for (k, v) in rows { From 159b8cd546f3a2b3384a2af4813ab0279f53acd3 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 13:46:09 +0100 Subject: [PATCH 09/15] Review: to_geojson writes coordinates as they are (callers convert held datasets first), Source tab keeps a streamed layer's source extent, doc placement --- crates/data/src/io.rs | 27 +++++++-------------------- crates/map/src/lib.rs | 4 ++-- crates/ui-egui/src/panes.rs | 3 ++- 3 files changed, 11 insertions(+), 23 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index e27f7949db..168fca08e6 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1820,25 +1820,12 @@ pub(crate) fn dominant_type(ds: &Dataset) -> GeometryType { } } -/// A dataset as a GeoJSON FeatureCollection value, in longitude/latitude: a dataset held in -/// another system has each geometry converted through WGS 84 ([`Dataset::lonlat_conversion`]), -/// a place that can't be given there written as missing (`null`), and every geometry without -/// one when its system can't be converted. Callers that must refuse such a place convert first -/// ([`Dataset::in_lonlat`]), which leaves nothing to convert here. +/// A dataset as a GeoJSON FeatureCollection value, of its coordinates as they are. GeoJSON is in +/// longitude/latitude, so a dataset held in another system ([`Dataset::coord_crs`]) is converted +/// first, by [`Dataset::in_lonlat`], which refuses, naming the feature, a place that can't be +/// given there; a writer that adds a legacy `crs` member passes its own system's coordinates. pub fn to_geojson(ds: &Dataset) -> Json { - let to = ds.lonlat_conversion().ok(); - let features: Vec = ds - .features - .iter() - .map(|f| match &to { - Some(t) if t.is_identity() => feature_to_geojson(&ds.fields, f), - Some(t) => { - let g = f.geometry.as_ref().map(|g| t.geometry(g)); - feature_to_geojson(&ds.fields, &crate::Feature { id: f.id, geometry: g, attrs: f.attrs.clone() }) - } - None => feature_to_geojson(&ds.fields, &crate::Feature { id: f.id, geometry: None, attrs: f.attrs.clone() }), - }) - .collect(); + let features: Vec = ds.features.iter().map(|f| feature_to_geojson(&ds.fields, f)).collect(); json!({"type": "FeatureCollection", "name": ds.name, "features": features}) } @@ -7005,7 +6992,7 @@ mod tests { } /// A GeoJSON read in the system its legacy `crs` member names is written back in - /// longitude/latitude, through WGS 84, as the format is: UTM 32N, Ingolstadt. + /// longitude/latitude, converted through WGS 84 first, as the format is: UTM 32N, Ingolstadt. #[test] fn a_held_geojson_is_written_in_lonlat() { let at = Coord::new(11.5, 48.7); @@ -7016,7 +7003,7 @@ mod tests { ); let (ds, _) = read_geojson(&text, "held").unwrap(); assert_eq!(ds.coord_crs(), Crs::Epsg(32632)); - let out = to_geojson(&ds); + let out = to_geojson(&ds.in_lonlat().unwrap()); let c = &out["features"][0]["geometry"]["coordinates"]; let (x, y) = (c[0].as_f64().unwrap(), c[1].as_f64().unwrap()); assert!((x - at.x).abs() < 1e-9 && (y - at.y).abs() < 1e-9, "{c}"); diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 54be92e144..b62d149f56 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -3674,8 +3674,6 @@ impl Unplaced { } } -/// A layer's geometry in longitude/latitude, made from its rows at a geometry revision in a -/// coordinate system ([`Layer::lonlat_in`]). /// Which of a layer's drawings a frame made: its flat projection ([`Layer::projected_in`]) or its /// longitude/latitude copy ([`Layer::lonlat_in`], [`Layer::count_unplaced`]). #[derive(Clone, Copy, Debug, Default)] @@ -3684,6 +3682,8 @@ struct Drawn { lonlat: bool, } +/// 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>>, diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index c5b6d59039..9330b3f23b 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -6970,8 +6970,9 @@ fn save_history_script(app: &mut RustGisApp) { pub(crate) fn source_details(ui: &mut Ui, l: &Layer, t: &Tokens) { // A layer held in another system shows its extent there, as its coordinates are: no // conversion of every place on the interface thread, which this pane is drawn on each frame. + // A streamed layer's is its source's whole extent, in longitude/latitude, read once. let held = l.dataset.coord_crs(); - let lonlat = held == rustgis_engine::data::raster::Crs::LonLat; + let lonlat = held == rustgis_engine::data::raster::Crs::LonLat || l.source.is_some(); let e = if lonlat { l.extent() } else { l.dataset.extent() }; let edge = |v: f64| if lonlat { format!("{v:.4}°") } else { format!("{v:.2}") }; if let Some(rl) = &l.raster { From ed699b9d147cbc3104df9c2775b3c563a84fc5ee Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 13:51:53 +0100 Subject: [PATCH 10/15] Rename the drawings-made flags DrawnBy (Drawn is the map's stack entry) --- crates/map/src/lib.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index b62d149f56..7839d433b2 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -375,7 +375,7 @@ pub struct Layer { /// Hit-testing and snapping use them too, but on the live map, which no export reads this /// from. #[serde(skip)] - drawn: Drawn, + drawn: DrawnBy, /// Allocation identities and byte totals, shared with render snapshots without retaining rows. #[serde(skip)] view_memory: view_memory::Cache, @@ -585,7 +585,7 @@ impl Layer { unplaced: Unplaced::default(), flat_unplaced: Unplaced::default(), extent_cache: ExtentCache::default(), - drawn: Drawn::default(), + drawn: DrawnBy::default(), geometry_rev: 0, view_memory: Default::default(), geometry_kinds: Default::default(), @@ -1212,12 +1212,12 @@ impl Layer { /// 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_of(Drawn { flat: true, lonlat: true }) + self.unplaced_of(DrawnBy { flat: true, lonlat: true }) } /// [`Layer::unplaced`] of the drawings `of` names: the larger of their counts made from its /// geometry as it is, so what one drawing left out is said, though another drew it. - fn unplaced_of(&self, of: Drawn) -> Option<&Result> { + fn unplaced_of(&self, of: DrawnBy) -> Option<&Result> { let fit = |u: &Unplaced, used: bool| used && u.fits(self); match ( fit(&self.unplaced, of.lonlat).then_some(&self.unplaced.count), @@ -2018,7 +2018,7 @@ impl Map { } // What the copy draws is marked anew ([`Layer::unplaced_drawn`]). for l in &mut self.layers { - l.drawn = Drawn::default(); + l.drawn = DrawnBy::default(); } } @@ -3677,7 +3677,7 @@ impl Unplaced { /// Which of a layer's drawings a frame made: its flat projection ([`Layer::projected_in`]) or its /// longitude/latitude copy ([`Layer::lonlat_in`], [`Layer::count_unplaced`]). #[derive(Clone, Copy, Debug, Default)] -struct Drawn { +struct DrawnBy { flat: bool, lonlat: bool, } @@ -4644,7 +4644,7 @@ mod tests { assert_eq!(wild.unplaced(), Some(&Ok(1)), "still the globe's"); // A drawing made since its map was detached (an export) says only what it left out: one // in the layer's own system, none, though the live map's globe left one out. - wild.drawn = Drawn::default(); + wild.drawn = DrawnBy::default(); assert!(wild.unplaced_drawn().is_none(), "not drawn"); wild.projected_in(&flat("EPSG:31467"), "gk"); assert_eq!(wild.unplaced_drawn(), Some(&Ok(0))); From 6de44bd6e60acebe51fd16cc1a73cddfe969dafc Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 14:21:08 +0100 Subject: [PATCH 11/15] Review round 4: GeoLibre relabels only to a system that converts (else kept as read, said), Source tab in degrees for any geographic system --- crates/geolibre/src/lib.rs | 34 ++++++++++++++++++++-------------- crates/ui-egui/src/panes.rs | 12 +++++++----- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index a3c24d04cc..ce41488216 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -774,20 +774,26 @@ fn load(file_name: &str, bytes: &[u8], layer_name: &str, job: &Job, dir: Option< // An output that says its system (a .prj, a GeoJSON `crs`) is held in it as // read; one in the working system that doesn't is relabelled to it. if job.crs != Crs::LonLat && ds.coord_crs() == Crs::LonLat && looks_projected(&ds) { - ds.held_in = job.crs; - ds.crs = Some(job.crs); - // Every place the layer keeps has one in longitude/latitude, as when it was - // converted there: a feature with one that hasn't is kept without geometry. - // Each place is converted to be checked; the layer keeps its own. - // A system with no conversion at all keeps the geometry: drawing says it. - let lost = match ds.lonlat_conversion() { - Ok(to) => convert_features(&mut ds, |c| to.point(c).filter(|l| l.is_finite()).map(|_| c)), - Err(_) => 0, - }; - if lost > 0 { - messages.push(format!( - "{layer_name}: {lost} features couldn't be converted to longitude/latitude and have no geometry" - )); + match job.crs.to(Crs::LonLat) { + Ok(to) => { + ds.held_in = job.crs; + ds.crs = Some(job.crs); + // Every place the layer keeps has one in longitude/latitude, as when + // it was converted there: a feature with one that hasn't is kept + // without geometry. Each place is converted to be checked; the layer + // keeps its own. + let lost = convert_features(&mut ds, |c| to.point(c).filter(|l| l.is_finite()).map(|_| c)); + if lost > 0 { + messages.push(format!( + "{layer_name}: {lost} features couldn't be converted to longitude/latitude and have no geometry" + )); + } + } + // Not held in a system it can't be converted from: kept as read, and said. + Err(e) => messages.push(format!( + "{layer_name}: its coordinates are in {}, which can't be converted to longitude/latitude ({e}); they are kept as read and may draw out of place", + job.crs.label() + )), } } Some(if ds.features.iter().all(|f| f.geometry.is_none()) { OutputLayer::Table(ds) } else { OutputLayer::Vector(ds) }) diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 9330b3f23b..25b26d3ae8 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -6974,7 +6974,9 @@ pub(crate) fn source_details(ui: &mut Ui, l: &Layer, t: &Tokens) { let held = l.dataset.coord_crs(); let lonlat = held == rustgis_engine::data::raster::Crs::LonLat || l.source.is_some(); let e = if lonlat { l.extent() } else { l.dataset.extent() }; - let edge = |v: f64| if lonlat { format!("{v:.4}°") } else { format!("{v:.2}") }; + // Degrees in any geographic system (NAD83, ETRS89), units of the system otherwise. + let degrees = lonlat || held.is_geographic(); + let edge = |v: f64| if degrees { format!("{v:.4}°") } else { format!("{v:.2}") }; if let Some(rl) = &l.raster { raster_details(ui, rl, t); return; @@ -6990,10 +6992,10 @@ pub(crate) fn source_details(ui: &mut Ui, l: &Layer, t: &Tokens) { ("Source", l.dataset.source.as_deref().map_or_else(|| tl!("In project").into(), rustgis_engine::sources::redact)), ("Source coordinate system", l.dataset.crs.map(|c| c.label()).unwrap_or_else(|| "EPSG:4326".into())), ("Held in", held.label()), - (if lonlat { "West" } else { "Min X" }, edge(e.min_x)), - (if lonlat { "East" } else { "Max X" }, edge(e.max_x)), - (if lonlat { "South" } else { "Min Y" }, edge(e.min_y)), - (if lonlat { "North" } else { "Max Y" }, edge(e.max_y)), + (if degrees { "West" } else { "Min X" }, edge(e.min_x)), + (if degrees { "East" } else { "Max X" }, edge(e.max_x)), + (if degrees { "South" } else { "Min Y" }, edge(e.min_y)), + (if degrees { "North" } else { "Max Y" }, edge(e.max_y)), ("Definition query", l.definition_query.clone().unwrap_or_else(|| "—".into())), ]; for (k, v) in rows { From a47a5f232bad83af4e8461a6a2facf9276129f79 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 14:33:14 +0100 Subject: [PATCH 12/15] GeoLibre: the notice for a system that can't be converted gives the feature count and says they draw off the map --- crates/geolibre/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index ce41488216..a6eef06649 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -791,7 +791,8 @@ fn load(file_name: &str, bytes: &[u8], layer_name: &str, job: &Job, dir: Option< } // Not held in a system it can't be converted from: kept as read, and said. Err(e) => messages.push(format!( - "{layer_name}: its coordinates are in {}, which can't be converted to longitude/latitude ({e}); they are kept as read and may draw out of place", + "{layer_name}: its {} features are in {}, which can't be converted to longitude/latitude ({e}); they are kept as read and draw off the map", + ds.features.len(), job.crs.label() )), } From 00d6204c3fac99adf1b8b60c5765b0276d304ca2 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 15:00:38 +0100 Subject: [PATCH 13/15] Review round 5: a moved label's annotation lands where the label was drawn on a direct-drawn map; Source tab names the system its extent is in, longitude/latitude for any geographic system --- crates/data/src/lib.rs | 2 +- crates/engine/src/cmd/labels.rs | 14 ++++++++++- crates/engine/src/tests/held_layers.rs | 35 ++++++++++++++++++++++++++ crates/ui-egui/src/panes.rs | 15 ++++++----- 4 files changed, 58 insertions(+), 8 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index b8c7aa0624..ffdd492a25 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -597,7 +597,7 @@ impl Dataset { /// there by a direct operation: `None` when it is shown on no such map, is in that system /// itself or in longitude/latitude, or there is no direct operation between the two (the way /// through WGS 84 then gives what the map draws). - fn shown_through(&self) -> Option { + pub fn shown_through(&self) -> Option { let (own, map) = (self.coord_crs(), self.shown_in?); let plain = |c: raster::Crs| matches!(c, raster::Crs::LonLat | raster::Crs::WebMercator); (own != map && !plain(own) && !plain(map) && own.to(map).is_ok_and(|t| t.is_direct())).then_some(map) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index bf71d06f36..ec049717d3 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -870,6 +870,18 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { let system = (l.dataset.coord_crs(), l.dataset.crs); let mut moved = Vec::new(); let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; + // A moved label is drawn where the map puts its place, by the direct operation into the + // map's system when there is one (Dataset::shown_through): its annotation is put at the + // layer's coordinates the map draws there, given in longitude/latitude through WGS 84 as + // hold_as reads them back. + let shown = match l.dataset.shown_through() { + Some(_) => Some(l.dataset.shown_from_lonlat().map_err(|e| format!("{}: {e}", l.name))?), + None => None, + }; + let put_at = |[x, y]: [f64; 2]| { + let c = Coord::new(x, y); + shown.as_ref().and_then(|back| back.point(c)).and_then(|own| to.point(own)).unwrap_or(c) + }; for (row, ft) in l.dataset.features.rows().enumerate() { if rows.get(row) != Some(&true) { continue; @@ -901,7 +913,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { // A label moved by hand becomes an annotation where it was put, and stays moved there // (its class's offset leaves it). let put = class.moved_to(ft.id()); - let at = put.map_or(at, |[x, y]| Coord::new(x, y)); + let at = put.map_or(at, put_at); let e = exprs.get(i).and_then(Option::as_ref); let number = |v: Option| v.map_or(Attr::Null, |v| Attr::Float(f64::from(v))); if by_size { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index c50d8026c6..21086f5e57 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1109,6 +1109,41 @@ fn edits_on_a_map_in_another_datums_system_land_on_what_it_draws() { assert_eq!(*l.dataset.geometry_to_lonlat(&stored).unwrap(), *g, "on Web Mercator, edits go through WGS 84"); } +/// A label moved on a map in another datum's system becomes an annotation where it was drawn: +/// at the layer's coordinates the map's direct operation puts there, not those WGS 84 gives +/// (some decimetres off between DHDN and ETRS89). +#[test] +fn a_moved_label_becomes_an_annotation_where_it_was_drawn() { + let gk = Crs::Epsg(31467); + let mut s = session(gk); + s.run("map.projection", &json!({"type": "EPSG:25832"})).unwrap(); + let flat = s.map().flat(); + assert_eq!(flat.direct_system(), Some(Crs::Epsg(25832))); + let id = s.map().layer_by_name("Wells").unwrap().id; + let drawn = s.map_mut().layer_mut(id).unwrap().projected_in(&flat, "test")[2].clone().unwrap(); + let Geometry::Point(drawn) = drawn else { panic!("a point") }; + let l = s.map().layer(id).unwrap(); + let (moved, target) = (l.dataset.features[1].id, l.dataset.features[2].geometry.clone().unwrap()); + let Geometry::Point(target) = target else { panic!("a point") }; + // Put on the map where well 2 is drawn, as a drag there gives it. + let put = flat.inverse(drawn).unwrap(); + s.run("labels.enable", &json!({"layer": "Wells", "on": true})).unwrap(); + s.run("labels.move", &json!({"layer": "Wells", "feature": moved, "to": [put.x, put.y]})).unwrap(); + let made = s.run("labels.convert", &json!({"layer": "Wells"})).unwrap(); + let a = s.map().layer(made["layer"].as_u64().unwrap() as u32).unwrap(); + assert_eq!(a.dataset.coord_crs(), gk, "held as the labelled layer is"); + let Some(Geometry::Point(at)) = a.dataset.features[1].geometry else { panic!("a point") }; + // Within the millimetre two inverses of the datum shift take: the direct one, then through + // WGS 84 as `hold_as` reads the annotation back. PROJ's own round trip moves it 0.85 mm: + // `echo 5401067.822206589 3684021.1657746523 | cs2cs -d 10 EPSG:31467 EPSG:25832` gives + // 683871.9767392263 5399346.3693805207, which `cs2cs -d 10 EPSG:25832 EPSG:31467` turns into + // 5401067.8229720965 3684021.1661309246 (PROJ 9.9.0, PROJ_NETWORK=OFF). + assert!((at.x - target.x).hypot(at.y - target.y) < 5e-3, "annotation at {at:?}, label drawn at {target:?}"); + // Through WGS 84 it would be off the drawn label. + let plain = Crs::LonLat.to(gk).unwrap().point(put).unwrap(); + assert!((plain.x - target.x).hypot(plain.y - target.y) > 0.1, "{plain:?} vs {target:?}"); +} + /// A project saved by an older release opens as it did (#2032 C2): a layer it kept in the /// project holds its features in longitude/latitude, as they were saved, and a layer read in /// place from a UTM 32N Shapefile is read again in the file's own system, at the same places. diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 25b26d3ae8..9d29f6b8d3 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -6968,14 +6968,16 @@ fn save_history_script(app: &mut RustGisApp) { /// What the Layer Properties pane's Source tab (#1803) shows of a layer: its geometry, counts, /// source, coordinate system, extent and fields, or a raster's own details. pub(crate) fn source_details(ui: &mut Ui, l: &Layer, t: &Tokens) { - // A layer held in another system shows its extent there, as its coordinates are: no + // A layer held in a projected system shows its extent there, as its coordinates are: no // conversion of every place on the interface thread, which this pane is drawn on each frame. - // A streamed layer's is its source's whole extent, in longitude/latitude, read once. + // One held in a geographic system (NAD83, ETRS89, or one in grads or latitude first) shows + // its longitude/latitude extent, converted once per edit (Layer::extent), in degrees. A + // streamed layer's is its source's whole extent, in longitude/latitude, read once. + use rustgis_engine::data::raster::Crs; let held = l.dataset.coord_crs(); - let lonlat = held == rustgis_engine::data::raster::Crs::LonLat || l.source.is_some(); - let e = if lonlat { l.extent() } else { l.dataset.extent() }; - // Degrees in any geographic system (NAD83, ETRS89), units of the system otherwise. - let degrees = lonlat || held.is_geographic(); + let degrees = held.is_geographic() || l.source.is_some(); + let e = if degrees { l.extent() } else { l.dataset.extent() }; + let extent_in = if degrees { Crs::LonLat } else { held }; let edge = |v: f64| if degrees { format!("{v:.4}°") } else { format!("{v:.2}") }; if let Some(rl) = &l.raster { raster_details(ui, rl, t); @@ -6992,6 +6994,7 @@ pub(crate) fn source_details(ui: &mut Ui, l: &Layer, t: &Tokens) { ("Source", l.dataset.source.as_deref().map_or_else(|| tl!("In project").into(), rustgis_engine::sources::redact)), ("Source coordinate system", l.dataset.crs.map(|c| c.label()).unwrap_or_else(|| "EPSG:4326".into())), ("Held in", held.label()), + ("Extent in", extent_in.label()), (if degrees { "West" } else { "Min X" }, edge(e.min_x)), (if degrees { "East" } else { "Max X" }, edge(e.max_x)), (if degrees { "South" } else { "Min Y" }, edge(e.min_y)), From 74b7d23cfafb3ed9315eefa596e2d309714c7fbe Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 15:03:17 +0100 Subject: [PATCH 14/15] Round 5: the Source tab converts a geographic layer's box, not every place, and shows none for an empty one; moved labels the map's conversion doesn't reach are said --- crates/engine/src/cmd/labels.rs | 16 ++++++++++++++-- crates/ui-egui/src/panes.rs | 19 +++++++++++++++---- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index ec049717d3..8a977d8165 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -878,9 +878,15 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { Some(_) => Some(l.dataset.shown_from_lonlat().map_err(|e| format!("{}: {e}", l.name))?), None => None, }; + // Those the map's way doesn't reach are put through WGS 84, and said. + let astray = std::cell::Cell::new(0usize); let put_at = |[x, y]: [f64; 2]| { let c = Coord::new(x, y); - shown.as_ref().and_then(|back| back.point(c)).and_then(|own| to.point(own)).unwrap_or(c) + let Some(back) = &shown else { return c }; + back.point(c).and_then(|own| to.point(own)).filter(|l| l.is_finite()).unwrap_or_else(|| { + astray.set(astray.get() + 1); + c + }) }; for (row, ft) in l.dataset.features.rows().enumerate() { if rows.get(row) != Some(&true) { @@ -952,6 +958,12 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { [("name", ds.name.clone().into()), ("n", repeated.to_string().into())], ) }); + let astray_note = (astray.get() > 0).then(|| { + NoticeText::format( + "{name}: {n} moved label(s) the map's own conversion doesn't reach put through WGS 84, which may be some decimetres from where they were drawn", + [("name", ds.name.clone().into()), ("n", astray.get().to_string().into())], + ) + }); let cut_note = (cut > 0).then(|| { format!( "{}: {cut} label text{} cut to {} characters", @@ -1007,7 +1019,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { if let Some(note) = cut_note { s.notify(note, false); } - for note in [flattened_note, repeated_note].into_iter().flatten() { + for note in [flattened_note, repeated_note, astray_note].into_iter().flatten() { s.notify_text(note, false); } if let Some((_, unread)) = &whole { diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 9d29f6b8d3..45526fdaa2 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -6971,14 +6971,25 @@ pub(crate) fn source_details(ui: &mut Ui, l: &Layer, t: &Tokens) { // A layer held in a projected system shows its extent there, as its coordinates are: no // conversion of every place on the interface thread, which this pane is drawn on each frame. // One held in a geographic system (NAD83, ETRS89, or one in grads or latitude first) shows - // its longitude/latitude extent, converted once per edit (Layer::extent), in degrees. A - // streamed layer's is its source's whole extent, in longitude/latitude, read once. + // its own box converted to longitude/latitude (its edges' places, not every place), in + // degrees. A streamed layer's is its source's whole extent, in longitude/latitude, read once. + // A box with no place that converts shows none. use rustgis_engine::data::raster::Crs; let held = l.dataset.coord_crs(); let degrees = held.is_geographic() || l.source.is_some(); - let e = if degrees { l.extent() } else { l.dataset.extent() }; + let e = if l.source.is_some() || held == Crs::LonLat { + l.extent() + } else if degrees { + l.dataset.lonlat_conversion().map_or(rustgis_engine::geom::Extent::EMPTY, |to| to.extent(&l.dataset.extent())) + } else { + l.dataset.extent() + }; let extent_in = if degrees { Crs::LonLat } else { held }; - let edge = |v: f64| if degrees { format!("{v:.4}°") } else { format!("{v:.2}") }; + let edge = |v: f64| match (v.is_finite(), degrees) { + (false, _) => "—".to_string(), + (true, true) => format!("{v:.4}°"), + (true, false) => format!("{v:.2}"), + }; if let Some(rl) = &l.raster { raster_details(ui, rl, t); return; From f78dc521fe1db9ea6cf6c4830c8521bdd804407b Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 15:40:44 +0100 Subject: [PATCH 15/15] Round 6: a streamed layer read whole for labels.convert keeps the map's system; geometry calculation and plugin features convert with one conversion per layer --- crates/engine/src/cmd/labels.rs | 4 +++- crates/engine/src/cmd/plugins.rs | 16 +++++++++------- crates/engine/src/geometry_calc.rs | 9 +++++++-- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 8a977d8165..c1859b5012 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -813,8 +813,10 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { } // Its features, all of them: a copy of a layer read in place holds those of its whole source. let whole = if s.map().layer(id).ok_or("no such layer")?.is_streamed() { - let (ds, unread) = super::whole::take_or_read(s, id)?; + let (mut ds, unread) = super::whole::take_or_read(s, id)?; let mut copy = s.map().layer(id).ok_or("no such layer")?.clone(); + // Shown on the map as the live layer is, for moved labels' places (Dataset::shown_in). + ds.shown_in = copy.dataset.shown_in; copy.dataset = ds; copy.source = None; Some((copy, unread)) diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index f67886cc0d..67213f5582 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -590,16 +590,18 @@ impl Bridge<'_> { // In longitude/latitude, which a response holds unless `crs` asks for another system, // whatever system the layer holds its coordinates in. let mut features = rustgis_data::Features::default(); + // Made at the first feature with a geometry, once for the layer. + let mut conversion = None; for r in rows.iter().take(limit).filter_map(|&i| l.dataset.features.row(i)) { let n = features.len(); features.push_row(r.to_feature()); - if let Some(g) = r.geometry() - && let std::borrow::Cow::Owned(g) = l - .dataset - .lonlat_conversion() - .and_then(|to| rustgis_data::Dataset::geometry_to_lonlat_by(&to, g)) - .map_err(|e| format!("{}: feature {}: {e}", l.name, r.id()))? - { + let Some(g) = r.geometry() else { continue }; + let failed = |e: String| format!("{}: feature {}: {e}", l.name, r.id()); + let to = match &mut conversion { + Some(to) => &*to, + slot @ None => slot.insert(l.dataset.lonlat_conversion().map_err(failed)?), + }; + if let std::borrow::Cow::Owned(g) = rustgis_data::Dataset::geometry_to_lonlat_by(to, g).map_err(failed)? { features.set_geometry(n, Some(g)); } } diff --git a/crates/engine/src/geometry_calc.rs b/crates/engine/src/geometry_calc.rs index 5433779a88..3a5aa92524 100644 --- a/crates/engine/src/geometry_calc.rs +++ b/crates/engine/src/geometry_calc.rs @@ -95,6 +95,8 @@ pub fn run(s: &mut Session, p: &Json) -> CmdResult { }; let mut values = Vec::with_capacity(rows.len()); let mut nulls = 0; + // Made at the first feature with a geometry, once for the layer. + let mut conversion = None; for row in &rows { let f = l.dataset.features.get(*row).ok_or("selection contains a missing feature")?; let value = if let Some(g) = &f.geometry { @@ -103,8 +105,11 @@ pub fn run(s: &mut Session, p: &Json) -> CmdResult { } // Measured and placed in longitude/latitude, from the layer's own coordinates through // WGS 84, whatever map it is shown on. - let to = l.dataset.lonlat_conversion().map_err(|e| format!("feature {}: {e}", f.id))?; - let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("feature {}: {e}", f.id))?; + let to = match &mut conversion { + Some(to) => &*to, + slot @ None => slot.insert(l.dataset.lonlat_conversion().map_err(|e| format!("feature {}: {e}", f.id))?), + }; + let g = rustgis_data::Dataset::geometry_to_lonlat_by(to, g).map_err(|e| format!("feature {}: {e}", f.id))?; let g = g.as_ref(); // Lengths and areas use longitude differences, so a shape drawn or buffered across the // antimeridian may run past ±180°; a coordinate has to be a real longitude.