From 9789a8624d7e4fe98bea58f60189c72633bd0193 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:29:00 -0600 Subject: [PATCH 01/14] feat(geom): UPS grid for the polar areas: readouts, polar MGRS and search (#1042) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit North of 84° N and south of 80° S, where the UTM zones stop, the UTM and MGRS readouts now give the Universal Polar Stereographic grid instead of "No UTM here", and search reads polar references. - New rustgis_geom::ups: polar stereographic on WGS 84 with k0 = 0.994 and a 2,000,000 m false origin, from NGA.SIG.0012 (2014) eqs. 18-22, with 84° N itself UPS and 80° S itself UTM (§10.4). - Polar MGRS with the NGA lettering (§§11.9-11.13): no zone number, Y/Z in the north and A/B in the south, 0° and 180° on the Z/B side, truncated digits. - parse_mgrs and parse_utm read ZAC7714662481, Z AC 77146 62481, north 2077146 1562481 and NGA.STND.0037's Y, 1735147, 2243078. - Search doesn't read text without digits as a grid reference, so words like BAN or ZAP stay words. Tested against NGA.SIG.0012's §10.2 and §10.3 tables, proj4rs, and GeographicLib's GeoConvert values. --- crates/data/tests/ups_vs_proj.rs | 54 +++ crates/engine/src/cmd/search.rs | 36 +- crates/geom/src/lib.rs | 4 +- crates/geom/src/ups.rs | 419 +++++++++++++++++++++ crates/geom/src/utm.rs | 326 +++++++++++++--- crates/ui-egui/src/coordreadout.rs | 32 +- crates/ui-egui/src/mapmenu.rs | 12 +- crates/ui-egui/src/searchbox.rs | 4 +- crates/ui-egui/tests/coordinate_readout.rs | 9 +- docs/user-guide/maps.md | 19 +- 10 files changed, 834 insertions(+), 81 deletions(-) create mode 100644 crates/data/tests/ups_vs_proj.rs create mode 100644 crates/geom/src/ups.rs diff --git a/crates/data/tests/ups_vs_proj.rs b/crates/data/tests/ups_vs_proj.rs new file mode 100644 index 0000000000..daad747eb2 --- /dev/null +++ b/crates/data/tests/ups_vs_proj.rs @@ -0,0 +1,54 @@ +//! UPS in `rustgis-geom` against proj4rs, which reprojects rasters and layers: polar +//! stereographic at UPS's scale of 0.994 and 2,000,000 m false origin (EPSG:5041 north, 5042 +//! south), at random places in both polar areas and at the poles, within a millimeter. + +use rustgis_data::raster::Crs; +use rustgis_geom::{Coord, ups}; + +/// A small deterministic generator (no dependency). +struct Lcg(u64); +impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + +fn proj(north: bool) -> rustgis_data::raster::Transformer { + let lat = if north { 90 } else { -90 }; + Crs::parse(&format!("+proj=stere +lat_0={lat} +lat_ts={lat} +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs")) + .unwrap() + .transformer() + .unwrap() +} + +/// Compares one place both ways; returns the largest difference in meters. +fn compare(t: &rustgis_data::raster::Transformer, p: Coord, north: bool) -> f64 { + let (e, n) = ups::to_ups_in_zone(p, north).unwrap(); + let want = t.from_lonlat(p).unwrap(); + let dm = (e - want.x).abs().max((n - want.y).abs()); + assert!(dm < 1e-3, "north {north} at {p:?}: ours {e} {n}, proj4rs {} {}", want.x, want.y); + let back = ups::from_ups(north, want.x, want.y).unwrap(); + let theirs = t.to_lonlat(want).unwrap(); + // Compare on the ground: near the pole a millimeter is many degrees of longitude. + let (x, y) = ups::to_ups_in_zone(back, north).unwrap(); + let (tx, ty) = ups::to_ups_in_zone(theirs, north).unwrap(); + assert!((x - tx).abs().max((y - ty).abs()) < 1e-3, "north {north} at {p:?}: ours {back:?}, proj4rs {theirs:?}"); + dm +} + +#[test] +fn random_polar_places_agree_with_proj4rs() { + let mut r = Lcg(2026); + let (north_t, south_t) = (proj(true), proj(false)); + let mut worst = 0.0f64; + for _ in 0..5_000 { + let lon = -180.0 + r.next() * 360.0; + worst = worst.max(compare(&north_t, Coord::new(lon, 84.0 + r.next() * 6.0), true)); + worst = worst.max(compare(&south_t, Coord::new(lon, -80.0 - 1e-9 - r.next() * 10.0), false)); + } + for (p, north) in [(Coord::new(0.0, 90.0), true), (Coord::new(0.0, -90.0), false), (Coord::new(180.0, 84.0), true)] { + worst = worst.max(compare(if north { &north_t } else { &south_t }, p, north)); + } + assert!(worst < 1e-3, "worst {worst} m"); +} diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 952f66737d..b38a497a3d 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -154,12 +154,15 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // zone and band) isn't looked for in the tables; two whole numbers (an id, years, a range) // may be either, and so may a bare 100 km MGRS square, which names Sentinel-2's tiles (33UVP); // an MGRS reference with digits is plainly a coordinate. UTM and MGRS are the Earth's grids, - // so on another body's map they name no place. + // so on another body's map they name no place. A polar (UPS) reference starts with a letter + // and has no zone number, so without digits it is three letters (BAN, ZAP), as often a word + // as a place: text with no digit isn't read as a grid reference (every other one has digits). let mut plainly_coordinate = false; + let grid_text = q.chars().any(|c| c.is_ascii_digit()); if let Some(c) = parse_lat_lon(&q) { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); - } else if map.body().is_earth() { + } else if map.body().is_earth() && grid_text { match read_grid_reference(&q) { Ok(c) => { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); @@ -698,7 +701,7 @@ mod tests { "38SAB4414084706", "38SMB441408470", "38TMB4414084706", - // Polar (UPS) references aren't read. + // A polar (UPS) letter after a zone number: UPS has no zone number. "38Z 444141 3684706", "38ZMB4414084706", "99X 1 2", @@ -795,6 +798,33 @@ mod tests { assert!(matches!(search(&s, "38SMB4414084706", 50).hits.first(), Some(Hit::Coordinate { .. }))); } + /// In the polar areas the grid is UPS: its MGRS references (no zone number) and positions are + /// found, while three letters alone (a 100 km square, or a word) aren't read as a reference. + #[test] + fn polar_grid_references_are_found() { + let s = Session::new(crate::sample::world_project()); + for q in ["ZFD9276707232", "Z FD 92767 07232", "zfd9276707232", "north 2392768 1607232", "Z 2392768 1607232"] { + match search(&s, q, 50).hits.first() { + Some(Hit::Coordinate { lon, lat }) => { + assert!((lon - 45.0).abs() < 1e-3 && (lat - 85.0).abs() < 1e-3, "{q}: {lon} {lat}") + } + other => panic!("{q}: {other:?}"), + } + } + match search(&s, "Y, 1735147, 2243078", 50).hits.first() { + Some(Hit::Coordinate { lon, lat }) => assert!(*lon < 0.0 && *lat > 86.0, "{lon} {lat}"), + other => panic!("{other:?}"), + } + for q in ["BAN", "ZAP", "Box", "Berlin", "Bay", "Zanzibar", "Y", "ZAH"] { + let r = search(&s, q, 50); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); + assert_eq!(r.grid_error, None, "{q}"); + } + // A polar reference that names no place says why. + assert_eq!(search(&s, "ZDA1234512345", 50).grid_error, Some(GridError::Square)); + assert_eq!(search(&s, "YRA1234512345", 50).grid_error, Some(GridError::OutsideZone)); + } + #[test] fn non_coordinates_are_refused() { for t in diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 366bed0974..48926c19ba 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -10,12 +10,14 @@ pub mod body; pub mod eqc; pub mod sinusoidal; pub mod triangulate; +pub mod ups; pub mod utm; pub use body::{BODIES, Body}; pub use eqc::EquidistantCylindrical; pub use sinusoidal::Sinusoidal; -pub use utm::{GridError, Mgrs, Utm, format_mgrs, format_utm, parse_mgrs, parse_utm, to_mgrs, to_utm}; +pub use ups::{Ups, format_ups, from_ups, to_ups}; +pub use utm::{GridError, Mgrs, Utm, format_mgrs, format_utm, parse_mgrs, parse_ups, parse_utm, to_mgrs, to_utm}; use std::sync::LazyLock; diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs new file mode 100644 index 0000000000..c87763adab --- /dev/null +++ b/crates/geom/src/ups.rs @@ -0,0 +1,419 @@ +//! WGS 84 Universal Polar Stereographic (UPS) coordinates: the grid of the polar areas, north of +//! 84° N and south of 80° S, where the UTM zones stop, and the 100 km squares MGRS uses there. +//! +//! The grid follows NGA.SIG.0012 (2014-03-25), "The Universal Grids and the Transverse Mercator +//! and Polar Stereographic Map Projections": +//! +//! - polar stereographic on WGS 84, with a scale of exactly 0.994 at the pole and a false easting +//! and false northing of 2,000,000 m (§10.1); +//! - the projection of eqs. (18)–(20) in §8, placed as eqs. (21) and (22) in §9.1 say: in both +//! zones the easting grows toward 90° E, and the northing grows toward 180° in the north and +//! toward 0° in the south, so the 2,000,000 m easting runs along the 0° and 180° meridians +//! (DMA TM 8358.2, §3-2.4); +//! - north UPS for latitudes of 84° N and more, south UPS for latitudes south of 80° S (§10.4): +//! 84° N itself is UPS, 80° S itself is UTM; +//! - MGRS in the polar areas (§§11.9–11.13, and NGA.STND.0037 §3-2c): no zone number, a letter for +//! the half (Y west and Z east in the north, A west and B east in the south; the 0° and 180° +//! meridians, at an easting of 2,000,000 m, are Z and B), then the 100 km square's column and +//! row letters, and the digits truncated to the precision. +//! +//! The conformal latitude is the one in [`crate::utm`] (Karney 2011, eqs. 7–9 and 19–21), which +//! gives the same values as §2.8 and §2.9's PhiToChi and ChiToPhi. + +use std::fmt; +use std::sync::LazyLock; + +use crate::Coord; +use crate::utm::{GridError, conformal_tan, eccentricity, geographic_tan, wgs84_a, wrap}; + +/// The northern limit of the UTM zones, where north UPS begins (degrees); 84° N itself is UPS. +pub const UPS_NORTH_FROM: f64 = 84.0; +/// The southern limit of the UTM zones (degrees); south UPS is south of it, 80° S itself is UTM. +pub const UPS_SOUTH_OF: f64 = -80.0; + +/// UPS's scale at the pole, exactly (NGA.SIG.0012 §10.1). +const K0: f64 = 0.994; +/// The false easting and false northing: the pole's grid coordinates (meters). +const FALSE_ORIGIN: f64 = 2_000_000.0; +/// MGRS 100 km square side (meters). +const SQUARE: f64 = 100_000.0; +/// The farthest from the pole (meters) an easting and northing may lie and still name a place; +/// past it they are typing errors, and the latitude series has nothing to gain. +const MAX_RADIUS: f64 = 20_000_000.0; + +/// k90 of NGA.SIG.0012 eq. (19): √(1 − e²) · exp(e · artanh e). +static K90: LazyLock = LazyLock::new(|| { + let e = eccentricity(); + (1.0 - e * e).sqrt() * (e * e.atanh()).exp() +}); + +/// The north zone's 100 km square column letters (band, column) from an easting of 1,300,000 m, +/// and its row letters from a northing of 1,300,000 m (NGA.SIG.0012 §11.10). +const NORTH_COLUMNS: [&[u8; 2]; 14] = [b"YR", b"YS", b"YT", b"YU", b"YX", b"YY", b"YZ", b"ZA", b"ZB", b"ZC", b"ZF", b"ZG", b"ZH", b"ZJ"]; +const NORTH_ROWS: &[u8; 14] = b"ABCDEFGHJKLMNP"; +/// The first 100 km square of the north zone's lettering, along either axis. +const NORTH_FIRST: i64 = 13; +/// The south zone's column letters from an easting of 800,000 m, and its row letters from a +/// northing of 800,000 m (NGA.SIG.0012 §11.11). +const SOUTH_COLUMNS: [&[u8; 2]; 24] = [ + b"AJ", b"AK", b"AL", b"AP", b"AQ", b"AR", b"AS", b"AT", b"AU", b"AX", b"AY", b"AZ", b"BA", b"BB", b"BC", b"BF", b"BG", b"BH", b"BJ", + b"BK", b"BL", b"BP", b"BQ", b"BR", +]; +const SOUTH_ROWS: &[u8; 24] = b"ABCDEFGHJKLMNPQRSTUVWXYZ"; +/// The first 100 km square of the south zone's lettering, along either axis. +const SOUTH_FIRST: i64 = 8; + +/// sin and cos of an angle in degrees, exact at multiples of 90°: on the 0° and 180° meridians the +/// easting is exactly 2,000,000 m, so a place there is in the Z or B half, as MGRS requires, and +/// longitude −180° falls on the same side as 180°. +fn sincosd(deg: f64) -> (f64, f64) { + let q = (deg / 90.0).round(); + let (s, c) = (deg - 90.0 * q).to_radians().sin_cos(); + match (q as i64).rem_euclid(4) { + 0 => (s, c), + 1 => (c, -s), + 2 => (-s, -c), + _ => (-c, s), + } +} + +/// The distance on the grid from the zone's own pole to a latitude measured toward that pole, in +/// meters: 2 a k0 / k90 · cos χ / (1 + sin χ), χ the conformal latitude (NGA.SIG.0012 eqs. 18 and +/// 21). cos χ / (1 + sin χ) is 1 / (τ′ + √(1 + τ′²)), written as √(1 + τ′²) − τ′ when τ′ is +/// negative so that it doesn't cancel. `None` at the other pole, where the projection has no +/// place. +fn polar_radius(lat: f64) -> Option { + if lat >= 90.0 { + return Some(0.0); + } + if lat <= -90.0 { + return None; + } + let taup = conformal_tan(lat.to_radians().tan()); + let h = taup.hypot(1.0); + let t = if taup >= 0.0 { 1.0 / (h + taup) } else { h - taup }; + let rho = 2.0 * wgs84_a() * K0 / *K90 * t; + rho.is_finite().then_some(rho) +} + +/// The latitude, measured toward the zone's own pole, at a distance from that pole on the grid: +/// with r = ρ k90 / (2 a k0), tan χ = (1 − r²) / 2r (NGA.SIG.0012 eq. 20), then the latitude from +/// the conformal one. +fn latitude_at(rho: f64) -> Option { + if rho == 0.0 { + return Some(90.0); + } + let r = rho * *K90 / (2.0 * wgs84_a() * K0); + let lat = geographic_tan((1.0 - r * r) / (2.0 * r))?.atan().to_degrees(); + lat.is_finite().then_some(lat) +} + +/// Which UPS zone a latitude lies in: `Some(true)` for north UPS (84° N to the pole), +/// `Some(false)` for south UPS (south of 80° S), `None` in the UTM latitudes, past a pole or for +/// a non-finite latitude. +pub fn ups_zone(lat: f64) -> Option { + if (UPS_NORTH_FROM..=90.0).contains(&lat) { + Some(true) + } else if (-90.0..UPS_SOUTH_OF).contains(&lat) { + Some(false) + } else { + None + } +} + +/// A place in UPS: the zone (north or south) and the easting and northing in meters; the pole is +/// at 2,000,000 m, 2,000,000 m. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ups { + pub north: bool, + pub easting: f64, + pub northing: f64, +} + +impl Ups { + /// The zone spelled out, as the readout writes it: `north` or `south`. + pub fn hemisphere(&self) -> &'static str { + if self.north { "north" } else { "south" } + } +} + +impl fmt::Display for Ups { + /// `north 2392768 1607232`, `south 2096454 1452981`: the zone, then the easting and northing + /// rounded to the meter, as GeographicLib's `GeoConvert -u -l` writes UPS (UPS has no zone + /// number). + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {:.0} {:.0}", self.hemisphere(), self.easting.round(), self.northing.round()) + } +} + +/// A place's UPS coordinates; `None` in the UTM latitudes (80° S up to 84° N) and for a non-finite +/// place. +pub fn to_ups(c: Coord) -> Option { + if !c.is_finite() { + return None; + } + let north = ups_zone(c.y)?; + let (easting, northing) = to_ups_in_zone(c, north)?; + Some(Ups { north, easting, northing }) +} + +/// A place's easting and northing in a UPS zone, as a projection to that zone works (EPSG:5041 +/// north, 5042 south), at any latitude but the other pole. `None` for a non-finite place, a +/// latitude past ±90° or the other pole. +pub fn to_ups_in_zone(c: Coord, north: bool) -> Option<(f64, f64)> { + if !c.is_finite() || c.y.abs() > 90.0 { + return None; + } + let rho = polar_radius(if north { c.y } else { -c.y })?; + let (sin, cos) = sincosd(wrap(c.x)); + let x = FALSE_ORIGIN + rho * sin; + let y = if north { FALSE_ORIGIN - rho * cos } else { FALSE_ORIGIN + rho * cos }; + (x.is_finite() && y.is_finite()).then_some((x, y)) +} + +/// The place (longitude, latitude) at an easting and northing in a UPS zone. The pole itself gets +/// longitude 0°. `None` for non-finite values, or an easting and northing more than 20,000 km from +/// the pole, which name no place. +pub fn from_ups(north: bool, easting: f64, northing: f64) -> Option { + if !easting.is_finite() || !northing.is_finite() { + return None; + } + let (dx, dy) = (easting - FALSE_ORIGIN, northing - FALSE_ORIGIN); + let rho = dx.hypot(dy); + if rho > MAX_RADIUS { + return None; + } + let lon = if rho == 0.0 { + 0.0 + } else if north { + dx.atan2(-dy).to_degrees() + } else { + dx.atan2(dy).to_degrees() + }; + let lat = latitude_at(rho)?; + Some(Coord::new(wrap(lon), if north { lat } else { -lat })) +} + +/// A place as `north 2392768 1607232` (see [`Ups`]'s `Display`); `None` in the UTM latitudes. +pub fn format_ups(c: Coord) -> Option { + to_ups(c).map(|u| u.to_string()) +} + +/// The MGRS letters of the 100 km square holding a UPS easting and northing (whole meters): the +/// half's letter (Y, Z, A or B), then the square's column and row letters. `None` outside the +/// lettered area of the zone (NGA.SIG.0012 §§11.10 and 11.11). +pub(crate) fn square_letters(north: bool, easting: i64, northing: i64) -> Option<(char, char, char)> { + let (col, row) = (easting.div_euclid(100_000), northing.div_euclid(100_000)); + let (columns, rows, first): (&[&[u8; 2]], &[u8], i64) = + if north { (&NORTH_COLUMNS, NORTH_ROWS, NORTH_FIRST) } else { (&SOUTH_COLUMNS, SOUTH_ROWS, SOUTH_FIRST) }; + let pair = columns.get(usize::try_from(col - first).ok()?)?; + let row = rows.get(usize::try_from(row - first).ok()?)?; + Some((char::from(pair[0]), char::from(pair[1]), char::from(*row))) +} + +/// The zone and the south-west corner (easting, northing in meters) of the 100 km square that a +/// half's letter and the square's letters name. [`GridError::Band`] for a letter that isn't a +/// polar half, [`GridError::Square`] for square letters that half doesn't use. +pub(crate) fn square_origin(half: char, column: char, row: char) -> Result<(bool, f64, f64), GridError> { + let north = match half { + 'Y' | 'Z' => true, + 'A' | 'B' => false, + _ => return Err(GridError::Band), + }; + let (columns, rows, first): (&[&[u8; 2]], &[u8], i64) = + if north { (&NORTH_COLUMNS, NORTH_ROWS, NORTH_FIRST) } else { (&SOUTH_COLUMNS, SOUTH_ROWS, SOUTH_FIRST) }; + let col = columns.iter().position(|p| char::from(p[0]) == half && char::from(p[1]) == column).ok_or(GridError::Square)?; + let row = rows.iter().position(|r| char::from(*r) == row).ok_or(GridError::Square)?; + let at = |i: usize| (first + i as i64) as f64 * SQUARE; + Ok((north, at(col), at(row))) +} + +/// Whether a UPS cell (south-west corner `e0`, `n0`, side `cell`) reaches into its zone: the +/// point of the cell nearest the pole lies at 84° N or more in the north, south of 80° S in the +/// south, give or take `slop_deg` for rounding. Squares at the corners of a zone's lettering lie +/// wholly in the UTM latitudes, and a reference there names no UPS place. +pub(crate) fn cell_reaches_zone(north: bool, e0: f64, n0: f64, cell: f64, slop_deg: f64) -> bool { + let near_pole = |lo: f64| FALSE_ORIGIN.clamp(lo, lo + cell); + match from_ups(north, near_pole(e0), near_pole(n0)) { + Some(p) if north => p.y >= UPS_NORTH_FROM - slop_deg, + Some(p) => p.y < UPS_SOUTH_OF + slop_deg, + None => false, + } +} + +/// Whether an easting lies in a polar half's side of its zone: Y and A west of the 2,000,000 m +/// easting, Z and B on it and east of it (NGA.STND.0037 App. B-5b). +pub(crate) fn easting_in_half(half: char, easting: f64) -> bool { + match half { + 'Y' | 'A' => easting < FALSE_ORIGIN, + 'Z' | 'B' => easting >= FALSE_ORIGIN, + _ => false, + } +} + +/// Whether a letter names a polar half of MGRS. +pub(crate) fn is_polar_half(letter: char) -> bool { + matches!(letter, 'A' | 'B' | 'Y' | 'Z') +} + +#[cfg(test)] +mod tests { + use super::*; + + fn c(lon: f64, lat: f64) -> Coord { + Coord::new(lon, lat) + } + + /// NGA.SIG.0012 §10.2 (north UPS, WGS 84): longitude, latitude → easting, northing, printed to + /// the micrometer. + #[test] + fn forward_matches_nga_table() { + let rows = [ + (90.0, 90.0, 2_000_000.000_000, 2_000_000.000_000), + (-179.0, 89.0, 1_998_062.320_046, 2_111_009.610_243), + (-90.0, 88.0, 1_777_930.731_071, 2_000_000.000_000), + (-1.0, 87.0, 1_994_185.827_038, 1_666_906.254_073), + (0.0, 86.0, 2_000_000.000_000, 1_555_731.570_643), + (1.0, 85.0, 2_009_694.068_153, 1_444_627.207_468), + (89.0, 84.0, 2_666_626.157_825, 1_988_363.997_132), + (90.0, 83.0, 2_778_095.750_322, 2_000_000.000_000), + (91.0, 82.0, 2_889_442.490_749, 2_015_525.276_426), + (179.0, 81.0, 2_017_473.190_606, 3_001_038.419_357), + (180.0, 80.0, 2_000_000.000_000, 3_112_951.136_955), + (0.0, 40.0, 2_000_000.000_000, -3_918_313.984_953), + (-90.0, 2.0, -10_206_568.118_587, 2_000_000.000_000), + ]; + for (lon, lat, e, n) in rows { + let (x, y) = to_ups_in_zone(c(lon, lat), true).unwrap(); + assert!((x - e).abs() < 2e-6 && (y - n).abs() < 2e-6, "{lon} {lat}: {x} {y}, want {e} {n}"); + // Back from our own easting and northing (NGA's are rounded to the micrometer, which + // near the pole is more than 1e-11° of longitude). + let back = from_ups(true, x, y).unwrap(); + assert!((back.y - lat).abs() < 1e-11, "{lon} {lat}: back {back:?}"); + if lat < 90.0 { + assert!((wrap(back.x - lon)).abs() < 1e-11, "{lon} {lat}: back {back:?}"); + } + } + } + + /// NGA.SIG.0012 §10.3 (south UPS, WGS 84): easting, northing → longitude, latitude, printed + /// to 1e-10°. The 180° meridian reads as −180° here (longitudes are in [−180°, 180°)). + #[test] + fn inverse_matches_nga_table() { + let rows = [ + (0.0, 0.0, -135.0, -64.916_412_333_2), + (1_000_000.0, 0.0, -153.434_948_822_9, -70.055_294_401_4), + (2_000_000.0, 0.0, -180.0, -72.126_361_016_3), + (1_000_000.0, 1_000_000.0, -135.0, -77.312_079_190_8), + (2_000_000.0, 1_000_000.0, 180.0, -81.010_663_264_5), + (2_000_000.0, 2_000_000.0, 0.0, -90.0), + (3_000_000.0, 2_000_000.0, 90.0, -81.010_663_264_5), + (2_000_000.0, 3_000_000.0, 0.0, -81.010_663_264_5), + (4_000_000.0, 4_000_000.0, 45.0, -64.916_412_333_2), + ]; + for (e, n, lon, lat) in rows { + let p = from_ups(false, e, n).unwrap(); + assert!((p.y - lat).abs() < 1e-9, "{e} {n}: {p:?}"); + assert!(wrap(p.x - lon).abs() < 1e-9, "{e} {n}: {p:?}"); + let (x, y) = to_ups_in_zone(p, false).unwrap(); + assert!((x - e).abs() < 1e-6 && (y - n).abs() < 1e-6, "{e} {n}: {x} {y}"); + } + } + + /// GeographicLib's `GeoConvert -u -l -p 0` for the same places. + #[test] + fn readout_matches_geoconvert() { + let cases = [ + (45.0, 85.0, "north 2392768 1607232"), + (170.0, -85.0, "south 2096454 1452981"), + (-180.0, 84.0, "north 2000000 2666728"), + (0.0, 90.0, "north 2000000 2000000"), + (0.0, -90.0, "south 2000000 2000000"), + ]; + for (lon, lat, want) in cases { + assert_eq!(format_ups(c(lon, lat)).as_deref(), Some(want), "{lon} {lat}"); + } + } + + #[test] + fn zones_follow_nga_ownership() { + assert_eq!(ups_zone(84.0), Some(true)); + assert_eq!(ups_zone(83.999_999), None); + assert_eq!(ups_zone(90.0), Some(true)); + assert_eq!(ups_zone(-80.0), None); + assert_eq!(ups_zone(-80.000_001), Some(false)); + assert_eq!(ups_zone(-90.0), Some(false)); + assert_eq!(ups_zone(90.5), None); + assert_eq!(ups_zone(f64::NAN), None); + assert!(to_ups(c(0.0, 0.0)).is_none()); + assert!(to_ups(c(f64::NAN, 85.0)).is_none()); + assert!(to_ups(c(0.0, f64::INFINITY)).is_none()); + } + + /// The 0° and 180° meridians are on the 2,000,000 m easting, so Z and B own them; −180° is + /// the same meridian as 180°. + #[test] + fn meridians_zero_and_180_are_on_the_central_easting() { + for lon in [0.0, 180.0, -180.0, 540.0] { + for (lat, north) in [(86.0, true), (-86.0, false)] { + let (x, _) = to_ups_in_zone(c(lon, lat), north).unwrap(); + assert_eq!(x, FALSE_ORIGIN, "{lon} {lat}"); + } + } + assert!(easting_in_half('Z', FALSE_ORIGIN) && !easting_in_half('Y', FALSE_ORIGIN)); + assert!(easting_in_half('B', FALSE_ORIGIN) && !easting_in_half('A', FALSE_ORIGIN)); + } + + #[test] + fn the_other_pole_and_hostile_values_name_no_place() { + assert!(to_ups_in_zone(c(0.0, -90.0), true).is_none()); + assert!(to_ups_in_zone(c(0.0, 90.0), false).is_none()); + assert!(to_ups_in_zone(c(0.0, 90.5), true).is_none()); + assert!(from_ups(true, f64::NAN, 0.0).is_none()); + assert!(from_ups(true, 1e300, 1e300).is_none()); + assert!(from_ups(false, f64::INFINITY, 2e6).is_none()); + assert_eq!(from_ups(true, 2e6, 2e6), Some(c(0.0, 90.0))); + } + + #[test] + fn letters_follow_nga_tables() { + // NGA.SIG.0012 §11.10: YU then YX, ZC then ZF; rows A to P. + assert_eq!(square_letters(true, 1_300_000, 1_300_000), Some(('Y', 'R', 'A'))); + assert_eq!(square_letters(true, 1_699_999, 2_699_999), Some(('Y', 'U', 'P'))); + assert_eq!(square_letters(true, 1_700_000, 2_000_000), Some(('Y', 'X', 'H'))); + assert_eq!(square_letters(true, 2_000_000, 2_000_000), Some(('Z', 'A', 'H'))); + assert_eq!(square_letters(true, 2_300_000, 2_000_000), Some(('Z', 'F', 'H'))); + assert_eq!(square_letters(true, 2_699_999, 2_000_000), Some(('Z', 'J', 'H'))); + assert_eq!(square_letters(true, 2_700_000, 2_000_000), None); + assert_eq!(square_letters(true, 1_299_999, 2_000_000), None); + // §11.11: AL then AP, BC then BF; rows A to Z (no I or O). + assert_eq!(square_letters(false, 800_000, 800_000), Some(('A', 'J', 'A'))); + assert_eq!(square_letters(false, 1_100_000, 2_000_000), Some(('A', 'P', 'N'))); + assert_eq!(square_letters(false, 2_000_000, 2_000_000), Some(('B', 'A', 'N'))); + assert_eq!(square_letters(false, 2_300_000, 3_199_999), Some(('B', 'F', 'Z'))); + assert_eq!(square_letters(false, 3_199_999, 799_999), None); + assert_eq!(square_letters(false, 3_200_000, 2_000_000), None); + for north in [true, false] { + let span = if north { 13..27 } else { 8..32 }; + for col in span.clone() { + for row in span.clone() { + let (h, cl, rw) = square_letters(north, col * 100_000, row * 100_000).unwrap(); + assert_eq!(square_origin(h, cl, rw), Ok((north, col as f64 * SQUARE, row as f64 * SQUARE))); + } + } + } + assert_eq!(square_origin('Y', 'A', 'A'), Err(GridError::Square)); + assert_eq!(square_origin('Z', 'D', 'A'), Err(GridError::Square)); + assert_eq!(square_origin('B', 'A', 'I'), Err(GridError::Square)); + assert_eq!(square_origin('C', 'A', 'A'), Err(GridError::Band)); + } + + #[test] + fn corner_squares_lie_outside_the_zone() { + // YRA, the north lettering's south-west corner, is wholly south of 84° N. + assert!(!cell_reaches_zone(true, 1_300_000.0, 1_300_000.0, SQUARE, 0.0)); + assert!(cell_reaches_zone(true, 2_000_000.0, 2_000_000.0, SQUARE, 0.0)); + assert!(cell_reaches_zone(false, 2_000_000.0, 2_000_000.0, SQUARE, 0.0)); + assert!(!cell_reaches_zone(false, 800_000.0, 800_000.0, SQUARE, 0.0)); + } +} diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index 7633884da8..85154b8d50 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -18,9 +18,10 @@ //! writes the zone with two digits (`04QFJ`), so references line up and sort; one digit is read //! as well. //! -//! Only the UTM latitudes, 80° S to 84° N, are covered: the polar areas use the Universal Polar -//! Stereographic (UPS) grid, which isn't implemented. There the functions return `None`, and a -//! typed polar reference is refused with [`GridError::Polar`]. +//! The UTM functions cover the UTM latitudes, 80° S up to 84° N. North of 84° N and south of +//! 80° S, the polar areas use the Universal Polar Stereographic grid ([`crate::ups`]): there +//! [`format_utm`] writes UPS (`north 2392768 1607232`), [`to_mgrs`] gives the polar MGRS reference +//! (`Z FD 92767 07232`, no zone number), and [`parse_utm`] and [`parse_mgrs`] read both grids. use std::fmt; use std::sync::LazyLock; @@ -100,8 +101,18 @@ static SERIES: LazyLock = LazyLock::new(|| { } }); +/// The WGS 84 semi-major axis (meters), for [`crate::ups`]. +pub(crate) fn wgs84_a() -> f64 { + WGS84_A +} + +/// The WGS 84 first eccentricity, for [`crate::ups`]. +pub(crate) fn eccentricity() -> f64 { + SERIES.e +} + /// tan of the conformal latitude from tan of the latitude, τ′(τ) (Karney 2011, eqs. 7–9). -fn conformal_tan(tau: f64) -> f64 { +pub(crate) fn conformal_tan(tau: f64) -> f64 { let e = SERIES.e; let sigma = (e * (e * tau / tau.hypot(1.0)).atanh()).sinh(); tau * sigma.hypot(1.0) - sigma * tau.hypot(1.0) @@ -109,7 +120,7 @@ fn conformal_tan(tau: f64) -> f64 { /// tan of the latitude from tan of the conformal latitude, by Newton's method (Karney 2011, /// eqs. 19–21). -fn geographic_tan(taup: f64) -> Option { +pub(crate) fn geographic_tan(taup: f64) -> Option { let e2m = 1.0 - SERIES.e * SERIES.e; let mut tau = taup / e2m; for _ in 0..10 { @@ -158,7 +169,7 @@ fn tm_inverse(x: f64, y: f64) -> Option<(f64, f64)> { } /// A longitude within [-180, 180). -fn wrap(lon: f64) -> f64 { +pub(crate) fn wrap(lon: f64) -> f64 { let l = (lon + 180.0).rem_euclid(360.0) - 180.0; if l >= 180.0 { l - 360.0 } else { l } } @@ -301,14 +312,17 @@ pub fn from_utm(zone: u8, north: bool, easting: f64, northing: f64) -> Option Option { - to_utm(c).map(|u| u.to_string()) + to_utm(c).map(|u| u.to_string()).or_else(|| crate::ups::format_ups(c)) } /// An MGRS reference: zone, band, the 100 km square's column and row letters, and the easting -/// and northing within the square truncated to `digits` digits each (0–5: 100 km to 1 m). +/// and northing within the square truncated to `digits` digits each (0–5: 100 km to 1 m). In the +/// polar areas (UPS) the zone is 0, as MGRS writes no zone number there, and the band is the +/// half's letter: Y or Z north of 84° N, A or B south of 80° S. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Mgrs { pub zone: u8, @@ -326,9 +340,19 @@ impl Mgrs { 10f64.powi(5 - i32::from(self.digits.min(5))) } - /// Without spaces: `33UVP1234523456`, `04QFJ12345678`. + /// Whether the reference is in a polar area (UPS), which MGRS writes without a zone number. + pub fn polar(&self) -> bool { + self.zone == 0 + } + + /// The zone and band as MGRS writes them: `33U`, `04Q`, or the polar half's letter alone (`Z`). + fn designator(&self) -> String { + if self.polar() { self.band.to_string() } else { format!("{:02}{}", self.zone, self.band) } + } + + /// Without spaces: `33UVP1234523456`, `04QFJ12345678`, `ZFD9276707232`. pub fn compact(&self) -> String { - format!("{:02}{}{}{}{}", self.zone, self.band, self.column, self.row, self.digit_groups().concat()) + format!("{}{}{}{}", self.designator(), self.column, self.row, self.digit_groups().concat()) } /// The easting and northing digits, zero-padded to the precision (empty for 100 km). @@ -347,9 +371,10 @@ impl Mgrs { } impl fmt::Display for Mgrs { - /// `33U VP 12345 23456` (the readout's form; `33U VP` at 100 km; `04Q FJ …` in zones 1–9). + /// `33U VP 12345 23456` (the readout's form; `33U VP` at 100 km; `04Q FJ …` in zones 1–9; + /// `Z FD 92767 07232` in the polar areas). fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:02}{} {}{}", self.zone, self.band, self.column, self.row)?; + write!(f, "{} {}{}", self.designator(), self.column, self.row)?; let [e, n] = self.digit_groups(); if !e.is_empty() { write!(f, " {e} {n}")?; @@ -359,10 +384,11 @@ impl fmt::Display for Mgrs { } /// A place's MGRS reference to `digits` digits per axis (clamped to 0–5: 100 km to 1 m), -/// truncated as MGRS requires; `None` outside 80° S to 84° N (the UPS areas). +/// truncated as MGRS requires (NGA.SIG.0012 §12.3); in the polar areas the UPS reference +/// (`Z FD 92767 07232`). `None` for a non-finite place or a latitude past ±90°. pub fn to_mgrs(c: Coord, digits: u8) -> Option { let digits = digits.min(5); - let u = to_utm(c)?; + let Some(u) = to_utm(c) else { return polar_mgrs(c, digits) }; // Whole metres first, truncated, so the square letters and the digits agree at an edge. Just // south of the equator the northing can round up to the full 10,000 km false northing, which // is the equator itself and row A of band N: it is kept a metre short, in row V of band M. @@ -390,7 +416,26 @@ pub fn to_mgrs(c: Coord, digits: u8) -> Option { }) } -/// A place as `33U VP 12345 23456` (1 m); `None` outside 80° S to 84° N. +/// A polar place's MGRS reference (NGA.SIG.0012 §§11.9–11.12): the UPS easting and northing in +/// whole meters, truncated, so the square letters and the digits agree at an edge. +fn polar_mgrs(c: Coord, digits: u8) -> Option { + let p = crate::ups::to_ups(c)?; + let (e, n) = (p.easting.floor() as i64, p.northing.floor() as i64); + let (band, column, row) = crate::ups::square_letters(p.north, e, n)?; + let scale = 10i64.pow(5 - u32::from(digits)); + Some(Mgrs { + zone: 0, + band, + column, + row, + easting: u32::try_from(e.rem_euclid(100_000) / scale).ok()?, + northing: u32::try_from(n.rem_euclid(100_000) / scale).ok()?, + digits, + }) +} + +/// A place as `33U VP 12345 23456` (1 m), or `Z FD 92767 07232` in the polar areas; `None` for +/// a non-finite place or a latitude past ±90°. pub fn format_mgrs(c: Coord) -> Option { to_mgrs(c, 5).map(|m| m.to_string()) } @@ -404,7 +449,8 @@ pub enum GridError { Zone, /// A letter that isn't a latitude band. Band, - /// A polar (UPS) reference: bands A, B, Y and Z. + /// A polar letter (A, B, Y or Z) after a zone number, or a UTM position north of 84° N or + /// south of 80° S: the polar areas are UPS, which has no zone number. Polar, /// 100 km square letters that the zone doesn't use. Square, @@ -424,7 +470,9 @@ impl fmt::Display for GridError { GridError::Syntax => "not a UTM or MGRS grid reference", GridError::Zone => "the UTM zone must be 1 to 60", GridError::Band => "the latitude band must be a letter from C to X (not I or O)", - GridError::Polar => "polar (UPS) grid references, north of 84° N or south of 80° S, aren't supported", + GridError::Polar => { + "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268 or Z AM 00775 44267" + } GridError::Square => "the 100 km square letters aren't used in this zone", GridError::Digits => "the grid digits must be an even count of 0 to 10, half for the easting and half for the northing", GridError::BandMismatch => "the northing doesn't fall in the latitude band given", @@ -477,6 +525,9 @@ fn cell_latitudes(zone: u8, north: bool, e0: f64, n0: f64, cell: f64) -> Option< /// The centre of the cell an MGRS reference names: the 2,000 km row cycle is settled by the band, /// which the cell must reach into. fn locate(m: &Mgrs) -> Result { + if m.polar() { + return locate_polar(m); + } if !(1..=60).contains(&m.zone) { return Err(GridError::Zone); } @@ -517,9 +568,78 @@ fn locate(m: &Mgrs) -> Result { found.ok_or(GridError::BandMismatch) } +/// The center of the cell a polar MGRS reference names (NGA.SIG.0012 §11.13): the square's +/// south-west corner from its letters, plus the digits. The cell must reach into its UPS zone: +/// the squares at the corners of the lettering lie wholly in the UTM latitudes. +fn locate_polar(m: &Mgrs) -> Result { + if m.digits > 5 { + return Err(GridError::Digits); + } + let (north, e0, n0) = crate::ups::square_origin(m.band, m.column, m.row)?; + let cell = m.precision_m(); + if f64::from(m.easting) * cell >= SQUARE || f64::from(m.northing) * cell >= SQUARE { + return Err(GridError::Digits); + } + let e0 = e0 + f64::from(m.easting) * cell; + let n0 = n0 + f64::from(m.northing) * cell; + if !crate::ups::cell_reaches_zone(north, e0, n0, cell, ROUNDING_DEG) { + return Err(GridError::OutsideZone); + } + crate::ups::from_ups(north, e0 + cell / 2.0, n0 + cell / 2.0).ok_or(GridError::OutsideZone) +} + /// Most characters a typed grid reference may have. const MAX_REF_CHARS: usize = 64; +/// An easting and a northing in meters, separated by spaces or commas: plain decimals only (no +/// signs, exponents or `inf`). +fn easting_and_northing(text: &str) -> Result<(f64, f64), GridError> { + let nums: Vec<&str> = text.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()).collect(); + let [es, ns] = nums.as_slice() else { return Err(GridError::Syntax) }; + let number = |s: &str| { + if !s.chars().all(|c| c.is_ascii_digit() || c == '.') { + return Err(GridError::Syntax); + } + s.parse::().ok().filter(|v| v.is_finite()).ok_or(GridError::Syntax) + }; + Ok((number(es)?, number(ns)?)) +} + +/// Reads a UPS position, which has no zone number: the zone spelled out, `north 2392768 1607232` +/// or `south 2096454 1452981` (any case), as the readout writes it, or the polar half's letter +/// before the easting and northing, `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and +/// A lie west of the 2,000,000 m easting and Z and B on or east of it. The place must lie in the +/// zone, at 84° N or more or south of 80° S, give or take the meter it was rounded to. +pub fn parse_ups(text: &str) -> Result { + let text = text.trim(); + if text.chars().count() > MAX_REF_CHARS { + return Err(GridError::Syntax); + } + let mut chars = text.chars().peekable(); + let mut word = String::new(); + while let Some(c) = chars.next_if(char::is_ascii_alphabetic) { + word.push(c.to_ascii_uppercase()); + } + let (north, half) = match word.as_str() { + "NORTH" => (true, None), + "SOUTH" => (false, None), + "Y" | "Z" => (true, word.chars().next()), + "A" | "B" => (false, word.chars().next()), + _ => return Err(GridError::Syntax), + }; + let rest: String = chars.collect(); + let (easting, northing) = easting_and_northing(&rest)?; + if half.is_some_and(|h| !crate::ups::easting_in_half(h, easting)) { + return Err(GridError::OutsideZone); + } + let p = crate::ups::from_ups(north, easting, northing).ok_or(GridError::OutsideZone)?; + let in_zone = if north { p.y >= crate::ups::UPS_NORTH_FROM - ROUNDING_DEG } else { p.y < crate::ups::UPS_SOUTH_OF + ROUNDING_DEG }; + if !in_zone { + return Err(GridError::OutsideZone); + } + Ok(p) +} + /// Reads a zone number (one or two digits) and the letter after it, skipping spaces. The zone /// isn't checked to be 1–60 here (the caller does, once the rest reads as a reference): until /// then, `75 Main St` is text. @@ -550,15 +670,21 @@ fn band_letter(letter: char) -> Result { /// `33U VP 12345 23456`, `33UVP 1234 2345`, `4QFJ` (100 km). The digits are an even count of 0 /// to 10, as one run or as two groups of the same length. The square letters are checked against /// the zone, and the northing against the band, so a reference that doesn't exist is refused -/// rather than placed somewhere else. Polar (UPS) references are refused with -/// [`GridError::Polar`]. +/// rather than placed somewhere else. +/// +/// In the polar areas MGRS writes no zone number (NGA.SIG.0012 §§11.9 and 11.13): the half's +/// letter (Y or Z north, A or B south), the square's letters, then the digits, as +/// `ZFD9276707232` or `Z FD 92767 07232`. A polar letter after a zone number (`38ZMB`) is refused +/// with [`GridError::Polar`]; text that starts with any other letter isn't a reference. pub fn parse_mgrs(text: &str) -> Result { let text = text.trim(); if text.chars().count() > MAX_REF_CHARS { return Err(GridError::Syntax); } let mut chars = text.chars().peekable(); - let (zone, band) = zone_and_letter(&mut chars)?; + let polar = chars.peek().is_some_and(char::is_ascii_alphabetic); + let (zone, band) = + if polar { (0, chars.next().map(|c| c.to_ascii_uppercase()).ok_or(GridError::Syntax)?) } else { zone_and_letter(&mut chars)? }; let mut letters = [' '; 2]; for l in letters.iter_mut() { while chars.next_if(|c| c.is_whitespace()).is_some() {} @@ -585,11 +711,19 @@ pub fn parse_mgrs(text: &str) -> Result { } _ => return Err(GridError::Digits), }; - // The zone first, as `parse_utm` does: `0AAA` names a bad zone, not a polar reference. - if !(1..=60).contains(&zone) { - return Err(GridError::Zone); - } - let band = band_letter(band)?; + let band = if polar { + // Only the polar halves' letters start a reference: `CAT` or `Main` is text. + if !crate::ups::is_polar_half(band) { + return Err(GridError::Syntax); + } + band + } else { + // The zone first, as `parse_utm` does: `0AAA` names a bad zone, not a polar reference. + if !(1..=60).contains(&zone) { + return Err(GridError::Zone); + } + band_letter(band)? + }; let [column, row] = letters; let digit = |s: &str| if s.is_empty() { Ok(0) } else { s.parse::().map_err(|_| GridError::Digits) }; let m = Mgrs { @@ -617,12 +751,17 @@ pub fn parse_mgrs(text: &str) -> Result { /// /// `S` after the zone is band S (32° N to 40° N). A northing outside band S may mean the /// southern hemisphere, so it is refused as [`GridError::Ambiguous`] rather than guessed. -/// Polar (UPS) references are refused. +/// +/// North of 84° N and south of 80° S the grid is UPS, read by [`parse_ups`]'s forms +/// (`north 2392768 1607232`); a UTM zone's position there is refused as [`GridError::Polar`]. pub fn parse_utm(text: &str) -> Result { let text = text.trim(); if text.chars().count() > MAX_REF_CHARS { return Err(GridError::Syntax); } + if text.starts_with(|c: char| c.is_ascii_alphabetic()) { + return parse_ups(text); + } let mut chars = text.chars().peekable(); let (zone, letter) = zone_and_letter(&mut chars)?; let mut word = String::from(letter); @@ -633,16 +772,7 @@ pub fn parse_utm(text: &str) -> Result { return Err(GridError::Syntax); } let rest: String = chars.collect(); - let nums: Vec<&str> = rest.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()).collect(); - let [es, ns] = nums.as_slice() else { return Err(GridError::Syntax) }; - let number = |s: &str| { - // Plain decimals only: no signs, exponents or "inf". - if s.is_empty() || !s.chars().all(|c| c.is_ascii_digit() || c == '.') { - return Err(GridError::Syntax); - } - s.parse::().ok().filter(|v| v.is_finite()).ok_or(GridError::Syntax) - }; - let (easting, northing) = (number(es)?, number(ns)?); + let (easting, northing) = easting_and_northing(&rest)?; if !(1..=60).contains(&zone) { return Err(GridError::Zone); } @@ -910,8 +1040,11 @@ mod tests { assert_eq!(to_mgrs(p, 9).unwrap().digits, 5); // The UTM readout rounds instead. assert_eq!(from_utm(38, true, 444_140.6, 3_684_706.4).map(format_utm), Some(Some("38north 444141 3684706".into()))); - assert!(to_mgrs(c(0.0, 84.0), 5).is_none()); - assert!(format_mgrs(c(0.0, -85.0)).is_none()); + // In the polar areas, UPS's MGRS (GeographicLib's `GeoConvert -m -p 0`), truncated too. + assert_eq!(to_mgrs(c(0.0, 84.0), 5).map(|m| m.compact()).as_deref(), Some("ZAA0000033272")); + assert_eq!(format_mgrs(c(170.0, -85.0)).as_deref(), Some("B AG 96454 52981")); + assert_eq!(to_mgrs(c(-0.0001, -88.0), 5).map(|m| m.compact()).as_deref(), Some("AZQ9999922069")); + assert_eq!(to_mgrs(c(170.0, -85.0), 2).map(|m| m.compact()).as_deref(), Some("BAG9652")); } #[test] @@ -1138,10 +1271,17 @@ mod tests { let zone_end = text.find(|ch: char| !ch.is_ascii_digit()).unwrap(); assert!(text[zone_end..].starts_with("north ") || text[zone_end..].starts_with("south "), "{text}"); } - // Where UTM has no zone the readout still writes nothing, and the hemisphere form of a - // polar position is refused. - for p in [c(0.0, 84.0), c(0.0, -80.000_1), c(0.0, 90.0)] { - assert!(format_utm(p).is_none(), "{p:?}"); + // Where UTM has no zone the readout writes UPS (GeographicLib's `GeoConvert -u -l`), which + // reads back; a UTM zone's position there is refused. + for (p, want) in [ + (c(0.0, 84.0), "north 2000000 1333272"), + (c(0.0001, -80.000_1), "south 2000002 3112940"), + (c(0.0, 90.0), "north 2000000 2000000"), + ] { + let text = format_utm(p).unwrap(); + assert_eq!(text, want, "{p:?}"); + let back = parse_utm(&text).unwrap(); + assert!((back.y - p.y).abs() < 1e-5, "{p:?} {back:?}"); } let (e, n) = to_utm_in_zone(c(15.0, 84.05), 33, true).unwrap(); assert_eq!(parse_utm(&format!("33north {} {}", e.round(), n.round())), Err(GridError::Polar)); @@ -1341,7 +1481,15 @@ mod tests { #[test] fn outside_utm_is_said_not_guessed() { - for p in [c(0.0, 84.0), c(10.0, 89.9), c(0.0, 90.0), c(-60.0, -80.5), c(0.0, -90.0), c(f64::NAN, 1.0)] { + // UTM has no zone in the polar areas; the readouts give UPS there instead. + for p in [c(0.0, 84.0), c(10.0, 89.9), c(0.0, 90.0), c(-60.0, -80.5), c(0.0, -90.0)] { + assert!(to_utm(p).is_none(), "{p:?}"); + let utm = format_utm(p).unwrap(); + assert!(utm.starts_with(if p.y > 0.0 { "north " } else { "south " }), "{p:?} {utm}"); + let mgrs = to_mgrs(p, 5).unwrap(); + assert!(mgrs.polar() && "ABYZ".contains(mgrs.band), "{p:?} {mgrs}"); + } + for p in [c(f64::NAN, 1.0), c(0.0, 90.5), c(0.0, -91.0), c(f64::INFINITY, 85.0)] { assert!(to_utm(p).is_none(), "{p:?}"); assert!(format_utm(p).is_none(), "{p:?}"); assert!(format_mgrs(p).is_none(), "{p:?}"); @@ -1354,4 +1502,92 @@ mod tests { assert!(to_utm_in_zone(c(100.0, 0.0), 31, true).is_none()); assert!(to_utm_in_zone(c(3.0, 91.0), 31, true).is_none()); } + + /// Polar MGRS against GeographicLib's `GeoConvert -m -p 0`: written, then read back in both + /// forms to the same cell. + #[test] + fn polar_mgrs_matches_geoconvert_and_reads_back() { + let cases = [ + (0.0, 84.0, "ZAA0000033272"), + (-0.5, 84.5, "YZA9466788941"), + (45.0, 85.0, "ZFD9276707232"), + (-135.0, 87.5, "YYJ0370596294"), + (10.0, 89.999, "ZAG0001999890"), + (0.0, 90.0, "ZAH0000000000"), + (179.9, 86.0, "ZAM0077544267"), + (-179.9, 86.0, "YZM9922444267"), + (180.0, 84.0, "ZAP0000066727"), + (-180.0, 84.0, "ZAP0000066727"), + (-60.0, -80.5, "ALT8456628525"), + (170.0, -85.0, "BAG9645452981"), + (30.0, -89.9, "BAN0555109614"), + (0.0, -90.0, "BAN0000000000"), + (0.0001, -80.0001, "BAZ0000112939"), + (-0.0001, -88.0, "AZQ9999922069"), + ]; + for (lon, lat, want) in cases { + let m = to_mgrs(c(lon, lat), 5).unwrap(); + assert_eq!(m.compact(), want, "{lon} {lat}"); + assert_eq!(parse_mgrs(want), Ok(m), "{want}"); + assert_eq!(parse_mgrs(&m.to_string()), Ok(m), "{m}"); + assert_eq!(parse_mgrs(&want.to_lowercase()), Ok(m), "{want}"); + let p = m.centre().unwrap(); + assert!((p.y - lat).abs() < 1e-4, "{want}: {p:?}"); + } + // UTM still owns 80° S itself. + assert_eq!(to_mgrs(c(0.0, -80.0), 5).map(|m| m.compact()).as_deref(), Some("31CDM4186716915")); + // NGA.STND.0037 App. B-5f's worked example, 86°46′ N 132°30′ W: zone Y, square XK. + let m = to_mgrs(c(-132.5, 86.0 + 46.0 / 60.0), 2).unwrap(); + assert_eq!((m.band, m.column, m.row), ('Y', 'X', 'K')); + } + + #[test] + fn polar_references_that_name_no_place_are_refused() { + for (text, why) in [ + ("ZDA", GridError::Square), // Z skips D and E + ("YAA", GridError::Square), // Y starts at R + ("BAI", GridError::Square), // no I + ("YRA", GridError::OutsideZone), // the north lettering's corner lies south of 84° N + ("AJA", GridError::OutsideZone), // the south lettering's corner lies north of 80° S + ("ZAH123", GridError::Digits), + ("ZAH 123 45", GridError::Digits), + ("38ZMB", GridError::Polar), // a polar letter after a zone number + ] { + assert_eq!(parse_mgrs(text), Err(why), "{text}"); + } + // Text starting with any other letter, or words, aren't references. + for text in ["CAT", "Main", "Berlin 12", "Z", "ZA", "BOX", "zap road"] { + assert!(matches!(parse_mgrs(text), Err(GridError::Syntax | GridError::Square)), "{text}"); + } + for text in ["CAT", "Main", "Berlin 12", "Z", "zap road"] { + assert_eq!(parse_mgrs(text), Err(GridError::Syntax), "{text}"); + } + } + + /// UPS positions: the readout's `north …`/`south …` and NGA.STND.0037 App. A-4's + /// `Y, 1735147, 2243078`, whose letter must match the side of the 2,000,000 m easting. + #[test] + fn ups_positions_read_both_forms() { + let p = parse_utm("north 2392768 1607232").unwrap(); + assert!((p.x - 45.0).abs() < 1e-4 && (p.y - 85.0).abs() < 1e-4, "{p:?}"); + assert_eq!(parse_utm("NORTH 2392768 1607232"), Ok(p)); + assert_eq!(parse_utm("Z 2392768 1607232"), Ok(p)); + let q = parse_utm("Y, 1735147, 2243078").unwrap(); + assert!(q.x < 0.0 && q.y > 84.0, "{q:?}"); + let s = parse_utm("south 2096454 1452981").unwrap(); + assert!((s.x - 170.0).abs() < 1e-4 && (s.y + 85.0).abs() < 1e-4, "{s:?}"); + assert_eq!(parse_utm("B 2096454 1452981"), Ok(s)); + for (text, why) in [ + ("Y 2392768 1607232", GridError::OutsideZone), // east of 2,000,000 m is Z + ("A 2096454 1452981", GridError::OutsideZone), // east of 2,000,000 m is B + ("north 2000000 100000", GridError::OutsideZone), // south of 84° N + ("south 2000000 3500000", GridError::OutsideZone), // north of 80° S + ("north 2000000", GridError::Syntax), + ("north -1 2000000", GridError::Syntax), + ("Q 2000000 2000000", GridError::Syntax), + ("north 1e300 2000000", GridError::Syntax), + ] { + assert_eq!(parse_utm(text), Err(why), "{text}"); + } + } } diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs index 6953ee3647..a0f7496fb0 100644 --- a/crates/ui-egui/src/coordreadout.rs +++ b/crates/ui-egui/src/coordreadout.rs @@ -69,9 +69,9 @@ impl CoordReadout { matches!(self, CoordReadout::Utm | CoordReadout::Mgrs) } - /// The place in this format; for UTM and MGRS `None` outside their latitudes (80° S to - /// 84° N) and on another body's map (`earth` false), and for every format `None` for a - /// non-finite place. + /// The place in this format; for UTM and MGRS, UPS in the polar areas (north of 84° N and + /// south of 80° S) and `None` on another body's map (`earth` false), and for every format + /// `None` for a non-finite place. pub fn format(self, c: Coord, earth: bool) -> Option { if !c.is_finite() || (self.earth_only() && !earth) { return None; @@ -84,10 +84,9 @@ impl CoordReadout { } } - /// The status bar's readout of the pointer: `—` off the map, and a short statement where UTM - /// and MGRS have no zone (the polar areas, which use UPS, and other bodies) rather than a - /// wrong grid reference; the [`hover`](Self::hover) text says why. It is no wider than a - /// reference, so the status bar keeps its room. + /// The status bar's readout of the pointer: `—` off the map, and a short statement on another + /// body's map, where the Earth's grids name no place, rather than a wrong grid reference. It is + /// no wider than a reference, so the status bar keeps its room. pub fn readout(self, c: Option, earth: bool) -> String { match c { None => "—".to_string(), @@ -96,11 +95,11 @@ impl CoordReadout { } } - /// The status bar readout's hover text: the current format, what a click does, and where - /// UTM and MGRS read. + /// The status bar readout's hover text: the current format, what a click does, and how UTM + /// and MGRS read near the poles. pub fn hover(self) -> String { i18n::fmt( - "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. UTM and MGRS cover the Earth from 80° S to 84° N.", + "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. North of 84° N and south of 80° S, UTM and MGRS read in UPS.", &[("format", self.label())], ) } @@ -150,15 +149,14 @@ mod tests { } #[test] - fn polar_places_say_they_are_outside_utm() { + fn polar_places_read_in_ups() { let pole = Coord::new(10.0, 86.0); + // GeographicLib's `GeoConvert -u -l` and `-m` for the same place. + assert_eq!(CoordReadout::Utm.readout(Some(pole), true), "north 2077146 1562481"); + assert_eq!(CoordReadout::Mgrs.readout(Some(pole), true), "Z AC 77146 62481"); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { - assert_eq!(f.format(pole, true), None); - let r = f.readout(Some(pole), true); - assert_eq!(r, format!("No {} here", f.label())); - // No wider than the reference it stands for, in the status bar. - assert!(r.chars().count() <= f.readout(Some(Coord::new(44.4, 33.3)), true).chars().count(), "{r}"); - assert!(f.hover().contains("80° S to 84° N")); + assert_eq!(f.format(pole, true).as_deref(), Some(f.readout(Some(pole), true).as_str())); + assert!(f.hover().contains("UPS")); } // Decimal and DMS read there as anywhere. assert_eq!(CoordReadout::Dms.readout(Some(pole), true), "10°00′00.0″ E 86°00′00.0″ N"); diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index f84a351c29..bf0c6ec583 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -131,7 +131,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { ) } else if fell_back { i18n::fmt( - "Copy coordinates to the clipboard. No {format} here: outside the UTM zones (80° S to 84° N), so latitude and longitude are copied", + "Copy coordinates to the clipboard. No {format} here, so latitude and longitude are copied", &[("format", format.label())], ) } else { @@ -286,11 +286,15 @@ mod tests { assert!((at.x - q.x).abs() < 1e-4 && (at.y - q.y).abs() < 1e-4, "{text} {at:?}"); } } - // Where UTM has no zone, the row falls back to latitude and longitude (and says so). + // Where UTM has no zone, the row gives UPS (`north …`, `Z …`), which reads back too. let pole = Coord::new(10.0, 86.0); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { - assert_eq!(coordinate_row(pole, f, true), ("86.000000, 10.000000".into(), true), "{f:?}"); - // On another body's map as well: UTM and MGRS are the Earth's grids. + let (text, fell_back) = coordinate_row(pole, f, true); + assert!(!fell_back && (text.starts_with("north ") || text.starts_with("Z ")), "{f:?}: {text}"); + let at = rustgis_engine::cmd::search::read_grid_reference(&text).unwrap_or_else(|e| panic!("{text}: {e}")); + assert!((at.x - pole.x).abs() < 1e-3 && (at.y - pole.y).abs() < 1e-4, "{text} {at:?}"); + // On another body's map the row falls back to latitude and longitude (and says so): + // UTM, MGRS and UPS are the Earth's grids. assert_eq!(coordinate_row(p, f, false), ("33.300000, 44.400000".into(), true), "{f:?}"); } assert!(!coordinate_row(pole, CoordReadout::Dms, true).1); diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index 0033bf8c5b..38a41be571 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -386,7 +386,9 @@ fn grid_error_text(e: rustgis_engine::geom::GridError) -> String { G::Syntax => tl_raw!("not a UTM or MGRS grid reference"), G::Zone => tl_raw!("the UTM zone must be 1 to 60"), G::Band => tl_raw!("the latitude band must be a letter from C to X (not I or O)"), - G::Polar => tl_raw!("polar (UPS) grid references, north of 84° N or south of 80° S, aren't supported"), + G::Polar => tl_raw!( + "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268 or Z AM 00775 44267" + ), G::Square => tl_raw!("the 100 km square letters aren't used in this zone"), G::Digits => tl_raw!("the grid digits must be an even count of 0 to 10, half for the easting and half for the northing"), G::BandMismatch => tl_raw!("the northing doesn't fall in the latitude band given"), diff --git a/crates/ui-egui/tests/coordinate_readout.rs b/crates/ui-egui/tests/coordinate_readout.rs index 00f6508c3f..c1aa8d6569 100644 --- a/crates/ui-egui/tests/coordinate_readout.rs +++ b/crates/ui-egui/tests/coordinate_readout.rs @@ -120,12 +120,15 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() h.get_by_label(&mgrs).click(); hover_map(&mut h); assert_eq!(h.state().map.coord_format, CoordReadout::Decimal); - // Where UTM has no zone the readout says so rather than showing a wrong reference. + // Where UTM has no zone the readout gives the polar grid, UPS (MGRS without a zone number). h.state_mut().run("ui.coordinateFormat", json!({"format": "mgrs"})).unwrap(); h.state_mut().run("map.goToXY", json!({"lon": 10.0, "lat": 84.5, "scale": 10000})).unwrap(); hover_map(&mut h); - assert!(h.state().map.pointer_lonlat.is_some_and(|c| c.y > 84.0)); - h.get_by_label("No MGRS here"); + let at = h.state().map.pointer_lonlat.unwrap(); + assert!(at.y > 84.0, "{at:?}"); + let polar = rustgis_engine::geom::format_mgrs(at).unwrap(); + assert!(polar.starts_with("Z "), "{polar}"); + h.get_by_label(&polar); // On another body's map UTM and MGRS, the Earth's grids, read nothing either. h.state_mut().run("map.body", json!({"name": "mars", "basemap": false})).unwrap(); h.state_mut().run("map.goToXY", json!({"lon": 44.4, "lat": 33.3, "scale": 10000})).unwrap(); diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 530f0b193f..46efbac374 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -129,9 +129,9 @@ rustgis-cli run --sample --cmd 'map.search={"query":"Tokyo","go":true}' **Right-click the map** for a menu about that place. Its first row shows the place in the status bar's coordinate format (latitude and longitude as `40.712800, -74.006000` for decimal degrees); -click it to copy it. North of 84° N and south of 80° S, where UTM and MGRS have no zone, and on -the map of another body than the Earth, it shows and copies the latitude and longitude, and its -hover text says why. Below it, **Copy As GeoJSON** +click it to copy it. North of 84° N and south of 80° S it gives the polar grid, UPS (see +[Coordinate readouts](#coordinate-readouts)). On the map of another body than the Earth it shows +and copies the latitude and longitude, and its hover text says why. Below it, **Copy As GeoJSON** copies the place as a point feature, **Center Map Here** and **Zoom In Here** move the view, and **Directions To Here** and **Directions From Here** open the [Directions](#directions) pane. **Quick Analysis** runs a tool at the place: a buffer of 500 m, 1 km or 5 km (¼, 1 or 5 miles when the Directions pane is set @@ -158,10 +158,15 @@ UTM states the hemisphere, as GeographicLib's `GeoConvert -u -l` writes it, not in plain UTM a letter after the zone is commonly read as the hemisphere, so `38S` (band S, 32° N to 40° N) would be taken for the southern hemisphere, 10,000 km away. Latitude bands are MGRS's. UTM and MGRS are on WGS 84, with the zone exceptions for southern Norway (32V) and Svalbard (31X, -33X, 35X and 37X), and cover 80° S to 84° N. Nearer the poles they would need the Universal Polar -Stereographic grid, which RustGIS doesn't have: there the readout shows *No UTM here* (or -*No MGRS here*) rather than a wrong reference, and so it does on the map of another body than -the Earth, where degrees still read. Scripts set the format with +33X, 35X and 37X), and cover 80° S up to 84° N. North of 84° N and south of 80° S the readouts +use the Universal Polar Stereographic grid (UPS), as NGA defines it (NGA.SIG.0012): the UTM +readout gives the zone spelled out and the easting and northing, `north 2077146 1562481`, as +GeographicLib writes it, and the MGRS readout gives the polar reference, which has no zone +number: a letter for the half (Y west and Z east of the 0° and 180° meridians in the north, A +and B in the south), the 100 km square and the digits, `Z AC 77146 62481`. 84° N itself is +UPS, 80° S itself is UTM. Search reads both, along with `ZAC7714662481` and the form +`Z 2077146 1562481`. On the map of another body than the Earth the readout shows *No UTM here* +(or *No MGRS here*) rather than a wrong reference, and degrees still read. Scripts set the format with `ui.coordinateFormat={"format":"utm"}` (`decimal`, `dms`, `utm` or `mgrs`); without `format` it steps to the next one. A saved format this version doesn't know, say from a newer RustGIS, reads as decimal degrees with a notice, and stays saved until you pick a format. From bdd7ad3070d048c354d871593f94bef3655bed79 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:22:14 -0600 Subject: [PATCH 02/14] fix(geom): tell polar grid references from words MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fixes for the UPS change: - parse_mgrs checks the polar letter (A, B, Y, Z) first, so "Elm 123" is text, not a digit-count error. - A polar 100 km square written as one word with no digits right after it is read only in capitals (ZAH, ZAH 12345 12345); "Bay 12", "Zoo 12" and "zap" stay text. Spaced (Z AH) or with digits attached it reads in any case, so a copied 100 km square pastes back into search. - parse_ups treats numbers outside the zone's lettered area (NGA.SIG.0012 §§11.10-11.11) as text, so "A 10 20" or "A1 12" give no grid error. - Search no longer filters digitless text itself; the parser decides. - Doc fixes in mapmenu.rs and on Mgrs's zone 0. --- crates/engine/src/cmd/search.rs | 36 +++++++++++++--- crates/geom/src/ups.rs | 10 +++++ crates/geom/src/utm.rs | 73 +++++++++++++++++++++++++-------- crates/ui-egui/src/mapmenu.rs | 6 +-- 4 files changed, 100 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index b38a497a3d..8d434280bc 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -154,15 +154,13 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // zone and band) isn't looked for in the tables; two whole numbers (an id, years, a range) // may be either, and so may a bare 100 km MGRS square, which names Sentinel-2's tiles (33UVP); // an MGRS reference with digits is plainly a coordinate. UTM and MGRS are the Earth's grids, - // so on another body's map they name no place. A polar (UPS) reference starts with a letter - // and has no zone number, so without digits it is three letters (BAN, ZAP), as often a word - // as a place: text with no digit isn't read as a grid reference (every other one has digits). + // so on another body's map they name no place. Polar (UPS) references have no zone number; + // the parser tells them from words (`ZAH` and `Z AH` are references, `Bay 12` and `zap` text). let mut plainly_coordinate = false; - let grid_text = q.chars().any(|c| c.is_ascii_digit()); if let Some(c) = parse_lat_lon(&q) { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); - } else if map.body().is_earth() && grid_text { + } else if map.body().is_earth() { match read_grid_reference(&q) { Ok(c) => { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); @@ -815,11 +813,37 @@ mod tests { Some(Hit::Coordinate { lon, lat }) => assert!(*lon < 0.0 && *lat > 86.0, "{lon} {lat}"), other => panic!("{other:?}"), } - for q in ["BAN", "ZAP", "Box", "Berlin", "Bay", "Zanzibar", "Y", "ZAH"] { + // Words and street names, with or without numbers, are text: no coordinate, no grid error. + for q in [ + "Bay 12", + "Ban 12", + "Bad 34", + "Zag 56", + "Ave 12", + "Zoo 12", + "Elm 123", + "A 10 20", + "A1 12", + "B 12, 34", + "zap", + "ban", + "Box", + "Berlin", + "Bay", + "Zanzibar", + "Y", + "north 10 20", + ] { let r = search(&s, q, 50); assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); assert_eq!(r.grid_error, None, "{q}"); } + // A 100 km polar square in capitals, as MGRS writes it, or spaced, reads back; like + // `33UVP` it may also be a name, so the tables are still searched. + for q in ["ZAH", "Z AH", "z ah", "BAN"] { + let r = search(&s, q, 50); + assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })), "{q}: {r:?}"); + } // A polar reference that names no place says why. assert_eq!(search(&s, "ZDA1234512345", 50).grid_error, Some(GridError::Square)); assert_eq!(search(&s, "YRA1234512345", 50).grid_error, Some(GridError::OutsideZone)); diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs index c87763adab..92ce0a1c87 100644 --- a/crates/geom/src/ups.rs +++ b/crates/geom/src/ups.rs @@ -251,6 +251,16 @@ pub(crate) fn easting_in_half(half: char, easting: f64) -> bool { } } +/// Whether an easting and northing lie in their zone's lettered area, where every UPS position +/// in the zone falls: 1,300,000 m up to 2,700,000 m in the north, 800,000 m up to 3,200,000 m in +/// the south, along both axes (NGA.SIG.0012 §§11.10 and 11.11). Numbers outside it aren't a UPS +/// position at all. +pub(crate) fn in_lettered_area(north: bool, easting: f64, northing: f64) -> bool { + let first = (if north { NORTH_FIRST } else { SOUTH_FIRST }) as f64 * SQUARE; + let span = first..(2.0 * FALSE_ORIGIN - first); + span.contains(&easting) && span.contains(&northing) +} + /// Whether a letter names a polar half of MGRS. pub(crate) fn is_polar_half(letter: char) -> bool { matches!(letter, 'A' | 'B' | 'Y' | 'Z') diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index 85154b8d50..8a501a9924 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -321,8 +321,11 @@ pub fn format_utm(c: Coord) -> Option { /// An MGRS reference: zone, band, the 100 km square's column and row letters, and the easting /// and northing within the square truncated to `digits` digits each (0–5: 100 km to 1 m). In the -/// polar areas (UPS) the zone is 0, as MGRS writes no zone number there, and the band is the -/// half's letter: Y or Z north of 84° N, A or B south of 80° S. +/// polar areas (UPS) the zone is 0, as MGRS writes no zone number there (and as GeographicLib's +/// UTMUPS numbers UPS), and the band is the half's letter: Y or Z north of 84° N, A or B south of +/// 80° S; [`Mgrs::polar`] tells them apart. Zone 0 is never a UTM zone, so code that turns a zone +/// into an EPSG code (326zz, 327zz) must check [`Mgrs::polar`] first; [`Mgrs::centre`] refuses a +/// polar letter with a UTM zone and a UTM band with zone 0. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Mgrs { pub zone: u8, @@ -608,8 +611,10 @@ fn easting_and_northing(text: &str) -> Result<(f64, f64), GridError> { /// Reads a UPS position, which has no zone number: the zone spelled out, `north 2392768 1607232` /// or `south 2096454 1452981` (any case), as the readout writes it, or the polar half's letter /// before the easting and northing, `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and -/// A lie west of the 2,000,000 m easting and Z and B on or east of it. The place must lie in the -/// zone, at 84° N or more or south of 80° S, give or take the meter it was rounded to. +/// A lie west of the 2,000,000 m easting and Z and B on or east of it. Numbers outside the zone's +/// lettered area (north 1,300,000 up to 2,700,000 m, south 800,000 up to 3,200,000 m) aren't a UPS +/// position and read as text ([`GridError::Syntax`]); a place inside it must lie in the zone, at +/// 84° N or more or south of 80° S, give or take the meter it was rounded to. pub fn parse_ups(text: &str) -> Result { let text = text.trim(); if text.chars().count() > MAX_REF_CHARS { @@ -629,6 +634,10 @@ pub fn parse_ups(text: &str) -> Result { }; let rest: String = chars.collect(); let (easting, northing) = easting_and_northing(&rest)?; + // Numbers outside the zone's lettered area aren't a UPS position (`A 10 20`, a road): text. + if !crate::ups::in_lettered_area(north, easting, northing) { + return Err(GridError::Syntax); + } if half.is_some_and(|h| !crate::ups::easting_in_half(h, easting)) { return Err(GridError::OutsideZone); } @@ -683,17 +692,40 @@ pub fn parse_mgrs(text: &str) -> Result { } let mut chars = text.chars().peekable(); let polar = chars.peek().is_some_and(char::is_ascii_alphabetic); - let (zone, band) = - if polar { (0, chars.next().map(|c| c.to_ascii_uppercase()).ok_or(GridError::Syntax)?) } else { zone_and_letter(&mut chars)? }; - let mut letters = [' '; 2]; - for l in letters.iter_mut() { - while chars.next_if(|c| c.is_whitespace()).is_some() {} - *l = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?.to_ascii_uppercase(); + let (zone, band) = if polar { + // Only the polar halves' letters start a reference: `Elm 123` or `Main` is text. + let half = chars.next().map(|c| c.to_ascii_uppercase()).ok_or(GridError::Syntax)?; + if !crate::ups::is_polar_half(half) { + return Err(GridError::Syntax); + } + (0, half) + } else { + zone_and_letter(&mut chars)? + }; + let mut spaced = false; + let mut typed = [' '; 2]; + for l in typed.iter_mut() { + while chars.next_if(|c| c.is_whitespace()).is_some() { + spaced = true; + } + *l = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?; } + let letters = typed.map(|c| c.to_ascii_uppercase()); + let digits_attached = chars.peek().is_some_and(char::is_ascii_digit); let rest: String = chars.collect(); if rest.chars().any(|c| !c.is_ascii_digit() && !c.is_whitespace()) { return Err(GridError::Syntax); } + // A polar reference written as one word of three letters, with no digits right after it, is + // as often a word (`Bay 12`, `zap`): it is read only in capitals, as MGRS writes it (`ZAH`, + // `ZAH 12345 12345`). Spaced (`Z AH`) or with its digits attached (`zah1234512345`), it is + // plainly a reference in any case. + if polar && !spaced && !digits_attached { + let first = text.chars().next().unwrap_or(' '); + if !(first.is_ascii_uppercase() && typed.iter().all(char::is_ascii_uppercase)) { + return Err(GridError::Syntax); + } + } let groups: Vec<&str> = rest.split_whitespace().collect(); let (e, n) = match groups.as_slice() { [] => ("", ""), @@ -712,10 +744,6 @@ pub fn parse_mgrs(text: &str) -> Result { _ => return Err(GridError::Digits), }; let band = if polar { - // Only the polar halves' letters start a reference: `CAT` or `Main` is text. - if !crate::ups::is_polar_half(band) { - return Err(GridError::Syntax); - } band } else { // The zone first, as `parse_utm` does: `0AAA` names a bad zone, not a polar reference. @@ -1562,6 +1590,15 @@ mod tests { for text in ["CAT", "Main", "Berlin 12", "Z", "zap road"] { assert_eq!(parse_mgrs(text), Err(GridError::Syntax), "{text}"); } + // A three-letter word before a number is text, not a polar square (`Bay 12` would be B AY + // in the south), and so is any word whose first letter isn't a polar half (`Elm 123`). + for text in ["Bay 12", "Ban 12", "Bad 34", "Zag 56", "Ave 12", "Zoo 12", "bay 12", "zap", "Elm 123", "Elm"] { + assert_eq!(parse_mgrs(text), Err(GridError::Syntax), "{text}"); + } + // In capitals, spaced, or with the digits attached, it is a reference. + for text in ["BAY 12", "B AY 12", "bay12", "Z AH", "z ah", "ZAH", "ZAH 12345 12345"] { + assert!(parse_mgrs(text).is_ok(), "{text}"); + } } /// UPS positions: the readout's `north …`/`south …` and NGA.STND.0037 App. A-4's @@ -1580,8 +1617,12 @@ mod tests { for (text, why) in [ ("Y 2392768 1607232", GridError::OutsideZone), // east of 2,000,000 m is Z ("A 2096454 1452981", GridError::OutsideZone), // east of 2,000,000 m is B - ("north 2000000 100000", GridError::OutsideZone), // south of 84° N - ("south 2000000 3500000", GridError::OutsideZone), // north of 80° S + ("north 2000000 1300000", GridError::OutsideZone), // lettered, but south of 84° N + ("south 2000000 3150000", GridError::OutsideZone), // lettered, but north of 80° S + ("north 2000000 100000", GridError::Syntax), // outside the lettered area + ("A 10 20", GridError::Syntax), + ("A1 12", GridError::Syntax), + ("B 12, 34", GridError::Syntax), ("north 2000000", GridError::Syntax), ("north -1 2000000", GridError::Syntax), ("Q 2000000 2000000", GridError::Syntax), diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index bf0c6ec583..ad38b3dc81 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -52,9 +52,9 @@ fn lat_lon(c: Coord) -> String { } /// The coordinate row: the text it shows and copies, in the readout's format, and whether it fell -/// back from it. Decimal degrees are `lat, lon` ([`lat_lon`]); north of 84° N or south of 80° S, -/// and on another body's map (`earth` false), UTM and MGRS fall back to them (and the row's hover -/// text says why). +/// back from it. Decimal degrees are `lat, lon` ([`lat_lon`]); north of 84° N and south of 80° S +/// UTM and MGRS give UPS (`north …`, `Z …`); on another body's map (`earth` false) they fall back +/// to latitude and longitude (and the row's hover text says why). fn coordinate_row(c: Coord, f: CoordReadout, earth: bool) -> (String, bool) { match f { CoordReadout::Decimal => (lat_lon(c), false), From cbe6ef618164bb3d2e4e475790b5e68eae75d021 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:15:15 -0600 Subject: [PATCH 03/14] fix(geom): keep codes like ATL as text, and other review fixes Three capital letters starting with A, B, Y or Z (ATL, AUS, YUL, BBC) were read as a polar 100 km square, so search went to Antarctica. A polar reference now needs a space after the half's letter (Z AH, as the readout writes it), digits attached (ZAH1234512345), or two equal digit groups (ZFD 92767 07232). Anything else is a word, in any case. Also: the Polar message's two examples now name the same place, a full UPS coordinate rounded onto the 0/180 line is accepted for Y and A, parse_ups needs a space or comma after its word, the readout no longer builds an extra string per frame, parse_ups is reachable from ups, and the user guide covers polar search and the Y/Z split. --- crates/data/tests/ups_vs_proj.rs | 2 +- crates/engine/src/cmd/search.rs | 13 ++- crates/geom/src/lib.rs | 2 +- crates/geom/src/ups.rs | 27 +++++-- crates/geom/src/utm.rs | 135 ++++++++++++++++++++----------- crates/ui-egui/src/searchbox.rs | 2 +- docs/user-guide/maps.md | 19 +++-- 7 files changed, 136 insertions(+), 64 deletions(-) diff --git a/crates/data/tests/ups_vs_proj.rs b/crates/data/tests/ups_vs_proj.rs index daad747eb2..491782e336 100644 --- a/crates/data/tests/ups_vs_proj.rs +++ b/crates/data/tests/ups_vs_proj.rs @@ -45,7 +45,7 @@ fn random_polar_places_agree_with_proj4rs() { for _ in 0..5_000 { let lon = -180.0 + r.next() * 360.0; worst = worst.max(compare(&north_t, Coord::new(lon, 84.0 + r.next() * 6.0), true)); - worst = worst.max(compare(&south_t, Coord::new(lon, -80.0 - 1e-9 - r.next() * 10.0), false)); + worst = worst.max(compare(&south_t, Coord::new(lon, -80.0 - 1e-9 - r.next() * (10.0 - 2e-9)), false)); } for (p, north) in [(Coord::new(0.0, 90.0), true), (Coord::new(0.0, -90.0), false), (Coord::new(180.0, 84.0), true)] { worst = worst.max(compare(if north { &north_t } else { &south_t }, p, north)); diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 8d434280bc..a981a3e329 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -833,14 +833,23 @@ mod tests { "Zanzibar", "Y", "north 10 20", + // Codes and acronyms in capitals: airports, not polar squares. + "ATL", + "AUS", + "YUL", + "BBC", + "ABC", + "BRU", + "ZAH", + "BAN", ] { let r = search(&s, q, 50); assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); assert_eq!(r.grid_error, None, "{q}"); } - // A 100 km polar square in capitals, as MGRS writes it, or spaced, reads back; like + // A 100 km polar square written as the readout writes it, spaced, reads back; like // `33UVP` it may also be a name, so the tables are still searched. - for q in ["ZAH", "Z AH", "z ah", "BAN"] { + for q in ["Z AH", "z ah", "B AN"] { let r = search(&s, q, 50); assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })), "{q}: {r:?}"); } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 48926c19ba..cc6c5cec7c 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -1,5 +1,5 @@ //! L0: coordinates, extents, the Web Mercator projection, geodesic measurement, map scale, and -//! UTM and MGRS coordinates ([`utm`]). +//! UTM and MGRS coordinates ([`utm`]), and UPS for the polar areas ([`ups`]). //! //! Everything here is plain math with no I/O. Longitude/latitude are WGS 84 degrees; projected //! coordinates are Web Mercator meters (EPSG:3857), which [`lonlat_to_plane`] continues beyond diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs index 92ce0a1c87..8c38f15627 100644 --- a/crates/geom/src/ups.rs +++ b/crates/geom/src/ups.rs @@ -13,9 +13,11 @@ //! - north UPS for latitudes of 84° N and more, south UPS for latitudes south of 80° S (§10.4): //! 84° N itself is UPS, 80° S itself is UTM; //! - MGRS in the polar areas (§§11.9–11.13, and NGA.STND.0037 §3-2c): no zone number, a letter for -//! the half (Y west and Z east in the north, A west and B east in the south; the 0° and 180° -//! meridians, at an easting of 2,000,000 m, are Z and B), then the 100 km square's column and -//! row letters, and the digits truncated to the precision. +//! the half (Y for western longitudes and Z for eastern ones in the north, A and B in the +//! south; the 0° and 180° meridians, at an easting of 2,000,000 m, are Z and B, by §§11.10 and +//! 11.11, where square 20 is ZA and BA), then the 100 km square's column and row letters, and +//! the digits truncated to the precision. A 100 km square alone is written spaced, `Z AH` +//! ([`crate::utm::parse_mgrs`] reads three letters alone as a word). //! //! The conformal latitude is the one in [`crate::utm`] (Karney 2011, eqs. 7–9 and 19–21), which //! gives the same values as §2.8 and §2.9's PhiToChi and ChiToPhi. @@ -24,6 +26,9 @@ use std::fmt; use std::sync::LazyLock; use crate::Coord; +/// Reads a UPS position (`north 2392768 1607232`, `Y, 1735147, 2243078`); it lives with the UTM +/// parser, which hands polar text to it. +pub use crate::utm::parse_ups; use crate::utm::{GridError, conformal_tan, eccentricity, geographic_tan, wgs84_a, wrap}; /// The northern limit of the UTM zones, where north UPS begins (degrees); 84° N itself is UPS. @@ -241,11 +246,14 @@ pub(crate) fn cell_reaches_zone(north: bool, e0: f64, n0: f64, cell: f64, slop_d } } -/// Whether an easting lies in a polar half's side of its zone: Y and A west of the 2,000,000 m -/// easting, Z and B on it and east of it (NGA.STND.0037 App. B-5b). +/// Whether a typed easting lies in a polar half's side of its zone: Y and A west of the +/// 2,000,000 m easting, Z and B on it and east of it (NGA.STND.0037 App. B-5b; the line itself +/// is Z and B by NGA.SIG.0012 §§11.10 and 11.11, where square 20 is ZA and BA). Full +/// coordinates are written rounded to the meter (NGA.STND.0037 App. A-2), so a place in Y or A +/// just west of the line may read 2,000,000: Y and A accept it, within half a meter. pub(crate) fn easting_in_half(half: char, easting: f64) -> bool { match half { - 'Y' | 'A' => easting < FALSE_ORIGIN, + 'Y' | 'A' => easting < FALSE_ORIGIN + 0.5, 'Z' | 'B' => easting >= FALSE_ORIGIN, _ => false, } @@ -370,8 +378,11 @@ mod tests { assert_eq!(x, FALSE_ORIGIN, "{lon} {lat}"); } } - assert!(easting_in_half('Z', FALSE_ORIGIN) && !easting_in_half('Y', FALSE_ORIGIN)); - assert!(easting_in_half('B', FALSE_ORIGIN) && !easting_in_half('A', FALSE_ORIGIN)); + assert!(easting_in_half('Z', FALSE_ORIGIN) && !easting_in_half('Z', FALSE_ORIGIN - 0.1)); + assert!(easting_in_half('B', FALSE_ORIGIN) && !easting_in_half('B', FALSE_ORIGIN - 0.1)); + // A typed full coordinate is rounded: Y and A take the line within half a meter. + assert!(easting_in_half('Y', FALSE_ORIGIN) && !easting_in_half('Y', FALSE_ORIGIN + 0.5)); + assert!(easting_in_half('A', FALSE_ORIGIN) && !easting_in_half('A', FALSE_ORIGIN + 1.0)); } #[test] diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index 8a501a9924..b8bc6aafcf 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -348,14 +348,24 @@ impl Mgrs { self.zone == 0 } - /// The zone and band as MGRS writes them: `33U`, `04Q`, or the polar half's letter alone (`Z`). - fn designator(&self) -> String { - if self.polar() { self.band.to_string() } else { format!("{:02}{}", self.zone, self.band) } + /// Writes the zone and band as MGRS writes them: `33U`, `04Q`, or the polar half's letter alone + /// (`Z`), without building a string (the readout writes a reference every frame). + fn write_designator(&self, f: &mut impl fmt::Write) -> fmt::Result { + if self.polar() { write!(f, "{}", self.band) } else { write!(f, "{:02}{}", self.zone, self.band) } } - /// Without spaces: `33UVP1234523456`, `04QFJ12345678`, `ZFD9276707232`. + /// Without spaces: `33UVP1234523456`, `04QFJ12345678`, `ZFD9276707232`. A polar 100 km square + /// alone (`ZAH`) reads back only spaced (`Z AH`, the `Display` form; see [`parse_mgrs`]). pub fn compact(&self) -> String { - format!("{}{}{}{}", self.designator(), self.column, self.row, self.digit_groups().concat()) + let mut out = String::with_capacity(15); + // Writing to a String can't fail. + let _ = self.write_designator(&mut out); + out.push(self.column); + out.push(self.row); + for group in self.digit_groups() { + out.push_str(&group); + } + out } /// The easting and northing digits, zero-padded to the precision (empty for 100 km). @@ -377,7 +387,8 @@ impl fmt::Display for Mgrs { /// `33U VP 12345 23456` (the readout's form; `33U VP` at 100 km; `04Q FJ …` in zones 1–9; /// `Z FD 92767 07232` in the polar areas). fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} {}{}", self.designator(), self.column, self.row)?; + self.write_designator(f)?; + write!(f, " {}{}", self.column, self.row)?; let [e, n] = self.digit_groups(); if !e.is_empty() { write!(f, " {e} {n}")?; @@ -474,7 +485,7 @@ impl fmt::Display for GridError { GridError::Zone => "the UTM zone must be 1 to 60", GridError::Band => "the latitude band must be a letter from C to X (not I or O)", GridError::Polar => { - "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268 or Z AM 00775 44267" + "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268 or Z AM 00000 44268" } GridError::Square => "the 100 km square letters aren't used in this zone", GridError::Digits => "the grid digits must be an even count of 0 to 10, half for the easting and half for the northing", @@ -632,6 +643,10 @@ pub fn parse_ups(text: &str) -> Result { "A" | "B" => (false, word.chars().next()), _ => return Err(GridError::Syntax), }; + // A space or comma after the word or letter: `north2000000 …` isn't written that way. + if !chars.peek().is_some_and(|c| c.is_whitespace() || *c == ',') { + return Err(GridError::Syntax); + } let rest: String = chars.collect(); let (easting, northing) = easting_and_northing(&rest)?; // Numbers outside the zone's lettered area aren't a UPS position (`A 10 20`, a road): text. @@ -683,8 +698,11 @@ fn band_letter(letter: char) -> Result { /// /// In the polar areas MGRS writes no zone number (NGA.SIG.0012 §§11.9 and 11.13): the half's /// letter (Y or Z north, A or B south), the square's letters, then the digits, as -/// `ZFD9276707232` or `Z FD 92767 07232`. A polar letter after a zone number (`38ZMB`) is refused -/// with [`GridError::Polar`]; text that starts with any other letter isn't a reference. +/// `ZFD9276707232` or `Z FD 92767 07232`. It must have a space after the half's letter or its +/// digits attached to the letters: three letters alone (`ATL`, `Bay 12`) are a word, so a 100 km +/// polar square is read spaced, `Z AH`, as the readout writes it. A polar letter after a zone +/// number (`38ZMB`) is refused with [`GridError::Polar`]; text that starts with any other letter +/// isn't a reference. pub fn parse_mgrs(text: &str) -> Result { let text = text.trim(); if text.chars().count() > MAX_REF_CHARS { @@ -702,31 +720,28 @@ pub fn parse_mgrs(text: &str) -> Result { } else { zone_and_letter(&mut chars)? }; - let mut spaced = false; - let mut typed = [' '; 2]; - for l in typed.iter_mut() { - while chars.next_if(|c| c.is_whitespace()).is_some() { - spaced = true; - } - *l = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?; + // Whether a space follows the zone and band (or the polar half's letter). + let spaced = chars.peek().is_some_and(|c| c.is_whitespace()); + let mut letters = [' '; 2]; + for l in letters.iter_mut() { + while chars.next_if(|c| c.is_whitespace()).is_some() {} + *l = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?.to_ascii_uppercase(); } - let letters = typed.map(|c| c.to_ascii_uppercase()); let digits_attached = chars.peek().is_some_and(char::is_ascii_digit); let rest: String = chars.collect(); if rest.chars().any(|c| !c.is_ascii_digit() && !c.is_whitespace()) { return Err(GridError::Syntax); } - // A polar reference written as one word of three letters, with no digits right after it, is - // as often a word (`Bay 12`, `zap`): it is read only in capitals, as MGRS writes it (`ZAH`, - // `ZAH 12345 12345`). Spaced (`Z AH`) or with its digits attached (`zah1234512345`), it is - // plainly a reference in any case. - if polar && !spaced && !digits_attached { - let first = text.chars().next().unwrap_or(' '); - if !(first.is_ascii_uppercase() && typed.iter().all(char::is_ascii_uppercase)) { - return Err(GridError::Syntax); - } - } let groups: Vec<&str> = rest.split_whitespace().collect(); + // A polar reference written as one word of three letters is as often a word or a code + // (`Bay 12`, `ATL`, `YUL`): it is text, unless its digits are attached (`ZAH1234512345`, + // MGRS's compact form) or follow as two equal groups of 2 to 5 (`ZFD 92767 07232`). Spaced + // after the half's letter (`Z AH`, `Z AH 12345 12345`, as the readout writes it) it is a + // reference in any form. Case doesn't matter. + let two_groups = matches!(groups.as_slice(), [e, n] if e.len() == n.len() && (2..=5).contains(&e.len())); + if polar && !spaced && !digits_attached && !two_groups { + return Err(GridError::Syntax); + } let (e, n) = match groups.as_slice() { [] => ("", ""), [one] => { @@ -1572,31 +1587,61 @@ mod tests { #[test] fn polar_references_that_name_no_place_are_refused() { for (text, why) in [ - ("ZDA", GridError::Square), // Z skips D and E - ("YAA", GridError::Square), // Y starts at R - ("BAI", GridError::Square), // no I - ("YRA", GridError::OutsideZone), // the north lettering's corner lies south of 84° N - ("AJA", GridError::OutsideZone), // the south lettering's corner lies north of 80° S + ("Z DA", GridError::Square), // Z skips D and E + ("Y AA", GridError::Square), // Y starts at R + ("B AI", GridError::Square), // no I + ("ZDA12", GridError::Square), // attached digits read as a reference too + ("Y RA", GridError::OutsideZone), // the north lettering's corner lies south of 84° N + ("A JA", GridError::OutsideZone), // the south lettering's corner lies north of 80° S ("ZAH123", GridError::Digits), - ("ZAH 123 45", GridError::Digits), + ("Z AH 123 45", GridError::Digits), ("38ZMB", GridError::Polar), // a polar letter after a zone number ] { assert_eq!(parse_mgrs(text), Err(why), "{text}"); } - // Text starting with any other letter, or words, aren't references. - for text in ["CAT", "Main", "Berlin 12", "Z", "ZA", "BOX", "zap road"] { - assert!(matches!(parse_mgrs(text), Err(GridError::Syntax | GridError::Square)), "{text}"); - } - for text in ["CAT", "Main", "Berlin 12", "Z", "zap road"] { - assert_eq!(parse_mgrs(text), Err(GridError::Syntax), "{text}"); - } - // A three-letter word before a number is text, not a polar square (`Bay 12` would be B AY - // in the south), and so is any word whose first letter isn't a polar half (`Elm 123`). - for text in ["Bay 12", "Ban 12", "Bad 34", "Zag 56", "Ave 12", "Zoo 12", "bay 12", "zap", "Elm 123", "Elm"] { + // Three letters alone, before a number or not, are a word or a code (`Bay 12` would be + // B AY in the south, `ATL` A TL), in any case; so is any text whose first letter isn't a + // polar half (`Elm 123`). + for text in [ + "CAT", + "Main", + "Berlin 12", + "Z", + "ZA", + "BOX", + "zap road", + "Bay 12", + "BAY 12", + "Ban 12", + "Bad 34", + "Zag 56", + "Ave 12", + "Zoo 12", + "bay 12", + "zap", + "ZAP", + "ZAH", + "ATL", + "AUS", + "YUL", + "BBC", + "ABC", + "BRU", + "BCN", + "BKK", + "ZAG", + "AMS", + "YYZ", + "Elm 123", + "Elm", + "BA Y 12", + "ZAH 1 2", + ] { assert_eq!(parse_mgrs(text), Err(GridError::Syntax), "{text}"); } - // In capitals, spaced, or with the digits attached, it is a reference. - for text in ["BAY 12", "B AY 12", "bay12", "Z AH", "z ah", "ZAH", "ZAH 12345 12345"] { + // Spaced after the half's letter, with the digits attached, or with two equal groups of + // digits, it is a reference. + for text in ["B AY 12", "bay12", "Z AH", "z ah", "Z AH 12345 12345", "ZAH1234512345", "ZFD 92767 07232", "zfd 92 07"] { assert!(parse_mgrs(text).is_ok(), "{text}"); } } diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index 38a41be571..b971d8437b 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -387,7 +387,7 @@ fn grid_error_text(e: rustgis_engine::geom::GridError) -> String { G::Zone => tl_raw!("the UTM zone must be 1 to 60"), G::Band => tl_raw!("the latitude band must be a letter from C to X (not I or O)"), G::Polar => tl_raw!( - "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268 or Z AM 00775 44267" + "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268 or Z AM 00000 44268" ), G::Square => tl_raw!("the 100 km square letters aren't used in this zone"), G::Digits => tl_raw!("the grid digits must be an even count of 0 to 10, half for the easting and half for the northing"), diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 46efbac374..5fac368100 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -160,12 +160,12 @@ to 40° N) would be taken for the southern hemisphere, 10,000 km away. Latitude UTM and MGRS are on WGS 84, with the zone exceptions for southern Norway (32V) and Svalbard (31X, 33X, 35X and 37X), and cover 80° S up to 84° N. North of 84° N and south of 80° S the readouts use the Universal Polar Stereographic grid (UPS), as NGA defines it (NGA.SIG.0012): the UTM -readout gives the zone spelled out and the easting and northing, `north 2077146 1562481`, as -GeographicLib writes it, and the MGRS readout gives the polar reference, which has no zone -number: a letter for the half (Y west and Z east of the 0° and 180° meridians in the north, A -and B in the south), the 100 km square and the digits, `Z AC 77146 62481`. 84° N itself is -UPS, 80° S itself is UTM. Search reads both, along with `ZAC7714662481` and the form -`Z 2077146 1562481`. On the map of another body than the Earth the readout shows *No UTM here* +readout gives the zone spelled out and the easting and northing rounded to the meter, +`north 2077146 1562481`, as GeographicLib writes it, and the MGRS readout gives the polar +reference, which has no zone number: a letter for the half (Y for western longitudes and Z for +eastern ones in the north, A and B in the south, with the 0° and 180° meridians in Z and B), +the 100 km square and the digits, truncated, `Z AC 77146 62481`. 84° N itself is UPS, 80° S +itself is UTM. On the map of another body than the Earth the readout shows *No UTM here* (or *No MGRS here*) rather than a wrong reference, and degrees still read. Scripts set the format with `ui.coordinateFormat={"format":"utm"}` (`decimal`, `dms`, `utm` or `mgrs`); without `format` it steps to the next one. A saved format this version doesn't know, say from a newer RustGIS, @@ -186,6 +186,13 @@ The [search box](#navigating) takes the same grid references, in any case: `S` after the zone is always band S (32° N to 40° N), as in `11S 384629 3768405` (Los Angeles); with a northing outside band S it could mean the southern hemisphere, so it finds nothing: write `south` instead. +- **UPS and polar MGRS**, north of 84° N and south of 80° S, which have no zone number: UPS as + the readout writes it, `north 2077146 1562481` or `south 2096454 1452981`, or with the half's + letter, `Z 2077146 1562481` or `Y, 1735147, 2243078`; polar MGRS as `ZAC7714662481`, + `Z AC 77146 62481` or `ZAC 77146 62481`. Three letters alone, or before a single number, are + read as a word (`ATL`, `Bay 12`), so a 100 km polar square alone is written spaced, `Z AC`, + as the readout writes it. A UTM zone's position past 84° N or 80° S, or a polar letter after a + zone number (`38ZMB`), finds nothing and the list says how UPS is written. A reference that doesn't exist (square letters the zone doesn't use, a northing or a square outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a From 662a57ca68f62c86ca59e1a522f4e2d65e0bc36b Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:34:34 -0600 Subject: [PATCH 04/14] fix(geom): read one-word polar references only with six digits Codes with a few digits (BAW1234, BAN12, Bay 12 34, Apt 12 14) were still read as polar references, and with digits search skipped the tables. A polar reference written as one word now needs at least six digits (100 m or finer), as references are written; spaced after the half's letter any precision reads, and a 100 km square alone needs capitals (Z AH, not Z Ah). ZAC 7714662481 now reads too. Also moves parse_ups into ups.rs, shares the zone check and the lettering tables, uses is_polar_half everywhere, and only lets Y and A take the 0/180 line itself. --- crates/engine/src/cmd/search.rs | 12 +++- crates/geom/src/lib.rs | 4 +- crates/geom/src/ups.rs | 72 +++++++++++++++---- crates/geom/src/utm.rs | 120 ++++++++++++++------------------ docs/user-guide/maps.md | 8 ++- 5 files changed, 128 insertions(+), 88 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index a981a3e329..9186de8b41 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -155,7 +155,7 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // may be either, and so may a bare 100 km MGRS square, which names Sentinel-2's tiles (33UVP); // an MGRS reference with digits is plainly a coordinate. UTM and MGRS are the Earth's grids, // so on another body's map they name no place. Polar (UPS) references have no zone number; - // the parser tells them from words (`ZAH` and `Z AH` are references, `Bay 12` and `zap` text). + // the parser tells them from words (`Z AH` and `ZAH1234512345` are references; `ZAH`, `ATL`, `BAW1234` and `Bay 12` are text). let mut plainly_coordinate = false; if let Some(c) = parse_lat_lon(&q) { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); @@ -833,6 +833,14 @@ mod tests { "Zanzibar", "Y", "north 10 20", + "BAW1234", + "YUL1234", + "BAN12", + "Bay 12 34", + "Apt 12 14", + "Z Ah", + "B Ag", + "z ah", // Codes and acronyms in capitals: airports, not polar squares. "ATL", "AUS", @@ -849,7 +857,7 @@ mod tests { } // A 100 km polar square written as the readout writes it, spaced, reads back; like // `33UVP` it may also be a name, so the tables are still searched. - for q in ["Z AH", "z ah", "B AN"] { + for q in ["Z AH", "B AN"] { let r = search(&s, q, 50); assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })), "{q}: {r:?}"); } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index cc6c5cec7c..7df40deeff 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -16,8 +16,8 @@ pub mod utm; pub use body::{BODIES, Body}; pub use eqc::EquidistantCylindrical; pub use sinusoidal::Sinusoidal; -pub use ups::{Ups, format_ups, from_ups, to_ups}; -pub use utm::{GridError, Mgrs, Utm, format_mgrs, format_utm, parse_mgrs, parse_ups, parse_utm, to_mgrs, to_utm}; +pub use ups::{Ups, format_ups, from_ups, parse_ups, to_ups}; +pub use utm::{GridError, Mgrs, Utm, format_mgrs, format_utm, parse_mgrs, parse_utm, to_mgrs, to_utm}; use std::sync::LazyLock; diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs index 8c38f15627..229d605d4d 100644 --- a/crates/geom/src/ups.rs +++ b/crates/geom/src/ups.rs @@ -26,10 +26,9 @@ use std::fmt; use std::sync::LazyLock; use crate::Coord; -/// Reads a UPS position (`north 2392768 1607232`, `Y, 1735147, 2243078`); it lives with the UTM -/// parser, which hands polar text to it. -pub use crate::utm::parse_ups; -use crate::utm::{GridError, conformal_tan, eccentricity, geographic_tan, wgs84_a, wrap}; +use crate::utm::{ + GridError, MAX_REF_CHARS, ROUNDING_DEG, conformal_tan, easting_and_northing, eccentricity, geographic_tan, wgs84_a, wrap, +}; /// The northern limit of the UTM zones, where north UPS begins (degrees); 84° N itself is UPS. pub const UPS_NORTH_FROM: f64 = 84.0; @@ -204,13 +203,18 @@ pub fn format_ups(c: Coord) -> Option { to_ups(c).map(|u| u.to_string()) } +/// A zone's lettering: its column letter pairs, its row letters, and the index of its first +/// 100 km square along either axis (NGA.SIG.0012 §§11.10 and 11.11). +fn lettering(north: bool) -> (&'static [&'static [u8; 2]], &'static [u8], i64) { + if north { (&NORTH_COLUMNS, NORTH_ROWS, NORTH_FIRST) } else { (&SOUTH_COLUMNS, SOUTH_ROWS, SOUTH_FIRST) } +} + /// The MGRS letters of the 100 km square holding a UPS easting and northing (whole meters): the /// half's letter (Y, Z, A or B), then the square's column and row letters. `None` outside the /// lettered area of the zone (NGA.SIG.0012 §§11.10 and 11.11). pub(crate) fn square_letters(north: bool, easting: i64, northing: i64) -> Option<(char, char, char)> { let (col, row) = (easting.div_euclid(100_000), northing.div_euclid(100_000)); - let (columns, rows, first): (&[&[u8; 2]], &[u8], i64) = - if north { (&NORTH_COLUMNS, NORTH_ROWS, NORTH_FIRST) } else { (&SOUTH_COLUMNS, SOUTH_ROWS, SOUTH_FIRST) }; + let (columns, rows, first) = lettering(north); let pair = columns.get(usize::try_from(col - first).ok()?)?; let row = rows.get(usize::try_from(row - first).ok()?)?; Some((char::from(pair[0]), char::from(pair[1]), char::from(*row))) @@ -225,8 +229,7 @@ pub(crate) fn square_origin(half: char, column: char, row: char) -> Result<(bool 'A' | 'B' => false, _ => return Err(GridError::Band), }; - let (columns, rows, first): (&[&[u8; 2]], &[u8], i64) = - if north { (&NORTH_COLUMNS, NORTH_ROWS, NORTH_FIRST) } else { (&SOUTH_COLUMNS, SOUTH_ROWS, SOUTH_FIRST) }; + let (columns, rows, first) = lettering(north); let col = columns.iter().position(|p| char::from(p[0]) == half && char::from(p[1]) == column).ok_or(GridError::Square)?; let row = rows.iter().position(|r| char::from(*r) == row).ok_or(GridError::Square)?; let at = |i: usize| (first + i as i64) as f64 * SQUARE; @@ -250,10 +253,10 @@ pub(crate) fn cell_reaches_zone(north: bool, e0: f64, n0: f64, cell: f64, slop_d /// 2,000,000 m easting, Z and B on it and east of it (NGA.STND.0037 App. B-5b; the line itself /// is Z and B by NGA.SIG.0012 §§11.10 and 11.11, where square 20 is ZA and BA). Full /// coordinates are written rounded to the meter (NGA.STND.0037 App. A-2), so a place in Y or A -/// just west of the line may read 2,000,000: Y and A accept it, within half a meter. +/// just west of the line may read 2,000,000: Y and A accept exactly that whole number too. pub(crate) fn easting_in_half(half: char, easting: f64) -> bool { match half { - 'Y' | 'A' => easting < FALSE_ORIGIN + 0.5, + 'Y' | 'A' => easting <= FALSE_ORIGIN, 'Z' | 'B' => easting >= FALSE_ORIGIN, _ => false, } @@ -264,7 +267,7 @@ pub(crate) fn easting_in_half(half: char, easting: f64) -> bool { /// the south, along both axes (NGA.SIG.0012 §§11.10 and 11.11). Numbers outside it aren't a UPS /// position at all. pub(crate) fn in_lettered_area(north: bool, easting: f64, northing: f64) -> bool { - let first = (if north { NORTH_FIRST } else { SOUTH_FIRST }) as f64 * SQUARE; + let first = lettering(north).2 as f64 * SQUARE; let span = first..(2.0 * FALSE_ORIGIN - first); span.contains(&easting) && span.contains(&northing) } @@ -274,6 +277,49 @@ pub(crate) fn is_polar_half(letter: char) -> bool { matches!(letter, 'A' | 'B' | 'Y' | 'Z') } +/// Reads a UPS position, which has no zone number: the zone spelled out, `north 2392768 1607232` +/// or `south 2096454 1452981` (any case), as the readout writes it, or the polar half's letter +/// before the easting and northing, `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and +/// A lie west of the 2,000,000 m easting and Z and B on or east of it. Numbers outside the zone's +/// lettered area (north 1,300,000 up to 2,700,000 m, south 800,000 up to 3,200,000 m) aren't a UPS +/// position and read as text ([`GridError::Syntax`]); a place inside it must lie in the zone, at +/// 84° N or more or south of 80° S, give or take the meter it was rounded to. +pub fn parse_ups(text: &str) -> Result { + let text = text.trim(); + if text.chars().count() > MAX_REF_CHARS { + return Err(GridError::Syntax); + } + let mut chars = text.chars().peekable(); + let mut word = String::new(); + while let Some(c) = chars.next_if(char::is_ascii_alphabetic) { + word.push(c.to_ascii_uppercase()); + } + let (north, half) = match word.as_str() { + "NORTH" => (true, None), + "SOUTH" => (false, None), + "Y" | "Z" => (true, word.chars().next()), + "A" | "B" => (false, word.chars().next()), + _ => return Err(GridError::Syntax), + }; + // A space or comma after the word or letter: `north2000000 …` isn't written that way. + if !chars.peek().is_some_and(|c| c.is_whitespace() || *c == ',') { + return Err(GridError::Syntax); + } + let rest: String = chars.collect(); + let (easting, northing) = easting_and_northing(&rest)?; + // Numbers outside the zone's lettered area aren't a UPS position (`A 10 20`, a road): text. + if !in_lettered_area(north, easting, northing) { + return Err(GridError::Syntax); + } + if half.is_some_and(|h| !easting_in_half(h, easting)) { + return Err(GridError::OutsideZone); + } + if !cell_reaches_zone(north, easting, northing, 0.0, ROUNDING_DEG) { + return Err(GridError::OutsideZone); + } + from_ups(north, easting, northing).ok_or(GridError::OutsideZone) +} + #[cfg(test)] mod tests { use super::*; @@ -380,8 +426,8 @@ mod tests { } assert!(easting_in_half('Z', FALSE_ORIGIN) && !easting_in_half('Z', FALSE_ORIGIN - 0.1)); assert!(easting_in_half('B', FALSE_ORIGIN) && !easting_in_half('B', FALSE_ORIGIN - 0.1)); - // A typed full coordinate is rounded: Y and A take the line within half a meter. - assert!(easting_in_half('Y', FALSE_ORIGIN) && !easting_in_half('Y', FALSE_ORIGIN + 0.5)); + // A typed full coordinate is rounded: Y and A take the line itself, not past it. + assert!(easting_in_half('Y', FALSE_ORIGIN) && !easting_in_half('Y', FALSE_ORIGIN + 0.4)); assert!(easting_in_half('A', FALSE_ORIGIN) && !easting_in_half('A', FALSE_ORIGIN + 1.0)); } diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index b8bc6aafcf..81a9213ece 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -50,7 +50,7 @@ const ROW_CYCLE: f64 = 2_000_000.0; const EDGE_SLOP_DEG: f64 = 0.5; /// How far (degrees) a place, or the nearest part of a cell, may lie outside its band, or past the /// UTM limits, for rounding: about a metre, the precision a UTM position is written to. -const ROUNDING_DEG: f64 = 1.0 / M_PER_DEG; +pub(crate) const ROUNDING_DEG: f64 = 1.0 / M_PER_DEG; /// Metres per degree of latitude, roughly, for turning a cell's size into degrees. const M_PER_DEG: f64 = 111_000.0; @@ -545,7 +545,7 @@ fn locate(m: &Mgrs) -> Result { if !(1..=60).contains(&m.zone) { return Err(GridError::Zone); } - if matches!(m.band, 'A' | 'B' | 'Y' | 'Z') { + if crate::ups::is_polar_half(m.band) { return Err(GridError::Polar); } if m.digits > 5 { @@ -603,11 +603,11 @@ fn locate_polar(m: &Mgrs) -> Result { } /// Most characters a typed grid reference may have. -const MAX_REF_CHARS: usize = 64; +pub(crate) const MAX_REF_CHARS: usize = 64; /// An easting and a northing in meters, separated by spaces or commas: plain decimals only (no /// signs, exponents or `inf`). -fn easting_and_northing(text: &str) -> Result<(f64, f64), GridError> { +pub(crate) fn easting_and_northing(text: &str) -> Result<(f64, f64), GridError> { let nums: Vec<&str> = text.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()).collect(); let [es, ns] = nums.as_slice() else { return Err(GridError::Syntax) }; let number = |s: &str| { @@ -619,51 +619,6 @@ fn easting_and_northing(text: &str) -> Result<(f64, f64), GridError> { Ok((number(es)?, number(ns)?)) } -/// Reads a UPS position, which has no zone number: the zone spelled out, `north 2392768 1607232` -/// or `south 2096454 1452981` (any case), as the readout writes it, or the polar half's letter -/// before the easting and northing, `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and -/// A lie west of the 2,000,000 m easting and Z and B on or east of it. Numbers outside the zone's -/// lettered area (north 1,300,000 up to 2,700,000 m, south 800,000 up to 3,200,000 m) aren't a UPS -/// position and read as text ([`GridError::Syntax`]); a place inside it must lie in the zone, at -/// 84° N or more or south of 80° S, give or take the meter it was rounded to. -pub fn parse_ups(text: &str) -> Result { - let text = text.trim(); - if text.chars().count() > MAX_REF_CHARS { - return Err(GridError::Syntax); - } - let mut chars = text.chars().peekable(); - let mut word = String::new(); - while let Some(c) = chars.next_if(char::is_ascii_alphabetic) { - word.push(c.to_ascii_uppercase()); - } - let (north, half) = match word.as_str() { - "NORTH" => (true, None), - "SOUTH" => (false, None), - "Y" | "Z" => (true, word.chars().next()), - "A" | "B" => (false, word.chars().next()), - _ => return Err(GridError::Syntax), - }; - // A space or comma after the word or letter: `north2000000 …` isn't written that way. - if !chars.peek().is_some_and(|c| c.is_whitespace() || *c == ',') { - return Err(GridError::Syntax); - } - let rest: String = chars.collect(); - let (easting, northing) = easting_and_northing(&rest)?; - // Numbers outside the zone's lettered area aren't a UPS position (`A 10 20`, a road): text. - if !crate::ups::in_lettered_area(north, easting, northing) { - return Err(GridError::Syntax); - } - if half.is_some_and(|h| !crate::ups::easting_in_half(h, easting)) { - return Err(GridError::OutsideZone); - } - let p = crate::ups::from_ups(north, easting, northing).ok_or(GridError::OutsideZone)?; - let in_zone = if north { p.y >= crate::ups::UPS_NORTH_FROM - ROUNDING_DEG } else { p.y < crate::ups::UPS_SOUTH_OF + ROUNDING_DEG }; - if !in_zone { - return Err(GridError::OutsideZone); - } - Ok(p) -} - /// Reads a zone number (one or two digits) and the letter after it, skipping spaces. The zone /// isn't checked to be 1–60 here (the caller does, once the rest reads as a reference): until /// then, `75 Main St` is text. @@ -684,7 +639,7 @@ fn zone_and_letter(chars: &mut std::iter::Peekable>) -> Resu /// Checks a band letter, telling the polar letters apart. fn band_letter(letter: char) -> Result { - if matches!(letter, 'A' | 'B' | 'Y' | 'Z') { + if crate::ups::is_polar_half(letter) { return Err(GridError::Polar); } band_latitudes(letter).map(|_| letter).ok_or(GridError::Band) @@ -698,9 +653,11 @@ fn band_letter(letter: char) -> Result { /// /// In the polar areas MGRS writes no zone number (NGA.SIG.0012 §§11.9 and 11.13): the half's /// letter (Y or Z north, A or B south), the square's letters, then the digits, as -/// `ZFD9276707232` or `Z FD 92767 07232`. It must have a space after the half's letter or its -/// digits attached to the letters: three letters alone (`ATL`, `Bay 12`) are a word, so a 100 km -/// polar square is read spaced, `Z AH`, as the readout writes it. A polar letter after a zone +/// `ZFD9276707232` or `Z FD 92767 07232`. Three letters written as one word are as often a word +/// or a code, so they are read only with at least six digits after them (`ZFD9276707232`, +/// `ZFD 927 072`, `ZAC 7714662481`): `ATL`, `Bay 12` and `BAW1234` are text. Spaced after the +/// half's letter it is read at any precision, and a 100 km square alone in capitals (`Z AH`, as +/// the readout writes it; `Z Ah` is a phrase). A polar letter after a zone /// number (`38ZMB`) is refused with [`GridError::Polar`]; text that starts with any other letter /// isn't a reference. pub fn parse_mgrs(text: &str) -> Result { @@ -723,23 +680,26 @@ pub fn parse_mgrs(text: &str) -> Result { // Whether a space follows the zone and band (or the polar half's letter). let spaced = chars.peek().is_some_and(|c| c.is_whitespace()); let mut letters = [' '; 2]; + let mut capitals = true; for l in letters.iter_mut() { while chars.next_if(|c| c.is_whitespace()).is_some() {} - *l = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?.to_ascii_uppercase(); + let c = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?; + capitals &= c.is_ascii_uppercase(); + *l = c.to_ascii_uppercase(); } - let digits_attached = chars.peek().is_some_and(char::is_ascii_digit); let rest: String = chars.collect(); if rest.chars().any(|c| !c.is_ascii_digit() && !c.is_whitespace()) { return Err(GridError::Syntax); } let groups: Vec<&str> = rest.split_whitespace().collect(); // A polar reference written as one word of three letters is as often a word or a code - // (`Bay 12`, `ATL`, `YUL`): it is text, unless its digits are attached (`ZAH1234512345`, - // MGRS's compact form) or follow as two equal groups of 2 to 5 (`ZFD 92767 07232`). Spaced - // after the half's letter (`Z AH`, `Z AH 12345 12345`, as the readout writes it) it is a - // reference in any form. Case doesn't matter. - let two_groups = matches!(groups.as_slice(), [e, n] if e.len() == n.len() && (2..=5).contains(&e.len())); - if polar && !spaced && !digits_attached && !two_groups { + // (`ATL`, `Bay 12`, the flight `BAW1234`): it is read only with at least six digits, 100 m or + // finer, as references are written (`ZAH1234512345`, `ZFD 92767 07232`, `ZAC 7714662481`). + // Spaced after the half's letter (`Z AH 12 34`, as the readout writes it) it is a reference at + // any precision; a 100 km square alone, with no digits, only with its square letters in + // capitals (`Z AH`), as `Z Ah` or `b ag` is a phrase. + let digit_count = groups.iter().map(|g| g.len()).sum::(); + if polar && ((!spaced && digit_count < 6) || (digit_count == 0 && !capitals)) { return Err(GridError::Syntax); } let (e, n) = match groups.as_slice() { @@ -795,7 +755,7 @@ pub fn parse_mgrs(text: &str) -> Result { /// `S` after the zone is band S (32° N to 40° N). A northing outside band S may mean the /// southern hemisphere, so it is refused as [`GridError::Ambiguous`] rather than guessed. /// -/// North of 84° N and south of 80° S the grid is UPS, read by [`parse_ups`]'s forms +/// North of 84° N and south of 80° S the grid is UPS, read by [`crate::ups::parse_ups`]'s forms /// (`north 2392768 1607232`); a UTM zone's position there is refused as [`GridError::Polar`]. pub fn parse_utm(text: &str) -> Result { let text = text.trim(); @@ -803,7 +763,7 @@ pub fn parse_utm(text: &str) -> Result { return Err(GridError::Syntax); } if text.starts_with(|c: char| c.is_ascii_alphabetic()) { - return parse_ups(text); + return crate::ups::parse_ups(text); } let mut chars = text.chars().peekable(); let (zone, letter) = zone_and_letter(&mut chars)?; @@ -1590,10 +1550,10 @@ mod tests { ("Z DA", GridError::Square), // Z skips D and E ("Y AA", GridError::Square), // Y starts at R ("B AI", GridError::Square), // no I - ("ZDA12", GridError::Square), // attached digits read as a reference too + ("ZDA123456", GridError::Square), // six digits or more read as a reference too ("Y RA", GridError::OutsideZone), // the north lettering's corner lies south of 84° N ("A JA", GridError::OutsideZone), // the south lettering's corner lies north of 80° S - ("ZAH123", GridError::Digits), + ("ZAH1234567", GridError::Digits), ("Z AH 123 45", GridError::Digits), ("38ZMB", GridError::Polar), // a polar letter after a zone number ] { @@ -1636,12 +1596,36 @@ mod tests { "Elm", "BA Y 12", "ZAH 1 2", + // Codes with a few digits: flights, apartments, short numbers. + "BAW1234", + "YUL1234", + "BAN12", + "bay12", + "Bay 12 34", + "Apt 12 14", + "Yuk 12 34", + "zfd 92 07", + "ZAH123", + // A one-letter word and a two-letter word is a phrase unless in capitals. + "Z Ah", + "B Ag", + "z ah", ] { assert_eq!(parse_mgrs(text), Err(GridError::Syntax), "{text}"); } - // Spaced after the half's letter, with the digits attached, or with two equal groups of - // digits, it is a reference. - for text in ["B AY 12", "bay12", "Z AH", "z ah", "Z AH 12345 12345", "ZAH1234512345", "ZFD 92767 07232", "zfd 92 07"] { + // Spaced after the half's letter, or written as one word with at least six digits (100 m + // or finer), it is a reference. + for text in [ + "B AY 12", + "b ay 12", + "Z AH", + "Z AH 12345 12345", + "ZAH1234512345", + "ZFD 92767 07232", + "zfd 927 072", + "ZAC 7714662481", + "zac7714662481", + ] { assert!(parse_mgrs(text).is_ok(), "{text}"); } } diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 5fac368100..dad976595d 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -189,9 +189,11 @@ The [search box](#navigating) takes the same grid references, in any case: - **UPS and polar MGRS**, north of 84° N and south of 80° S, which have no zone number: UPS as the readout writes it, `north 2077146 1562481` or `south 2096454 1452981`, or with the half's letter, `Z 2077146 1562481` or `Y, 1735147, 2243078`; polar MGRS as `ZAC7714662481`, - `Z AC 77146 62481` or `ZAC 77146 62481`. Three letters alone, or before a single number, are - read as a word (`ATL`, `Bay 12`), so a 100 km polar square alone is written spaced, `Z AC`, - as the readout writes it. A UTM zone's position past 84° N or 80° S, or a polar letter after a + `ZAC 77146 62481` or `Z AC 77146 62481`. Three letters written together are as often a word + or a code (`ATL`, `Bay 12`, `BAW1234`), so they're read only with at least six digits (100 m + or finer); with a space after the half's letter (`Z AC 77 62`) any precision reads, and a + 100 km square alone is written as the readout writes it, `Z AC`, in capitals. A UTM zone's + position past 84° N or 80° S, or a polar letter after a zone number (`38ZMB`), finds nothing and the list says how UPS is written. A reference that doesn't exist (square letters the zone doesn't use, a northing or a square From 670396c4f561d21a05445c79c5478258b18d6e74 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:05:18 -0600 Subject: [PATCH 05/14] refactor: parse every polar MGRS form, guess words in search parse_mgrs now reads every polar form NGA allows (ZAH, ZAH1234, BAG9652), so compact() always reads back. Telling a reference from a word that reads as one moves to search's read_grid_reference, next to spaced_square: letter-led text counts as a polar reference only when written as the readout writes it (Z AH 12 34), as one word with at least six digits (ZAC7714662481), or in capitals before two equal digit groups (ZFD 927 072). ATL, BAW1234, Apt 123456 and A St 12 stay text. Also: parse_ups converts once, one zone check, no redundant checks or accessor, and doc fixes. --- crates/engine/src/cmd/search.rs | 58 +++++++++++++- crates/geom/src/ups.rs | 38 ++++----- crates/geom/src/utm.rs | 131 +++++++------------------------- docs/user-guide/maps.md | 18 +++-- 4 files changed, 112 insertions(+), 133 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 9186de8b41..ff5a16443f 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -409,9 +409,14 @@ pub fn parse_grid_reference(text: &str) -> Option { /// refused: [`GridError::Syntax`] for text written as neither form, otherwise the reason of the /// form it was written in. A 100 km square alone written with spaces (`5 Ave`, `4K TV`) is a /// number and a word as often as a reference, so one that names no square is -/// [`GridError::Syntax`] too; written as one word (`38TMJ`), it says why. +/// [`GridError::Syntax`] too; written as one word (`38TMJ`), it says why. A polar reference has +/// no zone number, so text that starts with a letter is read as one only when written as +/// references are ([`written_as_polar_reference`]); UPS positions (`north 2077146 1562481`) are +/// read as [`rustgis_geom::parse_utm`] reads them. pub fn read_grid_reference(text: &str) -> Result { - match rustgis_geom::parse_mgrs(text) { + let letter_led = text.trim_start().starts_with(|c: char| c.is_ascii_alphabetic()); + let mgrs = if letter_led && !written_as_polar_reference(text) { Err(GridError::Syntax) } else { rustgis_geom::parse_mgrs(text) }; + match mgrs { Ok(m) => m.centre(), Err(mgrs) => match rustgis_geom::parse_utm(text) { Err(GridError::Syntax) if spaced_square(text) => Err(GridError::Syntax), @@ -421,6 +426,38 @@ pub fn read_grid_reference(text: &str) -> Result { } } +/// Whether letter-led text is written as a polar (UPS) MGRS reference is, rather than as a word +/// or code that happens to read as one (`ATL`, `Bay 12`, the flight `BAW1234`, `A St 12`, +/// `Apt 123456`): +/// - as the readout writes it: the half's letter, a space and the square's letters, in capitals +/// (`Z AH`, `Z AH 12 34`); +/// - as one word with at least six digits attached, 100 m or finer (`ZAC7714662481`, any case); +/// - or with the three letters in capitals before two equal groups of at least three digits +/// (`ZFD 927 072`, `ZFD 92767 07232`). +fn written_as_polar_reference(text: &str) -> bool { + let mut chars = text.trim().chars(); + let Some(half) = chars.next() else { return false }; + let rest = chars.as_str(); + let spaced = rest.starts_with(char::is_whitespace); + let rest = rest.trim_start(); + let letters: Vec = rest.chars().take(2).collect(); + if letters.len() != 2 || !letters.iter().all(char::is_ascii_alphabetic) { + return false; + } + let capitals = half.is_ascii_uppercase() && letters.iter().all(char::is_ascii_uppercase); + if spaced { + return capitals; + } + // The two letters are ASCII, so the digits start two bytes on. + let after = rest.get(2..).unwrap_or(""); + let attached = after.starts_with(|c: char| c.is_ascii_digit()); + match after.split_whitespace().collect::>().as_slice() { + [run] if attached => run.len() >= 6, + [e, n] => capitals && e.len() == n.len() && e.len() >= 3, + _ => false, + } +} + /// Whether `text` has spaces and no digits after its leading number: written so, an MGRS /// reference is a 100 km square alone. fn spaced_square(text: &str) -> bool { @@ -850,17 +887,30 @@ mod tests { "BRU", "ZAH", "BAN", + // A word and a long number, and phrases with digits. + "Apt 123456", + "Bay 123456", + "Bay 123 456", + "Box 123456", + "A St 12", + "a st 12", + "B St 12", + "ZAC 7714662481", ] { let r = search(&s, q, 50); assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); assert_eq!(r.grid_error, None, "{q}"); } // A 100 km polar square written as the readout writes it, spaced, reads back; like - // `33UVP` it may also be a name, so the tables are still searched. - for q in ["Z AH", "B AN"] { + // `33UVP` it may also be a name, so the tables are still searched. So do the other + // written forms of a reference. + for q in ["Z AH", "B AN", "Z AH 12 34", "ZAH1234512345", "zac7714662481", "ZFD 927 072"] { let r = search(&s, q, 50); assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })), "{q}: {r:?}"); } + // A reference written as one, but with fewer than six digits as one word, is text: the + // flight BAW1234 looks the same as ZAH1234. + assert!(!search(&s, "ZAH1234", 50).hits.iter().any(|h| matches!(h, Hit::Coordinate { .. }))); // A polar reference that names no place says why. assert_eq!(search(&s, "ZDA1234512345", 50).grid_error, Some(GridError::Square)); assert_eq!(search(&s, "YRA1234512345", 50).grid_error, Some(GridError::OutsideZone)); diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs index 229d605d4d..2805e0ce5e 100644 --- a/crates/geom/src/ups.rs +++ b/crates/geom/src/ups.rs @@ -16,8 +16,7 @@ //! the half (Y for western longitudes and Z for eastern ones in the north, A and B in the //! south; the 0° and 180° meridians, at an easting of 2,000,000 m, are Z and B, by §§11.10 and //! 11.11, where square 20 is ZA and BA), then the 100 km square's column and row letters, and -//! the digits truncated to the precision. A 100 km square alone is written spaced, `Z AH` -//! ([`crate::utm::parse_mgrs`] reads three letters alone as a word). +//! the digits truncated to the precision. //! //! The conformal latitude is the one in [`crate::utm`] (Karney 2011, eqs. 7–9 and 19–21), which //! gives the same values as §2.8 and §2.9's PhiToChi and ChiToPhi. @@ -27,7 +26,7 @@ use std::sync::LazyLock; use crate::Coord; use crate::utm::{ - GridError, MAX_REF_CHARS, ROUNDING_DEG, conformal_tan, easting_and_northing, eccentricity, geographic_tan, wgs84_a, wrap, + GridError, MAX_REF_CHARS, ROUNDING_DEG, WGS84_A, conformal_tan, easting_and_northing, eccentricity, geographic_tan, wrap, }; /// The northern limit of the UTM zones, where north UPS begins (degrees); 84° N itself is UPS. @@ -41,8 +40,9 @@ const K0: f64 = 0.994; const FALSE_ORIGIN: f64 = 2_000_000.0; /// MGRS 100 km square side (meters). const SQUARE: f64 = 100_000.0; -/// The farthest from the pole (meters) an easting and northing may lie and still name a place; -/// past it they are typing errors, and the latitude series has nothing to gain. +/// The farthest from the pole (meters) an easting and northing are converted. Every distance maps +/// to some latitude (about 2° on the zone's side of the equator at 12,000 km, 25° beyond it at +/// 20,000 km); past this the numbers can only be typing errors, so they are refused. const MAX_RADIUS: f64 = 20_000_000.0; /// k90 of NGA.SIG.0012 eq. (19): √(1 − e²) · exp(e · artanh e). @@ -96,7 +96,7 @@ fn polar_radius(lat: f64) -> Option { let taup = conformal_tan(lat.to_radians().tan()); let h = taup.hypot(1.0); let t = if taup >= 0.0 { 1.0 / (h + taup) } else { h - taup }; - let rho = 2.0 * wgs84_a() * K0 / *K90 * t; + let rho = 2.0 * WGS84_A * K0 / *K90 * t; rho.is_finite().then_some(rho) } @@ -107,7 +107,7 @@ fn latitude_at(rho: f64) -> Option { if rho == 0.0 { return Some(90.0); } - let r = rho * *K90 / (2.0 * wgs84_a() * K0); + let r = rho * *K90 / (2.0 * WGS84_A * K0); let lat = geographic_tan((1.0 - r * r) / (2.0 * r))?.atan().to_degrees(); lat.is_finite().then_some(lat) } @@ -153,9 +153,7 @@ impl fmt::Display for Ups { /// A place's UPS coordinates; `None` in the UTM latitudes (80° S up to 84° N) and for a non-finite /// place. pub fn to_ups(c: Coord) -> Option { - if !c.is_finite() { - return None; - } + // ups_zone refuses a non-finite latitude, and to_ups_in_zone a non-finite longitude. let north = ups_zone(c.y)?; let (easting, northing) = to_ups_in_zone(c, north)?; Some(Ups { north, easting, northing }) @@ -242,11 +240,13 @@ pub(crate) fn square_origin(half: char, column: char, row: char) -> Result<(bool /// wholly in the UTM latitudes, and a reference there names no UPS place. pub(crate) fn cell_reaches_zone(north: bool, e0: f64, n0: f64, cell: f64, slop_deg: f64) -> bool { let near_pole = |lo: f64| FALSE_ORIGIN.clamp(lo, lo + cell); - match from_ups(north, near_pole(e0), near_pole(n0)) { - Some(p) if north => p.y >= UPS_NORTH_FROM - slop_deg, - Some(p) => p.y < UPS_SOUTH_OF + slop_deg, - None => false, - } + from_ups(north, near_pole(e0), near_pole(n0)).is_some_and(|p| in_zone(north, p.y, slop_deg)) +} + +/// Whether a latitude lies in a UPS zone (84° N or more, or south of 80° S), give or take +/// `slop_deg`. +fn in_zone(north: bool, lat: f64, slop_deg: f64) -> bool { + if north { lat >= UPS_NORTH_FROM - slop_deg } else { lat < UPS_SOUTH_OF + slop_deg } } /// Whether a typed easting lies in a polar half's side of its zone: Y and A west of the @@ -280,7 +280,8 @@ pub(crate) fn is_polar_half(letter: char) -> bool { /// Reads a UPS position, which has no zone number: the zone spelled out, `north 2392768 1607232` /// or `south 2096454 1452981` (any case), as the readout writes it, or the polar half's letter /// before the easting and northing, `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and -/// A lie west of the 2,000,000 m easting and Z and B on or east of it. Numbers outside the zone's +/// A lie west of the 2,000,000 m easting (or on it, for a rounded coordinate) and Z and B on or +/// east of it. Numbers outside the zone's /// lettered area (north 1,300,000 up to 2,700,000 m, south 800,000 up to 3,200,000 m) aren't a UPS /// position and read as text ([`GridError::Syntax`]); a place inside it must lie in the zone, at /// 84° N or more or south of 80° S, give or take the meter it was rounded to. @@ -314,10 +315,11 @@ pub fn parse_ups(text: &str) -> Result { if half.is_some_and(|h| !easting_in_half(h, easting)) { return Err(GridError::OutsideZone); } - if !cell_reaches_zone(north, easting, northing, 0.0, ROUNDING_DEG) { + let p = from_ups(north, easting, northing).ok_or(GridError::OutsideZone)?; + if !in_zone(north, p.y, ROUNDING_DEG) { return Err(GridError::OutsideZone); } - from_ups(north, easting, northing).ok_or(GridError::OutsideZone) + Ok(p) } #[cfg(test)] diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index 81a9213ece..88680b38d2 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -34,7 +34,7 @@ pub const UTM_MIN_LAT: f64 = -80.0; pub const UTM_MAX_LAT: f64 = 84.0; /// WGS 84 semi-major axis (metres) and flattening. -const WGS84_A: f64 = 6_378_137.0; +pub(crate) const WGS84_A: f64 = 6_378_137.0; const WGS84_F: f64 = 1.0 / 298.257_223_563; /// UTM's scale on the central meridian, false easting and the southern false northing. const K0: f64 = 0.9996; @@ -101,11 +101,6 @@ static SERIES: LazyLock = LazyLock::new(|| { } }); -/// The WGS 84 semi-major axis (meters), for [`crate::ups`]. -pub(crate) fn wgs84_a() -> f64 { - WGS84_A -} - /// The WGS 84 first eccentricity, for [`crate::ups`]. pub(crate) fn eccentricity() -> f64 { SERIES.e @@ -354,8 +349,8 @@ impl Mgrs { if self.polar() { write!(f, "{}", self.band) } else { write!(f, "{:02}{}", self.zone, self.band) } } - /// Without spaces: `33UVP1234523456`, `04QFJ12345678`, `ZFD9276707232`. A polar 100 km square - /// alone (`ZAH`) reads back only spaced (`Z AH`, the `Display` form; see [`parse_mgrs`]). + /// Without spaces: `33UVP1234523456`, `04QFJ12345678`, `ZFD9276707232`; [`parse_mgrs`] reads it + /// back. pub fn compact(&self) -> String { let mut out = String::with_capacity(15); // Writing to a String can't fail. @@ -653,13 +648,11 @@ fn band_letter(letter: char) -> Result { /// /// In the polar areas MGRS writes no zone number (NGA.SIG.0012 §§11.9 and 11.13): the half's /// letter (Y or Z north, A or B south), the square's letters, then the digits, as -/// `ZFD9276707232` or `Z FD 92767 07232`. Three letters written as one word are as often a word -/// or a code, so they are read only with at least six digits after them (`ZFD9276707232`, -/// `ZFD 927 072`, `ZAC 7714662481`): `ATL`, `Bay 12` and `BAW1234` are text. Spaced after the -/// half's letter it is read at any precision, and a 100 km square alone in capitals (`Z AH`, as -/// the readout writes it; `Z Ah` is a phrase). A polar letter after a zone -/// number (`38ZMB`) is refused with [`GridError::Polar`]; text that starts with any other letter -/// isn't a reference. +/// `ZFD9276707232`, `Z FD 92767 07232` or `ZAH` (100 km), in any case and at any precision, as +/// NGA allows. Text that starts with a letter other than A, B, Y or Z isn't a reference, and a +/// polar letter after a zone number (`38ZMB`) is refused with [`GridError::Polar`]. Telling a +/// reference from a word that happens to read as one (`ATL`, `Bay 12`) is up to the caller that +/// takes free text: search's `read_grid_reference` does. pub fn parse_mgrs(text: &str) -> Result { let text = text.trim(); if text.chars().count() > MAX_REF_CHARS { @@ -677,31 +670,16 @@ pub fn parse_mgrs(text: &str) -> Result { } else { zone_and_letter(&mut chars)? }; - // Whether a space follows the zone and band (or the polar half's letter). - let spaced = chars.peek().is_some_and(|c| c.is_whitespace()); let mut letters = [' '; 2]; - let mut capitals = true; for l in letters.iter_mut() { while chars.next_if(|c| c.is_whitespace()).is_some() {} - let c = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?; - capitals &= c.is_ascii_uppercase(); - *l = c.to_ascii_uppercase(); + *l = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?.to_ascii_uppercase(); } let rest: String = chars.collect(); if rest.chars().any(|c| !c.is_ascii_digit() && !c.is_whitespace()) { return Err(GridError::Syntax); } let groups: Vec<&str> = rest.split_whitespace().collect(); - // A polar reference written as one word of three letters is as often a word or a code - // (`ATL`, `Bay 12`, the flight `BAW1234`): it is read only with at least six digits, 100 m or - // finer, as references are written (`ZAH1234512345`, `ZFD 92767 07232`, `ZAC 7714662481`). - // Spaced after the half's letter (`Z AH 12 34`, as the readout writes it) it is a reference at - // any precision; a 100 km square alone, with no digits, only with its square letters in - // capitals (`Z AH`), as `Z Ah` or `b ag` is a phrase. - let digit_count = groups.iter().map(|g| g.len()).sum::(); - if polar && ((!spaced && digit_count < 6) || (digit_count == 0 && !capitals)) { - return Err(GridError::Syntax); - } let (e, n) = match groups.as_slice() { [] => ("", ""), [one] => { @@ -1534,6 +1512,12 @@ mod tests { assert_eq!(parse_mgrs(want), Ok(m), "{want}"); assert_eq!(parse_mgrs(&m.to_string()), Ok(m), "{m}"); assert_eq!(parse_mgrs(&want.to_lowercase()), Ok(m), "{want}"); + // Every precision reads back, compact or spaced. + for digits in 0..=5 { + let r = to_mgrs(c(lon, lat), digits).unwrap(); + assert_eq!(parse_mgrs(&r.compact()), Ok(r), "{want} at {digits} digits"); + assert_eq!(parse_mgrs(&r.to_string()), Ok(r), "{want} at {digits} digits"); + } let p = m.centre().unwrap(); assert!((p.y - lat).abs() < 1e-4, "{want}: {p:?}"); } @@ -1547,85 +1531,26 @@ mod tests { #[test] fn polar_references_that_name_no_place_are_refused() { for (text, why) in [ - ("Z DA", GridError::Square), // Z skips D and E - ("Y AA", GridError::Square), // Y starts at R - ("B AI", GridError::Square), // no I - ("ZDA123456", GridError::Square), // six digits or more read as a reference too - ("Y RA", GridError::OutsideZone), // the north lettering's corner lies south of 84° N - ("A JA", GridError::OutsideZone), // the south lettering's corner lies north of 80° S - ("ZAH1234567", GridError::Digits), + ("ZDA", GridError::Square), // Z skips D and E + ("Z DA", GridError::Square), // spaced, the same + ("YAA", GridError::Square), // Y starts at R + ("BAI", GridError::Square), // no I + ("YRA", GridError::OutsideZone), // the north lettering's corner lies south of 84° N + ("AJA", GridError::OutsideZone), // the south lettering's corner lies north of 80° S + ("ZAH123", GridError::Digits), ("Z AH 123 45", GridError::Digits), ("38ZMB", GridError::Polar), // a polar letter after a zone number ] { assert_eq!(parse_mgrs(text), Err(why), "{text}"); } - // Three letters alone, before a number or not, are a word or a code (`Bay 12` would be - // B AY in the south, `ATL` A TL), in any case; so is any text whose first letter isn't a - // polar half (`Elm 123`). - for text in [ - "CAT", - "Main", - "Berlin 12", - "Z", - "ZA", - "BOX", - "zap road", - "Bay 12", - "BAY 12", - "Ban 12", - "Bad 34", - "Zag 56", - "Ave 12", - "Zoo 12", - "bay 12", - "zap", - "ZAP", - "ZAH", - "ATL", - "AUS", - "YUL", - "BBC", - "ABC", - "BRU", - "BCN", - "BKK", - "ZAG", - "AMS", - "YYZ", - "Elm 123", - "Elm", - "BA Y 12", - "ZAH 1 2", - // Codes with a few digits: flights, apartments, short numbers. - "BAW1234", - "YUL1234", - "BAN12", - "bay12", - "Bay 12 34", - "Apt 12 14", - "Yuk 12 34", - "zfd 92 07", - "ZAH123", - // A one-letter word and a two-letter word is a phrase unless in capitals. - "Z Ah", - "B Ag", - "z ah", - ] { + // Text that starts with any other letter, or doesn't go on as letters and digits, isn't a + // reference. + for text in ["CAT", "Main", "Elm 123", "Berlin 12", "Z", "ZA", "zap road", "Z 12"] { assert_eq!(parse_mgrs(text), Err(GridError::Syntax), "{text}"); } - // Spaced after the half's letter, or written as one word with at least six digits (100 m - // or finer), it is a reference. - for text in [ - "B AY 12", - "b ay 12", - "Z AH", - "Z AH 12345 12345", - "ZAH1234512345", - "ZFD 92767 07232", - "zfd 927 072", - "ZAC 7714662481", - "zac7714662481", - ] { + // Every form NGA allows reads, at any precision and in any case; telling a reference from + // a word that reads as one is search's job (`read_grid_reference`). + for text in ["ZAH", "Z AH", "z ah", "ZAH12", "ZAH1234", "BAG9652", "ZFD 9207", "ZAC 7714662481", "Z AH 12345 12345"] { assert!(parse_mgrs(text).is_ok(), "{text}"); } } diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index dad976595d..95030ea00f 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -171,7 +171,8 @@ itself is UTM. On the map of another body than the Earth the readout shows *No U it steps to the next one. A saved format this version doesn't know, say from a newer RustGIS, reads as decimal degrees with a notice, and stays saved until you pick a format. -The [search box](#navigating) takes the same grid references, in any case: +The [search box](#navigating) takes the same grid references, in any case (polar references have +their own rules, below): - **MGRS** with or without spaces: `33UWR2156621996`, `33U WR 21566 21996`, `33UWR 2156 2199`, or a 100 km square alone, `33UWR`; a zone below 10 with or without its leading zero (`04QFJ`, @@ -188,13 +189,14 @@ The [search box](#navigating) takes the same grid references, in any case: nothing: write `south` instead. - **UPS and polar MGRS**, north of 84° N and south of 80° S, which have no zone number: UPS as the readout writes it, `north 2077146 1562481` or `south 2096454 1452981`, or with the half's - letter, `Z 2077146 1562481` or `Y, 1735147, 2243078`; polar MGRS as `ZAC7714662481`, - `ZAC 77146 62481` or `Z AC 77146 62481`. Three letters written together are as often a word - or a code (`ATL`, `Bay 12`, `BAW1234`), so they're read only with at least six digits (100 m - or finer); with a space after the half's letter (`Z AC 77 62`) any precision reads, and a - 100 km square alone is written as the readout writes it, `Z AC`, in capitals. A UTM zone's - position past 84° N or 80° S, or a polar letter after a - zone number (`38ZMB`), finds nothing and the list says how UPS is written. + letter, `Z 2077146 1562481` or `Y, 1735147, 2243078`. Polar MGRS has no zone number, so three + letters and a few digits look like a word or a code (`ATL`, `Bay 12`, the flight `BAW1234`); + search reads one only as a reference is written: as the readout writes it, with a space after + the half's letter and the square in capitals (`Z AC`, `Z AC 77 62`, `Z AC 77146 62481`), as + one word with at least six digits (`ZAC7714662481`, 100 m or finer), or in capitals before + two equal groups of digits (`ZAC 771 624`, `ZAC 77146 62481`). A UTM zone's position past + 84° N or 80° S, or a polar letter after a zone number (`38ZMB`), finds nothing and the list + says how UPS is written. A reference that doesn't exist (square letters the zone doesn't use, a northing or a square outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a From 63c92a9296c83c6cf3df2aa6855b40678fb23ca2 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:36:11 -0600 Subject: [PATCH 06/14] fix(search): a polar reading never hides features or places Letter-led text that reads as a polar reference may still be a code or a name (BAG123456, ATL 1200 1430, A ST 12). For such text search now always looks in the attribute tables, puts the polar place after their hits, and the search box still offers Search places. Grid errors show only for the readout's spaced form (Z DA 12345 12345). Also: zone 0 with a UTM band is a zone error again, the polar form check counts digits, the UPS projection check joins utm_vs_proj.rs, and doc fixes. --- crates/data/tests/ups_vs_proj.rs | 54 --------------- crates/data/tests/utm_vs_proj.rs | 45 ++++++++++++- crates/engine/src/cmd/search.rs | 110 ++++++++++++++++++++++++------- crates/geom/src/utm.rs | 6 +- crates/ui-egui/src/searchbox.rs | 4 +- docs/user-guide/maps.md | 8 ++- 6 files changed, 142 insertions(+), 85 deletions(-) delete mode 100644 crates/data/tests/ups_vs_proj.rs diff --git a/crates/data/tests/ups_vs_proj.rs b/crates/data/tests/ups_vs_proj.rs deleted file mode 100644 index 491782e336..0000000000 --- a/crates/data/tests/ups_vs_proj.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! UPS in `rustgis-geom` against proj4rs, which reprojects rasters and layers: polar -//! stereographic at UPS's scale of 0.994 and 2,000,000 m false origin (EPSG:5041 north, 5042 -//! south), at random places in both polar areas and at the poles, within a millimeter. - -use rustgis_data::raster::Crs; -use rustgis_geom::{Coord, ups}; - -/// A small deterministic generator (no dependency). -struct Lcg(u64); -impl Lcg { - fn next(&mut self) -> f64 { - self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); - (self.0 >> 11) as f64 / (1u64 << 53) as f64 - } -} - -fn proj(north: bool) -> rustgis_data::raster::Transformer { - let lat = if north { 90 } else { -90 }; - Crs::parse(&format!("+proj=stere +lat_0={lat} +lat_ts={lat} +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs")) - .unwrap() - .transformer() - .unwrap() -} - -/// Compares one place both ways; returns the largest difference in meters. -fn compare(t: &rustgis_data::raster::Transformer, p: Coord, north: bool) -> f64 { - let (e, n) = ups::to_ups_in_zone(p, north).unwrap(); - let want = t.from_lonlat(p).unwrap(); - let dm = (e - want.x).abs().max((n - want.y).abs()); - assert!(dm < 1e-3, "north {north} at {p:?}: ours {e} {n}, proj4rs {} {}", want.x, want.y); - let back = ups::from_ups(north, want.x, want.y).unwrap(); - let theirs = t.to_lonlat(want).unwrap(); - // Compare on the ground: near the pole a millimeter is many degrees of longitude. - let (x, y) = ups::to_ups_in_zone(back, north).unwrap(); - let (tx, ty) = ups::to_ups_in_zone(theirs, north).unwrap(); - assert!((x - tx).abs().max((y - ty).abs()) < 1e-3, "north {north} at {p:?}: ours {back:?}, proj4rs {theirs:?}"); - dm -} - -#[test] -fn random_polar_places_agree_with_proj4rs() { - let mut r = Lcg(2026); - let (north_t, south_t) = (proj(true), proj(false)); - let mut worst = 0.0f64; - for _ in 0..5_000 { - let lon = -180.0 + r.next() * 360.0; - worst = worst.max(compare(&north_t, Coord::new(lon, 84.0 + r.next() * 6.0), true)); - worst = worst.max(compare(&south_t, Coord::new(lon, -80.0 - 1e-9 - r.next() * (10.0 - 2e-9)), false)); - } - for (p, north) in [(Coord::new(0.0, 90.0), true), (Coord::new(0.0, -90.0), false), (Coord::new(180.0, 84.0), true)] { - worst = worst.max(compare(if north { &north_t } else { &south_t }, p, north)); - } - assert!(worst < 1e-3, "worst {worst} m"); -} diff --git a/crates/data/tests/utm_vs_proj.rs b/crates/data/tests/utm_vs_proj.rs index 4b96b9205f..9a5560582a 100644 --- a/crates/data/tests/utm_vs_proj.rs +++ b/crates/data/tests/utm_vs_proj.rs @@ -1,9 +1,11 @@ //! The UTM series in `rustgis-geom` (Karney's Krüger series) against proj4rs, which reprojects //! rasters and layers: the same places in every zone and band, both hemispheres, the Norway -//! and Svalbard zones and the zones' edges, within a millimetre. +//! and Svalbard zones and the zones' edges, within a millimeter. And UPS, the grid of the polar +//! areas, against proj4rs's polar stereographic at UPS's scale of 0.994 and 2,000,000 m false +//! origin (EPSG:5041 north, 5042 south), at random polar places and at the poles. use rustgis_data::raster::Crs; -use rustgis_geom::{Coord, utm}; +use rustgis_geom::{Coord, ups, utm}; /// A small deterministic generator (no dependency). struct Lcg(u64); @@ -96,3 +98,42 @@ fn standard_zones_bands_and_exceptions_agree_with_proj4rs() { assert!((by_code.x - want.x).abs() < 1e-6 && (by_code.y - want.y).abs() < 1e-6, "EPSG:{epsg}"); } } + +fn ups_proj(north: bool) -> rustgis_data::raster::Transformer { + let lat = if north { 90 } else { -90 }; + Crs::parse(&format!("+proj=stere +lat_0={lat} +lat_ts={lat} +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs")) + .unwrap() + .transformer() + .unwrap() +} + +/// Compares one polar place both ways; returns the largest difference in meters. +fn compare_ups(t: &rustgis_data::raster::Transformer, p: Coord, north: bool) -> f64 { + let (e, n) = ups::to_ups_in_zone(p, north).unwrap(); + let want = t.from_lonlat(p).unwrap(); + let dm = (e - want.x).abs().max((n - want.y).abs()); + assert!(dm < 1e-3, "north {north} at {p:?}: ours {e} {n}, proj4rs {} {}", want.x, want.y); + let back = ups::from_ups(north, want.x, want.y).unwrap(); + let theirs = t.to_lonlat(want).unwrap(); + // Compare on the ground: near the pole a millimeter is many degrees of longitude. + let (x, y) = ups::to_ups_in_zone(back, north).unwrap(); + let (tx, ty) = ups::to_ups_in_zone(theirs, north).unwrap(); + assert!((x - tx).abs().max((y - ty).abs()) < 1e-3, "north {north} at {p:?}: ours {back:?}, proj4rs {theirs:?}"); + dm +} + +#[test] +fn random_polar_places_agree_with_proj4rs() { + let mut r = Lcg(2026); + let (north_t, south_t) = (ups_proj(true), ups_proj(false)); + let mut worst = 0.0f64; + for _ in 0..5_000 { + let lon = -180.0 + r.next() * 360.0; + worst = worst.max(compare_ups(&north_t, Coord::new(lon, 84.0 + r.next() * 6.0), true)); + worst = worst.max(compare_ups(&south_t, Coord::new(lon, -80.0 - 1e-9 - r.next() * (10.0 - 2e-9)), false)); + } + for (p, north) in [(Coord::new(0.0, 90.0), true), (Coord::new(0.0, -90.0), false), (Coord::new(180.0, 84.0), true)] { + worst = worst.max(compare_ups(if north { &north_t } else { &south_t }, p, north)); + } + assert!(worst < 1e-3, "worst {worst} m"); +} diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index ff5a16443f..ec77b4b98c 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -136,6 +136,10 @@ pub struct Results { /// that doesn't hold its northing, square letters the zone doesn't use, `S` that may mean /// south); `None` when it isn't written as one, or reads. pub grid_error: Option, + /// Whether the coordinate among the hits was read from text that may as well be a name or a + /// code: a polar (UPS) reference, which starts with a letter (`BAG123456`). The search box + /// still offers to look the text up as a place. + pub coordinate_may_be_text: bool, } /// Searches the active map for `query`: a coordinate first, then layers, bookmarks and features. @@ -154,14 +158,18 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // zone and band) isn't looked for in the tables; two whole numbers (an id, years, a range) // may be either, and so may a bare 100 km MGRS square, which names Sentinel-2's tiles (33UVP); // an MGRS reference with digits is plainly a coordinate. UTM and MGRS are the Earth's grids, - // so on another body's map they name no place. Polar (UPS) references have no zone number; - // the parser tells them from words (`Z AH` and `ZAH1234512345` are references; `ZAH`, `ATL`, `BAW1234` and `Bay 12` are text). + // so on another body's map they name no place. Polar (UPS) references and positions start + // with a letter, as names and codes do (`BAG123456`, `A ST 12`): read_grid_reference reads + // them only as references are written ([`polar_form`]), and even then the tables are still + // searched and the place comes after their hits, so a feature named so is found first. let mut plainly_coordinate = false; + let mut polar_place = None; if let Some(c) = parse_lat_lon(&q) { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); } else if map.body().is_earth() { match read_grid_reference(&q) { + Ok(c) if letter_led(&q) => polar_place = Some(c), Ok(c) => { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = rustgis_geom::parse_mgrs(&q).map_or(true, |m| m.digits > 0); @@ -238,7 +246,13 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { } } } - out.hits.truncate(limit.max(1)); + let limit = limit.max(1); + if let Some(c) = polar_place { + // After the other hits, but within the limit. + out.hits.insert(out.hits.len().min(limit - 1), Hit::Coordinate { lon: c.x, lat: c.y }); + out.coordinate_may_be_text = true; + } + out.hits.truncate(limit); out } @@ -414,8 +428,18 @@ pub fn parse_grid_reference(text: &str) -> Option { /// references are ([`written_as_polar_reference`]); UPS positions (`north 2077146 1562481`) are /// read as [`rustgis_geom::parse_utm`] reads them. pub fn read_grid_reference(text: &str) -> Result { - let letter_led = text.trim_start().starts_with(|c: char| c.is_ascii_alphabetic()); - let mgrs = if letter_led && !written_as_polar_reference(text) { Err(GridError::Syntax) } else { rustgis_geom::parse_mgrs(text) }; + let mgrs = if !letter_led(text) { + rustgis_geom::parse_mgrs(text) + } else { + match polar_form(text) { + // As the readout writes it: plainly meant as a reference, so it says why it names no + // place. + Some(PolarForm::Readout) => rustgis_geom::parse_mgrs(text), + // Compact forms look like codes too (`BAG123456`): read if they name a place, text if not. + Some(PolarForm::Compact) => rustgis_geom::parse_mgrs(text).map_err(|_| GridError::Syntax), + None => Err(GridError::Syntax), + } + }; match mgrs { Ok(m) => m.centre(), Err(mgrs) => match rustgis_geom::parse_utm(text) { @@ -426,36 +450,51 @@ pub fn read_grid_reference(text: &str) -> Result { } } -/// Whether letter-led text is written as a polar (UPS) MGRS reference is, rather than as a word -/// or code that happens to read as one (`ATL`, `Bay 12`, the flight `BAW1234`, `A St 12`, -/// `Apt 123456`): -/// - as the readout writes it: the half's letter, a space and the square's letters, in capitals -/// (`Z AH`, `Z AH 12 34`); -/// - as one word with at least six digits attached, 100 m or finer (`ZAC7714662481`, any case); -/// - or with the three letters in capitals before two equal groups of at least three digits -/// (`ZFD 927 072`, `ZFD 92767 07232`). -fn written_as_polar_reference(text: &str) -> bool { +/// Whether text starts with a letter, as a polar (UPS) MGRS reference or position does; no +/// other grid reference does. +fn letter_led(text: &str) -> bool { + text.trim_start().starts_with(|c: char| c.is_ascii_alphabetic()) +} + +/// How letter-led text is written as a polar MGRS reference, if it is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PolarForm { + /// As the readout writes it: the half's letter, a space and the square's letters, in + /// capitals (`Z AH`, `Z AH 12 34`). + Readout, + /// As one word with at least six digits attached, 100 m or finer (`ZAC7714662481`, any + /// case), or the three letters in capitals before two equal groups of at least three digits + /// (`ZFD 927 072`). + Compact, +} + +/// How letter-led text is written as a polar MGRS reference ([`PolarForm`]), rather than +/// as a word or code that happens to read as one (`ATL`, `Bay 12`, the flight `BAW1234`, +/// `A St 12`, `Apt 123456`); `None` for those. +fn polar_form(text: &str) -> Option { let mut chars = text.trim().chars(); - let Some(half) = chars.next() else { return false }; + let half = chars.next()?; let rest = chars.as_str(); let spaced = rest.starts_with(char::is_whitespace); let rest = rest.trim_start(); let letters: Vec = rest.chars().take(2).collect(); if letters.len() != 2 || !letters.iter().all(char::is_ascii_alphabetic) { - return false; + return None; } let capitals = half.is_ascii_uppercase() && letters.iter().all(char::is_ascii_uppercase); if spaced { - return capitals; + return capitals.then_some(PolarForm::Readout); } // The two letters are ASCII, so the digits start two bytes on. let after = rest.get(2..).unwrap_or(""); let attached = after.starts_with(|c: char| c.is_ascii_digit()); - match after.split_whitespace().collect::>().as_slice() { - [run] if attached => run.len() >= 6, - [e, n] => capitals && e.len() == n.len() && e.len() >= 3, + let digits = |s: &str| s.chars().filter(char::is_ascii_digit).count() == s.len(); + let compact = match after.split_whitespace().collect::>().as_slice() { + [run] if attached => digits(run) && run.len() >= 6, + [e, n] => capitals && digits(e) && digits(n) && e.len() == n.len() && e.len() >= 3, _ => false, - } + }; + compact.then_some(PolarForm::Compact) } /// Whether `text` has spaces and no digits after its leading number: written so, an MGRS @@ -911,9 +950,32 @@ mod tests { // A reference written as one, but with fewer than six digits as one word, is text: the // flight BAW1234 looks the same as ZAH1234. assert!(!search(&s, "ZAH1234", 50).hits.iter().any(|h| matches!(h, Hit::Coordinate { .. }))); - // A polar reference that names no place says why. - assert_eq!(search(&s, "ZDA1234512345", 50).grid_error, Some(GridError::Square)); - assert_eq!(search(&s, "YRA1234512345", 50).grid_error, Some(GridError::OutsideZone)); + // A polar reference written as the readout writes it that names no place says why; a + // compact one may be a code (`ABC123456`), so it says nothing. + assert_eq!(search(&s, "Z DA 12345 12345", 50).grid_error, Some(GridError::Square)); + assert_eq!(search(&s, "Y RA 12345 12345", 50).grid_error, Some(GridError::OutsideZone)); + for q in ["ZDA1234512345", "YRA1234512345", "ABC123456", "YAA123456"] { + assert_eq!(search(&s, q, 50).grid_error, None, "{q}"); + } + } + + /// A code that also reads as a polar reference (`BAG123456` is B AG 123 456, a place in + /// Antarctica) is still looked for in the tables, and a feature named so comes first, so + /// Enter or `go` goes to it rather than to the pole. + #[test] + fn features_named_like_polar_references_come_first() { + let mut s = Session::new(crate::sample::world_project()); + s.run("layer.addDataText", &json!({"fileName": "parts.csv", "text": "part,lon,lat\nBAG123456,10.0,50.0\n"})).unwrap(); + for q in ["BAG123456", "bag123456"] { + let r = search(&s, q, 50); + assert!(matches!(r.hits.first(), Some(Hit::Feature { value, .. }) if value == "BAG123456"), "{q}: {r:?}"); + assert!(r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); + } + // With no feature named so, the place is the first hit, and within the limit; it may still + // be text, so the search box offers places too. A UTM reference is plainly a coordinate. + let r = search(&s, "ZAC7714662481", 1); + assert!(matches!(r.hits.as_slice(), [Hit::Coordinate { .. }]) && r.coordinate_may_be_text); + assert!(!search(&s, "38SMB4414084706", 50).coordinate_may_be_text); } #[test] diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index 88680b38d2..ab69365e3f 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -534,7 +534,8 @@ fn cell_latitudes(zone: u8, north: bool, e0: f64, n0: f64, cell: f64) -> Option< /// The centre of the cell an MGRS reference names: the 2,000 km row cycle is settled by the band, /// which the cell must reach into. fn locate(m: &Mgrs) -> Result { - if m.polar() { + // Zone 0 with a polar half's letter is UPS; with any other letter it is a bad UTM zone. + if m.polar() && crate::ups::is_polar_half(m.band) { return locate_polar(m); } if !(1..=60).contains(&m.zone) { @@ -1530,6 +1531,9 @@ mod tests { #[test] fn polar_references_that_name_no_place_are_refused() { + // Built by hand, zone 0 with a UTM band is a bad zone, not a bad band. + let m = Mgrs { zone: 0, band: 'U', column: 'V', row: 'P', easting: 0, northing: 0, digits: 0 }; + assert_eq!(m.centre(), Err(GridError::Zone)); for (text, why) in [ ("ZDA", GridError::Square), // Z skips D and E ("Z DA", GridError::Square), // spaced, the same diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index b971d8437b..76c0c017c6 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -106,8 +106,10 @@ pub fn had_focus(st: &State, pass: u64) -> bool { st.focus_pass.is_some_and(|p| p + 1 == pass) } +/// Whether the query reads as a coordinate and nothing else, so looking it up as a place is no +/// use. A polar reference may as well be a name or a code (`BAG123456`), so it isn't. fn is_coordinate(st: &State) -> bool { - matches!(st.results.hits.first(), Some(Hit::Coordinate { .. })) + matches!(st.results.hits.first(), Some(Hit::Coordinate { .. })) && !st.results.coordinate_may_be_text } /// The box, at the bottom of the left pane (`ui` is the pane). diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 95030ea00f..650c1fa2ba 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -194,9 +194,11 @@ their own rules, below): search reads one only as a reference is written: as the readout writes it, with a space after the half's letter and the square in capitals (`Z AC`, `Z AC 77 62`, `Z AC 77146 62481`), as one word with at least six digits (`ZAC7714662481`, 100 m or finer), or in capitals before - two equal groups of digits (`ZAC 771 624`, `ZAC 77146 62481`). A UTM zone's position past - 84° N or 80° S, or a polar letter after a zone number (`38ZMB`), finds nothing and the list - says how UPS is written. + two equal groups of at least three digits (`ZAC 771 624`, `ZAC 77146 62481`). Since such text + may also be a name or a code, the attribute tables are still searched, their hits come before + the polar place, and **Search places** is still offered. A UTM zone's position past 84° N or + 80° S, or a polar letter after a zone number (`38ZMB`), finds nothing and the list says how UPS + is written. A reference that doesn't exist (square letters the zone doesn't use, a northing or a square outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a From b3b21bfdc5a3bc490fdaee0240f5dd20a5eca442 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:54:04 -0600 Subject: [PATCH 07/14] fix(search): keep features first at limit 1, trust pasted readouts With limit 1 a polar place could push out a feature named like it, so go jumped to the pole. It's now listed then only when nothing else matched. Text pasted from the readout (north 2077146 1562481, Z AC 77146 62481) is plainly a coordinate again and comes first. map.search answers coordinateMayBeText for the ambiguous case, and its help lists the polar forms. --- crates/engine/src/cmd/search.rs | 47 ++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index ec77b4b98c..9e3b6d7973 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -17,7 +17,7 @@ pub fn commands() -> Vec { vec![ // Not a view command: going to a feature selects it. C::new("map.search", "Search", "Map", search_cmd).inputs(search_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"query": "a latitude and longitude (40.7, -74.0; 40°42'N 74°0'W), a UTM position (33U 412345 5523456; 33 north 412345 5523456) or an MGRS reference (33UVP1234523456; 33U VP 12345 23456), a layer, a bookmark or a value in a layer's table", "limit"?: 1–50, "go"?: true (the first hit) | index}"#, + r#"{"query": "a latitude and longitude (40.7, -74.0; 40°42'N 74°0'W), a UTM position (33U 412345 5523456; 33 north 412345 5523456) or an MGRS reference (33UVP1234523456; 33U VP 12345 23456), north of 84° N or south of 80° S UPS (north 2077146 1562481) or polar MGRS (Z AC 77146 62481; ZAC7714662481), a layer, a bookmark or a value in a layer's table. Polar text that may be a name or a code (BAG123456) lists table hits first and answers coordinateMayBeText", "limit"?: 1–50, "go"?: true (the first hit) | index}"#, ), ] } @@ -142,7 +142,8 @@ pub struct Results { pub coordinate_may_be_text: bool, } -/// Searches the active map for `query`: a coordinate first, then layers, bookmarks and features. +/// Searches the active map for `query`: a coordinate first, then layers, bookmarks and features; a +/// polar reference that may be a name or a code comes after them (see [`Results`]). pub fn search(s: &Session, query: &str, limit: usize) -> Results { search_map(s.map(), query, limit) } @@ -169,7 +170,7 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { plainly_coordinate = q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); } else if map.body().is_earth() { match read_grid_reference(&q) { - Ok(c) if letter_led(&q) => polar_place = Some(c), + Ok(c) if letter_led(&q) && !as_the_readout_writes_it(&q) => polar_place = Some(c), Ok(c) => { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = rustgis_geom::parse_mgrs(&q).map_or(true, |m| m.digits > 0); @@ -247,8 +248,9 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { } } let limit = limit.max(1); - if let Some(c) = polar_place { - // After the other hits, but within the limit. + // After the other hits, within the limit; with room for one hit only, the place is listed only + // when nothing else matched, so a feature named like the reference stays the one to go to. + if let Some(c) = polar_place.filter(|_| out.hits.is_empty() || limit > 1) { out.hits.insert(out.hits.len().min(limit - 1), Hit::Coordinate { lon: c.x, lat: c.y }); out.coordinate_may_be_text = true; } @@ -407,6 +409,10 @@ fn search_cmd(s: &mut Session, p: &Value) -> CmdResult { if let Some(e) = r.grid_error { out["gridError"] = json!(e.to_string()); } + if r.coordinate_may_be_text { + // The coordinate hit came from polar grid text that may as well be a name or a code. + out["coordinateMayBeText"] = json!(true); + } Ok(out) } @@ -425,7 +431,7 @@ pub fn parse_grid_reference(text: &str) -> Option { /// number and a word as often as a reference, so one that names no square is /// [`GridError::Syntax`] too; written as one word (`38TMJ`), it says why. A polar reference has /// no zone number, so text that starts with a letter is read as one only when written as -/// references are ([`written_as_polar_reference`]); UPS positions (`north 2077146 1562481`) are +/// references are ([`polar_form`]); UPS positions (`north 2077146 1562481`) are /// read as [`rustgis_geom::parse_utm`] reads them. pub fn read_grid_reference(text: &str) -> Result { let mgrs = if !letter_led(text) { @@ -456,6 +462,20 @@ fn letter_led(text: &str) -> bool { text.trim_start().starts_with(|c: char| c.is_ascii_alphabetic()) } +/// Whether polar text is written exactly as the readout and its copy write a place, so it is +/// plainly a coordinate rather than a name or a code: UPS with the zone spelled out +/// (`north 2077146 1562481`), or polar MGRS spaced, in capitals, to the meter +/// (`Z AC 77146 62481`). +fn as_the_readout_writes_it(text: &str) -> bool { + let text = text.trim(); + let word = text.split_whitespace().next().unwrap_or("").to_ascii_lowercase(); + if word == "north" || word == "south" { + return true; + } + polar_form(text) == Some(PolarForm::Readout) + && matches!(text.split_whitespace().collect::>().as_slice(), [_, _, e, n] if e.len() == 5 && n.len() == 5) +} + /// How letter-led text is written as a polar MGRS reference, if it is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum PolarForm { @@ -488,7 +508,7 @@ fn polar_form(text: &str) -> Option { // The two letters are ASCII, so the digits start two bytes on. let after = rest.get(2..).unwrap_or(""); let attached = after.starts_with(|c: char| c.is_ascii_digit()); - let digits = |s: &str| s.chars().filter(char::is_ascii_digit).count() == s.len(); + let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit()); let compact = match after.split_whitespace().collect::>().as_slice() { [run] if attached => digits(run) && run.len() >= 6, [e, n] => capitals && digits(e) && digits(n) && e.len() == n.len() && e.len() >= 3, @@ -970,12 +990,25 @@ mod tests { let r = search(&s, q, 50); assert!(matches!(r.hits.first(), Some(Hit::Feature { value, .. }) if value == "BAG123456"), "{q}: {r:?}"); assert!(r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); + // With room for one hit, it is the feature, not the place. + let one = search(&s, q, 1); + assert!(matches!(one.hits.as_slice(), [Hit::Feature { .. }]), "{q}: {one:?}"); } + // `go` goes to the feature, and the answer says the place may be text. + let v = s.run("map.search", &json!({"query": "BAG123456", "limit": 1, "go": true})).unwrap(); + assert!(v["hits"][0]["kind"] == "feature", "{v}"); + let v = s.run("map.search", &json!({"query": "BAG123456"})).unwrap(); + assert_eq!(v["coordinateMayBeText"], json!(true), "{v}"); // With no feature named so, the place is the first hit, and within the limit; it may still // be text, so the search box offers places too. A UTM reference is plainly a coordinate. let r = search(&s, "ZAC7714662481", 1); assert!(matches!(r.hits.as_slice(), [Hit::Coordinate { .. }]) && r.coordinate_may_be_text); assert!(!search(&s, "38SMB4414084706", 50).coordinate_may_be_text); + // Pasted from the readout, a polar place is plainly a coordinate: first, and no place search. + for q in ["north 2077146 1562481", "South 2096454 1452981", "Z AC 77146 62481"] { + let r = search(&s, q, 50); + assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })) && !r.coordinate_may_be_text, "{q}: {r:?}"); + } } #[test] From ec774254d3d46b0d6d94309303412b9dd5f5238c Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:11:52 -0600 Subject: [PATCH 08/14] fix(search): UPS positions are plainly places; docs match UPS written with the zone or the half's letter (north 2077146 1562481, Z 2077146 1562481, Y, 1735147, 2243078, with or without commas) is now plainly a place, like a pasted MGRS readout. The user guide and comments now say which polar text is read as a place only and which is still looked up as text. The readout's hover says UTM and MGRS are the Earth's grids, and the menu drops a hover case real points can't reach. More search tests pin the readout cases and limit 1. --- crates/engine/src/cmd/search.rs | 42 +++++++++++++++++++++++------- crates/ui-egui/src/coordreadout.rs | 2 +- crates/ui-egui/src/mapmenu.rs | 5 ---- docs/user-guide/maps.md | 9 ++++--- 4 files changed, 40 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 9e3b6d7973..028d459ed6 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -137,8 +137,9 @@ pub struct Results { /// south); `None` when it isn't written as one, or reads. pub grid_error: Option, /// Whether the coordinate among the hits was read from text that may as well be a name or a - /// code: a polar (UPS) reference, which starts with a letter (`BAG123456`). The search box - /// still offers to look the text up as a place. + /// code: a polar (UPS) reference, which starts with a letter (`BAG123456`), unless written + /// exactly as the readout writes it ([`as_the_readout_writes_it`]). The search box still + /// offers to look the text up as a place. pub coordinate_may_be_text: bool, } @@ -161,8 +162,9 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // an MGRS reference with digits is plainly a coordinate. UTM and MGRS are the Earth's grids, // so on another body's map they name no place. Polar (UPS) references and positions start // with a letter, as names and codes do (`BAG123456`, `A ST 12`): read_grid_reference reads - // them only as references are written ([`polar_form`]), and even then the tables are still - // searched and the place comes after their hits, so a feature named so is found first. + // them only as references are written ([`polar_form`]). Unless written exactly as the + // readout writes it ([`as_the_readout_writes_it`]), the tables are still searched and the + // place comes after their hits, so a feature named so is found first. let mut plainly_coordinate = false; let mut polar_place = None; if let Some(c) = parse_lat_lon(&q) { @@ -468,8 +470,14 @@ fn letter_led(text: &str) -> bool { /// (`Z AC 77146 62481`). fn as_the_readout_writes_it(text: &str) -> bool { let text = text.trim(); - let word = text.split_whitespace().next().unwrap_or("").to_ascii_lowercase(); - if word == "north" || word == "south" { + // The word may be followed by a comma, as parse_ups reads it (`north, 2077146, 1562481`). + // UPS with the zone or the half's letter before two numbers in the lettered area + // (`Y, 1735147, 2243078`) is plainly a position: no name or code is written that way. + let word = text.split(|c: char| c.is_whitespace() || c == ',').next().unwrap_or("").to_ascii_lowercase(); + if matches!(word.as_str(), "north" | "south") { + return true; + } + if matches!(word.as_str(), "y" | "z" | "a" | "b") && rustgis_geom::parse_ups(text).is_ok() { return true; } polar_form(text) == Some(PolarForm::Readout) @@ -1004,10 +1012,26 @@ mod tests { let r = search(&s, "ZAC7714662481", 1); assert!(matches!(r.hits.as_slice(), [Hit::Coordinate { .. }]) && r.coordinate_may_be_text); assert!(!search(&s, "38SMB4414084706", 50).coordinate_may_be_text); - // Pasted from the readout, a polar place is plainly a coordinate: first, and no place search. - for q in ["north 2077146 1562481", "South 2096454 1452981", "Z AC 77146 62481"] { + // At limit 1 with a feature, the answer doesn't claim a place it left out. + let v = s.run("map.search", &json!({"query": "BAG123456", "limit": 1})).unwrap(); + assert!(v.get("coordinateMayBeText").is_none(), "{v}"); + // Pasted from the readout, a polar place is plainly a coordinate: first, no place search, + // and the tables aren't searched (a value written the same is not a hit). + s.run("layer.addDataText", &json!({"fileName": "odd.csv", "text": "v,lon,lat\nZ AC 77146 62481,1.0,1.0\n"})).unwrap(); + for q in [ + "north 2077146 1562481", + "South 2096454 1452981", + "north, 2077146, 1562481", + "Z AC 77146 62481", + "Z 2077146 1562481", + "Y, 1735147, 2243078", + ] { let r = search(&s, q, 50); - assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })) && !r.coordinate_may_be_text, "{q}: {r:?}"); + assert!(matches!(r.hits.as_slice(), [Hit::Coordinate { .. }]) && !r.coordinate_may_be_text, "{q}: {r:?}"); + } + // Shorter than the readout writes it, it may still be text. + for q in ["Z AC 7714 6248", "Z AC", "ZAC7714662481"] { + assert!(search(&s, q, 50).coordinate_may_be_text, "{q}"); } } diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs index a0f7496fb0..e1f1ff170a 100644 --- a/crates/ui-egui/src/coordreadout.rs +++ b/crates/ui-egui/src/coordreadout.rs @@ -99,7 +99,7 @@ impl CoordReadout { /// and MGRS read near the poles. pub fn hover(self) -> String { i18n::fmt( - "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. North of 84° N and south of 80° S, UTM and MGRS read in UPS.", + "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. UTM and MGRS are grids of the Earth, read in UPS north of 84° N and south of 80° S.", &[("format", self.label())], ) } diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index ad38b3dc81..ad577f4eeb 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -129,11 +129,6 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { "Copy coordinates to the clipboard. {format} is a grid of the Earth, so latitude and longitude are copied", &[("format", format.label())], ) - } else if fell_back { - i18n::fmt( - "Copy coordinates to the clipboard. No {format} here, so latitude and longitude are copied", - &[("format", format.label())], - ) } else { tl!("Copy coordinates to the clipboard").to_string() }; diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 650c1fa2ba..e3024e91c4 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -194,9 +194,12 @@ their own rules, below): search reads one only as a reference is written: as the readout writes it, with a space after the half's letter and the square in capitals (`Z AC`, `Z AC 77 62`, `Z AC 77146 62481`), as one word with at least six digits (`ZAC7714662481`, 100 m or finer), or in capitals before - two equal groups of at least three digits (`ZAC 771 624`, `ZAC 77146 62481`). Since such text - may also be a name or a code, the attribute tables are still searched, their hits come before - the polar place, and **Search places** is still offered. A UTM zone's position past 84° N or + two equal groups of at least three digits (`ZAC 771 624`, `ZAC 77146 62481`). A UPS position + (`north 2077146 1562481`, `Z 2077146 1562481`) and a reference written exactly as the readout + writes it (`Z AC 77146 62481`) are plainly places. Any + other polar text may also be a name or a code, so the attribute tables are still searched, + their hits come before the polar place, and **Search places** is still offered; with room + for one hit (`limit: 1`), a matching feature is the hit. A UTM zone's position past 84° N or 80° S, or a polar letter after a zone number (`38ZMB`), finds nothing and the list says how UPS is written. From 299fc80901028011c390c267e989f97f73a7f207 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:29:32 -0600 Subject: [PATCH 09/14] fix(geom): read GeographicLib's n/s UPS, say why a north/south typo fails parse_ups reads GeographicLib's short form (n 2392768 1607232), and a mistyped position after north or south (both numbers 100 km or more but outside the lettered area) now says it's outside the zone instead of nothing; north 10 20 and A 10 20 stay text. The Polar message shows a south example too, and the user guide documents coordinateMayBeText. --- crates/engine/src/cmd/search.rs | 18 +++++++++--------- crates/geom/src/ups.rs | 27 +++++++++++++++++---------- crates/geom/src/utm.rs | 9 ++++++--- crates/ui-egui/src/searchbox.rs | 2 +- docs/user-guide/maps.md | 4 +++- 5 files changed, 36 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 028d459ed6..0aabd2d5cd 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -138,7 +138,7 @@ pub struct Results { pub grid_error: Option, /// Whether the coordinate among the hits was read from text that may as well be a name or a /// code: a polar (UPS) reference, which starts with a letter (`BAG123456`), unless written - /// exactly as the readout writes it ([`as_the_readout_writes_it`]). The search box still + /// exactly as the readout writes it ([`plainly_polar_place`]). The search box still /// offers to look the text up as a place. pub coordinate_may_be_text: bool, } @@ -163,7 +163,7 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // so on another body's map they name no place. Polar (UPS) references and positions start // with a letter, as names and codes do (`BAG123456`, `A ST 12`): read_grid_reference reads // them only as references are written ([`polar_form`]). Unless written exactly as the - // readout writes it ([`as_the_readout_writes_it`]), the tables are still searched and the + // readout writes it ([`plainly_polar_place`]), the tables are still searched and the // place comes after their hits, so a feature named so is found first. let mut plainly_coordinate = false; let mut polar_place = None; @@ -172,7 +172,7 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { plainly_coordinate = q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); } else if map.body().is_earth() { match read_grid_reference(&q) { - Ok(c) if letter_led(&q) && !as_the_readout_writes_it(&q) => polar_place = Some(c), + Ok(c) if letter_led(&q) && !plainly_polar_place(&q) => polar_place = Some(c), Ok(c) => { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = rustgis_geom::parse_mgrs(&q).map_or(true, |m| m.digits > 0); @@ -464,17 +464,17 @@ fn letter_led(text: &str) -> bool { text.trim_start().starts_with(|c: char| c.is_ascii_alphabetic()) } -/// Whether polar text is written exactly as the readout and its copy write a place, so it is -/// plainly a coordinate rather than a name or a code: UPS with the zone spelled out -/// (`north 2077146 1562481`), or polar MGRS spaced, in capitals, to the meter -/// (`Z AC 77146 62481`). -fn as_the_readout_writes_it(text: &str) -> bool { +/// Whether polar text is plainly a place rather than a name or a code: any UPS position +/// [`rustgis_geom::parse_ups`] reads, led by the zone (`north 2077146 1562481`, `n …`) or the +/// half's letter (`Z 2077146 1562481`, `Y, 1735147, 2243078`), or polar MGRS written as the +/// readout writes it, spaced, in capitals, to the meter (`Z AC 77146 62481`). +fn plainly_polar_place(text: &str) -> bool { let text = text.trim(); // The word may be followed by a comma, as parse_ups reads it (`north, 2077146, 1562481`). // UPS with the zone or the half's letter before two numbers in the lettered area // (`Y, 1735147, 2243078`) is plainly a position: no name or code is written that way. let word = text.split(|c: char| c.is_whitespace() || c == ',').next().unwrap_or("").to_ascii_lowercase(); - if matches!(word.as_str(), "north" | "south") { + if matches!(word.as_str(), "north" | "south" | "n" | "s") { return true; } if matches!(word.as_str(), "y" | "z" | "a" | "b") && rustgis_geom::parse_ups(text).is_ok() { diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs index 2805e0ce5e..d2a6cd96b5 100644 --- a/crates/geom/src/ups.rs +++ b/crates/geom/src/ups.rs @@ -278,13 +278,16 @@ pub(crate) fn is_polar_half(letter: char) -> bool { } /// Reads a UPS position, which has no zone number: the zone spelled out, `north 2392768 1607232` -/// or `south 2096454 1452981` (any case), as the readout writes it, or the polar half's letter -/// before the easting and northing, `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and -/// A lie west of the 2,000,000 m easting (or on it, for a rounded coordinate) and Z and B on or -/// east of it. Numbers outside the zone's -/// lettered area (north 1,300,000 up to 2,700,000 m, south 800,000 up to 3,200,000 m) aren't a UPS -/// position and read as text ([`GridError::Syntax`]); a place inside it must lie in the zone, at -/// 84° N or more or south of 80° S, give or take the meter it was rounded to. +/// or `south 2096454 1452981` (any case), as the readout writes it, or as GeographicLib's short +/// form, `n 2392768 1607232`; or the polar half's letter before the easting and northing, +/// `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and A lie west of the 2,000,000 m +/// easting (or on it, for a rounded coordinate) and Z and B on or east of it. Numbers outside the +/// zone's lettered area (north 1,300,000 up to 2,700,000 m, south 800,000 up to 3,200,000 m) +/// aren't a UPS position: after `north` or `south` and with both numbers at least 100,000 m they +/// are a mistyped one ([`GridError::OutsideZone`]); otherwise text ([`GridError::Syntax`], as +/// `A 10 20` is a road). A place inside it +/// must lie in the zone, at 84° N or more or south of 80° S, give or take the meter it was rounded +/// to. pub fn parse_ups(text: &str) -> Result { let text = text.trim(); if text.chars().count() > MAX_REF_CHARS { @@ -296,8 +299,8 @@ pub fn parse_ups(text: &str) -> Result { word.push(c.to_ascii_uppercase()); } let (north, half) = match word.as_str() { - "NORTH" => (true, None), - "SOUTH" => (false, None), + "NORTH" | "N" => (true, None), + "SOUTH" | "S" => (false, None), "Y" | "Z" => (true, word.chars().next()), "A" | "B" => (false, word.chars().next()), _ => return Err(GridError::Syntax), @@ -310,7 +313,11 @@ pub fn parse_ups(text: &str) -> Result { let (easting, northing) = easting_and_northing(&rest)?; // Numbers outside the zone's lettered area aren't a UPS position (`A 10 20`, a road): text. if !in_lettered_area(north, easting, northing) { - return Err(GridError::Syntax); + // After the zone spelled out, with numbers the size of UPS coordinates (a typo such as + // `north 20771461 1562481`), it is a position, so it says why; after a single letter, or + // with small numbers (`A 10 20`, `North 10 20`), it may be a road or a code: text. + let position = half.is_none() && word.len() > 1 && easting >= SQUARE && northing >= SQUARE; + return Err(if position { GridError::OutsideZone } else { GridError::Syntax }); } if half.is_some_and(|h| !easting_in_half(h, easting)) { return Err(GridError::OutsideZone); diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index ab69365e3f..21402ebacc 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -344,7 +344,7 @@ impl Mgrs { } /// Writes the zone and band as MGRS writes them: `33U`, `04Q`, or the polar half's letter alone - /// (`Z`), without building a string (the readout writes a reference every frame). + /// (`Z`), without building a string of its own. fn write_designator(&self, f: &mut impl fmt::Write) -> fmt::Result { if self.polar() { write!(f, "{}", self.band) } else { write!(f, "{:02}{}", self.zone, self.band) } } @@ -480,7 +480,7 @@ impl fmt::Display for GridError { GridError::Zone => "the UTM zone must be 1 to 60", GridError::Band => "the latitude band must be a letter from C to X (not I or O)", GridError::Polar => { - "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268 or Z AM 00000 44268" + "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268, south 2000000 1555732, or polar MGRS such as Z AM 00000 44268" } GridError::Square => "the 100 km square letters aren't used in this zone", GridError::Digits => "the grid digits must be an even count of 0 to 10, half for the easting and half for the northing", @@ -1567,6 +1567,8 @@ mod tests { assert!((p.x - 45.0).abs() < 1e-4 && (p.y - 85.0).abs() < 1e-4, "{p:?}"); assert_eq!(parse_utm("NORTH 2392768 1607232"), Ok(p)); assert_eq!(parse_utm("Z 2392768 1607232"), Ok(p)); + // GeographicLib's short form (`GeoConvert -u`). + assert_eq!(parse_utm("n 2392768 1607232"), Ok(p)); let q = parse_utm("Y, 1735147, 2243078").unwrap(); assert!(q.x < 0.0 && q.y > 84.0, "{q:?}"); let s = parse_utm("south 2096454 1452981").unwrap(); @@ -1577,7 +1579,8 @@ mod tests { ("A 2096454 1452981", GridError::OutsideZone), // east of 2,000,000 m is B ("north 2000000 1300000", GridError::OutsideZone), // lettered, but south of 84° N ("south 2000000 3150000", GridError::OutsideZone), // lettered, but north of 80° S - ("north 2000000 100000", GridError::Syntax), // outside the lettered area + ("north 2000000 100000", GridError::OutsideZone), // outside the lettered area, after the zone + ("A 2000000 100000", GridError::Syntax), // after a single letter it may be text ("A 10 20", GridError::Syntax), ("A1 12", GridError::Syntax), ("B 12, 34", GridError::Syntax), diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index 76c0c017c6..5533c9dc68 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -389,7 +389,7 @@ fn grid_error_text(e: rustgis_engine::geom::GridError) -> String { G::Zone => tl_raw!("the UTM zone must be 1 to 60"), G::Band => tl_raw!("the latitude band must be a letter from C to X (not I or O)"), G::Polar => tl_raw!( - "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268 or Z AM 00000 44268" + "north of 84° N and south of 80° S the grid is UPS, which has no zone number: write north 2000000 2444268, south 2000000 1555732, or polar MGRS such as Z AM 00000 44268" ), G::Square => tl_raw!("the 100 km square letters aren't used in this zone"), G::Digits => tl_raw!("the grid digits must be an even count of 0 to 10, half for the easting and half for the northing"), diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index e3024e91c4..26e953f966 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -205,7 +205,9 @@ their own rules, below): A reference that doesn't exist (square letters the zone doesn't use, a northing or a square outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a -place somewhere else, and the list says why; `map.search` returns the reason as `gridError`. A +place somewhere else, and the list says why; `map.search` returns the reason as `gridError`, and +adds `"coordinateMayBeText": true` when a polar place among its hits may as well be a name or a +code. A 100 km square written with spaces, such as `5 Ave` or `4K TV`, is as likely ordinary text, so one that names no square gives no reason; written as one word, `38TMJ`, it does. On the map of another body, grid references find nothing. From 0d996c90d4e412010121afd0bc15b3b08ee7e11f Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:46:17 -0600 Subject: [PATCH 10/14] fix(search): keep north 412345 5523456 and N/S pairs as text A UTM position typed without its zone (north 412345 5523456) said "outside the zone given"; numbers outside the lettered area after any zone word are text again. GeographicLib's short n/s UPS still reads, but as a place that may be text, since a bare N 1400000 2000000 can be a State Plane pair; tables are still searched for it. Doc comments and tests updated. --- crates/engine/src/cmd/search.rs | 17 +++++++++-------- crates/geom/src/ups.rs | 13 +++++-------- crates/geom/src/utm.rs | 7 +++++-- 3 files changed, 19 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 0aabd2d5cd..42c2da24dd 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -137,8 +137,8 @@ pub struct Results { /// south); `None` when it isn't written as one, or reads. pub grid_error: Option, /// Whether the coordinate among the hits was read from text that may as well be a name or a - /// code: a polar (UPS) reference, which starts with a letter (`BAG123456`), unless written - /// exactly as the readout writes it ([`plainly_polar_place`]). The search box still + /// code: a polar (UPS) reference, which starts with a letter (`BAG123456`), unless it is + /// plainly a place ([`plainly_polar_place`]). The search box still /// offers to look the text up as a place. pub coordinate_may_be_text: bool, } @@ -162,8 +162,8 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // an MGRS reference with digits is plainly a coordinate. UTM and MGRS are the Earth's grids, // so on another body's map they name no place. Polar (UPS) references and positions start // with a letter, as names and codes do (`BAG123456`, `A ST 12`): read_grid_reference reads - // them only as references are written ([`polar_form`]). Unless written exactly as the - // readout writes it ([`plainly_polar_place`]), the tables are still searched and the + // them only as references are written ([`polar_form`]). Unless plainly a + // place ([`plainly_polar_place`]), the tables are still searched and the // place comes after their hits, so a feature named so is found first. let mut plainly_coordinate = false; let mut polar_place = None; @@ -465,8 +465,9 @@ fn letter_led(text: &str) -> bool { } /// Whether polar text is plainly a place rather than a name or a code: any UPS position -/// [`rustgis_geom::parse_ups`] reads, led by the zone (`north 2077146 1562481`, `n …`) or the -/// half's letter (`Z 2077146 1562481`, `Y, 1735147, 2243078`), or polar MGRS written as the +/// [`rustgis_geom::parse_ups`] reads, led by the zone spelled out (`north 2077146 1562481`; +/// GeographicLib's `n …` may be text, as `N 1400000 2000000` is a State Plane pair) or the half's +/// letter (`Z 2077146 1562481`, `Y, 1735147, 2243078`), or polar MGRS written as the /// readout writes it, spaced, in capitals, to the meter (`Z AC 77146 62481`). fn plainly_polar_place(text: &str) -> bool { let text = text.trim(); @@ -474,7 +475,7 @@ fn plainly_polar_place(text: &str) -> bool { // UPS with the zone or the half's letter before two numbers in the lettered area // (`Y, 1735147, 2243078`) is plainly a position: no name or code is written that way. let word = text.split(|c: char| c.is_whitespace() || c == ',').next().unwrap_or("").to_ascii_lowercase(); - if matches!(word.as_str(), "north" | "south" | "n" | "s") { + if matches!(word.as_str(), "north" | "south") { return true; } if matches!(word.as_str(), "y" | "z" | "a" | "b") && rustgis_geom::parse_ups(text).is_ok() { @@ -1030,7 +1031,7 @@ mod tests { assert!(matches!(r.hits.as_slice(), [Hit::Coordinate { .. }]) && !r.coordinate_may_be_text, "{q}: {r:?}"); } // Shorter than the readout writes it, it may still be text. - for q in ["Z AC 7714 6248", "Z AC", "ZAC7714662481"] { + for q in ["Z AC 7714 6248", "Z AC", "ZAC7714662481", "n 2077146 1562481", "N 2000000 1500000"] { assert!(search(&s, q, 50).coordinate_may_be_text, "{q}"); } } diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs index d2a6cd96b5..99b4d87f0f 100644 --- a/crates/geom/src/ups.rs +++ b/crates/geom/src/ups.rs @@ -283,9 +283,8 @@ pub(crate) fn is_polar_half(letter: char) -> bool { /// `Y, 1735147, 2243078` (NGA.STND.0037 App. A-4), where Y and A lie west of the 2,000,000 m /// easting (or on it, for a rounded coordinate) and Z and B on or east of it. Numbers outside the /// zone's lettered area (north 1,300,000 up to 2,700,000 m, south 800,000 up to 3,200,000 m) -/// aren't a UPS position: after `north` or `south` and with both numbers at least 100,000 m they -/// are a mistyped one ([`GridError::OutsideZone`]); otherwise text ([`GridError::Syntax`], as -/// `A 10 20` is a road). A place inside it +/// aren't a UPS position and read as text ([`GridError::Syntax`]): `A 10 20` is a road, and +/// `north 412345 5523456` a UTM position without its zone. A place inside it /// must lie in the zone, at 84° N or more or south of 80° S, give or take the meter it was rounded /// to. pub fn parse_ups(text: &str) -> Result { @@ -313,11 +312,9 @@ pub fn parse_ups(text: &str) -> Result { let (easting, northing) = easting_and_northing(&rest)?; // Numbers outside the zone's lettered area aren't a UPS position (`A 10 20`, a road): text. if !in_lettered_area(north, easting, northing) { - // After the zone spelled out, with numbers the size of UPS coordinates (a typo such as - // `north 20771461 1562481`), it is a position, so it says why; after a single letter, or - // with small numbers (`A 10 20`, `North 10 20`), it may be a road or a code: text. - let position = half.is_none() && word.len() > 1 && easting >= SQUARE && northing >= SQUARE; - return Err(if position { GridError::OutsideZone } else { GridError::Syntax }); + // Not a UPS position: a road or a code (`A 10 20`), or a UTM position without its zone + // (`north 412345 5523456`), which "outside the zone" would mislead about. Text. + return Err(GridError::Syntax); } if half.is_some_and(|h| !easting_in_half(h, easting)) { return Err(GridError::OutsideZone); diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index 21402ebacc..9d2e40d4ee 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -1569,6 +1569,7 @@ mod tests { assert_eq!(parse_utm("Z 2392768 1607232"), Ok(p)); // GeographicLib's short form (`GeoConvert -u`). assert_eq!(parse_utm("n 2392768 1607232"), Ok(p)); + assert!(parse_utm("s 2096454 1452981").is_ok_and(|q| q.y < -80.0)); let q = parse_utm("Y, 1735147, 2243078").unwrap(); assert!(q.x < 0.0 && q.y > 84.0, "{q:?}"); let s = parse_utm("south 2096454 1452981").unwrap(); @@ -1579,8 +1580,10 @@ mod tests { ("A 2096454 1452981", GridError::OutsideZone), // east of 2,000,000 m is B ("north 2000000 1300000", GridError::OutsideZone), // lettered, but south of 84° N ("south 2000000 3150000", GridError::OutsideZone), // lettered, but north of 80° S - ("north 2000000 100000", GridError::OutsideZone), // outside the lettered area, after the zone - ("A 2000000 100000", GridError::Syntax), // after a single letter it may be text + ("north 2000000 100000", GridError::Syntax), // outside the lettered area + ("north 412345 5523456", GridError::Syntax), // a UTM position without its zone + ("n 2000000 100000", GridError::Syntax), + ("A 2000000 100000", GridError::Syntax), // after a single letter it may be text ("A 10 20", GridError::Syntax), ("A1 12", GridError::Syntax), ("B 12, 34", GridError::Syntax), From 602607cc947081abc1bad211be35549469396cdb Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:37:53 -0600 Subject: [PATCH 11/14] fix(search): a lone-letter UPS that names no place says nothing N 1350000 1350000 (a State Plane pair) said "outside the zone given"; a UPS position after a lone letter that names no place is now text, and only north/south give a reason. The UPS limits reuse the UTM constants, a duplicate comment goes, and the readout width check moves to the other-body test. --- crates/engine/src/cmd/search.rs | 27 ++++++++++++++++++++++----- crates/geom/src/ups.rs | 5 ++--- crates/geom/src/utm.rs | 2 +- crates/ui-egui/src/coordreadout.rs | 5 ++++- 4 files changed, 29 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 42c2da24dd..5515915ab5 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -453,6 +453,9 @@ pub fn read_grid_reference(text: &str) -> Result { Err(mgrs) => match rustgis_geom::parse_utm(text) { Err(GridError::Syntax) if spaced_square(text) => Err(GridError::Syntax), Err(GridError::Syntax) => Err(mgrs), + // A UPS position that names no place after a lone letter (`N 1350000 1350000`, a State + // Plane pair, or `A …`) may be a code: text. After `north` or `south` it says why. + Err(_) if letter_led(text) && !led_by_zone_word(text) => Err(GridError::Syntax), utm => utm, }, } @@ -471,20 +474,29 @@ fn letter_led(text: &str) -> bool { /// readout writes it, spaced, in capitals, to the meter (`Z AC 77146 62481`). fn plainly_polar_place(text: &str) -> bool { let text = text.trim(); - // The word may be followed by a comma, as parse_ups reads it (`north, 2077146, 1562481`). // UPS with the zone or the half's letter before two numbers in the lettered area // (`Y, 1735147, 2243078`) is plainly a position: no name or code is written that way. - let word = text.split(|c: char| c.is_whitespace() || c == ',').next().unwrap_or("").to_ascii_lowercase(); - if matches!(word.as_str(), "north" | "south") { + if led_by_zone_word(text) { return true; } - if matches!(word.as_str(), "y" | "z" | "a" | "b") && rustgis_geom::parse_ups(text).is_ok() { + if matches!(first_word(text).as_str(), "y" | "z" | "a" | "b") && rustgis_geom::parse_ups(text).is_ok() { return true; } polar_form(text) == Some(PolarForm::Readout) && matches!(text.split_whitespace().collect::>().as_slice(), [_, _, e, n] if e.len() == 5 && n.len() == 5) } +/// The first word of text, in lowercase; it may be followed by a comma, as +/// [`rustgis_geom::parse_ups`] reads it (`north, 2077146, 1562481`). +fn first_word(text: &str) -> String { + text.trim().split(|c: char| c.is_whitespace() || c == ',').next().unwrap_or("").to_ascii_lowercase() +} + +/// Whether text starts with the UPS zone spelled out, `north` or `south`. +fn led_by_zone_word(text: &str) -> bool { + matches!(first_word(text).as_str(), "north" | "south") +} + /// How letter-led text is written as a polar MGRS reference, if it is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum PolarForm { @@ -1030,10 +1042,15 @@ mod tests { let r = search(&s, q, 50); assert!(matches!(r.hits.as_slice(), [Hit::Coordinate { .. }]) && !r.coordinate_may_be_text, "{q}: {r:?}"); } - // Shorter than the readout writes it, it may still be text. + // Shorter than the readout writes it, or GeographicLib's `n …` (a State Plane pair looks the + // same), it may still be text. for q in ["Z AC 7714 6248", "Z AC", "ZAC7714662481", "n 2077146 1562481", "N 2000000 1500000"] { assert!(search(&s, q, 50).coordinate_may_be_text, "{q}"); } + // One that names no UPS place after a lone letter (a State Plane pair near 81.8° N) says + // nothing; after `north` it says why. + assert_eq!(search(&s, "N 1350000 1350000", 50).grid_error, None); + assert_eq!(search(&s, "north 1350000 1350000", 50).grid_error, Some(GridError::OutsideZone)); } #[test] diff --git a/crates/geom/src/ups.rs b/crates/geom/src/ups.rs index 99b4d87f0f..fdf57b2577 100644 --- a/crates/geom/src/ups.rs +++ b/crates/geom/src/ups.rs @@ -30,9 +30,9 @@ use crate::utm::{ }; /// The northern limit of the UTM zones, where north UPS begins (degrees); 84° N itself is UPS. -pub const UPS_NORTH_FROM: f64 = 84.0; +pub const UPS_NORTH_FROM: f64 = crate::utm::UTM_MAX_LAT; /// The southern limit of the UTM zones (degrees); south UPS is south of it, 80° S itself is UTM. -pub const UPS_SOUTH_OF: f64 = -80.0; +pub const UPS_SOUTH_OF: f64 = crate::utm::UTM_MIN_LAT; /// UPS's scale at the pole, exactly (NGA.SIG.0012 §10.1). const K0: f64 = 0.994; @@ -310,7 +310,6 @@ pub fn parse_ups(text: &str) -> Result { } let rest: String = chars.collect(); let (easting, northing) = easting_and_northing(&rest)?; - // Numbers outside the zone's lettered area aren't a UPS position (`A 10 20`, a road): text. if !in_lettered_area(north, easting, northing) { // Not a UPS position: a road or a code (`A 10 20`), or a UTM position without its zone // (`north 412345 5523456`), which "outside the zone" would mislead about. Text. diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index 9d2e40d4ee..993a9bebdb 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -1583,7 +1583,7 @@ mod tests { ("north 2000000 100000", GridError::Syntax), // outside the lettered area ("north 412345 5523456", GridError::Syntax), // a UTM position without its zone ("n 2000000 100000", GridError::Syntax), - ("A 2000000 100000", GridError::Syntax), // after a single letter it may be text + ("A 2000000 100000", GridError::Syntax), // outside the lettered area too ("A 10 20", GridError::Syntax), ("A1 12", GridError::Syntax), ("B 12, 34", GridError::Syntax), diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs index e1f1ff170a..80ecda3f28 100644 --- a/crates/ui-egui/src/coordreadout.rs +++ b/crates/ui-egui/src/coordreadout.rs @@ -168,7 +168,10 @@ mod tests { let p = Coord::new(44.4, 33.3); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { assert_eq!(f.format(p, false), None); - assert_eq!(f.readout(Some(p), false), format!("No {} here", f.label())); + let r = f.readout(Some(p), false); + assert_eq!(r, format!("No {} here", f.label())); + // No wider than the reference it stands for, in the status bar. + assert!(r.chars().count() <= f.readout(Some(p), true).chars().count(), "{r}"); assert!(f.earth_only()); } for f in [CoordReadout::Decimal, CoordReadout::Dms] { From 10e9db4beea0edf4047802af936bfaa88b44c150 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:13:35 -0600 Subject: [PATCH 12/14] fix(search): keep table hits ahead of the polar place; house numbers stay text --- crates/engine/src/cmd/search.rs | 37 ++++++++++++++++++++++++--------- docs/user-guide/maps.md | 7 +++++-- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 5515915ab5..e0d7a26f62 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -250,10 +250,10 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { } } let limit = limit.max(1); - // After the other hits, within the limit; with room for one hit only, the place is listed only - // when nothing else matched, so a feature named like the reference stays the one to go to. - if let Some(c) = polar_place.filter(|_| out.hits.is_empty() || limit > 1) { - out.hits.insert(out.hits.len().min(limit - 1), Hit::Coordinate { lon: c.x, lat: c.y }); + // After every other hit, and only when they leave room, so no feature named like the + // reference is pushed out and `go` with any index still reaches the same feature. + if let Some(c) = polar_place.filter(|_| out.hits.len() < limit) { + out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); out.coordinate_may_be_text = true; } out.hits.truncate(limit); @@ -501,7 +501,7 @@ fn led_by_zone_word(text: &str) -> bool { #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum PolarForm { /// As the readout writes it: the half's letter, a space and the square's letters, in - /// capitals (`Z AH`, `Z AH 12 34`). + /// capitals, then no digits or two equal groups (`Z AH`, `Z AH 12 34`). Readout, /// As one word with at least six digits attached, 100 m or finer (`ZAC7714662481`, any /// case), or the three letters in capitals before two equal groups of at least three digits @@ -523,14 +523,22 @@ fn polar_form(text: &str) -> Option { return None; } let capitals = half.is_ascii_uppercase() && letters.iter().all(char::is_ascii_uppercase); - if spaced { - return capitals.then_some(PolarForm::Readout); - } // The two letters are ASCII, so the digits start two bytes on. let after = rest.get(2..).unwrap_or(""); - let attached = after.starts_with(|c: char| c.is_ascii_digit()); let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit()); - let compact = match after.split_whitespace().collect::>().as_slice() { + let groups: Vec<&str> = after.split_whitespace().collect(); + if spaced { + // The readout writes no digits (100 km) or two equal groups; a single number after a + // spaced, capitalized word is a house number (`A ST 12`, `Z ST 12`). + let as_written = match groups.as_slice() { + [] => true, + [e, n] => digits(e) && digits(n) && e.len() == n.len(), + _ => false, + }; + return (capitals && as_written).then_some(PolarForm::Readout); + } + let attached = after.starts_with(|c: char| c.is_ascii_digit()); + let compact = match groups.as_slice() { [run] if attached => digits(run) && run.len() >= 6, [e, n] => capitals && digits(e) && digits(n) && e.len() == n.len() && e.len() >= 3, _ => false, @@ -976,6 +984,11 @@ mod tests { "a st 12", "B St 12", "ZAC 7714662481", + // All-caps addresses: a house number after a spaced word, not the readout's two groups. + "A ST 12", + "Z ST 12", + "B ST 5", + "A ST 123", ] { let r = search(&s, q, 50); assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); @@ -1015,6 +1028,10 @@ mod tests { let one = search(&s, q, 1); assert!(matches!(one.hits.as_slice(), [Hit::Feature { .. }]), "{q}: {one:?}"); } + // Two features named so fill a limit of two: both are kept, ahead of any place. + s.run("layer.addDataText", &json!({"fileName": "more.csv", "text": "part,lon,lat\nBAG123456,11.0,51.0\n"})).unwrap(); + let two = search(&s, "BAG123456", 2); + assert!(matches!(two.hits.as_slice(), [Hit::Feature { .. }, Hit::Feature { .. }]), "{two:?}"); // `go` goes to the feature, and the answer says the place may be text. let v = s.run("map.search", &json!({"query": "BAG123456", "limit": 1, "go": true})).unwrap(); assert!(v["hits"][0]["kind"] == "feature", "{v}"); diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 26e953f966..6f763cfe63 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -192,7 +192,8 @@ their own rules, below): letter, `Z 2077146 1562481` or `Y, 1735147, 2243078`. Polar MGRS has no zone number, so three letters and a few digits look like a word or a code (`ATL`, `Bay 12`, the flight `BAW1234`); search reads one only as a reference is written: as the readout writes it, with a space after - the half's letter and the square in capitals (`Z AC`, `Z AC 77 62`, `Z AC 77146 62481`), as + the half's letter and the square in capitals, then no digits or two equal groups (`Z AC`, + `Z AC 77 62`, `Z AC 77146 62481`; `A ST 12` is an address), as one word with at least six digits (`ZAC7714662481`, 100 m or finer), or in capitals before two equal groups of at least three digits (`ZAC 771 624`, `ZAC 77146 62481`). A UPS position (`north 2077146 1562481`, `Z 2077146 1562481`) and a reference written exactly as the readout @@ -209,7 +210,9 @@ place somewhere else, and the list says why; `map.search` returns the reason as adds `"coordinateMayBeText": true` when a polar place among its hits may as well be a name or a code. A 100 km square written with spaces, such as `5 Ave` or `4K TV`, is as likely ordinary text, so one -that names no square gives no reason; written as one word, `38TMJ`, it does. On the map of +that names no square gives no reason; written as one word, `38TMJ`, it does. Polar MGRS written +compactly (`ZDA1234512345`) may be a code too, so one that names no place gives no reason either; +written as the readout writes it (`Z DA 12345 12345`), it does. On the map of another body, grid references find nothing. ### Directions From a67a4ba8529ad2c10ceb47007b2b00c31bf718b4 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:37:37 -0600 Subject: [PATCH 13/14] fix(search): a wrong half letter on a UPS position says why --- crates/engine/src/cmd/search.rs | 25 ++++++++++++++++++------- docs/user-guide/maps.md | 11 ++++++----- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index e0d7a26f62..1db003c090 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -453,9 +453,10 @@ pub fn read_grid_reference(text: &str) -> Result { Err(mgrs) => match rustgis_geom::parse_utm(text) { Err(GridError::Syntax) if spaced_square(text) => Err(GridError::Syntax), Err(GridError::Syntax) => Err(mgrs), - // A UPS position that names no place after a lone letter (`N 1350000 1350000`, a State - // Plane pair, or `A …`) may be a code: text. After `north` or `south` it says why. - Err(_) if letter_led(text) && !led_by_zone_word(text) => Err(GridError::Syntax), + // A UPS position that names no place after GeographicLib's `n` or `s` may be a State + // Plane pair (`N 1350000 1350000`): text. After `north`, `south` or a half's letter + // (`Y 2392768 1607232`, two numbers in the lettered area) it says why. + Err(_) if letter_led(text) && !led_by_zone_word(text) && !led_by_half_letter(text) => Err(GridError::Syntax), utm => utm, }, } @@ -479,7 +480,7 @@ fn plainly_polar_place(text: &str) -> bool { if led_by_zone_word(text) { return true; } - if matches!(first_word(text).as_str(), "y" | "z" | "a" | "b") && rustgis_geom::parse_ups(text).is_ok() { + if led_by_half_letter(text) && rustgis_geom::parse_ups(text).is_ok() { return true; } polar_form(text) == Some(PolarForm::Readout) @@ -497,6 +498,12 @@ fn led_by_zone_word(text: &str) -> bool { matches!(first_word(text).as_str(), "north" | "south") } +/// Whether text starts with a polar half's letter alone, `Y`, `Z`, `A` or `B`, as NGA writes a +/// UPS position (`Y, 1735147, 2243078`). +fn led_by_half_letter(text: &str) -> bool { + matches!(first_word(text).as_str(), "y" | "z" | "a" | "b") +} + /// How letter-led text is written as a polar MGRS reference, if it is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum PolarForm { @@ -1064,10 +1071,14 @@ mod tests { for q in ["Z AC 7714 6248", "Z AC", "ZAC7714662481", "n 2077146 1562481", "N 2000000 1500000"] { assert!(search(&s, q, 50).coordinate_may_be_text, "{q}"); } - // One that names no UPS place after a lone letter (a State Plane pair near 81.8° N) says - // nothing; after `north` it says why. + // One that names no UPS place after `n` (a State Plane pair near 81.8° N) says nothing; + // after `north` or a half's letter (Y east of 2,000,000 m is Z's) it says why. assert_eq!(search(&s, "N 1350000 1350000", 50).grid_error, None); - assert_eq!(search(&s, "north 1350000 1350000", 50).grid_error, Some(GridError::OutsideZone)); + for q in ["north 1350000 1350000", "Y 2392768 1607232", "a 2100000 1500000"] { + let r = search(&s, q, 50); + assert_eq!(r.grid_error, Some(GridError::OutsideZone), "{q}"); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}"); + } } #[test] diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 6f763cfe63..4e081c73aa 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -208,11 +208,12 @@ A reference that doesn't exist (square letters the zone doesn't use, a northing outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a place somewhere else, and the list says why; `map.search` returns the reason as `gridError`, and adds `"coordinateMayBeText": true` when a polar place among its hits may as well be a name or a -code. A -100 km square written with spaces, such as `5 Ave` or `4K TV`, is as likely ordinary text, so one -that names no square gives no reason; written as one word, `38TMJ`, it does. Polar MGRS written -compactly (`ZDA1234512345`) may be a code too, so one that names no place gives no reason either; -written as the readout writes it (`Z DA 12345 12345`), it does. On the map of +code. A 100 km square written with spaces, such as `5 Ave` or `4K TV`, is as likely ordinary +text, so one that names no square gives no reason; written as one word, `38TMJ`, it does. Polar +MGRS written compactly (`ZDA1234512345`) may be a code too, so one that names no place gives no +reason either; written as the readout writes it (`Z DA 12345 12345`), it does. A UPS position +after `n` or `s` may be a State Plane pair (`N 1350000 1350000`), so it gives no reason; after +`north`, `south` or the half's letter (`Y 2392768 1607232`), it does. On the map of another body, grid references find nothing. ### Directions From 6bb50a64dd3417b021232a850da2d55c359146dd Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:03:13 -0600 Subject: [PATCH 14/14] fix(search): a spaced polar square that names none is text, like 5 Ave --- crates/engine/src/cmd/search.rs | 14 ++++++++++++++ docs/user-guide/maps.md | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 1db003c090..47ba56cd8f 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -442,6 +442,11 @@ pub fn read_grid_reference(text: &str) -> Result { match polar_form(text) { // As the readout writes it: plainly meant as a reference, so it says why it names no // place. + // The square alone (`Z AC`) is a letter and a word as often (`A TO`), as `5 Ave` is: + // read if it names a square, text if not. + Some(PolarForm::Readout) if !text.bytes().any(|b| b.is_ascii_digit()) => { + rustgis_geom::parse_mgrs(text).map_err(|_| GridError::Syntax) + } Some(PolarForm::Readout) => rustgis_geom::parse_mgrs(text), // Compact forms look like codes too (`BAG123456`): read if they name a place, text if not. Some(PolarForm::Compact) => rustgis_geom::parse_mgrs(text).map_err(|_| GridError::Syntax), @@ -1018,6 +1023,15 @@ mod tests { for q in ["ZDA1234512345", "YRA1234512345", "ABC123456", "YAA123456"] { assert_eq!(search(&s, q, 50).grid_error, None, "{q}"); } + // The square alone is a letter and a word as often, as `5 Ave` is: one that names no + // square (`A TO`, row O isn't used) is text and says nothing; one that names a square + // (`A ST`) is found but may be text. + for q in ["A TO", "Z DA", "Y RA"] { + let r = search(&s, q, 50); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); + assert_eq!(r.grid_error, None, "{q}"); + } + assert!(search(&s, "A ST", 50).coordinate_may_be_text); } /// A code that also reads as a polar reference (`BAG123456` is B AG 123 456, a place in diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 59e0980df7..8541e01813 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -209,8 +209,8 @@ A reference that doesn't exist (square letters the zone doesn't use, a northing outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a place somewhere else, and the list says why; `map.search` returns the reason as `gridError`, and adds `"coordinateMayBeText": true` when a polar place among its hits may as well be a name or a -code. A 100 km square written with spaces, such as `5 Ave` or `4K TV`, is as likely ordinary -text, so one that names no square gives no reason; written as one word, `38TMJ`, it does. Polar +code. A 100 km square written with spaces, such as `5 Ave`, `4K TV` or `A TO`, is as likely +ordinary text, so one that names no square gives no reason; written as one word, `38TMJ`, it does. Polar MGRS written compactly (`ZDA1234512345`) may be a code too, so one that names no place gives no reason either; written as the readout writes it (`Z DA 12345 12345`), it does. A UPS position after `n` or `s` may be a State Plane pair (`N 1350000 1350000`), so it gives no reason; after