From 54f3af64e1f7728c04998ba05e766d8c64190d78 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 09:46:48 +0100 Subject: [PATCH 1/9] Readers keep a feature with a place that can't be given in longitude/latitude as the file holds it, and say so (#2032 C2f-4b-2a) --- crates/data/src/cityjson/tests.rs | 19 +-- crates/data/src/citymodel.rs | 42 +++---- crates/data/src/dxf.rs | 53 ++++---- crates/data/src/esripbf.rs | 22 ++-- crates/data/src/esripbf/tests.rs | 16 ++- crates/data/src/filegdb.rs | 16 +-- crates/data/src/filegdb/tests.rs | 11 +- crates/data/src/gml.rs | 26 ++-- crates/data/src/io.rs | 116 +++++++++--------- crates/data/src/landxml.rs | 20 ++- crates/data/src/mapinfo.rs | 21 ++-- crates/data/src/publish.rs | 19 +-- crates/data/src/source/geojson.rs | 92 ++++++-------- crates/data/src/source/tests.rs | 67 ++++++---- crates/data/src/unplaced_out_tests.rs | 46 +++++++ crates/engine/src/tests/unplaced_gp.rs | 7 +- .../tests/integration/define_projection.rs | 20 +-- crates/geolibre/src/lib.rs | 17 ++- docs/user-guide/data-formats.md | 21 +++- 19 files changed, 359 insertions(+), 292 deletions(-) diff --git a/crates/data/src/cityjson/tests.rs b/crates/data/src/cityjson/tests.rs index 46e191736b..e1d4c19471 100644 --- a/crates/data/src/cityjson/tests.rs +++ b/crates/data/src/cityjson/tests.rs @@ -625,10 +625,11 @@ fn what_a_file_says_of_its_coordinate_system_is_checked() { assert!(says(&out, "coordinates are not longitude/latitude"), "{:?}", messages_of(&out)); } -/// A geometry the coordinate system can't convert is lost, which defining the projection again can't -/// bring back, so the layer says so. With none converted the system is wrong: an error. +/// A geometry the coordinate system can't convert is kept as the file holds it and said; it doesn't +/// draw. With none converted the system seems wrong: said so, and kept, so Define Projection can +/// set the right one (#2032 C2f-4b). #[test] -fn objects_that_cant_be_converted_mark_the_layer() { +fn objects_that_cant_be_converted_are_kept_and_said() { let triangle = |a: i64| json!({"type": "LandUse", "geometry": [{"type": "MultiSurface", "lod": "1", "boundaries": [[[a, a + 1, a + 2]]]}]}); let near = [[0.0, 0.0, 0.0], [1000.0, 0.0, 0.0], [1000.0, 1000.0, 0.0]]; @@ -636,16 +637,18 @@ fn objects_that_cant_be_converted_mark_the_layer() { let vertices: Vec<[f64; 3]> = near.iter().chain(&far).copied().collect(); let bytes = doc(json!(vertices), json!({"a": triangle(0), "b": triangle(3)})); let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); - assert!(out[0].0.crs_incomplete); - assert!(says(&out, "1 city objects have coordinates outside their coordinate system"), "{:?}", messages_of(&out)); + assert!(!out[0].0.crs_incomplete); + assert!(out[0].0.features.rows().all(|r| r.geometry().is_some()), "both kept"); + assert!(says(&out, "1 city objects have a place in EPSG:3857 that can't be given in longitude/latitude"), "{:?}", messages_of(&out)); let bytes = doc(json!(vertices), json!({"a": triangle(0)})); let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); assert!(!out[0].0.crs_incomplete); // Only that the system given goes over the one the file names (`doc`'s EPSG:4326). assert_eq!(messages_of(&out), vec!["the file names EPSG:4326, and is read in EPSG:3857, the coordinate system given".to_string()]); let bytes = doc(json!(vertices), json!({"b": triangle(3)})); - let e = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap_err().to_string(); - assert!(e.contains("no object could be converted"), "{e}"); + let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); + assert!(out[0].0.features.rows().all(|r| r.geometry().is_some())); + assert!(says(&out, "none of the city objects has a place in longitude/latitude from EPSG:3857"), "{:?}", messages_of(&out)); } /// An object is counted once in a notice, however many of its geometry families it loses. @@ -664,7 +667,7 @@ fn an_object_losing_several_families_is_counted_once() { }), ); let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); - assert!(says(&out, "1 city objects have coordinates outside their coordinate system"), "{:?}", messages_of(&out)); + assert!(says(&out, "1 city objects have a place in EPSG:3857 that can't be given in longitude/latitude"), "{:?}", messages_of(&out)); } /// A byte order mark doesn't hide a model, and a file named only `.city.json` still names its layer. diff --git a/crates/data/src/citymodel.rs b/crates/data/src/citymodel.rs index 672a8906c2..9353df4663 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -148,7 +148,11 @@ pub(crate) struct Counts { pub(crate) tin_reliefs: usize, /// Implicit geometries inside a prototype (CityGML), which place nothing. pub(crate) nested_instances: usize, + /// Objects kept as the file holds them with a place that can't be given in longitude/latitude + /// from `crs`, which don't draw; `all_unconverted` when no object has one. pub(crate) unconverted: usize, + pub(crate) all_unconverted: bool, + pub(crate) crs: Option, pub(crate) bad_heights: usize, /// Objects whose lowest and highest Z, or lowest Z and ground, are too far apart for their /// difference to be a number. @@ -568,14 +572,13 @@ 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::lonlat_box(&g, &to_lonlat).map(|_| g); - if row.geometry.is_none() { - (row.unconverted, row.draws) = (true, false); - objects.insert(row.object); - } + // Kept as the file holds it, in its system; marked, as it doesn't draw, when it has no + // place in longitude/latitude (as `geometry_to_lonlat` would give it). + if let Some(g) = &row.geometry + && crate::io::lonlat_box(g, &to_lonlat).is_none() + { + (row.unconverted, row.draws) = (true, false); + objects.insert(row.object); } } counts.unconverted += objects.len(); @@ -591,15 +594,13 @@ pub(crate) fn finish( let is_3d = |b: &Built| b.solid || b.z.is_some_and(|(lo, hi)| hi > lo); counts.footprints = rows .iter() - .filter(|r| r.family == Family::Polygon && r.geometry.is_some()) + .filter(|r| r.family == Family::Polygon && r.geometry.is_some() && !r.unconverted) .filter(|r| built.get(r.object).is_some_and(is_3d)) .count(); - if counts.unconverted > 0 && rows.iter().all(|r| r.geometry.is_none()) { - return Err(DataError::Format(format!( - "{file_name}: no object could be converted from {} to longitude/latitude: that coordinate system doesn't seem to match the coordinates", - crs.label() - ))); - } + // None of them has a place there: its system doesn't seem to match the coordinates, said so, + // and the objects kept, so Define Projection can set the one that does. + counts.all_unconverted = counts.unconverted > 0 && rows.iter().all(|r| r.geometry.is_none() || r.unconverted); + counts.crs = Some(crs); let mut out = layers(stem, rows, &built, crs, &mut counts); if out.is_empty() { @@ -975,7 +976,7 @@ fn layers(stem: &str, rows: Vec, built: &[Built], crs: Crs, counts: &mut Co // (`raise_parents`), so standing too they would cover the lower parts with the tallest one. let carried: HashSet<&str> = rows .iter() - .filter(|r| r.family == Family::Polygon && r.geometry.is_some()) + .filter(|r| r.family == Family::Polygon && r.geometry.is_some() && !r.unconverted) .filter_map(|r| built.get(r.object)) .filter(|b| PARTS.contains(&b.ty.as_str()) && rises(b)) .flat_map(|b| b.parent_ids.iter().map(String::as_str)) @@ -1045,8 +1046,6 @@ fn layers(stem: &str, rows: Vec, built: &[Built], crs: Crs, counts: &mut Co } let mut ds = Dataset::new(&name, kind, order.iter().filter_map(|&i| fields.get(i).cloned()).collect()); let z_dropped = rows.iter().filter(|(r, _)| r.z_dropped).count(); - // What couldn't be converted can't come back by defining the projection again. - ds.crs_incomplete = rows.iter().any(|(r, _)| r.unconverted); for (row, b) in rows { let mut attrs = vec![Value::Null; fields.len()]; for (k, v) in &properties(b, row.lod.as_deref(), &renames) { @@ -1155,10 +1154,9 @@ pub(crate) fn messages(c: &Counts) -> Vec { ); say(c.nested_instances, format!("{} implicit geometries inside a prototype aren't placed", c.nested_instances)); say(c.tin_reliefs, format!("{} TINRelief objects aren't drawn and are left out", c.tin_reliefs)); - say( - c.unconverted, - format!("{} city objects have coordinates outside their coordinate system: they are kept without geometry", c.unconverted), - ); + if let Some(note) = c.crs.and_then(|crs| crate::io::kept_unplaced_note("", "city objects", c.unconverted, c.all_unconverted, crs)) { + say(c.unconverted, note); + } say( c.bad_heights, format!("{} city objects have heights that aren't finite numbers, which z_min, z_max and height leave out", c.bad_heights), diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 8aed10c6d9..278f24d4e6 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1693,20 +1693,18 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result 0 { - rep.messages.push(format!("{lost} features couldn't be converted from {}", c.label())); - } + rep.messages.extend(crate::io::kept_unplaced_note("", "features", lost, placed == 0, *c)); } if transformer.is_none() { for (_, loss) in losses { @@ -2053,16 +2049,17 @@ mod tests { "2 vertices without Y were left out of spline paths", ] ); - // A CRS-rejected placement contributes no partial counters. + // A placement with no place in longitude/latitude is kept as the drawing holds it + // (#2032 C2f-4b), so what it lost is said too. let text = "0 SECTION 2 ENTITIES 0 POINT 10 0 20 0 0 SPLINE 71 3 11 0 21 100 11 1 11 2 21 101 0 ENDSEC 0 EOF" .split_whitespace() .collect::>() .join("\n"); let layers = read("a.dxf", text.as_bytes(), &Options { crs: Some(Crs::from_epsg(4269).unwrap()), ..Options::default() }).unwrap(); let messages: Vec<&str> = layers.iter().flat_map(|(_, report)| &report.messages).map(|m| m.as_str()).collect(); - assert_eq!(messages.len(), 1); - assert!(messages[0].starts_with("1 features couldn't be converted from ")); - assert!(!messages[0].contains("without Y")); + assert_eq!(messages.len(), 2, "{messages:?}"); + assert!(messages.iter().any(|m| m.contains("from EPSG:4269") && m.contains("kept as the file holds them")), "{messages:?}"); + assert!(messages.iter().any(|m| m.contains("without Y")), "{messages:?}"); } #[test] @@ -2909,7 +2906,8 @@ mod tests { let layers = read("placed.dxf", text.as_bytes(), &opts).unwrap(); assert_eq!(layers.len(), 2); let lines = &layers[1].0; - assert_eq!(lines.features.len(), 2); + // The insertion at 100°N has no place in longitude/latitude: kept as the drawing holds it. + assert_eq!(lines.features.len(), 3); assert_eq!(lines.held_in, opts.crs.unwrap()); assert!(!lines.zm_dropped); for (i, x) in [10.0, 14.0].into_iter().enumerate() { @@ -2932,7 +2930,8 @@ mod tests { } let notes: Vec<&str> = layers.iter().flat_map(|(_, r)| &r.messages).filter(|m| m.contains("POLYLINE")).map(|m| m.as_str()).collect(); - assert_eq!(notes, ["4 unreadable POLYLINE vertices were left out of their lines"]); + // The kept insertion at 100°N counts its own (#2032 C2f-4b). + assert_eq!(notes, ["6 unreadable POLYLINE vertices were left out of their lines"]); let no_blocks = read("placed.dxf", text.as_bytes(), &Options { blocks: false, ..opts }).unwrap(); assert_eq!(no_blocks.len(), 1); assert!(no_blocks.iter().all(|(_, r)| r.messages.iter().all(|m| !m.contains("POLYLINE")))); @@ -3310,21 +3309,21 @@ mod tests { } } - /// A wholly rejected feature loses its geometry, not just heights in retained output. + /// A feature with no place in longitude/latitude is kept as the drawing holds it (#2032 + /// C2f-4b), its varying heights dropped and said, as any kept feature's. #[test] - fn varying_heights_exclude_crs_rejected_features() { + fn varying_heights_of_a_kept_unplaced_feature_are_said() { let text = "0 SECTION 2 ENTITIES 0 POINT 10 0 20 0 30 5 0 LINE 10 0 20 100 30 5 11 1 21 100 31 9 0 ENDSEC 0 EOF" .split_whitespace() .collect::>() .join("\n"); let layers = read("crs.dxf", text.as_bytes(), &Options { crs: Some(Crs::from_epsg(4269).unwrap()), ..Options::default() }).unwrap(); - assert_eq!(layers.iter().map(|(ds, _)| ds.features.len()).sum::(), 1); - assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Point(Coord::new(0.0, 0.0)))); - assert!(layers.iter().all(|(ds, r)| !ds.zm_dropped && r.messages.iter().all(|m| !m.contains("varying Z")))); + assert_eq!(layers.iter().map(|(ds, _)| ds.features.len()).sum::(), 2); + assert!(layers.iter().flat_map(|(ds, _)| ds.features.rows()).all(|r| r.geometry().is_some())); let messages: Vec<&str> = layers.iter().flat_map(|(_, r)| &r.messages).map(|m| m.as_str()).collect(); - assert_eq!(messages.len(), 1); - assert!(messages[0].starts_with("1 features couldn't be converted from "), "{messages:?}"); + assert!(messages.iter().any(|m| m.contains("EPSG:4269") && m.contains("kept as the file holds them")), "{messages:?}"); + assert!(messages.iter().any(|m| m.contains("varying Z")), "{messages:?}"); } #[test] diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 5eb31c3f6c..f860858a24 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -132,7 +132,8 @@ pub struct Losses { pub not_utf8: usize, /// Polygon rings without area. pub flat_rings: usize, - /// Features whose coordinates are outside their coordinate system. + /// Features with a place that can't be given in longitude/latitude (coordinates outside their + /// coordinate system): kept as the answer gives them, but not drawn. pub unprojected: usize, /// Features with Z or M values, dropped. pub with_zm: usize, @@ -170,7 +171,7 @@ impl Losses { } if self.unprojected > 0 { out.push(format!( - "{} features have coordinates outside their coordinate system: they are kept without geometry", + "{} features have a place that can't be given in longitude/latitude (coordinates outside their coordinate system): they are kept as the answer gives them, but don't draw", self.unprojected )); } @@ -360,16 +361,11 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> 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 ok = crate::io::lonlat_box(&g, t).is_some(); - unprojected += usize::from(!ok); - ok.then_some(g) - } - (g, _) => g, - }; + // Kept as the answer holds it, in its own system; counted when it has no place in + // longitude/latitude (as `geometry_to_lonlat` would give it). + if let (Some(g), Some(t)) = (&geometry, &to_lonlat) { + unprojected += usize::from(crate::io::lonlat_box(g, t).is_none()); + } ds.push_next(geometry, values); } if geometry_type.is_some() || any_geometry { @@ -380,8 +376,6 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result 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 { // Assumed, so said: an answer that names no coordinate system. no_crs: any_geometry && code.is_none() && wkt.is_none(), diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 045da4bb64..34a334ce46 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -245,7 +245,7 @@ fn an_answer_without_a_coordinate_system_is_said_to_be_read_as_longitude_latitud } #[test] -fn coordinates_past_longitude_latitude_lose_their_geometry_and_the_layer_says_so() { +fn coordinates_past_longitude_latitude_are_kept_and_the_layer_says_so() { // Web Mercator: 1,113,195 m is 10°; 1,000,000,000 m comes out near 8,983°, beyond the world. let bytes = answer(&[ message(8, &number(1, 3857)), @@ -255,10 +255,16 @@ fn coordinates_past_longitude_latitude_lose_their_geometry_and_the_layer_says_so ]); let (ds, report) = read(&bytes, "t").unwrap(); assert!(ds.features[0].geometry.is_some()); - assert_eq!(ds.features[1].geometry, None); - // Defining the projection again can't bring it back. - assert!(ds.crs_incomplete); - assert_eq!(report.messages, ["1 features have coordinates outside their coordinate system: they are kept without geometry"]); + // Kept as the answer gives it, and not drawn (#2032 C2f-4b): nothing was lost, so a + // projection can still be defined. + assert_eq!(ds.features[1].geometry, Some(Geometry::Point(c(1e9, 0.0)))); + assert!(!ds.crs_incomplete); + assert_eq!( + report.messages, + [ + "1 features have a place that can't be given in longitude/latitude (coordinates outside their coordinate system): they are kept as the answer gives them, but don't draw" + ] + ); } #[test] diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index a21ab43367..8c2941168f 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -410,15 +410,11 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> 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 ok = crate::io::places_in_lonlat(&g, t); - unprojected += usize::from(!ok); - ok.then_some(g) - } - (g, _) => g, - }; + // Kept as the file holds it, in its own system; counted when it has no place in + // longitude/latitude. + if let (Some(g), Some(t)) = (&geometry, &to_lonlat) { + unprojected += usize::from(!crate::io::places_in_lonlat(g, t)); + } ds.push_next(geometry, attrs); } let rounded: usize = rounded_dates.iter().sum(); @@ -439,7 +435,7 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 0 { report .messages - .push(format!("{unprojected} features have coordinates outside their coordinate system: they are kept without geometry")); + .push(format!("{unprojected} features have a place that can't be given in longitude/latitude (coordinates outside their coordinate system): they are kept as the file holds them, but don't draw")); } if zm { // The table declares them for every shape. diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index 64be0f0044..c5aac188eb 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -539,7 +539,8 @@ fn a_table_with_missing_files_is_said() { assert_eq!(read.unread[0].1, "its file a00000003.gdbtablx is missing"); } -/// A feature whose coordinates its coordinate system can't place keeps its row, and is said. +/// A feature whose coordinates its coordinate system can't place is kept as the file holds it, and +/// said (#2032 C2f-4b). #[test] fn coordinates_that_cant_be_converted_are_said() { const LAEA: &str = r#"PROJCS["ETRS89 / LAEA Europe",GEOGCS["ETRS89",DATUM["European_Terrestrial_Reference_System_1989",SPHEROID["GRS 1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["latitude_of_center",52],PARAMETER["longitude_of_center",10],PARAMETER["false_easting",4321000],PARAMETER["false_northing",3210000],UNIT["metre",1],AUTHORITY["EPSG","3035"]]"#; @@ -554,8 +555,12 @@ fn coordinates_that_cant_be_converted_are_said() { let (ds, report) = &layers[0]; let rows: Vec<&crate::Feature> = ds.features.iter().collect(); assert_eq!(rows.len(), 2); - assert!(rows[0].geometry.is_some() && rows[1].geometry.is_none(), "{:?}", rows[1].geometry); - assert!(report.messages.iter().any(|m| m.starts_with("1 features have coordinates outside")), "{report:?}"); + assert!(rows[0].geometry.is_some() && rows[1].geometry.is_some(), "{:?}", rows[1].geometry); + assert!(!ds.crs_incomplete); + assert!( + report.messages.iter().any(|m| m.starts_with("1 features have a place that can't be given in longitude/latitude")), + "{report:?}" + ); } #[test] diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 17642d96a3..722d6918ba 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -664,9 +664,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> Some((_, true)) => g.map_coords(&|c| Coord::new(c.y, c.x)), _ => g, }); - // 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. + // A place that can't be given in longitude/latitude is kept as the file holds it, and + // counted: its feature doesn't draw, and each step that needs longitude/latitude + // leaves it out and says so (#2032 C2f-4b). 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)) => { @@ -682,7 +683,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> _ if !c.is_finite() => c, _ => { missing.set(true); - Coord::new(f64::NAN, f64::NAN) + c } }); unplaced += usize::from(missing.get()); @@ -727,7 +728,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> 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 kept as missing coordinates and don't draw", + "{}: {unplaced} {what} places{system} that can't be given in longitude/latitude; they are kept as the file holds them, but don't draw", ds.name )); } @@ -886,11 +887,11 @@ 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's places that convert are still read in - /// longitude/latitude; its other places keep the file's numbers. + /// A place a file's system can't give in longitude/latitude is kept as the file holds it, and + /// said: its feature doesn't draw, and a step in longitude/latitude leaves it out (#2032 + /// C2f-4b). #[test] - fn a_place_with_no_longitude_latitude_is_kept_missing() { + fn a_place_with_no_longitude_latitude_is_kept_as_the_file_holds_it() { let gml = r#" 500000,4649776 1e15,4649776 "#; @@ -899,10 +900,11 @@ mod tests { 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_eq!(parts[0][1], Coord::new(1e15, 4649776.0), "the file's numbers"); 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()); + let said = &layers[0].1.messages; + assert!(said.iter().any(|m| m.contains("1 feature has places") && m.contains("kept as the file holds them")), "{said:?}"); + assert_eq!(ds.in_lonlat_leaving_out().unwrap().1, 1); } #[test] diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index a48832343e..f3b675cc90 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1690,6 +1690,29 @@ pub(crate) fn lonlat_box(g: &Geometry, t: &crate::raster::Transformer) -> Option ok.then_some(out) } +/// What a reader says of the `n` of its `what` (features, shapes, rows) it keeps as the file holds +/// them, held in `crs`, though a place of theirs can't be given in longitude/latitude (or comes +/// out beyond it): they don't draw (the map says so too), and every other step that needs +/// longitude/latitude leaves them out and says so (#2032 C2f-4b). `all` when none of the file's +/// has a place there: then its system doesn't seem to match its coordinates, and Define +/// Projection can set the one that does, as nothing was lost. `None` for none. +pub(crate) fn kept_unplaced_note(name: &str, what: &str, n: usize, all: bool, crs: Crs) -> Option { + let name = if name.is_empty() { String::new() } else { format!("{name}: ") }; + (n > 0).then(|| { + if all { + format!( + "{name}none of the {what} has a place in longitude/latitude from {}: it doesn't seem to be their coordinate system. They are kept as the file holds them, but don't draw; Define Projection can set the right one", + crs.label() + ) + } else { + format!( + "{name}{n} {what} have a place in {} that can't be given in longitude/latitude: they are kept as the file holds them, but don't draw", + crs.label() + ) + } + }) +} + /// 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). @@ -1931,26 +1954,20 @@ impl Collector { let mut said = Vec::new(); let declared = declared_crs(root, &mut said)?; report.messages.extend(said); - let mut unconverted = 0usize; + let (mut unconverted, mut placed) = (0usize, 0usize); // Only features kept count toward the heights dropped. let mut zm = 0usize; // Features kept, as longitude/latitude, with a latitude past the poles. let mut swapped = 0usize; 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 lonlat_box(&g, t) { - Some(_) => Some(g), - None => { - unconverted += 1; - continue; - } - }, - (_, g) => g, - }; + // Kept as the file holds it, in its declared system, and counted when it has no place + // in longitude/latitude (as [`geometry_to_lonlat`] would give it), as when the file is + // read in place. + if let (Some((_, t)), Some(g)) = (&declared, &geom) { + let has = lonlat_box(g, t).is_some(); + placed += usize::from(has); + unconverted += usize::from(!has); + } let mut attrs = vec![Value::Null; ds.fields.len()]; for (i, v) in values { if let (Some(slot), Some(field)) = (attrs.get_mut(i), ds.fields.get(i)) { @@ -1958,8 +1975,7 @@ impl Collector { } } zm += usize::from(had_z); - // Converted geometry is already within ±90.5° (or dropped above), so only what is read - // as longitude/latitude can be swapped. + // Only what is read as longitude/latitude can be swapped. swapped += usize::from(declared.is_none() && geom.as_ref().is_some_and(latitude_past_poles)); ds.features.push(crate::Feature { id: n as u64 + 1, geometry: geom, attrs }); } @@ -1967,15 +1983,7 @@ impl Collector { if let Some((crs, _)) = &declared { ds.crs = Some(*crs); ds.held_in = *crs; - if unconverted > 0 { - report.skipped += unconverted; - report.messages.push(format!( - "{unconverted} features couldn't be converted from {} to longitude/latitude and were skipped", - crs.label() - )); - } - // What couldn't be converted can't come back by defining the projection again. - ds.crs_incomplete = unconverted > 0; + report.messages.extend(kept_unplaced_note("", "features", unconverted, placed == 0, *crs)); } report.messages.extend(swapped_latitude_note(swapped)); // Last, as a source read in place notes it. @@ -2974,22 +2982,16 @@ 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. + // Kept as the file holds them, in its system; counted where they have no 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() { - if places_in_lonlat(&g, &t) { - f.geometry = Some(g); - } else { - lost += 1; - } - } - } - if lost > 0 { - report.skipped += lost; - report.messages.push(format!("{lost} rows couldn't be converted from {} to longitude/latitude", c.label())); + let (mut lost, mut placed) = (0usize, 0usize); + for g in ds.features.iter().filter_map(|f| f.geometry.as_ref()) { + let has = places_in_lonlat(g, &t); + placed += usize::from(has); + lost += usize::from(!has); } + report.messages.extend(kept_unplaced_note("", "rows", lost, placed == 0, c)); } let read_as_degrees = crs.is_none_or(Crs::is_geographic); let (mut outside, mut zero) = (0usize, 0usize); @@ -4107,19 +4109,16 @@ 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 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) + // Kept as the file holds it, in its own system; counted when it has no place in + // longitude/latitude. + if let (Some(t), Some(g)) = (&to_lonlat, &geom) { + let placed = places_lonlat_extent(g, t); + if let Some(e) = &placed { + lonlat_extent = lonlat_extent.union(e); } - (_, g) => g, - }; + converted += usize::from(placed.is_some()); + unconverted += usize::from(placed.is_none()); + } let attrs = dbf_attrs(&record, &ds.fields, &mut counts); ds.push_next(geom, attrs); } @@ -4147,9 +4146,9 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio } dbf_notices(&ds, &mut report, &counts); ds.geometry_type = dominant_type(&ds); - // A bad .prj must not turn a spatial layer into an attribute-only table and hide the - // conversion warning. Its shapes can be recovered by importing with an override. - if ds.geometry_type == GeometryType::None && (unconverted > 0 || not_numbers > 0) { + // Shapes whose coordinates aren't numbers must not turn a spatial layer into an + // attribute-only table. + if ds.geometry_type == GeometryType::None && not_numbers > 0 { ds.geometry_type = source_kind; } integral_numeric_to_integer(&mut ds, &decimals); @@ -4176,11 +4175,8 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio "{name}: {not_numbers} shape(s) have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry" )); } - ds.crs_incomplete = unconverted > 0; - if unconverted > 0 && converted == 0 { - report.messages.push("no shape could be converted to longitude/latitude: the .prj doesn't seem to match the coordinates"); - } else if unconverted > 0 { - report.messages.push(format!("{unconverted} shapes couldn't be converted to longitude/latitude and have no geometry")); + if let Some(c) = ds.crs.filter(|_| to_lonlat.is_some()) { + report.messages.extend(kept_unplaced_note("", "shapes", unconverted, converted == 0, c)); } Ok((ds, report)) } diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index aeba0300cf..6bc9c9d219 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -235,22 +235,16 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result 0 { - rep.messages.push(format!("{lost} features couldn't be converted from {}", c.label())); + let (mut lost, mut placed) = (0usize, 0usize); + for g in ds.features.iter().filter_map(|f| f.geometry.as_ref()) { + let has = crate::io::places_in_lonlat(g, t); + placed += usize::from(has); + lost += usize::from(!has); } + rep.messages.extend(crate::io::kept_unplaced_note("", "features", lost, placed == 0, *c)); } out.push((ds, rep)); } diff --git a/crates/data/src/mapinfo.rs b/crates/data/src/mapinfo.rs index ae61655a6f..bed1900a5a 100644 --- a/crates/data/src/mapinfo.rs +++ b/crates/data/src/mapinfo.rs @@ -444,17 +444,14 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe if let (Some(_), Some(c)) = (&t, crs) { ds.held_in = c; } - let (mut lost, mut null_text) = (0usize, Vec::new()); + let (mut lost, mut placed, mut null_text) = (0usize, 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 ok = crate::io::places_in_lonlat(&g, t); - lost += usize::from(!ok); - ok.then_some(g) - } - (_, g) => g, - }; + // Kept as the file holds it; counted when it has no place in longitude/latitude. + if let (Some(t), Some(g)) = (&t, &g) { + let has = crate::io::places_in_lonlat(g, t); + placed += usize::from(has); + lost += usize::from(!has); + } let row = rows.get(k); let attrs = ds .fields @@ -470,8 +467,8 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe .collect(); ds.push_next(g, attrs); } - if lost > 0 { - report.messages.push(format!("{lost} objects couldn't be converted to longitude/latitude")); + if let (Some(_), Some(c)) = (&t, crs) { + report.messages.extend(crate::io::kept_unplaced_note("", "objects", lost, placed == 0, c)); } report.messages.extend(crate::source::null_text_note(&ds.fields, &null_text)); ds.geometry_type = crate::io::dominant_type(&ds); diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 285e3e6419..d0230e6889 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -1517,9 +1517,10 @@ mod tests { } } - /// An unconverted source shape cannot supply geometry to a new geometry-less feature. + /// A source shape with no place in longitude/latitude is read as the file holds it (#2032 + /// C2f-4b), so a publish of an attribute edit writes it back unchanged, to the bit. #[test] - fn an_unconverted_shape_cannot_be_copied_to_a_geometryless_feature() { + fn a_shape_with_no_longitude_latitude_place_is_written_back_unchanged() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("parcels.shp"); let mut native = Dataset::new("parcels", GeometryType::Point, vec![Field::new("OWNER", FieldType::Text)]); @@ -1529,11 +1530,15 @@ mod tests { let crs = Crs::parse("EPSG:32616").unwrap(); std::fs::write(path.with_extension("prj"), crate::raster::wkt::to_wkt(crs).unwrap()).unwrap(); let (mut ds, sync) = read(&path); - assert_eq!(ds.features.iter().filter(|f| f.geometry.is_none()).count(), 1); - ds.push(None, vec![Value::Text("new".into())]); - let error = shapefile(&ds, &path, &sync).err().expect("unconverted shapes must not be assigned to new features").to_string(); - assert!(error.contains("source shape 1") && error.contains("converted") && error.contains("nothing was written"), "{error}"); - assert!(sync.files.changed(&path).unwrap().is_empty()); + assert_eq!(ds.features.iter().filter(|f| f.geometry.is_none()).count(), 0); + let mut rows: Vec<_> = ds.features.iter().cloned().collect(); + rows[1].attrs[0] = Value::Text("edited".into()); + ds.features = rows.into(); + shapefile(&ds, &path, &sync).unwrap(); + let (back, _) = read(&path); + let shapes: Vec> = back.features.iter().map(|f| f.geometry.clone()).collect(); + assert_eq!(shapes, [Some(Geometry::Point(Coord::new(1e30, 1e30))), Some(Geometry::Point(Coord::new(500_000.0, 0.0)))]); + assert_eq!(back.features.row(1).unwrap().value(0), &Value::Text("edited".into())); } /// After deletion, persistent layer ids differ from file row numbers. An attribute-only diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index ff48277804..05e910c4ed 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -77,9 +77,6 @@ pub struct GeoJsonSource { /// The coordinate system the file declares (its `crs`), converting what's read to /// longitude/latitude. reproject: Reproject, - /// The features (by place) the declared system can't convert: in no read, and not counted. - /// Sorted. - failed: Vec, /// Features left out when it was opened for geometry that couldn't be read. unreadable: usize, } @@ -231,26 +228,17 @@ impl GeoJsonSource { notes.push(format!("{} features had unreadable geometry", scan.skipped)); } let reproject = Reproject::known(declared_crs(&rest, &mut notes)?); - // The declaration may come after the features, so only now can each be tried: those the - // declared system can't convert are found here (and left out of every read, the count, - // the extent and the geometry type), as they are when the file is read whole. - let mut failed = Vec::new(); + // The declaration may come after the features, so only now can each be tried: those with + // a place the declared system can't give in longitude/latitude are counted and said, and + // kept as the file holds them (they don't draw), as when the file is read whole; the + // extent in longitude/latitude is that of the rest. let mut extent = scan.extent; if let Some(t) = reproject.transformer() { + let crs = reproject.crs(); file.rewind()?; let pass = convert_pass(&mut file, &scan.places, t)?; extent = pass.extent; - for (kept, lost) in scan.kinds.iter_mut().zip(pass.dropped) { - *kept = kept.saturating_sub(lost); - } - if !pass.failed.is_empty() { - notes.push(format!( - "{} features couldn't be converted from {} to longitude/latitude and were skipped", - pass.failed.len(), - reproject.label() - )); - } - failed = pass.failed; + notes.extend(crate::io::kept_unplaced_note("", "features", pass.unplaced, pass.placed == 0, crs)); } else { // Only coordinates read as they are can be longitude/latitude with the two swapped; // a declared system's features were converted above, and those that don't fit left out. @@ -269,20 +257,19 @@ impl GeoJsonSource { geometry_type, fields: scan.schema.fields(), extent, - count: Some((scan.places.len() - failed.len()) as u64), + count: Some(scan.places.len() as u64), crs: reproject.label(), indexed: false, notes: notes.into(), zm_dropped: false, }; - // Features the declared system can't convert are left out, and so are their heights. - let zm = scan.zm.iter().filter(|i| failed.binary_search(i).is_err()).count() as u64; + let zm = scan.zm.len() as u64; if zm > 0 { info.drop_zm(Some(zm)); } let unreadable = scan.skipped; version.check(&file)?; - Ok(GeoJsonSource { info, path: path.to_path_buf(), version, places: scan.places, boxes: scan.boxes, reproject, failed, unreadable }) + Ok(GeoJsonSource { info, path: path.to_path_buf(), version, places: scan.places, boxes: scan.boxes, reproject, unreadable }) } /// The features a request matches, in file order: every one without an extent; otherwise @@ -303,7 +290,7 @@ impl GeoJsonSource { Some((true, _)) => false, Some((false, [x0, y0, x1, y1])) => b[0] <= x1 && b[2] >= x0 && b[1] <= y1 && b[3] >= y0, }; - (i as u32, in_box && self.failed.binary_search(&(i as u32)).is_err()) + (i as u32, in_box) }) } } @@ -325,12 +312,8 @@ impl FeatureSource for GeoJsonSource { self.reproject.crs() } - fn lost_to_crs(&self) -> bool { - !self.failed.is_empty() - } - fn skipped_at_open(&self) -> usize { - self.unreadable + self.failed.len() + self.unreadable } fn visits_extent_chunks(&self) -> bool { @@ -450,18 +433,21 @@ impl GeoJsonSource { let json = read_place(f, pos, buf, place).ok_or(())?; let geometry = geojson_geometry(&json).map_err(|_| ())?; // Kept as the file holds it, in its own system; its own box answers a request given in - // that system ([`Request::own`]), else its box in longitude/latitude. + // that system ([`Request::own`]), else its box in longitude/latitude. One without + // geometry, or with a place that can't be given in longitude/latitude, doesn't meet a + // box in longitude/latitude; a read with no box takes it. let own = self.reproject.own_box(req); - let placed = match (own, self.reproject.transformer(), &geometry) { - (Some(_), _, g) => g.as_ref().map(crate::Geometry::extent), - (None, Some(t), Some(g)) => Some(lonlat_box(g, t).ok_or(())?), - (None, _, g) => g.as_ref().map(crate::Geometry::extent), - }; - // One without geometry doesn't match an extent. - let outside = match (&placed, own.or(req.extent)) { - (_, None) => false, - (None, Some(_)) => true, - (Some(e), Some(r)) => !e.intersects(&r), + let outside = match (own, req.extent) { + (Some(r), _) => geometry.as_ref().is_none_or(|g| !g.extent().intersects(&r)), + (None, None) => false, + (None, Some(r)) => { + let placed = match (self.reproject.transformer(), &geometry) { + (Some(t), Some(g)) => lonlat_box(g, t), + (None, g) => g.as_ref().map(crate::Geometry::extent), + (_, None) => None, + }; + placed.is_none_or(|e| !e.intersects(&r)) + } }; if outside || !wanted() { return Ok(None); @@ -498,11 +484,11 @@ fn read_place(f: &mut BufReader, pos: &mut u64, buf: &mut Vec< /// What a pass over a file's features converts to longitude/latitude finds. struct Pass { - /// Places of the features the transformer can't convert (see [`geometry_to_lonlat`]), sorted. - failed: Vec, - /// Points, lines and polygons among them (as [`Scan::kinds`]). - dropped: [usize; 3], - /// The extent, in longitude/latitude, of those it can. + /// Features with geometry the transformer can't give in longitude/latitude (see + /// [`geometry_to_lonlat`]), and those it can. + unplaced: usize, + placed: usize, + /// The extent, in longitude/latitude, of every place that converts. extent: Extent, } @@ -510,7 +496,7 @@ struct Pass { fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> Result { let mut f = BufReader::with_capacity(BUFFER, file); let (mut pos, mut buf) = (0u64, Vec::new()); - let mut pass = Pass { failed: Vec::new(), dropped: [0; 3], extent: Extent::EMPTY }; + let mut pass = Pass { unplaced: 0, placed: 0, extent: Extent::EMPTY }; // Counted as a step of its own, a feature at a time every so many. crate::progress::begin(places.len()); for (i, place) in places.iter().enumerate() { @@ -521,14 +507,16 @@ fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transforme if let Some(json) = read_place(&mut f, &mut pos, &mut buf, place) && let Ok(Some(g)) = geojson_geometry(&json) { - match geometry_to_lonlat(&g, t) { - Some(g) => pass.extent = pass.extent.union(&g.extent()), - None => { - pass.failed.push(i as u32); - if let Some(slot) = pass.dropped.get_mut(kind_slot(g.kind())) { - *slot += 1; - } + // The extent as a layer read whole gives it ([`crate::Dataset::lonlat_extent`]): + // every place that converts to a finite one, beyond longitude/latitude too. + g.for_each_coord(|c| { + if let Some(l) = t.to_lonlat(c).filter(|l| l.is_finite()) { + pass.extent.expand(l); } + }); + match geometry_to_lonlat(&g, t) { + Some(_) => pass.placed += 1, + None => pass.unplaced += 1, } } } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 665e7d1807..0e7a100f66 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -2779,8 +2779,8 @@ fn geojson_paths(file: &str, text: &str) -> (Dataset, Vec, String) { } let src = geojson::GeoJsonSource::open_with(&p, "x", crate::io::BYTES_FLOOR).unwrap(); // 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.texts().map(str::to_string).collect(), src.info().crs.clone()) + // declared system, as the file does. One with no place there is without geometry in this copy. + (whole.in_lonlat_leaving_out().unwrap().0.into_owned(), report.messages.texts().map(str::to_string).collect(), src.info().crs.clone()) } fn in_arnhem(e: &Extent) -> bool { @@ -2941,8 +2941,9 @@ fn geojson_crs_is_read_only_from_the_feature_collection() { #[test] fn geojson_features_that_cant_be_converted_are_skipped_and_counted() { // A coordinate the declared system can't convert (UTM 1e9 m east), or converts to beyond - // longitude/latitude (Web Mercator 1e9 m east is longitude 8983°): the feature is dropped, and - // its height with it (no Z notice for the 2D features kept). + // longitude/latitude (Web Mercator 1e9 m east is longitude 8983°): the feature is kept as the + // file holds it, said, and doesn't draw; nothing was lost, so a projection can still be + // defined (#2032 C2f-4b). for (crs, good, bad) in [("EPSG:32617", "[500000,4649776]", "[1e9,0,30]"), ("EPSG:3857", "[1000000,6000000]", "[1e9,0,30]")] { let text = format!( r#"{{"type":"FeatureCollection","crs":{},"features":[ @@ -2952,13 +2953,15 @@ fn geojson_features_that_cant_be_converted_are_skipped_and_counted() { named(crs) ); let (ds, messages, info_crs) = geojson_paths("far.geojson", &text); - assert_eq!(ds.features.len(), 2, "{crs}"); - assert_eq!(ds.features.iter().map(|f| f.id).collect::>(), [1, 3], "{crs}: ids are the features' places in the file"); - assert_eq!(messages.len(), 1, "{crs}: {messages:?}"); - assert!(messages[0].contains(&format!("1 features couldn't be converted from {crs}")), "{}", messages[0]); + assert_eq!(ds.features.iter().map(|f| f.id).collect::>(), [1, 2, 3], "{crs}: ids are the features' places in the file"); + assert!( + messages.iter().any(|m| m.contains(&format!( + "1 features have a place in {crs} that can't be given in longitude/latitude: they are kept as the file holds them" + ))), + "{crs}: {messages:?}" + ); assert_eq!(info_crs, crs); - assert!(ds.crs_incomplete, "{crs}: a projection can't be defined again over lost features"); - assert!(!ds.zm_dropped, "{crs}"); + assert!(!ds.crs_incomplete, "{crs}: nothing was lost"); let Some(Geometry::Point(c)) = ds.features.first().and_then(|f| f.geometry.clone()) else { panic!("a point") }; assert!(c.x.abs() < 180.0 && c.y.abs() < 90.0, "{crs}: {c:?}"); if crs == "EPSG:32617" { @@ -2977,36 +2980,48 @@ fn merc_collection(features: &[&str]) -> String { } #[test] -fn geojson_dropped_features_do_not_set_the_geometry_type() { - // Two points that can't be placed and one polygon that can: a polygon layer, as read whole. +fn geojson_kept_unplaced_features_set_the_geometry_type() { + // Features kept with no place in longitude/latitude are the file's: they count toward its + // geometry type, the same both ways. let (ds, _, _) = geojson_paths("kinds.geojson", &merc_collection(&[MERC_BAD, MERC_POLY, MERC_BAD])); - assert_eq!(ds.geometry_type, GeometryType::Polygon); - assert_eq!(ds.features.len(), 1); - // Nothing that can be placed: no geometry type at all, both ways. + assert_eq!(ds.geometry_type, GeometryType::Point); + assert_eq!(ds.features.len(), 3); + // Nothing that can be placed: kept, said as a system that doesn't seem to match, and a + // projection can still be defined. let (ds, messages, _) = geojson_paths("none.geojson", &merc_collection(&[MERC_BAD, MERC_BAD])); - assert_eq!(ds.geometry_type, GeometryType::None); - assert!(ds.features.is_empty() && ds.crs_incomplete); + assert_eq!(ds.geometry_type, GeometryType::Point); + assert!(ds.features.len() == 2 && !ds.crs_incomplete); assert_eq!(messages.len(), 1, "{messages:?}"); + assert!( + messages[0].contains("none of the features has a place in longitude/latitude from EPSG:3857") + && messages[0].contains("Define Projection"), + "{}", + messages[0] + ); } #[test] -fn geojson_sampling_skips_dropped_features() { - // Unplaceable features at every other place must not use up the sample: a read asking for - // two of the three placeable ones gets two, and says it matched three. +fn geojson_reads_in_longitude_latitude_leave_out_unplaced_features() { + // Unplaceable features at every other place are in a whole read; a read of a box in + // longitude/latitude leaves them out, as they meet none. let text = merc_collection(&[MERC_BAD, MERC_OK, MERC_BAD, MERC_OK, MERC_BAD, MERC_OK]); let p = dir().join("geojson-crs").join("alternating.geojson"); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(&p, &text).unwrap(); for in_memory in [crate::io::BYTES_FLOOR, 0] { let src = geojson::GeoJsonSource::open_with(&p, "x", in_memory).unwrap(); - assert_eq!(src.info().count, Some(3)); + assert_eq!(src.info().count, Some(6)); let all = src.read(&Request { extent: None, limit: 100, own: None }).unwrap(); - assert_eq!((all.features.len(), all.matched, all.skipped, all.complete), (3, 3, 0, true)); - let some = src.read(&Request { extent: None, limit: 2, own: None }).unwrap(); - assert_eq!((some.features.len(), some.matched, some.skipped, some.complete), (2, 3, 0, false)); - assert!(some.features.iter().all(|f| f.geometry.is_some())); - let ids: Vec = all.features.iter().map(|f| f.id).collect(); + assert_eq!((all.features.len(), all.matched, all.skipped, all.complete), (6, 6, 0, true)); + // Around the placeable ones (about 9°E, 47°N): those alone, and a sample of two of them + // says it matched three. + let around = Some(Extent { min_x: 8.0, min_y: 46.0, max_x: 10.0, max_y: 48.0 }); + let near = src.read(&Request { extent: around, limit: 100, own: None }).unwrap(); + assert_eq!((near.features.len(), near.matched, near.skipped, near.complete), (3, 3, 0, true)); + let ids: Vec = near.features.iter().map(|f| f.id).collect(); assert_eq!(ids, [2, 4, 6]); + let some = src.read(&Request { extent: around, limit: 2, own: None }).unwrap(); + assert_eq!((some.features.len(), some.matched, some.skipped, some.complete), (2, 3, 0, false)); } } diff --git a/crates/data/src/unplaced_out_tests.rs b/crates/data/src/unplaced_out_tests.rs index 9cbf2d3620..4c078475d7 100644 --- a/crates/data/src/unplaced_out_tests.rs +++ b/crates/data/src/unplaced_out_tests.rs @@ -147,3 +147,49 @@ fn an_infinite_coordinate_stays_as_it_is_and_isnt_placed() { assert_eq!(parts[0][2].y, f64::INFINITY); assert!(parts[0][0].is_finite() && parts[0][3].is_finite()); } + +/// A Shapefile whose `.prj` gives a shape no place in longitude/latitude keeps it as the file holds +/// it, says so, and leaves the layer whole (#2032 C2f-4b): nothing is lost, so Define Projection +/// stays open. When no shape has one, its system is said not to fit. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_shapefile_keeps_a_shape_with_no_longitude_latitude_place() { + let d = dir("kept-shp"); + for (far_only, file) in [(false, "some.shp"), (true, "all.shp")] { + let mut raw = Dataset::new("points", crate::GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + if !far_only { + raw.push(Some(Geometry::Point(Coord::new(451_000.0, 5_411_000.0))), vec![Value::Text("paris".into())]); + } + raw.push(Some(Geometry::Point(Coord::new(1e12, 1e12))), vec![Value::Text("far".into())]); + let path = d.join(file); + crate::io::write_path(&raw, &path).unwrap(); + std::fs::write(path.with_extension("prj"), crate::raster::wkt::to_wkt(utm31()).unwrap()).unwrap(); + let (ds, report) = crate::io::read_path(&path).unwrap(); + assert_eq!(ds.coord_crs(), utm31()); + assert!(!ds.crs_incomplete); + let far = ds.features.rows().last().and_then(|r| r.geometry().cloned()); + assert_eq!(far, Some(Geometry::Point(Coord::new(1e12, 1e12))), "kept as the file holds it"); + let said: Vec<&str> = report.messages.texts().collect(); + let expected = if far_only { + "none of the shapes has a place in longitude/latitude from EPSG:32631" + } else { + "1 shapes have a place in EPSG:32631" + }; + assert!(said.iter().any(|m| m.contains(expected) && m.contains("kept as the file holds them")), "{said:?}"); + assert_eq!(ds.in_lonlat_leaving_out().unwrap().1, 1); + } +} + +/// A delimited text file's rows with no place in longitude/latitude from the system given are +/// kept as the file holds them, and said (#2032 C2f-4b). +#[test] +fn a_csv_keeps_a_row_with_no_longitude_latitude_place() { + let text = "name,x,y\nparis,451000,5411000\nfar,1e12,1e12\n"; + let opts = crate::io::CsvOptions { x: Some("x".into()), y: Some("y".into()), crs: Some(utm31()), ..Default::default() }; + let (ds, report) = crate::io::read_csv_with(text, "pts", &opts).unwrap(); + assert_eq!(ds.features.len(), 2); + assert_eq!(ds.features.rows().last().and_then(|r| r.geometry().cloned()), Some(Geometry::Point(Coord::new(1e12, 1e12)))); + let said: Vec<&str> = report.messages.texts().collect(); + assert!(said.iter().any(|m| m.contains("1 rows have a place in EPSG:32631") && m.contains("kept as the file holds them")), "{said:?}"); + assert_eq!(report.skipped, 0); +} diff --git a/crates/engine/src/tests/unplaced_gp.rs b/crates/engine/src/tests/unplaced_gp.rs index 5b75569b45..4eba9931c5 100644 --- a/crates/engine/src/tests/unplaced_gp.rs +++ b/crates/engine/src/tests/unplaced_gp.rs @@ -250,10 +250,13 @@ fn a_search_area_file_leaves_out_what_it_cant_place() { rustgis_data::io::write_path(&ds, &path).unwrap(); std::fs::write(path.with_extension("prj"), rustgis_data::raster::wkt::to_wkt(robinson()).unwrap()).unwrap(); let loaded = crate::cmd::stac_area::load_file(path.to_str().unwrap()).unwrap(); - // Said by the reader while files are read into longitude/latitude (C2f-4b-2 keeps such a - // feature, and then the search area says it); a clean file says nothing of it. + // The reader keeps the far square as the file holds it and says so (#2032 C2f-4b), and the + // search area leaves it out; a clean file says nothing of it. let said = loaded.notices.iter().any(|n| n.contains("longitude/latitude")); assert_eq!(said, far, "{:?}", loaded.notices); + if far { + assert!(loaded.notices.iter().any(|n| n.contains("kept as the file holds them")), "{:?}", loaded.notices); + } } std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/engine/tests/integration/define_projection.rs b/crates/engine/tests/integration/define_projection.rs index 8b56587a86..9cec14c2c3 100644 --- a/crates/engine/tests/integration/define_projection.rs +++ b/crates/engine/tests/integration/define_projection.rs @@ -84,22 +84,22 @@ fn wrong_prj_can_be_replaced_without_reprojecting_native_numbers() { paris(&s.map().layer(id).unwrap().dataset); } +/// A `.prj` that gives the shapes no place in longitude/latitude keeps them as the file holds +/// them (#2032 C2f-4b), so Define Projection places them; an override on import does as well. #[test] -fn zip_override_precedes_wrong_prj_and_missing_geometry_requires_reimport() { +fn zip_override_precedes_wrong_prj_and_define_projection_places_what_it_kept() { // This nonzero datum shift rejects projected numbers mislabelled as geographic. let wrong = Crs::parse("EPSG:4277").unwrap(); - assert!(wrong.transformer().unwrap().to_lonlat(point(&native())).is_none(), "fixture must lose geometry with its wrong CRS"); + assert!(wrong.transformer().unwrap().to_lonlat(point(&native())).is_none(), "fixture must have no place with its wrong CRS"); let bytes = zip(Some(wrong)); let mut s = Session::new(Project::default()); let id = upload(&mut s, &bytes, None); - assert!(s.map().layer(id).unwrap().dataset.crs_incomplete); - let before = s.map().layer(id).unwrap().dataset.clone(); - let error = s.run("layer.defineProjection", &json!({"layer": id, "crs": "EPSG:32631"})).unwrap_err(); - assert!(error.contains("import the original file"), "{error}"); - assert_eq!(s.map().layer(id).unwrap().dataset, before); - let saved = s.project.saved_text(None).unwrap().0; - let restored = Project::from_json(&saved).unwrap(); - assert!(restored.maps[0].layers[0].dataset.crs_incomplete); + let ds = &s.map().layer(id).unwrap().dataset; + assert!(!ds.crs_incomplete); + let stored = ds.features.row(0).and_then(|r| r.geometry().cloned()); + assert_eq!(stored, Some(Geometry::Point(Coord::new(451_219.33, 5_411_550.20))), "kept as the file holds it"); + s.run("layer.defineProjection", &json!({"layer": id, "crs": "EPSG:32631"})).unwrap(); + paris(&s.map().layer(id).unwrap().dataset); let repaired = upload(&mut s, &bytes, Some("EPSG:32631")); paris(&s.map().layer(repaired).unwrap().dataset); assert!(!s.map().layer(repaired).unwrap().dataset.crs_incomplete); diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index cb0962bf07..3705b77ad9 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -1067,14 +1067,19 @@ fn load( 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)); + // A feature with a place that can't be given in longitude/latitude + // is kept as read, and counted: it doesn't draw (#2032 C2f-4b). Each + // place is converted to be checked; the layer keeps its own. + let lost = ds + .features + .rows() + .filter_map(|r| r.geometry()) + .filter(|g| Dataset::converted_to_lonlat(&to, g).is_none()) + .count(); if lost > 0 { messages.push(format!( - "{layer_name}: {lost} features couldn't be converted to longitude/latitude and have no geometry" + "{layer_name}: {lost} features have a place in {} that can't be given in longitude/latitude: they are kept as read, but don't draw", + job.crs.label() )); } } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 8fb6e945c8..72d622894b 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 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. | +| 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 kept as the file holds it and counted in a notice; it doesn't draw (see [Places with no longitude/latitude](#places-with-no-longitudelatitude)). 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. | @@ -787,6 +787,19 @@ south: an export in it writes a latitude beyond (Antarctica near the South Pole, one) at 85.05°, and says how many of the vertices the file holds it moved; a layer read in place and written a chunk at a time is counted as it's written. +### Places with no longitude/latitude + +A feature can have a place its file's coordinate system can't give in longitude/latitude: one far +past where that system reaches (a UTM easting of a billion metres, say), or every feature of a file +whose `.prj` or declared system doesn't fit its numbers. Shapefile, GeoJSON (with a `crs`), CSV and +other delimited text, File Geodatabase, ArcGIS feature service answers, MapInfo, DXF, LandXML, +CityJSON and CityGML, GML and GeoLibre projects keep such a feature as the file holds it, and one +notice counts them; when none of a file's features has such a place, the notice says its system +doesn't seem to fit, and Define Projection can set the one that does. Such a feature doesn't draw +(the map says how many it leaves out), and each step that needs longitude/latitude (an export in +WGS 84, a tool, an edit) leaves it out or refuses it and says so; written back in its own system, +it is exact. + Coordinate systems of other bodies than the Earth (Mars, the Moon and the rest of the IAU's `IAU_2015` codes, or any datum whose ellipsoid isn't the Earth's) aren't read as such yet: every layer is placed on the Earth. An EPSG or Esri code that comes with another body's WKT (in the WKT @@ -837,8 +850,10 @@ 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. -If the incorrect `.prj` prevented geometry from being read, Define Projection cannot restore -it. Choose **Import Original File…** in the dialog, or search for **Import Shapefile with +A feature whose `.prj` (or other declared system) gave it no place in longitude/latitude is kept +as the file holds it, so Define Projection places it once the right system is given. If a +reader still dropped geometry (a LiDAR file, or a layer read in place through a GeoPackage, +FlatGeobuf, GeoParquet, GDAL or DuckDB), Define Projection cannot restore it. Choose **Import Original File…** in the dialog, or search for **Import Shapefile with Projection…**. Enter the correct CRS before choosing the file. In the browser, pick the `.shp` and `.dbf` together, with any sidecars, or choose a ZIP. The override replaces the `.prj` before any conversion and applies to every Shapefile in a ZIP; other formats keep their own CRS. From cbdcf0b875c66abda77e6375f18805e71706eb66 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 10:11:34 +0100 Subject: [PATCH 2/9] Review: streamed sources keep such features too; a place is unplaced only when it doesn't convert to a finite one, one beyond longitude/latitude said as out of place; CSV with a given system; wording (#2032 C2f-4b-2) --- crates/data/src/cityjson/tests.rs | 24 ++++--- crates/data/src/citymodel.rs | 6 +- crates/data/src/dxf.rs | 2 +- crates/data/src/esripbf.rs | 16 ++++- crates/data/src/esripbf/tests.rs | 7 +- crates/data/src/io.rs | 90 ++++++++++++++----------- crates/data/src/landxml.rs | 2 +- crates/data/src/mapinfo.rs | 2 +- crates/data/src/publish.rs | 10 +-- crates/data/src/source/geojson.rs | 25 ++++--- crates/data/src/source/mod.rs | 64 +++++++++++++++--- crates/data/src/source/own_box_tests.rs | 7 +- crates/data/src/source/tests.rs | 25 +++---- crates/data/src/unplaced_out_tests.rs | 36 +++++++++- docs/user-guide/data-formats.md | 20 +++--- 15 files changed, 228 insertions(+), 108 deletions(-) diff --git a/crates/data/src/cityjson/tests.rs b/crates/data/src/cityjson/tests.rs index e1d4c19471..1439e1daa1 100644 --- a/crates/data/src/cityjson/tests.rs +++ b/crates/data/src/cityjson/tests.rs @@ -636,19 +636,23 @@ fn objects_that_cant_be_converted_are_kept_and_said() { let far = [[1e12, 0.0, 0.0], [1e12 + 1000.0, 0.0, 0.0], [1e12 + 1000.0, 1000.0, 0.0]]; let vertices: Vec<[f64; 3]> = near.iter().chain(&far).copied().collect(); let bytes = doc(json!(vertices), json!({"a": triangle(0), "b": triangle(3)})); - let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); + let out = read("m.city.json", &bytes, Some(Crs::Epsg(32631))).unwrap(); assert!(!out[0].0.crs_incomplete); assert!(out[0].0.features.rows().all(|r| r.geometry().is_some()), "both kept"); - assert!(says(&out, "1 city objects have a place in EPSG:3857 that can't be given in longitude/latitude"), "{:?}", messages_of(&out)); + assert!( + says(&out, "one of the city objects has a place in EPSG:32631 that can't be given in longitude/latitude"), + "{:?}", + messages_of(&out) + ); let bytes = doc(json!(vertices), json!({"a": triangle(0)})); - let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); + let out = read("m.city.json", &bytes, Some(Crs::Epsg(32631))).unwrap(); assert!(!out[0].0.crs_incomplete); // Only that the system given goes over the one the file names (`doc`'s EPSG:4326). - assert_eq!(messages_of(&out), vec!["the file names EPSG:4326, and is read in EPSG:3857, the coordinate system given".to_string()]); + assert_eq!(messages_of(&out), vec!["the file names EPSG:4326, and is read in EPSG:32631, the coordinate system given".to_string()]); let bytes = doc(json!(vertices), json!({"b": triangle(3)})); - let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); + let out = read("m.city.json", &bytes, Some(Crs::Epsg(32631))).unwrap(); assert!(out[0].0.features.rows().all(|r| r.geometry().is_some())); - assert!(says(&out, "none of the city objects has a place in longitude/latitude from EPSG:3857"), "{:?}", messages_of(&out)); + assert!(says(&out, "none of the city objects has a place in longitude/latitude from EPSG:32631"), "{:?}", messages_of(&out)); } /// An object is counted once in a notice, however many of its geometry families it loses. @@ -666,8 +670,12 @@ fn an_object_losing_several_families_is_counted_once() { "b": {"type": "LandUse", "geometry": [surface(3), line]}, }), ); - let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); - assert!(says(&out, "1 city objects have a place in EPSG:3857 that can't be given in longitude/latitude"), "{:?}", messages_of(&out)); + let out = read("m.city.json", &bytes, Some(Crs::Epsg(32631))).unwrap(); + assert!( + says(&out, "one of the city objects has a place in EPSG:32631 that can't be given in longitude/latitude"), + "{:?}", + messages_of(&out) + ); } /// A byte order mark doesn't hide a model, and a file named only `.city.json` still names its layer. diff --git a/crates/data/src/citymodel.rs b/crates/data/src/citymodel.rs index 9353df4663..0580575e6e 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -573,9 +573,9 @@ pub(crate) fn finish( let mut objects = HashSet::new(); for row in &mut rows { // Kept as the file holds it, in its system; marked, as it doesn't draw, when it has no - // place in longitude/latitude (as `geometry_to_lonlat` would give it). + // place in longitude/latitude. if let Some(g) = &row.geometry - && crate::io::lonlat_box(g, &to_lonlat).is_none() + && !crate::io::places_in_lonlat(g, &to_lonlat) { (row.unconverted, row.draws) = (true, false); objects.insert(row.object); @@ -1154,7 +1154,7 @@ pub(crate) fn messages(c: &Counts) -> Vec { ); say(c.nested_instances, format!("{} implicit geometries inside a prototype aren't placed", c.nested_instances)); say(c.tin_reliefs, format!("{} TINRelief objects aren't drawn and are left out", c.tin_reliefs)); - if let Some(note) = c.crs.and_then(|crs| crate::io::kept_unplaced_note("", "city objects", c.unconverted, c.all_unconverted, crs)) { + if let Some(note) = c.crs.and_then(|crs| crate::io::kept_unplaced_note("city objects", c.unconverted, c.all_unconverted, crs)) { say(c.unconverted, note); } say( diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 278f24d4e6..1d4f562a2c 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1713,7 +1713,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 { out.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(self.with_zm as u64)))); } @@ -353,7 +359,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result let shape = Shape { kind: shape_kind, transform: &transform, has_z, has_m }; let mut ds = Dataset::new(name, GeometryType::None, fields); let width = ds.fields.len(); - let (mut any_geometry, mut with_zm, mut unprojected) = (false, 0usize, 0usize); + let (mut any_geometry, mut with_zm, mut unprojected, mut beyond) = (false, 0usize, 0usize, false); for (n, bytes) in features.into_iter().enumerate() { let (values, geometry) = feature(bytes, &columns, width, &shape, &mut tally).map_err(|e| match e { DataError::Format(m) => invalid(format!("feature {}: {}", n + 1, m.strip_prefix(PREFIX).unwrap_or(&m))), @@ -362,9 +368,12 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> 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; counted when it has no place in - // longitude/latitude (as `geometry_to_lonlat` would give it). + // longitude/latitude. if let (Some(g), Some(t)) = (&geometry, &to_lonlat) { - unprojected += usize::from(crate::io::lonlat_box(g, t).is_none()); + match crate::io::places_lonlat_extent(g, t) { + Some(e) => beyond |= e.beyond_lonlat(), + None => unprojected += 1, + } } ds.push_next(geometry, values); } @@ -384,6 +393,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result not_utf8: tally.not_utf8, flat_rings: tally.flat_rings, unprojected, + beyond, with_zm, }; ds.zm_dropped = with_zm > 0; diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 34a334ce46..210b031366 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -255,14 +255,15 @@ fn coordinates_past_longitude_latitude_are_kept_and_the_layer_says_so() { ]); let (ds, report) = read(&bytes, "t").unwrap(); assert!(ds.features[0].geometry.is_some()); - // Kept as the answer gives it, and not drawn (#2032 C2f-4b): nothing was lost, so a - // projection can still be defined. + // Kept as the answer gives it (#2032 C2f-4b), and said: it converts beyond + // longitude/latitude, so it draws out of place. Nothing was lost, so a projection can still be + // defined. assert_eq!(ds.features[1].geometry, Some(Geometry::Point(c(1e9, 0.0)))); assert!(!ds.crs_incomplete); assert_eq!( report.messages, [ - "1 features have a place that can't be given in longitude/latitude (coordinates outside their coordinate system): they are kept as the answer gives them, but don't draw" + "coordinates are not longitude/latitude once converted from the answer's coordinate system; it may not match them, and they may draw out of place" ] ); } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index f3b675cc90..53e096021a 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1644,21 +1644,10 @@ pub(crate) fn is_epsg_or_crs84_name(name: &str) -> bool { up == "CRS84" || up == "OGC:CRS84" || up.strip_prefix("OGC:").and_then(|rest| tail(rest, ':')).is_some_and(|c| c == "CRS84") } -/// 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). -#[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))); - out.for_each_coord(|c: Coord| ok &= c.is_finite() && c.x.abs() <= 180.5 && c.y.abs() <= 90.5); - 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. +/// ([`Dataset::held_in`]), either way, and counts those that don't ([`kept_unplaced_note`]). +/// 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() } @@ -1691,28 +1680,41 @@ pub(crate) fn lonlat_box(g: &Geometry, t: &crate::raster::Transformer) -> Option } /// What a reader says of the `n` of its `what` (features, shapes, rows) it keeps as the file holds -/// them, held in `crs`, though a place of theirs can't be given in longitude/latitude (or comes -/// out beyond it): they don't draw (the map says so too), and every other step that needs -/// longitude/latitude leaves them out and says so (#2032 C2f-4b). `all` when none of the file's -/// has a place there: then its system doesn't seem to match its coordinates, and Define -/// Projection can set the one that does, as nothing was lost. `None` for none. -pub(crate) fn kept_unplaced_note(name: &str, what: &str, n: usize, all: bool, crs: Crs) -> Option { - let name = if name.is_empty() { String::new() } else { format!("{name}: ") }; +/// them, held in `crs`, though a place of theirs can't be given in longitude/latitude: they don't +/// draw (the map says so too), and every other step that needs longitude/latitude leaves them out +/// and says so (#2032 C2f-4b). `all` when none of the file's has a place there: then its system +/// doesn't seem to match its coordinates, and Define Projection can set the one that does, as +/// nothing was lost. `None` for none. +pub(crate) fn kept_unplaced_note(what: &str, n: usize, all: bool, crs: Crs) -> Option { (n > 0).then(|| { if all { format!( - "{name}none of the {what} has a place in longitude/latitude from {}: it doesn't seem to be their coordinate system. They are kept as the file holds them, but don't draw; Define Projection can set the right one", + "none of the {what} has a place in longitude/latitude from {}: it doesn't seem to be their coordinate system. They are kept as the file holds them, but don't draw; Define Projection can set the right one", crs.label() ) } else { - format!( - "{name}{n} {what} have a place in {} that can't be given in longitude/latitude: they are kept as the file holds them, but don't draw", - crs.label() - ) + let system = crs.label(); + if n == 1 { + format!("one of the {what} has a place in {system} that can't be given in longitude/latitude: it is kept as the file holds it, but doesn't draw") + } else { + format!("{n} {what} have a place in {system} that can't be given in longitude/latitude: they are kept as the file holds them, but don't draw") + } } }) } +/// What a reader says when the places of its features that do convert from `crs` come out beyond +/// longitude/latitude (`placed`, their box there): the system may not match the coordinates, +/// and they may draw out of place. +pub(crate) fn beyond_lonlat_note(placed: &rustgis_geom::Extent, crs: Crs) -> Option { + placed.beyond_lonlat().then(|| { + format!( + "coordinates are not longitude/latitude once converted from {}; it may not match them, and they may draw out of place", + crs.label() + ) + }) +} + /// 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). @@ -1955,18 +1957,22 @@ impl Collector { let declared = declared_crs(root, &mut said)?; report.messages.extend(said); let (mut unconverted, mut placed) = (0usize, 0usize); + let mut placed_extent = rustgis_geom::Extent::EMPTY; // Only features kept count toward the heights dropped. let mut zm = 0usize; // Features kept, as longitude/latitude, with a latitude past the poles. let mut swapped = 0usize; for (n, (geom, values, had_z)) in self.features.into_iter().enumerate() { // Kept as the file holds it, in its declared system, and counted when it has no place - // in longitude/latitude (as [`geometry_to_lonlat`] would give it), as when the file is - // read in place. + // in longitude/latitude ([`places_in_lonlat`]), as when the file is read in place. if let (Some((_, t)), Some(g)) = (&declared, &geom) { - let has = lonlat_box(g, t).is_some(); - placed += usize::from(has); - unconverted += usize::from(!has); + match places_lonlat_extent(g, t) { + Some(e) => { + placed += 1; + placed_extent = placed_extent.union(&e); + } + None => unconverted += 1, + } } let mut attrs = vec![Value::Null; ds.fields.len()]; for (i, v) in values { @@ -1983,7 +1989,8 @@ impl Collector { if let Some((crs, _)) = &declared { ds.crs = Some(*crs); ds.held_in = *crs; - report.messages.extend(kept_unplaced_note("", "features", unconverted, placed == 0, *crs)); + report.messages.extend(kept_unplaced_note("features", unconverted, placed == 0, *crs)); + report.messages.extend(beyond_lonlat_note(&placed_extent, *crs)); } report.messages.extend(swapped_latitude_note(swapped)); // Last, as a source read in place notes it. @@ -2985,15 +2992,22 @@ pub(crate) fn read_rows( // Kept as the file holds them, in its system; counted where they have no place in // longitude/latitude. ds.held_in = c; - let (mut lost, mut placed) = (0usize, 0usize); + let (mut lost, mut placed, mut placed_extent) = (0usize, 0usize, rustgis_geom::Extent::EMPTY); for g in ds.features.iter().filter_map(|f| f.geometry.as_ref()) { - let has = places_in_lonlat(g, &t); - placed += usize::from(has); - lost += usize::from(!has); + match places_lonlat_extent(g, &t) { + Some(e) => { + placed += 1; + placed_extent = placed_extent.union(&e); + } + None => lost += 1, + } } - report.messages.extend(kept_unplaced_note("", "rows", lost, placed == 0, c)); + report.messages.extend(kept_unplaced_note("rows", lost, placed == 0, c)); + report.messages.extend(beyond_lonlat_note(&placed_extent, c)); } - let read_as_degrees = crs.is_none_or(Crs::is_geographic); + // Read as longitude/latitude as they are: no system given, or longitude/latitude itself. A + // row a given system can't place is said above, as kept. + let read_as_degrees = crs.is_none_or(|c| c == Crs::LonLat); let (mut outside, mut zero) = (0usize, 0usize); for f in &ds.features { crate::progress::check()?; @@ -4176,7 +4190,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio )); } if let Some(c) = ds.crs.filter(|_| to_lonlat.is_some()) { - report.messages.extend(kept_unplaced_note("", "shapes", unconverted, converted == 0, c)); + report.messages.extend(kept_unplaced_note("shapes", unconverted, converted == 0, c)); } Ok((ds, report)) } diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 6bc9c9d219..8062a877e9 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -244,7 +244,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result, name: &str) -> Result<(Dataset, ReadRe ds.push_next(g, attrs); } if let (Some(_), Some(c)) = (&t, crs) { - report.messages.extend(crate::io::kept_unplaced_note("", "objects", lost, placed == 0, c)); + report.messages.extend(crate::io::kept_unplaced_note("objects", lost, placed == 0, c)); } report.messages.extend(crate::source::null_text_note(&ds.fields, &null_text)); ds.geometry_type = crate::io::dominant_type(&ds); diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index d0230e6889..8959426099 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -426,16 +426,18 @@ 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. + // A native shape the read left without geometry (a coordinate that isn't a number; one with + // no place in longitude/latitude is kept, #2032 C2f-4b) 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 from the source projection when it was read, so its native geometry can't be matched safely; check the source projection and add the file again; nothing was written", + "source shape {} was read without its geometry (a coordinate that isn't a number), so its native geometry can't be matched safely; add the file again; nothing was written", i + 1 ))); } diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 05e910c4ed..0fe14466a2 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -13,8 +13,7 @@ use std::path::{Path, PathBuf}; 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, lonlat_box, - swapped_latitude_note, + FeatureSink, Schema, declared_crs, geojson_attrs, geojson_geometry, geojson_has_z, latitude_past_poles, swapped_latitude_note, }; use crate::{DataError, Feature, GeometryType, Result}; use rustgis_geom::Extent; @@ -238,7 +237,8 @@ impl GeoJsonSource { file.rewind()?; let pass = convert_pass(&mut file, &scan.places, t)?; extent = pass.extent; - notes.extend(crate::io::kept_unplaced_note("", "features", pass.unplaced, pass.placed == 0, crs)); + notes.extend(crate::io::kept_unplaced_note("features", pass.unplaced, pass.placed == 0, crs)); + notes.extend(crate::io::beyond_lonlat_note(&pass.placed_extent, crs)); } else { // Only coordinates read as they are can be longitude/latitude with the two swapped; // a declared system's features were converted above, and those that don't fit left out. @@ -316,6 +316,11 @@ impl FeatureSource for GeoJsonSource { self.unreadable } + /// Counted when it was opened, as a file read whole counts them. + fn says_unplaced_at_open(&self) -> bool { + true + } + fn visits_extent_chunks(&self) -> bool { true } @@ -442,7 +447,7 @@ impl GeoJsonSource { (None, None) => false, (None, Some(r)) => { let placed = match (self.reproject.transformer(), &geometry) { - (Some(t), Some(g)) => lonlat_box(g, t), + (Some(t), Some(g)) => crate::io::places_lonlat_extent(g, t), (None, g) => g.as_ref().map(crate::Geometry::extent), (_, None) => None, }; @@ -485,9 +490,10 @@ fn read_place(f: &mut BufReader, pos: &mut u64, buf: &mut Vec< /// What a pass over a file's features converts to longitude/latitude finds. struct Pass { /// Features with geometry the transformer can't give in longitude/latitude (see - /// [`geometry_to_lonlat`]), and those it can. + /// [`crate::io::places_in_lonlat`]), and those it can, with their box there. unplaced: usize, placed: usize, + placed_extent: Extent, /// The extent, in longitude/latitude, of every place that converts. extent: Extent, } @@ -496,7 +502,7 @@ struct Pass { fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> Result { let mut f = BufReader::with_capacity(BUFFER, file); let (mut pos, mut buf) = (0u64, Vec::new()); - let mut pass = Pass { unplaced: 0, placed: 0, extent: Extent::EMPTY }; + let mut pass = Pass { unplaced: 0, placed: 0, placed_extent: Extent::EMPTY, extent: Extent::EMPTY }; // Counted as a step of its own, a feature at a time every so many. crate::progress::begin(places.len()); for (i, place) in places.iter().enumerate() { @@ -514,8 +520,11 @@ fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transforme pass.extent.expand(l); } }); - match geometry_to_lonlat(&g, t) { - Some(_) => pass.placed += 1, + match crate::io::places_lonlat_extent(&g, t) { + Some(e) => { + pass.placed += 1; + pass.placed_extent = pass.placed_extent.union(&e); + } None => pass.unplaced += 1, } } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 5515bf546e..3401531375 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -485,6 +485,12 @@ pub trait FeatureSource: Send + Sync { fn skipped_at_open(&self) -> usize { 0 } + /// Whether the source's notes ([`SourceInfo::notes`]) already count the features it keeps + /// with a place that can't be given in longitude/latitude, so a whole read doesn't count them + /// again. + fn says_unplaced_at_open(&self) -> bool { + false + } /// Reads the features a request asks for. A source read by its web address fails with /// [`remote::NEED`] until the bytes the read needs are fetched: run it with /// [`remote::drive`] (see [`FeatureSource::remote`]). @@ -748,6 +754,10 @@ impl FeatureSource for Fetching { self.0.skipped_at_open() } + fn says_unplaced_at_open(&self) -> bool { + self.0.says_unplaced_at_open() + } + fn read(&self, req: &Request) -> Result { read_blocking(&self.0, req) } @@ -776,9 +786,10 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, let Batch { features, skipped, unread_dates, rounded_dates, null_text, notes, not_utf8, .. } = batch; let mut ds = Dataset::new(info.name.clone(), info.geometry_type, info.fields.clone()); ds.crs = info.coordinate_system(); - // A streamed Shapefile skips unconvertible shapes rather than retaining empty geometry. - // Once materialized, it must still direct CRS repairs back to the original file. - ds.crs_incomplete = (info.format == "Shapefile" && skipped > 0) || src.lost_to_crs(); + // A shape with no place in longitude/latitude is kept as the source holds it + // ([`Reproject::place`]), so only a source that says it lost features to its system leaves + // Define Projection unable to place them. + ds.crs_incomplete = 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. @@ -803,6 +814,22 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, { ds.geometry_type = g.kind(); } + // The features kept with a place that can't be given in longitude/latitude, said once, as a + // file read whole says them; a source that said them when it was opened isn't counted again. + if !src.says_unplaced_at_open() + && let Ok(to) = ds.lonlat_conversion() + && !to.is_identity() + { + let (mut unplaced, mut placed) = (0usize, 0usize); + for g in ds.features.rows().filter_map(crate::RowRef::geometry) { + let has = Dataset::converted_to_lonlat(&to, g).is_some(); + placed += usize::from(has); + unplaced += usize::from(!has); + } + report.messages.extend( + crate::io::kept_unplaced_note("features", unplaced, placed == 0, ds.coord_crs()).map(|n| format!("{}: {n}", info.name)), + ); + } Ok((ds, report)) } @@ -1035,11 +1062,12 @@ impl Reproject { } /// A geometry as the file holds it, kept in the source's own coordinates, and whether it is - /// within `req`. Given the request's box in those coordinates ([`Request::own`]), its own box - /// is tested against it, converting nothing, so a geometry with no place in - /// longitude/latitude is kept too (`None` for one with a coordinate that isn't a number). - /// Otherwise as [`Reproject::read`]: `None` when a coordinate can't be converted to - /// longitude/latitude, and its box there tested against the extent. + /// within `req`; `None` for one with a coordinate that isn't a number, for the reader to + /// count. Given the request's box in those coordinates ([`Request::own`]), its own box is + /// tested against it, converting nothing. Otherwise its box in longitude/latitude + /// ([`Reproject::read`]) is tested against the extent; a geometry with a place that can't be + /// given there is kept as well (#2032 C2f-4b), within a read with no extent (a whole read) + /// and outside any extent. pub(crate) fn place(&self, g: Geometry, req: &Request) -> Option { if let Some(own) = self.own_box(req) { // A coordinate that isn't a number has no place here either: left out, as `read` @@ -1051,9 +1079,23 @@ impl Reproject { let inside = own == whole_plane() || g.extent().intersects(&own); return Some(Fitted { geometry: g, inside }); } - let Placed { geometry, lonlat } = self.read(g)?; - let inside = req.extent.is_none_or(|e| lonlat.intersects(&e)); - Some(Fitted { geometry, inside }) + if !g.is_finite() { + return None; + } + let Some(e) = req.extent else { return Some(Fitted { geometry: g, inside: true }) }; + let lonlat = match &self.t { + None => Some(g.extent()), + Some(t) => { + let mut box_ = Some(Extent::EMPTY); + g.for_each_coord(|c| match (t.to_lonlat(c).filter(|l| l.is_finite()), &mut box_) { + (Some(l), Some(b)) => b.expand(l), + _ => box_ = None, + }); + box_ + } + }; + let inside = lonlat.is_some_and(|l| l.intersects(&e)); + Some(Fitted { geometry: g, inside }) } /// The request's box in the source's own coordinates, when the asker gave it there diff --git a/crates/data/src/source/own_box_tests.rs b/crates/data/src/source/own_box_tests.rs index 960eb24918..8c353dcc43 100644 --- a/crates/data/src/source/own_box_tests.rs +++ b/crates/data/src/source/own_box_tests.rs @@ -125,8 +125,11 @@ fn a_box_in_its_own_system_is_tested_without_converting() { let r = Reproject::from_crs(utm31(), &mut notes); let (lonlat, utm) = around_paris(); let far = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(1e9, 5_411_500.0)]]); - // No place in longitude/latitude: left out as before without the box, kept with it. - assert!(r.place(far.clone(), &Request { extent: Some(lonlat), limit: 1, own: None }).is_none()); + // No place in longitude/latitude: kept as the file holds it (#2032 C2f-4b), outside a box + // there, within a whole read, and tested by its own box with one in its own system. + let kept = r.place(far.clone(), &Request { extent: Some(lonlat), limit: 1, own: None }).unwrap(); + assert!(!kept.inside && kept.geometry == far); + assert!(r.place(far.clone(), &Request { extent: None, limit: 1, own: None }).unwrap().inside); let fitted = r.place(far.clone(), &Request { extent: Some(lonlat), limit: 1, own: Some((utm31(), utm)) }).unwrap(); assert!(fitted.inside); assert_eq!(fitted.geometry, far); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 0e7a100f66..05af6ead3c 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -2954,12 +2954,14 @@ fn geojson_features_that_cant_be_converted_are_skipped_and_counted() { ); let (ds, messages, info_crs) = geojson_paths("far.geojson", &text); assert_eq!(ds.features.iter().map(|f| f.id).collect::>(), [1, 2, 3], "{crs}: ids are the features' places in the file"); - assert!( - messages.iter().any(|m| m.contains(&format!( - "1 features have a place in {crs} that can't be given in longitude/latitude: they are kept as the file holds them" - ))), - "{crs}: {messages:?}" - ); + // UTM can't convert it; Web Mercator converts it to beyond longitude/latitude, where it + // draws out of place, and says that. + let expected = if crs == "EPSG:32617" { + format!("one of the features has a place in {crs} that can't be given in longitude/latitude: it is kept as the file holds it") + } else { + format!("coordinates are not longitude/latitude once converted from {crs}") + }; + assert!(messages.iter().any(|m| m.contains(&expected)), "{crs}: {messages:?}"); assert_eq!(info_crs, crs); assert!(!ds.crs_incomplete, "{crs}: nothing was lost"); let Some(Geometry::Point(c)) = ds.features.first().and_then(|f| f.geometry.clone()) else { panic!("a point") }; @@ -2986,18 +2988,13 @@ fn geojson_kept_unplaced_features_set_the_geometry_type() { let (ds, _, _) = geojson_paths("kinds.geojson", &merc_collection(&[MERC_BAD, MERC_POLY, MERC_BAD])); assert_eq!(ds.geometry_type, GeometryType::Point); assert_eq!(ds.features.len(), 3); - // Nothing that can be placed: kept, said as a system that doesn't seem to match, and a - // projection can still be defined. + // Nothing in its place: kept, said as coordinates its system puts beyond longitude/latitude, + // and a projection can still be defined. let (ds, messages, _) = geojson_paths("none.geojson", &merc_collection(&[MERC_BAD, MERC_BAD])); assert_eq!(ds.geometry_type, GeometryType::Point); assert!(ds.features.len() == 2 && !ds.crs_incomplete); assert_eq!(messages.len(), 1, "{messages:?}"); - assert!( - messages[0].contains("none of the features has a place in longitude/latitude from EPSG:3857") - && messages[0].contains("Define Projection"), - "{}", - messages[0] - ); + assert!(messages[0].contains("coordinates are not longitude/latitude once converted from EPSG:3857"), "{}", messages[0]); } #[test] diff --git a/crates/data/src/unplaced_out_tests.rs b/crates/data/src/unplaced_out_tests.rs index 4c078475d7..5fde69ecac 100644 --- a/crates/data/src/unplaced_out_tests.rs +++ b/crates/data/src/unplaced_out_tests.rs @@ -173,9 +173,9 @@ fn a_shapefile_keeps_a_shape_with_no_longitude_latitude_place() { let expected = if far_only { "none of the shapes has a place in longitude/latitude from EPSG:32631" } else { - "1 shapes have a place in EPSG:32631" + "one of the shapes has a place in EPSG:32631" }; - assert!(said.iter().any(|m| m.contains(expected) && m.contains("kept as the file holds them")), "{said:?}"); + assert!(said.iter().any(|m| m.contains(expected) && m.contains("kept as the file holds")), "{said:?}"); assert_eq!(ds.in_lonlat_leaving_out().unwrap().1, 1); } } @@ -190,6 +190,36 @@ fn a_csv_keeps_a_row_with_no_longitude_latitude_place() { assert_eq!(ds.features.len(), 2); assert_eq!(ds.features.rows().last().and_then(|r| r.geometry().cloned()), Some(Geometry::Point(Coord::new(1e12, 1e12)))); let said: Vec<&str> = report.messages.texts().collect(); - assert!(said.iter().any(|m| m.contains("1 rows have a place in EPSG:32631") && m.contains("kept as the file holds them")), "{said:?}"); + assert!( + said.iter().any(|m| m.contains("one of the rows has a place in EPSG:32631") && m.contains("kept as the file holds it")), + "{said:?}" + ); assert_eq!(report.skipped, 0); } + +/// A Shapefile read in place keeps a shape with no place in longitude/latitude as the file holds +/// it, as one read whole does, and says so once (#2032 C2f-4b). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_streamed_shapefile_keeps_what_a_whole_read_keeps() { + crate::source::shp::use_temporary_index_dir(); + let d = dir("kept-streamed-shp"); + let mut raw = Dataset::new("points", crate::GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + raw.push(Some(Geometry::Point(Coord::new(451_000.0, 5_411_000.0))), vec![Value::Text("paris".into())]); + raw.push(Some(Geometry::Point(Coord::new(1e12, 1e12))), vec![Value::Text("far".into())]); + let path = d.join("points.shp"); + crate::io::write_path(&raw, &path).unwrap(); + std::fs::write(path.with_extension("prj"), crate::raster::wkt::to_wkt(utm31()).unwrap()).unwrap(); + let (whole, _) = crate::io::read_path(&path).unwrap(); + let src = crate::source::shp::ShpSource::open_path(&path, "points").unwrap(); + let (streamed, report) = crate::source::materialize(&src).unwrap(); + assert_eq!(streamed.features, whole.features); + assert_eq!(streamed.coord_crs(), utm31()); + assert!(!streamed.crs_incomplete); + let said: Vec<&str> = report.messages.texts().collect(); + assert_eq!(said.iter().filter(|m| m.contains("one of the features has a place in EPSG:32631")).count(), 1, "{said:?}"); + // A read of a box in longitude/latitude leaves it out; it meets none. + let paris = rustgis_geom::Extent { min_x: 2.0, min_y: 48.5, max_x: 2.7, max_y: 49.2 }; + let view = crate::source::FeatureSource::read(&src, &crate::source::Request { extent: Some(paris), limit: 10, own: None }).unwrap(); + assert_eq!(view.features.len(), 1); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 72d622894b..fcb67ab3d7 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 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 kept as the file holds it and counted in a notice; it doesn't draw (see [Places with no longitude/latitude](#places-with-no-longitudelatitude)). 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 is kept as the file holds it and counted in a notice; it doesn't draw. One whose coordinates convert to beyond ±180.5° longitude or ±90.5° latitude (the declared system doesn't fit the numbers) is kept too, and a notice says it may draw out of place (see [Places with no longitude/latitude](#places-with-no-longitudelatitude)). 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. | @@ -794,11 +794,15 @@ past where that system reaches (a UTM easting of a billion metres, say), or ever whose `.prj` or declared system doesn't fit its numbers. Shapefile, GeoJSON (with a `crs`), CSV and other delimited text, File Geodatabase, ArcGIS feature service answers, MapInfo, DXF, LandXML, CityJSON and CityGML, GML and GeoLibre projects keep such a feature as the file holds it, and one -notice counts them; when none of a file's features has such a place, the notice says its system -doesn't seem to fit, and Define Projection can set the one that does. Such a feature doesn't draw -(the map says how many it leaves out), and each step that needs longitude/latitude (an export in -WGS 84, a tool, an edit) leaves it out or refuses it and says so; written back in its own system, -it is exact. +notice counts them; so do GeoPackage, FlatGeobuf, GeoParquet, PostGIS and Shapefiles read in +place, and the files RustGIS reads through GDAL or DuckDB. When none of a Shapefile's, GeoJSON's, +CSV's, MapInfo, DXF, LandXML or city model's features has a place there, the notice says its +system doesn't seem to fit, and Define Projection can set the one that does. Such a feature +doesn't draw (the map says how many it leaves out), and each step that needs longitude/latitude +(an export in WGS 84, a tool, an edit) leaves it out or refuses it and says so; written back in +its own system, it is exact. A system that converts a place to beyond ±180.5° longitude or ±90.5° +latitude (Web Mercator a billion metres east is 8983°) doesn't fit either: such a feature is kept +and draws out of place, and a notice says so. Coordinate systems of other bodies than the Earth (Mars, the Moon and the rest of the IAU's `IAU_2015` codes, or any datum whose ellipsoid isn't the Earth's) aren't read as such yet: every @@ -852,8 +856,8 @@ clamped coordinates, import the original file again to recover them accurately. A feature whose `.prj` (or other declared system) gave it no place in longitude/latitude is kept as the file holds it, so Define Projection places it once the right system is given. If a -reader still dropped geometry (a LiDAR file, or a layer read in place through a GeoPackage, -FlatGeobuf, GeoParquet, GDAL or DuckDB), Define Projection cannot restore it. Choose **Import Original File…** in the dialog, or search for **Import Shapefile with +reader still dropped geometry (a LiDAR file, a MySQL or SQL Server table), Define Projection +cannot restore it. Choose **Import Original File…** in the dialog, or search for **Import Shapefile with Projection…**. Enter the correct CRS before choosing the file. In the browser, pick the `.shp` and `.dbf` together, with any sidecars, or choose a ZIP. The override replaces the `.prj` before any conversion and applies to every Shapefile in a ZIP; other formats keep their own CRS. From d1deb944d612fdd6f8e239454fe9e8835cfac1f9 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 10:21:55 +0100 Subject: [PATCH 3/9] Review: city models and whole reads through sources say places beyond longitude/latitude; field packages from a streamed Shapefile keep and say such features; ArcGIS views take them where they draw (#2032 C2f-4b-2) --- crates/data/src/cityjson/tests.rs | 13 +++++++++++++ crates/data/src/citymodel.rs | 20 +++++++++++++++----- crates/data/src/lib.rs | 30 ++++++++++++++++++++++++++++++ crates/data/src/source/arcgis.rs | 4 +++- crates/data/src/source/mod.rs | 15 ++------------- crates/engine/src/cmd/field.rs | 7 ++++++- crates/geolibre/src/lib.rs | 3 ++- docs/user-guide/data-formats.md | 6 ++++-- 8 files changed, 75 insertions(+), 23 deletions(-) diff --git a/crates/data/src/cityjson/tests.rs b/crates/data/src/cityjson/tests.rs index 1439e1daa1..7eee8d6b8b 100644 --- a/crates/data/src/cityjson/tests.rs +++ b/crates/data/src/cityjson/tests.rs @@ -655,6 +655,19 @@ fn objects_that_cant_be_converted_are_kept_and_said() { assert!(says(&out, "none of the city objects has a place in longitude/latitude from EPSG:32631"), "{:?}", messages_of(&out)); } +/// An object its system converts to beyond longitude/latitude (Web Mercator a trillion metres +/// east) is kept and draws out of place, and the layer says so (#2032 C2f-4b). +#[test] +fn objects_converted_beyond_longitude_latitude_are_said() { + let triangle = + |a: i64| json!({"type": "LandUse", "geometry": [{"type": "MultiSurface", "lod": "1", "boundaries": [[[a, a + 1, a + 2]]]}]}); + let far = [[1e12, 0.0, 0.0], [1e12 + 1000.0, 0.0, 0.0], [1e12 + 1000.0, 1000.0, 0.0]]; + let bytes = doc(json!(far), json!({"a": triangle(0)})); + let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); + assert!(out[0].0.features.rows().all(|r| r.geometry().is_some())); + assert!(says(&out, "coordinates are not longitude/latitude once converted from EPSG:3857"), "{:?}", messages_of(&out)); +} + /// An object is counted once in a notice, however many of its geometry families it loses. #[test] fn an_object_losing_several_families_is_counted_once() { diff --git a/crates/data/src/citymodel.rs b/crates/data/src/citymodel.rs index 0580575e6e..2407d8a186 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -152,6 +152,7 @@ pub(crate) struct Counts { /// from `crs`, which don't draw; `all_unconverted` when no object has one. pub(crate) unconverted: usize, pub(crate) all_unconverted: bool, + pub(crate) beyond: Option, pub(crate) crs: Option, pub(crate) bad_heights: usize, /// Objects whose lowest and highest Z, or lowest Z and ground, are too far apart for their @@ -571,17 +572,23 @@ pub(crate) fn finish( if crs != Crs::LonLat { let to_lonlat = crs.transformer().map_err(|e| DataError::Format(format!("{file_name}: {e}")))?; let mut objects = HashSet::new(); + let mut placed_extent = rustgis_geom::Extent::EMPTY; for row in &mut rows { // Kept as the file holds it, in its system; marked, as it doesn't draw, when it has no // place in longitude/latitude. - if let Some(g) = &row.geometry - && !crate::io::places_in_lonlat(g, &to_lonlat) - { - (row.unconverted, row.draws) = (true, false); - objects.insert(row.object); + if let Some(g) = &row.geometry { + match crate::io::places_lonlat_extent(g, &to_lonlat) { + Some(e) => placed_extent = placed_extent.union(&e), + None => { + (row.unconverted, row.draws) = (true, false); + objects.insert(row.object); + } + } } } counts.unconverted += objects.len(); + // Those that convert, beyond longitude/latitude: they draw out of place, said. + counts.beyond = crate::io::beyond_lonlat_note(&placed_extent, crs); } counts.parent_rounds = raise_parents(&mut built, MAX_PARENT_VISITS).unwrap_or(0); counts.ground_rounds = set_grounds(&mut built, MAX_PARENT_VISITS).unwrap_or(0); @@ -1157,6 +1164,9 @@ pub(crate) fn messages(c: &Counts) -> Vec { if let Some(note) = c.crs.and_then(|crs| crate::io::kept_unplaced_note("city objects", c.unconverted, c.all_unconverted, crs)) { say(c.unconverted, note); } + if let Some(note) = c.beyond.clone() { + say(1, note); + } say( c.bad_heights, format!("{} city objects have heights that aren't finite numbers, which z_min, z_max and height leave out", c.bad_heights), diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 172a85a687..ef562fbddc 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -548,6 +548,36 @@ impl Dataset { Self::geometry_to_lonlat_by(&self.shown_conversion()?, g) } + /// What a whole read of a source says of the features it kept as the source holds them + /// ([`source::Reproject::place`]): how many have a place that can't be given in + /// longitude/latitude, and whether those that convert come out beyond it, as a file read + /// whole says them (#2032 C2f-4b). One pass, each place converted to be checked and none kept; + /// nothing while its coordinates are longitude/latitude or its system can't be converted (the + /// map says that). + pub fn kept_unplaced_notes(&self) -> Vec { + let Ok(to) = self.lonlat_conversion() else { return Vec::new() }; + if to.is_identity() { + return Vec::new(); + } + let (mut unplaced, mut placed, mut extent) = (0usize, 0usize, Extent::EMPTY); + for g in self.features.rows().filter_map(RowRef::geometry) { + let (mut ok, mut e) = (true, Extent::EMPTY); + g.for_each_coord(|c| match to.point(c) { + Some(l) => e.expand(l), + None if !c.is_finite() => {} + None => ok = false, + }); + if ok { + placed += 1; + extent = extent.union(&e); + } else { + unplaced += 1; + } + } + let crs = self.coord_crs(); + io::kept_unplaced_note("features", unplaced, placed == 0, crs).into_iter().chain(io::beyond_lonlat_note(&extent, crs)).collect() + } + /// [`Dataset::geometry_to_lonlat`] of `g`, feature `id`'s geometry, for an edit of that one /// feature: refused naming the layer and the feature when one of its places can't be given in /// longitude/latitude, so it can't be edited there. diff --git a/crates/data/src/source/arcgis.rs b/crates/data/src/source/arcgis.rs index 8846c68db0..8fedaad6ce 100644 --- a/crates/data/src/source/arcgis.rs +++ b/crates/data/src/source/arcgis.rs @@ -399,7 +399,9 @@ impl ArcgisSource { /// Whether a feature, held in the layer's system, meets a view in longitude/latitude. fn meets(&self, g: &crate::Geometry, view: &Extent) -> bool { match &self.to_lonlat { - Some(t) => crate::io::lonlat_box(g, t).is_some_and(|b| b.intersects(view)), + // A place that converts beyond longitude/latitude meets the view where it draws, as a + // whole read keeps it (#2032 C2f-4b). + Some(t) => crate::io::places_lonlat_extent(g, t).is_some_and(|b| b.intersects(view)), None => g.extent().intersects(view), } } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3401531375..3e478b0074 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -816,19 +816,8 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, } // The features kept with a place that can't be given in longitude/latitude, said once, as a // file read whole says them; a source that said them when it was opened isn't counted again. - if !src.says_unplaced_at_open() - && let Ok(to) = ds.lonlat_conversion() - && !to.is_identity() - { - let (mut unplaced, mut placed) = (0usize, 0usize); - for g in ds.features.rows().filter_map(crate::RowRef::geometry) { - let has = Dataset::converted_to_lonlat(&to, g).is_some(); - placed += usize::from(has); - unplaced += usize::from(!has); - } - report.messages.extend( - crate::io::kept_unplaced_note("features", unplaced, placed == 0, ds.coord_crs()).map(|n| format!("{}: {n}", info.name)), - ); + if !src.says_unplaced_at_open() { + report.messages.extend(ds.kept_unplaced_notes().into_iter().map(|n| format!("{}: {n}", info.name))); } Ok((ds, report)) } diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 5920b2fe00..3911c47e2a 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -760,8 +760,13 @@ fn copy_stream( ]; losses.extend(info.notes.iter().chain(&batch.notes).cloned().map(|note| note.prefixed(&layer.name))); losses.extend(counted.into_iter().flatten().map(|note| note.prefixed(&layer.name))); - dataset.crs_incomplete = src.lost_to_crs() || (info.format == "Shapefile" && batch.skipped > 0); + // A shape with no place in longitude/latitude is kept as the source holds it (#2032 C2f-4b), + // and said, as a whole read says it. + dataset.crs_incomplete = src.lost_to_crs(); dataset.features = rows.into(); + if !src.says_unplaced_at_open() { + losses.extend(dataset.kept_unplaced_notes().into_iter().map(|n| format!("{}: {n}", layer.name))); + } if dataset.geometry_type == rustgis_data::GeometryType::None && let Some(g) = dataset.features.geometry(0) { diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 3705b77ad9..f46ac671fd 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -1077,8 +1077,9 @@ fn load( .filter(|g| Dataset::converted_to_lonlat(&to, g).is_none()) .count(); if lost > 0 { + let have = if lost == 1 { "feature has" } else { "features have" }; messages.push(format!( - "{layer_name}: {lost} features have a place in {} that can't be given in longitude/latitude: they are kept as read, but don't draw", + "{layer_name}: {lost} {have} a place in {} that can't be given in longitude/latitude: kept as read, but not drawn", job.crs.label() )); } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index fcb67ab3d7..16ddf955d1 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -795,14 +795,16 @@ whose `.prj` or declared system doesn't fit its numbers. Shapefile, GeoJSON (wit other delimited text, File Geodatabase, ArcGIS feature service answers, MapInfo, DXF, LandXML, CityJSON and CityGML, GML and GeoLibre projects keep such a feature as the file holds it, and one notice counts them; so do GeoPackage, FlatGeobuf, GeoParquet, PostGIS and Shapefiles read in -place, and the files RustGIS reads through GDAL or DuckDB. When none of a Shapefile's, GeoJSON's, +place, and the files RustGIS reads through GDAL or DuckDB (a layer read a view at a time is +counted by the map, as it draws). When none of a Shapefile's, GeoJSON's, CSV's, MapInfo, DXF, LandXML or city model's features has a place there, the notice says its system doesn't seem to fit, and Define Projection can set the one that does. Such a feature doesn't draw (the map says how many it leaves out), and each step that needs longitude/latitude (an export in WGS 84, a tool, an edit) leaves it out or refuses it and says so; written back in its own system, it is exact. A system that converts a place to beyond ±180.5° longitude or ±90.5° latitude (Web Mercator a billion metres east is 8983°) doesn't fit either: such a feature is kept -and draws out of place, and a notice says so. +and draws out of place. Shapefile, GeoJSON, CSV, ArcGIS feature service answers, city models and +whole reads of GeoPackage, FlatGeobuf, GeoParquet and PostGIS say so. Coordinate systems of other bodies than the Earth (Mars, the Moon and the rest of the IAU's `IAU_2015` codes, or any datum whose ellipsoid isn't the Earth's) aren't read as such yet: every From dec7cc5bafbbafb8d78cc14f87038b6f0aae1c5e Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 10:42:46 +0100 Subject: [PATCH 4/9] Drop the unused lonlat_box; the search-area test reads the singular note (#2032 C2f-4b-2) --- crates/data/src/io.rs | 14 -------------- crates/engine/src/tests/unplaced_gp.rs | 2 +- 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 53e096021a..2c43c61541 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1665,20 +1665,6 @@ pub(crate) fn places_lonlat_extent(g: &Geometry, t: &crate::raster::Transformer) ok.then_some(e) } -/// 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 a reader says of the `n` of its `what` (features, shapes, rows) it keeps as the file holds /// them, held in `crs`, though a place of theirs can't be given in longitude/latitude: they don't /// draw (the map says so too), and every other step that needs longitude/latitude leaves them out diff --git a/crates/engine/src/tests/unplaced_gp.rs b/crates/engine/src/tests/unplaced_gp.rs index 4eba9931c5..745eaf625e 100644 --- a/crates/engine/src/tests/unplaced_gp.rs +++ b/crates/engine/src/tests/unplaced_gp.rs @@ -255,7 +255,7 @@ fn a_search_area_file_leaves_out_what_it_cant_place() { let said = loaded.notices.iter().any(|n| n.contains("longitude/latitude")); assert_eq!(said, far, "{:?}", loaded.notices); if far { - assert!(loaded.notices.iter().any(|n| n.contains("kept as the file holds them")), "{:?}", loaded.notices); + assert!(loaded.notices.iter().any(|n| n.contains("kept as the file holds it")), "{:?}", loaded.notices); } } std::fs::remove_dir_all(&dir).ok(); From e44b70b5c135e404728d1b02bca65953637852f7 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 11:09:57 +0100 Subject: [PATCH 5/9] Review: a GeoJSON read of a longitude/latitude box leaves kept unplaced features out before sampling, each place converted once; Cancel in the whole-read count; city model groups ignore undrawn objects; ArcGIS pages count once; DXF, LandXML and MapInfo say places beyond longitude/latitude (#2032 C2f-4b-2) --- crates/data/src/citymodel.rs | 3 +- crates/data/src/dxf.rs | 13 +++++-- crates/data/src/io.rs | 5 ++- crates/data/src/landxml.rs | 13 +++++-- crates/data/src/lib.rs | 17 +++++---- crates/data/src/mapinfo.rs | 13 +++++-- crates/data/src/source/arcgis.rs | 5 +++ crates/data/src/source/geojson.rs | 61 ++++++++++++++++++++++--------- crates/data/src/source/mod.rs | 3 +- crates/data/src/source/tests.rs | 23 ++++++++++++ crates/engine/src/cmd/field.rs | 2 +- docs/user-guide/data-formats.md | 4 +- 12 files changed, 117 insertions(+), 45 deletions(-) diff --git a/crates/data/src/citymodel.rs b/crates/data/src/citymodel.rs index 2407d8a186..72ba3d65c3 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -1021,7 +1021,8 @@ fn layers(stem: &str, rows: Vec, built: &[Built], crs: Crs, counts: &mut Co for (((ty, family), rows), name) in sorted.into_iter().zip(names) { // A layer of volumes stands on its base, when one of them has a height to stand by, unless // every one of them stands in its parts. - let drawn = || rows.iter().filter(|(r, _)| r.geometry.is_some()); + // An object kept with no place in longitude/latitude draws nothing, so doesn't count. + let drawn = || rows.iter().filter(|(r, _)| r.geometry.is_some() && !r.unconverted); let standing = family == Family::Polygon && stands(&ty) && drawn().any(|(_, b)| rises(b)) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 1d4f562a2c..d3287f07f3 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1696,13 +1696,17 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result { + placed += 1; + placed_extent = placed_extent.union(&e); + } + None => lost += 1, + } ds.zm_dropped |= *varying; varying_count += usize::from(*varying); } @@ -1714,6 +1718,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Option { diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 8062a877e9..d7c12bb3d2 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -238,13 +238,18 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result { + placed += 1; + placed_extent = placed_extent.union(&e); + } + None => lost += 1, + } } rep.messages.extend(crate::io::kept_unplaced_note("features", lost, placed == 0, *c)); + rep.messages.extend(crate::io::beyond_lonlat_note(&placed_extent, *c)); } out.push((ds, rep)); } diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index ef562fbddc..01ab000b76 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -551,16 +551,17 @@ impl Dataset { /// What a whole read of a source says of the features it kept as the source holds them /// ([`source::Reproject::place`]): how many have a place that can't be given in /// longitude/latitude, and whether those that convert come out beyond it, as a file read - /// whole says them (#2032 C2f-4b). One pass, each place converted to be checked and none kept; - /// nothing while its coordinates are longitude/latitude or its system can't be converted (the - /// map says that). - pub fn kept_unplaced_notes(&self) -> Vec { - let Ok(to) = self.lonlat_conversion() else { return Vec::new() }; + /// whole says them (#2032 C2f-4b). One pass, each place converted to be checked and none kept, + /// looking at Cancel between features; nothing while its coordinates are longitude/latitude + /// or its system can't be converted (the map says that). + pub fn kept_unplaced_notes(&self) -> std::result::Result, String> { + let Ok(to) = self.lonlat_conversion() else { return Ok(Vec::new()) }; if to.is_identity() { - return Vec::new(); + return Ok(Vec::new()); } let (mut unplaced, mut placed, mut extent) = (0usize, 0usize, Extent::EMPTY); - for g in self.features.rows().filter_map(RowRef::geometry) { + for (i, g) in self.features.rows().filter_map(RowRef::geometry).enumerate() { + stop_when_asked(i)?; let (mut ok, mut e) = (true, Extent::EMPTY); g.for_each_coord(|c| match to.point(c) { Some(l) => e.expand(l), @@ -575,7 +576,7 @@ impl Dataset { } } let crs = self.coord_crs(); - io::kept_unplaced_note("features", unplaced, placed == 0, crs).into_iter().chain(io::beyond_lonlat_note(&extent, crs)).collect() + Ok(io::kept_unplaced_note("features", unplaced, placed == 0, crs).into_iter().chain(io::beyond_lonlat_note(&extent, crs)).collect()) } /// [`Dataset::geometry_to_lonlat`] of `g`, feature `id`'s geometry, for an edit of that one diff --git a/crates/data/src/mapinfo.rs b/crates/data/src/mapinfo.rs index b9faf8cb4b..63e627d5b8 100644 --- a/crates/data/src/mapinfo.rs +++ b/crates/data/src/mapinfo.rs @@ -444,13 +444,17 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe if let (Some(_), Some(c)) = (&t, crs) { ds.held_in = c; } - let (mut lost, mut placed, mut null_text) = (0usize, 0usize, Vec::new()); + let (mut lost, mut placed, mut placed_extent, mut null_text) = (0usize, 0usize, rustgis_geom::Extent::EMPTY, Vec::new()); for (k, g) in geoms.into_iter().enumerate() { // Kept as the file holds it; counted when it has no place in longitude/latitude. if let (Some(t), Some(g)) = (&t, &g) { - let has = crate::io::places_in_lonlat(g, t); - placed += usize::from(has); - lost += usize::from(!has); + match crate::io::places_lonlat_extent(g, t) { + Some(e) => { + placed += 1; + placed_extent = placed_extent.union(&e); + } + None => lost += 1, + } } let row = rows.get(k); let attrs = ds @@ -469,6 +473,7 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe } if let (Some(_), Some(c)) = (&t, crs) { report.messages.extend(crate::io::kept_unplaced_note("objects", lost, placed == 0, c)); + report.messages.extend(crate::io::beyond_lonlat_note(&placed_extent, c)); } report.messages.extend(crate::source::null_text_note(&ds.fields, &null_text)); ds.geometry_type = crate::io::dominant_type(&ds); diff --git a/crates/data/src/source/arcgis.rs b/crates/data/src/source/arcgis.rs index 8fedaad6ce..5b484237bd 100644 --- a/crates/data/src/source/arcgis.rs +++ b/crates/data/src/source/arcgis.rs @@ -658,6 +658,11 @@ impl ArcgisSource { } impl FeatureSource for ArcgisSource { + /// Its pages' notes count them ([`crate::esripbf::Losses`]). + fn says_unplaced_at_open(&self) -> bool { + true + } + fn info(&self) -> &SourceInfo { &self.info } diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 0fe14466a2..10c7ee55b0 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -78,6 +78,10 @@ pub struct GeoJsonSource { reproject: Reproject, /// Features left out when it was opened for geometry that couldn't be read. unreadable: usize, + /// The features (by place) kept with a place that can't be given in longitude/latitude: in a + /// whole read and a read of a box in its own system, but no read of a box in + /// longitude/latitude, which they meet none of. Sorted. + unplaced: Vec, } /// The features of a file as it's scanned. @@ -232,6 +236,7 @@ impl GeoJsonSource { // kept as the file holds them (they don't draw), as when the file is read whole; the // extent in longitude/latitude is that of the rest. let mut extent = scan.extent; + let mut unplaced = Vec::new(); if let Some(t) = reproject.transformer() { let crs = reproject.crs(); file.rewind()?; @@ -239,6 +244,7 @@ impl GeoJsonSource { extent = pass.extent; notes.extend(crate::io::kept_unplaced_note("features", pass.unplaced, pass.placed == 0, crs)); notes.extend(crate::io::beyond_lonlat_note(&pass.placed_extent, crs)); + unplaced = pass.unplaced_at; } else { // Only coordinates read as they are can be longitude/latitude with the two swapped; // a declared system's features were converted above, and those that don't fit left out. @@ -269,19 +275,30 @@ impl GeoJsonSource { } let unreadable = scan.skipped; version.check(&file)?; - Ok(GeoJsonSource { info, path: path.to_path_buf(), version, places: scan.places, boxes: scan.boxes, reproject, unreadable }) + Ok(GeoJsonSource { + info, + path: path.to_path_buf(), + version, + places: scan.places, + boxes: scan.boxes, + reproject, + unreadable, + unplaced, + }) } /// The features a request matches, in file order: every one without an extent; otherwise /// those whose boxes meet it (features without geometry never do). The extent is in the /// file's own coordinates. - fn matches(&self, extent: Option) -> impl Iterator + '_ { - self.candidates(extent).filter_map(|(i, matches)| matches.then_some(i)) + fn matches(&self, extent: Option, lonlat_view: bool) -> impl Iterator + '_ { + self.candidates(extent, lonlat_view).filter_map(|(i, matches)| matches.then_some(i)) } /// Walks every index entry, exposing rejected entries too so a full visit can count /// progress and check Cancel even across a long stretch outside the requested extent. - fn candidates(&self, extent: Option) -> impl Iterator + '_ { + /// A `lonlat_view` (a box given in longitude/latitude) leaves out the features kept with no + /// place there before they are counted or sampled. + fn candidates(&self, extent: Option, lonlat_view: bool) -> impl Iterator + '_ { // Rounded to the nearest f32: never past a box rounded outward that meets the extent. let e = extent.map(|e| (e.is_empty(), [e.min_x as f32, e.min_y as f32, e.max_x as f32, e.max_y as f32])); self.boxes.iter().enumerate().map(move |(i, b)| { @@ -290,7 +307,7 @@ impl GeoJsonSource { Some((true, _)) => false, Some((false, [x0, y0, x1, y1])) => b[0] <= x1 && b[2] >= x0 && b[1] <= y1 && b[3] >= y0, }; - (i as u32, in_box) + (i as u32, in_box && !(lonlat_view && self.unplaced.binary_search(&(i as u32)).is_ok())) }) } } @@ -338,7 +355,7 @@ impl FeatureSource for GeoJsonSource { let mut buf = Vec::new(); let mut batch = Batch { complete: true, ..Batch::default() }; crate::progress::begin(self.places.len()); - for (i, matches) in self.candidates(native) { + for (i, matches) in self.candidates(native, extent.is_some()) { crate::progress::step(1)?; if !matches { continue; @@ -369,7 +386,9 @@ impl FeatureSource for GeoJsonSource { if limit == 0 && req.extent.is_some() && extent.is_none() { return Err(super::unbounded_count()); } - let matched = self.matches(extent).count(); + // A box given in longitude/latitude: features with no place there don't meet it. + let lonlat_view = req.extent.is_some() && self.reproject.own_box(req).is_none(); + let matched = self.matches(extent, lonlat_view).count(); // A refused native box needs geometry filtering before sampling, just as an unindexed source does. let late = req.extent.is_some() && extent.is_none(); let step = if late { 1 } else { stride(matched as u64, limit).max(1) as usize }; @@ -384,7 +403,7 @@ impl FeatureSource for GeoJsonSource { if counted { crate::progress::begin(if late { matched } else { matched.min(limit) }); } - for (n, i) in self.matches(extent).step_by(step).take(if late { usize::MAX } else { limit }).enumerate() { + for (n, i) in self.matches(extent, lonlat_view).step_by(step).take(if late { usize::MAX } else { limit }).enumerate() { if counted { crate::progress::step(1)?; } else if n.is_multiple_of(PACE) { @@ -494,6 +513,8 @@ struct Pass { unplaced: usize, placed: usize, placed_extent: Extent, + /// Where the features with no place are, sorted. + unplaced_at: Vec, /// The extent, in longitude/latitude, of every place that converts. extent: Extent, } @@ -502,7 +523,7 @@ struct Pass { fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> Result { let mut f = BufReader::with_capacity(BUFFER, file); let (mut pos, mut buf) = (0u64, Vec::new()); - let mut pass = Pass { unplaced: 0, placed: 0, placed_extent: Extent::EMPTY, extent: Extent::EMPTY }; + let mut pass = Pass { unplaced: 0, placed: 0, placed_extent: Extent::EMPTY, unplaced_at: Vec::new(), extent: Extent::EMPTY }; // Counted as a step of its own, a feature at a time every so many. crate::progress::begin(places.len()); for (i, place) in places.iter().enumerate() { @@ -514,18 +535,22 @@ fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transforme && let Ok(Some(g)) = geojson_geometry(&json) { // The extent as a layer read whole gives it ([`crate::Dataset::lonlat_extent`]): - // every place that converts to a finite one, beyond longitude/latitude too. - g.for_each_coord(|c| { - if let Some(l) = t.to_lonlat(c).filter(|l| l.is_finite()) { + // every place that converts to a finite one, beyond longitude/latitude too; each + // place converted once. + let (mut all, mut e) = (true, Extent::EMPTY); + g.for_each_coord(|c| match t.to_lonlat(c).filter(|l| l.is_finite()) { + Some(l) => { pass.extent.expand(l); + e.expand(l); } + None => all = false, }); - match crate::io::places_lonlat_extent(&g, t) { - Some(e) => { - pass.placed += 1; - pass.placed_extent = pass.placed_extent.union(&e); - } - None => pass.unplaced += 1, + if all { + pass.placed += 1; + pass.placed_extent = pass.placed_extent.union(&e); + } else { + pass.unplaced += 1; + pass.unplaced_at.push(i as u32); } } } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3e478b0074..a84ddead2b 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -817,7 +817,8 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, // The features kept with a place that can't be given in longitude/latitude, said once, as a // file read whole says them; a source that said them when it was opened isn't counted again. if !src.says_unplaced_at_open() { - report.messages.extend(ds.kept_unplaced_notes().into_iter().map(|n| format!("{}: {n}", info.name))); + let notes = ds.kept_unplaced_notes().map_err(DataError::of_conversion)?; + report.messages.extend(notes.into_iter().map(|n| format!("{}: {n}", info.name))); } Ok((ds, report)) } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 05af6ead3c..f41cd8f704 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3022,6 +3022,29 @@ fn geojson_reads_in_longitude_latitude_leave_out_unplaced_features() { } } +#[test] +fn geojson_a_kept_unplaced_feature_does_not_use_up_a_sample() { + // A line with no place in longitude/latitude whose own box meets the view, ahead of a point + // in it: a read of one feature there gets the point, and counts one match (#2032 C2f-4b). + let text = format!( + r#"{{"type":"FeatureCollection","crs":{},"features":[ + {{"type":"Feature","properties":{{}},"geometry":{{"type":"LineString","coordinates":[[451500,5411500],[1e9,5411500]]}}}}, + {{"type":"Feature","properties":{{}},"geometry":{{"type":"Point","coordinates":[451500,5411500]}}}}]}}"#, + named("EPSG:32631") + ); + let p = dir().join("geojson-crs").join("ahead.geojson"); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, &text).unwrap(); + let paris = Some(Extent { min_x: 2.0, min_y: 48.5, max_x: 2.7, max_y: 49.2 }); + for in_memory in [crate::io::BYTES_FLOOR, 0] { + let src = geojson::GeoJsonSource::open_with(&p, "x", in_memory).unwrap(); + let one = src.read(&Request { extent: paris, limit: 1, own: None }).unwrap(); + assert_eq!((one.features.len(), one.matched), (1, 1)); + assert!(matches!(one.features[0].geometry, Some(Geometry::Point(_)))); + assert_eq!(src.read(&Request::all()).unwrap().features.len(), 2, "a whole read keeps both"); + } +} + #[test] fn geojson_unreadable_feature_alone_does_not_make_the_layer_incomplete() { // A declared system, one feature with geometry that can't be read, and all the others diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 3911c47e2a..1551d8d067 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -765,7 +765,7 @@ fn copy_stream( dataset.crs_incomplete = src.lost_to_crs(); dataset.features = rows.into(); if !src.says_unplaced_at_open() { - losses.extend(dataset.kept_unplaced_notes().into_iter().map(|n| format!("{}: {n}", layer.name))); + losses.extend(dataset.kept_unplaced_notes()?.into_iter().map(|n| format!("{}: {n}", layer.name))); } if dataset.geometry_type == rustgis_data::GeometryType::None && let Some(g) = dataset.features.geometry(0) diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 16ddf955d1..d3d04e8b0a 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -800,10 +800,10 @@ counted by the map, as it draws). When none of a Shapefile's, GeoJSON's, CSV's, MapInfo, DXF, LandXML or city model's features has a place there, the notice says its system doesn't seem to fit, and Define Projection can set the one that does. Such a feature doesn't draw (the map says how many it leaves out), and each step that needs longitude/latitude -(an export in WGS 84, a tool, an edit) leaves it out or refuses it and says so; written back in +(an export in WGS 84, a tool, an edit) leaves it out and says so, or refuses naming it where leaving it out would lose it (a write-back, a sync of an offline area holding it); written back in its own system, it is exact. A system that converts a place to beyond ±180.5° longitude or ±90.5° latitude (Web Mercator a billion metres east is 8983°) doesn't fit either: such a feature is kept -and draws out of place. Shapefile, GeoJSON, CSV, ArcGIS feature service answers, city models and +and draws out of place. Shapefile, GeoJSON, CSV, MapInfo, DXF, LandXML, ArcGIS feature service answers, city models and whole reads of GeoPackage, FlatGeobuf, GeoParquet and PostGIS say so. Coordinate systems of other bodies than the Earth (Mars, the Moon and the rest of the IAU's From dab1ec8ef1baae766fcf7fb3a24a5a2b8ea30ed7 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 11:20:06 +0100 Subject: [PATCH 6/9] Review: wrap and align the notes on what refuses such a feature (#2032 C2f-4b-2) --- crates/data/src/io.rs | 5 +++-- crates/data/src/lib.rs | 2 +- docs/user-guide/data-formats.md | 24 +++++++++++++----------- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index e734d59aa0..66e80d7164 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1668,8 +1668,9 @@ pub(crate) fn places_lonlat_extent(g: &Geometry, t: &crate::raster::Transformer) /// What a reader says of the `n` of its `what` (features, shapes, rows) it keeps as the file holds /// them, held in `crs`, though a place of theirs can't be given in longitude/latitude: they don't /// draw (the map says so too), and a step that needs longitude/latitude leaves them out and says -/// so, or, where leaving one out would lose it (a write-back, the plugin host's layers, a sync of -/// an offline area holding it), refuses naming it (#2032 C2f-4b). `all` when none of the file's has a place there: then its system +/// so, or refuses naming one where leaving it out would lose it (a write-back, a sync of an +/// offline area holding it, a Field Package's list of changes) or a contract says so (the plugin +/// host's layers) (#2032 C2f-4b). `all` when none of the file's has a place there: then its system /// doesn't seem to match its coordinates, and Define Projection can set the one that does, as /// nothing was lost. `None` for none. pub(crate) fn kept_unplaced_note(what: &str, n: usize, all: bool, crs: Crs) -> Option { diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 01ab000b76..3eabe84bbe 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -552,7 +552,7 @@ impl Dataset { /// ([`source::Reproject::place`]): how many have a place that can't be given in /// longitude/latitude, and whether those that convert come out beyond it, as a file read /// whole says them (#2032 C2f-4b). One pass, each place converted to be checked and none kept, - /// looking at Cancel between features; nothing while its coordinates are longitude/latitude + /// looking at Cancel every 256 features; nothing while its coordinates are longitude/latitude /// or its system can't be converted (the map says that). pub fn kept_unplaced_notes(&self) -> std::result::Result, String> { let Ok(to) = self.lonlat_conversion() else { return Ok(Vec::new()) }; diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index d3d04e8b0a..e7dcb5e48e 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -794,17 +794,19 @@ past where that system reaches (a UTM easting of a billion metres, say), or ever whose `.prj` or declared system doesn't fit its numbers. Shapefile, GeoJSON (with a `crs`), CSV and other delimited text, File Geodatabase, ArcGIS feature service answers, MapInfo, DXF, LandXML, CityJSON and CityGML, GML and GeoLibre projects keep such a feature as the file holds it, and one -notice counts them; so do GeoPackage, FlatGeobuf, GeoParquet, PostGIS and Shapefiles read in -place, and the files RustGIS reads through GDAL or DuckDB (a layer read a view at a time is -counted by the map, as it draws). When none of a Shapefile's, GeoJSON's, -CSV's, MapInfo, DXF, LandXML or city model's features has a place there, the notice says its -system doesn't seem to fit, and Define Projection can set the one that does. Such a feature -doesn't draw (the map says how many it leaves out), and each step that needs longitude/latitude -(an export in WGS 84, a tool, an edit) leaves it out and says so, or refuses naming it where leaving it out would lose it (a write-back, a sync of an offline area holding it); written back in -its own system, it is exact. A system that converts a place to beyond ±180.5° longitude or ±90.5° -latitude (Web Mercator a billion metres east is 8983°) doesn't fit either: such a feature is kept -and draws out of place. Shapefile, GeoJSON, CSV, MapInfo, DXF, LandXML, ArcGIS feature service answers, city models and -whole reads of GeoPackage, FlatGeobuf, GeoParquet and PostGIS say so. +notice counts them; so do GeoPackage, FlatGeobuf, GeoParquet, PostGIS and Shapefiles read in place, +and the files RustGIS reads through GDAL or DuckDB (a layer read a view at a time is counted by the +map, as it draws). When none of a Shapefile's, GeoJSON's, CSV's, MapInfo, DXF, LandXML or city +model's features has a place there, the notice says its system doesn't seem to fit, and Define +Projection can set the one that does. Such a feature doesn't draw (the map says how many it leaves +out), and each step that needs longitude/latitude (an export in WGS 84, a tool, an edit) leaves it +out and says so, or refuses naming it where leaving it out would lose it (a write-back, a sync of an +offline area holding it, a Field Package's list of changes) or a plugin tool takes the layer; +written back in its own system, it is exact. A system that converts a place to beyond ±180.5° +longitude or ±90.5° latitude (Web Mercator a billion metres east is 8983°) doesn't fit either: such +a feature is kept and draws out of place. Shapefile, GeoJSON, CSV, MapInfo, DXF, LandXML, ArcGIS +feature service answers, city models and whole reads of GeoPackage, FlatGeobuf, GeoParquet and +PostGIS say so. Coordinate systems of other bodies than the Earth (Mars, the Moon and the rest of the IAU's `IAU_2015` codes, or any datum whose ellipsoid isn't the Earth's) aren't read as such yet: every From 7ec415324014d0120617d57ca8afa0035935504a Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 11:22:45 +0100 Subject: [PATCH 7/9] Reproject::read is for MySQL and SQL Server only: not built for the browser (#2032 C2f-4b-2) --- crates/data/src/source/mod.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index a84ddead2b..a28d59e468 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -1032,11 +1032,13 @@ 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 - /// ([`Reproject::place`]); `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, + /// A geometry as the source holds it, kept in its own coordinates ([`Reproject::crs`]), with + /// its box in longitude/latitude for a request's extent to test, for a source read by its + /// rows (MySQL, SQL Server); `None` when a coordinate can't be converted to + /// longitude/latitude, as such a feature is left out there (the others keep it: + /// [`Reproject::place`]). Each coordinate is converted to be checked, /// none is kept converted. + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read(&self, g: Geometry) -> Option { let Some(t) = &self.t else { let lonlat = g.extent(); @@ -1441,6 +1443,7 @@ 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`]). +#[cfg(not(target_arch = "wasm32"))] pub(crate) struct Placed { pub(crate) geometry: Geometry, pub(crate) lonlat: Extent, From 67ac353aead1e75905a4de0cfc82eb8b02476cbb Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 12:15:13 +0100 Subject: [PATCH 8/9] Review: the notice of places beyond longitude/latitude counts them; File Geodatabase, GML and GeoLibre imports say it too (#2032 C2f-4b-2) --- crates/data/src/cityjson/tests.rs | 2 +- crates/data/src/citymodel.rs | 10 +++++++--- crates/data/src/dxf.rs | 6 +++--- crates/data/src/esripbf.rs | 19 ++++++++++++------ crates/data/src/esripbf/tests.rs | 2 +- crates/data/src/filegdb.rs | 10 ++++++++-- crates/data/src/gml.rs | 25 +++++++++++++++++++++++- crates/data/src/io.rs | 32 ++++++++++++++++--------------- crates/data/src/landxml.rs | 6 +++--- crates/data/src/lib.rs | 9 ++++++--- crates/data/src/mapinfo.rs | 6 +++--- crates/data/src/source/geojson.rs | 9 +++++---- crates/data/src/source/tests.rs | 4 ++-- crates/geolibre/src/lib.rs | 20 +++++++++++++------ 14 files changed, 107 insertions(+), 53 deletions(-) diff --git a/crates/data/src/cityjson/tests.rs b/crates/data/src/cityjson/tests.rs index 7eee8d6b8b..29b14558f1 100644 --- a/crates/data/src/cityjson/tests.rs +++ b/crates/data/src/cityjson/tests.rs @@ -665,7 +665,7 @@ fn objects_converted_beyond_longitude_latitude_are_said() { let bytes = doc(json!(far), json!({"a": triangle(0)})); let out = read("m.city.json", &bytes, Some(Crs::WebMercator)).unwrap(); assert!(out[0].0.features.rows().all(|r| r.geometry().is_some())); - assert!(says(&out, "coordinates are not longitude/latitude once converted from EPSG:3857"), "{:?}", messages_of(&out)); + assert!(says(&out, "coordinates that come out beyond longitude/latitude once converted from EPSG:3857"), "{:?}", messages_of(&out)); } /// An object is counted once in a notice, however many of its geometry families it loses. diff --git a/crates/data/src/citymodel.rs b/crates/data/src/citymodel.rs index 72ba3d65c3..da1ca68fb3 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -572,13 +572,17 @@ pub(crate) fn finish( if crs != Crs::LonLat { let to_lonlat = crs.transformer().map_err(|e| DataError::Format(format!("{file_name}: {e}")))?; let mut objects = HashSet::new(); - let mut placed_extent = rustgis_geom::Extent::EMPTY; + let mut beyond = HashSet::new(); for row in &mut rows { // Kept as the file holds it, in its system; marked, as it doesn't draw, when it has no // place in longitude/latitude. if let Some(g) = &row.geometry { match crate::io::places_lonlat_extent(g, &to_lonlat) { - Some(e) => placed_extent = placed_extent.union(&e), + Some(e) => { + if e.beyond_lonlat() { + beyond.insert(row.object); + } + } None => { (row.unconverted, row.draws) = (true, false); objects.insert(row.object); @@ -588,7 +592,7 @@ pub(crate) fn finish( } counts.unconverted += objects.len(); // Those that convert, beyond longitude/latitude: they draw out of place, said. - counts.beyond = crate::io::beyond_lonlat_note(&placed_extent, crs); + counts.beyond = crate::io::beyond_lonlat_note("city objects", beyond.len(), crs); } counts.parent_rounds = raise_parents(&mut built, MAX_PARENT_VISITS).unwrap_or(0); counts.ground_rounds = set_grounds(&mut built, MAX_PARENT_VISITS).unwrap_or(0); diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index d3287f07f3..3e96018c5d 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1696,14 +1696,14 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result { placed += 1; - placed_extent = placed_extent.union(&e); + beyond += usize::from(e.beyond_lonlat()); } None => lost += 1, } @@ -1718,7 +1718,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 { + let (count, have, they) = if self.beyond == 1 { + ("one feature".to_string(), "has", "it") + } else { + (format!("{} features", self.beyond), "have", "they") + }; + out.push(format!( + "{count} {have} coordinates that come out beyond longitude/latitude once converted from the answer's coordinate system: it may not be theirs, and {they} may draw out of place" + )); } if self.with_zm > 0 { out.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(self.with_zm as u64)))); @@ -359,7 +366,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result let shape = Shape { kind: shape_kind, transform: &transform, has_z, has_m }; let mut ds = Dataset::new(name, GeometryType::None, fields); let width = ds.fields.len(); - let (mut any_geometry, mut with_zm, mut unprojected, mut beyond) = (false, 0usize, 0usize, false); + let (mut any_geometry, mut with_zm, mut unprojected, mut beyond) = (false, 0usize, 0usize, 0usize); for (n, bytes) in features.into_iter().enumerate() { let (values, geometry) = feature(bytes, &columns, width, &shape, &mut tally).map_err(|e| match e { DataError::Format(m) => invalid(format!("feature {}: {}", n + 1, m.strip_prefix(PREFIX).unwrap_or(&m))), @@ -371,7 +378,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result // longitude/latitude. if let (Some(g), Some(t)) = (&geometry, &to_lonlat) { match crate::io::places_lonlat_extent(g, t) { - Some(e) => beyond |= e.beyond_lonlat(), + Some(e) => beyond += usize::from(e.beyond_lonlat()), None => unprojected += 1, } } diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 210b031366..2bcb0f7943 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -263,7 +263,7 @@ fn coordinates_past_longitude_latitude_are_kept_and_the_layer_says_so() { assert_eq!( report.messages, [ - "coordinates are not longitude/latitude once converted from the answer's coordinate system; it may not match them, and they may draw out of place" + "one feature has coordinates that come out beyond longitude/latitude once converted from the answer's coordinate system: it may not be theirs, and it may draw out of place" ] ); } diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 8c2941168f..bd16f8de32 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -359,7 +359,7 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result) -> Result beyond += usize::from(e.beyond_lonlat()), + None => unprojected += 1, + } } ds.push_next(geometry, attrs); } @@ -432,6 +435,9 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 0 { report.messages.push(format!("{curves} curved segments are drawn as straight lines")); } + if let Some(c) = crs.filter(|_| to_lonlat.is_some()) { + report.messages.extend(crate::io::beyond_lonlat_note("features", beyond, c)); + } if unprojected > 0 { report .messages diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 722d6918ba..b432f8d187 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -651,7 +651,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> 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; + let (mut unplaced, mut beyond) = (0usize, 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 @@ -688,6 +688,8 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> }); unplaced += usize::from(missing.get()); e = lonlat.get(); + // Converted, but beyond longitude/latitude: it draws out of place. + beyond += usize::from(!missing.get() && e.beyond_lonlat()); Some(kept) } (_, g) => { @@ -732,6 +734,9 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> ds.name )); } + if let Some((c, _)) = file_srs { + rep.messages.extend(crate::io::beyond_lonlat_note("features", beyond, c).map(|n| format!("{}: {n}", 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"); } @@ -907,6 +912,24 @@ mod tests { assert_eq!(ds.in_lonlat_leaving_out().unwrap().1, 1); } + /// A place a file's system converts to beyond longitude/latitude (Web Mercator a billion + /// metres east) is kept and said with a count; one in its place says nothing (#2032 C2f-4b). + #[test] + fn a_place_beyond_longitude_latitude_is_said() { + let gml = |x: &str| { + format!( + r#" +{x},6000000 +"# + ) + }; + let said = |x: &str| { + read("p.gml", gml(x).as_bytes()).unwrap()[0].1.messages.texts().any(|m| m.contains("come out beyond longitude/latitude")) + }; + assert!(said("1e9")); + assert!(!said("1000000")); + } + #[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 66e80d7164..21b27cdae3 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1691,15 +1691,17 @@ pub(crate) fn kept_unplaced_note(what: &str, n: usize, all: bool, crs: Crs) -> O }) } -/// What a reader says when the places of its features that do convert from `crs` come out beyond -/// longitude/latitude (`placed`, their box there): the system may not match the coordinates, -/// and they may draw out of place. -pub(crate) fn beyond_lonlat_note(placed: &rustgis_geom::Extent, crs: Crs) -> Option { - placed.beyond_lonlat().then(|| { - format!( - "coordinates are not longitude/latitude once converted from {}; it may not match them, and they may draw out of place", - crs.label() - ) +/// What a reader says of the `n` of its `what` whose places convert from `crs` but come out beyond +/// longitude/latitude (their box there is, [`rustgis_geom::Extent::beyond_lonlat`]): the system +/// may not be theirs, and they may draw out of place. `None` for none. +pub(crate) fn beyond_lonlat_note(what: &str, n: usize, crs: Crs) -> Option { + let system = crs.label(); + (n > 0).then(|| { + if n == 1 { + format!("one of the {what} has coordinates that come out beyond longitude/latitude once converted from {system}: it may not be their coordinate system, and it may draw out of place") + } else { + format!("{n} {what} have coordinates that come out beyond longitude/latitude once converted from {system}: it may not be their coordinate system, and they may draw out of place") + } }) } @@ -1945,7 +1947,7 @@ impl Collector { let declared = declared_crs(root, &mut said)?; report.messages.extend(said); let (mut unconverted, mut placed) = (0usize, 0usize); - let mut placed_extent = rustgis_geom::Extent::EMPTY; + let mut beyond = 0usize; // Only features kept count toward the heights dropped. let mut zm = 0usize; // Features kept, as longitude/latitude, with a latitude past the poles. @@ -1957,7 +1959,7 @@ impl Collector { match places_lonlat_extent(g, t) { Some(e) => { placed += 1; - placed_extent = placed_extent.union(&e); + beyond += usize::from(e.beyond_lonlat()); } None => unconverted += 1, } @@ -1978,7 +1980,7 @@ impl Collector { ds.crs = Some(*crs); ds.held_in = *crs; report.messages.extend(kept_unplaced_note("features", unconverted, placed == 0, *crs)); - report.messages.extend(beyond_lonlat_note(&placed_extent, *crs)); + report.messages.extend(beyond_lonlat_note("features", beyond, *crs)); } report.messages.extend(swapped_latitude_note(swapped)); // Last, as a source read in place notes it. @@ -2980,18 +2982,18 @@ pub(crate) fn read_rows( // Kept as the file holds them, in its system; counted where they have no place in // longitude/latitude. ds.held_in = c; - let (mut lost, mut placed, mut placed_extent) = (0usize, 0usize, rustgis_geom::Extent::EMPTY); + let (mut lost, mut placed, mut beyond) = (0usize, 0usize, 0usize); for g in ds.features.iter().filter_map(|f| f.geometry.as_ref()) { match places_lonlat_extent(g, &t) { Some(e) => { placed += 1; - placed_extent = placed_extent.union(&e); + beyond += usize::from(e.beyond_lonlat()); } None => lost += 1, } } report.messages.extend(kept_unplaced_note("rows", lost, placed == 0, c)); - report.messages.extend(beyond_lonlat_note(&placed_extent, c)); + report.messages.extend(beyond_lonlat_note("rows", beyond, c)); } // Read as longitude/latitude as they are: no system given, or longitude/latitude itself. A // row a given system can't place is said above, as kept. diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index d7c12bb3d2..a066f25d8a 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -238,18 +238,18 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result { placed += 1; - placed_extent = placed_extent.union(&e); + beyond += usize::from(e.beyond_lonlat()); } None => lost += 1, } } rep.messages.extend(crate::io::kept_unplaced_note("features", lost, placed == 0, *c)); - rep.messages.extend(crate::io::beyond_lonlat_note(&placed_extent, *c)); + rep.messages.extend(crate::io::beyond_lonlat_note("features", beyond, *c)); } out.push((ds, rep)); } diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 3eabe84bbe..a05e98c395 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -559,7 +559,7 @@ impl Dataset { if to.is_identity() { return Ok(Vec::new()); } - let (mut unplaced, mut placed, mut extent) = (0usize, 0usize, Extent::EMPTY); + let (mut unplaced, mut placed, mut beyond) = (0usize, 0usize, 0usize); for (i, g) in self.features.rows().filter_map(RowRef::geometry).enumerate() { stop_when_asked(i)?; let (mut ok, mut e) = (true, Extent::EMPTY); @@ -570,13 +570,16 @@ impl Dataset { }); if ok { placed += 1; - extent = extent.union(&e); + beyond += usize::from(e.beyond_lonlat()); } else { unplaced += 1; } } let crs = self.coord_crs(); - Ok(io::kept_unplaced_note("features", unplaced, placed == 0, crs).into_iter().chain(io::beyond_lonlat_note(&extent, crs)).collect()) + Ok(io::kept_unplaced_note("features", unplaced, placed == 0, crs) + .into_iter() + .chain(io::beyond_lonlat_note("features", beyond, crs)) + .collect()) } /// [`Dataset::geometry_to_lonlat`] of `g`, feature `id`'s geometry, for an edit of that one diff --git a/crates/data/src/mapinfo.rs b/crates/data/src/mapinfo.rs index 63e627d5b8..cd144937be 100644 --- a/crates/data/src/mapinfo.rs +++ b/crates/data/src/mapinfo.rs @@ -444,14 +444,14 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe if let (Some(_), Some(c)) = (&t, crs) { ds.held_in = c; } - let (mut lost, mut placed, mut placed_extent, mut null_text) = (0usize, 0usize, rustgis_geom::Extent::EMPTY, Vec::new()); + let (mut lost, mut placed, mut beyond, mut null_text) = (0usize, 0usize, 0usize, Vec::new()); for (k, g) in geoms.into_iter().enumerate() { // Kept as the file holds it; counted when it has no place in longitude/latitude. if let (Some(t), Some(g)) = (&t, &g) { match crate::io::places_lonlat_extent(g, t) { Some(e) => { placed += 1; - placed_extent = placed_extent.union(&e); + beyond += usize::from(e.beyond_lonlat()); } None => lost += 1, } @@ -473,7 +473,7 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe } if let (Some(_), Some(c)) = (&t, crs) { report.messages.extend(crate::io::kept_unplaced_note("objects", lost, placed == 0, c)); - report.messages.extend(crate::io::beyond_lonlat_note(&placed_extent, c)); + report.messages.extend(crate::io::beyond_lonlat_note("objects", beyond, c)); } report.messages.extend(crate::source::null_text_note(&ds.fields, &null_text)); ds.geometry_type = crate::io::dominant_type(&ds); diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 10c7ee55b0..7d97e77ece 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -243,7 +243,7 @@ impl GeoJsonSource { let pass = convert_pass(&mut file, &scan.places, t)?; extent = pass.extent; notes.extend(crate::io::kept_unplaced_note("features", pass.unplaced, pass.placed == 0, crs)); - notes.extend(crate::io::beyond_lonlat_note(&pass.placed_extent, crs)); + notes.extend(crate::io::beyond_lonlat_note("features", pass.beyond, crs)); unplaced = pass.unplaced_at; } else { // Only coordinates read as they are can be longitude/latitude with the two swapped; @@ -512,7 +512,8 @@ struct Pass { /// [`crate::io::places_in_lonlat`]), and those it can, with their box there. unplaced: usize, placed: usize, - placed_extent: Extent, + /// Those of them whose places come out beyond longitude/latitude. + beyond: usize, /// Where the features with no place are, sorted. unplaced_at: Vec, /// The extent, in longitude/latitude, of every place that converts. @@ -523,7 +524,7 @@ struct Pass { fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transformer) -> Result { let mut f = BufReader::with_capacity(BUFFER, file); let (mut pos, mut buf) = (0u64, Vec::new()); - let mut pass = Pass { unplaced: 0, placed: 0, placed_extent: Extent::EMPTY, unplaced_at: Vec::new(), extent: Extent::EMPTY }; + let mut pass = Pass { unplaced: 0, placed: 0, beyond: 0, unplaced_at: Vec::new(), extent: Extent::EMPTY }; // Counted as a step of its own, a feature at a time every so many. crate::progress::begin(places.len()); for (i, place) in places.iter().enumerate() { @@ -547,7 +548,7 @@ fn convert_pass(file: &mut File, places: &[Place], t: &crate::raster::Transforme }); if all { pass.placed += 1; - pass.placed_extent = pass.placed_extent.union(&e); + pass.beyond += usize::from(e.beyond_lonlat()); } else { pass.unplaced += 1; pass.unplaced_at.push(i as u32); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index f41cd8f704..eefca58bfc 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -2959,7 +2959,7 @@ fn geojson_features_that_cant_be_converted_are_skipped_and_counted() { let expected = if crs == "EPSG:32617" { format!("one of the features has a place in {crs} that can't be given in longitude/latitude: it is kept as the file holds it") } else { - format!("coordinates are not longitude/latitude once converted from {crs}") + format!("coordinates that come out beyond longitude/latitude once converted from {crs}") }; assert!(messages.iter().any(|m| m.contains(&expected)), "{crs}: {messages:?}"); assert_eq!(info_crs, crs); @@ -2994,7 +2994,7 @@ fn geojson_kept_unplaced_features_set_the_geometry_type() { assert_eq!(ds.geometry_type, GeometryType::Point); assert!(ds.features.len() == 2 && !ds.crs_incomplete); assert_eq!(messages.len(), 1, "{messages:?}"); - assert!(messages[0].contains("coordinates are not longitude/latitude once converted from EPSG:3857"), "{}", messages[0]); + assert!(messages[0].contains("coordinates that come out beyond longitude/latitude once converted from EPSG:3857"), "{}", messages[0]); } #[test] diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index f46ac671fd..d7a9813459 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -1070,12 +1070,20 @@ fn load( // A feature with a place that can't be given in longitude/latitude // is kept as read, and counted: it doesn't draw (#2032 C2f-4b). Each // place is converted to be checked; the layer keeps its own. - let lost = ds - .features - .rows() - .filter_map(|r| r.geometry()) - .filter(|g| Dataset::converted_to_lonlat(&to, g).is_none()) - .count(); + let (mut lost, mut beyond) = (0usize, 0usize); + for g in ds.features.rows().filter_map(|r| r.geometry()) { + match Dataset::converted_to_lonlat(&to, g) { + Some(l) => beyond += usize::from(l.extent().beyond_lonlat()), + None => lost += 1, + } + } + if beyond > 0 { + let have = if beyond == 1 { "feature has" } else { "features have" }; + messages.push(format!( + "{layer_name}: {beyond} {have} coordinates that come out beyond longitude/latitude once converted from {}: it may not be their coordinate system, and they may draw out of place", + job.crs.label() + )); + } if lost > 0 { let have = if lost == 1 { "feature has" } else { "features have" }; messages.push(format!( From 921352657239dbfb0f2deb5614ef8b176428c03f Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 12:21:39 +0100 Subject: [PATCH 9/9] Review: Shapefile counts the shapes beyond longitude/latitude too; places_in_lonlat goes with its last caller; one wording (#2032 C2f-4b-2) --- crates/data/src/esripbf.rs | 2 +- crates/data/src/esripbf/tests.rs | 2 +- crates/data/src/filegdb.rs | 6 ++++- crates/data/src/filegdb/tests.rs | 2 +- crates/data/src/io.rs | 39 +++++++++++++------------------ crates/data/src/source/geojson.rs | 2 +- 6 files changed, 25 insertions(+), 28 deletions(-) diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 3b9e2ea4bc..2ac67bb072 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -185,7 +185,7 @@ impl Losses { (format!("{} features", self.beyond), "have", "they") }; out.push(format!( - "{count} {have} coordinates that come out beyond longitude/latitude once converted from the answer's coordinate system: it may not be theirs, and {they} may draw out of place" + "{count} {have} coordinates that come out beyond longitude/latitude once converted from the answer's coordinate system: it may not be their coordinate system, and {they} may draw out of place" )); } if self.with_zm > 0 { diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 2bcb0f7943..f2bb7fff22 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -263,7 +263,7 @@ fn coordinates_past_longitude_latitude_are_kept_and_the_layer_says_so() { assert_eq!( report.messages, [ - "one feature has coordinates that come out beyond longitude/latitude once converted from the answer's coordinate system: it may not be theirs, and it may draw out of place" + "one feature has coordinates that come out beyond longitude/latitude once converted from the answer's coordinate system: it may not be their coordinate system, and it may draw out of place" ] ); } diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index bd16f8de32..6d568cd336 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -441,7 +441,11 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 0 { report .messages - .push(format!("{unprojected} features have a place that can't be given in longitude/latitude (coordinates outside their coordinate system): they are kept as the file holds them, but don't draw")); + .push(if unprojected == 1 { + "one feature has a place that can't be given in longitude/latitude (coordinates outside its coordinate system): it is kept as the file holds it, but doesn't draw".to_string() + } else { + format!("{unprojected} features have a place that can't be given in longitude/latitude (coordinates outside their coordinate system): they are kept as the file holds them, but don't draw") + }); } if zm { // The table declares them for every shape. diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index c5aac188eb..a847ae4f05 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -558,7 +558,7 @@ fn coordinates_that_cant_be_converted_are_said() { assert!(rows[0].geometry.is_some() && rows[1].geometry.is_some(), "{:?}", rows[1].geometry); assert!(!ds.crs_incomplete); assert!( - report.messages.iter().any(|m| m.starts_with("1 features have a place that can't be given in longitude/latitude")), + report.messages.iter().any(|m| m.starts_with("one feature has a place that can't be given in longitude/latitude")), "{report:?}" ); } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 21b27cdae3..13b04eaf17 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1644,17 +1644,11 @@ pub(crate) fn is_epsg_or_crs84_name(name: &str) -> bool { up == "CRS84" || up == "OGC:CRS84" || up.strip_prefix("OGC:").and_then(|rest| tail(rest, ':')).is_some_and(|c| c == "CRS84") } -/// 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`]), either way, and counts those that don't ([`kept_unplaced_note`]). -/// 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. +/// The box in longitude/latitude of `g`'s places, in the system `t` converts: `None` when one of +/// them has no place there (none that is finite). A reader keeps the geometry as the file holds +/// it, held in its system ([`Dataset::held_in`]), either way, and counts those with none +/// ([`kept_unplaced_note`]) and those whose box comes out beyond longitude/latitude +/// ([`beyond_lonlat_note`]). Each coordinate is converted to be checked, none is kept. pub(crate) fn places_lonlat_extent(g: &Geometry, t: &crate::raster::Transformer) -> Option { let mut ok = true; let mut e = rustgis_geom::Extent::EMPTY; @@ -1954,7 +1948,7 @@ impl Collector { let mut swapped = 0usize; for (n, (geom, values, had_z)) in self.features.into_iter().enumerate() { // Kept as the file holds it, in its declared system, and counted when it has no place - // in longitude/latitude ([`places_in_lonlat`]), as when the file is read in place. + // in longitude/latitude ([`places_lonlat_extent`]), as when the file is read in place. if let (Some((_, t)), Some(g)) = (&declared, &geom) { match places_lonlat_extent(g, t) { Some(e) => { @@ -4014,7 +4008,7 @@ 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 beyond = 0usize; let mut counts = DbfCounts::new(ds.fields.len(), not_utf8, encoding); let mut source_kind = GeometryType::None; let pt = |x: f64, y: f64| Coord::new(x, y); @@ -4118,7 +4112,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio if let (Some(t), Some(g)) = (&to_lonlat, &geom) { let placed = places_lonlat_extent(g, t); if let Some(e) = &placed { - lonlat_extent = lonlat_extent.union(e); + beyond += usize::from(e.beyond_lonlat()); } converted += usize::from(placed.is_some()); unconverted += usize::from(placed.is_none()); @@ -4161,15 +4155,14 @@ 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; } - // 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.beyond_lonlat() { - 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" - } else { - "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place" - }); + // Beyond longitude/latitude: as the file's shapes come out there from the `.prj`'s system + // (one that doesn't match them), counted; or as they are without a system to convert from. + match ds.crs.filter(|_| to_lonlat.is_some()) { + Some(c) => report.messages.extend(beyond_lonlat_note("shapes", beyond, c)), + None if ds.extent().beyond_lonlat() => { + report.messages.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place") + } + None => {} } if report.skipped > 0 { report.messages.push(format!("{} shapes were unreadable or unsupported", report.skipped)); diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 7d97e77ece..cfb27f8bdb 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -509,7 +509,7 @@ fn read_place(f: &mut BufReader, pos: &mut u64, buf: &mut Vec< /// What a pass over a file's features converts to longitude/latitude finds. struct Pass { /// Features with geometry the transformer can't give in longitude/latitude (see - /// [`crate::io::places_in_lonlat`]), and those it can, with their box there. + /// [`crate::io::places_lonlat_extent`]), and those it can, with their box there. unplaced: usize, placed: usize, /// Those of them whose places come out beyond longitude/latitude.