diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 0479214c34..9a53e37034 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -839,7 +839,13 @@ impl Crs { /// semi-major axis isn't the Earth's ([`super::planetary`]). Its longitude/latitude are read as /// they are, on the Earth. pub fn is_planetary(self) -> bool { - self.custom_def().and_then(|d| super::planetary::proj4_axes(&d.proj4)).is_some_and(|(a, _)| super::planetary::off_earth(a)) + self.planetary_semi_major().is_some() + } + + /// The semi-major axis, in metres, of another body's system ([`Crs::is_planetary`]), which + /// tells the bodies apart; `None` for the Earth's. + pub fn planetary_semi_major(self) -> Option { + self.custom_def().and_then(|d| super::planetary::proj4_axes(&d.proj4)).map(|(a, _)| a).filter(|a| super::planetary::off_earth(*a)) } /// A transformer between this system and WGS 84 longitude/latitude, built once a run per diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 2f99f709a9..5d1db0a3ac 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -312,7 +312,7 @@ map.body name? basemap? map.camera lon? lat? scale? map.clipping mode distance? map.colorVision mode -map.convertPosition lon x lat y position? digits? +map.convertPosition lon x lat y crs? position? digits? map.displayType mode map.drawingMode mode map.duplicate map? name? @@ -323,7 +323,7 @@ map.exportOrbit path frames? turn? width? height? dpi? speed? map.extent map.findPlace query provider? url? limit? go? map.goToLink url -map.goToXY lon x lat y position? scale? bearing? pitch? +map.goToXY lon x lat y crs? position? scale? bearing? pitch? map.graticule on? type? crs? onTop? color? map.import path text data map.link diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 9065bf7312..27ce619cfd 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -47,7 +47,7 @@ fn first() -> String { pub fn commands() -> Vec { vec![ C::new("raster.georeference", "Georeference", "Imagery › Alignment", georeference).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": raster, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minLon, minLat, maxLon, maxLat], "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326), "crs"?: the output's (default pointsCrs), "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF)}"#, + r#"{"layer": raster, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minX, minY, maxX, maxY] in degrees, or in crs when given, | "view" (the map view, in the map's own system on a flat map of the Earth, so the raster fills the view as drawn); not with transform, "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326; with transform only, not with an extent), "crs"?: the output's (default pointsCrs); with an extent of four numbers, their system and the result's, "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF); resampling, cellSize, name and path with transform only}"#, ), C::new("raster.project", "Project Raster", "Analyze › Raster", project_raster).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, @@ -250,17 +250,61 @@ fn rebuild(r: &Raster, transform: GeoTransform, crs: Crs, bands: Vec>) fn georeference(s: &mut Session, p: &Value) -> CmdResult { let layer = ps(p, "layer").ok_or("layer is required")?.to_string(); let r = raster(s, p)?; - if p.get("transform").is_some() { + if p.get("transform").is_some_and(|v| !v.is_null()) { + // A transform fits control points: an extent given beside it would be passed over. + if p.get("extent").is_some_and(|e| !e.is_null()) { + return Err("give either a transform with control points or an extent, not both".into()); + } return warp_to_fit(s, p, &layer, &r); } - let gt = if let Some(e) = p.get("extent").and_then(Value::as_array) { - let n: Vec = e.iter().filter_map(Value::as_f64).collect(); - let [x0, y0, x1, y1] = n.as_slice() else { return Err("extent is [minLon, minLat, maxLon, maxLat]".into()) }; + // An extent is placed in crs (or the map's system for "view"): pointsCrs, the control + // points' system, would be passed over. + if p.get("extent").is_some_and(|e| !e.is_null()) && crs_param_read(p, "pointsCrs")?.0.is_some() { + return Err("pointsCrs goes with control points and a transform, not with an extent (one of four numbers takes crs)".into()); + } + let mut crs = Crs::LonLat; + let extent = match p.get("extent") { + None | Some(Value::Null) => None, + Some(Value::String(v)) if v == "view" => { + if crs_param_read(p, "crs")?.0.is_some() { + return Err("crs goes with an extent of four numbers; \"view\" is in the map's own system".into()); + } + let (e, view_crs) = view_in_map_system(s)?; + crs = view_crs; + Some([e.min_x, e.min_y, e.max_x, e.max_y]) + } + Some(Value::Array(e)) => { + // Exactly four numbers: an entry that isn't one is refused, not passed over. + let n: Vec = e.iter().map_while(|v| v.as_f64().filter(|v| v.is_finite())).collect(); + let given = crs_param(s, p, "crs")?; + let ([x0, y0, x1, y1], 4) = (n.as_slice(), e.len()) else { + return Err("extent is [minX, minY, maxX, maxY] (degrees, or in crs)".into()); + }; + crs = given.unwrap_or(Crs::LonLat); + Some([*x0, *y0, *x1, *y1]) + } + Some(_) => return Err("extent is [minX, minY, maxX, maxY] (degrees, or in crs) or \"view\"".into()), + }; + // An extent places the raster on its own: control points beside it would be passed over. + if extent.is_some() && p.get("points").is_some_and(|v| !v.is_null()) { + return Err("give either an extent or control points, not both".into()); + } + // Without a transform the raster is placed where it is, its pixels kept: what only a warp + // uses (a new layer or file for its result, a cell size, a resampling) would be passed over, + // and the layer placed in place of a new one. Refused before anything is copied. + if let Some(key) = ["name", "path", "cellSize", "resampling"].into_iter().find(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return Err(format!("{key} goes with a transform, which warps the raster into a new grid; without one the layer itself is placed")); + } + let gt = if let Some([x0, y0, x1, y1]) = extent { if !(x0 < x1 && y0 < y1) { - return Err("extent is [minLon, minLat, maxLon, maxLat]".into()); + return Err("extent is [minX, minY, maxX, maxY]: each min below its max".into()); } - GeoTransform { origin_x: *x0, origin_y: *y1, pixel_width: (x1 - x0) / r.width as f64, pixel_height: -(y1 - y0) / r.height as f64 } + GeoTransform { origin_x: x0, origin_y: y1, pixel_width: (x1 - x0) / r.width as f64, pixel_height: -(y1 - y0) / r.height as f64 } } else { + // Without a transform the points are degrees, placed as such. + if crs_param_read(p, "crs")?.0.is_some() || crs_param_read(p, "pointsCrs")?.0.is_some() { + return Err("control points without a transform are longitude and latitude: give transform to use pointsCrs and crs".into()); + } let pts: Vec<[f64; 4]> = p .get("points") .and_then(Value::as_array) @@ -300,7 +344,7 @@ fn georeference(s: &mut Session, p: &Value) -> CmdResult { } GeoTransform { origin_x: bx, origin_y: by, pixel_width: ax, pixel_height: ay } }; - let mut out = rebuild(&r, gt, Crs::LonLat, copied(&r)?)?; + let mut out = rebuild(&r, gt, crs, copied(&r)?)?; // The same pixels, so the same values rounded when the file was read. out.rounded = r.rounded.clone(); out.rounded_some = r.rounded_some.clone(); @@ -309,6 +353,53 @@ fn georeference(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"layer": v["layer"], "extent": [e.min_x, e.min_y, e.max_x, e.max_y]})) } +/// The map view's rectangle and the system it is in, for fitting a raster to it: on a flat map of +/// the Earth, the view in the map's own units and system (Web Mercator's EPSG:3857, the map's EPSG +/// or ESRI code, or the definition of a preset or local view), so the raster fills the view as +/// drawn; on the globe and another body's map, the longitude and latitude box the view shows. +fn view_in_map_system(s: &Session) -> Result<(rustgis_geom::Extent, Crs), String> { + let m = s.map(); + let (w, h) = s.view_size; + // A turned or tilted view isn't a north-up rectangle a raster's grid can fill. + if m.camera.bearing != 0.0 || m.camera.pitch != 0.0 { + return Err("the map is turned or tilted: face north and look straight down (Reset North) to fit a raster to the view".into()); + } + let flat_earth = m.body().is_earth() && !m.projection.is_globe(); + if flat_earth { + let e = m.camera.extent(w, h); + let crs = match &m.projection { + rustgis_map::Projection::Custom(code) => match rustgis_map::projection::Projector::new(code)?.crs() { + Some(c) => c, + None => Crs::parse(&rustgis_map::projection::lookup(code)?.0)?, + }, + _ => Crs::WebMercator, + }; + if [e.min_x, e.min_y, e.max_x, e.max_y].iter().any(|v| !v.is_finite()) || e.is_empty() { + return Err("the map view shows no area to fit to".into()); + } + // A world copy past the antimeridian is the same place within the world's ±180°; a view + // wider than the world has no single place. + if matches!(m.projection, rustgis_map::Projection::WebMercator) { + let world = 2.0 * std::f64::consts::PI * rustgis_geom::MERCATOR_R; + if e.width() > world || e.height() > world { + return Err("the map view is wider than the world: zoom in to fit a raster to it".into()); + } + let shift = ((e.min_x + world / 2.0) / world).floor() * world; + let shift = if e.max_x - shift > world / 2.0 + 1e-6 { shift + world } else { shift }; + if e.min_x - shift < -world / 2.0 - 1e-6 { + return Err("the map view crosses the antimeridian: pan it to one side to fit a raster to it".into()); + } + return Ok((rustgis_geom::Extent::new(e.min_x - shift, e.min_y, e.max_x - shift, e.max_y), crs)); + } + return Ok((e, crs)); + } + let e = super::workspace::view_extent_of(m, (w, h)); + if e.is_empty() { + return Err("the map view shows no part of the map to fit to".into()); + } + Ok((e, Crs::LonLat)) +} + /// A coordinate system given as an EPSG code or any text [`Crs::parse`] reads. fn crs_param(s: &mut Session, p: &Value, key: &str) -> Result, String> { let (crs, warning) = crs_param_read(p, key)?; diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 235419f966..cf8057bee1 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -42,10 +42,10 @@ pub fn commands() -> Vec { .params(r#"{"extent": [minLon, minLat, maxLon, maxLat]}"#), C::new("map.goToXY", "By Coordinates…", "Home › Navigate › Locate", go_to_xy).roles(&[]).effects(crate::policy::Effects::NONE) .view() - .params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350), "scale"?: number, "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85)}"#), + .params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), or with crs the easting in that system, "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), or with crs the northing, "crs"?: the system x and y are in: "map" (the map's own, as the status bar reads it), an EPSG or ESRI code or other system text (EPSG:2056), or a layer's name (the system it was read in); default degrees, "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350; 2600000 mE 1200000 mN EPSG:2056, as the map's right-click menu copies it), "scale"?: number, "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85)}"#), C::new("map.convertPosition", "Convert Position", "Home › Navigate › Locate", convert_position).roles(&[]).effects(crate::policy::Effects::NONE) .view() - .params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350; Z AC 77146 62481), "digits"?: MGRS digits per axis, 0 (100 km) to 5 (1 m, the default)}"#), + .params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), or with crs the easting in that system, "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), or with crs the northing, "crs"?: the system x and y are in: "map" (the map's own), an EPSG or ESRI code or other system text (EPSG:2056), or a layer's name (the system it was read in); default degrees, "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350; Z AC 77146 62481; 2600000 mE 1200000 mN EPSG:2056), "digits"?: MGRS digits per axis, 0 (100 km) to 5 (1 m, the default)}"#), C::new("map.goToLink", "Go To Map Link", "Home › Navigate", go_to_link).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"url": a map link ending in #zoom/lat/lon[/bearing[/pitch]] (as MapLibre writes them; also #map=…), or just zoom/lat/lon[/bearing[/pitch]]}"#), @@ -372,6 +372,9 @@ pub(crate) fn read_position(map: &Map, text: &str) -> Result<(Coord, PositionRea && digits.chars().filter(|&c| c == '.').count() <= 1 }; let words: Vec<&str> = text.split(|c: char| c == ',' || c.is_whitespace()).filter(|w| !w.is_empty()).collect(); + if let Some(read) = read_system_position(map, text) { + return read.map(|c| (c, PositionRead::AsWritten)); + } if words.len() == 2 && words.iter().all(plain) { return Err("latitude must be within ±90 and longitude within ±180".into()); } @@ -396,6 +399,305 @@ pub(crate) fn read_position(map: &Map, text: &str) -> Result<(Coord, PositionRea } } +/// A coordinate system a place's coordinates are given in, ready to give the place's longitude and +/// latitude. +pub(crate) enum System { + /// A map's own (a flat projection, as the map draws it). + Flat(rustgis_map::projection::Flat), + /// A system as data names it. + Data(rustgis_data::raster::Transformer), +} + +impl System { + /// The system data names `crs`: Web Mercator as the map draws it, whose unit is the metre + /// (its conversion gives no parameters to read one from), else by its conversion. + fn of_crs(crs: rustgis_data::raster::Crs) -> Result { + if crs == rustgis_data::raster::Crs::WebMercator { + return Ok(System::Flat(rustgis_map::projection::Flat::Mercator)); + } + if let Some(e) = axes_refused(crs) { + return Err(e); + } + crs.transformer().map(System::Data) + } + + /// The unit it counts in as the readout writes it: `m`, `ft` (international) or `ftUS`; `None` + /// for another (degrees, a rarer foot). + pub(crate) fn unit(&self) -> Option<&'static str> { + let to_meter = match self { + System::Flat(rustgis_map::projection::Flat::Mercator) => 1.0, + System::Flat(rustgis_map::projection::Flat::Custom(p)) => p.to_meter(), + System::Data(t) => { + // Degrees aren't a length. + let p = t.params()?; + if p.method == "longlat" || p.method == "latlong" { + return None; + } + p.to_meter + } + }; + [("m", 1.0), ("ft", 0.3048), ("ftUS", 1200.0 / 3937.0)].into_iter().find(|(_, k)| (to_meter - k).abs() < 1e-9).map(|(u, _)| u) + } + + /// Whether it counts in degrees (a geographic system): a map's own never does. + fn is_geographic(&self) -> bool { + matches!(self, System::Data(t) if t.is_geographic()) + } + + /// The longitude and latitude of `at`, a place in this system; `None` where it names none: + /// where the inverse gives no place, or one that doesn't map back to `at` (to a centimetre, or + /// a millionth of the coordinate's size, up to two of its units) because the system's formulas don't reach so far. + pub(crate) fn to_lonlat(&self, at: Coord) -> Option { + if !at.is_finite() { + return None; + } + let (c, back) = match self { + System::Flat(f) => { + let c = f.inverse(at)?; + (c, f.forward_checked(c)) + } + System::Data(t) => { + let c = t.to_lonlat(at)?; + (c, t.from_lonlat(c)) + } + }; + let back = back?; + // To a hundredth of the system's unit (a centimetre in metres), or a millionth of the + // coordinate's size up to two units (2 m, 2 ft): an inverse that + // iterates (Robinson's, to about 1.5e-5°, some 1.6 m) comes back that close; a place past + // the formulas' reach doesn't. + let close = |a: f64, b: f64| (a - b).abs() <= 0.01_f64.max((a.abs() * 1e-6).min(2.0)); + (c.is_finite() && (-180.0..=180.0).contains(&c.x) && (-90.0..=90.0).contains(&c.y) && close(back.x, at.x) && close(back.y, at.y)) + .then_some(c) + } +} + +/// Why a system X and Y can't be given in: they are an easting and a northing, and one counted +/// west or south, or northing first (Lo29's westing and southing), would take them mirrored or +/// swapped, so it is refused, as the readout refuses to write in one. `None` for one counted east, +/// then north, and for degrees (their own branch reads them). +fn axes_refused(crs: rustgis_data::raster::Crs) -> Option { + let axes = crs.axis_directions(); + (!crs.is_geographic() && axes != [(1.0, 0.0), (0.0, 1.0)]).then(|| { + // The direction's larger component names it (`signum` of 0 is 1, so it can't). + let name = |(x, y): (f64, f64)| match (x.abs() >= y.abs(), x > 0.0, y > 0.0) { + (true, true, _) => "an easting", + (true, false, _) => "a westing", + (false, _, true) => "a northing", + (false, _, false) => "a southing", + }; + format!( + "{} counts {}, then {}, not an easting, then a northing: give the place in degrees, or in a system counted east, then north", + crs.label(), + name(axes[0]), + name(axes[1]) + ) + }) +} + +/// The system a layer's coordinates are given in, as Go To XY reads them: a raster's, its +/// pixels' (also one only assumed, as its pixels are placed in it); a layer of features', the one +/// it was read in. `None` for a layer of features that names none (longitude and latitude), and +/// for a raster with no pixels loaded, whose system is unknown ([`system_of`] refuses it, so check +/// that before taking `None` for degrees). Not +/// [`super::project::layer_system`], which leaves assumed systems out as the project's own. +pub fn layer_coordinates_system(l: &rustgis_map::Layer) -> Option { + match &l.raster { + Some(r) => r.data.as_ref().map(|d| d.crs), + None => l.dataset.crs, + } +} + +/// The system `name` gives: `map`, the map's own (the flat projection it draws in, not the globe +/// or another body's map); a layer of the map by that name, the system it was read in (longitude +/// and latitude for one that names none); else a code or other text a map's projection or data's +/// system takes (`EPSG:2056`, `Web Mercator`, `robinson +lon_0=150`, a PROJ string), which names +/// an Earth system, so none on another body's map (as [`read_system_position`] refuses it). +pub(crate) fn system_of(map: &Map, name: &str) -> Result { + let name = name.trim(); + if name.eq_ignore_ascii_case("map") { + if !map.body().is_earth() || map.projection.is_globe() { + return Err("the map has no flat system of its own here (the globe, or another body's map): give degrees".into()); + } + return Ok(System::Flat(map.flat())); + } + // A layer's name first, so a layer named as a system (`Albers`, `2056`) means the layer. + if let Some(l) = map.layer_by_name(name) { + // A raster with no pixels (still being read, or its file couldn't be) names no system: its + // system is unknown, not longitude and latitude. + if l.raster.as_ref().is_some_and(|r| r.data.is_none()) { + return Err(format!("layer '{name}' has no pixels loaded, so its system is unknown: wait until it has opened, or reload it")); + } + // A feature layer that names no system holds longitude and latitude. + let crs = layer_coordinates_system(l).unwrap_or(rustgis_data::raster::Crs::LonLat); + // A projection of the Earth names no place on another body's map, as its code doesn't; + // degrees are that map's own, and another body's projection is its own. + if !map.body().is_earth() && !crs.is_geographic() && !crs.is_planetary() { + return Err(format!("layer '{name}' is in {}, a system of the Earth, and names no place on this map", crs.label())); + } + // Nor does another body's projection on the Earth's map: its inverse gives that body's + // degrees, not the Earth's. (Its degrees are read as they are, as data reads them.) + if map.body().is_earth() && !crs.is_geographic() && crs.is_planetary() { + return Err(format!("layer '{name}' is in {}, a system of another body, and names no place on the Earth's map", crs.label())); + } + // Nor one body's projection on another's: Mars's inverse gives no place on the Moon. + if let Some(body) = other_body(map, crs.planetary_semi_major()).filter(|_| !crs.is_geographic()) { + return Err(format!("layer '{name}' is in {}, a system of {body}, and names no place on this map", crs.label())); + } + return System::of_crs(crs).map_err(|e| format!("layer '{name}': {e}")); + } + if let Some(named) = named_system(name) { + let (system, semi_major) = named?; + let planetary = semi_major.is_some(); + // An Earth system names no place on another body's map; that body's own does. Another + // body's projection names none on the Earth's. + if !map.body().is_earth() && !planetary { + return Err(format!("{name} is a system of the Earth and names no place on this map")); + } + if map.body().is_earth() && planetary && !system.is_geographic() { + return Err(format!("{name} is a system of another body and names no place on the Earth's map")); + } + if let Some(body) = other_body(map, semi_major).filter(|_| !system.is_geographic()) { + return Err(format!("{name} is a system of {body} and names no place on this map")); + } + return Ok(system); + } + Err(format!("'{name}' is neither \"map\", a coordinate system (EPSG:2056), nor a layer's name")) +} + +/// The body, said for a notice, that a system of another body than the Earth's +/// (`semi_major`, [`rustgis_data::raster::Crs::planetary_semi_major`]) is of, when the map is of +/// yet another body: their semi-major axes differ by more than a percent (the nearest pair of +/// bodies a map takes, Titan and Ganymede, differ by 2%). `None` on the Earth's map, for the +/// Earth's systems, and for the map's own body's. +fn other_body(map: &Map, semi_major: Option) -> Option { + let body = map.body(); + let a = semi_major.filter(|_| !body.is_earth())?; + if (a - body.a).abs() <= body.a * 0.01 { + return None; + } + let named = rustgis_geom::body::BODIES.iter().find(|b| !b.is_earth() && (a - b.a).abs() <= b.a * 0.01); + Some(named.map_or_else(|| format!("another body (a radius of {:.0} km)", a / 1000.0), |b| b.name.to_string())) +} + +/// A system named by a map projection's code (as the readout's copy names it) or by text data's +/// systems take, and whether it is another body's than the Earth's (a planetary PROJ string or +/// code); `None` for text that names neither, an error for one named but refused (counted +/// otherwise than east, then north). The globe names no flat system. +fn named_system(name: &str) -> Option), String>> { + // `map` is the map's own ([`system_of`]), not Web Mercator, which `Projection::from_code` + // takes it for. + if name.trim().eq_ignore_ascii_case("map") { + return None; + } + // A code a map projection takes is read as the map draws it, but counted as data names it: + // its axes and its body are the system's. + let crs = rustgis_data::raster::Crs::parse(name).ok(); + match Projection::from_code(name) { + Ok(Projection::Globe) => None, + Ok(p) => Some(match crs.and_then(axes_refused) { + Some(e) => Err(e), + None => Ok((System::Flat(rustgis_map::projection::Flat::of(&p)), crs.and_then(|c| c.planetary_semi_major()))), + }), + Err(_) => { + let c = crs?; + Some(System::of_crs(c).map(|s| (s, c.planetary_semi_major()))) + } + } +} + +/// A place written in a named system, as the map's right-click menu copies one: an easting and a +/// northing, each with an optional unit and axis letter (`2600000 mE`, `1200000 mN`; `ftE`, +/// `ftUSN`, a bare `E`), then the system (`EPSG:2056`, `Web Mercator`). `None` for text not +/// written so; an error for a system that names no flat Earth system here, or a place it names +/// none at. +pub(crate) fn read_system_position(map: &Map, text: &str) -> Option> { + let mut rest = text.trim(); + let mut numbers = [0.0; 2]; + let mut units: Vec<&str> = Vec::new(); + for (i, axis) in ['E', 'N'].into_iter().enumerate() { + numbers[i] = next_word(&mut rest)?.parse::().ok().filter(|v| v.is_finite())?; + // An optional unit and axis letter. + let mut after = rest; + let word = next_word(&mut after).unwrap_or(""); + if let Some(unit) = + ["ftUS", "ft", "m", ""].into_iter().find(|u| word.strip_prefix(u).is_some_and(|l| l.len() == 1 && l.starts_with(axis))) + { + rest = after; + if !unit.is_empty() { + units.push(unit); + } + } + } + let system = rest.trim_start_matches(|c: char| c == ',' || c.is_whitespace()).trim(); + // Only a system's name: a letter, so a third number (a height) isn't taken for one; and no + // WKT, which typed text would otherwise add to the table of systems files read. + if !system.chars().next().is_some_and(char::is_alphabetic) || system.contains('[') { + return None; + } + let (found, semi_major) = if system.eq_ignore_ascii_case("map") { + match system_of(map, "map") { + Ok(s) => (s, None), + Err(e) => return Some(Err(e)), + } + } else { + match named_system(system)? { + Ok(found) => found, + Err(e) => return Some(Err(e)), + } + }; + // An Earth system names no place on another body's map; that body's own does. Another + // body's projection names none on the Earth's. + let planetary = semi_major.is_some(); + if !map.body().is_earth() && !planetary { + return Some(Err(format!("{system} is a system of the Earth and names no place on this map"))); + } + if map.body().is_earth() && planetary && !found.is_geographic() { + return Some(Err(format!("{system} is a system of another body and names no place on the Earth's map"))); + } + if let Some(body) = other_body(map, semi_major).filter(|_| !found.is_geographic()) { + return Some(Err(format!("{system} is a system of {body} and names no place on this map"))); + } + // Degrees are written latitude first, as a position without a system reads them, while this + // form takes an easting first: the order would be a guess, so a system in degrees is refused. + if found.is_geographic() { + return Some(Err(format!( + "{system} counts in degrees: give the position without a system, latitude then longitude (or with N, S, E and W)" + ))); + } + // A unit written must be the system's: feet aren't read as metres. + if let Some(unit) = units.iter().find(|u| Some(**u) != found.unit()) { + let theirs = found.unit().unwrap_or("another unit"); + return Some(Err(format!("{system} counts in {theirs}, not {unit}"))); + } + let at = Coord::new(numbers[0], numbers[1]); + // Two numbers that read as a latitude and a longitude before `map` are degrees typed with the + // map's name, not metres a few steps from the map's origin: said, not taken for metres. + // Two numbers that read as a latitude and a longitude before a projected system (`map`, or + // a code) are degrees typed with its name, not a place a few steps from its origin: said, not + // taken for its units. Only numbers without a unit: `50 mE 30 mN map` says it is metres. + let degrees = at.x.abs() <= 180.0 && at.y.abs() <= 180.0 && (at.x.abs() <= 90.0 || at.y.abs() <= 90.0); + if degrees && units.is_empty() { + // With a unit it counts in, how to say these are its units after all. + let hint = + found.unit().map(|u| format!(", or write its unit after each number ({} {u}E {} {u}N)", at.x, at.y)).unwrap_or_default(); + return Some(Err(format!( + "{} {} {system} reads as degrees, not as a place in {system}: give degrees without a system, latitude then longitude{hint}", + at.x, at.y + ))); + } + Some(found.to_lonlat(at).ok_or_else(|| format!("{} {} names no place in {system}", at.x, at.y))) +} + +/// The next word of `rest` (words are parted by spaces and commas), moving past it. +fn next_word<'a>(rest: &mut &'a str) -> Option<&'a str> { + let t = rest.trim_start_matches(|c: char| c == ',' || c.is_whitespace()); + let end = t.find(|c: char| c == ',' || c.is_whitespace()).unwrap_or(t.len()); + let (w, r) = t.split_at(end); + *rest = r; + (!w.is_empty()).then_some(w) +} + /// What reading a typed position assumed. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum PositionRead { @@ -553,10 +855,18 @@ fn typed_place(map: &Map, p: &Value, moving: bool) -> Result<(Coord, Option return Err("position must be text, such as \"40.7128, -74.006\" or \"18TWL8395907350\"".into()), }; let given = |k: &str| !matches!(p.get(k), None | Some(Value::Null)); + let crs = match p.get("crs") { + None | Some(Value::Null) => None, + Some(Value::String(t)) if !t.trim().is_empty() => Some(t.trim()), + Some(_) => return Err("crs must be \"map\", a coordinate system such as \"EPSG:2056\", or a layer's name".into()), + }; let (lon, lat, notice) = if let Some(text) = position { if ["lon", "lat", "x", "y"].iter().any(|k| given(k)) { return Err("give a position or lon and lat, not both".into()); } + if crs.is_some() { + return Err("crs goes with x and y; a position names its own system (2600000 mE 1200000 mN EPSG:2056)".into()); + } let (c, read) = read_position(map, text)?; let reference = || text.trim().to_string().into(); let said = match read { @@ -577,6 +887,24 @@ fn typed_place(map: &Map, p: &Value, moving: bool) -> Result<(Coord, Option Result { + let key = keys.iter().find(|k| given(k)).ok_or_else(|| format!("{} is required (or a position)", keys[1]))?; + match p.get(*key) { + Some(Value::String(t)) => t.trim().parse::().ok(), + _ => f(p, key), + } + .filter(|v| v.is_finite()) + .ok_or_else(|| format!("{key} must be a number in {crs}")) + }; + // Both names of one axis: one would be passed over. + if ["lon", "x"].iter().all(|k| given(k)) || ["lat", "y"].iter().all(|k| given(k)) { + return Err("give x and y, or lon and lat, not both".into()); + } + let at = Coord::new(axis(["lon", "x"])?, axis(["lat", "y"])?); + let c = system_of(map, crs)?.to_lonlat(at).ok_or_else(|| format!("{} {} names no place in {crs}", at.x, at.y))?; + (c.x, c.y, None) } else { // A number, or text in degrees or degrees, minutes and seconds (`74°0′22″W`). let axis = |keys: [&str; 2], latitude: bool| -> Result { diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 07c65cb3dd..1f148e8788 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), 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}"#, + 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), an easting and northing with their system as the map's right-click menu copies them (2600000 mE 1200000 mN EPSG:2056; answers positionError when that names no place), 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}"#, ), ] } @@ -136,6 +136,11 @@ 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, + /// Why the query, written as an easting and a northing with their system (as the map's + /// right-click menu copies them), names no place: a unit the system doesn't count in, a + /// system of the Earth on another body's map, a place outside the system. `None` when it isn't + /// written so, or reads. + pub position_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 it is /// plainly a place ([`plainly_polar_place`]). The search box still @@ -167,9 +172,21 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // 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) { + // Read once: it may name a system whose conversion is made then, and the search box asks as + // you type. + let lat_lon = parse_lat_lon(&q); + let in_system = if lat_lon.is_none() { super::navigate::read_system_position(map, &q) } else { None }; + if let Some(c) = lat_lon { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); + } else if let Some(Ok(c)) = in_system { + // An easting and a northing in a named system, as the map's right-click menu copies them + // (`2600000 mE 1200000 mN EPSG:2056`). Plainly one when the system is a code; a name + // (`12 34 robinson`) may be a feature's too, so the tables are searched as well. + out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); + plainly_coordinate = q.contains(':'); + } else if let Some(Err(e)) = in_system { + out.position_error = Some(e); } else if map.body().is_earth() { match read_grid_reference(&q) { Ok(c) if letter_led(&q) && !plainly_polar_place(&q) => polar_place = Some(c), @@ -368,10 +385,11 @@ fn search_request(map: &rustgis_map::Map, p: &Value) -> Result<(Results, Option< ), }; if let Some(i) = pick { - r.hits.get(i).ok_or_else(|| match (r.hits.is_empty(), r.grid_error) { - (true, Some(e)) => format!("nothing matches '{query}': as a grid reference, {e}"), - (true, None) => format!("nothing matches '{query}'"), - (false, _) => format!("no hit {i}"), + r.hits.get(i).ok_or_else(|| match (r.hits.is_empty(), r.grid_error, &r.position_error) { + (true, Some(e), _) => format!("nothing matches '{query}': as a grid reference, {e}"), + (true, None, Some(e)) => format!("nothing matches '{query}': as a position, {e}"), + (true, None, None) => format!("nothing matches '{query}'"), + (false, ..) => format!("no hit {i}"), })?; } Ok((r, pick)) @@ -405,6 +423,9 @@ fn search_cmd(s: &mut Session, p: &Value) -> CmdResult { if let Some(e) = r.grid_error { out["gridError"] = json!(e.to_string()); } + if let Some(e) = &r.position_error { + out["positionError"] = json!(e); + } 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); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 520cdb06e2..83edddca81 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,6 +49,8 @@ mod write_notices; #[path = "tests/held_layers.rs"] mod held_layers; +#[path = "tests/map_system_places.rs"] +mod map_system_places; #[path = "tests/project_crs.rs"] mod project_crs; diff --git a/crates/engine/src/tests/map_system_places.rs b/crates/engine/src/tests/map_system_places.rs new file mode 100644 index 0000000000..a98daebfd9 --- /dev/null +++ b/crates/engine/src/tests/map_system_places.rs @@ -0,0 +1,379 @@ +//! Places in the map's or a layer's own system (#2032 C2f-8): Go To XY and Convert Position take +//! an easting and a northing in a named system (`crs`), and a typed position reads them as the +//! map's right-click menu copies them (`2600000 mE 1200000 mN EPSG:2056`), in the search box +//! too; Georeference's Fit To Map View places the raster in the map's own system. + +use rustgis_geom::Coord; +use serde_json::{Value, json}; + +use super::{out_raster, scan_layer, world}; +use crate::Session; + +/// Bern's old observatory, the Swiss grid's origin: E 2600000, N 1200000 in LV95 (EPSG:2056). +const BERN: Coord = Coord { x: 7.438_632, y: 46.951_082 }; + +fn near_bern(s: &Session) -> bool { + let c = s.map().center_lonlat(); + (c.x - BERN.x).abs() < 2e-3 && (c.y - BERN.y).abs() < 2e-3 +} + +fn away(s: &mut Session) { + s.run("map.goToXY", &json!({"lon": 2.35, "lat": 48.85})).unwrap(); + assert!(!near_bern(s)); +} + +#[test] +fn go_to_xy_takes_an_easting_and_northing_in_a_named_system() { + let mut s = world(); + // On the Web Mercator map, in LV95 by its code, as numbers or text. + for (x, y) in [(json!(2_600_000), json!(1_200_000)), (json!("2600000"), json!(" 1200000 "))] { + away(&mut s); + s.run("map.goToXY", &json!({"x": x, "y": y, "crs": "EPSG:2056"})).unwrap(); + assert!(near_bern(&s), "{:?}", s.map().center_lonlat()); + } + // In the map's own system: Web Mercator's metres here, then LV95's on a map drawn in it. + let merc = rustgis_geom::lonlat_to_merc(BERN); + away(&mut s); + s.run("map.goToXY", &json!({"x": merc.x, "y": merc.y, "crs": "map"})).unwrap(); + assert!(near_bern(&s)); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + away(&mut s); + s.run("map.goToXY", &json!({"x": 2_600_000, "y": 1_200_000, "crs": "MAP"})).unwrap(); + assert!(near_bern(&s)); + // In a layer's system: the sample's Cities are in degrees. + away(&mut s); + s.run("map.goToXY", &json!({"x": BERN.x, "y": BERN.y, "crs": "Cities"})).unwrap(); + assert!(near_bern(&s)); + // A system in degrees in a typed position: refused, as degrees are typed latitude first + // without one, and this form takes the easting first. + for system in ["EPSG:4326", "EPSG:4258"] { + let e = s.run("map.goToXY", &json!({"position": format!("40.7128, -74.006 {system}")})).unwrap_err(); + assert!(e.contains("counts in degrees"), "{system}: {e}"); + } + // Both names of an axis: refused, not one passed over. + let e = s.run("map.goToXY", &json!({"x": 2_600_000, "lon": 7.4, "y": 1_200_000, "crs": "EPSG:2056"})).unwrap_err(); + assert!(e.contains("not both"), "{e}"); + // Convert Position gives the same place. + let v = s.run("map.convertPosition", &json!({"x": 2_600_000, "y": 1_200_000, "crs": "EPSG:2056"})).unwrap(); + assert!((v["lon"].as_f64().unwrap() - BERN.x).abs() < 2e-3 && (v["lat"].as_f64().unwrap() - BERN.y).abs() < 2e-3, "{v}"); +} + +#[test] +fn a_position_with_its_system_reads_as_the_menu_copies_it() { + let mut s = world(); + for text in + ["2600000 mE 1200000 mN EPSG:2056", "2600000 1200000 EPSG:2056", "2600000, 1200000, epsg:2056", "2600000 E 1200000 N EPSG:2056"] + { + away(&mut s); + s.run("map.goToXY", &json!({"position": text})).unwrap_or_else(|e| panic!("{text}: {e}")); + assert!(near_bern(&s), "{text}: {:?}", s.map().center_lonlat()); + } + // Web Mercator by the name the readout copies, and in feet. + let merc = rustgis_geom::lonlat_to_merc(BERN); + away(&mut s); + s.run("map.goToXY", &json!({"position": format!("{:.2} mE {:.2} mN Web Mercator", merc.x, merc.y)})).unwrap(); + assert!(near_bern(&s)); + let v = s.run("map.convertPosition", &json!({"position": "2300000 ftUSE 10070000 ftUSN EPSG:2277"})).unwrap(); + let (lon, lat) = (v["lon"].as_f64().unwrap_or(0.0), v["lat"].as_f64().unwrap_or(0.0)); + assert!((-100.5..-95.0).contains(&lon) && (29.5..31.5).contains(&lat), "Texas Central, near Austin: {v}"); + // The search box finds it. + let hits = s.run("map.search", &json!({"query": "2600000 mE 1200000 mN EPSG:2056"})).unwrap(); + let found = hits.to_string(); + assert!(found.contains("7.43") && found.contains("46.95"), "{found}"); +} + +#[test] +fn places_in_a_system_are_refused_with_a_reason() { + let mut s = world(); + let err = |s: &mut Session, p: Value| s.run("map.goToXY", &p).expect_err(&p.to_string()); + assert!(err(&mut s, json!({"x": 1, "y": 2, "crs": "nowhere"})).contains("neither")); + assert!(err(&mut s, json!({"x": "a", "y": 2, "crs": "EPSG:2056"})).contains("number")); + assert!(err(&mut s, json!({"position": "2600000 1200000 EPSG:2056", "crs": "EPSG:2056"})).contains("position")); + assert!(err(&mut s, json!({"x": 1, "y": 2, "crs": 5})).contains("crs")); + // Far beyond the system's reach, no place. + assert!(err(&mut s, json!({"x": 1e9, "y": 1e9, "crs": "EPSG:2056"})).contains("no place")); + // The globe has no flat system of its own. + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + assert!(err(&mut s, json!({"x": 1, "y": 2, "crs": "map"})).contains("globe")); + // A unit the system doesn't count in names no place, and the search says why. + let v = s.run("map.search", &json!({"query": "2600000 ftE 1200000 ftN EPSG:2056"})).unwrap(); + assert_eq!(v["hits"], json!([]), "{v}"); + assert!(v["positionError"].as_str().is_some_and(|e| e.contains("counts in m, not ft")), "{v}"); + let e = s.run("map.search", &json!({"query": "2600000 ftE 1200000 ftN EPSG:2056", "go": true})).unwrap_err(); + assert!(e.contains("as a position") && e.contains("not ft"), "{e}"); + assert!(s.run("map.search", &json!({"query": "2600000 mE 1200000 mN EPSG:2056"})).unwrap().get("positionError").is_none()); +} + +/// On another body's map, a code names an Earth system: refused, not read as that body's +/// degrees, by `crs` as by a typed position. +#[test] +fn an_earth_system_names_no_place_on_another_body() { + let mut s = world(); + let err = |s: &mut Session, p: Value| s.run("map.goToXY", &p).expect_err(&p.to_string()); + s.run("map.body", &json!({"name": "mars", "basemap": false})).unwrap(); + for p in [json!({"x": 2_600_000, "y": 1_200_000, "crs": "EPSG:2056"}), json!({"position": "2600000 1200000 EPSG:2056"})] { + assert!(err(&mut s, p.clone()).contains("system of the Earth"), "{p}"); + let e = s.run("map.convertPosition", &p).expect_err(&p.to_string()); + assert!(e.contains("system of the Earth"), "{p}: {e}"); + } + // Nor does a layer held in a projection of the Earth, named as the system. + let mut swiss = rustgis_data::Dataset::new("Swiss", rustgis_data::GeometryType::Point, vec![]); + swiss.crs = Some(rustgis_data::raster::Crs::Epsg(2056)); + s.map_mut().add_dataset(swiss); + let p = json!({"x": 2_600_000, "y": 1_200_000, "crs": "Swiss"}); + assert!(err(&mut s, p.clone()).contains("a system of the Earth"), "{p}"); + let e = s.run("map.convertPosition", &p).expect_err(&p.to_string()); + assert!(e.contains("a system of the Earth"), "{e}"); + // A projection of Mars, given by its PROJ text as `crs`, is that map's own: it names a place + // there. (A typed position names its system by a name, which starts with a letter.) + let p = json!({"x": 100_000, "y": 200_000, "crs": "+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs"}); + let v = s.run("map.convertPosition", &p).unwrap_or_else(|e| panic!("{p}: {e}")); + // 100 km east along Mars's equator: 100000 / 3396190 rad. + let lon = v["lon"].as_f64().unwrap(); + assert!((lon - (100_000.0f64 / 3_396_190.0).to_degrees()).abs() < 1e-6, "{v}"); +} + +/// Degrees typed before a projected system's code are refused as before `map`; with units written +/// they are its units. +#[test] +fn degrees_typed_with_a_systems_code_are_refused() { + let mut s = world(); + let e = s.run("map.goToXY", &json!({"position": "46.95 7.44 EPSG:2056"})).unwrap_err(); + assert!(e.contains("reads as degrees") && e.contains("46.95 mE"), "{e}"); + let v = s.run("map.search", &json!({"query": "46.95 7.44 EPSG:2056"})).unwrap(); + assert!(v["positionError"].as_str().is_some_and(|e| e.contains("reads as degrees")), "{v}"); +} + +/// Another body's projection names no place on the Earth's map: its inverse gives that body's +/// degrees, not the Earth's. +#[test] +fn another_bodys_projection_names_no_place_on_the_earth() { + let mut s = world(); + let p = json!({"x": 100_000, "y": 200_000, "crs": "+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs"}); + let e = s.run("map.goToXY", &p).unwrap_err(); + assert!(e.contains("a system of another body"), "{e}"); + let mut mars = rustgis_data::Dataset::new("Mars plan", rustgis_data::GeometryType::Point, vec![]); + mars.crs = Some(rustgis_data::raster::Crs::parse("+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs").unwrap()); + s.map_mut().add_dataset(mars); + let e = s.run("map.convertPosition", &json!({"x": 100_000, "y": 200_000, "crs": "Mars plan"})).unwrap_err(); + assert!(e.contains("a system of another body"), "{e}"); +} + +/// A raster whose pixels couldn't be read names no system: refused with the reason, not taken +/// for longitude and latitude. +#[test] +fn a_raster_with_no_pixels_names_no_system() { + let mut s = world(); + scan_layer(&mut s, "relief"); + let id = s.map().layer_by_name("relief").unwrap().id; + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().data = None; + let e = s.run("map.goToXY", &json!({"x": 40, "y": 30, "crs": "relief"})).unwrap_err(); + assert!(e.contains("has no pixels loaded"), "{e}"); +} + +/// One body's projection names no place on another body's map either: Mars's inverse gives no +/// place on the Moon. The Moon's own projection does. +#[test] +fn a_projection_of_mars_names_no_place_on_the_moon() { + let mut s = world(); + s.run("map.body", &json!({"name": "moon", "basemap": false})).unwrap(); + let p = json!({"x": 100_000, "y": 200_000, "crs": "+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs"}); + let e = s.run("map.goToXY", &p).unwrap_err(); + assert!(e.contains("a system of Mars"), "{e}"); + let mut mars = rustgis_data::Dataset::new("Mars plan", rustgis_data::GeometryType::Point, vec![]); + mars.crs = Some(rustgis_data::raster::Crs::parse("+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs").unwrap()); + s.map_mut().add_dataset(mars); + let e = s.run("map.convertPosition", &json!({"x": 100_000, "y": 200_000, "crs": "Mars plan"})).unwrap_err(); + assert!(e.contains("a system of Mars"), "{e}"); + let moon = json!({"x": 100_000, "y": 200_000, "crs": "+proj=eqc +a=1737400 +b=1737400 +units=m +no_defs"}); + let v = s.run("map.convertPosition", &moon).unwrap_or_else(|e| panic!("{e}")); + assert!((v["lon"].as_f64().unwrap() - (100_000.0f64 / 1_737_400.0).to_degrees()).abs() < 1e-6, "{v}"); +} + +/// Degrees typed before `map` (latitude first, as without a system) are refused with the reason, +/// not read as metres a few steps from the map's origin; in the search box too. +#[test] +fn degrees_typed_with_the_maps_name_are_refused() { + let mut s = world(); + for text in ["40.7, -74.0 map", "-74.0 40.7 map"] { + let e = s.run("map.goToXY", &json!({"position": text})).unwrap_err(); + assert!(e.contains("reads as degrees"), "{text}: {e}"); + let v = s.run("map.search", &json!({"query": text})).unwrap(); + assert!(v["positionError"].as_str().is_some_and(|e| e.contains("reads as degrees")), "{text}: {v}"); + } + // Metres in the map's own system still go. + let merc = rustgis_geom::lonlat_to_merc(BERN); + away(&mut s); + s.run("map.goToXY", &json!({"position": format!("{:.0} {:.0} map", merc.x, merc.y)})).unwrap(); + assert!(near_bern(&s)); + // Small numbers with a unit written say they are metres: taken as such, by the map's origin. + s.run("map.goToXY", &json!({"position": "50 mE 30 mN map"})).unwrap(); + let c = s.map().center_lonlat(); + assert!(c.x.abs() < 1e-3 && c.y.abs() < 1e-3, "{c:?}"); +} + +/// A position in Web Mercator by a name only data's systems take is in metres, as Web Mercator +/// is: a unit of metres written with it is its own. +#[test] +fn web_mercator_by_any_name_counts_in_metres() { + let mut s = world(); + let merc = rustgis_geom::lonlat_to_merc(BERN); + // Names a map projection doesn't take, so they come by data's systems. + for name in ["EPSG:102100", "EPSG:102113"] { + assert_eq!(rustgis_data::raster::Crs::parse(name).ok(), Some(rustgis_data::raster::Crs::WebMercator), "{name}"); + assert!(rustgis_map::Projection::from_code(name).is_err(), "{name}"); + away(&mut s); + let text = format!("{:.2} mE {:.2} mN {name}", merc.x, merc.y); + s.run("map.goToXY", &json!({"position": text})).unwrap_or_else(|e| panic!("{text}: {e}")); + assert!(near_bern(&s), "{name}"); + } +} + +/// Fit To Map View on a projected map places the raster in the map's own system over the view's +/// rectangle, not over a box of degrees. +#[test] +fn fit_to_view_places_the_raster_in_the_maps_system() { + let mut s = world(); + s.view_size = (800.0, 600.0); + scan_layer(&mut s, "scan"); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + s.run("map.goToXY", &json!({"lon": BERN.x, "lat": BERN.y, "scale": 50_000})).unwrap(); + let v = s.run("raster.georeference", &json!({"layer": "scan", "extent": "view"})).unwrap(); + let r = out_raster(&s, &v); + assert_eq!(r.crs, rustgis_data::raster::Crs::Epsg(2056)); + let view = s.map().camera.extent(800.0, 600.0); + let t = r.transform; + let (right, bottom) = (t.origin_x + t.pixel_width * f64::from(r.width), t.origin_y + t.pixel_height * f64::from(r.height)); + for (a, b) in [(t.origin_x, view.min_x), (bottom, view.min_y), (right, view.max_x), (t.origin_y, view.max_y)] { + assert!((a - b).abs() < 1e-6, "{t:?} against the view {view:?}"); + } + // On Web Mercator, in its metres. + s.run("map.projection", &json!({"type": "mercator"})).unwrap(); + let v = s.run("raster.georeference", &json!({"layer": "scan", "extent": "view"})).unwrap(); + assert_eq!(out_raster(&s, &v).crs, rustgis_data::raster::Crs::WebMercator); + // A world copy past the antimeridian is fitted where it is within the world. + s.run("map.goToXY", &json!({"lon": 170.0, "lat": 0.0, "scale": 50_000})).unwrap(); + let world = 2.0 * std::f64::consts::PI * rustgis_geom::MERCATOR_R; + s.map_mut().camera.center.x += world; + let v = s.run("raster.georeference", &json!({"layer": "scan", "extent": "view"})).unwrap(); + let t = out_raster(&s, &v).transform; + assert!((t.origin_x - (s.map().camera.center.x - world)).abs() < 50_000.0, "{t:?}"); + // A turned or tilted view, or control points with a system but no transform, are refused. + s.run("map.setBearing", &json!({"bearing": 30})).unwrap(); + let e = s.run("raster.georeference", &json!({"layer": "scan", "extent": "view"})).unwrap_err(); + assert!(e.contains("turned or tilted"), "{e}"); + let e = s + .run("raster.georeference", &json!({"layer": "scan", "points": [[0, 0, 7, 47], [10, 10, 8, 46]], "crs": "EPSG:2056"})) + .unwrap_err(); + assert!(e.contains("transform"), "{e}"); + // Four numbers in a named system; degrees without one. + let v = s + .run("raster.georeference", &json!({"layer": "scan", "extent": [2_599_000, 1_199_000, 2_601_000, 1_201_000], "crs": "EPSG:2056"})) + .unwrap(); + assert_eq!(out_raster(&s, &v).crs, rustgis_data::raster::Crs::Epsg(2056)); + let v = s.run("raster.georeference", &json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0]})).unwrap(); + assert_eq!(out_raster(&s, &v).crs, rustgis_data::raster::Crs::LonLat); + assert!(s.run("raster.georeference", &json!({"layer": "scan", "extent": "view", "crs": "EPSG:2056"})).is_err()); + // What an extent doesn't use is refused, not passed over: control points' system, and an + // extent beside a transform. + let e = + s.run("raster.georeference", &json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0], "pointsCrs": "EPSG:2056"})).unwrap_err(); + assert!(e.contains("pointsCrs goes with control points"), "{e}"); + let e = s + .run( + "raster.georeference", + &json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0], "transform": "affine", "points": [[0, 0, 7.0, 47.0], [10, 0, 8.0, 47.0], [0, 10, 7.0, 46.0]]}), + ) + .unwrap_err(); + assert!(e.contains("not both"), "{e}"); + // Control points beside an extent, with no transform: refused, the layer as it was. + let before = s.map().layer_by_name("scan").unwrap().raster.as_ref().unwrap().data.as_ref().unwrap().transform; + let e = s + .run( + "raster.georeference", + &json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0], "points": [[0, 0, 7.0, 47.0], [10, 10, 8.0, 46.0]]}), + ) + .unwrap_err(); + assert!(e.contains("an extent or control points, not both"), "{e}"); + // What only a warp uses is refused without a transform, the layer placed nowhere new. + for (key, value) in + [("name", json!("aligned")), ("path", json!("aligned.tif")), ("cellSize", json!(0.01)), ("resampling", json!("cubic"))] + { + let mut p = json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0]}); + p[key] = value; + let e = s.run("raster.georeference", &p).unwrap_err(); + assert!(e.contains(&format!("{key} goes with a transform")), "{key}: {e}"); + } + assert!(s.map().layer_by_name("aligned").is_none()); + assert_eq!(s.map().layer_by_name("scan").unwrap().raster.as_ref().unwrap().data.as_ref().unwrap().transform, before); + // An entry that isn't a number is refused, not passed over, and nothing is placed. + let before = s.map().layers.len(); + for extent in [json!([0, 0, null, 10, 10]), json!([7, 46, 8, 47, "x"]), json!([7, 46, 8, "47"])] { + let e = s.run("raster.georeference", &json!({"layer": "scan", "extent": extent})).unwrap_err(); + assert!(e.contains("[minX, minY, maxX, maxY]"), "{extent}: {e}"); + } + assert_eq!(s.map().layers.len(), before); +} + +/// A layer named as a system means the layer; `map` after a position is the map's own system; a +/// unit that isn't the system's is refused rather than read as metres. +#[test] +fn names_and_units_mean_what_they_say() { + let mut s = world(); + // The sample's Cities, in degrees, renamed as LV95's bare code. + s.run("layer.rename", &json!({"layer": "Cities", "name": "2056"})).unwrap(); + away(&mut s); + s.run("map.goToXY", &json!({"x": BERN.x, "y": BERN.y, "crs": "2056"})).unwrap(); + assert!(near_bern(&s), "the layer, not EPSG:2056: {:?}", s.map().center_lonlat()); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + away(&mut s); + s.run("map.goToXY", &json!({"position": "2600000 mE 1200000 mN map"})).unwrap(); + assert!(near_bern(&s), "{:?}", s.map().center_lonlat()); + let e = s.run("map.goToXY", &json!({"position": "2600000 ftE 1200000 ftN EPSG:2056"})).unwrap_err(); + assert!(e.contains("counts in m, not ft"), "{e}"); +} + +/// A raster layer's system is its pixels' (a raster names none on its features): named in `crs`, +/// an LV95 raster takes an easting and a northing in LV95. +#[test] +fn a_raster_layers_system_is_its_pixels() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let mut s = world(); + let gt = GeoTransform { origin_x: 2_599_000.0, origin_y: 1_201_000.0, pixel_width: 100.0, pixel_height: -100.0 }; + let r = Raster::new("relief", 20, 20, vec![vec![1.0; 400]], gt, Crs::Epsg(2056), None, ColorHint::Gray, "Float32").unwrap(); + let bytes = geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "relief", rustgis_map::RasterLayer::from_bytes(r, "relief.tif".to_string(), bytes)).unwrap(); + away(&mut s); + s.run("map.goToXY", &json!({"x": 2_600_000, "y": 1_200_000, "crs": "relief"})).unwrap(); + assert!(near_bern(&s)); +} + +/// X and Y are an easting and a northing: a system counted west, then south (as South Africa's +/// Lo systems are) would take them mirrored, so it is refused with the reason. +#[test] +fn a_system_counted_other_than_east_then_north_is_refused() { + let mut s = world(); + let lo29 = "+proj=tmerc +lat_0=0 +lon_0=29 +k=1 +x_0=0 +y_0=0 +axis=wsu +ellps=WGS84 +units=m +no_defs"; + let e = s.run("map.goToXY", &json!({"x": 10_000, "y": 3_000_000, "crs": lo29})).unwrap_err(); + assert!(e.contains("counts a westing, then a southing"), "{e}"); + // By its EPSG code too (a code a map projection also takes), and as a typed position. + let e = s.run("map.goToXY", &json!({"x": 10_000, "y": 3_000_000, "crs": "EPSG:22275"})).unwrap_err(); + assert!(e.contains("counts a westing, then a southing"), "{e}"); + let e = s.run("map.goToXY", &json!({"position": "10000 3000000 EPSG:22275"})).unwrap_err(); + assert!(e.contains("counts a westing, then a southing"), "{e}"); + // A system whose EPSG definition names the northing first (LAEA Europe) still takes an + // easting, then a northing, as RustGIS holds and writes its coordinates. + s.run("map.goToXY", &json!({"position": "4200000 2600000 EPSG:3035"})).unwrap(); +} + +/// A place in Robinson, whose inverse iterates (to about 1.5e-5°, some 1.6 m), is taken: its +/// round trip comes back within a millionth of the coordinate's size. +#[test] +fn a_place_in_robinson_is_taken() { + let mut s = world(); + let robinson = rustgis_data::raster::Crs::parse("ESRI:54030").unwrap(); + let at = robinson.transformer().unwrap().from_lonlat(rustgis_geom::Coord::new(20.0, 30.0)).unwrap(); + let v = s.run("map.convertPosition", &json!({"x": at.x, "y": at.y, "crs": "ESRI:54030"})).unwrap(); + let (lon, lat) = (v["lon"].as_f64().unwrap(), v["lat"].as_f64().unwrap()); + assert!((lon - 20.0).abs() < 1e-4 && (lat - 30.0).abs() < 1e-4, "{v}"); +} diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 4d21922cc7..9e6c27325f 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -1189,17 +1189,9 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { .small() .weak(), ); + // In the map's own system on a flat map, so the raster fills the view as drawn. if ui.button(tl!("Fit To Map View")).clicked() { - let m = app.session.map(); - let (w, h) = app.session.view_size; - let e = m.camera.extent(w, h); - let (a, b) = ( - m.to_lonlat(rustgis_engine::geom::Coord::new(e.min_x, e.min_y)), - m.to_lonlat(rustgis_engine::geom::Coord::new(e.max_x, e.max_y)), - ); - if let (Some(a), Some(b)) = (a, b) { - run(app, "raster.georeference", json!({"layer": app.workflow.layer, "extent": [a.x, a.y, b.x, b.y]})); - } + run(app, "raster.georeference", json!({"layer": app.workflow.layer, "extent": "view"})); } ui.add( egui::TextEdit::multiline(&mut app.workflow.text) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c0f8871dc9..d354becb95 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -47,6 +47,13 @@ pub struct Dialogs { pub a: String, pub b: String, pub c: String, + /// Go To XY: the system its X and Y are in: empty for degrees, `map` for the map's own, or a + /// layer's name for the system it was read in. + pub xy_system: String, + /// Go To XY: the system `xy_system` named when its X and Y were filled ([`xy_key`]): the + /// map's projection, or a layer's, changing under the same entry makes them numbers in another + /// system. + pub xy_named: String, pub d: String, pub e: String, /// Add From Database: load the PostgreSQL table whole, to be edited and saved back. @@ -229,9 +236,9 @@ impl Dialogs { "goToXY" => { // The map's center, the longitude within ±180 even when the view has been panned // past the antimeridian. - let c = s.map().center_lonlat(); - self.a = format!("{:.4}", crate::mapmenu::wrap_lon(c.x)); - self.b = format!("{:.4}", c.y); + // In degrees, as every dialog opens afresh, the boxes' system noted. + [self.a, self.b] = center_in(s.map(), "").unwrap_or_default(); + self.xy_named = xy_key(s.map(), ""); } "bookmark" => self.text = rustgis_engine::cmd::navigate::new_bookmark_name(s.map()), "camera" => { @@ -434,29 +441,72 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { "selectByAttributes" => close = select_by_attributes(app, ui, &t), "goToXY" => { // UTM and MGRS are the Earth's grids, so another body's map offers degrees alone. - // A grid reference, once typed, is where Go goes: the degree boxes gray out. + // A grid reference, once typed, is where Go goes: the X and Y boxes gray out. let earth = app.session.map().body().is_earth(); let by_grid = earth && !app.dialogs.text.trim().is_empty(); + let systems = xy_systems(app.session.map()); + // A system gone (its layer removed or renamed) leaves degrees, and the boxes empty: + // their numbers were in that system, not degrees. + if !systems.iter().any(|(id, _)| *id == app.dialogs.xy_system) { + if !app.dialogs.xy_system.is_empty() { + app.dialogs.a.clear(); + app.dialogs.b.clear(); + } + app.dialogs.xy_system.clear(); + app.dialogs.xy_named = xy_key(app.session.map(), ""); + } + // The same entry naming another system now (the map's projection changed, or a + // layer's system was defined): the boxes take the center in it, or are emptied. + let named = xy_key(app.session.map(), &app.dialogs.xy_system); + if named != app.dialogs.xy_named { + [app.dialogs.a, app.dialogs.b] = center_in(app.session.map(), &app.dialogs.xy_system).unwrap_or_default(); + app.dialogs.xy_named = named; + } + let degrees = app.dialogs.xy_system.is_empty(); egui::Grid::new("xy").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { - let input_label = ui.label(tl!("Longitude (X)")); - ui.add_enabled( - !by_grid, - egui::TextEdit::singleline(&mut app.dialogs.a).hint_text("-74.006 · 74°0′22″W").desired_width(300.0), - ) - .labelled_by(input_label.id); + if systems.len() > 1 { + let input_label = ui.label(tl!("Coordinates in")); + let shown = systems.iter().find(|(id, _)| *id == app.dialogs.xy_system).map(|(_, l)| l.clone()).unwrap_or_default(); + let mut picked = None; + egui::ComboBox::from_id_salt("xy_system") + .selected_text(shown) + .width(300.0) + .show_ui(ui, |ui| { + for (id, label) in &systems { + if ui.selectable_label(*id == app.dialogs.xy_system, label).clicked() { + picked = Some(id.clone()); + } + } + }) + .response + .labelled_by(input_label.id); + if let Some(id) = picked.filter(|id| *id != app.dialogs.xy_system) { + // The boxes show the map's center in the system picked; empty when it + // has none there, so numbers in the old system aren't read in the new. + [app.dialogs.a, app.dialogs.b] = center_in(app.session.map(), &id).unwrap_or_default(); + app.dialogs.xy_named = xy_key(app.session.map(), &id); + app.dialogs.xy_system = id; + } + ui.end_row(); + } + let (x, y, x_hint, y_hint) = if degrees { + (tl!("Longitude (X)"), tl!("Latitude (Y)"), "-74.006 · 74°0′22″W", "40.7128 · 40°42′46″N") + } else { + (tl!("Easting (X)"), tl!("Northing (Y)"), "2600000", "1200000") + }; + let input_label = ui.label(x); + ui.add_enabled(!by_grid, egui::TextEdit::singleline(&mut app.dialogs.a).hint_text(x_hint).desired_width(300.0)) + .labelled_by(input_label.id); ui.end_row(); - let input_label = ui.label(tl!("Latitude (Y)")); - ui.add_enabled( - !by_grid, - egui::TextEdit::singleline(&mut app.dialogs.b).hint_text("40.7128 · 40°42′46″N").desired_width(300.0), - ) - .labelled_by(input_label.id); + let input_label = ui.label(y); + ui.add_enabled(!by_grid, egui::TextEdit::singleline(&mut app.dialogs.b).hint_text(y_hint).desired_width(300.0)) + .labelled_by(input_label.id); ui.end_row(); if earth { - let input_label = ui.label(tl!("Or grid reference")); + let input_label = ui.label(tl!("Or position")); ui.add( egui::TextEdit::singleline(&mut app.dialogs.text) - .hint_text("18TWL8395907350 · 18north 583959 4507351") + .hint_text("18TWL8395907350 · 2600000 mE 1200000 mN EPSG:2056") .desired_width(300.0), ) .labelled_by(input_label.id); @@ -468,18 +518,24 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { ui.end_row(); }); // Below the boxes, wrapped to the dialog's width rather than widening it. - let hint = if earth { - tl!("Degrees as decimals or degrees, minutes and seconds; or a UTM or MGRS reference in place of both.") - } else { - tl!("Degrees as decimals or degrees, minutes and seconds.") + let hint = match (earth, degrees) { + (true, true) => tl!( + "Degrees as decimals or degrees, minutes and seconds; or a UTM or MGRS reference, or an easting and northing with their system as the map's right-click menu copies them, in place of both." + ), + (true, false) => tl!( + "The easting and northing in the system chosen; or a UTM or MGRS reference, or an easting and northing with their system, in place of both." + ), + (false, _) => tl!("Degrees as decimals or degrees, minutes and seconds."), }; ui.label(egui::RichText::new(hint).weak()); close = buttons(app, ui, "Go", |app| { let grid = app.dialogs.text.trim(); let mut p = if app.session.map().body().is_earth() && !grid.is_empty() { json!({"position": grid}) - } else { + } else if app.dialogs.xy_system.is_empty() { json!({"lon": app.dialogs.a.trim(), "lat": app.dialogs.b.trim()}) + } else { + json!({"x": app.dialogs.a.trim(), "y": app.dialogs.b.trim(), "crs": app.dialogs.xy_system}) }; // The command refuses a scale it can't use: commas go only where they group // thousands (50,000), so a decimal comma (1,5) is refused, not read as 15. @@ -1062,6 +1118,78 @@ pub fn open_dxf_path(app: &mut RustGisApp, path: &str) -> Result open_dxf(app, path, DxfSource::Path(path.to_string())) } +/// The systems Go To XY offers, as (what `map.goToXY` takes as `crs`, its label): degrees; on a +/// flat map of the Earth, the map's own; and each layer read in a projected system, by name (at +/// most 20, the first of each system). +fn xy_systems(map: &rustgis_engine::map::Map) -> Vec<(String, String)> { + let mut v = vec![(String::new(), tl!("Degrees (longitude, latitude)").to_string())]; + if map.body().is_earth() && !map.projection.is_globe() { + v.push(("map".into(), crate::i18n::fmt("The map's system ({system})", &[("system", &map.projection.label())]))); + let mut seen = Vec::new(); + for l in &map.layers { + // A layer named `map` would be taken for the map's own system, and one whose name another + // layer has first would be taken for that one. + // By the name as `map.goToXY` reads it, trimmed (a layer named " map " is the map's). + let found_by_name = map.layer_by_name(l.name.trim()).is_some_and(|f| f.id == l.id); + // Only a system of the Earth counted east, then north: X and Y are an easting and a + // northing, and another body's projection names no place on the Earth's map. + let Some(crs) = rustgis_engine::cmd::navigate::layer_coordinates_system(l).filter(|c| { + !c.is_geographic() + && !c.is_planetary() + && c.axis_directions() == [(1.0, 0.0), (0.0, 1.0)] + && !l.name.trim().eq_ignore_ascii_case("map") + && found_by_name + }) else { + continue; + }; + if seen.contains(&crs) || seen.len() >= 20 { + continue; + } + seen.push(crs); + v.push(( + l.name.clone(), + crate::i18n::fmt("Layer {layer} ({system})", &[("layer", &l.name), ("system", &short(&crs.definition_text()))]), + )); + } + } + v +} + +/// The system a Go To XY entry (`id`, as [`xy_systems`] lists it) names now: degrees, the map's +/// projection, or the system a layer was read in, by its definition (not the list's wording, +/// which a change of language rewrites). +fn xy_key(map: &rustgis_engine::map::Map, id: &str) -> String { + match id { + "" => String::new(), + "map" => format!("map {}", map.projection.code()), + layer => map + .layer_by_name(layer.trim()) + .and_then(rustgis_engine::cmd::navigate::layer_coordinates_system) + .map(|c| format!("layer {}", c.definition_text())) + .unwrap_or_default(), + } +} + +/// `text` cut to 60 characters, with an ellipsis when cut (a PROJ definition in a list). +fn short(text: &str) -> String { + if text.chars().nth(60).is_some() { format!("{}…", text.chars().take(59).collect::()) } else { text.to_string() } +} + +/// The map's center in a Go To XY system (see [`xy_systems`]), as the X and Y boxes show it: degrees +/// to four decimals, else to two. +fn center_in(map: &rustgis_engine::map::Map, system: &str) -> Option<[String; 2]> { + let c = map.center_lonlat(); + let c = rustgis_engine::geom::Coord::new(crate::mapmenu::wrap_lon(c.x), c.y); + let at = match system { + "" => return Some([format!("{:.4}", c.x), format!("{:.4}", c.y)]), + "map" => map.flat().forward(c)?, + layer => { + rustgis_engine::cmd::navigate::layer_coordinates_system(map.layer_by_name(layer.trim())?)?.transformer().ok()?.from_lonlat(c)? + } + }; + at.is_finite().then(|| [format!("{:.2}", at.x), format!("{:.2}", at.y)]) +} + /// The current map's coordinate system, as a DXF import can be given it: Web Mercator and the /// globe as their EPSG codes; another flat projection as its EPSG code or, for a preset, what the /// map projects with, which is the map's exactly (a definition `Crs::parse` reads). @@ -3689,6 +3817,47 @@ mod tests { assert_eq!(h.state().session.map().projection.code(), "EPSG:2056"); } + /// Go To XY with the map's own system picked: when the map's projection changes while the + /// dialog is open, X and Y take the center in the new system, never the old numbers read in + /// it; numbers typed stay as they are frame after frame. + #[test] + fn go_to_xy_follows_the_maps_system_changing_under_it() { + let mut app = RustGisApp::with_sample(); + app.run("map.projection", json!({"type": "EPSG:2056"})).unwrap(); + app.run("map.goToXY", json!({"lon": 7.44, "lat": 46.95})).unwrap(); + app.dialogs.open("goToXY", &app.session).unwrap(); + app.dialogs.xy_system = "map".into(); + let frame = |app: RustGisApp| { + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(1400.0, 1000.0)) + .with_max_steps(8) + .with_context_setup(|ctx| crate::theme::install_fonts(ctx, &[], None)) + .build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(2); + h.into_state() + }; + let mut app = frame(app); + let lv95 = center_in(app.session.map(), "map").unwrap(); + assert_eq!([app.dialogs.a.clone(), app.dialogs.b.clone()], lv95, "the center in LV95"); + assert!(app.dialogs.a.parse::().unwrap() > 2_000_000.0, "{}", app.dialogs.a); + app.run("map.projection", json!({"type": "mercator"})).unwrap(); + let mut app = frame(app); + let mercator = center_in(app.session.map(), "map").unwrap(); + assert_eq!([app.dialogs.a.clone(), app.dialogs.b.clone()], mercator, "the center in Web Mercator, not LV95's numbers"); + assert_eq!(app.dialogs.xy_system, "map"); + // Numbers typed stay. + app.dialogs.a = "830000".into(); + let app = frame(app); + assert_eq!(app.dialogs.a, "830000"); + } + /// In the app, Escape in a coordinate system box closes its list, not the dialog, and the /// Escape shortcut (the Explore tool) doesn't take it; Enter in the blank box takes no recent /// system, while ↓ then Enter does. diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index ae9dc12894..21d3b57b37 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -291,8 +291,12 @@ fn list_area(app: &mut RustGisApp, ui: &Ui, frame_r: Rect, list: &[Row], t: &Tok // A grid reference that names no place says why (the band, the square letters, S // that may mean south), also while places can still be searched for it. let grid = st.results.grid_error.filter(|_| st.query == st.searched && st.results.hits.is_empty()); + // So does an easting and northing with their system that names none (#2032 C2f-8). + let position = st.results.position_error.as_ref().filter(|_| st.query == st.searched && st.results.hits.is_empty()); if let Some(e) = grid { note(ui, &grid_error_text(e), t.text_dim); + } else if let Some(e) = position { + note(ui, &crate::i18n::fmt_raw("No place at this position: {reason}", &[("reason", e.as_str())]), t.text_dim); } else if none { note(ui, tl_raw!("Nothing found"), t.text_dim); } diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index f5c598b3e5..18da4fa356 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -4808,6 +4808,61 @@ fn by_coordinates_reads_x_y_and_a_grid_reference() { assert!((c.y - 40.7128).abs() < 1e-3 && (c.x + 74.006).abs() < 1e-3, "{c:?}"); } +/// On a projected map By Coordinates offers the map's own system: picked, the boxes show the map's +/// center as an easting and a northing, and Go goes to the easting and northing typed. A position +/// written as the right-click menu copies it, with its system, goes there too. +#[test] +fn by_coordinates_takes_an_easting_and_northing_in_the_maps_system() { + let mut h = harness(); + h.state_mut().run("map.projection", json!({"type": "EPSG:2056"})).unwrap(); + h.state_mut().run("map.goToXY", json!({"lon": 8.54, "lat": 47.37, "scale": 50_000})).unwrap(); + h.state_mut().run("ui.dialog", json!({"name": "goToXY"})).unwrap(); + h.step(); + assert_eq!(h.state().dialogs.xy_system, "", "degrees first"); + h.step(); + h.get_by_label("Coordinates in").click(); + h.step(); + h.step(); + h.get_by_label("The map's system (EPSG:2056)").click(); + h.step(); + assert_eq!(h.state().dialogs.xy_system, "map"); + // Zürich, about E 2683000, N 1247000. + let (e, n): (f64, f64) = (h.state().dialogs.a.parse().unwrap(), h.state().dialogs.b.parse().unwrap()); + assert!((e - 2_683_000.0).abs() < 2_000.0 && (n - 1_247_000.0).abs() < 2_000.0, "{e} {n}"); + h.step(); + h.get_by_label("Easting (X)"); + h.state_mut().dialogs.a = "2600000".into(); + h.state_mut().dialogs.b = "1200000".into(); + h.step(); + h.get_by_label("Go").click(); + h.step(); + assert_eq!(h.state().dialogs.open, None, "{:?}", h.state().dialogs.error); + let c = h.state().session.map().center_lonlat(); + assert!((c.x - 7.4386).abs() < 2e-3 && (c.y - 46.9511).abs() < 2e-3, "Bern: {c:?}"); + // The menu's copy, pasted into the position box. + h.state_mut().run("map.goToXY", json!({"lon": 8.54, "lat": 47.37})).unwrap(); + h.state_mut().run("ui.dialog", json!({"name": "goToXY"})).unwrap(); + h.step(); + h.state_mut().dialogs.text = "2600000 mE 1200000 mN EPSG:2056".into(); + h.step(); + h.get_by_label("Go").click(); + h.step(); + assert_eq!(h.state().dialogs.open, None, "{:?}", h.state().dialogs.error); + let c = h.state().session.map().center_lonlat(); + assert!((c.x - 7.4386).abs() < 2e-3 && (c.y - 46.9511).abs() < 2e-3, "Bern: {c:?}"); + // The system picked gone (the map turned to the globe, with no flat system of its own): back + // to degrees with the boxes empty, so its easting and northing aren't sent as degrees. + h.state_mut().run("ui.dialog", json!({"name": "goToXY"})).unwrap(); + h.step(); + h.state_mut().dialogs.xy_system = "map".into(); + h.state_mut().dialogs.a = "2600000".into(); + h.state_mut().dialogs.b = "1200000".into(); + h.state_mut().run("map.projection", json!({"type": "globe"})).unwrap(); + h.step(); + let d = &h.state().dialogs; + assert_eq!((d.xy_system.as_str(), d.a.as_str(), d.b.as_str()), ("", "", "")); +} + /// Panned past the antimeridian, By Coordinates still opens on a longitude within ±180, so Go on /// the text it wrote goes there. #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 87ff24fe8a..ea42746460 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1990,8 +1990,23 @@ The Imagery tab's groups open their tools in the Workflows pane. The tab belongs images are in another geographic system (NAD83, say), the run says so. A geographic `crs` other than EPSG:4326 is refused. - **Georeference** places a raster from control points (column, row, longitude, latitude) or - stretches it over the map view. Those only shift and scale a north-up grid, as RustGIS's - geotransform has no rotation. With `transform` (`raster.georeference`) the points are fitted by any + stretches it over the map view (**Fit To Map View**, `"extent": "view"`). Those only shift and + scale a north-up grid, as RustGIS's geotransform has no rotation. Fitted to the view, the raster + is placed in the map's own system on a flat map of the Earth (Web Mercator's EPSG:3857, the map's + EPSG or ESRI code, or a preset's definition), so it fills the view as drawn; on the globe and + another body's map, over the longitude and latitude box the view shows. A turned or tilted map + is refused (Reset North first), as is a Web Mercator view wider than the world or across the + antimeridian; a view of a world copy past it is fitted to the same place within ±180°. Control + points without `transform` are longitude and latitude, and `pointsCrs` or `crs` with them is + refused. An `extent` of four + numbers is in degrees, or in `crs` when given (`{"extent": [2599000, 1199000, 2601000, 1201000], + "crs": "EPSG:2056"}`), and the raster is placed in that system; an entry that isn't a number is + refused, not passed over. An extent goes without control points, `transform` and `pointsCrs`: + any of them beside it is refused, as none would be used. So are `name`, `path`, `cellSize` and + `resampling` without `transform`, as only a warp makes a new raster; without one the layer itself + is placed. The `extent` it answers is in longitude/latitude, whatever system the raster is + placed in. + With `transform` (`raster.georeference`) the points are fitted by any of the Control Point Fit transforms and the raster is warped onto a new north-up grid covering the warped image: `{"layer": "scan", "transform": "spline", "points": [[column, row, x, y], …], "pointsCrs": "EPSG:4326", "crs": 32613, "resampling": "bilinear", "cellSize": 5, "name": "warped", diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 3550ecc2a0..3300db388a 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -14,9 +14,28 @@ Europe, Africa, Americas and East Asia), and **Locate**: **By Coordinates…** p (X) and latitude (Y), each in decimal degrees or degrees, minutes and seconds (`-74.006` or `74°0'22"W`; `40.7128` or `40°42'46"N`; an N or S in the longitude is refused, not swapped), or on the Earth's map to a UTM or MGRS grid reference in place of both (`18north 583959 4507351`, -`18TWL8395907350`). `map.goToXY` takes the same: `lon` and `lat` as numbers or text, or a -`position` read as the search box reads it, latitude first; two bare numbers there are said back -as the latitude and longitude they were read as. A reference that names no place says why; an +`18TWL8395907350`). On a flat map of the Earth, **Coordinates in** also offers the map's own +system and each layer's projected system: X and Y are then an easting and a northing there, +starting at the map's center. The position box (and the search box) also reads an easting and a +northing followed by their system, as the right-click menu copies them in map coordinates +(`2600000 mE 1200000 mN EPSG:2056`, `2600000 1200000 EPSG:2056`; the system as a code, `Web +Mercator`, a projection preset, or `map` for the map's own). A system in degrees is refused there, +as degrees go without a system, latitude first, and so are numbers that read as degrees typed +before a projected system with no unit written (`46.95 7.44 EPSG:2056`); with a unit written +after each number they are the system's. A layer in a projection of the Earth names +no place on another body's map, nor does another body's projection on the Earth's map (or on a +third body's: Mars's on the Moon's), and the dialog doesn't offer one. X and Y are an easting and a +northing: a system counted west or south, or northing first, is refused (and not offered in the +dialog), and a raster layer gives the system its pixels are in (one with no +pixels loaded, still opening or unreadable, is refused). A unit written (`m`, `ft`, `ftUS`) +must be the system's: feet in a system of metres are refused, not read as metres; the search +box then says why, and `map.search` returns the reason as `positionError`. On another body's map, a +system named by a code is the Earth's and is refused. `map.goToXY` takes the same: `lon` and `lat` as numbers or +text, or `x` and `y` with `crs` (`"map"`, a layer's name for the system it was read in, or a +code such as `EPSG:2056`; a layer named like a code means the layer), or a `position` read as the search box reads it, latitude first; two +bare numbers there are said back as the latitude and longitude they were read as. A place a +system's formulas don't reach (one that doesn't project back to the same easting and northing) +is refused. A reference that names no place says why; an MGRS reference coarser than a meter (`18TWL`) goes to the center of its square and says so. **By Place or Address…** finds a place or address with a geocoder. **New Bookmark…**