From 8c46b8f31ffa5693209000d40706540c26308c27 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:57:55 -0600 Subject: [PATCH 01/61] feat(data): read AIXM 5.1/5.2 messages at an effective date (#2077) --- Cargo.lock | 1 + crates/data/Cargo.toml | 2 + crates/data/src/aixm.rs | 1754 ++++++++++++++++++++++++ crates/data/src/aixm/tests.rs | 512 +++++++ crates/data/src/gml.rs | 2 +- crates/data/src/lib.rs | 1 + crates/data/tests/data/donlon-aixm.xml | 1598 +++++++++++++++++++++ 7 files changed, 3869 insertions(+), 1 deletion(-) create mode 100644 crates/data/src/aixm.rs create mode 100644 crates/data/src/aixm/tests.rs create mode 100644 crates/data/tests/data/donlon-aixm.xml diff --git a/Cargo.lock b/Cargo.lock index d05d95d5f5..4fd5c79f55 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5269,6 +5269,7 @@ dependencies = [ "unicode-normalization", "ureq", "url", + "web-time", "webpki-roots", "weezl 0.2.1", "zstd 0.14.4", diff --git a/crates/data/Cargo.toml b/crates/data/Cargo.toml index d5e3d7bac6..5b0a890510 100644 --- a/crates/data/Cargo.toml +++ b/crates/data/Cargo.toml @@ -30,6 +30,8 @@ terrio-crs = { workspace = true } miniz_oxide = { workspace = true } roxmltree = { workspace = true } quick-xml = { workspace = true } +# The effective date of an AIXM message when none is given: today, in the browser too. +web-time = { workspace = true } # zstd, the usual compression of GeoParquet, compiles to WebAssembly like the GeoTIFF one above. parquet = { workspace = true, features = ["zstd"] } url = { workspace = true } diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs new file mode 100644 index 0000000000..9592aab91a --- /dev/null +++ b/crates/data/src/aixm.rs @@ -0,0 +1,1754 @@ +//! AIXM 5.1, 5.1.1 and 5.2: aeronautical information (airports, navaids, designated points, routes, +//! airspace, obstacles…) in an `AIXMBasicMessage`, read into a layer per feature kind. +//! +//! An AIXM feature is a series of time slices, each valid for a period. The reader builds each +//! feature's state at one effective date (today unless one is given), following the AIXM +//! Temporality Concept (EUROCONTROL/FAA, version 1.1, on the AIXM wiki): of the slices with the same +//! interpretation and sequence number, the highest correction number holds; a slice whose +//! `validTime` is empty (`nilReason="inapplicable"`) is canceled; the BASELINE in force at the date +//! is the feature's state, a PERMDELTA in force since it changes it, and the TEMPDELTAs in force at +//! the date overlay it, each property they hold replacing all of that property's values (`nil` +//! removing them). A validity period includes its start and excludes its end. Features not in force +//! at the date, withdrawn before it (`featureLifetime`) or with only changes and no state are left +//! out and counted. +//! +//! Geometry is the GML 3.2 the AIXM profile allows (OGC 12-028r1): points, curves of +//! `GeodesicString`, `Geodesic`, `LineStringSegment`, `Arc`, `ArcString`, `Circle`, +//! `ArcByCenterPoint` and `CircleByCenterPoint` segments, and surfaces of polygon patches. Arcs are +//! drawn as points along them on the WGS 84 ellipsoid, within a meter of the curve; a geodesic edge +//! longer than 10 km is drawn as points along the geodesic. `ArcByCenterPoint` angles follow the +//! AIXM coding guidance: in a latitude-first system (`urn:ogc:def:crs:EPSG::4326`) bearings +//! clockwise from true north, the arc running from the start angle to the end angle (clockwise when +//! the start is the smaller); in a longitude-first one (CRS84), counter-clockwise from east. +//! +//! A property's simple value is an attribute, with its unit (`_uom`) and, for a reference to +//! another feature, the identifier it names (`urn:uuid:` left off) and its title (`_title`). A +//! nested record isn't, and is counted. An airspace is drawn from its single BASE volume, or from +//! BASE and UNION volumes as the parts of one shape; one built by subtraction, intersection or from +//! other airspaces is kept without a shape and counted, not drawn wrong. A vertical structure gives a +//! row per part. Runways, runway directions and routes, which have no geometry of their own, are +//! tables; other kinds with nothing to draw are counted. +//! +//! The file is hostile: no DTD is read, members are parsed one at a time within the node and +//! namespace limits every XML reader has, and the points arcs and geodesics add are bounded by the +//! file's size. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use quick_xml::Reader; +use quick_xml::events::{BytesStart, Event}; +use roxmltree::{Document, Node, ParsingOptions}; +use rustgis_geom::Coord; + +use crate::{DataError, Dataset, Field, Geometry, GeometryType, ReadReport, Result, Value}; + +/// How much of a file is looked at to tell whether it is AIXM. +pub const HEAD_BYTES: usize = 64 * 1024; + +/// AIXM namespaces start with this (`http://www.aixm.aero/schema/5.1`, `…/5.1.1`, `…/5.2`, and +/// their `/message` namespaces). +const AIXM: &str = "http://www.aixm.aero/schema/5."; +const GML: &str = "http://www.opengis.net/gml/3.2"; +const XLINK: &str = "http://www.w3.org/1999/xlink"; +const XSI: &str = "http://www.w3.org/2001/XMLSchema-instance"; + +/// Most layers read from one file. +const MAX_LAYERS: usize = 64; +/// Most attribute columns of a layer. +const MAX_COLUMNS: usize = 500; +/// The farthest a drawn arc strays from the curve, in meters. +const ARC_TOLERANCE_M: f64 = 1.0; +/// Most points one arc or circle is drawn with. +const MAX_ARC_POINTS: usize = 3600; +/// The longest straight piece of a drawn geodesic, in meters. +const GEODESIC_STEP_M: f64 = 10_000.0; +/// Most points one geodesic edge is drawn with. +const MAX_GEODESIC_POINTS: usize = 1000; +/// Points arcs and geodesics may add whatever the file's size. +const MIN_ADDED_POINTS: usize = 1_000_000; +/// The longest radius read, in meters: past a quarter of the Earth's circumference no airspace +/// is drawn by its center. +const MAX_RADIUS_M: f64 = 10_000_000.0; + +/// Kinds with no geometry of their own read as tables. +const TABLE_KINDS: &[&str] = &["Runway", "RunwayDirection", "Route"]; + +/// Time-slice properties that describe the slice, not the feature. +const SLICE_PROPERTIES: &[&str] = + &["validTime", "interpretation", "sequenceNumber", "correctionNumber", "featureLifetime", "timeSliceMetadata", "featureMetadata"]; + +/// Geometry elements a property can hold (AIXM's and GML's). +const SHAPES: &[&str] = &["Point", "ElevatedPoint", "Curve", "ElevatedCurve", "Surface", "ElevatedSurface", "LineString", "Polygon"]; + +/// What a read is asked for. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Options { + /// The effective date: milliseconds since 1970-01-01 UTC. Today when `None`. + pub at: Option, +} + +impl Options { + /// Reads `"at"` as a date or date and time (`2026-01-15`, `2026-01-15T12:00Z`): UTC unless it + /// says its zone. + pub fn at_text(text: &str) -> std::result::Result { + crate::time::parse_text(text) + .map(|t| Options { at: Some(t) }) + .ok_or_else(|| format!("'{text}' isn't a date (an AIXM effective date is written like 2026-01-15 or 2026-01-15T12:00Z)")) + } +} + +/// Whether a file is an AIXM message, by its root: an `AIXMBasicMessage` in an AIXM 5 namespace. +pub fn looks_like_aixm(bytes: &[u8]) -> bool { + let head = String::from_utf8_lossy(bytes.get(..HEAD_BYTES).unwrap_or(bytes)); + let mut reader = Reader::from_str(head.trim_start_matches('\u{feff}')); + loop { + match reader.read_event() { + Ok(Event::Start(e) | Event::Empty(e)) => { + return e.local_name().into_inner() == "AIXMBasicMessage" && namespace_of(&e).is_some_and(|ns| ns.starts_with(AIXM)); + } + Ok(Event::Eof) | Err(_) => return false, + Ok(_) => {} + } + } +} + +/// The namespace an element's own prefix (or the default) is declared with on it. +fn namespace_of(e: &BytesStart) -> Option { + let name = e.name(); + let want = match name.prefix() { + Some(p) => format!("xmlns:{}", p.into_inner()), + None => "xmlns".to_string(), + }; + e.attributes().flatten().find(|a| a.key.into_inner() == want).map(|a| a.value.trim().to_string()) +} + +/// The milliseconds of now, UTC. +fn now_ms() -> f64 { + web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0.0, |d| d.as_millis() as f64) +} + +/// A date as notices write it. +fn date_text(t: f64) -> String { + crate::time::format(t, "YYYY-MM-DD HH:mm") + " UTC" +} + +// --------------------------------------------------------------------------------------------- +// Index: the members, found in one pass with no tree. +// --------------------------------------------------------------------------------------------- + +#[derive(Default)] +struct Index { + /// Each `hasMember`: where it starts and ends in the text. + members: Vec<(usize, usize)>, + /// The root's namespace declarations, written as attributes (` xmlns:x="…"`). + namespaces: String, + /// `hasMember`s that only point elsewhere (`xlink:href`), not followed. + links: usize, + /// Where the text stops being XML, when it does before the root ends. + broken_at: Option, +} + +impl Index { + fn of(file_name: &str, text: &str) -> Result { + let mut reader = Reader::from_str(text); + let mut index = Index::default(); + let (mut depth, mut rooted) = (0usize, false); + let mut member: Option = None; + loop { + let start = usize::try_from(reader.buffer_position()).unwrap_or(usize::MAX); + let event = match reader.read_event() { + Ok(e) => e, + Err(_) => { + index.broken_at = Some(usize::try_from(reader.error_position()).unwrap_or(start)); + break; + } + }; + let end = usize::try_from(reader.buffer_position()).unwrap_or(usize::MAX); + match event { + Event::Start(ref e) | Event::Empty(ref e) if depth == 0 => { + if rooted { + return Err(DataError::Format(format!("{file_name}: more than one root element"))); + } + rooted = true; + if e.local_name().into_inner() != "AIXMBasicMessage" || !namespace_of(e).is_some_and(|ns| ns.starts_with(AIXM)) { + return Err(DataError::Format(format!( + "{file_name}: not an AIXM message (an AIXMBasicMessage in an AIXM 5 namespace)" + ))); + } + index.namespaces = declarations(e); + // An empty message (``) has no members. + if matches!(event, Event::Empty(_)) { + break; + } + depth = 1; + } + Event::Start(e) => { + if depth == 1 && e.local_name().into_inner() == "hasMember" { + member = Some(start); + } + depth += 1; + } + Event::Empty(e) => { + if depth == 1 && e.local_name().into_inner() == "hasMember" { + index.links += usize::from(e.attributes().flatten().any(|a| a.key.local_name().into_inner() == "href")); + } + } + Event::End(_) => { + depth = depth.saturating_sub(1); + if depth == 1 + && let Some(s) = member.take() + { + index.members.push((s, end)); + } + if depth == 0 { + break; + } + } + Event::Eof => { + if rooted && depth > 0 { + index.broken_at = Some(text.len()); + } + break; + } + _ => {} + } + } + if !rooted { + return Err(DataError::Format(format!("{file_name}: not an AIXM message (no root element)"))); + } + Ok(index) + } +} + +/// An element's namespace declarations, as attributes to write on a wrapper. +fn declarations(e: &BytesStart) -> String { + let mut out = String::new(); + for a in e.attributes().flatten() { + let key = a.key.into_inner(); + if key == "xmlns" || key.starts_with("xmlns:") { + let value = &a.value; + let quote = if value.contains('"') { '\'' } else { '"' }; + out.push(' '); + out.push_str(&key); + out.push('='); + out.push(quote); + out.push_str(&value); + out.push(quote); + } + } + out +} + +// --------------------------------------------------------------------------------------------- +// Small tree helpers. +// --------------------------------------------------------------------------------------------- + +fn local<'a>(n: &Node<'a, '_>) -> &'a str { + n.tag_name().name() +} + +fn in_ns(n: &Node, ns: &str) -> bool { + n.tag_name().namespace().is_some_and(|x| x.starts_with(ns)) +} + +fn is_aixm(n: &Node) -> bool { + in_ns(n, AIXM) +} + +fn is_gml(n: &Node) -> bool { + n.tag_name().namespace() == Some(GML) +} + +fn elements<'a, 'i>(n: Node<'a, 'i>) -> impl Iterator> { + n.children().filter(Node::is_element) +} + +fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option> { + elements(n).find(|c| local(c) == name) +} + +fn text_of(n: &Node) -> String { + n.children().filter(|t| t.is_text()).filter_map(|t| t.text()).collect::().trim().to_string() +} + +fn is_nil(n: &Node) -> bool { + n.attribute((XSI, "nil")).is_some_and(|v| matches!(v.trim(), "true" | "1")) +} + +/// A date of a `gml:beginPosition`/`endPosition`/`timePosition`: `Ok(None)` for an open end +/// (`indeterminatePosition`, or empty), `Err` for one that isn't a date. +fn position(n: Option) -> std::result::Result, ()> { + let Some(n) = n else { return Ok(None) }; + let t = text_of(&n); + if t.is_empty() { + return if n.attribute("indeterminatePosition").is_some() { Ok(None) } else { Err(()) }; + } + crate::time::parse_text(&t).map(Some).ok_or(()) +} + +// --------------------------------------------------------------------------------------------- +// Time slices. +// --------------------------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Interpretation { + Baseline, + PermDelta, + TempDelta, + Snapshot, +} + +/// What a slice says of itself, and where it is. +#[derive(Clone, Debug)] +struct Slice { + member: usize, + feature: usize, + slice: usize, + kind: Interpretation, + sequence: u64, + correction: u64, + /// Valid from (included) and until (excluded); an instant for a PERMDELTA or SNAPSHOT. + begin: Option, + end: Option, + canceled: bool, + /// The feature's lifetime, when the slice says it. + lifetime: Option<(Option, Option)>, +} + +/// A feature's slices, read from any number of members. +struct Feature { + kind: String, + slices: Vec, +} + +/// What a feature is at the date. +enum State { + /// Built from these slices: the state, then the changes over it in order. + Use { base: Slice, changes: Vec, snapshot: bool, temporary: usize }, + /// Not in force at the date: its validity is all before or after it. + NotInForce, + /// Withdrawn by the date, or not yet created (`featureLifetime`). + OutsideLifetime, + /// Only changes (PERMDELTA, TEMPDELTA) and no state to apply them to. + NoState, + /// Every slice canceled. + Canceled, +} + +fn in_force(begin: Option, end: Option, t: f64) -> bool { + begin.is_none_or(|b| b <= t) && end.is_none_or(|e| t < e) +} + +/// Each feature's state at `t`. +fn state_at(slices: &[Slice], t: f64) -> State { + // Of slices alike in interpretation and sequence number, the highest correction holds (the + // later in the file on a tie). + let mut held: BTreeMap<(u8, u64), &Slice> = BTreeMap::new(); + for s in slices { + let key = (s.kind as u8, s.sequence); + match held.get(&key) { + Some(h) if h.correction > s.correction => {} + _ => { + held.insert(key, s); + } + } + } + let live: Vec<&Slice> = held.values().copied().filter(|s| !s.canceled).collect(); + if live.is_empty() { + return if slices.is_empty() { State::NoState } else { State::Canceled }; + } + let of = |k: Interpretation| live.iter().copied().filter(move |s| s.kind == k); + // The BASELINE in force; of several (which the concept doesn't allow), the latest started. + let base = of(Interpretation::Baseline) + .filter(|s| in_force(s.begin, s.end, t)) + .max_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); + let (base, snapshot) = match base { + Some(b) => (b, false), + None => { + let baselines = of(Interpretation::Baseline).count(); + // A SNAPSHOT is a state at its own instant: the one nearest before the date, else the + // earliest after it. + let snap = of(Interpretation::Snapshot) + .filter(|s| s.begin.is_none_or(|b| b <= t)) + .max_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN))) + .or_else(|| { + of(Interpretation::Snapshot).min_by(|a, b| a.begin.unwrap_or(f64::MAX).total_cmp(&b.begin.unwrap_or(f64::MAX))) + }); + match snap { + Some(s) if baselines == 0 => (s, true), + _ if baselines > 0 => return State::NotInForce, + _ => return State::NoState, + } + } + }; + // PERMDELTAs since the state began, up to the date, in order. + let mut changes: Vec = of(Interpretation::PermDelta) + .filter(|s| s.begin.is_none_or(|b| b <= t) && s.begin.is_some_and(|b| base.begin.is_none_or(|bb| b > bb))) + .cloned() + .collect(); + changes.sort_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); + // The feature's lifetime: the latest a slice in force says. + let lifetime = changes.iter().rev().find_map(|s| s.lifetime).or(base.lifetime); + if let Some((from, until)) = lifetime + && !in_force(from, until, t) + { + return State::OutsideLifetime; + } + let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).cloned().collect(); + temps.sort_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); + let temporary = temps.len(); + changes.extend(temps); + State::Use { base: base.clone(), changes, snapshot, temporary } +} + +/// What the first pass found wrong with a slice. +#[derive(Default)] +struct SliceTrouble { + /// Slices with no interpretation RustGIS knows. + unknown: usize, + /// Slices with dates that aren't dates. + dates: usize, +} + +/// A slice's own properties. +fn slice_of(s: Node, at: (usize, usize, usize), trouble: &mut SliceTrouble) -> Option { + let kind = match child(s, "interpretation").map(|n| text_of(&n)).as_deref() { + Some("BASELINE") => Interpretation::Baseline, + Some("PERMDELTA") => Interpretation::PermDelta, + Some("TEMPDELTA") => Interpretation::TempDelta, + Some("SNAPSHOT") => Interpretation::Snapshot, + _ => { + trouble.unknown += 1; + return None; + } + }; + let number = |name: &str| child(s, name).and_then(|n| text_of(&n).parse::().ok()).unwrap_or(0); + let (mut begin, mut end, mut canceled) = (None, None, false); + let mut bad = false; + if let Some(v) = child(s, "validTime") { + match elements(v).next() { + Some(p) if local(&p) == "TimePeriod" => { + begin = position(child(p, "beginPosition")).unwrap_or_else(|()| { + bad = true; + None + }); + end = position(child(p, "endPosition")).unwrap_or_else(|()| { + bad = true; + None + }); + } + Some(i) if local(&i) == "TimeInstant" => { + begin = position(child(i, "timePosition")).unwrap_or_else(|()| { + bad = true; + None + }); + } + Some(_) => bad = true, + // An empty validTime cancels the slice (`nilReason="inapplicable"`). + None => canceled = true, + } + } + let lifetime = child(s, "featureLifetime").and_then(|l| elements(l).find(|p| local(p) == "TimePeriod")).map(|p| { + let from = position(child(p, "beginPosition")).unwrap_or_else(|()| { + bad = true; + None + }); + let until = position(child(p, "endPosition")).unwrap_or_else(|()| { + bad = true; + None + }); + (from, until) + }); + if bad { + trouble.dates += 1; + return None; + } + Some(Slice { + member: at.0, + feature: at.1, + slice: at.2, + kind, + sequence: number("sequenceNumber"), + correction: number("correctionNumber"), + begin, + end, + canceled, + lifetime, + }) +} + +/// The features of a member (an `AIXMBasicMessage`'s `hasMember` holds one). +fn features_of<'a, 'i>(wrapper: Node<'a, 'i>) -> Vec> { + elements(wrapper).next().map(|m| elements(m).filter(is_aixm).collect()).unwrap_or_default() +} + +/// A feature's time slices, in order. +fn slices_of<'a, 'i>(feature: Node<'a, 'i>) -> Vec> { + elements(feature).filter(|c| local(c) == "timeSlice").filter_map(|t| elements(t).next()).collect() +} + +/// A feature's identifier: its `gml:identifier`, else its `gml:id`. +fn identifier(f: Node) -> Option { + let id = elements(f).find(|c| is_gml(c) && local(c) == "identifier").map(|n| text_of(&n)).filter(|t| !t.is_empty()); + id.or_else(|| f.attribute((GML, "id")).map(|s| s.trim().to_string())) +} + +// --------------------------------------------------------------------------------------------- +// Geometry. +// --------------------------------------------------------------------------------------------- + +/// How a geometry's coordinates are read. +#[derive(Clone, Copy)] +struct Axes { + /// Latitude first. + swap: bool, +} + +/// What reading shapes found, for a layer's notices. +#[derive(Default)] +struct ShapeNotes { + /// Features drawn with arcs or circles as points along them. + arcs: bool, + /// Features whose curves were drawn with fewer points than the tolerance needs: the file's + /// point budget ran out. + coarse: bool, + /// Features with Z or M values dropped. + zm: bool, + /// Curve segments of kinds the profile doesn't allow, drawn straight between their positions. + unread_segments: Vec, + /// Rings or patches left out (too few points, unreadable, a border given by reference). + rings_lost: usize, + /// Of those, borders given by a reference to another feature's curve. + referenced: usize, +} + +/// Reads shapes, adding at most `budget` points to the file's positions. +struct Shapes { + budget: usize, + /// A system other than longitude/latitude a geometry was in (not read). + other_system: Option, + /// Geometries with no `srsName`, read as `urn:ogc:def:crs:EPSG::4326`. + assumed_system: usize, + /// A geographic system other than WGS 84 a geometry was read in as if it were. + as_wgs84: Option, +} + +fn wrap180(d: f64) -> f64 { + let r = (d + 180.0).rem_euclid(360.0) - 180.0; + if r == -180.0 && d > 0.0 { 180.0 } else { r } +} + +/// `c` moved by whole turns of longitude to lie next to `near`. +fn next_to(c: Coord, near: f64) -> Coord { + Coord::new(near + wrap180(c.x - near), c.y) +} + +impl Shapes { + /// Takes up to `n` added points from the budget: how many may be added. + fn take(&mut self, n: usize, notes: &mut ShapeNotes) -> usize { + let k = n.min(self.budget); + if k < n { + notes.coarse = true; + } + self.budget -= k; + k + } + + /// The system a geometry is in: its own `srsName` or its nearest ancestor's. + fn axes(&mut self, g: Node) -> Option { + let Some(name) = g.ancestors().find_map(|a| a.attribute("srsName")).map(str::trim) else { + self.assumed_system += 1; + return Some(Axes { swap: true }); + }; + if crate::ogc::warp::is_crs84(name) { + return Some(Axes { swap: false }); + } + match crate::gml::srs(name).map(|(c, _)| c) { + Some(c) if c.is_geographic() => { + if c.epsg() != 4326 { + self.as_wgs84.get_or_insert_with(|| name.to_string()); + } + Some(Axes { swap: crate::gml::lat_first(name, c) }) + } + _ => { + self.other_system.get_or_insert_with(|| name.to_string()); + None + } + } + } + + /// The positions under a node (`pos`, `posList`, `pointProperty`'s point), in order, as lon/lat. + fn positions(n: Node, axes: Axes, notes: &mut ShapeNotes) -> Option> { + let mut out = Vec::new(); + for c in n.descendants().filter(|d| d.is_element() && is_gml(d) && matches!(local(d), "pos" | "posList")) { + let v: Vec = text_of(&c).split_whitespace().map(|t| t.parse().ok()).collect::>()?; + let one = local(&c) == "pos" && (2..=4).contains(&v.len()); + let dim: usize = c + .ancestors() + .find_map(|a| a.attribute("srsDimension")) + .and_then(|d| d.trim().parse().ok()) + .filter(|d| (2..=4).contains(d)) + .unwrap_or(if one { v.len() } else { 2 }); + if !v.len().is_multiple_of(dim) { + return None; + } + if dim > 2 && !v.is_empty() { + notes.zm = true; + } + for p in v.chunks(dim) { + let (a, b) = (*p.first()?, *p.get(1)?); + let c = if axes.swap { Coord::new(b, a) } else { Coord::new(a, b) }; + if !c.is_finite() || c.y.abs() > 90.0 { + return None; + } + out.push(c); + } + } + Some(out) + } + + /// A point geometry. + fn point(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { + let axes = self.axes(g)?; + Self::positions(g, axes, notes)?.first().map(|c| Geometry::Point(*c)) + } + + /// A curve (or line string) as one run of points. + fn curve(&mut self, g: Node, notes: &mut ShapeNotes) -> Option> { + let axes = self.axes(g)?; + let Some(segments) = elements(g).find(|c| is_gml(c) && local(c) == "segments") else { + // A LineString or LinearRing: its positions, straight. + let c = Self::positions(g, axes, notes)?; + return (c.len() >= 2).then_some(c); + }; + let mut out: Vec = Vec::new(); + for s in elements(segments) { + let mut part = self.segment(s, axes, notes)?; + // Each part's longitudes next to where the line is, across the antimeridian too. + if let Some(last) = out.last().copied() { + part = part.into_iter().map(|c| next_to(c, last.x)).collect(); + if part.first().is_some_and(|f| (f.x - last.x).abs() < 1e-12 && (f.y - last.y).abs() < 1e-12) { + part.remove(0); + } + } + out.extend(part); + } + (out.len() >= 2).then_some(out) + } + + /// One curve segment's points. + fn segment(&mut self, s: Node, axes: Axes, notes: &mut ShapeNotes) -> Option> { + match local(&s) { + "LineStringSegment" => Self::positions(s, axes, notes), + "GeodesicString" | "Geodesic" => { + let c = Self::positions(s, axes, notes)?; + Some(self.geodesic(&c, notes)) + } + "ArcByCenterPoint" | "CircleByCenterPoint" => { + notes.arcs = true; + self.arc_by_center(s, axes, notes) + } + "Arc" | "ArcString" | "Circle" => { + notes.arcs = true; + let c = Self::positions(s, axes, notes)?; + Some(self.arcs_through(&c, local(&s) == "Circle", notes)) + } + other => { + if !notes.unread_segments.iter().any(|n| n == other) { + notes.unread_segments.push(other.to_string()); + } + Self::positions(s, axes, notes) + } + } + } + + /// A run of positions joined by geodesics on WGS 84, a point every [`GEODESIC_STEP_M`] at most. + fn geodesic(&mut self, c: &[Coord], notes: &mut ShapeNotes) -> Vec { + let mut out: Vec = Vec::with_capacity(c.len()); + for pair in c.windows(2) { + let (Some(&a), Some(&b)) = (pair.first(), pair.get(1)) else { continue }; + let a = out.last().map_or(a, |l| next_to(a, l.x)); + if out.is_empty() { + out.push(a); + } + let (d, az, _) = rustgis_geom::wgs84_inverse(a, b); + if d.is_finite() && d > GEODESIC_STEP_M { + let want = ((d / GEODESIC_STEP_M).ceil() as usize).min(MAX_GEODESIC_POINTS); + let n = self.take(want.saturating_sub(1), notes) + 1; + for k in 1..n { + let (p, _) = rustgis_geom::wgs84_direct(a, az, d * k as f64 / n as f64); + if p.is_finite() { + out.push(next_to(p, a.x)); + } + } + } + out.push(next_to(b, a.x)); + } + if c.len() == 1 + && let Some(&a) = c.first() + { + out.push(a); + } + out + } + + /// How many pieces an arc of `radius_m` turning `sweep_deg` is drawn with. + fn pieces(&mut self, radius_m: f64, sweep_deg: f64, notes: &mut ShapeNotes) -> usize { + let step = if radius_m <= ARC_TOLERANCE_M { 90.0 } else { (2.0 * (1.0 - ARC_TOLERANCE_M / radius_m).acos()).to_degrees() }; + let want = ((sweep_deg.abs() / step.max(1e-6)).ceil() as usize).clamp(4, MAX_ARC_POINTS); + self.take(want - 1, notes) + 1 + } + + /// An `ArcByCenterPoint` or `CircleByCenterPoint`. + fn arc_by_center(&mut self, s: Node, axes: Axes, notes: &mut ShapeNotes) -> Option> { + let center = *Self::positions(s, axes, notes)?.first()?; + let r = child(s, "radius")?; + let radius = text_of(&r).parse::().ok()? * meters_per(r.attribute("uom").unwrap_or("m"))?; + if !(radius.is_finite() && radius > 0.0 && radius <= MAX_RADIUS_M) { + return None; + } + let angle = |name: &str| -> Option> { + match child(s, name) { + None => Some(None), + Some(a) => { + let v = text_of(&a).parse::().ok()?; + let v = match a.attribute("uom").map(str::trim) { + None | Some("deg") => v, + Some("rad") => v.to_degrees(), + Some(_) => return None, + }; + v.is_finite().then_some(Some(v)) + } + } + }; + let (start, end) = (angle("startAngle")?.unwrap_or(0.0), angle("endAngle")?); + // Angles from the first axis: in a latitude-first system bearings from north, clockwise as + // they grow; in a longitude-first one from east, counter-clockwise. + let (bearing0, sweep) = match (local(&s), end) { + ("CircleByCenterPoint", _) => (if axes.swap { start } else { 90.0 - start }, 360.0), + (_, Some(end)) if (end - start).abs() < 360.0 => { + let d = end - start; + if axes.swap { (start, d) } else { (90.0 - start, -d) } + } + _ => return None, + }; + let n = self.pieces(radius, sweep, notes); + let mut out = Vec::with_capacity(n + 1); + for k in 0..=n { + let (p, _) = rustgis_geom::wgs84_direct(center, bearing0 + sweep * k as f64 / n as f64, radius); + if !p.is_finite() { + return None; + } + out.push(next_to(p, center.x)); + } + Some(out) + } + + /// Arcs through each three points (`Arc`, `ArcString`: start, a point on it, end; the next arc + /// starting at the last's end), or a full circle through three (`Circle`). + fn arcs_through(&mut self, c: &[Coord], circle: bool, notes: &mut ShapeNotes) -> Vec { + if c.len() < 3 { + return c.to_vec(); + } + let mut out: Vec = Vec::new(); + let mut i = 0; + while let (Some(&a), Some(&m), Some(&b)) = (c.get(i), c.get(i + 1), c.get(i + 2)) { + let arc = self.arc_through(a, m, b, circle, notes); + let skip = usize::from(!out.is_empty()); + out.extend(arc.into_iter().skip(skip)); + if circle { + break; + } + i += 2; + } + out + } + + /// The arc from `a` through `m` to `b`, worked out in an azimuthal equidistant plane around `m` + /// (distances true from it); straight when the three are in a line. + fn arc_through(&mut self, a: Coord, m: Coord, b: Coord, circle: bool, notes: &mut ShapeNotes) -> Vec { + let plane = rustgis_geom::Aeqd::new(m); + let (pa, pm, pb) = (plane.forward(next_to(a, m.x)), plane.forward(m), plane.forward(next_to(b, m.x))); + let d = 2.0 * (pa.x * (pm.y - pb.y) + pm.x * (pb.y - pa.y) + pb.x * (pa.y - pm.y)); + let straight = vec![a, m, b]; + if !d.is_finite() || d.abs() < 1e-9 { + return straight; + } + let sq = |p: Coord| p.x * p.x + p.y * p.y; + let ux = (sq(pa) * (pm.y - pb.y) + sq(pm) * (pb.y - pa.y) + sq(pb) * (pa.y - pm.y)) / d; + let uy = (sq(pa) * (pb.x - pm.x) + sq(pm) * (pa.x - pb.x) + sq(pb) * (pm.x - pa.x)) / d; + let r = (pa.x - ux).hypot(pa.y - uy); + if !r.is_finite() || r > MAX_RADIUS_M { + return straight; + } + let ang = |p: Coord| (p.y - uy).atan2(p.x - ux); + // Counter-clockwise when a → m → b turns left. + let ccw = (pm.x - pa.x) * (pb.y - pm.y) - (pm.y - pa.y) * (pb.x - pm.x) > 0.0; + let a0 = ang(pa); + let tau = std::f64::consts::TAU; + let sweep = if circle { + if ccw { tau } else { -tau } + } else { + let s = (ang(pb) - a0).rem_euclid(tau); + if ccw { s } else { s - tau } + }; + let n = self.pieces(r, sweep.to_degrees(), notes); + (0..=n) + .map(|k| { + let t = a0 + sweep * k as f64 / n as f64; + next_to(plane.inverse(Coord::new(ux + r * t.cos(), uy + r * t.sin())), m.x) + }) + .collect() + } + + /// A ring: a `gml:Ring` of curve members, or a `gml:LinearRing`; closed. + fn ring(&mut self, boundary: Node, notes: &mut ShapeNotes) -> Option> { + let r = elements(boundary).next()?; + let mut pts: Vec = match local(&r) { + "LinearRing" => { + let axes = self.axes(r)?; + Self::positions(r, axes, notes)? + } + "Ring" => { + let mut out: Vec = Vec::new(); + for m in elements(r).filter(|c| local(c) == "curveMember") { + let Some(c) = elements(m).next() else { + if m.attribute((XLINK, "href")).is_some() { + notes.referenced += 1; + } + return None; + }; + let mut part = self.curve(c, notes)?; + if let Some(last) = out.last().copied() { + part = part.into_iter().map(|p| next_to(p, last.x)).collect(); + if part.first().is_some_and(|f| (f.x - last.x).abs() < 1e-12 && (f.y - last.y).abs() < 1e-12) { + part.remove(0); + } + } + out.extend(part); + } + out + } + _ => return None, + }; + let first = *pts.first()?; + if pts.last().is_none_or(|l| (l.x - first.x).abs() > 1e-9 || (l.y - first.y).abs() > 1e-9) { + pts.push(first); + } else if let Some(l) = pts.last_mut() { + *l = first; + } + (pts.len() >= 4).then_some(pts) + } + + /// A surface's polygon patches (or a polygon): each its exterior and interiors. + fn surface(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { + let patches: Vec = if local(&g) == "Polygon" { + vec![g] + } else { + g.descendants().filter(|d| d.is_element() && is_gml(d) && matches!(local(d), "PolygonPatch" | "Polygon")).collect() + }; + let mut polys = Vec::new(); + for p in patches { + let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, notes)); + let Some(outer) = outer else { + notes.rings_lost += 1; + continue; + }; + let mut rings = vec![outer]; + for b in elements(p).filter(|c| local(c) == "interior") { + match self.ring(b, notes) { + Some(r) => rings.push(r), + None => notes.rings_lost += 1, + } + } + polys.push(rings); + } + (!polys.is_empty()).then_some(Geometry::Polygon(polys)) + } + + /// A geometry element (AIXM's or GML's) as a geometry. + fn shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { + match local(&g) { + "Point" | "ElevatedPoint" => self.point(g, notes), + "Curve" | "ElevatedCurve" | "LineString" => self.curve(g, notes).map(|c| Geometry::Line(vec![c])), + "Surface" | "ElevatedSurface" | "Polygon" => self.surface(g, notes), + _ => None, + } + } +} + +/// Metres in one of a length's units: UCUM's (`m`, `km`, `[nmi_i]`, `[ft_i]`, `[mi_i]`) and AIXM's +/// (`M`, `KM`, `NM`, `FT`, `MI`). +fn meters_per(uom: &str) -> Option { + Some(match uom.trim() { + "m" | "M" => 1.0, + "km" | "KM" => 1000.0, + "[nmi_i]" | "NM" | "nmi" => 1852.0, + "[ft_i]" | "FT" | "ft" => 0.3048, + "[mi_i]" | "MI" | "mi" => 1609.344, + _ => return None, + }) +} + +/// A property's geometry element, when it holds one. +fn shape_in<'a, 'i>(p: Node<'a, 'i>) -> Option> { + elements(p).find(|c| (is_aixm(c) || is_gml(c)) && SHAPES.contains(&local(c))) +} + +// --------------------------------------------------------------------------------------------- +// Rows and layers. +// --------------------------------------------------------------------------------------------- + +/// The first few distinct names a notice counts; more are said as `…`. +#[derive(Default)] +struct Names(Vec, bool); + +impl Names { + fn add(&mut self, p: &str) { + if !self.0.iter().any(|n| n == p) { + if self.0.len() < 3 { + self.0.push(p.to_string()); + } else { + self.1 = true; + } + } + } + fn said(&self) -> String { + self.0.join(", ") + if self.1 { ", …" } else { "" } + } +} + +/// A row's values by column; a column with no value is null. +type Attrs = BTreeMap; + +/// A layer being read. +#[derive(Default)] +struct Layer { + kind: String, + label: String, + columns: Vec, + rows: Vec<(Option, Attrs)>, + /// Properties not read (nested records): how many features had them, and the first names. + nested: usize, + nested_names: Names, + /// Values of properties past the column cap. + capped: usize, + /// Features kept without a shape: no geometry, or one that couldn't be read. + shapeless: usize, + unreadable: usize, + arcs: usize, + coarse: usize, + zm: usize, + unread_segments: Names, + approximated: usize, + rings_lost: usize, + referenced: usize, + /// Airspaces kept without a shape: built from other airspace or by subtraction/intersection. + derived: usize, + derived_names: Names, + /// Airspaces drawn as the parts of BASE and UNION volumes. + unions: usize, + /// Features as a TEMPDELTA changed them. + temporary: usize, + snapshots: usize, +} + +impl Layer { + fn column(&mut self, name: &str) -> bool { + if self.columns.iter().any(|c| c == name) { + return true; + } + if self.columns.len() >= MAX_COLUMNS { + self.capped += 1; + return false; + } + self.columns.push(name.to_string()); + true + } + + fn take_notes(&mut self, n: &ShapeNotes) { + self.arcs += usize::from(n.arcs); + self.coarse += usize::from(n.coarse); + self.zm += usize::from(n.zm); + if !n.unread_segments.is_empty() { + self.approximated += 1; + for s in &n.unread_segments { + self.unread_segments.add(s); + } + } + self.rings_lost += n.rings_lost; + self.referenced += n.referenced; + } +} + +/// A row being built: its values, and the nested properties not read. +#[derive(Default, Clone)] +struct Row { + attrs: Attrs, + /// Every column named, null or not, in order. + columns: Vec, + nested: Vec, +} + +impl Row { + fn set(&mut self, key: &str, value: String) { + if !self.columns.iter().any(|c| c == key) { + self.columns.push(key.to_string()); + } + match self.attrs.get_mut(key) { + // A property given more than once keeps every value. + Some(v) if !value.is_empty() => { + v.push_str("; "); + v.push_str(&value); + } + Some(_) => {} + None => { + self.attrs.insert(key.to_string(), value); + } + } + } + + fn null(&mut self, key: &str) { + if !self.columns.iter().any(|c| c == key) { + self.columns.push(key.to_string()); + } + } + + /// A property's simple value as attributes, under `prefix`. + fn property(&mut self, p: Node, prefix: &str) { + let name = format!("{prefix}{}", local(&p)); + if is_nil(&p) { + self.null(&name); + return; + } + if let Some(href) = p.attribute((XLINK, "href")) { + let id = href.trim(); + let id = id.strip_prefix("urn:uuid:").or_else(|| id.strip_prefix('#')).unwrap_or(id); + self.set(&name, id.to_string()); + if let Some(t) = p.attribute((XLINK, "title")) { + self.set(&format!("{name}_title"), t.trim().to_string()); + } + return; + } + if elements(p).next().is_some() { + if !self.nested.contains(&name) { + self.nested.push(name); + } + return; + } + self.set(&name, text_of(&p)); + if let Some(u) = p.attribute("uom") { + self.set(&format!("{name}_uom"), u.trim().to_string()); + } + } + + /// The simple values written on a geometry element (an `ElevatedPoint`'s elevation and datum, + /// a point's accuracy), each under its own name or, where the row has that name, the + /// property's. + fn shape_values(&mut self, g: Node, property: &str) { + for c in elements(g).filter(is_aixm) { + let prefix = if self.columns.iter().any(|k| k == local(&c)) { format!("{property}_") } else { String::new() }; + self.property(c, &prefix); + } + } +} + +/// The layers of a file in the order their kinds were first met. +#[derive(Default)] +struct Layers { + by_key: HashMap<(String, String), usize>, + list: Vec, + /// Features of kinds past [`MAX_LAYERS`]. + over: usize, +} + +impl Layers { + fn get(&mut self, kind: &str, label: &str) -> Option<&mut Layer> { + let key = (kind.to_string(), label.to_string()); + let i = match self.by_key.get(&key) { + Some(&i) => i, + None if self.list.len() >= MAX_LAYERS => { + self.over += 1; + return None; + } + None => { + self.list.push(Layer { kind: kind.to_string(), label: label.to_string(), ..Layer::default() }); + self.by_key.insert(key, self.list.len() - 1); + self.list.len() - 1 + } + }; + self.list.get_mut(i) + } + + fn has_kind(&self, kind: &str) -> bool { + self.list.iter().any(|l| l.kind == kind) + } + + fn push(&mut self, kind: &str, label: &str, geometry: Option, row: Row, notes: Option<&ShapeNotes>) { + let Some(layer) = self.get(kind, label) else { return }; + let mut attrs = Attrs::new(); + for c in &row.columns { + if layer.column(c) + && let Some(v) = row.attrs.get(c) + { + attrs.insert(c.clone(), v.clone()); + } + } + if !row.nested.is_empty() { + layer.nested += 1; + for n in &row.nested { + layer.nested_names.add(n); + } + } + if let Some(n) = notes { + layer.take_notes(n); + } + layer.rows.push((geometry, attrs)); + } +} + +/// A family label for a geometry. +fn family(g: &Geometry) -> &'static str { + match g { + Geometry::Point(_) | Geometry::MultiPoint(_) => "points", + Geometry::Line(_) => "lines", + Geometry::Polygon(_) => "polygons", + } +} + +/// Geometries of one family as one. +fn merged(gs: Vec) -> Option { + let mut it = gs.into_iter(); + let first = it.next()?; + Some(it.fold(first, |acc, g| match (acc, g) { + (Geometry::Point(a), Geometry::Point(b)) => Geometry::MultiPoint(vec![a, b]), + (Geometry::Point(a), Geometry::MultiPoint(mut b)) => { + b.insert(0, a); + Geometry::MultiPoint(b) + } + (Geometry::MultiPoint(mut a), Geometry::Point(b)) => { + a.push(b); + Geometry::MultiPoint(a) + } + (Geometry::MultiPoint(mut a), Geometry::MultiPoint(b)) => { + a.extend(b); + Geometry::MultiPoint(a) + } + (Geometry::Line(mut a), Geometry::Line(b)) => { + a.extend(b); + Geometry::Line(a) + } + (Geometry::Polygon(mut a), Geometry::Polygon(b)) => { + a.extend(b); + Geometry::Polygon(a) + } + (acc, _) => acc, + })) +} + +/// How each member is parsed: no DTD, and the node limit every XML reader has. +fn options<'a>() -> ParsingOptions<'a> { + ParsingOptions { allow_dtd: false, nodes_limit: crate::io::XML_NODES, ..ParsingOptions::default() } +} + +/// A slice's properties of the feature (not those describing the slice). +fn own<'a, 'i>(n: Node<'a, 'i>) -> Vec> { + elements(n).filter(|p| !SLICE_PROPERTIES.contains(&local(p))).collect() +} + +/// The shape of an airspace volume's horizontal projection. +fn projection<'a, 'i>(v: Option>) -> Option> { + v.and_then(|v| child(v, "horizontalProjection")).and_then(shape_in) +} + +/// What the read says of the file as a whole. +#[derive(Default)] +struct FileNotes { + not_in_force: usize, + outside_lifetime: usize, + no_state: usize, + canceled: usize, + unreadable_members: usize, + unknown_interpretation: usize, + bad_dates: usize, + no_slices: usize, + /// Features of kinds with nothing to draw, left out. + nothing_to_draw: usize, + nothing_names: Names, + other_system: Option, + assumed_system: usize, + as_wgs84: Option, +} + +/// Reads an AIXM message into a layer per feature kind (and per geometry property, for kinds with +/// several), at the effective date `opts.at` (today when not given). Cancel is looked at between +/// members; finding them first is one pass over the text without a look. +pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result> { + let max = crate::io::max_bytes(); + if bytes.len() as u64 > max { + return Err(DataError::Format(crate::io::file_size_error(file_name, max))); + } + let text = match std::str::from_utf8(bytes) { + Ok(t) => t, + // A file cut inside a character is read up to it. + Err(e) if e.error_len().is_none() => std::str::from_utf8(bytes.get(..e.valid_up_to()).unwrap_or_default()).unwrap_or_default(), + Err(_) => return Err(DataError::Format(format!("{file_name} is not UTF-8 text"))), + }; + let text = text.trim_start_matches('\u{feff}'); + let stem = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("AIXM").to_string(); + let at = opts.at.filter(|t| t.is_finite()).unwrap_or_else(now_ms); + let index = Index::of(file_name, text)?; + if index.members.is_empty() { + return Err(DataError::Format(format!("{file_name}: no features (hasMember elements) in the AIXM message"))); + } + let mut work_left = crate::xml::namespace_budget(text.len()); + let wrap = |member: &str, out: &mut String| { + out.clear(); + out.push_str("'); + out.push_str(member); + out.push_str(""); + }; + let mut notes = FileNotes::default(); + // First pass: each feature's slices, a member at a time. + let mut features: HashMap = HashMap::new(); + let mut order: Vec = Vec::new(); + let mut trouble = SliceTrouble::default(); + crate::progress::begin(index.members.len() * 2); + for (m, &(start, end)) in index.members.iter().enumerate() { + crate::progress::step(1)?; + let Some(member) = text.get(start..end) else { + notes.unreadable_members += 1; + continue; + }; + let mut wrapped = String::new(); + wrap(member, &mut wrapped); + let Ok(doc) = crate::xml::parse_within(&wrapped, options(), &mut work_left) else { + notes.unreadable_members += 1; + continue; + }; + for (fi, f) in features_of(doc.root_element()).into_iter().enumerate() { + let id = identifier(f).unwrap_or_else(|| format!("#{m}.{fi}")); + let slices: Vec = + slices_of(f).into_iter().enumerate().filter_map(|(si, s)| slice_of(s, (m, fi, si), &mut trouble)).collect(); + let entry = features.entry(id.clone()).or_insert_with(|| { + order.push(id.clone()); + Feature { kind: local(&f).to_string(), slices: Vec::new() } + }); + entry.slices.extend(slices); + } + } + notes.unknown_interpretation = trouble.unknown; + notes.bad_dates = trouble.dates; + // Second pass: each feature in force at the date, from its slices. + let mut layers = Layers::default(); + let mut shapes = Shapes { budget: text.len().max(MIN_ADDED_POINTS), other_system: None, assumed_system: 0, as_wgs84: None }; + // Rows of features with nothing to draw, by kind, kept until it is known whether the kind has + // a layer to hold them. + let mut shapeless: Vec<(String, Row, usize, bool)> = Vec::new(); + crate::progress::begin(index.members.len() + order.len()); + crate::progress::step(index.members.len())?; + for id in &order { + crate::progress::step(1)?; + let Some(feature) = features.get(id) else { continue }; + if feature.slices.is_empty() { + notes.no_slices += 1; + continue; + } + let (base, changes, snapshot, temporary) = match state_at(&feature.slices, at) { + State::Use { base, changes, snapshot, temporary } => (base, changes, snapshot, temporary), + State::NotInForce => { + notes.not_in_force += 1; + continue; + } + State::OutsideLifetime => { + notes.outside_lifetime += 1; + continue; + } + State::NoState => { + notes.no_state += 1; + continue; + } + State::Canceled => { + notes.canceled += 1; + continue; + } + }; + // The members holding its slices, each parsed again. + let mut wanted: Vec = std::iter::once(base.member).chain(changes.iter().map(|s| s.member)).collect(); + wanted.sort_unstable(); + wanted.dedup(); + let texts: Vec<(usize, String)> = wanted + .iter() + .filter_map(|&m| { + let (s, e) = *index.members.get(m)?; + let mut w = String::new(); + wrap(text.get(s..e)?, &mut w); + Some((m, w)) + }) + .collect(); + let mut docs: Vec<(usize, Document)> = Vec::new(); + for (m, w) in &texts { + match crate::xml::parse_within(w, options(), &mut work_left) { + Ok(d) => docs.push((*m, d)), + Err(_) => notes.unreadable_members += 1, + } + } + let find = |s: &Slice| -> Option { + let (_, doc) = docs.iter().find(|(m, _)| *m == s.member)?; + let f = *features_of(doc.root_element()).get(s.feature)?; + slices_of(f).get(s.slice).copied() + }; + let Some(base_node) = find(&base) else { + notes.unreadable_members += 1; + continue; + }; + // The state's properties, each change's replacing all values of the properties it holds. + let mut props = own(base_node); + for c in &changes { + let Some(n) = find(c) else { continue }; + let theirs = own(n); + let names: HashSet<&str> = theirs.iter().map(|p| local(p)).collect(); + props.retain(|p| !names.contains(local(p))); + props.extend(theirs); + } + let mut row = Row::default(); + row.set("identifier", id.trim_start_matches("urn:uuid:").to_string()); + let valid = |t: Option| t.map(|t| crate::time::format(t, "YYYY-MM-DDTHH:mm:ss") + "Z"); + match valid(base.begin) { + Some(v) => row.set("validFrom", v), + None => row.null("validFrom"), + } + match valid(base.end).filter(|_| !snapshot) { + Some(v) => row.set("validTo", v), + None => row.null("validTo"), + } + let kind = feature.kind.as_str(); + let mut fnotes = ShapeNotes::default(); + let placed = match kind { + "Airspace" => airspace(&props, &mut row, &mut shapes, &mut fnotes, &mut layers, kind, temporary, snapshot), + "VerticalStructure" => vertical_structure(&props, &row, &mut shapes, &mut layers, kind, temporary, snapshot), + _ => feature_rows(&props, &mut row, &mut shapes, &mut layers, kind, temporary, snapshot), + }; + if !placed { + shapeless.push((kind.to_string(), row, temporary, snapshot)); + } + } + // Features with nothing to draw: in their kind's layer when it has one, as a table for the + // kinds that are tables, else counted. + for (kind, row, temporary, snapshot) in shapeless { + if TABLE_KINDS.contains(&kind.as_str()) { + layers.push(&kind, "", None, row, None); + mark(&mut layers, &kind, "", temporary, snapshot); + } else if layers.has_kind(&kind) { + let label = layers.list.iter().find(|l| l.kind == kind).map(|l| l.label.clone()).unwrap_or_default(); + layers.push(&kind, &label, None, row, None); + if let Some(l) = layers.get(&kind, &label) { + l.shapeless += 1; + l.temporary += usize::from(temporary > 0); + l.snapshots += usize::from(snapshot); + } + } else { + notes.nothing_to_draw += 1; + notes.nothing_names.add(&kind); + } + } + notes.other_system = shapes.other_system.take(); + notes.as_wgs84 = shapes.as_wgs84.take(); + notes.assumed_system = shapes.assumed_system; + finish(&stem, at, layers, notes, &index, shapes.budget == 0) +} + +/// Adds a feature's rows: a row in a layer for each property holding a shape, or, when none does, +/// one of the shapes nested in its records by family. False when it has nothing to draw. +fn feature_rows( + props: &[Node], + row: &mut Row, + shapes: &mut Shapes, + layers: &mut Layers, + kind: &str, + temporary: usize, + snapshot: bool, +) -> bool { + let mut shaped: Vec<(String, Node)> = Vec::new(); + for p in props { + match shape_in(*p) { + Some(g) if !is_nil(p) => shaped.push((local(p).to_string(), g)), + _ => row.property(*p, ""), + } + } + if shaped.is_empty() { + // Shapes nested in records (a marking's elements, a light system's lights): by family. + let mut by_family: BTreeMap<&'static str, Vec> = BTreeMap::new(); + let mut notes = ShapeNotes::default(); + for p in props.iter().filter(|p| elements(**p).next().is_some()) { + let nested = p.descendants().skip(1).filter(|d| d.is_element() && (is_aixm(d) || is_gml(d)) && SHAPES.contains(&local(d))); + // Not those inside another shape (a surface's curves). + for g in nested.filter(|g| !g.ancestors().skip(1).take_while(|a| a != p).any(|a| SHAPES.contains(&local(&a)))) { + if let Some(geom) = shapes.shape(g, &mut notes) { + by_family.entry(family(&geom)).or_default().push(geom); + } + } + } + if by_family.is_empty() { + return false; + } + for (label, gs) in by_family { + layers.push(kind, label, merged(gs), row.clone(), Some(¬es)); + mark(layers, kind, label, temporary, snapshot); + } + return true; + } + for (name, g) in shaped { + let mut notes = ShapeNotes::default(); + let geom = shapes.shape(g, &mut notes); + let mut r = row.clone(); + r.shape_values(g, &name); + // A kind's shapes under different properties are different layers (an airport's reference + // point and its boundary); a kind with one is one layer, titled by its kind alone. + let label = name.as_str(); + let bad = geom.is_none(); + layers.push(kind, label, geom, r, Some(¬es)); + if let Some(l) = layers.get(kind, label) { + l.unreadable += usize::from(bad); + } + mark(layers, kind, label, temporary, snapshot); + } + true +} + +fn mark(layers: &mut Layers, kind: &str, label: &str, temporary: usize, snapshot: bool) { + if let Some(l) = layers.get(kind, label) { + l.temporary += usize::from(temporary > 0); + l.snapshots += usize::from(snapshot); + } +} + +/// An airspace: its volumes' operations decide what is drawn. Its limits are its BASE volume's. +#[allow(clippy::too_many_arguments)] +fn airspace( + props: &[Node], + row: &mut Row, + shapes: &mut Shapes, + notes: &mut ShapeNotes, + layers: &mut Layers, + kind: &str, + temporary: usize, + snapshot: bool, +) -> bool { + let mut components: Vec<(u64, String, Option)> = Vec::new(); + for p in props { + if local(p) == "geometryComponent" { + if is_nil(p) { + continue; + } + let Some(c) = elements(*p).find(|c| local(c) == "AirspaceGeometryComponent") else { continue }; + let op = child(c, "operation").map(|n| text_of(&n)).unwrap_or_default(); + let seq = child(c, "operationSequence").and_then(|n| text_of(&n).parse().ok()).unwrap_or(u64::MAX); + let volume = child(c, "theAirspaceVolume").and_then(|v| child(v, "AirspaceVolume")); + components.push((seq, op, volume)); + } else { + row.property(*p, ""); + } + } + if components.is_empty() { + return false; + } + components.sort_by_key(|(s, ..)| *s); + // The BASE volume's limits and width, as written. + if let Some((_, _, Some(v))) = components.iter().find(|(_, op, _)| op == "BASE").or(components.first()) { + for p in elements(*v).filter(|p| !matches!(local(p), "horizontalProjection" | "centreline" | "contributorAirspace")) { + let prefix = if row.columns.iter().any(|c| c == local(&p)) { "volume_" } else { "" }; + row.property(p, prefix); + } + } + let drawable = components.iter().all(|(_, op, v)| matches!(op.as_str(), "BASE" | "UNION") && projection(*v).is_some()); + let mut geom = None; + let mut unreadable = false; + if drawable { + let mut parts = Vec::new(); + for (_, _, v) in &components { + match projection(*v).and_then(|g| shapes.shape(g, notes)) { + Some(g) => parts.push(g), + None => unreadable = true, + } + } + if !unreadable { + geom = merged(parts); + } + } + layers.push(kind, "", geom, row.clone(), Some(notes)); + if let Some(l) = layers.get(kind, "") { + if !drawable { + l.derived += 1; + for (_, op, v) in &components { + if v.is_some_and(|v| child(v, "contributorAirspace").is_some()) { + l.derived_names.add("contributorAirspace"); + } else if projection(*v).is_none() { + l.derived_names.add("a volume without horizontalProjection"); + } else if !matches!(op.as_str(), "BASE" | "UNION") { + l.derived_names.add(op); + } + } + } else if unreadable { + l.unreadable += 1; + } else if components.len() > 1 { + l.unions += 1; + } + } + mark(layers, kind, "", temporary, snapshot); + true +} + +/// A vertical structure: a row per part, the structure's values with the part's (`part_…`). +fn vertical_structure( + props: &[Node], + base: &Row, + shapes: &mut Shapes, + layers: &mut Layers, + kind: &str, + temporary: usize, + snapshot: bool, +) -> bool { + let mut row = base.clone(); + let mut parts = Vec::new(); + for p in props { + if local(p) == "part" && !is_nil(p) { + if let Some(vp) = elements(*p).find(|c| local(c) == "VerticalStructurePart") { + parts.push(vp); + } + } else { + row.property(*p, ""); + } + } + if parts.is_empty() { + // Kept with its kind (or counted) as any other feature with nothing to draw. + return false; + } + let mut rows = Vec::new(); + for vp in parts { + let mut r = row.clone(); + let mut notes = ShapeNotes::default(); + let mut geom = None; + let mut bad = false; + for p in elements(vp) { + match shape_in(p) { + Some(g) if !is_nil(&p) => { + geom = shapes.shape(g, &mut notes); + bad = geom.is_none(); + r.shape_values(g, &format!("part_{}", local(&p))); + } + _ => r.property(p, "part_"), + } + } + rows.push((geom, r, notes, bad)); + } + // A part with no shape goes with the structure's first family of parts. + let first = rows.iter().find_map(|(g, ..)| g.as_ref().map(family)).unwrap_or("points"); + for (geom, r, notes, bad) in rows { + let label = geom.as_ref().map_or(first, family); + layers.push(kind, label, geom, r, Some(¬es)); + if let Some(l) = layers.get(kind, label) { + l.unreadable += usize::from(bad); + } + mark(layers, kind, label, temporary, snapshot); + } + true +} + +/// The layers as datasets, with what the read says. +fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, budget_spent: bool) -> Result> { + let mut file = ReadReport::default(); + let say = |r: &mut ReadReport, n: usize, one: &str, many: &str, rest: &str| { + if n > 0 { + let what = if n == 1 { one } else { many }; + r.messages.push(format!("{n} {what} {rest}")); + } + }; + let when = date_text(at); + say(&mut file, notes.not_in_force, "feature", "features", &format!("not in force on {when} (valid only at other times) left out")); + say( + &mut file, + notes.outside_lifetime, + "feature", + "features", + &format!("withdrawn by {when} or created after it (featureLifetime) left out"), + ); + say( + &mut file, + notes.no_state, + "feature", + "features", + "given only as changes (PERMDELTA or TEMPDELTA), with no BASELINE or SNAPSHOT to apply them to, left out", + ); + say(&mut file, notes.canceled, "feature", "features", "whose time slices were all canceled left out"); + say(&mut file, notes.no_slices, "feature", "features", "with no time slice RustGIS reads left out"); + say( + &mut file, + notes.unknown_interpretation, + "time slice", + "time slices", + "with no interpretation RustGIS knows (BASELINE, PERMDELTA, TEMPDELTA, SNAPSHOT) not read", + ); + say(&mut file, notes.bad_dates, "time slice", "time slices", "with a validTime or featureLifetime that isn't a date not read"); + say( + &mut file, + notes.unreadable_members, + "member", + "members", + "of the message couldn't be read (not well-formed XML, or past the reading limits)", + ); + say(&mut file, index.links, "member", "members", "of the message only point elsewhere (xlink:href) and weren't followed"); + if notes.nothing_to_draw > 0 { + file.messages.push(format!( + "{} features of kinds with nothing to draw left out ({})", + notes.nothing_to_draw, + notes.nothing_names.said() + )); + } + if let Some(at) = index.broken_at { + file.messages.push(format!("the file stops being well-formed XML at byte {at}: features after it weren't read")); + } + if layers.over > 0 { + file.messages.push(format!("{} features of more than {MAX_LAYERS} kinds were left out", layers.over)); + } + if let Some(s) = ¬es.other_system { + file.messages.push(format!("geometry in '{s}', not longitude/latitude, wasn't read")); + } + if let Some(s) = ¬es.as_wgs84 { + file.messages.push(format!("geometry in '{s}' was read as WGS 84 longitude/latitude")); + } + say( + &mut file, + notes.assumed_system, + "geometry", + "geometries", + "without an srsName read as urn:ogc:def:crs:EPSG::4326 (latitude first)", + ); + if budget_spent { + file.messages.push("arcs and geodesics added more points than the file's size allows: the rest were drawn with fewer points"); + } + let mut kinds_with_labels: HashMap = HashMap::new(); + for l in &layers.list { + *kinds_with_labels.entry(l.kind.clone()).or_default() += 1; + } + let mut out = Vec::new(); + for layer in layers.list { + let title = if layer.label.is_empty() || kinds_with_labels.get(&layer.kind).copied().unwrap_or(0) < 2 { + format!("{stem} {}", layer.kind) + } else { + format!("{stem} {} {}", layer.kind, layer.label) + }; + let fields: Vec = layer + .columns + .iter() + .map(|c| { + Field::new( + c.clone(), + crate::io::text_type(layer.rows.iter().filter_map(|(_, a)| a.get(c)).map(String::as_str).filter(|v| !v.is_empty())), + ) + }) + .collect(); + let mut ds = Dataset::new(title, GeometryType::None, fields); + for (g, attrs) in &layer.rows { + let row = ds.fields.iter().map(|f| attrs.get(&f.name).map_or(Value::Null, |v| Value::parse_file(v, f.ty))).collect(); + ds.push_next(g.clone(), row); + } + ds.geometry_type = crate::io::dominant_type(&ds); + let mut rep = if out.is_empty() { std::mem::take(&mut file) } else { ReadReport::default() }; + let name = ds.name.clone(); + // Each notice as one feature and as several say it. + let mut say = |n: usize, one: &str, many: &str| { + if n > 0 { + rep.messages.push(format!("{name}: {n} {}", if n == 1 { one } else { many })); + } + }; + say( + layer.unreadable, + "feature has geometry that couldn't be read and is kept without a shape", + "features have geometry that couldn't be read and are kept without a shape", + ); + say( + layer.shapeless, + "feature has no geometry and is kept without a shape", + "features have no geometry and are kept without a shape", + ); + let derived = layer.derived_names.said(); + say( + layer.derived, + &format!("airspace built from other airspace or by subtraction or intersection is kept without a shape, not drawn ({derived})"), + &format!( + "airspaces built from other airspace or by subtraction or intersection are kept without a shape, not drawn ({derived})" + ), + ); + say( + layer.unions, + "airspace is drawn as the parts of its BASE and UNION volumes, not merged into one outline; its limits are its BASE volume's", + "airspaces are drawn as the parts of their BASE and UNION volumes, not merged into one outline; their limits are their BASE volume's", + ); + say( + layer.arcs, + "feature has arcs or circles, drawn as points along them within a meter", + "features have arcs or circles, drawn as points along them within a meter", + ); + say( + layer.coarse, + "feature has arcs or geodesics drawn with fewer points than that needs: the file's point allowance ran out", + "features have arcs or geodesics drawn with fewer points than that needs: the file's point allowance ran out", + ); + let segments = layer.unread_segments.said(); + say( + layer.approximated, + &format!("feature has curve segments of kinds AIXM doesn't use, drawn straight between their positions ({segments})"), + &format!("features have curve segments of kinds AIXM doesn't use, drawn straight between their positions ({segments})"), + ); + say( + layer.rings_lost, + "ring or surface patch was left out: too few points, unreadable, or a border given by reference", + "rings or surface patches were left out: too few points, unreadable, or borders given by reference", + ); + say( + layer.referenced, + "border is given by reference to another feature's curve, which isn't followed", + "borders are given by reference to another feature's curve, which isn't followed", + ); + say( + layer.temporary, + &format!("feature is shown with a temporary change (TEMPDELTA) in force on {when}"), + &format!("features are shown with temporary changes (TEMPDELTA) in force on {when}"), + ); + say( + layer.snapshots, + "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked", + "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked", + ); + let nested = layer.nested_names.said(); + say( + layer.nested, + &format!("feature has nested records not read as attributes ({nested})"), + &format!("features have nested records not read as attributes ({nested})"), + ); + say( + layer.capped, + &format!("value of properties past the first {MAX_COLUMNS} names wasn't read"), + &format!("values of properties past the first {MAX_COLUMNS} names weren't read"), + ); + if layer.zm > 0 { + ds.zm_dropped = true; + rep.messages.push(format!("{name}: {}", crate::zm_note(Some(layer.zm as u64)))); + } + out.push((ds, rep)); + } + if out.is_empty() { + let mut why: Vec = file.messages.iter().map(|m| m.text.clone()).collect(); + if why.is_empty() { + why.push("no features in force".into()); + } + return Err(DataError::Format(format!("nothing to add at {when}: {}", why.join("; ")))); + } + Ok(out) +} + +#[cfg(test)] +mod tests; diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs new file mode 100644 index 0000000000..d05cedd172 --- /dev/null +++ b/crates/data/src/aixm/tests.rs @@ -0,0 +1,512 @@ +//! Tests of the AIXM reader: the Donlon 2025 sample (BSD-2-Clause, EUROCONTROL & FAA) and small +//! messages written here for each rule of the time slices, the arcs and hostile input. + +use super::*; + +const DONLON: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/donlon-aixm.xml")); + +fn at(date: &str) -> Options { + Options { at: crate::time::parse_text(date) } +} + +fn layer<'a>(out: &'a [(Dataset, ReadReport)], name: &str) -> &'a Dataset { + match out.iter().find(|(d, _)| d.name == name) { + Some((d, _)) => d, + None => panic!("no layer {name}: {:?}", out.iter().map(|(d, _)| d.name.as_str()).collect::>()), + } +} + +fn said(out: &[(Dataset, ReadReport)]) -> Vec { + out.iter().flat_map(|(_, r)| r.messages.iter().map(|m| m.text.clone())).collect() +} + +fn value(ds: &Dataset, row: usize, field: &str) -> Value { + let k = ds.fields.iter().position(|f| f.name == field).unwrap_or_else(|| panic!("no field {field} in {}", ds.name)); + ds.features[row].attrs[k].clone() +} + +fn row_where(ds: &Dataset, field: &str, text: &str) -> usize { + (0..ds.features.len()).find(|&i| value(ds, i, field) == Value::Text(text.into())).unwrap_or_else(|| panic!("no {field} = {text}")) +} + +fn ring(g: &Geometry) -> &[Coord] { + match g { + Geometry::Polygon(p) => &p[0][0], + other => panic!("not a polygon: {other:?}"), + } +} + +fn meters_between(a: Coord, b: Coord) -> f64 { + rustgis_geom::wgs84_distance_m(a, b) +} + +const NS: &str = r#"xmlns:message="http://www.aixm.aero/schema/5.1.1/message" xmlns:aixm="http://www.aixm.aero/schema/5.1.1" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance""#; + +fn message(members: &str) -> Vec { + format!("\n{members}").into_bytes() +} + +fn period(begin: &str, end: Option<&str>) -> String { + let end = match end { + Some(e) => format!("{e}"), + None => r#""#.to_string(), + }; + format!( + r#"{begin}{end}"# + ) +} + +fn slice(kind: &str, interpretation: &str, seq: u32, corr: u32, valid: &str, body: &str) -> String { + format!( + r#"{valid}{interpretation}{seq}{corr}{body}"# + ) +} + +fn feature(kind: &str, id: &str, slices: &[String]) -> String { + format!( + r#"{id}{}"#, + slices.concat() + ) +} + +fn named_point(name: &str) -> String { + format!( + r#"{name}45.71 -35.17"# + ) +} + +fn point(id: &str, slices: &[String]) -> String { + feature("DesignatedPoint", id, slices) +} + +fn baseline(seq: u32, corr: u32, begin: &str, end: Option<&str>, name: &str) -> String { + slice("DesignatedPoint", "BASELINE", seq, corr, &period(begin, end), &named_point(name)) +} + +fn names(bytes: &[u8], date: &str) -> (Vec, Vec) { + let out = read("t.xml", bytes, &at(date)).unwrap_or_else(|e| panic!("{e}")); + let ds = layer(&out, "t DesignatedPoint"); + ((0..ds.features.len()).map(|i| value(ds, i, "name")).collect(), said(&out)) +} + +// --------------------------------------------------------------------------------------------- +// The Donlon sample. +// --------------------------------------------------------------------------------------------- + +#[test] +fn donlon_gives_a_layer_per_kind_and_shape_property() { + let out = read("donlon-aixm.xml", DONLON, &at("2026-01-15")).unwrap(); + let mut got: Vec<&str> = out.iter().map(|(d, _)| d.name.as_str()).collect(); + got.sort_unstable(); + assert_eq!( + got, + [ + "donlon-aixm AirportHeliport ARP", + "donlon-aixm AirportHeliport aviationBoundary", + "donlon-aixm Airspace", + "donlon-aixm DesignatedPoint", + "donlon-aixm Navaid", + "donlon-aixm RouteSegment", + "donlon-aixm Runway", + "donlon-aixm VerticalStructure", + ] + ); + let dp = layer(&out, "donlon-aixm DesignatedPoint"); + assert_eq!(dp.geometry_type, GeometryType::Point); + assert_eq!(value(dp, 0, "designator"), Value::Text("ABOLA".into())); + assert_eq!(value(dp, 0, "identifier"), Value::Text("9fcb360c-6933-46d6-9c85-a337202efe70".into())); + // Latitude first in the file, longitude first here. + assert_eq!(dp.features[0].geometry, Some(Geometry::Point(Coord::new(-35.17, 45.71)))); + let arp = layer(&out, "donlon-aixm AirportHeliport ARP"); + assert_eq!(value(arp, 0, "designator"), Value::Text("EADD".into())); + assert_eq!(arp.features[0].geometry, Some(Geometry::Point(Coord::new(-31.94944444, 52.37166667)))); + // The elevation written on the reference point, with its unit and datum. + assert_eq!(value(arp, 0, "elevation"), Value::Int(30)); + assert_eq!(value(arp, 0, "elevation_uom"), Value::Text("M".into())); + assert_eq!(value(arp, 0, "verticalDatum"), Value::Text("EGM_96".into())); + assert_eq!(layer(&out, "donlon-aixm AirportHeliport aviationBoundary").geometry_type, GeometryType::Polygon); + // A runway has no geometry of its own: a table, its references kept as identifiers. + let rwy = layer(&out, "donlon-aixm Runway"); + assert_eq!(rwy.geometry_type, GeometryType::None); + assert_eq!(value(rwy, 0, "nominalLength"), Value::Int(3200)); + assert_eq!(value(rwy, 0, "associatedAirportHeliport"), Value::Text("1b54b2d6-a5ff-4e57-94c2-f4047a381c64".into())); + assert_eq!(value(rwy, 0, "associatedAirportHeliport_title"), Value::Text("EADD DONLON/INTL.".into())); + assert!(!said(&out).iter().any(|m| m.contains("Runway") && m.contains("no geometry")), "{:?}", said(&out)); +} + +#[test] +fn the_bravo_arc_runs_clockwise_from_west_through_north_to_southeast() { + // ASE_BRAVO_R: from its center west along a geodesic, an ArcByCenterPoint of 25 NM from + // bearing -90 to 137 (clockwise, as the AIXM guidance reads a latitude-first system), and back. + let out = read("donlon-aixm.xml", DONLON, &at("2026-01-15")).unwrap(); + let asp = layer(&out, "donlon-aixm Airspace"); + let i = row_where(asp, "name", "BRAVO"); + let ring = ring(asp.features[i].geometry.as_ref().unwrap()); + let center = Coord::new(-36.166666666666664, 55.2333333333333); + let radius = 25.0 * 1852.0; + let on_arc: Vec = ring.iter().copied().filter(|c| (meters_between(*c, center) - radius).abs() < 1.0).collect(); + assert!(on_arc.len() > 100, "{} points on the arc", on_arc.len()); + // It passes north of the center, which a counter-clockwise arc wouldn't. + let north = on_arc.iter().map(|c| c.y).fold(f64::MIN, f64::max); + assert!(north > 55.64, "northernmost {north}"); + // It joins the geodesics before and after it, within the file's rounding. + let near = |p: Coord| ring.iter().any(|c| meters_between(*c, p) < 30.0); + assert!(near(Coord::new(-36.89437338, 55.23116373)) && near(Coord::new(-35.67411607, 54.92816351))); + // The limits as written. + assert_eq!(value(asp, i, "upperLimit"), Value::Int(1525)); + assert_eq!(value(asp, i, "upperLimit_uom"), Value::Text("M".into())); + assert_eq!(value(asp, i, "upperLimitReference"), Value::Text("SFC".into())); + assert_eq!(value(asp, i, "lowerLimitReference"), Value::Text("SFC".into())); +} + +#[test] +fn the_vaardnor_circle_stays_within_a_meter_of_its_radius() { + let out = read("donlon-aixm.xml", DONLON, &at("2026-01-15")).unwrap(); + let asp = layer(&out, "donlon-aixm Airspace"); + let i = row_where(asp, "name", "VAARDNOR"); + let ring = ring(asp.features[i].geometry.as_ref().unwrap()); + let center = Coord::new(-22.1, 52.36666667); + assert!(ring.len() > 100); + for c in ring { + let d = meters_between(*c, center); + assert!((d - 15.0 * 1852.0).abs() < 0.01, "{d}"); + } +} + +#[test] +fn an_airspace_built_from_others_is_kept_without_a_shape_and_said() { + let out = read("donlon-aixm.xml", DONLON, &at("2026-01-15")).unwrap(); + let asp = layer(&out, "donlon-aixm Airspace"); + let i = row_where(asp, "name", "MAGNETO TMA"); + assert_eq!(asp.features[i].geometry, None); + let notes = said(&out); + assert!(notes.iter().any(|m| m.contains("1 airspace built from other airspace") && m.contains("contributorAirspace")), "{notes:?}"); +} + +#[test] +fn a_vertical_structure_gives_a_row_per_part() { + let out = read("donlon-aixm.xml", DONLON, &at("2026-01-15")).unwrap(); + let vs = layer(&out, "donlon-aixm VerticalStructure"); + assert_eq!(vs.features.len(), 5); + let parts: Vec = (0..5).map(|i| value(vs, i, "part_designator")).collect(); + assert_eq!(parts[0], Value::Text("OBST-EA-0002-1".into())); + assert_eq!(parts[4], Value::Text("OBST-EA-0002-5".into())); + assert!((0..5).all(|i| value(vs, i, "name") == Value::Text("OBST-EA-0002".into()))); + assert_eq!(value(vs, 0, "part_verticalExtent"), Value::Int(150)); + assert_eq!(value(vs, 0, "elevation"), Value::Int(264)); +} + +#[test] +fn a_long_route_segment_follows_its_geodesic() { + let out = read("donlon-aixm.xml", DONLON, &at("2026-01-15")).unwrap(); + let rs = layer(&out, "donlon-aixm RouteSegment"); + let Some(Geometry::Line(parts)) = &rs.features[0].geometry else { panic!("not a line") }; + let line = &parts[0]; + let (a, b) = (Coord::new(-33.495, 44.39666667), Coord::new(-28.64166667, 47.13666667)); + assert_eq!((line[0], *line.last().unwrap()), (a, b)); + // Points every 10 km at most, each on the geodesic: the lengths along it add up. + let whole = meters_between(a, b); + assert!(line.len() as f64 >= (whole / GEODESIC_STEP_M).ceil()); + let along: f64 = line.windows(2).map(|w| meters_between(w[0], w[1])).sum(); + assert!((along - whole).abs() < 0.01, "{along} vs {whole}"); + assert_eq!(value(rs, 0, "upperLimit_uom"), Value::Text("FL".into())); +} + +// --------------------------------------------------------------------------------------------- +// Time slices. +// --------------------------------------------------------------------------------------------- + +#[test] +fn the_highest_correction_holds_and_a_tempdelta_overlays_while_in_force() { + let temp = slice( + "DesignatedPoint", + "TEMPDELTA", + 1, + 0, + &period("2026-02-01T00:00:00Z", Some("2026-03-01T00:00:00Z")), + "TEMPORARY", + ); + let bytes = message(&point( + "a", + &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "FIRST"), baseline(1, 1, "2025-01-01T00:00:00Z", None, "CORRECTED"), temp], + )); + let (got, notes) = names(&bytes, "2026-01-15"); + assert_eq!(got, [Value::Text("CORRECTED".into())]); + assert!(notes.is_empty(), "{notes:?}"); + let out = read("t.xml", &bytes, &at("2026-02-10")).unwrap(); + let ds = layer(&out, "t DesignatedPoint"); + assert_eq!(value(ds, 0, "name"), Value::Text("TEMPORARY".into())); + // What the change doesn't hold stays the BASELINE's. + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(-35.17, 45.71)))); + assert!(said(&out).iter().any(|m| m.contains("1 feature is shown with a temporary change (TEMPDELTA) in force on 2026-02-10"))); + // A period excludes its end. + assert_eq!(names(&bytes, "2026-03-01").0, [Value::Text("CORRECTED".into())]); +} + +#[test] +fn a_tempdelta_with_a_nil_property_removes_its_value() { + let temp = slice( + "DesignatedPoint", + "TEMPDELTA", + 1, + 0, + &period("2026-02-01T00:00:00Z", None), + r#""#, + ); + let bytes = message(&point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "NAMED"), temp])); + assert_eq!(names(&bytes, "2026-02-10").0, [Value::Null]); +} + +#[test] +fn a_permanent_change_takes_over_from_its_date() { + let bytes = message(&point( + "a", + &[ + baseline(1, 1, "2025-01-01T00:00:00Z", Some("2026-01-01T00:00:00Z"), "BEFORE"), + baseline(2, 0, "2026-01-01T00:00:00Z", None, "AFTER"), + ], + )); + assert_eq!(names(&bytes, "2025-06-01").0, [Value::Text("BEFORE".into())]); + assert_eq!(names(&bytes, "2026-01-01").0, [Value::Text("AFTER".into())]); +} + +#[test] +fn features_left_out_at_the_date_are_counted() { + let lifetime = r#"2020-01-01T00:00:00Z2025-12-31T00:00:00Z"#; + let withdrawn = slice( + "DesignatedPoint", + "BASELINE", + 1, + 0, + &period("2025-01-01T00:00:00Z", None), + &(lifetime.to_string() + &named_point("WITHDRAWN")), + ); + let canceled = slice("DesignatedPoint", "BASELINE", 1, 1, r#""#, &named_point("CANCELED")); + let delta_only = slice("DesignatedPoint", "PERMDELTA", 1, 0, &period("2025-01-01T00:00:00Z", None), "DELTA"); + let members = [ + point("kept", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]), + point("later", &[baseline(1, 0, "2027-01-01T00:00:00Z", None, "LATER")]), + point("withdrawn", &[withdrawn]), + point("canceled", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "CANCELED"), canceled]), + point("delta", &[delta_only]), + ] + .concat(); + let (got, notes) = names(&message(&members), "2026-01-15"); + assert_eq!(got, [Value::Text("KEPT".into())]); + for want in [ + "1 feature not in force on 2026-01-15 00:00 UTC", + "1 feature withdrawn by 2026-01-15 00:00 UTC", + "1 feature whose time slices were all canceled", + "1 feature given only as changes (PERMDELTA or TEMPDELTA)", + ] { + assert!(notes.iter().any(|m| m.starts_with(want)), "{want}: {notes:?}"); + } +} + +#[test] +fn nothing_in_force_is_an_error_that_says_why() { + let bytes = message(&point("later", &[baseline(1, 0, "2027-01-01T00:00:00Z", None, "LATER")])); + let e = read("t.xml", &bytes, &at("2026-01-15")).unwrap_err().to_string(); + assert!(e.contains("not in force"), "{e}"); +} + +#[test] +fn a_snapshot_is_read_when_there_is_no_baseline_and_said() { + let valid = r#"2025-06-01T00:00:00Z"#; + let snap = format!( + r#"{valid}SNAPSHOT{}"#, + named_point("SNAP") + ); + let (got, notes) = names(&message(&point("s", &[snap])), "2026-01-15"); + assert_eq!(got, [Value::Text("SNAP".into())]); + assert!(notes.iter().any(|m| m.contains("SNAPSHOT")), "{notes:?}"); +} + +#[test] +fn a_clean_message_says_nothing() { + let bytes = message(&point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "CLEAN")])); + let (got, notes) = names(&bytes, "2026-01-15"); + assert_eq!(got.len(), 1); + assert!(notes.is_empty(), "{notes:?}"); +} + +#[test] +fn a_feature_split_across_members_is_put_together() { + let temp = slice("DesignatedPoint", "TEMPDELTA", 1, 0, &period("2026-01-01T00:00:00Z", None), "LATER MEMBER"); + let members = point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "FIRST MEMBER")]) + &point("a", &[temp]); + assert_eq!(names(&message(&members), "2026-01-15").0, [Value::Text("LATER MEMBER".into())]); +} + +// --------------------------------------------------------------------------------------------- +// Geometry. +// --------------------------------------------------------------------------------------------- + +/// An airspace whose outline is the BRAVO arc, in a latitude-first or longitude-first system. +fn arc_airspace(lat_first: bool) -> Vec { + // In a longitude-first system angles run counter-clockwise from east. + let (srs, start, end) = + if lat_first { ("urn:ogc:def:crs:EPSG::4326", "-90.0", "137.0") } else { ("urn:ogc:def:crs:OGC:1.3:CRS84", "180.0", "-47.0") }; + let pos = |lat: &str, lon: &str| if lat_first { format!("{lat} {lon}") } else { format!("{lon} {lat}") }; + let (c, w, se) = (pos("55.23333333", "-36.16666667"), pos("55.23116373", "-36.89437338"), pos("54.92816351", "-35.67411607")); + let body = format!( + r#"ARCBASE195STD{c} {w}{c}25.0{start}{end}{se} {c}"# + ); + message(&feature("Airspace", "arc", &[slice("Airspace", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])) +} + +#[test] +fn an_arc_in_a_longitude_first_system_is_the_same_arc() { + let shape = |lat_first| { + let out = read("t.xml", &arc_airspace(lat_first), &at("2026-01-15")).unwrap(); + layer(&out, "t Airspace").features[0].geometry.clone().unwrap() + }; + let (a, b) = (shape(true), shape(false)); + let (a, b) = (ring(&a), ring(&b)); + assert_eq!(a.len(), b.len()); + for (p, q) in a.iter().zip(b) { + assert!(meters_between(*p, *q) < 0.001, "{p:?} {q:?}"); + } + let out = read("t.xml", &arc_airspace(true), &at("2026-01-15")).unwrap(); + assert_eq!(said(&out), ["t Airspace: 1 feature has arcs or circles, drawn as points along them within a meter"]); + let ds = layer(&out, "t Airspace"); + assert_eq!(value(ds, 0, "upperLimit"), Value::Int(95)); + assert_eq!(value(ds, 0, "upperLimit_uom"), Value::Text("FL".into())); +} + +#[test] +fn an_arc_through_three_points_passes_through_them() { + let mut shapes = Shapes { budget: 1_000_000, other_system: None, assumed_system: 0, as_wgs84: None }; + let mut notes = ShapeNotes::default(); + let (a, m, b) = (Coord::new(10.0, 50.0), Coord::new(10.1, 50.07), Coord::new(10.2, 50.0)); + let arc = shapes.arc_through(a, m, b, false, &mut notes); + assert!(meters_between(arc[0], a) < 0.01 && meters_between(*arc.last().unwrap(), b) < 0.01); + assert!(arc.iter().any(|c| meters_between(*c, m) < 5.0)); + // Bulging north, through the middle point, not around the other way. + assert!(arc.iter().all(|c| c.y >= 49.999)); +} + +#[test] +fn arcs_past_the_point_allowance_are_drawn_coarser_and_said() { + let mut shapes = Shapes { budget: 0, other_system: None, assumed_system: 0, as_wgs84: None }; + let mut notes = ShapeNotes::default(); + let n = shapes.pieces(50_000.0, 180.0, &mut notes); + assert_eq!(n, 1); + assert!(notes.coarse); +} + +#[test] +fn a_radius_in_an_unknown_unit_or_past_the_limit_is_not_drawn() { + for (radius, uom) in [("25.0", "furlong"), ("1e9", "m"), ("-5", "m"), ("NaN", "m")] { + let bytes = String::from_utf8(arc_airspace(true)) + .unwrap() + .replace(r#"25.0"#, &format!(r#"{radius}"#)); + let out = read("t.xml", bytes.as_bytes(), &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t Airspace").features[0].geometry, None, "{radius} {uom}"); + assert!(said(&out).iter().any(|m| m.contains("couldn't be read")), "{:?}", said(&out)); + } +} + +#[test] +fn geometry_in_a_projected_system_is_not_read_and_said() { + let bytes = String::from_utf8(message(&point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "P")]))) + .unwrap() + .replace("urn:ogc:def:crs:EPSG::4326", "urn:ogc:def:crs:EPSG::32633"); + let out = read("t.xml", bytes.as_bytes(), &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t DesignatedPoint").features[0].geometry, None); + assert!(said(&out).iter().any(|m| m.contains("EPSG::32633")), "{:?}", said(&out)); +} + +#[test] +fn union_volumes_are_drawn_as_parts_and_subtractions_are_not_drawn() { + let volume = |op: &str, seq: u32, lat: f64| { + let ring = format!("{lat} 10 {lat} 11 {} 11 {} 10 {lat} 10", lat + 1.0, lat + 1.0); + format!( + r#"{op}{seq}{ring}"# + ) + }; + let airspace = |id: &str, second: &str| { + let body = format!("{id}{}{}", volume("BASE", 1, 50.0), volume(second, 2, 52.0)); + feature("Airspace", id, &[slice("Airspace", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]) + }; + let out = read("t.xml", &message(&(airspace("U", "UNION") + &airspace("S", "SUBTR"))), &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t Airspace"); + let Some(Geometry::Polygon(parts)) = &ds.features[row_where(ds, "name", "U")].geometry else { panic!() }; + assert_eq!(parts.len(), 2); + assert_eq!(ds.features[row_where(ds, "name", "S")].geometry, None); + let notes = said(&out); + assert!(notes.iter().any(|m| m.contains("1 airspace is drawn as the parts of its BASE and UNION volumes")), "{notes:?}"); + assert!( + notes.iter().any(|m| m.contains("1 airspace built from other airspace or by subtraction or intersection") && m.contains("SUBTR")) + ); +} + +// --------------------------------------------------------------------------------------------- +// The file. +// --------------------------------------------------------------------------------------------- + +#[test] +fn aixm_is_told_by_its_root() { + assert!(looks_like_aixm(DONLON)); + assert!(looks_like_aixm(&message(""))); + let v52 = br#""#; + assert!(looks_like_aixm(v52)); + assert!(!looks_like_aixm(br#""#)); + assert!(!looks_like_aixm(br#""#)); + assert!(!looks_like_aixm(br#""#)); +} + +#[test] +fn a_file_that_isnt_an_aixm_message_or_has_no_members_is_refused() { + let e = read("t.xml", br#""#, &at("2026-01-15")).unwrap_err(); + assert!(e.to_string().contains("not an AIXM message"), "{e}"); + let e = read("t.xml", &message(""), &at("2026-01-15")).unwrap_err(); + assert!(e.to_string().contains("no features"), "{e}"); +} + +#[test] +fn a_file_cut_short_keeps_the_members_before_and_says_so() { + let whole = message( + &(point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "A")]) + + &point("b", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "B")])), + ); + let cut = &whole[..whole.len() - 120]; + let out = read("t.xml", cut, &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t DesignatedPoint").features.len(), 1); + assert!(said(&out).iter().any(|m| m.contains("stops being well-formed XML")), "{:?}", said(&out)); +} + +#[test] +fn entities_and_doctypes_are_not_expanded() { + let doc = format!( + "]>{}{}", + point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "&b;")]), + point("b", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "PLAIN")]) + ); + let out = read("t.xml", doc.as_bytes(), &at("2026-01-15")).unwrap(); + assert_eq!(names(doc.as_bytes(), "2026-01-15").0, [Value::Text("PLAIN".into())]); + assert!(said(&out).iter().any(|m| m.contains("1 member of the message couldn't be read")), "{:?}", said(&out)); +} + +#[test] +fn junk_never_panics() { + let base = String::from_utf8(DONLON.to_vec()).unwrap(); + let mut seed = 7u64; + for _ in 0..200 { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let at_byte = (seed >> 33) as usize % base.len(); + let mut bytes = base.as_bytes().to_vec(); + bytes.truncate(at_byte); + let _ = read("t.xml", &bytes, &at("2026-01-15")); + let mut swapped = base.as_bytes().to_vec(); + if let Some(b) = swapped.get_mut(at_byte) { + *b = b"<>/\"=0-.9 x"[(seed as usize) % 11]; + } + let _ = read("t.xml", &swapped, &at("2026-01-15")); + } +} + +#[test] +fn an_effective_date_is_read_from_text() { + assert_eq!(Options::at_text("2026-01-15").unwrap(), at("2026-01-15")); + assert!(Options::at_text("next tuesday").unwrap_err().contains("isn't a date")); +} diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 972b92a18b..8b109382ec 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -49,7 +49,7 @@ fn without_layout(t: &str) -> &str { } /// A coordinate system named by `srsName`, and whether its axes are latitude first. -fn srs(name: &str) -> Option<(Crs, bool)> { +pub(crate) fn srs(name: &str) -> Option<(Crs, bool)> { let n = name.trim(); let up = n.to_ascii_uppercase(); if up.ends_with("CRS84") { diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index acb63a07ce..7415b3fdc4 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -5,6 +5,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod address; +pub mod aixm; pub mod citygml; pub mod cityjson; mod citymodel; diff --git a/crates/data/tests/data/donlon-aixm.xml b/crates/data/tests/data/donlon-aixm.xml new file mode 100644 index 0000000000..a69fbb4597 --- /dev/null +++ b/crates/data/tests/data/donlon-aixm.xml @@ -0,0 +1,1598 @@ + + + + + + + + 6a23b1fb-5eba-468e-974a-d37cdecf089f + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2013-04-23T12:00:00Z + + + + R + EAR1 + + BRAVO + NO + MIL + + + + + + BASE + 1 + + + + 1525 + SFC + + + 0 + SFC + + + + + + + + + + + + + + 55.23333333 -36.16666667 55.23116373 -36.89437338 + + + 55.2333333333333 -36.166666666666664 + 25.0 + -90.0 + 137.0 + + + 54.92816351 -35.67411607 55.23333333 -36.16666667 + + + + + + + + + 5.0 + + + + + + + + + + + + + timeInterval + DESCRIPTION + + + Activity periods to be published by NOTAM + + + + + + SHOOTING + AVBL_FOR_ACTIVATION + + + 1525 + SFC + 0 + SFC + BETWEEN + + + + + + + + + + + + + + + + 21a13c9f-a8ff-4fdd-9aaa-5dbfd91514b8 + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2013-04-23T12:00:00Z + + + + P + EAP2 + + VAARDNOR + NO + + + + + + + BASE + 1 + + + + 999 + STD + + + 0 + MSL + + + + + + + + + + + + + + 52.36666667 -22.10000000 + 15.0 + + + + + + + + + 5.0 + + + + + + + + + + + + + NUCLEAR + ACTIVE + + + 999 + STD + 0 + MSL + BETWEEN + + + + + + + + + + + + + + + + + fdaeffb4-6897-41fb-a33d-8861c2e91e69 + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2002-11-30T00:00:00Z + + + + TMA + EAMN + + MAGNETO TMA + YES + CIVIL + + + + + + + C + + + 460 + STD + 210 + STD + BETWEEN + + + + + + + + + + BASE + 1 + + + + + + + + + + + + + + + FULL_GEOMETRY + + + + + + + + + + + + UNION + 2 + + + + + + + + + + + + + + + FULL_GEOMETRY + + + + + + + + + + + + + + + UTC + 01-01 + 31-12 + ANY + ANY + 05:00 + 00:00 + YES + NO + + + + + ATS + ACTIVE + + + 460 + STD + 210 + STD + BETWEEN + + + + + + + + + + + + + UTC + 01-01 + 31-12 + ANY + 00:00 + 05:00 + YES + NO + + + + + ATS + AVBL_FOR_ACTIVATION + + + 460 + STD + 210 + STD + BETWEEN + + + + + + + + + + + + + + + + 9fcb360c-6933-46d6-9c85-a337202efe70 + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2009-01-01T00:00:00Z + + + + ABOLA + ICAO + ABOLA + + + 45.71000000 -35.17000000 + 5.0 + + + + + + + + + + + + + + 846caa7d-6af1-4c43-8e6b-0c7d01ba8515 + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2009-01-01T00:00:00Z + + + + LOWER + 195 + STD + 900 + MSL + + GDS + + 053 + + 233 + 478 + 9 + 9 + + NO + 1200 + 900 + MSL + 195 + STD + OTHER:RNP + 4 + + + + ON_REQUEST + NO + NO + YES + + + RAD_DME + + + + + + NO + + + + + + + + + + + + + + + + + + + + + + 44.39666667 -33.49500000 47.13666667 -28.64166667 + + + 0.5 + + + + + COMPULSORY + NO + NO + YES + + + + + + + + + + + + + FORWARD + NE + OPEN + + + 195 + STD + 900 + MSL + BETWEEN + + + + + + 195 + STD + 900 + MSL + BETWEEN + + + + + + + + + BACKWARD + SW + OPEN + + + 195 + STD + 900 + MSL + BETWEEN + + + + + + 195 + STD + 900 + MSL + BETWEEN + + + + + + + + length + REMARK + + + Accuracy unknown + + + + + + + minimumEnrouteAltitude + REMARK + + + Accuracy 50M + + + + + + + + + + + 1b54b2d6-a5ff-4e57-94c2-f4047a381c64 + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2009-01-01T00:00:00Z + + + + EADD + DONLON/INTL. + EADD + DLN + AH + YES + NO + CIVIL + 30 + 0.1 + EGM_96 + -3.0 + 1 + 1990 + 0.03 + 21.0 + YES + YES + YES + YES + 3500 + + -5.0 + NO + 2009-01-01 + + + + + DONLON + + + + + + + + + OPERATE + + + + + + 52.37166667 -31.94944444 + 0.1 + 30 + 12 + EGM_96 + 0.1 + + + + + + + + + + + + + 52.3822470371762 -31.9074597937666 52.3818188550575 -31.9144889649634 52.3812538261666 -31.9237300390958 + 52.3807311317237 -31.9322923896424 52.3801303511321 -31.9421337580615 52.3795599271567 -31.9514777317629 + 52.3791375267028 -31.958396891073 52.3788535605883 -31.9630483808547 52.3785182879742 -31.9685402534686 + 52.3781355569265 -31.9748094603085 52.3745897042406 -31.974228168312 52.3713523622993 -31.9736974930085 + 52.3683805162524 -31.9732103728696 52.3656812636639 -31.9727679622374 52.3618538550198 -31.9721406921716 + 52.3625038542097 -31.9627691254211 52.3630515065939 -31.9548642519843 52.3635905358198 -31.9470884602563 + 52.3641207641774 -31.9394395333169 52.3646059189655 -31.9324407447419 52.3651415775998 -31.9247133040712 + 52.3653575284866 -31.9215979580969 52.3658944641407 -31.9138690523474 52.3822470371762 -31.9074597937666 + + + + + + + + + 0.5 + + + + + + + + + + DONLON INTERNATIONAL AIRPORT + AIRPORT OPERATOR + + + + + + 4 W + DONLON + + + REPUBLIC OF DONLON + + + + + + + + AFTN + EADDYDYX + + + + + + + + + + INTERNET + www.donlonairport.com + + admin@donlonairport.com + + + + + + + + 01238282 + 01238292 + + + + + + + + + + + NORMAL + + + + PERMIT + + + + + + + UTC + 01-01 + 31-12 + WORK_DAY + 06:00 + 20:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + SAT + 07:00 + 20:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + SUN + 07:00 + 20:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + HOL + 07:00 + 20:00 + YES + NO + + + + + AND + + + + + ALL + + + + + + + + OR + + + + + INTL + + + + + NTL + + + + + + + + + + + OR + + + + + SCHEDULED + + + + + NON_SCHEDULED + + + + + PRIVATE + + + + + + + + + ALL + + + + + CONDITIONAL + + + + + + + UTC + 01-01 + 31-12 + WORK_DAY + 00:00 + 06:00 + NO + NO + + + + + UTC + 01-01 + 31-12 + WORK_DAY + AFT_WORK_DAY + 20:00 + 00:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + SAT + 00:00 + 07:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + SAT + SUN + 20:00 + 00:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + SUN + 00:00 + 07:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + SUN + MON + 20:00 + 00:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + HOL + 00:00 + 07:00 + YES + NO + + + + + UTC + 01-01 + 31-12 + HOL + AFT_HOL + 20:00 + 00:00 + YES + NO + + + + + AND + + + + + ALL + + + + + + + + OR + + + + + INTL + + + + + NTL + + + + + + + + + + + OR + + + + + SCHEDULED + + + + + NON_SCHEDULED + + + + + PRIVATE + + + + + + + + + + priorPermission + DESCRIPTION + + + Services are available O/R. Request to be submitted to the AD not later than 1500 (1400) UTC. + + + + + ALL + + + + + + + fieldElevation + DESCRIPTION + + + Geoid undulation at AD ELEV PSN is 12 M + + + + + + + altimeterCheckLocation + DESCRIPTION + + + Location: At apron. Elevation: 28 M. + + + + + + + secondaryPowerSupply + DESCRIPTION + + + Secondary power supply to all lighting at AD. Switch-over time: 1 SEC. + + + + + + + windDirectionIndicator + DESCRIPTION + + + 300 M from THR 09L, not lighted + + + + + + + landingDirectionIndicator + DESCRIPTION + + + 800 M W of ARP, lighted + + + + + + + transitionLevel + REMARK + + + By ATC + + + + + + + ARP + DESCRIPTION + + + ARP site at AD: 258°/1075 M from THR 09L. Direction and distance from (city): 045°, 9 KM from Donlon. + + + + + + + + + + + 6c7fac45-c24f-4e36-b196-687458d99070 + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2019-12-05T00:00:00Z + + + + OBST-EA-0002 + WINDMILL_FARMS + NO + + YES + + + + + + + + + + + + + 150 + 30 + WINDMILL + COMPLETED + + + + NO + NO + STEEL + OBST-EA-0002-1 + + + 47.74500000 -27.52583333 + 50 + 264 + + EGM_96 + 30 + + + + + + + + + + + + 150 + 30 + WINDMILL + COMPLETED + + + + NO + NO + STEEL + OBST-EA-0002-2 + + + 47.74222222 -27.52388889 + 50 + 253 + + EGM_96 + 30 + + + + + + + + + + + + 150 + 30 + WINDMILL + COMPLETED + + + + NO + NO + STEEL + OBST-EA-0002-3 + + + 47.74194444 -27.528888896 + 50 + 255 + + EGM_96 + 30 + + + + + + + + + + + + 150 + 30 + WINDMILL + COMPLETED + + + + NO + NO + STEEL + OBST-EA-0002-4 + + + 47.73888889 -27.52750000 + 50 + 239 + + EGM_96 + 30 + + + + + + + + + + + + 150 + 30 + WINDMILL + COMPLETED + + + + NO + NO + STEEL + OBST-EA-0002-5 + + + 47.73888889 -27.43361111 + 50 + 269 + + EGM_96 + 30 + + + + + + + + + + + + + + + + horizontalProjection_location + REMARK + + + WINDPARK DONLON IV + + + + + + + + markingICAOStandard + REMARK + + + marked=NO + + + + + + + + + REMARK + + + Obstacle Owner: DONLON WINDPARK INC, Donlon Street 253, 2020 DOLNLON, Phone: +00122256889, email: info@donlonwindinc.dl + + + + + + + + + REMARK + + + Horizontal resolution is 1 sec + + + + + + + + + REMARK + + + Vertical resolution is 1 m + + + + + + + + + + + + 51829538-2d2a-4d01-a4bf-87c045d247a8 + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2009-01-01T00:00:00Z + + + + VOR_DME + DON + DONLON + YES + TERMINAL + + + + + + + 1 + + NO + + + + + + + 1 + + YES + + + + + + + 52.44333333 -32.00083333 + 0.5 + 60 + 13 + EGM_96 + 0.1 + + + + + + + + + + OPERATIONAL + + + + + + + + + + + 9e51668f-bf8a-4f5b-ba6e-27087972b9b8 + + + + + 2025-11-01T00:00:00Z + + + + BASELINE + 1 + 0 + + + 2009-01-01T00:00:00Z + + + + 09L/27R + RWY + 3200 + 1 + 45 + 1 + 7.5 + 3320 + 300 + 0 + 0 + NO + + + CONC + + GOOD + 80 + RIGID + B + W + TECH + + + + + + + + + + + + + DESCRIPTION + + + Longitudinal slope RWY09L: -0.5%. Longitudinal slope RWY27R: +0.5%. + + + + + + + + + + From 87f68bfa3086b2de2903668c425f8134425d0752 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:28:16 -0600 Subject: [PATCH 02/61] feat: add AIXM messages through Add Data, with an effective date ("at") (#2077) --- ATTRIBUTION.md | 1 + README.md | 2 +- crates/data/src/aixm.rs | 217 +++++++++++++++++++------- crates/data/src/io.rs | 24 ++- crates/data/src/xml.rs | 18 +++ crates/engine/src/cmd/layer.rs | 59 +++++-- crates/engine/src/cmd/plugin_fetch.rs | 2 +- crates/engine/src/cmd/raster.rs | 4 +- crates/engine/src/tests.rs | 29 ++++ crates/ui-egui/src/lib.rs | 2 +- docs/user-guide/data-formats.md | 1 + docs/user-guide/data.md | 2 +- 12 files changed, 286 insertions(+), 75 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index dd38afe4eb..d806cc6c2d 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -31,6 +31,7 @@ of use. | CFF test font (`crates/render/testdata/test-cff.otf`), read only by the PDF font tests | The RustGIS project: generated for this test with [fontTools](https://github.com/fonttools/fonttools) by the script in `crates/render/testdata/README.md`; its glyphs are made up | Apache-2.0 | | Script-only and fallback test fonts (`crates/render/testdata/test-script-only.otf`, `crates/render/testdata/test-fallback.otf`, `crates/render/testdata/test-latin-catalog.otf`) | The RustGIS project: original square outlines and script cmap variants ([generation](crates/render/testdata/README.md)) | Apache-2.0 | | JAXA Earth catalog test copy (`crates/tiles/tests/data/jaxa_catalog.v2.md`), read only by tests | JAXA: the [JAXA Earth API](https://data.earth.jaxa.jp/) dataset catalog ([catalog.v2.md](https://data.earth.jaxa.jp/app/mcp/catalog.v2.md)), copied on 2026-11-08 | JAXA's [terms of use](https://earth.jaxa.jp/en/data/policy/): free to use and redistribute, with credit to JAXA | +| AIXM test message (`crates/data/tests/data/donlon-aixm.xml`), read only by tests | Nine members of the fictitious Donlon dataset's `Donlon_ALL_Baseline_ADM_upload.xml` ([aixm/Donlon_2025](https://github.com/aixm/Donlon_2025)), copyright (c) 2025 EUROCONTROL & FAA, copied on 2026-11-23 with the file's license notice; the members are unchanged | BSD-2-Clause | | CityGML test mesh (`crates/data/tests/data/rocking-chair.gml`), read only by tests | 97 faces of the rocking chair in OGC's CityGML 3.0 sample `Building_LOD3-EPSG25832.gml` ([CityGML-3.0Encodings](https://github.com/opengeospatial/CityGML-3.0Encodings/blob/master/Moved_to_CITYGML-3.0Encoding_CityGML/Examples/Examples-from-CityGML-2.0/building/CityGMLv3/Building_LOD3-EPSG25832.gml)), copyright (c) 2013 3DXScape, copied on 2026-11-12 and rewritten as a CityGML 2.0 object, coordinates unchanged | MIT | | Datum grid test files (`crates/data/tests/data/grids/us_noaa_conus.tif`, `us_noaa_ethpgn.tif`), read only by the datum grid tests | NOAA's NADCON and HARN grids as converted by [PROJ-data](https://github.com/OSGeo/PROJ-data) (`us_noaa`), copied unchanged from [cdn.proj.org](https://cdn.proj.org) | Public domain | | LERC GeoTIFF test files (`crates/data/tests/data/lerc/*.tif`), read only by the LERC tests | Written for the RustGIS project by `make_lerc.py` there with [GDAL](https://gdal.org) 3.9.3 through [rasterio](https://rasterio.readthedocs.io) 1.4.3, run only to write them; the values are made up | Apache-2.0 | diff --git a/README.md b/README.md index 11cdf893d4..7242c23f54 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ Every screenshot is RustGIS itself, rendered offscreen by `cargo run -p rustgis- | Area | Highlights | |---|---| -| **Data** | GeoJSON, CSV/TSV with x/y columns in other coordinate systems or WKT geometry, Excel and OpenDocument spreadsheets, GeoRSS, LandXML, encoded polylines, Shapefile (zipped too, in the browser as well), GeoPackage, GeoParquet, FlatGeobuf, KML/KMZ (with styles), GPX, GML, MapInfo MIF/MID, OpenStreetMap PBF, TopoJSON, CityJSON, CityGML 1.0–3.0, AutoCAD DXF, dBASE tables, PDF and GeoPDF pages (desktop), LiDAR point clouds (LAS, LAZ, COPC) and geotagged photos (large GeoPackage, GeoParquet and FlatGeobuf files, and Shapefiles on the desktop, are read in place), files by their web address, every vector format GDAL reads when it is installed (desktop), Esri File Geodatabases without GDAL (desktop), enterprise geodatabases on SQL Server through their `.sde` files (desktop), PostGIS, MySQL, MariaDB and SQL Server tables read live (desktop), and SQL queries and DuckDB databases through DuckDB Spatial when DuckDB is installed (desktop); PMTiles archives (by web address, or a file on the desktop) and MBTiles files; GeoJSON, CSV, GeoPackage (also as a table added to an existing file), GeoParquet, Shapefile, FlatGeobuf, KML/KMZ, GPX and WKT out (GeoPackage and FlatGeobuf not from the web app); standalone tables; reusable connections; Reload Data for linked files (desktop); geocoding (Find Place, address tables); a Data Sources pane (favourites, recent, saved services, a library) and an SQL pane (desktop); supported QGIS and GeoLibre projects and layer styles; layer and map files, styles, templates and packages | +| **Data** | GeoJSON, CSV/TSV with x/y columns in other coordinate systems or WKT geometry, Excel and OpenDocument spreadsheets, GeoRSS, LandXML, encoded polylines, Shapefile (zipped too, in the browser as well), GeoPackage, GeoParquet, FlatGeobuf, KML/KMZ (with styles), GPX, GML, AIXM (aeronautical information), MapInfo MIF/MID, OpenStreetMap PBF, TopoJSON, CityJSON, CityGML 1.0–3.0, AutoCAD DXF, dBASE tables, PDF and GeoPDF pages (desktop), LiDAR point clouds (LAS, LAZ, COPC) and geotagged photos (large GeoPackage, GeoParquet and FlatGeobuf files, and Shapefiles on the desktop, are read in place), files by their web address, every vector format GDAL reads when it is installed (desktop), Esri File Geodatabases without GDAL (desktop), enterprise geodatabases on SQL Server through their `.sde` files (desktop), PostGIS, MySQL, MariaDB and SQL Server tables read live (desktop), and SQL queries and DuckDB databases through DuckDB Spatial when DuckDB is installed (desktop); PMTiles archives (by web address, or a file on the desktop) and MBTiles files; GeoJSON, CSV, GeoPackage (also as a table added to an existing file), GeoParquet, Shapefile, FlatGeobuf, KML/KMZ, GPX and WKT out (GeoPackage and FlatGeobuf not from the web app); standalone tables; reusable connections; Reload Data for linked files (desktop); geocoding (Find Place, address tables); a Data Sources pane (favourites, recent, saved services, a library) and an SQL pane (desktop); supported QGIS and GeoLibre projects and layer styles; layer and map files, styles, templates and packages | | **Open data** | STAC search (Planetary Computer assets), NASA Earthdata imagery and granule search (GeoTIFFs added on the desktop), Hugging Face, Overture Maps, Source Cooperative, OpenStreetMap by area, geoBoundaries, CKAN, Socrata and ArcGIS Hub portals; S3 buckets with signed connections and a bucket browser; a Data Cubes pane with a catalog of cubes for the time slider (added on the desktop) | | **Rasters** | GeoTIFF and cloud-optimised GeoTIFF (any pixel type, tiled or striped, compressed), ASCII grids, GRIB 1 and 2 (simple packing on latitude/longitude grids), SRTM `.hgt` and DTED elevation, Zarr 2 and 3 stores (a variable at a time step, by web address, or folder on the desktop), and JPEG 2000, NetCDF, HDF, ERDAS Imagine and the other rasters GDAL reads when it is installed (desktop); reprojection by EPSG code; Stretch, RGB, Classify, Unique Values, Colormap and Shaded Relief; DRA, band combinations, brightness/contrast/gamma; raster functions, indices, change detection, classification, georeferencing; cloud-optimised GeoTIFF export (desktop); data cubes, point time-series charts (desktop), temporal summaries and trends (Sen's slope, Mann–Kendall); a spectral profile comparing a multiband raster's bands at points | | **Maps** | Multiple maps and layouts per project, renamed and duplicated from the Browser pane; a GPU renderer (beta) with smooth zoom and pan; tilt, rotation, terrain and a 3D globe; maps of the Moon, Mars and other celestial bodies; each layer kept and drawn in its own coordinate system, picked from PROJ 9.9's catalog by name, method, area or code, with datum grids downloaded on request; Web Mercator or another projection (Equal Earth, Robinson, Winkel Tripel, polar and regional presets, or a [supported](docs/user-guide/maps.md#projections) projected EPSG or ESRI code); a search box for layers, places and coordinates; UTM and MGRS readouts and an MGRS grid; an on-map right-click menu (copy the coordinate, quick buffer, viewshed and line of sight); identify pop-ups with links and pictures; bookmarks, extent history, coordinate navigation; five offline basemaps, with borders in 32 worldviews (31 downloaded when chosen) | diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 9592aab91a..d699926525 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -301,9 +301,10 @@ enum Interpretation { /// What a slice says of itself, and where it is. #[derive(Clone, Debug)] struct Slice { - member: usize, - feature: usize, - slice: usize, + /// Where it is written in the text. + range: (usize, usize), + /// The namespaces in scope there: an index into the read's scopes (0, the root's). + scope: usize, kind: Interpretation, sequence: u64, correction: u64, @@ -411,7 +412,7 @@ struct SliceTrouble { } /// A slice's own properties. -fn slice_of(s: Node, at: (usize, usize, usize), trouble: &mut SliceTrouble) -> Option { +fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTrouble) -> Option { let kind = match child(s, "interpretation").map(|n| text_of(&n)).as_deref() { Some("BASELINE") => Interpretation::Baseline, Some("PERMDELTA") => Interpretation::PermDelta, @@ -464,9 +465,8 @@ fn slice_of(s: Node, at: (usize, usize, usize), trouble: &mut SliceTrouble) -> O return None; } Some(Slice { - member: at.0, - feature: at.1, - slice: at.2, + range, + scope, kind, sequence: number("sequenceNumber"), correction: number("correctionNumber"), @@ -927,6 +927,7 @@ struct Layer { kind: String, label: String, columns: Vec, + named: HashSet, rows: Vec<(Option, Attrs)>, /// Properties not read (nested records): how many features had them, and the first names. nested: usize, @@ -955,13 +956,14 @@ struct Layer { impl Layer { fn column(&mut self, name: &str) -> bool { - if self.columns.iter().any(|c| c == name) { + if self.named.contains(name) { return true; } if self.columns.len() >= MAX_COLUMNS { self.capped += 1; return false; } + self.named.insert(name.to_string()); self.columns.push(name.to_string()); true } @@ -985,16 +987,22 @@ impl Layer { #[derive(Default, Clone)] struct Row { attrs: Attrs, - /// Every column named, null or not, in order. + /// Every column named, null or not, in order, and the same as a set. columns: Vec, + named: HashSet, nested: Vec, + nested_named: HashSet, } impl Row { - fn set(&mut self, key: &str, value: String) { - if !self.columns.iter().any(|c| c == key) { + fn name(&mut self, key: &str) { + if self.named.insert(key.to_string()) { self.columns.push(key.to_string()); } + } + + fn set(&mut self, key: &str, value: String) { + self.name(key); match self.attrs.get_mut(key) { // A property given more than once keeps every value. Some(v) if !value.is_empty() => { @@ -1009,9 +1017,7 @@ impl Row { } fn null(&mut self, key: &str) { - if !self.columns.iter().any(|c| c == key) { - self.columns.push(key.to_string()); - } + self.name(key); } /// A property's simple value as attributes, under `prefix`. @@ -1031,7 +1037,7 @@ impl Row { return; } if elements(p).next().is_some() { - if !self.nested.contains(&name) { + if self.nested_named.insert(name.clone()) { self.nested.push(name); } return; @@ -1047,7 +1053,7 @@ impl Row { /// property's. fn shape_values(&mut self, g: Node, property: &str) { for c in elements(g).filter(is_aixm) { - let prefix = if self.columns.iter().any(|k| k == local(&c)) { format!("{property}_") } else { String::new() }; + let prefix = if self.named.contains(local(&c)) { format!("{property}_") } else { String::new() }; self.property(c, &prefix); } } @@ -1057,6 +1063,11 @@ impl Row { #[derive(Default)] struct Layers { by_key: HashMap<(String, String), usize>, + /// Values rows may still hold: rows copied for a feature's parts or shapes are bounded by the + /// file's size, not by how many times a feature repeats them. + cells_left: usize, + /// Rows left out past that. + rows_over: usize, list: Vec, /// Features of kinds past [`MAX_LAYERS`]. over: usize, @@ -1085,6 +1096,12 @@ impl Layers { } fn push(&mut self, kind: &str, label: &str, geometry: Option, row: Row, notes: Option<&ShapeNotes>) { + let cells = row.columns.len().max(1); + if cells > self.cells_left { + self.rows_over += 1; + return; + } + self.cells_left -= cells; let Some(layer) = self.get(kind, label) else { return }; let mut attrs = Attrs::new(); for c in &row.columns { @@ -1146,6 +1163,56 @@ fn merged(gs: Vec) -> Option { })) } +/// Attribute values the layers may hold whatever the file's size. +const MIN_CELLS: usize = 4_000_000; + +/// Bytes wrapping slices may add whatever the file's size. +const MIN_WRAP_BYTES: usize = 16 << 20; + +/// The scope (an index into `scopes`) of the namespaces in force where slice `sl` is written: the +/// root's (0) unless its member, feature, time slice or itself declares more, when they are +/// written out once for every slice like it. `None` when writing them would pass `wrap_left`. +fn scope_of( + sl: Node, + text: &str, + start: usize, + prefix: usize, + scopes: &mut Vec, + ids: &mut HashMap, + wrap_left: &mut usize, +) -> Option { + // The start tags between the member and the slice's first child, looked at for declarations. + let declares = sl.ancestors().take_while(|a| a.parent_element().is_some()).any(|a| { + let r = a.range(); + let tag_end = a.first_child().map_or(r.end, |c| c.range().start); + r.start + .checked_sub(prefix) + .zip(tag_end.checked_sub(prefix)) + .and_then(|(x, y)| text.get(start + x..start + y)) + .is_some_and(|t| t.contains("xmlns")) + }); + if !declares { + return Some(0); + } + // Each in-scope namespace costs its writing; paid before it is written. + let cost = sl.namespaces().map(|n| n.uri().len() + n.name().map_or(0, str::len) + 10).sum::(); + *wrap_left = wrap_left.checked_sub(cost)?; + let mut decls = String::with_capacity(cost); + for n in sl.namespaces().filter(|n| n.name() != Some("xml")) { + let uri = n.uri().replace('&', "&").replace('<', "<").replace('"', """); + match n.name() { + Some(name) => decls.push_str(&format!(" xmlns:{name}=\"{uri}\"")), + None => decls.push_str(&format!(" xmlns=\"{uri}\"")), + } + } + if let Some(&i) = ids.get(&decls) { + return Some(i); + } + scopes.push(decls.clone()); + ids.insert(decls, scopes.len() - 1); + Some(scopes.len() - 1) +} + /// How each member is parsed: no DTD, and the node limit every XML reader has. fn options<'a>() -> ParsingOptions<'a> { ParsingOptions { allow_dtd: false, nodes_limit: crate::io::XML_NODES, ..ParsingOptions::default() } @@ -1164,6 +1231,8 @@ fn projection<'a, 'i>(v: Option>) -> Option> { /// What the read says of the file as a whole. #[derive(Default)] struct FileNotes { + /// Slices not read: wrapping or parsing them would pass the file's limits. + past_limits: usize, not_in_force: usize, outside_lifetime: usize, no_state: usize, @@ -1215,6 +1284,13 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = HashMap::new(); let mut order: Vec = Vec::new(); let mut trouble = SliceTrouble::default(); + // The namespace declarations slices are parsed with in the second pass: the root's, and any a + // slice has in scope besides (declared on its member, feature or itself), each written once. + let mut scopes: Vec = vec![index.namespaces.clone()]; + let mut scope_ids: HashMap = HashMap::new(); + // What wrapping slices may add to the text parsed, whatever namespaces they declare. + let mut wrap_left = text.len().saturating_mul(4).max(MIN_WRAP_BYTES); + let prefix = "".len(); crate::progress::begin(index.members.len() * 2); for (m, &(start, end)) in index.members.iter().enumerate() { crate::progress::step(1)?; @@ -1222,6 +1298,14 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result".len(); + if extra > wrap_left { + notes.past_limits += 1; + continue; + } + wrap_left -= extra; let mut wrapped = String::new(); wrap(member, &mut wrapped); let Ok(doc) = crate::xml::parse_within(&wrapped, options(), &mut work_left) else { @@ -1230,8 +1314,19 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = - slices_of(f).into_iter().enumerate().filter_map(|(si, s)| slice_of(s, (m, fi, si), &mut trouble)).collect(); + let mut slices = Vec::new(); + for sl in slices_of(f) { + let r = sl.range(); + let Some(range) = r.start.checked_sub(prefix).zip(r.end.checked_sub(prefix)).map(|(a, b)| (start + a, start + b)) else { + notes.unreadable_members += 1; + continue; + }; + let Some(scope) = scope_of(sl, text, start, prefix, &mut scopes, &mut scope_ids, &mut wrap_left) else { + notes.past_limits += 1; + continue; + }; + slices.extend(slice_of(sl, range, scope, &mut trouble)); + } let entry = features.entry(id.clone()).or_insert_with(|| { order.push(id.clone()); Feature { kind: local(&f).to_string(), slices: Vec::new() } @@ -1242,7 +1337,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result = std::iter::once(base.member).chain(changes.iter().map(|s| s.member)).collect(); - wanted.sort_unstable(); - wanted.dedup(); - let texts: Vec<(usize, String)> = wanted - .iter() - .filter_map(|&m| { - let (s, e) = *index.members.get(m)?; - let mut w = String::new(); - wrap(text.get(s..e)?, &mut w); - Some((m, w)) - }) - .collect(); - let mut docs: Vec<(usize, Document)> = Vec::new(); - for (m, w) in &texts { - match crate::xml::parse_within(w, options(), &mut work_left) { - Ok(d) => docs.push((*m, d)), - Err(_) => notes.unreadable_members += 1, + // Its slices in force, each parsed on its own with the namespaces in scope where it is + // written: the text parsed again is the slices', not their members'. + let wanted: Vec<&Slice> = std::iter::once(&base).chain(changes.iter()).collect(); + let mut texts: Vec = Vec::with_capacity(wanted.len()); + for sl in &wanted { + let decls = scopes.get(sl.scope).map_or("", String::as_str); + let body = text.get(sl.range.0..sl.range.1).unwrap_or_default(); + let extra = decls.len() + "".len(); + if extra > wrap_left { + texts.push(String::new()); + continue; } - } - let find = |s: &Slice| -> Option { - let (_, doc) = docs.iter().find(|(m, _)| *m == s.member)?; - let f = *features_of(doc.root_element()).get(s.feature)?; - slices_of(f).get(s.slice).copied() - }; - let Some(base_node) = find(&base) else { - notes.unreadable_members += 1; + wrap_left -= extra; + texts.push(format!("{body}")); + } + let docs: Vec> = + texts.iter().map(|t| if t.is_empty() { None } else { crate::xml::parse_within(t, options(), &mut work_left).ok() }).collect(); + let node = |i: usize| docs.get(i).and_then(Option::as_ref).and_then(|d| elements(d.root_element()).next()); + let Some(base_node) = node(0) else { + notes.past_limits += 1; continue; }; - // The state's properties, each change's replacing all values of the properties it holds. - let mut props = own(base_node); - for c in &changes { - let Some(n) = find(c) else { continue }; - let theirs = own(n); - let names: HashSet<&str> = theirs.iter().map(|p| local(p)).collect(); - props.retain(|p| !names.contains(local(p))); - props.extend(theirs); + // The state's properties, each change's replacing all values of the properties it holds: + // the last change holding a name gives that name's values (worked out in one pass, however + // many changes there are). + let mut layers_of: Vec> = vec![own(base_node)]; + for i in 1..wanted.len() { + match node(i) { + Some(n) => layers_of.push(own(n)), + None => { + notes.past_limits += 1; + layers_of.push(Vec::new()); + } + } + } + let mut last: HashMap<&str, usize> = HashMap::new(); + for (i, ps) in layers_of.iter().enumerate() { + for p in ps { + last.insert(local(p), i); + } } + let last = &last; + let props: Vec = + layers_of.iter().enumerate().flat_map(|(i, ps)| ps.iter().copied().filter(move |p| last.get(local(p)) == Some(&i))).collect(); let mut row = Row::default(); row.set("identifier", id.trim_start_matches("urn:uuid:").to_string()); let valid = |t: Option| t.map(|t| crate::time::format(t, "YYYY-MM-DDTHH:mm:ss") + "Z"); @@ -1459,7 +1560,7 @@ fn airspace( // The BASE volume's limits and width, as written. if let Some((_, _, Some(v))) = components.iter().find(|(_, op, _)| op == "BASE").or(components.first()) { for p in elements(*v).filter(|p| !matches!(local(p), "horizontalProjection" | "centreline" | "contributorAirspace")) { - let prefix = if row.columns.iter().any(|c| c == local(&p)) { "volume_" } else { "" }; + let prefix = if row.named.contains(local(&p)) { "volume_" } else { "" }; row.property(p, prefix); } } @@ -1599,6 +1700,14 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, "members", "of the message couldn't be read (not well-formed XML, or past the reading limits)", ); + say( + &mut file, + notes.past_limits, + "member or time slice", + "members or time slices", + "not read: reading them would pass the limits the file's size sets", + ); + say(&mut file, layers.rows_over, "row", "rows", "past the memory the file's size allows left out"); say(&mut file, index.links, "member", "members", "of the message only point elsewhere (xlink:href) and weren't followed"); if notes.nothing_to_draw > 0 { file.messages.push(format!( diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 291084107d..8b0d46dce2 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -252,6 +252,12 @@ pub fn is_citygml(file_name: &str, bytes: &[u8]) -> bool { matches!(ext.as_str(), "gml" | "xml") && crate::citygml::looks_like_citygml(bytes) } +/// Whether a `.gml` or `.xml` file is an AIXM message (aeronautical information), by its root. +pub fn is_aixm(file_name: &str, bytes: &[u8]) -> bool { + let ext = Path::new(file_name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + matches!(ext.as_str(), "gml" | "xml") && crate::aixm::looks_like_aixm(bytes) +} + /// Whether a file is a city model, CityJSON or CityGML: its layers all come from one reading, which /// takes the coordinate system a caller gives ([`read_city_model`]). pub fn is_city_model(file_name: &str, bytes: &[u8]) -> bool { @@ -285,7 +291,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { // they are added, on the desktop's UI thread, never ahead: within [`BYTES_FLOOR`] whatever the // memory (#2408), wherever they come from. let as_added = matches!(ext.as_str(), "kml" | "kmz" | "rss" | "atom" | "georss" | "landxml") - || (ext == "xml" && !crate::citygml::looks_like_citygml(bytes)); + || (ext == "xml" && !crate::citygml::looks_like_citygml(bytes) && !crate::aixm::looks_like_aixm(bytes)); let max = if as_added { BYTES_FLOOR } else { max_bytes() }; if bytes.len() as u64 > max { return Err(DataError::Format(file_size_error(file_name, max))); @@ -306,6 +312,8 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { let text = String::from_utf8_lossy(bytes.get(..bytes.len().min(8192)).unwrap_or(bytes)); if crate::citygml::looks_like_citygml(bytes) { plain(crate::citygml::read(file_name, bytes, None)?) + } else if crate::aixm::looks_like_aixm(bytes) { + plain(crate::aixm::read(file_name, bytes, &crate::aixm::Options::default())?) } else if crate::landxml::looks_like_landxml(&text) { plain(crate::landxml::read(file_name, bytes, None)?) } else if crate::georss::looks_like_georss(&text) { @@ -319,12 +327,13 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { .collect() } else { return Err(DataError::Format(format!( - "{file_name}: an XML file RustGIS doesn't read (it reads GeoRSS, LandXML, CityGML, KML and GPX)" + "{file_name}: an XML file RustGIS doesn't read (it reads AIXM, GeoRSS, LandXML, CityGML, KML and GPX)" ))); } } // A CityGML city model, or the features of a collection. "gml" if crate::citygml::looks_like_citygml(bytes) => plain(crate::citygml::read(file_name, bytes, None)?), + "gml" if crate::aixm::looks_like_aixm(bytes) => plain(crate::aixm::read(file_name, bytes, &crate::aixm::Options::default())?), "gml" => plain(crate::gml::read(file_name, bytes)?), "dxf" => plain(crate::dxf::read(file_name, bytes, &crate::dxf::Options::default())?), // OpenStreetMap PBF, not a vector tile (`.pbf` too). @@ -360,7 +369,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { /// The extension of a file from its first bytes, for a download whose address doesn't say: /// GeoParquet, FlatGeobuf, GeoTIFF, a zip, a GeoPackage, an ArcGIS feature service's protocol -/// buffer answer (`pbf`), KML, GPX, GeoJSON, delimited text, JPEG 2000, a PDF or GRIB (`None` for +/// buffer answer (`pbf`), KML, GPX, an AIXM message (`xml`), GeoJSON, delimited text, JPEG 2000, a PDF or GRIB (`None` for /// anything else, such as a web page). pub fn sniff_extension(bytes: &[u8]) -> Option<&'static str> { if let Some(ext) = crate::raster::jpeg2000_extension(bytes) { @@ -402,6 +411,8 @@ pub fn sniff_extension(bytes: &[u8]) -> Option<&'static str> { _ if start.starts_with('{') || start.starts_with('[') => "geojson", // A CityGML city model, by its root. _ if start.starts_with('<') && crate::citygml::looks_like_citygml(bytes) => "gml", + // An AIXM message, by its root. + _ if start.starts_with('<') && crate::aixm::looks_like_aixm(bytes) => "xml", _ if start.starts_with('<') && text.contains(" "kml", _ if start.starts_with('<') && text.contains(" "gpx", // Text whose first two lines a separator splits alike, and no control characters. @@ -456,7 +467,7 @@ pub fn read_bytes(file_name: &str, bytes: &[u8]) -> Result<(Dataset, ReadReport) return Err(DataError::Unsupported(format!("{ext} on its own: it is part of a Shapefile; add it together with its .shp"))); } // The first layer (`read_layers` reads them all), saying what else the file holds. - "xml" if is_citygml(file_name, bytes) => return first_layer(file_name, bytes), + "xml" if is_citygml(file_name, bytes) || is_aixm(file_name, bytes) => return first_layer(file_name, bytes), "zip" | "kml" | "kmz" | "gpx" | "gml" | "dxf" | "pbf" | "topojson" => return first_layer(file_name, bytes), "las" | "laz" => crate::lidar::read_bytes(bytes, &name, None)?, // A copy, since only borrowed bytes are given; `read_owned` takes them without one. @@ -531,7 +542,7 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { "xml" => { check_size(path)?; let bytes = crate::provenance::read(path)?; - if !is_citygml(&path.display().to_string(), &bytes) { + if !is_citygml(&path.display().to_string(), &bytes) && !is_aixm(&path.display().to_string(), &bytes) { return Err(DataError::Unsupported("xml".into())); } read_bytes(&path.display().to_string(), &bytes)? @@ -6275,8 +6286,9 @@ mod tests { #[test] fn formats_by_contents() { - let cases: [(&[u8], Option<&str>); 11] = [ + let cases: [(&[u8], Option<&str>); 12] = [ (b"PAR1\0\0", Some("parquet")), + (b"", Some("xml")), (b"fgb\x03fgb\0", Some("fgb")), (b"II*\0\x08\0", Some("tif")), (b"PK\x03\x04", Some("zip")), diff --git a/crates/data/src/xml.rs b/crates/data/src/xml.rs index e4a8600fac..96559ed3ea 100644 --- a/crates/data/src/xml.rs +++ b/crates/data/src/xml.rs @@ -362,6 +362,18 @@ mod tests { assert!(crate::georss::read("a.rss", &flood("rss")).is_err_and(|e| said(e.to_string()))); assert!(crate::landxml::read("a.xml", &flood("LandXML"), None).is_err_and(|e| said(e.to_string()))); assert!(crate::ogc::parse("https://x.example/wms", &flood("WMS_Capabilities")).is_err_and(|e| said(e.to_string()))); + // AIXM parses its members one at a time: each past the budget is counted, and with none + // read, nothing is added. + let aixm = format!( + "{}", + declarations(20_000), + "".repeat(50) + ); + let opts = crate::aixm::Options { at: Some(0.0) }; + assert!( + crate::aixm::read("a.xml", aixm.as_bytes(), &opts) + .is_err_and(|e| e.to_string().contains("couldn't be read") || e.to_string().contains("limits")) + ); } /// Every XML reader refuses a deeply nested document instead of overflowing the stack, run on @@ -386,6 +398,12 @@ mod tests { assert!(crate::georss::read("a.rss", &deep("rss", "channel")).is_err()); assert!(crate::landxml::read("a.xml", &deep("LandXML", "Parcels"), None).is_err()); assert!(crate::ogc::parse("https://x.example/wms", &deep("WMS_Capabilities", "Layer")).is_err()); + let aixm = String::from_utf8(deep("message:AIXMBasicMessage", "message:hasMember")).unwrap_or_default().replacen( + "", + "", + 1, + ); + assert!(crate::aixm::read("a.xml", aixm.as_bytes(), &crate::aixm::Options { at: Some(0.0) }).is_err()); true }) .unwrap() diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 91b84784e8..d7fe28f6a8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -21,7 +21,7 @@ pub const MAX_LAYER_NAME: usize = 200; pub fn commands() -> Vec { vec![ C::new("layer.addData", "Add Data", "Home › Add", add_data).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) - .params(r#"{"path": string, "name"?: string, "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: bool, "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV x/longitude column", "y"?: "CSV y/latitude column", "wkt"?: "CSV WKT geometry column", "delimiter"?: ","|";"|"\\t"|"|"}"#), + .params(r#"{"path": string, "name"?: string, "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: bool, "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV x/longitude column", "y"?: "CSV y/latitude column", "wkt"?: "CSV WKT geometry column", "delimiter"?: ","|";"|"\\t"|"|", "at"?: "an AIXM message's effective date (2026-01-15 or 2026-01-15T12:00Z; UTC unless it says): its features as they are then, today when left out"}"#), C::new("layer.addPhotos", "Add Photos", "Home › Add", add_photos).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( r#"{"paths"?: [JPEG photo files], "folder"?: "a folder of photos (every JPEG in it)", "name"?: "the layer (default Photos; photos join it when it exists)"}"#, ), @@ -51,14 +51,14 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands)", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "at"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands)", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) - .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), + .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "at"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), C::new("layer.addEncodedPolyline", "Add Encoded Polyline", "Home › Add", add_encoded_polyline).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"polyline": "encoded polyline text" | [texts] (one line each), "precision"?: 5 (Google) | 6 (OSRM, Valhalla), "name"?: text}"#, ), - C::new("layer.addDataText", "Add Data (from text)", "Home › Add", add_data_text).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"fileName": "name.geojson|.csv|.tsv|.city.json|.gml|.dxf (CityJSON and CityGML: all their layers)", "text": string, "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"? (as layer.addData, for delimited text; crs also for a CityJSON or CityGML model, and for a DXF), "layer"?, "paperSpace"?, "blocks"? (as layer.addData, for a DXF)}"#), + C::new("layer.addDataText", "Add Data (from text)", "Home › Add", add_data_text).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"fileName": "name.geojson|.csv|.tsv|.city.json|.gml|.dxf (CityJSON and CityGML: all their layers)", "text": string, "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"? (as layer.addData, for delimited text; crs also for a CityJSON or CityGML model, and for a DXF), "layer"?, "paperSpace"?, "blocks"? (as layer.addData, for a DXF), "at"? (as layer.addData, for an AIXM message)}"#), C::new("layer.addSample", "Add Sample Data", "Home › Add › Add Data", add_sample).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": "countries"|"cities"|"rivers"|"lakes"}"#), C::new("layer.remove", "Remove", "Layers", remove).roles(&[]).effects(crate::policy::Effects::NONE) .key("Delete") @@ -2303,15 +2303,45 @@ fn past_read_as_added(path: &str, len: u64) -> Option { (!ahead && len > floor).then(|| rustgis_data::io::file_size_error(path, floor)) } +/// An AIXM message's layers at the effective date `"at"` asks (today when it doesn't), or `None` +/// for a file that isn't one. `"at"` given for any other file is refused, not ignored. +fn aixm_reads(p: &Value, file_name: &str, bytes: &[u8]) -> Result>, String> { + let at = ps(p, "at").map(str::trim).filter(|t| !t.is_empty()); + if !rustgis_data::io::is_aixm(file_name, bytes) { + return match at { + Some(_) => Err(format!("\"at\" is the effective date of an AIXM message, and {file_name} isn't one")), + None => Ok(None), + }; + } + let opts = at.map(rustgis_data::aixm::Options::at_text).transpose()?.unwrap_or_default(); + let reads = rustgis_data::aixm::read(file_name, bytes, &opts).map_err(|e| e.to_string())?; + Ok(Some(reads.into_iter().map(|(dataset, report)| rustgis_data::io::LayerRead { dataset, report, styles: Vec::new() }).collect())) +} + /// Whether the desktop app reads a file of several layers whole ahead, off the UI thread -/// ([`add_data_ahead`], [`read_layers_file`]): a ZIP, a city model, a GML, GPX or TopoJSON file, -/// an OpenStreetMap extract (`.pbf`; a large one goes to GDAL instead where it is installed, and +/// ([`add_data_ahead`], [`read_layers_file`]): a ZIP, a city model, an AIXM message, a GML, GPX or +/// TopoJSON file, an OpenStreetMap extract (`.pbf`; a large one goes to GDAL instead where it is installed, and /// isn't read ahead, [`large_osm`]). #[cfg(not(target_arch = "wasm32"))] fn read_ahead_whole(path: &str) -> bool { let lower = path.to_ascii_lowercase(); [".zip", ".gml", ".gpx", ".topojson", ".pbf"].iter().any(|e| lower.ends_with(e)) - || (rustgis_data::io::is_multi_layer_name(path) && is_city_model_path(path)) + || (rustgis_data::io::is_multi_layer_name(path) && (is_city_model_path(path) || is_aixm_path(path))) +} + +/// Whether Add Data reads `path` as an AIXM message: a `.gml` or `.xml` file whose root (in its +/// first bytes, read here) is an `AIXMBasicMessage`. +#[cfg(not(target_arch = "wasm32"))] +fn is_aixm_path(path: &str) -> bool { + use std::io::Read; + let lower = path.to_ascii_lowercase(); + if !(lower.ends_with(".gml") || lower.ends_with(".xml")) { + return false; + } + let mut head = Vec::new(); + rustgis_data::provenance::open(path) + .and_then(|f| f.take(rustgis_data::aixm::HEAD_BYTES as u64).read_to_end(&mut head)) + .is_ok_and(|_| rustgis_data::aixm::looks_like_aixm(&head)) } /// Whether Add Data reads `path` as a city model's layers: a CityJSON model named `.city.json`, or @@ -2348,6 +2378,9 @@ fn read_layers_file(p: &Value, path: &str) -> LayersRead { let bytes = rustgis_data::provenance::read(path).map_err(|e| format!("{path}: {e}"))?; let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string()); let crs = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()); + if let Some(reads) = aixm_reads(p, &full, &bytes)? { + return Ok((full, reads)); + } let reads = match crs { Some(text) if full.to_ascii_lowercase().ends_with(".zip") => { rustgis_data::io::read_zip_in(&full, &bytes, Some(rustgis_data::raster::Crs::parse(text)?)) @@ -2754,7 +2787,10 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u let overlays = if kml && ps(p, "layer").is_none() { ground_overlays(s, file_name, bytes, local_file) } else { Vec::new() }; // A DXF drawing: its coordinate system (it never says) and one of its own layers. let dxf = rustgis_data::dxf::is_dxf_name(file_name); + // An AIXM message, at the effective date asked (today when none is). + let aixm = aixm_reads(p, file_name, bytes)?; let reads = match crs.filter(|_| landxml) { + _ if aixm.is_some() => aixm.unwrap_or_default(), _ if lower.ends_with(".zip") && crs.is_some() => { let crs = crs.map(|text| super::parse_crs(s, text)).transpose()?; rustgis_data::io::read_zip_in(file_name, bytes, crs) @@ -6064,8 +6100,9 @@ pub(crate) fn address_extension(url: &str) -> Option { } /// `layer.addUrl` keys for other kinds of address, which a window (`"bbox"`) doesn't read. -const WINDOW_UNREAD: [&str; 17] = [ +const WINDOW_UNREAD: [&str; 18] = [ "layer", + "at", "x", "y", "wkt", @@ -6861,11 +6898,15 @@ pub(crate) fn add_data_text_after(s: &mut Session, p: &Value, zoom: Option let raw_name = s_req(p, "fileName")?; let name = super::raster::bytes_file_name(raw_name).ok_or("fileName is required")?; let text = s_req(p, "text")?; - // A city model: all its layers, in the coordinate system given or with a layer picked. A DXF + // A city model or an AIXM message: all its layers, in the coordinate system given or with a layer picked. A DXF // drawing too, which takes its coordinate system and whether its blocks are drawn from here. if rustgis_data::dxf::is_dxf_name(name) || rustgis_data::cityjson::is_cityjson_name(name) || rustgis_data::io::is_citygml(name, text.as_bytes()) + // An AIXM message: all its layers, at the date asked; an effective date given for any + // other text is refused there. + || rustgis_data::io::is_aixm(name, text.as_bytes()) + || ps(p, "at").is_some_and(|t| !t.trim().is_empty()) || (["crs", "layer"].iter().any(|k| ps(p, k).is_some_and(|c| !c.trim().is_empty())) && rustgis_data::io::is_cityjson(name, text.as_bytes())) { diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index b15422068f..7b3e19ad4a 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -471,7 +471,7 @@ fn asked_by(asked: &Value, params: &Value) -> bool { // `cog`, `dates`, a `name` that isn't text…) it leaves out. `zoom` it passes on, but may change // (a link's data, once zoomed to), so it isn't compared. let passed_on = |k: &str, v: &Value| match k { - "name" | "layer" | "crs" | "connection" => v.as_str().is_some_and(|s| !s.trim().is_empty()), + "name" | "layer" | "crs" | "connection" | "at" => v.as_str().is_some_and(|s| !s.trim().is_empty()), "x" | "y" | "wkt" | "delimiter" | "paperSpace" | "blocks" | "stream" | "as" => !v.is_null(), "service" | "coverage" | "anonymous" => v == &json!(true), "bounds" => v.is_array(), diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 21cee18f32..87ef1d8903 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -37,7 +37,7 @@ pub fn commands() -> Vec { .inputs(crate::cmd::Inputs::single_layer).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view() .params(r#"{"layer"?:name|id}"#), C::new("layer.addDataBytes", "Add Data (from file contents)", "Home › Add", add_bytes::).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"fileName": "name.tif|.tiff|.asc|.grb|.grib|.grb2|.grib2 (GRIB)|.hgt|.dt0|.dt1|.dt2|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData)}"#), + .params(r#"{"fileName": "name.tif|.tiff|.asc|.grb|.grib|.grb2|.grib2 (GRIB)|.hgt|.dt0|.dt1|.dt2|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "at"? (as layer.addData)}"#), C::new("raster.symbology", "Symbology", "Style › Rendering", symbology).when(need_raster).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer"?, "type": "stretch"|"rgb"|"classify"|"unique"|"colormap"|"shadedRelief", "band"?: 1.., "ramp"?, "invert"?: bool, "classes"?: 1..32, "method"?, "azimuth"?, "altitude"?, "zFactor"?, "shadow"?: 0..1 (shadedRelief: how dark the shadows the terrain casts are; left out, kept; 0 casts none), "sky"?: 0..1 (shadedRelief: how much the share of the sky each cell sees dims its ambient light; left out, kept; 0 leaves it whole), "fill"?: 0..1 (shadedRelief: a fill light from the side opposite the sun that lightens the slopes turned toward it; left out, kept; 0 has none), "ambient"?: 0..1|null (shadedRelief: the share of the colour a slope turned fully from the sun keeps; left out, kept; null, the default: 0.25, or 0.5 balanced), "balanced"?: bool (shadedRelief: flat ground keeps the ramp's colour and slopes facing the sun brighten, up to 1.3; left out, kept; false, the default, lights as before), "rock"?: {"from"?: 0..90, "to"?: 0..90, "color"?: #RRGGBB} | false (shadedRelief: steep slopes tinted toward a rock colour before the light, from the ground's own slope in degrees, without the Z factor: the ramp below from, the colour above to, blended between; left out, kept; an object's missing keys keep the current rock's, or 25, 40 and #B2ACA4; false or null removes it), "grey"?: bool (shadedRelief without its colour ramp)}"#, ), @@ -863,7 +863,7 @@ pub(crate) fn add_named_bytes_read( let text = String::from_utf8(bytes).map_err(|_| format!("{name} is not a text file"))?; // The delimited-text and naming parameters carry over (not the data, already decoded). let mut q = json!({"fileName": name, "text": text}); - for k in ["name", "x", "y", "wkt", "crs", "delimiter", "layer", "paperSpace", "blocks"] { + for k in ["name", "x", "y", "wkt", "crs", "delimiter", "layer", "paperSpace", "blocks", "at"] { if let Some(v) = p.get(k) { q[k] = v.clone(); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 520cdb06e2..614dbcefd0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24125,6 +24125,35 @@ fn spreadsheets_feeds_landxml_and_polylines() { let _ = std::fs::remove_dir_all(dir); } +/// An AIXM message through the commands: a layer per kind at the effective date asked, from a +/// path and from text, an "at" that isn't a date refused, and "at" refused for any other file. +#[test] +fn aixm_messages_are_added_at_the_date_asked() { + let donlon = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../data/tests/data/donlon-aixm.xml")); + let dir = std::env::temp_dir().join(format!("rustgis-aixm-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("donlon.xml"); + std::fs::write(&path, donlon).unwrap(); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path.display().to_string(), "at": "2026-01-15"})).unwrap(); + for name in ["donlon Airspace", "donlon DesignatedPoint", "donlon RouteSegment", "donlon AirportHeliport ARP"] { + assert!(s.map().layer_by_name(name).is_some(), "no {name}"); + } + // Runways have no geometry of their own: a table of the project. + assert!(s.project.tables.iter().any(|t| t.dataset.name == "donlon Runway")); + // The same as text, before every feature began: nothing to add, and why. + let text = String::from_utf8(donlon.to_vec()).unwrap(); + let e = s.run("layer.addDataText", &json!({"fileName": "early.xml", "text": text, "at": "2000-01-01"})).unwrap_err(); + assert!(e.contains("not in force"), "{e}"); + let e = s.run("layer.addData", &json!({"path": path.display().to_string(), "at": "someday"})).unwrap_err(); + assert!(e.contains("isn't a date"), "{e}"); + let gpx = dir.join("track.gpx"); + std::fs::write(&gpx, r#"W"#).unwrap(); + let e = s.run("layer.addData", &json!({"path": gpx.display().to_string(), "at": "2026-01-15"})).unwrap_err(); + assert!(e.contains("isn't one"), "{e}"); + let _ = std::fs::remove_dir_all(dir); +} + /// A raster GDAL reads, added with a coordinate system: the project names the file and the /// choice, and opens it again after the conversion cache is cleared. (Runs where GDAL is.) #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e095f26fcc..f293bd17c5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -6047,7 +6047,7 @@ impl RustGisApp { }; // The request receipt is correlation only; its admitted claim stays outside JSON. let mut q = json!({"url": url}); - for k in ["name", "layer", "crs", "connection", "from"] { + for k in ["name", "layer", "crs", "connection", "from", "at"] { if let Some(v) = p.get(k).filter(|v| v.as_str().is_some_and(|s| !s.trim().is_empty())) { q[k] = v.clone(); } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index d2aac138ef..8567e4c3e4 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,6 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled or given only as changes are left out and counted. Simple properties are fields, with their unit (`_uom`) and, for a reference to another feature, its identifier and title (`_title`); vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A vertical structure gives a row per part. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 9d867d3716..cafdb29b32 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -15,7 +15,7 @@ Formats](data-formats.md). | FlatGeobuf (`.fgb`) | Yes | Yes (`share.exportLayer`) | | KML/KMZ (with their styles), GPX | Yes | Yes | | Spreadsheets (`.xlsx`, `.xls`, `.ods`), GeoRSS feeds, LandXML, encoded polylines | Yes | No | -| GML, MapInfo MIF/MID, OpenStreetMap PBF, TopoJSON, CityJSON and CityGML (footprints with heights), AutoCAD DXF (ASCII) | Yes | No | +| GML, AIXM (aeronautical information), MapInfo MIF/MID, OpenStreetMap PBF, TopoJSON, CityJSON and CityGML (footprints with heights), AutoCAD DXF (ASCII) | Yes | No | | LiDAR point clouds: LAS, LAZ, COPC (an evenly spread sample) | Yes | No | | Geotagged photos (JPEG with EXIF GPS): points with their thumbnails | Yes | No | | Esri File Geodatabase (`.gdb` folder; 3D multipatches as footprints) | Yes (desktop) | No | From d2cd189f6a5f7dab79d2eae66fd51311c5720cb6 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:34:44 -0600 Subject: [PATCH 03/61] fix(data): AIXM clippy lints, and charge namespace scopes as written --- crates/data/src/aixm.rs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index d699926525..c8689f1cf2 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -229,10 +229,10 @@ fn declarations(e: &BytesStart) -> String { let value = &a.value; let quote = if value.contains('"') { '\'' } else { '"' }; out.push(' '); - out.push_str(&key); + out.push_str(key); out.push('='); out.push(quote); - out.push_str(&value); + out.push_str(value); out.push(quote); } } @@ -331,7 +331,7 @@ enum State { /// Withdrawn by the date, or not yet created (`featureLifetime`). OutsideLifetime, /// Only changes (PERMDELTA, TEMPDELTA) and no state to apply them to. - NoState, + OnlyChanges, /// Every slice canceled. Canceled, } @@ -356,7 +356,7 @@ fn state_at(slices: &[Slice], t: f64) -> State { } let live: Vec<&Slice> = held.values().copied().filter(|s| !s.canceled).collect(); if live.is_empty() { - return if slices.is_empty() { State::NoState } else { State::Canceled }; + return if slices.is_empty() { State::OnlyChanges } else { State::Canceled }; } let of = |k: Interpretation| live.iter().copied().filter(move |s| s.kind == k); // The BASELINE in force; of several (which the concept doesn't allow), the latest started. @@ -378,7 +378,7 @@ fn state_at(slices: &[Slice], t: f64) -> State { match snap { Some(s) if baselines == 0 => (s, true), _ if baselines > 0 => return State::NotInForce, - _ => return State::NoState, + _ => return State::OnlyChanges, } } }; @@ -1195,7 +1195,20 @@ fn scope_of( return Some(0); } // Each in-scope namespace costs its writing; paid before it is written. - let cost = sl.namespaces().map(|n| n.uri().len() + n.name().map_or(0, str::len) + 10).sum::(); + // Charged as written: escaping can make a URI six times longer (`"` as `"`). + let escaped = |u: &str| { + u.len() + + u.bytes() + .map(|b| match b { + b'&' => 4, + b'<' => 3, + b'"' => 5, + _ => 0, + }) + .sum::() + }; + let cost = + sl.namespaces().filter(|n| n.name() != Some("xml")).map(|n| escaped(n.uri()) + n.name().map_or(0, str::len) + 10).sum::(); *wrap_left = wrap_left.checked_sub(cost)?; let mut decls = String::with_capacity(cost); for n in sl.namespaces().filter(|n| n.name() != Some("xml")) { @@ -1361,7 +1374,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result { + State::OnlyChanges => { notes.no_state += 1; continue; } @@ -1527,7 +1540,7 @@ fn mark(layers: &mut Layers, kind: &str, label: &str, temporary: usize, snapshot } /// An airspace: its volumes' operations decide what is drawn. Its limits are its BASE volume's. -#[allow(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "an airspace reads into the row, the shapes, the layers and its notes at once")] fn airspace( props: &[Node], row: &mut Row, From b06eb67f0f92c1d7ba4b0896847a2ae72fbbfe9a Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:47:05 -0600 Subject: [PATCH 04/61] fix: AIXM review findings: bounded rows, counted kinds and members, "at" refused on every other path --- crates/data/src/aixm.rs | 292 ++++++++++++++++++++++---------- crates/data/src/aixm/tests.rs | 80 ++++++++- crates/data/src/io.rs | 3 + crates/engine/src/cmd/layer.rs | 60 +++++-- crates/engine/src/cmd/raster.rs | 2 + crates/engine/src/tests.rs | 17 ++ docs/user-guide/data-formats.md | 2 +- 7 files changed, 355 insertions(+), 101 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index c8689f1cf2..a5a78c0165 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -144,6 +144,8 @@ struct Index { namespaces: String, /// `hasMember`s that only point elsewhere (`xlink:href`), not followed. links: usize, + /// `hasMember`s holding nothing. + empty: usize, /// Where the text stops being XML, when it does before the root ends. broken_at: Option, } @@ -153,7 +155,9 @@ impl Index { let mut reader = Reader::from_str(text); let mut index = Index::default(); let (mut depth, mut rooted) = (0usize, false); - let mut member: Option = None; + // The member being read: where it starts, whether it points elsewhere, and whether it + // holds an element. + let mut member: Option<(usize, bool, bool)> = None; loop { let start = usize::try_from(reader.buffer_position()).unwrap_or(usize::MAX); let event = match reader.read_event() { @@ -166,9 +170,6 @@ impl Index { let end = usize::try_from(reader.buffer_position()).unwrap_or(usize::MAX); match event { Event::Start(ref e) | Event::Empty(ref e) if depth == 0 => { - if rooted { - return Err(DataError::Format(format!("{file_name}: more than one root element"))); - } rooted = true; if e.local_name().into_inner() != "AIXMBasicMessage" || !namespace_of(e).is_some_and(|ns| ns.starts_with(AIXM)) { return Err(DataError::Format(format!( @@ -184,21 +185,37 @@ impl Index { } Event::Start(e) => { if depth == 1 && e.local_name().into_inner() == "hasMember" { - member = Some(start); + member = Some((start, has_href(&e), false)); + } else if depth == 2 + && let Some(m) = member.as_mut() + { + m.2 = true; } depth += 1; } Event::Empty(e) => { if depth == 1 && e.local_name().into_inner() == "hasMember" { - index.links += usize::from(e.attributes().flatten().any(|a| a.key.local_name().into_inner() == "href")); + if has_href(&e) { + index.links += 1; + } else { + index.empty += 1; + } + } else if depth == 2 + && let Some(m) = member.as_mut() + { + m.2 = true; } } Event::End(_) => { depth = depth.saturating_sub(1); if depth == 1 - && let Some(s) = member.take() + && let Some((s, href, held)) = member.take() { - index.members.push((s, end)); + match (held, href) { + (true, _) => index.members.push((s, end)), + (false, true) => index.links += 1, + (false, false) => index.empty += 1, + } } if depth == 0 { break; @@ -220,6 +237,11 @@ impl Index { } } +/// Whether an element points elsewhere (`xlink:href`). +fn has_href(e: &BytesStart) -> bool { + e.attributes().flatten().any(|a| a.key.local_name().into_inner() == "href") +} + /// An element's namespace declarations, as attributes to write on a wrapper. fn declarations(e: &BytesStart) -> String { let mut out = String::new(); @@ -482,6 +504,11 @@ fn features_of<'a, 'i>(wrapper: Node<'a, 'i>) -> Vec> { elements(wrapper).next().map(|m| elements(m).filter(is_aixm).collect()).unwrap_or_default() } +/// The elements of a member that aren't AIXM features (another schema's), not read. +fn foreign_in(wrapper: Node) -> usize { + elements(wrapper).next().map_or(0, |m| elements(m).filter(|c| !is_aixm(c)).count()) +} + /// A feature's time slices, in order. fn slices_of<'a, 'i>(feature: Node<'a, 'i>) -> Vec> { elements(feature).filter(|c| local(c) == "timeSlice").filter_map(|t| elements(t).next()).collect() @@ -523,12 +550,15 @@ struct ShapeNotes { } /// Reads shapes, adding at most `budget` points to the file's positions. +#[derive(Default)] struct Shapes { budget: usize, /// A system other than longitude/latitude a geometry was in (not read). other_system: Option, /// Geometries with no `srsName`, read as `urn:ogc:def:crs:EPSG::4326`. assumed_system: usize, + /// Whether the shape being read had one. + assumed_now: bool, /// A geographic system other than WGS 84 a geometry was read in as if it were. as_wgs84: Option, } @@ -543,6 +573,22 @@ fn next_to(c: Coord, near: f64) -> Coord { Coord::new(near + wrap180(c.x - near), c.y) } +impl ShapeNotes { + /// Adds what another shape's reading found. + fn absorb(&mut self, o: ShapeNotes) { + self.arcs |= o.arcs; + self.coarse |= o.coarse; + self.zm |= o.zm; + for n in o.unread_segments { + if !self.unread_segments.contains(&n) { + self.unread_segments.push(n); + } + } + self.rings_lost += o.rings_lost; + self.referenced += o.referenced; + } +} + impl Shapes { /// Takes up to `n` added points from the budget: how many may be added. fn take(&mut self, n: usize, notes: &mut ShapeNotes) -> usize { @@ -557,7 +603,7 @@ impl Shapes { /// The system a geometry is in: its own `srsName` or its nearest ancestor's. fn axes(&mut self, g: Node) -> Option { let Some(name) = g.ancestors().find_map(|a| a.attribute("srsName")).map(str::trim) else { - self.assumed_system += 1; + self.assumed_now = true; return Some(Axes { swap: true }); }; if crate::ogc::warp::is_crs84(name) { @@ -598,10 +644,11 @@ impl Shapes { for p in v.chunks(dim) { let (a, b) = (*p.first()?, *p.get(1)?); let c = if axes.swap { Coord::new(b, a) } else { Coord::new(a, b) }; - if !c.is_finite() || c.y.abs() > 90.0 { + if !c.is_finite() || c.y.abs() > 90.0 || c.x.abs() > 540.0 { return None; } - out.push(c); + // Next to the position before, so a line across the antimeridian stays continuous. + out.push(out.last().map_or(c, |l: &Coord| next_to(c, l.x))); } } Some(out) @@ -673,7 +720,9 @@ impl Shapes { } let (d, az, _) = rustgis_geom::wgs84_inverse(a, b); if d.is_finite() && d > GEODESIC_STEP_M { - let want = ((d / GEODESIC_STEP_M).ceil() as usize).min(MAX_GEODESIC_POINTS); + let need = (d / GEODESIC_STEP_M).ceil() as usize; + notes.coarse |= need > MAX_GEODESIC_POINTS; + let want = need.min(MAX_GEODESIC_POINTS); let n = self.take(want.saturating_sub(1), notes) + 1; for k in 1..n { let (p, _) = rustgis_geom::wgs84_direct(a, az, d * k as f64 / n as f64); @@ -695,7 +744,9 @@ impl Shapes { /// How many pieces an arc of `radius_m` turning `sweep_deg` is drawn with. fn pieces(&mut self, radius_m: f64, sweep_deg: f64, notes: &mut ShapeNotes) -> usize { let step = if radius_m <= ARC_TOLERANCE_M { 90.0 } else { (2.0 * (1.0 - ARC_TOLERANCE_M / radius_m).acos()).to_degrees() }; - let want = ((sweep_deg.abs() / step.max(1e-6)).ceil() as usize).clamp(4, MAX_ARC_POINTS); + let need = (sweep_deg.abs() / step.max(1e-6)).ceil() as usize; + notes.coarse |= need > MAX_ARC_POINTS; + let want = need.clamp(4, MAX_ARC_POINTS); self.take(want - 1, notes) + 1 } @@ -726,7 +777,7 @@ impl Shapes { // they grow; in a longitude-first one from east, counter-clockwise. let (bearing0, sweep) = match (local(&s), end) { ("CircleByCenterPoint", _) => (if axes.swap { start } else { 90.0 - start }, 360.0), - (_, Some(end)) if (end - start).abs() < 360.0 => { + (_, Some(end)) if (end - start).abs() <= 360.0 => { let d = end - start; if axes.swap { (start, d) } else { (90.0 - start, -d) } } @@ -761,6 +812,13 @@ impl Shapes { } i += 2; } + // An odd position past the last arc: joined straight, and said. + if !circle && i + 1 < c.len() { + out.extend(c.iter().skip(i + 1).copied()); + if !notes.unread_segments.iter().any(|n| n == "ArcString") { + notes.unread_segments.push("ArcString".to_string()); + } + } out } @@ -813,8 +871,10 @@ impl Shapes { let mut out: Vec = Vec::new(); for m in elements(r).filter(|c| local(c) == "curveMember") { let Some(c) = elements(m).next() else { + // Said as a border by reference, not also as a ring left out. if m.attribute((XLINK, "href")).is_some() { notes.referenced += 1; + notes.rings_lost = notes.rings_lost.saturating_sub(1); } return None; }; @@ -868,6 +928,13 @@ impl Shapes { /// A geometry element (AIXM's or GML's) as a geometry. fn shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { + self.assumed_now = false; + let shape = self.read_shape(g, notes); + self.assumed_system += usize::from(self.assumed_now); + shape + } + + fn read_shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { match local(&g) { "Point" | "ElevatedPoint" => self.point(g, notes), "Curve" | "ElevatedCurve" | "LineString" => self.curve(g, notes).map(|c| Geometry::Line(vec![c])), @@ -877,11 +944,12 @@ impl Shapes { } } -/// Metres in one of a length's units: UCUM's (`m`, `km`, `[nmi_i]`, `[ft_i]`, `[mi_i]`) and AIXM's +/// Meters in one of a length's units: UCUM's (`m`, `km`, `[nmi_i]`, `[ft_i]`, `[mi_i]`) and AIXM's /// (`M`, `KM`, `NM`, `FT`, `MI`). fn meters_per(uom: &str) -> Option { Some(match uom.trim() { "m" | "M" => 1.0, + "cm" | "CM" => 0.01, "km" | "KM" => 1000.0, "[nmi_i]" | "NM" | "nmi" => 1852.0, "[ft_i]" | "FT" | "ft" => 0.3048, @@ -992,17 +1060,29 @@ struct Row { named: HashSet, nested: Vec, nested_named: HashSet, + /// Values of names past [`MAX_COLUMNS`], not kept. + capped: usize, } impl Row { - fn name(&mut self, key: &str) { - if self.named.insert(key.to_string()) { - self.columns.push(key.to_string()); + /// Names a column; false past [`MAX_COLUMNS`] names, when its value isn't kept (counted). + fn name(&mut self, key: &str) -> bool { + if self.named.contains(key) { + return true; + } + if self.columns.len() >= MAX_COLUMNS { + self.capped += 1; + return false; } + self.named.insert(key.to_string()); + self.columns.push(key.to_string()); + true } fn set(&mut self, key: &str, value: String) { - self.name(key); + if !self.name(key) { + return; + } match self.attrs.get_mut(key) { // A property given more than once keeps every value. Some(v) if !value.is_empty() => { @@ -1017,7 +1097,7 @@ impl Row { } fn null(&mut self, key: &str) { - self.name(key); + let _ = self.name(key); } /// A property's simple value as attributes, under `prefix`. @@ -1069,40 +1149,59 @@ struct Layers { /// Rows left out past that. rows_over: usize, list: Vec, - /// Features of kinds past [`MAX_LAYERS`]. - over: usize, + /// Features of kinds past [`MAX_LAYERS`], by identifier. + over: HashSet, } impl Layers { - fn get(&mut self, kind: &str, label: &str) -> Option<&mut Layer> { + /// The layer of a kind and label, made when there is room for another. + fn index_of(&mut self, kind: &str, label: &str) -> Option { let key = (kind.to_string(), label.to_string()); - let i = match self.by_key.get(&key) { - Some(&i) => i, - None if self.list.len() >= MAX_LAYERS => { - self.over += 1; - return None; - } + match self.by_key.get(&key) { + Some(&i) => Some(i), + None if self.list.len() >= MAX_LAYERS => None, None => { self.list.push(Layer { kind: kind.to_string(), label: label.to_string(), ..Layer::default() }); self.by_key.insert(key, self.list.len() - 1); - self.list.len() - 1 + Some(self.list.len() - 1) } - }; - self.list.get_mut(i) + } + } + + fn at(&mut self, i: Option) -> Option<&mut Layer> { + i.and_then(|i| self.list.get_mut(i)) } fn has_kind(&self, kind: &str) -> bool { self.list.iter().any(|l| l.kind == kind) } - fn push(&mut self, kind: &str, label: &str, geometry: Option, row: Row, notes: Option<&ShapeNotes>) { + /// Adds a row to the layer of `kind` and `label`, which it returns; `None` when it is left out + /// (counted): past the values the file's size allows, or a kind past [`MAX_LAYERS`]. + /// `change` says whether the feature is as a TEMPDELTA has it, or a SNAPSHOT. + fn push( + &mut self, + kind: &str, + label: &str, + geometry: Option, + row: Row, + notes: Option<&ShapeNotes>, + change: (bool, bool), + ) -> Option { let cells = row.columns.len().max(1); if cells > self.cells_left { self.rows_over += 1; - return; + return None; } + let Some(i) = self.index_of(kind, label) else { + self.over.insert(row.attrs.get("identifier").cloned().unwrap_or_default()); + return None; + }; self.cells_left -= cells; - let Some(layer) = self.get(kind, label) else { return }; + let layer = self.list.get_mut(i)?; + layer.capped += row.capped; + layer.temporary += usize::from(change.0); + layer.snapshots += usize::from(change.1); let mut attrs = Attrs::new(); for c in &row.columns { if layer.column(c) @@ -1121,6 +1220,7 @@ impl Layers { layer.take_notes(n); } layer.rows.push((geometry, attrs)); + Some(i) } } @@ -1244,6 +1344,8 @@ fn projection<'a, 'i>(v: Option>) -> Option> { /// What the read says of the file as a whole. #[derive(Default)] struct FileNotes { + /// Elements of members that aren't AIXM features. + foreign: usize, /// Slices not read: wrapping or parsing them would pass the file's limits. past_limits: usize, not_in_force: usize, @@ -1281,7 +1383,15 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 { + why.push(format!("{} only point elsewhere (xlink:href)", index.links)); + } + if let Some(at) = index.broken_at { + why.push(format!("the file stops being well-formed XML at byte {at}")); + } + let why = if why.is_empty() { String::new() } else { format!(": {}", why.join("; ")) }; + return Err(DataError::Format(format!("{file_name}: no features (hasMember elements) in the AIXM message{why}"))); } let mut work_left = crate::xml::namespace_budget(text.len()); let wrap = |member: &str, out: &mut String| { @@ -1325,6 +1435,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result = Vec::new(); @@ -1452,16 +1563,14 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0, snapshot); if TABLE_KINDS.contains(&kind.as_str()) { - layers.push(&kind, "", None, row, None); - mark(&mut layers, &kind, "", temporary, snapshot); + layers.push(&kind, "", None, row, None, change); } else if layers.has_kind(&kind) { let label = layers.list.iter().find(|l| l.kind == kind).map(|l| l.label.clone()).unwrap_or_default(); - layers.push(&kind, &label, None, row, None); - if let Some(l) = layers.get(&kind, &label) { + let i = layers.push(&kind, &label, None, row, None, change); + if let Some(l) = layers.at(i) { l.shapeless += 1; - l.temporary += usize::from(temporary > 0); - l.snapshots += usize::from(snapshot); } } else { notes.nothing_to_draw += 1; @@ -1492,25 +1601,36 @@ fn feature_rows( _ => row.property(*p, ""), } } + let change = (temporary > 0, snapshot); if shaped.is_empty() { - // Shapes nested in records (a marking's elements, a light system's lights): by family. - let mut by_family: BTreeMap<&'static str, Vec> = BTreeMap::new(); - let mut notes = ShapeNotes::default(); + // Shapes nested in records (a marking's elements, a light system's lights): by family, + // each family with what its own shapes' reading found. + let mut by_family: BTreeMap<&'static str, (Vec, ShapeNotes)> = BTreeMap::new(); + let mut lost = ShapeNotes::default(); for p in props.iter().filter(|p| elements(**p).next().is_some()) { let nested = p.descendants().skip(1).filter(|d| d.is_element() && (is_aixm(d) || is_gml(d)) && SHAPES.contains(&local(d))); // Not those inside another shape (a surface's curves). for g in nested.filter(|g| !g.ancestors().skip(1).take_while(|a| a != p).any(|a| SHAPES.contains(&local(&a)))) { - if let Some(geom) = shapes.shape(g, &mut notes) { - by_family.entry(family(&geom)).or_default().push(geom); + let mut notes = ShapeNotes::default(); + match shapes.shape(g, &mut notes) { + Some(geom) => { + let (gs, n) = by_family.entry(family(&geom)).or_default(); + gs.push(geom); + n.absorb(notes); + } + None => lost.absorb(notes), } } } if by_family.is_empty() { return false; } - for (label, gs) in by_family { - layers.push(kind, label, merged(gs), row.clone(), Some(¬es)); - mark(layers, kind, label, temporary, snapshot); + let mut first = true; + for (label, (gs, mut notes)) in by_family { + if std::mem::take(&mut first) { + notes.absorb(std::mem::take(&mut lost)); + } + layers.push(kind, label, merged(gs), row.clone(), Some(¬es), change); } return true; } @@ -1521,24 +1641,15 @@ fn feature_rows( r.shape_values(g, &name); // A kind's shapes under different properties are different layers (an airport's reference // point and its boundary); a kind with one is one layer, titled by its kind alone. - let label = name.as_str(); let bad = geom.is_none(); - layers.push(kind, label, geom, r, Some(¬es)); - if let Some(l) = layers.get(kind, label) { + let i = layers.push(kind, &name, geom, r, Some(¬es), change); + if let Some(l) = layers.at(i) { l.unreadable += usize::from(bad); } - mark(layers, kind, label, temporary, snapshot); } true } -fn mark(layers: &mut Layers, kind: &str, label: &str, temporary: usize, snapshot: bool) { - if let Some(l) = layers.get(kind, label) { - l.temporary += usize::from(temporary > 0); - l.snapshots += usize::from(snapshot); - } -} - /// An airspace: its volumes' operations decide what is drawn. Its limits are its BASE volume's. #[expect(clippy::too_many_arguments, reason = "an airspace reads into the row, the shapes, the layers and its notes at once")] fn airspace( @@ -1592,8 +1703,8 @@ fn airspace( geom = merged(parts); } } - layers.push(kind, "", geom, row.clone(), Some(notes)); - if let Some(l) = layers.get(kind, "") { + let i = layers.push(kind, "", geom, row.clone(), Some(notes), (temporary > 0, snapshot)); + if let Some(l) = layers.at(i) { if !drawable { l.derived += 1; for (_, op, v) in &components { @@ -1611,7 +1722,6 @@ fn airspace( l.unions += 1; } } - mark(layers, kind, "", temporary, snapshot); true } @@ -1641,8 +1751,21 @@ fn vertical_structure( return false; } let mut rows = Vec::new(); - for vp in parts { + // Rows copied for the parts stay within what the file's size allows: checked before each copy, + // so a structure of many parts and many values can't outgrow it. + let mut room = layers.cells_left; + let count = parts.len(); + for (k, vp) in parts.into_iter().enumerate() { + if row.columns.len().max(1) > room { + layers.rows_over += count - k; + break; + } let mut r = row.clone(); + // What the structure lacks is said once for it, not for each part. + if k > 0 { + r.nested.clear(); + r.nested_named.clear(); + } let mut notes = ShapeNotes::default(); let mut geom = None; let mut bad = false; @@ -1656,17 +1779,18 @@ fn vertical_structure( _ => r.property(p, "part_"), } } + room = room.saturating_sub(r.columns.len().max(1)); rows.push((geom, r, notes, bad)); } // A part with no shape goes with the structure's first family of parts. let first = rows.iter().find_map(|(g, ..)| g.as_ref().map(family)).unwrap_or("points"); - for (geom, r, notes, bad) in rows { + for (k, (geom, r, notes, bad)) in rows.into_iter().enumerate() { let label = geom.as_ref().map_or(first, family); - layers.push(kind, label, geom, r, Some(¬es)); - if let Some(l) = layers.get(kind, label) { + let change = if k == 0 { (temporary > 0, snapshot) } else { (false, false) }; + let i = layers.push(kind, label, geom, r, Some(¬es), change); + if let Some(l) = layers.at(i) { l.unreadable += usize::from(bad); } - mark(layers, kind, label, temporary, snapshot); } true } @@ -1722,19 +1846,14 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, ); say(&mut file, layers.rows_over, "row", "rows", "past the memory the file's size allows left out"); say(&mut file, index.links, "member", "members", "of the message only point elsewhere (xlink:href) and weren't followed"); - if notes.nothing_to_draw > 0 { - file.messages.push(format!( - "{} features of kinds with nothing to draw left out ({})", - notes.nothing_to_draw, - notes.nothing_names.said() - )); - } + let nothing = format!("of kinds with nothing to draw left out ({})", notes.nothing_names.said()); + say(&mut file, notes.nothing_to_draw, "feature", "features", ¬hing); + say(&mut file, notes.foreign, "element", "elements", "of members that aren't AIXM features (another schema's) not read"); + say(&mut file, index.empty, "member", "members", "of the message hold nothing"); if let Some(at) = index.broken_at { file.messages.push(format!("the file stops being well-formed XML at byte {at}: features after it weren't read")); } - if layers.over > 0 { - file.messages.push(format!("{} features of more than {MAX_LAYERS} kinds were left out", layers.over)); - } + say(&mut file, layers.over.len(), "feature", "features", &format!("of kinds past the first {MAX_LAYERS} left out")); if let Some(s) = ¬es.other_system { file.messages.push(format!("geometry in '{s}', not longitude/latitude, wasn't read")); } @@ -1773,9 +1892,10 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, }) .collect(); let mut ds = Dataset::new(title, GeometryType::None, fields); - for (g, attrs) in &layer.rows { + let mut layer = layer; + for (g, attrs) in std::mem::take(&mut layer.rows) { let row = ds.fields.iter().map(|f| attrs.get(&f.name).map_or(Value::Null, |v| Value::parse_file(v, f.ty))).collect(); - ds.push_next(g.clone(), row); + ds.push_next(g, row); } ds.geometry_type = crate::io::dominant_type(&ds); let mut rep = if out.is_empty() { std::mem::take(&mut file) } else { ReadReport::default() }; @@ -1816,8 +1936,8 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, ); say( layer.coarse, - "feature has arcs or geodesics drawn with fewer points than that needs: the file's point allowance ran out", - "features have arcs or geodesics drawn with fewer points than that needs: the file's point allowance ran out", + "feature has arcs or geodesics drawn with fewer points than that needs (a curve's most points, or the file's point allowance, ran out)", + "features have arcs or geodesics drawn with fewer points than that needs (a curve's most points, or the file's point allowance, ran out)", ); let segments = layer.unread_segments.said(); say( @@ -1827,8 +1947,8 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, ); say( layer.rings_lost, - "ring or surface patch was left out: too few points, unreadable, or a border given by reference", - "rings or surface patches were left out: too few points, unreadable, or borders given by reference", + "ring or surface patch was left out: too few points, or unreadable", + "rings or surface patches were left out: too few points, or unreadable", ); say( layer.referenced, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index d05cedd172..8106497fdd 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -375,7 +375,7 @@ fn an_arc_in_a_longitude_first_system_is_the_same_arc() { #[test] fn an_arc_through_three_points_passes_through_them() { - let mut shapes = Shapes { budget: 1_000_000, other_system: None, assumed_system: 0, as_wgs84: None }; + let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; let mut notes = ShapeNotes::default(); let (a, m, b) = (Coord::new(10.0, 50.0), Coord::new(10.1, 50.07), Coord::new(10.2, 50.0)); let arc = shapes.arc_through(a, m, b, false, &mut notes); @@ -387,7 +387,7 @@ fn an_arc_through_three_points_passes_through_them() { #[test] fn arcs_past_the_point_allowance_are_drawn_coarser_and_said() { - let mut shapes = Shapes { budget: 0, other_system: None, assumed_system: 0, as_wgs84: None }; + let mut shapes = Shapes::default(); let mut notes = ShapeNotes::default(); let n = shapes.pieces(50_000.0, 180.0, &mut notes); assert_eq!(n, 1); @@ -510,3 +510,79 @@ fn an_effective_date_is_read_from_text() { assert_eq!(Options::at_text("2026-01-15").unwrap(), at("2026-01-15")); assert!(Options::at_text("next tuesday").unwrap_err().contains("isn't a date")); } + +// --------------------------------------------------------------------------------------------- +// Bounds and counts from review. +// --------------------------------------------------------------------------------------------- + +#[test] +fn a_structure_of_many_parts_and_values_stays_within_the_files_allowance() { + let values: String = (0..2000).map(|i| format!("x")).collect(); + let parts = "".repeat(10_000); + let body = format!("MANY{values}{parts}"); + let bytes = message(&feature( + "VerticalStructure", + "v", + &[slice("VerticalStructure", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)], + )); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + let rows: usize = out.iter().map(|(d, _)| d.features.len()).sum(); + let cells: usize = out.iter().map(|(d, _)| d.features.len() * d.fields.len()).sum(); + assert!(rows < 10_000 && cells <= MIN_CELLS, "{rows} rows, {cells} cells"); + let notes = said(&out); + assert!(notes.iter().any(|m| m.contains("past the memory the file's size allows")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains(&format!("past the first {MAX_COLUMNS} names"))), "{notes:?}"); +} + +#[test] +fn kinds_past_the_layer_limit_are_counted_once_a_feature() { + let members: String = (0..70) + .map(|k| { + let kind = format!("Kind{k}"); + feature(&kind, &format!("id{k}"), &[slice(&kind, "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &named_point("P"))]) + }) + .collect(); + let out = read("t.xml", &message(&members), &at("2026-01-15")).unwrap(); + assert_eq!(out.len(), MAX_LAYERS); + let notes = said(&out); + assert!(notes.iter().any(|m| m == &format!("6 features of kinds past the first {MAX_LAYERS} left out")), "{notes:?}"); +} + +#[test] +fn members_with_no_aixm_feature_are_counted() { + let foreign = r#""#; + let only_link = r#""#; + let empty = ""; + let members = point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "A")]) + foreign + only_link + empty; + let notes = names(&message(&members), "2026-01-15").1; + for want in [ + "1 element of members that aren't AIXM features (another schema's) not read", + "1 member of the message only point elsewhere (xlink:href) and weren't followed", + "1 member of the message hold nothing", + ] { + assert!(notes.iter().any(|m| m == want), "{want}: {notes:?}"); + } +} + +#[test] +fn an_arc_from_0_to_360_is_a_full_circle() { + let bytes = String::from_utf8(arc_airspace(true)).unwrap().replace( + r#"-90.0137.0"#, + r#"0360"#, + ); + let out = read("t.xml", bytes.as_bytes(), &at("2026-01-15")).unwrap(); + let ring = ring(layer(&out, "t Airspace").features[0].geometry.as_ref().unwrap()); + let center = Coord::new(-36.16666667, 55.23333333); + let south = ring.iter().filter(|c| (meters_between(**c, center) - 46_300.0).abs() < 1.0).map(|c| c.y).fold(f64::MAX, f64::min); + assert!(south < 54.82, "the circle reaches south of its center: {south}"); +} + +#[test] +fn a_ring_across_the_antimeridian_stays_continuous() { + let body = r#"PACIFIC0 179.50 179 0 -179 1 -179 1 179 0 179"#; + let bytes = message(&feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), body)])); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t WorkArea extent"); + let ring = ring(ds.features[0].geometry.as_ref().unwrap()); + assert!(ring.windows(2).all(|w| (w[0].x - w[1].x).abs() < 3.0), "{ring:?}"); +} diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 8b0d46dce2..dff1da4135 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3600,6 +3600,9 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut read_dbf(b, cpg.as_deref(), name, budget).map(|r| vec![r]) } else if is_city_model(leaf, &b) { read_city_member(leaf, &b, crs) + } else if is_aixm(leaf, &b) { + // An AIXM message: all its layers, as it is today. + crate::aixm::read(leaf, &b, &crate::aixm::Options::default()) } else if is_delimited_name(leaf) { read_delimited_bytes_budget(leaf, &b, &CsvOptions { crs, ..Default::default() }, budget).map(|r| vec![r]) } else { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index d7fe28f6a8..1345794f3e 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2012,6 +2012,8 @@ fn add_geodatabase(s: &mut Session, p: &Value, path: &str) -> CmdResult { /// DBF picks with geometry follow the full Shapefile import path. fn add_data(s: &mut Session, p: &Value) -> CmdResult { let path = s_req(p, "path")?; + // An effective date is for an AIXM message only: refused for any other file, not ignored. + check_at(p, path, || may_be_aixm_path(path))?; #[cfg(not(target_arch = "wasm32"))] if Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("dbf")) { if let Some(read) = super::reads::take::(s, &dbf_shapefile_key(path)) { @@ -2222,10 +2224,10 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { super::say_crs_note(s, crs); } let (full, reads) = read?; - // City models and OSM keep the file-wide report on their first layer. A feature-service + // City models, AIXM messages and OSM keep the file-wide report on their first layer. A feature-service // PBF has only one layer, so this flag does not transfer any report for it. #[cfg(not(target_arch = "wasm32"))] - let whole = is_city_model_path(path) || path.to_ascii_lowercase().ends_with(".pbf"); + let whole = is_city_model_path(path) || is_aixm_path(path) || path.to_ascii_lowercase().ends_with(".pbf"); #[cfg(target_arch = "wasm32")] let whole = !path.to_ascii_lowercase().ends_with(".zip"); return add_picked(s, p, &full, reads, whole, Vec::new(), None); @@ -2306,18 +2308,50 @@ fn past_read_as_added(path: &str, len: u64) -> Option { /// An AIXM message's layers at the effective date `"at"` asks (today when it doesn't), or `None` /// for a file that isn't one. `"at"` given for any other file is refused, not ignored. fn aixm_reads(p: &Value, file_name: &str, bytes: &[u8]) -> Result>, String> { - let at = ps(p, "at").map(str::trim).filter(|t| !t.is_empty()); - if !rustgis_data::io::is_aixm(file_name, bytes) { - return match at { - Some(_) => Err(format!("\"at\" is the effective date of an AIXM message, and {file_name} isn't one")), - None => Ok(None), - }; + let aixm = rustgis_data::io::is_aixm(file_name, bytes); + let opts = check_at(p, file_name, || aixm)?; + if !aixm { + return Ok(None); + } + if ps(p, "crs").is_some_and(|c| !c.trim().is_empty()) { + return Err(format!("\"crs\" doesn't apply to {file_name}: an AIXM message names its own system (srsName)")); } - let opts = at.map(rustgis_data::aixm::Options::at_text).transpose()?.unwrap_or_default(); let reads = rustgis_data::aixm::read(file_name, bytes, &opts).map_err(|e| e.to_string())?; Ok(Some(reads.into_iter().map(|(dataset, report)| rustgis_data::io::LayerRead { dataset, report, styles: Vec::new() }).collect())) } +/// The effective date `"at"` asks of an AIXM message, read as `aixm` says whether the file is +/// one: refused when it isn't text, isn't a date, or is given for any other file, never ignored. +pub(crate) fn check_at(p: &Value, file_name: &str, aixm: impl FnOnce() -> bool) -> Result { + let at = match p.get("at") { + None | Some(Value::Null) => return Ok(rustgis_data::aixm::Options::default()), + Some(Value::String(t)) if t.trim().is_empty() => return Ok(rustgis_data::aixm::Options::default()), + Some(Value::String(t)) => t.trim(), + Some(_) => return Err("\"at\" is a date written as text, such as 2026-01-15 or 2026-01-15T12:00Z".to_string()), + }; + if !aixm() { + let zipped = if file_name.to_ascii_lowercase().ends_with(".zip") { + " (an AIXM message in a zip is read as it is today: unzip it to choose a date)" + } else { + "" + }; + return Err(format!("\"at\" is the effective date of an AIXM message, and {file_name} isn't one{zipped}")); + } + rustgis_data::aixm::Options::at_text(at) +} + +/// Whether a file named `path` may be an AIXM message: by its first bytes on the desktop, by its +/// name in the browser (where its contents are checked when read). +fn may_be_aixm_path(path: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + return is_aixm_path(path); + #[cfg(target_arch = "wasm32")] + { + let lower = path.to_ascii_lowercase(); + lower.ends_with(".xml") || lower.ends_with(".gml") + } +} + /// Whether the desktop app reads a file of several layers whole ahead, off the UI thread /// ([`add_data_ahead`], [`read_layers_file`]): a ZIP, a city model, an AIXM message, a GML, GPX or /// TopoJSON file, an OpenStreetMap extract (`.pbf`; a large one goes to GDAL instead where it is installed, and @@ -2784,11 +2818,13 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u let lower = file_name.to_ascii_lowercase(); let kml = lower.ends_with(".kml") || lower.ends_with(".kmz"); // A KML's ground overlays (pictures) are raster layers, added after its placemarks. + // An AIXM message, at the effective date asked (today when none is); "at" for any other file + // is refused before anything else is read of it. + let aixm = aixm_reads(p, file_name, bytes)?; let overlays = if kml && ps(p, "layer").is_none() { ground_overlays(s, file_name, bytes, local_file) } else { Vec::new() }; // A DXF drawing: its coordinate system (it never says) and one of its own layers. let dxf = rustgis_data::dxf::is_dxf_name(file_name); - // An AIXM message, at the effective date asked (today when none is). - let aixm = aixm_reads(p, file_name, bytes)?; + let whole_aixm = aixm.is_some(); let reads = match crs.filter(|_| landxml) { _ if aixm.is_some() => aixm.unwrap_or_default(), _ if lower.ends_with(".zip") && crs.is_some() => { @@ -2824,7 +2860,7 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u if dxf { return add_reads(s, p, file_name, reads, overlays, zoom); } - let whole = rustgis_data::io::is_city_model(file_name, bytes) || rustgis_data::osm::looks_like_osm_pbf(bytes); + let whole = whole_aixm || rustgis_data::io::is_city_model(file_name, bytes) || rustgis_data::osm::looks_like_osm_pbf(bytes); add_picked(s, p, file_name, reads, whole, overlays, zoom) } diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 87ef1d8903..94321401a1 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -787,6 +787,8 @@ pub(crate) fn add_named_bytes_read( drawn: Option, asked: Option, ) -> CmdResult { + // An effective date is for an AIXM message only: refused for any other file, not ignored. + super::layer::check_at(p, &name, || rustgis_data::io::is_aixm(&name, &bytes))?; // A geotagged photo (an upload, a drop): a point in the photo layer, so several uploads // gather in one. let scan = wants_scan(p, &name)?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 614dbcefd0..95f4e367c1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24151,6 +24151,23 @@ fn aixm_messages_are_added_at_the_date_asked() { std::fs::write(&gpx, r#"W"#).unwrap(); let e = s.run("layer.addData", &json!({"path": gpx.display().to_string(), "at": "2026-01-15"})).unwrap_err(); assert!(e.contains("isn't one"), "{e}"); + // A single-layer file too, and the bytes of one: refused, never ignored. + let geojson = dir.join("roads.geojson"); + std::fs::write(&geojson, r#"{"type":"FeatureCollection","features":[]}"#).unwrap(); + let e = s.run("layer.addData", &json!({"path": geojson.display().to_string(), "at": "2026-01-15"})).unwrap_err(); + assert!(e.contains("isn't one"), "{e}"); + let e = s.run("layer.addData", &json!({"path": path.display().to_string(), "at": 20260115})).unwrap_err(); + assert!(e.contains("written as text"), "{e}"); + let e = s.run("layer.addData", &json!({"path": path.display().to_string(), "crs": "EPSG:3857"})).unwrap_err(); + assert!(e.contains("names its own system"), "{e}"); + // A layer picked that isn't the first still gets what the file as a whole says. + let later = r#"late2030-01-01T00:00:00ZBASELINE10LATER"#; + let text = String::from_utf8(donlon.to_vec()).unwrap().replacen("", &format!("{later}"), 1); + let picked = dir.join("picked.xml"); + std::fs::write(&picked, text).unwrap(); + s.notices.clear(); + s.run("layer.addData", &json!({"path": picked.display().to_string(), "layer": "picked Runway", "at": "2026-01-15"})).unwrap(); + assert!(s.notices.iter().any(|n| n.text.contains("1 feature not in force")), "{:?}", s.notices); let _ = std::fs::remove_dir_all(dir); } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 8567e4c3e4..3224c3c1fe 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled or given only as changes are left out and counted. Simple properties are fields, with their unit (`_uom`) and, for a reference to another feature, its identifier and title (`_title`); vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A vertical structure gives a row per part. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled or given only as changes are left out and counted. Simple properties are fields, with their unit (`_uom`) and, for a reference to another feature, its identifier and title (`_title`); vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A vertical structure gives a row per part. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 7ed3fe052c27103c7eb1b3da66fa86842b663133 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:02:58 -0600 Subject: [PATCH 05/61] fix: AIXM /code-review findings: picked layers keep only file-wide notes, sources recorded, lone volumes drawn, references said --- crates/data/src/aixm.rs | 73 +++++++++++++++++++++++-------- crates/data/src/aixm/tests.rs | 69 +++++++++++++++++++++++++++++ crates/data/src/io.rs | 14 +++++- crates/engine/command-surface.txt | 12 ++--- crates/engine/src/cmd/layer.rs | 23 ++++++++-- 5 files changed, 162 insertions(+), 29 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index a5a78c0165..9abe9254e6 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -553,14 +553,18 @@ struct ShapeNotes { #[derive(Default)] struct Shapes { budget: usize, - /// A system other than longitude/latitude a geometry was in (not read). + /// A system other than longitude/latitude a geometry was in (not read), and how many were. other_system: Option, + other_count: usize, + other_now: bool, /// Geometries with no `srsName`, read as `urn:ogc:def:crs:EPSG::4326`. assumed_system: usize, /// Whether the shape being read had one. assumed_now: bool, - /// A geographic system other than WGS 84 a geometry was read in as if it were. + /// A geographic system other than WGS 84 a geometry was read in as if it were, and how many. as_wgs84: Option, + as_wgs84_count: usize, + as_wgs84_now: bool, } fn wrap180(d: f64) -> f64 { @@ -613,11 +617,13 @@ impl Shapes { Some(c) if c.is_geographic() => { if c.epsg() != 4326 { self.as_wgs84.get_or_insert_with(|| name.to_string()); + self.as_wgs84_now = true; } Some(Axes { swap: crate::gml::lat_first(name, c) }) } _ => { self.other_system.get_or_insert_with(|| name.to_string()); + self.other_now = true; None } } @@ -871,10 +877,10 @@ impl Shapes { let mut out: Vec = Vec::new(); for m in elements(r).filter(|c| local(c) == "curveMember") { let Some(c) = elements(m).next() else { - // Said as a border by reference, not also as a ring left out. + // Said as a border by reference by the ring's patch, not also as a ring + // left out. if m.attribute((XLINK, "href")).is_some() { notes.referenced += 1; - notes.rings_lost = notes.rings_lost.saturating_sub(1); } return None; }; @@ -909,16 +915,19 @@ impl Shapes { }; let mut polys = Vec::new(); for p in patches { + // A ring lost to a border by reference is said as that, once. + let before = notes.referenced; let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, notes)); let Some(outer) = outer else { - notes.rings_lost += 1; + notes.rings_lost += usize::from(notes.referenced == before); continue; }; let mut rings = vec![outer]; for b in elements(p).filter(|c| local(c) == "interior") { + let before = notes.referenced; match self.ring(b, notes) { Some(r) => rings.push(r), - None => notes.rings_lost += 1, + None => notes.rings_lost += usize::from(notes.referenced == before), } } polys.push(rings); @@ -928,9 +937,11 @@ impl Shapes { /// A geometry element (AIXM's or GML's) as a geometry. fn shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { - self.assumed_now = false; + (self.assumed_now, self.other_now, self.as_wgs84_now) = (false, false, false); let shape = self.read_shape(g, notes); self.assumed_system += usize::from(self.assumed_now); + self.other_count += usize::from(self.other_now); + self.as_wgs84_count += usize::from(self.as_wgs84_now); shape } @@ -1359,9 +1370,9 @@ struct FileNotes { /// Features of kinds with nothing to draw, left out. nothing_to_draw: usize, nothing_names: Names, - other_system: Option, + other_system: Option<(String, usize)>, assumed_system: usize, - as_wgs84: Option, + as_wgs84: Option<(String, usize)>, } /// Reads an AIXM message into a layer per feature kind (and per geometry property, for kinds with @@ -1577,8 +1588,8 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0, snapshot) } else { (false, false) }; + let shapeless = geom.is_none() && !bad; let i = layers.push(kind, label, geom, r, Some(¬es), change); if let Some(l) = layers.at(i) { l.unreadable += usize::from(bad); + l.shapeless += usize::from(shapeless); } } true @@ -1854,11 +1884,17 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, file.messages.push(format!("the file stops being well-formed XML at byte {at}: features after it weren't read")); } say(&mut file, layers.over.len(), "feature", "features", &format!("of kinds past the first {MAX_LAYERS} left out")); - if let Some(s) = ¬es.other_system { - file.messages.push(format!("geometry in '{s}', not longitude/latitude, wasn't read")); + if let Some((s, n)) = ¬es.other_system { + say(&mut file, *n, "geometry", "geometries", &format!("in a system other than longitude/latitude ('{s}', or another) not read")); } - if let Some(s) = ¬es.as_wgs84 { - file.messages.push(format!("geometry in '{s}' was read as WGS 84 longitude/latitude")); + if let Some((s, n)) = ¬es.as_wgs84 { + say( + &mut file, + *n, + "geometry", + "geometries", + &format!("in a geographic system other than WGS 84 ('{s}', or another) read as WGS 84 longitude/latitude"), + ); } say( &mut file, @@ -1978,7 +2014,8 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, ); if layer.zm > 0 { ds.zm_dropped = true; - rep.messages.push(format!("{name}: {}", crate::zm_note(Some(layer.zm as u64)))); + // First, as every reader's: a layer picked from the file says it, the others don't. + rep.messages.insert(0, format!("{name}: {}", crate::zm_note(Some(layer.zm as u64)))); } out.push((ds, rep)); } diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 8106497fdd..37c34f36e8 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -586,3 +586,72 @@ fn a_ring_across_the_antimeridian_stays_continuous() { let ring = ring(ds.features[0].geometry.as_ref().unwrap()); assert!(ring.windows(2).all(|w| (w[0].x - w[1].x).abs() < 3.0), "{ring:?}"); } + +// --------------------------------------------------------------------------------------------- +// From /code-review. +// --------------------------------------------------------------------------------------------- + +/// An airspace of one volume, its component written as `component` around the volume. +fn one_volume(component: &str) -> Vec { + let volume = r#"50 10 50 11 51 11 51 10 50 10"#; + let body = format!("ONE{}", component.replace("VOLUME", volume)); + message(&feature("Airspace", "one", &[slice("Airspace", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])) +} + +#[test] +fn a_lone_volume_with_no_operation_is_drawn() { + let bytes = one_volume( + r#"VOLUME"#, + ); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + assert!(layer(&out, "t Airspace").features[0].geometry.is_some()); + assert!(said(&out).is_empty(), "{:?}", said(&out)); +} + +#[test] +fn a_volume_given_by_reference_keeps_the_airspace_from_being_drawn_partly() { + let bytes = one_volume( + r#"BASE1VOLUME"#, + ); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t Airspace").features[0].geometry, None); + assert!(said(&out).iter().any(|m| m.contains("a volume given by reference")), "{:?}", said(&out)); +} + +#[test] +fn a_border_given_by_reference_is_said_once() { + let body = r#"REF"#; + let bytes = message(&feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), body)])); + let notes = said(&read("t.xml", &bytes, &at("2026-01-15")).unwrap()); + assert!(notes.iter().any(|m| m.contains("1 border is given by reference")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("ring or surface patch was left out")), "{notes:?}"); +} + +#[test] +fn a_part_with_no_shape_is_counted() { + let located = r#"A47 -27"#; + let bare = r#"B"#; + let body = format!("VS{located}{bare}"); + let bytes = message(&feature( + "VerticalStructure", + "v", + &[slice("VerticalStructure", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)], + )); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t VerticalStructure").features.len(), 2); + assert!(said(&out).iter().any(|m| m.contains("1 feature has no geometry")), "{:?}", said(&out)); +} + +#[test] +fn a_layers_z_note_comes_first() { + let bytes = String::from_utf8(message(&point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "Z")]))) + .unwrap() + .replace("45.71 -35.17", "45.71 -35.17 12") + + ""; + let later = point("late", &[baseline(1, 0, "2030-01-01T00:00:00Z", None, "LATER")]); + let bytes = bytes.replacen("", &format!("{later}"), 1); + let out = read("t.xml", bytes.as_bytes(), &at("2026-01-15")).unwrap(); + let first = &out[0].1.messages; + assert!(first.first().is_some_and(|m| m.text.contains("Z or M")), "{:?}", first.iter().map(|m| &m.text).collect::>()); + assert!(first.iter().any(|m| m.text.contains("not in force"))); +} diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index dff1da4135..06169cf988 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3601,8 +3601,18 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut } else if is_city_model(leaf, &b) { read_city_member(leaf, &b, crs) } else if is_aixm(leaf, &b) { - // An AIXM message: all its layers, as it is today. - crate::aixm::read(leaf, &b, &crate::aixm::Options::default()) + // An AIXM message: all its layers, as it is today. It names its own system, so a + // system given for the zip isn't used for it, and that is said. + crate::aixm::read(leaf, &b, &crate::aixm::Options::default()).map(|mut layers| { + if crs.is_some() + && let Some((_, report)) = layers.first_mut() + { + report + .messages + .push(format!("{leaf}: the coordinate system given isn't used for an AIXM message, which names its own")); + } + layers + }) } else if is_delimited_name(leaf) { read_delimited_bytes_budget(leaf, &b, &CsvOptions { crs, ..Default::default() }, budget).map(|r| vec![r]) } else { diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 2f99f709a9..8c76eae783 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -186,7 +186,7 @@ info.commands info.databaseTables database password? info.diagnostics info.fileColumns path delimiter? layer? crs? -info.fileLayers path crs? +info.fileLayers path crs? at? info.infographic layer? info.project nameFilter? includeFields? job.new name description? assigned? viewExtent? @@ -212,17 +212,17 @@ labels.resetMoved layer? class? all? labels.scaleRange layer? class? min? max? clear? labels.style layer? class? size? color? halo? haloColor? haloWidth? spacing? stretch? bold? italic? font? background? wrapChar? wrapLength? lineAlign? labels.viewUnplaced on? -layer.addData path name? layer? paperSpace? blocks? stream? as? crs? x? y? wkt? delimiter? -layer.addDataBytes fileName data zoom? layer? name? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? -layer.addDataText fileName text name? x? y? wkt? crs? delimiter? layer? paperSpace? blocks? +layer.addData path name? layer? paperSpace? blocks? stream? as? crs? x? y? wkt? delimiter? at? +layer.addDataBytes fileName data zoom? layer? name? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? at? +layer.addDataText fileName text name? x? y? wkt? crs? delimiter? layer? paperSpace? blocks? at? layer.addDatabase database password? layer? crs? name? stream? -layer.addDownload id url name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? service? bounds? coverage? coverageCrs? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? +layer.addDownload id url name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? at? service? bounds? coverage? coverageCrs? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? layer.addEncodedPolyline polyline precision? name? layer.addLayerFile path? text? data? layer.addPhotos paths? folder? name? layer.addSample name layer.addSql sql name? database? password? crs? stream? ran? -layer.addUrl url bytes? format? name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? whole? cog? bbox? cellSize? cube? start? end? unit? interval? dates? connection? service? bounds? from? fromDocument? anonymous? coverage? coverageCrs? request? +layer.addUrl url bytes? format? name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? at? whole? cog? bbox? cellSize? cube? start? end? unit? interval? dates? connection? service? bounds? from? fromDocument? anonymous? coverage? coverageCrs? request? layer.addZarr path url variable? index? cells? bbox? crs? name? time? start? end? ran? summary? layer.aggregation layer? shape size? layer.blend layer? mode diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1345794f3e..c5accb43cd 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -27,7 +27,7 @@ pub fn commands() -> Vec { ), C::new("info.fileLayers", "List Layers in File", "Home › Add › Add Data", file_layers).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .params(r#"{"path": string, "crs"?: "EPSG:… for a CityJSON model (.city.json, a .json, or in a zip) or a CityGML model (.gml, .xml, or in a zip): it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows (as layer.addData)"}"#), + .params(r#"{"path": string, "crs"?: "EPSG:… for a CityJSON model (.city.json, a .json, or in a zip) or a CityGML model (.gml, .xml, or in a zip): it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows (as layer.addData)", "at"?: "an AIXM message's effective date: its layers then (as layer.addData)"}"#), C::new("info.fileColumns", "List Columns in File", "Home › Add › Add Data › Delimited Text", file_columns).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().params( r#"{"path": "a delimited text file (CSV, TSV, TXT, DAT, or gzip-compressed text) or a spreadsheet", "delimiter"?: ","|";"|"\\t"|"|", "layer"?: "a spreadsheet's sheet (the first by default)", "crs"?: "EPSG:… (or WKT), as layer.addData: a projected system keeps the columns found by name"}"#, ), @@ -2317,7 +2317,15 @@ fn aixm_reads(p: &Value, file_name: &str, bytes: &[u8]) -> Result CmdResult { return Err(rustgis_data::io::file_size_error(path, max)); } let bytes = rustgis_data::provenance::read(path).map_err(|e| format!("{path}: {e}"))?; + // An AIXM message's layers at the date asked, as Add Data would add them. + if let Some(reads) = aixm_reads(p, path, &bytes)? { + let layers: Vec = reads.into_iter().map(|l| l.dataset.name).collect(); + return Ok(json!({"count": layers.len(), "layers": layers})); + } let zip = path.to_ascii_lowercase().ends_with(".zip"); let layers: Vec = match crs.filter(|_| zip || rustgis_data::io::is_city_model(path, &bytes)) { Some(crs) => { @@ -6942,7 +6959,7 @@ pub(crate) fn add_data_text_after(s: &mut Session, p: &Value, zoom: Option // An AIXM message: all its layers, at the date asked; an effective date given for any // other text is refused there. || rustgis_data::io::is_aixm(name, text.as_bytes()) - || ps(p, "at").is_some_and(|t| !t.trim().is_empty()) + || p.get("at").is_some_and(|v| v.as_str().map_or(!v.is_null(), |t| !t.trim().is_empty())) || (["crs", "layer"].iter().any(|k| ps(p, k).is_some_and(|c| !c.trim().is_empty())) && rustgis_data::io::is_cityjson(name, text.as_bytes())) { From 95795f8d48962db8db4fe1cb4ccc840d4a8a2a52 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:24:34 -0600 Subject: [PATCH 06/61] feat(data): keep every AIXM value: nested records as path columns, a row per record holding shapes --- crates/data/src/aixm.rs | 349 +++++++++++++++++++++++--------- crates/data/src/aixm/tests.rs | 100 ++++++++- docs/user-guide/data-formats.md | 2 +- 3 files changed, 355 insertions(+), 96 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 9abe9254e6..10c3139ff4 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -21,9 +21,13 @@ //! clockwise from true north, the arc running from the start angle to the end angle (clockwise when //! the start is the smaller); in a longitude-first one (CRS84), counter-clockwise from east. //! -//! A property's simple value is an attribute, with its unit (`_uom`) and, for a reference to -//! another feature, the identifier it names (`urn:uuid:` left off) and its title (`_title`). A -//! nested record isn't, and is counted. An airspace is drawn from its single BASE volume, or from +//! Every value a feature holds is kept on its rows. A property's simple value is a column, with its +//! unit (`_uom`), why it is missing (`_nilReason`) and its other attributes, and for a reference to +//! another feature the identifier it names (`urn:uuid:` left off) and its title (`_title`). A +//! value nested in records is a column named by its path (`authority_1_type`, +//! `availability_usage_selection_timeInterval_day`), each record numbered when it repeats anywhere +//! in the layer, so the values of one record share their columns on every row. The values written +//! on a shape (elevation, accuracy, datum) are kept wherever the shape is. An airspace is drawn from its single BASE volume, or from //! BASE and UNION volumes as the parts of one shape; one built by subtraction, intersection or from //! other airspaces is kept without a shape and counted, not drawn wrong. A vertical structure gives a //! row per part. Runways, runway directions and routes, which have no geometry of their own, are @@ -55,7 +59,9 @@ const XSI: &str = "http://www.w3.org/2001/XMLSchema-instance"; /// Most layers read from one file. const MAX_LAYERS: usize = 64; /// Most attribute columns of a layer. -const MAX_COLUMNS: usize = 500; +const MAX_COLUMNS: usize = 2000; +/// Deepest a nested value is read: past it a record's values are counted, not kept. +const MAX_PATH: usize = 64; /// The farthest a drawn arc strays from the curve, in meters. const ARC_TOLERANCE_M: f64 = 1.0; /// Most points one arc or circle is drawn with. @@ -1007,11 +1013,8 @@ struct Layer { label: String, columns: Vec, named: HashSet, - rows: Vec<(Option, Attrs)>, - /// Properties not read (nested records): how many features had them, and the first names. - nested: usize, - nested_names: Names, - /// Values of properties past the column cap. + rows: Vec<(Option, Attrs, Nested)>, + /// Values of properties past the column cap, or nested past [`MAX_PATH`]. capped: usize, /// Features kept without a shape: no geometry, or one that couldn't be read. shapeless: usize, @@ -1028,6 +1031,8 @@ struct Layer { derived_names: Names, /// Airspaces drawn as the parts of BASE and UNION volumes. unions: usize, + /// Shapes in the records of features drawn from their own shapes, not drawn. + shapes_in_records: usize, /// Features as a TEMPDELTA changed them. temporary: usize, snapshots: usize, @@ -1062,16 +1067,23 @@ impl Layer { } } -/// A row being built: its values, and the nested properties not read. +/// A row's values nested in records, each by its path: every step a property's name and which of +/// its kind among its siblings it is (from 1). `None` is a value given as missing (`nil`). They are +/// named as columns once the layer's rows are all read ([`path_columns`]). +type Nested = Vec<(Vec<(String, usize)>, Option)>; + +/// A row being built: its values, simple ones by column and nested ones by path. #[derive(Default, Clone)] struct Row { attrs: Attrs, /// Every column named, null or not, in order, and the same as a set. columns: Vec, named: HashSet, - nested: Vec, - nested_named: HashSet, - /// Values of names past [`MAX_COLUMNS`], not kept. + /// Values in records, by path. + paths: Nested, + /// How many records of each property the feature has had so far. + records: HashMap, + /// Values of names past [`MAX_COLUMNS`], or nested past [`MAX_PATH`], not kept. capped: usize, } @@ -1114,28 +1126,59 @@ impl Row { /// A property's simple value as attributes, under `prefix`. fn property(&mut self, p: Node, prefix: &str) { let name = format!("{prefix}{}", local(&p)); - if is_nil(&p) { - self.null(&name); + if !is_nil(&p) && elements(p).next().is_some() && p.attribute((XLINK, "href")).is_none() { + // A record: each of its values under its path, numbered by which record it is. + let n = self.records.entry(name.clone()).or_default(); + *n += 1; + let mut path = vec![(name, *n)]; + self.record(p, &mut path, false); return; } - if let Some(href) = p.attribute((XLINK, "href")) { - let id = href.trim(); - let id = id.strip_prefix("urn:uuid:").or_else(|| id.strip_prefix('#')).unwrap_or(id); - self.set(&name, id.to_string()); - if let Some(t) = p.attribute((XLINK, "title")) { - self.set(&format!("{name}_title"), t.trim().to_string()); + for (key, value) in leaf_values(p, &name) { + match value { + Some(v) => self.set(&key, v), + None => self.null(&key), } - return; } - if elements(p).next().is_some() { - if self.nested_named.insert(name.clone()) { - self.nested.push(name); - } + } + + /// The values in a record (a property holding an object, or the object), each under `path` + /// and its own name. An object (`AuthorityForNavaidEquipment`, `gml:TimePeriod`) adds no step: + /// its properties are the record's. A shape's GML isn't a value (it is the feature's shape, or + /// one drawn with it); the values AIXM writes on it (elevation, accuracy) are. With + /// `aixm_only`, only AIXM's properties are read. + fn record(&mut self, node: Node, path: &mut Vec<(String, usize)>, aixm_only: bool) { + if path.len() > MAX_PATH { + self.capped += 1; return; } - self.set(&name, text_of(&p)); - if let Some(u) = p.attribute("uom") { - self.set(&format!("{name}_uom"), u.trim().to_string()); + let mut seen: HashMap<&str, usize> = HashMap::new(); + for c in elements(node) { + if aixm_only && !is_aixm(&c) { + continue; + } + let name = local(&c); + // AIXM and GML name objects with a capital, properties without. + if name.starts_with(|ch: char| ch.is_ascii_uppercase()) { + let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); + self.record(c, path, shape); + continue; + } + let n = seen.entry(name).or_default(); + *n += 1; + path.push((name.to_string(), *n)); + if elements(c).next().is_some() && c.attribute((XLINK, "href")).is_none() { + self.record(c, path, false); + } else if let Some((last, _)) = path.last().cloned() { + for (key, value) in leaf_values(c, &last) { + let mut at = path.clone(); + if let Some(step) = at.last_mut() { + step.0 = key; + } + self.paths.push((at, value)); + } + } + path.pop(); } } @@ -1150,6 +1193,69 @@ impl Row { } } +/// A property's value and those written on it, each under its own name from `name`: its text (or +/// `None` when given as missing), the identifier a reference names (`urn:uuid:` left off) with its +/// title (`_title`), its unit (`_uom`), why it is missing (`_nilReason`), its language (`_lang`) +/// and any other attribute (`_` and its name). An element's id and the XML plumbing aren't values. +fn leaf_values(p: Node, name: &str) -> Vec<(String, Option)> { + let mut out = Vec::new(); + if is_nil(&p) { + out.push((name.to_string(), None)); + } else if let Some(href) = p.attribute((XLINK, "href")) { + let id = href.trim(); + let id = id.strip_prefix("urn:uuid:").or_else(|| id.strip_prefix('#')).unwrap_or(id); + out.push((name.to_string(), Some(id.to_string()))); + } else { + out.push((name.to_string(), Some(text_of(&p)))); + } + for a in p.attributes() { + let key = match (a.namespace(), a.name()) { + (Some(XLINK), "title") => "title", + (Some(XLINK) | Some(XSI), _) | (Some(GML), "id") | (None, "id") => continue, + (_, other) => other, + }; + out.push((format!("{name}_{key}"), Some(a.value().trim().to_string()))); + } + out +} + +/// The column of each nested value of a layer's rows: its path's names joined by `_`, each step +/// numbered (`authority_1_type`) when its record repeats anywhere in the layer, so every row's +/// values of one record share their columns. +fn path_columns(rows: &[(Option, Attrs, Nested)]) -> HashSet { + let mut repeating = HashSet::new(); + for (_, _, nested) in rows { + for (path, _) in nested { + let mut key = String::new(); + for (name, n) in path { + key.push('/'); + key.push_str(name); + if *n > 1 { + repeating.insert(key.clone()); + } + } + } + } + repeating +} + +/// A nested value's column, as [`path_columns`] numbers it. +fn path_column(path: &[(String, usize)], repeating: &HashSet) -> String { + let (mut key, mut column) = (String::new(), String::new()); + for (name, n) in path { + key.push('/'); + key.push_str(name); + if !column.is_empty() { + column.push('_'); + } + column.push_str(name); + if repeating.contains(&key) { + column.push_str(&format!("_{n}")); + } + } + column +} + /// The layers of a file in the order their kinds were first met. #[derive(Default)] struct Layers { @@ -1199,7 +1305,7 @@ impl Layers { notes: Option<&ShapeNotes>, change: (bool, bool), ) -> Option { - let cells = row.columns.len().max(1); + let cells = (row.columns.len() + row.paths.len()).max(1); if cells > self.cells_left { self.rows_over += 1; return None; @@ -1221,16 +1327,10 @@ impl Layers { attrs.insert(c.clone(), v.clone()); } } - if !row.nested.is_empty() { - layer.nested += 1; - for n in &row.nested { - layer.nested_names.add(n); - } - } if let Some(n) = notes { layer.take_notes(n); } - layer.rows.push((geometry, attrs)); + layer.rows.push((geometry, attrs, row.paths)); Some(i) } } @@ -1594,8 +1694,28 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result &'static str { + match name { + "Point" | "ElevatedPoint" => "points", + "Curve" | "ElevatedCurve" | "LineString" => "lines", + _ => "polygons", + } +} + +/// The shapes nested in a record (not those inside another shape, such as a surface's curves). +fn nested_shapes<'a, 'i>(p: Node<'a, 'i>) -> Vec> { + p.descendants() + .skip(1) + .filter(|d| d.is_element() && (is_aixm(d) || is_gml(d)) && SHAPES.contains(&local(d))) + .filter(|g| !g.ancestors().skip(1).take_while(|a| *a != p).any(|a| SHAPES.contains(&local(&a)))) + .collect() +} + +/// Adds a feature's rows: a row in a layer for each property holding a shape; or, when none does, +/// a row for each record holding shapes (a light system's lights, a marking's elements), with the +/// feature's other values and the record's own (`element_style`), its shapes its geometry. False +/// when it has nothing to draw. fn feature_rows( props: &[Node], row: &mut Row, @@ -1606,56 +1726,76 @@ fn feature_rows( snapshot: bool, ) -> bool { let mut shaped: Vec<(String, Node)> = Vec::new(); + let mut parts: Vec = Vec::new(); for p in props { match shape_in(*p) { Some(g) if !is_nil(p) => shaped.push((local(p).to_string(), g)), + _ if !is_nil(p) && p.attribute((XLINK, "href")).is_none() && !nested_shapes(*p).is_empty() => parts.push(*p), _ => row.property(*p, ""), } } let change = (temporary > 0, snapshot); - if shaped.is_empty() { - // Shapes nested in records (a marking's elements, a light system's lights): by family, - // each family with what its own shapes' reading found. - let mut by_family: BTreeMap<&'static str, (Vec, ShapeNotes)> = BTreeMap::new(); - let mut lost = ShapeNotes::default(); - for p in props.iter().filter(|p| elements(**p).next().is_some()) { - let nested = p.descendants().skip(1).filter(|d| d.is_element() && (is_aixm(d) || is_gml(d)) && SHAPES.contains(&local(d))); - // Not those inside another shape (a surface's curves). - for g in nested.filter(|g| !g.ancestors().skip(1).take_while(|a| a != p).any(|a| SHAPES.contains(&local(&a)))) { - let mut notes = ShapeNotes::default(); - match shapes.shape(g, &mut notes) { - Some(geom) => { - let (gs, n) = by_family.entry(family(&geom)).or_default(); - gs.push(geom); - n.absorb(notes); - } - None => lost.absorb(notes), - } - } - } - if by_family.is_empty() { - return false; + if !shaped.is_empty() { + // A feature drawn from its own shapes: its records' values are kept as columns, and the + // shapes in them (not drawn) are counted. + let mut in_records = 0; + for p in &parts { + in_records += nested_shapes(*p).len(); + row.property(*p, ""); } - let mut first = true; - for (label, (gs, mut notes)) in by_family { - if std::mem::take(&mut first) { - notes.absorb(std::mem::take(&mut lost)); + let mut first = None; + for (name, g) in shaped { + let mut notes = ShapeNotes::default(); + let geom = shapes.shape(g, &mut notes); + let mut r = row.clone(); + r.shape_values(g, &name); + // A kind's shapes under different properties are different layers (an airport's + // reference point and its boundary); a kind with one is one layer, titled by its kind. + let bad = geom.is_none(); + let i = layers.push(kind, &name, geom, r, Some(¬es), change); + first = first.or(i); + if let Some(l) = layers.at(i) { + l.unreadable += usize::from(bad); } - layers.push(kind, label, merged(gs), row.clone(), Some(¬es), change); + } + if let Some(l) = layers.at(first) { + l.shapes_in_records += in_records; } return true; } - for (name, g) in shaped { - let mut notes = ShapeNotes::default(); - let geom = shapes.shape(g, &mut notes); + if parts.is_empty() { + return false; + } + // Rows copied for the records stay within what the file's size allows: checked before each + // copy, as a vertical structure's parts are. + let mut room = layers.cells_left; + let count = parts.len(); + for (k, p) in parts.into_iter().enumerate() { + if (row.columns.len() + row.paths.len()).max(1) > room { + layers.rows_over += count - k; + break; + } let mut r = row.clone(); - r.shape_values(g, &name); - // A kind's shapes under different properties are different layers (an airport's reference - // point and its boundary); a kind with one is one layer, titled by its kind alone. - let bad = geom.is_none(); - let i = layers.push(kind, &name, geom, r, Some(¬es), change); - if let Some(l) = layers.at(i) { - l.unreadable += usize::from(bad); + let mut path = vec![(local(&p).to_string(), 1)]; + r.record(p, &mut path, false); + room = room.saturating_sub((r.columns.len() + r.paths.len()).max(1)); + // The record's shapes by family, each family a row of its own (most records have one). + let mut by_family: BTreeMap<&'static str, (Vec, ShapeNotes)> = BTreeMap::new(); + for g in nested_shapes(p) { + let mut notes = ShapeNotes::default(); + let geom = shapes.shape(g, &mut notes); + let (gs, n) = by_family.entry(element_family(local(&g))).or_default(); + gs.extend(geom); + n.absorb(notes); + } + // What the feature was is said once for it, with its first row. + let change = if k == 0 { change } else { (false, false) }; + for (label, (gs, notes)) in by_family { + let bad = gs.is_empty(); + let i = layers.push(kind, label, merged(gs), r.clone(), Some(¬es), change); + if let Some(l) = layers.at(i) { + l.unreadable += usize::from(bad); + } } } true @@ -1687,6 +1827,9 @@ fn airspace( } continue; }; + // Every component's values as its record (its operation, its volume's limits, the + // airspaces it is built from), besides the BASE volume's limits below. + row.property(*p, ""); let op = child(c, "operation").map(|n| text_of(&n)).unwrap_or_default(); let seq = child(c, "operationSequence").and_then(|n| text_of(&n).parse().ok()).unwrap_or(u64::MAX); let volume = child(c, "theAirspaceVolume").and_then(|v| child(v, "AirspaceVolume")); @@ -1784,16 +1927,11 @@ fn vertical_structure( let mut room = layers.cells_left; let count = parts.len(); for (k, vp) in parts.into_iter().enumerate() { - if row.columns.len().max(1) > room { + if (row.columns.len() + row.paths.len()).max(1) > room { layers.rows_over += count - k; break; } let mut r = row.clone(); - // What the structure lacks is said once for it, not for each part. - if k > 0 { - r.nested.clear(); - r.nested_named.clear(); - } let mut notes = ShapeNotes::default(); let mut geom = None; let mut bad = false; @@ -1807,7 +1945,7 @@ fn vertical_structure( _ => r.property(p, "part_"), } } - room = room.saturating_sub(r.columns.len().max(1)); + room = room.saturating_sub((r.columns.len() + r.paths.len()).max(1)); rows.push((geom, r, notes, bad)); } // A part with no shape goes with the structure's first family of parts. @@ -1917,19 +2055,43 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, } else { format!("{stem} {} {}", layer.kind, layer.label) }; + // Nested values as columns, named by their paths across the whole layer. + let mut layer = layer; + let repeating = path_columns(&layer.rows); + let mut rows = Vec::with_capacity(layer.rows.len()); + for (g, mut attrs, nested) in std::mem::take(&mut layer.rows) { + for (path, value) in nested { + let column = path_column(&path, &repeating); + if !layer.column(&column) { + continue; + } + if let Some(v) = value { + match attrs.get_mut(&column) { + Some(old) if !v.is_empty() => { + old.push_str("; "); + old.push_str(&v); + } + Some(_) => {} + None => { + attrs.insert(column, v); + } + } + } + } + rows.push((g, attrs)); + } let fields: Vec = layer .columns .iter() .map(|c| { Field::new( c.clone(), - crate::io::text_type(layer.rows.iter().filter_map(|(_, a)| a.get(c)).map(String::as_str).filter(|v| !v.is_empty())), + crate::io::text_type(rows.iter().filter_map(|(_, a)| a.get(c)).map(String::as_str).filter(|v| !v.is_empty())), ) }) .collect(); let mut ds = Dataset::new(title, GeometryType::None, fields); - let mut layer = layer; - for (g, attrs) in std::mem::take(&mut layer.rows) { + for (g, attrs) in rows { let row = ds.fields.iter().map(|f| attrs.get(&f.name).map_or(Value::Null, |v| Value::parse_file(v, f.ty))).collect(); ds.push_next(g, row); } @@ -1965,6 +2127,11 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, "airspace is drawn as the parts of its BASE and UNION volumes, not merged into one outline; its limits are its BASE volume's", "airspaces are drawn as the parts of their BASE and UNION volumes, not merged into one outline; their limits are their BASE volume's", ); + say( + layer.shapes_in_records, + "shape in the records of features drawn from their own shape isn't drawn (its record's values are kept)", + "shapes in the records of features drawn from their own shapes aren't drawn (their records' values are kept)", + ); say( layer.arcs, "feature has arcs or circles, drawn as points along them within a meter", @@ -2001,16 +2168,10 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked", "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked", ); - let nested = layer.nested_names.said(); - say( - layer.nested, - &format!("feature has nested records not read as attributes ({nested})"), - &format!("features have nested records not read as attributes ({nested})"), - ); say( layer.capped, - &format!("value of properties past the first {MAX_COLUMNS} names wasn't read"), - &format!("values of properties past the first {MAX_COLUMNS} names weren't read"), + &format!("value past the first {MAX_COLUMNS} columns, or nested deeper than {MAX_PATH} records, wasn't read"), + &format!("values past the first {MAX_COLUMNS} columns, or nested deeper than {MAX_PATH} records, weren't read"), ); if layer.zm > 0 { ds.zm_dropped = true; diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 37c34f36e8..3e678bf5ae 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -531,7 +531,7 @@ fn a_structure_of_many_parts_and_values_stays_within_the_files_allowance() { assert!(rows < 10_000 && cells <= MIN_CELLS, "{rows} rows, {cells} cells"); let notes = said(&out); assert!(notes.iter().any(|m| m.contains("past the memory the file's size allows")), "{notes:?}"); - assert!(notes.iter().any(|m| m.contains(&format!("past the first {MAX_COLUMNS} names"))), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains(&format!("past the first {MAX_COLUMNS} columns"))), "{notes:?}"); } #[test] @@ -655,3 +655,101 @@ fn a_layers_z_note_comes_first() { assert!(first.first().is_some_and(|m| m.text.contains("Z or M")), "{:?}", first.iter().map(|m| &m.text).collect::>()); assert!(first.iter().any(|m| m.text.contains("not in force"))); } + +// --------------------------------------------------------------------------------------------- +// Every value kept: nested records as path columns. +// --------------------------------------------------------------------------------------------- + +#[test] +fn records_are_kept_as_path_columns_numbered_alike_on_every_row() { + let authority = |t: &str, org: &str| { + format!( + r#"{t}"# + ) + }; + let note = r#"REMARKCoverage: 250 KM"#; + let body = + |name: &str, auths: &str| format!("{}{auths}{note}", named_point(name)); + let two = slice( + "DesignatedPoint", + "BASELINE", + 1, + 0, + &period("2025-01-01T00:00:00Z", None), + &body("TWO", &(authority("OWN", "o1") + &authority("OPERATE", "o2"))), + ); + let one = slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body("ONE", &authority("OWN", "o3"))); + let bytes = message(&(point("two", &[two]) + &point("one", &[one]))); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t DesignatedPoint"); + let (two, one) = (row_where(ds, "name", "TWO"), row_where(ds, "name", "ONE")); + let text = |row: usize, field: &str| value(ds, row, field); + // Repeating on one row, so numbered on both. + assert_eq!(text(two, "authority_1_type"), Value::Text("OWN".into())); + assert_eq!(text(two, "authority_2_type"), Value::Text("OPERATE".into())); + assert_eq!(text(two, "authority_2_theOrganisationAuthority"), Value::Text("o2".into())); + assert_eq!(text(two, "authority_2_theOrganisationAuthority_title"), Value::Text("ORG o2".into())); + assert_eq!(text(one, "authority_1_type"), Value::Text("OWN".into())); + assert_eq!(text(one, "authority_2_type"), Value::Null); + // Never repeating: no numbers. A note's language and a missing value's reason are kept. + assert_eq!(text(one, "annotation_translatedNote_note"), Value::Text("Coverage: 250 KM".into())); + assert_eq!(text(one, "annotation_translatedNote_note_lang"), Value::Text("ENG".into())); + assert_eq!(text(one, "annotation_purpose"), Value::Text("REMARK".into())); + assert_eq!(text(one, "class"), Value::Null); + assert_eq!(text(one, "class_nilReason"), Value::Text("inapplicable".into())); + // Nothing is left out, so nothing is said. + assert!(said(&out).is_empty(), "{:?}", said(&out)); +} + +#[test] +fn donlon_keeps_every_value_of_its_features() { + let out = read("donlon-aixm.xml", DONLON, &at("2026-01-15")).unwrap(); + let asp = layer(&out, "donlon-aixm Airspace"); + let i = row_where(asp, "name", "BRAVO"); + let has = |want: &str| { + asp.fields.iter().enumerate().any(|(k, f)| f.name.starts_with("activation") && asp.features[i].attrs[k] == Value::Text(want.into())) + }; + assert!(has("Activity periods to be published by NOTAM")); + assert!(has("SHOOTING") && has("AVBL_FOR_ACTIVATION")); + let op = asp.fields.iter().position(|f| f.name.starts_with("geometryComponent") && f.name.ends_with("operation")).unwrap(); + assert_eq!(asp.features[i].attrs[op], Value::Text("BASE".into())); + assert_eq!(value(asp, i, "class_nilReason"), Value::Text("inapplicable".into())); + // The route segment's start and end points, by reference. + let rs = layer(&out, "donlon-aixm RouteSegment"); + assert!( + rs.fields.iter().any(|f| f.name.starts_with("start_") && f.name.ends_with("pointChoice_fixDesignatedPoint")), + "{:?}", + rs.fields.iter().map(|f| &f.name).collect::>() + ); + // Nothing the features hold is said as not read. + assert!(!said(&out).iter().any(|m| m.contains("not read as attributes") || m.contains("columns")), "{:?}", said(&out)); +} + +#[test] +fn a_light_system_gives_a_row_per_light_with_its_own_values() { + let light = |color: &str, lat: &str| { + format!( + r#"LIGHT{color}{lat} -32.029"# + ) + }; + let body = format!( + "YES{}{}{}", + light("WHITE", "52.1"), + light("RED", "52.2"), + light("GREEN", "52.3") + ); + let bytes = message(&feature( + "RunwayDirectionLightSystem", + "l", + &[slice("RunwayDirectionLightSystem", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)], + )); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t RunwayDirectionLightSystem"); + assert_eq!(ds.features.len(), 3); + let colors: Vec = (0..3).map(|i| value(ds, i, "element_colour")).collect(); + assert_eq!(colors, ["WHITE", "RED", "GREEN"].map(|c| Value::Text(c.into()))); + assert!((0..3).all(|i| value(ds, i, "emergencyLighting") == Value::Text("YES".into()))); + assert_eq!(value(ds, 1, "element_location_elevation"), Value::Int(29)); + assert_eq!(ds.features[2].geometry, Some(Geometry::Point(Coord::new(-32.0, 52.3)))); + assert!(said(&out).is_empty(), "{:?}", said(&out)); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 3224c3c1fe..1070201ee0 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled or given only as changes are left out and counted. Simple properties are fields, with their unit (`_uom`) and, for a reference to another feature, its identifier and title (`_title`); vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A vertical structure gives a row per part. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled or given only as changes are left out and counted. Every value a feature holds is kept: simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 4182b011d70cf2dc06088aa3a63a5c0aeb4d20c2 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:30:46 -0600 Subject: [PATCH 07/61] fix(data): AIXM rows bounded in bytes, record depth bounded in objects too --- crates/data/src/aixm.rs | 77 +++++++++++++++++++++++++---------- crates/data/src/aixm/tests.rs | 34 +++++++++++++++- 2 files changed, 88 insertions(+), 23 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 10c3139ff4..abdc086df3 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -1083,8 +1083,12 @@ struct Row { paths: Nested, /// How many records of each property the feature has had so far. records: HashMap, - /// Values of names past [`MAX_COLUMNS`], or nested past [`MAX_PATH`], not kept. + /// Values of names past [`MAX_COLUMNS`], nested past [`MAX_PATH`], or past `limit`, not kept. capped: usize, + /// The bytes its values and their names and paths hold, and the most they may (none until + /// set: a row being read stops keeping values past what the file's size allows). + bytes: usize, + limit: Option, } impl Row { @@ -1102,8 +1106,24 @@ impl Row { true } + /// Takes `cost` bytes for a value, or counts it as not kept past the row's limit. + fn afford(&mut self, cost: usize) -> bool { + let cost = cost + VALUE_OVERHEAD; + if self.limit.is_some_and(|l| self.bytes + cost > l) { + self.capped += 1; + return false; + } + self.bytes += cost; + true + } + + /// What the row holds, in bytes: what keeping it, or a copy of it, costs. + fn weight(&self) -> usize { + self.bytes.max(1) + } + fn set(&mut self, key: &str, value: String) { - if !self.name(key) { + if !self.name(key) || !self.afford(key.len() + value.len()) { return; } match self.attrs.get_mut(key) { @@ -1148,7 +1168,13 @@ impl Row { /// one drawn with it); the values AIXM writes on it (elevation, accuracy) are. With /// `aixm_only`, only AIXM's properties are read. fn record(&mut self, node: Node, path: &mut Vec<(String, usize)>, aixm_only: bool) { - if path.len() > MAX_PATH { + self.record_at(node, path, aixm_only, 0); + } + + /// As [`Row::record`], `depth` records and objects down: bounded whether the depth is in + /// properties (the path) or in objects (which add no step to it). + fn record_at(&mut self, node: Node, path: &mut Vec<(String, usize)>, aixm_only: bool, depth: usize) { + if path.len() > MAX_PATH || depth > 2 * MAX_PATH { self.capped += 1; return; } @@ -1161,16 +1187,22 @@ impl Row { // AIXM and GML name objects with a capital, properties without. if name.starts_with(|ch: char| ch.is_ascii_uppercase()) { let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); - self.record(c, path, shape); + self.record_at(c, path, shape, depth + 1); continue; } let n = seen.entry(name).or_default(); *n += 1; path.push((name.to_string(), *n)); if elements(c).next().is_some() && c.attribute((XLINK, "href")).is_none() { - self.record(c, path, false); + self.record_at(c, path, false, depth + 1); } else if let Some((last, _)) = path.last().cloned() { + // Each value keeps its own copy of its path: paid for in bytes, so deep paths + // can't make the copies outgrow what the file's size allows. + let path_bytes: usize = path.iter().map(|(n, _)| n.len() + VALUE_OVERHEAD).sum(); for (key, value) in leaf_values(c, &last) { + if !self.afford(path_bytes + key.len() + value.as_ref().map_or(0, String::len)) { + continue; + } let mut at = path.clone(); if let Some(step) = at.last_mut() { step.0 = key; @@ -1260,9 +1292,9 @@ fn path_column(path: &[(String, usize)], repeating: &HashSet) -> String #[derive(Default)] struct Layers { by_key: HashMap<(String, String), usize>, - /// Values rows may still hold: rows copied for a feature's parts or shapes are bounded by the - /// file's size, not by how many times a feature repeats them. - cells_left: usize, + /// Bytes rows may still hold: rows copied for a feature's parts or records are bounded by the + /// file's size, not by how many times a feature repeats them or how long its values are. + bytes_left: usize, /// Rows left out past that. rows_over: usize, list: Vec, @@ -1305,8 +1337,8 @@ impl Layers { notes: Option<&ShapeNotes>, change: (bool, bool), ) -> Option { - let cells = (row.columns.len() + row.paths.len()).max(1); - if cells > self.cells_left { + let cells = row.weight(); + if cells > self.bytes_left { self.rows_over += 1; return None; } @@ -1314,7 +1346,7 @@ impl Layers { self.over.insert(row.attrs.get("identifier").cloned().unwrap_or_default()); return None; }; - self.cells_left -= cells; + self.bytes_left -= cells; let layer = self.list.get_mut(i)?; layer.capped += row.capped; layer.temporary += usize::from(change.0); @@ -1374,8 +1406,10 @@ fn merged(gs: Vec) -> Option { })) } -/// Attribute values the layers may hold whatever the file's size. -const MIN_CELLS: usize = 4_000_000; +/// Bytes the layers' values may hold whatever the file's size. +const MIN_ROW_BYTES: usize = 64 << 20; +/// What keeping one value costs besides its text: its slot, its column's or path step's slot. +const VALUE_OVERHEAD: usize = 24; /// Bytes wrapping slices may add whatever the file's size. const MIN_WRAP_BYTES: usize = 16 << 20; @@ -1572,7 +1606,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result = layers_of.iter().enumerate().flat_map(|(i, ps)| ps.iter().copied().filter(move |p| last.get(local(p)) == Some(&i))).collect(); - let mut row = Row::default(); + // A row being read keeps no more than the layers still may. + let mut row = Row { limit: Some(layers.bytes_left), ..Row::default() }; row.set("identifier", id.trim_start_matches("urn:uuid:").to_string()); let valid = |t: Option| t.map(|t| crate::time::format(t, "YYYY-MM-DDTHH:mm:ss") + "Z"); match valid(base.begin) { @@ -1768,17 +1803,17 @@ fn feature_rows( } // Rows copied for the records stay within what the file's size allows: checked before each // copy, as a vertical structure's parts are. - let mut room = layers.cells_left; + let mut room = layers.bytes_left; let count = parts.len(); for (k, p) in parts.into_iter().enumerate() { - if (row.columns.len() + row.paths.len()).max(1) > room { + if row.weight() > room { layers.rows_over += count - k; break; } let mut r = row.clone(); let mut path = vec![(local(&p).to_string(), 1)]; r.record(p, &mut path, false); - room = room.saturating_sub((r.columns.len() + r.paths.len()).max(1)); + room = room.saturating_sub(r.weight()); // The record's shapes by family, each family a row of its own (most records have one). let mut by_family: BTreeMap<&'static str, (Vec, ShapeNotes)> = BTreeMap::new(); for g in nested_shapes(p) { @@ -1924,10 +1959,10 @@ fn vertical_structure( let mut rows = Vec::new(); // Rows copied for the parts stay within what the file's size allows: checked before each copy, // so a structure of many parts and many values can't outgrow it. - let mut room = layers.cells_left; + let mut room = layers.bytes_left; let count = parts.len(); for (k, vp) in parts.into_iter().enumerate() { - if (row.columns.len() + row.paths.len()).max(1) > room { + if row.weight() > room { layers.rows_over += count - k; break; } @@ -1945,7 +1980,7 @@ fn vertical_structure( _ => r.property(p, "part_"), } } - room = room.saturating_sub((r.columns.len() + r.paths.len()).max(1)); + room = room.saturating_sub(r.weight()); rows.push((geom, r, notes, bad)); } // A part with no shape goes with the structure's first family of parts. diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 3e678bf5ae..e93ac7b700 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -527,8 +527,7 @@ fn a_structure_of_many_parts_and_values_stays_within_the_files_allowance() { )); let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); let rows: usize = out.iter().map(|(d, _)| d.features.len()).sum(); - let cells: usize = out.iter().map(|(d, _)| d.features.len() * d.fields.len()).sum(); - assert!(rows < 10_000 && cells <= MIN_CELLS, "{rows} rows, {cells} cells"); + assert!(rows < 10_000, "{rows} rows"); let notes = said(&out); assert!(notes.iter().any(|m| m.contains("past the memory the file's size allows")), "{notes:?}"); assert!(notes.iter().any(|m| m.contains(&format!("past the first {MAX_COLUMNS} columns"))), "{notes:?}"); @@ -753,3 +752,34 @@ fn a_light_system_gives_a_row_per_light_with_its_own_values() { assert_eq!(ds.features[2].geometry, Some(Geometry::Point(Coord::new(-32.0, 52.3)))); assert!(said(&out).is_empty(), "{:?}", said(&out)); } + +#[test] +fn objects_nested_past_the_limit_are_counted_not_followed() { + let open: String = (0..150).map(|i| format!("")).collect(); + let close: String = (0..150).rev().map(|i| format!("")).collect(); + let body = format!("{}{open}x{close}", named_point("DEEP")); + let out = read( + "t.xml", + &message(&point("d", &[slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + assert_eq!(layer(&out, "t DesignatedPoint").features.len(), 1); + assert!(said(&out).iter().any(|m| m.contains("nested deeper")), "{:?}", said(&out)); +} + +#[test] +fn a_long_value_copied_onto_many_rows_stays_within_the_files_allowance() { + let long = "N".repeat(1 << 20); + let light = r#"52 -32"#; + let body = format!("{long}{}", light.repeat(1000)); + let bytes = message(&feature( + "RunwayDirectionLightSystem", + "l", + &[slice("RunwayDirectionLightSystem", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)], + )); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + let rows = layer(&out, "t RunwayDirectionLightSystem").features.len(); + assert!(rows < 1000, "{rows} rows of a megabyte each"); + assert!(said(&out).iter().any(|m| m.contains("past the memory the file's size allows")), "{:?}", said(&out)); +} From 4c3303a6f500f0da3eedd689df7e22b735008c86 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:46:51 -0600 Subject: [PATCH 08/61] feat(data): AIXM borders followed by reference, FAA NASR subscriber files, paths kept once --- crates/data/src/aixm.rs | 422 ++++++++++++++++++++++++++++------ crates/data/src/aixm/tests.rs | 61 +++++ 2 files changed, 407 insertions(+), 76 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index abdc086df3..8e6850676b 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -103,21 +103,38 @@ impl Options { } } -/// Whether a file is an AIXM message, by its root: an `AIXMBasicMessage` in an AIXM 5 namespace. +/// Whether a file is an AIXM message, by its root: an `AIXMBasicMessage` in an AIXM 5 namespace, +/// or an FAA NASR subscriber file of AIXM 5 features ([`is_root`]). pub fn looks_like_aixm(bytes: &[u8]) -> bool { let head = String::from_utf8_lossy(bytes.get(..HEAD_BYTES).unwrap_or(bytes)); let mut reader = Reader::from_str(head.trim_start_matches('\u{feff}')); loop { match reader.read_event() { - Ok(Event::Start(e) | Event::Empty(e)) => { - return e.local_name().into_inner() == "AIXMBasicMessage" && namespace_of(&e).is_some_and(|ns| ns.starts_with(AIXM)); - } + Ok(Event::Start(e) | Event::Empty(e)) => return is_root(&e), Ok(Event::Eof) | Err(_) => return false, Ok(_) => {} } } } +/// The FAA's namespaces for its NASR subscriber files. +const FAA: &str = "http://www.faa.gov/aixm5"; + +/// Whether an element is the root of a message RustGIS reads: an `AIXMBasicMessage` in an AIXM 5 +/// namespace, or the FAA's `SubscriberFile` (its 28-day NASR data) saying it holds AIXM 5 +/// (`AIXMVersion="AIXM5.1"`), whose `Member`s hold AIXM features as `hasMember`s do. +fn is_root(e: &BytesStart) -> bool { + let ns = namespace_of(e); + match e.local_name().into_inner() { + "AIXMBasicMessage" => ns.is_some_and(|ns| ns.starts_with(AIXM)), + "SubscriberFile" => { + ns.is_some_and(|ns| ns.starts_with(FAA)) + && e.attributes().flatten().any(|a| a.key.local_name().into_inner() == "AIXMVersion" && a.value.trim().starts_with("AIXM5")) + } + _ => false, + } +} + /// The namespace an element's own prefix (or the default) is declared with on it. fn namespace_of(e: &BytesStart) -> Option { let name = e.name(); @@ -177,9 +194,9 @@ impl Index { match event { Event::Start(ref e) | Event::Empty(ref e) if depth == 0 => { rooted = true; - if e.local_name().into_inner() != "AIXMBasicMessage" || !namespace_of(e).is_some_and(|ns| ns.starts_with(AIXM)) { + if !is_root(e) { return Err(DataError::Format(format!( - "{file_name}: not an AIXM message (an AIXMBasicMessage in an AIXM 5 namespace)" + "{file_name}: not an AIXM message (an AIXMBasicMessage in an AIXM 5 namespace, or an FAA NASR subscriber file of AIXM 5)" ))); } index.namespaces = declarations(e); @@ -190,7 +207,7 @@ impl Index { depth = 1; } Event::Start(e) => { - if depth == 1 && e.local_name().into_inner() == "hasMember" { + if depth == 1 && is_member(&e) { member = Some((start, has_href(&e), false)); } else if depth == 2 && let Some(m) = member.as_mut() @@ -200,7 +217,7 @@ impl Index { depth += 1; } Event::Empty(e) => { - if depth == 1 && e.local_name().into_inner() == "hasMember" { + if depth == 1 && is_member(&e) { if has_href(&e) { index.links += 1; } else { @@ -243,6 +260,12 @@ impl Index { } } +/// Whether an element under the root holds a feature: a message's `hasMember`, a subscriber +/// file's `Member`. +fn is_member(e: &BytesStart) -> bool { + matches!(e.local_name().into_inner(), "hasMember" | "Member") +} + /// Whether an element points elsewhere (`xlink:href`). fn has_href(e: &BytesStart) -> bool { e.attributes().flatten().any(|a| a.key.local_name().into_inner() == "href") @@ -551,8 +574,12 @@ struct ShapeNotes { unread_segments: Vec, /// Rings or patches left out (too few points, unreadable, a border given by reference). rings_lost: usize, - /// Of those, borders given by a reference to another feature's curve. + /// Of those, borders given by a reference to a curve not in the file (or not in force). referenced: usize, + /// Borders given by reference, followed along the GeoBorder they name; of those, ones whose + /// ends lie more than [`FAR_FROM_BORDER_M`] from it. + followed: usize, + far: usize, } /// Reads shapes, adding at most `budget` points to the file's positions. @@ -571,6 +598,8 @@ struct Shapes { as_wgs84: Option, as_wgs84_count: usize, as_wgs84_now: bool, + /// The borders references may follow, by [`border_key`]: each GeoBorder's at the date. + borders: HashMap>, } fn wrap180(d: f64) -> f64 { @@ -596,6 +625,8 @@ impl ShapeNotes { } self.rings_lost += o.rings_lost; self.referenced += o.referenced; + self.followed += o.followed; + self.far += o.far; } } @@ -880,17 +911,43 @@ impl Shapes { Self::positions(r, axes, notes)? } "Ring" => { - let mut out: Vec = Vec::new(); + // Its members: curves written out, and borders given by reference, which are cut + // once the points either side of them are known. + let mut members: Vec, String>> = Vec::new(); for m in elements(r).filter(|c| local(c) == "curveMember") { - let Some(c) = elements(m).next() else { - // Said as a border by reference by the ring's patch, not also as a ring - // left out. - if m.attribute((XLINK, "href")).is_some() { - notes.referenced += 1; + match elements(m).next() { + Some(c) => members.push(Ok(self.curve(c, notes)?)), + None => match m.attribute((XLINK, "href")) { + Some(h) => members.push(Err(border_key(h))), + None => return None, + }, + } + } + let mut out: Vec = Vec::new(); + let n = members.len(); + for i in 0..n { + let mut part = match members.get(i) { + Some(Ok(c)) => c.clone(), + Some(Err(key)) => { + // The written points before and after it, round the ring. + let before = (1..n).find_map(|k| match members.get((i + n - k) % n) { + Some(Ok(c)) => c.last().copied(), + _ => None, + }); + let after = (1..n).find_map(|k| match members.get((i + k) % n) { + Some(Ok(c)) => c.first().copied(), + _ => None, + }); + // Said as a border by reference by the ring's patch, not also as a + // ring left out. + let Some(part) = self.follow(key, before, after, notes) else { + notes.referenced += 1; + return None; + }; + part } - return None; + None => return None, }; - let mut part = self.curve(c, notes)?; if let Some(last) = out.last().copied() { part = part.into_iter().map(|p| next_to(p, last.x)).collect(); if part.first().is_some_and(|f| (f.x - last.x).abs() < 1e-12 && (f.y - last.y).abs() < 1e-12) { @@ -912,6 +969,30 @@ impl Shapes { (pts.len() >= 4).then_some(pts) } + /// The part of a border given by reference (`key`, [`border_key`]) a ring follows: from the + /// point on it nearest `before` (the end of the member before) to the one nearest `after` (the + /// start of the next), the shorter way round a border that closes; the whole border when the + /// ring has no other points. AIXM leaves this cut to the reader (its coding guidance, "Geoborder + /// for Airspace Border"), so each is counted, and those whose ends lie far from the border. + fn follow(&mut self, key: &str, before: Option, after: Option, notes: &mut ShapeNotes) -> Option> { + let border = self.borders.get(key)?; + let part = match (before, after) { + (Some(a), Some(b)) => { + let (part, off) = cut(border, a, b)?; + notes.far += usize::from(off > FAR_FROM_BORDER_M); + part + } + _ => border.clone(), + }; + // Its points are paid for as a curve's added points are. + let n = part.len(); + if self.take(n, notes) < n { + return None; + } + notes.followed += 1; + Some(part) + } + /// A surface's polygon patches (or a polygon): each its exterior and interiors. fn surface(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { let patches: Vec = if local(&g) == "Polygon" { @@ -961,6 +1042,79 @@ impl Shapes { } } +/// How far from a border the ends of a part cut from it may lie before that is said, in meters. +const FAR_FROM_BORDER_M: f64 = 50.0; + +/// What a reference names a border by: `#` and a curve's `gml:id`, or its feature's identifier. +fn border_key(href: &str) -> String { + let h = href.trim(); + match h.strip_prefix('#') { + Some(id) => format!("#{id}"), + None => format!("uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)), + } +} + +/// Where on `line` a point is nearest `p`: the segment, how far along it (0 to 1), the point, and +/// its distance from `p` in meters. Worked out in a plane around `p` (longitude scaled by the +/// cosine of its latitude), fine at the scale of a border's segments. +fn nearest_on(line: &[Coord], p: Coord) -> Option<(usize, f64, Coord, f64)> { + let k = p.y.to_radians().cos().max(1e-6); + let mut best: Option<(usize, f64, Coord, f64)> = None; + for (i, w) in line.windows(2).enumerate() { + let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue }; + let (a, b) = (next_to(a, p.x), next_to(b, p.x)); + let (dx, dy) = ((b.x - a.x) * k, b.y - a.y); + let len2 = dx * dx + dy * dy; + let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; + let q = Coord::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); + let d2 = ((q.x - p.x) * k).powi(2) + (q.y - p.y).powi(2); + if best.is_none_or(|(_, _, _, bd)| d2 < bd) { + best = Some((i, t, q, d2)); + } + } + best.map(|(i, t, q, _)| (i, t, q, rustgis_geom::wgs84_distance_m(q, p))) +} + +/// The part of `line` from the point nearest `a` to the one nearest `b`, and the farther of the +/// two ends from its point. Along the line either way; on a line that closes (an island's +/// coast), the shorter way round. +fn cut(line: &[Coord], a: Coord, b: Coord) -> Option<(Vec, f64)> { + let (ia, ta, pa, da) = nearest_on(line, a)?; + let (ib, tb, pb, db) = nearest_on(line, b)?; + let at = |i: usize| line.get(i).copied(); + let forward = (ia as f64 + ta) <= (ib as f64 + tb); + // Along the line: the vertices between the two points, in the order traveled. + let mut direct = vec![pa]; + if forward { + direct.extend((ia + 1..=ib).filter_map(at)); + } else { + direct.extend((ib + 1..=ia).rev().filter_map(at)); + } + direct.push(pb); + let closes = match (line.first(), line.last()) { + (Some(f), Some(l)) => line.len() > 3 && (f.x - l.x).abs() < 1e-9 && (f.y - l.y).abs() < 1e-9, + _ => false, + }; + let part = if closes { + // The other way round, through where the line closes (its last point is its first). + let last = line.len() - 1; + let mut round = vec![pa]; + if forward { + round.extend((0..=ia).rev().filter_map(at)); + round.extend((ib + 1..last).rev().filter_map(at)); + } else { + round.extend((ia + 1..last).filter_map(at)); + round.extend((0..=ib).filter_map(at)); + } + round.push(pb); + let length = |l: &[Coord]| l.windows(2).map(|w| rustgis_geom::wgs84_distance_m(w[0], w[1])).sum::(); + if length(&round) < length(&direct) { round } else { direct } + } else { + direct + }; + Some((part, da.max(db))) +} + /// Meters in one of a length's units: UCUM's (`m`, `km`, `[nmi_i]`, `[ft_i]`, `[mi_i]`) and AIXM's /// (`M`, `KM`, `NM`, `FT`, `MI`). fn meters_per(uom: &str) -> Option { @@ -1012,8 +1166,10 @@ struct Layer { kind: String, label: String, columns: Vec, - named: HashSet, - rows: Vec<(Option, Attrs, Nested)>, + /// Each column's number. + named: HashMap, + /// Its rows: their shape, their simple values by column number, their nested ones by path. + rows: Vec<(Option, Vec<(usize, String)>, Nested)>, /// Values of properties past the column cap, or nested past [`MAX_PATH`]. capped: usize, /// Features kept without a shape: no geometry, or one that couldn't be read. @@ -1031,6 +1187,9 @@ struct Layer { derived_names: Names, /// Airspaces drawn as the parts of BASE and UNION volumes. unions: usize, + /// Borders given by reference followed along a GeoBorder, and those with ends far from it. + followed: usize, + far: usize, /// Shapes in the records of features drawn from their own shapes, not drawn. shapes_in_records: usize, /// Features as a TEMPDELTA changed them. @@ -1039,17 +1198,19 @@ struct Layer { } impl Layer { - fn column(&mut self, name: &str) -> bool { - if self.named.contains(name) { - return true; + /// A column's number, made when there is room for another; `None` (counted) past + /// [`MAX_COLUMNS`]. + fn column(&mut self, name: &str) -> Option { + if let Some(&i) = self.named.get(name) { + return Some(i); } if self.columns.len() >= MAX_COLUMNS { self.capped += 1; - return false; + return None; } - self.named.insert(name.to_string()); + self.named.insert(name.to_string(), self.columns.len()); self.columns.push(name.to_string()); - true + Some(self.columns.len() - 1) } fn take_notes(&mut self, n: &ShapeNotes) { @@ -1064,13 +1225,29 @@ impl Layer { } self.rings_lost += n.rings_lost; self.referenced += n.referenced; + self.followed += n.followed; + self.far += n.far; } } -/// A row's values nested in records, each by its path: every step a property's name and which of -/// its kind among its siblings it is (from 1). `None` is a value given as missing (`nil`). They are -/// named as columns once the layer's rows are all read ([`path_columns`]). -type Nested = Vec<(Vec<(String, usize)>, Option)>; +/// A path to a nested value: every step a property's name and which of its kind among its +/// siblings it is (from 1). +type Path = Vec<(String, usize)>; + +/// Every path a read meets, each kept once: a value holds its path's number, not a copy of it. +#[derive(Default)] +struct Paths { + ids: HashMap, + list: Vec, +} + +/// The paths of a read, shared by its rows. +type SharedPaths = std::rc::Rc>; + +/// A row's values nested in records, each by its path's number ([`Paths`]). `None` is a value +/// given as missing (`nil`). They are named as columns once the layer's rows are all read +/// ([`path_columns`]). +type Nested = Vec<(usize, Option)>; /// A row being built: its values, simple ones by column and nested ones by path. #[derive(Default, Clone)] @@ -1079,8 +1256,9 @@ struct Row { /// Every column named, null or not, in order, and the same as a set. columns: Vec, named: HashSet, - /// Values in records, by path. + /// Values in records, by path, and the read's paths. paths: Nested, + interned: SharedPaths, /// How many records of each property the feature has had so far. records: HashMap, /// Values of names past [`MAX_COLUMNS`], nested past [`MAX_PATH`], or past `limit`, not kept. @@ -1117,6 +1295,26 @@ impl Row { true } + /// The number of a path, kept once for the read: a path met for the first time is paid for in + /// bytes, so the paths together can't outgrow what the file's size allows. + fn path_id(&mut self, at: Path) -> Option { + let shared = std::rc::Rc::clone(&self.interned); + let Ok(mut paths) = shared.try_borrow_mut() else { + self.capped += 1; + return None; + }; + if let Some(&id) = paths.ids.get(&at) { + return Some(id); + } + if !self.afford(at.iter().map(|(n, _)| n.len() + VALUE_OVERHEAD).sum()) { + return None; + } + let id = paths.list.len(); + paths.list.push(at.clone()); + paths.ids.insert(at, id); + Some(id) + } + /// What the row holds, in bytes: what keeping it, or a copy of it, costs. fn weight(&self) -> usize { self.bytes.max(1) @@ -1196,18 +1394,17 @@ impl Row { if elements(c).next().is_some() && c.attribute((XLINK, "href")).is_none() { self.record_at(c, path, false, depth + 1); } else if let Some((last, _)) = path.last().cloned() { - // Each value keeps its own copy of its path: paid for in bytes, so deep paths - // can't make the copies outgrow what the file's size allows. - let path_bytes: usize = path.iter().map(|(n, _)| n.len() + VALUE_OVERHEAD).sum(); for (key, value) in leaf_values(c, &last) { - if !self.afford(path_bytes + key.len() + value.as_ref().map_or(0, String::len)) { + if !self.afford(value.as_ref().map_or(0, String::len)) { continue; } let mut at = path.clone(); if let Some(step) = at.last_mut() { step.0 = key; } - self.paths.push((at, value)); + if let Some(id) = self.path_id(at) { + self.paths.push((id, value)); + } } } path.pop(); @@ -1225,6 +1422,21 @@ impl Row { } } +/// The identifier a reference names: a UUID (`urn:uuid:` left off), a local `#id`, or the +/// `gml:id` an XPath picks (the FAA's `#/faa:SubscriberFile/faa:Member/aixm:Navaid[@gml:id='N1']`, +/// brackets written as `%5B`/`%5D` or not): what the feature it names is known by in its columns. +fn reference(href: &str) -> String { + let h = href.trim(); + if let Some(at) = h.find("@gml:id") { + let rest = h.get(at..).unwrap_or_default(); + let mut quoted = rest.split(['\'', '"']); + if let (Some(_), Some(id)) = (quoted.next(), quoted.next()) { + return id.trim().to_string(); + } + } + h.strip_prefix("urn:uuid:").or_else(|| h.strip_prefix('#')).unwrap_or(h).to_string() +} + /// A property's value and those written on it, each under its own name from `name`: its text (or /// `None` when given as missing), the identifier a reference names (`urn:uuid:` left off) with its /// title (`_title`), its unit (`_uom`), why it is missing (`_nilReason`), its language (`_lang`) @@ -1234,9 +1446,7 @@ fn leaf_values(p: Node, name: &str) -> Vec<(String, Option)> { if is_nil(&p) { out.push((name.to_string(), None)); } else if let Some(href) = p.attribute((XLINK, "href")) { - let id = href.trim(); - let id = id.strip_prefix("urn:uuid:").or_else(|| id.strip_prefix('#')).unwrap_or(id); - out.push((name.to_string(), Some(id.to_string()))); + out.push((name.to_string(), Some(reference(href)))); } else { out.push((name.to_string(), Some(text_of(&p)))); } @@ -1254,10 +1464,12 @@ fn leaf_values(p: Node, name: &str) -> Vec<(String, Option)> { /// The column of each nested value of a layer's rows: its path's names joined by `_`, each step /// numbered (`authority_1_type`) when its record repeats anywhere in the layer, so every row's /// values of one record share their columns. -fn path_columns(rows: &[(Option, Attrs, Nested)]) -> HashSet { +fn path_columns(rows: &[(Option, Vec<(usize, String)>, Nested)], paths: &Paths) -> HashSet { + let used: HashSet = rows.iter().flat_map(|(_, _, nested)| nested.iter().map(|(id, _)| *id)).collect(); let mut repeating = HashSet::new(); - for (_, _, nested) in rows { - for (path, _) in nested { + for id in used { + let Some(path) = paths.list.get(id) else { continue }; + { let mut key = String::new(); for (name, n) in path { key.push('/'); @@ -1351,12 +1563,12 @@ impl Layers { layer.capped += row.capped; layer.temporary += usize::from(change.0); layer.snapshots += usize::from(change.1); - let mut attrs = Attrs::new(); + let mut attrs = Vec::with_capacity(row.attrs.len()); for c in &row.columns { - if layer.column(c) + if let Some(k) = layer.column(c) && let Some(v) = row.attrs.get(c) { - attrs.insert(c.clone(), v.clone()); + attrs.push((k, v.clone())); } } if let Some(n) = notes { @@ -1606,11 +1818,18 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = Vec::new(); + // GeoBorders first: airspace borders follow them by reference. + let (mut first, rest): (Vec, Vec) = + order.into_iter().partition(|id| features.get(id).is_some_and(|f| f.kind == "GeoBorder")); + first.extend(rest); + let order = first; crate::progress::begin(index.members.len() + order.len()); crate::progress::step(index.members.len())?; for id in &order { @@ -1684,7 +1903,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = layers_of.iter().enumerate().flat_map(|(i, ps)| ps.iter().copied().filter(move |p| last.get(local(p)) == Some(&i))).collect(); // A row being read keeps no more than the layers still may. - let mut row = Row { limit: Some(layers.bytes_left), ..Row::default() }; + let mut row = Row { limit: Some(layers.bytes_left), interned: std::rc::Rc::clone(&paths), ..Row::default() }; row.set("identifier", id.trim_start_matches("urn:uuid:").to_string()); let valid = |t: Option| t.map(|t| crate::time::format(t, "YYYY-MM-DDTHH:mm:ss") + "Z"); match valid(base.begin) { @@ -1696,6 +1915,18 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result row.null("validTo"), } let kind = feature.kind.as_str(); + // A GeoBorder's line, at the date, for the borders that follow it by reference: by its + // identifier and its curve's id. + if kind == "GeoBorder" + && let Some(g) = props.iter().filter(|p| local(p) == "border").find_map(|p| shape_in(*p)) + && let Some(Geometry::Line(parts)) = shapes.shape(g, &mut ShapeNotes::default()) + { + let line: Vec = parts.concat(); + if let Some(gid) = g.attribute((GML, "id")) { + shapes.borders.insert(format!("#{}", gid.trim()), line.clone()); + } + shapes.borders.insert(border_key(id), line); + } let mut fnotes = ShapeNotes::default(); let placed = match kind { "Airspace" => airspace(&props, &mut row, &mut shapes, &mut fnotes, &mut layers, kind, temporary, snapshot), @@ -1726,7 +1957,8 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result> { +fn finish( + stem: &str, + at: f64, + layers: Layers, + notes: FileNotes, + index: &Index, + budget_spent: bool, + paths: &Paths, +) -> Result> { let mut file = ReadReport::default(); let say = |r: &mut ReadReport, n: usize, one: &str, many: &str, rest: &str| { if n > 0 { @@ -2090,44 +2330,64 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, } else { format!("{stem} {} {}", layer.kind, layer.label) }; - // Nested values as columns, named by their paths across the whole layer. + // Nested values as columns, named by their paths across the whole layer; each path's + // column worked out once. let mut layer = layer; - let repeating = path_columns(&layer.rows); - let mut rows = Vec::with_capacity(layer.rows.len()); + let repeating = path_columns(&layer.rows, paths); + let mut column_of: HashMap> = HashMap::new(); + let mut rows: Vec<(Option, Vec<(usize, String)>)> = Vec::with_capacity(layer.rows.len()); for (g, mut attrs, nested) in std::mem::take(&mut layer.rows) { - for (path, value) in nested { - let column = path_column(&path, &repeating); - if !layer.column(&column) { - continue; + for (id, value) in nested { + let k = match column_of.get(&id) { + Some(k) => *k, + None => { + let k = paths.list.get(id).and_then(|p| layer.column(&path_column(p, &repeating))); + column_of.insert(id, k); + k + } + }; + if let (Some(k), Some(v)) = (k, value) { + attrs.push((k, v)); } - if let Some(v) = value { - match attrs.get_mut(&column) { - Some(old) if !v.is_empty() => { + } + // A column given more than once keeps every value, in order. + attrs.sort_by_key(|(k, _)| *k); + let mut merged: Vec<(usize, String)> = Vec::with_capacity(attrs.len()); + for (k, v) in attrs { + match merged.last_mut() { + Some((last, old)) if *last == k => { + if !v.is_empty() { old.push_str("; "); old.push_str(&v); } - Some(_) => {} - None => { - attrs.insert(column, v); - } } + _ => merged.push((k, v)), } } - rows.push((g, attrs)); - } - let fields: Vec = layer - .columns - .iter() - .map(|c| { - Field::new( - c.clone(), - crate::io::text_type(rows.iter().filter_map(|(_, a)| a.get(c)).map(String::as_str).filter(|v| !v.is_empty())), - ) - }) - .collect(); + rows.push((g, merged)); + } + // Each column typed from its values, looked at where they are. + let mut values: Vec> = vec![Vec::new(); layer.columns.len()]; + for (_, attrs) in &rows { + for (k, v) in attrs { + if let Some(col) = values.get_mut(*k) + && !v.is_empty() + { + col.push(v); + } + } + } + let fields: Vec = + layer.columns.iter().zip(&values).map(|(c, vs)| Field::new(c.clone(), crate::io::text_type(vs.iter().copied()))).collect(); + drop(values); let mut ds = Dataset::new(title, GeometryType::None, fields); for (g, attrs) in rows { - let row = ds.fields.iter().map(|f| attrs.get(&f.name).map_or(Value::Null, |v| Value::parse_file(v, f.ty))).collect(); + let mut row = vec![Value::Null; ds.fields.len()]; + for (k, v) in attrs { + if let (Some(slot), Some(f)) = (row.get_mut(k), ds.fields.get(k)) { + *slot = Value::parse_file(&v, f.ty); + } + } ds.push_next(g, row); } ds.geometry_type = crate::io::dominant_type(&ds); @@ -2190,8 +2450,18 @@ fn finish(stem: &str, at: f64, layers: Layers, notes: FileNotes, index: &Index, ); say( layer.referenced, - "border is given by reference to another feature's curve, which isn't followed", - "borders are given by reference to another feature's curve, which isn't followed", + "border is given by reference to a curve that isn't in the file (or not in force then), so it can't be followed", + "borders are given by reference to curves that aren't in the file (or not in force then), so they can't be followed", + ); + say( + layer.followed, + "border given by reference is drawn along the GeoBorder it names, between the points on it nearest those either side (AIXM leaves this cut to the reader)", + "borders given by reference are drawn along the GeoBorders they name, between the points on them nearest those either side (AIXM leaves this cut to the reader)", + ); + say( + layer.far, + &format!("border followed by reference starts or ends more than {FAR_FROM_BORDER_M} m from the GeoBorder"), + &format!("borders followed by reference start or end more than {FAR_FROM_BORDER_M} m from the GeoBorder"), ); say( layer.temporary, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index e93ac7b700..e1f8a8faa9 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -783,3 +783,64 @@ fn a_long_value_copied_onto_many_rows_stays_within_the_files_allowance() { assert!(rows < 1000, "{rows} rows of a megabyte each"); assert!(said(&out).iter().any(|m| m.contains("past the memory the file's size allows")), "{:?}", said(&out)); } + +#[test] +fn a_border_given_by_reference_is_followed_between_the_points_either_side() { + let border = r#"NORTH-SOUTH50 9 50 10.5 50 12"#; + let geo = feature("GeoBorder", "border-1", &[slice("GeoBorder", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), border)]); + let ring_xml = r#"50 11 50.5 11 50.5 10 50 10"#; + let body = format!( + r#"FOLLOWSBASE1{ring_xml}"# + ); + // The airspace comes first in the file: the border it follows is read first all the same. + let asp = feature("Airspace", "a", &[slice("Airspace", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let out = read("t.xml", &message(&(asp + &geo)), &at("2026-01-15")).unwrap(); + let ring = ring(layer(&out, "t Airspace").features[0].geometry.as_ref().unwrap()); + // From the point before (10, 50) along the border through its vertex at 10.5 to the next (11, 50). + assert!(ring.iter().any(|c| (c.x - 10.5).abs() < 1e-9 && (c.y - 50.0).abs() < 1e-9), "{ring:?}"); + assert!(!ring.iter().any(|c| c.x < 9.99 || c.x > 11.01), "{ring:?}"); + assert_eq!(ring.first(), ring.last()); + let notes = said(&out); + assert!(notes.iter().any(|m| m.contains("1 border given by reference is drawn along the GeoBorder")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("can't be followed") || m.contains("more than")), "{notes:?}"); +} + +#[test] +fn a_closed_border_is_cut_the_shorter_way_round() { + let square = [Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0), Coord::new(0.0, 1.0), Coord::new(0.0, 0.0)]; + let (part, off) = cut(&square, Coord::new(0.5, 0.0), Coord::new(1.0, 0.5)).unwrap(); + assert_eq!(part, [Coord::new(0.5, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 0.5)]); + assert!(off < 1e-6); + let (part, _) = cut(&square, Coord::new(1.0, 0.5), Coord::new(0.5, 0.0)).unwrap(); + assert_eq!(part, [Coord::new(1.0, 0.5), Coord::new(1.0, 0.0), Coord::new(0.5, 0.0)]); +} + +#[test] +fn an_faa_subscriber_file_is_read_and_its_references_name_the_features() { + let file = r##" + + + + + + 2026-10-29T00:00:00.000-04:00 + BASELINE + ABC + 32.9 -97.0 + + + + + + +"##; + assert!(looks_like_aixm(file.as_bytes())); + let out = read("NAV_AIXM.xml", file.as_bytes(), &at("2026-11-23")).unwrap(); + let ds = layer(&out, "NAV_AIXM Navaid"); + assert_eq!(value(ds, 0, "identifier"), Value::Text("NAVAID_0000001".into())); + assert_eq!(value(ds, 0, "designator"), Value::Text("ABC".into())); + assert_eq!(value(ds, 0, "navaidEquipment_theNavaidEquipment"), Value::Text("TACAN_0000001".into())); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(-97.0, 32.9)))); + // A subscriber file not of AIXM 5 isn't taken for one. + assert!(!looks_like_aixm(file.replace("AIXM5.1\"", "AIXM4.5\"").as_bytes())); +} From 4820bb171cb2163375cc5196da94375d0e379ebd Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:54:30 -0600 Subject: [PATCH 09/61] feat(data): AIXM route segments between their points, NAD83 (CRS83), empty time positions; border scans bounded --- crates/data/src/aixm.rs | 139 +++++++++++++++++++++++++++++----- crates/data/src/aixm/tests.rs | 55 ++++++++++++++ 2 files changed, 173 insertions(+), 21 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 8e6850676b..15c52c13ca 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -328,11 +328,16 @@ fn is_nil(n: &Node) -> bool { /// A date of a `gml:beginPosition`/`endPosition`/`timePosition`: `Ok(None)` for an open end /// (`indeterminatePosition`, or empty), `Err` for one that isn't a date. -fn position(n: Option) -> std::result::Result, ()> { +fn position(n: Option, empty: &std::cell::Cell) -> std::result::Result, ()> { let Some(n) = n else { return Ok(None) }; let t = text_of(&n); if t.is_empty() { - return if n.attribute("indeterminatePosition").is_some() { Ok(None) } else { Err(()) }; + // An empty position that doesn't say it is unknown (the FAA's ``) is + // read as open too, and counted. + if n.attribute("indeterminatePosition").is_none() { + empty.set(empty.get() + 1); + } + return Ok(None); } crate::time::parse_text(&t).map(Some).ok_or(()) } @@ -460,6 +465,8 @@ struct SliceTrouble { unknown: usize, /// Slices with dates that aren't dates. dates: usize, + /// Validity or lifetime ends left empty without saying they are unknown, read as open. + empty: usize, } /// A slice's own properties. @@ -475,22 +482,23 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro } }; let number = |name: &str| child(s, name).and_then(|n| text_of(&n).parse::().ok()).unwrap_or(0); + let empty = std::cell::Cell::new(0); let (mut begin, mut end, mut canceled) = (None, None, false); let mut bad = false; if let Some(v) = child(s, "validTime") { match elements(v).next() { Some(p) if local(&p) == "TimePeriod" => { - begin = position(child(p, "beginPosition")).unwrap_or_else(|()| { + begin = position(child(p, "beginPosition"), &empty).unwrap_or_else(|()| { bad = true; None }); - end = position(child(p, "endPosition")).unwrap_or_else(|()| { + end = position(child(p, "endPosition"), &empty).unwrap_or_else(|()| { bad = true; None }); } Some(i) if local(&i) == "TimeInstant" => { - begin = position(child(i, "timePosition")).unwrap_or_else(|()| { + begin = position(child(i, "timePosition"), &empty).unwrap_or_else(|()| { bad = true; None }); @@ -501,16 +509,17 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro } } let lifetime = child(s, "featureLifetime").and_then(|l| elements(l).find(|p| local(p) == "TimePeriod")).map(|p| { - let from = position(child(p, "beginPosition")).unwrap_or_else(|()| { + let from = position(child(p, "beginPosition"), &empty).unwrap_or_else(|()| { bad = true; None }); - let until = position(child(p, "endPosition")).unwrap_or_else(|()| { + let until = position(child(p, "endPosition"), &empty).unwrap_or_else(|()| { bad = true; None }); (from, until) }); + trouble.empty += empty.get(); if bad { trouble.dates += 1; return None; @@ -580,6 +589,8 @@ struct ShapeNotes { /// ends lie more than [`FAR_FROM_BORDER_M`] from it. followed: usize, far: usize, + /// A route segment drawn between the points it names, having no curve. + between: bool, } /// Reads shapes, adding at most `budget` points to the file's positions. @@ -600,6 +611,9 @@ struct Shapes { as_wgs84_now: bool, /// The borders references may follow, by [`border_key`]: each GeoBorder's at the date. borders: HashMap>, + /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of + /// route segments that name them. + points: HashMap, } fn wrap180(d: f64) -> f64 { @@ -650,6 +664,13 @@ impl Shapes { if crate::ogc::warp::is_crs84(name) { return Some(Axes { swap: false }); } + // OGC's CRS83: NAD83 longitude/latitude, as the FAA writes it; within a couple of meters + // of WGS 84 in North America, read as it and said. + if name.trim().to_ascii_uppercase().ends_with(":CRS83") { + self.as_wgs84.get_or_insert_with(|| name.to_string()); + self.as_wgs84_now = true; + return Some(Axes { swap: false }); + } match crate::gml::srs(name).map(|(c, _)| c) { Some(c) if c.is_geographic() => { if c.epsg() != 4326 { @@ -925,19 +946,38 @@ impl Shapes { } let mut out: Vec = Vec::new(); let n = members.len(); + // Each member's nearest written points before and after it, round the ring: two + // passes, however many members are references. + let end_of = |m: Option<&std::result::Result, String>>| match m { + Some(Ok(c)) => c.last().copied(), + _ => None, + }; + let start_of = |m: Option<&std::result::Result, String>>| match m { + Some(Ok(c)) => c.first().copied(), + _ => None, + }; + let mut befores: Vec> = vec![None; n]; + let mut carry = (0..n).rev().find_map(|k| end_of(members.get(k))); + for i in 0..n { + if let Some(b) = befores.get_mut(i) { + *b = carry; + } + carry = end_of(members.get(i)).or(carry); + } + let mut afters: Vec> = vec![None; n]; + let mut carry = (0..n).find_map(|k| start_of(members.get(k))); + for i in (0..n).rev() { + if let Some(a) = afters.get_mut(i) { + *a = carry; + } + carry = start_of(members.get(i)).or(carry); + } for i in 0..n { let mut part = match members.get(i) { Some(Ok(c)) => c.clone(), Some(Err(key)) => { - // The written points before and after it, round the ring. - let before = (1..n).find_map(|k| match members.get((i + n - k) % n) { - Some(Ok(c)) => c.last().copied(), - _ => None, - }); - let after = (1..n).find_map(|k| match members.get((i + k) % n) { - Some(Ok(c)) => c.first().copied(), - _ => None, - }); + let before = befores.get(i).copied().flatten(); + let after = afters.get(i).copied().flatten(); // Said as a border by reference by the ring's patch, not also as a // ring left out. let Some(part) = self.follow(key, before, after, notes) else { @@ -975,6 +1015,12 @@ impl Shapes { /// ring has no other points. AIXM leaves this cut to the reader (its coding guidance, "Geoborder /// for Airspace Border"), so each is counted, and those whose ends lie far from the border. fn follow(&mut self, key: &str, before: Option, after: Option, notes: &mut ShapeNotes) -> Option> { + let scan = self.borders.get(key)?.len(); + // Looking along the border is paid for as points are, so references can't make the + // looking outgrow what the file's size allows. + if self.take(scan, notes) < scan { + return None; + } let border = self.borders.get(key)?; let part = match (before, after) { (Some(a), Some(b)) => { @@ -1190,6 +1236,8 @@ struct Layer { /// Borders given by reference followed along a GeoBorder, and those with ends far from it. followed: usize, far: usize, + /// Route segments drawn between the points they name. + between: usize, /// Shapes in the records of features drawn from their own shapes, not drawn. shapes_in_records: usize, /// Features as a TEMPDELTA changed them. @@ -1227,6 +1275,7 @@ impl Layer { self.referenced += n.referenced; self.followed += n.followed; self.far += n.far; + self.between += usize::from(n.between); } } @@ -1701,6 +1750,8 @@ fn projection<'a, 'i>(v: Option>) -> Option> { /// What the read says of the file as a whole. #[derive(Default)] struct FileNotes { + /// Time positions left empty without saying they are unknown, read as open. + empty_dates: usize, /// Elements of members that aren't AIXM features. foreign: usize, /// Slices not read: wrapping or parsing them would pass the file's limits. @@ -1817,6 +1868,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result = Vec::new(); - // GeoBorders first: airspace borders follow them by reference. - let (mut first, rest): (Vec, Vec) = - order.into_iter().partition(|id| features.get(id).is_some_and(|f| f.kind == "GeoBorder")); - first.extend(rest); - let order = first; + // GeoBorders first: airspace borders follow them by reference; route segments last: one with + // no curve is drawn between the points it names. + let rank = |id: &String| match features.get(id).map(|f| f.kind.as_str()) { + Some("GeoBorder") => 0, + Some("RouteSegment") => 2, + _ => 1, + }; + let mut order = order; + order.sort_by_key(rank); crate::progress::begin(index.members.len() + order.len()); crate::progress::step(index.members.len())?; for id in &order { @@ -1927,6 +1983,12 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result airspace(&props, &mut row, &mut shapes, &mut fnotes, &mut layers, kind, temporary, snapshot), @@ -1961,6 +2023,20 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Option> { + let end = |name: &str| -> Option { + let p = props.iter().find(|p| local(p) == name)?; + let r = + p.descendants().find(|d| d.is_element() && local(d).starts_with("pointChoice_") && d.attribute((XLINK, "href")).is_some())?; + shapes.points.get(&reference(r.attribute((XLINK, "href"))?)).copied() + }; + let (a, b) = (end("start")?, end("end")?); + let mut notes = ShapeNotes::default(); + Some(shapes.geodesic(&[a, b], &mut notes)) +} + /// The family a shape element draws as, by its name (what a layer of its shapes is labeled). fn element_family(name: &str) -> &'static str { match name { @@ -2030,6 +2106,15 @@ fn feature_rows( } return true; } + // A route segment with no curve: a geodesic between the points its start and end name. + if parts.is_empty() + && kind == "RouteSegment" + && let Some(line) = between(props, shapes) + { + let notes = ShapeNotes { between: true, ..ShapeNotes::default() }; + layers.push(kind, "curveExtent", Some(Geometry::Line(vec![line])), row.clone(), Some(¬es), change); + return true; + } if parts.is_empty() { return false; } @@ -2272,6 +2357,13 @@ fn finish( "time slices", "with no interpretation RustGIS knows (BASELINE, PERMDELTA, TEMPDELTA, SNAPSHOT) not read", ); + say( + &mut file, + notes.empty_dates, + "time position", + "time positions", + "left empty (not said to be unknown) read as open: no start or no end", + ); say(&mut file, notes.bad_dates, "time slice", "time slices", "with a validTime or featureLifetime that isn't a date not read"); say( &mut file, @@ -2453,6 +2545,11 @@ fn finish( "border is given by reference to a curve that isn't in the file (or not in force then), so it can't be followed", "borders are given by reference to curves that aren't in the file (or not in force then), so they can't be followed", ); + say( + layer.between, + "route segment with no curve is drawn as a geodesic between the points its start and end name", + "route segments with no curve are drawn as geodesics between the points their start and end name", + ); say( layer.followed, "border given by reference is drawn along the GeoBorder it names, between the points on it nearest those either side (AIXM leaves this cut to the reader)", diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index e1f8a8faa9..0cb9ecb978 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -844,3 +844,58 @@ fn an_faa_subscriber_file_is_read_and_its_references_name_the_features() { // A subscriber file not of AIXM 5 isn't taken for one. assert!(!looks_like_aixm(file.replace("AIXM5.1\"", "AIXM4.5\"").as_bytes())); } + +#[test] +fn many_references_to_a_long_border_stay_within_the_files_allowance() { + let line: String = (0..5000).map(|i| format!("50 {} ", 9.0 + f64::from(i) * 0.0005)).collect(); + let border = format!( + r#"LONG{line}"# + ); + let geo = feature("GeoBorder", "border-1", &[slice("GeoBorder", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &border)]); + let refs = r#""#.repeat(20_000); + let ring_xml = format!( + r#"{refs}50 11 50.5 11 50.5 10 50 10"# + ); + let body = format!( + r#"MANY{ring_xml}"# + ); + let area = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let out = read("t.xml", &message(&(area + &geo)), &at("2026-01-15")).unwrap(); + // 20,000 cuts of a 5,000-point border would be 100 million steps; the allowance stops them. + assert!(said(&out).iter().any(|m| m.contains("can't be followed")), "{:?}", said(&out)); +} + +#[test] +fn faa_route_segments_are_drawn_between_their_points_in_nad83() { + let point = |id: &str, lat: f64, lon: f64| { + format!( + r#"2026-10-29T00:00:00.000-04:00BASELINE{id}{lon} {lat}"# + ) + }; + let xpath = |id: &str| format!("#/faa:SubscriberFile/faa:Member/aixm:DesignatedPoint%5B@gml:id='{id}'%5D"); + let segment = format!( + r#"2026-10-29T00:00:00.000-04:00BASELINE"#, + xpath("A"), + xpath("B") + ); + // The segment comes before the points it names. + let file = format!( + r#"{segment}{}{}"#, + point("A", 32.0, -97.0), + point("B", 33.0, -96.0) + ); + let out = read("AWY_AIXM.xml", file.as_bytes(), &at("2026-11-23")).unwrap(); + let rs = layer(&out, "AWY_AIXM RouteSegment"); + let Some(Geometry::Line(parts)) = &rs.features[0].geometry else { panic!("{:?}", rs.features[0].geometry) }; + assert_eq!(parts[0].first(), Some(&Coord::new(-97.0, 32.0))); + assert_eq!(parts[0].last(), Some(&Coord::new(-96.0, 33.0))); + assert!(parts[0].len() > 10, "drawn along the geodesic"); + let notes = said(&out); + for want in [ + "1 route segment with no curve is drawn as a geodesic between the points its start and end name", + "read as WGS 84 longitude/latitude", + "2 time positions left empty (not said to be unknown) read as open", + ] { + assert!(notes.iter().any(|m| m.contains(want)), "{want}: {notes:?}"); + } +} From 29482f44a247b4a825bd447be06fe77489659e64 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:58:40 -0600 Subject: [PATCH 10/61] fix(data): an AIXM shape with empty positions is said as no geometry, not unreadable --- crates/data/src/aixm.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 15c52c13ca..19e31a7c3f 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -2094,11 +2094,15 @@ fn feature_rows( r.shape_values(g, &name); // A kind's shapes under different properties are different layers (an airport's // reference point and its boundary); a kind with one is one layer, titled by its kind. - let bad = geom.is_none(); + // A shape whose positions are all empty (``, as the FAA writes a + // position it doesn't have) gives none: said as no geometry, not as unreadable. + let empty = !g.descendants().any(|d| d.is_element() && is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()); + let bad = geom.is_none() && !empty; let i = layers.push(kind, &name, geom, r, Some(¬es), change); first = first.or(i); if let Some(l) = layers.at(i) { l.unreadable += usize::from(bad); + l.shapeless += usize::from(empty); } } if let Some(l) = layers.at(first) { From 3d888a28aa43e3a1084b7c48954c2d1ae707ba12 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:02:24 -0600 Subject: [PATCH 11/61] test(data): a DFS airspace extract (CC BY 4.0) that follows a state border by reference; docs for FAA files and borders --- ATTRIBUTION.md | 1 + crates/data/src/aixm.rs | 3 +- crates/data/src/aixm/tests.rs | 24 + crates/data/tests/data/dfs-airspace-aixm.xml | 2239 ++++++++++++++++++ docs/user-guide/data-formats.md | 2 +- 5 files changed, 2267 insertions(+), 2 deletions(-) create mode 100644 crates/data/tests/data/dfs-airspace-aixm.xml diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index d806cc6c2d..6749d2a967 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -31,6 +31,7 @@ of use. | CFF test font (`crates/render/testdata/test-cff.otf`), read only by the PDF font tests | The RustGIS project: generated for this test with [fontTools](https://github.com/fonttools/fonttools) by the script in `crates/render/testdata/README.md`; its glyphs are made up | Apache-2.0 | | Script-only and fallback test fonts (`crates/render/testdata/test-script-only.otf`, `crates/render/testdata/test-fallback.otf`, `crates/render/testdata/test-latin-catalog.otf`) | The RustGIS project: original square outlines and script cmap variants ([generation](crates/render/testdata/README.md)) | Apache-2.0 | | JAXA Earth catalog test copy (`crates/tiles/tests/data/jaxa_catalog.v2.md`), read only by tests | JAXA: the [JAXA Earth API](https://data.earth.jaxa.jp/) dataset catalog ([catalog.v2.md](https://data.earth.jaxa.jp/app/mcp/catalog.v2.md)), copied on 2026-11-08 | JAXA's [terms of use](https://earth.jaxa.jp/en/data/policy/): free to use and redistribute, with credit to JAXA | +| AIXM test message from DFS (`crates/data/tests/data/dfs-airspace-aixm.xml`), read only by tests | Three members of DFS Deutsche Flugsicherung GmbH's `ED_Airspace_ReferencedBorders_2026-10-29_2026-10-29_snapshot.xml` ([aip.dfs.de/datasets](https://aip.dfs.de/datasets/)): the GERMANY_NETHERLANDS GeoBorder and the MASKIRCHEN B AREA and BERLIN X airspaces, copied on 2026-11-23, the members unchanged and the message metadata left out | CC BY 4.0 | | AIXM test message (`crates/data/tests/data/donlon-aixm.xml`), read only by tests | Nine members of the fictitious Donlon dataset's `Donlon_ALL_Baseline_ADM_upload.xml` ([aixm/Donlon_2025](https://github.com/aixm/Donlon_2025)), copyright (c) 2025 EUROCONTROL & FAA, copied on 2026-11-23 with the file's license notice; the members are unchanged | BSD-2-Clause | | CityGML test mesh (`crates/data/tests/data/rocking-chair.gml`), read only by tests | 97 faces of the rocking chair in OGC's CityGML 3.0 sample `Building_LOD3-EPSG25832.gml` ([CityGML-3.0Encodings](https://github.com/opengeospatial/CityGML-3.0Encodings/blob/master/Moved_to_CITYGML-3.0Encoding_CityGML/Examples/Examples-from-CityGML-2.0/building/CityGMLv3/Building_LOD3-EPSG25832.gml)), copyright (c) 2013 3DXScape, copied on 2026-11-12 and rewritten as a CityGML 2.0 object, coordinates unchanged | MIT | | Datum grid test files (`crates/data/tests/data/grids/us_noaa_conus.tif`, `us_noaa_ethpgn.tif`), read only by the datum grid tests | NOAA's NADCON and HARN grids as converted by [PROJ-data](https://github.com/OSGeo/PROJ-data) (`us_noaa`), copied unchanged from [cdn.proj.org](https://cdn.proj.org) | Public domain | diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 19e31a7c3f..c572fcca10 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -2096,7 +2096,8 @@ fn feature_rows( // reference point and its boundary); a kind with one is one layer, titled by its kind. // A shape whose positions are all empty (``, as the FAA writes a // position it doesn't have) gives none: said as no geometry, not as unreadable. - let empty = !g.descendants().any(|d| d.is_element() && is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()); + let empty = + !g.descendants().any(|d| d.is_element() && is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()); let bad = geom.is_none() && !empty; let i = layers.push(kind, &name, geom, r, Some(¬es), change); first = first.or(i); diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 0cb9ecb978..7148bf3e10 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -899,3 +899,27 @@ fn faa_route_segments_are_drawn_between_their_points_in_nad83() { assert!(notes.iter().any(|m| m.contains(want)), "{want}: {notes:?}"); } } + +const DFS: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/dfs-airspace-aixm.xml")); + +#[test] +fn dfs_airspace_follows_the_state_border_it_names() { + let out = read("dfs-airspace-aixm.xml", DFS, &at("2026-11-23")).unwrap(); + let asp = layer(&out, "dfs-airspace-aixm Airspace"); + let i = row_where(asp, "name", "MASKIRCHEN B AREA"); + let ring = ring(asp.features[i].geometry.as_ref().unwrap()); + // From the written point at 51.0875 N 6.005 E, along the Dutch border, back to 50.92 N 6.06 E: + // the stretch of border between them, not all of it (which runs to the North Sea). + assert!(ring.len() > 10, "{ring:?}"); + assert!(ring.iter().all(|c| (5.8..6.3).contains(&c.x) && (50.85..51.15).contains(&c.y)), "{ring:?}"); + assert_eq!(ring.first(), ring.last()); + assert_eq!(value(asp, i, "geometryComponent_theAirspaceVolume_lowerLimit"), Value::Int(95)); + assert_eq!(value(asp, i, "lowerLimit_uom"), Value::Text("FL".into())); + // BERLIN X is drawn from its arcs. + assert!(asp.features[row_where(asp, "name", "BERLIN X")].geometry.is_some()); + let notes = said(&out); + for want in ["1 border given by reference is drawn along the GeoBorder", "1 feature has arcs or circles", "SNAPSHOT"] { + assert!(notes.iter().any(|m| m.contains(want)), "{want}: {notes:?}"); + } + assert!(!notes.iter().any(|m| m.contains("more than 50 m")), "{notes:?}"); +} diff --git a/crates/data/tests/data/dfs-airspace-aixm.xml b/crates/data/tests/data/dfs-airspace-aixm.xml new file mode 100644 index 0000000000..3483c7d932 --- /dev/null +++ b/crates/data/tests/data/dfs-airspace-aixm.xml @@ -0,0 +1,2239 @@ + + + + + + 0bf35787-9bc9-473b-b308-c04343fec2f5 + + + + + 2026-10-29T00:00:00Z + + + SNAPSHOT + + + 2016-03-03T00:00:00Z + + + + GERMANY_NETHERLANDS + STATE + + + + + 53.666666666666664 6.5 + 53.560555555555553 6.6066666666666674 + 53.522777777777776 6.6722222222222234 + 53.50416666666667 6.7416666666666671 + 53.495833333333337 6.8163888888888886 + 53.474444444444444 6.8636111111111111 + 53.398888888888891 6.9494444444444454 + 53.336388888888891 6.993611111111111 + 53.31666666666667 7.0250000000000004 + 53.299999999999997 7.1916666666666673 + 53.213333333333338 7.2169444444444446 + 53.201025000000001 7.2176333333333336 + 53.197822222222221 7.217625 + 53.195552777777777 7.2165527777777783 + 53.194836111111108 7.215644444444445 + 53.193836111111111 7.2134583333333344 + 53.192511111111109 7.2114555555555562 + 53.18848055555555 7.2080444444444449 + 53.180280555555555 7.2275 + 53.176969444444445 7.212563888888889 + 53.176544444444446 7.2081361111111111 + 53.176566666666666 7.2036555555555557 + 53.161697222222223 7.1908305555555554 + 53.160927777777779 7.1907361111111117 + 53.159886111111106 7.1912111111111114 + 53.15956388888889 7.1911527777777779 + 53.157380555555555 7.1893166666666666 + 53.155444444444441 7.1892250000000004 + 53.14801388888889 7.189627777777778 + 53.144397222222224 7.1855583333333337 + 53.142280555555558 7.1838944444444444 + 53.140405555555553 7.1832166666666666 + 53.138033333333333 7.1802555555555561 + 53.138538888888888 7.1789666666666667 + 53.13815833333333 7.1789388888888892 + 53.130027777777777 7.1802861111111111 + 53.127872222222223 7.1809333333333338 + 53.126672222222226 7.1818305555555559 + 53.124897222222224 7.1836111111111114 + 53.124927777777778 7.184075 + 53.124222222222222 7.185894444444445 + 53.121769444444446 7.1829000000000001 + 53.113413888888893 7.2027944444444447 + 53.081388888888895 7.1992194444444451 + 53.010880555555552 7.212969444444445 + 53.007041666666666 7.2174472222222219 + 53.005924999999998 7.216105555555556 + 53.005652777777776 7.2164888888888887 + 53.005119444444446 7.2151305555555556 + 53.000511111111109 7.2095638888888889 + 52.941586111111107 7.181516666666667 + 52.863944444444449 7.1043861111111104 + 52.859999999999999 7.0995916666666661 + 52.859738888888891 7.0987055555555552 + 52.859236111111116 7.0986611111111104 + 52.849888888888891 7.0872583333333328 + 52.838200000000001 7.0927416666666661 + 52.822450000000003 7.0807444444444441 + 52.822216666666669 7.0805305555555549 + 52.822325000000006 7.0800722222222223 + 52.821602777777784 7.0795305555555554 + 52.821483333333333 7.0799833333333329 + 52.810316666666665 7.0715527777777778 + 52.729188888888892 7.0649194444444454 + 52.644616666666664 7.054758333333333 + 52.644433333333332 7.0547722222222218 + 52.64436111111111 7.0556333333333328 + 52.643416666666667 7.0557222222222222 + 52.632727777777781 7.0417916666666667 + 52.632708333333333 7.0395777777777777 + 52.633002777777776 7.0383166666666668 + 52.634377777777779 7.0367249999999997 + 52.634824999999999 7.0356583333333331 + 52.634636111111114 7.0287694444444444 + 52.635727777777774 7.0213416666666664 + 52.636733333333332 7.0126416666666671 + 52.638580555555556 7.0064833333333336 + 52.639202777777776 7.0057416666666663 + 52.640913888888889 7.0044527777777779 + 52.641847222222225 7.0021111111111107 + 52.642147222222221 7.0005388888888893 + 52.642152777777774 6.9994111111111108 + 52.641297222222221 6.9937583333333331 + 52.641369444444443 6.992258333333333 + 52.643669444444441 6.9841833333333332 + 52.645066666666665 6.9817694444444447 + 52.646263888888889 6.9758916666666666 + 52.646061111111109 6.9748277777777776 + 52.642602777777775 6.9702138888888889 + 52.641755555555555 6.9681388888888893 + 52.641705555555554 6.9591222222222227 + 52.639200000000002 6.9542583333333337 + 52.638977777777775 6.9534861111111113 + 52.639319444444446 6.9452444444444454 + 52.637936111111109 6.9397972222222224 + 52.637841666666667 6.938736111111111 + 52.638316666666668 6.9346361111111117 + 52.640163888888885 6.9288166666666671 + 52.639844444444442 6.9193638888888893 + 52.639986111111114 6.918769444444445 + 52.641827777777777 6.9156388888888891 + 52.646002777777774 6.9149555555555562 + 52.646411111111114 6.914625 + 52.646711111111109 6.9140055555555557 + 52.647938888888888 6.9079305555555557 + 52.648580555555554 6.9030055555555556 + 52.650980555555556 6.8986694444444439 + 52.651338888888887 6.8974527777777777 + 52.65154722222222 6.8916916666666674 + 52.650547222222222 6.8799750000000008 + 52.651469444444444 6.876930555555556 + 52.652963888888884 6.8741333333333339 + 52.653261111111107 6.8731972222222231 + 52.652983333333331 6.8714277777777779 + 52.651849999999996 6.8694833333333341 + 52.649794444444446 6.864497222222222 + 52.649574999999999 6.8538249999999996 + 52.648613888888889 6.8511222222222221 + 52.651802777777775 6.838886111111111 + 52.651955555555553 6.8376722222222224 + 52.651497222222218 6.8316777777777773 + 52.650708333333334 6.8302972222222218 + 52.649883333333335 6.8295472222222218 + 52.649036111111108 6.8275194444444454 + 52.647733333333335 6.8222277777777771 + 52.647691666666667 6.8185861111111112 + 52.648619444444442 6.8161916666666666 + 52.649102777777777 6.8080194444444446 + 52.649447222222221 6.8072249999999999 + 52.651177777777775 6.8058555555555564 + 52.651874999999997 6.8032194444444443 + 52.651891666666664 6.8023749999999996 + 52.650641666666665 6.7943166666666661 + 52.650950000000002 6.7932722222222219 + 52.652555555555551 6.7908555555555559 + 52.652805555555553 6.7897833333333333 + 52.652363888888885 6.7873972222222223 + 52.652524999999997 6.7838805555555552 + 52.65166111111111 6.777363888888889 + 52.650244444444446 6.7742805555555554 + 52.650052777777773 6.7720916666666664 + 52.646863888888888 6.7678805555555552 + 52.648827777777775 6.7588333333333344 + 52.647261111111114 6.7555055555555557 + 52.647058333333334 6.7555500000000004 + 52.646791666666665 6.7548833333333329 + 52.646344444444445 6.754544444444444 + 52.645833333333336 6.7534638888888887 + 52.646361111111112 6.752477777777778 + 52.647041666666667 6.7519138888888888 + 52.647633333333332 6.7534694444444447 + 52.647933333333334 6.7536500000000004 + 52.648136111111114 6.7530833333333344 + 52.648024999999997 6.7522527777777777 + 52.647277777777781 6.7507111111111113 + 52.646888888888888 6.750491666666667 + 52.645386111111108 6.7420444444444447 + 52.641205555555558 6.7369611111111114 + 52.637527777777777 6.7306972222222221 + 52.633222222222223 6.7264027777777784 + 52.631447222222221 6.7208138888888893 + 52.631344444444444 6.7182833333333338 + 52.630313888888892 6.7151333333333332 + 52.628897222222221 6.7128027777777781 + 52.627863888888889 6.7100444444444447 + 52.627494444444444 6.7100333333333344 + 52.627316666666665 6.7101694444444444 + 52.626844444444444 6.7120027777777782 + 52.62683611111111 6.7142444444444447 + 52.625902777777782 6.7149027777777777 + 52.62341111111111 6.7181416666666669 + 52.623033333333332 6.7184249999999999 + 52.621969444444446 6.7186111111111124 + 52.621552777777779 6.7204138888888894 + 52.620355555555555 6.7221277777777777 + 52.620375000000003 6.7229000000000001 + 52.619144444444444 6.7243861111111114 + 52.618488888888891 6.7250027777777781 + 52.617847222222224 6.7252861111111111 + 52.614988888888888 6.7273361111111116 + 52.610413888888893 6.7250777777777779 + 52.609083333333338 6.7247555555555554 + 52.608541666666667 6.7244250000000001 + 52.607602777777778 6.724505555555556 + 52.605661111111111 6.7241583333333343 + 52.604594444444444 6.7237749999999998 + 52.604133333333337 6.7239222222222219 + 52.603161111111113 6.723725 + 52.598308333333335 6.7209500000000002 + 52.596358333333335 6.7208138888888893 + 52.594900000000003 6.7216222222222219 + 52.593341666666667 6.720077777777778 + 52.588625 6.7187972222222223 + 52.563536111111105 6.7666611111111123 + 52.561641666666667 6.7666972222222226 + 52.561563888888884 6.7639416666666667 + 52.559177777777776 6.7537750000000001 + 52.559044444444439 6.7519972222222222 + 52.559244444444438 6.7506055555555564 + 52.562066666666666 6.7400305555555553 + 52.562152777777776 6.7383805555555556 + 52.561749999999996 6.7343777777777776 + 52.56325833333333 6.725975 + 52.562627777777777 6.7255861111111113 + 52.561780555555551 6.7255361111111114 + 52.553105555555554 6.7210166666666664 + 52.552677777777774 6.7206972222222223 + 52.552513888888889 6.720219444444445 + 52.551672222222223 6.7199999999999998 + 52.550891666666665 6.7181805555555556 + 52.550330555555554 6.7162388888888893 + 52.549805555555551 6.7162694444444444 + 52.549227777777773 6.7160277777777777 + 52.548699999999997 6.7162388888888893 + 52.548436111111108 6.7161027777777784 + 52.55331944444444 6.680883333333334 + 52.521011111111108 6.7053416666666674 + 52.515983333333331 6.703986111111111 + 52.48628055555556 6.6975527777777781 + 52.478124999999999 6.7177416666666669 + 52.477183333333336 6.7204694444444444 + 52.477019444444444 6.7237749999999998 + 52.464113888888889 6.7527361111111111 + 52.459600000000002 6.7747638888888888 + 52.459580555555561 6.804469444444444 + 52.459963888888893 6.8317916666666667 + 52.459191666666669 6.8447361111111107 + 52.459708333333339 6.8542999999999994 + 52.449916666666667 6.8525444444444439 + 52.451361111111112 6.8618194444444454 + 52.446547222222222 6.889063888888888 + 52.442244444444441 6.906083333333334 + 52.435427777777775 6.9416611111111113 + 52.436624999999999 6.9473027777777778 + 52.443991666666662 6.9610583333333338 + 52.443630555555551 6.9617833333333339 + 52.443991666666662 6.9621833333333338 + 52.444622222222222 6.9619499999999999 + 52.449927777777773 6.9669305555555558 + 52.454472222222222 6.9699777777777783 + 52.459716666666672 6.9744472222222234 + 52.462902777777778 6.9760833333333334 + 52.463038888888889 6.9759972222222224 + 52.463119444444445 6.9761944444444444 + 52.465683333333338 6.977530555555556 + 52.469769444444445 6.9876111111111108 + 52.467355555555557 6.991827777777778 + 52.465488888888892 6.9939083333333336 + 52.462130555555561 6.9945777777777778 + 52.454711111111116 7.0000277777777784 + 52.445283333333329 7.0051055555555557 + 52.429133333333333 7.0107999999999997 + 52.422983333333327 7.0219944444444442 + 52.413697222222218 7.0280222222222219 + 52.407336111111107 7.032486111111111 + 52.406497222222221 7.0334166666666667 + 52.403852777777779 7.0347111111111111 + 52.402650000000001 7.0361222222222217 + 52.402741666666664 7.0382555555555557 + 52.402527777777777 7.0416638888888894 + 52.400863888888885 7.0465611111111111 + 52.400738888888888 7.0505444444444443 + 52.400555555555556 7.0510166666666674 + 52.399924999999996 7.051652777777778 + 52.401041666666664 7.0553222222222223 + 52.400580555555557 7.0559750000000001 + 52.399408333333334 7.0587333333333344 + 52.397136111111109 7.0591083333333344 + 52.396475000000002 7.0590055555555553 + 52.396180555555553 7.0585305555555564 + 52.390366666666665 7.0640027777777776 + 52.373605555555557 7.0721611111111109 + 52.372772222222224 7.0720472222222224 + 52.37168888888889 7.0722888888888891 + 52.368011111111109 7.0722638888888882 + 52.366808333333331 7.072769444444444 + 52.356527777777778 7.0720583333333327 + 52.35187777777778 7.0722555555555564 + 52.337963888888893 7.0562472222222219 + 52.334958333333333 7.0561499999999997 + 52.332950000000004 7.0548166666666674 + 52.332163888888893 7.0554500000000004 + 52.328697222222225 7.052138888888889 + 52.324933333333334 7.0480305555555551 + 52.323747222222224 7.0471833333333329 + 52.322830555555562 7.0469583333333334 + 52.321294444444447 7.0472416666666664 + 52.319952777777779 7.0480638888888887 + 52.31944166666667 7.0476111111111113 + 52.318494444444447 7.0475416666666666 + 52.316391666666661 7.0457333333333336 + 52.316613888888888 7.046469444444444 + 52.315300000000001 7.0474583333333332 + 52.314908333333328 7.0468555555555552 + 52.313913888888884 7.0432972222222219 + 52.313477777777777 7.0435472222222222 + 52.312427777777778 7.0388333333333328 + 52.311113888888883 7.0413277777777781 + 52.310158333333334 7.0405388888888893 + 52.307627777777775 7.0395000000000003 + 52.302452777777773 7.0338027777777778 + 52.291980555555554 7.0264277777777782 + 52.287319444444442 7.0262277777777777 + 52.281522222222222 7.0295444444444444 + 52.280183333333333 7.0296138888888891 + 52.279363888888888 7.0288361111111106 + 52.278933333333335 7.0279833333333332 + 52.277955555555558 7.0275194444444447 + 52.273644444444443 7.028569444444444 + 52.271705555555556 7.0320749999999999 + 52.256144444444445 7.0423972222222222 + 52.241236111111114 7.0657916666666667 + 52.237222222222222 7.0630222222222221 + 52.23471111111111 7.0612861111111114 + 52.227572222222221 7.0391000000000004 + 52.225716666666671 7.0263999999999998 + 52.225941666666671 7.0204527777777779 + 52.225058333333337 7.0191861111111109 + 52.225838888888887 7.0175333333333336 + 52.226511111111115 7.0146638888888893 + 52.227350000000001 7.0130861111111109 + 52.227047222222225 7.0124194444444443 + 52.226808333333338 7.0126555555555559 + 52.226883333333333 7.0117916666666664 + 52.227591666666669 7.0112249999999996 + 52.228597222222227 7.0034916666666662 + 52.227036111111111 6.9969916666666672 + 52.226980555555556 6.9942527777777777 + 52.227241666666671 6.9921666666666669 + 52.22699166666667 6.9898333333333333 + 52.226852777777779 6.9890805555555557 + 52.226305555555555 6.988833333333333 + 52.225983333333332 6.9878611111111111 + 52.225455555555556 6.9870999999999999 + 52.225272222222223 6.9851944444444447 + 52.224513888888893 6.9850222222222227 + 52.224066666666666 6.9855 + 52.223447222222227 6.9854222222222226 + 52.223058333333334 6.9844555555555559 + 52.222825 6.9844416666666671 + 52.222341666666665 6.9827833333333338 + 52.221038888888891 6.9812277777777778 + 52.219302777777777 6.9805944444444448 + 52.218183333333336 6.9797583333333337 + 52.217975000000003 6.9800611111111124 + 52.21723055555556 6.979713888888889 + 52.216141666666672 6.9795333333333334 + 52.214594444444444 6.9797666666666673 + 52.213336111111111 6.9790138888888889 + 52.212222222222223 6.9786333333333337 + 52.209888888888891 6.9763611111111112 + 52.206833333333336 6.9746361111111108 + 52.206780555555561 6.9748250000000001 + 52.205405555555558 6.9740888888888888 + 52.202980555555555 6.9709055555555564 + 52.201977777777778 6.9703583333333334 + 52.198041666666661 6.9672499999999999 + 52.197894444444444 6.9674000000000014 + 52.196241666666666 6.9646888888888894 + 52.195374999999999 6.9641500000000001 + 52.194299999999998 6.9623944444444454 + 52.192255555555555 6.9621361111111124 + 52.191288888888884 6.9624222222222221 + 52.187030555555552 6.957386111111111 + 52.185566666666666 6.9564527777777778 + 52.184080555555553 6.9544638888888892 + 52.183952777777776 6.9547277777777783 + 52.181058333333333 6.9512472222222224 + 52.181130555555555 6.9503722222222226 + 52.180505555555555 6.9495083333333332 + 52.179469444444443 6.9378861111111112 + 52.178750000000001 6.9362833333333338 + 52.178449999999998 6.9337444444444447 + 52.177613888888885 6.915633333333334 + 52.177147222222217 6.9118555555555563 + 52.175961111111107 6.908063888888889 + 52.175463888888885 6.9081083333333337 + 52.175069444444439 6.9067500000000006 + 52.173794444444439 6.9058416666666673 + 52.172669444444445 6.9059638888888903 + 52.17218611111111 6.905591666666667 + 52.171547222222223 6.905880555555556 + 52.170658333333328 6.905591666666667 + 52.170069444444444 6.9058972222222224 + 52.169916666666666 6.9057222222222228 + 52.16705833333333 6.900838888888889 + 52.164974999999998 6.896663888888888 + 52.156011111111113 6.8804611111111118 + 52.155977777777778 6.881966666666667 + 52.132975000000002 6.873302777777778 + 52.131936111111109 6.8730333333333338 + 52.130655555555556 6.8735333333333344 + 52.130283333333331 6.8734611111111112 + 52.130000000000003 6.8718972222222234 + 52.129522222222221 6.8710444444444452 + 52.129169444444443 6.8708722222222223 + 52.128072222222222 6.867091666666667 + 52.124966666666666 6.8627527777777777 + 52.120461111111112 6.8554749999999993 + 52.119197222222226 6.8432000000000004 + 52.118405555555555 6.822713888888889 + 52.11877777777778 6.7605833333333329 + 52.112952777777778 6.7597305555555556 + 52.109300000000005 6.7595944444444447 + 52.107533333333336 6.759241666666667 + 52.106569444444446 6.7587833333333336 + 52.105294444444446 6.7585833333333332 + 52.105313888888894 6.7584 + 52.103963888888892 6.7580333333333336 + 52.099299999999999 6.7576333333333336 + 52.097988888888892 6.7565694444444446 + 52.097130555555559 6.7554749999999997 + 52.096924999999999 6.7563138888888892 + 52.096016666666671 6.7555083333333332 + 52.095233333333333 6.7552666666666674 + 52.094863888888888 6.7550083333333344 + 52.09588055555556 6.7532944444444443 + 52.095802777777777 6.7502805555555554 + 52.094844444444448 6.7487083333333331 + 52.094388888888894 6.7465027777777777 + 52.093191666666669 6.745516666666667 + 52.093119444444447 6.7445055555555564 + 52.092088888888888 6.7452027777777781 + 52.091802777777779 6.7445861111111114 + 52.091149999999999 6.7450833333333344 + 52.090061111111112 6.7455083333333334 + 52.087561111111114 6.7502305555555564 + 52.085480555555556 6.7510861111111113 + 52.085027777777782 6.7509305555555557 + 52.081922222222225 6.7476166666666666 + 52.080911111111114 6.745025 + 52.080333333333336 6.7440249999999997 + 52.074633333333338 6.7354722222222234 + 52.072911111111111 6.7138749999999998 + 52.070144444444445 6.6959750000000007 + 52.069808333333334 6.6946611111111114 + 52.068586111111117 6.6954861111111112 + 52.068302777777781 6.6964694444444444 + 52.067352777777778 6.6968666666666667 + 52.064269444444442 6.6958833333333336 + 52.064197222222219 6.6952555555555557 + 52.059149999999995 6.6917027777777784 + 52.059141666666662 6.6914972222222229 + 52.056452777777778 6.689572222222222 + 52.056397222222216 6.6874000000000002 + 52.055524999999996 6.6868083333333344 + 52.053149999999995 6.6869861111111124 + 52.052541666666663 6.6867444444444448 + 52.052349999999997 6.6882000000000001 + 52.039858333333335 6.6878555555555561 + 52.040072222222221 6.7141472222222234 + 52.028408333333331 6.7529750000000002 + 52.022313888888888 6.7641 + 52.018786111111112 6.766313888888889 + 52.017894444444444 6.7721416666666663 + 52.015636111111114 6.7762555555555553 + 51.998097222222221 6.8114111111111111 + 51.994969444444443 6.8077999999999994 + 51.993527777777778 6.8266083333333327 + 51.989777777777782 6.828322222222222 + 51.986194444444443 6.8303527777777777 + 51.97943055555556 6.8296000000000001 + 51.976408333333332 6.8302333333333332 + 51.974347222222221 6.8323083333333328 + 51.972938888888891 6.832755555555555 + 51.971808333333335 6.8328138888888894 + 51.970047222222227 6.8324277777777773 + 51.964108333333336 6.8285305555555551 + 51.964130555555556 6.8217694444444454 + 51.963633333333334 6.8138388888888883 + 51.961833333333338 6.8124611111111113 + 51.958747222222222 6.7988749999999998 + 51.943977777777775 6.7962444444444454 + 51.943419444444444 6.7964444444444441 + 51.94255555555555 6.7972722222222224 + 51.935297222222218 6.7939916666666669 + 51.931191666666663 6.7859749999999996 + 51.929661111111109 6.7889444444444447 + 51.916202777777777 6.7700333333333331 + 51.916069444444446 6.7659916666666664 + 51.915394444444445 6.7634916666666669 + 51.914427777777775 6.7616500000000004 + 51.913988888888888 6.7594916666666673 + 51.913802777777775 6.7569166666666662 + 51.91309444444444 6.7546249999999999 + 51.912627777777779 6.7540250000000004 + 51.912355555555557 6.754175 + 51.912041666666667 6.7540333333333331 + 51.910472222222218 6.7541333333333338 + 51.910069444444446 6.7543972222222219 + 51.908733333333331 6.7526555555555552 + 51.908552777777778 6.7520555555555557 + 51.907224999999997 6.7511861111111111 + 51.905724999999997 6.745541666666667 + 51.905269444444443 6.7405027777777784 + 51.904683333333331 6.7371388888888886 + 51.898705555555559 6.7325277777777783 + 51.89608611111111 6.7218999999999998 + 51.906391666666664 6.7032333333333334 + 51.90936111111111 6.7038388888888889 + 51.909730555555555 6.7032583333333333 + 51.909722222222221 6.7013750000000014 + 51.90904722222222 6.6997805555555558 + 51.909844444444445 6.6976250000000004 + 51.915063888888888 6.6955611111111111 + 51.915174999999998 6.6957638888888891 + 51.915722222222222 6.6955388888888887 + 51.915861111111113 6.6951777777777783 + 51.914733333333331 6.6926000000000014 + 51.914947222222224 6.6900916666666674 + 51.915149999999997 6.6898472222222223 + 51.91501944444444 6.6895500000000014 + 51.915383333333331 6.6886972222222223 + 51.916169444444442 6.6842500000000014 + 51.91737222222222 6.6847333333333339 + 51.91759444444444 6.6840833333333336 + 51.915938888888888 6.6747888888888891 + 51.913866666666664 6.6687250000000002 + 51.911205555555554 6.6620694444444446 + 51.90720833333333 6.6488416666666659 + 51.904469444444445 6.6376777777777773 + 51.901052777777778 6.6341638888888887 + 51.900874999999999 6.6277277777777783 + 51.90195277777778 6.6253361111111113 + 51.897261111111114 6.6043277777777778 + 51.894083333333334 6.5857833333333327 + 51.888311111111108 6.5695249999999996 + 51.885494444444447 6.5638694444444443 + 51.884416666666667 6.5627722222222218 + 51.884063888888889 6.5618333333333334 + 51.884127777777778 6.5609972222222224 + 51.882933333333334 6.5606694444444447 + 51.882544444444441 6.5610055555555551 + 51.882205555555558 6.5606111111111112 + 51.882533333333335 6.5587999999999997 + 51.882397222222224 6.5577833333333331 + 51.882288888888887 6.5576444444444446 + 51.882013888888892 6.5577888888888891 + 51.881827777777779 6.5575055555555553 + 51.881783333333331 6.556 + 51.882666666666665 6.5552805555555551 + 51.883363888888887 6.5553805555555558 + 51.883533333333332 6.555244444444444 + 51.884063888888889 6.5526777777777774 + 51.886208333333336 6.5523277777777773 + 51.885511111111107 6.5497027777777781 + 51.88536666666667 6.5482722222222218 + 51.883963888888886 6.5491416666666664 + 51.883427777777776 6.549894444444444 + 51.883125 6.5494111111111106 + 51.883233333333337 6.5476555555555551 + 51.884597222222219 6.5453722222222224 + 51.884444444444441 6.5437972222222234 + 51.883524999999999 6.5423916666666662 + 51.882633333333331 6.5421583333333331 + 51.881966666666671 6.5413333333333332 + 51.881708333333336 6.5407083333333329 + 51.880938888888892 6.5398916666666667 + 51.880863888888889 6.5389444444444447 + 51.880338888888886 6.5385944444444446 + 51.879597222222223 6.5372222222222218 + 51.878866666666667 6.5342833333333328 + 51.877736111111112 6.5318194444444444 + 51.877002777777776 6.5293527777777776 + 51.87658888888889 6.5292083333333331 + 51.876036111111112 6.5298666666666669 + 51.874155555555554 6.5244472222222223 + 51.873719444444447 6.5245861111111108 + 51.873138888888889 6.5181611111111106 + 51.873416666666664 6.5170194444444443 + 51.873508333333334 6.5154500000000004 + 51.873008333333331 6.514216666666667 + 51.871941666666665 6.512483333333333 + 51.870897222222226 6.5115722222222221 + 51.869750000000003 6.5085361111111109 + 51.868558333333333 6.5045416666666664 + 51.867530555555554 6.5030666666666663 + 51.867913888888893 6.5028555555555556 + 51.867805555555556 6.5019027777777776 + 51.868194444444448 6.5013944444444443 + 51.868002777777775 6.5010611111111114 + 51.866877777777781 6.5010527777777778 + 51.865683333333337 6.5020944444444444 + 51.864708333333333 6.5022083333333329 + 51.862661111111116 6.5008444444444446 + 51.862275000000004 6.5002916666666666 + 51.86096388888889 6.496372222222222 + 51.859836111111115 6.4913249999999998 + 51.859338888888892 6.4903000000000004 + 51.859044444444443 6.4877916666666664 + 51.857105555555556 6.4829138888888886 + 51.856708333333337 6.4772027777777783 + 51.855477777777779 6.473897222222222 + 51.85498888888889 6.473330555555556 + 51.854722222222222 6.4733583333333344 + 51.854600000000005 6.4729000000000001 + 51.853836111111114 6.4725166666666674 + 51.854050000000001 6.4694083333333339 + 51.854433333333333 6.4671861111111113 + 51.855377777777782 6.4639944444444444 + 51.856438888888889 6.4617055555555556 + 51.858086111111113 6.4590388888888892 + 51.859322222222225 6.4574722222222221 + 51.861350000000002 6.4553694444444449 + 51.862852777777782 6.4541194444444443 + 51.86461111111111 6.4517555555555557 + 51.865244444444443 6.4511722222222234 + 51.865505555555558 6.4484722222222226 + 51.865005555555555 6.446680555555556 + 51.863750000000003 6.4454861111111112 + 51.8628 6.4440166666666672 + 51.862383333333334 6.4424666666666672 + 51.861861111111111 6.4413805555555559 + 51.862108333333332 6.4387305555555558 + 51.860219444444446 6.4342027777777782 + 51.859986111111112 6.4337638888888904 + 51.859744444444445 6.4339277777777779 + 51.859408333333334 6.4324250000000003 + 51.860155555555558 6.4309416666666666 + 51.860636111111113 6.4293750000000003 + 51.861677777777778 6.4291361111111112 + 51.862102777777778 6.4295361111111111 + 51.862741666666665 6.4291055555555561 + 51.863275000000002 6.4292611111111118 + 51.863477777777781 6.4288472222222222 + 51.865127777777779 6.4284916666666669 + 51.865619444444448 6.4277250000000006 + 51.866202777777779 6.4260972222222223 + 51.865872222222222 6.4254361111111118 + 51.865949999999998 6.424236111111111 + 51.866463888888887 6.423775 + 51.866322222222223 6.4230666666666671 + 51.866922222222222 6.4220277777777781 + 51.866705555555555 6.4212472222222221 + 51.866758333333337 6.420208333333334 + 51.86720833333333 6.4185472222222222 + 51.869419444444446 6.4140638888888892 + 51.86985 6.4134944444444448 + 51.87027777777778 6.4133444444444452 + 51.871097222222225 6.4122750000000002 + 51.870458333333332 6.4111000000000002 + 51.870288888888886 6.411027777777778 + 51.870011111111111 6.4112638888888904 + 51.86987222222222 6.4107361111111114 + 51.869500000000002 6.4103722222222226 + 51.869816666666665 6.4100138888888889 + 51.869902777777781 6.408727777777778 + 51.870686111111112 6.4067250000000007 + 51.870669444444445 6.4057166666666667 + 51.870280555555553 6.4045000000000014 + 51.869824999999999 6.4040944444444454 + 51.869083333333336 6.4023555555555562 + 51.869352777777777 6.4013500000000008 + 51.869994444444444 6.4011472222222228 + 51.870408333333337 6.4007861111111124 + 51.870180555555557 6.3992166666666668 + 51.870908333333333 6.3982944444444447 + 51.870238888888892 6.39635 + 51.871133333333333 6.3959083333333338 + 51.87200277777778 6.3951805555555561 + 51.873038888888892 6.3936666666666673 + 51.873822222222223 6.3931194444444452 + 51.874005555555556 6.3922500000000007 + 51.873911111111113 6.3904777777777779 + 51.872875000000001 6.391030555555556 + 51.872358333333331 6.3909166666666684 + 51.872052777777782 6.3904750000000003 + 51.870691666666666 6.3897111111111116 + 51.86718888888889 6.388355555555556 + 51.865358333333333 6.3870444444444452 + 51.864561111111115 6.3868222222222224 + 51.864205555555557 6.3869388888888894 + 51.863647222222227 6.3875638888888897 + 51.861902777777779 6.3879666666666672 + 51.861783333333335 6.3889972222222227 + 51.861913888888893 6.3895416666666671 + 51.861408333333337 6.3903444444444446 + 51.861602777777776 6.3907277777777782 + 51.861383333333336 6.3914527777777783 + 51.860733333333336 6.391516666666667 + 51.860433333333333 6.3918388888888904 + 51.859188888888887 6.3953500000000014 + 51.857713888888888 6.3969055555555556 + 51.856886111111109 6.3990194444444448 + 51.856025000000002 6.4000472222222227 + 51.855466666666665 6.4013583333333344 + 51.854588888888891 6.4050666666666674 + 51.854402777777779 6.4076138888888892 + 51.853330555555559 6.4089499999999999 + 51.852663888888891 6.4089611111111111 + 51.852358333333335 6.4091750000000003 + 51.84878888888889 6.4048555555555557 + 51.848386111111111 6.4053055555555556 + 51.847363888888893 6.405186111111111 + 51.84579166666667 6.4032777777777783 + 51.844469444444449 6.4024388888888897 + 51.84319444444445 6.4025250000000007 + 51.841113888888891 6.404238888888889 + 51.84019444444445 6.4046833333333337 + 51.839608333333338 6.4054888888888897 + 51.838888888888889 6.4060638888888892 + 51.838322222222224 6.4069416666666674 + 51.835894444444449 6.408180555555556 + 51.835711111111117 6.4073861111111112 + 51.836508333333335 6.4029888888888893 + 51.833286111111114 6.4045472222222228 + 51.829561111111111 6.4066833333333344 + 51.829086111111117 6.4071805555555557 + 51.828505555555559 6.4072638888888891 + 51.828111111111113 6.4075361111111118 + 51.82725833333334 6.4018083333333333 + 51.82864444444445 6.4000500000000002 + 51.830150000000003 6.3961194444444454 + 51.830094444444448 6.3951416666666674 + 51.830744444444449 6.3940361111111113 + 51.831236111111117 6.3924666666666674 + 51.831969444444447 6.392211111111112 + 51.832322222222224 6.3917638888888897 + 51.832694444444449 6.3908527777777779 + 51.832691666666669 6.3900305555555557 + 51.833272222222227 6.3895027777777784 + 51.83368055555556 6.3880055555555559 + 51.834336111111114 6.3828861111111106 + 51.834772222222227 6.3821305555555554 + 51.834963888888893 6.3771777777777769 + 51.834580555555561 6.3728888888888884 + 51.834227777777777 6.3714111111111107 + 51.833358333333337 6.3692416666666674 + 51.833275 6.3685055555555552 + 51.835161111111113 6.3633277777777772 + 51.835413888888894 6.362966666666666 + 51.835808333333333 6.3628527777777784 + 51.83849444444445 6.3640388888888886 + 51.842675 6.3625499999999997 + 51.845827777777778 6.360205555555555 + 51.847297222222224 6.3581388888888881 + 51.847894444444449 6.3565916666666666 + 51.849344444444448 6.352119444444444 + 51.850044444444443 6.3487416666666663 + 51.850666666666669 6.3470916666666666 + 51.850999999999999 6.3433138888888889 + 51.85071388888889 6.3391888888888888 + 51.851555555555557 6.333044444444444 + 51.851580555555557 6.3267472222222221 + 51.851377777777778 6.3245638888888891 + 51.85165555555556 6.3203055555555556 + 51.85156388888889 6.3190277777777784 + 51.851091666666669 6.3173388888888891 + 51.850322222222225 6.3129055555555551 + 51.850338888888892 6.3107416666666669 + 51.849886111111111 6.308386111111111 + 51.849086111111113 6.3061999999999996 + 51.852919444444446 6.3045527777777783 + 51.853597222222227 6.303719444444444 + 51.856583333333333 6.3024638888888891 + 51.856763888888892 6.3024388888888891 + 51.856977777777779 6.3028055555555564 + 51.861986111111115 6.3006944444444439 + 51.864516666666667 6.3004444444444454 + 51.865169444444447 6.2987305555555553 + 51.865961111111112 6.2982055555555556 + 51.867158333333336 6.2991138888888889 + 51.867808333333336 6.2989555555555556 + 51.868316666666665 6.2956444444444442 + 51.869069444444442 6.294169444444444 + 51.871516666666665 6.288008333333333 + 51.872166666666665 6.2834555555555553 + 51.87307777777778 6.2821888888888893 + 51.87405833333333 6.2799527777777779 + 51.874538888888893 6.2767694444444446 + 51.874708333333331 6.2727194444444443 + 51.87446666666667 6.2710638888888894 + 51.874061111111111 6.2697750000000001 + 51.873750000000001 6.2691416666666662 + 51.869969444444443 6.2653333333333334 + 51.86826111111111 6.262291666666667 + 51.868111111111112 6.2617027777777778 + 51.868183333333334 6.2591972222222223 + 51.868844444444441 6.2531305555555559 + 51.869500000000002 6.248216666666667 + 51.869933333333336 6.2462638888888886 + 51.869616666666666 6.2443277777777784 + 51.868961111111112 6.2420111111111112 + 51.869075000000002 6.2395361111111107 + 51.869822222222226 6.236391666666667 + 51.87019166666667 6.2337388888888894 + 51.868522222222225 6.2245972222222221 + 51.868458333333336 6.2226138888888887 + 51.867619444444443 6.2150888888888893 + 51.86902222222222 6.2101805555555556 + 51.87157222222222 6.2030194444444442 + 51.874702777777777 6.1960416666666669 + 51.878280555555556 6.1896416666666667 + 51.882533333333335 6.1835527777777779 + 51.882941666666667 6.1834638888888893 + 51.883252777777777 6.183619444444445 + 51.885002777777778 6.182291666666667 + 51.885780555555556 6.1820138888888891 + 51.886852777777776 6.1859916666666672 + 51.887352777777778 6.1914305555555558 + 51.888944444444441 6.1895194444444446 + 51.88966111111111 6.1898666666666671 + 51.891208333333331 6.1913166666666672 + 51.891661111111112 6.1910805555555557 + 51.892152777777774 6.1874888888888888 + 51.893911111111109 6.1825638888888887 + 51.894166666666663 6.1827083333333333 + 51.901288888888885 6.1697722222222229 + 51.900822222222217 6.168911111111111 + 51.900944444444441 6.1679138888888891 + 51.899880555555555 6.1666833333333333 + 51.898597222222222 6.1656361111111124 + 51.901141666666668 6.1630277777777778 + 51.900941666666668 6.1622833333333338 + 51.903219444444446 6.1598694444444444 + 51.905102777777778 6.1573888888888888 + 51.90528333333333 6.1562055555555562 + 51.905011111111108 6.1560444444444444 + 51.905202777777774 6.1542888888888889 + 51.904841666666663 6.1543111111111113 + 51.904555555555554 6.1540555555555558 + 51.899858333333334 6.1305500000000004 + 51.899738888888891 6.1305944444444442 + 51.899338888888892 6.1287249999999993 + 51.898205555555556 6.1256694444444442 + 51.898713888888885 6.1242638888888887 + 51.900719444444441 6.1205027777777774 + 51.901672222222224 6.1179249999999996 + 51.897716666666668 6.1148194444444437 + 51.898963888888886 6.1123472222222217 + 51.898813888888888 6.1118027777777773 + 51.895847222222223 6.1092749999999993 + 51.894874999999999 6.1101583333333327 + 51.892472222222224 6.1034583333333332 + 51.891952777777774 6.1039861111111096 + 51.891680555555553 6.1062249999999993 + 51.892019444444443 6.110297222222222 + 51.89255277777778 6.1132166666666663 + 51.892061111111111 6.1178527777777774 + 51.891077777777774 6.1210944444444442 + 51.890547222222224 6.121513888888888 + 51.890047222222222 6.1225999999999994 + 51.890155555555552 6.124397222222222 + 51.889455555555557 6.1269083333333327 + 51.888513888888887 6.1286638888888882 + 51.888275 6.1301138888888884 + 51.887908333333336 6.1306972222222216 + 51.887416666666667 6.1309222222222219 + 51.886555555555553 6.1331305555555549 + 51.886386111111108 6.1354472222222229 + 51.885805555555557 6.1371305555555562 + 51.885027777777779 6.1378611111111114 + 51.883597222222221 6.1380555555555558 + 51.882594444444443 6.1391166666666672 + 51.881027777777781 6.1398944444444448 + 51.880336111111113 6.1407944444444436 + 51.879022222222225 6.1418416666666671 + 51.877286111111111 6.1428472222222226 + 51.876586111111109 6.1430361111111118 + 51.876252777777779 6.1436111111111114 + 51.874980555555553 6.1432972222222224 + 51.874166666666667 6.1437444444444447 + 51.873222222222225 6.1437527777777783 + 51.872069444444442 6.1446222222222229 + 51.869747222222223 6.144541666666667 + 51.869255555555554 6.1456472222222223 + 51.86900277777778 6.1469166666666668 + 51.868269444444444 6.1483888888888893 + 51.867511111111114 6.1491055555555558 + 51.867052777777779 6.1491888888888893 + 51.866458333333334 6.1500000000000004 + 51.866180555555559 6.1508222222222226 + 51.866255555555554 6.1518611111111117 + 51.865774999999999 6.1551027777777794 + 51.865425000000002 6.1562250000000001 + 51.864583333333336 6.1576694444444451 + 51.863816666666665 6.1600666666666672 + 51.862972222222226 6.1615583333333337 + 51.862216666666669 6.1647500000000006 + 51.861708333333333 6.1654750000000007 + 51.861605555555556 6.1670833333333333 + 51.861172222222223 6.1672944444444449 + 51.860750000000003 6.1671250000000004 + 51.859836111111115 6.1651250000000006 + 51.859000000000002 6.1644333333333341 + 51.857441666666666 6.1643361111111119 + 51.853680555555556 6.1636000000000006 + 51.851961111111116 6.1642527777777794 + 51.850963888888892 6.1652361111111116 + 51.850211111111115 6.1656416666666667 + 51.840722222222226 6.1665611111111112 + 51.84429166666667 6.1527611111111113 + 51.846083333333333 6.1436472222222234 + 51.846983333333334 6.1374611111111124 + 51.847438888888888 6.1324555555555564 + 51.847725000000004 6.1263944444444443 + 51.847744444444444 6.1114916666666659 + 51.848386111111111 6.1051027777777778 + 51.849047222222225 6.1010305555555551 + 51.851075000000002 6.0936805555555553 + 51.852738888888894 6.0892777777777773 + 51.854294444444449 6.0860305555555554 + 51.858474999999999 6.0786416666666661 + 51.861261111111112 6.073230555555555 + 51.865344444444446 6.0635277777777778 + 51.863300000000002 6.0623250000000004 + 51.861183333333337 6.0616416666666666 + 51.861294444444447 6.0604361111111107 + 51.857630555555559 6.0595972222222221 + 51.857366666666671 6.0540111111111106 + 51.856633333333335 6.0513472222222218 + 51.85496666666667 6.0530944444444454 + 51.852544444444447 6.0553083333333344 + 51.852372222222222 6.0552638888888888 + 51.847038888888889 6.0417750000000003 + 51.844105555555558 6.0369083333333329 + 51.842661111111113 6.035622222222222 + 51.843422222222223 6.0334361111111114 + 51.84236388888889 6.0326750000000002 + 51.84511944444445 6.029152777777778 + 51.842844444444445 6.022788888888889 + 51.841638888888895 6.0202083333333336 + 51.841669444444449 6.0182611111111113 + 51.841433333333335 6.0175527777777784 + 51.840852777777783 6.0169861111111107 + 51.838133333333339 6.0159166666666666 + 51.835100000000004 6.0100777777777781 + 51.83399166666667 6.0056611111111113 + 51.832411111111114 6.0019416666666663 + 51.831922222222225 5.9986583333333332 + 51.831297222222226 5.9967222222222221 + 51.830922222222227 5.9945250000000003 + 51.830652777777779 5.9867999999999997 + 51.83164166666667 5.9830277777777781 + 51.832411111111114 5.9782833333333336 + 51.832983333333338 5.9763388888888889 + 51.833394444444444 5.9730944444444454 + 51.833341666666669 5.9711444444444446 + 51.834358333333334 5.9681750000000013 + 51.83690555555556 5.9630166666666664 + 51.82425833333334 5.9454527777777777 + 51.824080555555561 5.9457805555555554 + 51.823536111111117 5.9450194444444451 + 51.82255277777778 5.9468111111111117 + 51.820572222222225 5.9514611111111124 + 51.816894444444451 5.9581083333333336 + 51.815469444444439 5.9557055555555554 + 51.815905555555553 5.9547722222222221 + 51.814766666666664 5.9528611111111109 + 51.816238888888883 5.9506638888888892 + 51.815436111111111 5.9495972222222226 + 51.816455555555549 5.9480805555555554 + 51.815111111111108 5.9459194444444448 + 51.814369444444445 5.9470000000000001 + 51.813841666666661 5.9465555555555554 + 51.813452777777776 5.9465333333333339 + 51.812508333333334 5.9482861111111109 + 51.812797222222223 5.9487416666666668 + 51.812438888888884 5.9493916666666671 + 51.811413888888886 5.9484805555555562 + 51.811380555555552 5.9479833333333332 + 51.810669444444443 5.9503222222222227 + 51.809952777777774 5.9567138888888893 + 51.809038888888885 5.9577749999999998 + 51.80875833333333 5.9589527777777782 + 51.807061111111111 5.9630777777777784 + 51.806005555555551 5.9650444444444446 + 51.805605555555552 5.9657611111111111 + 51.804974999999999 5.9661638888888904 + 51.804380555555554 5.9669138888888886 + 51.804538888888885 5.967336111111111 + 51.803730555555553 5.9679083333333338 + 51.801836111111108 5.9713055555555554 + 51.801352777777772 5.971744444444445 + 51.799044444444441 5.9756361111111111 + 51.798630555555555 5.9771944444444447 + 51.797658333333331 5.9790749999999999 + 51.795619444444441 5.9743944444444441 + 51.795333333333332 5.9747888888888889 + 51.795208333333335 5.9745944444444454 + 51.794277777777779 5.9767916666666672 + 51.789586111111106 5.9726277777777783 + 51.788799999999995 5.9750694444444443 + 51.788466666666665 5.9739750000000003 + 51.786055555555556 5.9745499999999998 + 51.785052777777778 5.9745527777777783 + 51.785986111111107 5.9795361111111109 + 51.785572222222221 5.9807861111111116 + 51.784177777777778 5.9817083333333336 + 51.785058333333332 5.9846777777777778 + 51.784427777777779 5.9847916666666663 + 51.782883333333331 5.9878944444444446 + 51.78373055555555 5.9897611111111111 + 51.783413888888887 5.9902222222222221 + 51.783200000000001 5.9904388888888889 + 51.778741666666669 5.983422222222222 + 51.777766666666665 5.9843333333333337 + 51.777788888888885 5.9845500000000014 + 51.775591666666664 5.9836805555555559 + 51.775369444444443 5.9840666666666671 + 51.773683333333331 5.9823416666666667 + 51.772227777777779 5.9868083333333333 + 51.769688888888886 5.9907500000000002 + 51.770247222222224 5.9920611111111111 + 51.766327777777775 5.990566666666667 + 51.760058333333333 5.9791916666666669 + 51.759708333333336 5.9782833333333336 + 51.759700000000002 5.976572222222222 + 51.759047222222222 5.9749388888888886 + 51.759258333333335 5.9740805555555561 + 51.751463888888885 5.9583333333333339 + 51.751941666666667 5.9568138888888891 + 51.748938888888887 5.9519611111111113 + 51.747933333333336 5.9533194444444444 + 51.746961111111112 5.9528138888888886 + 51.745480555555559 5.9525138888888893 + 51.742274999999999 5.9523833333333336 + 51.741555555555557 5.953130555555556 + 51.740927777777777 5.9531388888888888 + 51.739422222222224 5.954680555555556 + 51.738119444444443 5.9551472222222221 + 51.73865 5.956863888888889 + 51.738286111111115 5.9591583333333338 + 51.738783333333338 5.9611138888888888 + 51.738772222222224 5.9657833333333334 + 51.738500000000002 5.9684138888888887 + 51.739111111111114 5.9708555555555556 + 51.7393 5.9733666666666672 + 51.738744444444443 5.9791972222222221 + 51.738822222222225 5.9814722222222221 + 51.739286111111113 5.9849972222222219 + 51.738927777777782 5.9873250000000002 + 51.738594444444445 5.9926138888888891 + 51.738305555555556 5.9942000000000002 + 51.73543055555556 5.999883333333333 + 51.734591666666667 6.0022972222222224 + 51.733702777777779 6.0038111111111112 + 51.730761111111114 6.013436111111111 + 51.729038888888894 6.0174777777777777 + 51.727927777777779 6.0225055555555551 + 51.72548888888889 6.0295249999999996 + 51.723822222222225 6.0322611111111106 + 51.723233333333333 6.0321861111111108 + 51.72141666666667 6.0330027777777779 + 51.721086111111113 6.0336583333333333 + 51.721425000000004 6.0346222222222217 + 51.721225000000004 6.0350388888888888 + 51.720313888888889 6.0347444444444447 + 51.71776944444445 6.0354277777777776 + 51.718119444444447 6.0383916666666666 + 51.718425000000003 6.038388888888889 + 51.719516666666671 6.0377138888888888 + 51.719927777777777 6.0378805555555557 + 51.716908333333336 6.044944444444444 + 51.715830555555556 6.0439888888888884 + 51.714975000000003 6.0436861111111106 + 51.713336111111111 6.0420222222222222 + 51.713733333333337 6.0397999999999996 + 51.713702777777783 6.0378527777777773 + 51.712747222222227 6.0376722222222217 + 51.712858333333337 6.0355222222222222 + 51.712713888888892 6.0345444444444443 + 51.713336111111111 6.0334000000000003 + 51.713186111111114 6.0321833333333332 + 51.711866666666673 6.0284777777777778 + 51.711544444444449 6.0282166666666663 + 51.710677777777782 6.0280472222222219 + 51.710127777777778 6.026933333333333 + 51.708863888888892 6.0261388888888892 + 51.70834444444445 6.0261944444444442 + 51.707338888888891 6.0269833333333329 + 51.706788888888894 6.0271388888888886 + 51.705100000000002 6.027166666666667 + 51.704208333333334 6.0268499999999996 + 51.703233333333337 6.0278083333333337 + 51.702600000000004 6.0280944444444442 + 51.700572222222227 6.0277583333333329 + 51.699227777777772 6.0290083333333344 + 51.698505555555549 6.0305444444444447 + 51.696299999999994 6.0311694444444441 + 51.694963888888886 6.031047222222222 + 51.692230555555554 6.0317666666666669 + 51.690061111111106 6.0301999999999998 + 51.689622222222219 6.0282444444444447 + 51.687399999999997 6.0300972222222224 + 51.684008333333331 6.0323000000000002 + 51.682944444444445 6.0303694444444442 + 51.6828 6.0305416666666662 + 51.679758333333332 6.0302888888888893 + 51.67959722222222 6.0300666666666674 + 51.678938888888887 6.0302583333333333 + 51.67809722222222 6.029816666666667 + 51.676163888888887 6.0319444444444441 + 51.672761111111107 6.0366416666666662 + 51.66383611111111 6.0723805555555552 + 51.664805555555553 6.0756722222222219 + 51.66415277777778 6.0763249999999998 + 51.66341388888889 6.0784055555555554 + 51.663422222222223 6.079644444444444 + 51.661947222222224 6.0789833333333334 + 51.661591666666666 6.0795416666666666 + 51.661505555555557 6.0808416666666663 + 51.661716666666663 6.0830944444444439 + 51.661958333333331 6.0831944444444446 + 51.66244722222222 6.0842444444444439 + 51.662844444444445 6.0846749999999998 + 51.662911111111107 6.085344444444444 + 51.662538888888889 6.0865305555555551 + 51.661836111111107 6.0871972222222217 + 51.661216666666668 6.0874638888888883 + 51.660263888888885 6.0873166666666663 + 51.659849999999999 6.0878888888888882 + 51.659697222222221 6.0950361111111109 + 51.658116666666665 6.0996527777777771 + 51.660608333333329 6.1019638888888883 + 51.660502777777779 6.1028361111111114 + 51.659238888888886 6.106036111111111 + 51.658991666666665 6.1083833333333333 + 51.656533333333329 6.116883333333333 + 51.655972222222218 6.1180833333333329 + 51.654261111111111 6.116422222222222 + 51.653227777777779 6.1157666666666666 + 51.651388888888889 6.1165249999999993 + 51.650741666666669 6.117252777777777 + 51.646866666666668 6.1094138888888887 + 51.644730555555554 6.1116833333333327 + 51.641933333333334 6.1080416666666659 + 51.629805555555556 6.1027444444444443 + 51.624080555555558 6.1000111111111108 + 51.620886111111112 6.0972277777777784 + 51.622149999999998 6.0939249999999996 + 51.617550000000001 6.0943749999999994 + 51.615197222222221 6.0943500000000004 + 51.605858333333337 6.0914194444444441 + 51.593847222222223 6.117086111111111 + 51.593666666666671 6.1192833333333327 + 51.592747222222222 6.1214861111111114 + 51.58110555555556 6.1305444444444444 + 51.574150000000003 6.1408000000000014 + 51.570566666666672 6.1470333333333338 + 51.566583333333334 6.1570083333333336 + 51.538552777777774 6.1769055555555559 + 51.533477777777776 6.1886777777777784 + 51.527380555555553 6.1999305555555564 + 51.519097222222221 6.2077083333333336 + 51.513391666666664 6.2120222222222221 + 51.509786111111111 6.2130722222222223 + 51.504480555555553 6.213805555555556 + 51.502913888888891 6.2141944444444448 + 51.499302777777778 6.2137027777777778 + 51.499219444444442 6.2138222222222224 + 51.493255555555557 6.2127861111111109 + 51.491308333333336 6.2127638888888894 + 51.484341666666666 6.2185138888888893 + 51.484983333333332 6.2190305555555554 + 51.474966666666667 6.2235555555555564 + 51.470180555555558 6.2231055555555557 + 51.469469444444449 6.2228444444444442 + 51.468716666666666 6.2236750000000001 + 51.466163888888893 6.2222944444444446 + 51.461094444444448 6.2221000000000002 + 51.455347222222223 6.2200027777777782 + 51.446647222222218 6.220594444444445 + 51.446736111111107 6.2142416666666671 + 51.446227777777771 6.2139111111111109 + 51.433883333333327 6.2147666666666668 + 51.399519444444444 6.2052555555555564 + 51.400925000000001 6.2113611111111124 + 51.40026944444444 6.2266666666666666 + 51.399533333333331 6.2260333333333344 + 51.399374999999999 6.2267694444444448 + 51.396552777777778 6.2237027777777776 + 51.391602777777777 6.2176416666666672 + 51.389636111111109 6.2144250000000003 + 51.388833333333331 6.2163666666666666 + 51.387516666666663 6.2147416666666668 + 51.36033611111111 6.2263888888888888 + 51.339463888888893 6.1898805555555558 + 51.334880555555557 6.1942361111111124 + 51.334672222222224 6.1923555555555554 + 51.334944444444446 6.1909111111111113 + 51.33506944444445 6.1883027777777784 + 51.334138888888894 6.1830972222222229 + 51.333872222222226 6.1802222222222234 + 51.333572222222223 6.1789027777777781 + 51.333463888888893 6.1789777777777779 + 51.333227777777779 6.1782388888888891 + 51.333411111111111 6.1780861111111118 + 51.333058333333334 6.1741333333333337 + 51.333208333333339 6.1713638888888891 + 51.332988888888892 6.1685583333333334 + 51.331905555555558 6.1681972222222221 + 51.331455555555557 6.168252777777778 + 51.330111111111115 6.1691305555555562 + 51.329375000000006 6.1693777777777781 + 51.327516666666668 6.1670805555555557 + 51.32555277777778 6.1641861111111114 + 51.323022222222228 6.1620888888888894 + 51.321602777777784 6.1616 + 51.319691666666671 6.159588888888889 + 51.315644444444445 6.1594194444444446 + 51.312419444444444 6.1555305555555559 + 51.311116666666663 6.154238888888889 + 51.30960833333333 6.1541944444444452 + 51.307449999999996 6.1538250000000003 + 51.298116666666665 6.145144444444445 + 51.285702777777779 6.1290138888888883 + 51.277552777777778 6.1247583333333333 + 51.274730555555557 6.1244999999999994 + 51.24762777777778 6.0856166666666667 + 51.242555555555555 6.0726555555555564 + 51.227116666666667 6.0835472222222222 + 51.222669444444449 6.0860249999999994 + 51.222041666666669 6.0835944444444454 + 51.222447222222222 6.0809638888888884 + 51.222436111111115 6.0732583333333334 + 51.222086111111111 6.0706944444444444 + 51.220550000000003 6.0679888888888884 + 51.213352777777779 6.0684666666666667 + 51.213213888888895 6.0694944444444454 + 51.18279444444444 6.073144444444444 + 51.177194444444439 6.0785138888888888 + 51.171633333333332 6.0821888888888891 + 51.170966666666665 6.0878416666666659 + 51.170766666666665 6.0880833333333326 + 51.170730555555551 6.0888666666666662 + 51.170963888888885 6.0892277777777783 + 51.170561111111105 6.0889333333333333 + 51.17059444444444 6.0895861111111111 + 51.170400000000001 6.0896694444444446 + 51.170499999999997 6.090866666666666 + 51.170816666666667 6.0909416666666667 + 51.170780555555552 6.0914388888888888 + 51.17059444444444 6.0914111111111104 + 51.170527777777778 6.0916583333333332 + 51.17068611111111 6.0922999999999998 + 51.17059444444444 6.0920027777777772 + 51.170413888888888 6.0921166666666666 + 51.170444444444442 6.0926527777777784 + 51.170586111111106 6.0925777777777776 + 51.170716666666664 6.0929055555555554 + 51.170516666666664 6.0930972222222222 + 51.17039444444444 6.0938138888888886 + 51.170605555555554 6.0942277777777774 + 51.17068888888889 6.0940722222222217 + 51.170786111111106 6.0941833333333326 + 51.170588888888886 6.0946472222222221 + 51.170813888888887 6.0947583333333331 + 51.170772222222219 6.0950916666666668 + 51.170927777777777 6.0950388888888893 + 51.171091666666662 6.095275 + 51.170924999999997 6.0956222222222216 + 51.17111388888889 6.09565 + 51.17113333333333 6.0959972222222216 + 51.170924999999997 6.0963305555555554 + 51.17071111111111 6.0962333333333332 + 51.17079722222222 6.0971388888888889 + 51.170588888888886 6.097088888888889 + 51.170511111111111 6.0978499999999993 + 51.169986111111108 6.0988027777777774 + 51.169880555555551 6.1001111111111106 + 51.170122222222219 6.1006416666666663 + 51.170894444444443 6.1005833333333328 + 51.170924999999997 6.1009805555555552 + 51.171288888888888 6.1015222222222221 + 51.171405555555552 6.1014388888888886 + 51.171680555555554 6.1020833333333329 + 51.171588888888884 6.102605555555555 + 51.171816666666665 6.1027083333333332 + 51.171688888888887 6.1028111111111114 + 51.171841666666666 6.1030138888888894 + 51.171611111111112 6.1033083333333327 + 51.171799999999998 6.1033805555555549 + 51.172066666666666 6.1041888888888884 + 51.171955555555556 6.1047666666666673 + 51.172194444444443 6.1056472222222222 + 51.172122222222221 6.1060833333333333 + 51.172288888888886 6.1061722222222219 + 51.172355555555555 6.1067388888888887 + 51.172541666666667 6.1067666666666662 + 51.172580555555555 6.1073972222222217 + 51.172899999999998 6.1075499999999998 + 51.172927777777772 6.1079166666666662 + 51.173202777777774 6.1080138888888884 + 51.173222222222222 6.1090888888888886 + 51.173513888888884 6.109602777777777 + 51.173313888888885 6.1099527777777771 + 51.173649999999995 6.110377777777777 + 51.173830555555554 6.1112888888888888 + 51.174052777777774 6.1110055555555549 + 51.17424444444444 6.1116805555555551 + 51.174611111111112 6.1116694444444439 + 51.174949999999995 6.1127388888888889 + 51.175252777777779 6.1127249999999993 + 51.175436111111111 6.113347222222222 + 51.175916666666666 6.1137499999999996 + 51.175816666666663 6.1139277777777776 + 51.177094444444442 6.1148638888888884 + 51.177405555555552 6.1153055555555564 + 51.177919444444441 6.1154333333333328 + 51.178752777777774 6.1171833333333332 + 51.17915 6.1175555555555547 + 51.181433333333331 6.1227527777777784 + 51.182697222222217 6.1275249999999986 + 51.183741666666663 6.1296249999999999 + 51.18698333333333 6.1403861111111118 + 51.189811111111105 6.1499000000000006 + 51.192838888888886 6.1611027777777778 + 51.194413888888889 6.1651722222222229 + 51.186358333333331 6.1807250000000007 + 51.173338888888885 6.1388027777777783 + 51.158463888888889 6.1754222222222221 + 51.157258333333331 6.1736972222222226 + 51.155236111111108 6.1701138888888893 + 51.154244444444444 6.1672750000000001 + 51.152891666666662 6.1644611111111116 + 51.152672222222222 6.1628500000000006 + 51.148697222222225 6.1633388888888891 + 51.149144444444445 6.1613111111111118 + 51.149408333333334 6.160855555555556 + 51.149366666666666 6.1598805555555556 + 51.149172222222219 6.1598027777777782 + 51.149133333333332 6.1589833333333344 + 51.148899999999998 6.1587194444444444 + 51.149080555555557 6.1580777777777778 + 51.149000000000001 6.1573972222222224 + 51.148808333333335 6.1574666666666671 + 51.14852777777778 6.1572416666666667 + 51.148783333333334 6.1569416666666674 + 51.148627777777776 6.1563333333333334 + 51.148375000000001 6.1563083333333344 + 51.148383333333335 6.1561194444444451 + 51.148608333333335 6.1561027777777779 + 51.148377777777775 6.1556194444444454 + 51.148474999999998 6.1552805555555556 + 51.148333333333333 6.1551444444444448 + 51.148222222222223 6.1554305555555562 + 51.148200000000003 6.1548666666666669 + 51.147986111111109 6.1547750000000008 + 51.148313888888886 6.1545027777777781 + 51.148022222222224 6.1541805555555564 + 51.148244444444444 6.1540611111111119 + 51.148202777777776 6.1532972222222222 + 51.148355555555554 6.1531611111111113 + 51.148188888888889 6.1525500000000006 + 51.147999999999996 6.1525916666666669 + 51.148002777777776 6.1520305555555561 + 51.148297222222219 6.1505972222222223 + 51.148647222222223 6.1506611111111118 + 51.148291666666665 6.1498583333333334 + 51.14875 6.1488444444444452 + 51.14843611111111 6.1486444444444448 + 51.148652777777777 6.1483638888888894 + 51.148636111111109 6.1476361111111117 + 51.148400000000002 6.1462611111111114 + 51.148158333333335 6.1462527777777778 + 51.148077777777779 6.1458027777777779 + 51.147986111111109 6.1460305555555559 + 51.14781111111111 6.1457722222222229 + 51.148002777777776 6.1450750000000003 + 51.147644444444445 6.145494444444445 + 51.14716111111111 6.1450000000000014 + 51.14738333333333 6.1449138888888903 + 51.147024999999999 6.1444055555555561 + 51.147263888888887 6.1440944444444447 + 51.147008333333332 6.1438666666666668 + 51.146213888888887 6.1395138888888896 + 51.146374999999999 6.1395166666666672 + 51.146366666666665 6.1380194444444447 + 51.14577222222222 6.1364888888888904 + 51.145536111111113 6.1364722222222223 + 51.145688888888891 6.1360666666666672 + 51.145494444444445 6.1359222222222227 + 51.145352777777781 6.1349555555555559 + 51.145077777777779 6.1344916666666673 + 51.145302777777779 6.1344861111111113 + 51.145352777777781 6.1338277777777783 + 51.145055555555558 6.133688888888889 + 51.145269444444445 6.1327166666666661 + 51.145119444444447 6.1327444444444437 + 51.144958333333335 6.1323833333333333 + 51.14500833333333 6.1321944444444441 + 51.145191666666669 6.1322277777777776 + 51.145066666666665 6.1319416666666662 + 51.145208333333336 6.1315972222222221 + 51.145002777777776 6.131352777777777 + 51.145200000000003 6.1308499999999997 + 51.144999999999996 6.1300333333333326 + 51.144747222222222 6.1299277777777776 + 51.144972222222222 6.1296972222222221 + 51.14480833333333 6.1281888888888894 + 51.144966666666669 6.128136111111111 + 51.145086111111112 6.1275138888888883 + 51.144686111111113 6.126894444444444 + 51.144769444444442 6.1264555555555553 + 51.145055555555558 6.1263722222222219 + 51.145099999999999 6.1257722222222224 + 51.144877777777779 6.1256388888888882 + 51.144880555555552 6.1259583333333332 + 51.144672222222219 6.126033333333333 + 51.144736111111108 6.1255694444444444 + 51.144411111111111 6.1254638888888886 + 51.144277777777781 6.1251083333333334 + 51.144558333333336 6.1244027777777772 + 51.144372222222223 6.1244055555555548 + 51.144311111111108 6.1240083333333333 + 51.143758333333331 6.1240944444444443 + 51.14371388888889 6.1232694444444444 + 51.143277777777776 6.1233111111111107 + 51.143097222222224 6.1222166666666666 + 51.142911111111111 6.122405555555555 + 51.142841666666669 6.1219833333333327 + 51.142666666666663 6.1220583333333334 + 51.142800000000001 6.1213305555555548 + 51.142555555555553 6.1214555555555554 + 51.142494444444445 6.1212361111111111 + 51.142411111111109 6.1214222222222219 + 51.142216666666663 6.1210083333333332 + 51.141444444444446 6.1214694444444442 + 51.14096111111111 6.1212944444444437 + 51.140605555555553 6.1201722222222221 + 51.140677777777775 6.1198611111111108 + 51.139994444444447 6.1183444444444444 + 51.140225000000001 6.1178722222222222 + 51.140005555555554 6.1173972222222224 + 51.139633333333336 6.1173916666666663 + 51.139647222222223 6.1169527777777777 + 51.139141666666667 6.116422222222222 + 51.139336111111113 6.1159972222222221 + 51.138986111111109 6.1152638888888884 + 51.13903611111111 6.1138666666666666 + 51.138511111111107 6.1131777777777776 + 51.138463888888886 6.111963888888889 + 51.137608333333333 6.1093888888888888 + 51.137450000000001 6.1061138888888884 + 51.137019444444441 6.1054138888888883 + 51.136761111111113 6.1039166666666667 + 51.136261111111111 6.1034611111111108 + 51.136444444444443 6.1029194444444439 + 51.136344444444447 6.1022416666666661 + 51.136744444444446 6.1020416666666666 + 51.136447222222223 6.1009166666666674 + 51.13623333333333 6.1007749999999996 + 51.136297222222218 6.100280555555555 + 51.13612222222222 6.1003888888888884 + 51.136072222222225 6.0998388888888888 + 51.135730555555554 6.0997249999999994 + 51.135816666666663 6.099444444444444 + 51.134763888888891 6.096425 + 51.134741666666663 6.0926944444444437 + 51.135047222222219 6.0919944444444454 + 51.134791666666665 6.0916861111111107 + 51.133011111111109 6.091069444444444 + 51.132119444444442 6.0901611111111107 + 51.131252777777782 6.0898249999999994 + 51.130916666666664 6.0893111111111109 + 51.130163888888887 6.0891833333333327 + 51.129302777777781 6.0871027777777771 + 51.129019444444445 6.0874277777777772 + 51.128599999999999 6.0887194444444441 + 51.127855555555556 6.0886638888888882 + 51.127450000000003 6.087736111111111 + 51.127541666666666 6.0865222222222224 + 51.126019444444445 6.0844250000000004 + 51.125655555555554 6.0864472222222217 + 51.124597222222221 6.0869916666666661 + 51.123891666666665 6.0834999999999999 + 51.124044444444444 6.0832111111111109 + 51.124980555555553 6.0825555555555564 + 51.126011111111112 6.0809138888888894 + 51.124547222222226 6.0799861111111113 + 51.122141666666664 6.0805499999999997 + 51.120941666666667 6.0756972222222219 + 51.120649999999998 6.0756249999999996 + 51.119722222222222 6.0761972222222216 + 51.119211111111113 6.0759611111111109 + 51.118836111111115 6.0735222222222216 + 51.118566666666666 6.0729694444444444 + 51.118341666666666 6.0729666666666668 + 51.118247222222223 6.0720138888888888 + 51.117955555555554 6.0713694444444446 + 51.118155555555553 6.070666666666666 + 51.11803611111111 6.0672888888888883 + 51.116855555555553 6.0623972222222218 + 51.115927777777777 6.0602916666666662 + 51.113819444444445 6.0577944444444443 + 51.110741666666669 6.0552361111111113 + 51.110263888888888 6.0563750000000001 + 51.109549999999999 6.0568305555555551 + 51.10628611111111 6.0525944444444439 + 51.101119444444443 6.0444000000000004 + 51.101316666666669 6.0433888888888889 + 51.100902777777776 6.0419499999999999 + 51.098375000000004 6.0392583333333336 + 51.096597222222222 6.0366888888888894 + 51.095886111111113 6.03505 + 51.095569444444443 6.0337916666666667 + 51.094608333333333 6.0295611111111107 + 51.094241666666669 6.025894444444444 + 51.093377777777782 6.0239277777777778 + 51.093261111111111 6.022475 + 51.092841666666672 6.0206888888888894 + 51.094580555555559 6.0175916666666662 + 51.092358333333337 6.0157055555555559 + 51.091447222222222 6.0140777777777776 + 51.090949999999999 6.012666666666667 + 51.091191666666667 6.0109083333333331 + 51.090850000000003 6.0095305555555552 + 51.089619444444445 6.0083083333333329 + 51.086797222222224 6.003825 + 51.084252777777778 5.997786111111111 + 51.082063888888889 5.9947027777777784 + 51.079847222222227 5.9921750000000014 + 51.074619444444451 5.9884611111111123 + 51.073586111111112 5.9849750000000004 + 51.073177777777779 5.9817638888888887 + 51.073055555555555 5.9813916666666671 + 51.07253333333334 5.9809277777777776 + 51.072319444444446 5.980291666666667 + 51.071900000000007 5.9801833333333336 + 51.071344444444449 5.9795805555555557 + 51.069477777777784 5.9817277777777784 + 51.067702777777782 5.9786611111111112 + 51.066886111111117 5.9787444444444446 + 51.066438888888889 5.978472222222222 + 51.064741666666663 5.9765333333333333 + 51.064541666666663 5.9759333333333338 + 51.063158333333334 5.9747833333333338 + 51.062908333333333 5.9731611111111116 + 51.061877777777774 5.9718777777777783 + 51.061633333333333 5.970969444444445 + 51.06070555555555 5.9699777777777783 + 51.060516666666665 5.9699944444444446 + 51.060236111111109 5.9706000000000001 + 51.05971944444444 5.9707833333333333 + 51.05801944444444 5.9707777777777782 + 51.056916666666666 5.9701277777777779 + 51.055563888888884 5.9681138888888894 + 51.054927777777777 5.9696083333333334 + 51.054600000000001 5.9701305555555564 + 51.054186111111107 5.9703111111111111 + 51.052280555555555 5.9693861111111124 + 51.051072222222217 5.9682277777777779 + 51.049816666666665 5.9684777777777782 + 51.049144444444444 5.969297222222222 + 51.047927777777772 5.9684388888888886 + 51.046772222222224 5.9691972222222223 + 51.046283333333328 5.968552777777778 + 51.046366666666664 5.9682805555555554 + 51.045883333333329 5.9680138888888887 + 51.044761111111107 5.9678361111111116 + 51.044138888888888 5.9668999999999999 + 51.044058333333332 5.965786111111111 + 51.043586111111111 5.9649694444444448 + 51.043799999999997 5.964494444444445 + 51.043686111111107 5.9638388888888887 + 51.04196944444444 5.9616833333333332 + 51.042008333333328 5.960491666666667 + 51.04098333333333 5.9578305555555557 + 51.039955555555551 5.9582361111111108 + 51.038238888888884 5.9594666666666667 + 51.036119444444445 5.9581111111111111 + 51.034727777777775 5.9577777777777783 + 51.035083333333333 5.9563138888888894 + 51.034922222222221 5.9562111111111111 + 51.035033333333331 5.9557000000000002 + 51.035902777777778 5.9550611111111111 + 51.036530555555551 5.9540055555555558 + 51.036969444444445 5.9498000000000006 + 51.036622222222221 5.9464444444444444 + 51.037030555555553 5.9465194444444442 + 51.036588888888886 5.9430972222222227 + 51.036094444444444 5.9430000000000014 + 51.035608333333329 5.9415777777777778 + 51.035652777777777 5.9408361111111114 + 51.03511944444444 5.9381277777777779 + 51.036299999999997 5.9379027777777784 + 51.038297222222219 5.9364111111111111 + 51.041230555555551 5.9346055555555557 + 51.044105555555554 5.9315055555555558 + 51.048233333333329 5.9263166666666667 + 51.062477777777772 5.9196777777777783 + 51.063952777777772 5.9187333333333338 + 51.066883333333337 5.9132055555555558 + 51.06184722222222 5.9056444444444454 + 51.057141666666666 5.8963722222222223 + 51.053236111111111 5.8922944444444436 + 51.053127777777775 5.8920000000000003 + 51.052180555555552 5.8871972222222224 + 51.052083333333329 5.8820499999999996 + 51.051474999999996 5.8751861111111117 + 51.05168611111111 5.8686888888888893 + 51.051572222222219 5.8667361111111118 + 51.051238888888889 5.8669166666666666 + 51.051105555555552 5.8663138888888886 + 51.046697222222221 5.8670833333333334 + 51.046180555555551 5.8673750000000009 + 51.041624999999996 5.872238888888889 + 51.039122222222218 5.8746277777777776 + 51.03811944444444 5.8774111111111118 + 51.03744722222222 5.8780833333333344 + 51.031569444444443 5.8768750000000001 + 51.029216666666663 5.8745916666666673 + 51.02676944444444 5.8753833333333336 + 51.024616666666667 5.8766555555555557 + 51.023880555555557 5.8766527777777782 + 51.020619444444442 5.8789138888888894 + 51.019874999999999 5.8789805555555557 + 51.018661111111108 5.8785333333333334 + 51.017838888888889 5.8788722222222223 + 51.01338611111111 5.8842611111111109 + 51.013816666666663 5.8854472222222221 + 51.013475 5.8883472222222224 + 51.012300000000003 5.8927138888888884 + 51.011019444444443 5.8956388888888887 + 51.004533333333335 5.8954749999999994 + 51.002172222222221 5.9055166666666672 + 50.996138888888893 5.9043527777777776 + 50.987205555555555 5.9037361111111117 + 50.984347222222226 5.8994972222222222 + 50.981352777777779 5.8956694444444437 + 50.981097222222225 5.8938027777777773 + 50.980308333333333 5.8925944444444438 + 50.979555555555557 5.8937833333333334 + 50.977308333333333 5.8956666666666662 + 50.97710277777778 5.8961833333333331 + 50.976486111111114 5.896805555555555 + 50.974866666666671 5.8970861111111104 + 50.974583333333335 5.9024277777777794 + 50.974552777777781 5.9046944444444449 + 50.974722222222226 5.9056000000000006 + 50.976411111111112 5.9117277777777781 + 50.977825000000003 5.9155888888888892 + 50.978086111111111 5.9171722222222227 + 50.977747222222227 5.9185527777777782 + 50.979547222222223 5.9229916666666673 + 50.982286111111115 5.9276499999999999 + 50.985355555555557 5.9338861111111116 + 50.987208333333335 5.9501333333333344 + 50.988419444444446 5.9551833333333333 + 50.98500555555556 5.9573916666666671 + 50.983158333333336 5.9608805555555557 + 50.983058333333332 5.9607861111111111 + 50.980941666666666 5.965011111111111 + 50.979772222222223 5.9663250000000003 + 50.979397222222225 5.9675750000000001 + 50.979427777777779 5.9685083333333333 + 50.980555555555554 5.9739361111111116 + 50.982916666666668 5.9795750000000014 + 50.983219444444444 5.9813583333333344 + 50.983069444444446 5.9822416666666669 + 50.98211666666667 5.9842222222222219 + 50.983402777777776 6.0173638888888892 + 50.983680555555559 6.0172249999999998 + 50.983819444444443 6.0186999999999999 + 50.983272222222226 6.0229305555555559 + 50.983272222222226 6.0265111111111107 + 50.981641666666668 6.0268944444444443 + 50.981311111111111 6.0268027777777773 + 50.974022222222224 6.0226444444444454 + 50.971005555555557 6.0211638888888892 + 50.96895 6.0194555555555551 + 50.965275000000005 6.0173083333333333 + 50.962366666666668 6.0152083333333337 + 50.9604 6.0129999999999999 + 50.960033333333335 6.0106861111111112 + 50.959486111111111 6.0090805555555553 + 50.958058333333334 6.0066388888888893 + 50.956777777777781 6.0051972222222219 + 50.954302777777784 6.0118 + 50.952644444444445 6.0168527777777774 + 50.94788333333333 6.015077777777778 + 50.934702777777773 6.0182027777777778 + 50.930863888888886 6.0385888888888886 + 50.930852777777773 6.0397916666666669 + 50.929341666666666 6.0444138888888892 + 50.928958333333334 6.0449999999999999 + 50.928080555555553 6.0455833333333331 + 50.928430555555551 6.0471944444444441 + 50.929386111111107 6.0491472222222233 + 50.92990555555555 6.050872222222222 + 50.927155555555551 6.0561611111111109 + 50.922249999999998 6.0540222222222217 + 50.921238888888887 6.0618083333333344 + 50.922036111111112 6.0629666666666662 + 50.921013888888886 6.0657666666666668 + 50.920655555555555 6.0681833333333328 + 50.923133333333332 6.0717749999999997 + 50.922586111111109 6.0774638888888894 + 50.92153888888889 6.0821333333333332 + 50.92093333333333 6.0838388888888888 + 50.919372222222222 6.0868305555555553 + 50.918524999999995 6.0894388888888882 + 50.919572222222222 6.0901666666666667 + 50.921230555555553 6.0937277777777776 + 50.920713888888884 6.0941638888888887 + 50.920313888888884 6.0941722222222223 + 50.919074999999999 6.0934722222222222 + 50.917436111111108 6.0920916666666667 + 50.916230555555558 6.0893305555555557 + 50.914099999999998 6.0868361111111096 + 50.913002777777777 6.0867722222222218 + 50.912277777777774 6.0864361111111114 + 50.91011944444444 6.0824083333333334 + 50.909174999999998 6.0813777777777771 + 50.90754444444444 6.0804638888888887 + 50.905591666666666 6.0797777777777773 + 50.905155555555552 6.0797527777777773 + 50.904575000000001 6.08005 + 50.902913888888889 6.0798305555555556 + 50.899172222222219 6.0773250000000001 + 50.896966666666664 6.0773166666666674 + 50.896444444444441 6.0767694444444436 + 50.895258333333331 6.0764444444444443 + 50.894630555555558 6.0765111111111114 + 50.894555555555556 6.0761249999999993 + 50.894255555555553 6.0762444444444439 + 50.894075000000001 6.0758000000000001 + 50.893599999999999 6.0758333333333328 + 50.892844444444442 6.0752527777777772 + 50.89203333333333 6.0762527777777784 + 50.891536111111108 6.076138888888889 + 50.891138888888889 6.0754083333333329 + 50.890455555555555 6.0753972222222217 + 50.889705555555558 6.0762499999999999 + 50.888977777777775 6.0764333333333331 + 50.887758333333331 6.0771611111111108 + 50.887538888888891 6.0776805555555553 + 50.887986111111111 6.0780694444444441 + 50.887741666666663 6.0785388888888887 + 50.887027777777774 6.0788000000000002 + 50.886724999999998 6.0791833333333329 + 50.886272222222225 6.0791722222222218 + 50.886116666666666 6.0794666666666668 + 50.885172222222224 6.0782166666666662 + 50.884930555555556 6.0786055555555549 + 50.884505555555556 6.078611111111111 + 50.884299999999996 6.0788361111111104 + 50.884272222222222 6.0795916666666674 + 50.883958333333332 6.0800083333333328 + 50.883483333333331 6.079933333333333 + 50.88336944444444 6.0792222222222216 + 50.882647222222225 6.0793083333333344 + 50.88239166666667 6.0798777777777779 + 50.882544444444441 6.0801749999999997 + 50.883030555555557 6.0804027777777776 + 50.882958333333335 6.0810111111111107 + 50.881374999999998 6.0826638888888889 + 50.881108333333337 6.0839138888888886 + 50.880669444444443 6.0848111111111107 + 50.880136111111113 6.0850166666666663 + 50.87981666666667 6.0863749999999994 + 50.879147222222223 6.0868944444444439 + 50.87853888888889 6.0872166666666674 + 50.877952777777779 6.0869444444444438 + 50.87638611111111 6.0850388888888887 + 50.875158333333331 6.0863361111111107 + 50.873413888888891 6.0872916666666663 + 50.87242777777778 6.0881027777777774 + 50.871477777777777 6.0861416666666663 + 50.870963888888888 6.086580555555555 + 50.870447222222225 6.0867222222222219 + 50.869330555555557 6.0865416666666663 + 50.864936111111113 6.0834666666666664 + 50.864550000000001 6.0810527777777779 + 50.862563888888893 6.0810416666666667 + 50.861177777777776 6.0778277777777774 + 50.860580555555558 6.0772388888888891 + 50.846538888888894 6.0741722222222219 + 50.850252777777776 6.0631249999999994 + 50.850200000000001 6.0625472222222223 + 50.850430555555555 6.062094444444444 + 50.850538888888892 6.0609416666666656 + 50.85091388888889 6.0601194444444442 + 50.851077777777782 6.0567388888888889 + 50.851286111111115 6.0568027777777784 + 50.851311111111116 6.056597222222222 + 50.851622222222225 6.0568944444444446 + 50.851869444444446 6.0567500000000001 + 50.852016666666671 6.0572222222222223 + 50.852994444444448 6.0569388888888884 + 50.854280555555555 6.0571472222222233 + 50.854463888888887 6.0570111111111107 + 50.854397222222225 6.0566166666666668 + 50.854952777777783 6.0566499999999994 + 50.855450000000005 6.0570944444444441 + 50.856033333333336 6.0569916666666668 + 50.857130555555557 6.0565083333333334 + 50.857236111111114 6.0551861111111114 + 50.856938888888891 6.0540194444444442 + 50.855533333333334 6.0522583333333344 + 50.85530277777778 6.0507111111111112 + 50.854894444444447 6.0502888888888888 + 50.854186111111112 6.0501361111111107 + 50.853544444444445 6.0475500000000002 + 50.852844444444443 6.0464305555555553 + 50.852605555555556 6.0451694444444444 + 50.852708333333332 6.0445222222222217 + 50.852497222222226 6.0439166666666662 + 50.85230277777778 6.0440444444444443 + 50.851916666666668 6.0438055555555552 + 50.851750000000003 6.0428555555555556 + 50.851197222222225 6.0421527777777779 + 50.851127777777776 6.0401055555555558 + 50.850858333333335 6.0394805555555564 + 50.851002777777779 6.0376361111111114 + 50.850505555555557 6.0361055555555554 + 50.850383333333333 6.0335722222222223 + 50.849411111111117 6.0316444444444448 + 50.849311111111113 6.0317305555555558 + 50.847558333333339 6.0276861111111106 + 50.847200000000001 6.0260527777777781 + 50.847744444444444 6.0256222222222222 + 50.84641666666667 6.0222361111111109 + 50.846261111111112 6.018933333333333 + 50.838794444444446 6.0159305555555553 + 50.83732777777778 6.0184333333333333 + 50.833886111111113 6.0163083333333329 + 50.829666666666668 6.018766666666667 + 50.827805555555557 6.025266666666667 + 50.826616666666673 6.0227138888888891 + 50.825102777777779 6.0239888888888888 + 50.821597222222223 6.0247000000000002 + 50.821455555555559 6.0251361111111112 + 50.820847222222227 6.0257666666666667 + 50.820369444444445 6.0262305555555553 + 50.819955555555559 6.0263083333333336 + 50.819183333333335 6.025641666666667 + 50.818402777777784 6.0237222222222222 + 50.818263888888893 6.0237666666666669 + 50.816805555555561 6.0221083333333336 + 50.815925 6.0244888888888886 + 50.81464444444444 6.0235250000000002 + 50.814030555555554 6.0249611111111108 + 50.809483333333333 6.0160916666666671 + 50.808561111111111 6.0148055555555553 + 50.806769444444441 6.0132166666666667 + 50.803980555555555 6.0100749999999996 + 50.802763888888883 6.0076472222222224 + 50.801430555555555 6.0036333333333332 + 50.80426111111111 5.9988472222222224 + 50.805883333333334 5.9950833333333344 + 50.808188888888886 5.9911805555555553 + 50.810619444444441 5.9855333333333336 + 50.810252777777777 5.9844361111111111 + 50.80865 5.9813194444444449 + 50.808513888888889 5.9814472222222221 + 50.807277777777777 5.9802555555555559 + 50.805794444444444 5.9802 + 50.804672222222223 5.9786999999999999 + 50.805063888888888 5.9779 + 50.803480555555552 5.9768222222222223 + 50.802402777777772 5.9757750000000014 + 50.799930555555555 5.9754083333333332 + 50.798455555555556 5.9750777777777779 + 50.79806111111111 5.9748250000000001 + 50.797119444444441 5.976922222222222 + 50.796680555555554 5.9771888888888887 + 50.796922222222221 5.9778500000000001 + 50.796519444444442 5.9783499999999998 + 50.796347222222224 5.9791555555555558 + 50.796005555555553 5.9790944444444447 + 50.795966666666665 5.9794083333333337 + 50.795833333333334 5.9792361111111116 + 50.795858333333328 5.9795222222222222 + 50.79559722222222 5.9796611111111124 + 50.795469444444443 5.980058333333333 + 50.795138888888886 5.980175 + 50.795016666666662 5.9814277777777782 + 50.795224999999995 5.9816916666666664 + 50.795013888888889 5.9818833333333332 + 50.795227777777775 5.9821138888888887 + 50.795222222222222 5.9827277777777779 + 50.794894444444445 5.9831500000000002 + 50.794758333333334 5.9840777777777783 + 50.794983333333334 5.9844833333333334 + 50.794736111111106 5.9846500000000002 + 50.794786111111108 5.9851027777777777 + 50.794563888888888 5.9849944444444443 + 50.794555555555554 5.9851888888888887 + 50.794252777777778 5.9852944444444454 + 50.79443055555555 5.985555555555556 + 50.794244444444445 5.9855722222222223 + 50.794258333333332 5.9858305555555553 + 50.793927777777775 5.9856444444444454 + 50.793830555555552 5.9859555555555559 + 50.79376388888889 5.9867638888888894 + 50.794083333333333 5.9874749999999999 + 50.794077777777773 5.9882027777777784 + 50.790500000000002 5.9946416666666664 + 50.790052777777774 5.9959305555555558 + 50.787427777777779 5.9958722222222223 + 50.787038888888887 5.9969638888888888 + 50.786769444444445 5.997061111111111 + 50.786566666666666 5.9974583333333333 + 50.786963888888884 5.9984638888888888 + 50.786869444444442 5.9987055555555564 + 50.786375 5.9994694444444443 + 50.786136111111112 5.9994500000000004 + 50.785786111111108 5.9998750000000003 + 50.785550000000001 5.9998416666666667 + 50.785591666666662 6.0001611111111108 + 50.784724999999995 6.0013694444444443 + 50.784638888888885 6.0018583333333337 + 50.78426944444444 6.002127777777778 + 50.784194444444445 6.0030388888888888 + 50.783380555555553 6.0054638888888894 + 50.782299999999999 6.0065833333333334 + 50.782186111111109 6.0064527777777776 + 50.781880555555553 6.0066305555555557 + 50.781938888888888 6.0070499999999996 + 50.781580555555557 6.0073916666666669 + 50.780924999999996 6.0095749999999999 + 50.78050833333333 6.0098861111111113 + 50.780427777777774 6.0105472222222218 + 50.780186111111114 6.0106083333333338 + 50.780250000000002 6.0120583333333331 + 50.779891666666664 6.0130861111111109 + 50.779494444444445 6.0134249999999998 + 50.779513888888886 6.0143944444444442 + 50.778847222222218 6.0156333333333336 + 50.778633333333332 6.0171611111111112 + 50.778205555555552 6.0177166666666668 + 50.777986111111112 6.0177083333333332 + 50.777683333333336 6.0189250000000003 + 50.777413888888887 6.0191055555555559 + 50.777105555555558 6.0201916666666664 + 50.776874999999997 6.0201861111111112 + 50.776827777777775 6.0205638888888888 + 50.776505555555552 6.0202999999999998 + 50.77598888888889 6.022211111111111 + 50.776049999999998 6.0240194444444448 + 50.775541666666669 6.0251055555555553 + 50.775533333333335 6.0261083333333332 + 50.775230555555552 6.0263083333333336 + 50.775141666666663 6.0266388888888889 + 50.774852777777774 6.0267111111111111 + 50.774763888888891 6.0270111111111113 + 50.774211111111107 6.0271805555555558 + 50.774147222222219 6.0276472222222219 + 50.773449999999997 6.0278083333333337 + 50.772647222222218 6.0265083333333331 + 50.76936111111111 6.0235472222222217 + 50.768594444444446 6.0230972222222219 + 50.768499999999996 6.0227166666666667 + 50.766469444444446 6.0216472222222226 + 50.765319444444444 6.0203833333333332 + 50.764566666666667 6.0191861111111109 + 50.763358333333336 6.0183611111111111 + 50.758741666666666 6.0195333333333334 + 50.754288888888887 6.0210083333333344 + + + + + + + + + + + 150ea2a6-3f77-47dc-a583-b250643a46fb + + + + + 2026-10-29T00:00:00Z + + + SNAPSHOT + + + 2020-01-02T00:00:00Z + + + + RAS + EDGGDLGMKB + DLG-ATS + MASKIRCHEN B AREA + + + + + + + + 195 + STD + 95 + STD + + + + + + + + + + + + + + 50.921666667000 6.058611111000 + 51.087500000000 6.005000000000 + + + + + + + + + + + + + + + + + + + UTC + + + ANY + ANY + 00:00 + + + + 00:00 + + + + NO + NO + + + + ACTIVE + + + + + activation + DESCRIPTION + + + + H24 + + + + + + + + REMARK + + + + + For details see AIP Belgium. + + + + + + + + DESCRIPTION + + + + + Within Langen FIR. + + + + + + + + + + + + 6ce57539-6c6c-4375-9acb-4b4e581ba2bc + + + + + 2026-10-29T00:00:00Z + + + SNAPSHOT + + + 2024-03-21T00:00:00Z + + + + CLASS + EDDBCLCX + + BERLIN X + + + + + + C + + + + + + + 100 + STD + 1500 + MSL + + + + + + + + + + + + + 52.499166667000 13.740833333000 + 52.525845972000 13.855054222000 + + + 52.525845972 13.855054222 52.523920587 13.857393463 + + + 52.360833333 13.495833333 + 16.5 + 53.424344062999999 + 87.996035649000007 + + + 52.369585962 13.944211818 52.367190194 13.944307389 + + + 52.367190194000 13.944307389000 + 52.342500000000 13.838888889000 + 52.499166667000 13.740833333000 + + + + + + + + + + + + + + + + + + + UTC + + + ANY + ANY + 00:00 + + + + 00:00 + + + + NO + NO + + + + ACTIVE + + + + + activation + DESCRIPTION + + + + H24 + + + + + + + + + + diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 1070201ee0..0bea57b081 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled or given only as changes are left out and counted. Every value a feature holds is kept: simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled or given only as changes are left out and counted. Every value a feature holds is kept: simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 442acf7224c9f50f1d6ec27187ece253048897c7 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:06:41 -0600 Subject: [PATCH 12/61] fix(data): AIXM clippy lints --- crates/data/src/aixm.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index c572fcca10..4969327a91 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -938,10 +938,7 @@ impl Shapes { for m in elements(r).filter(|c| local(c) == "curveMember") { match elements(m).next() { Some(c) => members.push(Ok(self.curve(c, notes)?)), - None => match m.attribute((XLINK, "href")) { - Some(h) => members.push(Err(border_key(h))), - None => return None, - }, + None => members.push(Err(border_key(m.attribute((XLINK, "href"))?))), } } let mut out: Vec = Vec::new(); @@ -1884,7 +1881,6 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 2, _ => 1, }; - let mut order = order; order.sort_by_key(rank); crate::progress::begin(index.members.len() + order.len()); crate::progress::step(index.members.len())?; From a2450a6a6d7e0f00466857033e1866ce0d5410d7 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:00:02 -0600 Subject: [PATCH 13/61] fix(data): AIXM border chains meet where the borders join; a border named again straight after is followed once --- crates/data/src/aixm.rs | 56 +++++++++++++++++++++++++++++++++-- crates/data/src/aixm/tests.rs | 29 +++++++++++++++++- 2 files changed, 81 insertions(+), 4 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 4969327a91..74e01a9801 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -938,9 +938,19 @@ impl Shapes { for m in elements(r).filter(|c| local(c) == "curveMember") { match elements(m).next() { Some(c) => members.push(Ok(self.curve(c, notes)?)), - None => members.push(Err(border_key(m.attribute((XLINK, "href"))?))), + None => { + // The same border named again straight after is the same stretch of + // it (DFS writes a border's members so), followed once. + let key = border_key(m.attribute((XLINK, "href"))?); + if !matches!(members.last(), Some(Err(k)) if *k == key) { + members.push(Err(key)); + } + } } } + if members.len() > 1 && matches!((members.first(), members.last()), (Some(Err(a)), Some(Err(b))) if a == b) { + members.pop(); + } let mut out: Vec = Vec::new(); let n = members.len(); // Each member's nearest written points before and after it, round the ring: two @@ -973,8 +983,19 @@ impl Shapes { let mut part = match members.get(i) { Some(Ok(c)) => c.clone(), Some(Err(key)) => { - let before = befores.get(i).copied().flatten(); - let after = afters.get(i).copied().flatten(); + // Next to another border (a state's outline is a chain of them), the + // stretch starts or ends where the two meet: this border's end nearest + // that one. Next to written points, at the nearest of those. + let neighbor = |k: usize| match members.get(k % n) { + Some(Err(other)) if other != key && n > 1 => Some(other.clone()), + _ => None, + }; + let before = neighbor(i + n - 1) + .and_then(|other| self.junction(key, &other, notes)) + .or_else(|| befores.get(i).copied().flatten()); + let after = neighbor(i + 1) + .and_then(|other| self.junction(key, &other, notes)) + .or_else(|| afters.get(i).copied().flatten()); // Said as a border by reference by the ring's patch, not also as a // ring left out. let Some(part) = self.follow(key, before, after, notes) else { @@ -1036,6 +1057,35 @@ impl Shapes { Some(part) } + /// Where the border `key` meets the border `other` next to it in a ring: the point of `key` + /// nearest `other`, of those an end of either gives (its own ends, or the point on it nearest + /// one of `other`'s, where `other` runs on past where they meet or stops short). Looking along + /// both is paid for as points are. + fn junction(&mut self, key: &str, other: &str, notes: &mut ShapeNotes) -> Option { + let scan = self.borders.get(other)?.len() + self.borders.get(key)?.len(); + if self.take(scan, notes) < scan { + return None; + } + let (line, them) = (self.borders.get(key)?, self.borders.get(other)?); + let mut best: Option<(f64, Coord)> = None; + let mut consider = |d: f64, c: Coord| { + if best.is_none_or(|(bd, _)| d < bd) { + best = Some((d, c)); + } + }; + for end in [line.first(), line.last()].into_iter().flatten() { + if let Some((.., d)) = nearest_on(them, *end) { + consider(d, *end); + } + } + for end in [them.first(), them.last()].into_iter().flatten() { + if let Some((_, _, on, d)) = nearest_on(line, *end) { + consider(d, on); + } + } + best.map(|(_, c)| c) + } + /// A surface's polygon patches (or a polygon): each its exterior and interiors. fn surface(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { let patches: Vec = if local(&g) == "Polygon" { diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 7148bf3e10..cfb83e5453 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -852,7 +852,10 @@ fn many_references_to_a_long_border_stay_within_the_files_allowance() { r#"LONG{line}"# ); let geo = feature("GeoBorder", "border-1", &[slice("GeoBorder", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &border)]); - let refs = r#""#.repeat(20_000); + // Two borders named in turn: a repeated one is followed once, so each of these is a cut. + let geo2 = geo.replace("border-1", "border-2"); + let geo = geo + &geo2; + let refs = r#""#.repeat(10_000); let ring_xml = format!( r#"{refs}50 11 50.5 11 50.5 10 50 10"# ); @@ -923,3 +926,27 @@ fn dfs_airspace_follows_the_state_border_it_names() { } assert!(!notes.iter().any(|m| m.contains("more than 50 m")), "{notes:?}"); } + +#[test] +fn a_chain_of_borders_meets_where_they_join_and_a_repeated_one_is_followed_once() { + let geo = |id: &str, pos: &str| { + let body = format!( + r#"{id}{pos}"# + ); + feature("GeoBorder", id, &[slice("GeoBorder", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]) + }; + // A runs west to east along 50 N beyond the corner at 10 E; B runs north from that corner. + let borders = geo("south", "50 8.5 50 9 50 9.5 50 10 50 10.5") + &geo("east", "50 10 50.5 10 51 10"); + let ring_xml = r#"51 10 51 9 50 9"#; + let body = format!( + r#"CORNER{ring_xml}"# + ); + let area = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let out = read("t.xml", &message(&(area + &borders)), &at("2026-01-15")).unwrap(); + let ring = ring(layer(&out, "t WorkArea").features[0].geometry.as_ref().unwrap()); + // The square from 9 to 10 E, 50 to 51 N: south border from 9 to the corner, east border up. + assert!(ring.iter().all(|c| (8.999..=10.001).contains(&c.x) && (49.999..=51.001).contains(&c.y)), "{ring:?}"); + let a: f64 = ring.windows(2).map(|w| (w[1].x - w[0].x) * (w[1].y + w[0].y) / 2.0).sum::().abs(); + assert!((a - 1.0).abs() < 1e-6, "area {a}: {ring:?}"); + assert!(said(&out).iter().any(|m| m.contains("2 borders given by reference are drawn")), "{:?}", said(&out)); +} From 96c3096dcf0238085fcb5b1a1c38d38731b4c2a2 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:10:04 -0600 Subject: [PATCH 14/61] fix(data): AIXM review findings: two-border rings, links by gml:id, why a border isn't followed, held rows charged, route segments kept as a table --- crates/data/src/aixm.rs | 282 +++++++++++++++++++++++++++------- crates/data/src/aixm/tests.rs | 62 +++++++- 2 files changed, 283 insertions(+), 61 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 74e01a9801..2a62324258 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -77,7 +77,7 @@ const MIN_ADDED_POINTS: usize = 1_000_000; const MAX_RADIUS_M: f64 = 10_000_000.0; /// Kinds with no geometry of their own read as tables. -const TABLE_KINDS: &[&str] = &["Runway", "RunwayDirection", "Route"]; +const TABLE_KINDS: &[&str] = &["Runway", "RunwayDirection", "Route", "RouteSegment"]; /// Time-slice properties that describe the slice, not the feature. const SLICE_PROPERTIES: &[&str] = @@ -375,6 +375,8 @@ struct Slice { /// A feature's slices, read from any number of members. struct Feature { kind: String, + /// Its own `gml:id`: what a local link (`#id`) or the FAA's XPath names it by. + gml_id: Option, slices: Vec, } @@ -591,6 +593,9 @@ struct ShapeNotes { far: usize, /// A route segment drawn between the points it names, having no curve. between: bool, + /// Borders by reference not followed: past the work allowed, or too short to cut. + border_allowance: usize, + border_unusable: usize, } /// Reads shapes, adding at most `budget` points to the file's positions. @@ -611,6 +616,8 @@ struct Shapes { as_wgs84_now: bool, /// The borders references may follow, by [`border_key`]: each GeoBorder's at the date. borders: HashMap>, + /// Steps of looking along borders still allowed ([`Shapes::scan`]). + scan_left: usize, /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of /// route segments that name them. points: HashMap, @@ -641,6 +648,9 @@ impl ShapeNotes { self.referenced += o.referenced; self.followed += o.followed; self.far += o.far; + self.border_allowance += o.border_allowance; + self.border_unusable += o.border_unusable; + self.between |= o.between; } } @@ -666,7 +676,7 @@ impl Shapes { } // OGC's CRS83: NAD83 longitude/latitude, as the FAA writes it; within a couple of meters // of WGS 84 in North America, read as it and said. - if name.trim().to_ascii_uppercase().ends_with(":CRS83") { + if name.trim().to_ascii_uppercase().ends_with(":CRS83") || name.trim().to_ascii_uppercase().ends_with("/CRS83") { self.as_wgs84.get_or_insert_with(|| name.to_string()); self.as_wgs84_now = true; return Some(Axes { swap: false }); @@ -952,6 +962,8 @@ impl Shapes { members.pop(); } let mut out: Vec = Vec::new(); + // Borders followed, counted once the ring is drawn. + let mut followed = 0; let n = members.len(); // Each member's nearest written points before and after it, round the ring: two // passes, however many members are references. @@ -990,19 +1002,41 @@ impl Shapes { Some(Err(other)) if other != key && n > 1 => Some(other.clone()), _ => None, }; - let before = neighbor(i + n - 1) - .and_then(|other| self.junction(key, &other, notes)) - .or_else(|| befores.get(i).copied().flatten()); - let after = neighbor(i + 1) - .and_then(|other| self.junction(key, &other, notes)) - .or_else(|| afters.get(i).copied().flatten()); - // Said as a border by reference by the ring's patch, not also as a - // ring left out. - let Some(part) = self.follow(key, before, after, notes) else { - notes.referenced += 1; - return None; + let (prev, next) = (neighbor(i + n - 1), neighbor(i + 1)); + // The same border either side (a ring of two borders): they meet at + // both its ends, so it is followed whole, turned to meet the line. + let (before, after) = if prev.is_some() && prev == next { + (None, None) + } else { + ( + prev.and_then(|other| self.junction(key, &other, notes)).or_else(|| befores.get(i).copied().flatten()), + next.and_then(|other| self.junction(key, &other, notes)).or_else(|| afters.get(i).copied().flatten()), + ) }; - part + // Said as a border by reference by the ring's patch, not also as a + // ring left out; each why in its own notice. + match self.follow(key, before, after, notes) { + Ok(part) => { + followed += 1; + match out.last() { + // A whole border turned to start where the line is. + Some(&end) if before.is_none() && after.is_none() => { + let gap = + |c: Option<&Coord>| c.map_or(f64::INFINITY, |c| rustgis_geom::wgs84_distance_m(*c, end)); + if gap(part.last()) < gap(part.first()) { part.into_iter().rev().collect() } else { part } + } + _ => part, + } + } + Err(why) => { + match why { + Unfollowed::Missing => notes.referenced += 1, + Unfollowed::Allowance => notes.border_allowance += 1, + Unfollowed::Unusable => notes.border_unusable += 1, + } + return None; + } + } } None => return None, }; @@ -1014,6 +1048,9 @@ impl Shapes { } out.extend(part); } + if out.len() >= 3 { + notes.followed += followed; + } out } _ => return None, @@ -1032,17 +1069,26 @@ impl Shapes { /// start of the next), the shorter way round a border that closes; the whole border when the /// ring has no other points. AIXM leaves this cut to the reader (its coding guidance, "Geoborder /// for Airspace Border"), so each is counted, and those whose ends lie far from the border. - fn follow(&mut self, key: &str, before: Option, after: Option, notes: &mut ShapeNotes) -> Option> { - let scan = self.borders.get(key)?.len(); - // Looking along the border is paid for as points are, so references can't make the - // looking outgrow what the file's size allows. - if self.take(scan, notes) < scan { - return None; - } - let border = self.borders.get(key)?; + fn follow( + &mut self, + key: &str, + before: Option, + after: Option, + notes: &mut ShapeNotes, + ) -> std::result::Result, Unfollowed> { + let scan = self.borders.get(key).ok_or(Unfollowed::Missing)?.len(); + if scan < 2 { + return Err(Unfollowed::Unusable); + } + // Looking along borders has an allowance of its own, set by the file's size, so + // references can't make the looking outgrow it, nor take the points arcs are drawn with. + if !self.scan(scan) { + return Err(Unfollowed::Allowance); + } + let border = self.borders.get(key).ok_or(Unfollowed::Missing)?; let part = match (before, after) { (Some(a), Some(b)) => { - let (part, off) = cut(border, a, b)?; + let (part, off) = cut(border, a, b).ok_or(Unfollowed::Unusable)?; notes.far += usize::from(off > FAR_FROM_BORDER_M); part } @@ -1051,10 +1097,20 @@ impl Shapes { // Its points are paid for as a curve's added points are. let n = part.len(); if self.take(n, notes) < n { - return None; + return Err(Unfollowed::Allowance); + } + Ok(part) + } + + /// Takes `n` steps of looking along borders from their allowance: false when it is spent. + fn scan(&mut self, n: usize) -> bool { + match self.scan_left.checked_sub(n) { + Some(left) => { + self.scan_left = left; + true + } + None => false, } - notes.followed += 1; - Some(part) } /// Where the border `key` meets the border `other` next to it in a ring: the point of `key` @@ -1063,7 +1119,7 @@ impl Shapes { /// both is paid for as points are. fn junction(&mut self, key: &str, other: &str, notes: &mut ShapeNotes) -> Option { let scan = self.borders.get(other)?.len() + self.borders.get(key)?.len(); - if self.take(scan, notes) < scan { + if !self.scan(scan) { return None; } let (line, them) = (self.borders.get(key)?, self.borders.get(other)?); @@ -1083,7 +1139,10 @@ impl Shapes { consider(d, on); } } - best.map(|(_, c)| c) + // Borders that don't meet (a gap between them) are joined across it, and that is said. + let (d, c) = best?; + notes.far += usize::from(d > FAR_FROM_BORDER_M); + Some(c) } /// A surface's polygon patches (or a polygon): each its exterior and interiors. @@ -1115,6 +1174,15 @@ impl Shapes { (!polys.is_empty()).then_some(Geometry::Polygon(polys)) } + /// A shape read a second time (a border or point kept for the features that name it): what + /// it costs and what it finds are counted by its own reading, not again. + fn quietly(&mut self, g: Node) -> Option { + let kept = (self.budget, self.assumed_system, self.other_count, self.as_wgs84_count); + let shape = self.shape(g, &mut ShapeNotes::default()); + (self.budget, self.assumed_system, self.other_count, self.as_wgs84_count) = kept; + shape + } + /// A geometry element (AIXM's or GML's) as a geometry. fn shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { (self.assumed_now, self.other_now, self.as_wgs84_now) = (false, false, false); @@ -1135,6 +1203,17 @@ impl Shapes { } } +/// Why a border given by reference wasn't followed. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Unfollowed { + /// No GeoBorder by that name in the file, in force at the date. + Missing, + /// Following it would pass the work the file's size allows. + Allowance, + /// A border too short to cut (fewer than two points). + Unusable, +} + /// How far from a border the ends of a part cut from it may lie before that is said, in meters. const FAR_FROM_BORDER_M: f64 = 50.0; @@ -1200,7 +1279,7 @@ fn cut(line: &[Coord], a: Coord, b: Coord) -> Option<(Vec, f64)> { round.extend((0..=ib).filter_map(at)); } round.push(pb); - let length = |l: &[Coord]| l.windows(2).map(|w| rustgis_geom::wgs84_distance_m(w[0], w[1])).sum::(); + let length = |l: &[Coord]| l.windows(2).filter_map(|w| Some(rustgis_geom::wgs84_distance_m(*w.first()?, *w.get(1)?))).sum::(); if length(&round) < length(&direct) { round } else { direct } } else { direct @@ -1263,6 +1342,8 @@ struct Layer { named: HashMap, /// Its rows: their shape, their simple values by column number, their nested ones by path. rows: Vec<(Option, Vec<(usize, String)>, Nested)>, + /// Values not kept: past the memory the file's size allows. + over_bytes: usize, /// Values of properties past the column cap, or nested past [`MAX_PATH`]. capped: usize, /// Features kept without a shape: no geometry, or one that couldn't be read. @@ -1285,6 +1366,9 @@ struct Layer { far: usize, /// Route segments drawn between the points they name. between: usize, + /// Borders by reference not followed: past the work allowed, or too short to cut. + border_allowance: usize, + border_unusable: usize, /// Shapes in the records of features drawn from their own shapes, not drawn. shapes_in_records: usize, /// Features as a TEMPDELTA changed them. @@ -1323,6 +1407,8 @@ impl Layer { self.followed += n.followed; self.far += n.far; self.between += usize::from(n.between); + self.border_allowance += n.border_allowance; + self.border_unusable += n.border_unusable; } } @@ -1335,6 +1421,9 @@ type Path = Vec<(String, usize)>; struct Paths { ids: HashMap, list: Vec, + /// The bytes the paths hold, and the most they may: one allowance for the whole read. + bytes: usize, + limit: usize, } /// The paths of a read, shared by its rows. @@ -1363,6 +1452,8 @@ struct Row { /// set: a row being read stops keeping values past what the file's size allows). bytes: usize, limit: Option, + /// Values not kept: past the memory the file's size allows. + over_bytes: usize, } impl Row { @@ -1384,7 +1475,7 @@ impl Row { fn afford(&mut self, cost: usize) -> bool { let cost = cost + VALUE_OVERHEAD; if self.limit.is_some_and(|l| self.bytes + cost > l) { - self.capped += 1; + self.over_bytes += 1; return false; } self.bytes += cost; @@ -1402,9 +1493,14 @@ impl Row { if let Some(&id) = paths.ids.get(&at) { return Some(id); } - if !self.afford(at.iter().map(|(n, _)| n.len() + VALUE_OVERHEAD).sum()) { + // A new path is kept twice (in the list and as its key): charged so to the read's + // allowance for paths, whichever row meets it first, kept or not. + let cost = 2 * at.iter().map(|(n, _)| n.len() + VALUE_OVERHEAD).sum::() + 4 * VALUE_OVERHEAD; + if paths.bytes + cost > paths.limit { + self.over_bytes += 1; return None; } + paths.bytes += cost; let id = paths.list.len(); paths.list.push(at.clone()); paths.ids.insert(at, id); @@ -1479,7 +1575,7 @@ impl Row { } let name = local(&c); // AIXM and GML name objects with a capital, properties without. - if name.starts_with(|ch: char| ch.is_ascii_uppercase()) { + if name.starts_with(|ch: char| ch.is_ascii_uppercase()) && elements(c).next().is_some() { let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); self.record_at(c, path, shape, depth + 1); continue; @@ -1657,6 +1753,7 @@ impl Layers { self.bytes_left -= cells; let layer = self.list.get_mut(i)?; layer.capped += row.capped; + layer.over_bytes += row.over_bytes; layer.temporary += usize::from(change.0); layer.snapshots += usize::from(change.1); let mut attrs = Vec::with_capacity(row.attrs.len()); @@ -1846,7 +1943,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result Result = Vec::new(); @@ -1931,6 +2033,14 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 2, _ => 1, }; + // The layers still come in the order their kinds are first met in the file. + let mut kind_rank: HashMap = HashMap::new(); + for id in &order { + if let Some(f) = features.get(id) { + let next = kind_rank.len(); + kind_rank.entry(f.kind.clone()).or_insert(next); + } + } order.sort_by_key(rank); crate::progress::begin(index.members.len() + order.len()); crate::progress::step(index.members.len())?; @@ -2021,18 +2131,25 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = parts.concat(); if let Some(gid) = g.attribute((GML, "id")) { shapes.borders.insert(format!("#{}", gid.trim()), line.clone()); } + if let Some(gid) = &feature.gml_id { + shapes.borders.insert(format!("#{gid}"), line.clone()); + } shapes.borders.insert(border_key(id), line); } - // Where a point feature is, for route segments that name it. + // Where a point feature is, for route segments that name it: by its identifier and its + // own gml:id (a local link's or an XPath's). if let Some(g) = props.iter().find_map(|p| shape_in(*p).filter(|g| matches!(local(g), "Point" | "ElevatedPoint"))) - && let Some(Geometry::Point(c)) = shapes.shape(g, &mut ShapeNotes::default()) + && let Some(Geometry::Point(c)) = shapes.quietly(g) { + if let Some(gid) = &feature.gml_id { + shapes.points.insert(gid.clone(), c); + } shapes.points.insert(id.trim_start_matches("urn:uuid:").to_string(), c); } let mut fnotes = ShapeNotes::default(); @@ -2042,21 +2159,30 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result feature_rows(&props, &mut row, &mut shapes, &mut layers, kind, temporary, snapshot), }; if !placed { - shapeless.push((kind.to_string(), row, temporary, snapshot)); + // Held until it is known whether its kind has a layer: its bytes reserved now. + let w = row.weight(); + if w > layers.bytes_left { + layers.rows_over += 1; + } else { + layers.bytes_left -= w; + shapeless.push((kind.to_string(), row, temporary, snapshot)); + } } } // Features with nothing to draw: in their kind's layer when it has one, as a table for the // kinds that are tables, else counted. for (kind, row, temporary, snapshot) in shapeless { let change = (temporary > 0, snapshot); - if TABLE_KINDS.contains(&kind.as_str()) { - layers.push(&kind, "", None, row, None, change); - } else if layers.has_kind(&kind) { + // What was reserved for it, given back to be taken as it is added. + layers.bytes_left += row.weight(); + if layers.has_kind(&kind) { let label = layers.list.iter().find(|l| l.kind == kind).map(|l| l.label.clone()).unwrap_or_default(); let i = layers.push(&kind, &label, None, row, None, change); if let Some(l) = layers.at(i) { l.shapeless += 1; } + } else if TABLE_KINDS.contains(&kind.as_str()) { + layers.push(&kind, "", None, row, None, change); } else { notes.nothing_to_draw += 1; notes.nothing_names.add(&kind); @@ -2065,22 +2191,31 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Option> { - let end = |name: &str| -> Option { +fn between(props: &[Node], shapes: &mut Shapes) -> Option<(Vec, ShapeNotes)> { + let mut end = |name: &str| -> Option { let p = props.iter().find(|p| local(p) == name)?; - let r = - p.descendants().find(|d| d.is_element() && local(d).starts_with("pointChoice_") && d.attribute((XLINK, "href")).is_some())?; - shapes.points.get(&reference(r.attribute((XLINK, "href"))?)).copied() + let choice = p.descendants().find(|d| d.is_element() && local(d).starts_with("pointChoice_"))?; + match choice.attribute((XLINK, "href")) { + Some(h) => shapes.points.get(&reference(h)).copied(), + // A position written in place (`pointChoice_position`). + None => match shape_in(choice).and_then(|g| shapes.quietly(g)) { + Some(Geometry::Point(c)) => Some(c), + _ => None, + }, + } }; let (a, b) = (end("start")?, end("end")?); - let mut notes = ShapeNotes::default(); - Some(shapes.geodesic(&[a, b], &mut notes)) + let mut notes = ShapeNotes { between: true, ..ShapeNotes::default() }; + let line = shapes.geodesic(&[a, b], &mut notes); + Some((line, notes)) } /// The family a shape element draws as, by its name (what a layer of its shapes is labeled). @@ -2144,6 +2279,7 @@ fn feature_rows( // position it doesn't have) gives none: said as no geometry, not as unreadable. let empty = !g.descendants().any(|d| d.is_element() && is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()); + let empty = empty && geom.is_none(); let bad = geom.is_none() && !empty; let i = layers.push(kind, &name, geom, r, Some(¬es), change); first = first.or(i); @@ -2157,12 +2293,14 @@ fn feature_rows( } return true; } - // A route segment with no curve: a geodesic between the points its start and end name. - if parts.is_empty() - && kind == "RouteSegment" - && let Some(line) = between(props, shapes) + // A route segment with no curve: a geodesic between the points its start and end name (or + // hold), its start and end kept as records. + if kind == "RouteSegment" + && let Some((line, notes)) = between(props, shapes) { - let notes = ShapeNotes { between: true, ..ShapeNotes::default() }; + for p in &parts { + row.property(*p, ""); + } layers.push(kind, "curveExtent", Some(Geometry::Line(vec![line])), row.clone(), Some(¬es), change); return true; } @@ -2220,6 +2358,7 @@ fn airspace( for p in props { if local(p) == "geometryComponent" { if is_nil(p) { + row.property(*p, ""); continue; } // A volume given by reference to another feature's isn't followed: the airspace isn't @@ -2228,6 +2367,7 @@ fn airspace( if p.attribute((XLINK, "href")).is_some() { components.push((u64::MAX, "REFERENCE".to_string(), None)); } + row.property(*p, ""); continue; }; // Every component's values as its record (its operation, its volume's limits, the @@ -2313,8 +2453,10 @@ fn vertical_structure( let mut parts = Vec::new(); for p in props { if local(p) == "part" && !is_nil(p) { - if let Some(vp) = elements(*p).find(|c| local(c) == "VerticalStructurePart") { - parts.push(vp); + match elements(*p).find(|c| local(c) == "VerticalStructurePart") { + Some(vp) => parts.push(vp), + // A part given by reference: its link kept. + None => row.property(*p, ""), } } else { row.property(*p, ""); @@ -2482,6 +2624,11 @@ fn finish( for (g, mut attrs, nested) in std::mem::take(&mut layer.rows) { for (id, value) in nested { let k = match column_of.get(&id) { + // A path past the cap: each of its values not kept is counted. + Some(None) => { + layer.capped += 1; + None + } Some(k) => *k, None => { let k = paths.list.get(id).and_then(|p| layer.column(&path_column(p, &repeating))); @@ -2499,7 +2646,9 @@ fn finish( for (k, v) in attrs { match merged.last_mut() { Some((last, old)) if *last == k => { - if !v.is_empty() { + if old.is_empty() { + *old = v; + } else if !v.is_empty() { old.push_str("; "); old.push_str(&v); } @@ -2596,6 +2745,16 @@ fn finish( "border is given by reference to a curve that isn't in the file (or not in force then), so it can't be followed", "borders are given by reference to curves that aren't in the file (or not in force then), so they can't be followed", ); + say( + layer.border_allowance, + "border given by reference isn't followed: following it would pass the work the file's size allows", + "borders given by reference aren't followed: following them would pass the work the file's size allows", + ); + say( + layer.border_unusable, + "border given by reference isn't followed: the GeoBorder it names has too few points to cut", + "borders given by reference aren't followed: the GeoBorders they name have too few points to cut", + ); say( layer.between, "route segment with no curve is drawn as a geodesic between the points its start and end name", @@ -2621,6 +2780,11 @@ fn finish( "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked", "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked", ); + say( + layer.over_bytes, + "value wasn't kept: past the memory the file's size allows", + "values weren't kept: past the memory the file's size allows", + ); say( layer.capped, &format!("value past the first {MAX_COLUMNS} columns, or nested deeper than {MAX_PATH} records, wasn't read"), diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index cfb83e5453..96bc9c3725 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -865,7 +865,7 @@ fn many_references_to_a_long_border_stay_within_the_files_allowance() { let area = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); let out = read("t.xml", &message(&(area + &geo)), &at("2026-01-15")).unwrap(); // 20,000 cuts of a 5,000-point border would be 100 million steps; the allowance stops them. - assert!(said(&out).iter().any(|m| m.contains("can't be followed")), "{:?}", said(&out)); + assert!(said(&out).iter().any(|m| m.contains("would pass the work the file's size allows")), "{:?}", said(&out)); } #[test] @@ -896,7 +896,7 @@ fn faa_route_segments_are_drawn_between_their_points_in_nad83() { let notes = said(&out); for want in [ "1 route segment with no curve is drawn as a geodesic between the points its start and end name", - "read as WGS 84 longitude/latitude", + "2 geometries in a geographic system other than WGS 84", "2 time positions left empty (not said to be unknown) read as open", ] { assert!(notes.iter().any(|m| m.contains(want)), "{want}: {notes:?}"); @@ -950,3 +950,61 @@ fn a_chain_of_borders_meets_where_they_join_and_a_repeated_one_is_followed_once( assert!((a - 1.0).abs() < 1e-6, "area {a}: {ring:?}"); assert!(said(&out).iter().any(|m| m.contains("2 borders given by reference are drawn")), "{:?}", said(&out)); } + +#[test] +fn a_ring_of_two_borders_follows_each_whole() { + let geo = |id: &str, pos: &str| { + let body = format!( + r#"{id}{pos}"# + ); + feature("GeoBorder", id, &[slice("GeoBorder", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]) + }; + // A land border from (50 N, 9 E) round by the east to (51 N, 9 E), and a coast back by the west. + let borders = geo("land", "50 9 50 10 51 10 51 9") + &geo("coast", "50 9 50.5 8.5 51 9"); + let ring_xml = r#""#; + let body = format!( + r#"ISLAND{ring_xml}"# + ); + let area = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let out = read("t.xml", &message(&(area + &borders)), &at("2026-01-15")).unwrap(); + let ring = ring(layer(&out, "t WorkArea").features[0].geometry.as_ref().unwrap()); + let a: f64 = ring.windows(2).map(|w| (w[1].x - w[0].x) * (w[1].y + w[0].y) / 2.0).sum::().abs(); + assert!((a - 1.25).abs() < 1e-6, "area {a}: {ring:?}"); + assert!(!said(&out).iter().any(|m| m.contains("has no geometry") || m.contains("left out")), "{:?}", said(&out)); +} + +#[test] +fn a_point_named_by_its_gml_id_is_found_though_it_has_an_identifier() { + let point = |gid: &str, uuid: &str, lat: f64| { + format!( + r#"{uuid}{}"#, + slice( + "DesignatedPoint", + "BASELINE", + 1, + 0, + &period("2025-01-01T00:00:00Z", None), + &format!( + r#"{lat} 10"# + ) + ) + ) + }; + let body = r##""##; + let seg = feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), body)]); + let out = read("t.xml", &message(&(seg + &point("P1", "u1", 50.0) + &point("P2", "u2", 51.0))), &at("2026-01-15")).unwrap(); + let Some(Geometry::Line(parts)) = &layer(&out, "t RouteSegment").features[0].geometry else { panic!("not drawn") }; + assert_eq!(parts[0].first(), Some(&Coord::new(10.0, 50.0))); + assert_eq!(parts[0].last(), Some(&Coord::new(10.0, 51.0))); +} + +#[test] +fn route_segments_whose_points_are_elsewhere_are_kept_as_a_table() { + let body = r#"12"#; + let seg = feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), body)]); + let out = read("t.xml", &message(&seg), &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t RouteSegment"); + assert_eq!(ds.geometry_type, GeometryType::None); + assert_eq!(value(ds, 0, "length"), Value::Int(12)); + assert_eq!(value(ds, 0, "start_pointChoice_fixDesignatedPoint"), Value::Text("not-here".into())); +} From 28bfa7efae1ff12b5bcd496d18c8763d36918fca Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:14:15 -0600 Subject: [PATCH 15/61] fix(data): an AIXM shape read again pays for its points; inline route segment ends are points only --- crates/data/src/aixm.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 2a62324258..4a4708b0f2 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -1175,11 +1175,12 @@ impl Shapes { } /// A shape read a second time (a border or point kept for the features that name it): what - /// it costs and what it finds are counted by its own reading, not again. + /// it finds is said by its own reading, not again; the points it adds are paid for all the + /// same, so reading again can't add points past the allowance. fn quietly(&mut self, g: Node) -> Option { - let kept = (self.budget, self.assumed_system, self.other_count, self.as_wgs84_count); + let kept = (self.assumed_system, self.other_count, self.as_wgs84_count); let shape = self.shape(g, &mut ShapeNotes::default()); - (self.budget, self.assumed_system, self.other_count, self.as_wgs84_count) = kept; + (self.assumed_system, self.other_count, self.as_wgs84_count) = kept; shape } @@ -2206,7 +2207,7 @@ fn between(props: &[Node], shapes: &mut Shapes) -> Option<(Vec, ShapeNote match choice.attribute((XLINK, "href")) { Some(h) => shapes.points.get(&reference(h)).copied(), // A position written in place (`pointChoice_position`). - None => match shape_in(choice).and_then(|g| shapes.quietly(g)) { + None => match shape_in(choice).filter(|g| matches!(local(g), "Point" | "ElevatedPoint")).and_then(|g| shapes.quietly(g)) { Some(Geometry::Point(c)) => Some(c), _ => None, }, From c17313294953fcb7dbdf67a09e4949c841b8274a Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:16:46 -0600 Subject: [PATCH 16/61] fix(data): AIXM clippy lint --- crates/data/src/aixm.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 4a4708b0f2..5749c6af4c 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -2193,7 +2193,6 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Date: Mon, 23 Nov 2026 15:41:59 -0600 Subject: [PATCH 17/61] fix(data): AIXM review findings: junction and whole-border counts, rings said once, inline segment ends, held rows' own allowance --- crates/data/src/aixm.rs | 185 ++++++++++++++++++++++------------ crates/data/src/aixm/tests.rs | 40 ++++++++ 2 files changed, 160 insertions(+), 65 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 5749c6af4c..4dc8f4e902 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -56,7 +56,9 @@ const GML: &str = "http://www.opengis.net/gml/3.2"; const XLINK: &str = "http://www.w3.org/1999/xlink"; const XSI: &str = "http://www.w3.org/2001/XMLSchema-instance"; -/// Most layers read from one file. +/// Most layers read from one file. Features are read GeoBorders first and route segments last +/// (borders are followed and points named by others), so in a file of more kinds than this, route +/// segments are the first left out; the layers that are kept come in the file's order. const MAX_LAYERS: usize = 64; /// Most attribute columns of a layer. const MAX_COLUMNS: usize = 2000; @@ -591,6 +593,8 @@ struct ShapeNotes { /// ends lie more than [`FAR_FROM_BORDER_M`] from it. followed: usize, far: usize, + /// Borders by reference followed whole (a ring of two borders: no points to cut them at). + followed_whole: usize, /// A route segment drawn between the points it names, having no curve. between: bool, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -647,6 +651,7 @@ impl ShapeNotes { self.rings_lost += o.rings_lost; self.referenced += o.referenced; self.followed += o.followed; + self.followed_whole += o.followed_whole; self.far += o.far; self.border_allowance += o.border_allowance; self.border_unusable += o.border_unusable; @@ -936,6 +941,9 @@ impl Shapes { /// A ring: a `gml:Ring` of curve members, or a `gml:LinearRing`; closed. fn ring(&mut self, boundary: Node, notes: &mut ShapeNotes) -> Option> { let r = elements(boundary).next()?; + // Borders followed (cut, or whole) and those far from where they meet, counted once the + // ring is drawn. + let (mut followed, mut whole, mut far) = (0, 0, 0); let mut pts: Vec = match local(&r) { "LinearRing" => { let axes = self.axes(r)?; @@ -962,8 +970,6 @@ impl Shapes { members.pop(); } let mut out: Vec = Vec::new(); - // Borders followed, counted once the ring is drawn. - let mut followed = 0; let n = members.len(); // Each member's nearest written points before and after it, round the ring: two // passes, however many members are references. @@ -1008,16 +1014,43 @@ impl Shapes { let (before, after) = if prev.is_some() && prev == next { (None, None) } else { - ( - prev.and_then(|other| self.junction(key, &other, notes)).or_else(|| befores.get(i).copied().flatten()), - next.and_then(|other| self.junction(key, &other, notes)).or_else(|| afters.get(i).copied().flatten()), - ) + // Where it meets the borders either side; a gap between two is + // counted once, from the first of them. + let before = match prev { + Some(other) => match self.junction(key, &other) { + Ok((c, _)) => Some(c), + Err(why) => { + say_unfollowed(why, notes); + return None; + } + }, + None => None, + }; + let after = match next { + Some(other) => match self.junction(key, &other) { + Ok((c, gap)) => { + far += usize::from(gap); + Some(c) + } + Err(why) => { + say_unfollowed(why, notes); + return None; + } + }, + None => None, + }; + (before.or_else(|| befores.get(i).copied().flatten()), after.or_else(|| afters.get(i).copied().flatten())) }; // Said as a border by reference by the ring's patch, not also as a // ring left out; each why in its own notice. match self.follow(key, before, after, notes) { - Ok(part) => { - followed += 1; + Ok((part, off)) => { + far += usize::from(off); + if before.is_none() && after.is_none() { + whole += 1; + } else { + followed += 1; + } match out.last() { // A whole border turned to start where the line is. Some(&end) if before.is_none() && after.is_none() => { @@ -1029,11 +1062,7 @@ impl Shapes { } } Err(why) => { - match why { - Unfollowed::Missing => notes.referenced += 1, - Unfollowed::Allowance => notes.border_allowance += 1, - Unfollowed::Unusable => notes.border_unusable += 1, - } + say_unfollowed(why, notes); return None; } } @@ -1048,9 +1077,6 @@ impl Shapes { } out.extend(part); } - if out.len() >= 3 { - notes.followed += followed; - } out } _ => return None, @@ -1061,7 +1087,13 @@ impl Shapes { } else if let Some(l) = pts.last_mut() { *l = first; } - (pts.len() >= 4).then_some(pts) + if pts.len() < 4 { + return None; + } + notes.followed += followed; + notes.followed_whole += whole; + notes.far += far; + Some(pts) } /// The part of a border given by reference (`key`, [`border_key`]) a ring follows: from the @@ -1075,7 +1107,7 @@ impl Shapes { before: Option, after: Option, notes: &mut ShapeNotes, - ) -> std::result::Result, Unfollowed> { + ) -> std::result::Result<(Vec, bool), Unfollowed> { let scan = self.borders.get(key).ok_or(Unfollowed::Missing)?.len(); if scan < 2 { return Err(Unfollowed::Unusable); @@ -1086,20 +1118,19 @@ impl Shapes { return Err(Unfollowed::Allowance); } let border = self.borders.get(key).ok_or(Unfollowed::Missing)?; - let part = match (before, after) { + let (part, far) = match (before, after) { (Some(a), Some(b)) => { let (part, off) = cut(border, a, b).ok_or(Unfollowed::Unusable)?; - notes.far += usize::from(off > FAR_FROM_BORDER_M); - part + (part, off > FAR_FROM_BORDER_M) } - _ => border.clone(), + _ => (border.clone(), false), }; // Its points are paid for as a curve's added points are. let n = part.len(); if self.take(n, notes) < n { return Err(Unfollowed::Allowance); } - Ok(part) + Ok((part, far)) } /// Takes `n` steps of looking along borders from their allowance: false when it is spent. @@ -1117,12 +1148,12 @@ impl Shapes { /// nearest `other`, of those an end of either gives (its own ends, or the point on it nearest /// one of `other`'s, where `other` runs on past where they meet or stops short). Looking along /// both is paid for as points are. - fn junction(&mut self, key: &str, other: &str, notes: &mut ShapeNotes) -> Option { - let scan = self.borders.get(other)?.len() + self.borders.get(key)?.len(); + fn junction(&mut self, key: &str, other: &str) -> std::result::Result<(Coord, bool), Unfollowed> { + let scan = self.borders.get(other).ok_or(Unfollowed::Missing)?.len() + self.borders.get(key).ok_or(Unfollowed::Missing)?.len(); if !self.scan(scan) { - return None; + return Err(Unfollowed::Allowance); } - let (line, them) = (self.borders.get(key)?, self.borders.get(other)?); + let (line, them) = (self.borders.get(key).ok_or(Unfollowed::Missing)?, self.borders.get(other).ok_or(Unfollowed::Missing)?); let mut best: Option<(f64, Coord)> = None; let mut consider = |d: f64, c: Coord| { if best.is_none_or(|(bd, _)| d < bd) { @@ -1140,9 +1171,8 @@ impl Shapes { } } // Borders that don't meet (a gap between them) are joined across it, and that is said. - let (d, c) = best?; - notes.far += usize::from(d > FAR_FROM_BORDER_M); - Some(c) + let (d, c) = best.ok_or(Unfollowed::Unusable)?; + Ok((c, d > FAR_FROM_BORDER_M)) } /// A surface's polygon patches (or a polygon): each its exterior and interiors. @@ -1155,18 +1185,19 @@ impl Shapes { let mut polys = Vec::new(); for p in patches { // A ring lost to a border by reference is said as that, once. - let before = notes.referenced; + let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable; + let before = said(notes); let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, notes)); let Some(outer) = outer else { - notes.rings_lost += usize::from(notes.referenced == before); + notes.rings_lost += usize::from(said(notes) == before); continue; }; let mut rings = vec![outer]; for b in elements(p).filter(|c| local(c) == "interior") { - let before = notes.referenced; + let before = said(notes); match self.ring(b, notes) { Some(r) => rings.push(r), - None => notes.rings_lost += usize::from(notes.referenced == before), + None => notes.rings_lost += usize::from(said(notes) == before), } } polys.push(rings); @@ -1215,6 +1246,15 @@ enum Unfollowed { Unusable, } +/// Counts why a border given by reference wasn't followed. +fn say_unfollowed(why: Unfollowed, notes: &mut ShapeNotes) { + match why { + Unfollowed::Missing => notes.referenced += 1, + Unfollowed::Allowance => notes.border_allowance += 1, + Unfollowed::Unusable => notes.border_unusable += 1, + } +} + /// How far from a border the ends of a part cut from it may lie before that is said, in meters. const FAR_FROM_BORDER_M: f64 = 50.0; @@ -1367,6 +1407,8 @@ struct Layer { far: usize, /// Route segments drawn between the points they name. between: usize, + /// Borders by reference followed whole. + followed_whole: usize, /// Borders by reference not followed: past the work allowed, or too short to cut. border_allowance: usize, border_unusable: usize, @@ -1406,6 +1448,7 @@ impl Layer { self.rings_lost += n.rings_lost; self.referenced += n.referenced; self.followed += n.followed; + self.followed_whole += n.followed_whole; self.far += n.far; self.between += usize::from(n.between); self.border_allowance += n.border_allowance; @@ -1447,7 +1490,7 @@ struct Row { interned: SharedPaths, /// How many records of each property the feature has had so far. records: HashMap, - /// Values of names past [`MAX_COLUMNS`], nested past [`MAX_PATH`], or past `limit`, not kept. + /// Values of names past [`MAX_COLUMNS`], or nested past [`MAX_PATH`], not kept. capped: usize, /// The bytes its values and their names and paths hold, and the most they may (none until /// set: a row being read stops keeping values past what the file's size allows). @@ -1576,10 +1619,16 @@ impl Row { } let name = local(&c); // AIXM and GML name objects with a capital, properties without. - if name.starts_with(|ch: char| ch.is_ascii_uppercase()) && elements(c).next().is_some() { - let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); - self.record_at(c, path, shape, depth + 1); - continue; + if name.starts_with(|ch: char| ch.is_ascii_uppercase()) { + if elements(c).next().is_some() { + let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); + self.record_at(c, path, shape, depth + 1); + continue; + } + // An object with nothing in it holds no value; one with text is a value. + if text_of(&c).is_empty() { + continue; + } } let n = seen.entry(name).or_default(); *n += 1; @@ -1588,14 +1637,13 @@ impl Row { self.record_at(c, path, false, depth + 1); } else if let Some((last, _)) = path.last().cloned() { for (key, value) in leaf_values(c, &last) { - if !self.afford(value.as_ref().map_or(0, String::len)) { - continue; - } let mut at = path.clone(); if let Some(step) = at.last_mut() { step.0 = key; } - if let Some(id) = self.path_id(at) { + if let Some(id) = self.path_id(at) + && self.afford(value.as_ref().map_or(0, String::len)) + { self.paths.push((id, value)); } } @@ -2027,6 +2075,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = Vec::new(); + let mut held_left = text.len().saturating_mul(2).max(MIN_ROW_BYTES); // GeoBorders first: airspace borders follow them by reference; route segments last: one with // no curve is drawn between the points it names. let rank = |id: &String| match features.get(id).map(|f| f.kind.as_str()) { @@ -2156,16 +2205,17 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result airspace(&props, &mut row, &mut shapes, &mut fnotes, &mut layers, kind, temporary, snapshot), - "VerticalStructure" => vertical_structure(&props, &row, &mut shapes, &mut layers, kind, temporary, snapshot), + "VerticalStructure" => vertical_structure(&props, &mut row, &mut shapes, &mut layers, kind, temporary, snapshot), _ => feature_rows(&props, &mut row, &mut shapes, &mut layers, kind, temporary, snapshot), }; if !placed { - // Held until it is known whether its kind has a layer: its bytes reserved now. + // Held until it is known whether its kind has a layer, within an allowance of their + // own: rows held and then let go can't crowd out rows that are drawn. let w = row.weight(); - if w > layers.bytes_left { + if w > held_left { layers.rows_over += 1; } else { - layers.bytes_left -= w; + held_left -= w; shapeless.push((kind.to_string(), row, temporary, snapshot)); } } @@ -2174,8 +2224,6 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0, snapshot); - // What was reserved for it, given back to be taken as it is added. - layers.bytes_left += row.weight(); if layers.has_kind(&kind) { let label = layers.list.iter().find(|l| l.kind == kind).map(|l| l.label.clone()).unwrap_or_default(); let i = layers.push(&kind, &label, None, row, None, change); @@ -2200,24 +2248,27 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Option<(Vec, ShapeNotes)> { - let mut end = |name: &str| -> Option { - let p = props.iter().find(|p| local(p) == name)?; - let choice = p.descendants().find(|d| d.is_element() && local(d).starts_with("pointChoice_"))?; - match choice.attribute((XLINK, "href")) { - Some(h) => shapes.points.get(&reference(h)).copied(), - // A position written in place (`pointChoice_position`). - None => match shape_in(choice).filter(|g| matches!(local(g), "Point" | "ElevatedPoint")).and_then(|g| shapes.quietly(g)) { - Some(Geometry::Point(c)) => Some(c), - _ => None, - }, - } - }; - let (a, b) = (end("start")?, end("end")?); let mut notes = ShapeNotes { between: true, ..ShapeNotes::default() }; + let a = segment_end(props, "start", shapes, &mut notes)?; + let b = segment_end(props, "end", shapes, &mut notes)?; let line = shapes.geodesic(&[a, b], &mut notes); Some((line, notes)) } +/// Where a route segment's `start` or `end` is: the point it names, or one written in place +/// (`pointChoice_position`, read as any shape is, with what its reading finds). +fn segment_end(props: &[Node], name: &str, shapes: &mut Shapes, notes: &mut ShapeNotes) -> Option { + let p = props.iter().find(|p| local(p) == name)?; + let choice = p.descendants().find(|d| d.is_element() && local(d).starts_with("pointChoice_"))?; + match choice.attribute((XLINK, "href")) { + Some(h) => shapes.points.get(&reference(h)).copied(), + None => match shape_in(choice).filter(|g| matches!(local(g), "Point" | "ElevatedPoint")).and_then(|g| shapes.shape(g, notes)) { + Some(Geometry::Point(c)) => Some(c), + _ => None, + }, + } +} + /// The family a shape element draws as, by its name (what a layer of its shapes is labeled). fn element_family(name: &str) -> &'static str { match name { @@ -2442,14 +2493,13 @@ fn airspace( /// A vertical structure: a row per part, the structure's values with the part's (`part_…`). fn vertical_structure( props: &[Node], - base: &Row, + row: &mut Row, shapes: &mut Shapes, layers: &mut Layers, kind: &str, temporary: usize, snapshot: bool, ) -> bool { - let mut row = base.clone(); let mut parts = Vec::new(); for p in props { if local(p) == "part" && !is_nil(p) { @@ -2745,6 +2795,11 @@ fn finish( "border is given by reference to a curve that isn't in the file (or not in force then), so it can't be followed", "borders are given by reference to curves that aren't in the file (or not in force then), so they can't be followed", ); + say( + layer.followed_whole, + "border given by reference is drawn whole along the GeoBorder it names: the ring names no other points to cut it at", + "borders given by reference are drawn whole along the GeoBorders they name: their rings name no other points to cut them at", + ); say( layer.border_allowance, "border given by reference isn't followed: following it would pass the work the file's size allows", diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 96bc9c3725..a5441fce01 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1008,3 +1008,43 @@ fn route_segments_whose_points_are_elsewhere_are_kept_as_a_table() { assert_eq!(value(ds, 0, "length"), Value::Int(12)); assert_eq!(value(ds, 0, "start_pointChoice_fixDesignatedPoint"), Value::Text("not-here".into())); } + +#[test] +fn a_structure_whose_parts_are_all_references_keeps_its_values() { + let body = r#"MAST"#; + let vs = + feature("VerticalStructure", "v", &[slice("VerticalStructure", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), body)]); + let point = point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "A")]); + // A kind with nothing to draw is counted; its values reach the notice's count, not a table. + let out = read("t.xml", &message(&(vs + &point)), &at("2026-01-15")).unwrap(); + assert!( + said(&out).iter().any(|m| m.contains("1 feature of kinds with nothing to draw left out (VerticalStructure)")), + "{:?}", + said(&out) + ); + // With a drawn part beside it, the structure's row keeps its name and the part's link. + let located = r#"47 -27"#; + let body = format!("{body}{located}"); + let vs = + feature("VerticalStructure", "v", &[slice("VerticalStructure", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let out = read("t.xml", &message(&vs), &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t VerticalStructure"); + assert_eq!(value(ds, 0, "name"), Value::Text("MAST".into())); + assert_eq!(value(ds, 0, "part"), Value::Text("p1".into())); + assert_eq!(value(ds, 0, "part_title"), Value::Text("MAST PART".into())); +} + +#[test] +fn a_route_segment_end_written_in_place_says_what_its_reading_finds() { + let end = |name: &str, lat: f64| { + format!( + r#"-97 {lat}"# + ) + }; + let body = end("start", 32.0) + &end("end", 33.0); + let seg = feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let out = read("t.xml", &message(&seg), &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t RouteSegment"); + assert!(matches!(ds.features[0].geometry, Some(Geometry::Line(_)))); + assert!(said(&out).iter().any(|m| m.contains("2 geometries in a geographic system other than WGS 84")), "{:?}", said(&out)); +} From b5ab68be7dc48b3aa02b78fb8381a0c24b64da08 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:52:03 -0600 Subject: [PATCH 18/61] fix(data): AIXM review findings: route segment ends read once, empty objects that say something kept, junction fallback said --- crates/data/src/aixm.rs | 99 ++++++++++++++++++++++------------- crates/data/src/aixm/tests.rs | 24 ++++++++- 2 files changed, 85 insertions(+), 38 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 4dc8f4e902..a8c914439a 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -57,8 +57,9 @@ const XLINK: &str = "http://www.w3.org/1999/xlink"; const XSI: &str = "http://www.w3.org/2001/XMLSchema-instance"; /// Most layers read from one file. Features are read GeoBorders first and route segments last -/// (borders are followed and points named by others), so in a file of more kinds than this, route -/// segments are the first left out; the layers that are kept come in the file's order. +/// (borders are followed and points named by others), and tables of features with nothing to draw +/// are made after all of them, so in a file of more kinds than this those are the first left out; +/// the layers that are kept come in the file's order. const MAX_LAYERS: usize = 64; /// Most attribute columns of a layer. const MAX_COLUMNS: usize = 2000; @@ -595,6 +596,9 @@ struct ShapeNotes { far: usize, /// Borders by reference followed whole (a ring of two borders: no points to cut them at). followed_whole: usize, + /// Borders cut at the written points, not where they meet the next border: working that out + /// would pass the work the file's size allows. + cut_at_points: usize, /// A route segment drawn between the points it names, having no curve. between: bool, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -652,6 +656,7 @@ impl ShapeNotes { self.referenced += o.referenced; self.followed += o.followed; self.followed_whole += o.followed_whole; + self.cut_at_points += o.cut_at_points; self.far += o.far; self.border_allowance += o.border_allowance; self.border_unusable += o.border_unusable; @@ -943,7 +948,7 @@ impl Shapes { let r = elements(boundary).next()?; // Borders followed (cut, or whole) and those far from where they meet, counted once the // ring is drawn. - let (mut followed, mut whole, mut far) = (0, 0, 0); + let (mut followed, mut whole, mut far, mut fallback) = (0, 0, 0, 0); let mut pts: Vec = match local(&r) { "LinearRing" => { let axes = self.axes(r)?; @@ -1016,29 +1021,23 @@ impl Shapes { } else { // Where it meets the borders either side; a gap between two is // counted once, from the first of them. - let before = match prev { - Some(other) => match self.junction(key, &other) { - Ok((c, _)) => Some(c), - Err(why) => { - say_unfollowed(why, notes); - return None; - } - }, - None => None, - }; - let after = match next { - Some(other) => match self.junction(key, &other) { + // One that can't be worked out (past the work allowed, or a + // border not there to meet) is cut at the written points instead. + let mut meet = |s: &mut Self, other: Option, count_gap: bool| match other { + Some(other) => match s.junction(key, &other) { Ok((c, gap)) => { - far += usize::from(gap); + far += usize::from(gap && count_gap); Some(c) } Err(why) => { - say_unfollowed(why, notes); - return None; + fallback += usize::from(why == Unfollowed::Allowance); + None } }, None => None, }; + let before = meet(self, prev, false); + let after = meet(self, next, true); (before.or_else(|| befores.get(i).copied().flatten()), after.or_else(|| afters.get(i).copied().flatten())) }; // Said as a border by reference by the ring's patch, not also as a @@ -1093,6 +1092,7 @@ impl Shapes { notes.followed += followed; notes.followed_whole += whole; notes.far += far; + notes.cut_at_points += fallback; Some(pts) } @@ -1125,11 +1125,12 @@ impl Shapes { } _ => (border.clone(), false), }; - // Its points are paid for as a curve's added points are. + // Its points are paid for as a curve's added points are; one that can't be takes none. let n = part.len(); - if self.take(n, notes) < n { + if self.budget < n { return Err(Unfollowed::Allowance); } + self.take(n, notes); Ok((part, far)) } @@ -1409,6 +1410,8 @@ struct Layer { between: usize, /// Borders by reference followed whole. followed_whole: usize, + /// Borders cut at the written points, the work of meeting the next border past the allowance. + cut_at_points: usize, /// Borders by reference not followed: past the work allowed, or too short to cut. border_allowance: usize, border_unusable: usize, @@ -1449,6 +1452,7 @@ impl Layer { self.referenced += n.referenced; self.followed += n.followed; self.followed_whole += n.followed_whole; + self.cut_at_points += n.cut_at_points; self.far += n.far; self.between += usize::from(n.between); self.border_allowance += n.border_allowance; @@ -1625,8 +1629,10 @@ impl Row { self.record_at(c, path, shape, depth + 1); continue; } - // An object with nothing in it holds no value; one with text is a value. - if text_of(&c).is_empty() { + // An object with nothing in it holds no value; one with text, or what an attribute + // says (a link, why it is missing, a unit), is a value. + let says = c.attributes().any(|a| !(a.namespace() == Some(GML) && a.name() == "id")); + if text_of(&c).is_empty() && !says { continue; } } @@ -1641,10 +1647,14 @@ impl Row { if let Some(step) = at.last_mut() { step.0 = key; } - if let Some(id) = self.path_id(at) - && self.afford(value.as_ref().map_or(0, String::len)) - { - self.paths.push((id, value)); + // Paid for first; given back when its path can't be kept. + let cost = value.as_ref().map_or(0, String::len); + if !self.afford(cost) { + continue; + } + match self.path_id(at) { + Some(id) => self.paths.push((id, value)), + None => self.bytes = self.bytes.saturating_sub(cost + VALUE_OVERHEAD), } } } @@ -2248,24 +2258,36 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Option<(Vec, ShapeNotes)> { + // Both ends found first: a segment drawn neither way reads its ends' shapes once, as records. + let (a, b) = (segment_end(props, "start", shapes)?, segment_end(props, "end", shapes)?); let mut notes = ShapeNotes { between: true, ..ShapeNotes::default() }; - let a = segment_end(props, "start", shapes, &mut notes)?; - let b = segment_end(props, "end", shapes, &mut notes)?; + let at = |end: End, shapes: &mut Shapes, notes: &mut ShapeNotes| match end { + End::Named(c) => Some(c), + End::Written(g) => match shapes.shape(g, notes) { + Some(Geometry::Point(c)) => Some(c), + _ => None, + }, + }; + let a = at(a, shapes, &mut notes)?; + let b = at(b, shapes, &mut notes)?; let line = shapes.geodesic(&[a, b], &mut notes); Some((line, notes)) } -/// Where a route segment's `start` or `end` is: the point it names, or one written in place -/// (`pointChoice_position`, read as any shape is, with what its reading finds). -fn segment_end(props: &[Node], name: &str, shapes: &mut Shapes, notes: &mut ShapeNotes) -> Option { +/// A route segment's `start` or `end`: a point it names, or one written in place. +enum End<'a, 'i> { + Named(Coord), + Written(Node<'a, 'i>), +} + +/// Where a route segment's `start` or `end` is: the point it names (when that is in the file), or +/// one written in place (`pointChoice_position`), read as any shape is, with what its reading finds. +fn segment_end<'a, 'i>(props: &[Node<'a, 'i>], name: &str, shapes: &Shapes) -> Option> { let p = props.iter().find(|p| local(p) == name)?; let choice = p.descendants().find(|d| d.is_element() && local(d).starts_with("pointChoice_"))?; match choice.attribute((XLINK, "href")) { - Some(h) => shapes.points.get(&reference(h)).copied(), - None => match shape_in(choice).filter(|g| matches!(local(g), "Point" | "ElevatedPoint")).and_then(|g| shapes.shape(g, notes)) { - Some(Geometry::Point(c)) => Some(c), - _ => None, - }, + Some(h) => shapes.points.get(&reference(h)).copied().map(End::Named), + None => shape_in(choice).filter(|g| matches!(local(g), "Point" | "ElevatedPoint")).map(End::Written), } } @@ -2795,6 +2817,11 @@ fn finish( "border is given by reference to a curve that isn't in the file (or not in force then), so it can't be followed", "borders are given by reference to curves that aren't in the file (or not in force then), so they can't be followed", ); + say( + layer.cut_at_points, + "border given by reference is cut at the written points nearest it, not where it meets the next border: working that out would pass the work the file's size allows", + "borders given by reference are cut at the written points nearest them, not where they meet the next border: working that out would pass the work the file's size allows", + ); say( layer.followed_whole, "border given by reference is drawn whole along the GeoBorder it names: the ring names no other points to cut it at", diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index a5441fce01..9d9fb7b679 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -948,7 +948,12 @@ fn a_chain_of_borders_meets_where_they_join_and_a_repeated_one_is_followed_once( assert!(ring.iter().all(|c| (8.999..=10.001).contains(&c.x) && (49.999..=51.001).contains(&c.y)), "{ring:?}"); let a: f64 = ring.windows(2).map(|w| (w[1].x - w[0].x) * (w[1].y + w[0].y) / 2.0).sum::().abs(); assert!((a - 1.0).abs() < 1e-6, "area {a}: {ring:?}"); - assert!(said(&out).iter().any(|m| m.contains("2 borders given by reference are drawn")), "{:?}", said(&out)); + let notes = said(&out); + assert!( + notes.iter().any(|m| m.contains("2 borders given by reference are drawn along the GeoBorders they name, between")), + "{notes:?}" + ); + assert!(!notes.iter().any(|m| m.contains("drawn whole")), "{notes:?}"); } #[test] @@ -970,7 +975,9 @@ fn a_ring_of_two_borders_follows_each_whole() { let ring = ring(layer(&out, "t WorkArea").features[0].geometry.as_ref().unwrap()); let a: f64 = ring.windows(2).map(|w| (w[1].x - w[0].x) * (w[1].y + w[0].y) / 2.0).sum::().abs(); assert!((a - 1.25).abs() < 1e-6, "area {a}: {ring:?}"); - assert!(!said(&out).iter().any(|m| m.contains("has no geometry") || m.contains("left out")), "{:?}", said(&out)); + let notes = said(&out); + assert!(!notes.iter().any(|m| m.contains("has no geometry") || m.contains("left out")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("2 borders given by reference are drawn whole along the GeoBorders they name")), "{notes:?}"); } #[test] @@ -1048,3 +1055,16 @@ fn a_route_segment_end_written_in_place_says_what_its_reading_finds() { assert!(matches!(ds.features[0].geometry, Some(Geometry::Line(_)))); assert!(said(&out).iter().any(|m| m.contains("2 geometries in a geographic system other than WGS 84")), "{:?}", said(&out)); } + +#[test] +fn an_empty_object_that_says_something_is_kept() { + let body = format!("{}", named_point("N")); + let out = read( + "t.xml", + &message(&point("a", &[slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + let ds = layer(&out, "t DesignatedPoint"); + assert_eq!(value(ds, 0, "record_Thing_nilReason"), Value::Text("unknown".into())); +} From a53d8f42b46a26c8935aeb0d5c6c3a449baa3d13 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:03:04 -0600 Subject: [PATCH 19/61] fix(data): AIXM rings whose borders can't be joined aren't drawn and say why; route segment ends counted once; plumbing isn't a value --- crates/data/src/aixm.rs | 80 +++++++++++++++++------------------ crates/data/src/aixm/tests.rs | 9 ++++ 2 files changed, 49 insertions(+), 40 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index a8c914439a..1a134e9687 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -596,9 +596,6 @@ struct ShapeNotes { far: usize, /// Borders by reference followed whole (a ring of two borders: no points to cut them at). followed_whole: usize, - /// Borders cut at the written points, not where they meet the next border: working that out - /// would pass the work the file's size allows. - cut_at_points: usize, /// A route segment drawn between the points it names, having no curve. between: bool, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -656,7 +653,6 @@ impl ShapeNotes { self.referenced += o.referenced; self.followed += o.followed; self.followed_whole += o.followed_whole; - self.cut_at_points += o.cut_at_points; self.far += o.far; self.border_allowance += o.border_allowance; self.border_unusable += o.border_unusable; @@ -948,7 +944,7 @@ impl Shapes { let r = elements(boundary).next()?; // Borders followed (cut, or whole) and those far from where they meet, counted once the // ring is drawn. - let (mut followed, mut whole, mut far, mut fallback) = (0, 0, 0, 0); + let (mut followed, mut whole, mut far) = (0, 0, 0); let mut pts: Vec = match local(&r) { "LinearRing" => { let axes = self.axes(r)?; @@ -1022,22 +1018,21 @@ impl Shapes { // Where it meets the borders either side; a gap between two is // counted once, from the first of them. // One that can't be worked out (past the work allowed, or a - // border not there to meet) is cut at the written points instead. + // border not there to meet) leaves the ring undrawn, and why is said. let mut meet = |s: &mut Self, other: Option, count_gap: bool| match other { - Some(other) => match s.junction(key, &other) { - Ok((c, gap)) => { - far += usize::from(gap && count_gap); - Some(c) - } - Err(why) => { - fallback += usize::from(why == Unfollowed::Allowance); - None - } - }, - None => None, + Some(other) => s.junction(key, &other).map(|(c, gap)| { + far += usize::from(gap && count_gap); + Some(c) + }), + None => Ok(None), + }; + let (before, after) = match (meet(self, prev, false), meet(self, next, true)) { + (Ok(b), Ok(a)) => (b, a), + (Err(why), _) | (_, Err(why)) => { + say_unfollowed(why, notes); + return None; + } }; - let before = meet(self, prev, false); - let after = meet(self, next, true); (before.or_else(|| befores.get(i).copied().flatten()), after.or_else(|| afters.get(i).copied().flatten())) }; // Said as a border by reference by the ring's patch, not also as a @@ -1092,7 +1087,6 @@ impl Shapes { notes.followed += followed; notes.followed_whole += whole; notes.far += far; - notes.cut_at_points += fallback; Some(pts) } @@ -1410,8 +1404,6 @@ struct Layer { between: usize, /// Borders by reference followed whole. followed_whole: usize, - /// Borders cut at the written points, the work of meeting the next border past the allowance. - cut_at_points: usize, /// Borders by reference not followed: past the work allowed, or too short to cut. border_allowance: usize, border_unusable: usize, @@ -1452,7 +1444,6 @@ impl Layer { self.referenced += n.referenced; self.followed += n.followed; self.followed_whole += n.followed_whole; - self.cut_at_points += n.cut_at_points; self.far += n.far; self.between += usize::from(n.between); self.border_allowance += n.border_allowance; @@ -1631,7 +1622,7 @@ impl Row { } // An object with nothing in it holds no value; one with text, or what an attribute // says (a link, why it is missing, a unit), is a value. - let says = c.attributes().any(|a| !(a.namespace() == Some(GML) && a.name() == "id")); + let says = !SHAPES.contains(&name) && (is_nil(&c) || c.attributes().any(|a| value_attribute(&a).is_some())); if text_of(&c).is_empty() && !says { continue; } @@ -1702,16 +1693,24 @@ fn leaf_values(p: Node, name: &str) -> Vec<(String, Option)> { out.push((name.to_string(), Some(text_of(&p)))); } for a in p.attributes() { - let key = match (a.namespace(), a.name()) { - (Some(XLINK), "title") => "title", - (Some(XLINK) | Some(XSI), _) | (Some(GML), "id") | (None, "id") => continue, - (_, other) => other, - }; - out.push((format!("{name}_{key}"), Some(a.value().trim().to_string()))); + if let Some(key) = value_attribute(&a) { + out.push((format!("{name}_{key}"), Some(a.value().trim().to_string()))); + } } out } +/// The name an attribute is kept under, when it holds a value: a reference's title, a unit, why +/// a value is missing, a language, any other; not an element's id or the XML plumbing (other +/// XLink and XML Schema attributes). +fn value_attribute<'a>(a: &roxmltree::Attribute<'a, '_>) -> Option<&'a str> { + match (a.namespace(), a.name()) { + (Some(XLINK), "title") => Some("title"), + (Some(XLINK) | Some(XSI), _) | (Some(GML), "id") | (None, "id") => None, + (_, other) => Some(other), + } +} + /// The column of each nested value of a layer's rows: its path's names joined by `_`, each step /// numbered (`authority_1_type`) when its record repeats anywhere in the layer, so every row's /// values of one record share their columns. @@ -2261,15 +2260,21 @@ fn between(props: &[Node], shapes: &mut Shapes) -> Option<(Vec, ShapeNote // Both ends found first: a segment drawn neither way reads its ends' shapes once, as records. let (a, b) = (segment_end(props, "start", shapes)?, segment_end(props, "end", shapes)?); let mut notes = ShapeNotes { between: true, ..ShapeNotes::default() }; - let at = |end: End, shapes: &mut Shapes, notes: &mut ShapeNotes| match end { - End::Named(c) => Some(c), - End::Written(g) => match shapes.shape(g, notes) { + let quiet = |end: &End, shapes: &mut Shapes| match end { + End::Named(c) => Some(*c), + End::Written(g) => match shapes.quietly(*g) { Some(Geometry::Point(c)) => Some(c), _ => None, }, }; - let a = at(a, shapes, &mut notes)?; - let b = at(b, shapes, &mut notes)?; + let (ca, cb) = (quiet(&a, shapes)?, quiet(&b, shapes)?); + // Drawn from them: what the ends written in place find is said with the segment. + for end in [&a, &b] { + if let End::Written(g) = end { + let _ = shapes.shape(*g, &mut notes); + } + } + let (a, b) = (ca, cb); let line = shapes.geodesic(&[a, b], &mut notes); Some((line, notes)) } @@ -2817,11 +2822,6 @@ fn finish( "border is given by reference to a curve that isn't in the file (or not in force then), so it can't be followed", "borders are given by reference to curves that aren't in the file (or not in force then), so they can't be followed", ); - say( - layer.cut_at_points, - "border given by reference is cut at the written points nearest it, not where it meets the next border: working that out would pass the work the file's size allows", - "borders given by reference are cut at the written points nearest them, not where they meet the next border: working that out would pass the work the file's size allows", - ); say( layer.followed_whole, "border given by reference is drawn whole along the GeoBorder it names: the ring names no other points to cut it at", diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 9d9fb7b679..fd3e2b324d 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1067,4 +1067,13 @@ fn an_empty_object_that_says_something_is_kept() { .unwrap(); let ds = layer(&out, "t DesignatedPoint"); assert_eq!(value(ds, 0, "record_Thing_nilReason"), Value::Text("unknown".into())); + // One carrying only XML plumbing gives no column. + let body = format!("{}", named_point("N")); + let out = read( + "t.xml", + &message(&point("b", &[slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + assert!(!layer(&out, "t DesignatedPoint").fields.iter().any(|f| f.name.starts_with("record_Plumbing"))); } From 54658a8eb2b0151f91f8b6e4ccb2de7b210de43b Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:12:54 -0600 Subject: [PATCH 20/61] fix(data): an empty AIXM object that only links keeps its link; tests for unjoined borders and one-good-end route segments --- crates/data/src/aixm.rs | 11 ++++++---- crates/data/src/aixm/tests.rs | 41 ++++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 1a134e9687..919b6acc0b 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -1200,9 +1200,10 @@ impl Shapes { (!polys.is_empty()).then_some(Geometry::Polygon(polys)) } - /// A shape read a second time (a border or point kept for the features that name it): what - /// it finds is said by its own reading, not again; the points it adds are paid for all the - /// same, so reading again can't add points past the allowance. + /// A shape read without saying what it finds: one read again elsewhere (a border or point kept + /// for the features that name it), or before its feature is known to be drawn from it (a + /// route segment's ends). The points it adds are paid for all the same, so reading again can't + /// add points past the allowance. fn quietly(&mut self, g: Node) -> Option { let kept = (self.assumed_system, self.other_count, self.as_wgs84_count); let shape = self.shape(g, &mut ShapeNotes::default()); @@ -1622,7 +1623,9 @@ impl Row { } // An object with nothing in it holds no value; one with text, or what an attribute // says (a link, why it is missing, a unit), is a value. - let says = !SHAPES.contains(&name) && (is_nil(&c) || c.attributes().any(|a| value_attribute(&a).is_some())); + let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); + let says = !shape + && (is_nil(&c) || c.attribute((XLINK, "href")).is_some() || c.attributes().any(|a| value_attribute(&a).is_some())); if text_of(&c).is_empty() && !says { continue; } diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index fd3e2b324d..761f57c827 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1053,7 +1053,14 @@ fn a_route_segment_end_written_in_place_says_what_its_reading_finds() { let out = read("t.xml", &message(&seg), &at("2026-01-15")).unwrap(); let ds = layer(&out, "t RouteSegment"); assert!(matches!(ds.features[0].geometry, Some(Geometry::Line(_)))); - assert!(said(&out).iter().any(|m| m.contains("2 geometries in a geographic system other than WGS 84")), "{:?}", said(&out)); + assert!(said(&out).iter().any(|m| m.starts_with("2 geometries in a geographic system other than WGS 84")), "{:?}", said(&out)); + // One end good and the other in a projected system: not drawn, and each end said once. + let bad = end("end", 33.0).replace("urn:ogc:def:crs:OGC:1.3:CRS83", "urn:ogc:def:crs:EPSG::32614"); + let body = end("start", 32.0) + &bad; + let seg = feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let notes = said(&read("t.xml", &message(&seg), &at("2026-01-15")).unwrap()); + assert!(notes.iter().any(|m| m.starts_with("1 geometry in a geographic system other than WGS 84")), "{notes:?}"); + assert!(notes.iter().any(|m| m.starts_with("1 geometry in a system other than longitude/latitude")), "{notes:?}"); } #[test] @@ -1067,6 +1074,15 @@ fn an_empty_object_that_says_something_is_kept() { .unwrap(); let ds = layer(&out, "t DesignatedPoint"); assert_eq!(value(ds, 0, "record_Thing_nilReason"), Value::Text("unknown".into())); + // One that only points elsewhere keeps its link. + let body = format!("{}", named_point("N")); + let out = read( + "t.xml", + &message(&point("c", &[slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + assert_eq!(value(layer(&out, "t DesignatedPoint"), 0, "record_Linked"), Value::Text("abc".into())); // One carrying only XML plumbing gives no column. let body = format!("{}", named_point("N")); let out = read( @@ -1077,3 +1093,26 @@ fn an_empty_object_that_says_something_is_kept() { .unwrap(); assert!(!layer(&out, "t DesignatedPoint").fields.iter().any(|f| f.name.starts_with("record_Plumbing"))); } + +#[test] +fn a_ring_whose_borders_cant_be_joined_within_the_allowance_isnt_drawn_and_says_why() { + let doc = format!( + r#"51 10 51 9 50 9"# + ); + let doc = roxmltree::Document::parse(&doc).unwrap(); + let boundary = doc.root_element().first_element_child().unwrap(); + let line = |pts: &[(f64, f64)]| pts.iter().map(|&(x, y)| Coord::new(x, y)).collect::>(); + let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; + shapes.borders.insert("uuid:a".into(), line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)])); + shapes.borders.insert("uuid:b".into(), line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)])); + // With room to look along both borders where they meet: drawn. + shapes.scan_left = 1000; + let mut notes = ShapeNotes::default(); + assert!(shapes.ring(boundary, &mut notes).is_some()); + assert_eq!((notes.followed, notes.border_allowance), (2, 0)); + // Without: not drawn, and said as past the work allowed, once. + shapes.scan_left = 4; + let mut notes = ShapeNotes::default(); + assert!(shapes.ring(boundary, &mut notes).is_none()); + assert_eq!((notes.followed, notes.border_allowance, notes.rings_lost), (0, 1, 0)); +} From ebfbf93be9ae237320f2b26a81e0834658379fa5 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:18:38 -0600 Subject: [PATCH 21/61] fix(data): an AIXM object that links and holds values keeps both; quiet reads leave the notices' system names; blank links aren't values --- crates/data/src/aixm.rs | 29 +++++++++++++++++++++++------ crates/data/src/aixm/tests.rs | 23 +++++++++++++++++++++-- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 919b6acc0b..9866c19289 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -1205,9 +1205,9 @@ impl Shapes { /// route segment's ends). The points it adds are paid for all the same, so reading again can't /// add points past the allowance. fn quietly(&mut self, g: Node) -> Option { - let kept = (self.assumed_system, self.other_count, self.as_wgs84_count); + let kept = (self.assumed_system, self.other_count, self.as_wgs84_count, self.other_system.clone(), self.as_wgs84.clone()); let shape = self.shape(g, &mut ShapeNotes::default()); - (self.assumed_system, self.other_count, self.as_wgs84_count) = kept; + (self.assumed_system, self.other_count, self.as_wgs84_count, self.other_system, self.as_wgs84) = kept; shape } @@ -1616,16 +1616,33 @@ impl Row { let name = local(&c); // AIXM and GML name objects with a capital, properties without. if name.starts_with(|ch: char| ch.is_ascii_uppercase()) { + let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); + let links = c.attribute((XLINK, "href")).is_some_and(|h| !h.trim().is_empty()); if elements(c).next().is_some() { - let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); + // An object that links elsewhere and holds values too keeps both. + if links && !shape { + path.push((name.to_string(), 1)); + for (key, value) in leaf_values(c, name).into_iter().filter(|(k, _)| k == name || k.ends_with("_title")) { + let mut at = path.clone(); + if let Some(step) = at.last_mut() { + step.0 = key; + } + let cost = value.as_ref().map_or(0, String::len); + if self.afford(cost) { + match self.path_id(at) { + Some(id) => self.paths.push((id, value)), + None => self.bytes = self.bytes.saturating_sub(cost + VALUE_OVERHEAD), + } + } + } + path.pop(); + } self.record_at(c, path, shape, depth + 1); continue; } // An object with nothing in it holds no value; one with text, or what an attribute // says (a link, why it is missing, a unit), is a value. - let shape = SHAPES.contains(&name) && (is_aixm(&c) || is_gml(&c)); - let says = !shape - && (is_nil(&c) || c.attribute((XLINK, "href")).is_some() || c.attributes().any(|a| value_attribute(&a).is_some())); + let says = !shape && (is_nil(&c) || links || c.attributes().any(|a| value_attribute(&a).is_some())); if text_of(&c).is_empty() && !says { continue; } diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 761f57c827..12c34fe8da 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1083,6 +1083,20 @@ fn an_empty_object_that_says_something_is_kept() { ) .unwrap(); assert_eq!(value(layer(&out, "t DesignatedPoint"), 0, "record_Linked"), Value::Text("abc".into())); + // One that links and holds values keeps both. + let body = format!( + "{}x", + named_point("N") + ); + let out = read( + "t.xml", + &message(&point("d", &[slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + let ds = layer(&out, "t DesignatedPoint"); + assert_eq!(value(ds, 0, "record_Linked"), Value::Text("abc".into())); + assert_eq!(value(ds, 0, "record_note"), Value::Text("x".into())); // One carrying only XML plumbing gives no column. let body = format!("{}", named_point("N")); let out = read( @@ -1110,9 +1124,14 @@ fn a_ring_whose_borders_cant_be_joined_within_the_allowance_isnt_drawn_and_says_ let mut notes = ShapeNotes::default(); assert!(shapes.ring(boundary, &mut notes).is_some()); assert_eq!((notes.followed, notes.border_allowance), (2, 0)); - // Without: not drawn, and said as past the work allowed, once. + // Without: not drawn, and said as past the work allowed, once: not also as a ring left out. + let surface = format!( + r#"{}"#, + &doc.input_text()[boundary.range()] + ); + let surface = roxmltree::Document::parse(&surface).unwrap(); shapes.scan_left = 4; let mut notes = ShapeNotes::default(); - assert!(shapes.ring(boundary, &mut notes).is_none()); + assert!(shapes.surface(surface.root_element(), &mut notes).is_none()); assert_eq!((notes.followed, notes.border_allowance, notes.rings_lost), (0, 1, 0)); } From bcaea0c18383e3fc765194834a247951d8ab9cc3 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:42:15 -0600 Subject: [PATCH 22/61] test(data): trailing spaces off two comment lines of the Donlon fixture (pre-commit) --- ATTRIBUTION.md | 2 +- crates/data/tests/data/donlon-aixm.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 6749d2a967..f72f439be1 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -32,7 +32,7 @@ of use. | Script-only and fallback test fonts (`crates/render/testdata/test-script-only.otf`, `crates/render/testdata/test-fallback.otf`, `crates/render/testdata/test-latin-catalog.otf`) | The RustGIS project: original square outlines and script cmap variants ([generation](crates/render/testdata/README.md)) | Apache-2.0 | | JAXA Earth catalog test copy (`crates/tiles/tests/data/jaxa_catalog.v2.md`), read only by tests | JAXA: the [JAXA Earth API](https://data.earth.jaxa.jp/) dataset catalog ([catalog.v2.md](https://data.earth.jaxa.jp/app/mcp/catalog.v2.md)), copied on 2026-11-08 | JAXA's [terms of use](https://earth.jaxa.jp/en/data/policy/): free to use and redistribute, with credit to JAXA | | AIXM test message from DFS (`crates/data/tests/data/dfs-airspace-aixm.xml`), read only by tests | Three members of DFS Deutsche Flugsicherung GmbH's `ED_Airspace_ReferencedBorders_2026-10-29_2026-10-29_snapshot.xml` ([aip.dfs.de/datasets](https://aip.dfs.de/datasets/)): the GERMANY_NETHERLANDS GeoBorder and the MASKIRCHEN B AREA and BERLIN X airspaces, copied on 2026-11-23, the members unchanged and the message metadata left out | CC BY 4.0 | -| AIXM test message (`crates/data/tests/data/donlon-aixm.xml`), read only by tests | Nine members of the fictitious Donlon dataset's `Donlon_ALL_Baseline_ADM_upload.xml` ([aixm/Donlon_2025](https://github.com/aixm/Donlon_2025)), copyright (c) 2025 EUROCONTROL & FAA, copied on 2026-11-23 with the file's license notice; the members are unchanged | BSD-2-Clause | +| AIXM test message (`crates/data/tests/data/donlon-aixm.xml`), read only by tests | Nine members of the fictitious Donlon dataset's `Donlon_ALL_Baseline_ADM_upload.xml` ([aixm/Donlon_2025](https://github.com/aixm/Donlon_2025)), copyright (c) 2025 EUROCONTROL & FAA, copied on 2026-11-23 with the file's license notice; the members are unchanged but for trailing spaces removed from two comment lines | BSD-2-Clause | | CityGML test mesh (`crates/data/tests/data/rocking-chair.gml`), read only by tests | 97 faces of the rocking chair in OGC's CityGML 3.0 sample `Building_LOD3-EPSG25832.gml` ([CityGML-3.0Encodings](https://github.com/opengeospatial/CityGML-3.0Encodings/blob/master/Moved_to_CITYGML-3.0Encoding_CityGML/Examples/Examples-from-CityGML-2.0/building/CityGMLv3/Building_LOD3-EPSG25832.gml)), copyright (c) 2013 3DXScape, copied on 2026-11-12 and rewritten as a CityGML 2.0 object, coordinates unchanged | MIT | | Datum grid test files (`crates/data/tests/data/grids/us_noaa_conus.tif`, `us_noaa_ethpgn.tif`), read only by the datum grid tests | NOAA's NADCON and HARN grids as converted by [PROJ-data](https://github.com/OSGeo/PROJ-data) (`us_noaa`), copied unchanged from [cdn.proj.org](https://cdn.proj.org) | Public domain | | LERC GeoTIFF test files (`crates/data/tests/data/lerc/*.tif`), read only by the LERC tests | Written for the RustGIS project by `make_lerc.py` there with [GDAL](https://gdal.org) 3.9.3 through [rasterio](https://rasterio.readthedocs.io) 1.4.3, run only to write them; the values are made up | Apache-2.0 | diff --git a/crates/data/tests/data/donlon-aixm.xml b/crates/data/tests/data/donlon-aixm.xml index a69fbb4597..c269bcfa96 100644 --- a/crates/data/tests/data/donlon-aixm.xml +++ b/crates/data/tests/data/donlon-aixm.xml @@ -1379,8 +1379,8 @@ From b7f792285fe82d55dcdac056870e7ce1528394dd Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:01:37 -0600 Subject: [PATCH 23/61] fix(data): AIXM review findings: snapshots kept apart, holes and changes that can't be read, extensions by namespace, route path types, unlocated records, dense rows bounded, names-only listing; "at" checked on every path --- crates/data/src/aixm.rs | 314 +++++++++++++++++++++++++++------ crates/data/src/aixm/tests.rs | 211 +++++++++++++++++++++- crates/data/src/time.rs | 4 + crates/data/src/xml.rs | 52 ++++-- crates/engine/src/cmd/layer.rs | 17 +- crates/engine/src/tests.rs | 11 ++ crates/ui-egui/src/lib.rs | 5 + 7 files changed, 536 insertions(+), 78 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 9866c19289..9f19332cea 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -94,6 +94,8 @@ const SHAPES: &[&str] = &["Point", "ElevatedPoint", "Curve", "ElevatedCurve", "S pub struct Options { /// The effective date: milliseconds since 1970-01-01 UTC. Today when `None`. pub at: Option, + /// Only the layers' names are wanted (`info.fileLayers`): no shape is drawn and no value kept. + pub names_only: bool, } impl Options { @@ -101,11 +103,18 @@ impl Options { /// says its zone. pub fn at_text(text: &str) -> std::result::Result { crate::time::parse_text(text) - .map(|t| Options { at: Some(t) }) + .map(|t| Options { at: Some(t), ..Options::default() }) .ok_or_else(|| format!("'{text}' isn't a date (an AIXM effective date is written like 2026-01-15 or 2026-01-15T12:00Z)")) } } +/// The names of the layers [`read`] gives a message at `opts.at`, worked out without drawing +/// their shapes or keeping their values: what listing a file's layers needs. +pub fn layer_names(file_name: &str, bytes: &[u8], opts: &Options) -> Result> { + let opts = Options { names_only: true, ..*opts }; + Ok(read(file_name, bytes, &opts)?.into_iter().map(|(d, _)| d.name).collect()) +} + /// Whether a file is an AIXM message, by its root: an `AIXMBasicMessage` in an AIXM 5 namespace, /// or an FAA NASR subscriber file of AIXM 5 features ([`is_root`]). pub fn looks_like_aixm(bytes: &[u8]) -> bool { @@ -377,6 +386,8 @@ struct Slice { /// A feature's slices, read from any number of members. struct Feature { + /// Its identifier (`gml:identifier`, else its `gml:id`). + id: String, kind: String, /// Its own `gml:id`: what a local link (`#id`) or the FAA's XPath names it by. gml_id: Option, @@ -406,7 +417,13 @@ fn state_at(slices: &[Slice], t: f64) -> State { // Of slices alike in interpretation and sequence number, the highest correction holds (the // later in the file on a tie). let mut held: BTreeMap<(u8, u64), &Slice> = BTreeMap::new(); + // SNAPSHOTs have no sequence or correction number: each is its own instant, all kept. + let mut snapshots: Vec<&Slice> = Vec::new(); for s in slices { + if s.kind == Interpretation::Snapshot { + snapshots.push(s); + continue; + } let key = (s.kind as u8, s.sequence); match held.get(&key) { Some(h) if h.correction > s.correction => {} @@ -415,7 +432,7 @@ fn state_at(slices: &[Slice], t: f64) -> State { } } } - let live: Vec<&Slice> = held.values().copied().filter(|s| !s.canceled).collect(); + let live: Vec<&Slice> = held.values().copied().chain(snapshots).filter(|s| !s.canceled).collect(); if live.is_empty() { return if slices.is_empty() { State::OnlyChanges } else { State::Canceled }; } @@ -472,6 +489,8 @@ struct SliceTrouble { dates: usize, /// Validity or lifetime ends left empty without saying they are unknown, read as open. empty: usize, + /// Slices with a sequence or correction number that isn't a number, read as 0. + numbers: usize, } /// A slice's own properties. @@ -486,7 +505,15 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro return None; } }; - let number = |name: &str| child(s, name).and_then(|n| text_of(&n).parse::().ok()).unwrap_or(0); + // A number that isn't one is read as 0 and counted. + let unread_number = std::cell::Cell::new(false); + let number = |name: &str| match child(s, name).map(|n| text_of(&n)) { + Some(t) if !t.is_empty() => t.parse::().unwrap_or_else(|_| { + unread_number.set(true); + 0 + }), + _ => 0, + }; let empty = std::cell::Cell::new(0); let (mut begin, mut end, mut canceled) = (None, None, false); let mut bad = false; @@ -509,8 +536,12 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }); } Some(_) => bad = true, - // An empty validTime cancels the slice (`nilReason="inapplicable"`). - None => canceled = true, + // An empty validTime cancels the slice only when it says so + // (`nilReason="inapplicable"`); any other is a validity RustGIS can't read. + None => match v.attribute("nilReason").map(str::trim) { + Some("inapplicable") => canceled = true, + _ => bad = true, + }, } } let lifetime = child(s, "featureLifetime").and_then(|l| elements(l).find(|p| local(p) == "TimePeriod")).map(|p| { @@ -525,21 +556,13 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro (from, until) }); trouble.empty += empty.get(); + let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); + trouble.numbers += usize::from(unread_number.get()); if bad { trouble.dates += 1; return None; } - Some(Slice { - range, - scope, - kind, - sequence: number("sequenceNumber"), - correction: number("correctionNumber"), - begin, - end, - canceled, - lifetime, - }) + Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime }) } /// The features of a member (an `AIXMBasicMessage`'s `hasMember` holds one). @@ -598,6 +621,10 @@ struct ShapeNotes { followed_whole: usize, /// A route segment drawn between the points it names, having no curve. between: bool, + /// An arc or circle not drawn: the file's point allowance ran out. + past_allowance: bool, + /// A route segment with no curve and a `pathType` RustGIS doesn't draw. + path_unread: bool, /// Borders by reference not followed: past the work allowed, or too short to cut. border_allowance: usize, border_unusable: usize, @@ -623,6 +650,8 @@ struct Shapes { borders: HashMap>, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, + /// Only the layers' names are wanted: a shape is its family's placeholder, not drawn. + names_only: bool, /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of /// route segments that name them. points: HashMap, @@ -657,6 +686,8 @@ impl ShapeNotes { self.border_allowance += o.border_allowance; self.border_unusable += o.border_unusable; self.between |= o.between; + self.past_allowance |= o.past_allowance; + self.path_unread |= o.path_unread; } } @@ -821,6 +852,25 @@ impl Shapes { out } + /// A rhumb line (loxodrome) from `a` to `b`: straight on a Mercator map, a point every + /// [`GEODESIC_STEP_M`] at most, from the same allowance as geodesics. + fn rhumb(&mut self, a: Coord, b: Coord, notes: &mut ShapeNotes) -> Vec { + let b = next_to(b, a.x); + let merc = |lat: f64| (std::f64::consts::FRAC_PI_4 + lat.to_radians().clamp(-1.5, 1.5) / 2.0).tan().ln(); + let (ya, yb) = (merc(a.y), merc(b.y)); + let d = rustgis_geom::wgs84_distance_m(a, b); + let need = if d.is_finite() { (d / GEODESIC_STEP_M).ceil() as usize } else { 1 }; + notes.coarse |= need > MAX_GEODESIC_POINTS; + let n = self.take(need.clamp(1, MAX_GEODESIC_POINTS).saturating_sub(1), notes) + 1; + (0..=n) + .map(|k| { + let t = k as f64 / n as f64; + let y = ya + (yb - ya) * t; + Coord::new(a.x + (b.x - a.x) * t, (2.0 * y.exp().atan() - std::f64::consts::FRAC_PI_2).to_degrees()) + }) + .collect() + } + /// How many pieces an arc of `radius_m` turning `sweep_deg` is drawn with. fn pieces(&mut self, radius_m: f64, sweep_deg: f64, notes: &mut ShapeNotes) -> usize { let step = if radius_m <= ARC_TOLERANCE_M { 90.0 } else { (2.0 * (1.0 - ARC_TOLERANCE_M / radius_m).acos()).to_degrees() }; @@ -864,6 +914,11 @@ impl Shapes { _ => return None, }; let n = self.pieces(radius, sweep, notes); + // A full circle in fewer than three pieces isn't one: not drawn, and said. + if sweep.abs() >= 360.0 && n < 3 { + notes.past_allowance = true; + return None; + } let mut out = Vec::with_capacity(n + 1); for k in 0..=n { let (p, _) = rustgis_geom::wgs84_direct(center, bearing0 + sweep * k as f64 / n as f64, radius); @@ -1187,15 +1242,23 @@ impl Shapes { notes.rings_lost += usize::from(said(notes) == before); continue; }; + // A hole that can't be read leaves the patch out: drawn without it, the patch would + // cover what the hole excludes. let mut rings = vec![outer]; + let mut hole_lost = false; for b in elements(p).filter(|c| local(c) == "interior") { let before = said(notes); match self.ring(b, notes) { Some(r) => rings.push(r), - None => notes.rings_lost += usize::from(said(notes) == before), + None => { + notes.rings_lost += usize::from(said(notes) == before); + hole_lost = true; + } } } - polys.push(rings); + if !hole_lost { + polys.push(rings); + } } (!polys.is_empty()).then_some(Geometry::Polygon(polys)) } @@ -1222,6 +1285,14 @@ impl Shapes { } fn read_shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { + if self.names_only { + let o = Coord::new(0.0, 0.0); + return Some(match element_family(local(&g)) { + "points" => Geometry::Point(o), + "lines" => Geometry::Line(vec![vec![o, o]]), + _ => Geometry::Polygon(vec![vec![vec![o, o, o, o]]]), + }); + } match local(&g) { "Point" | "ElevatedPoint" => self.point(g, notes), "Curve" | "ElevatedCurve" | "LineString" => self.curve(g, notes).map(|c| Geometry::Line(vec![c])), @@ -1271,7 +1342,9 @@ fn nearest_on(line: &[Coord], p: Coord) -> Option<(usize, f64, Coord, f64)> { let mut best: Option<(usize, f64, Coord, f64)> = None; for (i, w) in line.windows(2).enumerate() { let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue }; - let (a, b) = (next_to(a, p.x), next_to(b, p.x)); + // The segment moved as one next to the point: its ends keep their short span across 180°. + let a = next_to(a, p.x); + let b = next_to(b, a.x); let (dx, dy) = ((b.x - a.x) * k, b.y - a.y); let len2 = dx * dx + dy * dy; let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; @@ -1403,6 +1476,14 @@ struct Layer { far: usize, /// Route segments drawn between the points they name. between: usize, + /// Features with an arc or circle not drawn: the point allowance ran out. + past_allowance: usize, + /// Route segments with no curve and a `pathType` RustGIS doesn't draw. + path_unread: usize, + /// Rows left out: the table they'd make passes the memory the file's size allows. + dense_over: usize, + /// Records holding no shape beside records of the same property that do: rows of their own. + unlocated: usize, /// Borders by reference followed whole. followed_whole: usize, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -1418,12 +1499,13 @@ struct Layer { impl Layer { /// A column's number, made when there is room for another; `None` (counted) past /// [`MAX_COLUMNS`]. - fn column(&mut self, name: &str) -> Option { + fn column(&mut self, name: &str, value: bool) -> Option { if let Some(&i) = self.named.get(name) { return Some(i); } + // Only a value past the cap is one not kept. if self.columns.len() >= MAX_COLUMNS { - self.capped += 1; + self.capped += usize::from(value); return None; } self.named.insert(name.to_string(), self.columns.len()); @@ -1447,6 +1529,8 @@ impl Layer { self.followed_whole += n.followed_whole; self.far += n.far; self.between += usize::from(n.between); + self.past_allowance += usize::from(n.past_allowance); + self.path_unread += usize::from(n.path_unread); self.border_allowance += n.border_allowance; self.border_unusable += n.border_unusable; } @@ -1498,12 +1582,12 @@ struct Row { impl Row { /// Names a column; false past [`MAX_COLUMNS`] names, when its value isn't kept (counted). - fn name(&mut self, key: &str) -> bool { + fn name(&mut self, key: &str, value: bool) -> bool { if self.named.contains(key) { return true; } if self.columns.len() >= MAX_COLUMNS { - self.capped += 1; + self.capped += usize::from(value); return false; } self.named.insert(key.to_string()); @@ -1553,7 +1637,7 @@ impl Row { } fn set(&mut self, key: &str, value: String) { - if !self.name(key) || !self.afford(key.len() + value.len()) { + if !self.name(key, true) || !self.afford(key.len() + value.len()) { return; } match self.attrs.get_mut(key) { @@ -1570,7 +1654,7 @@ impl Row { } fn null(&mut self, key: &str) { - let _ = self.name(key); + let _ = self.name(key, false); } /// A property's simple value as attributes, under `prefix`. @@ -1782,6 +1866,8 @@ struct Layers { list: Vec, /// Features of kinds past [`MAX_LAYERS`], by identifier. over: HashSet, + /// Only the layers' names are wanted: rows aren't kept. + names_only: bool, } impl Layers { @@ -1836,7 +1922,7 @@ impl Layers { layer.snapshots += usize::from(change.1); let mut attrs = Vec::with_capacity(row.attrs.len()); for c in &row.columns { - if let Some(k) = layer.column(c) + if let Some(k) = layer.column(c, row.attrs.contains_key(c)) && let Some(v) = row.attrs.get(c) { attrs.push((k, v.clone())); @@ -1845,6 +1931,9 @@ impl Layers { if let Some(n) = notes { layer.take_notes(n); } + if self.names_only { + return Some(i); + } layer.rows.push((geometry, attrs, row.paths)); Some(i) } @@ -1954,6 +2043,15 @@ fn scope_of( Some(scopes.len() - 1) } +/// What a change replaces a property by: its name, or for an `extension`, its name and the +/// namespace of the extension it holds (AIXM replaces extensions within their namespace). +fn property_key(p: Node) -> String { + match (local(&p), elements(p).next().and_then(|e| e.tag_name().namespace())) { + ("extension", Some(ns)) => format!("extension {ns}"), + (name, _) => name.to_string(), + } +} + /// How each member is parsed: no DTD, and the node limit every XML reader has. fn options<'a>() -> ParsingOptions<'a> { ParsingOptions { allow_dtd: false, nodes_limit: crate::io::XML_NODES, ..ParsingOptions::default() } @@ -1972,6 +2070,10 @@ fn projection<'a, 'i>(v: Option>) -> Option> { /// What the read says of the file as a whole. #[derive(Default)] struct FileNotes { + /// Slices with a sequence or correction number that isn't a number, read as 0. + bad_numbers: usize, + /// Features left out because a change in force at the date couldn't be read. + incomplete: usize, /// Time positions left empty without saying they are unknown, read as open. empty_dates: usize, /// Elements of members that aren't AIXM features. @@ -2081,9 +2183,16 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result Result Result> = vec![own(base_node)]; + let mut incomplete = false; for i in 1..wanted.len() { match node(i) { Some(n) => layers_of.push(own(n)), - None => { - notes.past_limits += 1; - layers_of.push(Vec::new()); - } + None => incomplete = true, } } - let mut last: HashMap<&str, usize> = HashMap::new(); + if incomplete { + notes.incomplete += 1; + continue; + } + // Extensions are replaced within their own namespace (each its own key). + let mut last: HashMap = HashMap::new(); for (i, ps) in layers_of.iter().enumerate() { for p in ps { - last.insert(local(p), i); + last.insert(property_key(*p), i); } } let last = &last; - let props: Vec = - layers_of.iter().enumerate().flat_map(|(i, ps)| ps.iter().copied().filter(move |p| last.get(local(p)) == Some(&i))).collect(); + let props: Vec = layers_of + .iter() + .enumerate() + .flat_map(|(i, ps)| ps.iter().copied().filter(move |p| last.get(&property_key(*p)) == Some(&i))) + .collect(); // A row being read keeps no more than the layers still may. let mut row = Row { limit: Some(layers.bytes_left), interned: std::rc::Rc::clone(&paths), ..Row::default() }; row.set("identifier", id.trim_start_matches("urn:uuid:").to_string()); @@ -2271,15 +2392,15 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Option<(Vec, ShapeNotes)> { +fn between(props: &[Node], shapes: &mut Shapes) -> Option<(Option>, ShapeNotes)> { // Both ends found first: a segment drawn neither way reads its ends' shapes once, as records. let (a, b) = (segment_end(props, "start", shapes)?, segment_end(props, "end", shapes)?); - let mut notes = ShapeNotes { between: true, ..ShapeNotes::default() }; let quiet = |end: &End, shapes: &mut Shapes| match end { End::Named(c) => Some(*c), End::Written(g) => match shapes.quietly(*g) { @@ -2288,14 +2409,25 @@ fn between(props: &[Node], shapes: &mut Shapes) -> Option<(Vec, ShapeNote }, }; let (ca, cb) = (quiet(&a, shapes)?, quiet(&b, shapes)?); + let mut notes = ShapeNotes { between: true, ..ShapeNotes::default() }; // Drawn from them: what the ends written in place find is said with the segment. for end in [&a, &b] { if let End::Written(g) = end { let _ = shapes.shape(*g, &mut notes); } } - let (a, b) = (ca, cb); - let line = shapes.geodesic(&[a, b], &mut notes); + // The path its pathType says: a geodesic (GDS, or a great circle, GRC, which the ellipsoid's + // geodesic is) by default, a rhumb line (RHL); another isn't drawn, and that is said. + let path = props.iter().find(|p| local(p) == "pathType").map(|p| text_of(p)).unwrap_or_default(); + let line = match path.as_str() { + "" | "GDS" | "GRC" => Some(shapes.geodesic(&[ca, cb], &mut notes)), + "RHL" => Some(shapes.rhumb(ca, cb, &mut notes)), + _ => { + notes.between = false; + notes.path_unread = true; + None + } + }; Some((line, notes)) } @@ -2349,11 +2481,23 @@ fn feature_rows( ) -> bool { let mut shaped: Vec<(String, Node)> = Vec::new(); let mut parts: Vec = Vec::new(); + let mut others: Vec = Vec::new(); for p in props { match shape_in(*p) { Some(g) if !is_nil(p) => shaped.push((local(p).to_string(), g)), _ if !is_nil(p) && p.attribute((XLINK, "href")).is_none() && !nested_shapes(*p).is_empty() => parts.push(*p), - _ => row.property(*p, ""), + _ => others.push(*p), + } + } + // A record with no shape of a property whose other records hold one (an unlocated light + // beside located ones) is a row of its own, not values on every located one's row. + let record_names: HashSet<&str> = if shaped.is_empty() { parts.iter().map(|p| local(p)).collect() } else { HashSet::new() }; + let mut unlocated: Vec = Vec::new(); + for p in others { + if record_names.contains(local(&p)) && !is_nil(&p) && elements(p).next().is_some() { + unlocated.push(p); + } else { + row.property(p, ""); } } let change = (temporary > 0, snapshot); @@ -2399,7 +2543,8 @@ fn feature_rows( for p in &parts { row.property(*p, ""); } - layers.push(kind, "curveExtent", Some(Geometry::Line(vec![line])), row.clone(), Some(¬es), change); + let line = line.map(|l| vec![l]); + layers.push(kind, "curveExtent", line.map(Geometry::Line), row.clone(), Some(¬es), change); return true; } if parts.is_empty() { @@ -2408,6 +2553,21 @@ fn feature_rows( // Rows copied for the records stay within what the file's size allows: checked before each // copy, as a vertical structure's parts are. let mut room = layers.bytes_left; + let first_label = parts.iter().flat_map(|p| nested_shapes(*p)).next().map_or("points", |g| element_family(local(&g))); + for p in unlocated { + if row.weight() > room { + layers.rows_over += 1; + continue; + } + let mut r = row.clone(); + let mut path = vec![(local(&p).to_string(), 1)]; + r.record(p, &mut path, false); + room = room.saturating_sub(r.weight()); + let i = layers.push(kind, first_label, None, r, None, (false, false)); + if let Some(l) = layers.at(i) { + l.unlocated += 1; + } + } let count = parts.len(); for (k, p) in parts.into_iter().enumerate() { if row.weight() > room { @@ -2507,6 +2667,10 @@ fn airspace( None => unreadable = true, } } + // Parts of different kinds (a line where a surface is meant) aren't one shape. + if parts.first().is_some_and(|f| parts.iter().any(|g| family(g) != family(f))) { + unreadable = true; + } if !unreadable { geom = merged(parts); } @@ -2606,6 +2770,9 @@ fn vertical_structure( } /// The layers as datasets, with what the read says. +/// What a row of a table holds besides its values (its shape's slot, its bookkeeping), in bytes. +const DENSE_ROW_OVERHEAD: usize = 64; + fn finish( stem: &str, at: f64, @@ -2614,6 +2781,7 @@ fn finish( index: &Index, budget_spent: bool, paths: &Paths, + dense_left: &mut usize, ) -> Result> { let mut file = ReadReport::default(); let say = |r: &mut ReadReport, n: usize, one: &str, many: &str, rest: &str| { @@ -2654,6 +2822,14 @@ fn finish( "time positions", "left empty (not said to be unknown) read as open: no start or no end", ); + say(&mut file, notes.bad_numbers, "time slice", "time slices", "with a sequence or correction number that isn't a number read as 0"); + say( + &mut file, + notes.incomplete, + "feature", + "features", + "left out: a change to it in force then couldn't be read within the limits the file's size sets", + ); say(&mut file, notes.bad_dates, "time slice", "time slices", "with a validTime or featureLifetime that isn't a date not read"); say( &mut file, @@ -2721,18 +2897,17 @@ fn finish( for (g, mut attrs, nested) in std::mem::take(&mut layer.rows) { for (id, value) in nested { let k = match column_of.get(&id) { - // A path past the cap: each of its values not kept is counted. - Some(None) => { - layer.capped += 1; - None - } Some(k) => *k, None => { - let k = paths.list.get(id).and_then(|p| layer.column(&path_column(p, &repeating))); + let k = paths.list.get(id).and_then(|p| layer.column(&path_column(p, &repeating), false)); column_of.insert(id, k); k } }; + // A value past the cap is counted, each one; a missing one isn't a loss. + if k.is_none() && value.is_some() { + layer.capped += 1; + } if let (Some(k), Some(v)) = (k, value) { attrs.push((k, v)); } @@ -2770,6 +2945,15 @@ fn finish( layer.columns.iter().zip(&values).map(|(c, vs)| Field::new(c.clone(), crate::io::text_type(vs.iter().copied()))).collect(); drop(values); let mut ds = Dataset::new(title, GeometryType::None, fields); + // The table holds a value for every column of every row: the rows that fit the memory the + // file's size allows are kept, and the rest counted. + let per_row = (ds.fields.len() * std::mem::size_of::()).max(1) + DENSE_ROW_OVERHEAD; + let fit = *dense_left / per_row; + if rows.len() > fit { + layer.dense_over += rows.len() - fit; + rows.truncate(fit); + } + *dense_left -= rows.len() * per_row; for (g, attrs) in rows { let mut row = vec![Value::Null; ds.fields.len()]; for (k, v) in attrs { @@ -2834,8 +3018,8 @@ fn finish( ); say( layer.rings_lost, - "ring or surface patch was left out: too few points, or unreadable", - "rings or surface patches were left out: too few points, or unreadable", + "ring or surface patch was left out (with the patch it is a hole of): too few points, or unreadable", + "rings or surface patches were left out (with the patches they are holes of): too few points, or unreadable", ); say( layer.referenced, @@ -2857,10 +3041,30 @@ fn finish( "border given by reference isn't followed: the GeoBorder it names has too few points to cut", "borders given by reference aren't followed: the GeoBorders they name have too few points to cut", ); + say( + layer.past_allowance, + "feature has an arc or circle that isn't drawn: the file's point allowance ran out", + "features have an arc or circle that isn't drawn: the file's point allowance ran out", + ); + say( + layer.path_unread, + "route segment with no curve isn't drawn: its pathType is one RustGIS doesn't draw", + "route segments with no curve aren't drawn: their pathType is one RustGIS doesn't draw", + ); + say( + layer.dense_over, + "row is left out: the table would pass the memory the file's size allows", + "rows are left out: the table would pass the memory the file's size allows", + ); + say( + layer.unlocated, + "record with no shape (beside ones of the same property that have one) is a row without a shape", + "records with no shape (beside ones of the same property that have one) are rows without a shape", + ); say( layer.between, - "route segment with no curve is drawn as a geodesic between the points its start and end name", - "route segments with no curve are drawn as geodesics between the points their start and end name", + "route segment with no curve is drawn between the points its start and end name, as its pathType says (a geodesic, or a rhumb line)", + "route segments with no curve are drawn between the points their start and end name, as their pathType says (geodesics, or rhumb lines)", ); say( layer.followed, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 12c34fe8da..bf93912df5 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -6,7 +6,7 @@ use super::*; const DONLON: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/donlon-aixm.xml")); fn at(date: &str) -> Options { - Options { at: crate::time::parse_text(date) } + Options { at: crate::time::parse_text(date), ..Options::default() } } fn layer<'a>(out: &'a [(Dataset, ReadReport)], name: &str) -> &'a Dataset { @@ -895,7 +895,7 @@ fn faa_route_segments_are_drawn_between_their_points_in_nad83() { assert!(parts[0].len() > 10, "drawn along the geodesic"); let notes = said(&out); for want in [ - "1 route segment with no curve is drawn as a geodesic between the points its start and end name", + "1 route segment with no curve is drawn between the points its start and end name", "2 geometries in a geographic system other than WGS 84", "2 time positions left empty (not said to be unknown) read as open", ] { @@ -1135,3 +1135,210 @@ fn a_ring_whose_borders_cant_be_joined_within_the_allowance_isnt_drawn_and_says_ assert!(shapes.surface(surface.root_element(), &mut notes).is_none()); assert_eq!((notes.followed, notes.border_allowance, notes.rings_lost), (0, 1, 0)); } + +// --------------------------------------------------------------------------------------------- +// From the review of PR #2819. +// --------------------------------------------------------------------------------------------- + +fn snapshot_at(date: &str, name: &str) -> String { + let valid = format!( + r#"{date}"# + ); + format!( + r#"{valid}SNAPSHOT{}"#, + named_point(name) + ) +} + +#[test] +fn snapshots_at_different_instants_are_all_kept() { + let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "JANUARY"), snapshot_at("2026-02-01T00:00:00Z", "FEBRUARY")])); + assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("JANUARY".into())]); + assert_eq!(names(&bytes, "2026-02-15").0, [Value::Text("FEBRUARY".into())]); +} + +#[test] +fn an_empty_valid_time_cancels_only_when_it_says_so() { + let unknown = slice("DesignatedPoint", "BASELINE", 1, 1, r#""#, &named_point("UNKNOWN")); + let members = point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]) + &point("b", &[unknown]); + let (got, notes) = names(&message(&members), "2026-01-15"); + assert_eq!(got, [Value::Text("KEPT".into())]); + assert!(notes.iter().any(|m| m.starts_with("1 time slice with a validTime or featureLifetime that isn't a date")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("canceled")), "{notes:?}"); +} + +#[test] +fn a_sequence_number_that_isnt_one_is_said() { + let s = baseline(1, 0, "2025-01-01T00:00:00Z", None, "A") + .replace("1", "one"); + let notes = names(&message(&point("a", &[s])), "2026-01-15").1; + assert!( + notes.iter().any(|m| m.starts_with("1 time slice with a sequence or correction number that isn't a number read as 0")), + "{notes:?}" + ); +} + +#[test] +fn features_of_two_kinds_sharing_an_identifier_are_both_read() { + let navaid = + feature("Navaid", "same", &[slice("Navaid", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &named_point("NAV"))]); + let out = + read("t.xml", &message(&(point("same", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "POINT")]) + &navaid)), &at("2026-01-15")) + .unwrap(); + assert_eq!(layer(&out, "t DesignatedPoint").features.len(), 1); + assert_eq!(layer(&out, "t Navaid").features.len(), 1); +} + +#[test] +fn a_permdelta_changes_an_open_baseline_from_its_instant() { + let valid = r#"2026-02-01T00:00:00Z"#; + let perm = slice("DesignatedPoint", "PERMDELTA", 2, 0, valid, "RENAMED"); + let bytes = message(&point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "ORIGINAL"), perm])); + assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("ORIGINAL".into())]); + let out = read("t.xml", &bytes, &at("2026-02-01")).unwrap(); + let ds = layer(&out, "t DesignatedPoint"); + assert_eq!(value(ds, 0, "name"), Value::Text("RENAMED".into())); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(-35.17, 45.71)))); +} + +#[test] +fn an_airspace_hole_that_cant_be_read_leaves_the_airspace_undrawn() { + let body = r#"HOLED50 9 50 11 52 11 52 9 50 9"#; + let bytes = message(&feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), body)])); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t WorkArea").features[0].geometry, None); + assert!(said(&out).iter().any(|m| m.contains("1 border is given by reference")), "{:?}", said(&out)); +} + +#[test] +fn a_border_segment_across_180_degrees_stays_whole() { + // An edge from 179 E to 179 W, and a point at Greenwich: nowhere near it. + let line = [Coord::new(179.0, 0.0), Coord::new(-179.0, 0.0)]; + let (.., d) = nearest_on(&line, Coord::new(0.0, 0.0)).unwrap(); + assert!(d > 19_000_000.0, "{d}"); + // And a point on it is on it. + let (.., d) = nearest_on(&line, Coord::new(180.0, 0.0)).unwrap(); + assert!(d < 1.0, "{d}"); +} + +#[test] +fn a_tempdelta_replaces_extensions_within_their_namespace() { + let ext = |ns: &str, value: &str| { + format!(r#"{value}"#) + }; + let base = slice( + "DesignatedPoint", + "BASELINE", + 1, + 0, + &period("2025-01-01T00:00:00Z", None), + &(named_point("P") + &ext("a", "A1") + &ext("b", "B1")), + ); + let temp = slice("DesignatedPoint", "TEMPDELTA", 1, 0, &period("2026-01-01T00:00:00Z", None), &ext("a", "A2")); + let out = read("t.xml", &message(&point("p", &[base, temp])), &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t DesignatedPoint"); + let all: Vec = + (0..ds.fields.len()).filter(|&k| ds.fields[k].name.starts_with("extension")).map(|k| ds.features[0].attrs[k].to_string()).collect(); + assert!( + all.iter().any(|v| v.contains("A2")) && all.iter().any(|v| v.contains("B1")) && !all.iter().any(|v| v.contains("A1")), + "{all:?}" + ); +} + +#[test] +fn a_route_segment_follows_its_path_type() { + let end = |name: &str, lat: f64, lon: f64| { + format!( + r#"{lat} {lon}"# + ) + }; + let segment = |path: &str| { + let body = format!("{path}{}{}", end("start", 60.0, 0.0), end("end", 60.0, 40.0)); + message(&feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])) + }; + let line = |path: &str| { + let out = read("t.xml", &segment(path), &at("2026-01-15")).unwrap(); + layer(&out, "t RouteSegment").features[0].geometry.clone() + }; + // A rhumb line along 60 N stays on it; a geodesic between the same points bows north. + let Some(Geometry::Line(rhl)) = line("RHL") else { panic!() }; + assert!(rhl[0].iter().all(|c| (c.y - 60.0).abs() < 1e-9)); + let Some(Geometry::Line(gds)) = line("GDS") else { panic!() }; + assert!(gds[0].iter().any(|c| c.y > 61.0)); + // A path type RustGIS doesn't draw: kept without a shape, and said. + let out = read("t.xml", &segment("OTHER"), &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t RouteSegment").features[0].geometry, None); + assert!(said(&out).iter().any(|m| m.contains("1 route segment with no curve isn't drawn: its pathType")), "{:?}", said(&out)); +} + +#[test] +fn an_unlocated_record_beside_located_ones_is_a_row_of_its_own() { + let light = |color: &str, at: &str| { + format!( + r#"{color}{at}"# + ) + }; + let located = r#"52 -32"#; + let body = light("RED", "") + &light("GREEN", located); + let bytes = message(&feature( + "RunwayDirectionLightSystem", + "l", + &[slice("RunwayDirectionLightSystem", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)], + )); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + let ds = layer(&out, "t RunwayDirectionLightSystem"); + assert_eq!(ds.features.len(), 2); + let green = row_where(ds, "element_colour", "GREEN"); + assert!(ds.features[green].geometry.is_some()); + let red = row_where(ds, "element_colour", "RED"); + assert_eq!(ds.features[red].geometry, None); + assert!(said(&out).iter().any(|m| m.contains("1 record with no shape")), "{:?}", said(&out)); +} + +#[test] +fn a_circle_past_the_point_allowance_isnt_drawn_and_says_so() { + let doc = format!( + r#"50 1010"# + ); + let doc = roxmltree::Document::parse(&doc).unwrap(); + let mut shapes = Shapes::default(); + let mut notes = ShapeNotes::default(); + assert!(shapes.shape(doc.root_element().first_element_child().unwrap(), &mut notes).is_none()); + assert!(notes.past_allowance); +} + +#[test] +fn an_airspace_of_a_surface_and_a_line_isnt_merged() { + let volume = |op: &str, seq: u32, shape: &str| { + format!( + r#"{op}{seq}{shape}"# + ) + }; + let surface = r#"50 10 50 11 51 11 51 10 50 10"#; + let curve = r#"52 10 52 11"#; + let body = format!("MIXED{}{}", volume("BASE", 1, surface), volume("UNION", 2, curve)); + let out = read( + "t.xml", + &message(&feature("Airspace", "a", &[slice("Airspace", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + assert_eq!(layer(&out, "t Airspace").features[0].geometry, None); + assert!(said(&out).iter().any(|m| m.contains("couldn't be read")), "{:?}", said(&out)); +} + +#[test] +fn an_effective_date_with_an_offset_past_a_day_is_refused() { + assert!(Options::at_text("2026-01-15T12:00+99:99").is_err()); + assert!(Options::at_text("2026-01-15T12:00+05:30").is_ok()); +} + +#[test] +fn layer_names_match_the_layers_read() { + let opts = at("2026-01-15"); + let mut read_names: Vec = read("donlon-aixm.xml", DONLON, &opts).unwrap().into_iter().map(|(d, _)| d.name).collect(); + let mut listed = layer_names("donlon-aixm.xml", DONLON, &opts).unwrap(); + read_names.sort(); + listed.sort(); + assert_eq!(listed, read_names); +} diff --git a/crates/data/src/time.rs b/crates/data/src/time.rs index 06fba78f2d..e0f37b51b6 100644 --- a/crates/data/src/time.rs +++ b/crates/data/src/time.rs @@ -287,6 +287,10 @@ pub fn parse_text(s: &str) -> Option { let sign = if zone.starts_with('-') { -1 } else { 1 }; let z = zone.get(1..)?.replace(':', ""); let (hh, mm) = (digits(z.get(..2)?, 2, 2)?, z.get(2..).filter(|r| !r.is_empty()).map(|r| digits(r, 2, 2)).unwrap_or(Some(0))?); + // An offset is at most 23:59 (real ones are within ±14:00): `+99:99` isn't one. + if hh > 23 || mm > 59 { + return None; + } offset_min = sign * (hh * 60 + mm); } } diff --git a/crates/data/src/xml.rs b/crates/data/src/xml.rs index 96559ed3ea..dcaed129af 100644 --- a/crates/data/src/xml.rs +++ b/crates/data/src/xml.rs @@ -362,18 +362,27 @@ mod tests { assert!(crate::georss::read("a.rss", &flood("rss")).is_err_and(|e| said(e.to_string()))); assert!(crate::landxml::read("a.xml", &flood("LandXML"), None).is_err_and(|e| said(e.to_string()))); assert!(crate::ogc::parse("https://x.example/wms", &flood("WMS_Capabilities")).is_err_and(|e| said(e.to_string()))); - // AIXM parses its members one at a time: each past the budget is counted, and with none - // read, nothing is added. - let aixm = format!( - "{}", - declarations(20_000), - "".repeat(50) - ); - let opts = crate::aixm::Options { at: Some(0.0) }; - assert!( - crate::aixm::read("a.xml", aixm.as_bytes(), &opts) - .is_err_and(|e| e.to_string().contains("couldn't be read") || e.to_string().contains("limits")) - ); + // AIXM parses its members one at a time: members that would be read are refused for their + // namespace work (counted as members that couldn't be read), not for running out of room + // to wrap them (which is said otherwise), and with none read, nothing is added. + let aixm = |declared: usize| { + format!( + "{}", + declarations(declared), + aixm_point("").repeat(5) + ) + }; + let opts = crate::aixm::Options { at: Some(0.0), ..Default::default() }; + assert!(crate::aixm::read("a.xml", aixm(0).as_bytes(), &opts).is_ok(), "the same members read without the flood"); + let e = crate::aixm::read("a.xml", aixm(20_000).as_bytes(), &opts).unwrap_err().to_string(); + assert!(e.contains("5 members of the message couldn't be read") && !e.contains("would pass the limits"), "{e}"); + } + + /// An AIXM message of one designated point (valid from 1960), `inner` in its time slice. + fn aixm_point(inner: &str) -> String { + format!( + r#"p1960-01-01T00:00:00ZBASELINE50 10{inner}"# + ) } /// Every XML reader refuses a deeply nested document instead of overflowing the stack, run on @@ -398,12 +407,19 @@ mod tests { assert!(crate::georss::read("a.rss", &deep("rss", "channel")).is_err()); assert!(crate::landxml::read("a.xml", &deep("LandXML", "Parcels"), None).is_err()); assert!(crate::ogc::parse("https://x.example/wms", &deep("WMS_Capabilities", "Layer")).is_err()); - let aixm = String::from_utf8(deep("message:AIXMBasicMessage", "message:hasMember")).unwrap_or_default().replacen( - "", - "", - 1, - ); - assert!(crate::aixm::read("a.xml", aixm.as_bytes(), &crate::aixm::Options { at: Some(0.0) }).is_err()); + // A point that reads with a few nested records is refused with ten thousand: the + // depth, not anything else, stops it. + let aixm = |depth: usize| { + let nested = format!("{}{}", "".repeat(depth), "".repeat(depth)); + format!( + "{}", + aixm_point(&nested) + ) + }; + let opts = crate::aixm::Options { at: Some(0.0), ..Default::default() }; + assert!(crate::aixm::read("a.xml", aixm(5).as_bytes(), &opts).is_ok()); + let e = crate::aixm::read("a.xml", aixm(10_000).as_bytes(), &opts).unwrap_err().to_string(); + assert!(e.contains("couldn't be read"), "{e}"); true }) .unwrap() diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5accb43cd..2d2534c9aa 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -3160,6 +3160,8 @@ fn apply_styles(s: &mut Session, id: u32, styles: &[(String, rustgis_data::kml:: /// layers, or the one layer of other files. `layer.addData` takes a name with `"layer"`. fn file_layers(s: &mut Session, p: &Value) -> CmdResult { let path = s_req(p, "path")?; + // An effective date is for an AIXM message only: refused for any other file, not ignored. + check_at(p, path, || may_be_aixm_path(path))?; let path = &*gdb_path(path); let err = |e: rustgis_data::DataError| format!("{path}: {e}"); // A geodatabase read without GDAL; through GDAL if it can't be and GDAL is installed. @@ -3230,9 +3232,14 @@ fn file_layers(s: &mut Session, p: &Value) -> CmdResult { return Err(rustgis_data::io::file_size_error(path, max)); } let bytes = rustgis_data::provenance::read(path).map_err(|e| format!("{path}: {e}"))?; - // An AIXM message's layers at the date asked, as Add Data would add them. - if let Some(reads) = aixm_reads(p, path, &bytes)? { - let layers: Vec = reads.into_iter().map(|l| l.dataset.name).collect(); + // An AIXM message's layers at the date asked, as Add Data would add them: their names + // only, without drawing their shapes or keeping their values. + if rustgis_data::io::is_aixm(path, &bytes) { + if ps(p, "crs").is_some_and(|c| !c.trim().is_empty()) { + return Err(format!("\"crs\" doesn't apply to {path}: an AIXM message names its own system (srsName)")); + } + let opts = check_at(p, path, || true)?; + let layers = rustgis_data::aixm::layer_names(path, &bytes, &opts).map_err(err)?; return Ok(json!({"count": layers.len(), "layers": layers})); } let zip = path.to_ascii_lowercase().ends_with(".zip"); @@ -5035,6 +5042,10 @@ pub(crate) fn fixed_download_urls(p: &Value) -> Option> { pub(crate) fn add_url(s: &mut Session, p: &Value) -> CmdResult { let owner = s.continuation()?; let url = ps(p, "url").map(str::trim).unwrap_or(""); + // An effective date is for an AIXM message only (`.xml`, `.gml`, or an address that doesn't + // say, whose contents are checked once fetched): refused for any other address, before it is + // opened in place or downloaded. + check_at(p, url, || address_extension(url).is_none_or(|e| e == "xml" || e == "gml"))?; let out = add_url_as_given(s, p).map_err(|e| crate::sources::message_with_address(url, &e))?; s.check_continuation(&owner)?; Ok(out) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 95f4e367c1..c8fd7f256b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24168,6 +24168,17 @@ fn aixm_messages_are_added_at_the_date_asked() { s.notices.clear(); s.run("layer.addData", &json!({"path": picked.display().to_string(), "layer": "picked Runway", "at": "2026-01-15"})).unwrap(); assert!(s.notices.iter().any(|n| n.text.contains("1 feature not in force")), "{:?}", s.notices); + // Listed by name at the date asked, as Add Data would add them; "at" refused for any other file + // listed, and for an address that can't be a message, before it is opened. + let listed = s.run("info.fileLayers", &json!({"path": path.display().to_string(), "at": "2026-01-15"})).unwrap(); + let names: Vec<&str> = listed["layers"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect(); + assert!(names.contains(&"donlon Airspace") && names.contains(&"donlon Runway"), "{names:?}"); + let csv = dir.join("points.csv"); + std::fs::write(&csv, "x,y\n1,2\n").unwrap(); + let e = s.run("info.fileLayers", &json!({"path": csv.display().to_string(), "at": "2026-01-15"})).unwrap_err(); + assert!(e.contains("isn't one"), "{e}"); + let e = s.run("layer.addUrl", &json!({"url": "https://example.com/roads.fgb", "at": "2026-01-15"})).unwrap_err(); + assert!(e.contains("isn't one"), "{e}"); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f293bd17c5..bff3914068 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -6052,6 +6052,11 @@ impl RustGisApp { q[k] = v.clone(); } } + // An effective date given as anything but text is passed on, for the command to refuse + // rather than the import to go on without it. + if let Some(v) = p.get("at").filter(|v| !v.is_null() && !v.is_string()) { + q["at"] = v.clone(); + } // A PDF's page may be given as a number too (#2336): any other value is passed on as // given, for `layer.addDownload` to refuse rather than open the first page. if let Some(v) = p.get("layer").filter(|v| !v.is_null() && !v.is_string()) { From 888e64ee2060654a3b2131be8835b9608ed3291f Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:15:49 -0600 Subject: [PATCH 24/61] fix(data): AIXM review findings: rhumb lines near the poles, three-point circles, patches lost to holes counted, records of drawn route segments kept; "at" refused before a download --- crates/data/src/aixm.rs | 52 +++++++++++++++++++++------------- crates/data/src/aixm/tests.rs | 45 +++++++++++++++++++++++++++++ crates/engine/src/cmd/layer.rs | 10 +++++++ crates/ui-egui/src/lib.rs | 8 ++++++ 4 files changed, 95 insertions(+), 20 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 9f19332cea..88d9f4f868 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -557,11 +557,11 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }); trouble.empty += empty.get(); let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); - trouble.numbers += usize::from(unread_number.get()); if bad { trouble.dates += 1; return None; } + trouble.numbers += usize::from(unread_number.get()); Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime }) } @@ -809,7 +809,8 @@ impl Shapes { "Arc" | "ArcString" | "Circle" => { notes.arcs = true; let c = Self::positions(s, axes, notes)?; - Some(self.arcs_through(&c, local(&s) == "Circle", notes)) + let drawn = self.arcs_through(&c, local(&s) == "Circle", notes); + (!drawn.is_empty()).then_some(drawn) } other => { if !notes.unread_segments.iter().any(|n| n == other) { @@ -856,17 +857,23 @@ impl Shapes { /// [`GEODESIC_STEP_M`] at most, from the same allowance as geodesics. fn rhumb(&mut self, a: Coord, b: Coord, notes: &mut ShapeNotes) -> Vec { let b = next_to(b, a.x); - let merc = |lat: f64| (std::f64::consts::FRAC_PI_4 + lat.to_radians().clamp(-1.5, 1.5) / 2.0).tan().ln(); + let pole = std::f64::consts::FRAC_PI_2 - 1e-9; + let merc = |lat: f64| (std::f64::consts::FRAC_PI_4 + lat.to_radians().clamp(-pole, pole) / 2.0).tan().ln(); let (ya, yb) = (merc(a.y), merc(b.y)); let d = rustgis_geom::wgs84_distance_m(a, b); let need = if d.is_finite() { (d / GEODESIC_STEP_M).ceil() as usize } else { 1 }; notes.coarse |= need > MAX_GEODESIC_POINTS; let n = self.take(need.clamp(1, MAX_GEODESIC_POINTS).saturating_sub(1), notes) + 1; + // Its ends are the points named, exactly; the points between are on the rhumb line. (0..=n) - .map(|k| { - let t = k as f64 / n as f64; - let y = ya + (yb - ya) * t; - Coord::new(a.x + (b.x - a.x) * t, (2.0 * y.exp().atan() - std::f64::consts::FRAC_PI_2).to_degrees()) + .map(|k| match k { + 0 => a, + _ if k == n => b, + _ => { + let t = k as f64 / n as f64; + let y = ya + (yb - ya) * t; + Coord::new(a.x + (b.x - a.x) * t, (2.0 * y.exp().atan() - std::f64::consts::FRAC_PI_2).to_degrees()) + } }) .collect() } @@ -986,6 +993,11 @@ impl Shapes { if ccw { s } else { s - tau } }; let n = self.pieces(r, sweep.to_degrees(), notes); + // A full circle in fewer than three pieces isn't one: not drawn, and said. + if circle && n < 3 { + notes.past_allowance = true; + return Vec::new(); + } (0..=n) .map(|k| { let t = a0 + sweep * k as f64 / n as f64; @@ -1235,7 +1247,7 @@ impl Shapes { let mut polys = Vec::new(); for p in patches { // A ring lost to a border by reference is said as that, once. - let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable; + let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable + usize::from(n.past_allowance); let before = said(notes); let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, notes)); let Some(outer) = outer else { @@ -1247,16 +1259,15 @@ impl Shapes { let mut rings = vec![outer]; let mut hole_lost = false; for b in elements(p).filter(|c| local(c) == "interior") { - let before = said(notes); match self.ring(b, notes) { Some(r) => rings.push(r), - None => { - notes.rings_lost += usize::from(said(notes) == before); - hole_lost = true; - } + None => hole_lost = true, } } - if !hole_lost { + // The patch left out for its hole is counted, whatever lost the hole (said too). + if hole_lost { + notes.rings_lost += 1; + } else { polys.push(rings); } } @@ -1514,8 +1525,9 @@ impl Layer { } fn take_notes(&mut self, n: &ShapeNotes) { - self.arcs += usize::from(n.arcs); - self.coarse += usize::from(n.coarse); + // A circle not drawn for the point allowance is said as that alone. + self.arcs += usize::from(n.arcs && !n.past_allowance); + self.coarse += usize::from(n.coarse && !n.past_allowance); self.zm += usize::from(n.zm); if !n.unread_segments.is_empty() { self.approximated += 1; @@ -1911,7 +1923,7 @@ impl Layers { return None; } let Some(i) = self.index_of(kind, label) else { - self.over.insert(row.attrs.get("identifier").cloned().unwrap_or_default()); + self.over.insert(format!("{kind}\u{1}{}", row.attrs.get("identifier").map_or("", String::as_str))); return None; }; self.bytes_left -= cells; @@ -2522,7 +2534,7 @@ fn feature_rows( let empty = !g.descendants().any(|d| d.is_element() && is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()); let empty = empty && geom.is_none(); - let bad = geom.is_none() && !empty; + let bad = geom.is_none() && !empty && !notes.past_allowance; let i = layers.push(kind, &name, geom, r, Some(¬es), change); first = first.or(i); if let Some(l) = layers.at(i) { @@ -2540,7 +2552,7 @@ fn feature_rows( if kind == "RouteSegment" && let Some((line, notes)) = between(props, shapes) { - for p in &parts { + for p in parts.iter().chain(&unlocated) { row.property(*p, ""); } let line = line.map(|l| vec![l]); @@ -2692,7 +2704,7 @@ fn airspace( l.derived_names.add(op); } } - } else if unreadable { + } else if unreadable && !notes.past_allowance { l.unreadable += 1; } else if components.len() > 1 { l.unions += 1; diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index bf93912df5..8fdc285b62 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1342,3 +1342,48 @@ fn layer_names_match_the_layers_read() { listed.sort(); assert_eq!(listed, read_names); } + +#[test] +fn a_rhumb_line_near_a_pole_ends_at_its_points() { + let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; + let mut notes = ShapeNotes::default(); + let (a, b) = (Coord::new(0.0, 88.0), Coord::new(20.0, 88.0)); + let line = shapes.rhumb(a, b, &mut notes); + assert_eq!((line.first(), line.last()), (Some(&a), Some(&b))); + assert!(line.iter().all(|c| (c.y - 88.0).abs() < 1e-6), "{line:?}"); +} + +#[test] +fn a_three_point_circle_past_the_allowance_isnt_drawn_and_says_so() { + let mut shapes = Shapes::default(); + let mut notes = ShapeNotes::default(); + let drawn = shapes.arcs_through(&[Coord::new(10.0, 50.0), Coord::new(10.1, 50.1), Coord::new(10.2, 50.0)], true, &mut notes); + assert!(drawn.is_empty()); + assert!(notes.past_allowance); +} + +#[test] +fn a_patch_left_out_for_its_hole_is_counted_beside_the_holes_reason() { + let patch = |hole: &str| { + format!( + r#"50 9 50 11 52 11 52 9 50 9{hole}"# + ) + }; + let hole = r#""#; + let body = format!( + r#"TWO{}{}"#, + patch(hole), + patch("") + ); + let out = read( + "t.xml", + &message(&feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + let Some(Geometry::Polygon(parts)) = &layer(&out, "t WorkArea").features[0].geometry else { panic!("not drawn") }; + assert_eq!(parts.len(), 1); + let notes = said(&out); + assert!(notes.iter().any(|m| m.contains("1 ring or surface patch was left out")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("1 border is given by reference")), "{notes:?}"); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 2d2534c9aa..5602dc85ed 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2348,6 +2348,14 @@ pub(crate) fn check_at(p: &Value, file_name: &str, aixm: impl FnOnce() -> bool) rustgis_data::aixm::Options::at_text(at) } +/// Refuses an effective date (`"at"`) for an address that can't be an AIXM message (one naming +/// another kind of file), before anything is downloaded: what `layer.addUrl` does, for the app's +/// own way of adding an address. +pub fn check_url_at(p: &Value) -> Result<(), String> { + let url = ps(p, "url").map(str::trim).unwrap_or(""); + check_at(p, url, || address_extension(url).is_none_or(|e| e == "xml" || e == "gml")).map(|_| ()) +} + /// Whether a file named `path` may be an AIXM message: by its first bytes on the desktop, by its /// name in the browser (where its contents are checked when read). fn may_be_aixm_path(path: &str) -> bool { @@ -3234,6 +3242,8 @@ fn file_layers(s: &mut Session, p: &Value) -> CmdResult { let bytes = rustgis_data::provenance::read(path).map_err(|e| format!("{path}: {e}"))?; // An AIXM message's layers at the date asked, as Add Data would add them: their names // only, without drawing their shapes or keeping their values. + // Told by its name before it was read (in the browser): now by its contents. + check_at(p, path, || rustgis_data::io::is_aixm(path, &bytes))?; if rustgis_data::io::is_aixm(path, &bytes) { if ps(p, "crs").is_some_and(|c| !c.trim().is_empty()) { return Err(format!("\"crs\" doesn't apply to {path}: an AIXM message names its own system (srsName)")); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bff3914068..2ab7aa7d5b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5913,6 +5913,14 @@ impl RustGisApp { if let Some(id) = claim { self.session.download_continues(id)?; } + // An effective date for an address that can't be an AIXM message is refused before the + // download, not after it. + if let Err(e) = rustgis_engine::cmd::layer::check_url_at(p) { + if let Some(id) = claim { + self.session.download_failed(id); + } + return Err(e); + } let still = claim.and_then(|id| self.session.download_still(id)); rustgis_engine::render::rustgis_tiles::cache::with_optional_still(still, || { if p.get("geolibreZarr").and_then(Value::as_bool) == Some(true) { From 2e25c33a28e31b93789368e3fac32227e3b3e555 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:24:19 -0600 Subject: [PATCH 25/61] fix(data): AIXM point-allowance losses counted per part; no notice suppressed; empty arc segments don't stop a curve --- crates/data/src/aixm.rs | 52 +++++++++++++++++++++-------------- crates/data/src/aixm/tests.rs | 4 +-- 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 88d9f4f868..3ccda22934 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -555,13 +555,13 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }); (from, until) }); - trouble.empty += empty.get(); let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); if bad { trouble.dates += 1; return None; } trouble.numbers += usize::from(unread_number.get()); + trouble.empty += empty.get(); Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime }) } @@ -621,8 +621,9 @@ struct ShapeNotes { followed_whole: usize, /// A route segment drawn between the points it names, having no curve. between: bool, - /// An arc or circle not drawn: the file's point allowance ran out. - past_allowance: bool, + /// Arcs or circles not drawn: the file's point allowance ran out (a count, so each part read + /// can tell whether it was one of them). + past_allowance: usize, /// A route segment with no curve and a `pathType` RustGIS doesn't draw. path_unread: bool, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -686,7 +687,7 @@ impl ShapeNotes { self.border_allowance += o.border_allowance; self.border_unusable += o.border_unusable; self.between |= o.between; - self.past_allowance |= o.past_allowance; + self.past_allowance += o.past_allowance; self.path_unread |= o.path_unread; } } @@ -809,8 +810,9 @@ impl Shapes { "Arc" | "ArcString" | "Circle" => { notes.arcs = true; let c = Self::positions(s, axes, notes)?; + let before = notes.past_allowance; let drawn = self.arcs_through(&c, local(&s) == "Circle", notes); - (!drawn.is_empty()).then_some(drawn) + (notes.past_allowance == before).then_some(drawn) } other => { if !notes.unread_segments.iter().any(|n| n == other) { @@ -923,7 +925,7 @@ impl Shapes { let n = self.pieces(radius, sweep, notes); // A full circle in fewer than three pieces isn't one: not drawn, and said. if sweep.abs() >= 360.0 && n < 3 { - notes.past_allowance = true; + notes.past_allowance += 1; return None; } let mut out = Vec::with_capacity(n + 1); @@ -995,7 +997,7 @@ impl Shapes { let n = self.pieces(r, sweep.to_degrees(), notes); // A full circle in fewer than three pieces isn't one: not drawn, and said. if circle && n < 3 { - notes.past_allowance = true; + notes.past_allowance += 1; return Vec::new(); } (0..=n) @@ -1247,7 +1249,7 @@ impl Shapes { let mut polys = Vec::new(); for p in patches { // A ring lost to a border by reference is said as that, once. - let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable + usize::from(n.past_allowance); + let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable + n.past_allowance; let before = said(notes); let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, notes)); let Some(outer) = outer else { @@ -1525,9 +1527,8 @@ impl Layer { } fn take_notes(&mut self, n: &ShapeNotes) { - // A circle not drawn for the point allowance is said as that alone. - self.arcs += usize::from(n.arcs && !n.past_allowance); - self.coarse += usize::from(n.coarse && !n.past_allowance); + self.arcs += usize::from(n.arcs); + self.coarse += usize::from(n.coarse); self.zm += usize::from(n.zm); if !n.unread_segments.is_empty() { self.approximated += 1; @@ -1541,7 +1542,7 @@ impl Layer { self.followed_whole += n.followed_whole; self.far += n.far; self.between += usize::from(n.between); - self.past_allowance += usize::from(n.past_allowance); + self.past_allowance += usize::from(n.past_allowance > 0); self.path_unread += usize::from(n.path_unread); self.border_allowance += n.border_allowance; self.border_unusable += n.border_unusable; @@ -1923,7 +1924,11 @@ impl Layers { return None; } let Some(i) = self.index_of(kind, label) else { - self.over.insert(format!("{kind}\u{1}{}", row.attrs.get("identifier").map_or("", String::as_str))); + let next = self.over.len(); + match row.attrs.get("identifier").filter(|i| !i.is_empty()) { + Some(id) => self.over.insert(format!("{kind}\u{1}{id}")), + None => self.over.insert(format!("{kind}\u{1}#{next}")), + }; return None; }; self.bytes_left -= cells; @@ -2525,6 +2530,7 @@ fn feature_rows( for (name, g) in shaped { let mut notes = ShapeNotes::default(); let geom = shapes.shape(g, &mut notes); + let refused = notes.past_allowance > 0; let mut r = row.clone(); r.shape_values(g, &name); // A kind's shapes under different properties are different layers (an airport's @@ -2534,7 +2540,7 @@ fn feature_rows( let empty = !g.descendants().any(|d| d.is_element() && is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()); let empty = empty && geom.is_none(); - let bad = geom.is_none() && !empty && !notes.past_allowance; + let bad = geom.is_none() && !empty && !refused; let i = layers.push(kind, &name, geom, r, Some(¬es), change); first = first.or(i); if let Some(l) = layers.at(i) { @@ -2602,7 +2608,8 @@ fn feature_rows( // What the feature was is said once for it, with its first row. let change = if k == 0 { change } else { (false, false) }; for (label, (gs, notes)) in by_family { - let bad = gs.is_empty(); + // Lost to the point allowance is said as that, not as unreadable. + let bad = gs.is_empty() && notes.past_allowance == 0; let i = layers.push(kind, label, merged(gs), r.clone(), Some(¬es), change); if let Some(l) = layers.at(i) { l.unreadable += usize::from(bad); @@ -2670,12 +2677,15 @@ fn airspace( } let drawable = components.iter().all(|(_, op, v)| matches!(op.as_str(), "BASE" | "UNION") && projection(*v).is_some()); let mut geom = None; - let mut unreadable = false; + // A part not drawn: unreadable, or lost to the point allowance (said as that). + let (mut unreadable, mut refused) = (false, false); if drawable { let mut parts = Vec::new(); for (_, _, v) in &components { + let before = notes.past_allowance; match projection(*v).and_then(|g| shapes.shape(g, notes)) { Some(g) => parts.push(g), + None if notes.past_allowance > before => refused = true, None => unreadable = true, } } @@ -2683,7 +2693,7 @@ fn airspace( if parts.first().is_some_and(|f| parts.iter().any(|g| family(g) != family(f))) { unreadable = true; } - if !unreadable { + if !unreadable && !refused { geom = merged(parts); } } @@ -2704,8 +2714,10 @@ fn airspace( l.derived_names.add(op); } } - } else if unreadable && !notes.past_allowance { + } else if unreadable { l.unreadable += 1; + } else if refused { + // Said by the allowance's own notice. } else if components.len() > 1 { l.unions += 1; } @@ -3055,8 +3067,8 @@ fn finish( ); say( layer.past_allowance, - "feature has an arc or circle that isn't drawn: the file's point allowance ran out", - "features have an arc or circle that isn't drawn: the file's point allowance ran out", + "feature has an arc or circle that isn't drawn, nor the ring or patch it bounds: the file's point allowance ran out", + "features have an arc or circle that isn't drawn, nor the ring or patch it bounds: the file's point allowance ran out", ); say( layer.path_unread, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 8fdc285b62..03e904b3ae 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1304,7 +1304,7 @@ fn a_circle_past_the_point_allowance_isnt_drawn_and_says_so() { let mut shapes = Shapes::default(); let mut notes = ShapeNotes::default(); assert!(shapes.shape(doc.root_element().first_element_child().unwrap(), &mut notes).is_none()); - assert!(notes.past_allowance); + assert_eq!(notes.past_allowance, 1); } #[test] @@ -1359,7 +1359,7 @@ fn a_three_point_circle_past_the_allowance_isnt_drawn_and_says_so() { let mut notes = ShapeNotes::default(); let drawn = shapes.arcs_through(&[Coord::new(10.0, 50.0), Coord::new(10.1, 50.1), Coord::new(10.2, 50.0)], true, &mut notes); assert!(drawn.is_empty()); - assert!(notes.past_allowance); + assert_eq!(notes.past_allowance, 1); } #[test] From 704dc74df70a045bc0f812eb6b347ef13ee98d21 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:33:01 -0600 Subject: [PATCH 26/61] fix(data): AIXM full circles keep eight points past the point allowance instead of being refused; arcs with too few positions said; features past the layer cap counted by feature --- crates/data/src/aixm.rs | 70 ++++++++++++++--------------------- crates/data/src/aixm/tests.rs | 37 +++++++++++++++--- 2 files changed, 59 insertions(+), 48 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 3ccda22934..fc4f0fb536 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -621,9 +621,8 @@ struct ShapeNotes { followed_whole: usize, /// A route segment drawn between the points it names, having no curve. between: bool, - /// Arcs or circles not drawn: the file's point allowance ran out (a count, so each part read - /// can tell whether it was one of them). - past_allowance: usize, + /// An arc given fewer than the three positions it needs, drawn straight between them. + short_arcs: bool, /// A route segment with no curve and a `pathType` RustGIS doesn't draw. path_unread: bool, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -687,7 +686,7 @@ impl ShapeNotes { self.border_allowance += o.border_allowance; self.border_unusable += o.border_unusable; self.between |= o.between; - self.past_allowance += o.past_allowance; + self.short_arcs |= o.short_arcs; self.path_unread |= o.path_unread; } } @@ -810,9 +809,10 @@ impl Shapes { "Arc" | "ArcString" | "Circle" => { notes.arcs = true; let c = Self::positions(s, axes, notes)?; - let before = notes.past_allowance; - let drawn = self.arcs_through(&c, local(&s) == "Circle", notes); - (notes.past_allowance == before).then_some(drawn) + if c.is_empty() { + return None; + } + Some(self.arcs_through(&c, local(&s) == "Circle", notes)) } other => { if !notes.unread_segments.iter().any(|n| n == other) { @@ -886,7 +886,10 @@ impl Shapes { let need = (sweep_deg.abs() / step.max(1e-6)).ceil() as usize; notes.coarse |= need > MAX_ARC_POINTS; let want = need.clamp(4, MAX_ARC_POINTS); - self.take(want - 1, notes) + 1 + // A full circle keeps at least 8 pieces past the allowance (said as coarse): each circle + // in the text is far longer than 8 points, so the extra stays bounded by the file's size. + let floor = if sweep_deg.abs() >= 360.0 { 8 } else { 1 }; + (self.take(want - 1, notes) + 1).max(floor) } /// An `ArcByCenterPoint` or `CircleByCenterPoint`. @@ -923,11 +926,6 @@ impl Shapes { _ => return None, }; let n = self.pieces(radius, sweep, notes); - // A full circle in fewer than three pieces isn't one: not drawn, and said. - if sweep.abs() >= 360.0 && n < 3 { - notes.past_allowance += 1; - return None; - } let mut out = Vec::with_capacity(n + 1); for k in 0..=n { let (p, _) = rustgis_geom::wgs84_direct(center, bearing0 + sweep * k as f64 / n as f64, radius); @@ -943,6 +941,7 @@ impl Shapes { /// starting at the last's end), or a full circle through three (`Circle`). fn arcs_through(&mut self, c: &[Coord], circle: bool, notes: &mut ShapeNotes) -> Vec { if c.len() < 3 { + notes.short_arcs = true; return c.to_vec(); } let mut out: Vec = Vec::new(); @@ -995,11 +994,6 @@ impl Shapes { if ccw { s } else { s - tau } }; let n = self.pieces(r, sweep.to_degrees(), notes); - // A full circle in fewer than three pieces isn't one: not drawn, and said. - if circle && n < 3 { - notes.past_allowance += 1; - return Vec::new(); - } (0..=n) .map(|k| { let t = a0 + sweep * k as f64 / n as f64; @@ -1249,7 +1243,7 @@ impl Shapes { let mut polys = Vec::new(); for p in patches { // A ring lost to a border by reference is said as that, once. - let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable + n.past_allowance; + let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable; let before = said(notes); let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, notes)); let Some(outer) = outer else { @@ -1490,7 +1484,7 @@ struct Layer { /// Route segments drawn between the points they name. between: usize, /// Features with an arc or circle not drawn: the point allowance ran out. - past_allowance: usize, + short_arcs: usize, /// Route segments with no curve and a `pathType` RustGIS doesn't draw. path_unread: usize, /// Rows left out: the table they'd make passes the memory the file's size allows. @@ -1542,7 +1536,7 @@ impl Layer { self.followed_whole += n.followed_whole; self.far += n.far; self.between += usize::from(n.between); - self.past_allowance += usize::from(n.past_allowance > 0); + self.short_arcs += usize::from(n.short_arcs); self.path_unread += usize::from(n.path_unread); self.border_allowance += n.border_allowance; self.border_unusable += n.border_unusable; @@ -1879,6 +1873,8 @@ struct Layers { list: Vec, /// Features of kinds past [`MAX_LAYERS`], by identifier. over: HashSet, + /// The feature being read (its kind and identifier): what `over` counts. + feature: String, /// Only the layers' names are wanted: rows aren't kept. names_only: bool, } @@ -1924,11 +1920,7 @@ impl Layers { return None; } let Some(i) = self.index_of(kind, label) else { - let next = self.over.len(); - match row.attrs.get("identifier").filter(|i| !i.is_empty()) { - Some(id) => self.over.insert(format!("{kind}\u{1}{id}")), - None => self.over.insert(format!("{kind}\u{1}#{next}")), - }; + self.over.insert(self.feature.clone()); return None; }; self.bytes_left -= cells; @@ -2252,9 +2244,10 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0; let mut r = row.clone(); r.shape_values(g, &name); // A kind's shapes under different properties are different layers (an airport's @@ -2540,7 +2532,7 @@ fn feature_rows( let empty = !g.descendants().any(|d| d.is_element() && is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()); let empty = empty && geom.is_none(); - let bad = geom.is_none() && !empty && !refused; + let bad = geom.is_none() && !empty; let i = layers.push(kind, &name, geom, r, Some(¬es), change); first = first.or(i); if let Some(l) = layers.at(i) { @@ -2608,8 +2600,7 @@ fn feature_rows( // What the feature was is said once for it, with its first row. let change = if k == 0 { change } else { (false, false) }; for (label, (gs, notes)) in by_family { - // Lost to the point allowance is said as that, not as unreadable. - let bad = gs.is_empty() && notes.past_allowance == 0; + let bad = gs.is_empty(); let i = layers.push(kind, label, merged(gs), r.clone(), Some(¬es), change); if let Some(l) = layers.at(i) { l.unreadable += usize::from(bad); @@ -2677,15 +2668,12 @@ fn airspace( } let drawable = components.iter().all(|(_, op, v)| matches!(op.as_str(), "BASE" | "UNION") && projection(*v).is_some()); let mut geom = None; - // A part not drawn: unreadable, or lost to the point allowance (said as that). - let (mut unreadable, mut refused) = (false, false); + let mut unreadable = false; if drawable { let mut parts = Vec::new(); for (_, _, v) in &components { - let before = notes.past_allowance; match projection(*v).and_then(|g| shapes.shape(g, notes)) { Some(g) => parts.push(g), - None if notes.past_allowance > before => refused = true, None => unreadable = true, } } @@ -2693,7 +2681,7 @@ fn airspace( if parts.first().is_some_and(|f| parts.iter().any(|g| family(g) != family(f))) { unreadable = true; } - if !unreadable && !refused { + if !unreadable { geom = merged(parts); } } @@ -2716,8 +2704,6 @@ fn airspace( } } else if unreadable { l.unreadable += 1; - } else if refused { - // Said by the allowance's own notice. } else if components.len() > 1 { l.unions += 1; } @@ -3066,9 +3052,9 @@ fn finish( "borders given by reference aren't followed: the GeoBorders they name have too few points to cut", ); say( - layer.past_allowance, - "feature has an arc or circle that isn't drawn, nor the ring or patch it bounds: the file's point allowance ran out", - "features have an arc or circle that isn't drawn, nor the ring or patch it bounds: the file's point allowance ran out", + layer.short_arcs, + "feature has an arc given fewer than the three positions it needs, drawn straight between them", + "features have an arc given fewer than the three positions it needs, drawn straight between them", ); say( layer.path_unread, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 03e904b3ae..e552cccae8 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1296,15 +1296,16 @@ fn an_unlocated_record_beside_located_ones_is_a_row_of_its_own() { } #[test] -fn a_circle_past_the_point_allowance_isnt_drawn_and_says_so() { +fn a_circle_past_the_point_allowance_keeps_eight_points_and_says_so() { let doc = format!( r#"50 1010"# ); let doc = roxmltree::Document::parse(&doc).unwrap(); let mut shapes = Shapes::default(); let mut notes = ShapeNotes::default(); - assert!(shapes.shape(doc.root_element().first_element_child().unwrap(), &mut notes).is_none()); - assert_eq!(notes.past_allowance, 1); + let Some(Geometry::Line(l)) = shapes.shape(doc.root_element().first_element_child().unwrap(), &mut notes) else { panic!("not drawn") }; + assert_eq!(l[0].len(), 9); + assert!(notes.coarse); } #[test] @@ -1354,12 +1355,36 @@ fn a_rhumb_line_near_a_pole_ends_at_its_points() { } #[test] -fn a_three_point_circle_past_the_allowance_isnt_drawn_and_says_so() { +fn a_three_point_circle_past_the_allowance_keeps_eight_points_and_says_so() { let mut shapes = Shapes::default(); let mut notes = ShapeNotes::default(); let drawn = shapes.arcs_through(&[Coord::new(10.0, 50.0), Coord::new(10.1, 50.1), Coord::new(10.2, 50.0)], true, &mut notes); - assert!(drawn.is_empty()); - assert_eq!(notes.past_allowance, 1); + assert_eq!(drawn.len(), 9); + assert!(notes.coarse); +} + +#[test] +fn an_arc_with_too_few_positions_is_drawn_straight_and_said_and_none_is_unreadable() { + let curve = |arc: &str| { + format!( + r#"C50 10 50 11{arc}"# + ) + }; + let run = |arc: &str| { + let bytes = message(&feature( + "RouteSegment", + "r", + &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &curve(arc))], + )); + read("t.xml", &bytes, &at("2026-01-15")).unwrap() + }; + let out = run("50 11 51 11"); + assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some()); + assert!(said(&out).iter().any(|m| m.contains("1 feature has an arc given fewer than the three positions")), "{:?}", said(&out)); + let out = run("50 11 50.5 11.5 51 11"); + assert!(!said(&out).iter().any(|m| m.contains("fewer than the three positions")), "{:?}", said(&out)); + let out = run(""); + assert_eq!(layer(&out, "t RouteSegment").features[0].geometry, None); } #[test] From 2bbf0cb51ae0543e965795a7ededb6e125a40133 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:43:31 -0600 Subject: [PATCH 27/61] fix(data): AIXM empty arcs skipped and said, circles past three positions and arcs drawn straight said, the circle floor charged and only when short, shapeless rows counted by their own feature --- crates/data/src/aixm.rs | 47 +++++++++++++++++++++++++---------- crates/data/src/aixm/tests.rs | 31 ++++++++++++++++++++--- 2 files changed, 62 insertions(+), 16 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index fc4f0fb536..37c62c85f9 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -621,8 +621,11 @@ struct ShapeNotes { followed_whole: usize, /// A route segment drawn between the points it names, having no curve. between: bool, - /// An arc given fewer than the three positions it needs, drawn straight between them. + /// An arc or circle not given the three positions it needs (fewer, or a circle given more): + /// drawn through the positions it has, or the first three. short_arcs: bool, + /// An arc or circle whose points are in a line, or past the largest radius: drawn straight. + straight_arcs: bool, /// A route segment with no curve and a `pathType` RustGIS doesn't draw. path_unread: bool, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -687,6 +690,7 @@ impl ShapeNotes { self.border_unusable += o.border_unusable; self.between |= o.between; self.short_arcs |= o.short_arcs; + self.straight_arcs |= o.straight_arcs; self.path_unread |= o.path_unread; } } @@ -809,9 +813,6 @@ impl Shapes { "Arc" | "ArcString" | "Circle" => { notes.arcs = true; let c = Self::positions(s, axes, notes)?; - if c.is_empty() { - return None; - } Some(self.arcs_through(&c, local(&s) == "Circle", notes)) } other => { @@ -888,8 +889,13 @@ impl Shapes { let want = need.clamp(4, MAX_ARC_POINTS); // A full circle keeps at least 8 pieces past the allowance (said as coarse): each circle // in the text is far longer than 8 points, so the extra stays bounded by the file's size. - let floor = if sweep_deg.abs() >= 360.0 { 8 } else { 1 }; - (self.take(want - 1, notes) + 1).max(floor) + let n = self.take(want - 1, notes) + 1; + let floor = want.min(8); + if sweep_deg.abs() >= 360.0 && n < floor { + self.budget = self.budget.saturating_sub(floor - n); + return floor; + } + n } /// An `ArcByCenterPoint` or `CircleByCenterPoint`. @@ -955,6 +961,10 @@ impl Shapes { } i += 2; } + // A circle is through its first three positions: any more are said. + if circle && c.len() > 3 { + notes.short_arcs = true; + } // An odd position past the last arc: joined straight, and said. if !circle && i + 1 < c.len() { out.extend(c.iter().skip(i + 1).copied()); @@ -973,6 +983,7 @@ impl Shapes { let d = 2.0 * (pa.x * (pm.y - pb.y) + pm.x * (pb.y - pa.y) + pb.x * (pa.y - pm.y)); let straight = vec![a, m, b]; if !d.is_finite() || d.abs() < 1e-9 { + notes.straight_arcs = true; return straight; } let sq = |p: Coord| p.x * p.x + p.y * p.y; @@ -980,6 +991,7 @@ impl Shapes { let uy = (sq(pa) * (pb.x - pm.x) + sq(pm) * (pa.x - pb.x) + sq(pb) * (pm.x - pa.x)) / d; let r = (pa.x - ux).hypot(pa.y - uy); if !r.is_finite() || r > MAX_RADIUS_M { + notes.straight_arcs = true; return straight; } let ang = |p: Coord| (p.y - uy).atan2(p.x - ux); @@ -1483,8 +1495,10 @@ struct Layer { far: usize, /// Route segments drawn between the points they name. between: usize, - /// Features with an arc or circle not drawn: the point allowance ran out. + /// Features with an arc or circle not given the three positions it needs. short_arcs: usize, + /// Features with an arc or circle drawn straight: its points in a line, or too far apart. + straight_arcs: usize, /// Route segments with no curve and a `pathType` RustGIS doesn't draw. path_unread: usize, /// Rows left out: the table they'd make passes the memory the file's size allows. @@ -1537,6 +1551,7 @@ impl Layer { self.far += n.far; self.between += usize::from(n.between); self.short_arcs += usize::from(n.short_arcs); + self.straight_arcs += usize::from(n.straight_arcs); self.path_unread += usize::from(n.path_unread); self.border_allowance += n.border_allowance; self.border_unusable += n.border_unusable; @@ -1871,7 +1886,7 @@ struct Layers { /// Rows left out past that. rows_over: usize, list: Vec, - /// Features of kinds past [`MAX_LAYERS`], by identifier. + /// Features of kinds past [`MAX_LAYERS`], by kind and identifier. over: HashSet, /// The feature being read (its kind and identifier): what `over` counts. feature: String, @@ -2224,7 +2239,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = Vec::new(); + let mut shapeless: Vec<(String, Row, usize, bool, String)> = Vec::new(); let mut held_left = text.len().saturating_mul(2).max(MIN_ROW_BYTES); // GeoBorders first: airspace borders follow them by reference; route segments last: one with // no curve is drawn between the points it names. @@ -2376,13 +2391,14 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0, snapshot); if layers.has_kind(&kind) { let label = layers.list.iter().find(|l| l.kind == kind).map(|l| l.label.clone()).unwrap_or_default(); @@ -3053,8 +3069,13 @@ fn finish( ); say( layer.short_arcs, - "feature has an arc given fewer than the three positions it needs, drawn straight between them", - "features have an arc given fewer than the three positions it needs, drawn straight between them", + "feature has an arc or circle not given the three positions it needs, drawn through the positions it has (a circle through its first three)", + "features have an arc or circle not given the three positions it needs, drawn through the positions they have (a circle through its first three)", + ); + say( + layer.straight_arcs, + "feature has an arc or circle drawn straight: its points are in a line, or too far apart to be one", + "features have an arc or circle drawn straight: their points are in a line, or too far apart to be one", ); say( layer.path_unread, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index e552cccae8..88ff450f53 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1380,11 +1380,36 @@ fn an_arc_with_too_few_positions_is_drawn_straight_and_said_and_none_is_unreadab }; let out = run("50 11 51 11"); assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some()); - assert!(said(&out).iter().any(|m| m.contains("1 feature has an arc given fewer than the three positions")), "{:?}", said(&out)); + assert!(said(&out).iter().any(|m| m.contains("1 feature has an arc or circle not given the three positions")), "{:?}", said(&out)); let out = run("50 11 50.5 11.5 51 11"); - assert!(!said(&out).iter().any(|m| m.contains("fewer than the three positions")), "{:?}", said(&out)); + assert!(!said(&out).iter().any(|m| m.contains("not given the three positions")), "{:?}", said(&out)); let out = run(""); - assert_eq!(layer(&out, "t RouteSegment").features[0].geometry, None); + assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some()); + assert!(said(&out).iter().any(|m| m.contains("1 feature has an arc or circle not given the three positions")), "{:?}", said(&out)); +} + +#[test] +fn a_circle_given_more_than_three_positions_or_in_a_line_is_said() { + let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; + let mut notes = ShapeNotes::default(); + let c = [Coord::new(10.0, 50.0), Coord::new(10.1, 50.1), Coord::new(10.2, 50.0), Coord::new(10.1, 49.9)]; + shapes.arcs_through(&c, true, &mut notes); + assert!(notes.short_arcs && !notes.straight_arcs); + let mut notes = ShapeNotes::default(); + shapes.arcs_through(&[Coord::new(10.0, 50.0), Coord::new(10.0, 50.1), Coord::new(10.0, 50.2)], false, &mut notes); + assert!(notes.straight_arcs && !notes.short_arcs); + let mut notes = ShapeNotes::default(); + shapes.arcs_through(&c[..3], true, &mut notes); + assert!(!notes.straight_arcs && !notes.short_arcs); +} + +#[test] +fn a_small_circle_with_points_to_spare_keeps_what_it_needs() { + let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; + let mut notes = ShapeNotes::default(); + let n = shapes.pieces(0.5, 360.0, &mut notes); + assert_eq!(n, 4); + assert!(!notes.coarse); } #[test] From 98b2f43d902dcb551759e1abb26f529f9cfce565 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:52:54 -0600 Subject: [PATCH 28/61] fix(data): AIXM shapes that give nothing say nothing of their arcs; empty arcs said as left out; an Arc through its first three positions; held keys counted --- crates/data/src/aixm.rs | 43 +++++++++++++++++++++++++++-------- crates/data/src/aixm/tests.rs | 24 +++++++++++++++++-- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 37c62c85f9..37e7548607 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -621,11 +621,13 @@ struct ShapeNotes { followed_whole: usize, /// A route segment drawn between the points it names, having no curve. between: bool, - /// An arc or circle not given the three positions it needs (fewer, or a circle given more): - /// drawn through the positions it has, or the first three. + /// An arc or circle not given the three positions it needs (fewer, or an Arc or Circle given + /// more): drawn through the positions it has, or the first three. short_arcs: bool, /// An arc or circle whose points are in a line, or past the largest radius: drawn straight. straight_arcs: bool, + /// An arc or circle with no positions: left out, the line joined straight across it. + empty_arcs: bool, /// A route segment with no curve and a `pathType` RustGIS doesn't draw. path_unread: bool, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -691,6 +693,7 @@ impl ShapeNotes { self.between |= o.between; self.short_arcs |= o.short_arcs; self.straight_arcs |= o.straight_arcs; + self.empty_arcs |= o.empty_arcs; self.path_unread |= o.path_unread; } } @@ -811,8 +814,17 @@ impl Shapes { self.arc_by_center(s, axes, notes) } "Arc" | "ArcString" | "Circle" => { + let mut c = Self::positions(s, axes, notes)?; + if c.is_empty() { + notes.empty_arcs = true; + return Some(Vec::new()); + } notes.arcs = true; - let c = Self::positions(s, axes, notes)?; + // An Arc is one arc, through three positions: any more are said. + if local(&s) == "Arc" && c.len() > 3 { + notes.short_arcs = true; + c.truncate(3); + } Some(self.arcs_through(&c, local(&s) == "Circle", notes)) } other => { @@ -887,12 +899,12 @@ impl Shapes { let need = (sweep_deg.abs() / step.max(1e-6)).ceil() as usize; notes.coarse |= need > MAX_ARC_POINTS; let want = need.clamp(4, MAX_ARC_POINTS); - // A full circle keeps at least 8 pieces past the allowance (said as coarse): each circle - // in the text is far longer than 8 points, so the extra stays bounded by the file's size. + // A full circle keeps at least 8 pieces (or what it needs, if fewer) when the allowance has + // run out, said as coarse: each circle in the text is far longer than 8 points, so the + // extra stays bounded by the file's size. let n = self.take(want - 1, notes) + 1; let floor = want.min(8); if sweep_deg.abs() >= 360.0 && n < floor { - self.budget = self.budget.saturating_sub(floor - n); return floor; } n @@ -1296,7 +1308,12 @@ impl Shapes { /// A geometry element (AIXM's or GML's) as a geometry. fn shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { (self.assumed_now, self.other_now, self.as_wgs84_now) = (false, false, false); + // A shape that gives nothing says nothing of how its arcs were drawn. + let arcs = (notes.arcs, notes.short_arcs, notes.empty_arcs, notes.straight_arcs); let shape = self.read_shape(g, notes); + if shape.is_none() { + (notes.arcs, notes.short_arcs, notes.empty_arcs, notes.straight_arcs) = arcs; + } self.assumed_system += usize::from(self.assumed_now); self.other_count += usize::from(self.other_now); self.as_wgs84_count += usize::from(self.as_wgs84_now); @@ -1499,6 +1516,8 @@ struct Layer { short_arcs: usize, /// Features with an arc or circle drawn straight: its points in a line, or too far apart. straight_arcs: usize, + /// Features with an arc or circle with no positions, left out. + empty_arcs: usize, /// Route segments with no curve and a `pathType` RustGIS doesn't draw. path_unread: usize, /// Rows left out: the table they'd make passes the memory the file's size allows. @@ -1552,6 +1571,7 @@ impl Layer { self.between += usize::from(n.between); self.short_arcs += usize::from(n.short_arcs); self.straight_arcs += usize::from(n.straight_arcs); + self.empty_arcs += usize::from(n.empty_arcs); self.path_unread += usize::from(n.path_unread); self.border_allowance += n.border_allowance; self.border_unusable += n.border_unusable; @@ -2386,7 +2406,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result held_left { layers.rows_over += 1; } else { @@ -3069,14 +3089,19 @@ fn finish( ); say( layer.short_arcs, - "feature has an arc or circle not given the three positions it needs, drawn through the positions it has (a circle through its first three)", - "features have an arc or circle not given the three positions it needs, drawn through the positions they have (a circle through its first three)", + "feature has an arc or circle not given the three positions it needs, drawn through the positions it has (or its first three)", + "features have an arc or circle not given the three positions it needs, drawn through the positions they have (or their first three)", ); say( layer.straight_arcs, "feature has an arc or circle drawn straight: its points are in a line, or too far apart to be one", "features have an arc or circle drawn straight: their points are in a line, or too far apart to be one", ); + say( + layer.empty_arcs, + "feature has an arc or circle with no positions, left out: its line is joined straight across it", + "features have an arc or circle with no positions, left out: their lines are joined straight across them", + ); say( layer.path_unread, "route segment with no curve isn't drawn: its pathType is one RustGIS doesn't draw", diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 88ff450f53..c7147571e7 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1364,7 +1364,7 @@ fn a_three_point_circle_past_the_allowance_keeps_eight_points_and_says_so() { } #[test] -fn an_arc_with_too_few_positions_is_drawn_straight_and_said_and_none_is_unreadable() { +fn an_arc_with_too_few_positions_is_drawn_through_them_and_an_empty_one_is_skipped_both_said() { let curve = |arc: &str| { format!( r#"C50 10 50 11{arc}"# @@ -1385,7 +1385,27 @@ fn an_arc_with_too_few_positions_is_drawn_straight_and_said_and_none_is_unreadab assert!(!said(&out).iter().any(|m| m.contains("not given the three positions")), "{:?}", said(&out)); let out = run(""); assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some()); - assert!(said(&out).iter().any(|m| m.contains("1 feature has an arc or circle not given the three positions")), "{:?}", said(&out)); + let notes = said(&out); + assert!(notes.iter().any(|m| m.contains("1 feature has an arc or circle with no positions, left out")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("not given the three positions") || m.contains("drawn as points along them")), "{notes:?}"); + // In a line straight (along a meridian), drawn straight and said; a real arc says nothing of it. + let out = run("50 11 50.5 11 51 11"); + assert!(said(&out).iter().any(|m| m.contains("1 feature has an arc or circle drawn straight")), "{:?}", said(&out)); + let out = run("50 11 50.5 11.5 51 11"); + assert!(!said(&out).iter().any(|m| m.contains("drawn straight:")), "{:?}", said(&out)); + // An Arc of five positions: through the first three, and said. + let out = run("50 11 50.5 11.5 51 11 51.5 10.5 52 11"); + assert!(said(&out).iter().any(|m| m.contains("not given the three positions")), "{:?}", said(&out)); +} + +#[test] +fn an_empty_arc_that_is_the_whole_line_says_nothing_of_arcs() { + let body = r#"E"#; + let bytes = + message(&feature("RouteSegment", "r", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), body)])); + let out = read("t.xml", &bytes, &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t RouteSegment").features[0].geometry, None); + assert!(!said(&out).iter().any(|m| m.contains("arc")), "{:?}", said(&out)); } #[test] From 6794ab9ff64958f392979ce6fbdef09d2ffc68e6 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:05:37 -0600 Subject: [PATCH 29/61] fix(data): AIXM says how shapes were drawn only for rows that are drawn; an Arc of more than three positions drawn whole; empty-arc wording --- crates/data/src/aixm.rs | 61 +++++++++++++++++------------------ crates/data/src/aixm/tests.rs | 28 ++++++++++++++-- 2 files changed, 56 insertions(+), 33 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 37e7548607..b208bb1cc9 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -622,11 +622,11 @@ struct ShapeNotes { /// A route segment drawn between the points it names, having no curve. between: bool, /// An arc or circle not given the three positions it needs (fewer, or an Arc or Circle given - /// more): drawn through the positions it has, or the first three. + /// more): drawn through the positions it has (a circle through its first three). short_arcs: bool, /// An arc or circle whose points are in a line, or past the largest radius: drawn straight. straight_arcs: bool, - /// An arc or circle with no positions: left out, the line joined straight across it. + /// An arc or circle with no positions: left out, the line going on without it. empty_arcs: bool, /// A route segment with no curve and a `pathType` RustGIS doesn't draw. path_unread: bool, @@ -814,16 +814,16 @@ impl Shapes { self.arc_by_center(s, axes, notes) } "Arc" | "ArcString" | "Circle" => { - let mut c = Self::positions(s, axes, notes)?; + let c = Self::positions(s, axes, notes)?; if c.is_empty() { notes.empty_arcs = true; return Some(Vec::new()); } notes.arcs = true; - // An Arc is one arc, through three positions: any more are said. + // An Arc is one arc, through three positions: any more are drawn as an ArcString + // would be, and said. if local(&s) == "Arc" && c.len() > 3 { notes.short_arcs = true; - c.truncate(3); } Some(self.arcs_through(&c, local(&s) == "Circle", notes)) } @@ -1308,12 +1308,7 @@ impl Shapes { /// A geometry element (AIXM's or GML's) as a geometry. fn shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { (self.assumed_now, self.other_now, self.as_wgs84_now) = (false, false, false); - // A shape that gives nothing says nothing of how its arcs were drawn. - let arcs = (notes.arcs, notes.short_arcs, notes.empty_arcs, notes.straight_arcs); let shape = self.read_shape(g, notes); - if shape.is_none() { - (notes.arcs, notes.short_arcs, notes.empty_arcs, notes.straight_arcs) = arcs; - } self.assumed_system += usize::from(self.assumed_now); self.other_count += usize::from(self.other_now); self.as_wgs84_count += usize::from(self.as_wgs84_now); @@ -1553,25 +1548,29 @@ impl Layer { Some(self.columns.len() - 1) } - fn take_notes(&mut self, n: &ShapeNotes) { - self.arcs += usize::from(n.arcs); - self.coarse += usize::from(n.coarse); - self.zm += usize::from(n.zm); - if !n.unread_segments.is_empty() { - self.approximated += 1; - for s in &n.unread_segments { - self.unread_segments.add(s); + /// The notes of a row's shapes. How a shape was drawn is said only for a row that is drawn; + /// why something wasn't is said either way. + fn take_notes(&mut self, n: &ShapeNotes, drawn: bool) { + if drawn { + self.arcs += usize::from(n.arcs); + self.coarse += usize::from(n.coarse); + self.zm += usize::from(n.zm); + if !n.unread_segments.is_empty() { + self.approximated += 1; + for s in &n.unread_segments { + self.unread_segments.add(s); + } } + self.followed += n.followed; + self.followed_whole += n.followed_whole; + self.far += n.far; + self.between += usize::from(n.between); + self.short_arcs += usize::from(n.short_arcs); + self.straight_arcs += usize::from(n.straight_arcs); + self.empty_arcs += usize::from(n.empty_arcs); } self.rings_lost += n.rings_lost; self.referenced += n.referenced; - self.followed += n.followed; - self.followed_whole += n.followed_whole; - self.far += n.far; - self.between += usize::from(n.between); - self.short_arcs += usize::from(n.short_arcs); - self.straight_arcs += usize::from(n.straight_arcs); - self.empty_arcs += usize::from(n.empty_arcs); self.path_unread += usize::from(n.path_unread); self.border_allowance += n.border_allowance; self.border_unusable += n.border_unusable; @@ -1973,7 +1972,7 @@ impl Layers { } } if let Some(n) = notes { - layer.take_notes(n); + layer.take_notes(n, geometry.is_some()); } if self.names_only { return Some(i); @@ -2406,7 +2405,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result held_left { layers.rows_over += 1; } else { @@ -3089,8 +3088,8 @@ fn finish( ); say( layer.short_arcs, - "feature has an arc or circle not given the three positions it needs, drawn through the positions it has (or its first three)", - "features have an arc or circle not given the three positions it needs, drawn through the positions they have (or their first three)", + "feature has an arc or circle not given the three positions it needs, drawn through the positions it has (a circle through its first three)", + "features have an arc or circle not given the three positions it needs, drawn through the positions they have (a circle through its first three)", ); say( layer.straight_arcs, @@ -3099,8 +3098,8 @@ fn finish( ); say( layer.empty_arcs, - "feature has an arc or circle with no positions, left out: its line is joined straight across it", - "features have an arc or circle with no positions, left out: their lines are joined straight across them", + "feature has an arc or circle with no positions, left out: its line goes on without it", + "features have an arc or circle with no positions, left out: their lines go on without them", ); say( layer.path_unread, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index c7147571e7..b4bfad9c43 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1392,10 +1392,34 @@ fn an_arc_with_too_few_positions_is_drawn_through_them_and_an_empty_one_is_skipp let out = run("50 11 50.5 11 51 11"); assert!(said(&out).iter().any(|m| m.contains("1 feature has an arc or circle drawn straight")), "{:?}", said(&out)); let out = run("50 11 50.5 11.5 51 11"); - assert!(!said(&out).iter().any(|m| m.contains("drawn straight:")), "{:?}", said(&out)); - // An Arc of five positions: through the first three, and said. + assert!(!said(&out).iter().any(|m| m.contains("drawn straight:") || m.contains("with no positions")), "{:?}", said(&out)); + // An Arc of five positions: all of them drawn, as an ArcString would be, and said. let out = run("50 11 50.5 11.5 51 11 51.5 10.5 52 11"); assert!(said(&out).iter().any(|m| m.contains("not given the three positions")), "{:?}", said(&out)); + let Some(Geometry::Line(l)) = &layer(&out, "t RouteSegment").features[0].geometry else { panic!("not drawn") }; + assert!(l[0].last().is_some_and(|c| (c.x - 11.0).abs() < 1e-9 && (c.y - 52.0).abs() < 1e-9), "{:?}", l[0].last()); +} + +#[test] +fn an_airspace_not_drawn_says_nothing_of_how_its_parts_were_drawn() { + let volume = |op: &str, seq: u32, shape: &str| { + format!( + r#"{op}{seq}{shape}"# + ) + }; + let circle = r#"50 1010"#; + let bad = r#"not numbers"#; + let body = format!("HALF{}{}", volume("BASE", 1, circle), volume("UNION", 2, bad)); + let out = read( + "t.xml", + &message(&feature("Airspace", "a", &[slice("Airspace", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + assert_eq!(layer(&out, "t Airspace").features[0].geometry, None); + let notes = said(&out); + assert!(notes.iter().any(|m| m.contains("couldn't be read")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("arcs or circles")), "{notes:?}"); } #[test] From 338aa3024fffe57d228635efdc3a07f2e7afea5a Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:15:37 -0600 Subject: [PATCH 30/61] fix(data): AIXM chained arcs stay whole across 180 degrees; merged shapes not drawn bring only why; arcs said only where drawn; an Arc's odd position said by its name --- crates/data/src/aixm.rs | 53 +++++++++++++++++++++++------------ crates/data/src/aixm/tests.rs | 33 ++++++++++++++++++---- 2 files changed, 62 insertions(+), 24 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index b208bb1cc9..04891b45b6 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -621,8 +621,8 @@ struct ShapeNotes { followed_whole: usize, /// A route segment drawn between the points it names, having no curve. between: bool, - /// An arc or circle not given the three positions it needs (fewer, or an Arc or Circle given - /// more): drawn through the positions it has (a circle through its first three). + /// An arc or circle not given the three positions it needs (fewer, or a circle given more): + /// drawn through the positions it has (a circle through its first three). short_arcs: bool, /// An arc or circle whose points are in a line, or past the largest radius: drawn straight. straight_arcs: bool, @@ -673,6 +673,18 @@ fn next_to(c: Coord, near: f64) -> Coord { } impl ShapeNotes { + /// What a shape that wasn't drawn found: why, not how it was drawn. + fn losses_only(self) -> ShapeNotes { + ShapeNotes { + rings_lost: self.rings_lost, + referenced: self.referenced, + border_allowance: self.border_allowance, + border_unusable: self.border_unusable, + path_unread: self.path_unread, + ..ShapeNotes::default() + } + } + /// Adds what another shape's reading found. fn absorb(&mut self, o: ShapeNotes) { self.arcs |= o.arcs; @@ -819,13 +831,7 @@ impl Shapes { notes.empty_arcs = true; return Some(Vec::new()); } - notes.arcs = true; - // An Arc is one arc, through three positions: any more are drawn as an ArcString - // would be, and said. - if local(&s) == "Arc" && c.len() > 3 { - notes.short_arcs = true; - } - Some(self.arcs_through(&c, local(&s) == "Circle", notes)) + Some(self.arcs_through(&c, local(&s), notes)) } other => { if !notes.unread_segments.iter().any(|n| n == other) { @@ -957,17 +963,25 @@ impl Shapes { /// Arcs through each three points (`Arc`, `ArcString`: start, a point on it, end; the next arc /// starting at the last's end), or a full circle through three (`Circle`). - fn arcs_through(&mut self, c: &[Coord], circle: bool, notes: &mut ShapeNotes) -> Vec { + fn arcs_through(&mut self, c: &[Coord], name: &str, notes: &mut ShapeNotes) -> Vec { + let circle = name == "Circle"; if c.len() < 3 { notes.short_arcs = true; return c.to_vec(); } let mut out: Vec = Vec::new(); + // Each point next to the one before it, so a chain of arcs across 180 degrees stays whole. + let put = |out: &mut Vec, p: Coord| { + let p = out.last().map_or(p, |l| next_to(p, l.x)); + out.push(p); + }; let mut i = 0; while let (Some(&a), Some(&m), Some(&b)) = (c.get(i), c.get(i + 1), c.get(i + 2)) { let arc = self.arc_through(a, m, b, circle, notes); let skip = usize::from(!out.is_empty()); - out.extend(arc.into_iter().skip(skip)); + for p in arc.into_iter().skip(skip) { + put(&mut out, p); + } if circle { break; } @@ -979,9 +993,11 @@ impl Shapes { } // An odd position past the last arc: joined straight, and said. if !circle && i + 1 < c.len() { - out.extend(c.iter().skip(i + 1).copied()); - if !notes.unread_segments.iter().any(|n| n == "ArcString") { - notes.unread_segments.push("ArcString".to_string()); + for &p in c.iter().skip(i + 1) { + put(&mut out, p); + } + if !notes.unread_segments.iter().any(|n| n == name) { + notes.unread_segments.push(name.to_string()); } } out @@ -1006,6 +1022,7 @@ impl Shapes { notes.straight_arcs = true; return straight; } + notes.arcs = true; let ang = |p: Coord| (p.y - uy).atan2(p.x - ux); // Counter-clockwise when a → m → b turns left. let ccw = (pm.x - pa.x) * (pb.y - pm.y) - (pm.y - pa.y) * (pb.x - pm.x) > 0.0; @@ -2629,8 +2646,8 @@ fn feature_rows( let mut notes = ShapeNotes::default(); let geom = shapes.shape(g, &mut notes); let (gs, n) = by_family.entry(element_family(local(&g))).or_default(); + n.absorb(if geom.is_some() { notes } else { notes.losses_only() }); gs.extend(geom); - n.absorb(notes); } // What the feature was is said once for it, with its first row. let change = if k == 0 { change } else { (false, false) }; @@ -3089,7 +3106,7 @@ fn finish( say( layer.short_arcs, "feature has an arc or circle not given the three positions it needs, drawn through the positions it has (a circle through its first three)", - "features have an arc or circle not given the three positions it needs, drawn through the positions they have (a circle through its first three)", + "features have an arc or circle not given the three positions it needs, drawn through the positions they have (circles through their first three)", ); say( layer.straight_arcs, @@ -3098,8 +3115,8 @@ fn finish( ); say( layer.empty_arcs, - "feature has an arc or circle with no positions, left out: its line goes on without it", - "features have an arc or circle with no positions, left out: their lines go on without them", + "feature has an arc or circle with no positions, left out: its line is joined straight from the positions either side", + "features have an arc or circle with no positions, left out: their lines are joined straight from the positions either side", ); say( layer.path_unread, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index b4bfad9c43..3f1c3220fa 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1358,7 +1358,7 @@ fn a_rhumb_line_near_a_pole_ends_at_its_points() { fn a_three_point_circle_past_the_allowance_keeps_eight_points_and_says_so() { let mut shapes = Shapes::default(); let mut notes = ShapeNotes::default(); - let drawn = shapes.arcs_through(&[Coord::new(10.0, 50.0), Coord::new(10.1, 50.1), Coord::new(10.2, 50.0)], true, &mut notes); + let drawn = shapes.arcs_through(&[Coord::new(10.0, 50.0), Coord::new(10.1, 50.1), Coord::new(10.2, 50.0)], "Circle", &mut notes); assert_eq!(drawn.len(), 9); assert!(notes.coarse); } @@ -1393,11 +1393,17 @@ fn an_arc_with_too_few_positions_is_drawn_through_them_and_an_empty_one_is_skipp assert!(said(&out).iter().any(|m| m.contains("1 feature has an arc or circle drawn straight")), "{:?}", said(&out)); let out = run("50 11 50.5 11.5 51 11"); assert!(!said(&out).iter().any(|m| m.contains("drawn straight:") || m.contains("with no positions")), "{:?}", said(&out)); - // An Arc of five positions: all of them drawn, as an ArcString would be, and said. + // An Arc of five positions: all of them drawn, as an ArcString would be. let out = run("50 11 50.5 11.5 51 11 51.5 10.5 52 11"); - assert!(said(&out).iter().any(|m| m.contains("not given the three positions")), "{:?}", said(&out)); + assert!(!said(&out).iter().any(|m| m.contains("not given the three positions") || m.contains("straight between")), "{:?}", said(&out)); let Some(Geometry::Line(l)) = &layer(&out, "t RouteSegment").features[0].geometry else { panic!("not drawn") }; assert!(l[0].last().is_some_and(|c| (c.x - 11.0).abs() < 1e-9 && (c.y - 52.0).abs() < 1e-9), "{:?}", l[0].last()); + // Of four: the last joined straight, said under its own name. + let out = run("50 11 50.5 11.5 51 11 51.5 10.5"); + assert!(said(&out).iter().any(|m| m.contains("drawn straight between their positions (Arc)")), "{:?}", said(&out)); + // Two positions: no arc drawn, so none said. + let out = run("50 11 51 11"); + assert!(!said(&out).iter().any(|m| m.contains("drawn as points along them")), "{:?}", said(&out)); } #[test] @@ -1437,13 +1443,13 @@ fn a_circle_given_more_than_three_positions_or_in_a_line_is_said() { let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; let mut notes = ShapeNotes::default(); let c = [Coord::new(10.0, 50.0), Coord::new(10.1, 50.1), Coord::new(10.2, 50.0), Coord::new(10.1, 49.9)]; - shapes.arcs_through(&c, true, &mut notes); + shapes.arcs_through(&c, "Circle", &mut notes); assert!(notes.short_arcs && !notes.straight_arcs); let mut notes = ShapeNotes::default(); - shapes.arcs_through(&[Coord::new(10.0, 50.0), Coord::new(10.0, 50.1), Coord::new(10.0, 50.2)], false, &mut notes); + shapes.arcs_through(&[Coord::new(10.0, 50.0), Coord::new(10.0, 50.1), Coord::new(10.0, 50.2)], "Arc", &mut notes); assert!(notes.straight_arcs && !notes.short_arcs); let mut notes = ShapeNotes::default(); - shapes.arcs_through(&c[..3], true, &mut notes); + shapes.arcs_through(&c[..3], "Circle", &mut notes); assert!(!notes.straight_arcs && !notes.short_arcs); } @@ -1481,3 +1487,18 @@ fn a_patch_left_out_for_its_hole_is_counted_beside_the_holes_reason() { assert!(notes.iter().any(|m| m.contains("1 ring or surface patch was left out")), "{notes:?}"); assert!(notes.iter().any(|m| m.contains("1 border is given by reference")), "{notes:?}"); } + +#[test] +fn a_chain_of_arcs_across_180_degrees_stays_whole() { + let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; + let mut notes = ShapeNotes::default(); + let c = [ + Coord::new(179.90, 10.0), + Coord::new(179.95, 10.02), + Coord::new(179.98, 10.0), + Coord::new(-179.97, 9.98), + Coord::new(-179.92, 10.0), + ]; + let line = shapes.arcs_through(&c, "ArcString", &mut notes); + assert!(line.windows(2).all(|w| (w[1].x - w[0].x).abs() < 1.0), "{line:?}"); +} From 9a683767b03629f7cb2e6ebfdecc12f82f9c4430 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:20:53 -0600 Subject: [PATCH 31/61] fix(data): AIXM empty-arc notice wording holds at a line's end --- crates/data/src/aixm.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 04891b45b6..c43e84cf27 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -626,7 +626,7 @@ struct ShapeNotes { short_arcs: bool, /// An arc or circle whose points are in a line, or past the largest radius: drawn straight. straight_arcs: bool, - /// An arc or circle with no positions: left out, the line going on without it. + /// An arc or circle with no positions: left out, the line going on from the positions around it. empty_arcs: bool, /// A route segment with no curve and a `pathType` RustGIS doesn't draw. path_unread: bool, @@ -3115,8 +3115,8 @@ fn finish( ); say( layer.empty_arcs, - "feature has an arc or circle with no positions, left out: its line is joined straight from the positions either side", - "features have an arc or circle with no positions, left out: their lines are joined straight from the positions either side", + "feature has an arc or circle with no positions, left out: its line goes on from the positions around it", + "features have an arc or circle with no positions, left out: their lines go on from the positions around them", ); say( layer.path_unread, From a3a551980f3d50aa98091383c0fbdd5ba28b3d77 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:50:15 -0600 Subject: [PATCH 32/61] fix(data): AIXM review findings: snapshots taken as they are, unreadable corrections withhold their feature, route ends by the kind they name, unresolved route segments said, names-only listing matches a read, patch and structure-part notes, border edges near 180 degrees; "at" refused for a GeoTIFF found at an address --- crates/data/src/aixm.rs | 166 ++++++++++++++++++++++++++------- crates/data/src/aixm/tests.rs | 144 ++++++++++++++++++++++++++++ crates/engine/src/cmd/layer.rs | 2 + crates/engine/src/tests.rs | 3 + 4 files changed, 279 insertions(+), 36 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index c43e84cf27..5e8c6c9996 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -382,6 +382,9 @@ struct Slice { canceled: bool, /// The feature's lifetime, when the slice says it. lifetime: Option<(Option, Option)>, + /// Its validity or lifetime isn't a date: it keeps its place among its corrections, and the + /// feature is left out when it is the one that holds. + unreadable: bool, } /// A feature's slices, read from any number of members. @@ -406,6 +409,8 @@ enum State { OnlyChanges, /// Every slice canceled. Canceled, + /// The slice that holds (the latest correction) has a validity that isn't a date. + Unreadable, } fn in_force(begin: Option, end: Option, t: f64) -> bool { @@ -421,7 +426,10 @@ fn state_at(slices: &[Slice], t: f64) -> State { let mut snapshots: Vec<&Slice> = Vec::new(); for s in slices { if s.kind == Interpretation::Snapshot { - snapshots.push(s); + // A snapshot whose instant isn't a date can't be placed: not read (counted). + if !s.unreadable { + snapshots.push(s); + } continue; } let key = (s.kind as u8, s.sequence); @@ -432,6 +440,9 @@ fn state_at(slices: &[Slice], t: f64) -> State { } } } + if held.values().any(|s| s.unreadable) { + return State::Unreadable; + } let live: Vec<&Slice> = held.values().copied().chain(snapshots).filter(|s| !s.canceled).collect(); if live.is_empty() { return if slices.is_empty() { State::OnlyChanges } else { State::Canceled }; @@ -454,7 +465,13 @@ fn state_at(slices: &[Slice], t: f64) -> State { of(Interpretation::Snapshot).min_by(|a, b| a.begin.unwrap_or(f64::MAX).total_cmp(&b.begin.unwrap_or(f64::MAX))) }); match snap { - Some(s) if baselines == 0 => (s, true), + // Taken as it is: a SNAPSHOT already holds the changes in force at its instant. + Some(s) if baselines == 0 => { + return match s.lifetime { + Some((from, until)) if !in_force(from, until, t) => State::OutsideLifetime, + _ => State::Use { base: s.clone(), changes: Vec::new(), snapshot: true, temporary: 0 }, + }; + } _ if baselines > 0 => return State::NotInForce, _ => return State::OnlyChanges, } @@ -558,11 +575,12 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); if bad { trouble.dates += 1; - return None; + let (begin, end, canceled, lifetime) = (None, None, false, None); + return Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime, unreadable: true }); } trouble.numbers += usize::from(unread_number.get()); trouble.empty += empty.get(); - Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime }) + Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime, unreadable: false }) } /// The features of a member (an `AIXMBasicMessage`'s `hasMember` holds one). @@ -600,6 +618,10 @@ struct Axes { /// What reading shapes found, for a layer's notices. #[derive(Default)] struct ShapeNotes { + /// A route segment with no curve whose start or end names a point that isn't in the file. + route_unlocated: bool, + /// A vertical structure part holding more than one shape: the first drawn. + extra_shapes: bool, /// Features drawn with arcs or circles as points along them. arcs: bool, /// Features whose curves were drawn with fewer points than the tolerance needs: the file's @@ -655,8 +677,6 @@ struct Shapes { borders: HashMap>, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, - /// Only the layers' names are wanted: a shape is its family's placeholder, not drawn. - names_only: bool, /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of /// route segments that name them. points: HashMap, @@ -676,6 +696,8 @@ impl ShapeNotes { /// What a shape that wasn't drawn found: why, not how it was drawn. fn losses_only(self) -> ShapeNotes { ShapeNotes { + route_unlocated: self.route_unlocated, + extra_shapes: self.extra_shapes, rings_lost: self.rings_lost, referenced: self.referenced, border_allowance: self.border_allowance, @@ -687,6 +709,8 @@ impl ShapeNotes { /// Adds what another shape's reading found. fn absorb(&mut self, o: ShapeNotes) { + self.route_unlocated |= o.route_unlocated; + self.extra_shapes |= o.extra_shapes; self.arcs |= o.arcs; self.coarse |= o.coarse; self.zm |= o.zm; @@ -1283,12 +1307,14 @@ impl Shapes { }; let mut polys = Vec::new(); for p in patches { + // Each patch's notes its own: how it was drawn is said only when it is kept. + let mut pn = ShapeNotes::default(); // A ring lost to a border by reference is said as that, once. let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable; - let before = said(notes); - let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, notes)); + let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, &mut pn)); let Some(outer) = outer else { - notes.rings_lost += usize::from(said(notes) == before); + pn.rings_lost += usize::from(said(&pn) == 0); + notes.absorb(pn.losses_only()); continue; }; // A hole that can't be read leaves the patch out: drawn without it, the patch would @@ -1296,15 +1322,17 @@ impl Shapes { let mut rings = vec![outer]; let mut hole_lost = false; for b in elements(p).filter(|c| local(c) == "interior") { - match self.ring(b, notes) { + match self.ring(b, &mut pn) { Some(r) => rings.push(r), None => hole_lost = true, } } // The patch left out for its hole is counted, whatever lost the hole (said too). if hole_lost { - notes.rings_lost += 1; + pn.rings_lost += 1; + notes.absorb(pn.losses_only()); } else { + notes.absorb(pn); polys.push(rings); } } @@ -1333,14 +1361,6 @@ impl Shapes { } fn read_shape(&mut self, g: Node, notes: &mut ShapeNotes) -> Option { - if self.names_only { - let o = Coord::new(0.0, 0.0); - return Some(match element_family(local(&g)) { - "points" => Geometry::Point(o), - "lines" => Geometry::Line(vec![vec![o, o]]), - _ => Geometry::Polygon(vec![vec![vec![o, o, o, o]]]), - }); - } match local(&g) { "Point" | "ElevatedPoint" => self.point(g, notes), "Curve" | "ElevatedCurve" | "LineString" => self.curve(g, notes).map(|c| Geometry::Line(vec![c])), @@ -1390,16 +1410,20 @@ fn nearest_on(line: &[Coord], p: Coord) -> Option<(usize, f64, Coord, f64)> { let mut best: Option<(usize, f64, Coord, f64)> = None; for (i, w) in line.windows(2).enumerate() { let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue }; - // The segment moved as one next to the point: its ends keep their short span across 180°. - let a = next_to(a, p.x); - let b = next_to(b, a.x); - let (dx, dy) = ((b.x - a.x) * k, b.y - a.y); - let len2 = dx * dx + dy * dy; - let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; - let q = Coord::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); - let d2 = ((q.x - p.x) * k).powi(2) + (q.y - p.y).powi(2); - if best.is_none_or(|(_, _, _, bd)| d2 < bd) { - best = Some((i, t, q, d2)); + // The segment moved as one next to the point (its ends keep their short span across + // 180°), and tried a turn either way too: a long edge's nearer end may be on the other. + let a0 = next_to(a, p.x); + let b0 = next_to(b, a0.x); + for shift in [0.0, -360.0, 360.0] { + let (a, b) = (Coord::new(a0.x + shift, a0.y), Coord::new(b0.x + shift, b0.y)); + let (dx, dy) = ((b.x - a.x) * k, b.y - a.y); + let len2 = dx * dx + dy * dy; + let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; + let q = Coord::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); + let d2 = ((q.x - p.x) * k).powi(2) + (q.y - p.y).powi(2); + if best.is_none_or(|(_, _, _, bd)| d2 < bd) { + best = Some((i, t, next_to(q, p.x), d2)); + } } } best.map(|(i, t, q, _)| (i, t, q, rustgis_geom::wgs84_distance_m(q, p))) @@ -1536,6 +1560,10 @@ struct Layer { dense_over: usize, /// Records holding no shape beside records of the same property that do: rows of their own. unlocated: usize, + /// Route segments whose start or end names a point not in the file: kept without a line. + route_unlocated: usize, + /// Vertical structure parts holding more than one shape: the first drawn. + extra_shapes: usize, /// Borders by reference followed whole. followed_whole: usize, /// Borders by reference not followed: past the work allowed, or too short to cut. @@ -1589,6 +1617,8 @@ impl Layer { self.rings_lost += n.rings_lost; self.referenced += n.referenced; self.path_unread += usize::from(n.path_unread); + self.route_unlocated += usize::from(n.route_unlocated); + self.extra_shapes += usize::from(n.extra_shapes); self.border_allowance += n.border_allowance; self.border_unusable += n.border_unusable; } @@ -2143,6 +2173,8 @@ struct FileNotes { not_in_force: usize, outside_lifetime: usize, no_state: usize, + /// Features whose slice that holds has a validity that isn't a date: left out. + unreadable_state: usize, canceled: usize, unreadable_members: usize, unknown_interpretation: usize, @@ -2268,7 +2300,6 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result { + notes.unreadable_state += 1; + continue; + } }; // Its slices in force, each parsed on its own with the namespaces in scope where it is // written: the text parsed again is the slices', not their members'. @@ -2408,10 +2443,14 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result(props: &[Node<'a, 'i>], name: &str, shapes: &Shapes) -> O let p = props.iter().find(|p| local(p) == name)?; let choice = p.descendants().find(|d| d.is_element() && local(d).starts_with("pointChoice_"))?; match choice.attribute((XLINK, "href")) { - Some(h) => shapes.points.get(&reference(h)).copied().map(End::Named), + Some(h) => { + let target = reference(h); + let local_link = h.trim().starts_with('#') || h.contains("@gml:id"); + let found = if local_link { + shapes.points.get(&format!("#{target}")) + } else { + // The kind the choice names, then any point so named. + point_kind(local(&choice)) + .and_then(|k| shapes.points.get(&format!("{k}\u{1}{target}"))) + .or_else(|| shapes.points.get(&target)) + }; + found.copied().map(End::Named) + } None => shape_in(choice).filter(|g| matches!(local(g), "Point" | "ElevatedPoint")).map(End::Written), } } +/// The kind of feature a route end's choice names (`pointChoice_fixDesignatedPoint`: a +/// DesignatedPoint). +fn point_kind(choice: &str) -> Option<&'static str> { + Some(match choice.strip_prefix("pointChoice_")? { + "fixDesignatedPoint" => "DesignatedPoint", + "navaidSystem" => "Navaid", + "aimingPoint" => "TouchDownLiftOff", + "runwayPoint" => "RunwayCentrelinePoint", + "airportReferencePoint" => "AirportHeliport", + _ => return None, + }) +} + /// The family a shape element draws as, by its name (what a layer of its shapes is labeled). fn element_family(name: &str) -> &'static str { match name { @@ -2610,6 +2674,12 @@ fn feature_rows( return true; } if parts.is_empty() { + // A route segment naming ends that aren't in the file: in its layer without a line. + if kind == "RouteSegment" && props.iter().any(|p| matches!(local(p), "start" | "end")) { + let notes = ShapeNotes { route_unlocated: true, ..ShapeNotes::default() }; + layers.push(kind, "curveExtent", None, row.clone(), Some(¬es), change); + return true; + } return false; } // Rows copied for the records stay within what the file's size allows: checked before each @@ -2802,12 +2872,19 @@ fn vertical_structure( let mut r = row.clone(); let mut notes = ShapeNotes::default(); let mut geom = None; - let mut bad = false; + let (mut bad, mut seen) = (false, false); for p in elements(vp) { match shape_in(p) { Some(g) if !is_nil(&p) => { - geom = shapes.shape(g, &mut notes); - bad = geom.is_none(); + if seen { + notes.extra_shapes = true; + } else { + seen = true; + let mut own = ShapeNotes::default(); + geom = shapes.shape(g, &mut own); + bad = geom.is_none(); + notes.absorb(if bad { own.losses_only() } else { own }); + } r.shape_values(g, &format!("part_{}", local(&p))); } _ => r.property(p, "part_"), @@ -2869,6 +2946,13 @@ fn finish( "given only as changes (PERMDELTA or TEMPDELTA), with no BASELINE or SNAPSHOT to apply them to, left out", ); say(&mut file, notes.canceled, "feature", "features", "whose time slices were all canceled left out"); + say( + &mut file, + notes.unreadable_state, + "feature", + "features", + "left out: the time slice that holds (its latest correction) has a validity that isn't a date", + ); say(&mut file, notes.no_slices, "feature", "features", "with no time slice RustGIS reads left out"); say( &mut file, @@ -3133,6 +3217,16 @@ fn finish( "record with no shape (beside ones of the same property that have one) is a row without a shape", "records with no shape (beside ones of the same property that have one) are rows without a shape", ); + say( + layer.route_unlocated, + "route segment is kept without a line: a point its start or end names isn't in the file", + "route segments are kept without a line: a point their start or end names isn't in the file", + ); + say( + layer.extra_shapes, + "structure part holds more than one shape: the first is drawn, the others' values kept", + "structure parts hold more than one shape: the first is drawn, the others' values kept", + ); say( layer.between, "route segment with no curve is drawn between the points its start and end name, as its pathType says (a geodesic, or a rhumb line)", diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 3f1c3220fa..be5cd9095a 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1502,3 +1502,147 @@ fn a_chain_of_arcs_across_180_degrees_stays_whole() { let line = shapes.arcs_through(&c, "ArcString", &mut notes); assert!(line.windows(2).all(|w| (w[1].x - w[0].x).abs() < 1.0), "{line:?}"); } + +// --------------------------------------------------------------------------------------------- +// From the second review of PR #2819. +// --------------------------------------------------------------------------------------------- + +#[test] +fn a_snapshot_is_taken_as_it_is_without_changes_over_it() { + let temp = slice( + "DesignatedPoint", + "TEMPDELTA", + 1, + 0, + &period("2026-01-10T00:00:00Z", Some("2026-01-20T00:00:00Z")), + "TEMP", + ); + let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "SNAP"), temp])); + assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("SNAP".into())]); +} + +#[test] +fn a_correction_that_cant_be_read_withholds_its_feature() { + let unknown = slice("DesignatedPoint", "BASELINE", 1, 1, r#""#, &named_point("CORRECTED")); + let bytes = message( + &(point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "OLD"), unknown]) + + &point("b", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")])), + ); + let (got, notes) = names(&bytes, "2026-01-15"); + assert_eq!(got, [Value::Text("KEPT".into())]); + assert!(notes.iter().any(|m| m.contains("1 feature left out: the time slice that holds")), "{notes:?}"); + // A clean file says nothing of it. + let notes = names(&message(&point("b", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")])), "2026-01-15").1; + assert!(!notes.iter().any(|m| m.contains("the time slice that holds")), "{notes:?}"); +} + +fn structure(parts: &str) -> Vec { + message(&feature( + "VerticalStructure", + "v", + &[slice( + "VerticalStructure", + "BASELINE", + 1, + 0, + &period("2025-01-01T00:00:00Z", None), + &format!("MAST{parts}"), + )], + )) +} + +fn part(id: &str, shapes: &str) -> String { + format!( + r#"{id}{shapes}"# + ) +} + +const PART_POINT: &str = r#"52 -32"#; + +#[test] +fn listing_names_gives_what_a_read_gives_for_a_structure_with_a_part_that_cant_be_drawn() { + let bad_curve = r#"52 -32"#; + let good_curve = r#"52 -32 52.1 -32"#; + for bytes in [structure(&(part("A", PART_POINT) + &part("B", bad_curve))), structure(&(part("A", PART_POINT) + &part("B", good_curve)))] + { + let opts = at("2026-01-15"); + let mut read_names: Vec = read("t.xml", &bytes, &opts).unwrap().into_iter().map(|(d, _)| d.name).collect(); + let mut listed = layer_names("t.xml", &bytes, &opts).unwrap(); + read_names.sort(); + listed.sort(); + assert_eq!(listed, read_names); + } +} + +#[test] +fn a_structure_part_with_two_shapes_draws_the_first_and_says_so() { + let line = r#"52 -32 52.1 -32"#; + let out = read("t.xml", &structure(&part("A", &format!("{PART_POINT}{line}"))), &at("2026-01-15")).unwrap(); + assert!(said(&out).iter().any(|m| m.contains("1 structure part holds more than one shape")), "{:?}", said(&out)); + let out = read("t.xml", &structure(&part("A", PART_POINT)), &at("2026-01-15")).unwrap(); + assert!(!said(&out).iter().any(|m| m.contains("more than one shape")), "{:?}", said(&out)); +} + +fn named_at(kind: &str, id: &str, lat: f64, lon: f64) -> String { + let body = format!( + r#"{kind}{lat} {lon}"# + ); + feature(kind, id, &[slice(kind, "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]) +} + +fn route_to(choice: &str, start_id: &str) -> String { + let end = |name: &str, href: &str| { + format!( + r#""# + ) + }; + let body = format!("{}{}", end("start", start_id), end("end", "far")); + feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]) +} + +#[test] +fn a_route_end_is_the_point_of_the_kind_it_names() { + let members = named_at("DesignatedPoint", "same", 50.0, 10.0) + + &named_at("Navaid", "same", 55.0, 20.0) + + &named_at("DesignatedPoint", "far", 50.0, 12.0); + let out = read("t.xml", &message(&(members + &route_to("pointChoice_fixDesignatedPoint", "same"))), &at("2026-01-15")).unwrap(); + let Some(Geometry::Line(l)) = &layer(&out, "t RouteSegment").features[0].geometry else { panic!("not drawn") }; + assert_eq!(l[0].first(), Some(&Coord::new(10.0, 50.0))); +} + +#[test] +fn a_route_segment_whose_ends_arent_in_the_file_is_kept_and_said() { + let out = read("t.xml", &message(&route_to("pointChoice_fixDesignatedPoint", "missing")), &at("2026-01-15")).unwrap(); + let rs = layer(&out, "t RouteSegment"); + assert_eq!(rs.features.len(), 1); + assert_eq!(rs.features[0].geometry, None); + assert!(said(&out).iter().any(|m| m.contains("1 route segment is kept without a line")), "{:?}", said(&out)); +} + +#[test] +fn a_patch_left_out_says_nothing_of_how_it_was_drawn() { + let circle_with_hole = r#"50 1010"#; + let square = r#"52 9 52 11 54 11 54 9 52 9"#; + let body = format!( + r#"TWO{circle_with_hole}{square}"# + ); + let out = read( + "t.xml", + &message(&feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + assert!(layer(&out, "t WorkArea").features[0].geometry.is_some()); + let notes = said(&out); + assert!(notes.iter().any(|m| m.contains("1 ring or surface patch was left out")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("arcs or circles")), "{notes:?}"); +} + +#[test] +fn a_long_edge_ending_near_180_degrees_is_near_a_point_across_it() { + let line = [Coord::new(0.0, 0.0), Coord::new(179.999755859375, 0.0)]; + let (.., d) = nearest_on(&line, Coord::new(-180.0, 0.0)).unwrap(); + assert!(d < 50.0, "{d}"); + let (.., d) = nearest_on(&[Coord::new(179.0, 0.0), Coord::new(-179.0, 0.0)], Coord::new(0.0, 0.0)).unwrap(); + assert!(d > 19_000_000.0, "{d}"); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 5602dc85ed..3308ebd038 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5913,6 +5913,8 @@ pub(crate) fn add_cog(s: &mut Session, p: &Value, url: &str, probed: bool) -> Cm /// [`add_cog`], a GeoTIFF that can't be read now added all the same (unless `strict`), showing /// why: a project being imported keeps its layers. pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, probed: bool) -> CmdResult { + // An effective date is for an AIXM message: a GeoTIFF found at an address refuses it. + check_at(p, url, || false)?; let stem = cog_name(url); let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&stem); let empty_before = super::map_is_empty(s); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c8fd7f256b..8ad8c35c24 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24179,6 +24179,9 @@ fn aixm_messages_are_added_at_the_date_asked() { assert!(e.contains("isn't one"), "{e}"); let e = s.run("layer.addUrl", &json!({"url": "https://example.com/roads.fgb", "at": "2026-01-15"})).unwrap_err(); assert!(e.contains("isn't one"), "{e}"); + // An address with no extension found to be a GeoTIFF refuses it too, before it is added. + let e = crate::cmd::layer::add_cog(&mut s, &json!({"at": "2026-01-15"}), "https://example.test/download", true).unwrap_err(); + assert!(e.contains("isn't one"), "{e}"); let _ = std::fs::remove_dir_all(dir); } From 35d3f37600986bb5e589a289edf45011dcb25360 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:05:16 -0600 Subject: [PATCH 33/61] fix(data): AIXM snapshots take the changes begun since their instant; only an unreadable baseline correction withholds a feature; route ends only of the kind named; structure parts drawn from their first readable shape; unresolved-route notice only for a missing point --- crates/data/src/aixm.rs | 94 ++++++++++++++++++++-------------- crates/data/src/aixm/tests.rs | 49 ++++++++++++++---- crates/engine/src/cmd/layer.rs | 7 +-- 3 files changed, 99 insertions(+), 51 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 5e8c6c9996..4a2b9c3d9c 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -94,7 +94,8 @@ const SHAPES: &[&str] = &["Point", "ElevatedPoint", "Curve", "ElevatedCurve", "S pub struct Options { /// The effective date: milliseconds since 1970-01-01 UTC. Today when `None`. pub at: Option, - /// Only the layers' names are wanted (`info.fileLayers`): no shape is drawn and no value kept. + /// Only the layers' names are wanted (`info.fileLayers`): shapes are read as a full read reads + /// them (so the names are the same), but no row or value is kept. pub names_only: bool, } @@ -108,8 +109,8 @@ impl Options { } } -/// The names of the layers [`read`] gives a message at `opts.at`, worked out without drawing -/// their shapes or keeping their values: what listing a file's layers needs. +/// The names of the layers [`read`] gives a message at `opts.at`: its shapes read as a read reads +/// them, its rows and values not kept. What listing a file's layers needs. pub fn layer_names(file_name: &str, bytes: &[u8], opts: &Options) -> Result> { let opts = Options { names_only: true, ..*opts }; Ok(read(file_name, bytes, &opts)?.into_iter().map(|(d, _)| d.name).collect()) @@ -382,8 +383,8 @@ struct Slice { canceled: bool, /// The feature's lifetime, when the slice says it. lifetime: Option<(Option, Option)>, - /// Its validity or lifetime isn't a date: it keeps its place among its corrections, and the - /// feature is left out when it is the one that holds. + /// Its validity or lifetime isn't a date: it keeps its place among its corrections. A + /// BASELINE's that holds leaves the feature out; a change's is left out itself (counted). unreadable: bool, } @@ -409,7 +410,7 @@ enum State { OnlyChanges, /// Every slice canceled. Canceled, - /// The slice that holds (the latest correction) has a validity that isn't a date. + /// The state's latest correction (or every slice) has a validity that isn't a date. Unreadable, } @@ -440,12 +441,19 @@ fn state_at(slices: &[Slice], t: f64) -> State { } } } - if held.values().any(|s| s.unreadable) { + // The state's latest correction isn't a date: what it is then can't be known. + if held.values().any(|s| s.unreadable && s.kind == Interpretation::Baseline) { return State::Unreadable; } - let live: Vec<&Slice> = held.values().copied().chain(snapshots).filter(|s| !s.canceled).collect(); + let live: Vec<&Slice> = held.values().copied().chain(snapshots).filter(|s| !s.canceled && !s.unreadable).collect(); if live.is_empty() { - return if slices.is_empty() { State::OnlyChanges } else { State::Canceled }; + return if slices.is_empty() { + State::OnlyChanges + } else if slices.iter().all(|s| s.unreadable) { + State::Unreadable + } else { + State::Canceled + }; } let of = |k: Interpretation| live.iter().copied().filter(move |s| s.kind == k); // The BASELINE in force; of several (which the concept doesn't allow), the latest started. @@ -465,13 +473,7 @@ fn state_at(slices: &[Slice], t: f64) -> State { of(Interpretation::Snapshot).min_by(|a, b| a.begin.unwrap_or(f64::MAX).total_cmp(&b.begin.unwrap_or(f64::MAX))) }); match snap { - // Taken as it is: a SNAPSHOT already holds the changes in force at its instant. - Some(s) if baselines == 0 => { - return match s.lifetime { - Some((from, until)) if !in_force(from, until, t) => State::OutsideLifetime, - _ => State::Use { base: s.clone(), changes: Vec::new(), snapshot: true, temporary: 0 }, - }; - } + Some(s) if baselines == 0 => (s, true), _ if baselines > 0 => return State::NotInForce, _ => return State::OnlyChanges, } @@ -490,7 +492,10 @@ fn state_at(slices: &[Slice], t: f64) -> State { { return State::OutsideLifetime; } - let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).cloned().collect(); + // A SNAPSHOT already holds the changes in force at its instant: only those begun since go + // over it. + let since = |s: &Slice| !snapshot || s.begin.is_some_and(|b| base.begin.is_none_or(|bb| b > bb)); + let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t) && since(s)).cloned().collect(); temps.sort_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); let temporary = temps.len(); changes.extend(temps); @@ -620,7 +625,7 @@ struct Axes { struct ShapeNotes { /// A route segment with no curve whose start or end names a point that isn't in the file. route_unlocated: bool, - /// A vertical structure part holding more than one shape: the first drawn. + /// A vertical structure part holding more than one shape: the first that can be is drawn. extra_shapes: bool, /// Features drawn with arcs or circles as points along them. arcs: bool, @@ -1562,7 +1567,7 @@ struct Layer { unlocated: usize, /// Route segments whose start or end names a point not in the file: kept without a line. route_unlocated: usize, - /// Vertical structure parts holding more than one shape: the first drawn. + /// Vertical structure parts holding more than one shape: the first that can be is drawn. extra_shapes: usize, /// Borders by reference followed whole. followed_whole: usize, @@ -2544,23 +2549,34 @@ fn segment_end<'a, 'i>(props: &[Node<'a, 'i>], name: &str, shapes: &Shapes) -> O let p = props.iter().find(|p| local(p) == name)?; let choice = p.descendants().find(|d| d.is_element() && local(d).starts_with("pointChoice_"))?; match choice.attribute((XLINK, "href")) { - Some(h) => { - let target = reference(h); - let local_link = h.trim().starts_with('#') || h.contains("@gml:id"); - let found = if local_link { - shapes.points.get(&format!("#{target}")) - } else { - // The kind the choice names, then any point so named. - point_kind(local(&choice)) - .and_then(|k| shapes.points.get(&format!("{k}\u{1}{target}"))) - .or_else(|| shapes.points.get(&target)) - }; - found.copied().map(End::Named) - } + Some(h) => named_point(shapes, choice, h).map(End::Named), None => shape_in(choice).filter(|g| matches!(local(g), "Point" | "ElevatedPoint")).map(End::Written), } } +/// Where the point a route end's choice links to is: by its gml:id for a local link; else of the +/// kind the choice names, or (a choice of no known kind) any point of that identifier. +fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { + let target = reference(href); + if href.trim().starts_with('#') || href.contains("@gml:id") { + return shapes.points.get(&format!("#{target}")).copied(); + } + match point_kind(local(&choice)) { + Some(k) => shapes.points.get(&format!("{k}\u{1}{target}")).copied(), + None => shapes.points.get(&target).copied(), + } +} + +/// Whether a route segment's start or end links to a point that isn't in the file. +fn names_a_missing_point(props: &[Node], shapes: &Shapes) -> bool { + props.iter().filter(|p| matches!(local(p), "start" | "end")).any(|p| { + p.descendants() + .find(|d| d.is_element() && local(d).starts_with("pointChoice_")) + .and_then(|c| c.attribute((XLINK, "href")).map(|h| named_point(shapes, c, h).is_none())) + .unwrap_or(false) + }) +} + /// The kind of feature a route end's choice names (`pointChoice_fixDesignatedPoint`: a /// DesignatedPoint). fn point_kind(choice: &str) -> Option<&'static str> { @@ -2675,7 +2691,7 @@ fn feature_rows( } if parts.is_empty() { // A route segment naming ends that aren't in the file: in its layer without a line. - if kind == "RouteSegment" && props.iter().any(|p| matches!(local(p), "start" | "end")) { + if kind == "RouteSegment" && names_a_missing_point(props, shapes) { let notes = ShapeNotes { route_unlocated: true, ..ShapeNotes::default() }; layers.push(kind, "curveExtent", None, row.clone(), Some(¬es), change); return true; @@ -2876,12 +2892,14 @@ fn vertical_structure( for p in elements(vp) { match shape_in(p) { Some(g) if !is_nil(&p) => { - if seen { + if geom.is_some() { notes.extra_shapes = true; } else { - seen = true; let mut own = ShapeNotes::default(); geom = shapes.shape(g, &mut own); + // One that can't be read beside one drawn: not drawn, and said. + notes.extra_shapes |= seen && geom.is_some(); + seen = true; bad = geom.is_none(); notes.absorb(if bad { own.losses_only() } else { own }); } @@ -2951,7 +2969,7 @@ fn finish( notes.unreadable_state, "feature", "features", - "left out: the time slice that holds (its latest correction) has a validity that isn't a date", + "left out: the time slice that holds its state (the latest correction) has a validity that isn't a date", ); say(&mut file, notes.no_slices, "feature", "features", "with no time slice RustGIS reads left out"); say( @@ -3224,8 +3242,8 @@ fn finish( ); say( layer.extra_shapes, - "structure part holds more than one shape: the first is drawn, the others' values kept", - "structure parts hold more than one shape: the first is drawn, the others' values kept", + "structure part holds more than one shape: one is drawn (the first that can be), the others' values kept", + "structure parts hold more than one shape: one is drawn (the first that can be), the others' values kept", ); say( layer.between, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index be5cd9095a..3dc7a8fd45 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1508,17 +1508,29 @@ fn a_chain_of_arcs_across_180_degrees_stays_whole() { // --------------------------------------------------------------------------------------------- #[test] -fn a_snapshot_is_taken_as_it_is_without_changes_over_it() { - let temp = slice( - "DesignatedPoint", - "TEMPDELTA", - 1, - 0, - &period("2026-01-10T00:00:00Z", Some("2026-01-20T00:00:00Z")), - "TEMP", - ); - let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "SNAP"), temp])); +fn a_snapshot_takes_only_the_changes_begun_since_its_instant() { + let temp = |begin: &str| { + slice("DesignatedPoint", "TEMPDELTA", 1, 0, &period(begin, Some("2026-01-20T00:00:00Z")), "TEMP") + }; + // In force at the snapshot's instant: already in it. + let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "SNAP"), temp("2025-12-20T00:00:00Z")])); assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("SNAP".into())]); + // Begun since: over it. + let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "SNAP"), temp("2026-01-10T00:00:00Z")])); + assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("TEMP".into())]); +} + +#[test] +fn a_change_that_cant_be_read_is_left_out_and_a_snapshot_that_cant_is_unreadable() { + let bad_temp = slice("DesignatedPoint", "TEMPDELTA", 2, 0, r#""#, "TEMP"); + let (got, notes) = names(&message(&point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "BASE"), bad_temp])), "2026-01-15"); + assert_eq!(got, [Value::Text("BASE".into())]); + assert!(notes.iter().any(|m| m.contains("1 time slice with a validTime or featureLifetime that isn't a date not read")), "{notes:?}"); + let bad_snap = snapshot_at("not-a-date", "SNAP"); + let bytes = message(&(point("s", &[bad_snap]) + &point("b", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]))); + let notes = names(&bytes, "2026-01-15").1; + assert!(notes.iter().any(|m| m.contains("1 feature left out: the time slice that holds its state")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("canceled")), "{notes:?}"); } #[test] @@ -1617,6 +1629,23 @@ fn a_route_segment_whose_ends_arent_in_the_file_is_kept_and_said() { assert_eq!(rs.features.len(), 1); assert_eq!(rs.features[0].geometry, None); assert!(said(&out).iter().any(|m| m.contains("1 route segment is kept without a line")), "{:?}", said(&out)); + // The kind named and not in the file: not drawn to a point of another kind. + let members = named_at("DesignatedPoint", "same", 50.0, 10.0) + &named_at("DesignatedPoint", "far", 50.0, 12.0); + let out = read("t.xml", &message(&(members.clone() + &route_to("pointChoice_navaidSystem", "same"))), &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t RouteSegment").features[0].geometry, None); + // Both ends found: nothing said of it. + let out = read("t.xml", &message(&(members + &route_to("pointChoice_fixDesignatedPoint", "same"))), &at("2026-01-15")).unwrap(); + assert!(!said(&out).iter().any(|m| m.contains("kept without a line")), "{:?}", said(&out)); +} + +#[test] +fn a_structure_part_is_drawn_from_its_first_shape_that_can_be() { + let bad_point = r#"abc def"#; + let line = r#"52 -32 52.1 -32"#; + let out = read("t.xml", &structure(&part("A", &format!("{bad_point}{line}"))), &at("2026-01-15")).unwrap(); + let vs = &out.iter().find(|(d, _)| d.name.starts_with("t VerticalStructure")).unwrap().0; + assert!(matches!(vs.features[0].geometry, Some(Geometry::Line(_)))); + assert!(said(&out).iter().any(|m| m.contains("more than one shape")), "{:?}", said(&out)); } #[test] diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3308ebd038..3d440d997e 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -3241,7 +3241,7 @@ fn file_layers(s: &mut Session, p: &Value) -> CmdResult { } let bytes = rustgis_data::provenance::read(path).map_err(|e| format!("{path}: {e}"))?; // An AIXM message's layers at the date asked, as Add Data would add them: their names - // only, without drawing their shapes or keeping their values. + // only, its rows and values not kept. // Told by its name before it was read (in the browser): now by its contents. check_at(p, path, || rustgis_data::io::is_aixm(path, &bytes))?; if rustgis_data::io::is_aixm(path, &bytes) { @@ -5913,8 +5913,9 @@ pub(crate) fn add_cog(s: &mut Session, p: &Value, url: &str, probed: bool) -> Cm /// [`add_cog`], a GeoTIFF that can't be read now added all the same (unless `strict`), showing /// why: a project being imported keeps its layers. pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, probed: bool) -> CmdResult { - // An effective date is for an AIXM message: a GeoTIFF found at an address refuses it. - check_at(p, url, || false)?; + // An effective date is for an AIXM message: a GeoTIFF found at an address refuses it (named by + // its file name, so no key in the address is quoted). + check_at(p, &cog_name(url), || false)?; let stem = cog_name(url); let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&stem); let empty_before = super::map_is_empty(s); From 4b88d26111853a878d0228f1a0bb6bff3fcf9214 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:16:26 -0600 Subject: [PATCH 34/61] fix(data): AIXM features with an unreadable time slice that may apply are left out; snapshots keep temporary changes in force; the refusal of "at" doesn't quote addresses --- crates/data/src/aixm.rs | 29 +++++++++--------- crates/data/src/aixm/tests.rs | 56 +++++++++++++++++++++------------- crates/engine/src/cmd/layer.rs | 10 +++--- crates/engine/src/tests.rs | 3 +- 4 files changed, 56 insertions(+), 42 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 4a2b9c3d9c..97e26b1d98 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -383,8 +383,8 @@ struct Slice { canceled: bool, /// The feature's lifetime, when the slice says it. lifetime: Option<(Option, Option)>, - /// Its validity or lifetime isn't a date: it keeps its place among its corrections. A - /// BASELINE's that holds leaves the feature out; a change's is left out itself (counted). + /// Its validity or lifetime isn't a date: it keeps its place among its corrections, and + /// the feature is left out when it is the latest of them. unreadable: bool, } @@ -410,7 +410,7 @@ enum State { OnlyChanges, /// Every slice canceled. Canceled, - /// The state's latest correction (or every slice) has a validity that isn't a date. + /// A slice that may hold (the latest correction) has a validity that isn't a date. Unreadable, } @@ -441,15 +441,16 @@ fn state_at(slices: &[Slice], t: f64) -> State { } } } - // The state's latest correction isn't a date: what it is then can't be known. - if held.values().any(|s| s.unreadable && s.kind == Interpretation::Baseline) { + // A state or change whose latest correction isn't a date may hold at any date: what the + // feature is then can't be known, and showing it without that would be wrong. + if held.values().any(|s| s.unreadable) { return State::Unreadable; } let live: Vec<&Slice> = held.values().copied().chain(snapshots).filter(|s| !s.canceled && !s.unreadable).collect(); if live.is_empty() { return if slices.is_empty() { State::OnlyChanges - } else if slices.iter().all(|s| s.unreadable) { + } else if slices.iter().any(|s| s.unreadable) { State::Unreadable } else { State::Canceled @@ -492,10 +493,8 @@ fn state_at(slices: &[Slice], t: f64) -> State { { return State::OutsideLifetime; } - // A SNAPSHOT already holds the changes in force at its instant: only those begun since go - // over it. - let since = |s: &Slice| !snapshot || s.begin.is_some_and(|b| base.begin.is_none_or(|bb| b > bb)); - let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t) && since(s)).cloned().collect(); + // Over a SNAPSHOT too: one it already holds is put back over any PERMDELTA since. + let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).cloned().collect(); temps.sort_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); let temporary = temps.len(); changes.extend(temps); @@ -2969,7 +2968,7 @@ fn finish( notes.unreadable_state, "feature", "features", - "left out: the time slice that holds its state (the latest correction) has a validity that isn't a date", + "left out: a time slice of it that may apply (the latest correction) has a validity that isn't a date", ); say(&mut file, notes.no_slices, "feature", "features", "with no time slice RustGIS reads left out"); say( @@ -3237,8 +3236,8 @@ fn finish( ); say( layer.route_unlocated, - "route segment is kept without a line: a point its start or end names isn't in the file", - "route segments are kept without a line: a point their start or end names isn't in the file", + "route segment is kept without a line: a point its start or end names isn't in the file, or has no position on the date asked", + "route segments are kept without a line: a point their start or end names isn't in the file, or has no position on the date asked", ); say( layer.extra_shapes, @@ -3267,8 +3266,8 @@ fn finish( ); say( layer.snapshots, - "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked", - "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked", + "feature is a SNAPSHOT: its state at its own instant, with any changes the file gives since, which may not be its state on the date asked", + "features are SNAPSHOTs: their state at their own instant, with any changes the file gives since, which may not be their state on the date asked", ); say( layer.over_bytes, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 3dc7a8fd45..55672e956e 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1508,29 +1508,43 @@ fn a_chain_of_arcs_across_180_degrees_stays_whole() { // --------------------------------------------------------------------------------------------- #[test] -fn a_snapshot_takes_only_the_changes_begun_since_its_instant() { - let temp = |begin: &str| { - slice("DesignatedPoint", "TEMPDELTA", 1, 0, &period(begin, Some("2026-01-20T00:00:00Z")), "TEMP") - }; - // In force at the snapshot's instant: already in it. - let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "SNAP"), temp("2025-12-20T00:00:00Z")])); - assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("SNAP".into())]); - // Begun since: over it. - let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "SNAP"), temp("2026-01-10T00:00:00Z")])); +fn a_snapshot_keeps_a_temporary_change_over_a_permanent_one_since() { + let temp = slice( + "DesignatedPoint", + "TEMPDELTA", + 1, + 0, + &period("2025-12-20T00:00:00Z", Some("2026-01-20T00:00:00Z")), + "TEMP", + ); + let valid = r#"2026-01-10T00:00:00Z"#; + let perm = slice("DesignatedPoint", "PERMDELTA", 2, 0, valid, "PERM"); + let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "TEMP"), temp, perm])); assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("TEMP".into())]); + let (got, notes) = names(&bytes, "2026-02-15"); + assert_eq!(got, [Value::Text("PERM".into())]); + assert!(notes.iter().any(|m| m.contains("with any changes the file gives since")), "{notes:?}"); } #[test] -fn a_change_that_cant_be_read_is_left_out_and_a_snapshot_that_cant_is_unreadable() { - let bad_temp = slice("DesignatedPoint", "TEMPDELTA", 2, 0, r#""#, "TEMP"); - let (got, notes) = names(&message(&point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "BASE"), bad_temp])), "2026-01-15"); - assert_eq!(got, [Value::Text("BASE".into())]); - assert!(notes.iter().any(|m| m.contains("1 time slice with a validTime or featureLifetime that isn't a date not read")), "{notes:?}"); - let bad_snap = snapshot_at("not-a-date", "SNAP"); - let bytes = message(&(point("s", &[bad_snap]) + &point("b", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]))); - let notes = names(&bytes, "2026-01-15").1; - assert!(notes.iter().any(|m| m.contains("1 feature left out: the time slice that holds its state")), "{notes:?}"); - assert!(!notes.iter().any(|m| m.contains("canceled")), "{notes:?}"); +fn a_change_or_snapshot_that_cant_be_read_withholds_its_feature() { + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let temp = |corr, valid: &str| slice("DesignatedPoint", "TEMPDELTA", 2, corr, valid, "TEMP"); + let unknown = r#""#; + let base = baseline(1, 0, "2025-01-01T00:00:00Z", None, "BASE"); + for slices in [ + vec![base.clone(), temp(0, unknown)], + vec![base.clone(), temp(0, &period("2026-01-01T00:00:00Z", None)), temp(1, unknown)], + vec![snapshot_at("not-a-date", "SNAP")], + ] { + let (got, notes) = names(&message(&(point("a", &slices) + &kept)), "2026-01-15"); + assert_eq!(got, [Value::Text("KEPT".into())]); + assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice of it that may apply")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("canceled")), "{notes:?}"); + } + // One superseded by a correction that can be read withholds nothing. + let (got, _) = names(&message(&point("a", &[base, temp(0, unknown), temp(1, &period("2026-01-01T00:00:00Z", None))])), "2026-01-15"); + assert_eq!(got, [Value::Text("TEMP".into())]); } #[test] @@ -1542,10 +1556,10 @@ fn a_correction_that_cant_be_read_withholds_its_feature() { ); let (got, notes) = names(&bytes, "2026-01-15"); assert_eq!(got, [Value::Text("KEPT".into())]); - assert!(notes.iter().any(|m| m.contains("1 feature left out: the time slice that holds")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice of it that may apply")), "{notes:?}"); // A clean file says nothing of it. let notes = names(&message(&point("b", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")])), "2026-01-15").1; - assert!(!notes.iter().any(|m| m.contains("the time slice that holds")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("a time slice of it that may apply")), "{notes:?}"); } fn structure(parts: &str) -> Vec { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3d440d997e..deddb414ea 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2353,7 +2353,7 @@ pub(crate) fn check_at(p: &Value, file_name: &str, aixm: impl FnOnce() -> bool) /// own way of adding an address. pub fn check_url_at(p: &Value) -> Result<(), String> { let url = ps(p, "url").map(str::trim).unwrap_or(""); - check_at(p, url, || address_extension(url).is_none_or(|e| e == "xml" || e == "gml")).map(|_| ()) + check_at(p, "the file at that address", || address_extension(url).is_none_or(|e| e == "xml" || e == "gml")).map(|_| ()) } /// Whether a file named `path` may be an AIXM message: by its first bytes on the desktop, by its @@ -5055,7 +5055,7 @@ pub(crate) fn add_url(s: &mut Session, p: &Value) -> CmdResult { // An effective date is for an AIXM message only (`.xml`, `.gml`, or an address that doesn't // say, whose contents are checked once fetched): refused for any other address, before it is // opened in place or downloaded. - check_at(p, url, || address_extension(url).is_none_or(|e| e == "xml" || e == "gml"))?; + check_at(p, "the file at that address", || address_extension(url).is_none_or(|e| e == "xml" || e == "gml"))?; let out = add_url_as_given(s, p).map_err(|e| crate::sources::message_with_address(url, &e))?; s.check_continuation(&owner)?; Ok(out) @@ -5913,9 +5913,9 @@ pub(crate) fn add_cog(s: &mut Session, p: &Value, url: &str, probed: bool) -> Cm /// [`add_cog`], a GeoTIFF that can't be read now added all the same (unless `strict`), showing /// why: a project being imported keeps its layers. pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, probed: bool) -> CmdResult { - // An effective date is for an AIXM message: a GeoTIFF found at an address refuses it (named by - // its file name, so no key in the address is quoted). - check_at(p, &cog_name(url), || false)?; + // An effective date is for an AIXM message: a GeoTIFF found at an address refuses it (the + // address isn't quoted: it can hold a key). + check_at(p, "the file at that address", || false)?; let stem = cog_name(url); let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&stem); let empty_before = super::map_is_empty(s); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8ad8c35c24..2896c9e5f9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24177,7 +24177,8 @@ fn aixm_messages_are_added_at_the_date_asked() { std::fs::write(&csv, "x,y\n1,2\n").unwrap(); let e = s.run("info.fileLayers", &json!({"path": csv.display().to_string(), "at": "2026-01-15"})).unwrap_err(); assert!(e.contains("isn't one"), "{e}"); - let e = s.run("layer.addUrl", &json!({"url": "https://example.com/roads.fgb", "at": "2026-01-15"})).unwrap_err(); + let e = s.run("layer.addUrl", &json!({"url": "https://example.com/roads.fgb?token=SECRET", "at": "2026-01-15"})).unwrap_err(); + assert!(!e.contains("SECRET"), "{e}"); assert!(e.contains("isn't one"), "{e}"); // An address with no extension found to be a GeoTIFF refuses it too, before it is added. let e = crate::cmd::layer::add_cog(&mut s, &json!({"at": "2026-01-15"}), "https://example.test/download", true).unwrap_err(); From 6d87132df1449e3ff4bc82a2540e04ce8a057d6b Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:22:59 -0600 Subject: [PATCH 35/61] fix(data): AIXM time slices with an unreadable date judged by the dates they do have; canceled corrections of them counted as canceled; a zip address keeps its hint --- crates/data/src/aixm.rs | 49 +++++++++++++++++++--------------- crates/data/src/aixm/tests.rs | 43 ++++++++++++++++++++++++++++- crates/engine/src/cmd/layer.rs | 9 +++++-- crates/engine/src/tests.rs | 2 ++ 4 files changed, 79 insertions(+), 24 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 97e26b1d98..30a08db0aa 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -384,7 +384,7 @@ struct Slice { /// The feature's lifetime, when the slice says it. lifetime: Option<(Option, Option)>, /// Its validity or lifetime isn't a date: it keeps its place among its corrections, and - /// the feature is left out when it is the latest of them. + /// the feature is left out when it is the latest of them and may apply on the date. unreadable: bool, } @@ -427,10 +427,7 @@ fn state_at(slices: &[Slice], t: f64) -> State { let mut snapshots: Vec<&Slice> = Vec::new(); for s in slices { if s.kind == Interpretation::Snapshot { - // A snapshot whose instant isn't a date can't be placed: not read (counted). - if !s.unreadable { - snapshots.push(s); - } + snapshots.push(s); continue; } let key = (s.kind as u8, s.sequence); @@ -441,19 +438,22 @@ fn state_at(slices: &[Slice], t: f64) -> State { } } } - // A state or change whose latest correction isn't a date may hold at any date: what the - // feature is then can't be known, and showing it without that would be wrong. - if held.values().any(|s| s.unreadable) { + // Slices with a date that isn't one are judged by the dates they do have (one missing is + // open): where one may apply, what the feature is then can't be known, and showing it without + // that would be wrong. + let (unread, live): (Vec<&Slice>, Vec<&Slice>) = + held.values().copied().chain(snapshots).filter(|s| !s.canceled).partition(|s| s.unreadable); + let unread_of = |k: Interpretation| unread.iter().copied().filter(move |s| s.kind == k); + if unread_of(Interpretation::Baseline).any(|s| in_force(s.begin, s.end, t)) { return State::Unreadable; } - let live: Vec<&Slice> = held.values().copied().chain(snapshots).filter(|s| !s.canceled && !s.unreadable).collect(); if live.is_empty() { - return if slices.is_empty() { - State::OnlyChanges - } else if slices.iter().any(|s| s.unreadable) { - State::Unreadable - } else { - State::Canceled + let state = unread_of(Interpretation::Baseline).chain(unread_of(Interpretation::Snapshot)).next(); + return match (state, unread.is_empty()) { + (Some(_), _) => State::Unreadable, + (None, false) => State::OnlyChanges, + _ if slices.is_empty() => State::OnlyChanges, + _ => State::Canceled, }; } let of = |k: Interpretation| live.iter().copied().filter(move |s| s.kind == k); @@ -474,9 +474,11 @@ fn state_at(slices: &[Slice], t: f64) -> State { of(Interpretation::Snapshot).min_by(|a, b| a.begin.unwrap_or(f64::MAX).total_cmp(&b.begin.unwrap_or(f64::MAX))) }); match snap { - Some(s) if baselines == 0 => (s, true), _ if baselines > 0 => return State::NotInForce, - _ => return State::OnlyChanges, + // Another that can't be placed may be the nearer. + _ if unread_of(Interpretation::Snapshot).next().is_some() => return State::Unreadable, + Some(s) => (s, true), + None => return State::OnlyChanges, } } }; @@ -493,6 +495,11 @@ fn state_at(slices: &[Slice], t: f64) -> State { { return State::OutsideLifetime; } + let perm_may_apply = |s: &Slice| s.begin.is_none_or(|b| b <= t && base.begin.is_none_or(|bb| b > bb)); + if unread_of(Interpretation::PermDelta).any(perm_may_apply) || unread_of(Interpretation::TempDelta).any(|s| in_force(s.begin, s.end, t)) + { + return State::Unreadable; + } // Over a SNAPSHOT too: one it already holds is put back over any PERMDELTA since. let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).cloned().collect(); temps.sort_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); @@ -579,8 +586,8 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); if bad { trouble.dates += 1; - let (begin, end, canceled, lifetime) = (None, None, false, None); - return Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime, unreadable: true }); + // The dates that are dates are kept: they say when it can't apply. + return Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled: false, lifetime: None, unreadable: true }); } trouble.numbers += usize::from(unread_number.get()); trouble.empty += empty.get(); @@ -3266,8 +3273,8 @@ fn finish( ); say( layer.snapshots, - "feature is a SNAPSHOT: its state at its own instant, with any changes the file gives since, which may not be its state on the date asked", - "features are SNAPSHOTs: their state at their own instant, with any changes the file gives since, which may not be their state on the date asked", + "feature is a SNAPSHOT: its state at its own instant, with the changes the file gives for the date asked, which may not be its state on the date asked", + "features are SNAPSHOTs: their state at their own instant, with the changes the file gives for the date asked, which may not be their state on the date asked", ); say( layer.over_bytes, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 55672e956e..ae83536ad1 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1523,7 +1523,47 @@ fn a_snapshot_keeps_a_temporary_change_over_a_permanent_one_since() { assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("TEMP".into())]); let (got, notes) = names(&bytes, "2026-02-15"); assert_eq!(got, [Value::Text("PERM".into())]); - assert!(notes.iter().any(|m| m.contains("with any changes the file gives since")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("with the changes the file gives for the date asked")), "{notes:?}"); +} + +#[test] +fn a_temporary_change_begun_after_a_snapshot_goes_over_it() { + let temp = slice( + "DesignatedPoint", + "TEMPDELTA", + 1, + 0, + &period("2026-01-10T00:00:00Z", Some("2026-01-20T00:00:00Z")), + "TEMP", + ); + let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "SNAP"), temp])); + assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("TEMP".into())]); + assert_eq!(names(&bytes, "2026-01-25").0, [Value::Text("SNAP".into())]); +} + +#[test] +fn a_slice_that_cant_be_read_hides_nothing_it_cant_apply_to() { + let base = baseline(1, 0, "2025-01-01T00:00:00Z", None, "BASE"); + // A change that begins after the date, its end not a date. + let later = slice("DesignatedPoint", "TEMPDELTA", 2, 0, &period("2030-01-01T00:00:00Z", Some("bad")), "X"); + let bytes = message(&point("a", &[base.clone(), later])); + assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("BASE".into())]); + let e = read("t.xml", &bytes, &at("2031-01-15")).unwrap_err().to_string(); + assert!(e.contains("may apply"), "{e}"); + // A permanent change begun before the state on the date, its lifetime not a date. + let instant = r#"2024-01-01T00:00:00Z"#; + let lifetime = r#"bad"#; + let old = slice("DesignatedPoint", "PERMDELTA", 2, 0, instant, lifetime); + assert_eq!(names(&message(&point("a", &[base, old])), "2026-01-15").0, [Value::Text("BASE".into())]); +} + +#[test] +fn a_canceled_correction_of_one_that_cant_be_read_is_canceled() { + let bad = slice("DesignatedPoint", "BASELINE", 1, 0, &period("bad", None), &named_point("A")); + let canceled = slice("DesignatedPoint", "BASELINE", 1, 1, r#""#, ""); + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let notes = names(&message(&(point("a", &[bad, canceled]) + &kept)), "2026-01-15").1; + assert!(notes.iter().any(|m| m.contains("canceled")) && !notes.iter().any(|m| m.contains("may apply")), "{notes:?}"); } #[test] @@ -1536,6 +1576,7 @@ fn a_change_or_snapshot_that_cant_be_read_withholds_its_feature() { vec![base.clone(), temp(0, unknown)], vec![base.clone(), temp(0, &period("2026-01-01T00:00:00Z", None)), temp(1, unknown)], vec![snapshot_at("not-a-date", "SNAP")], + vec![snapshot_at("2025-01-01T00:00:00Z", "OLD"), snapshot_at("not-a-date", "NEW")], ] { let (got, notes) = names(&message(&(point("a", &slices) + &kept)), "2026-01-15"); assert_eq!(got, [Value::Text("KEPT".into())]); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index deddb414ea..e59334c324 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2348,12 +2348,17 @@ pub(crate) fn check_at(p: &Value, file_name: &str, aixm: impl FnOnce() -> bool) rustgis_data::aixm::Options::at_text(at) } +/// How a refusal names an address: not quoted, since it can hold a key, but a zip said as one. +fn unquoted(url: &str) -> &'static str { + if address_extension(url).as_deref() == Some("zip") { "that address's .zip" } else { "the file at that address" } +} + /// Refuses an effective date (`"at"`) for an address that can't be an AIXM message (one naming /// another kind of file), before anything is downloaded: what `layer.addUrl` does, for the app's /// own way of adding an address. pub fn check_url_at(p: &Value) -> Result<(), String> { let url = ps(p, "url").map(str::trim).unwrap_or(""); - check_at(p, "the file at that address", || address_extension(url).is_none_or(|e| e == "xml" || e == "gml")).map(|_| ()) + check_at(p, unquoted(url), || address_extension(url).is_none_or(|e| e == "xml" || e == "gml")).map(|_| ()) } /// Whether a file named `path` may be an AIXM message: by its first bytes on the desktop, by its @@ -5055,7 +5060,7 @@ pub(crate) fn add_url(s: &mut Session, p: &Value) -> CmdResult { // An effective date is for an AIXM message only (`.xml`, `.gml`, or an address that doesn't // say, whose contents are checked once fetched): refused for any other address, before it is // opened in place or downloaded. - check_at(p, "the file at that address", || address_extension(url).is_none_or(|e| e == "xml" || e == "gml"))?; + check_at(p, unquoted(url), || address_extension(url).is_none_or(|e| e == "xml" || e == "gml"))?; let out = add_url_as_given(s, p).map_err(|e| crate::sources::message_with_address(url, &e))?; s.check_continuation(&owner)?; Ok(out) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2896c9e5f9..35c21111d1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24179,6 +24179,8 @@ fn aixm_messages_are_added_at_the_date_asked() { assert!(e.contains("isn't one"), "{e}"); let e = s.run("layer.addUrl", &json!({"url": "https://example.com/roads.fgb?token=SECRET", "at": "2026-01-15"})).unwrap_err(); assert!(!e.contains("SECRET"), "{e}"); + let z = s.run("layer.addUrl", &json!({"url": "https://example.com/a.zip?token=SECRET", "at": "2026-01-15"})).unwrap_err(); + assert!(z.contains("unzip it") && !z.contains("SECRET"), "{z}"); assert!(e.contains("isn't one"), "{e}"); // An address with no extension found to be a GeoTIFF refuses it too, before it is added. let e = crate::cmd::layer::add_cog(&mut s, &json!({"at": "2026-01-15"}), "https://example.test/download", true).unwrap_err(); From ebc5324545427820d20c2f6923a9434c814e8b44 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:07:37 -0600 Subject: [PATCH 36/61] fix(data): AIXM states follow the Temporality Concept: snapshots as they are, slices with no period withhold; route segments never points; shapes and patches lost beside drawn ones counted --- crates/data/src/aixm.rs | 236 +++++++++++++++++++++++----------- crates/data/src/aixm/tests.rs | 121 ++++++++++++----- 2 files changed, 255 insertions(+), 102 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 30a08db0aa..a25d1e1528 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -10,7 +10,9 @@ //! the date overlay it, each property they hold replacing all of that property's values (`nil` //! removing them). A validity period includes its start and excludes its end. Features not in force //! at the date, withdrawn before it (`featureLifetime`) or with only changes and no state are left -//! out and counted. +//! out and counted, as are those with a slice that may apply then whose validity can't be read. A +//! feature with no BASELINE is shown as its nearest SNAPSHOT, without changes over it (it already +//! holds those of its instant), and said. //! //! Geometry is the GML 3.2 the AIXM profile allows (OGC 12-028r1): points, curves of //! `GeodesicString`, `Geodesic`, `LineStringSegment`, `Arc`, `ArcString`, `Circle`, @@ -400,8 +402,9 @@ struct Feature { /// What a feature is at the date. enum State { - /// Built from these slices: the state, then the changes over it in order. - Use { base: Slice, changes: Vec, snapshot: bool, temporary: usize }, + /// Built from these slices: the state, then the changes over it in order. `skipped`: a + /// SNAPSHOT the file gives changes since, not applied to it. + Use { base: Slice, changes: Vec, snapshot: bool, temporary: usize, skipped: bool }, /// Not in force at the date: its validity is all before or after it. NotInForce, /// Withdrawn by the date, or not yet created (`featureLifetime`). @@ -444,50 +447,43 @@ fn state_at(slices: &[Slice], t: f64) -> State { let (unread, live): (Vec<&Slice>, Vec<&Slice>) = held.values().copied().chain(snapshots).filter(|s| !s.canceled).partition(|s| s.unreadable); let unread_of = |k: Interpretation| unread.iter().copied().filter(move |s| s.kind == k); + let of = |k: Interpretation| live.iter().copied().filter(move |s| s.kind == k); if unread_of(Interpretation::Baseline).any(|s| in_force(s.begin, s.end, t)) { return State::Unreadable; } - if live.is_empty() { - let state = unread_of(Interpretation::Baseline).chain(unread_of(Interpretation::Snapshot)).next(); - return match (state, unread.is_empty()) { - (Some(_), _) => State::Unreadable, - (None, false) => State::OnlyChanges, - _ if slices.is_empty() => State::OnlyChanges, - _ => State::Canceled, - }; - } - let of = |k: Interpretation| live.iter().copied().filter(move |s| s.kind == k); - // The BASELINE in force; of several (which the concept doesn't allow), the latest started. + // The BASELINE in force; of several (which the concept doesn't allow, TS_009), the latest + // started, the later in the file on a tie (sequence numbers give no order, 3.6). + let started = |s: &Slice| s.begin.unwrap_or(f64::NEG_INFINITY); let base = of(Interpretation::Baseline) .filter(|s| in_force(s.begin, s.end, t)) - .max_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); + .max_by(|a, b| started(a).total_cmp(&started(b)).then(a.range.0.cmp(&b.range.0))); let (base, snapshot) = match base { Some(b) => (b, false), + None if of(Interpretation::Baseline).chain(unread_of(Interpretation::Baseline)).next().is_some() => return State::NotInForce, + // A snapshot that can't be placed may be the nearest. + None if unread_of(Interpretation::Snapshot).next().is_some() => return State::Unreadable, None => { - let baselines = of(Interpretation::Baseline).count(); // A SNAPSHOT is a state at its own instant: the one nearest before the date, else the // earliest after it. let snap = of(Interpretation::Snapshot) .filter(|s| s.begin.is_none_or(|b| b <= t)) - .max_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN))) - .or_else(|| { - of(Interpretation::Snapshot).min_by(|a, b| a.begin.unwrap_or(f64::MAX).total_cmp(&b.begin.unwrap_or(f64::MAX))) - }); + .max_by(|a, b| started(a).total_cmp(&started(b))) + .or_else(|| of(Interpretation::Snapshot).min_by(|a, b| started(a).total_cmp(&started(b)))); match snap { - _ if baselines > 0 => return State::NotInForce, - // Another that can't be placed may be the nearer. - _ if unread_of(Interpretation::Snapshot).next().is_some() => return State::Unreadable, Some(s) => (s, true), + None if live.is_empty() && unread.is_empty() && !slices.is_empty() => return State::Canceled, None => return State::OnlyChanges, } } }; // PERMDELTAs since the state began, up to the date, in order. - let mut changes: Vec = of(Interpretation::PermDelta) - .filter(|s| s.begin.is_none_or(|b| b <= t) && s.begin.is_some_and(|b| base.begin.is_none_or(|bb| b > bb))) - .cloned() - .collect(); - changes.sort_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); + let since = |s: &Slice| s.begin.is_none_or(|b| b <= t && base.begin.is_none_or(|bb| b > bb)); + if unread_of(Interpretation::PermDelta).any(since) { + return State::Unreadable; + } + let by_start = |a: &Slice, b: &Slice| started(a).total_cmp(&started(b)).then(a.range.0.cmp(&b.range.0)); + let mut changes: Vec = of(Interpretation::PermDelta).filter(|s| since(s)).cloned().collect(); + changes.sort_by(by_start); // The feature's lifetime: the latest a slice in force says. let lifetime = changes.iter().rev().find_map(|s| s.lifetime).or(base.lifetime); if let Some((from, until)) = lifetime @@ -495,17 +491,22 @@ fn state_at(slices: &[Slice], t: f64) -> State { { return State::OutsideLifetime; } - let perm_may_apply = |s: &Slice| s.begin.is_none_or(|b| b <= t && base.begin.is_none_or(|bb| b > bb)); - if unread_of(Interpretation::PermDelta).any(perm_may_apply) || unread_of(Interpretation::TempDelta).any(|s| in_force(s.begin, s.end, t)) - { + let unread_temps = unread_of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).count(); + let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).cloned().collect(); + if snapshot { + // A SNAPSHOT is a baseline and its temporary changes already merged (3.4), and changes are + // defined over a baseline: it is shown as it is, and changes it can't hold are said. + let begun_since = temps.iter().filter(|s| base.begin.is_none_or(|bb| s.begin.is_none_or(|b| b > bb))).count(); + let skipped = !changes.is_empty() || begun_since > 0 || unread_temps > 0; + return State::Use { base: base.clone(), changes: Vec::new(), snapshot, temporary: 0, skipped }; + } + if unread_temps > 0 { return State::Unreadable; } - // Over a SNAPSHOT too: one it already holds is put back over any PERMDELTA since. - let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).cloned().collect(); - temps.sort_by(|a, b| a.begin.unwrap_or(f64::MIN).total_cmp(&b.begin.unwrap_or(f64::MIN)).then(a.sequence.cmp(&b.sequence))); + temps.sort_by(by_start); let temporary = temps.len(); changes.extend(temps); - State::Use { base: base.clone(), changes, snapshot, temporary } + State::Use { base: base.clone(), changes, snapshot, temporary, skipped: false } } /// What the first pass found wrong with a slice. @@ -545,6 +546,8 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro let empty = std::cell::Cell::new(0); let (mut begin, mut end, mut canceled) = (None, None, false); let mut bad = false; + // One without a validTime (which every slice has, if only empty) could apply at any date. + bad |= child(s, "validTime").is_none(); if let Some(v) = child(s, "validTime") { match elements(v).next() { Some(p) if local(&p) == "TimePeriod" => { @@ -558,6 +561,8 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }); } Some(i) if local(&i) == "TimeInstant" => { + // A BASELINE and a TEMPDELTA have a period (TS_001, TS_003): until when isn't said. + bad |= matches!(kind, Interpretation::Baseline | Interpretation::TempDelta); begin = position(child(i, "timePosition"), &empty).unwrap_or_else(|()| { bad = true; None @@ -572,17 +577,21 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }, } } - let lifetime = child(s, "featureLifetime").and_then(|l| elements(l).find(|p| local(p) == "TimePeriod")).map(|p| { - let from = position(child(p, "beginPosition"), &empty).unwrap_or_else(|()| { - bad = true; - None - }); - let until = position(child(p, "endPosition"), &empty).unwrap_or_else(|()| { - bad = true; - None + // A TEMPDELTA has no lifetime (TS_016): one it gives isn't used. + let lifetime = child(s, "featureLifetime") + .filter(|_| kind != Interpretation::TempDelta) + .and_then(|l| elements(l).find(|p| local(p) == "TimePeriod")) + .map(|p| { + let from = position(child(p, "beginPosition"), &empty).unwrap_or_else(|()| { + bad = true; + None + }); + let until = position(child(p, "endPosition"), &empty).unwrap_or_else(|()| { + bad = true; + None + }); + (from, until) }); - (from, until) - }); let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); if bad { trouble.dates += 1; @@ -631,6 +640,10 @@ struct Axes { struct ShapeNotes { /// A route segment with no curve whose start or end names a point that isn't in the file. route_unlocated: bool, + /// A route segment with no curve and an end that isn't given or can't be read. + route_no_ends: bool, + /// Shapes that couldn't be read beside one of the same row that is drawn. + parts_lost: usize, /// A vertical structure part holding more than one shape: the first that can be is drawn. extra_shapes: bool, /// Features drawn with arcs or circles as points along them. @@ -709,6 +722,8 @@ impl ShapeNotes { ShapeNotes { route_unlocated: self.route_unlocated, extra_shapes: self.extra_shapes, + route_no_ends: self.route_no_ends, + parts_lost: self.parts_lost, rings_lost: self.rings_lost, referenced: self.referenced, border_allowance: self.border_allowance, @@ -722,6 +737,8 @@ impl ShapeNotes { fn absorb(&mut self, o: ShapeNotes) { self.route_unlocated |= o.route_unlocated; self.extra_shapes |= o.extra_shapes; + self.route_no_ends |= o.route_no_ends; + self.parts_lost += o.parts_lost; self.arcs |= o.arcs; self.coarse |= o.coarse; self.zm |= o.zm; @@ -1317,14 +1334,18 @@ impl Shapes { g.descendants().filter(|d| d.is_element() && is_gml(d) && matches!(local(d), "PolygonPatch" | "Polygon")).collect() }; let mut polys = Vec::new(); + let mut lost_to_border = 0; for p in patches { // Each patch's notes its own: how it was drawn is said only when it is kept. let mut pn = ShapeNotes::default(); - // A ring lost to a border by reference is said as that, once. - let said = |n: &ShapeNotes| n.referenced + n.border_allowance + n.border_unusable; + // A patch lost to a border by reference is said as that; beside one drawn, counted too. let outer = elements(p).find(|c| local(c) == "exterior").and_then(|b| self.ring(b, &mut pn)); let Some(outer) = outer else { - pn.rings_lost += usize::from(said(&pn) == 0); + if pn.referenced + pn.border_allowance + pn.border_unusable == 0 { + pn.rings_lost += 1; + } else { + lost_to_border += 1; + } notes.absorb(pn.losses_only()); continue; }; @@ -1347,7 +1368,11 @@ impl Shapes { polys.push(rings); } } - (!polys.is_empty()).then_some(Geometry::Polygon(polys)) + if polys.is_empty() { + return None; + } + notes.rings_lost += lost_to_border; + Some(Geometry::Polygon(polys)) } /// A shape read without saying what it finds: one read again elsewhere (a border or point kept @@ -1573,6 +1598,10 @@ struct Layer { unlocated: usize, /// Route segments whose start or end names a point not in the file: kept without a line. route_unlocated: usize, + /// Route segments with an end that isn't given or can't be read: kept without a line. + route_no_ends: usize, + /// Shapes that couldn't be read beside one of the same row that is drawn. + parts_lost: usize, /// Vertical structure parts holding more than one shape: the first that can be is drawn. extra_shapes: usize, /// Borders by reference followed whole. @@ -1630,6 +1659,8 @@ impl Layer { self.path_unread += usize::from(n.path_unread); self.route_unlocated += usize::from(n.route_unlocated); self.extra_shapes += usize::from(n.extra_shapes); + self.route_no_ends += usize::from(n.route_no_ends); + self.parts_lost += n.parts_lost; self.border_allowance += n.border_allowance; self.border_unusable += n.border_unusable; } @@ -2184,7 +2215,9 @@ struct FileNotes { not_in_force: usize, outside_lifetime: usize, no_state: usize, - /// Features whose slice that holds has a validity that isn't a date: left out. + /// Features shown as a SNAPSHOT that the file gives changes since, not applied. + snapshot_changes: usize, + /// Features with a slice that may apply whose validity isn't a date: left out. unreadable_state: usize, canceled: usize, unreadable_members: usize, @@ -2347,7 +2380,10 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result (base, changes, snapshot, temporary), + State::Use { base, changes, snapshot, temporary, skipped } => { + notes.snapshot_changes += usize::from(skipped); + (base, changes, snapshot, temporary) + } State::NotInForce => { notes.not_in_force += 1; continue; @@ -2573,6 +2609,15 @@ fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { } } +/// Whether a shape gives no positions: empty ones (as the FAA writes a position it doesn't have), +/// and no border or point by reference. +fn no_positions(g: Node) -> bool { + !g.descendants().any(|d| { + d.is_element() + && ((is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()) || d.attribute((XLINK, "href")).is_some()) + }) +} + /// Whether a route segment's start or end links to a point that isn't in the file. fn names_a_missing_point(props: &[Node], shapes: &Shapes) -> bool { props.iter().filter(|p| matches!(local(p), "start" | "end")).any(|p| { @@ -2667,9 +2712,7 @@ fn feature_rows( // reference point and its boundary); a kind with one is one layer, titled by its kind. // A shape whose positions are all empty (``, as the FAA writes a // position it doesn't have) gives none: said as no geometry, not as unreadable. - let empty = - !g.descendants().any(|d| d.is_element() && is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()); - let empty = empty && geom.is_none(); + let empty = geom.is_none() && no_positions(g); let bad = geom.is_none() && !empty; let i = layers.push(kind, &name, geom, r, Some(¬es), change); first = first.or(i); @@ -2695,13 +2738,30 @@ fn feature_rows( layers.push(kind, "curveExtent", line.map(Geometry::Line), row.clone(), Some(¬es), change); return true; } - if parts.is_empty() { - // A route segment naming ends that aren't in the file: in its layer without a line. - if kind == "RouteSegment" && names_a_missing_point(props, shapes) { - let notes = ShapeNotes { route_unlocated: true, ..ShapeNotes::default() }; - layers.push(kind, "curveExtent", None, row.clone(), Some(¬es), change); - return true; + // One that can't be drawn between its ends is in its layer without a line, an end written in + // place kept as its values: it isn't a point. + if kind == "RouteSegment" { + let missing = names_a_missing_point(props, shapes); + let mut in_records = 0; + for p in parts.iter().chain(&unlocated) { + if matches!(local(p), "start" | "end") { + // Read for what it finds (its system): it isn't drawn. + for g in nested_shapes(*p) { + let _ = shapes.shape(g, &mut ShapeNotes::default()); + } + } else { + in_records += nested_shapes(*p).len(); + } + row.property(*p, ""); + } + let notes = ShapeNotes { route_unlocated: missing, route_no_ends: !missing, ..ShapeNotes::default() }; + let i = layers.push(kind, "curveExtent", None, row.clone(), Some(¬es), change); + if let Some(l) = layers.at(i) { + l.shapes_in_records += in_records; } + return true; + } + if parts.is_empty() { return false; } // Rows copied for the records stay within what the file's size allows: checked before each @@ -2737,17 +2797,24 @@ fn feature_rows( for g in nested_shapes(p) { let mut notes = ShapeNotes::default(); let geom = shapes.shape(g, &mut notes); + notes.parts_lost += usize::from(geom.is_none() && !no_positions(g)); let (gs, n) = by_family.entry(element_family(local(&g))).or_default(); n.absorb(if geom.is_some() { notes } else { notes.losses_only() }); gs.extend(geom); } // What the feature was is said once for it, with its first row. let change = if k == 0 { change } else { (false, false) }; - for (label, (gs, notes)) in by_family { - let bad = gs.is_empty(); + for (label, (gs, mut notes)) in by_family { + // None drawn: the row is said to be without a shape, not its shapes one by one. + let bad = gs.is_empty() && notes.parts_lost > 0; + let empty = gs.is_empty() && !bad; + if bad { + notes.parts_lost = 0; + } let i = layers.push(kind, label, merged(gs), r.clone(), Some(¬es), change); if let Some(l) = layers.at(i) { l.unreadable += usize::from(bad); + l.shapeless += usize::from(empty); } } } @@ -2894,26 +2961,28 @@ fn vertical_structure( let mut r = row.clone(); let mut notes = ShapeNotes::default(); let mut geom = None; - let (mut bad, mut seen) = (false, false); + let mut unreadable = 0; for p in elements(vp) { match shape_in(p) { Some(g) if !is_nil(&p) => { if geom.is_some() { - notes.extra_shapes = true; + notes.extra_shapes |= !no_positions(g); } else { let mut own = ShapeNotes::default(); geom = shapes.shape(g, &mut own); - // One that can't be read beside one drawn: not drawn, and said. - notes.extra_shapes |= seen && geom.is_some(); - seen = true; - bad = geom.is_none(); - notes.absorb(if bad { own.losses_only() } else { own }); + unreadable += usize::from(geom.is_none() && !no_positions(g)); + notes.absorb(if geom.is_some() { own } else { own.losses_only() }); } r.shape_values(g, &format!("part_{}", local(&p))); } _ => r.property(p, "part_"), } } + // Beside one drawn, those that couldn't be read are counted one by one. + let bad = geom.is_none() && unreadable > 0; + if geom.is_some() { + notes.parts_lost += unreadable; + } room = room.saturating_sub(r.weight()); rows.push((geom, r, notes, bad)); } @@ -2977,6 +3046,13 @@ fn finish( "features", "left out: a time slice of it that may apply (the latest correction) has a validity that isn't a date", ); + say( + &mut file, + notes.snapshot_changes, + "feature", + "features", + "shown as a SNAPSHOT without the changes the file gives since its instant: changes apply to a BASELINE", + ); say(&mut file, notes.no_slices, "feature", "features", "with no time slice RustGIS reads left out"); say( &mut file, @@ -3000,7 +3076,13 @@ fn finish( "features", "left out: a change to it in force then couldn't be read within the limits the file's size sets", ); - say(&mut file, notes.bad_dates, "time slice", "time slices", "with a validTime or featureLifetime that isn't a date not read"); + say( + &mut file, + notes.bad_dates, + "time slice", + "time slices", + "with no validTime, or with one or a featureLifetime that can't be read (a feature it may apply to is left out)", + ); say( &mut file, notes.unreadable_members, @@ -3246,6 +3328,16 @@ fn finish( "route segment is kept without a line: a point its start or end names isn't in the file, or has no position on the date asked", "route segments are kept without a line: a point their start or end names isn't in the file, or has no position on the date asked", ); + say( + layer.route_no_ends, + "route segment is kept without a line: its start or end isn't given, or can't be read", + "route segments are kept without a line: their start or end isn't given, or can't be read", + ); + say( + layer.parts_lost, + "shape couldn't be read and is left out: its row is drawn from its other shapes", + "shapes couldn't be read and are left out: their rows are drawn from their other shapes", + ); say( layer.extra_shapes, "structure part holds more than one shape: one is drawn (the first that can be), the others' values kept", @@ -3273,8 +3365,8 @@ fn finish( ); say( layer.snapshots, - "feature is a SNAPSHOT: its state at its own instant, with the changes the file gives for the date asked, which may not be its state on the date asked", - "features are SNAPSHOTs: their state at their own instant, with the changes the file gives for the date asked, which may not be their state on the date asked", + "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked", + "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked", ); say( layer.over_bytes, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index ae83536ad1..6471ab52f4 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1163,7 +1163,7 @@ fn an_empty_valid_time_cancels_only_when_it_says_so() { let members = point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]) + &point("b", &[unknown]); let (got, notes) = names(&message(&members), "2026-01-15"); assert_eq!(got, [Value::Text("KEPT".into())]); - assert!(notes.iter().any(|m| m.starts_with("1 time slice with a validTime or featureLifetime that isn't a date")), "{notes:?}"); + assert!(notes.iter().any(|m| m.starts_with("1 time slice with no validTime, or with one")), "{notes:?}"); assert!(!notes.iter().any(|m| m.contains("canceled")), "{notes:?}"); } @@ -1507,38 +1507,96 @@ fn a_chain_of_arcs_across_180_degrees_stays_whole() { // From the second review of PR #2819. // --------------------------------------------------------------------------------------------- +fn change(kind: &str, seq: u32, valid: &str, body: &str) -> String { + slice("DesignatedPoint", kind, seq, 0, valid, body) +} + +fn instant(date: &str) -> String { + format!(r#"{date}"#) +} + #[test] -fn a_snapshot_keeps_a_temporary_change_over_a_permanent_one_since() { - let temp = slice( - "DesignatedPoint", - "TEMPDELTA", - 1, - 0, - &period("2025-12-20T00:00:00Z", Some("2026-01-20T00:00:00Z")), - "TEMP", - ); - let valid = r#"2026-01-10T00:00:00Z"#; - let perm = slice("DesignatedPoint", "PERMDELTA", 2, 0, valid, "PERM"); - let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "TEMP"), temp, perm])); - assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("TEMP".into())]); - let (got, notes) = names(&bytes, "2026-02-15"); - assert_eq!(got, [Value::Text("PERM".into())]); - assert!(notes.iter().any(|m| m.contains("with the changes the file gives for the date asked")), "{notes:?}"); +fn a_snapshot_is_shown_as_it_is_and_changes_since_are_said() { + let snap = snapshot_at("2026-01-01T00:00:00Z", "SNAP"); + let temp = |from: &str| change("TEMPDELTA", 1, &period(from, Some("2026-01-20T00:00:00Z")), "TEMP"); + let perm = change("PERMDELTA", 1, &instant("2026-01-10T00:00:00Z"), "PERM"); + for (slices, said) in [ + (vec![snap.clone()], false), + // In force at its instant: it holds it already. + (vec![snap.clone(), temp("2025-12-20T00:00:00Z")], false), + (vec![snap.clone(), temp("2026-01-10T00:00:00Z")], true), + (vec![snap.clone(), perm], true), + ] { + let (got, notes) = names(&message(&point("s", &slices)), "2026-01-15"); + assert_eq!(got, [Value::Text("SNAP".into())]); + assert_eq!(notes.iter().any(|m| m.contains("1 feature shown as a SNAPSHOT without the changes")), said, "{notes:?}"); + } + // Withdrawn since: not shown. + let end = r#"2020-01-01T00:00:00Z2026-01-10T00:00:00Z"#; + let bytes = message(&point("s", &[snap, change("PERMDELTA", 1, &instant("2026-01-10T00:00:00Z"), end)])); + assert!(read("t.xml", &bytes, &at("2026-01-15")).is_err()); } #[test] -fn a_temporary_change_begun_after_a_snapshot_goes_over_it() { - let temp = slice( - "DesignatedPoint", - "TEMPDELTA", - 1, - 0, - &period("2026-01-10T00:00:00Z", Some("2026-01-20T00:00:00Z")), - "TEMP", +fn a_slice_whose_period_isnt_said_withholds_its_feature_while_it_may_apply() { + let base = baseline(1, 0, "2025-01-01T00:00:00Z", None, "BASE"); + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let temp = |valid: &str| change("TEMPDELTA", 1, valid, "TEMP"); + let run = |t: String, date| names(&message(&(point("a", &[base.clone(), t]) + &kept)), date).0; + assert_eq!(run(temp(""), "2026-01-15"), [Value::Text("KEPT".into())]); + // An instant where a period is required: not before it, at least. + let t = temp(&instant("2026-01-01T00:00:00Z")); + assert_eq!(run(t.clone(), "2026-01-15"), [Value::Text("KEPT".into())]); + assert_eq!(run(t, "2025-12-15").len(), 2); + // A lifetime on a temporary change isn't used, read or not. + let lifetime = r#"TEMPbad"#; + let t = change("TEMPDELTA", 1, &period("2026-01-01T00:00:00Z", None), lifetime); + assert!(run(t, "2026-01-15").contains(&Value::Text("TEMP".into()))); +} + +#[test] +fn a_route_segment_is_never_drawn_as_a_point() { + let written = r#"50 10"#; + let missing = r#""#; + let nil = r#""#; + for (start, why) in [(missing, "names isn't in the file"), (nil, "start or end isn't given")] { + let body = format!("{start}{written}"); + let seg = feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let out = read("t.xml", &message(&seg), &at("2026-01-15")).unwrap(); + assert_eq!(layer(&out, "t RouteSegment").features[0].geometry, None); + assert!(said(&out).iter().any(|m| m.contains(why)), "{:?}", said(&out)); + } +} + +#[test] +fn a_shape_lost_beside_one_drawn_is_counted() { + let light = |pos: &str| { + format!(r#"{pos}"#) + }; + let run = |second: &str| { + let body = format!( + "{}{}", + light("52 -32"), + light(second) + ); + let f = feature("LightSystem", "l", &[slice("LightSystem", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + said(&read("t.xml", &message(&f), &at("2026-01-15")).unwrap()) + }; + assert!(run("abc def").iter().any(|m| m.contains("1 shape couldn't be read and is left out"))); + assert!(!run("52.1 -32").iter().any(|m| m.contains("left out"))); + assert!(!run("").iter().any(|m| m.contains("left out"))); +} + +#[test] +fn a_patch_lost_to_a_border_beside_one_drawn_is_counted() { + let lost = r#""#; + let square = r#"52 9 52 11 54 11 54 9 52 9"#; + let body = format!( + r#"{lost}{square}"# ); - let bytes = message(&point("s", &[snapshot_at("2026-01-01T00:00:00Z", "SNAP"), temp])); - assert_eq!(names(&bytes, "2026-01-15").0, [Value::Text("TEMP".into())]); - assert_eq!(names(&bytes, "2026-01-25").0, [Value::Text("SNAP".into())]); + let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let notes = said(&read("t.xml", &message(&f), &at("2026-01-15")).unwrap()); + assert!(notes.iter().any(|m| m.contains("1 ring or surface patch was left out")), "{notes:?}"); } #[test] @@ -1563,7 +1621,10 @@ fn a_canceled_correction_of_one_that_cant_be_read_is_canceled() { let canceled = slice("DesignatedPoint", "BASELINE", 1, 1, r#""#, ""); let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); let notes = names(&message(&(point("a", &[bad, canceled]) + &kept)), "2026-01-15").1; - assert!(notes.iter().any(|m| m.contains("canceled")) && !notes.iter().any(|m| m.contains("may apply")), "{notes:?}"); + assert!( + notes.iter().any(|m| m.contains("canceled")) && !notes.iter().any(|m| m.contains("feature left out: a time slice")), + "{notes:?}" + ); } #[test] @@ -1700,7 +1761,7 @@ fn a_structure_part_is_drawn_from_its_first_shape_that_can_be() { let out = read("t.xml", &structure(&part("A", &format!("{bad_point}{line}"))), &at("2026-01-15")).unwrap(); let vs = &out.iter().find(|(d, _)| d.name.starts_with("t VerticalStructure")).unwrap().0; assert!(matches!(vs.features[0].geometry, Some(Geometry::Line(_)))); - assert!(said(&out).iter().any(|m| m.contains("more than one shape")), "{:?}", said(&out)); + assert!(said(&out).iter().any(|m| m.contains("1 shape couldn't be read and is left out")), "{:?}", said(&out)); } #[test] From edd3bfe73bbfe9a5b4a0bb353d00567cbcc4426d Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:15:00 -0600 Subject: [PATCH 37/61] fix(data): AIXM time slices that can't be read judged by the dates they have; shapes of route segments' records counted; the guide says what is left out --- crates/data/src/aixm.rs | 62 ++++++++++++++++++++++----------- crates/data/src/aixm/tests.rs | 47 ++++++++++++++++++++++++- docs/user-guide/data-formats.md | 2 +- 3 files changed, 89 insertions(+), 22 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index a25d1e1528..ff34c06ee1 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -448,20 +448,21 @@ fn state_at(slices: &[Slice], t: f64) -> State { held.values().copied().chain(snapshots).filter(|s| !s.canceled).partition(|s| s.unreadable); let unread_of = |k: Interpretation| unread.iter().copied().filter(move |s| s.kind == k); let of = |k: Interpretation| live.iter().copied().filter(move |s| s.kind == k); - if unread_of(Interpretation::Baseline).any(|s| in_force(s.begin, s.end, t)) { - return State::Unreadable; - } // The BASELINE in force; of several (which the concept doesn't allow, TS_009), the latest // started, the later in the file on a tie (sequence numbers give no order, 3.6). let started = |s: &Slice| s.begin.unwrap_or(f64::NEG_INFINITY); let base = of(Interpretation::Baseline) .filter(|s| in_force(s.begin, s.end, t)) .max_by(|a, b| started(a).total_cmp(&started(b)).then(a.range.0.cmp(&b.range.0))); + // One that can't be read may hold instead, unless it began before the one that does. + if unread_of(Interpretation::Baseline) + .any(|s| in_force(s.begin, s.end, t) && !s.begin.is_some_and(|b| base.is_some_and(|base| b < started(base)))) + { + return State::Unreadable; + } let (base, snapshot) = match base { Some(b) => (b, false), None if of(Interpretation::Baseline).chain(unread_of(Interpretation::Baseline)).next().is_some() => return State::NotInForce, - // A snapshot that can't be placed may be the nearest. - None if unread_of(Interpretation::Snapshot).next().is_some() => return State::Unreadable, None => { // A SNAPSHOT is a state at its own instant: the one nearest before the date, else the // earliest after it. @@ -469,6 +470,16 @@ fn state_at(slices: &[Slice], t: f64) -> State { .filter(|s| s.begin.is_none_or(|b| b <= t)) .max_by(|a, b| started(a).total_cmp(&started(b))) .or_else(|| of(Interpretation::Snapshot).min_by(|a, b| started(a).total_cmp(&started(b)))); + // One that can't be read may be the one shown: nearer before the date, or (with none + // before it) earlier after. + let nearer = |u: &Slice| match (u.begin, snap) { + (Some(b), Some(s)) if started(s) <= t => b <= t && b >= started(s), + (Some(b), Some(s)) => b <= started(s), + _ => true, + }; + if unread_of(Interpretation::Snapshot).any(nearer) { + return State::Unreadable; + } match snap { Some(s) => (s, true), None if live.is_empty() && unread.is_empty() && !slices.is_empty() => return State::Canceled, @@ -491,16 +502,17 @@ fn state_at(slices: &[Slice], t: f64) -> State { { return State::OutsideLifetime; } - let unread_temps = unread_of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).count(); + let unread_temp = unread_of(Interpretation::TempDelta).any(|s| in_force(s.begin, s.end, t)); let mut temps: Vec = of(Interpretation::TempDelta).filter(|s| in_force(s.begin, s.end, t)).cloned().collect(); if snapshot { // A SNAPSHOT is a baseline and its temporary changes already merged (3.4), and changes are // defined over a baseline: it is shown as it is, and changes it can't hold are said. - let begun_since = temps.iter().filter(|s| base.begin.is_none_or(|bb| s.begin.is_none_or(|b| b > bb))).count(); - let skipped = !changes.is_empty() || begun_since > 0 || unread_temps > 0; + // A temporary change in force at its instant or on the date, not both, isn't reflected. + let differs = |s: &Slice| in_force(s.begin, s.end, t) != base.begin.is_some_and(|bb| in_force(s.begin, s.end, bb)); + let skipped = !changes.is_empty() || of(Interpretation::TempDelta).chain(unread_of(Interpretation::TempDelta)).any(differs); return State::Use { base: base.clone(), changes: Vec::new(), snapshot, temporary: 0, skipped }; } - if unread_temps > 0 { + if unread_temp { return State::Unreadable; } temps.sort_by(by_start); @@ -593,13 +605,16 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro (from, until) }); let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); - if bad { + trouble.numbers += usize::from(unread_number.get()); + trouble.empty += empty.get(); + // A PERMDELTA applies from its instant: one without can't be placed. + bad |= kind == Interpretation::PermDelta && begin.is_none(); + // A canceled slice is off the timeline, whatever else it holds. + if bad && !canceled { trouble.dates += 1; // The dates that are dates are kept: they say when it can't apply. return Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled: false, lifetime: None, unreadable: true }); } - trouble.numbers += usize::from(unread_number.get()); - trouble.empty += empty.get(); Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime, unreadable: false }) } @@ -2731,15 +2746,23 @@ fn feature_rows( if kind == "RouteSegment" && let Some((line, notes)) = between(props, shapes) { + let mut in_records = 0; for p in parts.iter().chain(&unlocated) { + // Its ends are in its line. + if line.is_none() || !matches!(local(p), "start" | "end") { + in_records += nested_shapes(*p).len(); + } row.property(*p, ""); } let line = line.map(|l| vec![l]); - layers.push(kind, "curveExtent", line.map(Geometry::Line), row.clone(), Some(¬es), change); + let i = layers.push(kind, "curveExtent", line.map(Geometry::Line), row.clone(), Some(¬es), change); + if let Some(l) = layers.at(i) { + l.shapes_in_records += in_records; + } return true; } - // One that can't be drawn between its ends is in its layer without a line, an end written in - // place kept as its values: it isn't a point. + // One that can't be drawn between its ends is in its layer without a line: the shapes of its + // records (an end written in place) are counted as not drawn. if kind == "RouteSegment" { let missing = names_a_missing_point(props, shapes); let mut in_records = 0; @@ -2749,9 +2772,8 @@ fn feature_rows( for g in nested_shapes(*p) { let _ = shapes.shape(g, &mut ShapeNotes::default()); } - } else { - in_records += nested_shapes(*p).len(); } + in_records += nested_shapes(*p).len(); row.property(*p, ""); } let notes = ShapeNotes { route_unlocated: missing, route_no_ends: !missing, ..ShapeNotes::default() }; @@ -3044,14 +3066,14 @@ fn finish( notes.unreadable_state, "feature", "features", - "left out: a time slice of it that may apply (the latest correction) has a validity that isn't a date", + "left out: a time slice of it that may apply (the latest correction) has no validTime or period, or a validTime or featureLifetime that can't be read", ); say( &mut file, notes.snapshot_changes, "feature", "features", - "shown as a SNAPSHOT without the changes the file gives since its instant: changes apply to a BASELINE", + "shown as a SNAPSHOT without the changes the file gives since its instant (begun or ended): changes apply to a BASELINE", ); say(&mut file, notes.no_slices, "feature", "features", "with no time slice RustGIS reads left out"); say( @@ -3081,7 +3103,7 @@ fn finish( notes.bad_dates, "time slice", "time slices", - "with no validTime, or with one or a featureLifetime that can't be read (a feature it may apply to is left out)", + "with no validTime or period, or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out)", ); say( &mut file, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 6471ab52f4..dc84c59810 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1163,7 +1163,7 @@ fn an_empty_valid_time_cancels_only_when_it_says_so() { let members = point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]) + &point("b", &[unknown]); let (got, notes) = names(&message(&members), "2026-01-15"); assert_eq!(got, [Value::Text("KEPT".into())]); - assert!(notes.iter().any(|m| m.starts_with("1 time slice with no validTime, or with one")), "{notes:?}"); + assert!(notes.iter().any(|m| m.starts_with("1 time slice with no validTime or period")), "{notes:?}"); assert!(!notes.iter().any(|m| m.contains("canceled")), "{notes:?}"); } @@ -1526,6 +1526,10 @@ fn a_snapshot_is_shown_as_it_is_and_changes_since_are_said() { (vec![snap.clone(), temp("2025-12-20T00:00:00Z")], false), (vec![snap.clone(), temp("2026-01-10T00:00:00Z")], true), (vec![snap.clone(), perm], true), + // In force at its instant, ended since. + (vec![snap.clone(), change("TEMPDELTA", 1, &period("2025-12-20T00:00:00Z", Some("2026-01-10T00:00:00Z")), "")], true), + // Not read to its end, but begun before it and may still hold: as any it holds already. + (vec![snap.clone(), change("TEMPDELTA", 1, &period("2025-12-20T00:00:00Z", Some("bad")), "")], false), ] { let (got, notes) = names(&message(&point("s", &slices)), "2026-01-15"); assert_eq!(got, [Value::Text("SNAP".into())]); @@ -1565,6 +1569,7 @@ fn a_route_segment_is_never_drawn_as_a_point() { let out = read("t.xml", &message(&seg), &at("2026-01-15")).unwrap(); assert_eq!(layer(&out, "t RouteSegment").features[0].geometry, None); assert!(said(&out).iter().any(|m| m.contains(why)), "{:?}", said(&out)); + assert!(said(&out).iter().any(|m| m.contains("1 shape")), "{:?}", said(&out)); } } @@ -1791,3 +1796,43 @@ fn a_long_edge_ending_near_180_degrees_is_near_a_point_across_it() { let (.., d) = nearest_on(&[Coord::new(179.0, 0.0), Coord::new(-179.0, 0.0)], Coord::new(0.0, 0.0)).unwrap(); assert!(d > 19_000_000.0, "{d}"); } + +#[test] +fn slices_that_cant_be_read_are_judged_by_the_dates_they_have() { + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let run = |slices: &[String]| names(&message(&(point("a", slices) + &kept)), "2026-01-15"); + let shown = |slices: &[String], name: &str| run(slices).0.contains(&Value::Text(name.into())); + let base = baseline(2, 0, "2025-01-01T00:00:00Z", None, "BASE"); + // A permanent change with no instant: not applied, and its feature withheld. + let unplaced = r#""#; + assert_eq!(run(&[base.clone(), change("PERMDELTA", 1, unplaced, "OTHER")]).0, [Value::Text("KEPT".into())]); + // A baseline that began before the one that holds, its end unread; and one that began after. + assert!(shown(&[baseline(1, 0, "2020-01-01T00:00:00Z", Some("bad"), "OLD"), base.clone()], "BASE")); + assert!(!shown(&[baseline(1, 0, "2025-06-01T00:00:00Z", Some("bad"), "NEW"), base.clone()], "BASE")); + // A snapshot that isn't the nearest, its lifetime unread; and one that is. + let lifetime = r#"bad"#; + let unread = |date: &str| snapshot_at(date, "UNREAD").replace("", &format!("{lifetime}")); + let snap = snapshot_at("2026-01-01T00:00:00Z", "SNAP"); + assert!(shown(&[unread("2024-01-01T00:00:00Z"), snap.clone()], "SNAP")); + assert!(shown(&[unread("2027-01-01T00:00:00Z"), snap.clone()], "SNAP")); + assert!(!shown(&[unread("2026-01-10T00:00:00Z"), snap], "SNAP")); + // A canceled change is canceled, whatever its lifetime says. + let canceled = change("PERMDELTA", 1, r#""#, lifetime); + assert!(shown(&[base.clone(), canceled], "BASE")); + // A number that isn't one is said on a slice that can't be read too. + let odd = baseline(7, 0, "bad", None, "X").replace("7<", "abc<"); + let notes = run(&[base, odd]).1; + assert!(notes.iter().any(|m| m.contains("number that isn't a number read as 0")), "{notes:?}"); +} + +#[test] +fn a_drawn_route_segment_says_the_other_shapes_of_its_records() { + let area = r#"52 9 52 11 54 11 52 9"#; + let members = named_at("DesignatedPoint", "near", 50.0, 10.0) + &named_at("DesignatedPoint", "far", 50.0, 12.0); + let plain = route_to("pointChoice_fixDesignatedPoint", "near"); + for (route, count) in [(plain.clone(), 0), (plain.replace("", &format!("{area}")), 1)] { + let out = read("t.xml", &message(&(members.clone() + &route)), &at("2026-01-15")).unwrap(); + assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some()); + assert_eq!(said(&out).iter().filter(|m| m.contains("1 shape")).count(), count, "{:?}", said(&out)); + } +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 0bea57b081..af6c6bc403 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled or given only as changes are left out and counted. Every value a feature holds is kept: simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT, without later changes, and said. Every value a feature holds is kept: simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From f03daeeabc7a6c0253eb3eabfbceb48aefd3f35f Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:18:33 -0600 Subject: [PATCH 38/61] fix(data): AIXM changes that may differ from a snapshot said; shapes in route segments' ends counted; notice wording --- crates/data/src/aixm.rs | 33 ++++++++++++++++++++------------ crates/data/src/aixm/tests.rs | 34 ++++++++++++++++++++++++++++----- docs/user-guide/data-formats.md | 2 +- 3 files changed, 51 insertions(+), 18 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index ff34c06ee1..322179f6ea 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -489,6 +489,7 @@ fn state_at(slices: &[Slice], t: f64) -> State { }; // PERMDELTAs since the state began, up to the date, in order. let since = |s: &Slice| s.begin.is_none_or(|b| b <= t && base.begin.is_none_or(|bb| b > bb)); + // One that can't be read may be a withdrawal: its feature is left out, a SNAPSHOT's too. if unread_of(Interpretation::PermDelta).any(since) { return State::Unreadable; } @@ -509,7 +510,10 @@ fn state_at(slices: &[Slice], t: f64) -> State { // defined over a baseline: it is shown as it is, and changes it can't hold are said. // A temporary change in force at its instant or on the date, not both, isn't reflected. let differs = |s: &Slice| in_force(s.begin, s.end, t) != base.begin.is_some_and(|bb| in_force(s.begin, s.end, bb)); - let skipped = !changes.is_empty() || of(Interpretation::TempDelta).chain(unread_of(Interpretation::TempDelta)).any(differs); + // One that can't be read may be either, unless the dates it has rule it out on both. + let may_differ = |s: &Slice| in_force(s.begin, s.end, t) || base.begin.is_none_or(|bb| in_force(s.begin, s.end, bb)); + let skipped = + !changes.is_empty() || of(Interpretation::TempDelta).any(differs) || unread_of(Interpretation::TempDelta).any(may_differ); return State::Use { base: base.clone(), changes: Vec::new(), snapshot, temporary: 0, skipped }; } if unread_temp { @@ -606,7 +610,6 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }); let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); trouble.numbers += usize::from(unread_number.get()); - trouble.empty += empty.get(); // A PERMDELTA applies from its instant: one without can't be placed. bad |= kind == Interpretation::PermDelta && begin.is_none(); // A canceled slice is off the timeline, whatever else it holds. @@ -615,6 +618,7 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro // The dates that are dates are kept: they say when it can't apply. return Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled: false, lifetime: None, unreadable: true }); } + trouble.empty += empty.get(); Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime, unreadable: false }) } @@ -2633,6 +2637,14 @@ fn no_positions(g: Node) -> bool { }) } +/// How many shapes of a route segment's record aren't drawn: those with positions, but for the +/// points its line is `drawn` between. +fn undrawn_shapes(p: Node, drawn: bool) -> usize { + let end = drawn && matches!(local(&p), "start" | "end"); + let in_line = |g: &Node| end && g.parent_element().is_some_and(|c| local(&c) == "pointChoice_position"); + nested_shapes(p).into_iter().filter(|g| !no_positions(*g) && !in_line(g)).count() +} + /// Whether a route segment's start or end links to a point that isn't in the file. fn names_a_missing_point(props: &[Node], shapes: &Shapes) -> bool { props.iter().filter(|p| matches!(local(p), "start" | "end")).any(|p| { @@ -2748,10 +2760,7 @@ fn feature_rows( { let mut in_records = 0; for p in parts.iter().chain(&unlocated) { - // Its ends are in its line. - if line.is_none() || !matches!(local(p), "start" | "end") { - in_records += nested_shapes(*p).len(); - } + in_records += undrawn_shapes(*p, line.is_some()); row.property(*p, ""); } let line = line.map(|l| vec![l]); @@ -2773,7 +2782,7 @@ fn feature_rows( let _ = shapes.shape(g, &mut ShapeNotes::default()); } } - in_records += nested_shapes(*p).len(); + in_records += undrawn_shapes(*p, false); row.property(*p, ""); } let notes = ShapeNotes { route_unlocated: missing, route_no_ends: !missing, ..ShapeNotes::default() }; @@ -3066,14 +3075,14 @@ fn finish( notes.unreadable_state, "feature", "features", - "left out: a time slice of it that may apply (the latest correction) has no validTime or period, or a validTime or featureLifetime that can't be read", + "left out: a time slice of it that may apply (the latest correction) has no validTime, period or instant, or a validTime or featureLifetime that can't be read", ); say( &mut file, notes.snapshot_changes, "feature", "features", - "shown as a SNAPSHOT without the changes the file gives since its instant (begun or ended): changes apply to a BASELINE", + "shown as a SNAPSHOT without changes the file gives (or may give) between its instant and the date asked: changes apply to a BASELINE", ); say(&mut file, notes.no_slices, "feature", "features", "with no time slice RustGIS reads left out"); say( @@ -3103,7 +3112,7 @@ fn finish( notes.bad_dates, "time slice", "time slices", - "with no validTime or period, or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out)", + "with no validTime, period or instant, or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out, or shown as its SNAPSHOT)", ); say( &mut file, @@ -3271,8 +3280,8 @@ fn finish( ); say( layer.shapes_in_records, - "shape in the records of features drawn from their own shape isn't drawn (its record's values are kept)", - "shapes in the records of features drawn from their own shapes aren't drawn (their records' values are kept)", + "shape in the records of features drawn from their own shape, or of route segments, isn't drawn (its record's values are kept)", + "shapes in the records of features drawn from their own shapes, or of route segments, aren't drawn (their records' values are kept)", ); say( layer.arcs, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index dc84c59810..55b611c0be 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1163,7 +1163,7 @@ fn an_empty_valid_time_cancels_only_when_it_says_so() { let members = point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]) + &point("b", &[unknown]); let (got, notes) = names(&message(&members), "2026-01-15"); assert_eq!(got, [Value::Text("KEPT".into())]); - assert!(notes.iter().any(|m| m.starts_with("1 time slice with no validTime or period")), "{notes:?}"); + assert!(notes.iter().any(|m| m.starts_with("1 time slice with no validTime, period or instant")), "{notes:?}"); assert!(!notes.iter().any(|m| m.contains("canceled")), "{notes:?}"); } @@ -1528,12 +1528,14 @@ fn a_snapshot_is_shown_as_it_is_and_changes_since_are_said() { (vec![snap.clone(), perm], true), // In force at its instant, ended since. (vec![snap.clone(), change("TEMPDELTA", 1, &period("2025-12-20T00:00:00Z", Some("2026-01-10T00:00:00Z")), "")], true), - // Not read to its end, but begun before it and may still hold: as any it holds already. - (vec![snap.clone(), change("TEMPDELTA", 1, &period("2025-12-20T00:00:00Z", Some("bad")), "")], false), + // An end that isn't a date may be between the two; a begin after both rules it out. + (vec![snap.clone(), change("TEMPDELTA", 1, &period("2025-12-20T00:00:00Z", Some("bad")), "")], true), + (vec![snap.clone(), change("TEMPDELTA", 1, "", "")], true), + (vec![snap.clone(), change("TEMPDELTA", 1, &period("2027-01-01T00:00:00Z", Some("bad")), "")], false), ] { let (got, notes) = names(&message(&point("s", &slices)), "2026-01-15"); assert_eq!(got, [Value::Text("SNAP".into())]); - assert_eq!(notes.iter().any(|m| m.contains("1 feature shown as a SNAPSHOT without the changes")), said, "{notes:?}"); + assert_eq!(notes.iter().any(|m| m.contains("1 feature shown as a SNAPSHOT without changes")), said, "{notes:?}"); } // Withdrawn since: not shown. let end = r#"2020-01-01T00:00:00Z2026-01-10T00:00:00Z"#; @@ -1830,9 +1832,31 @@ fn a_drawn_route_segment_says_the_other_shapes_of_its_records() { let area = r#"52 9 52 11 54 11 52 9"#; let members = named_at("DesignatedPoint", "near", 50.0, 10.0) + &named_at("DesignatedPoint", "far", 50.0, 12.0); let plain = route_to("pointChoice_fixDesignatedPoint", "near"); - for (route, count) in [(plain.clone(), 0), (plain.replace("", &format!("{area}")), 1)] { + for (route, count) in [ + (plain.clone(), 0), + (plain.replace("", &format!("{area}")), 1), + (plain.replace("", &format!("{area}")), 1), + ] { let out = read("t.xml", &message(&(members.clone() + &route)), &at("2026-01-15")).unwrap(); assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some()); assert_eq!(said(&out).iter().filter(|m| m.contains("1 shape")).count(), count, "{:?}", said(&out)); } } + +#[test] +fn an_empty_route_end_isnt_a_shape_that_isnt_drawn() { + let empty = r#""#; + let seg = feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), empty)]); + let notes = said(&read("t.xml", &message(&seg), &at("2026-01-15")).unwrap()); + assert!(!notes.iter().any(|m| m.contains("1 shape")), "{notes:?}"); +} + +#[test] +fn an_empty_instant_is_said_once() { + let perm = + change("PERMDELTA", 1, r#""#, ""); + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let notes = names(&message(&(point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "A"), perm]) + &kept)), "2026-01-15").1; + assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice")), "{notes:?}"); + assert!(!notes.iter().any(|m| m.contains("read as open")), "{notes:?}"); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index af6c6bc403..87cd8e4d06 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT, without later changes, and said. Every value a feature holds is kept: simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, is left out), and changes not applied to it are said. Every value a feature holds is kept: simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 08eb052c9c37d83776bdbde2a103628c27035c5a Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:23:26 -0600 Subject: [PATCH 39/61] fix(data): AIXM snapshot notice covers changes ahead of the date; notices name what a time slice needs --- crates/data/src/aixm.rs | 20 +++++++++++++------- crates/data/src/aixm/tests.rs | 8 ++++++-- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 322179f6ea..a56e38111b 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -510,10 +510,15 @@ fn state_at(slices: &[Slice], t: f64) -> State { // defined over a baseline: it is shown as it is, and changes it can't hold are said. // A temporary change in force at its instant or on the date, not both, isn't reflected. let differs = |s: &Slice| in_force(s.begin, s.end, t) != base.begin.is_some_and(|bb| in_force(s.begin, s.end, bb)); + // A snapshot after the date holds the PERMDELTAs up to its instant. + let ahead = |s: &Slice| s.begin.is_none_or(|b| t < b && base.begin.is_some_and(|bb| b <= bb)); + let perm_ahead = of(Interpretation::PermDelta).chain(unread_of(Interpretation::PermDelta)).any(ahead); // One that can't be read may be either, unless the dates it has rule it out on both. let may_differ = |s: &Slice| in_force(s.begin, s.end, t) || base.begin.is_none_or(|bb| in_force(s.begin, s.end, bb)); - let skipped = - !changes.is_empty() || of(Interpretation::TempDelta).any(differs) || unread_of(Interpretation::TempDelta).any(may_differ); + let skipped = !changes.is_empty() + || perm_ahead + || of(Interpretation::TempDelta).any(differs) + || unread_of(Interpretation::TempDelta).any(may_differ); return State::Use { base: base.clone(), changes: Vec::new(), snapshot, temporary: 0, skipped }; } if unread_temp { @@ -2633,7 +2638,8 @@ fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { fn no_positions(g: Node) -> bool { !g.descendants().any(|d| { d.is_element() - && ((is_gml(&d) && matches!(local(&d), "pos" | "posList") && !text_of(&d).is_empty()) || d.attribute((XLINK, "href")).is_some()) + && ((is_gml(&d) && matches!(local(&d), "pos" | "posList" | "coordinates" | "coord" | "X") && !text_of(&d).is_empty()) + || d.attribute((XLINK, "href")).is_some()) }) } @@ -2726,7 +2732,7 @@ fn feature_rows( // shapes in them (not drawn) are counted. let mut in_records = 0; for p in &parts { - in_records += nested_shapes(*p).len(); + in_records += undrawn_shapes(*p, false); row.property(*p, ""); } let mut first = None; @@ -3075,14 +3081,14 @@ fn finish( notes.unreadable_state, "feature", "features", - "left out: a time slice of it that may apply (the latest correction) has no validTime, period or instant, or a validTime or featureLifetime that can't be read", + "left out: a time slice of it that may apply (the latest correction) has no validTime of the kind it needs (a period, or a PERMDELTA's instant), or a validTime or featureLifetime that can't be read", ); say( &mut file, notes.snapshot_changes, "feature", "features", - "shown as a SNAPSHOT without changes the file gives (or may give) between its instant and the date asked: changes apply to a BASELINE", + "shown as a SNAPSHOT that doesn't reflect changes begun or ended (or that may have) between its instant and the date asked", ); say(&mut file, notes.no_slices, "feature", "features", "with no time slice RustGIS reads left out"); say( @@ -3112,7 +3118,7 @@ fn finish( notes.bad_dates, "time slice", "time slices", - "with no validTime, period or instant, or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out, or shown as its SNAPSHOT)", + "with no validTime of the kind it needs (a period, or a PERMDELTA's instant), or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out, or shown as its SNAPSHOT)", ); say( &mut file, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 55b611c0be..bdb8484941 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1163,7 +1163,7 @@ fn an_empty_valid_time_cancels_only_when_it_says_so() { let members = point("a", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]) + &point("b", &[unknown]); let (got, notes) = names(&message(&members), "2026-01-15"); assert_eq!(got, [Value::Text("KEPT".into())]); - assert!(notes.iter().any(|m| m.starts_with("1 time slice with no validTime, period or instant")), "{notes:?}"); + assert!(notes.iter().any(|m| m.starts_with("1 time slice with no validTime of the kind it needs")), "{notes:?}"); assert!(!notes.iter().any(|m| m.contains("canceled")), "{notes:?}"); } @@ -1535,8 +1535,12 @@ fn a_snapshot_is_shown_as_it_is_and_changes_since_are_said() { ] { let (got, notes) = names(&message(&point("s", &slices)), "2026-01-15"); assert_eq!(got, [Value::Text("SNAP".into())]); - assert_eq!(notes.iter().any(|m| m.contains("1 feature shown as a SNAPSHOT without changes")), said, "{notes:?}"); + assert_eq!(notes.iter().any(|m| m.contains("1 feature shown as a SNAPSHOT that doesn't reflect changes")), said, "{notes:?}"); } + // One after the date, holding a permanent change not in force yet. + let ahead = change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), "SNAP"); + let notes = names(&message(&point("s", &[snap.clone(), ahead])), "2025-12-01").1; + assert!(notes.iter().any(|m| m.contains("SNAPSHOT that doesn't reflect")), "{notes:?}"); // Withdrawn since: not shown. let end = r#"2020-01-01T00:00:00Z2026-01-10T00:00:00Z"#; let bytes = message(&point("s", &[snap, change("PERMDELTA", 1, &instant("2026-01-10T00:00:00Z"), end)])); From aeb9aa74c6a73a5927bebd3bb395794ab9df4521 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:06:15 -0600 Subject: [PATCH 40/61] fix: "at" refused for a window of a GeoTIFF and a service's decoded answer; AIXM snapshots with no instant withheld; a second position in a route end counted; the guide says the limits --- crates/data/src/aixm.rs | 38 +++++++++++++++++++----------- crates/data/src/aixm/tests.rs | 40 ++++++++++++++++++++++++++++---- crates/engine/src/cmd/layer.rs | 3 +++ crates/engine/src/cmd/service.rs | 6 ++++- crates/engine/src/tests.rs | 15 ++++++++++++ docs/user-guide/data-formats.md | 2 +- 6 files changed, 85 insertions(+), 19 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index a56e38111b..bac4ef188b 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -23,7 +23,8 @@ //! clockwise from true north, the arc running from the start angle to the end angle (clockwise when //! the start is the smaller); in a longitude-first one (CRS84), counter-clockwise from east. //! -//! Every value a feature holds is kept on its rows. A property's simple value is a column, with its +//! Every value a feature holds is kept on its rows, within limits on columns, nesting and memory (those +//! past them are counted). A property's simple value is a column, with its //! unit (`_uom`), why it is missing (`_nilReason`) and its other attributes, and for a reference to //! another feature the identifier it names (`urn:uuid:` left off) and its title (`_title`). A //! value nested in records is a column named by its path (`authority_1_type`, @@ -615,8 +616,9 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }); let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); trouble.numbers += usize::from(unread_number.get()); - // A PERMDELTA applies from its instant: one without can't be placed. - bad |= kind == Interpretation::PermDelta && begin.is_none(); + // A PERMDELTA applies from its instant and a SNAPSHOT is a state at its: one without can't be + // placed (TS_002, TS_004). + bad |= matches!(kind, Interpretation::PermDelta | Interpretation::Snapshot) && begin.is_none(); // A canceled slice is off the timeline, whatever else it holds. if bad && !canceled { trouble.dates += 1; @@ -2644,11 +2646,20 @@ fn no_positions(g: Node) -> bool { } /// How many shapes of a route segment's record aren't drawn: those with positions, but for the -/// points its line is `drawn` between. -fn undrawn_shapes(p: Node, drawn: bool) -> usize { - let end = drawn && matches!(local(&p), "start" | "end"); - let in_line = |g: &Node| end && g.parent_element().is_some_and(|c| local(&c) == "pointChoice_position"); - nested_shapes(p).into_iter().filter(|g| !no_positions(*g) && !in_line(g)).count() +/// ones its line is drawn between (`in_line`). +fn undrawn_shapes(p: Node, in_line: &[roxmltree::NodeId]) -> usize { + nested_shapes(p).into_iter().filter(|g| !no_positions(*g) && !in_line.contains(&g.id())).count() +} + +/// The shapes of a route segment's ends written in place: those [`between`] draws its line between. +fn written_ends(props: &[Node], shapes: &Shapes) -> Vec { + ["start", "end"] + .iter() + .filter_map(|name| match segment_end(props, name, shapes)? { + End::Written(g) => Some(g.id()), + End::Named(_) => None, + }) + .collect() } /// Whether a route segment's start or end links to a point that isn't in the file. @@ -2732,7 +2743,7 @@ fn feature_rows( // shapes in them (not drawn) are counted. let mut in_records = 0; for p in &parts { - in_records += undrawn_shapes(*p, false); + in_records += undrawn_shapes(*p, &[]); row.property(*p, ""); } let mut first = None; @@ -2764,9 +2775,10 @@ fn feature_rows( if kind == "RouteSegment" && let Some((line, notes)) = between(props, shapes) { + let in_line = if line.is_some() { written_ends(props, shapes) } else { Vec::new() }; let mut in_records = 0; for p in parts.iter().chain(&unlocated) { - in_records += undrawn_shapes(*p, line.is_some()); + in_records += undrawn_shapes(*p, &in_line); row.property(*p, ""); } let line = line.map(|l| vec![l]); @@ -2788,7 +2800,7 @@ fn feature_rows( let _ = shapes.shape(g, &mut ShapeNotes::default()); } } - in_records += undrawn_shapes(*p, false); + in_records += undrawn_shapes(*p, &[]); row.property(*p, ""); } let notes = ShapeNotes { route_unlocated: missing, route_no_ends: !missing, ..ShapeNotes::default() }; @@ -3081,7 +3093,7 @@ fn finish( notes.unreadable_state, "feature", "features", - "left out: a time slice of it that may apply (the latest correction) has no validTime of the kind it needs (a period, or a PERMDELTA's instant), or a validTime or featureLifetime that can't be read", + "left out: a time slice of it that may apply (the latest correction) has no validTime of the kind it needs (a period, or an instant for a PERMDELTA or SNAPSHOT), or a validTime or featureLifetime that can't be read", ); say( &mut file, @@ -3118,7 +3130,7 @@ fn finish( notes.bad_dates, "time slice", "time slices", - "with no validTime of the kind it needs (a period, or a PERMDELTA's instant), or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out, or shown as its SNAPSHOT)", + "with no validTime of the kind it needs (a period, or an instant for a PERMDELTA or SNAPSHOT), or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out, or shown as its SNAPSHOT)", ); say( &mut file, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index bdb8484941..b5726bc8dd 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1543,8 +1543,12 @@ fn a_snapshot_is_shown_as_it_is_and_changes_since_are_said() { assert!(notes.iter().any(|m| m.contains("SNAPSHOT that doesn't reflect")), "{notes:?}"); // Withdrawn since: not shown. let end = r#"2020-01-01T00:00:00Z2026-01-10T00:00:00Z"#; - let bytes = message(&point("s", &[snap, change("PERMDELTA", 1, &instant("2026-01-10T00:00:00Z"), end)])); - assert!(read("t.xml", &bytes, &at("2026-01-15")).is_err()); + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let bytes = message(&(point("s", &[snap, change("PERMDELTA", 1, &instant("2026-01-10T00:00:00Z"), end)]) + &kept)); + assert_eq!(names(&bytes, "2026-01-05").0.len(), 2); + let (got, notes) = names(&bytes, "2026-01-15"); + assert_eq!(got, [Value::Text("KEPT".into())]); + assert!(notes.iter().any(|m| m.contains("featureLifetime") && !m.contains("can't be read")), "{notes:?}"); } #[test] @@ -1814,14 +1818,23 @@ fn slices_that_cant_be_read_are_judged_by_the_dates_they_have() { assert_eq!(run(&[base.clone(), change("PERMDELTA", 1, unplaced, "OTHER")]).0, [Value::Text("KEPT".into())]); // A baseline that began before the one that holds, its end unread; and one that began after. assert!(shown(&[baseline(1, 0, "2020-01-01T00:00:00Z", Some("bad"), "OLD"), base.clone()], "BASE")); - assert!(!shown(&[baseline(1, 0, "2025-06-01T00:00:00Z", Some("bad"), "NEW"), base.clone()], "BASE")); + assert_eq!(run(&[baseline(1, 0, "2025-06-01T00:00:00Z", Some("bad"), "NEW"), base.clone()]).0, [Value::Text("KEPT".into())]); // A snapshot that isn't the nearest, its lifetime unread; and one that is. let lifetime = r#"bad"#; let unread = |date: &str| snapshot_at(date, "UNREAD").replace("", &format!("{lifetime}")); let snap = snapshot_at("2026-01-01T00:00:00Z", "SNAP"); assert!(shown(&[unread("2024-01-01T00:00:00Z"), snap.clone()], "SNAP")); assert!(shown(&[unread("2027-01-01T00:00:00Z"), snap.clone()], "SNAP")); - assert!(!shown(&[unread("2026-01-10T00:00:00Z"), snap], "SNAP")); + assert_eq!(run(&[unread("2026-01-10T00:00:00Z"), snap.clone()]).0, [Value::Text("KEPT".into())]); + // A snapshot with no instant can't be placed, so it isn't chosen over one that can. + for date in ["", "\" indeterminatePosition=\"unknown"] { + let dated = snapshot_at("2026-06-01T00:00:00Z", "LATER"); + let undated = snapshot_at("X", "UNDATED").replace( + "X", + if date.is_empty() { "" } else { r#""# }, + ); + assert_eq!(run(&[undated, dated]).0, [Value::Text("KEPT".into())]); + } // A canceled change is canceled, whatever its lifetime says. let canceled = change("PERMDELTA", 1, r#""#, lifetime); assert!(shown(&[base.clone(), canceled], "BASE")); @@ -1847,6 +1860,25 @@ fn a_drawn_route_segment_says_the_other_shapes_of_its_records() { } } +#[test] +fn a_second_position_in_a_route_end_is_counted() { + let point = |id: &str, pos: &str| { + format!( + r#"{pos}"# + ) + }; + let end = |name: &str, inner: &str| { + format!(r#"{inner}"#) + }; + for (second, count) in [("", 0), (point("g3", "40 10").as_str(), 1)] { + let body = end("start", &format!("{}{second}", point("g1", "50 10"))) + &end("end", &point("g2", "50 12")); + let seg = feature("RouteSegment", "rs", &[slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let out = read("t.xml", &message(&seg), &at("2026-01-15")).unwrap(); + assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some()); + assert_eq!(said(&out).iter().filter(|m| m.contains("1 shape")).count(), count, "{:?}", said(&out)); + } +} + #[test] fn an_empty_route_end_isnt_a_shape_that_isnt_drawn() { let empty = r#""#; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index e59334c324..b561d94e1d 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6227,6 +6227,8 @@ fn no_geolibre_state(p: &Value) -> Result<(), String> { /// Refuses what can't be a window of `url`, before anything is fetched. fn window_checks(p: &Value, url: &str, scan: bool) -> Result<(), String> { + // A window is of a GeoTIFF: an effective date, which is for an AIXM message, is refused. + check_at(p, "a window of a GeoTIFF", || false)?; no_geolibre_state(p)?; if scan || b(p, "whole") == Some(true) || rustgis_data::time::is_template(url) { return Err(format!( @@ -6877,6 +6879,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { // with no axes to check against bounds. if let Some(i) = s.landed_reads.iter().position(|(d, _)| *d == id) { let (_, read) = s.landed_reads.remove(i); + check_at(p, "the service's answer", || false)?; let r = add_read(s, p, *read, b(p, "zoom"))?; return added_download(s, p, r, service || coverage, &url); } diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 0624097137..80cb5d6e2a 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -662,7 +662,11 @@ pub(crate) fn add_service_layer( } // Read in protocol buffer pages: their positions as the service's system places them, so // there are no axes to check. - Downloaded::Read(read) => super::layer::add_read(s, p, *read, zoom)?, + Downloaded::Read(read) => { + // Never an AIXM message, so an effective date is refused. + super::layer::check_at(p, "the service's answer", || false)?; + super::layer::add_read(s, p, *read, zoom)? + } }; mark_service_source(s, &r, url); match &drawing { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 35c21111d1..f657a14d8c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24181,6 +24181,21 @@ fn aixm_messages_are_added_at_the_date_asked() { assert!(!e.contains("SECRET"), "{e}"); let z = s.run("layer.addUrl", &json!({"url": "https://example.com/a.zip?token=SECRET", "at": "2026-01-15"})).unwrap_err(); assert!(z.contains("unzip it") && !z.contains("SECRET"), "{z}"); + // A window of a GeoTIFF, before it is read; and a service's answer read already. + let e = s.run("layer.addUrl", &json!({"url": "https://example.test/download", "bbox": [0, 0, 1, 1], "at": "2026-01-15"})).unwrap_err(); + assert!(e.contains("a window of a GeoTIFF isn't one"), "{e}"); + for (at, refused) in [(json!("2026-01-15"), true), (json!(null), false)] { + s.landed_reads.push(( + 7, + Box::new(( + rustgis_data::Dataset::new("pbf", rustgis_data::GeometryType::Point, Vec::new()), + rustgis_data::ReadReport::default(), + )), + )); + let r = + s.run("layer.addDownload", &json!({"id": 7, "url": "https://example.test/FeatureServer/0/query", "service": true, "at": at})); + assert_eq!(r.as_ref().is_err_and(|e| e.contains("the service's answer isn't one")), refused, "{r:?}"); + } assert!(e.contains("isn't one"), "{e}"); // An address with no extension found to be a GeoTIFF refuses it too, before it is added. let e = crate::cmd::layer::add_cog(&mut s, &json!({"at": "2026-01-15"}), "https://example.test/download", true).unwrap_err(); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 87cd8e4d06..100841ce14 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, is left out), and changes not applied to it are said. Every value a feature holds is kept: simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, is left out), and changes not applied to it are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values past them are counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 9a52548e5dd769a80eec998103fa46ae27163fc4 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:12:06 -0600 Subject: [PATCH 41/61] fix: a decoded service download refused for "at" is kept; AIXM route shapes told apart across time slices; a later snapshot isn't shown before its feature's creation --- crates/data/src/aixm.rs | 21 +++++++++++++++------ crates/data/src/aixm/tests.rs | 26 ++++++++++++++++++++++++++ crates/engine/src/cmd/layer.rs | 4 +--- crates/engine/src/tests.rs | 26 +++++++++++--------------- docs/user-guide/data-formats.md | 2 +- 5 files changed, 54 insertions(+), 25 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index bac4ef188b..27c273d4ad 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -513,7 +513,15 @@ fn state_at(slices: &[Slice], t: f64) -> State { let differs = |s: &Slice| in_force(s.begin, s.end, t) != base.begin.is_some_and(|bb| in_force(s.begin, s.end, bb)); // A snapshot after the date holds the PERMDELTAs up to its instant. let ahead = |s: &Slice| s.begin.is_none_or(|b| t < b && base.begin.is_some_and(|bb| b <= bb)); - let perm_ahead = of(Interpretation::PermDelta).chain(unread_of(Interpretation::PermDelta)).any(ahead); + // One of those may be the feature's creation. + if unread_of(Interpretation::PermDelta).any(ahead) { + return State::Unreadable; + } + let created = |s: &Slice| s.lifetime.is_some_and(|(from, _)| from.is_some_and(|f| t < f)); + if of(Interpretation::PermDelta).any(|s| ahead(s) && created(s)) { + return State::OutsideLifetime; + } + let perm_ahead = of(Interpretation::PermDelta).any(ahead); // One that can't be read may be either, unless the dates it has rule it out on both. let may_differ = |s: &Slice| in_force(s.begin, s.end, t) || base.begin.is_none_or(|bb| in_force(s.begin, s.end, bb)); let skipped = !changes.is_empty() @@ -2647,16 +2655,17 @@ fn no_positions(g: Node) -> bool { /// How many shapes of a route segment's record aren't drawn: those with positions, but for the /// ones its line is drawn between (`in_line`). -fn undrawn_shapes(p: Node, in_line: &[roxmltree::NodeId]) -> usize { - nested_shapes(p).into_iter().filter(|g| !no_positions(*g) && !in_line.contains(&g.id())).count() +fn undrawn_shapes(p: Node, in_line: &[Node]) -> usize { + nested_shapes(p).into_iter().filter(|g| !no_positions(*g) && !in_line.contains(g)).count() } -/// The shapes of a route segment's ends written in place: those [`between`] draws its line between. -fn written_ends(props: &[Node], shapes: &Shapes) -> Vec { +/// The shapes of a route segment's ends written in place: those [`between`] draws its line between +/// (nodes, not their ids: each slice is a document of its own). +fn written_ends<'a, 'i>(props: &[Node<'a, 'i>], shapes: &Shapes) -> Vec> { ["start", "end"] .iter() .filter_map(|name| match segment_end(props, name, shapes)? { - End::Written(g) => Some(g.id()), + End::Written(g) => Some(g), End::Named(_) => None, }) .collect() diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index b5726bc8dd..9907340fef 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1879,6 +1879,32 @@ fn a_second_position_in_a_route_end_is_counted() { } } +#[test] +fn a_route_segments_shapes_are_told_apart_across_time_slices() { + // The same node of two documents: the change's start, in the line, and the state's area, not. + let written = |name: &str, pos: &str| { + format!( + r#"{pos}"# + ) + }; + let body = written("area", "40 10") + &written("end", "50 12"); + let base = slice("RouteSegment", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body); + let temp = slice("RouteSegment", "TEMPDELTA", 1, 0, &period("2026-01-01T00:00:00Z", None), &written("start", "50 10")); + let out = read("t.xml", &message(&feature("RouteSegment", "rs", &[base, temp])), &at("2026-01-15")).unwrap(); + assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some()); + assert!(said(&out).iter().any(|m| m.contains("1 shape")), "{:?}", said(&out)); +} + +#[test] +fn a_snapshot_after_its_features_creation_isnt_shown_before_it() { + let life = r#"2025-12-10T00:00:00Z"#; + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let slices = [snapshot_at("2026-01-01T00:00:00Z", "SNAP"), change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), life)]; + let bytes = message(&(point("s", &slices) + &kept)); + assert_eq!(names(&bytes, "2025-12-01").0, [Value::Text("KEPT".into())]); + assert_eq!(names(&bytes, "2025-12-20").0.len(), 2); +} + #[test] fn an_empty_route_end_isnt_a_shape_that_isnt_drawn() { let empty = r#""#; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index b561d94e1d..8a6da7463d 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6227,8 +6227,6 @@ fn no_geolibre_state(p: &Value) -> Result<(), String> { /// Refuses what can't be a window of `url`, before anything is fetched. fn window_checks(p: &Value, url: &str, scan: bool) -> Result<(), String> { - // A window is of a GeoTIFF: an effective date, which is for an AIXM message, is refused. - check_at(p, "a window of a GeoTIFF", || false)?; no_geolibre_state(p)?; if scan || b(p, "whole") == Some(true) || rustgis_data::time::is_template(url) { return Err(format!( @@ -6878,8 +6876,8 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { // A download read already (an ArcGIS layer's protocol buffer pages, joined): added as read, // with no axes to check against bounds. if let Some(i) = s.landed_reads.iter().position(|(d, _)| *d == id) { - let (_, read) = s.landed_reads.remove(i); check_at(p, "the service's answer", || false)?; + let (_, read) = s.landed_reads.remove(i); let r = add_read(s, p, *read, b(p, "zoom"))?; return added_download(s, p, r, service || coverage, &url); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f657a14d8c..d49eca3f48 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24181,21 +24181,17 @@ fn aixm_messages_are_added_at_the_date_asked() { assert!(!e.contains("SECRET"), "{e}"); let z = s.run("layer.addUrl", &json!({"url": "https://example.com/a.zip?token=SECRET", "at": "2026-01-15"})).unwrap_err(); assert!(z.contains("unzip it") && !z.contains("SECRET"), "{z}"); - // A window of a GeoTIFF, before it is read; and a service's answer read already. - let e = s.run("layer.addUrl", &json!({"url": "https://example.test/download", "bbox": [0, 0, 1, 1], "at": "2026-01-15"})).unwrap_err(); - assert!(e.contains("a window of a GeoTIFF isn't one"), "{e}"); - for (at, refused) in [(json!("2026-01-15"), true), (json!(null), false)] { - s.landed_reads.push(( - 7, - Box::new(( - rustgis_data::Dataset::new("pbf", rustgis_data::GeometryType::Point, Vec::new()), - rustgis_data::ReadReport::default(), - )), - )); - let r = - s.run("layer.addDownload", &json!({"id": 7, "url": "https://example.test/FeatureServer/0/query", "service": true, "at": at})); - assert_eq!(r.as_ref().is_err_and(|e| e.contains("the service's answer isn't one")), refused, "{r:?}"); - } + // A service's answer read already: refused and kept, to be added without it. + s.landed_reads.push(( + 7, + Box::new((rustgis_data::Dataset::new("pbf", rustgis_data::GeometryType::Point, Vec::new()), rustgis_data::ReadReport::default())), + )); + let asked = json!({"id": 7, "url": "https://example.test/FeatureServer/0/query", "service": true}); + let mut dated = asked.clone(); + dated["at"] = json!("2026-01-15"); + let e2 = s.run("layer.addDownload", &dated).unwrap_err(); + assert!(e2.contains("the service's answer isn't one"), "{e2}"); + s.run("layer.addDownload", &asked).unwrap(); assert!(e.contains("isn't one"), "{e}"); // An address with no extension found to be a GeoTIFF refuses it too, before it is added. let e = crate::cmd::layer::add_cog(&mut s, &json!({"at": "2026-01-15"}), "https://example.test/download", true).unwrap_err(); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 100841ce14..ca470785dd 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, is left out), and changes not applied to it are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values past them are counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, is left out), and changes begun or ended between its instant and the date, which it doesn't reflect, are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 838f9f7de143f877ad761fa2caae349459452822 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:20:06 -0600 Subject: [PATCH 42/61] fix: refused decoded downloads aren't held, landed windows refuse "at"; AIXM later snapshots judged by the latest lifetime given --- crates/data/src/aixm.rs | 22 ++++++++++++++-------- crates/data/src/aixm/tests.rs | 18 +++++++++++++++++- crates/engine/src/cmd/layer.rs | 4 +++- crates/engine/src/tests.rs | 10 +++++++++- docs/user-guide/data-formats.md | 2 +- 5 files changed, 44 insertions(+), 12 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 27c273d4ad..1d9cf63253 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -513,15 +513,21 @@ fn state_at(slices: &[Slice], t: f64) -> State { let differs = |s: &Slice| in_force(s.begin, s.end, t) != base.begin.is_some_and(|bb| in_force(s.begin, s.end, bb)); // A snapshot after the date holds the PERMDELTAs up to its instant. let ahead = |s: &Slice| s.begin.is_none_or(|b| t < b && base.begin.is_some_and(|bb| b <= bb)); - // One of those may be the feature's creation. - if unread_of(Interpretation::PermDelta).any(ahead) { - return State::Unreadable; - } - let created = |s: &Slice| s.lifetime.is_some_and(|(from, _)| from.is_some_and(|f| t < f)); - if of(Interpretation::PermDelta).any(|s| ahead(s) && created(s)) { - return State::OutsideLifetime; + // One of those may be the feature's creation, unless the snapshot's lifetime (in force on + // the date, above) or a change by then says it existed. Of those read, the latest to give a + // lifetime says. + let known = + base.lifetime.is_some_and(|(from, _)| from.is_some()) || of(Interpretation::PermDelta).any(|s| s.begin.is_some_and(|b| b <= t)); + if !known { + if unread_of(Interpretation::PermDelta).any(ahead) { + return State::Unreadable; + } + let last = of(Interpretation::PermDelta).filter(|s| ahead(s) && s.lifetime.is_some()).max_by(|a, b| by_start(a, b)); + if last.and_then(|s| s.lifetime).is_some_and(|(from, _)| from.is_some_and(|f| t < f)) { + return State::OutsideLifetime; + } } - let perm_ahead = of(Interpretation::PermDelta).any(ahead); + let perm_ahead = of(Interpretation::PermDelta).chain(unread_of(Interpretation::PermDelta)).any(ahead); // One that can't be read may be either, unless the dates it has rule it out on both. let may_differ = |s: &Slice| in_force(s.begin, s.end, t) || base.begin.is_none_or(|bb| in_force(s.begin, s.end, bb)); let skipped = !changes.is_empty() diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 9907340fef..1cf5908b67 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1901,8 +1901,24 @@ fn a_snapshot_after_its_features_creation_isnt_shown_before_it() { let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); let slices = [snapshot_at("2026-01-01T00:00:00Z", "SNAP"), change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), life)]; let bytes = message(&(point("s", &slices) + &kept)); - assert_eq!(names(&bytes, "2025-12-01").0, [Value::Text("KEPT".into())]); + let (got, notes) = names(&bytes, "2025-12-01"); + assert_eq!(got, [Value::Text("KEPT".into())]); + assert!(notes.iter().any(|m| m.contains("featureLifetime") && !m.contains("can't be read")), "{notes:?}"); assert_eq!(names(&bytes, "2025-12-20").0.len(), 2); + // One that can't be read may be its creation. + let run = |slices: &[String]| names(&message(&(point("s", slices) + &kept)), "2025-12-01"); + let unread = change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), &life.replace("2025-12-10T00:00:00Z", "bad")); + let snap = snapshot_at("2026-01-01T00:00:00Z", "SNAP"); + let (got, notes) = run(&[snap.clone(), unread.clone()]); + assert_eq!(got, [Value::Text("KEPT".into())]); + assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice")), "{notes:?}"); + // Not where the snapshot's own lifetime says it existed, nor a later change that does. + let since = life.replace("2025-12-10", "2020-01-01"); + let lived = snap.replace("", &format!("{since}")); + assert_eq!(run(&[lived.clone(), unread]).0.len(), 2); + assert_eq!(run(&[lived, change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), life)]).0.len(), 2); + let restated = change("PERMDELTA", 2, &instant("2025-12-20T00:00:00Z"), &since); + assert_eq!(run(&[snap, change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), life), restated]).0.len(), 2); } #[test] diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 8a6da7463d..56f1a68bc1 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6865,6 +6865,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { #[cfg(not(target_arch = "wasm32"))] if let Some(i) = s.landed_windows.iter().position(|(d, _)| *d == id) { let (_, read) = s.landed_windows.remove(i); + check_at(p, "a window of a GeoTIFF", || false)?; let r = add_window(s, p, read)?; return added_download(s, p, r, false, &url); } @@ -6876,8 +6877,9 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { // A download read already (an ArcGIS layer's protocol buffer pages, joined): added as read, // with no axes to check against bounds. if let Some(i) = s.landed_reads.iter().position(|(d, _)| *d == id) { - check_at(p, "the service's answer", || false)?; + // Taken first, as bytes are: the app doesn't ask for it again, and it would be held. let (_, read) = s.landed_reads.remove(i); + check_at(p, "the service's answer", || false)?; let r = add_read(s, p, *read, b(p, "zoom"))?; return added_download(s, p, r, service || coverage, &url); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d49eca3f48..25dd952c1f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24181,7 +24181,10 @@ fn aixm_messages_are_added_at_the_date_asked() { assert!(!e.contains("SECRET"), "{e}"); let z = s.run("layer.addUrl", &json!({"url": "https://example.com/a.zip?token=SECRET", "at": "2026-01-15"})).unwrap_err(); assert!(z.contains("unzip it") && !z.contains("SECRET"), "{z}"); - // A service's answer read already: refused and kept, to be added without it. + // A window of a GeoTIFF, before it is read. + let w = s.run("layer.addUrl", &json!({"url": "https://example.test/download", "bbox": [0, 0, 1, 1], "at": "2026-01-15"})).unwrap_err(); + assert!(w.contains("doesn't read at"), "{w}"); + // A service's answer read already: refused, and not held. s.landed_reads.push(( 7, Box::new((rustgis_data::Dataset::new("pbf", rustgis_data::GeometryType::Point, Vec::new()), rustgis_data::ReadReport::default())), @@ -24191,6 +24194,11 @@ fn aixm_messages_are_added_at_the_date_asked() { dated["at"] = json!("2026-01-15"); let e2 = s.run("layer.addDownload", &dated).unwrap_err(); assert!(e2.contains("the service's answer isn't one"), "{e2}"); + assert!(s.landed_reads.is_empty()); + s.landed_reads.push(( + 7, + Box::new((rustgis_data::Dataset::new("pbf", rustgis_data::GeometryType::Point, Vec::new()), rustgis_data::ReadReport::default())), + )); s.run("layer.addDownload", &asked).unwrap(); assert!(e.contains("isn't one"), "{e}"); // An address with no extension found to be a GeoTIFF refuses it too, before it is added. diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index ca470785dd..dcf18df2f9 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, is left out), and changes begun or ended between its instant and the date, which it doesn't reflect, are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn or not yet created on the date, or that may be, is left out), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 791be8ecb18664d516820f21162070a10511d0f3 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:25:14 -0600 Subject: [PATCH 43/61] fix(data): AIXM snapshots after the date judged by their own lifetime only; a test for a landed window given "at" --- crates/data/src/aixm.rs | 14 ------------- crates/data/src/aixm/tests.rs | 35 +++++++++++++-------------------- crates/engine/src/cmd/layer.rs | 3 ++- crates/engine/src/tests.rs | 7 +++++++ docs/user-guide/data-formats.md | 2 +- 5 files changed, 24 insertions(+), 37 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 1d9cf63253..b158addda1 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -513,20 +513,6 @@ fn state_at(slices: &[Slice], t: f64) -> State { let differs = |s: &Slice| in_force(s.begin, s.end, t) != base.begin.is_some_and(|bb| in_force(s.begin, s.end, bb)); // A snapshot after the date holds the PERMDELTAs up to its instant. let ahead = |s: &Slice| s.begin.is_none_or(|b| t < b && base.begin.is_some_and(|bb| b <= bb)); - // One of those may be the feature's creation, unless the snapshot's lifetime (in force on - // the date, above) or a change by then says it existed. Of those read, the latest to give a - // lifetime says. - let known = - base.lifetime.is_some_and(|(from, _)| from.is_some()) || of(Interpretation::PermDelta).any(|s| s.begin.is_some_and(|b| b <= t)); - if !known { - if unread_of(Interpretation::PermDelta).any(ahead) { - return State::Unreadable; - } - let last = of(Interpretation::PermDelta).filter(|s| ahead(s) && s.lifetime.is_some()).max_by(|a, b| by_start(a, b)); - if last.and_then(|s| s.lifetime).is_some_and(|(from, _)| from.is_some_and(|f| t < f)) { - return State::OutsideLifetime; - } - } let perm_ahead = of(Interpretation::PermDelta).chain(unread_of(Interpretation::PermDelta)).any(ahead); // One that can't be read may be either, unless the dates it has rule it out on both. let may_differ = |s: &Slice| in_force(s.begin, s.end, t) || base.begin.is_none_or(|bb| in_force(s.begin, s.end, bb)); diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 1cf5908b67..3f5918a235 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1896,29 +1896,22 @@ fn a_route_segments_shapes_are_told_apart_across_time_slices() { } #[test] -fn a_snapshot_after_its_features_creation_isnt_shown_before_it() { - let life = r#"2025-12-10T00:00:00Z"#; +fn a_snapshot_after_the_date_is_judged_by_its_own_lifetime() { let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); - let slices = [snapshot_at("2026-01-01T00:00:00Z", "SNAP"), change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), life)]; - let bytes = message(&(point("s", &slices) + &kept)); - let (got, notes) = names(&bytes, "2025-12-01"); - assert_eq!(got, [Value::Text("KEPT".into())]); - assert!(notes.iter().any(|m| m.contains("featureLifetime") && !m.contains("can't be read")), "{notes:?}"); - assert_eq!(names(&bytes, "2025-12-20").0.len(), 2); - // One that can't be read may be its creation. - let run = |slices: &[String]| names(&message(&(point("s", slices) + &kept)), "2025-12-01"); - let unread = change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), &life.replace("2025-12-10T00:00:00Z", "bad")); let snap = snapshot_at("2026-01-01T00:00:00Z", "SNAP"); - let (got, notes) = run(&[snap.clone(), unread.clone()]); - assert_eq!(got, [Value::Text("KEPT".into())]); - assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice")), "{notes:?}"); - // Not where the snapshot's own lifetime says it existed, nor a later change that does. - let since = life.replace("2025-12-10", "2020-01-01"); - let lived = snap.replace("", &format!("{since}")); - assert_eq!(run(&[lived.clone(), unread]).0.len(), 2); - assert_eq!(run(&[lived, change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), life)]).0.len(), 2); - let restated = change("PERMDELTA", 2, &instant("2025-12-20T00:00:00Z"), &since); - assert_eq!(run(&[snap, change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), life), restated]).0.len(), 2); + let life = |from: &str| { + let life = format!( + r#"{from}"# + ); + snap.replace("", &format!("{life}")) + }; + let run = |s: String| names(&message(&(point("s", &[s]) + &kept)), "2025-12-01"); + assert_eq!(run(life("2025-12-10T00:00:00Z")).0, [Value::Text("KEPT".into())]); + for s in [life("2020-01-01T00:00:00Z"), snap.clone()] { + let (got, notes) = run(s); + assert_eq!(got.len(), 2); + assert!(notes.iter().any(|m| m.contains("may not be its state on the date asked")), "{notes:?}"); + } } #[test] diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 56f1a68bc1..1e52a2d27d 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6855,7 +6855,8 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { let p = bound.as_ref(); let id = f(p, "id").filter(|v| *v >= 0.0 && v.fract() == 0.0).map(|v| v as u64).ok_or("id is required")?; let url = ps(p, "url").unwrap_or("data").to_string(); - // Read before the download is taken, so a bad one leaves it to be added again. + // Read before the download is taken, so a bad one leaves it to be added again (a refused "at", + // judged by what landed, doesn't). let service = super::b(p, "service").unwrap_or(false); let coverage = super::b(p, "coverage").unwrap_or(false); if (service || coverage) && ps(p, "url").is_none_or(|url| url.trim().is_empty()) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 25dd952c1f..aad4e2954b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -48703,6 +48703,13 @@ fn a_cog_windows_read_is_apart_from_adding_it() { let layers = s.map().layers.len(); let read = std::thread::spawn(move || read_cog_window(&asked)).join().unwrap().unwrap(); assert_eq!(s.map().layers.len(), layers, "nothing added yet"); + // An effective date is for an AIXM message: refused, and not held. + let dated = read_cog_window(&window_asked(&s, &p).unwrap()).unwrap(); + let id = s.download_started(); + assert!(s.download_landed_window(id, dated)); + let e = s.run("layer.addDownload", &json!({"id": id, "url": url, "at": "2026-01-15"})).unwrap_err(); + assert!(e.contains("a window of a GeoTIFF isn't one"), "{e}"); + assert!(s.landed_windows.is_empty() && s.map().layers.len() == layers); let id = s.download_started(); assert!(s.download_landed_window(id, read)); let mark = s.notice_mark(); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index dcf18df2f9..90538752fe 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn or not yet created on the date, or that may be, is left out), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, is left out), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 2ba50d140c1944bb6fe435436e73a8d0dbd03e40 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:32:26 -0600 Subject: [PATCH 44/61] fix(data): AIXM snapshot notice says the feature may not have existed; ties between snapshots --- crates/data/src/aixm.rs | 11 ++++++----- crates/data/src/aixm/tests.rs | 16 ++++++++++++++++ docs/user-guide/data-formats.md | 2 +- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index b158addda1..ac105bfd96 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -469,8 +469,8 @@ fn state_at(slices: &[Slice], t: f64) -> State { // earliest after it. let snap = of(Interpretation::Snapshot) .filter(|s| s.begin.is_none_or(|b| b <= t)) - .max_by(|a, b| started(a).total_cmp(&started(b))) - .or_else(|| of(Interpretation::Snapshot).min_by(|a, b| started(a).total_cmp(&started(b)))); + .max_by(|a, b| started(a).total_cmp(&started(b)).then(a.range.0.cmp(&b.range.0))) + .or_else(|| of(Interpretation::Snapshot).min_by(|a, b| started(a).total_cmp(&started(b)).then(b.range.0.cmp(&a.range.0)))); // One that can't be read may be the one shown: nearer before the date, or (with none // before it) earlier after. let nearer = |u: &Slice| match (u.begin, snap) { @@ -511,7 +511,8 @@ fn state_at(slices: &[Slice], t: f64) -> State { // defined over a baseline: it is shown as it is, and changes it can't hold are said. // A temporary change in force at its instant or on the date, not both, isn't reflected. let differs = |s: &Slice| in_force(s.begin, s.end, t) != base.begin.is_some_and(|bb| in_force(s.begin, s.end, bb)); - // A snapshot after the date holds the PERMDELTAs up to its instant. + // A snapshot after the date holds the PERMDELTAs up to its instant, its creation maybe among + // them: that isn't worked back (the concept has no rule for it), and is said. let ahead = |s: &Slice| s.begin.is_none_or(|b| t < b && base.begin.is_some_and(|bb| b <= bb)); let perm_ahead = of(Interpretation::PermDelta).chain(unread_of(Interpretation::PermDelta)).any(ahead); // One that can't be read may be either, unless the dates it has rule it out on both. @@ -3415,8 +3416,8 @@ fn finish( ); say( layer.snapshots, - "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked", - "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked", + "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked (it may not have existed then)", + "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked (they may not have existed then)", ); say( layer.over_bytes, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 3f5918a235..ea570ff43f 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1907,6 +1907,22 @@ fn a_snapshot_after_the_date_is_judged_by_its_own_lifetime() { }; let run = |s: String| names(&message(&(point("s", &[s]) + &kept)), "2025-12-01"); assert_eq!(run(life("2025-12-10T00:00:00Z")).0, [Value::Text("KEPT".into())]); + // Two at one instant: the later in the file, on either date. + let two = message(&point("s", &[snap.clone(), snapshot_at("2026-01-01T00:00:00Z", "SECOND")])); + for date in ["2025-12-01", "2026-01-15"] { + assert_eq!(names(&two, date).0, [Value::Text("SECOND".into())]); + } + // A creation given by a change before it, read or not, isn't worked back: said. + for from in ["2025-12-10T00:00:00Z", "bad"] { + let created = format!( + r#"{from}"# + ); + let perm = change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), &created); + let (got, notes) = names(&message(&(point("s", &[snap.clone(), perm]) + &kept)), "2025-12-01"); + assert_eq!(got.len(), 2); + assert!(notes.iter().any(|m| m.contains("may not have existed then")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("SNAPSHOT that doesn't reflect changes")), "{notes:?}"); + } for s in [life("2020-01-01T00:00:00Z"), snap.clone()] { let (got, notes) = run(s); assert_eq!(got.len(), 2); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 90538752fe..a9992a0e5c 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, is left out), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 03296163eec5f5eea75d34eb307dbc4f330b8482 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:32:53 -0600 Subject: [PATCH 45/61] test(engine): the .fgb refusal asserted beside its case; a decoded download's outcome asserted --- crates/engine/src/tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index aad4e2954b..4ac9252f46 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24178,7 +24178,7 @@ fn aixm_messages_are_added_at_the_date_asked() { let e = s.run("info.fileLayers", &json!({"path": csv.display().to_string(), "at": "2026-01-15"})).unwrap_err(); assert!(e.contains("isn't one"), "{e}"); let e = s.run("layer.addUrl", &json!({"url": "https://example.com/roads.fgb?token=SECRET", "at": "2026-01-15"})).unwrap_err(); - assert!(!e.contains("SECRET"), "{e}"); + assert!(e.contains("isn't one") && !e.contains("SECRET"), "{e}"); let z = s.run("layer.addUrl", &json!({"url": "https://example.com/a.zip?token=SECRET", "at": "2026-01-15"})).unwrap_err(); assert!(z.contains("unzip it") && !z.contains("SECRET"), "{z}"); // A window of a GeoTIFF, before it is read. @@ -24199,8 +24199,9 @@ fn aixm_messages_are_added_at_the_date_asked() { 7, Box::new((rustgis_data::Dataset::new("pbf", rustgis_data::GeometryType::Point, Vec::new()), rustgis_data::ReadReport::default())), )); + let layers = s.map().layers.len(); s.run("layer.addDownload", &asked).unwrap(); - assert!(e.contains("isn't one"), "{e}"); + assert!(s.landed_reads.is_empty() && s.map().layers.len() == layers + 1); // An address with no extension found to be a GeoTIFF refuses it too, before it is added. let e = crate::cmd::layer::add_cog(&mut s, &json!({"at": "2026-01-15"}), "https://example.test/download", true).unwrap_err(); assert!(e.contains("isn't one"), "{e}"); From 0e955d816a60a57681712af546c4033c21d78be6 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:51:54 -0600 Subject: [PATCH 46/61] fix(data): AIXM PERMDELTAs given a period withheld, snapshots given one said; features found by any member's gml:id; ties; a blank "at" for a window; the guide on routes and arcs --- crates/data/src/aixm.rs | 45 +++++++++++++------ crates/data/src/aixm/tests.rs | 79 +++++++++++++++++++++++++++++++++ crates/engine/src/cmd/layer.rs | 8 +++- crates/engine/src/tests.rs | 4 ++ docs/user-guide/data-formats.md | 2 +- 5 files changed, 122 insertions(+), 16 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index ac105bfd96..3737183a4e 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -17,7 +17,8 @@ //! Geometry is the GML 3.2 the AIXM profile allows (OGC 12-028r1): points, curves of //! `GeodesicString`, `Geodesic`, `LineStringSegment`, `Arc`, `ArcString`, `Circle`, //! `ArcByCenterPoint` and `CircleByCenterPoint` segments, and surfaces of polygon patches. Arcs are -//! drawn as points along them on the WGS 84 ellipsoid, within a meter of the curve; a geodesic edge +//! drawn as points along them on the WGS 84 ellipsoid, within a meter of the curve (coarser, and +//! said, once the points the file's size allows run out); a geodesic edge //! longer than 10 km is drawn as points along the geodesic. `ArcByCenterPoint` angles follow the //! AIXM coding guidance: in a latitude-first system (`urn:ogc:def:crs:EPSG::4326`) bearings //! clockwise from true north, the arc running from the start angle to the end angle (clockwise when @@ -396,8 +397,9 @@ struct Feature { /// Its identifier (`gml:identifier`, else its `gml:id`). id: String, kind: String, - /// Its own `gml:id`: what a local link (`#id`) or the FAA's XPath names it by. - gml_id: Option, + /// Its own `gml:id`s, one for each member that gives it: what a local link (`#id`) or the FAA's + /// XPath names it by. + gml_ids: HashSet, slices: Vec, } @@ -474,8 +476,8 @@ fn state_at(slices: &[Slice], t: f64) -> State { // One that can't be read may be the one shown: nearer before the date, or (with none // before it) earlier after. let nearer = |u: &Slice| match (u.begin, snap) { - (Some(b), Some(s)) if started(s) <= t => b <= t && b >= started(s), - (Some(b), Some(s)) => b <= started(s), + (Some(b), Some(s)) if started(s) <= t => b <= t && (b > started(s) || b == started(s) && u.range.0 > s.range.0), + (Some(b), Some(s)) => b < started(s) || b == started(s) && u.range.0 > s.range.0, _ => true, }; if unread_of(Interpretation::Snapshot).any(nearer) { @@ -543,6 +545,8 @@ struct SliceTrouble { empty: usize, /// Slices with a sequence or correction number that isn't a number, read as 0. numbers: usize, + /// SNAPSHOTs given a period, read at its start. + periods: usize, } /// A slice's own properties. @@ -568,12 +572,18 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }; let empty = std::cell::Cell::new(0); let (mut begin, mut end, mut canceled) = (None, None, false); + let mut period = false; let mut bad = false; // One without a validTime (which every slice has, if only empty) could apply at any date. bad |= child(s, "validTime").is_none(); if let Some(v) = child(s, "validTime") { match elements(v).next() { Some(p) if local(&p) == "TimePeriod" => { + // A PERMDELTA has an instant (TS_002): when its change is made isn't said. A + // SNAPSHOT has too, but some systems work one out for a period (TS_004's note): it + // is read at its start, and said. + bad |= kind == Interpretation::PermDelta; + period = kind == Interpretation::Snapshot; begin = position(child(p, "beginPosition"), &empty).unwrap_or_else(|()| { bad = true; None @@ -627,6 +637,7 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro return Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled: false, lifetime: None, unreadable: true }); } trouble.empty += empty.get(); + trouble.periods += usize::from(period); Some(Slice { range, scope, kind, sequence, correction, begin, end, canceled, lifetime, unreadable: false }) } @@ -2231,6 +2242,8 @@ fn projection<'a, 'i>(v: Option>) -> Option> { struct FileNotes { /// Slices with a sequence or correction number that isn't a number, read as 0. bad_numbers: usize, + /// SNAPSHOT slices given a period, read at its start. + snapshot_periods: usize, /// Features left out because a change in force at the date couldn't be read. incomplete: usize, /// Time positions left empty without saying they are unknown, read as open. @@ -2263,6 +2276,12 @@ struct FileNotes { /// several), at the effective date `opts.at` (today when not given). Cancel is looked at between /// members; finding them first is one pass over the text without a look. pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result> { + read_within(file_name, bytes, opts, MIN_ROW_BYTES * 4) +} + +/// [`read`], its tables of at most eight times the file's size, or `dense_floor` bytes when that is +/// more. +fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize) -> Result> { let max = crate::io::max_bytes(); if bytes.len() as u64 > max { return Err(DataError::Format(crate::io::file_size_error(file_name, max))); @@ -2350,13 +2369,9 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result Result Result ResultPERM"); + assert_eq!(run(&[base.clone(), perm.clone()], "2025-12-15").0, [Value::Text("BASE".into()), Value::Text("KEPT".into())]); + for d in ["2026-01-15", "2026-06-15"] { + let (got, notes) = run(&[base.clone(), perm.clone()], d); + assert_eq!(got, [Value::Text("KEPT".into())]); + assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice")), "{notes:?}"); + } + let said = |notes: &[String]| notes.iter().any(|m| m.contains("1 SNAPSHOT given a period")); + let (got, notes) = run(&[slice("DesignatedPoint", "SNAPSHOT", 1, 0, &valid, &named_point("SNAP"))], "2026-01-15"); + assert!(got.len() == 2 && said(¬es), "{got:?} {notes:?}"); + assert!(!said(&run(&[snapshot_at("2026-01-01T00:00:00Z", "SNAP")], "2026-01-15").1)); +} + +#[test] +fn a_later_snapshot_wins_a_tie_read_or_not() { + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let lifetime = r#"bad"#; + let snap = snapshot_at("2026-01-01T00:00:00Z", "SNAP"); + let unread = snap.replace("", &format!("{lifetime}")); + for d in ["2025-12-15", "2026-01-15"] { + let run = |s: &[String]| names(&message(&(point("a", s) + &kept)), d).0; + assert_eq!(run(&[unread.clone(), snap.clone()]), [Value::Text("SNAP".into()), Value::Text("KEPT".into())]); + assert_eq!(run(&[snap.clone(), unread.clone()]), [Value::Text("KEPT".into())]); + } +} + +#[test] +fn a_feature_is_found_by_the_gml_id_of_any_of_its_members() { + let member = |gid: &str, seq: u32, from: &str, to: Option<&str>, pos: &str| { + let b = format!( + r#"{pos}"# + ); + feature("DesignatedPoint", "near", &[slice("DesignatedPoint", "BASELINE", seq, 0, &period(from, to), &b)]) + .replace(r#"gml:id="f""#, &format!(r#"gml:id="{gid}""#)) + }; + let members = member("p-old", 1, "2020-01-01T00:00:00Z", Some("2025-01-01T00:00:00Z"), "40 10") + + &member("p-new", 2, "2025-01-01T00:00:00Z", None, "50 10") + + &named_at("DesignatedPoint", "far", 50.0, 12.0); + for id in ["p-old", "p-new"] { + let route = route_to("pointChoice_fixDesignatedPoint", "X").replace("urn:uuid:X", &format!("#{id}")); + let out = read("t.xml", &message(&(members.clone() + &route)), &at("2026-01-15")).unwrap(); + let Some(Geometry::Line(l)) = &layer(&out, "t RouteSegment").features[0].geometry else { panic!("{id} not drawn") }; + assert_eq!(l[0].first(), Some(&Coord::new(10.0, 50.0))); + } +} + +#[test] +fn rows_past_the_tables_memory_are_left_out_and_said() { + let wide: String = (0..1500).map(|i| format!("1")).collect(); + let one = |i: usize, more: &str| { + point( + &format!("p{i}"), + &[slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &(named_point("N") + more))], + ) + }; + let rows = 400; + let sparse = message(&(0..rows).map(|i| one(i, if i == 0 { &wide } else { "" })).collect::()); + let narrow = message(&(0..rows).map(|i| one(i, "")).collect::()); + let run = |bytes: &[u8], floor| { + let out = read_within("t.xml", bytes, &at("2026-01-15"), floor).unwrap(); + (layer(&out, "t DesignatedPoint").features.len(), said(&out)) + }; + // Sparse and wide: what eight times the file allows, the rest said. + let (kept, notes) = run(&sparse, 0); + assert!(kept > 0 && kept < rows, "{kept}"); + assert!(notes.iter().any(|m| m.contains(&format!("{} rows are left out", rows - kept))), "{notes:?}"); + // The same within the floor, and tall and narrow without it: all kept, nothing said. + for (n, notes) in [run(&sparse, 1 << 30), run(&narrow, 0)] { + assert_eq!(n, rows); + assert!(!notes.iter().any(|m| m.contains("left out")), "{notes:?}"); + } +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1e52a2d27d..502e434f3a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6247,7 +6247,13 @@ fn window_checks(p: &Value, url: &str, scan: bool) -> Result<(), String> { // A data cube's file is a tile layer that follows the time slider, and a window is a raster: // `"cube": false` asks for nothing. let cube = (b(p, "cube") == Some(true)).then_some("cube"); - let unread: Vec<&str> = WINDOW_UNREAD.iter().copied().filter(|k| p.get(*k).is_some_and(|v| !v.is_null())).chain(cube).collect(); + // A blank effective date is none, as everywhere (`check_at`). + let unread: Vec<&str> = WINDOW_UNREAD + .iter() + .copied() + .filter(|k| p.get(*k).is_some_and(|v| !v.is_null() && !(*k == "at" && v.as_str().is_some_and(|t| t.trim().is_empty())))) + .chain(cube) + .collect(); if !unread.is_empty() { return Err(format!("{url}: a window (\"bbox\") doesn't read {}: leave it out", unread.join(", "))); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4ac9252f46..b10cb49aba 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24184,6 +24184,10 @@ fn aixm_messages_are_added_at_the_date_asked() { // A window of a GeoTIFF, before it is read. let w = s.run("layer.addUrl", &json!({"url": "https://example.test/download", "bbox": [0, 0, 1, 1], "at": "2026-01-15"})).unwrap_err(); assert!(w.contains("doesn't read at"), "{w}"); + for blank in ["", " "] { + let p = json!({"url": "https://example.test/download", "bbox": [0, 0, 1, 1], "at": blank}); + assert!(crate::cmd::layer::window_asked(&s, &p).is_ok(), "{blank:?}"); + } // A service's answer read already: refused, and not held. s.landed_reads.push(( 7, diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index a9992a0e5c..aba255fa4e 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter, and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn as a geodesic between the points its start and end name. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter (coarser, and said, past the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 8356b4f211dbf9f005473bdedaaac7065b8d49cb Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:03:19 -0600 Subject: [PATCH 47/61] fix(data): AIXM borders' points shared by their names, not copied; PERMDELTA periods judged whole; snapshot periods' ends not used; notice wording --- crates/data/src/aixm.rs | 43 +++++++++++++++++++++------------ crates/data/src/aixm/tests.rs | 41 ++++++++++++++++++++++++++++--- docs/user-guide/data-formats.md | 2 +- 3 files changed, 67 insertions(+), 19 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 3737183a4e..7bc7c3a68e 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -12,7 +12,8 @@ //! at the date, withdrawn before it (`featureLifetime`) or with only changes and no state are left //! out and counted, as are those with a slice that may apply then whose validity can't be read. A //! feature with no BASELINE is shown as its nearest SNAPSHOT, without changes over it (it already -//! holds those of its instant), and said. +//! holds those of its instant), and said; one given a period is read at its start, and said. A +//! PERMDELTA given a period can't be placed, and withholds its feature while it may apply. //! //! Geometry is the GML 3.2 the AIXM profile allows (OGC 12-028r1): points, curves of //! `GeodesicString`, `Geodesic`, `LineStringSegment`, `Arc`, `ArcString`, `Circle`, @@ -493,7 +494,9 @@ fn state_at(slices: &[Slice], t: f64) -> State { // PERMDELTAs since the state began, up to the date, in order. let since = |s: &Slice| s.begin.is_none_or(|b| b <= t && base.begin.is_none_or(|bb| b > bb)); // One that can't be read may be a withdrawal: its feature is left out, a SNAPSHOT's too. - if unread_of(Interpretation::PermDelta).any(since) { + // One given a period (only it has an end) may be made anywhere in it. + let may_since = |s: &Slice| since(s) || s.begin.is_some_and(|b| b <= t) && s.end.is_some_and(|e| base.begin.is_some_and(|bb| e > bb)); + if unread_of(Interpretation::PermDelta).any(may_since) { return State::Unreadable; } let by_start = |a: &Slice, b: &Slice| started(a).total_cmp(&started(b)).then(a.range.0.cmp(&b.range.0)); @@ -516,7 +519,9 @@ fn state_at(slices: &[Slice], t: f64) -> State { // A snapshot after the date holds the PERMDELTAs up to its instant, its creation maybe among // them: that isn't worked back (the concept has no rule for it), and is said. let ahead = |s: &Slice| s.begin.is_none_or(|b| t < b && base.begin.is_some_and(|bb| b <= bb)); - let perm_ahead = of(Interpretation::PermDelta).chain(unread_of(Interpretation::PermDelta)).any(ahead); + let may_ahead = + |s: &Slice| ahead(s) || s.end.is_some_and(|e| e > t) && s.begin.is_some_and(|b| base.begin.is_some_and(|bb| b <= bb)); + let perm_ahead = of(Interpretation::PermDelta).any(ahead) || unread_of(Interpretation::PermDelta).any(may_ahead); // One that can't be read may be either, unless the dates it has rule it out on both. let may_differ = |s: &Slice| in_force(s.begin, s.end, t) || base.begin.is_none_or(|bb| in_force(s.begin, s.end, bb)); let skipped = !changes.is_empty() @@ -588,10 +593,17 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro bad = true; None }); - end = position(child(p, "endPosition"), &empty).unwrap_or_else(|()| { - bad = true; - None - }); + // A SNAPSHOT's end isn't used. + if !period { + end = position(child(p, "endPosition"), &empty).unwrap_or_else(|()| { + bad = true; + None + }); + } + // An open PERMDELTA period has an end for `state_at` to tell it from an instant. + if kind == Interpretation::PermDelta { + end = end.or(Some(f64::INFINITY)); + } } Some(i) if local(&i) == "TimeInstant" => { // A BASELINE and a TEMPDELTA have a period (TS_001, TS_003): until when isn't said. @@ -735,8 +747,9 @@ struct Shapes { as_wgs84: Option, as_wgs84_count: usize, as_wgs84_now: bool, - /// The borders references may follow, by [`border_key`]: each GeoBorder's at the date. - borders: HashMap>, + /// The borders references may follow, by [`border_key`] and by `gml:id`: each GeoBorder's at the + /// date, its points shared by every name it has (a file can give one any number). + borders: HashMap>, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of @@ -1311,7 +1324,7 @@ impl Shapes { let (part, off) = cut(border, a, b).ok_or(Unfollowed::Unusable)?; (part, off > FAR_FROM_BORDER_M) } - _ => (border.clone(), false), + _ => (border.to_vec(), false), }; // Its points are paid for as a curve's added points are; one that can't be takes none. let n = part.len(); @@ -2519,7 +2532,7 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize && let Some(g) = props.iter().filter(|p| local(p) == "border").find_map(|p| shape_in(*p)) && let Some(Geometry::Line(parts)) = shapes.quietly(g) { - let line: Vec = parts.concat(); + let line: std::rc::Rc<[Coord]> = parts.concat().into(); if let Some(gid) = g.attribute((GML, "id")) { shapes.borders.insert(format!("#{}", gid.trim()), line.clone()); } @@ -3111,7 +3124,7 @@ fn finish( notes.unreadable_state, "feature", "features", - "left out: a time slice of it that may apply (the latest correction) has no validTime of the kind it needs (a period, or an instant for a PERMDELTA or SNAPSHOT), or a validTime or featureLifetime that can't be read", + "left out: a time slice of it that may apply (the latest correction) has no validTime of the kind it needs (a period, an instant for a PERMDELTA, or for a SNAPSHOT an instant or a period with a start), or a validTime or featureLifetime that can't be read", ); say( &mut file, @@ -3149,7 +3162,7 @@ fn finish( notes.bad_dates, "time slice", "time slices", - "with no validTime of the kind it needs (a period, or an instant for a PERMDELTA or SNAPSHOT), or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out, or shown as its SNAPSHOT)", + "with no validTime of the kind it needs (a period, an instant for a PERMDELTA, or for a SNAPSHOT an instant or a period with a start), or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out, or shown as its SNAPSHOT)", ); say( &mut file, @@ -3433,8 +3446,8 @@ fn finish( ); say( layer.snapshots, - "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked (it may not have existed then)", - "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked (they may not have existed then)", + "feature is a SNAPSHOT: its state at its own instant, which may not be its state on the date asked (one later than that date may not have existed on it)", + "features are SNAPSHOTs: their state at their own instant, which may not be their state on the date asked (those later than that date may not have existed on it)", ); say( layer.over_bytes, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 78c7e15478..3f06472cf4 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1117,8 +1117,8 @@ fn a_ring_whose_borders_cant_be_joined_within_the_allowance_isnt_drawn_and_says_ let boundary = doc.root_element().first_element_child().unwrap(); let line = |pts: &[(f64, f64)]| pts.iter().map(|&(x, y)| Coord::new(x, y)).collect::>(); let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; - shapes.borders.insert("uuid:a".into(), line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)])); - shapes.borders.insert("uuid:b".into(), line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)])); + shapes.borders.insert("uuid:a".into(), line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)]).into()); + shapes.borders.insert("uuid:b".into(), line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)]).into()); // With room to look along both borders where they meet: drawn. shapes.scan_left = 1000; let mut notes = ShapeNotes::default(); @@ -1920,7 +1920,7 @@ fn a_snapshot_after_the_date_is_judged_by_its_own_lifetime() { let perm = change("PERMDELTA", 1, &instant("2025-12-10T00:00:00Z"), &created); let (got, notes) = names(&message(&(point("s", &[snap.clone(), perm]) + &kept)), "2025-12-01"); assert_eq!(got.len(), 2); - assert!(notes.iter().any(|m| m.contains("may not have existed then")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("may not have existed on it")), "{notes:?}"); assert!(notes.iter().any(|m| m.contains("SNAPSHOT that doesn't reflect changes")), "{notes:?}"); } for s in [life("2020-01-01T00:00:00Z"), snap.clone()] { @@ -1961,7 +1961,23 @@ fn a_change_given_a_period_is_withheld_and_a_snapshot_is_read_at_its_start_and_s assert_eq!(got, [Value::Text("KEPT".into())]); assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice")), "{notes:?}"); } + // One whose period spans the state's start may be made after it; one that ended by then isn't. + let spans = |end| change("PERMDELTA", 1, &period("2024-12-01T00:00:00Z", end), "PERM"); + for (end, count) in [(Some("2025-06-01T00:00:00Z"), 1), (None, 1), (Some("bad"), 1), (Some("2025-01-01T00:00:00Z"), 2)] { + assert_eq!(run(&[base.clone(), spans(end)], "2026-01-15").0.len(), count, "{end:?}"); + } + // And before a later snapshot: said. + let later = run(&[snapshot_at("2026-03-01T00:00:00Z", "SNAP"), perm], "2026-01-15").1; + assert!(later.iter().any(|m| m.contains("doesn't reflect changes")), "{later:?}"); let said = |notes: &[String]| notes.iter().any(|m| m.contains("1 SNAPSHOT given a period")); + // Its end isn't used, read or not. + for end in ["PERM", ""] { + let valid = format!( + r#"2026-01-01T00:00:00Z{end}"# + ); + let (got, notes) = run(&[slice("DesignatedPoint", "SNAPSHOT", 1, 0, &valid, &named_point("SNAP"))], "2026-01-15"); + assert!(got.len() == 2 && said(¬es) && !notes.iter().any(|m| m.contains("read as open")), "{got:?} {notes:?}"); + } let (got, notes) = run(&[slice("DesignatedPoint", "SNAPSHOT", 1, 0, &valid, &named_point("SNAP"))], "2026-01-15"); assert!(got.len() == 2 && said(¬es), "{got:?} {notes:?}"); assert!(!said(&run(&[snapshot_at("2026-01-01T00:00:00Z", "SNAP")], "2026-01-15").1)); @@ -2026,3 +2042,22 @@ fn rows_past_the_tables_memory_are_left_out_and_said() { assert!(!notes.iter().any(|m| m.contains("left out")), "{notes:?}"); } } + +#[test] +fn a_border_is_followed_by_the_gml_id_of_any_of_its_members() { + let border = |gid: &str, seq: u32, from: &str, to: Option<&str>| { + let b = r#"50 9 50 10 51 10"#; + feature("GeoBorder", "line", &[slice("GeoBorder", "BASELINE", seq, 0, &period(from, to), b)]) + .replace(r#"gml:id="f""#, &format!(r#"gml:id="{gid}""#)) + }; + let members = + border("b-old", 1, "2020-01-01T00:00:00Z", Some("2025-01-01T00:00:00Z")) + &border("b-new", 2, "2025-01-01T00:00:00Z", None); + for id in ["b-old", "b-new"] { + let area = format!( + r##"51 10 51 9 50 9"## + ); + let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &area)]); + let out = read("t.xml", &message(&(members.clone() + &f)), &at("2026-01-15")).unwrap(); + assert!(layer(&out, "t WorkArea").features[0].geometry.is_some(), "{id}: {:?}", said(&out)); + } +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index aba255fa4e..7acb8e415d 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter (coarser, and said, past the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter (coarser, and said, past the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 7a6690c5394593de1393761adac5e46474fd2b91 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:10:25 -0600 Subject: [PATCH 48/61] fix(data): AIXM borders named two ways are one border; one rule for when an unreadable PERMDELTA may be made --- crates/data/src/aixm.rs | 43 +++++++++++++++++------------- crates/data/src/aixm/tests.rs | 49 +++++++++++++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 20 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 7bc7c3a68e..e989a2264d 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -382,7 +382,8 @@ struct Slice { kind: Interpretation, sequence: u64, correction: u64, - /// Valid from (included) and until (excluded); an instant for a PERMDELTA or SNAPSHOT. + /// Valid from (included) and until (excluded). An instant for a PERMDELTA or SNAPSHOT, which has no + /// end; but a PERMDELTA wrongly given a period has one, infinite when it is open or can't be read. begin: Option, end: Option, canceled: bool, @@ -425,6 +426,16 @@ fn in_force(begin: Option, end: Option, t: f64) -> bool { begin.is_none_or(|b| b <= t) && end.is_none_or(|e| t < e) } +/// Whether a PERMDELTA that can't be read may be made after `from` and by `to`: at its instant, +/// anywhere in its period (which includes its start and not its end), or, with neither, at any time. +fn may_be_made(s: &Slice, from: f64, to: f64) -> bool { + let (first, last) = match (s.begin, s.end) { + (Some(b), None) => (b, b), + (b, e) => (b.unwrap_or(f64::NEG_INFINITY), e.unwrap_or(f64::INFINITY)), + }; + from < to && first <= to && last > from +} + /// Each feature's state at `t`. fn state_at(slices: &[Slice], t: f64) -> State { // Of slices alike in interpretation and sequence number, the highest correction holds (the @@ -494,9 +505,7 @@ fn state_at(slices: &[Slice], t: f64) -> State { // PERMDELTAs since the state began, up to the date, in order. let since = |s: &Slice| s.begin.is_none_or(|b| b <= t && base.begin.is_none_or(|bb| b > bb)); // One that can't be read may be a withdrawal: its feature is left out, a SNAPSHOT's too. - // One given a period (only it has an end) may be made anywhere in it. - let may_since = |s: &Slice| since(s) || s.begin.is_some_and(|b| b <= t) && s.end.is_some_and(|e| base.begin.is_some_and(|bb| e > bb)); - if unread_of(Interpretation::PermDelta).any(may_since) { + if unread_of(Interpretation::PermDelta).any(|s| may_be_made(s, started(base), t)) { return State::Unreadable; } let by_start = |a: &Slice, b: &Slice| started(a).total_cmp(&started(b)).then(a.range.0.cmp(&b.range.0)); @@ -519,9 +528,8 @@ fn state_at(slices: &[Slice], t: f64) -> State { // A snapshot after the date holds the PERMDELTAs up to its instant, its creation maybe among // them: that isn't worked back (the concept has no rule for it), and is said. let ahead = |s: &Slice| s.begin.is_none_or(|b| t < b && base.begin.is_some_and(|bb| b <= bb)); - let may_ahead = - |s: &Slice| ahead(s) || s.end.is_some_and(|e| e > t) && s.begin.is_some_and(|b| base.begin.is_some_and(|bb| b <= bb)); - let perm_ahead = of(Interpretation::PermDelta).any(ahead) || unread_of(Interpretation::PermDelta).any(may_ahead); + let perm_ahead = + of(Interpretation::PermDelta).any(ahead) || unread_of(Interpretation::PermDelta).any(|s| may_be_made(s, t, started(base))); // One that can't be read may be either, unless the dates it has rule it out on both. let may_differ = |s: &Slice| in_force(s.begin, s.end, t) || base.begin.is_none_or(|bb| in_force(s.begin, s.end, bb)); let skipped = !changes.is_empty() @@ -747,9 +755,10 @@ struct Shapes { as_wgs84: Option, as_wgs84_count: usize, as_wgs84_now: bool, - /// The borders references may follow, by [`border_key`] and by `gml:id`: each GeoBorder's at the - /// date, its points shared by every name it has (a file can give one any number). - borders: HashMap>, + /// The borders references may follow, by [`border_key`]: each GeoBorder's at the date, held once. + borders: HashMap>, + /// The key of the border a `gml:id` (its curve's, or any of its members') names. + border_names: HashMap, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of @@ -1168,6 +1177,7 @@ impl Shapes { // The same border named again straight after is the same stretch of // it (DFS writes a border's members so), followed once. let key = border_key(m.attribute((XLINK, "href"))?); + let key = self.border_names.get(&key).cloned().unwrap_or(key); if !matches!(members.last(), Some(Err(k)) if *k == key) { members.push(Err(key)); } @@ -1324,7 +1334,7 @@ impl Shapes { let (part, off) = cut(border, a, b).ok_or(Unfollowed::Unusable)?; (part, off > FAR_FROM_BORDER_M) } - _ => (border.to_vec(), false), + _ => (border.clone(), false), }; // Its points are paid for as a curve's added points are; one that can't be takes none. let n = part.len(); @@ -2532,14 +2542,11 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize && let Some(g) = props.iter().filter(|p| local(p) == "border").find_map(|p| shape_in(*p)) && let Some(Geometry::Line(parts)) = shapes.quietly(g) { - let line: std::rc::Rc<[Coord]> = parts.concat().into(); - if let Some(gid) = g.attribute((GML, "id")) { - shapes.borders.insert(format!("#{}", gid.trim()), line.clone()); - } - for gid in &feature.gml_ids { - shapes.borders.insert(format!("#{gid}"), line.clone()); + let key = border_key(id); + for gid in g.attribute((GML, "id")).map(str::trim).into_iter().chain(feature.gml_ids.iter().map(String::as_str)) { + shapes.border_names.insert(format!("#{gid}"), key.clone()); } - shapes.borders.insert(border_key(id), line); + shapes.borders.insert(key, parts.concat()); } // Where a point feature is, for route segments that name it: by its identifier and its // own gml:id (a local link's or an XPath's). diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 3f06472cf4..b27ff4604c 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1117,8 +1117,8 @@ fn a_ring_whose_borders_cant_be_joined_within_the_allowance_isnt_drawn_and_says_ let boundary = doc.root_element().first_element_child().unwrap(); let line = |pts: &[(f64, f64)]| pts.iter().map(|&(x, y)| Coord::new(x, y)).collect::>(); let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; - shapes.borders.insert("uuid:a".into(), line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)]).into()); - shapes.borders.insert("uuid:b".into(), line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)]).into()); + shapes.borders.insert("uuid:a".into(), line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)])); + shapes.borders.insert("uuid:b".into(), line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)])); // With room to look along both borders where they meet: drawn. shapes.scan_left = 1000; let mut notes = ShapeNotes::default(); @@ -1966,6 +1966,26 @@ fn a_change_given_a_period_is_withheld_and_a_snapshot_is_read_at_its_start_and_s for (end, count) in [(Some("2025-06-01T00:00:00Z"), 1), (None, 1), (Some("bad"), 1), (Some("2025-01-01T00:00:00Z"), 2)] { assert_eq!(run(&[base.clone(), spans(end)], "2026-01-15").0.len(), count, "{end:?}"); } + // On the state's own date there is no time for it since; nor one that ended before the state, + // its start not known. + assert_eq!(run(&[base.clone(), spans(None)], "2025-01-01").0.len(), 2); + let ended = |end: &str| { + let valid = format!( + r#"{end}"# + ); + change("PERMDELTA", 1, &valid, "PERM") + }; + assert_eq!(run(&[base.clone(), ended("2020-01-01T00:00:00Z")], "2026-01-15").0.len(), 2); + assert_eq!(run(&[base.clone(), ended("2025-06-01T00:00:00Z")], "2026-01-15").0.len(), 1); + // Past a snapshot's instant, or open, and before one later than the date: shown, and said. + for end in [Some("2026-04-01T00:00:00Z"), None, Some("bad")] { + let p = change("PERMDELTA", 1, &period("2026-01-01T00:00:00Z", end), "PERM"); + let (got, notes) = run(&[snapshot_at("2026-03-01T00:00:00Z", "SNAP"), p.clone()], "2026-01-15"); + assert!(got.len() == 2 && notes.iter().any(|m| m.contains("doesn't reflect changes")), "{end:?} {got:?} {notes:?}"); + // On its own date it reflects them all. + let notes = run(&[snapshot_at("2026-01-15T00:00:00Z", "SNAP"), p], "2026-01-15").1; + assert!(!notes.iter().any(|m| m.contains("doesn't reflect changes")), "{end:?} {notes:?}"); + } // And before a later snapshot: said. let later = run(&[snapshot_at("2026-03-01T00:00:00Z", "SNAP"), perm], "2026-01-15").1; assert!(later.iter().any(|m| m.contains("doesn't reflect changes")), "{later:?}"); @@ -2061,3 +2081,28 @@ fn a_border_is_followed_by_the_gml_id_of_any_of_its_members() { assert!(layer(&out, "t WorkArea").features[0].geometry.is_some(), "{id}: {:?}", said(&out)); } } + +#[test] +fn a_border_named_two_ways_in_a_row_is_one_border() { + let b = r#"50 8 50 9 50 9.5 50 10 50 11"#; + let border = |gid: &str, seq: u32, from: &str, to: Option<&str>| { + feature("GeoBorder", "line", &[slice("GeoBorder", "BASELINE", seq, 0, &period(from, to), b)]) + .replace(r#"gml:id="f""#, &format!(r#"gml:id="{gid}""#)) + }; + let members = + border("b-old", 1, "2020-01-01T00:00:00Z", Some("2025-01-01T00:00:00Z")) + &border("b-new", 2, "2025-01-01T00:00:00Z", None); + let drawn = |refs: &[&str]| { + let refs: String = refs.iter().map(|r| format!(r#""#)).collect(); + let area = format!( + r#"{refs}50 10 51 10 51 9 50 9"# + ); + let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &area)]); + let out = read("t.xml", &message(&(members.clone() + &f)), &at("2026-01-15")).unwrap(); + ring(layer(&out, "t WorkArea").features[0].geometry.as_ref().unwrap()).to_vec() + }; + let once = drawn(&["#b-new"]); + assert!(once.iter().all(|c| (8.999..=10.001).contains(&c.x)), "{once:?}"); + for refs in [["#b-old", "#b-new"], ["#c", "#b-new"], ["urn:uuid:line", "#b-old"]] { + assert_eq!(drawn(&refs), once, "{refs:?}"); + } +} From 6043109a9abefa2d72d379a836468fed7c9458b5 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:21:37 -0600 Subject: [PATCH 49/61] fix(data): AIXM borders numbered, so a reference holds no identifier and alike identifiers aren't mixed; a PERMDELTA period that ends before it begins --- crates/data/src/aixm.rs | 57 +++++++++++++++++++++-------------- crates/data/src/aixm/tests.rs | 39 ++++++++++++++++++++++-- 2 files changed, 71 insertions(+), 25 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index e989a2264d..3875443ce4 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -431,6 +431,8 @@ fn in_force(begin: Option, end: Option, t: f64) -> bool { fn may_be_made(s: &Slice, from: f64, to: f64) -> bool { let (first, last) = match (s.begin, s.end) { (Some(b), None) => (b, b), + // One that ends before it begins is wrong in one of them: its end isn't known. + (Some(b), Some(e)) if e < b => (b, f64::INFINITY), (b, e) => (b.unwrap_or(f64::NEG_INFINITY), e.unwrap_or(f64::INFINITY)), }; from < to && first <= to && last > from @@ -504,7 +506,8 @@ fn state_at(slices: &[Slice], t: f64) -> State { }; // PERMDELTAs since the state began, up to the date, in order. let since = |s: &Slice| s.begin.is_none_or(|b| b <= t && base.begin.is_none_or(|bb| b > bb)); - // One that can't be read may be a withdrawal: its feature is left out, a SNAPSHOT's too. + // One that can't be read and may be made between the state and the date may be a withdrawal: its + // feature is left out, a SNAPSHOT's too (one later than the date is shown, and the change said). if unread_of(Interpretation::PermDelta).any(|s| may_be_made(s, started(base), t)) { return State::Unreadable; } @@ -755,10 +758,11 @@ struct Shapes { as_wgs84: Option, as_wgs84_count: usize, as_wgs84_now: bool, - /// The borders references may follow, by [`border_key`]: each GeoBorder's at the date, held once. - borders: HashMap>, - /// The key of the border a `gml:id` (its curve's, or any of its members') names. - border_names: HashMap, + /// The borders references may follow: each GeoBorder's at the date, held once. + borders: Vec>, + /// Which border a name names ([`border_key`]): its identifier, its curve's `gml:id`, and its + /// members'. A reference holds the number, which no identifier's length makes larger. + border_names: HashMap, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of @@ -1169,7 +1173,7 @@ impl Shapes { "Ring" => { // Its members: curves written out, and borders given by reference, which are cut // once the points either side of them are known. - let mut members: Vec, String>> = Vec::new(); + let mut members: Vec, usize>> = Vec::new(); for m in elements(r).filter(|c| local(c) == "curveMember") { match elements(m).next() { Some(c) => members.push(Ok(self.curve(c, notes)?)), @@ -1177,7 +1181,7 @@ impl Shapes { // The same border named again straight after is the same stretch of // it (DFS writes a border's members so), followed once. let key = border_key(m.attribute((XLINK, "href"))?); - let key = self.border_names.get(&key).cloned().unwrap_or(key); + let key = self.border_names.get(&key).copied().unwrap_or(NO_BORDER); if !matches!(members.last(), Some(Err(k)) if *k == key) { members.push(Err(key)); } @@ -1191,11 +1195,11 @@ impl Shapes { let n = members.len(); // Each member's nearest written points before and after it, round the ring: two // passes, however many members are references. - let end_of = |m: Option<&std::result::Result, String>>| match m { + let end_of = |m: Option<&std::result::Result, usize>>| match m { Some(Ok(c)) => c.last().copied(), _ => None, }; - let start_of = |m: Option<&std::result::Result, String>>| match m { + let start_of = |m: Option<&std::result::Result, usize>>| match m { Some(Ok(c)) => c.first().copied(), _ => None, }; @@ -1218,12 +1222,12 @@ impl Shapes { for i in 0..n { let mut part = match members.get(i) { Some(Ok(c)) => c.clone(), - Some(Err(key)) => { + Some(&Err(key)) => { // Next to another border (a state's outline is a chain of them), the // stretch starts or ends where the two meet: this border's end nearest // that one. Next to written points, at the nearest of those. let neighbor = |k: usize| match members.get(k % n) { - Some(Err(other)) if other != key && n > 1 => Some(other.clone()), + Some(&Err(other)) if other != key && n > 1 => Some(other), _ => None, }; let (prev, next) = (neighbor(i + n - 1), neighbor(i + 1)); @@ -1236,8 +1240,8 @@ impl Shapes { // counted once, from the first of them. // One that can't be worked out (past the work allowed, or a // border not there to meet) leaves the ring undrawn, and why is said. - let mut meet = |s: &mut Self, other: Option, count_gap: bool| match other { - Some(other) => s.junction(key, &other).map(|(c, gap)| { + let mut meet = |s: &mut Self, other: Option, count_gap: bool| match other { + Some(other) => s.junction(key, other).map(|(c, gap)| { far += usize::from(gap && count_gap); Some(c) }), @@ -1307,14 +1311,14 @@ impl Shapes { Some(pts) } - /// The part of a border given by reference (`key`, [`border_key`]) a ring follows: from the + /// The part of a border given by reference (`key`, its number) a ring follows: from the /// point on it nearest `before` (the end of the member before) to the one nearest `after` (the /// start of the next), the shorter way round a border that closes; the whole border when the /// ring has no other points. AIXM leaves this cut to the reader (its coding guidance, "Geoborder /// for Airspace Border"), so each is counted, and those whose ends lie far from the border. fn follow( &mut self, - key: &str, + key: usize, before: Option, after: Option, notes: &mut ShapeNotes, @@ -1345,6 +1349,12 @@ impl Shapes { Ok((part, far)) } + /// Keeps a border under its names. + fn add_border(&mut self, names: impl IntoIterator, line: Vec) { + self.border_names.extend(names.into_iter().map(|n| (n, self.borders.len()))); + self.borders.push(line); + } + /// Takes `n` steps of looking along borders from their allowance: false when it is spent. fn scan(&mut self, n: usize) -> bool { match self.scan_left.checked_sub(n) { @@ -1360,7 +1370,7 @@ impl Shapes { /// nearest `other`, of those an end of either gives (its own ends, or the point on it nearest /// one of `other`'s, where `other` runs on past where they meet or stops short). Looking along /// both is paid for as points are. - fn junction(&mut self, key: &str, other: &str) -> std::result::Result<(Coord, bool), Unfollowed> { + fn junction(&mut self, key: usize, other: usize) -> std::result::Result<(Coord, bool), Unfollowed> { let scan = self.borders.get(other).ok_or(Unfollowed::Missing)?.len() + self.borders.get(key).ok_or(Unfollowed::Missing)?.len(); if !self.scan(scan) { return Err(Unfollowed::Allowance); @@ -1490,7 +1500,11 @@ fn say_unfollowed(why: Unfollowed, notes: &mut ShapeNotes) { /// How far from a border the ends of a part cut from it may lie before that is said, in meters. const FAR_FROM_BORDER_M: f64 = 50.0; -/// What a reference names a border by: `#` and a curve's `gml:id`, or its feature's identifier. +/// The number of a border that isn't in the file. +const NO_BORDER: usize = usize::MAX; + +/// What a reference names a border by: `#` and a `gml:id`, or its feature's identifier. Which border +/// that is, `Shapes::border_names` says. fn border_key(href: &str) -> String { let h = href.trim(); match h.strip_prefix('#') { @@ -2537,16 +2551,13 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize } let kind = feature.kind.as_str(); // A GeoBorder's line, at the date, for the borders that follow it by reference: by its - // identifier and its curve's id. + // identifier, its curve's id and its members'. if kind == "GeoBorder" && let Some(g) = props.iter().filter(|p| local(p) == "border").find_map(|p| shape_in(*p)) && let Some(Geometry::Line(parts)) = shapes.quietly(g) { - let key = border_key(id); - for gid in g.attribute((GML, "id")).map(str::trim).into_iter().chain(feature.gml_ids.iter().map(String::as_str)) { - shapes.border_names.insert(format!("#{gid}"), key.clone()); - } - shapes.borders.insert(key, parts.concat()); + let gids = g.attribute((GML, "id")).map(str::trim).into_iter().chain(feature.gml_ids.iter().map(String::as_str)); + shapes.add_border(gids.map(|gid| format!("#{gid}")).chain([border_key(id)]), parts.concat()); } // Where a point feature is, for route segments that name it: by its identifier and its // own gml:id (a local link's or an XPath's). diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index b27ff4604c..801fdde90e 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1117,8 +1117,8 @@ fn a_ring_whose_borders_cant_be_joined_within_the_allowance_isnt_drawn_and_says_ let boundary = doc.root_element().first_element_child().unwrap(); let line = |pts: &[(f64, f64)]| pts.iter().map(|&(x, y)| Coord::new(x, y)).collect::>(); let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; - shapes.borders.insert("uuid:a".into(), line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)])); - shapes.borders.insert("uuid:b".into(), line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)])); + shapes.add_border(["uuid:a".to_string()], line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)])); + shapes.add_border(["uuid:b".to_string()], line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)])); // With room to look along both borders where they meet: drawn. shapes.scan_left = 1000; let mut notes = ShapeNotes::default(); @@ -1977,6 +1977,18 @@ fn a_change_given_a_period_is_withheld_and_a_snapshot_is_read_at_its_start_and_s }; assert_eq!(run(&[base.clone(), ended("2020-01-01T00:00:00Z")], "2026-01-15").0.len(), 2); assert_eq!(run(&[base.clone(), ended("2025-06-01T00:00:00Z")], "2026-01-15").0.len(), 1); + // One that ends before it begins, whichever date is wrong. + let reversed = change("PERMDELTA", 1, &period("2026-01-01T00:00:00Z", Some("2024-02-01T00:00:00Z")), "PERM"); + assert_eq!(run(&[base.clone(), reversed], "2026-01-15").0.len(), 1); + let reversed = change("PERMDELTA", 1, &period("2026-02-01T00:00:00Z", Some("2024-02-01T00:00:00Z")), "PERM"); + let notes = run(&[snapshot_at("2026-03-01T00:00:00Z", "SNAP"), reversed], "2026-01-15").1; + assert!(notes.iter().any(|m| m.contains("doesn't reflect changes")), "{notes:?}"); + // One with no date at all: withheld since the state, shown and said before a later snapshot. + let undated = change("PERMDELTA", 1, &instant("bad"), "PERM"); + assert_eq!(run(&[base.clone(), undated.clone()], "2026-01-15").0.len(), 1); + assert_eq!(run(&[base.clone(), undated.clone()], "2025-01-01").0.len(), 2); + let (got, notes) = run(&[snapshot_at("2026-03-01T00:00:00Z", "SNAP"), undated], "2026-01-15"); + assert!(got.len() == 2 && notes.iter().any(|m| m.contains("doesn't reflect changes")), "{got:?} {notes:?}"); // Past a snapshot's instant, or open, and before one later than the date: shown, and said. for end in [Some("2026-04-01T00:00:00Z"), None, Some("bad")] { let p = change("PERMDELTA", 1, &period("2026-01-01T00:00:00Z", end), "PERM"); @@ -2106,3 +2118,26 @@ fn a_border_named_two_ways_in_a_row_is_one_border() { assert_eq!(drawn(&refs), once, "{refs:?}"); } } + +#[test] +fn borders_of_alike_identifiers_are_told_apart_by_their_gml_ids() { + let border = |id: &str, gid: &str, curve: &str, lat: f64| { + let b = format!( + r#"{lat} 9 {lat} 10"# + ); + feature("GeoBorder", id, &[slice("GeoBorder", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &b)]) + .replace(r#"gml:id="f""#, &format!(r#"gml:id="{gid}""#)) + }; + let members = border("urn:uuid:X", "b1", "c1", 50.0) + &border("X", "b2", "c2", 40.0); + for (name, lat) in [("#b1", 50.0), ("#c1", 50.0), ("#b2", 40.0), ("#c2", 40.0)] { + let area = format!( + r#"{lat} 10 51 10 51 9 {lat} 9"# + ); + let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &area)]); + let out = read("t.xml", &message(&(members.clone() + &f)), &at("2026-01-15")).unwrap(); + let r = ring(layer(&out, "t WorkArea").features[0].geometry.as_ref().unwrap()).to_vec(); + assert!(r.iter().all(|c| (c.y - lat).abs() < 1e-6 || (c.y - 51.0).abs() < 0.1 || c.y > lat), "{name}: {r:?}"); + assert!(r.iter().filter(|c| (c.y - lat).abs() < 1e-9).count() >= 2, "{name}: {r:?}"); + assert!(lat == 40.0 || r.iter().all(|c| c.y > 49.0), "{name}: {r:?}"); + } +} From 1393fe1fab1cb35daf5abe0edfa4dfb5cab43d7c Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:29:40 -0600 Subject: [PATCH 50/61] fix(data): AIXM periods that end before they begin withhold their feature; a border name two have is neither's; a ring with a missing border spends nothing --- crates/data/src/aixm.rs | 65 +++++++++++++++++++-------------- crates/data/src/aixm/tests.rs | 69 ++++++++++++++++++++++++++++++----- 2 files changed, 98 insertions(+), 36 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 3875443ce4..eff90843a7 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -431,8 +431,6 @@ fn in_force(begin: Option, end: Option, t: f64) -> bool { fn may_be_made(s: &Slice, from: f64, to: f64) -> bool { let (first, last) = match (s.begin, s.end) { (Some(b), None) => (b, b), - // One that ends before it begins is wrong in one of them: its end isn't known. - (Some(b), Some(e)) if e < b => (b, f64::INFINITY), (b, e) => (b.unwrap_or(f64::NEG_INFINITY), e.unwrap_or(f64::INFINITY)), }; from < to && first <= to && last > from @@ -648,6 +646,12 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro }); (from, until) }); + // A period that ends before it begins is wrong in one of them: neither says when it applies. + if begin.zip(end).is_some_and(|(b, e)| e < b) { + bad = true; + begin = None; + end = (kind == Interpretation::PermDelta).then_some(f64::INFINITY); + } let (sequence, correction) = (number("sequenceNumber"), number("correctionNumber")); trouble.numbers += usize::from(unread_number.get()); // A PERMDELTA applies from its instant and a SNAPSHOT is a state at its: one without can't be @@ -760,9 +764,9 @@ struct Shapes { as_wgs84_now: bool, /// The borders references may follow: each GeoBorder's at the date, held once. borders: Vec>, - /// Which border a name names ([`border_key`]): its identifier, its curve's `gml:id`, and its - /// members'. A reference holds the number, which no identifier's length makes larger. - border_names: HashMap, + /// Which border a name names (`None`, more than one): its identifier, its curve's `gml:id`, and + /// its members'. A reference holds the number, which no identifier's length makes larger. + border_names: HashMap>, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of @@ -1180,8 +1184,12 @@ impl Shapes { None => { // The same border named again straight after is the same stretch of // it (DFS writes a border's members so), followed once. - let key = border_key(m.attribute((XLINK, "href"))?); - let key = self.border_names.get(&key).copied().unwrap_or(NO_BORDER); + // One not in the file leaves the ring undrawn, before work is spent + // on the rest of it. + let Some(key) = self.border_named(m.attribute((XLINK, "href"))?) else { + say_unfollowed(Unfollowed::Missing, notes); + return None; + }; if !matches!(members.last(), Some(Err(k)) if *k == key) { members.push(Err(key)); } @@ -1349,10 +1357,26 @@ impl Shapes { Ok((part, far)) } - /// Keeps a border under its names. - fn add_border(&mut self, names: impl IntoIterator, line: Vec) { - self.border_names.extend(names.into_iter().map(|n| (n, self.borders.len()))); + /// Keeps a border under its names: its identifier as written, and without `urn:uuid:`, and its + /// `gml:id`s. A name two borders have is neither's. + fn add_border<'a>(&mut self, id: &str, gids: impl IntoIterator, line: Vec) { + let n = self.borders.len(); self.borders.push(line); + let id = id.trim(); + let names = [format!("id:{id}"), format!("uuid:{}", id.strip_prefix("urn:uuid:").unwrap_or(id))]; + for name in names.into_iter().chain(gids.into_iter().map(|g| format!("#{}", g.trim()))) { + self.border_names.entry(name).and_modify(|k| *k = if *k == Some(n) { Some(n) } else { None }).or_insert(Some(n)); + } + } + + /// The border a reference names: by a `gml:id` (`#id`), or by its identifier, as written first. + fn border_named(&self, href: &str) -> Option { + let h = href.trim(); + if h.starts_with('#') { + return self.border_names.get(h).copied().flatten(); + } + let by = |name: String| self.border_names.get(&name).copied().flatten(); + by(format!("id:{h}")).or_else(|| by(format!("uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)))) } /// Takes `n` steps of looking along borders from their allowance: false when it is spent. @@ -1500,19 +1524,6 @@ fn say_unfollowed(why: Unfollowed, notes: &mut ShapeNotes) { /// How far from a border the ends of a part cut from it may lie before that is said, in meters. const FAR_FROM_BORDER_M: f64 = 50.0; -/// The number of a border that isn't in the file. -const NO_BORDER: usize = usize::MAX; - -/// What a reference names a border by: `#` and a `gml:id`, or its feature's identifier. Which border -/// that is, `Shapes::border_names` says. -fn border_key(href: &str) -> String { - let h = href.trim(); - match h.strip_prefix('#') { - Some(id) => format!("#{id}"), - None => format!("uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)), - } -} - /// Where on `line` a point is nearest `p`: the segment, how far along it (0 to 1), the point, and /// its distance from `p` in meters. Worked out in a plane around `p` (longitude scaled by the /// cosine of its latitude), fine at the scale of a border's segments. @@ -2556,8 +2567,8 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize && let Some(g) = props.iter().filter(|p| local(p) == "border").find_map(|p| shape_in(*p)) && let Some(Geometry::Line(parts)) = shapes.quietly(g) { - let gids = g.attribute((GML, "id")).map(str::trim).into_iter().chain(feature.gml_ids.iter().map(String::as_str)); - shapes.add_border(gids.map(|gid| format!("#{gid}")).chain([border_key(id)]), parts.concat()); + let gids = g.attribute((GML, "id")).into_iter().chain(feature.gml_ids.iter().map(String::as_str)); + shapes.add_border(id, gids, parts.concat()); } // Where a point feature is, for route segments that name it: by its identifier and its // own gml:id (a local link's or an XPath's). @@ -3374,8 +3385,8 @@ fn finish( ); say( layer.referenced, - "border is given by reference to a curve that isn't in the file (or not in force then), so it can't be followed", - "borders are given by reference to curves that aren't in the file (or not in force then), so they can't be followed", + "border is given by reference to a curve that isn't in the file (or not in force then, or of a name more than one has), so it can't be followed", + "borders are given by reference to curves that aren't in the file (or not in force then, or of a name more than one has), so they can't be followed", ); say( layer.followed_whole, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 801fdde90e..8f59ded028 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1117,8 +1117,8 @@ fn a_ring_whose_borders_cant_be_joined_within_the_allowance_isnt_drawn_and_says_ let boundary = doc.root_element().first_element_child().unwrap(); let line = |pts: &[(f64, f64)]| pts.iter().map(|&(x, y)| Coord::new(x, y)).collect::>(); let mut shapes = Shapes { budget: 1_000_000, ..Shapes::default() }; - shapes.add_border(["uuid:a".to_string()], line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)])); - shapes.add_border(["uuid:b".to_string()], line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)])); + shapes.add_border("a", [], line(&[(9.0, 50.0), (9.5, 50.0), (10.0, 50.0)])); + shapes.add_border("b", [], line(&[(10.0, 50.0), (10.0, 50.5), (10.0, 51.0)])); // With room to look along both borders where they meet: drawn. shapes.scan_left = 1000; let mut notes = ShapeNotes::default(); @@ -2129,15 +2129,66 @@ fn borders_of_alike_identifiers_are_told_apart_by_their_gml_ids() { .replace(r#"gml:id="f""#, &format!(r#"gml:id="{gid}""#)) }; let members = border("urn:uuid:X", "b1", "c1", 50.0) + &border("X", "b2", "c2", 40.0); - for (name, lat) in [("#b1", 50.0), ("#c1", 50.0), ("#b2", 40.0), ("#c2", 40.0)] { + let drawn = |name: &str, members: &str| { let area = format!( - r#"{lat} 10 51 10 51 9 {lat} 9"# + r#"45 10 45 9"# ); let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &area)]); - let out = read("t.xml", &message(&(members.clone() + &f)), &at("2026-01-15")).unwrap(); - let r = ring(layer(&out, "t WorkArea").features[0].geometry.as_ref().unwrap()).to_vec(); - assert!(r.iter().all(|c| (c.y - lat).abs() < 1e-6 || (c.y - 51.0).abs() < 0.1 || c.y > lat), "{name}: {r:?}"); - assert!(r.iter().filter(|c| (c.y - lat).abs() < 1e-9).count() >= 2, "{name}: {r:?}"); - assert!(lat == 40.0 || r.iter().all(|c| c.y > 49.0), "{name}: {r:?}"); + let out = read("t.xml", &message(&(members.to_string() + &f)), &at("2026-01-15")).unwrap(); + let lats = layer(&out, "t WorkArea").features[0].geometry.as_ref().map(|g| { + let mut l: Vec = ring(g).iter().map(|c| c.y.round() as i64).collect(); + l.sort_unstable(); + l.dedup(); + l + }); + (lats, said(&out)) + }; + // Each by its own gml:ids, and by its identifier as it is written. + for (name, lat) in [("#b1", 50), ("#c1", 50), ("urn:uuid:X", 50), ("#b2", 40), ("#c2", 40), ("X", 40)] { + let (lats, _) = drawn(name, &members); + let lats = lats.unwrap_or_else(|| panic!("{name} not drawn")); + assert!(lats.contains(&lat) && !lats.contains(&(90 - lat)), "{name}: {lats:?}"); + } + // A name two have is neither's, and that is said; an identifier that looks like a gml:id isn't one. + let shared = members.replace("c2", "c1"); + let (lats, notes) = drawn("#c1", &shared); + assert_eq!(lats, None); + assert!(notes.iter().any(|m| m.contains("of a name more than one has")), "{notes:?}"); + let odd = members.clone() + &border("#b1", "b3", "c3", 40.0); + assert!(drawn("#b1", &odd).0.is_some_and(|l| l.contains(&50))); +} + +#[test] +fn a_border_not_in_the_file_spends_nothing_of_those_that_are() { + let doc = format!( + r#""# + ); + let doc = roxmltree::Document::parse(&doc).unwrap(); + let mut shapes = Shapes { budget: 1000, scan_left: 1000, ..Shapes::default() }; + shapes.add_border("v", [], vec![Coord::new(9.0, 50.0), Coord::new(10.0, 50.0)]); + let mut notes = ShapeNotes::default(); + assert!(shapes.ring(doc.root_element().first_element_child().unwrap(), &mut notes).is_none()); + assert_eq!((notes.referenced, notes.border_allowance, shapes.budget, shapes.scan_left), (1, 0, 1000, 1000)); +} + +#[test] +fn a_period_that_ends_before_it_begins_withholds_its_feature() { + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let base = baseline(1, 0, "2025-01-01T00:00:00Z", None, "BASE"); + for (begin, end) in [("2026-01-10T00:00:00Z", "2025-01-20T00:00:00Z"), ("2027-01-01T00:00:00Z", "2025-06-01T00:00:00Z")] { + let valid = period(begin, Some(end)); + for kind in ["TEMPDELTA", "PERMDELTA"] { + let (got, notes) = + names(&message(&(point("a", &[base.clone(), change(kind, 1, &valid, "X")]) + &kept)), "2026-01-15"); + assert_eq!(got, [Value::Text("KEPT".into())], "{kind} {begin}"); + assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice")), "{notes:?}"); + } + let (got, notes) = names(&message(&(point("a", &[baseline(1, 0, begin, Some(end), "BASE")]) + &kept)), "2026-01-15"); + assert_eq!(got, [Value::Text("KEPT".into())], "{begin}"); + assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice")), "{notes:?}"); } + // Before a later snapshot: shown, and said. + let perm = change("PERMDELTA", 1, &period("2026-04-01T00:00:00Z", Some("2026-02-01T00:00:00Z")), "X"); + let (got, notes) = names(&message(&(point("a", &[snapshot_at("2026-03-01T00:00:00Z", "SNAP"), perm]) + &kept)), "2026-01-15"); + assert!(got.len() == 2 && notes.iter().any(|m| m.contains("doesn't reflect changes")), "{notes:?}"); } From effad5550511b9e8fced165fe97a2c8c0b087045 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:35:51 -0600 Subject: [PATCH 51/61] fix(data): AIXM references name one border or point or none; lifetimes that end before they begin; rings with a missing border cost nothing --- crates/data/src/aixm.rs | 86 +++++++++++++++++++++------------ crates/data/src/aixm/tests.rs | 47 ++++++++++++++++++ docs/user-guide/data-formats.md | 2 +- 3 files changed, 103 insertions(+), 32 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index eff90843a7..1b6df6a2a0 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -644,9 +644,11 @@ fn slice_of(s: Node, range: (usize, usize), scope: usize, trouble: &mut SliceTro bad = true; None }); + bad |= from.zip(until).is_some_and(|(f, u)| u < f); (from, until) }); - // A period that ends before it begins is wrong in one of them: neither says when it applies. + // A period that ends before it begins has either date wrong, or the two swapped: neither says + // when it applies. if begin.zip(end).is_some_and(|(b, e)| e < b) { bad = true; begin = None; @@ -771,7 +773,7 @@ struct Shapes { scan_left: usize, /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of /// route segments that name them. - points: HashMap, + points: HashMap>, } fn wrap180(d: f64) -> f64 { @@ -1177,6 +1179,13 @@ impl Shapes { "Ring" => { // Its members: curves written out, and borders given by reference, which are cut // once the points either side of them are known. + // A border not in the file leaves the ring undrawn, before work is spent on it. + let missing = + |m: &Node| elements(*m).next().is_none() && m.attribute((XLINK, "href")).and_then(|h| self.border_named(h)).is_none(); + if elements(r).filter(|c| local(c) == "curveMember").any(|m| missing(&m)) { + say_unfollowed(Unfollowed::Missing, notes); + return None; + } let mut members: Vec, usize>> = Vec::new(); for m in elements(r).filter(|c| local(c) == "curveMember") { match elements(m).next() { @@ -1184,12 +1193,7 @@ impl Shapes { None => { // The same border named again straight after is the same stretch of // it (DFS writes a border's members so), followed once. - // One not in the file leaves the ring undrawn, before work is spent - // on the rest of it. - let Some(key) = self.border_named(m.attribute((XLINK, "href"))?) else { - say_unfollowed(Unfollowed::Missing, notes); - return None; - }; + let key = self.border_named(m.attribute((XLINK, "href"))?)?; if !matches!(members.last(), Some(Err(k)) if *k == key) { members.push(Err(key)); } @@ -1358,25 +1362,33 @@ impl Shapes { } /// Keeps a border under its names: its identifier as written, and without `urn:uuid:`, and its - /// `gml:id`s. A name two borders have is neither's. + /// `gml:id`s. A name two borders have is neither's, and one with no `line` (not in force, or that + /// can't be read) keeps its names from another's. fn add_border<'a>(&mut self, id: &str, gids: impl IntoIterator, line: Vec) { let n = self.borders.len(); self.borders.push(line); let id = id.trim(); let names = [format!("id:{id}"), format!("uuid:{}", id.strip_prefix("urn:uuid:").unwrap_or(id))]; for name in names.into_iter().chain(gids.into_iter().map(|g| format!("#{}", g.trim()))) { - self.border_names.entry(name).and_modify(|k| *k = if *k == Some(n) { Some(n) } else { None }).or_insert(Some(n)); + self.name_border(n, name); } } + /// Gives border `n` one more name. + fn name_border(&mut self, n: usize, name: String) { + self.border_names.entry(name).and_modify(|k| *k = k.filter(|k| *k == n)).or_insert(Some(n)); + } + /// The border a reference names: by a `gml:id` (`#id`), or by its identifier, as written first. fn border_named(&self, href: &str) -> Option { let h = href.trim(); - if h.starts_with('#') { - return self.border_names.get(h).copied().flatten(); - } - let by = |name: String| self.border_names.get(&name).copied().flatten(); - by(format!("id:{h}")).or_else(|| by(format!("uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)))) + let by = |name: &str| self.border_names.get(name).copied(); + let named = if h.starts_with('#') { + by(h) + } else { + by(&format!("id:{h}")).or_else(|| by(&format!("uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)))) + }; + named.flatten().filter(|n| self.borders.get(*n).is_some_and(|l| !l.is_empty())) } /// Takes `n` steps of looking along borders from their allowance: false when it is spent. @@ -2459,6 +2471,14 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize } } order.sort_by_key(rank); + // Every GeoBorder's names first, in force or not: a reference names that one and no other. + let mut border_of: HashMap = HashMap::new(); + for key in &order { + if let Some(f) = features.get(key).filter(|f| f.kind == "GeoBorder") { + border_of.insert(key.clone(), shapes.borders.len()); + shapes.add_border(&f.id, f.gml_ids.iter().map(String::as_str), Vec::new()); + } + } crate::progress::begin(index.members.len() + order.len()); crate::progress::step(index.members.len())?; for key in &order { @@ -2563,12 +2583,16 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize let kind = feature.kind.as_str(); // A GeoBorder's line, at the date, for the borders that follow it by reference: by its // identifier, its curve's id and its members'. - if kind == "GeoBorder" + if let Some(&n) = border_of.get(key) && let Some(g) = props.iter().filter(|p| local(p) == "border").find_map(|p| shape_in(*p)) && let Some(Geometry::Line(parts)) = shapes.quietly(g) { - let gids = g.attribute((GML, "id")).into_iter().chain(feature.gml_ids.iter().map(String::as_str)); - shapes.add_border(id, gids, parts.concat()); + if let Some(gid) = g.attribute((GML, "id")) { + shapes.name_border(n, format!("#{}", gid.trim())); + } + if let Some(line) = shapes.borders.get_mut(n) { + *line = parts.concat(); + } } // Where a point feature is, for route segments that name it: by its identifier and its // own gml:id (a local link's or an XPath's). @@ -2576,13 +2600,13 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize && let Some(Geometry::Point(c)) = shapes.quietly(g) { // By its own gml:id (a local link or an XPath), by its kind and identifier, and by - // its identifier alone for a link whose kind isn't known (the first so named). - for gid in &feature.gml_ids { - shapes.points.insert(format!("#{gid}"), c); - } + // its identifier alone for a link whose kind isn't known. + // A name of features in more than one place is none's. let uuid = id.trim_start_matches("urn:uuid:"); - shapes.points.insert(format!("{kind}\u{1}{uuid}"), c); - shapes.points.entry(uuid.to_string()).or_insert(c); + let names = [format!("{kind}\u{1}{uuid}"), uuid.to_string()]; + for name in feature.gml_ids.iter().map(|g| format!("#{g}")).chain(names) { + shapes.points.entry(name).and_modify(|p| *p = p.filter(|p| *p == c)).or_insert(Some(c)); + } } let mut fnotes = ShapeNotes::default(); let placed = match kind { @@ -2686,11 +2710,11 @@ fn segment_end<'a, 'i>(props: &[Node<'a, 'i>], name: &str, shapes: &Shapes) -> O fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { let target = reference(href); if href.trim().starts_with('#') || href.contains("@gml:id") { - return shapes.points.get(&format!("#{target}")).copied(); + return shapes.points.get(&format!("#{target}")).copied().flatten(); } match point_kind(local(&choice)) { - Some(k) => shapes.points.get(&format!("{k}\u{1}{target}")).copied(), - None => shapes.points.get(&target).copied(), + Some(k) => shapes.points.get(&format!("{k}\u{1}{target}")).copied().flatten(), + None => shapes.points.get(&target).copied().flatten(), } } @@ -3153,7 +3177,7 @@ fn finish( notes.unreadable_state, "feature", "features", - "left out: a time slice of it that may apply (the latest correction) has no validTime of the kind it needs (a period, an instant for a PERMDELTA, or for a SNAPSHOT an instant or a period with a start), or a validTime or featureLifetime that can't be read", + "left out: a time slice of it that may apply (the latest correction) has no validTime of the kind it needs (a period, an instant for a PERMDELTA, or for a SNAPSHOT an instant or a period with a start), or a validTime or featureLifetime that can't be read or ends before it begins", ); say( &mut file, @@ -3191,7 +3215,7 @@ fn finish( notes.bad_dates, "time slice", "time slices", - "with no validTime of the kind it needs (a period, an instant for a PERMDELTA, or for a SNAPSHOT an instant or a period with a start), or with a validTime or featureLifetime that can't be read (a feature it may apply to is left out, or shown as its SNAPSHOT)", + "with no validTime of the kind it needs (a period, an instant for a PERMDELTA, or for a SNAPSHOT an instant or a period with a start), or with a validTime or featureLifetime that can't be read or ends before it begins (a feature it may apply to is left out, or shown as its SNAPSHOT)", ); say( &mut file, @@ -3435,8 +3459,8 @@ fn finish( ); say( layer.route_unlocated, - "route segment is kept without a line: a point its start or end names isn't in the file, or has no position on the date asked", - "route segments are kept without a line: a point their start or end names isn't in the file, or has no position on the date asked", + "route segment is kept without a line: a point its start or end names isn't in the file, has no position on the date asked, or has a name others share", + "route segments are kept without a line: a point their start or end names isn't in the file, has no position on the date asked, or has a name others share", ); say( layer.route_no_ends, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 8f59ded028..d874d764e5 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2154,6 +2154,14 @@ fn borders_of_alike_identifiers_are_told_apart_by_their_gml_ids() { let (lats, notes) = drawn("#c1", &shared); assert_eq!(lats, None); assert!(notes.iter().any(|m| m.contains("of a name more than one has")), "{notes:?}"); + // One not in force is no other: not drawn along the one whose identifier is alike. + let past = members.replacen("2025-01-01T00:00:00Z", "2030-01-01T00:00:00Z", 1); + for name in ["urn:uuid:X", "#b1"] { + let (lats, notes) = drawn(name, &past); + assert_eq!(lats, None, "{name}"); + assert!(notes.iter().any(|m| m.contains("not in force then")), "{notes:?}"); + } + assert!(drawn("X", &past).0.is_some_and(|l| l.contains(&40))); let odd = members.clone() + &border("#b1", "b3", "c3", 40.0); assert!(drawn("#b1", &odd).0.is_some_and(|l| l.contains(&50))); } @@ -2169,6 +2177,13 @@ fn a_border_not_in_the_file_spends_nothing_of_those_that_are() { let mut notes = ShapeNotes::default(); assert!(shapes.ring(doc.root_element().first_element_child().unwrap(), &mut notes).is_none()); assert_eq!((notes.referenced, notes.border_allowance, shapes.budget, shapes.scan_left), (1, 0, 1000, 1000)); + // Nor the curves written before it. + let doc = format!( + r#"50 1010"# + ); + let doc = roxmltree::Document::parse(&doc).unwrap(); + assert!(shapes.ring(doc.root_element().first_element_child().unwrap(), &mut notes).is_none()); + assert_eq!((shapes.budget, shapes.scan_left), (1000, 1000)); } #[test] @@ -2192,3 +2207,35 @@ fn a_period_that_ends_before_it_begins_withholds_its_feature() { let (got, notes) = names(&message(&(point("a", &[snapshot_at("2026-03-01T00:00:00Z", "SNAP"), perm]) + &kept)), "2026-01-15"); assert!(got.len() == 2 && notes.iter().any(|m| m.contains("doesn't reflect changes")), "{notes:?}"); } + +#[test] +fn a_route_end_named_as_two_points_are_is_neither() { + let far = named_at("DesignatedPoint", "far", 50.0, 12.0); + let run = |points: &str, route: &str| { + let out = read("t.xml", &message(&(points.to_string() + &far + route)), &at("2026-01-15")).unwrap(); + (layer(&out, "t RouteSegment").features[0].geometry.is_some(), said(&out)) + }; + let by_id = route_to("pointChoice_fixDesignatedPoint", "X"); + let by_gid = by_id.replace("urn:uuid:X", "#p"); + let two = |lat: f64| { + (named_at("DesignatedPoint", "X", 50.0, 10.0) + &named_at("DesignatedPoint", "urn:uuid:X", lat, 10.0)) + .replace(r#"gml:id="f""#, r#"gml:id="p""#) + }; + for route in [&by_id, &by_gid] { + let (drawn, notes) = run(&two(40.0), route); + assert!(!drawn && notes.iter().any(|m| m.contains("has a name others share")), "{notes:?}"); + // In one place, they are as one. + assert!(run(&two(50.0), route).0); + } +} + +#[test] +fn a_lifetime_that_ends_before_it_begins_withholds_its_feature_and_says_so() { + let life = r#"2020-06-01T00:00:00Z2020-03-01T00:00:00Z"#; + let kept = point("k", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "KEPT")]); + let body = named_point("A") + life; + let a = point("a", &[slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)]); + let (got, notes) = names(&message(&(a + &kept)), "2026-01-15"); + assert_eq!(got, [Value::Text("KEPT".into())]); + assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice") && m.contains("ends before it begins")), "{notes:?}"); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 7acb8e415d..355b629533 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter (coarser, and said, past the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read (or ends before it begins) are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter (coarser, and said, past the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From d8a1d0668966c7e1d46d1197847b50279473e939 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:43:57 -0600 Subject: [PATCH 52/61] fix(data): AIXM route ends name one point, in force or not; a ring member that names nothing --- crates/data/src/aixm.rs | 94 ++++++++++++++++++++++------------- crates/data/src/aixm/tests.rs | 41 ++++++++++++--- 2 files changed, 94 insertions(+), 41 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 1b6df6a2a0..51a4f709b9 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -771,9 +771,11 @@ struct Shapes { border_names: HashMap>, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, - /// Where each point feature is (a navaid, a designated point), by its identifier: the ends of - /// route segments that name them. - points: HashMap>, + /// Where each feature a route segment's end can name ([`POINT_KINDS`]) is at the date, if + /// anywhere. + points: Vec>, + /// Which of them a name names (`None`, more than one). + point_names: HashMap>, } fn wrap180(d: f64) -> f64 { @@ -1180,8 +1182,9 @@ impl Shapes { // Its members: curves written out, and borders given by reference, which are cut // once the points either side of them are known. // A border not in the file leaves the ring undrawn, before work is spent on it. - let missing = - |m: &Node| elements(*m).next().is_none() && m.attribute((XLINK, "href")).and_then(|h| self.border_named(h)).is_none(); + let missing = |m: &Node| { + elements(*m).next().is_none() && m.attribute((XLINK, "href")).is_some_and(|h| self.border_named(h).is_none()) + }; if elements(r).filter(|c| local(c) == "curveMember").any(|m| missing(&m)) { say_unfollowed(Unfollowed::Missing, notes); return None; @@ -1391,6 +1394,20 @@ impl Shapes { named.flatten().filter(|n| self.borders.get(*n).is_some_and(|l| !l.is_empty())) } + /// Keeps a point feature under its names, its place not known yet: its `gml:id`s, and its + /// identifier as written and without `urn:uuid:`, of its kind and of any. A name two have is + /// neither's. + fn add_point(&mut self, f: &Feature) { + let n = self.points.len(); + self.points.push(None); + let id = f.id.trim(); + let bare = id.strip_prefix("urn:uuid:").unwrap_or(id); + let ids = [f.kind.as_str(), "*"].into_iter().flat_map(|k| [format!("{k}\u{1}id:{id}"), format!("{k}\u{1}uuid:{bare}")]); + for name in f.gml_ids.iter().map(|g| format!("#{g}")).chain(ids) { + self.point_names.entry(name).and_modify(|k| *k = k.filter(|k| *k == n)).or_insert(Some(n)); + } + } + /// Takes `n` steps of looking along borders from their allowance: false when it is spent. fn scan(&mut self, n: usize) -> bool { match self.scan_left.checked_sub(n) { @@ -2471,7 +2488,8 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize } } order.sort_by_key(rank); - // Every GeoBorder's names first, in force or not: a reference names that one and no other. + // Every GeoBorder's identifiers and gml:ids first, in force or not: a reference to one names it + // and no other (its curve's gml:id is known once it is read). let mut border_of: HashMap = HashMap::new(); for key in &order { if let Some(f) = features.get(key).filter(|f| f.kind == "GeoBorder") { @@ -2479,6 +2497,16 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize shapes.add_border(&f.id, f.gml_ids.iter().map(String::as_str), Vec::new()); } } + // And those of the points route segments name, in a file that has any. + let mut point_of: HashMap = HashMap::new(); + if features.values().any(|f| f.kind == "RouteSegment") { + for key in &order { + if let Some(f) = features.get(key).filter(|f| POINT_KINDS.iter().any(|(_, k)| *k == f.kind)) { + point_of.insert(key.clone(), shapes.points.len()); + shapes.add_point(f); + } + } + } crate::progress::begin(index.members.len() + order.len()); crate::progress::step(index.members.len())?; for key in &order { @@ -2594,19 +2622,13 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize *line = parts.concat(); } } - // Where a point feature is, for route segments that name it: by its identifier and its - // own gml:id (a local link's or an XPath's). - if let Some(g) = props.iter().find_map(|p| shape_in(*p).filter(|g| matches!(local(g), "Point" | "ElevatedPoint"))) + // Where a point feature is, for route segments that name it. + if let Some(&n) = point_of.get(key) + && let Some(g) = props.iter().find_map(|p| shape_in(*p).filter(|g| matches!(local(g), "Point" | "ElevatedPoint"))) && let Some(Geometry::Point(c)) = shapes.quietly(g) + && let Some(p) = shapes.points.get_mut(n) { - // By its own gml:id (a local link or an XPath), by its kind and identifier, and by - // its identifier alone for a link whose kind isn't known. - // A name of features in more than one place is none's. - let uuid = id.trim_start_matches("urn:uuid:"); - let names = [format!("{kind}\u{1}{uuid}"), uuid.to_string()]; - for name in feature.gml_ids.iter().map(|g| format!("#{g}")).chain(names) { - shapes.points.entry(name).and_modify(|p| *p = p.filter(|p| *p == c)).or_insert(Some(c)); - } + *p = Some(c); } let mut fnotes = ShapeNotes::default(); let placed = match kind { @@ -2709,13 +2731,14 @@ fn segment_end<'a, 'i>(props: &[Node<'a, 'i>], name: &str, shapes: &Shapes) -> O /// kind the choice names, or (a choice of no known kind) any point of that identifier. fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { let target = reference(href); - if href.trim().starts_with('#') || href.contains("@gml:id") { - return shapes.points.get(&format!("#{target}")).copied().flatten(); - } - match point_kind(local(&choice)) { - Some(k) => shapes.points.get(&format!("{k}\u{1}{target}")).copied().flatten(), - None => shapes.points.get(&target).copied().flatten(), - } + let by = |name: String| shapes.point_names.get(&name).copied(); + let named = if href.trim().starts_with('#') || href.contains("@gml:id") { + by(format!("#{target}")) + } else { + let k = point_kind(local(&choice)).unwrap_or("*"); + by(format!("{k}\u{1}id:{}", href.trim())).or_else(|| by(format!("{k}\u{1}uuid:{target}"))) + }; + named.flatten().and_then(|n| shapes.points.get(n).copied().flatten()) } /// Whether a shape gives no positions: empty ones (as the FAA writes a position it doesn't have), @@ -2759,16 +2782,19 @@ fn names_a_missing_point(props: &[Node], shapes: &Shapes) -> bool { /// The kind of feature a route end's choice names (`pointChoice_fixDesignatedPoint`: a /// DesignatedPoint). fn point_kind(choice: &str) -> Option<&'static str> { - Some(match choice.strip_prefix("pointChoice_")? { - "fixDesignatedPoint" => "DesignatedPoint", - "navaidSystem" => "Navaid", - "aimingPoint" => "TouchDownLiftOff", - "runwayPoint" => "RunwayCentrelinePoint", - "airportReferencePoint" => "AirportHeliport", - _ => return None, - }) + let name = choice.strip_prefix("pointChoice_")?; + POINT_KINDS.iter().find(|(c, _)| *c == name).map(|(_, k)| *k) } +/// What a route segment's end can name, by its choice (the AIXM 5.1.1 schema's SegmentPoint). +const POINT_KINDS: [(&str, &str); 5] = [ + ("fixDesignatedPoint", "DesignatedPoint"), + ("navaidSystem", "Navaid"), + ("aimingPoint", "TouchDownLiftOff"), + ("runwayPoint", "RunwayCentrelinePoint"), + ("airportReferencePoint", "AirportHeliport"), +]; + /// The family a shape element draws as, by its name (what a layer of its shapes is labeled). fn element_family(name: &str) -> &'static str { match name { @@ -3409,8 +3435,8 @@ fn finish( ); say( layer.referenced, - "border is given by reference to a curve that isn't in the file (or not in force then, or of a name more than one has), so it can't be followed", - "borders are given by reference to curves that aren't in the file (or not in force then, or of a name more than one has), so they can't be followed", + "border is given by reference to a curve that isn't in the file (or not in force then, can't be read, or has a name others share), so it can't be followed", + "borders are given by reference to curves that aren't in the file (or not in force then, can't be read, or have a name others share), so they can't be followed", ); say( layer.followed_whole, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index d874d764e5..4fbe612c5a 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2153,7 +2153,7 @@ fn borders_of_alike_identifiers_are_told_apart_by_their_gml_ids() { let shared = members.replace("c2", "c1"); let (lats, notes) = drawn("#c1", &shared); assert_eq!(lats, None); - assert!(notes.iter().any(|m| m.contains("of a name more than one has")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("has a name others share")), "{notes:?}"); // One not in force is no other: not drawn along the one whose identifier is alike. let past = members.replacen("2025-01-01T00:00:00Z", "2030-01-01T00:00:00Z", 1); for name in ["urn:uuid:X", "#b1"] { @@ -2221,12 +2221,39 @@ fn a_route_end_named_as_two_points_are_is_neither() { (named_at("DesignatedPoint", "X", 50.0, 10.0) + &named_at("DesignatedPoint", "urn:uuid:X", lat, 10.0)) .replace(r#"gml:id="f""#, r#"gml:id="p""#) }; - for route in [&by_id, &by_gid] { - let (drawn, notes) = run(&two(40.0), route); - assert!(!drawn && notes.iter().any(|m| m.contains("has a name others share")), "{notes:?}"); - // In one place, they are as one. - assert!(run(&two(50.0), route).0); - } + let (drawn, notes) = run(&two(40.0), &by_gid); + assert!(!drawn && notes.iter().any(|m| m.contains("has a name others share")), "{notes:?}"); + // One written exactly so is that one. + let start = |points: &str, route: &str| { + let out = read("t.xml", &message(&(points.to_string() + &far + route)), &at("2026-01-15")).unwrap(); + match &layer(&out, "t RouteSegment").features[0].geometry { + Some(Geometry::Line(l)) => l[0].first().copied(), + _ => None, + } + }; + assert_eq!(start(&two(40.0), &by_id), Some(Coord::new(10.0, 40.0))); + assert_eq!(start(&two(40.0), &by_id.replace("urn:uuid:X", "X")), Some(Coord::new(10.0, 50.0))); + // Two with neither written so: neither. + let alike = named_at("DesignatedPoint", "X", 50.0, 10.0) + &named_at("DesignatedPoint", "urn:uuid:X", 40.0, 10.0); + assert_eq!(start(&alike.replace("urn:uuid:X", "urn:uuid:Y"), &by_id), Some(Coord::new(10.0, 50.0))); + // One not in force is no other of an alike identifier. + let past = + two(40.0).replace("2025-01-01T00:00:00Z", "2030-01-01T00:00:00Z").replacen("2030-01-01T00:00:00Z", "2025-01-01T00:00:00Z", 1); + assert_eq!(start(&past, &by_id), None); + assert_eq!(start(&past, &by_id.replace("urn:uuid:X", "X")), Some(Coord::new(10.0, 50.0))); + // An identifier that looks like a gml:id isn't one. + let odd = named_at("DesignatedPoint", "A", 50.0, 10.0).replace(r#"gml:id="f""#, r#"gml:id="p""#) + + &named_at("DesignatedPoint", "#p", 40.0, 10.0); + assert_eq!(start(&odd, &by_gid), Some(Coord::new(10.0, 50.0))); +} + +#[test] +fn a_ring_member_that_names_nothing_isnt_a_missing_border() { + let area = r#""#; + let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), area)]); + let notes = said(&read("t.xml", &message(&f), &at("2026-01-15")).unwrap()); + assert!(!notes.iter().any(|m| m.contains("border is given by reference")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("1 ring or surface patch was left out")), "{notes:?}"); } #[test] From 9f17b61c5f9d2470abe2de1d79970b6838020607 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:49:38 -0600 Subject: [PATCH 53/61] fix(data): AIXM route ends by any feature's gml:id; borders by XPath; empty ring members spend nothing --- crates/data/src/aixm.rs | 23 ++++++++++++++------- crates/data/src/aixm/tests.rs | 39 +++++++++++++++++++++++++++-------- 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 51a4f709b9..0a4df634b4 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -771,8 +771,7 @@ struct Shapes { border_names: HashMap>, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, - /// Where each feature a route segment's end can name ([`POINT_KINDS`]) is at the date, if - /// anywhere. + /// Where each feature a route segment's end can name is at the date, if anywhere. points: Vec>, /// Which of them a name names (`None`, more than one). point_names: HashMap>, @@ -1181,7 +1180,12 @@ impl Shapes { "Ring" => { // Its members: curves written out, and borders given by reference, which are cut // once the points either side of them are known. - // A border not in the file leaves the ring undrawn, before work is spent on it. + // A member that gives nothing, or a border not in the file, leaves the ring undrawn + // before work is spent on it. + let named = |m: &Node| m.attribute((XLINK, "href")).is_some_and(|h| !h.trim().is_empty()); + if elements(r).filter(|c| local(c) == "curveMember").any(|m| elements(m).next().is_none() && !named(&m)) { + return None; + } let missing = |m: &Node| { elements(*m).next().is_none() && m.attribute((XLINK, "href")).is_some_and(|h| self.border_named(h).is_none()) }; @@ -1386,7 +1390,9 @@ impl Shapes { fn border_named(&self, href: &str) -> Option { let h = href.trim(); let by = |name: &str| self.border_names.get(name).copied(); - let named = if h.starts_with('#') { + let named = if h.contains("@gml:id") { + by(&format!("#{}", reference(h))) + } else if h.starts_with('#') { by(h) } else { by(&format!("id:{h}")).or_else(|| by(&format!("uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)))) @@ -1402,7 +1408,8 @@ impl Shapes { self.points.push(None); let id = f.id.trim(); let bare = id.strip_prefix("urn:uuid:").unwrap_or(id); - let ids = [f.kind.as_str(), "*"].into_iter().flat_map(|k| [format!("{k}\u{1}id:{id}"), format!("{k}\u{1}uuid:{bare}")]); + let kinds = if POINT_KINDS.iter().any(|(_, k)| *k == f.kind) { vec![f.kind.as_str(), "*"] } else { Vec::new() }; + let ids = kinds.into_iter().flat_map(|k| [format!("{k}\u{1}id:{id}"), format!("{k}\u{1}uuid:{bare}")]); for name in f.gml_ids.iter().map(|g| format!("#{g}")).chain(ids) { self.point_names.entry(name).and_modify(|k| *k = k.filter(|k| *k == n)).or_insert(Some(n)); } @@ -2497,11 +2504,13 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize shapes.add_border(&f.id, f.gml_ids.iter().map(String::as_str), Vec::new()); } } - // And those of the points route segments name, in a file that has any. + // And those of the points route segments name, in a file that has any: any feature by its + // gml:id, and one of a kind their ends can name by its identifier. let mut point_of: HashMap = HashMap::new(); if features.values().any(|f| f.kind == "RouteSegment") { for key in &order { - if let Some(f) = features.get(key).filter(|f| POINT_KINDS.iter().any(|(_, k)| *k == f.kind)) { + crate::progress::check()?; + if let Some(f) = features.get(key).filter(|f| f.kind != "RouteSegment") { point_of.insert(key.clone(), shapes.points.len()); shapes.add_point(f); } diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 4fbe612c5a..0b9ee5c5d9 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2144,7 +2144,9 @@ fn borders_of_alike_identifiers_are_told_apart_by_their_gml_ids() { (lats, said(&out)) }; // Each by its own gml:ids, and by its identifier as it is written. - for (name, lat) in [("#b1", 50), ("#c1", 50), ("urn:uuid:X", 50), ("#b2", 40), ("#c2", 40), ("X", 40)] { + for (name, lat) in + [("#b1", 50), ("#c1", 50), ("urn:uuid:X", 50), ("#//aixm:GeoBorder[@gml:id='b1']", 50), ("#b2", 40), ("#c2", 40), ("X", 40)] + { let (lats, _) = drawn(name, &members); let lats = lats.unwrap_or_else(|| panic!("{name} not drawn")); assert!(lats.contains(&lat) && !lats.contains(&(90 - lat)), "{name}: {lats:?}"); @@ -2233,9 +2235,16 @@ fn a_route_end_named_as_two_points_are_is_neither() { }; assert_eq!(start(&two(40.0), &by_id), Some(Coord::new(10.0, 40.0))); assert_eq!(start(&two(40.0), &by_id.replace("urn:uuid:X", "X")), Some(Coord::new(10.0, 50.0))); - // Two with neither written so: neither. - let alike = named_at("DesignatedPoint", "X", 50.0, 10.0) + &named_at("DesignatedPoint", "urn:uuid:X", 40.0, 10.0); - assert_eq!(start(&alike.replace("urn:uuid:X", "urn:uuid:Y"), &by_id), Some(Coord::new(10.0, 50.0))); + // One written without its prefix is found with it. + assert_eq!(start(&named_at("DesignatedPoint", "X", 50.0, 10.0), &by_id), Some(Coord::new(10.0, 50.0))); + // A choice of no known kind naming an identifier two kinds share: neither. + let kinds = named_at("DesignatedPoint", "X", 50.0, 10.0) + &named_at("Navaid", "X", 40.0, 10.0); + let unknown = by_id.replace("pointChoice_fixDesignatedPoint xlink:href=\"urn:uuid:X", "pointChoice_other xlink:href=\"urn:uuid:X"); + assert_eq!(start(&kinds, &unknown), None); + assert_eq!(start(&kinds, &by_id), Some(Coord::new(10.0, 50.0))); + // Any feature with a position, by its gml:id. + let vor = named_at("VOR", "V", 50.0, 10.0).replace(r#"gml:id="f""#, r#"gml:id="p""#); + assert_eq!(start(&vor, &by_gid), Some(Coord::new(10.0, 50.0))); // One not in force is no other of an alike identifier. let past = two(40.0).replace("2025-01-01T00:00:00Z", "2030-01-01T00:00:00Z").replacen("2030-01-01T00:00:00Z", "2025-01-01T00:00:00Z", 1); @@ -2249,11 +2258,23 @@ fn a_route_end_named_as_two_points_are_is_neither() { #[test] fn a_ring_member_that_names_nothing_isnt_a_missing_border() { - let area = r#""#; - let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), area)]); - let notes = said(&read("t.xml", &message(&f), &at("2026-01-15")).unwrap()); - assert!(!notes.iter().any(|m| m.contains("border is given by reference")), "{notes:?}"); - assert!(notes.iter().any(|m| m.contains("1 ring or surface patch was left out")), "{notes:?}"); + for member in ["", r#""#] { + let area = format!( + r#"{member}"# + ); + let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &area)]); + let notes = said(&read("t.xml", &message(&f), &at("2026-01-15")).unwrap()); + assert!(!notes.iter().any(|m| m.contains("border is given by reference")), "{notes:?}"); + assert!(notes.iter().any(|m| m.contains("1 ring or surface patch was left out")), "{notes:?}"); + // And spends nothing. + let doc = format!( + r#"50 1010{member}"# + ); + let doc = roxmltree::Document::parse(&doc).unwrap(); + let mut shapes = Shapes { budget: 1000, ..Shapes::default() }; + assert!(shapes.ring(doc.root_element().first_element_child().unwrap(), &mut ShapeNotes::default()).is_none()); + assert_eq!(shapes.budget, 1000); + } } #[test] From faddd13be565cc4dd53b15e27aeed25b2bdb8476 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:57:01 -0600 Subject: [PATCH 54/61] fix(data): AIXM references into another document name nothing of this one; a system's name isn't copied for each shape --- crates/data/src/aixm.rs | 14 ++++++++------ crates/data/src/aixm/tests.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 0a4df634b4..7f76747771 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -1390,7 +1390,8 @@ impl Shapes { fn border_named(&self, href: &str) -> Option { let h = href.trim(); let by = |name: &str| self.border_names.get(name).copied(); - let named = if h.contains("@gml:id") { + // A link into another document (`file.xml#…`) names nothing of this one. + let named = if h.starts_with('#') && h.contains("@gml:id") { by(&format!("#{}", reference(h))) } else if h.starts_with('#') { by(h) @@ -1511,7 +1512,7 @@ impl Shapes { /// route segment's ends). The points it adds are paid for all the same, so reading again can't /// add points past the allowance. fn quietly(&mut self, g: Node) -> Option { - let kept = (self.assumed_system, self.other_count, self.as_wgs84_count, self.other_system.clone(), self.as_wgs84.clone()); + let kept = (self.assumed_system, self.other_count, self.as_wgs84_count, self.other_system.take(), self.as_wgs84.take()); let shape = self.shape(g, &mut ShapeNotes::default()); (self.assumed_system, self.other_count, self.as_wgs84_count, self.other_system, self.as_wgs84) = kept; shape @@ -2739,13 +2740,14 @@ fn segment_end<'a, 'i>(props: &[Node<'a, 'i>], name: &str, shapes: &Shapes) -> O /// Where the point a route end's choice links to is: by its gml:id for a local link; else of the /// kind the choice names, or (a choice of no known kind) any point of that identifier. fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { - let target = reference(href); + let h = href.trim(); let by = |name: String| shapes.point_names.get(&name).copied(); - let named = if href.trim().starts_with('#') || href.contains("@gml:id") { - by(format!("#{target}")) + // A link into another document (`file.xml#…`) names nothing of this one. + let named = if h.starts_with('#') { + by(format!("#{}", reference(h))) } else { let k = point_kind(local(&choice)).unwrap_or("*"); - by(format!("{k}\u{1}id:{}", href.trim())).or_else(|| by(format!("{k}\u{1}uuid:{target}"))) + by(format!("{k}\u{1}id:{h}")).or_else(|| by(format!("{k}\u{1}uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)))) }; named.flatten().and_then(|n| shapes.points.get(n).copied().flatten()) } diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 0b9ee5c5d9..1ef4e6c06a 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2163,6 +2163,10 @@ fn borders_of_alike_identifiers_are_told_apart_by_their_gml_ids() { assert_eq!(lats, None, "{name}"); assert!(notes.iter().any(|m| m.contains("not in force then")), "{notes:?}"); } + // Nor one of another document. + for name in ["other.xml#//aixm:GeoBorder[@gml:id='b1']", "other.xml#b1"] { + assert_eq!(drawn(name, &members).0, None, "{name}"); + } assert!(drawn("X", &past).0.is_some_and(|l| l.contains(&40))); let odd = members.clone() + &border("#b1", "b3", "c3", 40.0); assert!(drawn("#b1", &odd).0.is_some_and(|l| l.contains(&50))); @@ -2242,6 +2246,11 @@ fn a_route_end_named_as_two_points_are_is_neither() { let unknown = by_id.replace("pointChoice_fixDesignatedPoint xlink:href=\"urn:uuid:X", "pointChoice_other xlink:href=\"urn:uuid:X"); assert_eq!(start(&kinds, &unknown), None); assert_eq!(start(&kinds, &by_id), Some(Coord::new(10.0, 50.0))); + // One of another document is none of this one's; an XPath into this one is. + let here = named_at("DesignatedPoint", "X", 50.0, 10.0).replace(r#"gml:id="f""#, r#"gml:id="p""#); + let xpath = "#/m/aixm:DesignatedPoint[@gml:id='p']"; + assert_eq!(start(&here, &by_gid.replace("#p", xpath)), Some(Coord::new(10.0, 50.0))); + assert_eq!(start(&here, &by_gid.replace("#p", &format!("other.xml{xpath}"))), None); // Any feature with a position, by its gml:id. let vor = named_at("VOR", "V", 50.0, 10.0).replace(r#"gml:id="f""#, r#"gml:id="p""#); assert_eq!(start(&vor, &by_gid), Some(Coord::new(10.0, 50.0))); From 584a260b012543c75d9ecb98ec7faa1f8f2d11d2 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:49:52 -0600 Subject: [PATCH 55/61] fix(data): AIXM UUIDs matched in either case; a border's curve ids are its own at any date; the guide on arc limits --- crates/data/src/aixm.rs | 47 ++++++++++++++++++--------------- crates/data/src/aixm/tests.rs | 42 ++++++++++++++++++++++++----- docs/user-guide/data-formats.md | 2 +- 3 files changed, 62 insertions(+), 29 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 7f76747771..62b7f42c45 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -18,8 +18,8 @@ //! Geometry is the GML 3.2 the AIXM profile allows (OGC 12-028r1): points, curves of //! `GeodesicString`, `Geodesic`, `LineStringSegment`, `Arc`, `ArcString`, `Circle`, //! `ArcByCenterPoint` and `CircleByCenterPoint` segments, and surfaces of polygon patches. Arcs are -//! drawn as points along them on the WGS 84 ellipsoid, within a meter of the curve (coarser, and -//! said, once the points the file's size allows run out); a geodesic edge +//! drawn as points along them on the WGS 84 ellipsoid, to within a meter of the curve (coarser, and +//! said, past 3,600 points on one or the points the file's size allows); a geodesic edge //! longer than 10 km is drawn as points along the geodesic. `ArcByCenterPoint` angles follow the //! AIXM coding guidance: in a latitude-first system (`urn:ogc:def:crs:EPSG::4326`) bearings //! clockwise from true north, the arc running from the start angle to the end angle (clockwise when @@ -399,8 +399,8 @@ struct Feature { /// Its identifier (`gml:identifier`, else its `gml:id`). id: String, kind: String, - /// Its own `gml:id`s, one for each member that gives it: what a local link (`#id`) or the FAA's - /// XPath names it by. + /// Its own `gml:id`s, one for each member that gives it (and a GeoBorder's curves'): what a local + /// link (`#id`) or the FAA's XPath names it by. gml_ids: HashSet, slices: Vec, } @@ -1375,17 +1375,12 @@ impl Shapes { let n = self.borders.len(); self.borders.push(line); let id = id.trim(); - let names = [format!("id:{id}"), format!("uuid:{}", id.strip_prefix("urn:uuid:").unwrap_or(id))]; + let names = [format!("id:{id}"), format!("uuid:{}", bare_id(id))]; for name in names.into_iter().chain(gids.into_iter().map(|g| format!("#{}", g.trim()))) { - self.name_border(n, name); + self.border_names.entry(name).and_modify(|k| *k = k.filter(|k| *k == n)).or_insert(Some(n)); } } - /// Gives border `n` one more name. - fn name_border(&mut self, n: usize, name: String) { - self.border_names.entry(name).and_modify(|k| *k = k.filter(|k| *k == n)).or_insert(Some(n)); - } - /// The border a reference names: by a `gml:id` (`#id`), or by its identifier, as written first. fn border_named(&self, href: &str) -> Option { let h = href.trim(); @@ -1396,7 +1391,7 @@ impl Shapes { } else if h.starts_with('#') { by(h) } else { - by(&format!("id:{h}")).or_else(|| by(&format!("uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)))) + by(&format!("id:{h}")).or_else(|| by(&format!("uuid:{}", bare_id(h)))) }; named.flatten().filter(|n| self.borders.get(*n).is_some_and(|l| !l.is_empty())) } @@ -1408,7 +1403,7 @@ impl Shapes { let n = self.points.len(); self.points.push(None); let id = f.id.trim(); - let bare = id.strip_prefix("urn:uuid:").unwrap_or(id); + let bare = bare_id(id); let kinds = if POINT_KINDS.iter().any(|(_, k)| *k == f.kind) { vec![f.kind.as_str(), "*"] } else { Vec::new() }; let ids = kinds.into_iter().flat_map(|k| [format!("{k}\u{1}id:{id}"), format!("{k}\u{1}uuid:{bare}")]); for name in f.gml_ids.iter().map(|g| format!("#{g}")).chain(ids) { @@ -2457,6 +2452,11 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize Feature { id: id.clone(), kind: local(&f).to_string(), gml_ids: HashSet::new(), slices: Vec::new() } }); entry.gml_ids.extend(f.attribute((GML, "id")).map(|g| g.trim().to_string())); + // A GeoBorder is named by its curve's too, at any date. + if local(&f) == "GeoBorder" { + let curves = slices_of(f).into_iter().flat_map(elements).filter(|p| local(p) == "border").filter_map(shape_in); + entry.gml_ids.extend(curves.filter_map(|g| g.attribute((GML, "id"))).map(|g| g.trim().to_string())); + } entry.slices.extend(slices); } } @@ -2497,7 +2497,7 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize } order.sort_by_key(rank); // Every GeoBorder's identifiers and gml:ids first, in force or not: a reference to one names it - // and no other (its curve's gml:id is known once it is read). + // and no other. let mut border_of: HashMap = HashMap::new(); for key in &order { if let Some(f) = features.get(key).filter(|f| f.kind == "GeoBorder") { @@ -2624,13 +2624,9 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize if let Some(&n) = border_of.get(key) && let Some(g) = props.iter().filter(|p| local(p) == "border").find_map(|p| shape_in(*p)) && let Some(Geometry::Line(parts)) = shapes.quietly(g) + && let Some(line) = shapes.borders.get_mut(n) { - if let Some(gid) = g.attribute((GML, "id")) { - shapes.name_border(n, format!("#{}", gid.trim())); - } - if let Some(line) = shapes.borders.get_mut(n) { - *line = parts.concat(); - } + *line = parts.concat(); } // Where a point feature is, for route segments that name it. if let Some(&n) = point_of.get(key) @@ -2737,6 +2733,15 @@ fn segment_end<'a, 'i>(props: &[Node<'a, 'i>], name: &str, shapes: &Shapes) -> O } } +/// An identifier without `urn:uuid:`, and a UUID in lower case (its hexadecimal digits are the same +/// in either, RFC 4122 section 3). +fn bare_id(id: &str) -> std::borrow::Cow<'_, str> { + let id = id.strip_prefix("urn:uuid:").unwrap_or(id); + let uuid = id.len() == 36 + && id.bytes().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { b == b'-' } else { b.is_ascii_hexdigit() }); + if uuid { id.to_ascii_lowercase().into() } else { id.into() } +} + /// Where the point a route end's choice links to is: by its gml:id for a local link; else of the /// kind the choice names, or (a choice of no known kind) any point of that identifier. fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { @@ -2747,7 +2752,7 @@ fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { by(format!("#{}", reference(h))) } else { let k = point_kind(local(&choice)).unwrap_or("*"); - by(format!("{k}\u{1}id:{h}")).or_else(|| by(format!("{k}\u{1}uuid:{}", h.strip_prefix("urn:uuid:").unwrap_or(h)))) + by(format!("{k}\u{1}id:{h}")).or_else(|| by(format!("{k}\u{1}uuid:{}", bare_id(h)))) }; named.flatten().and_then(|n| shapes.points.get(n).copied().flatten()) } diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 1ef4e6c06a..33a0ccc7d1 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2010,6 +2010,14 @@ fn a_change_given_a_period_is_withheld_and_a_snapshot_is_read_at_its_start_and_s let (got, notes) = run(&[slice("DesignatedPoint", "SNAPSHOT", 1, 0, &valid, &named_point("SNAP"))], "2026-01-15"); assert!(got.len() == 2 && said(¬es) && !notes.iter().any(|m| m.contains("read as open")), "{got:?} {notes:?}"); } + // Its instant is its start, as one given that instant. + let from = |s: String| { + let out = read("t.xml", &message(&point("a", &[s])), &at("2026-01-15")).unwrap(); + value(layer(&out, "t DesignatedPoint"), 0, "validFrom") + }; + let given = from(snapshot_at("2026-01-01T00:00:00Z", "SNAP")); + assert_ne!(given, Value::Null); + assert_eq!(from(slice("DesignatedPoint", "SNAPSHOT", 1, 0, &valid, &named_point("SNAP"))), given); let (got, notes) = run(&[slice("DesignatedPoint", "SNAPSHOT", 1, 0, &valid, &named_point("SNAP"))], "2026-01-15"); assert!(got.len() == 2 && said(¬es), "{got:?} {notes:?}"); assert!(!said(&run(&[snapshot_at("2026-01-01T00:00:00Z", "SNAP")], "2026-01-15").1)); @@ -2077,20 +2085,26 @@ fn rows_past_the_tables_memory_are_left_out_and_said() { #[test] fn a_border_is_followed_by_the_gml_id_of_any_of_its_members() { - let border = |gid: &str, seq: u32, from: &str, to: Option<&str>| { - let b = r#"50 9 50 10 51 10"#; - feature("GeoBorder", "line", &[slice("GeoBorder", "BASELINE", seq, 0, &period(from, to), b)]) + // The past line goes by 50.2, the one in force by 50.7. + let border = |gid: &str, seq: u32, from: &str, to: Option<&str>, mid: f64| { + let b = format!( + r#"50 9 {mid} 10 51 10"# + ); + feature("GeoBorder", "line", &[slice("GeoBorder", "BASELINE", seq, 0, &period(from, to), &b)]) .replace(r#"gml:id="f""#, &format!(r#"gml:id="{gid}""#)) }; - let members = - border("b-old", 1, "2020-01-01T00:00:00Z", Some("2025-01-01T00:00:00Z")) + &border("b-new", 2, "2025-01-01T00:00:00Z", None); - for id in ["b-old", "b-new"] { + let members = border("b-old", 1, "2020-01-01T00:00:00Z", Some("2025-01-01T00:00:00Z"), 50.2) + + &border("b-new", 2, "2025-01-01T00:00:00Z", None, 50.7); + for id in ["b-old", "b-new", "c-b-old", "c-b-new"] { let area = format!( r##"51 10 51 9 50 9"## ); let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &area)]); let out = read("t.xml", &message(&(members.clone() + &f)), &at("2026-01-15")).unwrap(); - assert!(layer(&out, "t WorkArea").features[0].geometry.is_some(), "{id}: {:?}", said(&out)); + let g = layer(&out, "t WorkArea").features[0].geometry.as_ref(); + let r = ring(g.unwrap_or_else(|| panic!("{id}: {:?}", said(&out)))); + let by = |lat: f64| r.iter().any(|c| (c.x - 10.0).abs() < 1e-9 && (c.y - lat).abs() < 1e-9); + assert!(by(50.7) && !by(50.2), "{id}: {r:?}"); } } @@ -2156,6 +2170,16 @@ fn borders_of_alike_identifiers_are_told_apart_by_their_gml_ids() { let (lats, notes) = drawn("#c1", &shared); assert_eq!(lats, None); assert!(notes.iter().any(|m| m.contains("has a name others share")), "{notes:?}"); + // Nor when one of the two isn't in force. + let later = shared.replacen("2025-01-01T00:00:00Z", "2030-01-01T00:00:00Z", 1); + assert_eq!(drawn("#c1", &later).0, None); + // A UUID is the same in either case; another identifier isn't. + let uuid = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; + let one = border(uuid, "u", "cu", 50.0) + &border("Abc", "a", "ca", 40.0); + for name in [uuid.to_string(), format!("urn:uuid:{}", uuid.to_uppercase())] { + assert!(drawn(&name, &one).0.is_some_and(|l| l.contains(&50)), "{name}"); + } + assert_eq!(drawn("ABC", &one).0, None); // One not in force is no other: not drawn along the one whose identifier is alike. let past = members.replacen("2025-01-01T00:00:00Z", "2030-01-01T00:00:00Z", 1); for name in ["urn:uuid:X", "#b1"] { @@ -2246,6 +2270,10 @@ fn a_route_end_named_as_two_points_are_is_neither() { let unknown = by_id.replace("pointChoice_fixDesignatedPoint xlink:href=\"urn:uuid:X", "pointChoice_other xlink:href=\"urn:uuid:X"); assert_eq!(start(&kinds, &unknown), None); assert_eq!(start(&kinds, &by_id), Some(Coord::new(10.0, 50.0))); + // A UUID is the same in either case. + let uuid = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; + let upper = by_id.replace("urn:uuid:X", &format!("urn:uuid:{}", uuid.to_uppercase())); + assert_eq!(start(&named_at("DesignatedPoint", uuid, 50.0, 10.0), &upper), Some(Coord::new(10.0, 50.0))); // One of another document is none of this one's; an XPath into this one is. let here = named_at("DesignatedPoint", "X", 50.0, 10.0).replace(r#"gml:id="f""#, r#"gml:id="p""#); let xpath = "#/m/aixm:DesignatedPoint[@gml:id='p']"; diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 355b629533..d5542d8976 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read (or ends before it begins) are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, within a meter (coarser, and said, past the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read (or ends before it begins) are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, to within a meter (coarser, and said, past 3,600 points on one or the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From d96b4ed74003a652f9a74bd3d08808971aed9550 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:56:22 -0600 Subject: [PATCH 56/61] fix(data): AIXM features are one however their UUID is written; a past curve's name isn't the border's line in force --- crates/data/src/aixm.rs | 76 +++++++++++++++++++++++++---------- crates/data/src/aixm/tests.rs | 44 +++++++++++++++++++- 2 files changed, 97 insertions(+), 23 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 62b7f42c45..fb6e3a9bbe 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -399,9 +399,11 @@ struct Feature { /// Its identifier (`gml:identifier`, else its `gml:id`). id: String, kind: String, - /// Its own `gml:id`s, one for each member that gives it (and a GeoBorder's curves'): what a local - /// link (`#id`) or the FAA's XPath names it by. + /// Its own `gml:id`s, one for each member that gives it: what a local link (`#id`) or the FAA's + /// XPath names it by. gml_ids: HashSet, + /// A GeoBorder's curves' `gml:id`s, at every date. + curve_ids: HashSet, slices: Vec, } @@ -769,6 +771,8 @@ struct Shapes { /// Which border a name names (`None`, more than one): its identifier, its curve's `gml:id`, and /// its members'. A reference holds the number, which no identifier's length makes larger. border_names: HashMap>, + /// The names that are curves': whether each is its border's line at the date. + border_curves: HashMap, /// Steps of looking along borders still allowed ([`Shapes::scan`]). scan_left: usize, /// Where each feature a route segment's end can name is at the date, if anywhere. @@ -1368,7 +1372,7 @@ impl Shapes { Ok((part, far)) } - /// Keeps a border under its names: its identifier as written, and without `urn:uuid:`, and its + /// Keeps a border under its names: its identifier as written, and bare ([`bare_id`]), and its /// `gml:id`s. A name two borders have is neither's, and one with no `line` (not in force, or that /// can't be read) keeps its names from another's. fn add_border<'a>(&mut self, id: &str, gids: impl IntoIterator, line: Vec) { @@ -1381,15 +1385,29 @@ impl Shapes { } } + /// Keeps the names of the curves of the border last added, at every date, from other borders: + /// one is followed by its curve's name only at the date that curve is its line. + fn reserve_curves<'a>(&mut self, ids: impl IntoIterator) { + let Some(n) = self.borders.len().checked_sub(1) else { return }; + for id in ids { + let name = format!("#{}", id.trim()); + // A curve and its feature of one name are one border either way. + let known = self.border_names.entry(name.clone()).and_modify(|k| *k = k.filter(|k| *k == n)); + if let std::collections::hash_map::Entry::Vacant(e) = known { + e.insert(Some(n)); + self.border_curves.insert(name, false); + } + } + } + /// The border a reference names: by a `gml:id` (`#id`), or by its identifier, as written first. fn border_named(&self, href: &str) -> Option { let h = href.trim(); let by = |name: &str| self.border_names.get(name).copied(); // A link into another document (`file.xml#…`) names nothing of this one. - let named = if h.starts_with('#') && h.contains("@gml:id") { - by(&format!("#{}", reference(h))) - } else if h.starts_with('#') { - by(h) + let named = if h.starts_with('#') { + let name = if h.contains("@gml:id") { format!("#{}", reference(h)) } else { h.to_string() }; + by(&name).filter(|_| self.border_curves.get(&name).copied().unwrap_or(true)) } else { by(&format!("id:{h}")).or_else(|| by(&format!("uuid:{}", bare_id(h)))) }; @@ -1397,7 +1415,7 @@ impl Shapes { } /// Keeps a point feature under its names, its place not known yet: its `gml:id`s, and its - /// identifier as written and without `urn:uuid:`, of its kind and of any. A name two have is + /// identifier as written and bare ([`bare_id`]), of its kind and of any. A name two have is /// neither's. fn add_point(&mut self, f: &Feature) { let n = self.points.len(); @@ -2445,17 +2463,24 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize }; slices.extend(slice_of(sl, range, scope, &mut trouble)); } - // A feature is its kind and identifier: two kinds sharing one aren't put together. - let key = format!("{}\u{1}{id}", local(&f)); + // A feature is its kind and identifier (a UUID however it is written): two kinds sharing + // one aren't put together. + let bare = bare_id(&id); + let key = format!("{}\u{1}{}", local(&f), if is_uuid(&bare) { &*bare } else { id.as_str() }); let entry = features.entry(key.clone()).or_insert_with(|| { order.push(key.clone()); - Feature { id: id.clone(), kind: local(&f).to_string(), gml_ids: HashSet::new(), slices: Vec::new() } + Feature { + id: id.clone(), + kind: local(&f).to_string(), + gml_ids: HashSet::new(), + curve_ids: HashSet::new(), + slices: Vec::new(), + } }); entry.gml_ids.extend(f.attribute((GML, "id")).map(|g| g.trim().to_string())); - // A GeoBorder is named by its curve's too, at any date. if local(&f) == "GeoBorder" { let curves = slices_of(f).into_iter().flat_map(elements).filter(|p| local(p) == "border").filter_map(shape_in); - entry.gml_ids.extend(curves.filter_map(|g| g.attribute((GML, "id"))).map(|g| g.trim().to_string())); + entry.curve_ids.extend(curves.filter_map(|g| g.attribute((GML, "id"))).map(|g| g.trim().to_string())); } entry.slices.extend(slices); } @@ -2503,6 +2528,7 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize if let Some(f) = features.get(key).filter(|f| f.kind == "GeoBorder") { border_of.insert(key.clone(), shapes.borders.len()); shapes.add_border(&f.id, f.gml_ids.iter().map(String::as_str), Vec::new()); + shapes.reserve_curves(f.curve_ids.iter().map(String::as_str)); } } // And those of the points route segments name, in a file that has any: any feature by its @@ -2619,14 +2645,16 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize None => row.null("validTo"), } let kind = feature.kind.as_str(); - // A GeoBorder's line, at the date, for the borders that follow it by reference: by its - // identifier, its curve's id and its members'. + // A GeoBorder's line, at the date, for the borders that follow it by reference. if let Some(&n) = border_of.get(key) && let Some(g) = props.iter().filter(|p| local(p) == "border").find_map(|p| shape_in(*p)) && let Some(Geometry::Line(parts)) = shapes.quietly(g) && let Some(line) = shapes.borders.get_mut(n) { *line = parts.concat(); + if let Some(drawn) = g.attribute((GML, "id")).and_then(|c| shapes.border_curves.get_mut(&format!("#{}", c.trim()))) { + *drawn = true; + } } // Where a point feature is, for route segments that name it. if let Some(&n) = point_of.get(key) @@ -2733,13 +2761,19 @@ fn segment_end<'a, 'i>(props: &[Node<'a, 'i>], name: &str, shapes: &Shapes) -> O } } -/// An identifier without `urn:uuid:`, and a UUID in lower case (its hexadecimal digits are the same -/// in either, RFC 4122 section 3). +/// An identifier without `urn:uuid:` (in either case, RFC 8141 section 3.1), and a UUID in lower case +/// (its hexadecimal digits are the same in either, RFC 4122 section 3). fn bare_id(id: &str) -> std::borrow::Cow<'_, str> { - let id = id.strip_prefix("urn:uuid:").unwrap_or(id); - let uuid = id.len() == 36 - && id.bytes().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { b == b'-' } else { b.is_ascii_hexdigit() }); - if uuid { id.to_ascii_lowercase().into() } else { id.into() } + let id = id.trim(); + let id = match id.split_at_checked("urn:uuid:".len()) { + Some((urn, rest)) if urn.eq_ignore_ascii_case("urn:uuid:") => rest, + _ => id, + }; + if is_uuid(id) { id.to_ascii_lowercase().into() } else { id.into() } +} + +fn is_uuid(id: &str) -> bool { + id.len() == 36 && id.bytes().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { b == b'-' } else { b.is_ascii_hexdigit() }) } /// Where the point a route end's choice links to is: by its gml:id for a local link; else of the diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 33a0ccc7d1..af49f702c2 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2095,13 +2095,19 @@ fn a_border_is_followed_by_the_gml_id_of_any_of_its_members() { }; let members = border("b-old", 1, "2020-01-01T00:00:00Z", Some("2025-01-01T00:00:00Z"), 50.2) + &border("b-new", 2, "2025-01-01T00:00:00Z", None, 50.7); - for id in ["b-old", "b-new", "c-b-old", "c-b-new"] { + // Its line then is the one in force, whichever member is named; a past line's own name isn't it. + for (id, drawn) in [("b-old", true), ("b-new", true), ("c-b-new", true), ("c-b-old", false)] { let area = format!( r##"51 10 51 9 50 9"## ); let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &area)]); let out = read("t.xml", &message(&(members.clone() + &f)), &at("2026-01-15")).unwrap(); let g = layer(&out, "t WorkArea").features[0].geometry.as_ref(); + assert_eq!(g.is_some(), drawn, "{id}"); + if !drawn { + assert!(said(&out).iter().any(|m| m.contains("not in force then")), "{:?}", said(&out)); + continue; + } let r = ring(g.unwrap_or_else(|| panic!("{id}: {:?}", said(&out)))); let by = |lat: f64| r.iter().any(|c| (c.x - 10.0).abs() < 1e-9 && (c.y - lat).abs() < 1e-9); assert!(by(50.7) && !by(50.2), "{id}: {r:?}"); @@ -2176,7 +2182,7 @@ fn borders_of_alike_identifiers_are_told_apart_by_their_gml_ids() { // A UUID is the same in either case; another identifier isn't. let uuid = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; let one = border(uuid, "u", "cu", 50.0) + &border("Abc", "a", "ca", 40.0); - for name in [uuid.to_string(), format!("urn:uuid:{}", uuid.to_uppercase())] { + for name in [uuid.to_string(), format!("urn:uuid:{}", uuid.to_uppercase()), format!("URN:UUID:{}", uuid.to_uppercase())] { assert!(drawn(&name, &one).0.is_some_and(|l| l.contains(&50)), "{name}"); } assert_eq!(drawn("ABC", &one).0, None); @@ -2274,6 +2280,21 @@ fn a_route_end_named_as_two_points_are_is_neither() { let uuid = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; let upper = by_id.replace("urn:uuid:X", &format!("urn:uuid:{}", uuid.to_uppercase())); assert_eq!(start(&named_at("DesignatedPoint", uuid, 50.0, 10.0), &upper), Some(Coord::new(10.0, 50.0))); + // A border's curve of the same gml:id as a point is no point. + let curve = feature( + "GeoBorder", + "line", + &[slice( + "GeoBorder", + "BASELINE", + 1, + 0, + &period("2025-01-01T00:00:00Z", None), + r#"50 9 50 10"#, + )], + ); + let p = named_at("DesignatedPoint", "X", 50.0, 10.0).replace(r#"gml:id="f""#, r#"gml:id="p""#); + assert_eq!(start(&(curve + &p), &by_gid), Some(Coord::new(10.0, 50.0))); // One of another document is none of this one's; an XPath into this one is. let here = named_at("DesignatedPoint", "X", 50.0, 10.0).replace(r#"gml:id="f""#, r#"gml:id="p""#); let xpath = "#/m/aixm:DesignatedPoint[@gml:id='p']"; @@ -2324,3 +2345,22 @@ fn a_lifetime_that_ends_before_it_begins_withholds_its_feature_and_says_so() { assert_eq!(got, [Value::Text("KEPT".into())]); assert!(notes.iter().any(|m| m.contains("1 feature left out: a time slice") && m.contains("ends before it begins")), "{notes:?}"); } + +#[test] +fn a_feature_whose_members_write_its_uuid_differently_is_one() { + let uuid = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; + let base = point(uuid, &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "OLD")]); + for other in [uuid.to_uppercase(), format!("urn:uuid:{uuid}"), format!("URN:UUID:{}", uuid.to_uppercase())] { + let perm = point(&other, &[change("PERMDELTA", 1, &instant("2025-06-01T00:00:00Z"), "NEW")]); + assert_eq!(names(&message(&(base.clone() + &perm)), "2026-01-15").0, [Value::Text("NEW".into())], "{other}"); + // And a route finds it. + let far = named_at("DesignatedPoint", "far", 50.0, 12.0); + let route = route_to("pointChoice_fixDesignatedPoint", uuid); + let out = read("t.xml", &message(&(base.clone() + &perm + &far + &route)), &at("2026-01-15")).unwrap(); + assert!(layer(&out, "t RouteSegment").features[0].geometry.is_some(), "{other}"); + } + // Identifiers that aren't UUIDs are as they are written. + let two = point("abc", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "A")]) + + &point("ABC", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "B")]); + assert_eq!(names(&message(&two), "2026-01-15").0.len(), 2); +} From 34443da8cf28578fa377d6fcd6dcbf6f4d95ace4 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:02:55 -0600 Subject: [PATCH 57/61] fix(data): AIXM UUIDs told apart only as UUIDs; the guide on border names --- crates/data/src/aixm.rs | 19 ++++++++++++------- crates/data/src/aixm/tests.rs | 23 +++++++++++++++++++---- docs/user-guide/data-formats.md | 2 +- 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index fb6e3a9bbe..97dd6c8e47 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -1,7 +1,8 @@ //! AIXM 5.1, 5.1.1 and 5.2: aeronautical information (airports, navaids, designated points, routes, //! airspace, obstacles…) in an `AIXMBasicMessage`, read into a layer per feature kind. //! -//! An AIXM feature is a series of time slices, each valid for a period. The reader builds each +//! A feature is its kind and identifier, a UUID being the same in either case, with `urn:uuid:` or +//! not. An AIXM feature is a series of time slices, each valid for a period. The reader builds each //! feature's state at one effective date (today unless one is given), following the AIXM //! Temporality Concept (EUROCONTROL/FAA, version 1.1, on the AIXM wiki): of the slices with the same //! interpretation and sequence number, the highest correction number holds; a slice whose @@ -1378,8 +1379,7 @@ impl Shapes { fn add_border<'a>(&mut self, id: &str, gids: impl IntoIterator, line: Vec) { let n = self.borders.len(); self.borders.push(line); - let id = id.trim(); - let names = [format!("id:{id}"), format!("uuid:{}", bare_id(id))]; + let names = [format!("id:{}", as_written(id)), format!("uuid:{}", bare_id(id))]; for name in names.into_iter().chain(gids.into_iter().map(|g| format!("#{}", g.trim()))) { self.border_names.entry(name).and_modify(|k| *k = k.filter(|k| *k == n)).or_insert(Some(n)); } @@ -1409,7 +1409,7 @@ impl Shapes { let name = if h.contains("@gml:id") { format!("#{}", reference(h)) } else { h.to_string() }; by(&name).filter(|_| self.border_curves.get(&name).copied().unwrap_or(true)) } else { - by(&format!("id:{h}")).or_else(|| by(&format!("uuid:{}", bare_id(h)))) + by(&format!("id:{}", as_written(h))).or_else(|| by(&format!("uuid:{}", bare_id(h)))) }; named.flatten().filter(|n| self.borders.get(*n).is_some_and(|l| !l.is_empty())) } @@ -1420,8 +1420,7 @@ impl Shapes { fn add_point(&mut self, f: &Feature) { let n = self.points.len(); self.points.push(None); - let id = f.id.trim(); - let bare = bare_id(id); + let (id, bare) = (as_written(&f.id), bare_id(&f.id)); let kinds = if POINT_KINDS.iter().any(|(_, k)| *k == f.kind) { vec![f.kind.as_str(), "*"] } else { Vec::new() }; let ids = kinds.into_iter().flat_map(|k| [format!("{k}\u{1}id:{id}"), format!("{k}\u{1}uuid:{bare}")]); for name in f.gml_ids.iter().map(|g| format!("#{g}")).chain(ids) { @@ -2772,6 +2771,12 @@ fn bare_id(id: &str) -> std::borrow::Cow<'_, str> { if is_uuid(id) { id.to_ascii_lowercase().into() } else { id.into() } } +/// An identifier as it is written; a UUID, which is the same however it is, bare. +fn as_written(id: &str) -> std::borrow::Cow<'_, str> { + let bare = bare_id(id); + if is_uuid(&bare) { bare } else { id.trim().into() } +} + fn is_uuid(id: &str) -> bool { id.len() == 36 && id.bytes().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { b == b'-' } else { b.is_ascii_hexdigit() }) } @@ -2786,7 +2791,7 @@ fn named_point(shapes: &Shapes, choice: Node, href: &str) -> Option { by(format!("#{}", reference(h))) } else { let k = point_kind(local(&choice)).unwrap_or("*"); - by(format!("{k}\u{1}id:{h}")).or_else(|| by(format!("{k}\u{1}uuid:{}", bare_id(h)))) + by(format!("{k}\u{1}id:{}", as_written(h))).or_else(|| by(format!("{k}\u{1}uuid:{}", bare_id(h)))) }; named.flatten().and_then(|n| shapes.points.get(n).copied().flatten()) } diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index af49f702c2..e64bf61a43 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2096,12 +2096,20 @@ fn a_border_is_followed_by_the_gml_id_of_any_of_its_members() { let members = border("b-old", 1, "2020-01-01T00:00:00Z", Some("2025-01-01T00:00:00Z"), 50.2) + &border("b-new", 2, "2025-01-01T00:00:00Z", None, 50.7); // Its line then is the one in force, whichever member is named; a past line's own name isn't it. - for (id, drawn) in [("b-old", true), ("b-new", true), ("c-b-new", true), ("c-b-old", false)] { + for (date, id, drawn) in [ + ("2026-01-15", "b-old", true), + ("2026-01-15", "b-new", true), + ("2026-01-15", "c-b-new", true), + ("2026-01-15", "c-b-old", false), + ("2022-01-15", "b-new", true), + ("2022-01-15", "c-b-old", true), + ("2022-01-15", "c-b-new", false), + ] { let area = format!( r##"51 10 51 9 50 9"## ); - let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &area)]); - let out = read("t.xml", &message(&(members.clone() + &f)), &at("2026-01-15")).unwrap(); + let f = feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2020-01-01T00:00:00Z", None), &area)]); + let out = read("t.xml", &message(&(members.clone() + &f)), &at(date)).unwrap(); let g = layer(&out, "t WorkArea").features[0].geometry.as_ref(); assert_eq!(g.is_some(), drawn, "{id}"); if !drawn { @@ -2110,7 +2118,8 @@ fn a_border_is_followed_by_the_gml_id_of_any_of_its_members() { } let r = ring(g.unwrap_or_else(|| panic!("{id}: {:?}", said(&out)))); let by = |lat: f64| r.iter().any(|c| (c.x - 10.0).abs() < 1e-9 && (c.y - lat).abs() < 1e-9); - assert!(by(50.7) && !by(50.2), "{id}: {r:?}"); + let now = date.starts_with("2026"); + assert!(by(50.7) == now && by(50.2) != now, "{date} {id}: {r:?}"); } } @@ -2300,6 +2309,12 @@ fn a_route_end_named_as_two_points_are_is_neither() { let xpath = "#/m/aixm:DesignatedPoint[@gml:id='p']"; assert_eq!(start(&here, &by_gid.replace("#p", xpath)), Some(Coord::new(10.0, 50.0))); assert_eq!(start(&here, &by_gid.replace("#p", &format!("other.xml{xpath}"))), None); + // Two kinds that write one UUID differently: a choice of no known kind is neither's. + let both = named_at("DesignatedPoint", &uuid.to_uppercase(), 50.0, 10.0) + &named_at("Navaid", uuid, 40.0, 10.0); + for name in [uuid.to_string(), uuid.to_uppercase(), format!("urn:uuid:{uuid}")] { + assert_eq!(start(&both, &unknown.replace("urn:uuid:X", &name)), None, "{name}"); + assert_eq!(start(&both, &by_id.replace("urn:uuid:X", &name)), Some(Coord::new(10.0, 50.0)), "{name}"); + } // Any feature with a position, by its gml:id. let vor = named_at("VOR", "V", 50.0, 10.0).replace(r#"gml:id="f""#, r#"gml:id="p""#); assert_eq!(start(&vor, &by_gid), Some(Coord::new(10.0, 50.0))); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index d5542d8976..60303fdf22 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read (or ends before it begins) are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, to within a meter (coarser, and said, past 3,600 points on one or the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said). A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read (or ends before it begins) are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, to within a meter (coarser, and said, past 3,600 points on one or the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said); one named by a curve that isn't the GeoBorder's on the date, or by a name two share, isn't followed, and that is said. A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From 82ea6c8723174527bd0b6538be8c765c590ae617 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:22:30 -0600 Subject: [PATCH 58/61] fix(data): AIXM holes across 180 degrees inside their exteriors; units numbered as their values; a slice past the limits withholds its feature; a zip's AIXM members charged to it; the Donlon sample is BSD-3-Clause --- ATTRIBUTION.md | 2 +- crates/data/src/aixm.rs | 39 ++++++++++++++++++++++++++++---- crates/data/src/aixm/tests.rs | 42 ++++++++++++++++++++++++++++++++++- crates/data/src/io.rs | 26 +++++++++++++--------- 4 files changed, 93 insertions(+), 16 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f72f439be1..af958aaa43 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -32,7 +32,7 @@ of use. | Script-only and fallback test fonts (`crates/render/testdata/test-script-only.otf`, `crates/render/testdata/test-fallback.otf`, `crates/render/testdata/test-latin-catalog.otf`) | The RustGIS project: original square outlines and script cmap variants ([generation](crates/render/testdata/README.md)) | Apache-2.0 | | JAXA Earth catalog test copy (`crates/tiles/tests/data/jaxa_catalog.v2.md`), read only by tests | JAXA: the [JAXA Earth API](https://data.earth.jaxa.jp/) dataset catalog ([catalog.v2.md](https://data.earth.jaxa.jp/app/mcp/catalog.v2.md)), copied on 2026-11-08 | JAXA's [terms of use](https://earth.jaxa.jp/en/data/policy/): free to use and redistribute, with credit to JAXA | | AIXM test message from DFS (`crates/data/tests/data/dfs-airspace-aixm.xml`), read only by tests | Three members of DFS Deutsche Flugsicherung GmbH's `ED_Airspace_ReferencedBorders_2026-10-29_2026-10-29_snapshot.xml` ([aip.dfs.de/datasets](https://aip.dfs.de/datasets/)): the GERMANY_NETHERLANDS GeoBorder and the MASKIRCHEN B AREA and BERLIN X airspaces, copied on 2026-11-23, the members unchanged and the message metadata left out | CC BY 4.0 | -| AIXM test message (`crates/data/tests/data/donlon-aixm.xml`), read only by tests | Nine members of the fictitious Donlon dataset's `Donlon_ALL_Baseline_ADM_upload.xml` ([aixm/Donlon_2025](https://github.com/aixm/Donlon_2025)), copyright (c) 2025 EUROCONTROL & FAA, copied on 2026-11-23 with the file's license notice; the members are unchanged but for trailing spaces removed from two comment lines | BSD-2-Clause | +| AIXM test message (`crates/data/tests/data/donlon-aixm.xml`), read only by tests | Nine members of the fictitious Donlon dataset's `Donlon_ALL_Baseline_ADM_upload.xml` ([aixm/Donlon_2025](https://github.com/aixm/Donlon_2025)), copyright (c) 2025 EUROCONTROL & FAA, copied on 2026-11-23 with the file's license notice; the members are unchanged but for trailing spaces removed from two comment lines | BSD-3-Clause | | CityGML test mesh (`crates/data/tests/data/rocking-chair.gml`), read only by tests | 97 faces of the rocking chair in OGC's CityGML 3.0 sample `Building_LOD3-EPSG25832.gml` ([CityGML-3.0Encodings](https://github.com/opengeospatial/CityGML-3.0Encodings/blob/master/Moved_to_CITYGML-3.0Encoding_CityGML/Examples/Examples-from-CityGML-2.0/building/CityGMLv3/Building_LOD3-EPSG25832.gml)), copyright (c) 2013 3DXScape, copied on 2026-11-12 and rewritten as a CityGML 2.0 object, coordinates unchanged | MIT | | Datum grid test files (`crates/data/tests/data/grids/us_noaa_conus.tif`, `us_noaa_ethpgn.tif`), read only by the datum grid tests | NOAA's NADCON and HARN grids as converted by [PROJ-data](https://github.com/OSGeo/PROJ-data) (`us_noaa`), copied unchanged from [cdn.proj.org](https://cdn.proj.org) | Public domain | | LERC GeoTIFF test files (`crates/data/tests/data/lerc/*.tif`), read only by the LERC tests | Written for the RustGIS project by `make_lerc.py` there with [GDAL](https://gdal.org) 3.9.3 through [rasterio](https://rasterio.readthedocs.io) 1.4.3, run only to write them; the values are made up | Apache-2.0 | diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 97dd6c8e47..7474d99a41 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -1497,9 +1497,15 @@ impl Shapes { // cover what the hole excludes. let mut rings = vec![outer]; let mut hole_lost = false; + let middle = |r: &[Coord]| r.iter().map(|c| c.x).sum::() / r.len().max(1) as f64; + let outer_middle = middle(&rings[0]); for b in elements(p).filter(|c| local(c) == "interior") { match self.ring(b, &mut pn) { - Some(r) => rings.push(r), + // Its longitudes in the exterior's run: a hole across 180° is where it is. + Some(r) => { + let turn = ((outer_middle - middle(&r)) / 360.0).round() * 360.0; + rings.push(if turn == 0.0 { r } else { r.into_iter().map(|c| Coord::new(c.x + turn, c.y)).collect() }); + } None => hole_lost = true, } } @@ -1919,6 +1925,12 @@ impl Row { } fn null(&mut self, key: &str) { + // Its name is paid for as a value would be, though nothing is lost past the limit. + let cost = key.len() + VALUE_OVERHEAD; + if self.named.contains(key) || self.limit.is_some_and(|l| self.bytes + cost > l) { + return; + } + self.bytes += cost; let _ = self.name(key, false); } @@ -2003,9 +2015,16 @@ impl Row { self.record_at(c, path, false, depth + 1); } else if let Some((last, _)) = path.last().cloned() { for (key, value) in leaf_values(c, &last) { + // A unit and the like are a step under the property, so they are numbered as it + // is (`limit_1_uom` beside `limit_1`). let mut at = path.clone(); - if let Some(step) = at.last_mut() { - step.0 = key; + match key.strip_prefix(last.as_str()).and_then(|q| q.strip_prefix('_')) { + Some(q) if !q.is_empty() => at.push((q.to_string(), 1)), + _ => { + if let Some(step) = at.last_mut() { + step.0 = key; + } + } } // Paid for first; given back when its path can't be kept. let cost = value.as_ref().map_or(0, String::len); @@ -2426,6 +2445,8 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize let mut wrap_left = text.len().saturating_mul(4).max(MIN_WRAP_BYTES); let prefix = "".len(); crate::progress::begin(index.members.len() * 2); + // Features with a slice the limits left unread: what they are then can't be known. + let mut withheld: HashSet = HashSet::new(); for (m, &(start, end)) in index.members.iter().enumerate() { crate::progress::step(1)?; let Some(member) = text.get(start..end) else { @@ -2450,6 +2471,7 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize for (fi, f) in features_of(doc.root_element()).into_iter().enumerate() { let id = identifier(f).unwrap_or_else(|| format!("#{m}.{fi}")); let mut slices = Vec::new(); + let mut cut = false; for sl in slices_of(f) { let r = sl.range(); let Some(range) = r.start.checked_sub(prefix).zip(r.end.checked_sub(prefix)).map(|(a, b)| (start + a, start + b)) else { @@ -2457,7 +2479,9 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize continue; }; let Some(scope) = scope_of(sl, text, start, prefix, &mut scopes, &mut scope_ids, &mut wrap_left) else { + // Its feature is left out: what it was then may be this slice. notes.past_limits += 1; + cut = true; continue; }; slices.extend(slice_of(sl, range, scope, &mut trouble)); @@ -2482,6 +2506,9 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize entry.curve_ids.extend(curves.filter_map(|g| g.attribute((GML, "id"))).map(|g| g.trim().to_string())); } entry.slices.extend(slices); + if cut { + withheld.insert(key.clone()); + } } } notes.unknown_interpretation = trouble.unknown; @@ -2547,6 +2574,10 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize for key in &order { crate::progress::step(1)?; let Some(feature) = features.get(key) else { continue }; + if withheld.contains(key) { + notes.incomplete += 1; + continue; + } layers.feature.clone_from(key); let id = &feature.id; if feature.slices.is_empty() { @@ -3289,7 +3320,7 @@ fn finish( notes.incomplete, "feature", "features", - "left out: a change to it in force then couldn't be read within the limits the file's size sets", + "left out: a time slice of it couldn't be read within the limits the file's size sets", ); say( &mut file, diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index e64bf61a43..4285b2f022 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -1,4 +1,4 @@ -//! Tests of the AIXM reader: the Donlon 2025 sample (BSD-2-Clause, EUROCONTROL & FAA) and small +//! Tests of the AIXM reader: the Donlon 2025 sample (BSD-3-Clause, EUROCONTROL & FAA) and small //! messages written here for each rule of the time slices, the arcs and hostile input. use super::*; @@ -171,6 +171,12 @@ fn the_vaardnor_circle_stays_within_a_meter_of_its_radius() { let d = meters_between(*c, center); assert!((d - 15.0 * 1852.0).abs() < 0.01, "{d}"); } + // And between them: each edge's middle within a meter of the circle. + for w in ring.windows(2) { + let (len, azimuth, _) = rustgis_geom::wgs84_inverse(w[0], w[1]); + let mid = rustgis_geom::wgs84_direct(w[0], azimuth, len / 2.0).0; + assert!((meters_between(mid, center) - 15.0 * 1852.0).abs() < 1.0, "{mid:?}"); + } } #[test] @@ -2379,3 +2385,37 @@ fn a_feature_whose_members_write_its_uuid_differently_is_one() { + &point("ABC", &[baseline(1, 0, "2025-01-01T00:00:00Z", None, "B")]); assert_eq!(names(&message(&two), "2026-01-15").0.len(), 2); } + +#[test] +fn a_unit_is_numbered_as_its_value_is() { + let rec = |limits: &str| { + let body = format!("{}{limits}", named_point("P")); + let out = read( + "t.xml", + &message(&point("p", &[slice("DesignatedPoint", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + let ds = layer(&out, "t DesignatedPoint"); + ds.fields.iter().map(|f| f.name.clone()).filter(|n| n.contains("limit")).collect::>() + }; + let two = rec(r#"100200"#); + assert!(two.contains(&"annotation_limit_1_uom".to_string()) && !two.iter().any(|n| n == "annotation_limit_uom"), "{two:?}"); + let one = rec(r#"100"#); + assert!(one.contains(&"annotation_limit_uom".to_string()), "{one:?}"); +} + +#[test] +fn a_hole_across_180_degrees_is_inside_its_exterior() { + let body = r#"-10 178 -10 -178 10 -178 10 178 -10 178-5 -179 -5 179 5 179 5 -179 -5 -179"#; + let out = read( + "t.xml", + &message(&feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), body)])), + &at("2026-01-15"), + ) + .unwrap(); + let Some(Geometry::Polygon(p)) = &layer(&out, "t WorkArea").features[0].geometry else { panic!() }; + let span = |r: &[Coord]| (r.iter().map(|c| c.x).fold(f64::MAX, f64::min), r.iter().map(|c| c.x).fold(f64::MIN, f64::max)); + let ((a, b), (c, d)) = (span(&p[0][0]), span(&p[0][1])); + assert!(a <= c && d <= b, "{:?} {:?}", p[0][0], p[0][1]); +} diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index f6c0b352da..65412709d4 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -4001,16 +4001,22 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge } else if is_aixm(leaf, &b) { // An AIXM message: all its layers, as it is today. It names its own system, so a // system given for the zip isn't used for it, and that is said. - crate::aixm::read(leaf, &b, &crate::aixm::Options::default()).map(|mut layers| { - if crs.is_some() - && let Some((_, report)) = layers.first_mut() - { - report - .messages - .push(format!("{leaf}: the coordinate system given isn't used for an AIXM message, which names its own")); - } - plain(layers) - }) + crate::aixm::read(leaf, &b, &crate::aixm::Options::default()) + .and_then(|layers| { + // Kept while the rest are read: charged to what the zip may hold. + charge_retained(layers.iter().map(|(d, _)| d), leaf, budget)?; + Ok(layers) + }) + .map(|mut layers| { + if crs.is_some() + && let Some((_, report)) = layers.first_mut() + { + report + .messages + .push(format!("{leaf}: the coordinate system given isn't used for an AIXM message, which names its own")); + } + plain(layers) + }) } else if is_delimited_name(leaf) { read_delimited_bytes_budget(leaf, &b, &CsvOptions { crs, ..Default::default() }, budget).map(|r| plain(vec![r])) } else if crate::sheets::is_sheet_name(leaf) { From 46b071b07d979ab7f1f0a63bc5f7244ff02862d9 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:22:45 -0600 Subject: [PATCH 59/61] fix(ui): List Tables leaves an AIXM message to Add Data, which lists it off the frame --- crates/engine/src/cmd/layer.rs | 2 +- crates/ui-egui/src/dialogs.rs | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index bb343f13b4..eebe483e7c 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2385,7 +2385,7 @@ fn read_ahead_whole(path: &str) -> bool { /// Whether Add Data reads `path` as an AIXM message: a `.gml` or `.xml` file whose root (in its /// first bytes, read here) is an `AIXMBasicMessage`. #[cfg(not(target_arch = "wasm32"))] -fn is_aixm_path(path: &str) -> bool { +pub fn is_aixm_path(path: &str) -> bool { use std::io::Read; let lower = path.to_ascii_lowercase(); if !(lower.ends_with(".gml") || lower.ends_with(".xml")) { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9d0f895cb4..590d53363e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2495,7 +2495,21 @@ fn gpkg_add_layer(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { }; #[cfg(target_arch = "wasm32")] let too_large = || false; - if list && too_large() { + // An AIXM message is read whole, its shapes too, to list it: not on the frame. Add Data lists + // it off the frame, with progress and Cancel. + #[cfg(not(target_arch = "wasm32"))] + let aixm = || rustgis_engine::cmd::layer::is_aixm_path(&path); + #[cfg(target_arch = "wasm32")] + let aixm = || false; + if list && aixm() { + app.dialogs.listed = None; + app.dialogs.list.clear(); + app.dialogs.c.clear(); + app.dialogs.info = None; + app.dialogs.error = Some( + tl!("List Tables doesn't read an AIXM message: add it with Add Data, which lists its layers as it reads them").to_string(), + ); + } else if list && too_large() { app.dialogs.listed = None; app.dialogs.list.clear(); app.dialogs.c.clear(); From 19010b9b65f55a21a96c7567e8a67e867449946e Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:06:20 -0600 Subject: [PATCH 60/61] fix: an AIXM read sized with memory::planned, refused past it with a way out; "at" refused for a GeoLibre download --- crates/data/src/aixm.rs | 47 ++++++++++++++++++++++++++------- crates/data/src/aixm/tests.rs | 10 ++++++- crates/engine/src/cmd/layer.rs | 4 +++ crates/engine/src/tests.rs | 9 +++++++ docs/user-guide/data-formats.md | 2 +- 5 files changed, 61 insertions(+), 11 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 7474d99a41..9e3b59c369 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -39,6 +39,9 @@ //! row per part. Runways, runway directions and routes, which have no geometry of their own, are //! tables; other kinds with nothing to draw are counted. //! +//! A read takes about twice the message's size in memory beside it; one past what the computer can +//! set aside then ([`crate::memory::planned`]) is refused before it is read, saying so. +//! //! The file is hostile: no DTD is read, members are parsed one at a time within the node and //! namespace limits every XML reader has, and the points arcs and geodesics add are bounded by the //! file's size. @@ -2392,12 +2395,22 @@ struct FileNotes { /// several), at the effective date `opts.at` (today when not given). Cancel is looked at between /// members; finding them first is one pass over the text without a look. pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result> { - read_within(file_name, bytes, opts, MIN_ROW_BYTES * 4) + // What the read may hold beside the file: what this computer can set aside now (#2431). + let planned = crate::memory::planned(MIN_PLANNED, usize::MAX, 1); + read_within(file_name, bytes, opts, MIN_ROW_BYTES * 4, planned) } +/// The least a read plans for, whatever the computer: a small message always reads. +const MIN_PLANNED: usize = 256 << 20; + +/// What a read holds beside the file, for each byte of it: its index, rows, paths and points, as +/// measured (about three times the file at peak, the file's own bytes included: 1.5 to 1.6 GB for a +/// 509 MB message). +const HELD_PER_BYTE: usize = 2; + /// [`read`], its tables of at most eight times the file's size, or `dense_floor` bytes when that is /// more. -fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize) -> Result> { +fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize, planned: usize) -> Result> { let max = crate::io::max_bytes(); if bytes.len() as u64 > max { return Err(DataError::Format(crate::io::file_size_error(file_name, max))); @@ -2408,6 +2421,17 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize Err(e) if e.error_len().is_none() => std::str::from_utf8(bytes.get(..e.valid_up_to()).unwrap_or_default()).unwrap_or_default(), Err(_) => return Err(DataError::Format(format!("{file_name} is not UTF-8 text"))), }; + // What it will hold, against what it may: past that it is refused, with a way out, rather than + // run out of memory partway. + let need = text.len().saturating_mul(HELD_PER_BYTE); + if need > planned { + let mib = |b: usize| (b >> 20).max(1); + return Err(DataError::Format(format!( + "{file_name}: reading this AIXM message takes about {} MiB beside the file, more than this computer can set aside now ({} MiB): close other projects or large layers, or read a smaller extract of it", + mib(need), + mib(planned) + ))); + } let text = text.trim_start_matches('\u{feff}'); let stem = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("AIXM").to_string(); let at = opts.at.filter(|t| t.is_finite()).unwrap_or_else(now_ms); @@ -2442,7 +2466,7 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize let mut scopes: Vec = vec![index.namespaces.clone()]; let mut scope_ids: HashMap = HashMap::new(); // What wrapping slices may add to the text parsed, whatever namespaces they declare. - let mut wrap_left = text.len().saturating_mul(4).max(MIN_WRAP_BYTES); + let mut wrap_left = text.len().saturating_mul(4).max(MIN_WRAP_BYTES).min(planned); let prefix = "".len(); crate::progress::begin(index.members.len() * 2); // Features with a slice the limits left unread: what they are then can't be known. @@ -2518,10 +2542,15 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize notes.snapshot_periods = trouble.periods; // Second pass: each feature in force at the date, from its slices. // The nested paths of every row, each kept once. - let paths: SharedPaths = - std::rc::Rc::new(std::cell::RefCell::new(Paths { limit: text.len().saturating_mul(2).max(MIN_ROW_BYTES), ..Paths::default() })); - let mut layers = - Layers { names_only: opts.names_only, bytes_left: text.len().saturating_mul(4).max(MIN_ROW_BYTES), ..Layers::default() }; + let paths: SharedPaths = std::rc::Rc::new(std::cell::RefCell::new(Paths { + limit: text.len().saturating_mul(2).max(MIN_ROW_BYTES).min(planned), + ..Paths::default() + })); + let mut layers = Layers { + names_only: opts.names_only, + bytes_left: text.len().saturating_mul(4).max(MIN_ROW_BYTES).min(planned), + ..Layers::default() + }; let mut shapes = Shapes { budget: text.len().max(MIN_ADDED_POINTS), scan_left: text.len().saturating_mul(8).max(MIN_ADDED_POINTS * 8), @@ -2530,7 +2559,7 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize // Rows of features with nothing to draw, by kind, kept until it is known whether the kind has // a layer to hold them. let mut shapeless: Vec<(String, Row, usize, bool, String)> = Vec::new(); - let mut held_left = text.len().saturating_mul(2).max(MIN_ROW_BYTES); + let mut held_left = text.len().saturating_mul(2).max(MIN_ROW_BYTES).min(planned); // GeoBorders first: airspace borders follow them by reference; route segments last: one with // no curve is drawn between the points it names. let rank = |id: &String| match features.get(id).map(|f| f.kind.as_str()) { @@ -2735,7 +2764,7 @@ fn read_within(file_name: &str, bytes: &[u8], opts: &Options, dense_floor: usize notes.assumed_system = shapes.assumed_system; let paths = paths.try_borrow_mut().map(|mut p| std::mem::take(&mut *p)).unwrap_or_default(); layers.list.sort_by_key(|l| kind_rank.get(&l.kind).copied().unwrap_or(usize::MAX)); - let mut dense_left = text.len().saturating_mul(8).max(dense_floor); + let mut dense_left = text.len().saturating_mul(8).max(dense_floor).min(planned); finish(&stem, at, layers, notes, &index, shapes.budget == 0, &paths, &mut dense_left) } diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 4285b2f022..409ec9dda0 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2075,7 +2075,7 @@ fn rows_past_the_tables_memory_are_left_out_and_said() { let sparse = message(&(0..rows).map(|i| one(i, if i == 0 { &wide } else { "" })).collect::()); let narrow = message(&(0..rows).map(|i| one(i, "")).collect::()); let run = |bytes: &[u8], floor| { - let out = read_within("t.xml", bytes, &at("2026-01-15"), floor).unwrap(); + let out = read_within("t.xml", bytes, &at("2026-01-15"), floor, usize::MAX).unwrap(); (layer(&out, "t DesignatedPoint").features.len(), said(&out)) }; // Sparse and wide: what eight times the file allows, the rest said. @@ -2419,3 +2419,11 @@ fn a_hole_across_180_degrees_is_inside_its_exterior() { let ((a, b), (c, d)) = (span(&p[0][0]), span(&p[0][1])); assert!(a <= c && d <= b, "{:?} {:?}", p[0][0], p[0][1]); } + +#[test] +fn a_message_past_the_memory_the_computer_can_set_aside_is_refused_with_a_way_out() { + let opts = at("2026-01-15"); + let e = read_within("donlon-aixm.xml", DONLON, &opts, 0, DONLON.len()).unwrap_err().to_string(); + assert!(e.contains("takes about") && e.contains("read a smaller extract"), "{e}"); + assert!(read_within("donlon-aixm.xml", DONLON, &opts, 0, DONLON.len() * HELD_PER_BYTE).is_ok()); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index eebe483e7c..e931eaa284 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7067,6 +7067,10 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { let i = s.downloaded.iter().position(|(d, _)| *d == id).ok_or("no such download (it was dropped when another project opened)")?; let (_, bytes) = s.downloaded.remove(i); let read_at = s.downloaded_reach.iter().position(|(d, _)| *d == id).map(|i| s.downloaded_reach.remove(i).1); + // A GeoLibre download is never an AIXM message: an effective date is refused, not dropped. + if ["geolibreProject", "geolibreLayer", "geolibreZarr"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + check_at(p, "a GeoLibre download", || false)?; + } if p.get("geolibreProject").and_then(Value::as_bool) == Some(true) { if bytes.len() > rustgis_map::geolibre::MAX_TEXT { return Err("GeoLibre project exceeds 64 MiB".into()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 79fa9bb0e4..06af56f4d8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -25889,6 +25889,15 @@ fn aixm_messages_are_added_at_the_date_asked() { assert!(e.contains("isn't one") && !e.contains("SECRET"), "{e}"); let z = s.run("layer.addUrl", &json!({"url": "https://example.com/a.zip?token=SECRET", "at": "2026-01-15"})).unwrap_err(); assert!(z.contains("unzip it") && !z.contains("SECRET"), "{z}"); + // A GeoLibre download is never an AIXM message. + for key in ["geolibreProject", "geolibreLayer", "geolibreZarr"] { + let id = s.download_started(); + assert!(s.download_landed(id, b"{}".to_vec())); + let mut q = json!({"id": id, "url": "https://example.test/project.json", "at": "2026-01-15"}); + q[key] = json!(true); + let g = s.run("layer.addDownload", &q).unwrap_err(); + assert!(g.contains("a GeoLibre download isn't one"), "{key}: {g}"); + } // A window of a GeoTIFF, before it is read. let w = s.run("layer.addUrl", &json!({"url": "https://example.test/download", "bbox": [0, 0, 1, 1], "at": "2026-01-15"})).unwrap_err(); assert!(w.contains("doesn't read at"), "{w}"); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index d5e20b3caa..2ea082590f 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read (or ends before it begins) are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, to within a meter (coarser, and said, past 3,600 points on one or the points the file's size allows), and long geodesic edges as points along the geodesic. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said); one named by a curve that isn't the GeoBorder's on the date, or by a name two share, isn't followed, and that is said. A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | +| AIXM | `.xml`, or `.gml` | Add Data, drop the file, upload, or From URL… | Aeronautical information (AIXM 5.1, 5.1.1 and 5.2 messages, and the FAA's 28-day NASR subscriber files of AIXM 5.1): a layer per feature kind (airports and heliports, navaids, designated points, route segments, airspace, obstacles…), and one per geometry property for a kind with several, such as an airport's reference point and its boundary. Each feature is read as it is on one effective date, `"at"` (`2026-01-15`, or with a time, UTC), today when left out: the BASELINE in force then with the highest correction, a PERMDELTA since, and the TEMPDELTAs in force over it; features not in force, withdrawn, canceled, given only as changes, or with a time slice that may apply then and can't be read (or ends before it begins) are left out and counted; a feature with no BASELINE is shown as its nearest SNAPSHOT as it is, read at its start when given a period (one withdrawn since, or that may be, or whose own lifetime hasn't begun is left out; one whose only snapshot is later may not have existed on the date), and changes whose effect differs between its instant and the date are said. Every value a feature holds is kept, within limits on columns (2,000), nesting and memory (values, and rows past the memory limit, are left out and counted): simple properties are fields, with their unit (`_uom`), why a value is missing (`_nilReason`) and other attributes, and for a reference to another feature its identifier and title (`_title`); values nested in records are fields named by their path (`authority_1_type`), numbered when a record repeats; vertical limits are kept as written (value, unit and reference: `FL`, `FT`, `M`; `SFC`, `MSL`, `STD`…). Arcs and circles given by a center (`ArcByCenterPoint`, `CircleByCenterPoint`) or by three points are drawn as points along them on the WGS 84 ellipsoid, to within a meter (coarser, and said, past 3,600 points on one or the points the file's size allows), and long geodesic edges as points along the geodesic. Reading a message takes about twice its size in memory beside the file; one past what the computer can set aside then is refused, saying so, before it is read. An airspace is drawn from its BASE volume, or its BASE and UNION volumes as parts; one built from other airspace or by subtraction or intersection is kept without a shape and said. A border given by reference to a GeoBorder in the same file is drawn along it, between the points on it nearest those either side (AIXM leaves this cut to the reader, so it is said); one named by a curve that isn't the GeoBorder's on the date, or by a name two share, isn't followed, and that is said. A route segment with no curve is drawn between the points its start and end name as its `pathType` says: a geodesic (`GDS`, `GRC` or none) or a rhumb line (`RHL`); with another, or an end that can't be found, it is kept without a line, and said. Positions in OGC's CRS83 (NAD83, as the FAA writes them) are read as WGS 84 and said. A vertical structure gives a row per part, and a feature whose shapes are in its records (a light system's lights, a marking's elements) a row per record. Runways, runway directions and routes are tables; other kinds with nothing to draw are counted. A message in a zip is read as it is today (unzip it to choose a date); `"at"` given for any other file, and `"crs"` given for an AIXM message (which names its own system), are refused. | | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | From a0f39932eb6b6707047d4b6870ad16ca1335ff51 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:17:42 -0600 Subject: [PATCH 61/61] fix: an address's answer refused for "at" without its last segment; holes kept in their exterior's span; a null past the column cap costs nothing; List Tables leaves a zip holding AIXM to Add Data --- crates/data/src/aixm.rs | 15 ++++-- crates/data/src/aixm/tests.rs | 80 ++++++++++++++++++++++++++++++++ crates/data/src/io.rs | 9 ++++ crates/engine/src/cmd/layer.rs | 9 ++++ crates/engine/src/cmd/service.rs | 1 + crates/engine/src/tests.rs | 6 +++ crates/ui-egui/src/dialogs.rs | 11 +++-- 7 files changed, 123 insertions(+), 8 deletions(-) diff --git a/crates/data/src/aixm.rs b/crates/data/src/aixm.rs index 9e3b59c369..3d78870e7d 100644 --- a/crates/data/src/aixm.rs +++ b/crates/data/src/aixm.rs @@ -1500,13 +1500,18 @@ impl Shapes { // cover what the hole excludes. let mut rings = vec![outer]; let mut hole_lost = false; - let middle = |r: &[Coord]| r.iter().map(|c| c.x).sum::() / r.len().max(1) as f64; - let outer_middle = middle(&rings[0]); + let span = |r: &[Coord]| r.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), c| (a.min(c.x), b.max(c.x))); + let outer_span = span(&rings[0]); for b in elements(p).filter(|c| local(c) == "interior") { match self.ring(b, &mut pn) { - // Its longitudes in the exterior's run: a hole across 180° is where it is. + // Its longitudes in the exterior's run: a hole across 180° is where it is. Of its + // images a whole turn apart, the one most inside the exterior's span, itself first. Some(r) => { - let turn = ((outer_middle - middle(&r)) / 360.0).round() * 360.0; + let (lo, hi) = span(&r); + let inside = |t: f64| (hi + t).min(outer_span.1) - (lo + t).max(outer_span.0); + let turn = [0.0, -360.0, 360.0, -720.0, 720.0] + .into_iter() + .fold(0.0, |best, t| if inside(t) > inside(best) + 1e-9 { t } else { best }); rings.push(if turn == 0.0 { r } else { r.into_iter().map(|c| Coord::new(c.x + turn, c.y)).collect() }); } None => hole_lost = true, @@ -1930,7 +1935,7 @@ impl Row { fn null(&mut self, key: &str) { // Its name is paid for as a value would be, though nothing is lost past the limit. let cost = key.len() + VALUE_OVERHEAD; - if self.named.contains(key) || self.limit.is_some_and(|l| self.bytes + cost > l) { + if self.named.contains(key) || self.columns.len() >= MAX_COLUMNS || self.limit.is_some_and(|l| self.bytes + cost > l) { return; } self.bytes += cost; diff --git a/crates/data/src/aixm/tests.rs b/crates/data/src/aixm/tests.rs index 409ec9dda0..9223c529b2 100644 --- a/crates/data/src/aixm/tests.rs +++ b/crates/data/src/aixm/tests.rs @@ -2427,3 +2427,83 @@ fn a_message_past_the_memory_the_computer_can_set_aside_is_refused_with_a_way_ou assert!(e.contains("takes about") && e.contains("read a smaller extract"), "{e}"); assert!(read_within("donlon-aixm.xml", DONLON, &opts, 0, DONLON.len() * HELD_PER_BYTE).is_ok()); } + +#[test] +fn a_hole_is_kept_in_its_exteriors_span_however_wide() { + let patch = |ext: &[(f64, f64)], hole: &[(f64, f64)]| { + let pos = |r: &[(f64, f64)]| r.iter().map(|(x, y)| format!("{y} {x}")).collect::>().join(" "); + let body = format!( + r#"{}{}"#, + pos(ext), + pos(hole) + ); + let out = read( + "t.xml", + &message(&feature("WorkArea", "w", &[slice("WorkArea", "BASELINE", 1, 0, &period("2025-01-01T00:00:00Z", None), &body)])), + &at("2026-01-15"), + ) + .unwrap(); + let Some(Geometry::Polygon(p)) = layer(&out, "t WorkArea").features[0].geometry.clone() else { panic!() }; + let span = |r: &[Coord]| r.iter().fold((f64::MAX, f64::MIN), |(a, b), c| (a.min(c.x), b.max(c.x))); + let ((a, b), (c, d)) = (span(&p[0][0]), span(&p[0][1])); + assert!(a <= c && d <= b, "{:?} {:?}", p[0][0], p[0][1]); + }; + // A wide exterior the hole's mean is far from, and one past 180 degrees. + let wide = [(0.0, 0.0), (125.0, 0.0), (-110.0, 0.0), (-110.0, 10.0), (125.0, 10.0), (0.0, 10.0), (0.0, 5.0), (0.0, 0.0)]; + patch(&wide, &[(-120.0, 2.0), (-115.0, 2.0), (-115.0, 8.0), (-120.0, 8.0), (-120.0, 2.0)]); + let around = [(-170.0, -5.0), (0.0, -5.0), (170.0, -5.0), (170.0, 5.0), (0.0, 5.0), (-170.0, 5.0), (-170.0, -5.0)]; + patch(&around, &[(159.0, -1.0), (161.0, -1.0), (161.0, 1.0), (159.0, 1.0), (159.0, -1.0)]); +} + +#[test] +fn a_null_past_the_column_cap_costs_nothing() { + let mut row = Row::default(); + for i in 0..MAX_COLUMNS { + let _ = row.name(&format!("c{i}"), true); + } + let before = row.bytes; + for _ in 0..3 { + row.null("past"); + } + assert_eq!(row.bytes, before); +} + +#[test] +fn a_correction_left_out_at_the_limits_withholds_its_feature() { + // Each slice declares its own namespace beside the feature's many: their scopes pass what the + // file's size allows, after the BASELINE's fits. + let decls: String = (0..400).map(|i| format!(r#" xmlns:n{i}="urn:a-long-namespace-name-to-pay-for-{i}""#)).collect(); + let slice_in = |seq: u32, corr: u32, name: &str| { + slice("DesignatedPoint", "BASELINE", seq, corr, &period("2025-01-01T00:00:00Z", None), &named_point(name)).replacen( + " = (0..12).map(|c| slice_in(1, c, &format!("C{c}"))).collect(); + let p = point("a", &slices).replacen(r#" = (0..ds.features.len()).map(|i| value(ds, i, "name")).collect(); + assert_eq!(names, [Value::Text("KEPT".into())], "{:?}", said(&out)); + assert!( + said(&out).iter().any(|m| m.contains("1 feature left out: a time slice of it couldn't be read within the limits")), + "{:?}", + said(&out) + ); + // With room, the latest correction holds. + let out = read_within("t.xml", &bytes, &at("2026-01-15"), 0, usize::MAX).unwrap(); + let ds = layer(&out, "t DesignatedPoint"); + assert!((0..ds.features.len()).any(|i| value(ds, i, "name") == Value::Text("C11".into())), "{:?}", said(&out)); +} + +#[test] +fn a_zip_holding_an_aixm_message_is_told() { + let zip = |name: &str, bytes: &[u8]| crate::zip::write(&[(name.to_string(), bytes.to_vec())]).unwrap(); + assert!(crate::io::zip_holds_aixm(&zip("donlon.xml", DONLON))); + assert!(!crate::io::zip_holds_aixm(&zip("points.csv", b"x,y\n1,2\n"))); + assert!(!crate::io::zip_holds_aixm(&zip("other.xml", b""))); +} diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 65412709d4..ae3acc40d2 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3856,6 +3856,15 @@ pub fn read_zip_in(file_name: &str, bytes: &[u8], crs: Option) -> Result bool { + let xml = |n: &str| { + let n = n.to_ascii_lowercase(); + !is_resource_fork(&n) && (n.ends_with(".xml") || n.ends_with(".gml")) + }; + crate::zip::read_matching(bytes, xml).is_ok_and(|members| members.iter().any(|(n, b)| is_aixm(n, b))) +} + pub fn read_zip_layers(file_name: &str, bytes: &[u8], crs: Option) -> Result> { read_zip_layers_budget(file_name, bytes, crs, &mut csv_memory_budget()) } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index e931eaa284..dec09449b6 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2346,6 +2346,12 @@ pub(crate) fn check_at(p: &Value, file_name: &str, aixm: impl FnOnce() -> bool) rustgis_data::aixm::Options::at_text(at) } +/// Refuses an effective date for an address's answer that isn't an AIXM message, naming the +/// address without quoting it (its last segment, which names the file, can hold a key). +pub(crate) fn check_answer_at(p: &Value, url: &str, name: &str, bytes: &[u8]) -> Result<(), String> { + check_at(p, unquoted(url), || rustgis_data::io::is_aixm(name, bytes)).map(|_| ()) +} + /// How a refusal names an address: not quoted, since it can hold a key, but a zip said as one. fn unquoted(url: &str) -> &'static str { if address_extension(url).as_deref() == Some("zip") { "that address's .zip" } else { "the file at that address" } @@ -5616,6 +5622,7 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { crate::render::rustgis_tiles::cache::download_blocking(url).map_err(named)? }; let name = url_file_name(url, &bytes).map_err(named)?; + check_answer_at(p, url, &name, &bytes)?; let left_out = parts_left_out(url, &bytes, p); let cut = url_name_cut("Add Data From URL", url, p, &bytes); // A WCS coverage's own system it was asked for in, for an answer that doesn't say it. @@ -5751,6 +5758,7 @@ fn add_url_range(s: &mut Session, p: &Value, url: &str, range: (u64, u64), publi let bytes = bytes.map_err(|e| range_failed(&ranged, e)).map_err(named)?; check_range_answer(&ranged, &bytes).map_err(named)?; let name = url_file_name(&ranged, &bytes).map_err(named)?; + check_answer_at(p, url, &name, &bytes)?; super::raster::add_named_bytes(s, p, name, bytes, b(p, "zoom")).map_err(named) } @@ -7115,6 +7123,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { #[cfg(target_arch = "wasm32")] let drawn = None; let asked = if coverage { super::raster::coverage_system(p, &url) } else { None }; + check_answer_at(p, &url, &name, &bytes)?; let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), drawn, asked)?; if let Some(n) = left_out { s.notify(n, false); diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index a07b6fefea..3756da2f74 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -679,6 +679,7 @@ pub(crate) fn add_service_layer( Downloaded::Bytes(bytes) => { let bytes = features_answer(s, name, url, bytes, bounds); let file = file(&bytes)?; + super::layer::check_answer_at(p, url, &file, &bytes)?; super::raster::add_named_bytes(s, p, file, bytes, zoom)? } // Read in protocol buffer pages: their positions as the service's system places them, so diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 06af56f4d8..cd20c6187e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -25889,6 +25889,12 @@ fn aixm_messages_are_added_at_the_date_asked() { assert!(e.contains("isn't one") && !e.contains("SECRET"), "{e}"); let z = s.run("layer.addUrl", &json!({"url": "https://example.com/a.zip?token=SECRET", "at": "2026-01-15"})).unwrap_err(); assert!(z.contains("unzip it") && !z.contains("SECRET"), "{z}"); + // An answer from an address with no extension is refused without naming its last segment. + let id = s.download_started(); + assert!(s.download_landed(id, br#"{"type":"FeatureCollection","features":[]}"#.to_vec())); + let e3 = + s.run("layer.addDownload", &json!({"id": id, "url": "https://example.test/api/key-SECRET42", "at": "2026-01-15"})).unwrap_err(); + assert!(e3.contains("isn't one") && !e3.contains("SECRET42"), "{e3}"); // A GeoLibre download is never an AIXM message. for key in ["geolibreProject", "geolibreLayer", "geolibreZarr"] { let id = s.download_started(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 590d53363e..1d92aadcd7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2495,10 +2495,15 @@ fn gpkg_add_layer(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { }; #[cfg(target_arch = "wasm32")] let too_large = || false; - // An AIXM message is read whole, its shapes too, to list it: not on the frame. Add Data lists - // it off the frame, with progress and Cancel. + // An AIXM message is read whole, its shapes too, to list it, in a zip too: not on the frame. Add + // Data lists it off the frame, with progress and Cancel. #[cfg(not(target_arch = "wasm32"))] - let aixm = || rustgis_engine::cmd::layer::is_aixm_path(&path); + let aixm = || { + rustgis_engine::cmd::layer::is_aixm_path(&path) + || (path.to_ascii_lowercase().ends_with(".zip") + && !too_large() + && std::fs::read(&path).is_ok_and(|b| rustgis_engine::data::io::zip_holds_aixm(&b))) + }; #[cfg(target_arch = "wasm32")] let aixm = || false; if list && aixm() {