From 0a7458fd647bf00f0f5c83e96d03f6511adcab34 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 09:26:30 +0100 Subject: [PATCH] feat(crs): export and save from the system a layer holds its coordinates in (#2032 C1e part 1) io::project, write_bytes_in, write_path_to, the streamed export, the Shapefile publish, the whole-layer Web Mercator count and the Shapefile and CSV export notes convert from the system the layer (or, streamed, its source: FeatureSource::coord_crs) holds its coordinates in, instead of taking them for longitude/latitude. Every layer and source still holds longitude/latitude, so nothing changes yet; a test-only override of Dataset::coord_crs and a test source in UTM try the paths. --- crates/data/src/export.rs | 14 ++++- crates/data/src/export/tests.rs | 36 +++++++++++ crates/data/src/io.rs | 107 ++++++++++++++++++++++++++++---- crates/data/src/lib.rs | 62 +++++++++++++++++- crates/data/src/publish.rs | 32 ++++++++-- crates/data/src/source/mod.rs | 10 +++ 6 files changed, 240 insertions(+), 21 deletions(-) diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 297f283c50..824ca311a9 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -239,7 +239,11 @@ fn write_chunks_as( GeometryType::None => first_kind(src, 1 << 20)?, t => t, }; - let t = if crs == Crs::LonLat { None } else { Some(Crs::LonLat.to(crs).map_err(DataError::Format)?) }; + // From the system the source gives its features in. + let held = src.coord_crs(); + let t = if crs == held { None } else { Some(held.to(crs).map_err(DataError::Format)?) }; + // The longitude/latitude of a place, for the count of those Web Mercator can't hold. + let to_lonlat = if held == Crs::LonLat { None } else { Some(held.to(Crs::LonLat).map_err(DataError::Format)?) }; let mut total = 0usize; let mut filtered = 0usize; let mut skipped = 0usize; @@ -277,7 +281,13 @@ fn write_chunks_as( // leave out only features without geometry. if crs == Crs::WebMercator { for g in chunk.iter().filter_map(|f| f.geometry.as_ref()) { - g.for_each_coord(|c| beyond_web_mercator += usize::from(c.x.is_finite() && c.y.abs() > rustgis_geom::MAX_LAT)); + g.for_each_coord(|c| { + let c = match &to_lonlat { + Some(t) => t.point(c).unwrap_or(rustgis_geom::Coord::new(f64::NAN, f64::NAN)), + None => c, + }; + beyond_web_mercator += usize::from(c.x.is_finite() && c.y.abs() > rustgis_geom::MAX_LAT) + }); } } if let Some(t) = &t { diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 20ffb15248..112a2eca04 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -51,6 +51,8 @@ struct Runs { chunks: bool, /// Rows it reports as unreadable, as a GeoPackage's bad rows are. unreadable: usize, + /// The system it gives its features in. + held: Crs, } impl Runs { @@ -77,6 +79,7 @@ impl Runs { passes: Default::default(), chunks: true, unreadable: 0, + held: Crs::LonLat, } } } @@ -85,6 +88,9 @@ impl FeatureSource for Runs { fn info(&self) -> &SourceInfo { &self.info } + fn coord_crs(&self) -> Crs { + self.held + } fn read(&self, _: &Request) -> Result { Ok(Batch { features: self.features.clone(), @@ -655,3 +661,33 @@ fn a_mixed_layer_added_to_a_geopackage_keeps_every_kind() { assert_eq!(rows, 300); } } + +/// A source that gives its features in its own system (UTM 32N here; every source gives +/// longitude/latitude until #2032 C2) is exported a chunk at a time from it: a GeoJSON in +/// longitude/latitude, a GeoPackage in its own system and one in Web Mercator, which counts places +/// past where Web Mercator ends by their latitude (a square's 5 vertices at 86° N), not by the +/// source's northings. +#[test] +fn a_streamed_export_is_written_from_the_system_its_source_gives() { + let d = folder("held"); + let mut lonlat = squares(); + let ring = vec![Coord::new(9.0, 86.0), Coord::new(9.5, 86.0), Coord::new(9.5, 86.5), Coord::new(9.0, 86.5), Coord::new(9.0, 86.0)]; + lonlat.push_next(Some(Geometry::Polygon(vec![vec![ring]])), vec![Value::Null, Value::Int(-2), Value::Null, Value::Null]); + let utm = Crs::Epsg(32632); + let ds = crate::io::project(&lonlat, utm).unwrap(); + let layer = Dataset::new(ds.name.clone(), ds.geometry_type, ds.fields.clone()); + let src = Runs { held: utm, ..Runs::new(&ds, 10) }; + let first = |ds: &Dataset| match &ds.features[0].geometry { + Some(Geometry::Polygon(p)) => p[0][0][0], + g => panic!("{g:?}"), + }; + let want = first(&lonlat); + for (name, crs, beyond) in [("out.geojson", Crs::LonLat, 0), ("own.gpkg", utm, 0), ("merc.gpkg", Crs::WebMercator, 5)] { + let e = write_source_in(&src, &layer, &d.join(name), crs).unwrap(); + 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))); + assert!((p.x - want.x).abs() < 1e-7 && (p.y - want.y).abs() < 1e-7, "{name}: {p:?} {want:?}"); + } +} diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 7949750b5c..c501e20b87 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -617,14 +617,17 @@ pub fn default_export_note(ds: &Dataset, path: &str) -> Option { }) } -/// The dataset (in longitude/latitude, as every dataset is) in `crs`'s coordinates. 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`]: +/// 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. pub fn project(ds: &Dataset, crs: Crs) -> Result { - if crs == Crs::LonLat { + let from = ds.coord_crs(); + if crs == from { return Ok(ds.clone()); } let mut out = ds.clone(); - let to = Crs::LonLat.to(crs).map_err(DataError::Format)?; + let to = from.to(crs).map_err(DataError::Format)?; project_features(&mut out.features, &to)?; Ok(out) } @@ -708,9 +711,12 @@ pub fn write_bytes_in(ds: &Dataset, ext: &str, crs: Crs) -> Result<(Vec, usi return Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label()))); } check_projected(&ext, crs)?; - return projected_bytes(&project(ds, crs)?, &ext, crs); } - projected_bytes(ds, &ext, crs) + // From the system the dataset holds its coordinates in: as they are when that is `crs`. + if crs == ds.coord_crs() { + return projected_bytes(ds, &ext, crs); + } + projected_bytes(&project(ds, crs)?, &ext, crs) } /// [`write_bytes_in`] for a dataset already in `crs`'s coordinates. @@ -790,11 +796,15 @@ pub fn write_path_in(ds: &Dataset, path: &Path, crs: Crs) -> Result { /// also returns the table written. pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> Result<(usize, Option)> { let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + if crs != Crs::LonLat && PROJECTED_FORMATS.contains(&ext.as_str()) { + check_projected(&ext, crs)?; + } let projected; - let ds = if crs == Crs::LonLat || !PROJECTED_FORMATS.contains(&ext.as_str()) { + // From the system the dataset holds its coordinates in ([`project`]): as they are when that + // is `crs`, and when `crs` is one the format can't hold, which is refused below. + let ds = if crs == ds.coord_crs() || (crs != Crs::LonLat && !PROJECTED_FORMATS.contains(&ext.as_str())) { ds } else { - check_projected(&ext, crs)?; projected = project(ds, crs)?; &projected }; @@ -4310,6 +4320,8 @@ impl std::ops::AddAssign for CsvLosses { pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, target: &str) -> Result> { Ok(match ext { "csv" => { + // Of the longitude/latitude the file is written in. + let ds = ds.in_lonlat().map_err(DataError::Format)?; let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?; let mut notes = losses.notes(&ds.fields, target); notes.extend(losses.coordinates_note(&ds.fields, target)); @@ -4486,13 +4498,16 @@ fn shapefile_geometry_losses(g: Option<&Geometry>, gt: GeometryType, drawable: f /// What an export to a Shapefile in `crs` says it leaves out of the geometry it writes, one /// 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 longitude/latitude, 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 +/// 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 +/// 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 /// breaks and other control characters in it show as spaces. pub fn shapefile_geometry_notes(ds: &Dataset, target: &str, crs: Crs) -> Vec { - let drawable: fn(&Coord) -> bool = if crs == Crs::LonLat { |c| c.x.is_finite() && c.y.is_finite() } else { |_| true }; + // Written as held when `crs` is the system the layer holds its coordinates in; otherwise a + // converted copy, which refused every vertex that isn't a place. + let drawable: fn(&Coord) -> bool = if crs == ds.coord_crs() { |c| c.x.is_finite() && c.y.is_finite() } else { |_| true }; let (mut vertices, mut parts) = (0usize, 0usize); for f in &ds.features { let Some((v, p)) = shapefile_geometry_losses(f.geometry.as_ref(), ds.geometry_type, drawable) else { continue }; @@ -7868,4 +7883,70 @@ mod tests { assert_eq!(read_back.fields[1].ty, FieldType::Integer); assert_eq!(read_back.features[0].attrs[1], Value::Int(1)); } + + /// A layer held in its own system (UTM 32N here; every layer's is longitude/latitude until + /// #2032 C2) is written from it: in longitude/latitude for a format that holds only those, in + /// another system by the direct operation between the two, and in its own as it is. + #[test] + fn a_layer_is_written_from_the_system_it_holds() { + let (utm, etrs) = (Crs::Epsg(32632), Crs::Epsg(25832)); + let lonlat = Coord::new(9.0, 48.7); + let at = utm.transformer().unwrap().from_lonlat(lonlat).unwrap(); + let mut ds = Dataset::new("held", GeometryType::Point, vec![]); + ds.push(Some(Geometry::Point(at)), vec![]); + let _held = crate::tests::HeldIn::new(utm); + assert_eq!(ds.coord_crs(), utm); + // GeoJSON: longitude/latitude. + let (bytes, _) = write_bytes_in(&ds, "geojson", Crs::LonLat).unwrap(); + let read = read_bytes("held.geojson", &bytes).unwrap().0; + let Some(Geometry::Point(p)) = read.features[0].geometry.clone() else { panic!("a point") }; + assert!((p.x - lonlat.x).abs() < 1e-9 && (p.y - lonlat.y).abs() < 1e-9, "{p:?}"); + // Its own system: the coordinates as they are. + let same = project(&ds, utm).unwrap(); + assert_eq!(same.features[0].geometry, ds.features[0].geometry); + // Another: by the direct operation from it. + let other = project(&ds, etrs).unwrap(); + let want = utm.to(etrs).unwrap().point(at).unwrap(); + assert_eq!(other.features[0].geometry, Some(Geometry::Point(want))); + // A file written whole, in the layer's own system, and in longitude/latitude. + let d = std::env::temp_dir().join(format!("rustgis-held-writes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + 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 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:?}"); + } + let _ = std::fs::remove_dir_all(&d); + } + + /// The notes of an export of a layer held in its own system (UTM 32N here) are those of what + /// is written: a CSV's of the longitude/latitude it writes (as for the same layer held in + /// them), and a Shapefile's vertices left out only when it is written as held. + #[test] + fn an_exports_notes_are_of_what_it_writes() { + let utm = Crs::Epsg(32632); + // With x and y fields, which a CSV reader could take for the position: a point the file + // can't give a longitude/latitude would be said. + let fields = vec![Field::new("x", FieldType::Double), Field::new("y", FieldType::Double)]; + let mut lonlat = Dataset::new("held", GeometryType::Point, fields); + for (lon, lat) in [(9.0, 48.7), (10.0, 50.0)] { + lonlat.push(Some(Geometry::Point(Coord::new(lon, lat))), vec![Value::Float(1.0), Value::Float(2.0)]); + } + let want = export_losses_notes(&lonlat, "csv", None, "out.csv").unwrap(); + let held = project(&lonlat, utm).unwrap(); + let _held = crate::tests::HeldIn::new(utm); + assert_eq!(export_losses_notes(&held, "csv", None, "out.csv").unwrap(), want); + // A line with a missing coordinate: its vertex is left out of a Shapefile written as + // held, and noted; in any other system the export's conversion refuses the line instead + // (`project`), so there is nothing to note. + let mut line = Dataset::new("line", GeometryType::Polyline, vec![]); + let parts = vec![vec![Coord::new(500_000.0, 5_400_000.0), Coord::new(f64::NAN, 5_400_100.0), Coord::new(500_100.0, 5_400_200.0)]]; + line.push(Some(Geometry::Line(parts)), vec![]); + let own = shapefile_geometry_notes(&line, "out.shp", utm); + assert!(own.iter().any(|n| n.contains("1 vertex with a missing or infinite coordinate")), "{own:?}"); + assert!(shapefile_geometry_notes(&line, "out.shp", Crs::Epsg(25832)).is_empty()); + } } diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index e9024cc5d0..30f48ded2a 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -439,6 +439,10 @@ impl Dataset { /// a layer whose conversion fails (`Layer::projected_in`) and doesn't say so yet: before this /// returns another system, that needs a notice, as AGENTS.md's "Never silent" asks. pub fn coord_crs(&self) -> raster::Crs { + #[cfg(test)] + if let Some(held) = tests::held_in() { + return held; + } raster::Crs::LonLat } @@ -748,7 +752,19 @@ fn web_mercator_note(layers: &[(&Dataset, rustgis_geom::Extent)], target: &str) .filter_map(|(ds, e)| { let mut moved = 0usize; if !ds.windowed { - let mut count = |c: Coord| moved += usize::from(c.x.is_finite() && c.y.abs() > MAX_LAT); + // By latitude, from the system the layer holds its coordinates in: none counted + // when that can't be converted (its export can't be written either). + let to = match ds.lonlat_conversion() { + Ok(t) => (!t.is_identity()).then_some(t), + Err(_) => return None, + }; + let mut count = |c: Coord| { + let c = match &to { + Some(t) => t.point(c).unwrap_or(Coord::new(f64::NAN, f64::NAN)), + None => c, + }; + moved += usize::from(c.x.is_finite() && c.y.abs() > MAX_LAT) + }; for g in ds.features.iter().filter_map(|f| f.geometry.as_ref()) { if shapefile { crate::io::shapefile_vertices(g, ds.geometry_type, &mut count); @@ -1133,6 +1149,50 @@ fn convert_keeping_missing(to: &raster::Reprojection, g: &Geometry, held: &HeldP mod tests { use super::*; + thread_local! { + /// The system this thread's tests hold every dataset's coordinates in ([`HeldIn`]). + static HELD_IN: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// What [`Dataset::coord_crs`] says on this thread while a [`HeldIn`] is alive: what a dataset + /// that keeps the coordinates it was read in (#2032 C2) will say, for the paths that convert + /// from it to be tried before it does. + pub(crate) fn held_in() -> Option { + HELD_IN.try_with(std::cell::Cell::get).ok().flatten() + } + + /// Every dataset on this thread is taken to hold its coordinates in a system until dropped, + /// on the thread that made it (it can't be sent to another). + pub(crate) struct HeldIn(Option, std::marker::PhantomData<*const ()>); + + impl HeldIn { + pub(crate) fn new(crs: raster::Crs) -> HeldIn { + HeldIn(HELD_IN.with(|h| h.replace(Some(crs))), std::marker::PhantomData) + } + } + + impl Drop for HeldIn { + fn drop(&mut self) { + let _ = HELD_IN.try_with(|h| h.set(self.0)); + } + } + + /// An export in Web Mercator counts the places past where it ends by their latitude, from the + /// system the layer holds its coordinates in (UTM 32N here): one at 86° N, not every northing. + #[test] + fn web_mercators_end_is_counted_by_latitude() { + let utm = raster::Crs::Epsg(32632); + let t = utm.transformer().unwrap(); + let mut ds = Dataset::new("held", GeometryType::Point, vec![]); + for lat in [48.7, 86.0] { + ds.push(Some(Geometry::Point(t.from_lonlat(Coord::new(9.0, lat)).unwrap())), vec![]); + } + let _held = HeldIn::new(utm); + let note = web_mercator_note(&[(&ds, ds.extent())], "out.gpkg").unwrap_or_default(); + assert_eq!(note, web_mercator_said(&[("held", Some(1))], "out.gpkg").unwrap_or_default()); + assert!(!note.is_empty()); + } + /// Analysis and measurement read a longitude/latitude dataset as it is: no copy, and the /// measure and the area check of the geometry itself. #[test] diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 690d121249..db0da53a85 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -401,13 +401,20 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result(ds: &'a Dataset, crs: Option, as_held: Option<(&Dataset, &Dataset)>) -> Result> { - let Some(c) = crs else { return Ok(std::borrow::Cow::Borrowed(ds)) }; - let t = Crs::LonLat.to(c).map_err(DataError::Format)?; + // 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 { + return Ok(std::borrow::Cow::Borrowed(ds)); + } + 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()), @@ -778,6 +785,21 @@ mod tests { use super::*; use crate::{Coord, Field, GeometryType}; + /// A layer held in the file's own system (#2032 C2) is written as it is held; one held in + /// another is converted from it, without matching the file as read in longitude/latitude. + #[test] + fn a_layer_held_in_the_files_system_is_written_as_it_is() { + let (utm, etrs) = (Crs::Epsg(32632), Crs::Epsg(25832)); + let at = Coord::new(500_000.0, 5_400_000.0); + let mut ds = Dataset::new("held", GeometryType::Point, vec![]); + ds.push(Some(Geometry::Point(at)), vec![]); + let _held = crate::tests::HeldIn::new(utm); + let same = in_file(&ds, Some(utm), None).unwrap(); + assert!(matches!(same, std::borrow::Cow::Borrowed(_))); + let other = in_file(&ds, Some(etrs), Some((&ds, &ds))).unwrap(); + assert_eq!(other.features[0].geometry, Some(Geometry::Point(utm.to(etrs).unwrap().point(at).unwrap()))); + } + /// A small polygon layer of parcels with an owner, an area with decimals and a count. fn parcels() -> Dataset { let mut ds = Dataset::new( diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index b6e496e6cd..38febdbb5f 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -366,6 +366,12 @@ 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. + fn coord_crs(&self) -> crate::raster::Crs { + crate::raster::Crs::LonLat + } /// Whether features were left out of every read because the coordinate system the source /// declares can't place them, so that defining its projection again can't bring them back. fn lost_to_crs(&self) -> bool { @@ -619,6 +625,10 @@ impl FeatureSource for Fetching { self.0.info() } + fn coord_crs(&self) -> crate::raster::Crs { + self.0.coord_crs() + } + fn lost_to_crs(&self) -> bool { self.0.lost_to_crs() }