diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 68b5c3a3ce..2bf9565977 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -497,17 +497,19 @@ pub fn commands() -> Vec { if !(dx.is_finite() && dy.is_finite()) || dx.abs() > 4e7 || dy.abs() > 4e7 { return Err("dx and dy must be finite distances in the command's units (limit: 40,000 km per axis after ground-to-grid)".into()); } - // In Web Mercator, as always, while a feature and its result stay within its square - // (each moved once, and kept for the move); one that doesn't, and those sharing a - // vertex with it, move on the ground (#1033), or for a move of no distance stay as - // they are. + // A layer held in a projected system moves along its own grid (#2032 C2f-6). Any + // other in Web Mercator, as always, while a feature and its result stay within its + // square (each moved once, and kept for the move); one that doesn't, and those + // sharing a vertex with it, move on the ground (#1033), or for a move of no distance + // stay as they are. + let own = one_grid(s, dx == 0.0 && dy == 0.0); let mut shifted: HashMap<(u32, usize), Geometry> = HashMap::new(); - for l in s.map().layers.iter().filter(|l| !l.is_raster() && !l.selection.is_empty()) { + for l in s.map().layers.iter().filter(|l| !l.is_raster() && !l.selection.is_empty() && !own.contains_key(&l.id)) { let to = l.dataset.shown_conversion()?; for r in &l.selection { - // Moved in longitude/latitude, from the layer's own coordinates (`modify` writes + // Moved in longitude/latitude, from the layer's own coordinates (`modify_in` writes // it back in them). A feature with a place that can't be given there stays - // as it is (`modify` counts it). + // as it is (`modify_in` counts it). let Some(own) = l.dataset.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; let Some(g) = rustgis_data::Dataset::converted_to_lonlat(&to, own) else { continue }; if !within_square(&g) { @@ -527,14 +529,21 @@ pub fn commands() -> Vec { let (planes, ground, coarse) = if still { (HashMap::new(), 0, 0) } else { - move_planes(s, |key| shifted.contains_key(&key), dx.hypot(dy))? + move_planes(s, &own, |key| shifted.contains_key(&key), dx.hypot(dy))? }; let mut placed = HashMap::new(); placed.try_reserve(ground).map_err(|_| "not enough memory to move the selection on the ground")?; // Each group's move, worked out once: its planes and its turn's sine and cosine. let mut moves: HashMap<(i64, i64), (Aeqd, Aeqd, f64, f64)> = HashMap::new(); - let done = move_features(s, |key, g| match planes.get(&key) { - Some(center) => { + let done = move_features(s, &own, |key, g| match (own.get(&key.0), planes.get(&key)) { + // A move of no distance (with other layers' features in Web Mercator) leaves + // these as they are, with no edit of them recorded. + (Some(_), _) if still => Ok(None), + (Some(grid), _) => { + let d = grid.step(dx, dy); + OwnGrid::map(g, |c| Coord::new(c.x + d.x, c.y + d.y)).map(Some) + } + (None, Some(center)) => { let (from, to, sin, cos) = *moves.entry(vertex_key(*center)).or_insert_with(|| { let (from, to, turn) = ground_move(*center, dx, dy); let (sin, cos) = turn.sin_cos(); @@ -543,7 +552,7 @@ pub fn commands() -> Vec { polar_transform(g, (&from, &to), Some(&mut placed), |p| Coord::new(p.x * cos + p.y * sin, p.y * cos - p.x * sin)) .map(Some) } - None => Ok(shifted.remove(&key)), + (None, None) => Ok(shifted.remove(&key)), })?; center_notice(s, coarse); Ok(done) @@ -553,13 +562,17 @@ pub fn commands() -> Vec { C::new("edit.rotate", "Rotate", "Edit › Features › Modify", |s, p| { let deg = f(p, "angle").ok_or("angle is required")?; let mut steps = CenterSteps::new(); - let done = move_features(s, |_, g| { + let own = own_grids(s); + let done = move_features(s, &own, |key, g| { // Any point, a feature's or a text graphic's, turns on itself: left out, so a // selection of points alone fails rather than recording an edit that changes // nothing (and an undo step). if matches!(g, Geometry::Point(_)) { return Ok(None); } + if let Some(grid) = own.get(&key.0) { + return grid.rotate(g, deg).map(Some); + } let (sin, cos) = (-deg.to_radians()).sin_cos(); about_center( g, @@ -579,11 +592,15 @@ pub fn commands() -> Vec { C::new("edit.scale", "Scale", "Edit › Features › Modify", |s, p| { let k = f(p, "factor").filter(|k| *k > 0.0 && *k < 1e6).ok_or("factor must be a positive number")?; let mut steps = CenterSteps::new(); - let done = move_features(s, |_, g| { + let own = own_grids(s); + let done = move_features(s, &own, |key, g| { // Any point, a feature's or a text graphic's, scales on itself: left out, as above. if matches!(g, Geometry::Point(_)) { return Ok(None); } + if own.contains_key(&key.0) { + return OwnGrid::scale(g, k).map(Some); + } let merc = |c: Coord, m: Coord| Coord::new(c.x + (m.x - c.x) * k, c.y + (m.y - c.y) * k); about_center(g, merc, |p| Coord::new(p.x * k, p.y * k), &mut steps) })?; @@ -594,7 +611,7 @@ pub fn commands() -> Vec { .params(r#"{"factor": number}"#), C::new("edit.flip", "Flip Line", "Edit › Features › Modify", |s, _| { // Only the vertices' order changes, so in the layer's own coordinates, as stored. - modify_in(s, Space::Own, |_, g| match g { + modify_in(s, |_| Space::Own, |_, g| match g { Geometry::Line(parts) => Ok(Some(Geometry::Line(parts.iter().rev().map(|p| p.iter().rev().copied().collect()).collect()))), _ => Ok(None), }) @@ -682,6 +699,120 @@ fn distance_unit_metres(p: &Json) -> Result { rustgis_geom::distance_unit_metres(&unit.to_ascii_lowercase()).ok_or_else(|| "units must be Meters, Feet, Kilometers or Miles".into()) } +/// The grid of a layer held in a projected system, which Move, Rotate, Scale and Traverse work in +/// (#2032 C2f-6), as the analysis tools do ([`rustgis_analysis::works_in`]): distances flat in its +/// unit, directions from its grid north, by the order and direction of its axes. A layer in +/// longitude/latitude, Web Mercator, another world projection or a geographic system has none, +/// and is edited in Web Mercator or on the ground, as before. +#[derive(Clone, Copy)] +struct OwnGrid { + /// The system. + crs: rustgis_data::raster::Crs, + /// Metres per unit of its coordinates. + unit_m: f64, + /// The (east, north) of a step of one along x, then along y. + axes: [(f64, f64); 2], +} + +impl OwnGrid { + /// The grid layer `l` is edited in, if any. + fn of(l: &rustgis_map::Layer) -> Option { + let crs = l.dataset.coord_crs(); + // Graphics are edited as before: their shapes share no places with features. + if l.is_raster() || l.graphics || !rustgis_analysis::works_in(crs) { + return None; + } + let (unit_m, axes) = crs.unit_and_axes(); + let [(xe, xn), (ye, yn)] = axes; + // Axes along one line give no plane to step in. + ((xe * yn - ye * xn).abs() > 1e-9).then_some(Self { crs, unit_m, axes }) + } + + /// A step `(e, n)` east and north of the grid, in its units, as a step of its coordinates. + fn coords_of(self, e: f64, n: f64) -> Coord { + let [(xe, xn), (ye, yn)] = self.axes; + let det = xe * yn - ye * xn; + Coord::new((e * yn - n * ye) / det, (xe * n - xn * e) / det) + } + + /// A step of its coordinates as (east, north) of the grid, in its units. + fn east_north(self, d: Coord) -> (f64, f64) { + let [(xe, xn), (ye, yn)] = self.axes; + (d.x * xe + d.y * ye, d.x * xn + d.y * yn) + } + + /// A step of `dx` and `dy` metres east and north of the grid, in its coordinates. + fn step(self, dx: f64, dy: f64) -> Coord { + self.coords_of(dx / self.unit_m, dy / self.unit_m) + } + + /// `g` with each vertex `f` gives for it (one missing a coordinate, or with an infinite one, + /// stays as it was, as in longitude/latitude); refused when a vertex would get none. + fn map(g: &Geometry, f: impl Fn(Coord) -> Coord) -> Result { + let lost = std::cell::Cell::new(false); + let done = g.map_coords(&|c: Coord| { + if !c.is_finite() { + return c; + } + let p = f(c); + lost.set(lost.get() || !p.is_finite()); + p + }); + if lost.get() { + return Err("that would carry a vertex past any coordinate its layer's system can hold".into()); + } + Ok(done) + } + + /// `g` turned clockwise by `deg` (grid north up) about the middle of its extent. + fn rotate(self, g: &Geometry, deg: f64) -> Result { + let (sin, cos) = (-deg.to_radians()).sin_cos(); + let c = g.extent().center(); + Self::map(g, |p| { + let (e, n) = self.east_north(Coord::new(p.x - c.x, p.y - c.y)); + let d = self.coords_of(e * cos - n * sin, e * sin + n * cos); + Coord::new(c.x + d.x, c.y + d.y) + }) + } + + /// `g` scaled by `k` about the middle of its extent. + fn scale(g: &Geometry, k: f64) -> Result { + let c = g.extent().center(); + Self::map(g, |p| Coord::new(c.x + (p.x - c.x) * k, c.y + (p.y - c.y) * k)) + } +} + +/// The grid each layer with a selection is edited in ([`OwnGrid`]), by layer id. +fn own_grids(s: &Session) -> HashMap { + s.map().layers.iter().filter(|l| !l.selection.is_empty()).filter_map(|l| Some((l.id, OwnGrid::of(l)?))).collect() +} + +/// The grid a Move takes for its selection: [`own_grids`] while every layer with a selection is +/// held in one projected system; none when they are in more than one (or some in one and some +/// not), since a feature of one may share a place with a feature of another that a step on +/// another grid, or in Web Mercator, would tear from it. That selection moves in Web Mercator or +/// on the ground, as before, and says so (a move of no distance, refused, says nothing). Graphics +/// layers, whose shapes share no places with features, don't count. +fn one_grid(s: &mut Session, still: bool) -> HashMap { + let own = own_grids(s); + let selected: Vec<&rustgis_map::Layer> = + s.map().layers.iter().filter(|l| !l.is_raster() && !l.graphics && !l.selection.is_empty()).collect(); + let first = own.values().next().map(|g| g.crs); + let one = selected.iter().all(|l| own.get(&l.id).is_some_and(|g| Some(g.crs) == first)); + if own.is_empty() || one { + return own; + } + if still { + return HashMap::new(); + } + let names = selected.iter().filter(|l| own.contains_key(&l.id)).map(|l| format!("'{}'", l.name)).collect::>().join(", "); + s.warn(format!( + "the selection spans layers in more than one coordinate system, so {names} moved the same way as \ + the rest, in Web Mercator (or on the ground), not along its own grid, to keep places the layers share together: select one system's layers to move along its grid" + )); + HashMap::new() +} + /// A point moved by metres east and north (Web Mercator stretched to the point's latitude). fn shift(c: Coord, dx: f64, dy: f64) -> Coord { let k = 1.0 / c.y.to_radians().cos().max(0.01); @@ -888,13 +1019,15 @@ fn about_center( /// ([`ground_movable`]). With the map, how many vertices move on the ground. fn move_planes( s: &Session, + own: &HashMap, stays: impl Fn((u32, usize)) -> bool, reach_m: f64, ) -> Result<(HashMap<(u32, usize), Coord>, usize, usize), String> { // In longitude/latitude, from each layer's own coordinates. let mut selected: Vec<((u32, usize), std::borrow::Cow<'_, Geometry>)> = Vec::new(); - // A feature with a place that can't be given there isn't moved ([`modify`] counts it). - for l in s.map().layers.iter().filter(|l| !l.is_raster() && !l.selection.is_empty()) { + // A feature with a place that can't be given there isn't moved ([`modify_in`] counts it), nor + // one of a layer moved along its own grid (`own`). + for l in s.map().layers.iter().filter(|l| !l.is_raster() && !l.selection.is_empty() && !own.contains_key(&l.id)) { let to = l.dataset.shown_conversion()?; for r in &l.selection { let Some(g) = l.dataset.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; @@ -1117,11 +1250,17 @@ fn polar_transform( }) } -/// [`modify`] for a move, turn or scale, which leaves a vertex missing a coordinate (or with an -/// infinite one) where it was: says how many of the features it changed have one. -fn move_features(s: &mut Session, mut change: impl FnMut((u32, usize), &Geometry) -> Result, String>) -> CmdResult { +/// [`modify_in`] for a move, turn or scale, which leaves a vertex missing a coordinate (or with an +/// infinite one) where it was: says how many of the features it changed have one. A layer in +/// `own` gives its geometry in its own coordinates, to be changed in its grid. +fn move_features( + s: &mut Session, + own: &HashMap, + mut change: impl FnMut((u32, usize), &Geometry) -> Result, String>, +) -> CmdResult { let mut missing = 0usize; - let done = modify(s, |key, g| { + let space = |id: u32| if own.contains_key(&id) { Space::Own } else { Space::LonLat }; + let done = modify_in(s, space, |key, g| { let moved = change(key, g)?; if moved.is_some() { let mut has = false; @@ -1136,14 +1275,6 @@ fn move_features(s: &mut Session, mut change: impl FnMut((u32, usize), &Geometry Ok(done) } -/// Applies a geometry change to every selected feature of every layer (in the selection's layers), -/// in longitude/latitude ([`Space::LonLat`]). A feature with a place that can't be given there is -/// left as it is, and said with a count per layer; when every changeable feature is such a -/// feature, the edit is refused saying why. -fn modify(s: &mut Session, change: impl FnMut((u32, usize), &Geometry) -> Result, String>) -> CmdResult { - modify_in(s, Space::LonLat, change) -} - /// Where [`modify_in`] gives each geometry to a change. #[derive(Clone, Copy, PartialEq)] enum Space { @@ -1151,13 +1282,19 @@ enum Space { /// change left as stored. LonLat, /// In the layer's own coordinates, as stored: for a change that only reorders vertices (a - /// flip), so a feature with a place that can't be given in longitude/latitude changes too. + /// flip), or one made in the layer's own grid ([`OwnGrid`]), so a feature with a place that + /// can't be given in longitude/latitude changes too. Own, } +/// Applies a geometry change to every selected feature of every layer (in the selection's layers), +/// each layer's geometry given in the [`Space`] `space` gives for its id. In longitude/latitude +/// ([`Space::LonLat`]), a feature with a place that can't be given there is left as it is, and +/// said with a count per layer; when every changeable feature is such a feature, the edit is +/// refused saying why. fn modify_in( s: &mut Session, - space: Space, + space: impl Fn(u32) -> Space, mut change: impl FnMut((u32, usize), &Geometry) -> Result, String>, ) -> CmdResult { let mut n = 0; @@ -1167,7 +1304,7 @@ fn modify_in( let mut changes = Vec::new(); let l = s.map().layer(id).ok_or("no such layer")?; let selection = l.selection.clone(); - let to = match space { + let to = match space(id) { Space::LonLat => Some(l.dataset.shown_conversion()?), Space::Own => None, }; @@ -1772,7 +1909,25 @@ fn traverse(s: &mut Session, p: &Json) -> CmdResult { } let unit = distance_unit_metres(p)?; let g2g = s.map().editing.settings.ground_to_grid; - let mut pts = vec![start]; + let id = s.layer_id(p)?; + let l = s.map().layer(id).ok_or("no such layer")?; + let gt = l.geometry_type(); + // A layer held in a projected system is drawn on its own grid (#2032 C2f-6): the start in its + // coordinates, each leg flat in its unit from its grid north. + let grid = OwnGrid::of(l); + // The start converted, or a stored place that reads exactly as it (a traverse begun at a + // corner), as an added feature keeps it. + let start_own = match grid { + Some(_) => Some(match held_places(s, id, &[], &[&Geometry::Point(start)]).get(start) { + Some(stored) => stored, + None => rustgis_data::raster::Crs::LonLat + .to(l.dataset.coord_crs())? + .point(start) + .ok_or_else(|| format!("the start can't be given in the system '{}' is held in", l.name))?, + }), + None => None, + }; + let mut pts = vec![start_own.unwrap_or(start)]; for leg in legs { let d = leg .get("distance") @@ -1786,11 +1941,26 @@ fn traverse(s: &mut Session, p: &Json) -> CmdResult { (dx, dy) = ground_to_grid(dx, dy, k, rot); } let last = pts.last().copied().unwrap_or(start); - pts.push(shift(last, dx, dy)); + pts.push(match grid { + Some(grid) => { + let d = grid.step(dx, dy); + Coord::new(last.x + d.x, last.y + d.y) + } + None => shift(last, dx, dy), + }); } - let id = s.layer_id(p)?; - let gt = s.map().layer(id).map(|l| l.geometry_type()).ok_or("no such layer")?; // The layer decides: a polygon layer gets a closed traverse, a line layer an open one. + if let Some(first) = start_own { + let g = match gt { + GeometryType::Polygon => { + pts.push(first); + Geometry::Polygon(vec![vec![pts]]) + } + GeometryType::Polyline => Geometry::Line(vec![pts]), + _ => return Err("traverses go into a line or polygon layer".into()), + }; + return super::edit::add_feature_own(s, id, &json!({"layer": id}), g); + } let g = match gt { GeometryType::Polygon => { pts.push(start); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a4110ec14a..c34d95e108 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -143,19 +143,36 @@ pub(crate) fn add_feature(s: &mut Session, p: &Json) -> CmdResult { add_geometry(s, id, p, g) } +/// [`add_feature`] with `g` in layer `id`'s own coordinates, written as it is: for a shape made +/// in its own grid (a traverse, #2032 C2f-6). +pub(crate) fn add_feature_own(s: &mut Session, id: u32, p: &Json, g: Geometry) -> CmdResult { + fits(s, id, &g)?; + insert(s, id, p, g) +} + +/// Refuses `g` where layer `id` can't take it: of another kind, or too few vertices. +fn fits(s: &Session, id: u32, g: &Geometry) -> Result<(), String> { + let want = s.map().layer(id).ok_or("no layer")?.geometry_type(); + if want != g.kind() && want != GeometryType::None { + return Err(format!("{} can't go in a {} layer", g.kind().label(), want.label())); + } + validate(g) +} + /// Inserts an already validated construction through the same attributes, templates and rules. pub(crate) fn add_geometry(s: &mut Session, id: u32, p: &Json, g: Geometry) -> CmdResult { // A place snapped to a stored one stays as stored. let held = super::design::held_places(s, id, &[], &[&g]); - let l = s.map_mut().layer_mut(id).ok_or("no layer")?; - let want = l.geometry_type(); - let ok = want == g.kind() || want == GeometryType::None; - if !ok { - return Err(format!("{} can't go in a {} layer", g.kind().label(), want.label())); - } - validate(&g)?; + fits(s, id, &g)?; // Given in longitude/latitude, written in the layer's own coordinates. - let g = l.dataset.edit_from_lonlat(g, &held)?; + let g = s.map().layer(id).ok_or("no layer")?.dataset.edit_from_lonlat(g, &held)?; + insert(s, id, p, g) +} + +/// Inserts `g`, in layer `id`'s own coordinates, with a feature template's defaults and the given +/// attributes, as one edit. +fn insert(s: &mut Session, id: u32, p: &Json, g: Geometry) -> CmdResult { + let l = s.map_mut().layer_mut(id).ok_or("no layer")?; // A feature template's defaults, then the given attributes. let template = match ps(p, "template") { Some(t) => { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fdddcbb010..99d013055c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8,6 +8,8 @@ mod formats_out; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/held_databases.rs"] mod held_databases; +#[path = "tests/own_grid_edits.rs"] +mod own_grid_edits; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/scene_losses.rs"] mod scene_losses; diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index aef8d1b31e..59dcc7c978 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -321,8 +321,8 @@ fn a_held_layer_is_analysed_alike() { } } -/// A geometry set, a move in metres and an undo leave the same places, and a held layer keeps -/// its system through them. +/// A geometry set and an undo leave the same places, a move in metres steps along the held +/// layer's grid, and a held layer keeps its system through them. #[test] fn a_held_layer_is_edited_alike() { let mut ss = both(); @@ -330,19 +330,15 @@ fn a_held_layer_is_edited_alike() { run_both(&mut ss, "edit.setGeometry", &json!({"layer": "Wells", "row": 0, "geometry": g})); assert_close(&lonlat(&ss[0], "Wells"), &lonlat(&ss[1], "Wells"), "setGeometry"); run_both(&mut ss, "select.rows", &json!({"layer": "Parcels", "rows": [4]})); + let was = stored(&ss[1], "Parcels"); run_both(&mut ss, "edit.move", &json!({"dx": 250.0, "dy": -100.0})); - let [a, b] = [lonlat(&ss[0], "Parcels"), lonlat(&ss[1], "Parcels")]; - // A move in metres on the map: the two agree to well within a centimetre. - assert_eq!(a.len(), b.len(), "move: feature count"); - for (p, q) in a.iter().zip(&b) { - assert_eq!(shape(p), shape(q), "move: shape"); - let (mut ca, mut cb) = (Vec::new(), Vec::new()); - p.as_ref().unwrap().for_each_coord(|c| ca.push(c)); - q.as_ref().unwrap().for_each_coord(|c| cb.push(c)); - for (p, q) in ca.iter().zip(&cb) { - assert!((p.x - q.x).abs() < 1e-7 && (p.y - q.y).abs() < 1e-7, "move: {p:?} vs {q:?}"); - } + // A move in metres goes along the held layer's own grid (#2032 C2f-6): every stored + // coordinate of the moved parcel steps by exactly that, the rest stay as stored. + for (i, (p, q)) in stored(&ss[1], "Parcels").iter().zip(&was).enumerate() { + let want = if i == 4 { q.as_ref().unwrap().map_coords(&|c| Coord::new(c.x + 250.0, c.y - 100.0)) } else { q.clone().unwrap() }; + assert_eq!(p.as_ref(), Some(&want), "move: parcel {i}"); } + assert_eq!(shape(&lonlat(&ss[0], "Parcels")[4]), shape(&lonlat(&ss[1], "Parcels")[4]), "move: shape"); run_both(&mut ss, "edit.undo", &Value::Null); assert_close(&lonlat(&ss[0], "Parcels"), &lonlat(&ss[1], "Parcels"), "undo"); assert_eq!(ss[1].map().layer_by_name("Parcels").unwrap().dataset.coord_crs(), UTM); diff --git a/crates/engine/src/tests/own_grid_edits.rs b/crates/engine/src/tests/own_grid_edits.rs new file mode 100644 index 0000000000..23d5ba4c4a --- /dev/null +++ b/crates/engine/src/tests/own_grid_edits.rs @@ -0,0 +1,277 @@ +//! Move, Rotate, Scale and Traverse on a layer held in a projected system work in its own grid +//! (#2032 C2f-6): distances flat in its unit, directions from its grid north, by its axes. A +//! layer in longitude/latitude, Web Mercator or a world projection is edited as before. + +use crate::{Project, Session}; +use rustgis_data::raster::Crs; +use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value}; +use serde_json::json; + +/// UTM zone 32N, in metres, east then north. +const UTM: Crs = Crs::Epsg(32632); + +/// A square of 0.005° near Ingolstadt (2.5° east of UTM 32N's central meridian, its grid turned +/// some 1.9° from north there) and a line through it, in longitude/latitude. +fn square() -> Geometry { + let (x, y) = (11.5, 48.7); + Geometry::Polygon(vec![vec![vec![ + Coord::new(x, y), + Coord::new(x + 0.005, y), + Coord::new(x + 0.005, y + 0.005), + Coord::new(x, y + 0.005), + Coord::new(x, y), + ]]]) +} + +fn line() -> Geometry { + Geometry::Line(vec![vec![Coord::new(11.49, 48.69), Coord::new(11.515, 48.705), Coord::new(11.53, 48.73)]]) +} + +/// A dataset `name` of `kind` with `geoms` (longitude/latitude) held in `crs`. +fn held(name: &str, kind: GeometryType, geoms: Vec, crs: Crs) -> Dataset { + let mut ds = Dataset::new(name, kind, vec![Field::new("name", FieldType::Text)]); + for (i, g) in geoms.into_iter().enumerate() { + ds.push(Some(g), vec![Value::Text(format!("{name} {i}"))]); + } + ds.hold_in(crs).unwrap(); + ds +} + +/// A session with editing on and `layers` added. +fn session(layers: Vec) -> Session { + let mut s = Session::new(Project::default()); + for ds in layers { + crate::cmd::layer::add_dataset(&mut s, ds); + } + s.map_mut().editing.settings.enabled = true; + s +} + +fn select_all(s: &mut Session) { + for l in &mut s.map_mut().layers { + l.selection = (0..l.dataset.features.len()).collect(); + } +} + +/// Every vertex of layer `name`, as it holds them. +fn stored(s: &Session, name: &str) -> Vec { + let mut out = Vec::new(); + for f in &s.map().layer_by_name(name).unwrap().dataset.features { + if let Some(g) = &f.geometry { + g.for_each_coord(|c| out.push(c)); + } + } + out +} + +/// What `cmd` with `p` said. +fn run(s: &mut Session, cmd: &str, p: serde_json::Value) -> Vec { + let mark = s.notice_mark(); + s.run(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")); + s.notices_since(mark).iter().map(|n| n.text.clone()).collect() +} + +/// A move adds the distance to every stored coordinate, exactly as a step on the grid, in the +/// layers of one projected system. +#[test] +fn a_move_steps_along_the_layers_own_grid() { + let mut s = session(vec![ + held("Parcels", GeometryType::Polygon, vec![square()], UTM), + held("Roads", GeometryType::Polyline, vec![line()], UTM), + ]); + let (before, roads) = (stored(&s, "Parcels"), stored(&s, "Roads")); + select_all(&mut s); + let said = run(&mut s, "edit.move", json!({"dx": 250.0, "dy": -100.0})); + assert!(said.iter().all(|t| !t.contains("more than one coordinate system")), "{said:?}"); + let after = stored(&s, "Parcels"); + assert_eq!(after, before.iter().map(|c| Coord::new(c.x + 250.0, c.y - 100.0)).collect::>()); + assert_eq!(stored(&s, "Roads"), roads.iter().map(|c| Coord::new(c.x + 250.0, c.y - 100.0)).collect::>()); + for l in &mut s.map_mut().layers { + l.selection = if l.name == "Parcels" { vec![0] } else { Vec::new() }; + } + // In feet, the same step in metres. + run(&mut s, "edit.move", json!({"dx": 1000.0, "dy": 0.0, "units": "Feet"})); + let feet = stored(&s, "Parcels"); + for (a, b) in feet.iter().zip(&after) { + assert!((a.x - b.x - 304.8).abs() < 1e-9 && a.y == b.y, "{a:?} vs {b:?}"); + } + // Ground to grid scales and turns the step before it is taken. + run(&mut s, "edit.groundToGrid", json!({"scale": 0.9996, "rotation": 90.0})); + run(&mut s, "edit.move", json!({"dx": 0.0, "dy": 1000.0})); + for (a, b) in stored(&s, "Parcels").iter().zip(&feet) { + assert!((a.x - b.x - 999.6).abs() < 1e-6 && (a.y - b.y).abs() < 1e-6, "{a:?} vs {b:?}"); + } + // Undo, step by step (Ground To Grid is one too), puts it back as stored, to the bit. + for _ in 0..8 { + if stored(&s, "Parcels") == before || s.run("edit.undo", &json!(null)).is_err() { + break; + } + } + assert_eq!(stored(&s, "Parcels"), before, "undo puts it back as stored, to the bit"); + // A move of no distance on that layer alone changes nothing, as before. + for l in &mut s.map_mut().layers { + l.selection = if l.name == "Parcels" { vec![0] } else { Vec::new() }; + } + let e = s.run("edit.move", &json!({"dx": 0.0, "dy": 0.0})).unwrap_err(); + assert!(e.contains("no distance"), "{e}"); +} + +/// In a system in US survey feet, a move in metres goes as many of its feet; in one whose axes +/// point west and south, east is the way x falls. +#[test] +fn a_move_follows_the_systems_unit_and_axes() { + // NAD83 / New York Long Island (ftUS), near New York. + let ny = held("Lots", GeometryType::Polygon, vec![square_at(-73.9, 40.75)], Crs::Epsg(2263)); + // Hartebeesthoek94 / Lo29, x west and y south, near Johannesburg. + let lo = held("Erven", GeometryType::Polygon, vec![square_at(28.5, -26.2)], Crs::Epsg(2053)); + assert_eq!(lo.coord_crs().axis_directions(), [(-1.0, 0.0), (0.0, -1.0)], "Lo29 points west and south"); + let mut s = session(vec![ny, lo]); + let (ny0, lo0) = (stored(&s, "Lots"), stored(&s, "Erven")); + // One layer at a time: two systems at once move together in Web Mercator. + for name in ["Lots", "Erven"] { + for l in &mut s.map_mut().layers { + l.selection = if l.name == name { vec![0] } else { Vec::new() }; + } + run(&mut s, "edit.move", json!({"dx": 100.0, "dy": 50.0})); + } + let ft = 1200.0 / 3937.0; + for (a, b) in stored(&s, "Lots").iter().zip(&ny0) { + assert!((a.x - b.x - 100.0 / ft).abs() < 1e-6 && (a.y - b.y - 50.0 / ft).abs() < 1e-6, "{a:?} vs {b:?}"); + } + for (a, b) in stored(&s, "Erven").iter().zip(&lo0) { + assert!((a.x - b.x + 100.0).abs() < 1e-9 && (a.y - b.y + 50.0).abs() < 1e-9, "{a:?} vs {b:?}"); + } +} + +fn square_at(x: f64, y: f64) -> Geometry { + Geometry::Polygon(vec![vec![vec![ + Coord::new(x, y), + Coord::new(x + 0.002, y), + Coord::new(x + 0.002, y + 0.002), + Coord::new(x, y + 0.002), + Coord::new(x, y), + ]]]) +} + +/// Rotate turns clockwise with grid north up, and Scale scales, about the middle of the feature's +/// extent in its own coordinates; with the axes swapped (north first), clockwise still turns +/// north to east. +#[test] +fn rotate_and_scale_work_about_the_middle_of_the_own_extent() { + let mut s = session(vec![held("Roads", GeometryType::Polyline, vec![line()], UTM)]); + let before = stored(&s, "Roads"); + let mid = extent_middle(&before); + select_all(&mut s); + run(&mut s, "edit.rotate", json!({"angle": 90.0})); + for (a, b) in stored(&s, "Roads").iter().zip(&before) { + // North of the middle turns east: (e, n) → (n, −e). + let want = Coord::new(mid.x + (b.y - mid.y), mid.y - (b.x - mid.x)); + assert!((a.x - want.x).abs() < 1e-6 && (a.y - want.y).abs() < 1e-6, "{a:?} vs {want:?}"); + } + run(&mut s, "edit.undo", json!(null)); + run(&mut s, "edit.scale", json!({"factor": 2.0})); + for (a, b) in stored(&s, "Roads").iter().zip(&before) { + let want = Coord::new(mid.x + (b.x - mid.x) * 2.0, mid.y + (b.y - mid.y) * 2.0); + assert!((a.x - want.x).abs() < 1e-6 && (a.y - want.y).abs() < 1e-6, "{a:?} vs {want:?}"); + } + // UTM 32N with north first: x north, y east. + let neu = Crs::parse("+proj=utm +zone=32 +datum=WGS84 +units=m +axis=neu +no_defs").unwrap(); + assert_eq!(neu.axis_directions(), [(0.0, 1.0), (1.0, 0.0)]); + let mut s = session(vec![held("Roads", GeometryType::Polyline, vec![line()], neu)]); + let before = stored(&s, "Roads"); + let mid = extent_middle(&before); + select_all(&mut s); + run(&mut s, "edit.rotate", json!({"angle": 90.0})); + for (a, b) in stored(&s, "Roads").iter().zip(&before) { + // x is north, y east: (n, e) → (−e, n). + let want = Coord::new(mid.x - (b.y - mid.y), mid.y + (b.x - mid.x)); + assert!((a.x - want.x).abs() < 1e-6 && (a.y - want.y).abs() < 1e-6, "{a:?} vs {want:?}"); + } +} + +fn extent_middle(cs: &[Coord]) -> Coord { + let (mut lo, mut hi) = (Coord::new(f64::INFINITY, f64::INFINITY), Coord::new(f64::NEG_INFINITY, f64::NEG_INFINITY)); + for c in cs { + lo = Coord::new(lo.x.min(c.x), lo.y.min(c.y)); + hi = Coord::new(hi.x.max(c.x), hi.y.max(c.y)); + } + Coord::new((lo.x + hi.x) / 2.0, (lo.y + hi.y) / 2.0) +} + +/// A feature of a projected layer with a place that can't be given in longitude/latitude moves +/// with the rest, since nothing is converted; no notice counts it. +#[test] +fn a_feature_with_no_lonlat_place_moves_on_the_grid() { + let mut ds = held("Roads", GeometryType::Polyline, vec![line()], UTM); + let far = Coord::new(1e12, 1e12); + assert_eq!(ds.lonlat_conversion().unwrap().point(far), None, "the far place truly has none in longitude/latitude"); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(700_000.0, 5_400_000.0), far]])), vec![Value::Text("far".into())]); + let mut s = session(vec![ds]); + select_all(&mut s); + let said = run(&mut s, "edit.move", json!({"dx": 10.0, "dy": 0.0})); + assert!(said.iter().all(|t| !t.contains("can't be given")), "{said:?}"); + assert_eq!(stored(&s, "Roads").last().copied(), Some(Coord::new(1e12 + 10.0, 1e12))); +} + +/// A traverse into a projected layer starts at the given longitude/latitude converted into its +/// system, and steps each leg on its grid: a closed polygon of exact metres. +#[test] +fn a_traverse_is_drawn_on_the_layers_grid() { + let mut s = session(vec![held("Lots", GeometryType::Polygon, vec![square()], UTM)]); + let start = Crs::LonLat.to(UTM).unwrap().point(Coord::new(11.6, 48.8)).unwrap(); + let r = s + .run( + "edit.traverse", + &json!({"layer": "Lots", "start": [11.6, 48.8], "legs": [{"distance": 100, "bearing": 90}, {"distance": 50, "bearing": 0}, {"distance": 100, "bearing": 270}]}), + ) + .unwrap(); + let row = r["row"].as_u64().unwrap() as usize; + let Some(Geometry::Polygon(p)) = s.map().layer_by_name("Lots").unwrap().dataset.features[row].geometry.clone() else { + panic!("a polygon") + }; + let want = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0), (0.0, 0.0)]; + assert_eq!(p[0][0].len(), want.len()); + for (c, (dx, dy)) in p[0][0].iter().zip(want) { + assert!((c.x - start.x - dx).abs() < 1e-6 && (c.y - start.y - dy).abs() < 1e-6, "{c:?}"); + } + assert_eq!(p[0][0].first(), p[0][0].last(), "closed on its start, to the bit"); +} + +/// A selection spanning a projected layer and one in longitude/latitude moves both in Web +/// Mercator, as before, so a corner they share stays together, and says why. +#[test] +fn a_selection_across_systems_moves_together_as_before() { + let corner = Geometry::Line(vec![vec![Coord::new(11.5, 48.7), Coord::new(11.52, 48.71)]]); + let mut s = session(vec![ + held("Parcels", GeometryType::Polygon, vec![square()], UTM), + held("Roads", GeometryType::Polyline, vec![corner.clone()], Crs::LonLat), + ]); + select_all(&mut s); + let said = run(&mut s, "edit.move", json!({"dx": 250.0, "dy": -100.0})); + assert!(said.iter().any(|t| t.contains("more than one coordinate system") && t.contains("'Parcels'")), "{said:?}"); + let parcel = s.map().layer_by_name("Parcels").unwrap().dataset.lonlat_conversion().unwrap().point(stored(&s, "Parcels")[0]).unwrap(); + let road = stored(&s, "Roads")[0]; + assert!((parcel.x - road.x).abs() < 1e-8 && (parcel.y - road.y).abs() < 1e-8, "{parcel:?} vs {road:?}"); +} + +/// A traverse begun at a stored corner, given as that corner reads in longitude/latitude, starts +/// on the corner as stored, to the bit, as an added feature does. +#[test] +fn a_traverse_from_a_corner_starts_on_it_as_stored() { + let mut s = session(vec![held("Lots", GeometryType::Polygon, vec![square()], UTM)]); + let corner = stored(&s, "Lots")[1]; + let lonlat = s.map().layer_by_name("Lots").unwrap().dataset.lonlat_conversion().unwrap().point(corner).unwrap(); + let r = s + .run( + "edit.traverse", + &json!({"layer": "Lots", "start": [lonlat.x, lonlat.y], "legs": [{"distance": 100, "bearing": 90}, {"distance": 50, "bearing": 0}]}), + ) + .unwrap(); + let Some(Geometry::Polygon(p)) = + s.map().layer_by_name("Lots").unwrap().dataset.features[r["row"].as_u64().unwrap() as usize].geometry.clone() + else { + panic!("a polygon") + }; + assert_eq!(p[0][0][0], corner); + assert_eq!(p[0][0][1], Coord::new(corner.x + 100.0, corner.y)); +} diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 79261e3fea..38749658de 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -68,8 +68,20 @@ you edit the value or choose units; click **Apply elevation** to apply the new i and flip line direction. A single point turns and scales on itself, so Rotate and Scale leave points (text graphics included) as they are: with only points selected they change nothing, say so, and add no undo step. Edit › Tools lists every editing tool. + In a layer held in a projected system (UTM, a national grid; not Web Mercator, another world + projection or a geographic system), Move, Rotate and Scale work in the layer's own coordinates, + as the analysis tools do: Move steps the distances east and north along its grid, measured flat + in its unit (so in UTM a kilometre on the grid is between about 0.999 and 1.0004 km on the + ground, and its north is grid north; Ground to grid below corrects ground distances and + directions to it), following the system's axes when they point west, south or north first; Rotate turns clockwise + with grid north up, and Scale scales, about the middle of the feature's extent there. A Move + whose selection spans layers in more than one system (or some in one and some in + longitude/latitude; graphics don't count) moves them all as below, so places they share stay + together, and says so. The rest of this paragraph, about Web Mercator and the ground, is for + the other layers. A selected feature with a place that can't be given in longitude/latitude (one far past where - its layer's own system reaches) is left as it is by Move, Rotate, Scale, Split and Cut Polygon, + its layer's own system reaches) is left as it is by Move, Rotate and Scale (except in a layer + edited in its own grid, where it changes with the rest), Split and Cut Polygon, and a notice counts them by layer; Flip Line flips it in the layer's own coordinates. An edit of that one feature (a vertex, Reshape, Trace, Merge with it, a shape conversion) is refused, naming the layer and the feature; Set Geometry gives it a new shape, and Delete removes it. @@ -159,7 +171,10 @@ you edit the value or choose units; click **Apply elevation** to apply the new i between the two systems; this is not a change to its geometry's coordinates. An edit whose label point the surface's system can't give is refused. - **Ground to grid**: a scale factor and rotation applied to entered distances and directions - (Move, and `edit.traverse`, which draws a line or polygon from distances and bearings). + (Move, and `edit.traverse`, which draws a line or polygon from distances and bearings). Into a + layer held in a projected system, a traverse starts at the given longitude/latitude converted + into that system and steps each leg on its grid, flat in its unit from grid north, as Move does; + into any other layer, each leg goes east and north in Web Mercator stretched to the latitude. - **Topology**: rules (must not overlap, must not have gaps, must not self-intersect, must not have dangles, must be covered by); Validate lists the errors, and clicking one zooms to it. Primary rows follow the layer's definition query, independently of selection, time windows diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 82e07640ac..cf26786c5c 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 778 +count = 769