diff --git a/crates/data/src/cityjson/tests.rs b/crates/data/src/cityjson/tests.rs index 46e191736b..29b14558f1 100644 --- a/crates/data/src/cityjson/tests.rs +++ b/crates/data/src/cityjson/tests.rs @@ -625,27 +625,47 @@ 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]]; 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(); - assert!(out[0].0.crs_incomplete); - assert!(says(&out, "1 city objects have coordinates outside their coordinate system"), "{:?}", messages_of(&out)); + 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, "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 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::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: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 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. @@ -663,8 +683,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 coordinates outside their coordinate system"), "{:?}", 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 672a8906c2..da1ca68fb3 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -148,7 +148,12 @@ 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) 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 /// difference to be a number. @@ -567,18 +572,27 @@ 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 beyond = 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. + if let Some(g) = &row.geometry { + match crate::io::places_lonlat_extent(g, &to_lonlat) { + Some(e) => { + if e.beyond_lonlat() { + beyond.insert(row.object); + } + } + 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("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); @@ -591,15 +605,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 +987,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)) @@ -1013,7 +1025,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)) @@ -1045,8 +1058,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 +1166,12 @@ 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); + } + 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/dxf.rs b/crates/data/src/dxf.rs index 8aed10c6d9..3e96018c5d 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1693,20 +1693,22 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result { + placed += 1; + beyond += usize::from(e.beyond_lonlat()); + } + None => lost += 1, } + ds.zm_dropped |= *varying; + varying_count += usize::from(*varying); } } for (index, loss) in &losses { @@ -1715,9 +1717,8 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> 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)); + rep.messages.extend(crate::io::beyond_lonlat_note("features", beyond, *c)); } if transformer.is_none() { for (_, loss) in losses { @@ -2053,16 +2054,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 +2911,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 +2935,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 +3314,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..2ac67bb072 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -132,10 +132,13 @@ 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, + /// Places that convert to beyond longitude/latitude (the answer's system may not fit them). + pub beyond: usize, } impl Losses { @@ -148,6 +151,7 @@ impl Losses { self.flat_rings = self.flat_rings.saturating_add(other.flat_rings); self.unprojected = self.unprojected.saturating_add(other.unprojected); self.with_zm = self.with_zm.saturating_add(other.with_zm); + self.beyond = self.beyond.saturating_add(other.beyond); } /// What they say, one message per kind (as [`read`] says them). @@ -170,10 +174,20 @@ 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 )); } + if self.beyond > 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 their coordinate system, 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)))); } @@ -352,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) = (false, 0usize, 0usize); + 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))), @@ -360,16 +374,14 @@ 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) + // Kept as the answer holds it, in its own system; counted when it has no place in + // longitude/latitude. + if let (Some(g), Some(t)) = (&geometry, &to_lonlat) { + match crate::io::places_lonlat_extent(g, t) { + Some(e) => beyond += usize::from(e.beyond_lonlat()), + None => unprojected += 1, } - (g, _) => g, - }; + } ds.push_next(geometry, values); } if geometry_type.is_some() || any_geometry { @@ -380,8 +392,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(), @@ -390,6 +400,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 045da4bb64..f2bb7fff22 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,17 @@ 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 (#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, + [ + "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" + ] + ); } #[test] diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index a21ab43367..6d568cd336 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 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) + // 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) { + match crate::io::places_lonlat_extent(g, t) { + Some(e) => beyond += usize::from(e.beyond_lonlat()), + None => unprojected += 1, } - (g, _) => g, - }; + } ds.push_next(geometry, attrs); } let rounded: usize = rounded_dates.iter().sum(); @@ -436,10 +435,17 @@ 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 - .push(format!("{unprojected} features have coordinates outside their coordinate system: they are kept without geometry")); + .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 64be0f0044..a847ae4f05 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("one feature has 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..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 @@ -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,11 +683,13 @@ 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()); e = lonlat.get(); + // Converted, but beyond longitude/latitude: it draws out of place. + beyond += usize::from(!missing.get() && e.beyond_lonlat()); Some(kept) } (_, g) => { @@ -727,10 +730,13 @@ 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 )); } + 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"); } @@ -886,11 +892,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 +905,29 @@ 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); + } + + /// 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] diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index a48832343e..13b04eaf17 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1644,28 +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") } -/// 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. -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; @@ -1676,18 +1659,44 @@ 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 a step that needs longitude/latitude leaves them out and says +/// 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 { + (n > 0).then(|| { + if all { + format!( + "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 { + 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 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") + } + }) } /// What takes a FeatureCollection's features as they're read. @@ -1931,26 +1940,24 @@ 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); + 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. 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; + // Kept as the file holds it, in its declared system, and counted when it has no 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) => { + placed += 1; + beyond += usize::from(e.beyond_lonlat()); } - }, - (_, g) => g, - }; + None => unconverted += 1, + } + } 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 +1965,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 +1973,8 @@ 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(beyond_lonlat_note("features", beyond, *crs)); } report.messages.extend(swapped_latitude_note(swapped)); // Last, as a source read in place notes it. @@ -2974,24 +2973,25 @@ 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; + 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; + beyond += usize::from(e.beyond_lonlat()); } + None => lost += 1, } } - if lost > 0 { - report.skipped += lost; - report.messages.push(format!("{lost} rows couldn't be converted from {} to longitude/latitude", c.label())); - } + report.messages.extend(kept_unplaced_note("rows", lost, placed == 0, c)); + report.messages.extend(beyond_lonlat_note("rows", beyond, 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()?; @@ -4008,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); @@ -4107,19 +4107,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 { + beyond += usize::from(e.beyond_lonlat()); } - (_, 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 +4144,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); @@ -4158,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)); @@ -4176,11 +4172,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..a066f25d8a 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -235,22 +235,21 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result { + placed += 1; + beyond += usize::from(e.beyond_lonlat()); } + None => lost += 1, } } - if lost > 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)); + 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 172a85a687..a05e98c395 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -548,6 +548,40 @@ 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, + /// 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()) }; + if to.is_identity() { + return Ok(Vec::new()); + } + 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); + 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; + 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("features", beyond, 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/mapinfo.rs b/crates/data/src/mapinfo.rs index ae61655a6f..cd144937be 100644 --- a/crates/data/src/mapinfo.rs +++ b/crates/data/src/mapinfo.rs @@ -444,17 +444,18 @@ 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 beyond, mut null_text) = (0usize, 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) + // 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; + beyond += usize::from(e.beyond_lonlat()); + } + None => lost += 1, } - (_, g) => g, - }; + } let row = rows.get(k); let attrs = ds .fields @@ -470,8 +471,9 @@ 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::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/publish.rs b/crates/data/src/publish.rs index 285e3e6419..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 ))); } @@ -1517,9 +1519,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 +1532,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/arcgis.rs b/crates/data/src/source/arcgis.rs index 8846c68db0..5b484237bd 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), } } @@ -656,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 ff48277804..cfb27f8bdb 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; @@ -77,11 +76,12 @@ 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, + /// 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. @@ -231,26 +231,20 @@ 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; + let mut unplaced = Vec::new(); 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)); + 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; // a declared system's features were converted above, and those that don't fit left out. @@ -269,32 +263,42 @@ 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, + 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)| { @@ -303,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 && self.failed.binary_search(&(i as u32)).is_err()) + (i as u32, in_box && !(lonlat_view && self.unplaced.binary_search(&(i as u32)).is_ok())) }) } } @@ -325,12 +329,13 @@ 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 } - fn skipped_at_open(&self) -> usize { - self.unreadable + self.failed.len() + /// 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 { @@ -350,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; @@ -381,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 }; @@ -396,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) { @@ -450,18 +457,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)) => crate::io::places_lonlat_extent(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 +508,15 @@ 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 + /// [`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. + beyond: usize, + /// Where the features with no place are, sorted. + unplaced_at: Vec, + /// The extent, in longitude/latitude, of every place that converts. extent: Extent, } @@ -510,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 { failed: Vec::new(), dropped: [0; 3], 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() { @@ -521,14 +535,23 @@ 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; 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, + }); + if all { + pass.placed += 1; + 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/mod.rs b/crates/data/src/source/mod.rs index 5515bf546e..a28d59e468 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,12 @@ 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 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)) } @@ -1015,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(); @@ -1035,11 +1054,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 +1071,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 @@ -1409,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, 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 665e7d1807..eefca58bfc 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,17 @@ 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"); + // 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 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); - 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 +2982,66 @@ 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 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::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("coordinates that come out beyond longitude/latitude once converted from EPSG:3857"), "{}", 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)); + } +} + +#[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"); } } diff --git a/crates/data/src/unplaced_out_tests.rs b/crates/data/src/unplaced_out_tests.rs index 9cbf2d3620..5fde69ecac 100644 --- a/crates/data/src/unplaced_out_tests.rs +++ b/crates/data/src/unplaced_out_tests.rs @@ -147,3 +147,79 @@ 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 { + "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")), "{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("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/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 5920b2fe00..1551d8d067 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/engine/src/tests/unplaced_gp.rs b/crates/engine/src/tests/unplaced_gp.rs index 5b75569b45..745eaf625e 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 it")), "{:?}", 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..d7a9813459 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -1067,14 +1067,28 @@ 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 (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!( - "{layer_name}: {lost} features couldn't be converted to longitude/latitude and have no geometry" + "{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 8fb6e945c8..e7dcb5e48e 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 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. | @@ -787,6 +787,27 @@ 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; 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 layer is placed on the Earth. An EPSG or Esri code that comes with another body's WKT (in the WKT @@ -837,8 +858,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, 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.