Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 36 additions & 12 deletions crates/data/src/cityjson/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
57 changes: 35 additions & 22 deletions crates/data/src/citymodel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
pub(crate) crs: Option<Crs>,
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.
Expand Down Expand Up @@ -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);
Expand All @@ -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() {
Expand Down Expand Up @@ -975,7 +987,7 @@ fn layers(stem: &str, rows: Vec<Row>, 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR makes carried skip unconverted rows, but the drawn closure at line 1024 (not in the diff, so I'm anchoring here) still counts every row with a geometry. A kept-unplaced row keeps its geometry, so it is in drawn() while it is not in carried. standing at line 1028 is !drawn().all(|(_, b)| carried.contains(...)), so it can no longer be false whenever an unplaced object shares the group.

Failure scenario: a Building layer where object A is a multi-part volume carried by its parts, and object B is a volume with no lon/lat place. Before this PR, B had no geometry, drawn() was just A's parts, all carried, so standing was false. Now drawn() also contains B, which isn't carried, so standing becomes true and A is drawn differently because of an object that draws nothing.

Suggested fix, at line 1024: make drawn exclude unconverted rows, as carried does:

        let drawn = || rows.iter().filter(|(r, _)| r.geometry.is_some() && !r.unconverted);

Confidence: medium-high from reading the code; I haven't run a city model through it.

Category: bug

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 03a577f: drawn now leaves out unconverted rows too, matching carried, so an object kept with no place (which draws nothing) no longer decides whether its group stands.

.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))
Expand Down Expand Up @@ -1013,7 +1025,8 @@ fn layers(stem: &str, rows: Vec<Row>, 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))
Expand Down Expand Up @@ -1045,8 +1058,6 @@ fn layers(stem: &str, rows: Vec<Row>, 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) {
Expand Down Expand Up @@ -1155,10 +1166,12 @@ pub(crate) fn messages(c: &Counts) -> Vec<String> {
);
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),
Expand Down
56 changes: 30 additions & 26 deletions crates/data/src/dxf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1693,20 +1693,22 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result<Vec<(Datase
// What the drawing as a whole said goes with its first layer only.
let mut rep = if layers.is_empty() { report.clone() } else { ReadReport::default() };
if let Some((t, c)) = &transformer {
// Kept as the drawing holds them, in its system, where they have a place in
// Kept as the drawing holds them, in its system; counted where they have no place in
// longitude/latitude.
ds.held_in = *c;
let mut lost = 0usize;
for (f, varying) in ds.features.iter_mut().zip(&flags) {
let (mut lost, mut placed, mut beyond) = (0usize, 0usize, 0usize);
for (f, varying) in ds.features.iter().zip(&flags) {
crate::progress::check()?;
if let Some(g) = f.geometry.take() {
if crate::io::places_in_lonlat(&g, t) {
f.geometry = Some(g);
ds.zm_dropped |= *varying;
varying_count += usize::from(*varying);
} else {
lost += 1;
if let Some(g) = &f.geometry {
match crate::io::places_lonlat_extent(g, t) {
Some(e) => {
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 {
Expand All @@ -1715,9 +1717,8 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result<Vec<(Datase
}
}
ds.features.retain(|f| f.geometry.is_some());
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));
}
if transformer.is_none() {
for (_, loss) in losses {
Expand Down Expand Up @@ -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::<Vec<_>>()
.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]
Expand Down Expand Up @@ -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() {
Expand All @@ -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"))));
Expand Down Expand Up @@ -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::<Vec<_>>()
.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::<usize>(), 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::<usize>(), 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]
Expand Down
Loading
Loading