diff --git a/crates/analysis/src/sketch_edit.rs b/crates/analysis/src/sketch_edit.rs index 65bcdbac09..7fa49f26a7 100644 --- a/crates/analysis/src/sketch_edit.rs +++ b/crates/analysis/src/sketch_edit.rs @@ -1,6 +1,10 @@ //! Editing a feature with a drawn line: cutting polygons in pieces, reshaping a boundary or a //! line, and tracing along a feature's edge. Computed in Web Mercator metres, as the other -//! editing tools are; vertices an edit doesn't move keep their exact longitude and latitude. +//! editing tools are; vertices an edit doesn't move keep their exact longitude and latitude. In a +//! run in a projected system's own plane ([`crate::convert::Plane::Own`], #2032 C2f-7) the +//! geometry and the line are in that system's coordinates, and the work is in its own plane, in +//! metres east and north of its grid: a cut or a reshape meets the layer's segments where they +//! run straight, in the layer's own coordinates. use std::collections::HashMap; @@ -24,7 +28,36 @@ fn within_work(a: usize, b: usize) -> Result<(), String> { /// Why an edit past [`MAX_WORK`] is refused. const TOO_MUCH: &str = "the shapes and the line have too many vertices to edit together"; -/// A point in Web Mercator metres and the longitude/latitude it came from. +/// Whether the run is in a projected system's own plane, rather than in longitude/latitude. +fn own() -> bool { + crate::convert::plane() == crate::convert::Plane::Own +} + +/// A place in the plane the work is in, in metres: Web Mercator's for longitude/latitude; east and +/// north of a projected system's grid, by the order and direction of its axes, in its own plane. +fn to_m(c: Coord) -> Coord { + if !own() { + return lonlat_to_merc(c); + } + let u = crate::convert::run_plane().unit_m; + let (e, n) = crate::convert::own_east_north(c.x, c.y); + Coord::new(e * u, n * u) +} + +/// [`to_m`] undone. +fn from_m(m: Coord) -> Coord { + if !own() { + return merc_to_lonlat(m); + } + let r = crate::convert::run_plane(); + let [(xe, xn), (ye, yn)] = r.axes; + let (e, n) = (m.x / r.unit_m, m.y / r.unit_m); + let det = xe * yn - ye * xn; + Coord::new((e * yn - n * ye) / det, (xe * n - xn * e) / det) +} + +/// A point in metres ([`to_m`]) and the coordinates it came from: longitude/latitude, or a +/// projected system's own in its plane. #[derive(Clone, Copy, Debug)] struct Pt { m: Coord, @@ -32,13 +65,13 @@ struct Pt { } impl Pt { - /// An input vertex: its longitude/latitude kept as given. + /// An input vertex: its coordinates kept as given. fn of(ll: Coord) -> Pt { - Pt { m: lonlat_to_merc(ll), ll } + Pt { m: to_m(ll), ll } } /// A new point worked out in metres. fn at(m: Coord) -> Pt { - Pt { m, ll: merc_to_lonlat(m) } + Pt { m, ll: from_m(m) } } } @@ -47,12 +80,13 @@ fn dist(a: Coord, b: Coord) -> f64 { (a.x - b.x).hypot(a.y - b.y) } -/// The input as metres, refusing coordinates that don't project (a pole, NaN). -/// Longitudes beyond ±360° (as `edit.vertex` takes, for features unwrapped across the -/// antimeridian) aren't coordinates on the Earth. +/// The input as metres ([`to_m`]), refusing coordinates that don't project (a pole, NaN). In +/// longitude/latitude, longitudes beyond ±360° (as `edit.vertex` takes, for features unwrapped +/// across the antimeridian) aren't coordinates on the Earth; in a projected system's own plane +/// any finite coordinate is one. fn project(path: &[Coord]) -> Result, String> { let pts: Vec = path.iter().map(|c| Pt::of(*c)).collect(); - if pts.iter().all(|p| p.m.is_finite() && p.ll.x.abs() <= 360.0 && p.ll.y.abs() <= 90.0) { + if pts.iter().all(|p| p.m.is_finite() && (own() || (p.ll.x.abs() <= 360.0 && p.ll.y.abs() <= 90.0))) { Ok(pts) } else { Err("the shape has coordinates that can't be drawn on the map".into()) @@ -76,7 +110,7 @@ fn area2(ring: &[Pt]) -> f64 { ring.windows(2).filter_map(|w| Some((w.first()?.m, w.get(1)?.m))).map(|(a, b)| a.x * b.y - b.x * a.y).sum() } -/// [`area2`] of a ring in longitude/latitude. +/// [`area2`] of a ring in its coordinates (longitude/latitude, or a projected system's own). fn area2_ll(ring: &[Coord]) -> f64 { area2(&ring.iter().map(|c| Pt::of(*c)).collect::>()) } @@ -445,7 +479,7 @@ fn valid(rings: &[Vec]) -> bool { /// A polygon (outer ring, then holes) as a `geo` polygon in metres. fn geo_polygon(rings: &[Vec]) -> Option> { - let ring = |r: &Vec| geo::LineString::new(r.iter().map(|c| lonlat_to_merc(*c)).map(|m| geo::coord! {x: m.x, y: m.y}).collect()); + let ring = |r: &Vec| geo::LineString::new(r.iter().map(|c| to_m(*c)).map(|m| geo::coord! {x: m.x, y: m.y}).collect()); let mut it = rings.iter(); let outer = it.next()?; Some(geo::Polygon::new(ring(outer), it.map(ring).collect())) @@ -799,7 +833,8 @@ pub struct Reshaped { } /// A path traced along a feature's edge, and how far (Web Mercator metres, which exceed ground -/// metres by 1/cos(latitude)) its ends were from the points asked for. +/// metres by 1/cos(latitude); in a projected system's own plane, metres of its grid) its ends were +/// from the points asked for. #[derive(Clone, Debug, PartialEq)] pub struct Traced { pub path: Vec, @@ -825,7 +860,7 @@ fn nearest(path: &[Pt], c: Coord) -> Option<(f64, f64, Coord)> { /// `part`, when given, is the line part or polygon ring to follow (polygons' rings numbered in /// order, holes after their outer ring), as already chosen on the map. pub fn trace(g: &Geometry, from: Coord, to: Coord, part: Option) -> Result { - let (f, t) = (lonlat_to_merc(from), lonlat_to_merc(to)); + let (f, t) = (to_m(from), to_m(to)); let closed = matches!(g, Geometry::Polygon(_)); if !matches!(g, Geometry::Line(_) | Geometry::Polygon(_)) { return Err("only lines and polygons can be traced".into()); diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index ee82817cd1..507f55473c 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -681,7 +681,7 @@ pub fn commands() -> Vec { .when(need_editable_selection) .params(r#"{"line": GeoJSON LineString (lon/lat) drawn across the selected line or polygon's boundary}"#), C::new("edit.trace", "Trace Edge Path", "Edit › Features", sketch::trace).roles(&[]).effects(crate::policy::Effects::NONE).view().params( - r#"{"from": [lon, lat], "to": [lon, lat], "layer"?, "row"?: number (else the nearest edge within the tolerance), "tolerancePx"?: number (default: the snapping tolerance)}"#, + r#"{"from": [lon, lat], "to": [lon, lat], "layer"?, "row"?: number (else the nearest edge within the tolerance), "tolerancePx"?: number (default: the snapping tolerance)} (fromOffM and toOffM in Web Mercator metres, or metres of the grid of a layer held in a projected system)"#, ), C::new("edit.traverse", "Traverse", "Edit › Features › Modify", traverse).roles(&[]).effects(crate::policy::Effects::NONE).when(need_editable).params( r#"{"layer"?, "start": [lon, lat], "units"?: "Meters" (default)|"Feet"|"Kilometers"|"Miles", "legs": [{"distance": number, "bearing": degrees from north}]} (closed in a polygon layer, open in a line layer)"#, @@ -750,18 +750,18 @@ fn distance_unit_metres(p: &Json) -> Result { /// 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 { +pub(super) struct OwnGrid { /// The system. - crs: rustgis_data::raster::Crs, + pub(super) crs: rustgis_data::raster::Crs, /// Metres per unit of its coordinates. - unit_m: f64, + pub(super) 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 { + pub(super) 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) { @@ -1479,7 +1479,9 @@ pub(crate) fn held_places(s: &Session, id: u32, originals: &[&Geometry], edited: // Only what an edited place still lacks is held from here on. held.want_only(edited); let system = l.dataset.coord_crs(); - let Ok(to_own) = rustgis_data::raster::Crs::LonLat.to(system) else { return held }; + // Through the map's system when the layer is shown through it: the route its stored places + // are read by, so a place snapped to one lands within the box looked in. + let Ok(to_own) = l.dataset.shown_from_lonlat() else { return held }; // The places not held yet, each in the layer's coordinates, and the box they are in there, // padded by what a round trip moves a place: a stored place reading as one lies within it. let mut within = rustgis_geom::Extent::EMPTY; @@ -1509,6 +1511,23 @@ pub(crate) fn held_places(s: &Session, id: u32, originals: &[&Geometry], edited: held } +/// A line drawn on the map, in longitude/latitude, in the coordinates of layer `id`, held in a +/// projected system, for an edit worked out there (#2032 C2f-7): a point snapped to a stored place +/// of a layer in that system is that place, as stored ([`held_places`]); any other is converted +/// as the layer is drawn ([`rustgis_data::Dataset::shown_from_lonlat`]). +pub(super) fn line_in_own(s: &Session, id: u32, line: &[Coord]) -> Result, String> { + let held = held_places(s, id, &[], &[&Geometry::Line(vec![line.to_vec()])]); + // Through the map's system when the layer is shown through it, as its features are drawn. + let to = s.map().layer(id).ok_or("no such layer")?.dataset.shown_from_lonlat()?; + line.iter() + .map(|c| { + held.get(*c) + .or_else(|| to.point(*c)) + .ok_or_else(|| "a point of the line is no place in the layer's coordinate system".to_string()) + }) + .collect() +} + /// How far a round trip through longitude/latitude may move place `c`, in its own units, with /// room to spare: a millionth of its size. fn round_trip_reach(c: Coord) -> f64 { @@ -1565,15 +1584,20 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { if sel.len() < 2 { return Err("select two or more features to merge".into()); } - // Merged in longitude/latitude, from the layer's own coordinates, and written back in them, the - // places it keeps as stored. - // A feature with a place that can't be given there refuses the merge, naming it: the merged - // shape would lose that place. + // Held in a projected system, merged in its own coordinates, as they are: the shapes are + // unioned where their segments run straight there (#2032 C2f-7), and nothing is converted. + // Otherwise merged in longitude/latitude, from the layer's own coordinates, and written back + // in them, the places it keeps as stored; a feature with a place that can't be given there + // refuses the merge, naming it: the merged shape would lose that place. + let own = OwnGrid::of(l).is_some(); let with_ids: Vec<(u64, &Geometry)> = sel.iter().filter_map(|r| l.dataset.features.row(*r)).filter_map(|f| Some((f.id(), f.geometry()?))).collect(); let originals: Vec<&Geometry> = with_ids.iter().map(|(_, g)| *g).collect(); - let geoms: Vec = - with_ids.iter().map(|(fid, g)| l.dataset.feature_to_lonlat(*fid, g).map(std::borrow::Cow::into_owned)).collect::>()?; + let geoms: Vec = if own { + originals.iter().map(|g| (*g).clone()).collect() + } else { + with_ids.iter().map(|(fid, g)| l.dataset.feature_to_lonlat(*fid, g).map(std::borrow::Cow::into_owned)).collect::>()? + }; let kind = |g: &Geometry| match g { Geometry::Point(_) | Geometry::MultiPoint(_) => 0, Geometry::Line(_) => 1, @@ -1582,12 +1606,19 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { if geoms.len() != sel.len() || geoms.windows(2).any(|w| w.first().map(kind) != w.get(1).map(kind)) { return Err("merge features of one kind (all points, all lines or all polygons), each with a shape".into()); } - let merged = rustgis_analysis::topology::merge(&geoms).ok_or("these features can't be merged")?; - let mut held = rustgis_data::HeldPlaces::default(); - for g in &originals { - l.dataset.hold_places(g, None, &mut held); - } - let merged = l.dataset.edit_from_lonlat(merged, &held)?; + let merged = { + let _plane = own.then(|| rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(l.dataset.coord_crs()))); + rustgis_analysis::topology::merge(&geoms).ok_or("these features can't be merged")? + }; + let merged = if own { + merged + } else { + let mut held = rustgis_data::HeldPlaces::default(); + for g in &originals { + l.dataset.hold_places(g, None, &mut held); + } + l.dataset.edit_from_lonlat(merged, &held)? + }; let keep = sel.first().copied().ok_or("nothing selected")?; let mut changes = Vec::new(); for r in sel.iter().skip(1).rev() { @@ -1648,6 +1679,9 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { return Err("lon and lat are degrees".into()); } let id = selection_layer(s)?; + if let Some(grid) = s.map().layer(id).and_then(OwnGrid::of) { + return split_own(s, id, grid, at); + } let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; // A vertex past ±90° is no place: the search would take it for the pole, so the lines are // refused up front, before any is split. @@ -1829,6 +1863,84 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { Ok(json!({"split": true})) } +/// [`split`] of the selected lines of layer `id`, held in `grid`'s projected system, in its own +/// coordinates (#2032 C2f-7): at the point nearest `at` (longitude/latitude) on its segments as they run straight there, measured flat in its +/// grid. Every place of the line stays as stored; only the point it is split at is new. +fn split_own(s: &mut Session, id: u32, grid: OwnGrid, at: Coord) -> CmdResult { + // Converted as the layer is drawn; the split point is projected onto a segment anyway, so + // stored places aren't looked up for it. + let to_own = s.map().layer(id).ok_or("no such layer")?.dataset.shown_from_lonlat()?; + let at = to_own.point(at).ok_or("the point to split at is no place in the layer's coordinate system")?; + // A millimetre and a centimetre of the grid, in its units. + let (mm, cm) = (0.001 / grid.unit_m, 0.01 / grid.unit_m); + let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; + let (mut changes, mut unmeasured) = (Vec::new(), 0usize); + for r in l.selection.clone() { + let Some(Geometry::Line(parts)) = l.dataset.features.geometry(r) else { continue }; + let parts = parts.clone(); + let mut best: Option<(f64, usize, usize, Coord)> = None; + for (pi, part) in parts.iter().enumerate() { + for (si, w) in part.windows(2).enumerate() { + let (a, b) = (w[0], w[1]); + if !(a.is_finite() && b.is_finite()) { + unmeasured += 1; + continue; + } + let (dx, dy) = (b.x - a.x, b.y - a.y); + let len2 = dx * dx + dy * dy; + let t = if len2 > 0.0 { (((at.x - a.x) * dx + (at.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; + let q = Coord::new(a.x + t * dx, a.y + t * dy); + let d = (q.x - at.x).hypot(q.y - at.y); + // A segment too long to measure (its distance not a number) is passed over. + if !d.is_finite() { + unmeasured += 1; + } else if best.is_none_or(|b| d < b.0) { + best = Some((d, pi, si, q)); + } + } + } + let Some((_, pi, si, q)) = best else { continue }; + let Some(part) = parts.get(pi) else { continue }; + let apart = |a: &Coord, b: Coord| (a.x - b.x).hypot(a.y - b.y); + // At a vertex (to within a millimetre), the parts meet there, without it repeated. + let q = [part.get(si), part.get(si + 1)].into_iter().flatten().find(|v| apart(v, q) < mm).copied().unwrap_or(q); + let mut first: Vec = part.iter().take(si + 1).copied().collect(); + if first.last() != Some(&q) { + first.push(q); + } + let mut second = vec![q]; + second.extend(part.iter().skip(si + 1).copied().skip_while(|c| *c == q)); + // At (or within a centimetre of) the line's ends isn't a split. + let near = |a: Option<&Coord>| a.is_some_and(|a| apart(a, q) < cm); + if first.len() < 2 || second.len() < 2 || near(first.first()) || near(second.last()) { + continue; + } + let mut a_parts: Vec> = parts.iter().take(pi).cloned().collect(); + a_parts.push(first); + let mut b_parts = vec![second]; + b_parts.extend(parts.iter().skip(pi + 1).cloned()); + let Some(f) = l.dataset.features.get(r).cloned() else { continue }; + l.dataset.features.set_geometry(r, Some(Geometry::Line(a_parts))); + l.dataset.push(Some(Geometry::Line(b_parts)), f.attrs.clone()); + changes.push(Change { before: Some(f), row: Some(r) }); + changes.push(Change { before: None, row: Some(l.dataset.features.len() - 1) }); + } + if changes.is_empty() { + if unmeasured > 0 { + return Err(format!( + "no line could be split away from its ends; {unmeasured} segment(s) could not be measured because of invalid coordinates" + )); + } + return Err("select a line to split (away from its ends)".into()); + } + l.touch_geometry(); + apply(s, id, changes)?; + if unmeasured > 0 { + s.warn(format!("{unmeasured} segment(s) of the selected lines could not be measured because of invalid coordinates; the split search skipped them, so the point found may not be the nearest")); + } + Ok(json!({"split": true})) +} + /// How many ground distances one split may work out along segments (a million, as its notices /// say); past them, a segment counts as near as the nearest point found on it so far, its nearer /// end at first. diff --git a/crates/engine/src/cmd/design/sketch.rs b/crates/engine/src/cmd/design/sketch.rs index 98fcfd52ae..0cf8281ca4 100644 --- a/crates/engine/src/cmd/design/sketch.rs +++ b/crates/engine/src/cmd/design/sketch.rs @@ -48,16 +48,48 @@ fn point(p: &Value, key: &str) -> Result { pub(super) fn cut_polygon(s: &mut Session, p: &Value) -> CmdResult { let line = line(p)?; let id = selection_layer(s)?; + // A layer held in a projected system is cut in its own plane, the line converted into it: + // the pieces meet its segments where they run straight, and only the points the cut makes + // are new (#2032 C2f-7). + let own = s.map().layer(id).and_then(super::OwnGrid::of); + if let Some(grid) = own { + let line = super::line_in_own(s, id, &line)?; + return cut_polygon_with(s, id, &line, Some(grid)); + } + cut_polygon_with(s, id, &line, None) +} + +/// [`cut_polygon`] with `line` in longitude/latitude, or, given the layer's `own` grid, in its +/// own coordinates, cut in its plane. +fn cut_polygon_with(s: &mut Session, id: u32, line: &[Coord], own: Option) -> CmdResult { let l = s.map().layer(id).ok_or("no such layer")?; let mut cut_up = Vec::new(); let (mut missed, mut work, mut unplaced) = (0, 0, 0); - let to = l.dataset.shown_conversion()?; + // Only a cut in longitude/latitude converts the polygons. + let to = if own.is_none() { Some(l.dataset.shown_conversion()?) } else { None }; for &r in &l.selection { let Some(f) = l.dataset.features.get(r) else { continue }; + if let Some(grid) = own { + // The plane is the layer's only while the cut is worked out. + let cut = { + let _plane = rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(grid.crs)); + l.dataset.features.geometry(r).map(|g| sketch_edit::cut_polygon(g, line, &mut work)).transpose()?.flatten() + }; + match cut { + Some(pieces) => { + for g in &pieces { + super::super::edit::validate(g)?; + } + cut_up.push((r, f, pieces)); + } + None => missed += 1, + } + continue; + } // Cut in longitude/latitude, from the layer's own coordinates; the pieces go back in them. // A polygon with a place that can't be given there isn't cut; it is counted and said. let lonlat = match f.geometry.as_ref() { - Some(g) => match rustgis_data::Dataset::converted_to_lonlat(&to, g) { + Some(g) => match to.as_ref().and_then(|to| rustgis_data::Dataset::converted_to_lonlat(to, g)) { Some(g) => Some(g), None => { unplaced += 1; @@ -66,7 +98,7 @@ pub(super) fn cut_polygon(s: &mut Session, p: &Value) -> CmdResult { }, None => None, }; - match lonlat.map(|g| sketch_edit::cut_polygon(&g, &line, &mut work)).transpose()?.flatten() { + match lonlat.map(|g| sketch_edit::cut_polygon(&g, line, &mut work)).transpose()?.flatten() { Some(pieces) => { for g in &pieces { super::super::edit::validate(g)?; @@ -78,12 +110,17 @@ pub(super) fn cut_polygon(s: &mut Session, p: &Value) -> CmdResult { } // The polygons' places, and the line's where it was snapped to one, stay as stored: looked for // once for every piece. - let originals: Vec<&Geometry> = cut_up.iter().filter_map(|(_, f, _)| f.geometry.as_ref()).collect(); - let held = super::held_places(s, id, &originals, &cut_up.iter().flat_map(|(_, _, pieces)| pieces).collect::>()); + // Worked out in the layer's own coordinates, the pieces are written as they are. let mut cuts = Vec::new(); - for (r, f, pieces) in cut_up { - let pieces = pieces.into_iter().map(|g| l.dataset.edit_from_lonlat(g, &held)).collect::, _>>()?; - cuts.push((r, f.clone(), pieces)); + if own.is_some() { + cuts = cut_up.into_iter().map(|(r, f, pieces)| (r, f.clone(), pieces)).collect(); + } else { + let originals: Vec<&Geometry> = cut_up.iter().filter_map(|(_, f, _)| f.geometry.as_ref()).collect(); + let held = super::held_places(s, id, &originals, &cut_up.iter().flat_map(|(_, _, pieces)| pieces).collect::>()); + for (r, f, pieces) in cut_up { + let pieces = pieces.into_iter().map(|g| l.dataset.edit_from_lonlat(g, &held)).collect::, _>>()?; + cuts.push((r, f.clone(), pieces)); + } } let unplaced_said = (unplaced > 0).then(|| super::unplaced_said(&[(l.name.clone(), unplaced)])); if cuts.is_empty() { @@ -131,21 +168,34 @@ pub(super) fn reshape(s: &mut Session, p: &Value) -> CmdResult { let [r] = l.selection.as_slice() else { return Err("select one feature to reshape".into()) }; let r = *r; let f = l.dataset.features.get(r).cloned().ok_or("no such row")?; - // Reshaped in longitude/latitude, from the layer's own coordinates, and written back in them, - // what the line left (or snapped to) as stored. let own = f.geometry.as_ref().ok_or("the feature has no shape")?; - let lonlat = l.dataset.feature_to_lonlat(f.id, own)?; - let done = sketch_edit::reshape(&lonlat, &line)?; - super::super::edit::validate(&done.geometry)?; - let held = super::held_places(s, id, &[own], &[&done.geometry]); - let reshaped = l.dataset.edit_from_lonlat(done.geometry, &held)?; + let (reshaped, holes_removed) = match super::OwnGrid::of(l) { + // Held in a projected system: reshaped in its own plane, the line converted into it, and + // written as it is (#2032 C2f-7). + Some(grid) => { + let line = super::line_in_own(s, id, &line)?; + let _plane = rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(grid.crs)); + let done = sketch_edit::reshape(own, &line)?; + super::super::edit::validate(&done.geometry)?; + (done.geometry, done.holes_removed) + } + // Reshaped in longitude/latitude, from the layer's own coordinates, and written back in + // them, what the line left (or snapped to) as stored. + None => { + let lonlat = l.dataset.feature_to_lonlat(f.id, own)?; + let done = sketch_edit::reshape(&lonlat, &line)?; + super::super::edit::validate(&done.geometry)?; + let held = super::held_places(s, id, &[own], &[&done.geometry]); + (l.dataset.edit_from_lonlat(done.geometry, &held)?, done.holes_removed) + } + }; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; if let Some(feat) = l.dataset.features.get_mut(r) { feat.geometry = Some(reshaped); } l.touch_geometry(); apply(s, id, vec![Change { before: Some(f), row: Some(r) }])?; - let n = done.holes_removed; + let n = holes_removed; if n > 0 { s.notify(format!("Reshape removed {n} hole(s) left outside the new boundary of row {r}"), false); } @@ -154,8 +204,8 @@ pub(super) fn reshape(s: &mut Session, p: &Value) -> CmdResult { /// The path along a feature's edge from `from` to `to`: a given feature's (`layer`, `row`), or /// else the nearest line or polygon edge passing within the tolerance of both points (in `layer` -/// when it is given). Returns how far (Web Mercator metres) each point was from the edge it was -/// moved onto. +/// when it is given). Returns how far each point was from the edge it was moved onto: in Web +/// Mercator metres, or metres of a projected layer's own grid ([`traced`]). pub(super) fn trace(s: &mut Session, p: &Value) -> CmdResult { let (from, to) = (point(p, "from")?, point(p, "to")?); let (id, row, part) = match p.get("row") { @@ -183,12 +233,7 @@ pub(super) fn trace(s: &mut Session, p: &Value) -> CmdResult { (id, row, part) } }; - // Traced in longitude/latitude, from the layer's own coordinates. - let l = s.map().layer(id).ok_or("no such row")?; - let feature = l.dataset.features.row(row).ok_or("no such row")?; - let own = feature.geometry().ok_or("the feature has no shape")?; - let g = l.dataset.feature_to_lonlat(feature.id(), own)?; - let t = sketch_edit::trace(&g, from, to, part)?; + let t = traced(s, id, row, from, to, part)?; let path: Vec<[f64; 2]> = t.path.iter().map(|c| [c.x, c.y]).collect(); // How far each point was moved onto the edge, so a far-off point isn't taken silently. Ok(json!({"layer": id, "row": row, "path": path, "fromOffM": t.from_m, "toOffM": t.to_m})) @@ -203,9 +248,35 @@ pub fn trace_between(s: &mut Session, from: Coord, to: Coord) -> Option) -> Result { + let l = s.map().layer(id).ok_or("no such row")?; + let feature = l.dataset.features.row(row).ok_or("no such row")?; + let own = feature.geometry().ok_or("the feature has no shape")?; + let Some(grid) = super::OwnGrid::of(l) else { + let g = l.dataset.feature_to_lonlat(feature.id(), own)?; + return sketch_edit::trace(&g, from, to, part); + }; + // Through the map's system when the layer is shown through it, as the path goes back. + let to_own = l.dataset.shown_from_lonlat()?; + let place = |c: Coord| to_own.point(c).ok_or_else(|| "a point of the trace is no place in the layer's coordinate system".to_string()); + let (f, t) = (place(from)?, place(to)?); + let traced = { + let _plane = rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(grid.crs)); + sketch_edit::trace(own, f, t, part)? + }; + let back = Geometry::Line(vec![traced.path]); + let Geometry::Line(mut parts) = l.dataset.feature_to_lonlat(feature.id(), &back)?.into_owned() else { + return Err("the traced path has no place in longitude/latitude".into()); + }; + let path = parts.pop().ok_or("the traced path has no place in longitude/latitude")?; + Ok(sketch_edit::Traced { path, ..traced }) } /// The drawn line or polygon feature with a ring or part passing nearest both points, each within diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3738e0b2bb..624f1efbcd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -10,6 +10,8 @@ mod formats_out; mod held_databases; #[path = "tests/own_grid_edits.rs"] mod own_grid_edits; +#[path = "tests/own_segments.rs"] +mod own_segments; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/scene_losses.rs"] mod scene_losses; diff --git a/crates/engine/src/tests/own_segments.rs b/crates/engine/src/tests/own_segments.rs new file mode 100644 index 0000000000..c44abfd70e --- /dev/null +++ b/crates/engine/src/tests/own_segments.rs @@ -0,0 +1,246 @@ +//! Cut Polygon, Reshape, Split, Merge and Trace on a layer held in a projected system work on its +//! own segments (#2032 C2f-7): where they run straight in its own coordinates, not in +//! longitude/latitude or Web Mercator. Every place the edit doesn't make stays as stored, and the +//! places it makes lie on the layer's segments there. + +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. +const UTM: Crs = Crs::Epsg(32632); + +/// A dataset `name` of `kind` with `geoms` given in UTM 32N, held there. +fn held(name: &str, kind: GeometryType, geoms: Vec) -> Dataset { + held_in(name, kind, geoms, UTM) +} + +/// [`held`] in `crs`: the coordinates given are stored as they are, in it. +fn held_in(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.held_in = crs; + ds.crs = Some(crs); + ds +} + +/// A square of `side` metres with its south-west corner at (`x`, `y`) in UTM 32N, anticlockwise. +fn square(x: f64, y: f64, side: f64) -> Geometry { + let c = |dx: f64, dy: f64| Coord::new(x + dx, y + dy); + Geometry::Polygon(vec![vec![vec![c(0.0, 0.0), c(side, 0.0), c(side, side), c(0.0, side), c(0.0, 0.0)]]]) +} + +fn session(ds: Dataset) -> Session { + let mut s = Session::new(Project::default()); + crate::cmd::layer::add_dataset(&mut s, ds); + s.map_mut().editing.settings.enabled = true; + let l = &mut s.map_mut().layers[0]; + l.selection = (0..l.dataset.features.len()).collect(); + s +} + +/// Every vertex of the layer, as it holds them. +fn stored(s: &Session) -> Vec { + let mut out = Vec::new(); + for f in &s.map().layers[0].dataset.features { + if let Some(g) = &f.geometry { + g.for_each_coord(|c| out.push(c)); + } + } + out +} + +/// A UTM 32N place in longitude/latitude, as a line drawn on the map gives it. +fn lonlat(c: Coord) -> [f64; 2] { + let c = UTM.to(Crs::LonLat).unwrap().point(c).unwrap(); + [c.x, c.y] +} + +/// How far `c` is from the nearest of `segments`' straight segments, in metres of the grid. +fn off(c: Coord, segments: &[(Coord, Coord)]) -> f64 { + segments + .iter() + .map(|(a, b)| { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let t = (((c.x - a.x) * dx + (c.y - a.y) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0); + (a.x + t * dx - c.x).hypot(a.y + t * dy - c.y) + }) + .fold(f64::INFINITY, f64::min) +} + +/// The square's sides. +fn sides(x: f64, y: f64, side: f64) -> Vec<(Coord, Coord)> { + let c = |dx: f64, dy: f64| Coord::new(x + dx, y + dy); + vec![(c(0.0, 0.0), c(side, 0.0)), (c(side, 0.0), c(side, side)), (c(side, side), c(0.0, side)), (c(0.0, side), c(0.0, 0.0))] +} + +/// A 20 km square well east of UTM 32N's central meridian, where its grid lines curve in +/// longitude/latitude by metres over that length. +const X: f64 = 700_000.0; +const Y: f64 = 5_300_000.0; +const SIDE: f64 = 20_000.0; + +#[test] +fn a_cut_meets_the_layers_own_sides() { + let mut s = session(held("Parcels", GeometryType::Polygon, vec![square(X, Y, SIDE)])); + let before = stored(&s); + // A line drawn north–south across the square, a quarter of the way in. + let line = [lonlat(Coord::new(X + 5_000.0, Y - 1_000.0)), lonlat(Coord::new(X + 5_000.0, Y + SIDE + 1_000.0))]; + let r = s.run("edit.cutPolygon", &json!({"line": {"type": "LineString", "coordinates": line}})).unwrap(); + assert_eq!(r["pieces"], 2); + let after = stored(&s); + let made: Vec = after.iter().copied().filter(|c| !before.contains(c)).collect(); + // The square's corners stay as stored; the cut makes its two points on the square's sides, + // where they run straight in UTM, and on the line converted into it. + assert!(before.iter().all(|c| after.contains(c))); + assert!(!made.is_empty()); + for c in &made { + assert!(off(*c, &sides(X, Y, SIDE)) < 1e-6, "{c:?} is {} m off the square's sides", off(*c, &sides(X, Y, SIDE))); + assert!((c.x - (X + 5_000.0)).abs() < 1e-3, "{c:?}"); + } +} + +#[test] +fn a_reshape_meets_the_layers_own_sides() { + let mut s = session(held("Parcels", GeometryType::Polygon, vec![square(X, Y, SIDE)])); + let before = stored(&s); + // A bump out of the south side, drawn from inside to inside. + let line = [ + lonlat(Coord::new(X + 5_000.0, Y + 2_000.0)), + lonlat(Coord::new(X + 5_000.0, Y - 3_000.0)), + lonlat(Coord::new(X + 15_000.0, Y - 3_000.0)), + lonlat(Coord::new(X + 15_000.0, Y + 2_000.0)), + ]; + s.run("edit.reshape", &json!({"line": {"type": "LineString", "coordinates": line}})).unwrap(); + let after = stored(&s); + // Each new place once: the ring's first is also its last. + let mut crossings: Vec = Vec::new(); + for c in after.iter().copied().filter(|c| !before.contains(c) && (c.y - Y).abs() < 1.0) { + if !crossings.contains(&c) { + crossings.push(c); + } + } + assert_eq!(crossings.len(), 2, "{after:?}"); + for c in crossings { + assert!(off(c, &sides(X, Y, SIDE)) < 1e-6, "{c:?}"); + } + // The north corners, which the reshape didn't reach, stay as stored. + assert!(after.contains(&Coord::new(X + SIDE, Y + SIDE)) && after.contains(&Coord::new(X, Y + SIDE))); +} + +#[test] +fn a_split_is_on_the_layers_own_segment() { + let road = Geometry::Line(vec![vec![Coord::new(X, Y), Coord::new(X + SIDE, Y + SIDE), Coord::new(X + 2.0 * SIDE, Y + SIDE)]]); + let mut s = session(held("Roads", GeometryType::Polyline, vec![road])); + let before = stored(&s); + let at = lonlat(Coord::new(X + 8_000.0, Y + 8_000.0)); + s.run("edit.split", &json!({"lon": at[0], "lat": at[1]})).unwrap(); + let after = stored(&s); + assert_eq!(s.map().layers[0].dataset.features.len(), 2); + assert!(before.iter().all(|c| after.contains(c))); + let made: Vec = after.iter().copied().filter(|c| !before.contains(c)).collect(); + assert!(!made.is_empty()); + for c in made { + // On the diagonal as it runs straight in UTM, at the point asked for. + assert!((c.x - c.y + (Y - X)).abs() / 2f64.sqrt() < 1e-6, "{c:?}"); + assert!((c.x - (X + 8_000.0)).abs() < 1e-3, "{c:?}"); + } +} + +#[test] +fn a_merge_unions_the_layers_own_shapes_as_stored() { + // Two squares sharing a side, as stored in UTM: merged, they are one square with no place + // converted. + let mut s = session(held("Parcels", GeometryType::Polygon, vec![square(X, Y, SIDE), square(X + SIDE, Y, SIDE)])); + let before = stored(&s); + s.run("edit.merge", &json!({})).unwrap(); + let l = &s.map().layers[0]; + assert_eq!(l.dataset.features.len(), 1); + let Some(Geometry::Polygon(p)) = &l.dataset.features[0].geometry else { panic!() }; + assert_eq!(p.len(), 1, "{p:?}"); + assert!(stored(&s).iter().all(|c| before.contains(c)), "{:?}", stored(&s)); +} + +#[test] +fn a_merge_meets_the_layers_own_sides_where_the_shapes_cross() { + // A triangle reaching out of the square's east side: merged, the two points where its sides + // cross the square's east side are new, on that side as it runs straight in UTM. + let triangle = Geometry::Polygon(vec![vec![vec![ + Coord::new(X + 10_000.0, Y + 10_000.0), + Coord::new(X + 30_000.0, Y + 4_000.0), + Coord::new(X + 30_000.0, Y + 16_000.0), + Coord::new(X + 10_000.0, Y + 10_000.0), + ]]]); + let mut s = session(held("Parcels", GeometryType::Polygon, vec![square(X, Y, SIDE), triangle])); + let before = stored(&s); + s.run("edit.merge", &json!({})).unwrap(); + let made: Vec = stored(&s).into_iter().filter(|c| !before.contains(c)).collect(); + assert!(!made.is_empty()); + for c in made { + assert!((c.x - (X + SIDE)).abs() < 1e-6, "{c:?} is off the square's east side"); + } +} + +#[test] +fn a_split_in_a_layer_in_feet_is_on_its_own_segment() { + // New York Long Island (US survey feet): a line split a few miles along, at the point asked. + const NY: Crs = Crs::Epsg(2263); + let (x, y) = (1_000_000.0, 200_000.0); + let road = Geometry::Line(vec![vec![Coord::new(x, y), Coord::new(x + 60_000.0, y + 30_000.0)]]); + let mut s = session(held_in("Roads", GeometryType::Polyline, vec![road], NY)); + let at = NY.to(Crs::LonLat).unwrap().point(Coord::new(x + 20_000.0, y + 10_000.0)).unwrap(); + s.run("edit.split", &json!({"lon": at.x, "lat": at.y})).unwrap(); + assert_eq!(s.map().layers[0].dataset.features.len(), 2); + let made: Vec = + stored(&s).into_iter().filter(|c| *c != Coord::new(x, y) && *c != Coord::new(x + 60_000.0, y + 30_000.0)).collect(); + assert!(!made.is_empty()); + for c in made { + // On the line (y = x / 2 from its start), at the point asked for. + assert!(((c.y - y) - (c.x - x) / 2.0).abs() < 1e-6, "{c:?}"); + assert!((c.x - (x + 20_000.0)).abs() < 1e-3, "{c:?}"); + } +} + +#[test] +fn a_trace_ends_on_the_layers_own_side() { + let mut s = session(held("Parcels", GeometryType::Polygon, vec![square(X, Y, SIDE)])); + let (from, to) = (lonlat(Coord::new(X + 3_000.0, Y + 1.0)), lonlat(Coord::new(X + SIDE - 1.0, Y + 12_000.0))); + let r = s.run("edit.trace", &json!({"from": from, "to": to, "layer": 1, "row": 0})).unwrap(); + let to_utm = Crs::LonLat.to(UTM).unwrap(); + let path: Vec = r["path"] + .as_array() + .unwrap() + .iter() + .map(|c| to_utm.point(Coord::new(c[0].as_f64().unwrap(), c[1].as_f64().unwrap())).unwrap()) + .collect(); + // Its ends on the square's sides as they run straight in UTM (to the round trip's millimetre), + // a metre from the points asked for, by the grid's metres. + for end in [path[0], path[path.len() - 1]] { + assert!(off(end, &sides(X, Y, SIDE)) < 1e-3, "{end:?}"); + } + assert!((r["fromOffM"].as_f64().unwrap() - 1.0).abs() < 1e-3, "{r}"); +} + +#[test] +fn a_split_says_how_many_segments_it_couldnt_measure_and_a_clean_one_says_nothing() { + let split = |road: Geometry| { + let mut s = session(held("Roads", GeometryType::Polyline, vec![road])); + let at = lonlat(Coord::new(X + 8_000.0, Y + 8_000.0)); + let mark = s.notice_mark(); + s.run("edit.split", &json!({"lon": at[0], "lat": at[1]})).unwrap(); + s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>() + }; + // A segment to a vertex missing a coordinate is passed over, and said. + let said = split(Geometry::Line(vec![vec![ + Coord::new(X, Y), + Coord::new(X + SIDE, Y + SIDE), + Coord::new(f64::NAN, Y + SIDE), + Coord::new(X + 2.0 * SIDE, Y + SIDE), + ]])); + assert!(said.iter().any(|t| t.contains("2 segment(s)") && t.contains("could not be measured")), "{said:?}"); + let said = split(Geometry::Line(vec![vec![Coord::new(X, Y), Coord::new(X + SIDE, Y + SIDE)]])); + assert!(said.iter().all(|t| !t.contains("could not be measured")), "{said:?}"); +} diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index c14f2c1590..607b44f60b 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -96,14 +96,14 @@ you edit the value or choose units; click **Apply elevation** to apply the new i 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. Rotate and Scale turn each feature about its own middle anyway, so - they take each layer's own grid even then. The rest of this paragraph, about Web Mercator and the ground, is for - the other layers. + they take each layer's own grid even then. 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 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. + its layer's own system reaches) is left as it is by Move, Rotate and Scale, Split and Cut + Polygon (in a layer edited in its own grid, each of these changes it with the rest), 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, a shape conversion; Reshape, Trace or Merge with it, outside a layer + edited in its own grid) is refused, naming the layer and the feature; Set Geometry gives it a new shape, and Delete removes it. Beyond 85.05°, where Web Mercator stops, Move, Rotate and Scale work on the ground: a feature that reaches beyond it, or that the edit would take beyond it, moves rigidly, together with the selected features sharing a vertex with it (their center goes the distance and direction asked, @@ -135,6 +135,14 @@ you edit the value or choose units; click **Apply elevation** to apply the new i ground (once a split has worked out a million distances along segments near the point, a segment counts as near as the nearest point found on it so far, its nearer end at first, and the split says how many lines it cut that way, or left whole when that point was an end). +- **On a layer's own segments:** in a layer held in a projected system (as for Move above), + Cut Polygon, Reshape, Split, Merge and Trace work on its segments as they run straight in its + own coordinates. The line drawn (or the point Split is given) is converted into them, a point + snapped to a place of a layer in that system being that place as stored; the points a cut, a + reshape or a split makes lie on the layer's segments there, every other place stays as + stored, and Merge unions the shapes as stored, converting nothing. Their distances (a + centimetre at a line's end, Trace's `fromOffM` and `toOffM`) are metres of its grid. Other + layers are edited in Web Mercator, as below. - **Cut Polygon** (Edit › Tools, or the Editing pane): select polygons, then click a line across them and double-click to finish. Each polygon the line crosses from edge to edge is cut into pieces; a zigzag line can make several. The pieces keep the original's attributes. The @@ -160,7 +168,8 @@ you edit the value or choose units; click **Apply elevation** to apply the new i `edit.trace={"from": [lon, lat], "to": [lon, lat]}` returns the path along the nearest edge passing within the snapping tolerance of both points (`"layer"` keeps the search to one layer; add `"row"` to trace a given feature), and how far each point was from the edge (`fromOffM`, `toOffM`, in Web Mercator metres, which - run longer than ground metres away from the equator). + run longer than ground metres away from the equator; for a layer held in a projected system, + in metres of its grid). - **Edit Vertices** (Edit › Features): reshape the selected features on the map. Their vertices show as square handles and each edge has a round midpoint handle. Drag a vertex to move it; drag a midpoint, or click an edge, to insert a vertex; click a vertex and press ++delete++ to