From 63a7c8bf88c46f0a1a36b442ded0e09e84965063 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 16:45:55 +0100 Subject: [PATCH 1/2] C2d: a layer held in its own coordinate system is saved there, exactly, and requires native-coordinates (#2032) --- crates/data/src/gml.rs | 4 +- crates/data/src/lib.rs | 134 +++++++------- crates/engine/src/cmd/items.rs | 4 +- crates/engine/src/project.rs | 13 +- crates/engine/src/project_capabilities.rs | 16 +- crates/engine/src/tests/held_layers.rs | 87 ++++++++- docs/maintaining.md | 7 + docs/user-guide/data-formats.md | 11 +- docs/user-guide/workspace.md | 9 + schema/fixtures/held_native.rgis | 211 ++++++++++++++++++++++ schema/project.schema.json | 18 +- 11 files changed, 424 insertions(+), 90 deletions(-) create mode 100644 schema/fixtures/held_native.rgis diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 1626fb6059..3eb7c648f5 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -879,8 +879,8 @@ mod tests { } /// 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. + /// reader converted the file, so the layer's places that convert are still 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#" diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index ffdd492a25..b3ab3038e6 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -411,8 +411,9 @@ impl<'de> 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`]): 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. +/// own system for a file read in one (and a saved project keeps it), WGS 84 longitude/latitude +/// for one without, for features drawn or made by tools and plugins, and for a project saved by +/// an older release. #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct Dataset { pub name: String, @@ -424,7 +425,8 @@ pub struct Dataset { 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`], which is this system for a file - /// read now and longitude/latitude for one a saved project holds. + /// read now or a project saved by this release, and longitude/latitude for one a project saved + /// by an older release holds. #[serde(default, skip_serializing_if = "Option::is_none")] pub crs: Option, /// Import lost geometry while interpreting source coordinates. Defining a projection cannot @@ -440,9 +442,11 @@ pub struct Dataset { #[serde(skip)] pub windowed: bool, /// The system its geometry is in ([`Dataset::coord_crs`]): longitude/latitude unless it was - /// put in another with [`Dataset::hold_in`]. A project saves its features in - /// longitude/latitude, as older releases read them, so a saved dataset reads back held there. - #[serde(skip, default = "held_in_lonlat")] + /// put in another with [`Dataset::hold_in`]. A project saves its features in it, exactly, + /// with the system beside them (`held_in`, absent for longitude/latitude, as every release + /// saved them before), so a saved dataset reads back held as it was; a project with one + /// requires `native-coordinates`. + #[serde(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 @@ -453,7 +457,8 @@ pub struct Dataset { pub shown_in: Option, } -/// What a dataset read from a project holds its coordinates in ([`Dataset::held_in`]). +/// What a dataset saved without a system of its own holds its coordinates in +/// ([`Dataset::held_in`]): longitude/latitude, as every release saved them before. fn held_in_lonlat() -> raster::Crs { raster::Crs::LonLat } @@ -653,20 +658,8 @@ 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: 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 })?; - } - } + // In the system it holds them in, exactly, as it reads them back (`held_in`, below). + st.serialize_field("features", if self.windowed { none } else { self.features.as_slice() })?; st.serialize_field("source", &self.source)?; if let Some(crs) = &self.crs { st.serialize_field("crs", crs)?; @@ -683,53 +676,13 @@ impl Serialize for Dataset { } else { st.skip_field("zm_dropped")?; } - st.end() - } -} - -/// 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))?; + // Absent for longitude/latitude, as every release saved a dataset before. + if self.held_in != raster::Crs::LonLat && !self.windowed { + st.serialize_field("held_in", &self.held_in)?; + } else { + st.skip_field("held_in")?; } - seq.end() + st.end() } } @@ -1435,6 +1388,53 @@ fn convert_keeping_missing(to: &raster::Reprojection, g: &Geometry, held: &HeldP mod tests { use super::*; + /// A dataset held in another system saves its features there, exactly, with the system + /// beside them, and reads back held as it was, bit for bit, with no conversion (#2032 C2d): + /// in UTM, in Robinson and in a system given by its PROJ definition. A window onto a source + /// saves no rows, and one in longitude/latitude no system, as every release saved them. + #[test] + fn a_held_dataset_reads_back_bit_for_bit() { + let defined = + raster::Crs::parse("+proj=tmerc +lat_0=0 +lon_0=9 +k=0.9996 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs").unwrap(); + let bits = |ds: &Dataset| -> Vec> { + ds.features + .rows() + .map(|r| { + let mut out = Vec::new(); + if let Some(g) = r.geometry() { + g.for_each_coord(|c| out.push((c.x.to_bits(), c.y.to_bits()))); + } + out + }) + .collect() + }; + for crs in [raster::Crs::Epsg(32632), raster::Crs::parse("ESRI:54030").unwrap(), defined] { + let mut ds = Dataset::new("held", GeometryType::Polyline, vec![Field::new("n", FieldType::Integer)]); + let line = |x: f64| vec![Coord::new(x, 48.7), Coord::new(x + 0.013, 48.71), Coord::new(x + 0.031, 48.69)]; + ds.push(Some(Geometry::Line(vec![line(11.5), line(11.6)])), vec![Value::Int(1)]); + ds.push(None, vec![Value::Int(2)]); + ds.push(Some(Geometry::Line(vec![line(8.1)])), vec![Value::Int(3)]); + ds.hold_in(crs).unwrap(); + let saved = serde_json::to_value(&ds).unwrap(); + assert_eq!(saved["held_in"], serde_json::to_value(crs).unwrap(), "{}", crs.label()); + let back: Dataset = serde_json::from_value(saved).unwrap(); + assert_eq!(back.coord_crs(), crs, "{}", crs.label()); + assert_eq!(bits(&back), bits(&ds), "{}", crs.label()); + assert_eq!(back.features.len(), 3); + } + let mut window = Dataset::new("window", GeometryType::Point, vec![]); + window.push(Some(Geometry::Point(Coord::new(11.5, 48.7))), vec![]); + window.hold_in(raster::Crs::Epsg(32632)).unwrap(); + window.windowed = true; + let v = serde_json::to_value(&window).unwrap(); + assert!(v.get("held_in").is_none() && v["features"] == serde_json::json!([]), "{v}"); + let mut plain = Dataset::new("plain", GeometryType::Point, vec![]); + plain.push(Some(Geometry::Point(Coord::new(11.5, 48.7))), vec![]); + let v = serde_json::to_value(&plain).unwrap(); + assert!(v.get("held_in").is_none(), "{v}"); + assert_eq!(serde_json::from_value::(v).unwrap().coord_crs(), raster::Crs::LonLat); + } + /// 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] diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 433062ed9f..7fc451edb6 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -862,8 +862,8 @@ fn package_map(s: &mut Session, mobile: bool, tol: f64) -> Result, Strin if l.is_raster() || tol <= 0.0 { continue; } - // Simplified in longitude/latitude, as the package saves it, whatever system the - // layer holds its coordinates in. + // Simplified in longitude/latitude, as the tolerance is in degrees, whatever system + // the layer holds its coordinates in; the package saves it there. if let std::borrow::Cow::Owned(ds) = l.dataset.in_lonlat()? { l.dataset = ds; } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 266bf2645b..7606a6587c 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -98,7 +98,11 @@ pub const CAPABILITIES: &[&str] = &[ "zarr-window", "blank-paper", "layout-frame-border", + NATIVE_COORDINATES, ]; +/// A layer or table saved in a coordinate system of its own, not longitude/latitude +/// (`Dataset::held_in`, #2032 C2d): an older reader would read its coordinates as degrees. +pub(crate) const NATIVE_COORDINATES: &str = "native-coordinates"; /// Independent marker sizes alongside classified point colours (`Layer::size_by`). pub(crate) const SIZE_BY_CAPABILITY: &str = "classified-point-size"; /// The most entries a document's `requires` may list: past it the document is refused without @@ -515,12 +519,15 @@ struct TableFile { crs_incomplete: bool, #[serde(default)] zm_dropped: bool, + /// The system its features are in, when not longitude/latitude (`Dataset::held_in`). + #[serde(default)] + held_in: Option, } impl From for Table { /// Loads stored data under a fresh runtime identity, never one supplied by the file. fn from(t: TableFile) -> Self { - let TableFile { id, name, geometry_type, fields, features, source, crs, crs_incomplete, zm_dropped } = t; + let TableFile { id, name, geometry_type, fields, features, source, crs, crs_incomplete, zm_dropped, held_in } = t; Table { id, instance_id: next_table_instance(), @@ -534,8 +541,8 @@ impl From for Table { crs_incomplete, zm_dropped, windowed: false, - // Saved in longitude/latitude, as `Dataset`'s own saving writes them. - held_in: rustgis_data::raster::Crs::LonLat, + // As `Dataset`'s own saving writes them. + held_in: held_in.unwrap_or(rustgis_data::raster::Crs::LonLat), shown_in: None, }, } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index de0a4b02f2..0a9548315f 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -39,6 +39,10 @@ impl Project { { required.push("field-generation"); } + // A table saved in a coordinate system of its own, as a layer's is (map_capabilities). + if !required.contains(&super::NATIVE_COORDINATES) && self.tables.iter().any(|t| held_natively(&t.dataset)) { + required.push(super::NATIVE_COORDINATES); + } // Saved symbology keeps its images too. if !required.contains(&"picture-markers") && self.styles.iter().any(|s| s.renderer.has_picture_markers()) { required.push("picture-markers"); @@ -402,6 +406,13 @@ fn zarr_window(layer: &Layer) -> bool { layer.raster.as_ref().and_then(|r| r.time_zarr.as_ref()).is_some_and(|z| z.window.is_some()) } +/// Whether a dataset saves coordinates in a coordinate system of its own (`Dataset::held_in`), +/// which an older reader would take for longitude/latitude. One with no features (a template's +/// layers) saves none, so an older release may open it. +fn held_natively(ds: &rustgis_data::Dataset) -> bool { + !ds.windowed && ds.coord_crs() != rustgis_data::raster::Crs::LonLat && !ds.features.is_empty() +} + /// The capabilities a layer needs, in [`map_capabilities`]'s order. fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { [ @@ -410,6 +421,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (layer.size_by.is_some(), super::SIZE_BY_CAPABILITY), (layer.has_picture_markers(), "picture-markers"), (zarr_window(layer), "zarr-window"), + (held_natively(&layer.dataset), super::NATIVE_COORDINATES), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) @@ -430,7 +442,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static mut pictures, mut zarr, ) = (false, false, false, false, false, false, false, false, false, false, false); - let (mut offline_area_id, mut paper) = (false, false); + let (mut offline_area_id, mut paper, mut native) = (false, false, false); for map in maps { offline_area_id |= map.offline_area_id.is_some(); // A blank basemap's paper colour (#2532), which an older reader would draw and save white. @@ -450,6 +462,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static sized |= map.layers.iter().any(|layer| layer.size_by.is_some()); pictures |= map.layers.iter().any(Layer::has_picture_markers); zarr |= map.layers.iter().any(zarr_window); + native |= map.layers.iter().any(|layer| held_natively(&layer.dataset)); legends |= map.tiles.iter().any(|tile| { tile.legends.iter().any(|legend| rustgis_data::login_address::inner(&legend.url).len() > rustgis_map::tiles::MAX_LEGEND_URL) }); @@ -468,6 +481,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (zarr, "zarr-window"), (offline_area_id, "offline-map-area-id"), (paper, "blank-paper"), + (native, super::NATIVE_COORDINATES), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 21086f5e57..384f98527c 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -401,20 +401,69 @@ fn a_selection_layer_of_a_held_layer_is_relabelled_as_it_is() { 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. +/// A project saves a held layer's features in its own system, exactly, with the system beside +/// them, and requires `native-coordinates`, so an older release refuses it rather than read them +/// as degrees (#2032 C2d). It opens back held as it was, bit for bit, as do a layer file and a map +/// file of it. A project of layers in longitude/latitude saves them as every release did, and +/// requires nothing. #[test] -fn a_held_layer_is_saved_in_lonlat() { - let [plain, mut held] = both(); +fn a_held_layer_is_saved_with_its_own_coordinates() { + let [mut plain, mut held] = both(); let dir = Dir::new("project"); let path = dir.path().join("held.rgis"); held.run("project.saveAs", &json!({"path": path.display().to_string()})).unwrap(); - let mut back = Session::new(Project::default()); - back.run("project.open", &json!({"path": path.display().to_string()})).unwrap(); + let saved: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(saved["requires"], json!(["native-coordinates"])); + let wells = &saved["maps"][0]["layers"].as_array().unwrap().iter().find(|l| l["name"] == "Wells").unwrap()["dataset"]; + assert_eq!(wells["held_in"], json!({"Epsg": 32632})); + let x = wells["features"][0]["geometry"]["Point"]["x"].as_f64().unwrap(); + assert!((600_000.0..800_000.0).contains(&x), "features saved in UTM 32N: {x}"); + let (back, _) = opened(&path); for layer in ["Wells", "Roads", "Parcels"] { - assert_eq!(back.map().layer_by_name(layer).unwrap().dataset.coord_crs(), Crs::LonLat); - assert_close(&lonlat(&back, layer), &lonlat(&plain, layer), layer); + assert_eq!(back.map().layer_by_name(layer).unwrap().dataset.coord_crs(), UTM, "{layer}"); + assert_eq!(stored(&back, layer), stored(&held, layer), "{layer}: bit for bit"); } + // A layer file and a map file keep them alike, and require it too. + let lyr = dir.path().join("wells.rgislyr"); + held.run("layer.save", &json!({"layer": "Wells", "path": lyr.display().to_string()})).unwrap(); + let rgismap = dir.path().join("held.rgismap"); + held.run("map.save", &json!({"path": rgismap.display().to_string()})).unwrap(); + for (command, file) in [("layer.addLayerFile", &lyr), ("map.import", &rgismap)] { + let header: Value = serde_json::from_str(&std::fs::read_to_string(file).unwrap()).unwrap(); + assert_eq!(header["requires"], json!(["native-coordinates"]), "{command}"); + let mut s = Session::new(Project::default()); + s.run(command, &json!({"path": file.display().to_string()})).unwrap(); + let wells = s.project.maps.iter().flat_map(|m| &m.layers).filter(|l| l.name.starts_with("Wells")).last().unwrap(); + assert_eq!(wells.dataset.coord_crs(), UTM, "{command}"); + let got: Vec> = wells.dataset.features.iter().map(|f| f.geometry.clone()).collect(); + assert_eq!(got, stored(&held, "Wells"), "{command}: bit for bit"); + } + let lonlat_path = dir.path().join("plain.rgis"); + plain.run("project.saveAs", &json!({"path": lonlat_path.display().to_string()})).unwrap(); + let saved: Value = serde_json::from_str(&std::fs::read_to_string(&lonlat_path).unwrap()).unwrap(); + assert!(saved.get("requires").is_none(), "{}", saved["requires"]); + let wells = &saved["maps"][0]["layers"].as_array().unwrap().iter().find(|l| l["name"] == "Wells").unwrap()["dataset"]; + assert!(wells.get("held_in").is_none()); + // A held layer with no features (a template's) saves no coordinates, so requires nothing. + let mut empty = Session::new(Project::default()); + let mut ds = Dataset::new("Empty", GeometryType::Point, Vec::new()); + ds.hold_in(UTM).unwrap(); + empty.map_mut().add_dataset(ds); + assert!(!empty.project.required_capabilities().contains(&"native-coordinates")); +} + +/// A session with the project at `path` opened, and what was said meanwhile. +fn opened(path: &std::path::Path) -> (Session, Vec) { + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + s.run("project.open", &json!({"path": path.display().to_string()})).unwrap(); + let said = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + (s, said) +} + +/// A layer's geometry as it holds it. +fn stored(s: &Session, layer: &str) -> Vec> { + s.map().layer_by_name(layer).unwrap().dataset.features.iter().map(|f| f.geometry.clone()).collect() } /// The numbers of a text file (an OBJ's vertices), in order. @@ -1242,3 +1291,25 @@ fn a_project_saved_by_an_older_release_opens_as_it_did() { 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"]); } + +/// A project fixture with a layer kept in UTM 32N, its features saved there (#2032 C2d), opens +/// held there, at the places PROJ gives for its points' longitude/latitude: `printf "48.7 11.5\n48.71 +/// 11.5\n" | cs2cs -d 6 EPSG:4326 EPSG:32632` gives 683944.533251 5397122.834867 and 683908.073487 +/// 5398234.294584 (PROJ 9.9.0, PROJ_NETWORK=OFF). +#[test] +fn the_held_layer_fixture_opens_held() { + let p = Project::from_json(include_str!("../../../../schema/fixtures/held_native.rgis")).unwrap(); + let wells = &p.maps[0].layers[0].dataset; + assert_eq!(wells.coord_crs(), UTM); + let at: Vec = wells + .features + .iter() + .map(|f| match f.geometry { + Some(Geometry::Point(c)) => c, + ref g => panic!("a point: {g:?}"), + }) + .collect(); + for (c, (x, y)) in at.iter().zip([(683_944.533_251, 5_397_122.834_867), (683_908.073_487, 5_398_234.294_584)]) { + assert!((c.x - x).abs() < 1e-6 && (c.y - y).abs() < 1e-6, "{c:?}"); + } +} diff --git a/docs/maintaining.md b/docs/maintaining.md index d04e050029..af13242a09 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -198,6 +198,13 @@ too, since an older reader warns that it ignores the key; `"border": null` only back and needs nothing. A saved `layout.import` whose `text` has such a frame requires it as well. Layout files are not covered, as for backgrounds (#2277). +Projects, map files and layer files with a layer or table held in a coordinate system of its own +(`Dataset::held_in`: a file's system, kept since #2580) save its features in that system, exactly, +with `held_in` beside them, and require `native-coordinates`: an older reader would read those +coordinates as longitude/latitude, and one that saved the project again would lose its system and +its exact coordinates. A layer or table in longitude/latitude is saved as before and requires +nothing (#2032 C2d). + A coordinate system read from WKT is saved with its PROJ definition, which older readers read, and its WKT beside it (`wkt`), which this release reads first. Projects, map files and layer files require `crs-wkt` when a saved system's definition doesn't place points as its WKT does diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index de449d7fca..46a5b98c6d 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -766,11 +766,12 @@ 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 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. +A layer read from a file keeps the file's own numbers, so Define Projection only relabels them. So +does a layer kept in a project saved by this release, which keeps its numbers in its own system. +A layer kept in a project saved by an older release holds its geometry in longitude/latitude, as +those releases saved 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. diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 301a5285ac..7651c61be2 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -25,6 +25,15 @@ archives do here; the package file itself is smaller. `gp.env` reports the limit (or any, added with `"stream": true`) is read in place and stays out of the project file; a smaller one is loaded whole. +A layer kept in the project is saved in the coordinate system it is held in: a layer read from a +file in its own system (a UTM Shapefile, say) keeps that system and its coordinates to the last +digit, and opens again held as it was, drawn, edited and exported as before. Layer files, map +files, project and map packages, autosave and recovery keep them too; a mobile map package +simplifies its layers in longitude/latitude and saves them there. Such a project, map or layer +file needs this version or a later one: an older release refuses it, naming +`native-coordinates`, rather than read its coordinates as longitude/latitude. A project whose +layers are all in longitude/latitude is saved as before and opens in older releases. + **Open** also accepts a project package (`.rgispkg`), as do drag-and-drop and the desktop command line. A package opens as a new, unsaved project; Save writes a plain `.rgis` file. Opening or creating a project clears undo history; saving does not. diff --git a/schema/fixtures/held_native.rgis b/schema/fixtures/held_native.rgis new file mode 100644 index 0000000000..bb19b4b3f9 --- /dev/null +++ b/schema/fixtures/held_native.rgis @@ -0,0 +1,211 @@ +{ + "requires": [ + "native-coordinates" + ], + "format": 2, + "name": "A layer kept in its own coordinate system", + "maps": [ + { + "name": "Map", + "layers": [ + { + "id": 1, + "name": "Wells", + "visible": true, + "dataset": { + "name": "Wells", + "geometry_type": "Point", + "fields": [ + { + "name": "name", + "ty": "Text", + "alias": null + }, + { + "name": "n", + "ty": "Integer", + "alias": null + } + ], + "features": [ + { + "id": 1, + "geometry": { + "Point": { + "x": 683944.5332506967, + "y": 5397122.83486662 + } + }, + "attrs": [ + { + "Text": "w0" + }, + { + "Int": 0 + } + ] + }, + { + "id": 2, + "geometry": { + "Point": { + "x": 683908.0734874264, + "y": 5398234.2945844 + } + }, + "attrs": [ + { + "Text": "w1" + }, + { + "Int": 1 + } + ] + } + ], + "source": null, + "crs": { + "Epsg": 32632 + }, + "held_in": { + "Epsg": 32632 + } + }, + "renderer": { + "Single": { + "fill": [ + 224, + 123, + 57, + 255 + ], + "stroke": [ + 255, + 255, + 255, + 255 + ], + "stroke_width": 1.0, + "size": 7.0, + "marker": "Circle" + } + }, + "labels": { + "enabled": false, + "field": "name", + "size": 10.0, + "color": [ + 43, + 43, + 43, + 255 + ], + "halo": true, + "bold": false, + "min_scale": null, + "max_scale": null, + "closest": null, + "farthest": null, + "placement": "Auto" + }, + "transparency": 0.0, + "min_scale": null, + "max_scale": null, + "definition_query": null, + "selection": [], + "expanded": true, + "selectable": true, + "graphics": false, + "blend": "Normal", + "mask": null, + "display_filters": [], + "aggregation": null, + "extrusion": null, + "priority": 0, + "geometry_rev": 0 + } + ], + "basemap": "Paper", + "camera": { + "center": { + "x": 0.0, + "y": 2000000.0 + }, + "res": 30000.0, + "bearing": 0.0, + "pitch": 0.0 + }, + "bookmarks": [], + "graticule": true, + "projection": "WebMercator", + "popup_mode": "Topmost", + "label_display": { + "paused": false, + "locked": false, + "show_unplaced": false + }, + "editing": { + "relationships": [], + "snapping": { + "enabled": false, + "tolerance_px": 10.0, + "vertex": true, + "edge": true, + "end": true + }, + "topology": [], + "settings": { + "enabled": true, + "show_vertices": true, + "elevation": "None", + "ground_to_grid": null + } + }, + "swipe": null, + "view": { + "effects": { + "stars": true, + "sun_time": null, + "weather": "None", + "vignette": false, + "edges": false, + "tilt_shift": false, + "grain": false, + "brightness": 0.0, + "contrast": 0.0, + "saturation": 0.0, + "sepia": 0.0 + }, + "wireframe": false, + "clip_distance": null, + "terrain": null + }, + "animation": [], + "next_layer_id": 2 + } + ], + "active_map": 0, + "tables": [], + "next_table_id": 1, + "gp_history": [], + "layouts": [], + "folders": [], + "styles": [], + "ramps": [], + "tasks": [], + "gp_env": { + "extent": null, + "cell_size": null + }, + "models": [], + "workspaces": [], + "link_views": false, + "jobs": [], + "offline_areas": [], + "reports": [], + "presentations": [], + "notebooks": [], + "dl_models": [], + "shared": [], + "data_stores": [] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 5ceaedeb24..99bc90e282 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -745,6 +745,18 @@ "geometry_type": { "$ref": "#/$defs/GeometryType" }, + "held_in": { + "anyOf": [ + { + "$ref": "#/$defs/Crs" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The system its features are in, when not longitude/latitude (`Dataset::held_in`)." + }, "id": { "default": 0, "format": "uint32", @@ -1093,7 +1105,8 @@ "crs-wkt", "zarr-window", "blank-paper", - "layout-frame-border" + "layout-frame-border", + "native-coordinates" ], "type": "string" }, @@ -1184,7 +1197,8 @@ "crs-wkt", "zarr-window", "blank-paper", - "layout-frame-border" + "layout-frame-border", + "native-coordinates" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2 From 4da2da18bbb4384b658ad92087f26d34728b2900 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 18:27:05 +0100 Subject: [PATCH 2/2] Review: an empty held layer requires native-coordinates too; held table test; round trip through JSON text; docs --- crates/data/src/lib.rs | 8 +++-- crates/engine/src/project_capabilities.rs | 8 ++--- crates/engine/src/tests/held_layers.rs | 37 ++++++++++++++++++++--- docs/maintaining.md | 5 +-- docs/user-guide/workspace.md | 8 ++--- 5 files changed, 48 insertions(+), 18 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index b3ab3038e6..385a177b56 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -1415,9 +1415,11 @@ mod tests { ds.push(None, vec![Value::Int(2)]); ds.push(Some(Geometry::Line(vec![line(8.1)])), vec![Value::Int(3)]); ds.hold_in(crs).unwrap(); - let saved = serde_json::to_value(&ds).unwrap(); - assert_eq!(saved["held_in"], serde_json::to_value(crs).unwrap(), "{}", crs.label()); - let back: Dataset = serde_json::from_value(saved).unwrap(); + // Through JSON text, as a project saves it. + let saved = serde_json::to_string(&ds).unwrap(); + let held_in = serde_json::from_str::(&saved).unwrap()["held_in"].clone(); + assert_eq!(held_in, serde_json::to_value(crs).unwrap(), "{}", crs.label()); + let back: Dataset = serde_json::from_str(&saved).unwrap(); assert_eq!(back.coord_crs(), crs, "{}", crs.label()); assert_eq!(bits(&back), bits(&ds), "{}", crs.label()); assert_eq!(back.features.len(), 3); diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 0a9548315f..fd0d0b6d9d 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -406,11 +406,11 @@ fn zarr_window(layer: &Layer) -> bool { layer.raster.as_ref().and_then(|r| r.time_zarr.as_ref()).is_some_and(|z| z.window.is_some()) } -/// Whether a dataset saves coordinates in a coordinate system of its own (`Dataset::held_in`), -/// which an older reader would take for longitude/latitude. One with no features (a template's -/// layers) saves none, so an older release may open it. +/// Whether a dataset is saved in a coordinate system of its own (`Dataset::held_in`): an older +/// reader would take its coordinates for longitude/latitude, and save it again without its +/// system (one with no features too, such as a template's layers). fn held_natively(ds: &rustgis_data::Dataset) -> bool { - !ds.windowed && ds.coord_crs() != rustgis_data::raster::Crs::LonLat && !ds.features.is_empty() + !ds.windowed && ds.coord_crs() != rustgis_data::raster::Crs::LonLat } /// The capabilities a layer needs, in [`map_capabilities`]'s order. diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 384f98527c..04c8ca8223 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -418,7 +418,8 @@ fn a_held_layer_is_saved_with_its_own_coordinates() { assert_eq!(wells["held_in"], json!({"Epsg": 32632})); let x = wells["features"][0]["geometry"]["Point"]["x"].as_f64().unwrap(); assert!((600_000.0..800_000.0).contains(&x), "features saved in UTM 32N: {x}"); - let (back, _) = opened(&path); + let (back, said) = opened(&path); + assert!(said.is_empty(), "nothing to say: {said:?}"); for layer in ["Wells", "Roads", "Parcels"] { assert_eq!(back.map().layer_by_name(layer).unwrap().dataset.coord_crs(), UTM, "{layer}"); assert_eq!(stored(&back, layer), stored(&held, layer), "{layer}: bit for bit"); @@ -444,20 +445,46 @@ fn a_held_layer_is_saved_with_its_own_coordinates() { assert!(saved.get("requires").is_none(), "{}", saved["requires"]); let wells = &saved["maps"][0]["layers"].as_array().unwrap().iter().find(|l| l["name"] == "Wells").unwrap()["dataset"]; assert!(wells.get("held_in").is_none()); - // A held layer with no features (a template's) saves no coordinates, so requires nothing. + // A held layer with no features (a template's) requires it too: an older reader would save + // it again without its system. let mut empty = Session::new(Project::default()); let mut ds = Dataset::new("Empty", GeometryType::Point, Vec::new()); ds.hold_in(UTM).unwrap(); empty.map_mut().add_dataset(ds); - assert!(!empty.project.required_capabilities().contains(&"native-coordinates")); + assert!(empty.project.required_capabilities().contains(&"native-coordinates")); } -/// A session with the project at `path` opened, and what was said meanwhile. +/// A table held in a system of its own is saved there with its system and requires +/// `native-coordinates`, and opens back held, bit for bit; one in longitude/latitude requires +/// nothing (#2032 C2d). +#[test] +fn a_held_table_is_saved_with_its_own_coordinates() { + let dir = Dir::new("project-table"); + for (crs, required) in [(UTM, true), (Crs::LonLat, false)] { + let mut s = Session::new(Project::default()); + let mut ds = layers().remove(0); + ds.hold_in(crs).unwrap(); + let rows: Vec> = ds.features.iter().map(|f| f.geometry.clone()).collect(); + s.project.add_table(ds); + let path = dir.path().join(format!("{}.rgis", crs.label().replace(':', "-"))); + s.run("project.saveAs", &json!({"path": path.display().to_string()})).unwrap(); + let saved: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(saved.get("requires").is_some_and(|r| r == &json!(["native-coordinates"])), required, "{}", crs.label()); + let (back, said) = opened(&path); + assert!(said.is_empty(), "nothing to say: {said:?}"); + let t = &back.project.tables[0].dataset; + assert_eq!(t.coord_crs(), crs); + assert_eq!(t.features.iter().map(|f| f.geometry.clone()).collect::>(), rows, "{}: bit for bit", crs.label()); + } +} + +/// A session with the project at `path` opened, and what was said meanwhile besides that it +/// opened. fn opened(path: &std::path::Path) -> (Session, Vec) { let mut s = Session::new(Project::default()); let mark = s.notice_mark(); s.run("project.open", &json!({"path": path.display().to_string()})).unwrap(); - let said = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let said = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| !t.starts_with("Opened ")).collect(); (s, said) } diff --git a/docs/maintaining.md b/docs/maintaining.md index af13242a09..3ed9caf578 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -202,8 +202,9 @@ Projects, map files and layer files with a layer or table held in a coordinate s (`Dataset::held_in`: a file's system, kept since #2580) save its features in that system, exactly, with `held_in` beside them, and require `native-coordinates`: an older reader would read those coordinates as longitude/latitude, and one that saved the project again would lose its system and -its exact coordinates. A layer or table in longitude/latitude is saved as before and requires -nothing (#2032 C2d). +its exact coordinates. That holds for one with no features too (a template's layers), whose system +an older reader would also save away. A layer or table in longitude/latitude, or a window onto a +streamed source, is saved as before and requires nothing (#2032 C2d). A coordinate system read from WKT is saved with its PROJ definition, which older readers read, and its WKT beside it (`wkt`), which this release reads first. Projects, map files and layer diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 7651c61be2..71c2510655 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -28,11 +28,11 @@ smaller one is loaded whole. A layer kept in the project is saved in the coordinate system it is held in: a layer read from a file in its own system (a UTM Shapefile, say) keeps that system and its coordinates to the last digit, and opens again held as it was, drawn, edited and exported as before. Layer files, map -files, project and map packages, autosave and recovery keep them too; a mobile map package -simplifies its layers in longitude/latitude and saves them there. Such a project, map or layer +files, project and map packages, autosave and recovery keep them too; a mobile map package that +simplifies its layers does so in longitude/latitude and saves them there. Such a project, map or layer file needs this version or a later one: an older release refuses it, naming -`native-coordinates`, rather than read its coordinates as longitude/latitude. A project whose -layers are all in longitude/latitude is saved as before and opens in older releases. +`native-coordinates`, rather than read its coordinates as longitude/latitude. Layers in +longitude/latitude are saved as before and don't need it. **Open** also accepts a project package (`.rgispkg`), as do drag-and-drop and the desktop command line. A package opens as a new, unsaved project; Save writes a plain `.rgis` file.