Skip to content
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ gpkg.addLayer path table? limit? name?
gpkg.discardEdits layer?
gpkg.pendingEdits layer?
gpkg.saveEdits layer?
graphics.add shape points layer? text? fill? outline? width? size? fontSize? bold? italic? align? letterSpacing? image? path?
graphics.add shape points layer? text? fill? outline? width? size? fontSize? bold? italic? align? letterSpacing? image? path? frame?
graphics.edit layer row points? text? fontSize? bold? italic? align? letterSpacing? fill? outline? width? size?
graphics.keepTool on?
graphics.newLayer name?
Expand Down
213 changes: 178 additions & 35 deletions crates/engine/src/cmd/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub fn commands() -> Vec<C> {
}).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"name"?: string}"#),
C::new("graphics.add", "Add Graphic", "Edit › Graphics", add).roles(&[]).effects(crate::policy::Effects::NONE).params(
r##"{"shape": "point"|"text"|"line"|"curve"|"freehand"|"polygon"|"lasso"|"rectangle"|"circle"|"ellipse"|"picture", "points": [[lon, lat], …] (rectangle, ellipse, picture: two corners; circle: centre and a point on the edge), "layer"?: graphics layer, "text"?: string (dynamic tokens: {map} {scale} {date} {time} {crs} {layers} {center}), "fill"?: "#RRGGBBAA", "outline"?: "#RRGGBBAA", "width"?: number, "size"?: number, "fontSize"?: number, "bold"?: bool, "italic"?: bool, "align"?: "left"|"center"|"right" (a text's lines in their block, which stays centred on its point), "letterSpacing"?: points, -5 to 50, "image"?: base64 PNG/JPEG, "path"?: picture file}"##,
r##"{"shape": "point"|"text"|"line"|"curve"|"freehand"|"polygon"|"lasso"|"rectangle"|"circle"|"ellipse"|"picture", "points": [[lon, lat], …] (rectangle, ellipse, picture: two corners; circle: centre and a point on the edge), "layer"?: graphics layer, "text"?: string (dynamic tokens: {map} {scale} {date} {time} {crs} {layers} {center}), "fill"?: "#RRGGBBAA", "outline"?: "#RRGGBBAA", "width"?: number, "size"?: number, "fontSize"?: number, "bold"?: bool, "italic"?: bool, "align"?: "left"|"center"|"right" (a text's lines in their block, which stays centred on its point), "letterSpacing"?: points, -5 to 50, "image"?: base64 PNG/JPEG, "path"?: picture file, "frame"?: "mercator" (default: a rectangle a box of longitudes and latitudes, a circle, ellipse or curve round in Web Mercator)|"view" (built in the map's own coordinates as the view faces, as a drag on the map previews it; a picture stays a box of longitudes and latitudes)}"##,
),
C::new("graphics.style", "Graphic Style", "Edit › Graphics", style).roles(&[]).effects(crate::policy::Effects::NONE)
.when(super::need_selection)
Expand Down Expand Up @@ -84,21 +84,56 @@ fn target(s: &mut Session, p: &Value) -> Result<u32, String> {
})
}

fn points(p: &Value) -> Result<Vec<Coord>, String> {
impl Plane {
/// The latitude a graphic's points are kept within: 85° in Web Mercator (the default plane,
/// or a view of a Web Mercator map), where a pole is infinitely far; 90° in a view of a map
/// in another projection, which may show a pole.
fn lat_max(&self) -> f64 {
if matches!(self, Plane::View { flat: rustgis_map::projection::Flat::Custom(_), .. }) { 90.0 } else { 85.0 }
}

/// `pts` kept within [`Plane::lat_max`], and how many were moved to it.
fn clamped(&self, pts: impl IntoIterator<Item = Coord>) -> (Vec<Coord>, usize) {
let m = self.lat_max();
let mut moved = 0;
let pts = pts
.into_iter()
.map(|c| {
let y = c.y.clamp(-m, m);
moved += usize::from(y != c.y);
Coord::new(c.x, y)
})
.collect();
(pts, moved)
}
}

/// The points given, in longitude/latitude, kept within `plane`'s latitude
/// ([`Plane::clamped`]), and how many were moved to it.
fn points(p: &Value, plane: &Plane) -> Result<(Vec<Coord>, usize), String> {
let arr = p.get("points").and_then(Value::as_array).ok_or("points is required")?;
if arr.len() > MAX_POINTS {
return Err(format!("a graphic takes at most {MAX_POINTS} points"));
}
arr.iter()
let given = arr
.iter()
.map(|v| {
let x = v.get(0).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= 540.0);
let y = v.get(1).and_then(Value::as_f64).filter(|y| y.is_finite() && y.abs() <= 90.0);
match (x, y) {
(Some(x), Some(y)) => Ok(Coord::new(x, y.clamp(-85.0, 85.0))),
(Some(x), Some(y)) => Ok(Coord::new(x, y)),
_ => Err("each point is [lon, lat]".to_string()),
}
})
.collect()
.collect::<Result<Vec<_>, _>>()?;
Ok(plane.clamped(given))
}

/// Says that `n` points of a graphic were placed at 85°, where a Web Mercator map stops.
fn say_clamped(s: &mut Session, n: usize) {
if n > 0 {
s.notify(format!("{n} point(s) of the graphic past 85° latitude were placed at 85°: a Web Mercator map can't show a pole"), false);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With no frame, the points are built in Web Mercator even on a polar map, so this message is wrong there: "a Web Mercator map can't show a pole" is untrue when the map shows one. A message that says what happened and how to keep the point would be clearer, for example: "…placed at 85°: built in Web Mercator, which can't show a pole; "frame": "view" keeps it where it was given on a map that shows one". Wording only.

Category: quality

}
}

fn need(pts: &[Coord], n: usize, shape: &str) -> Result<(), String> {
Expand All @@ -121,9 +156,88 @@ fn ring(mut pts: Vec<Coord>) -> Vec<Coord> {
pts
}

/// A smooth curve through the points (Catmull-Rom).
fn curve(pts: &[Coord]) -> Vec<Coord> {
let m: Vec<Coord> = pts.iter().map(|c| lonlat_to_merc(*c)).collect();
/// The plane a graphic's rectangle, circle, ellipse or curve is built in. Web Mercator facing
/// north is what a command builds in unless told otherwise, as every release did; the view's
/// (`"frame": "view"`) is the map's own coordinates turned to the camera's bearing, the plane a
/// shape dragged on the map is previewed in, so what is drawn is what was dragged on any map: on
/// one in UTM a rectangle has the view's square corners, not a box of longitudes and latitudes,
/// and a circle is round there, not round in Web Mercator.
pub enum Plane {
Mercator,
View { flat: rustgis_map::projection::Flat, cos: f64, sin: f64 },
}

impl Plane {
/// The plane `"frame"` names: absent or `"mercator"`, Web Mercator; `"view"`, the map's view.
fn of(s: &Session, p: &Value) -> Result<Self, String> {
match p.get("frame") {
None | Some(Value::Null) => Ok(Plane::Mercator),
Some(Value::String(f)) if f == "mercator" => Ok(Plane::Mercator),
Some(Value::String(f)) if f == "view" => Ok(Plane::view(s)),
Some(other) => Err(format!("frame {other} is neither \"view\" nor \"mercator\"")),
}
}

/// The map's view: its own coordinates, x to the right and y up as the camera faces.
pub fn view(s: &Session) -> Self {
let map = s.map();
let b = map.camera.bearing;
// Exactly 1 and 0 facing north, as the camera turns it.
let (sin, cos) = if b == 0.0 || !b.is_finite() { (0.0, 1.0) } else { b.to_radians().sin_cos() };
Plane::View { flat: map.flat(), cos, sin }
}

/// A place in longitude/latitude in the plane; `None` where the map doesn't show it.
fn to(&self, c: Coord) -> Option<Coord> {
match self {
Plane::Mercator => Some(lonlat_to_merc(c)),
Plane::View { flat, cos, sin } => {
let m = flat.forward_checked(c)?;
Some(Coord::new(m.x * cos - m.y * sin, m.x * sin + m.y * cos))
}
}
}

/// A place in the plane in longitude/latitude; `None` past the map's projection: where the
/// place read back isn't one the map shows at that same place (outside a limited projection's
/// area, or folded over), as [`Plane::to`] refuses it.
fn back(&self, v: Coord) -> Option<Coord> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confidence: medium-low. to rejects a point the projection doesn't map back to itself (Flat::forward_checked, which checks the round trip and the domain), but back only calls flat.inverse, which accepts any finite lat/lon up to ±90°. So a circle, ellipse or curve whose ring points leave a limited projection's area of use (or fold) may be accepted and drawn wrongly, even though the PR says "a shape that leaves the map's projection is refused, not drawn folded". Only the centre and corners are checked today. Please check that a ring point round-trips through forward_checked (a point on a limited projection's edge, far from its zone, is the case to test), or say why the inverse can't return such a point.

Category: bug

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 48895d7: Plane::back now reads the place back through Flat::forward_checked and refuses it unless it lands on the same plane point (within a millionth of its size, at least 1 mm). Web Mercator is left out of the check, since it reads every place back and clamps past 85° as it draws, so a circle reaching past 85° on the default map is still added. Tests: a_ring_point_past_the_maps_projection_is_refused, a_circle_past_85_degrees_on_a_web_mercator_map_is_drawn_and_one_round_the_pole_on_a_polar_map.

match self {
Plane::Mercator => Some(merc_to_lonlat(v)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Web Mercator a circle, ellipse or view-frame rectangle can have ring points past 85°, and they are stored that way with no notice. points() keeps only the centre and edge (or corners) within 85°, but the radius is a Euclidean distance in Mercator metres, so the ring reaches further than the edge's latitude when the edge lies east or west of the centre. Example: centre (0°, 84°), edge (30°, 84°), frame absent. The ring's top is at about 86.2°. back returns merc_to_lonlat unchanged, so those vertices stay past 85° in the data. The renderer clamps them at 85.05°, so the circle is drawn flattened, and nothing is said.

This contradicts the PR text ("Web Mercator keeps clamping at 85°") and the comment in a_circle_near_85_degrees… ("the circle can't reach past 85° on Web Mercator"), which only tests a vertical edge, where the top equals the edge's latitude. Suggest clamping the ring's vertices here and adding them to the notice count, or refusing a Mercator ring that leaves 85°, plus a test with an east-west edge. Confidence: medium-high from the arithmetic; I could not run it.

Category: bug

Plane::View { flat, cos, sin } => {
let m = Coord::new(v.x * cos + v.y * sin, v.y * cos - v.x * sin);
let c = flat.inverse(m)?;
// Web Mercator reads every place back where it is (past 85° it is clamped as it
// is drawn).
if matches!(flat, rustgis_map::projection::Flat::Mercator) {
return Some(c);
}
let again = flat.forward_checked(c)?;
// A millionth of its size, and at least a millimetre: what a round trip moves a
// place, with room to spare.
let reach = (1e-6 * m.x.abs().max(m.y.abs())).max(1e-3);
((again.x - m.x).abs() <= reach && (again.y - m.y).abs() <= reach).then_some(c)
}
}
}

#[cfg(test)]
pub(crate) fn back_for_tests(&self, v: Coord) -> Option<Coord> {
self.back(v)
}

fn all_to(&self, pts: &[Coord], shape: &str) -> Result<Vec<Coord>, String> {
pts.iter().map(|c| self.to(*c).ok_or_else(|| format!("a point of the {shape} isn't on the map"))).collect()
}

fn all_back(&self, pts: impl IntoIterator<Item = Coord>, shape: &str) -> Result<Vec<Coord>, String> {
pts.into_iter().map(|v| self.back(v).ok_or_else(|| format!("the {shape} reaches past the map's projection"))).collect()
}
}

/// A smooth curve through the points (Catmull-Rom), in the plane.
fn curve(pts: &[Coord], plane: &Plane) -> Result<Vec<Coord>, String> {
let m = plane.all_to(pts, "curve")?;
let n = m.len();
let at = |i: isize| m.get(i.clamp(0, n as isize - 1) as usize).copied().unwrap_or_default();
let mut out = Vec::new();
Expand All @@ -141,25 +255,35 @@ fn curve(pts: &[Coord]) -> Vec<Coord> {
if let Some(l) = m.last() {
out.push(*l);
}
out.into_iter().map(merc_to_lonlat).collect()
plane.all_back(out, "curve")
}

/// An ellipse inscribed in the box between two corners, drawn round on the flat map.
fn ellipse(a: Coord, b: Coord) -> Vec<Coord> {
let (a, b) = (lonlat_to_merc(a), lonlat_to_merc(b));
/// An ellipse inscribed in the box between two corners in the plane, drawn round there.
fn ellipse(a: Coord, b: Coord, plane: &Plane, shape: &str) -> Result<Vec<Coord>, String> {
let (cx, cy) = ((a.x + b.x) / 2.0, (a.y + b.y) / 2.0);
let (rx, ry) = ((a.x - b.x).abs() / 2.0, (a.y - b.y).abs() / 2.0);
ring(
(0..72)
.map(|i| {
let t = i as f64 / 72.0 * std::f64::consts::TAU;
merc_to_lonlat(Coord::new(cx + rx * t.cos(), cy + ry * t.sin()))
})
.collect(),
)
let around = (0..72).map(|i| {
let t = i as f64 / 72.0 * std::f64::consts::TAU;
Coord::new(cx + rx * t.cos(), cy + ry * t.sin())
});
Ok(ring(plane.all_back(around, shape)?))
}

fn geometry(shape: &str, pts: Vec<Coord>) -> Result<Geometry, String> {
/// Two corners in the plane, refused when they share a side.
fn corners(pts: &[Coord], plane: &Plane, shape: &str) -> Result<(Coord, Coord), String> {
let (a, b) = ends(pts, shape)?;
let (a, b) = (plane.to(a), plane.to(b));
let (a, b) = a.zip(b).ok_or_else(|| format!("a corner of the {shape} isn't on the map"))?;
if a.x == b.x || a.y == b.y {
return Err(format!("a{} {shape} needs two different corners", if shape == "ellipse" { "n" } else { "" }));
}
Ok((a, b))
}

/// The shape a graphic of `shape` through `pts` (longitude/latitude) takes, built in `plane`.
/// A picture is a box of longitudes and latitudes in every plane: it is drawn upright on the
/// map over its box there.
pub fn geometry(shape: &str, pts: Vec<Coord>, plane: &Plane) -> Result<Geometry, String> {
Ok(match shape {
"point" | "text" => Geometry::Point(*pts.first().ok_or("a point needs a location")?),
"line" | "freehand" => {
Expand All @@ -168,12 +292,18 @@ fn geometry(shape: &str, pts: Vec<Coord>) -> Result<Geometry, String> {
}
"curve" => {
need(&pts, 2, shape)?;
Geometry::Line(vec![curve(&pts)])
Geometry::Line(vec![curve(&pts, plane)?])
}
"polygon" | "lasso" => {
need(&pts, 3, shape)?;
Geometry::Polygon(vec![vec![ring(pts)]])
}
"rectangle" if matches!(plane, Plane::View { .. }) => {
let (a, b) = corners(&pts, plane, shape)?;
let (x0, x1, y0, y1) = (a.x.min(b.x), a.x.max(b.x), a.y.min(b.y), a.y.max(b.y));
let around = [Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1)];
Geometry::Polygon(vec![vec![ring(plane.all_back(around, shape)?)]])
}
"rectangle" | "picture" => {
let (a, b) = ends(&pts, shape)?;
if a.x == b.x || a.y == b.y {
Expand All @@ -190,27 +320,33 @@ fn geometry(shape: &str, pts: Vec<Coord>) -> Result<Geometry, String> {
}
"circle" => {
let (c, e) = ends(&pts, shape)?;
let (c, e) = (lonlat_to_merc(c), lonlat_to_merc(e));
let (c, e) = plane.to(c).zip(plane.to(e)).ok_or("the circle's centre or edge isn't on the map")?;
let r = ((e.x - c.x).powi(2) + (e.y - c.y).powi(2)).sqrt();
if r <= 0.0 {
return Err("a circle needs a radius".into());
}
Geometry::Polygon(vec![vec![ellipse(
merc_to_lonlat(Coord::new(c.x - r, c.y - r)),
merc_to_lonlat(Coord::new(c.x + r, c.y + r)),
)]])
Geometry::Polygon(vec![vec![ellipse(Coord::new(c.x - r, c.y - r), Coord::new(c.x + r, c.y + r), plane, shape)?]])
}
"ellipse" => {
let (a, b) = ends(&pts, shape)?;
if a.x == b.x || a.y == b.y {
return Err("an ellipse needs two different corners".into());
}
Geometry::Polygon(vec![vec![ellipse(a, b)]])
let (a, b) = corners(&pts, plane, shape)?;
Geometry::Polygon(vec![vec![ellipse(a, b, plane, shape)?]])
}
other => return Err(format!("unknown shape '{other}'")),
})
}

/// The outline a shape dragged between `pts` takes on the map (`"frame": "view"`), in
/// longitude/latitude: what the drag previews, so the preview is the graphic it adds.
pub fn dragged_outline(s: &Session, shape: &str, pts: &[Coord]) -> Option<Vec<Coord>> {
// Kept within the latitude the graphic will be added within, so the outline is the one added.
let plane = Plane::view(s);
let (pts, _) = plane.clamped(pts.iter().copied());
match geometry(shape, pts, &plane).ok()? {
Geometry::Polygon(p) => p.into_iter().next()?.into_iter().next(),
_ => None,
}
}

/// The italic, alignment and letter spacing a command gives a text (#535): `None` where not given.
#[derive(Default)]
struct TextStyle {
Expand Down Expand Up @@ -345,7 +481,9 @@ fn add(s: &mut Session, p: &Value) -> CmdResult {
if !graphics::SHAPES.contains(&shape.as_str()) {
return Err(format!("unknown shape '{shape}'"));
}
let g = geometry(&shape, points(p)?)?;
let plane = Plane::of(s, p)?;
let (pts, clamped) = points(p, &plane)?;
let g = geometry(&shape, pts, &plane)?;
let text = ps(p, "text").map(|t| super::within("text", "a graphic's text", t, 2000)).transpose()?;
if shape == "text" && text.as_deref().is_none_or(|t| t.trim().is_empty()) {
return Err("text is required".into());
Expand Down Expand Up @@ -387,6 +525,7 @@ fn add(s: &mut Session, p: &Value) -> CmdResult {
}
}
l.touch_geometry();
say_clamped(s, clamped);
Ok(json!({"layer": id, "row": row, "shape": shape}))
}

Expand Down Expand Up @@ -420,11 +559,14 @@ fn edit(s: &mut Session, p: &Value) -> CmdResult {
if !matches!(kind.as_str(), "point" | "text") {
return Err("only a point or a text graphic is placed again by its points".into());
}
Some(geometry(&kind, points(p)?)?)
// As the map shows it: a point at 88° on a polar map stays there.
let plane = Plane::view(s);
let (pts, clamped) = points(p, &plane)?;
Some((geometry(&kind, pts, &plane)?, clamped))
}
None => None,
};
if let Some(g) = placed {
if let Some((g, clamped)) = placed {
let held = super::design::held_places(s, id, &[], &[&g]);
let l = s.map_mut().layer_mut(id).ok_or("no such layer")?;
// Placed in longitude/latitude, written in the layer's own coordinates.
Expand All @@ -433,6 +575,7 @@ fn edit(s: &mut Session, p: &Value) -> CmdResult {
ft.geometry = Some(g);
}
l.touch_geometry();
say_clamped(s, clamped);
// A null is no style, as `restyle` reads it: placed with only nulls, it is just placed.
let styled = ["text", "fill", "outline", "width", "size", "fontSize", "bold", "italic", "align", "letterSpacing"]
.iter()
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use crate::{Project, Session, sample};

#[path = "tests/formats_out.rs"]
mod formats_out;
#[path = "tests/graphics_frames.rs"]
mod graphics_frames;
#[cfg(not(target_arch = "wasm32"))]
#[path = "tests/held_databases.rs"]
mod held_databases;
Expand Down
Loading
Loading