Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -718,12 +718,14 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult {
let kind = ps(p, "kind").ok_or("kind is required")?;
let dem = ps(p, "layer").map(|n| raster_named(s, n)).transpose()?;
let z = |c: Coord| dem.as_ref().and_then(|d| rasterops::elevation_at(d, 0, c));
// Ground lengths and areas on the map's body.
let body = s.map().body();
Comment thread
giswqs marked this conversation as resolved.
Resolved
let out = match kind {
"distance" => {
if pts.len() < 2 {
return Err("a distance needs two or more points".into());
}
let flat = rustgis_geom::geodesic_length_m(&pts);
let flat = body.length(rustgis_geom::geodesic_length_m(&pts));
// Along the surface when there's an elevation raster.
let surface = dem.as_ref().map(|d| {
let prof = rasterops::profile(d, 0, &pts, 500);
Expand All @@ -734,7 +736,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult {
(Some(x), Some(y)) => y - x,
_ => 0.0,
};
((c.0 - a.0).powi(2) + dh * dh).sqrt()
(body.length(c.0 - a.0).powi(2) + dh * dh).sqrt()
}
_ => 0.0,
})
Expand All @@ -750,7 +752,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult {
if let Some(first) = pts.first() {
ring.push(*first);
}
json!({"kind": "area", "squareMetres": rustgis_geom::geodesic_ring_area_m2(&ring), "perimeterMetres": rustgis_geom::geodesic_length_m(&ring)})
json!({"kind": "area", "squareMetres": body.area(rustgis_geom::geodesic_ring_area_m2(&ring)), "perimeterMetres": body.length(rustgis_geom::geodesic_length_m(&ring))})
}
"height" => {
let (Some(a), Some(c)) = (pts.first(), pts.get(1)) else { return Err("a height needs two points (base, top)".into()) };
Expand All @@ -765,6 +767,8 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult {
let base = f(p, "base");
let rings = vec![pts.clone()];
let (cx, cy) = d.cell_size_m();
// A geographic raster's cells are degrees, measured on the Earth: on the map's body.
let (cx, cy) = if d.crs.is_geographic() { (body.length(cx), body.length(cy)) } else { (cx, cy) };
Comment thread
giswqs marked this conversation as resolved.
Resolved
let (mut above, mut below, mut n, mut lowest) = (0.0, 0.0, 0usize, f64::INFINITY);
let mut cells = Vec::new();
let mut e = Extent::EMPTY;
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/cmd/sharing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ fn web_map_html(m: &Map, title: &str) -> Result<String, String> {
}
}
let c = m.center_lonlat();
let bg = css(m.basemap.palette().0);
let bg = css(m.palette().0);
Ok(format!(
r#"<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{title}</title>
<style>html,body{{margin:0;height:100%;overflow:hidden;font-family:system-ui,sans-serif}}canvas{{display:block}}
Expand Down Expand Up @@ -1023,7 +1023,7 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result<Vec<u8>, String> {
fn viewpoint(m: &Map, at: &rustgis_map::Camera, view: (f64, f64)) -> (Value, Value) {
let size = |v: f64| if v.is_finite() { v.clamp(1.0, 1e6) } else { 1.0 };
let (w, h) = (size(view.0), size(view.1));
let ground = at.res * m.flat().ground_per_unit(at.center);
let ground = at.res * m.ground_per_unit(at.center);
let distance = h / 2.0 / rustgis_map::camera::TAN_HALF_FOV * ground;
let distance = if distance.is_finite() { distance.clamp(1.0, 1e9) } else { 1e6 };
let (bearing, pitch) = (at.bearing.to_radians(), at.pitch.to_radians());
Expand Down
50 changes: 50 additions & 0 deletions crates/engine/src/cmd/tiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! MapLibre styles) over the basemap.

use rustgis_map::effects::Blend;
use rustgis_map::planets;
use rustgis_map::tiles::{MAX_TILE_LAYERS, TileKind, TileLayer};
use serde_json::{Value, json};

Expand All @@ -13,6 +14,7 @@ use crate::{CmdResult, CommandSpec as C, Session};
pub const NETWORK: &[&str] = &[
"map.route",
"map.addTiles",
"map.body",
Comment thread
giswqs marked this conversation as resolved.
Resolved
"map.terrain",
"layer.addUrl",
"service.layers",
Expand Down Expand Up @@ -49,9 +51,57 @@ pub fn commands() -> Vec<C> {
r#"{"name"?: text | "index"?: number (0 = top) | "id"?: catalog id, "visible"?: bool, "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference", "move"?: "up"|"down"|"top"|"bottom", "rename"?: text}"#,
),
C::new("map.tiles", "Tile Layers", "Home › Add", |s, _| Ok(list(s, false))).view(),
C::new("map.body", "Celestial Body", "Home › Add", body).params(
r#"{"name"?: "earth"|"moon"|"mars"|"mercury"|"venus"|"io"|"europa"|"ganymede"|"callisto"|"titan"|"pluto"|"charon" (map.bodies lists them; default: the basemap's body), "basemap"?: a planetary basemap's id (default: the body's first; the Earth's removes the planetary ones) | false (adds none, keeping the web basemaps but other bodies')}"#,
),
C::new("map.bodies", "Celestial Bodies", "Home › Add", |s, _| Ok(bodies(s))).view(),
]
}

/// The bodies a map can be on, with their sizes and basemaps, and the one it is on.
fn bodies(s: &Session) -> Value {
let list: Vec<Value> = rustgis_geom::BODIES
.iter()
.map(|b| {
let maps: Vec<Value> = planets::basemaps_of(b.id).map(|m| json!({"id": m.id, "name": m.name})).collect();
json!({"id": b.id, "name": b.name, "equatorialRadius": b.a, "meanRadius": b.mean_radius_m(), "basemaps": maps})
})
.collect();
json!({"body": s.map().body().id, "bodies": list})
}

/// Moves the map to a celestial body: its size sets the map's distances, areas and scale, and
/// (unless `basemap` is false) one of its basemaps replaces the web basemaps.
fn body(s: &mut Session, p: &Value) -> CmdResult {
let keep = p.get("basemap").and_then(Value::as_bool) == Some(false);
Comment thread
giswqs marked this conversation as resolved.
Resolved
let basemap = match ps(p, "basemap") {
Some(id) => Some(planets::basemap(id).ok_or_else(|| format!("no planetary basemap '{id}' (map.bodies lists them)"))?),
None => None,
};
let body = match ps(p, "name") {
Some(n) => rustgis_geom::Body::find(n).ok_or_else(|| {
let ids: Vec<&str> = rustgis_geom::BODIES.iter().map(|b| b.id).collect();
format!("unknown body '{n}' ({})", ids.join(", "))
})?,
None => rustgis_geom::Body::get(basemap.ok_or("name or basemap is required")?.body),
};
if let Some(m) = basemap.filter(|m| m.body != body.id) {
return Err(format!("'{}' is a basemap of {}, not {}", m.id, rustgis_geom::Body::get(m.body).name, body.name));
}
let basemap = if keep { None } else { basemap.or_else(|| planets::basemaps_of(body.id).next()) };
let m = s.map_mut();
m.body = body.id.to_string();
Comment thread
giswqs marked this conversation as resolved.
Resolved
// Other bodies' basemaps always go (with `keep`, this body's and the Earth's web basemaps
// stay); on the Earth, the web basemaps the map had stay.
m.tiles.retain(|t| t.overlay || planets::basemap(&t.id).is_none_or(|b| keep && b.body == body.id));
if let Some(b) = basemap {
let tile = json!({"url": b.url, "kind": "raster", "name": format!("{} · {}", body.name, b.name), "attribution": b.attribution,
"maxZoom": b.max_zoom, "tms": b.tms, "id": b.id, "replace": true});
add(s, &tile)?;
Comment thread
giswqs marked this conversation as resolved.
Resolved
}
Ok(json!({"body": body.id, "name": body.name, "meanRadius": body.mean_radius_m(), "basemap": basemap.map(|b| b.id)}))
}

/// The map's tile layers (index 0 on top), as `map.tiles` and `info.project` list them; `redact`
/// drops the credentials from their addresses.
pub(crate) fn list(s: &Session, redact: bool) -> Value {
Expand Down
89 changes: 84 additions & 5 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2675,13 +2675,18 @@ fn layer_effects_and_imagery_tools() {
// Mensuration.
let m = s.run("raster.measure", &json!({"layer": dem, "kind": "height", "points": [[10.0015, 45.0385], [10.0205, 45.0195]]})).unwrap();
assert!(m["metres"].as_f64().unwrap() > 50.0, "{m}");
s.run(
"raster.measure",
&json!({"layer": dem, "kind": "volume", "points": [[10.015, 45.015], [10.025, 45.015], [10.025, 45.025], [10.015, 45.025]]}),
)
.unwrap();
let volume =
json!({"layer": dem, "kind": "volume", "points": [[10.015, 45.015], [10.025, 45.015], [10.025, 45.025], [10.015, 45.025]]});
let on_earth = s.run("raster.measure", &volume).unwrap()["cubicMetresAbove"].as_f64().unwrap();
s.run("raster.measure", &json!({"kind": "area", "points": [[0, 0], [1, 0], [1, 1]]})).unwrap();
assert_eq!(s.run("raster.measurements", &Value::Null).unwrap().as_array().unwrap().len(), 3);
// On Mars the degree cells of this raster are Mars' size: the same heights over a smaller
// ground (#223).
s.run("map.body", &json!({"name": "mars", "basemap": false})).unwrap();
let on_mars = s.run("raster.measure", &volume).unwrap()["cubicMetresAbove"].as_f64().unwrap();
let k = rustgis_geom::Body::get("mars").ratio();
assert!(on_earth > 0.0 && (on_mars / on_earth - k * k).abs() < 1e-9, "{on_earth} {on_mars}");
s.run("map.body", &json!({"name": "earth"})).unwrap();
// Workspaces: an orthomosaic of two rasters, a DSM mosaic and its mesh.
s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Valley", "images": [dem, "dem_later"]})).unwrap();
s.run("imagery.workspaceOptions", &json!({"name": "Valley", "cellSize": 0.002})).unwrap();
Expand Down Expand Up @@ -8840,6 +8845,80 @@ fn scripts_refuse_edits_to_streamed_layers() {
let _ = std::fs::remove_file(path);
}

/// A map on Mars (#223): the body switcher puts a Mars basemap under it, its measurements and
/// scale are Mars', and the project keeps the body; back on the Earth the Mars basemap goes.
#[test]
fn celestial_bodies_set_the_basemap_and_the_measurements() {
let mut s = Session::new(Project::default());
let earth = |s: &mut Session| {
s.run("raster.measure", &json!({"kind": "distance", "points": [[0, 0], [90, 0]]})).unwrap()["metres"].as_f64().unwrap()
};
let on_earth = earth(&mut s);
let earth_scale = s.map().scale();
s.run("map.addTiles", &json!({"url": "https://tile.openstreetmap.org/{z}/{x}/{y}.png", "id": "osm"})).unwrap();
let v = s.run("map.body", &json!({"name": "Mars"})).unwrap();
assert_eq!(v["body"], "mars");
assert_eq!(s.map().body().id, "mars");
// Mars' basemap replaces the Earth's.
let tiles = s.run("map.tiles", &Value::Null).unwrap();
let ids: Vec<&str> = tiles.as_array().unwrap().iter().filter_map(|t| t["id"].as_str()).collect();
assert_eq!(ids, ["planet-mars-viking-mdim21"]);
assert!(s.map().tiles.first().is_some_and(|t| t.tms));
// The built-in basemap's Earth land isn't drawn on Mars: a plain background under its tiles.
let (background, land, ..) = s.map().palette();
assert_eq!(background, land);
// A quarter of Mars' equator, and the scale of a smaller world.
let on_mars = earth(&mut s);
let k = rustgis_geom::Body::get("mars").ratio();
assert!((on_mars / on_earth - k).abs() < 1e-9 && (on_mars - std::f64::consts::FRAC_PI_2 * 3_389_526.7).abs() < 1.0, "{on_mars}");
assert!((s.map().scale() / earth_scale - k).abs() < 1e-9);
let area = s.run("raster.measure", &json!({"kind": "area", "points": [[0, 0], [1, 0], [1, 1]]})).unwrap();
// Leaving Mars without a new basemap still takes Mars' off.
s.run("map.body", &json!({"name": "earth", "basemap": false})).unwrap();
assert!(s.map().tiles.is_empty());
let earth_area = s.run("raster.measure", &json!({"kind": "area", "points": [[0, 0], [1, 0], [1, 1]]})).unwrap();
let ratio = area["squareMetres"].as_f64().unwrap() / earth_area["squareMetres"].as_f64().unwrap();
assert!((ratio - k * k).abs() < 1e-9, "{ratio}");
// Another of Mars' basemaps, named alone; saved and opened again, the map is still on Mars.
s.run("map.body", &json!({"basemap": "mars-hillshade"})).unwrap();
assert_eq!(s.map().body().id, "mars");
assert_eq!(s.map().tiles.len(), 1);
let text = serde_json::to_string(&s.project).unwrap();
let p = Project::from_json(&text).unwrap();
assert_eq!(p.maps.first().map(|m| m.body().id), Some("mars"));
// Back on the Earth the planetary basemap goes; an Earth map saves no body.
s.run("map.body", &json!({"name": "earth"})).unwrap();
assert!(s.map().tiles.is_empty() && s.map().body().is_earth());
assert!(!serde_json::to_string(&s.project).unwrap().contains("\"body\""));
// Undo goes back to Mars.
assert!(s.undo());
assert_eq!(s.map().body().id, "mars");
// Bad names and mismatches are refused, and nothing changes.
assert!(s.run("map.body", &json!({"name": "vulcan"})).is_err());
assert!(s.run("map.body", &json!({"name": "moon", "basemap": "mars-hillshade"})).is_err());
assert!(s.run("map.body", &json!({})).is_err());
assert_eq!(s.map().body().id, "mars");
let bodies = s.run("map.bodies", &Value::Null).unwrap();
assert_eq!(bodies["body"], "mars");
assert_eq!(bodies["bodies"].as_array().map(Vec::len), Some(rustgis_geom::BODIES.len()));
// A basemap the map has no room for (overlays fill it) fails, and the map stays as it was:
// on its body, with its tile layers.
let mut full = Session::new(Project::default());
for i in 0..rustgis_map::tiles::MAX_TILE_LAYERS {
full.run("map.addTiles", &json!({"url": format!("https://o{i}.example.com/{{z}}/{{x}}/{{y}}.png"), "overlay": true})).unwrap();
}
assert!(full.run("map.body", &json!({"name": "mars"})).is_err());
assert!(full.map().body().is_earth());
assert_eq!(full.map().tiles.len(), rustgis_map::tiles::MAX_TILE_LAYERS);
// A project naming an unknown body is on the Earth.
let odd = text.replace("\"body\":\"mars\"", "\"body\":\"vulcan\"");
assert_ne!(odd, text);
let p = Project::from_json(&odd).unwrap();
assert!(p.maps.first().is_some_and(|m| m.body().is_earth()));
// Saved again, it keeps the body's id (a newer version's, say).
assert!(serde_json::to_string(&p).unwrap().contains("\"body\":\"vulcan\""));
}

/// Text elements take italic, alignment and letter spacing (#213, point c): set when added or
/// later, kept through a save, plain by default and not written until changed; a bad value is an
/// error that changes nothing.
Expand Down
110 changes: 110 additions & 0 deletions crates/geom/src/body.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
//! Celestial bodies: the Earth, the Moon, Mars and the other bodies a map can show (#223).
//!
//! Coordinates stay longitude/latitude degrees and the map stays a Web Mercator sphere whatever
//! the body; what changes is how big that sphere is on the ground. Every measurement here is made
//! on the Earth's sphere and comes from angles, so a body's lengths are the Earth's times the ratio
//! of their mean radii ([`Body::ratio`]) and its areas the Earth's times its square. That is exact
//! for a sphere, which is how every body but the Earth and Mars is modelled, and within Mars'
//! flattening (0.6%) for Mars.

/// A celestial body: a rotational ellipsoid by its equatorial radius and flattening.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Body {
/// The id a map stores (`"earth"`, `"mars"`…).
pub id: &'static str,
/// Its name, in English.
pub name: &'static str,
/// Equatorial (semi-major) radius, metres.
pub a: f64,
/// Inverse flattening; 0 for a sphere.
pub inv_f: f64,
}

/// The Earth (WGS 84), the body a map is on unless told otherwise.
pub const EARTH: Body = Body { id: "earth", name: "Earth", a: 6_378_137.0, inv_f: 298.257_223_563 };

/// The bodies a map can be on: the Earth (WGS 84) and the IAU figures of the others, the Moon and
/// Mars first, then the rest by name.
pub const BODIES: [Body; 12] = [
EARTH,
Body { id: "moon", name: "Moon", a: 1_737_400.0, inv_f: 0.0 },
Body { id: "mars", name: "Mars", a: 3_396_190.0, inv_f: 169.894_447 },
Body { id: "callisto", name: "Callisto", a: 2_410_300.0, inv_f: 0.0 },
Body { id: "charon", name: "Charon", a: 606_000.0, inv_f: 0.0 },
Body { id: "europa", name: "Europa", a: 1_560_800.0, inv_f: 0.0 },
Body { id: "ganymede", name: "Ganymede", a: 2_631_200.0, inv_f: 0.0 },
Body { id: "io", name: "Io", a: 1_821_600.0, inv_f: 0.0 },
Body { id: "mercury", name: "Mercury", a: 2_439_400.0, inv_f: 0.0 },
Body { id: "pluto", name: "Pluto", a: 1_188_300.0, inv_f: 0.0 },
Body { id: "titan", name: "Titan", a: 2_574_730.0, inv_f: 0.0 },
Body { id: "venus", name: "Venus", a: 6_051_800.0, inv_f: 0.0 },
];

impl Body {
/// The body with this id or name (any case), if there is one.
pub fn find(s: &str) -> Option<&'static Body> {
let s = s.trim();
BODIES.iter().find(|b| b.id.eq_ignore_ascii_case(s) || b.name.eq_ignore_ascii_case(s))
}

/// The body with this id, or the Earth for an unknown one (as a project file may hold).
pub fn get(id: &str) -> &'static Body {
Body::find(id).unwrap_or(&EARTH)
}

pub fn is_earth(&self) -> bool {
self.id == EARTH.id
}

/// Polar radius, metres.
pub fn b(&self) -> f64 {
if self.inv_f > 0.0 { self.a * (1.0 - 1.0 / self.inv_f) } else { self.a }
}

/// Mean radius `(2a + b) / 3`, metres.
pub fn mean_radius_m(&self) -> f64 {
(2.0 * self.a + self.b()) / 3.0
}

/// Ground lengths on this body over the same lengths measured on the Earth's sphere
/// ([`crate::EARTH_RADIUS_M`]): exactly 1 on the Earth.
pub fn ratio(&self) -> f64 {
if self.is_earth() { 1.0 } else { self.mean_radius_m() / crate::EARTH_RADIUS_M }
}

/// A length measured on the Earth's sphere ([`crate::geodesic_length_m`]) as this body's.
pub fn length(&self, earth_m: f64) -> f64 {
earth_m * self.ratio()
}

/// An area measured on the Earth's sphere ([`crate::geodesic_ring_area_m2`]) as this body's.
pub fn area(&self, earth_m2: f64) -> f64 {
earth_m2 * self.ratio() * self.ratio()
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn bodies_scale_measurements_by_their_radius() {
assert_eq!(Body::get("earth").ratio(), 1.0);
assert_eq!(Body::get("nope").id, "earth");
assert_eq!(Body::find("MARS").map(|b| b.id), Some("mars"));
assert_eq!(Body::find("Moon").map(|b| b.id), Some("moon"));
// A quarter of the Moon's equator.
let moon = Body::get("moon");
let quarter = moon.length(crate::haversine_m(crate::Coord::new(0.0, 0.0), crate::Coord::new(90.0, 0.0)));
assert!((quarter - std::f64::consts::FRAC_PI_2 * 1_737_400.0).abs() < 1e-3, "{quarter}");
// Mars' mean radius, (2a + b) / 3, and its areas the square of the ratio.
let mars = Body::get("mars");
assert!((mars.mean_radius_m() - 3_389_526.7).abs() < 0.1, "{}", mars.mean_radius_m());
assert!((mars.area(1.0) - mars.ratio().powi(2)).abs() < 1e-12);
// Every id is distinct and every body is real.
for (i, b) in BODIES.iter().enumerate() {
assert!(b.a > 0.0 && b.ratio() > 0.0 && b.ratio().is_finite());
assert!(BODIES.iter().skip(i + 1).all(|o| o.id != b.id));
}
}
}
3 changes: 3 additions & 0 deletions crates/geom/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
//! coordinates are Web Mercator metres (EPSG:3857).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]

pub mod body;
pub mod triangulate;

pub use body::{BODIES, Body};

use serde::{Deserialize, Serialize};

/// Mean Earth radius used by the haversine formula (metres).
Expand Down
Loading
Loading