diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 6831993902..e10af903c0 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -79,7 +79,7 @@ pub fn commands() -> Vec { C::new("map.basemap", "Basemap", "Home › Add", basemap).roles(&[]).effects(crate::policy::Effects::NONE) .params(r##"{"name": "paper"|"midnight"|"ocean"|"atlas"|"blank", "keepTiles"?: bool (keeps the web tile basemaps over it), "color"?: "#RRGGBB" (blank: the paper's colour, drawn where a blank map draws white, the tilted view's sky included; null or #FFFFFF: white; default: as it was. Another basemap takes the paper off and keeps its own colours; a color given with it is said as a warning)}"##), C::new("map.graticule", "Graticule", "View › Display", graticule).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre)}"#), + .params(r##"{"on"?: bool (toggles when omitted, on when a type or crs is given, kept as it is when only onTop or color is given), "type"?: "degrees"|"measured"|"utm"|"mgrs", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre), "onTop"?: bool (the lines over the layers, under the labels; false or null: with the basemap, under the layers), "color"?: "#RRGGBB"|"#RRGGBBAA" ("" or null: the basemap's)}"##), C::new("map.reloadWebLayers", "Reload Web Layers", "View › Display", |_, _| { // The map view draws again when the tile cache's generation moves. crate::render::rustgis_tiles::cache::clear(); @@ -868,9 +868,26 @@ fn set_bearing(s: &mut Session, p: &Value) -> CmdResult { /// Shows or hides the map's graticule, and sets what it draws: a type or a coordinate system /// given shows it too. A coordinate system is for the measured grid, and refused (naming it) when -/// it can't be read or isn't projected. +/// it can't be read or isn't projected. Whether its lines go over the layers, and their color, +/// are set without showing or hiding it. fn graticule(s: &mut Session, p: &Value) -> CmdResult { use rustgis_map::graticule::GraticuleType; + let on_top = match p.get("onTop") { + None => None, + // As for the color: null puts the default back (under the layers). + Some(Value::Null) => Some(false), + Some(v) => Some(super::bool_value(v).ok_or_else(|| format!("onTop must be true or false, not {v}"))?), + }; + let color = match p.get("color") { + None => None, + Some(Value::Null) => Some(None), + Some(Value::String(c)) if c.trim().is_empty() => Some(None), + Some(v) => Some(Some( + v.as_str() + .and_then(rustgis_map::Rgba::from_hex) + .ok_or_else(|| format!("color must be #RRGGBB or #RRGGBBAA (\"\" or null for the basemap's), not {v}"))?, + )), + }; let kind = match p.get("type") { None | Some(Value::Null) => None, Some(Value::String(t)) => Some(GraticuleType::from_name(t).ok_or_else(|| { @@ -914,12 +931,32 @@ fn graticule(s: &mut Session, p: &Value) -> CmdResult { return Err(format!("crs is the measured grid's; the graticule is \"{}\" (give \"type\": \"measured\")", kind_after.code())); } let set = kind.is_some() || crs.is_some(); - m.graticule = super::b(p, "on").unwrap_or(if set { true } else { !m.graticule }); + // Only the lines' place or color given: shown or hidden as it was. + let styled = on_top.is_some() || color.is_some(); + m.graticule = super::b(p, "on").unwrap_or(if set { + true + } else if styled { + m.graticule + } else { + !m.graticule + }); m.graticule_type = kind_after; if let Some(c) = crs { m.graticule_crs = c; } - Ok(json!({"on": m.graticule, "type": m.graticule_type.code(), "crs": m.graticule_crs})) + if let Some(t) = on_top { + m.graticule_on_top = t; + } + if let Some(c) = color { + m.graticule_color = c; + } + Ok(json!({ + "on": m.graticule, + "type": m.graticule_type.code(), + "crs": m.graticule_crs, + "onTop": m.graticule_on_top, + "color": m.graticule_color.map(rustgis_map::Rgba::hex), + })) } fn basemap(s: &mut Session, p: &Value) -> CmdResult { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 7606a6587c..0fa7973be6 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -87,6 +87,9 @@ pub const CAPABILITIES: &[&str] = &[ "layout-element-background", SIZE_BY_CAPABILITY, "picture-markers", + "graticule-mgrs", + "graticule-on-top", + "graticule-color", "layout-element-ink", "layout-element-wrap", "layout-chart-data", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index fd0d0b6d9d..cdc7d8ed86 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -127,6 +127,9 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("tabulate-intersection-empty-zones", command_uses_tabulate_empty_zones), ("layout-element-background", command_uses_element_background), ("picture-markers", command_uses_picture_marker), + ("graticule-mgrs", command_draws_mgrs_graticule), + ("graticule-on-top", command_puts_graticule_on_top), + ("graticule-color", command_colors_graticule), ("layout-element-ink", command_uses_element_ink), ("layout-element-wrap", command_uses_element_wrap), ("layout-chart-data", command_uses_chart_data), @@ -136,6 +139,42 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-frame-border", command_uses_frame_border), ]; +/// A saved `map.graticule` that switches to the MGRS grid, its type read as the command reads it: +/// an older reader refuses the type, so the command would fail there. +fn command_draws_mgrs_graticule(id: &str, params: &Value) -> bool { + match id { + "map.graticule" => params + .get("type") + .and_then(Value::as_str) + .and_then(rustgis_map::graticule::GraticuleType::from_name) + .is_some_and(|t| t == rustgis_map::graticule::GraticuleType::Mgrs), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_draws_mgrs_graticule)), + _ => false, + } +} + +/// A saved `map.graticule` that sets whether the grid draws over the layers, or puts the default +/// back with `null`: an older reader ignores the key, and without `on`, `type` or `crs` it toggles +/// the grid where this one keeps it as it is, so any value needs it. +fn command_puts_graticule_on_top(id: &str, params: &Value) -> bool { + match id { + "map.graticule" => params.get("onTop").is_some(), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_puts_graticule_on_top)), + _ => false, + } +} + +/// A saved `map.graticule` that sets the grid's color, or puts the palette's back with `null` or +/// `""`: an older reader ignores the key, and without `on`, `type` or `crs` it toggles the grid +/// where this one keeps it as it is, so any value needs it. +fn command_colors_graticule(id: &str, params: &Value) -> bool { + match id { + "map.graticule" => params.get("color").is_some(), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_colors_graticule)), + _ => false, + } +} + /// A layout command that changes a map frame's border (#2557): an older reader warns that it /// ignores `border` and draws the default one. `null` only gives the default back, which an older /// reader's frames always have. @@ -441,12 +480,21 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static mut sized, mut pictures, mut zarr, - ) = (false, false, false, false, false, false, false, false, false, false, false); + mut mgrs, + mut on_top, + mut grid_color, + ) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false); let (mut offline_area_id, mut paper, mut native) = (false, false, false); for map in maps { offline_area_id |= map.offline_area_id.is_some(); // A blank basemap's paper colour (#2532), which an older reader would draw and save white. paper |= map.paper.is_some(); + // An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the + // project by name rather than failing to read the type. + mgrs |= map.graticule_type == rustgis_map::graticule::GraticuleType::Mgrs; + // Nor the graticule drawn over the layers or in a color of its own: it would save them away. + on_top |= map.graticule_on_top; + grid_color |= map.graticule_color.is_some(); if let Some(t) = &map.view.terrain { block |= t.block.is_some(); // A round block (#2318), which an older reader would draw and save as a box. @@ -482,6 +530,9 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (offline_area_id, "offline-map-area-id"), (paper, "blank-paper"), (native, super::NATIVE_COORDINATES), + (mgrs, "graticule-mgrs"), + (on_top, "graticule-on-top"), + (grid_color, "graticule-color"), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) @@ -564,6 +615,28 @@ mod tests { serde_json::from_slice(bytes).unwrap() } + /// A saved MGRS graticule drawn on top in a color of its own (#1042 piece 8) reads back as it + /// was, and saving names all three again; a map without them names none. + #[test] + fn graticule_mgrs_fixture_reads_its_grid() { + use rustgis_map::graticule::GraticuleType; + let fixture = Project::from_json(include_str!("../../../schema/fixtures/graticule_mgrs.rgis")).unwrap(); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["graticule-mgrs", "graticule-on-top", "graticule-color"])); + let map = &fixture.maps[0]; + assert_eq!(map.graticule_type, GraticuleType::Mgrs); + assert!(map.graticule && map.graticule_on_top); + assert_eq!(map.graticule_color.map(|c| (c.r(), c.g(), c.b(), c.a())), Some((48, 48, 48, 153))); + let reopened = Project::from_json(&saved.to_string()).unwrap(); + assert_eq!(serde_json::to_value(&reopened).unwrap(), saved); + let mut plain = fixture; + let map = &mut plain.maps[0]; + map.graticule_type = GraticuleType::Utm; + map.graticule_on_top = false; + map.graticule_color = None; + assert!(serde_json::to_value(&plain).unwrap().get("requires").is_none()); + } + /// A saved image marker reads back as the image it was, and saving names it again. #[test] fn picture_markers_fixture_reads_its_image() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 45548b2f8f..69f4b37238 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -14071,6 +14071,135 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { } } +/// An older RustGIS doesn't know the MGRS graticule (#1042 piece 8): a project showing it names +/// it among what it requires, so that reader refuses the project by name; other types need nothing. +#[test] +fn an_mgrs_graticule_is_required_by_name_in_the_saved_project() { + let mut s = world(); + s.run("map.graticule", &json!({"on": true, "type": "utm"})).unwrap(); + assert!(serde_json::to_value(&s.project).unwrap().get("requires").is_none()); + s.run("map.graticule", &json!({"on": true, "type": "mgrs"})).unwrap(); + assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["graticule-mgrs"])); + s.run("map.graticule", &json!({"type": "degrees"})).unwrap(); + assert!(serde_json::to_value(&s.project).unwrap().get("requires").is_none()); +} + +/// A saved task or script that sets whether the graticule is on top, or its color, names that among +/// what the project requires, so an older RustGIS refuses it rather than running it without the +/// key (and toggling the grid instead); one that sets neither names nothing. +#[test] +fn saved_graticule_settings_are_required_by_name() { + let s = world(); + let with_task = |params: Value| { + let mut project = s.project.clone(); + project.tasks = vec![ + serde_json::from_value(json!({"name": "Grid", "steps": [{"title": "Grid", "command": "map.graticule", "params": params}]})) + .unwrap(), + ]; + serde_json::to_value(&project).unwrap().get("requires").cloned() + }; + assert_eq!(with_task(json!({"onTop": true})), Some(json!(["graticule-on-top"]))); + assert_eq!(with_task(json!({"color": "#ff000080"})), Some(json!(["graticule-color"]))); + assert_eq!(with_task(json!({"onTop": true, "color": "#000000"})), Some(json!(["graticule-on-top", "graticule-color"]))); + // Any value, null included: an older reader would toggle the grid where this one keeps it, even + // for the defaults, and `onTop` reads "true" and 1 as true. + for on_top in [json!(null), json!(false), json!("true"), json!(1)] { + assert_eq!(with_task(json!({"onTop": on_top})), Some(json!(["graticule-on-top"])), "{on_top}"); + } + for color in [json!(null), json!(""), json!(" ")] { + assert_eq!(with_task(json!({"color": color})), Some(json!(["graticule-color"])), "{color}"); + } + for nothing in [json!({"type": "utm"}), json!({"on": false})] { + assert_eq!(with_task(nothing.clone()), None, "{nothing}"); + } + // In a script, too. + let mut project = s.project.clone(); + project.tasks = vec![ + serde_json::from_value( + json!({"name": "Script", "steps": [{"title": "Run", "command": "script.run", "params": {"script": "map.graticule {\"onTop\": true}"}}]}), + ) + .unwrap(), + ]; + assert_eq!(serde_json::to_value(&project).unwrap()["requires"], json!(["graticule-on-top"])); +} + +/// A saved command that switches the graticule to MGRS names the MGRS grid among what the project +/// requires, its type read as the command reads it; other types don't. +#[test] +fn saved_commands_switching_to_mgrs_require_it() { + let s = world(); + let with_step = |command: &str, params: Value| { + let mut project = s.project.clone(); + project.tasks = vec![ + serde_json::from_value(json!({"name": "Grid", "steps": [{"title": "Grid", "command": command, "params": params}]})).unwrap(), + ]; + serde_json::to_value(&project).unwrap().get("requires").cloned() + }; + for mgrs in ["mgrs", " MGRS ", "Mgrs"] { + assert_eq!(with_step("map.graticule", json!({"type": mgrs})), Some(json!(["graticule-mgrs"])), "{mgrs}"); + } + for other in [json!("utm"), json!("degrees"), json!("measured"), json!("ups"), json!(null), json!(1)] { + assert_eq!(with_step("map.graticule", json!({"type": other})), None, "{other}"); + } + let script = |line: &str| with_step("script.run", json!({"script": line})); + assert_eq!(script("map.graticule {\"type\": \"mgrs\"}"), Some(json!(["graticule-mgrs"]))); + assert_eq!(script("map.graticule {\"type\": \"utm\"}"), None); +} + +/// The graticule's lines over the layers, and their color (#1042): set without showing or hiding +/// it, reset to the basemap's with null or "", refused (naming the value) when not a true/false or +/// a #RRGGBB/#RRGGBBAA color with nothing changed; a project names each among what it requires +/// only when a map uses it, and keeps them. +#[test] +fn the_graticule_goes_on_top_in_a_color_of_its_own() { + let mut s = world(); + let on = s.map().graticule; + let r = s.run("map.graticule", &json!({"onTop": true, "color": "#ff000080"})).unwrap(); + assert_eq!((r["on"].clone(), r["onTop"].clone(), r["color"].clone()), (json!(on), json!(true), json!("#FF000080"))); + assert_eq!(s.map().graticule_color, Some(rustgis_map::Rgba::new(255, 0, 0, 128))); + let r = s.run("map.graticule", &json!({"color": "#00FF00"})).unwrap(); + assert_eq!((r["on"].clone(), r["onTop"].clone(), r["color"].clone()), (json!(on), json!(true), json!("#00FF00"))); + for (p, e) in [ + (json!({"onTop": "maybe"}), "onTop must be true or false, not \"maybe\""), + (json!({"onTop": [1]}), "onTop must be true or false, not [1]"), + (json!({"color": "red"}), "color must be #RRGGBB or #RRGGBBAA (\"\" or null for the basemap's), not \"red\""), + (json!({"color": "#12345"}), "color must be #RRGGBB or #RRGGBBAA"), + (json!({"color": 255}), "color must be #RRGGBB or #RRGGBBAA (\"\" or null for the basemap's), not 255"), + ] { + let got = s.run("map.graticule", &p).unwrap_err(); + assert!(got.starts_with(e), "{p}: {got}"); + } + // Unchanged by the refusals. + assert!(s.map().graticule_on_top); + assert_eq!(s.map().graticule_color, Some(rustgis_map::Rgba::rgb(0, 255, 0))); + assert_eq!(s.map().graticule_rgba(), rustgis_map::Rgba::rgb(0, 255, 0)); + // Saved, required by name, and back. + let v = serde_json::to_value(&s.project).unwrap(); + assert_eq!(v["requires"], json!(["graticule-on-top", "graticule-color"])); + let back = crate::Project::from_json(&v.to_string()).unwrap(); + assert!(back.map().graticule_on_top); + assert_eq!(back.map().graticule_color, Some(rustgis_map::Rgba::rgb(0, 255, 0))); + // Reset: under the layers, in the basemap's color; neither saved nor required. + let r = s.run("map.graticule", &json!({"onTop": false, "color": null})).unwrap(); + assert_eq!((r["onTop"].clone(), r["color"].clone()), (json!(false), json!(null))); + s.run("map.graticule", &json!({"color": "#123456"})).unwrap(); + s.run("map.graticule", &json!({"color": " "})).unwrap(); + // `onTop: null` puts the default back too, without showing or hiding the grid. + s.run("map.graticule", &json!({"onTop": true})).unwrap(); + let r = s.run("map.graticule", &json!({"onTop": null})).unwrap(); + assert_eq!((r["on"].clone(), r["onTop"].clone()), (json!(on), json!(false))); + assert_eq!(s.map().graticule_color, None); + assert_eq!(s.map().graticule_rgba(), s.map().palette().3); + assert_eq!(s.map().graticule, on); + let text = serde_json::to_string(&s.project).unwrap(); + assert!(!text.contains("graticule_on_top") && !text.contains("graticule_color") && !text.contains("\"requires\""), "{text}"); + // An older reader that knows neither refuses such a project by name. + let mut v = v; + v["requires"] = json!(["graticule-on-top", "graticule-color", "graticule-later"]); + let e = crate::Project::from_json(&v.to_string()).unwrap_err(); + assert!(e.contains("graticule-later"), "{e}"); +} + /// The graticule's type and the measured grid's coordinate system (#1042): a type or system given /// shows it; no parameters toggle it as before; a system that isn't projected, can't be read, or /// is given for another type is refused, naming it; a project keeps them, and one without them @@ -14082,15 +14211,25 @@ fn the_graticule_takes_a_type_and_a_measured_grids_system() { assert_eq!(s.map().graticule_type, GraticuleType::Degrees); s.run("map.graticule", &json!({"on": false})).unwrap(); let r = s.run("map.graticule", &json!({"type": "UTM"})).unwrap(); - assert_eq!(r, json!({"on": true, "type": "utm", "crs": null})); + assert_eq!(r, json!({"on": true, "type": "utm", "crs": null, "onTop": false, "color": null})); // No parameters: toggled, the type kept. s.run("map.graticule", &json!({})).unwrap(); assert!(!s.map().graticule && s.map().graticule_type == GraticuleType::Utm); let r = s.run("map.graticule", &json!({"type": "measured", "crs": " EPSG:2056 "})).unwrap(); - assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056"})); + assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056", "onTop": false, "color": null})); + // MGRS (#1042), named in any case, and kept with the project; it takes no system either. + let r = s.run("map.graticule", &json!({"type": " Mgrs "})).unwrap(); + // (The measured grid's system is kept for when it is picked again.) + assert_eq!(r, json!({"on": true, "type": "mgrs", "crs": "EPSG:2056", "onTop": false, "color": null})); + let back = crate::Project::from_json(&serde_json::to_string(&s.project).unwrap()).unwrap(); + assert_eq!(back.map().graticule_type, GraticuleType::Mgrs); + let got = s.run("map.graticule", &json!({"type": "mgrs", "crs": "EPSG:2056"})).unwrap_err(); + assert!(got.starts_with("crs is the measured grid's; the graticule is \"mgrs\""), "{got}"); + let r = s.run("map.graticule", &json!({"type": "measured", "crs": " EPSG:2056 "})).unwrap(); + assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056", "onTop": false, "color": null})); for (p, e) in [ - (json!({"type": "mgrs"}), "type must be one of degrees, measured, utm, not \"mgrs\""), - (json!({"type": 3}), "type must be one of \"degrees\", \"measured\", \"utm\", not 3"), + (json!({"type": "ups"}), "type must be one of degrees, measured, utm, mgrs, not \"ups\""), + (json!({"type": 3}), "type must be one of \"degrees\", \"measured\", \"utm\", \"mgrs\", not 3"), (json!({"crs": "EPSG:4326"}), "crs: EPSG:4326 is geographic"), (json!({"crs": "EPSG:4978"}), "crs: EPSG:4978 is geocentric"), (json!({"type": "utm", "crs": "EPSG:2056"}), "crs is the measured grid's; the graticule is \"utm\""), diff --git a/crates/engine/tests/project_save_roundtrip.rs b/crates/engine/tests/project_save_roundtrip.rs index ab46baf31b..0772c51742 100644 --- a/crates/engine/tests/project_save_roundtrip.rs +++ b/crates/engine/tests/project_save_roundtrip.rs @@ -126,7 +126,12 @@ fn step() -> impl Strategy { prop::sample::select(vec!["Albers Equal Area Conic +lat_1=29.5 +lat_2=45.5", "EPSG:3857", "EPSG:4326"]) .prop_map(|t| ("map.projection", json!({"type": t}))), (-180.0..180.0f64).prop_map(|b| ("map.setBearing", json!({"bearing": b}))), - prop::sample::select(vec!["degrees", "measured", "utm"]).prop_map(|t| ("map.graticule", json!({"on": true, "type": t}))), + ( + prop::sample::select(vec!["degrees", "measured", "utm", "mgrs"]), + any::(), + prop::sample::select(vec![Value::Null, json!("#FF0000"), json!("#00FF0080")]), + ) + .prop_map(|(t, top, c)| ("map.graticule", json!({"on": true, "type": t, "onTop": top, "color": c}))), (-180.0..180.0f64, -85.0..85.0f64, number()) .prop_map(|(x, y, s)| ("map.camera", json!({"lon": x, "lat": y, "scale": s * 1e5 + 1.0}))), name().prop_map(|n| ("map.new", json!({"name": n}))), diff --git a/crates/map/src/graticule.rs b/crates/map/src/graticule.rs index 59dcd823d3..ac2740773f 100644 --- a/crates/map/src/graticule.rs +++ b/crates/map/src/graticule.rs @@ -1,5 +1,6 @@ //! What the map's graticule draws (#1042): latitudes and longitudes, a measured grid of eastings -//! and northings in one projected system, or the UTM zones with each zone's own grid. +//! and northings in one projected system, the UTM zones with each zone's own grid, or the MGRS +//! grid with its grid zone designations and 100 km squares named. use serde::{Deserialize, Serialize}; @@ -16,10 +17,15 @@ pub enum GraticuleType { /// The UTM zones (WGS 84) and their latitude bands, with the Norway and Svalbard exceptions, /// and in each zone its own eastings and northings once few zones are in view. Utm, + /// The MGRS grid (NGA.STND.0037): the UTM zones and bands as grid zone designations, and in + /// each of a few in view its own grid at a power of ten that suits the scale (100 km to + /// 100 m), the 100 km lines heavier, named by grid zone designation or 100 km square. Nothing + /// is drawn in the polar areas (UPS) yet. + Mgrs, } impl GraticuleType { - pub const ALL: [GraticuleType; 3] = [GraticuleType::Degrees, GraticuleType::Measured, GraticuleType::Utm]; + pub const ALL: [GraticuleType; 4] = [GraticuleType::Degrees, GraticuleType::Measured, GraticuleType::Utm, GraticuleType::Mgrs]; /// The name a command takes. pub fn code(self) -> &'static str { @@ -27,6 +33,7 @@ impl GraticuleType { GraticuleType::Degrees => "degrees", GraticuleType::Measured => "measured", GraticuleType::Utm => "utm", + GraticuleType::Mgrs => "mgrs", } } @@ -36,6 +43,7 @@ impl GraticuleType { GraticuleType::Degrees => "Latitude and Longitude", GraticuleType::Measured => "Measured Grid", GraticuleType::Utm => "UTM Zones", + GraticuleType::Mgrs => "MGRS", } } @@ -67,7 +75,8 @@ mod tests { assert_eq!(GraticuleType::from_name(&t.code().to_uppercase()), Some(t)); } assert_eq!(GraticuleType::from_name(" utm "), Some(GraticuleType::Utm)); - assert_eq!(GraticuleType::from_name("mgrs"), None); + assert_eq!(GraticuleType::from_name("Mgrs"), Some(GraticuleType::Mgrs)); + assert_eq!(GraticuleType::from_name("ups"), None); } #[test] diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 7839d433b2..feec036014 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1837,13 +1837,20 @@ pub struct Map { pub bookmarks: Vec, #[serde(default = "yes")] pub graticule: bool, - /// What the graticule draws: latitudes and longitudes, a measured grid or the UTM zones. + /// What the graticule draws: latitudes and longitudes, a measured grid, the UTM zones or MGRS. #[serde(default, skip_serializing_if = "graticule::GraticuleType::is_degrees")] pub graticule_type: graticule::GraticuleType, /// A measured graticule's coordinate system (`EPSG:2056`, WKT or a PROJ string): none is the /// map's own when it is projected, else the UTM zone (WGS 84) at the view's centre. #[serde(default, skip_serializing_if = "Option::is_none")] pub graticule_crs: Option, + /// The graticule's lines drawn over the map's layers and web tile layers (just under the + /// labels), rather than with the basemap under them, where filled layers hide them. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub graticule_on_top: bool, + /// The graticule's color (with its opacity): none is the basemap palette's. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub graticule_color: Option, /// Flat map or 3D globe. #[serde(default)] pub projection: Projection, @@ -1985,6 +1992,8 @@ impl Map { graticule: true, graticule_type: graticule::GraticuleType::Degrees, graticule_crs: None, + graticule_on_top: false, + graticule_color: None, projection: Projection::WebMercator, popup_mode: PopupMode::Topmost, label_display: LabelDisplay::default(), @@ -3172,6 +3181,11 @@ impl Map { (grey, grey, Rgba::new(0, 0, 0, 0), grat) } + /// The graticule's color: the one set for it, else the basemap palette's. + pub fn graticule_rgba(&self) -> Rgba { + self.graticule_color.unwrap_or(self.palette().3) + } + /// The blank basemap's paper colour, when the map is on the blank basemap and has one: always /// opaque, a file's translucent one included (the paper is the backdrop: nothing shows through). pub fn blank_paper(&self) -> Option { @@ -3412,6 +3426,8 @@ impl Map { graticule: _, graticule_type: _, graticule_crs: _, + graticule_on_top: _, + graticule_color: _, projection: _, popup_mode: _, label_display: _, diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index a5595b33a9..bad16783fe 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -389,6 +389,8 @@ impl MapLook { graticule, graticule_type, graticule_crs, + graticule_on_top, + graticule_color, projection, popup_mode, label_display, @@ -419,6 +421,8 @@ impl MapLook { graticule: *graticule, graticule_type: *graticule_type, graticule_crs: graticule_crs.clone(), + graticule_on_top: *graticule_on_top, + graticule_color: *graticule_color, projection: projection.clone(), popup_mode: *popup_mode, label_display: *label_display, @@ -457,6 +461,8 @@ impl MapLook { graticule, graticule_type, graticule_crs, + graticule_on_top, + graticule_color, projection, popup_mode: _, label_display, @@ -483,6 +489,8 @@ impl MapLook { && *graticule == map.graticule && *graticule_type == map.graticule_type && *graticule_crs == map.graticule_crs + && *graticule_on_top == map.graticule_on_top + && *graticule_color == map.graticule_color && *projection == map.projection && *label_display == map.label_display && *label_lock == map.label_lock @@ -647,6 +655,13 @@ mod tests { assert!(!grouped.same(&MapLook::of(&map))); map.graticule = !map.graticule; assert!(!before.same(&MapLook::of(&map))); + // The grid drawn over the layers, or in a color of its own, draws differently too. + let gridded = MapLook::of(&map); + map.graticule_on_top = !map.graticule_on_top; + assert!(!gridded.same(&MapLook::of(&map)), "the grid over the layers"); + let on_top = MapLook::of(&map); + map.graticule_color = Some(crate::Rgba::rgb(51, 102, 153)); + assert!(!on_top.same(&MapLook::of(&map)), "the grid's own color"); // The blank basemap's paper colour (#2532) is the map's background. let white = MapLook::of(&map); map.paper = Some(Rgba([241, 234, 223, 255])); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 47b68864eb..c59803f435 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4300,7 +4300,7 @@ fn render_frame( }; // Basemap. - let (water, land, outline, grat) = map.palette(); + let (water, land, outline, _) = map.palette(); match &globe { Some(g) => globe_backdrop(pm.pixels(), g, water, space(view, map), view.pixels_per_point as f32), None if !gpu => pm.fill(tiny_skia::Color::from_rgba8(water.r(), water.g(), water.b(), 255)), @@ -4382,61 +4382,87 @@ fn render_frame( } } } - if cold && map.graticule && grat.a() > 0 { - let p = paint(grat, 1.0); - // A measured or UTM graticule's lines (#1042), else latitudes and longitudes. - let grid = mapgrid::lines(map, view); - let step = if view.camera.res > 8000.0 { - 30.0 - } else if view.camera.res > 2000.0 { - 15.0 - } else if view.camera.res > 400.0 { - 5.0 - } else { - 1.0 - }; - let (lat_max, lat_min) = if globe.is_some() { (90.0, -90.0) } else { (85.0, -85.0) }; - let lines = grid.unwrap_or_else(|| { - let mut lines = Vec::new(); - let mut lon = -180.0; - while lon <= 180.0 { - lines.push((0..=36).map(|i| Coord::new(lon, lat_min + (lat_max - lat_min) * i as f64 / 36.0)).collect::>()); - lon += step; - } - let mut lat = -90.0 + step; - while lat < 90.0 { - lines.push((0..=72).map(|i| Coord::new(-180.0 + i as f64 * 5.0, lat)).collect::>()); - lat += step; - } - lines - }); - let lines = if globe.is_some() { - lines - } else if custom { - // Parallels are cut at the map's edge like any line (#209). - match flat.project(&Geometry::Line(lines)) { - Geometry::Line(parts) => parts, - _ => Vec::new(), - } - } else { - lines.into_iter().map(|l| l.into_iter().map(lonlat_to_merc).collect()).collect() - }; - if gpu { - let mut e = Extent::EMPTY; - for l in &lines { - for c in l { - e.expand(*c); + // The graticule's lines: with the basemap, under the layers and web tile layers, or over them + // all (`graticule_on_top`), still under the labels. + let grat = map.graticule_rgba(); + macro_rules! draw_graticule { + () => {{ + if map.graticule && grat.a() > 0 { + let p = paint(grat, 1.0); + // A measured, UTM or MGRS graticule's lines (#1042), else latitudes and longitudes; the + // MGRS grid's grid zone designations and 100 km lines (`major`) are drawn heavier. + let (major, grid) = match mapgrid::lines(map, view) { + Some(g) => (g.major, Some(g.minor)), + None => (Vec::new(), None), + }; + let step = if view.camera.res > 8000.0 { + 30.0 + } else if view.camera.res > 2000.0 { + 15.0 + } else if view.camera.res > 400.0 { + 5.0 + } else { + 1.0 + }; + let (lat_max, lat_min) = if globe.is_some() { (90.0, -90.0) } else { (85.0, -85.0) }; + let lines = grid.unwrap_or_else(|| { + let mut lines = Vec::new(); + let mut lon = -180.0; + while lon <= 180.0 { + lines.push((0..=36).map(|i| Coord::new(lon, lat_min + (lat_max - lat_min) * i as f64 / 36.0)).collect::>()); + lon += step; + } + let mut lat = -90.0 + step; + while lat < 90.0 { + lines.push((0..=72).map(|i| Coord::new(-180.0 + i as f64 * 5.0, lat)).collect::>()); + lat += step; + } + lines + }); + let project = |lines: Vec>| -> Vec> { + if globe.is_some() { + lines + } else if custom { + // Parallels are cut at the map's edge like any line (#209). + match flat.project(&Geometry::Line(lines)) { + Geometry::Line(parts) => parts, + _ => Vec::new(), + } + } else { + lines.into_iter().map(|l| l.into_iter().map(lonlat_to_merc).collect()).collect() + } + }; + let (lines, major) = (project(lines), project(major)); + // The minor lines, then the major ones over them. An empty set (an MGRS view + // zoomed out has only major lines) draws nothing: no CPU image in the GPU scene. + for (lines, width) in [(lines, 0.6f32), (major, 1.2)] { + if lines.is_empty() { + continue; + } + if gpu { + let mut e = Extent::EMPTY; + for l in &lines { + for c in l { + e.expand(*c); + } + } + flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; + let tessellated = + !e.is_empty() && mesh::collect_graticule(&mut cmds, &lines, &e, grat, width, ctx.ppp, map_per_px).is_ok(); + if !tessellated { + ctx.line(&mut pm, &lines, &p, width); + cpu_dirty = true; + } + } else { + ctx.line(&mut pm, &lines, &p, width); + } } } - flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; - let tessellated = !e.is_empty() && mesh::collect_graticule(&mut cmds, &lines, &e, grat, ctx.ppp, map_per_px).is_ok(); - if !tessellated { - ctx.line(&mut pm, &lines, &p, 0.6); - cpu_dirty = true; - } - } else { - ctx.line(&mut pm, &lines, &p, 0.6); - } + }}; + } + // Under the layers, it's in the picture a warm frame starts from (see `frame_cache`). + if cold && !map.graticule_on_top { + draw_graticule!(); } // Web tile layers, at their places in the drawing order (#808): those under all the map's @@ -5947,6 +5973,14 @@ fn render_frame( if let Some(id) = below { draw_tiles!(Some(id)); } + if map.graticule_on_top { + draw_graticule!(); + // The grid's lines left as a picture (Lyon refused them) spoil a turned or tilted + // stand-in as a layer's would. + if pictureless && (cpu_dirty || holds_picture(&cmds)) { + return None; + } + } if let Some(plan) = cached.take() { frame_cache::keep(plan, captured, captured_alone); } @@ -6053,7 +6087,55 @@ fn render_frame( }; post::apply(pm.pixels(), &map.view.effects, vision, &lonlat); } - let labels = placed.labels; + let mut labels = placed.labels; + let mut label_layers = label_layers; + // The MGRS graticule's names (#1042), over the placed labels and apart from their collisions, + // with no layer of their own in a recording, in the graticule's color made opaque. A tilted + // view's bands draw none: their places would repeat from band to band. Paused labels pause + // them too (and so drapes and tilt patches, drawn paused, leave them out). + if map.graticule && grat.a() > 0 && !map.label_display.paused && matches!(labels_to, Labels::Own | Labels::Turned(_)) { + let color = Rgba::rgb(grat.r(), grat.g(), grat.b()); + let measure = |t: &str| text::measure(t, mapgrid::LABEL_PT, false); + for (text, x, y) in mapgrid::labels(map, view, measure) { + // Into the turned view's screen, as the placed labels are, and only a name all of + // which shows there: the north-up frame reaches past the turned view's edges. + let (x, y) = match turned { + Some(to) => { + let (sx, sy) = to.to_screen(view.camera.to_map(f64::from(x), f64::from(y), view.width, view.height)); + let (hw, hh) = mapgrid::label_reach(measure(&text)); + if !(hw <= sx && sx <= to.width - hw && hh <= sy && sy <= to.height - hh) { + continue; + } + (sx as f32, sy as f32) + } + None => (x, y), + }; + labels.push(PlacedLabel { + text, + x, + y, + size: mapgrid::LABEL_PT, + color, + halo: Some(halo_for(color)), + halo_width: None, + bold: false, + icon: None, + align: 0.0, + framed: false, + italic: false, + spacing: 0.0, + font: None, + line_align: TextAlign::Center, + angle: None, + collide: Default::default(), + glyphs: Vec::new(), + background: None, + }); + if pm.is_recording() { + label_layers.push((u32::MAX, String::new())); + } + } + } let attribution = tile_out.attribution; let tiles_pending = tile_out.pending; let tile_errors = tile_out.errors; @@ -9236,6 +9318,165 @@ mod tests { assert!(!world().is_empty()); } + /// The MGRS graticule's names (#1042) come with the frame's placed labels, after them, in the + /// graticule's color with a halo, on a turned view too; another graticule has none, nor does + /// a hidden one. + #[test] + fn the_mgrs_graticule_names_come_with_the_labels() { + let mut m = Map::new("Map"); + m.graticule_type = rustgis_map::graticule::GraticuleType::Mgrs; + let camera = Camera { center: lonlat_to_merc(Coord::new(14.5, 48.2)), res: 500.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; + let grid = |m: &mut Map, view: &View| -> Vec { + render(m, view).unwrap().labels.into_iter().filter(|l| l.size == mapgrid::LABEL_PT && l.halo.is_some()).collect() + }; + let named = grid(&mut m, &view); + assert!(named.iter().any(|l| l.text == "33U VP"), "{:?}", named.iter().map(|l| &l.text).collect::>()); + let (.., grat) = m.palette(); + assert!(named.iter().all(|l| (l.color.r(), l.color.g(), l.color.b(), l.color.a()) == (grat.r(), grat.g(), grat.b(), 255))); + let turned = View { camera: Camera { bearing: 30.0, ..camera }, ..view }; + assert!(!grid(&mut m, &turned).is_empty()); + m.graticule_type = rustgis_map::graticule::GraticuleType::Utm; + assert!(grid(&mut m, &view).is_empty()); + m.graticule_type = rustgis_map::graticule::GraticuleType::Mgrs; + m.graticule = false; + assert!(grid(&mut m, &view).is_empty()); + } + + /// The MGRS names pause with the labels; on a turned view, a name is kept only when all of it + /// shows, never cut at the view's edge. + #[test] + fn mgrs_names_pause_and_keep_within_a_turned_view() { + let mut m = Map::new("Map"); + m.graticule_type = rustgis_map::graticule::GraticuleType::Mgrs; + let camera = Camera { center: lonlat_to_merc(Coord::new(14.5, 48.2)), res: 500.0, bearing: 30.0, pitch: 0.0 }; + let view = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; + let grid = |m: &mut Map, view: &View| -> Vec { + render(m, view).unwrap().labels.into_iter().filter(|l| l.size == mapgrid::LABEL_PT && l.halo.is_some()).collect() + }; + // Views over several places, so some names fall near the turned view's edges. + for i in 0..12 { + let at = Coord::new(12.0 + 0.37 * f64::from(i), 47.0 + 0.23 * f64::from(i)); + let v = View { camera: Camera { center: lonlat_to_merc(at), ..camera }, ..view }; + let named = grid(&mut m, &v); + assert!(!named.is_empty()); + for l in &named { + let hw = f64::from(text::measure(&l.text, mapgrid::LABEL_PT, false)) / 2.0; + let hh = f64::from(mapgrid::LABEL_PT) * 1.33 * 1.2 / 2.0; + let (x, y) = (f64::from(l.x), f64::from(l.y)); + assert!(x - hw >= 0.0 && x + hw <= v.width && y - hh >= 0.0 && y + hh <= v.height, "{} at {x}, {y}", l.text); + } + } + m.label_display.paused = true; + for v in [view, View { camera: Camera { bearing: 0.0, ..camera }, ..view }] { + assert!(grid(&mut m, &v).is_empty()); + } + } + + /// The graticule's lines are drawn with the basemap, so an opaque filled layer hides them, + /// unless they are on top (over the layers, under the labels), in every type; a color set for + /// them is used, with its opacity, and the MGRS names take it opaque. On the GPU the lines' + /// meshes come before the layer's, or after it when on top. + #[test] + fn the_graticule_draws_over_the_layers_when_on_top_in_its_own_color() { + use rustgis_map::graticule::GraticuleType; + let mut m = Map::new("Map"); + let id = square_layer(&mut m, "cover", -40.0, -40.0, 80.0); + let red = Rgba::rgb(255, 0, 0); + if let Some(l) = m.layer_mut(id) { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill: red, stroke_width: 0.0, ..l.symbol(0) }); + } + // Lines through the view's center whatever the step, at four pixels a point so that the + // thinnest (0.6 pt) has pixels it covers whole. + let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 6000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 100.0, height: 75.0, pixels_per_point: 4.0, camera, sky: false }; + let pixels = |m: &mut Map| -> Vec<[u8; 4]> { + render(m, &view) + .unwrap() + .pixmap + .pixels() + .iter() + .map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect() + }; + let not_red = |px: &[[u8; 4]]| px.iter().filter(|p| p[..3] != [255, 0, 0]).count(); + // Under the layer: all of it the layer's fill, the default grid as much as a set one. + assert_eq!(not_red(&pixels(&mut m)), 0); + m.graticule_color = Some(Rgba::rgb(0, 0, 255)); + assert_eq!(not_red(&pixels(&mut m)), 0); + // On top: the lines over the fill, in their color. + m.graticule_on_top = true; + for t in GraticuleType::ALL { + m.graticule_type = t; + let px = pixels(&mut m); + assert!(px.contains(&[0, 0, 255, 255]), "{t:?}"); + } + m.graticule_type = GraticuleType::Degrees; + // The basemap's color when none is set, now seen over the fill too. + m.graticule_color = None; + assert!(not_red(&pixels(&mut m)) > 0); + // A color's opacity is kept: half see-through blue over red. + m.graticule_color = Some(Rgba::new(0, 0, 255, 128)); + let px = pixels(&mut m); + assert!(px.iter().any(|p| p[0] > 100 && p[0] < 160 && p[2] > 100 && p[2] < 160), "half blue over red"); + assert!(!px.contains(&[0, 0, 255, 255])); + // Hidden: none either way. + m.graticule = false; + assert_eq!(not_red(&pixels(&mut m)), 0); + m.graticule = true; + // The MGRS names in the set color, made opaque. + m.graticule_type = GraticuleType::Mgrs; + let near = View { camera: Camera { center: lonlat_to_merc(Coord::new(14.5, 48.2)), res: 500.0, ..camera }, ..view }; + let named: Vec = + render(&mut m, &near).unwrap().labels.into_iter().filter(|l| l.size == mapgrid::LABEL_PT && l.halo.is_some()).collect(); + assert!(!named.is_empty() && named.iter().all(|l| l.color == Rgba::rgb(0, 0, 255))); + // On the GPU: the grid's mesh (its color) after the layer's when on top, before it when not. + m.graticule_type = GraticuleType::Degrees; + m.graticule_color = Some(Rgba::rgb(0, 0, 255)); + let blue = [0.0f32, 0.0, 1.0, 1.0]; + for on_top in [false, true] { + m.graticule_on_top = on_top; + let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &view, Backend::Gpu) else { panic!("gpu scene") }; + let meshes: Vec = scene + .cmds + .iter() + .filter_map(|c| match c { + gpu_scene::DrawCmd::Mesh { vertices, .. } => Some(vertices.iter().any(|v| v.color == blue)), + _ => None, + }) + .collect(); + let (grid, layer) = (meshes.iter().position(|g| *g), meshes.iter().rposition(|g| !*g)); + let (Some(grid), Some(layer)) = (grid, layer) else { panic!("{meshes:?}") }; + assert_eq!(grid > layer, on_top, "{meshes:?}"); + } + } + + /// An MGRS view at the 100 km step has major lines only; on the GPU its empty set of minor + /// lines adds no CPU image to the scene, under the layers or on top of them. + #[test] + fn an_mgrs_grid_of_major_lines_only_adds_no_image_on_the_gpu() { + let mut m = Map::new("Map"); + m.graticule_type = rustgis_map::graticule::GraticuleType::Mgrs; + let camera = Camera { center: lonlat_to_merc(Coord::new(14.5, 48.2)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; + let grid = mapgrid::lines(&m, &view).unwrap(); + assert!(grid.minor.is_empty() && !grid.major.is_empty(), "{} minor, {} major", grid.minor.len(), grid.major.len()); + let images = |m: &mut Map| { + let Some(RenderOutput::Gpu(scene)) = render_backend(m, &view, Backend::Gpu) else { panic!("gpu scene") }; + scene.cmds.iter().filter(|c| matches!(c, gpu_scene::DrawCmd::Image { .. })).count() + }; + m.graticule = false; + let without = images(&mut m); + m.graticule = true; + for on_top in [false, true] { + m.graticule_on_top = on_top; + assert_eq!(images(&mut m), without, "on top: {on_top}"); + } + } + #[test] fn a_selected_text_graphic_is_framed_with_its_label() { let mut m = Map::new("Map"); diff --git a/crates/render/src/mapgrid.rs b/crates/render/src/mapgrid.rs index 0fa7c97fc5..1c8ed57b4c 100644 --- a/crates/render/src/mapgrid.rs +++ b/crates/render/src/mapgrid.rs @@ -1,9 +1,13 @@ -//! The lines of the map's measured and UTM graticules (#1042), in longitude/latitude for the +//! The lines of the map's measured, UTM and MGRS graticules (#1042), in longitude/latitude for the //! graticule's drawing to project like its latitudes and longitudes. A measured grid is a layout's //! measured grid (#1012) over the view; the UTM one draws the zones and latitude bands, and in each -//! zone in view its own eastings and northings. +//! zone in view its own eastings and northings. The MGRS one (NGA.STND.0037) draws the same zones +//! and bands as grid zone designations, each one's grid at a power of ten that suits the scale, and +//! names the grid zone designations or the 100 km squares in view. -use rustgis_geom::utm::{UTM_MAX_LAT, UTM_MIN_LAT, band_latitudes, zone_longitudes}; +use rustgis_geom::utm::{ + UTM_MAX_LAT, UTM_MIN_LAT, band_latitudes, from_utm, latitude_band, square_letters, to_utm_in_zone, utm_zone, zone_longitudes, +}; use rustgis_geom::{Coord, Extent}; use rustgis_map::Map; use rustgis_map::globe::Globe; @@ -23,22 +27,48 @@ const MAX_GRIDDED_CELLS: usize = 8; /// The points a meridian or a parallel is drawn with, per degree. const PER_DEGREE: f64 = 2.0; -/// The graticule's lines in longitude/latitude for a measured or UTM graticule; `None` for +/// The side of an MGRS 100 km square, in meters: the MGRS grid's coarsest step. +const SQUARE: f64 = 100_000.0; +/// The MGRS grid's finest step, in meters. +const MGRS_FINEST: f64 = 100.0; +/// The most grid zone designations in view whose grid is drawn finer than 100 km: four meet at a +/// corner; past them the view is wide enough for 100 km lines. +const FEW_CELLS: usize = 4; +/// The size of the MGRS graticule's labels, in points (as a layout's MGRS square labels). +pub(crate) const LABEL_PT: f32 = 10.0; +/// A label's height in points: a line of [`LABEL_PT`] text. +const LABEL_H: f64 = LABEL_PT as f64 * 1.33 * 1.2; +/// The places across and down a 100 km square (and half as many across a grid zone designation) +/// whose middle on the screen places its label. +const LABEL_SAMPLES: u32 = 8; +/// The most 100 km squares of one grid zone designation looked at for names in one view. +const MAX_SQUARES: i64 = 400; + +/// A graticule's lines in longitude/latitude, in two weights: the MGRS grid's grid zone +/// designations and 100 km lines are `major`, drawn heavier; every other line is `minor`. +#[derive(Debug, Default)] +pub(crate) struct GridLines { + pub(crate) major: Vec>, + pub(crate) minor: Vec>, +} + +/// The graticule's lines in longitude/latitude for a measured, UTM or MGRS graticule; `None` for /// latitudes and longitudes, which the graticule draws itself. They cover the view and the margin /// around it the GPU moves a frame's meshes within while panning ([`crate::GPU_CULL_MARGIN`]), at /// the step the view itself suits. -pub(crate) fn lines(map: &Map, view: &View) -> Option>> { +pub(crate) fn lines(map: &Map, view: &View) -> Option { if map.graticule_type == GraticuleType::Degrees { return None; } let globe = map.projection.is_globe().then(|| Globe::new(&view.camera, view.width, view.height)); let (shown, around) = (in_view(map, view, globe.as_ref(), 0.0), in_view(map, view, globe.as_ref(), crate::GPU_CULL_MARGIN)); let center = at(map, view, globe.as_ref(), view.width / 2.0, view.height / 2.0).or_else(|| shown.get(shown.len() / 2).copied()); - let Some(center) = center else { return Some(Vec::new()) }; + let Some(center) = center else { return Some(GridLines::default()) }; Some(match map.graticule_type { - GraticuleType::Degrees => Vec::new(), - GraticuleType::Measured => measured(map, center, &shown, &around), - GraticuleType::Utm => utm(center, &shown, &around), + GraticuleType::Degrees => GridLines::default(), + GraticuleType::Measured => GridLines { minor: measured(map, center, &shown, &around), major: Vec::new() }, + GraticuleType::Utm => zones(center, &shown, &around, false), + GraticuleType::Mgrs => zones(center, &shown, &around, true), }) } @@ -68,14 +98,33 @@ fn in_view(map: &Map, view: &View, globe: Option<&Globe>, margin: f64) -> Vec Option { +/// How far the places `shown` reach across or down, the more of the two, in `tr`'s system. +fn span_over(tr: &rustgis_data::raster::Transformer, shown: &[Coord]) -> Option { let mut m = Extent::EMPTY; for c in shown.iter().filter_map(|c| tr.from_lonlat(*c)) { m.expand(c); } - (!m.is_empty() && m.width().is_finite() && m.height().is_finite()) - .then(|| nice_step(m.width().max(m.height()), rustgis_map::layout::MIN_MEASURED_STEP)) + (!m.is_empty() && m.width().is_finite() && m.height().is_finite()).then(|| m.width().max(m.height())) +} + +/// The step that draws about eight lines across the places `shown`, in `tr`'s system. +fn step_over(tr: &rustgis_data::raster::Transformer, shown: &[Coord]) -> Option { + span_over(tr, shown).map(|span| nice_step(span, rustgis_map::layout::MIN_MEASURED_STEP)) +} + +/// The MGRS grid's step for a view `span` meters across (the more of across and down) showing +/// `cells` grid zone designations: the power of ten, from 100 m to 100 km, that draws between +/// three and thirty lines across it (NGA.STND.0037 asks for a power of ten that suits the scale); +/// 100 km while more than [`FEW_CELLS`] grid zone designations show. +fn mgrs_step(span: f64, cells: usize) -> f64 { + if cells > FEW_CELLS { + return SQUARE; + } + let (finest, coarsest) = (MGRS_FINEST.log10(), SQUARE.log10()); + let power = (span / 3.0).log10().floor(); + // (A view of no width, or a span that isn't a number: the finest step.) + let power = if power.is_nan() { finest } else { power.clamp(finest, coarsest) }; + 10f64.powi(power as i32) } /// A measured grid over the view and around it: the layout's measured grid in the map's graticule @@ -113,49 +162,70 @@ fn extents(places: &[Coord]) -> Vec { vec![e] } -/// The UTM zones and latitude bands in view and around it, and in each of a few zones in view its -/// eastings and northings, one step apart in all of them (the step the view suits in the zone at -/// its centre). +/// Every UTM zone-and-band cell (grid zone designation): its zone, band, and longitudes and +/// latitudes, with the Norway and Svalbard exceptions. +fn cells() -> impl Iterator { + BANDS.chars().flat_map(|band| { + (1..=60u8).filter_map(move |zone| { + let (south, north) = band_latitudes(band)?; + let (west, east) = zone_longitudes(zone, band)?; + Some((zone, band, Extent { min_x: west, min_y: south, max_x: east, max_y: north })) + }) + }) +} + +/// The UTM graticule's lines (all of them minor; see [`zones`]). +#[cfg(test)] fn utm(center: Coord, shown: &[Coord], around: &[Coord]) -> Vec> { + zones(center, shown, around, false).minor +} + +/// The UTM zones and latitude bands in view and around it, and in each of a few zones in view its +/// own grid, one step apart in all of them, cut at the zone's edges. For UTM (`mgrs` false) the +/// step is the one the view suits in the zone at its center, and every line is minor; for MGRS a +/// power of ten ([`mgrs_step`]), with the zones' edges and the 100 km lines major. +fn zones(center: Coord, shown: &[Coord], around: &[Coord], mgrs: bool) -> GridLines { + let mut out = GridLines::default(); let parts = extents(around); if parts.is_empty() { - return Vec::new(); + return out; } let has_lon = |lon: f64, south: f64, north: f64| parts.iter().any(|e| e.min_x <= lon && lon <= e.max_x && e.min_y <= north && south <= e.max_y); - let mut lines = Vec::new(); + let edges = if mgrs { &mut out.major } else { &mut out.minor }; + // (Made once a frame: the map redraws often.) + let all: Vec<(u8, char, Extent)> = cells().collect(); // Each zone's western edge within each band, and the last zone's eastern one at 180°, so the - // Norway and Svalbard zones are drawn as they are. - let mut cells = Vec::new(); - for band in BANDS.chars() { - let Some((south, north)) = band_latitudes(band) else { continue }; - for zone in 1..=60u8 { - let Some((west, east)) = zone_longitudes(zone, band) else { continue }; - cells.push((zone, band, Extent { min_x: west, min_y: south, max_x: east, max_y: north })); - if has_lon(west, south, north) { - lines.push(meridian(west, south, north)); + // Norway and Svalbard zones are drawn as they are. (`cells` gives them band by band.) + for band_cells in all.chunk_by(|a, b| a.1 == b.1) { + let Some((south, north)) = band_cells.first().map(|(_, _, c)| (c.min_y, c.max_y)) else { continue }; + for (_, _, cell) in band_cells { + if has_lon(cell.min_x, south, north) { + edges.push(meridian(cell.min_x, south, north)); } } if has_lon(180.0, south, north) { - lines.push(meridian(180.0, south, north)); + edges.push(meridian(180.0, south, north)); } } // The bands' edges, and the zones' southern and northern limits. - let edges = BANDS.chars().filter_map(|b| band_latitudes(b).map(|(south, _)| south)).chain([UTM_MAX_LAT]); - for lat in edges { + let lats = BANDS.chars().filter_map(|b| band_latitudes(b).map(|(south, _)| south)).chain([UTM_MAX_LAT]); + for lat in lats { for e in parts.iter().filter(|e| e.min_y <= lat && lat <= e.max_y) { - lines.push(parallel(lat, e.min_x.max(-180.0), e.max_x.min(180.0))); + edges.push(parallel(lat, e.min_x.max(-180.0), e.max_x.min(180.0))); } } // Eastings and northings when few zone-and-band cells are in the view itself (not counting // the margin, so they don't come and go as it pans), drawn over the margin too. let seen_parts = extents(shown); - let seen_cells = cells.iter().filter(|(_, _, c)| seen_parts.iter().any(|e| overlaps(c, e))).count(); + let seen_cells = all.iter().filter(|(_, _, c)| seen_parts.iter().any(|e| overlaps(c, e))).count(); if seen_cells == 0 || seen_cells > MAX_GRIDDED_CELLS { - return lines; + return out; } - let in_view: Vec<_> = cells.into_iter().filter_map(|(z, b, c)| parts.iter().find(|e| overlaps(&c, e)).map(|e| (z, b, c, *e))).collect(); - let Some(step) = zone_transformer(center).and_then(|tr| step_over(&tr, shown)) else { return lines }; + let in_view: Vec<_> = all.iter().filter_map(|&(z, b, c)| parts.iter().find(|e| overlaps(&c, e)).map(|e| (z, b, c, *e))).collect(); + let step = zone_transformer(center) + .and_then(|tr| if mgrs { span_over(&tr, shown).map(|span| mgrs_step(span, seen_cells)) } else { step_over(&tr, shown) }); + let Some(step) = step else { return out }; for (zone, band, cell, e) in in_view { let north = band >= 'N'; let epsg = if north { 32_600 } else { 32_700 } + u32::from(zone); @@ -168,21 +238,191 @@ fn utm(center: Coord, shown: &[Coord], around: &[Coord]) -> Vec> { max_x: cell.max_x.min(e.max_x), max_y: cell.max_y.min(e.max_y), }; - let frame: Vec = (0..=8) - .flat_map(|i| { - let t = f64::from(i) / 8.0; - let (x, y) = (part.min_x + part.width() * t, part.min_y + part.height() * t); - [Coord::new(x, part.min_y), Coord::new(x, part.max_y), Coord::new(part.min_x, y), Coord::new(part.max_x, y)] - }) - .collect(); + let frame = frame_of(&part); let g = Grid { kind: GridKind::Measured, step, labels: false, ..Grid::default() }; let mut zone_lines = Vec::new(); measured_lines(&g, &tr, &frame, false, &mut zone_lines); - for (pts, _, _) in zone_lines { - lines.extend(clip(&pts, &cell)); + for (pts, _, easting) in zone_lines { + // An MGRS line at a whole 100 km (its first point's easting or northing) bounds squares. + let value = pts.first().and_then(|c| tr.from_lonlat(*c)).map(|p| if easting { p.x } else { p.y }); + let major = mgrs && value.is_some_and(|v| (v - (v / SQUARE).round() * SQUARE).abs() < 1.0); + let to = if major { &mut out.major } else { &mut out.minor }; + to.extend(clip(&pts, &cell)); + } + } + out +} + +/// The MGRS graticule's labels on `view` (text, and its center in the view's points), none for +/// another type. Zoomed out, or while the 100 km squares are too small on the screen to name, each +/// grid zone designation in view is named (`33U`) at the middle of what shows of it; zoomed in, +/// each 100 km square of each one, by its letters (`VP`), with its grid zone designation (`33U VP`) +/// when more than one is in view. A label goes only where its corners, edge middles and center all +/// stay within its zone and square and the view (a sample, [`label_fits`]), so a zone or square cut +/// too small isn't named. Nothing is named in the polar +/// areas (UPS). `width` measures a text across in points at [`LABEL_PT`]. +pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec<(String, f32, f32)> { + if map.graticule_type != GraticuleType::Mgrs { + return Vec::new(); + } + let globe = map.projection.is_globe().then(|| Globe::new(&view.camera, view.width, view.height)); + let globe = globe.as_ref(); + let (w, h) = (view.width, view.height); + let on_view = |(x, y): (f64, f64)| (0.0..=w).contains(&x) && (0.0..=h).contains(&y); + // Where a place is drawn, on the view or off it (on a globe, only on its near side). + let project = |c: Coord| -> Option<(f64, f64)> { + let s = match globe { + Some(g) => g.forward(c)?, + None => view.to_screen(map.to_map(c)?), + }; + (s.0.is_finite() && s.1.is_finite()).then_some(s) + }; + // Where a place is on the view, if it is on it. + let screen = |c: Coord| project(c).filter(|s| on_view(*s)); + let place = |x: f64, y: f64| at(map, view, globe, x, y); + let shown = in_view(map, view, globe, 0.0); + let parts = extents(&shown); + let seen: Vec<(u8, char, Extent)> = cells().filter(|(_, _, c)| parts.iter().any(|e| overlaps(c, e))).collect(); + if seen.is_empty() { + return Vec::new(); + } + // A 100 km square's side on the screen, from a kilometer's, at the view's center or else the + // first place in view in a grid zone designation (a view centered past 84° N still shows + // band X). + let square_pt = place(w / 2.0, h / 2.0).into_iter().chain(shown.iter().copied()).find_map(|c| { + let &(zone, band, _) = seen.iter().find(|(_, _, cell)| cell.contains(c))?; + let north = band >= 'N'; + let (e, n) = to_utm_in_zone(c, zone, north)?; + let (sx, sy) = screen(c)?; + let side = |p: Option| p.and_then(project).map(|(x, y)| (x - sx).hypot(y - sy) * SQUARE / 1000.0); + Some(side(from_utm(zone, north, e + 1000.0, n))?.min(side(from_utm(zone, north, e, n + 1000.0))?)) + }); + // Squares named once the 100 km lines are drawn and a square is three labels tall. + let squares = seen.len() <= MAX_GRIDDED_CELLS && square_pt.is_some_and(|s| s >= 3.0 * LABEL_H); + // With more than one grid zone designation reaching into the view, a square's name carries + // its own: every named square is in one of the `seen` cells. + let one_gzd = seen.len() <= 1; + let mut out: Vec<(String, f32, f32)> = Vec::new(); + let mut named = std::collections::BTreeSet::new(); + for (zone, band, cell) in seen { + let north = band >= 'N'; + let gzd = format!("{zone:02}{band}"); + let in_cell = |c: Coord| utm_zone(c) == Some(zone) && latitude_band(c.y) == Some(band); + for e in parts.iter().filter(|e| overlaps(&cell, e)) { + let part = Extent { + min_x: cell.min_x.max(e.min_x), + min_y: cell.min_y.max(e.min_y), + max_x: cell.max_x.min(e.max_x), + max_y: cell.max_y.min(e.max_y), + }; + if !squares { + let samples = grid_of(LABEL_SAMPLES / 2, part.min_x, part.min_y, part.max_x, part.max_y).filter(|c| in_cell(*c)); + let Some((x, y)) = middle(samples.filter_map(&screen)) else { continue }; + let fits = |c: Coord| in_cell(c); + if !named.contains(&(zone, band, 0, 0)) && label_fits(&gzd, (x, y), &width, on_view, place, fits) { + named.insert((zone, band, 0, 0)); + out.push((gzd.clone(), x as f32, y as f32)); + } + continue; + } + // The squares the part reaches, by its edges' eastings and northings in the zone. + let mut m = Extent::EMPTY; + for c in frame_of(&part) { + if let Some((x, y)) = to_utm_in_zone(c, zone, north) { + m.expand(Coord::new(x, y)); + } + } + if m.is_empty() { + continue; + } + let (pad_x, pad_y) = (m.width() * 0.01, m.height() * 0.01); + let (e0, e1) = (((m.min_x - pad_x) / SQUARE).floor() as i64, ((m.max_x + pad_x) / SQUARE).floor() as i64); + let (n0, n1) = (((m.min_y - pad_y) / SQUARE).floor() as i64, ((m.max_y + pad_y) / SQUARE).floor() as i64); + if (e1 - e0 + 1).saturating_mul(n1 - n0 + 1) > MAX_SQUARES { + continue; + } + for (ie, inn) in (e0..=e1).flat_map(|ie| (n0..=n1).map(move |inn| (ie, inn))) { + let (se, sn) = (ie as f64 * SQUARE, inn as f64 * SQUARE); + let Some((column, row)) = square_letters(zone, se + SQUARE / 2.0, sn + SQUARE / 2.0) else { continue }; + // What of the square the part reaches, sampled in the zone's grid. + let (x0, x1) = (se.max(m.min_x - pad_x), (se + SQUARE).min(m.max_x + pad_x)); + let (y0, y1) = (sn.max(m.min_y - pad_y), (sn + SQUARE).min(m.max_y + pad_y)); + if x0 >= x1 || y0 >= y1 { + continue; + } + let samples = + grid_of(LABEL_SAMPLES, x0, y0, x1, y1).filter_map(|p| from_utm(zone, north, p.x, p.y)).filter(|c| in_cell(*c)); + let Some((x, y)) = middle(samples.filter_map(&screen)) else { continue }; + let text = if one_gzd { format!("{column}{row}") } else { format!("{gzd} {column}{row}") }; + let fits = |c: Coord| { + in_cell(c) + && to_utm_in_zone(c, zone, north) + .is_some_and(|(x, y)| (x / SQUARE).floor() as i64 == ie && (y / SQUARE).floor() as i64 == inn) + }; + if !named.contains(&(zone, band, ie, inn)) && label_fits(&text, (x, y), &width, on_view, place, fits) { + named.insert((zone, band, ie, inn)); + out.push((text, x as f32, y as f32)); + } + } } } - lines + out +} + +/// `n` places across and down a box, at the middles of its cells. +fn grid_of(n: u32, x0: f64, y0: f64, x1: f64, y1: f64) -> impl Iterator { + (0..n).flat_map(move |i| { + (0..n).map(move |j| { + let (ti, tj) = ((f64::from(i) + 0.5) / f64::from(n), (f64::from(j) + 0.5) / f64::from(n)); + Coord::new(x0 + (x1 - x0) * ti, y0 + (y1 - y0) * tj) + }) + }) +} + +/// A longitude/latitude box's edges, eight points a side. +fn frame_of(b: &Extent) -> Vec { + (0..=8) + .flat_map(|i| { + let t = f64::from(i) / 8.0; + let (x, y) = (b.min_x + b.width() * t, b.min_y + b.height() * t); + [Coord::new(x, b.min_y), Coord::new(x, b.max_y), Coord::new(b.min_x, y), Coord::new(b.max_x, y)] + }) + .collect() +} + +/// The middle of points on the screen; `None` for none. +fn middle(points: impl Iterator) -> Option<(f64, f64)> { + let (mut sx, mut sy, mut n) = (0.0, 0.0, 0u32); + for (x, y) in points { + (sx, sy, n) = (sx + x, sy + y, n + 1); + } + (n > 0).then(|| (sx / f64::from(n), sy / f64::from(n))) +} + +/// Whether a label `text` centered at `(x, y)` (points), with a little room around it, lies on the +/// view (`on_view`) and over the place it names (`fits`, for the places under its corners, its +/// edges' middles and its center, as `place` finds them). +fn label_fits( + text: &str, + (x, y): (f64, f64), + width: impl Fn(&str) -> f32, + on_view: impl Fn((f64, f64)) -> bool, + place: impl Fn(f64, f64) -> Option, + fits: impl Fn(Coord) -> bool, +) -> bool { + let (hw, hh) = label_reach(width(text)); + [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (0.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)].iter().all( + |&(kx, ky)| { + let p = (x + kx * hw, y + ky * hh); + on_view(p) && place(p.0, p.1).is_some_and(&fits) + }, + ) +} + +/// How far a label `width` points across reaches from its center, across and down (points), with +/// a little room around it. +pub(crate) fn label_reach(width: f32) -> (f64, f64) { + (f64::from(width) / 2.0 + 2.0, LABEL_H / 2.0 + 2.0) } /// The transformer of the UTM zone at `c` (by its 6° zone and hemisphere), made once a code. @@ -301,10 +541,10 @@ mod tests { let (mut m, view) = winterthur("EPSG:2056"); assert!(lines(&m, &view).is_none(), "latitudes and longitudes"); m.graticule_type = GraticuleType::Measured; - let own = lines(&m, &view).unwrap(); + let own = lines(&m, &view).unwrap().minor; assert!(straight_in(&own, 2056), "{own:?}"); m.graticule_crs = Some("EPSG:32632".into()); - let utm = lines(&m, &view).unwrap(); + let utm = lines(&m, &view).unwrap().minor; assert!(straight_in(&utm, 32632) && !straight_in(&utm, 2056)); // On a Web Mercator map with no system given: the UTM zone at the view's centre (32N). let (mut m, _) = winterthur("EPSG:3857"); @@ -312,7 +552,7 @@ mod tests { let center = m.to_map(Coord::new(8.73, 47.5)).unwrap(); let view = View { camera: rustgis_map::camera::Camera::new(center, 10.0), ..view }; m.graticule_type = GraticuleType::Measured; - assert!(straight_in(&lines(&m, &view).unwrap(), 32632)); + assert!(straight_in(&lines(&m, &view).unwrap().minor, 32632)); } /// The grid covers the margin around the view that the GPU pans a frame within, so panning @@ -331,7 +571,7 @@ mod tests { } let mut drawn = Extent::EMPTY; let mut eastings = Vec::new(); - for l in lines(&m, &view).unwrap() { + for l in lines(&m, &view).unwrap().minor { let pts: Vec = l.iter().map(|c| tr.from_lonlat(*c).unwrap()).collect(); pts.iter().for_each(|p| drawn.expand(*p)); if pts.iter().all(|p| (p.x - pts[0].x).abs() < 0.01) { @@ -447,4 +687,235 @@ mod tests { // Lines on both sides. assert!(inner.iter().any(|l| l.iter().all(|c| c.x < 12.0)) && inner.iter().any(|l| l.iter().all(|c| c.x > 12.0))); } + + /// Places over a longitude/latitude box, 13 a side. + fn over(w: f64, s: f64, e: f64, n: f64) -> Vec { + (0..=12) + .flat_map(|i| (0..=12).map(move |j| Coord::new(w + (e - w) * f64::from(i) / 12.0, s + (n - s) * f64::from(j) / 12.0))) + .collect() + } + + /// A Web Mercator map with the MGRS graticule, its view 800 × 600 points centered on `lon`, + /// `lat` at `res` Web Mercator meters a point. + fn mgrs_view(lon: f64, lat: f64, res: f64) -> (Map, View) { + let mut m = Map::new("m"); + m.graticule_type = GraticuleType::Mgrs; + let center = m.to_map(Coord::new(lon, lat)).unwrap(); + let camera = rustgis_map::camera::Camera::new(center, res); + (m, View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }) + } + + /// The MGRS labels on a view, with each character 6 points across. + fn labels_on(m: &Map, view: &View) -> Vec<(String, f32, f32)> { + labels(m, view, |t| t.chars().count() as f32 * 6.0) + } + + /// Whether each label names the place under its center as `to_mgrs` does (`name` writes it). + fn name_their_places(m: &Map, view: &View, labels: &[(String, f32, f32)], name: impl Fn(&rustgis_geom::Mgrs) -> String) { + let globe = m.projection.is_globe().then(|| Globe::new(&view.camera, view.width, view.height)); + for (text, x, y) in labels { + let c = at(m, view, globe.as_ref(), f64::from(*x), f64::from(*y)).unwrap(); + let r = rustgis_geom::to_mgrs(c, 0).unwrap(); + assert_eq!(text, &name(&r), "at {c:?}"); + } + } + + fn gzd(r: &rustgis_geom::Mgrs) -> String { + format!("{:02}{}", r.zone, r.band) + } + + /// A line's easting (`true`) or northing in `tr`'s system, when it keeps one. + fn grid_value(l: &[Coord], tr: &rustgis_data::raster::Transformer) -> Option<(bool, f64)> { + let pts: Vec = l.iter().filter_map(|c| tr.from_lonlat(*c)).collect(); + let first = pts.first()?; + if pts.iter().all(|p| (p.x - first.x).abs() < 0.01) { + Some((true, first.x)) + } else if pts.iter().all(|p| (p.y - first.y).abs() < 0.01) { + Some((false, first.y)) + } else { + None + } + } + + /// The MGRS grid's step is a power of ten, three to thirty lines across the view, from 100 km + /// to 100 m, and 100 km while more than four grid zone designations show. + #[test] + fn the_mgrs_step_is_a_power_of_ten_by_scale() { + for (span, cells, step) in [ + (2e6, 2, 1e5), + (4e5, 1, 1e5), + (2e5, 1, 1e4), + (3.1e4, 1, 1e4), + (2.9e4, 1, 1e3), + (3.1e3, 4, 1e3), + (2.9e3, 1, 100.0), + (50.0, 1, 100.0), + (0.0, 1, 100.0), + (f64::NAN, 1, 100.0), + (f64::INFINITY, 1, 1e5), + (3.1e3, 5, 1e5), + ] { + assert_eq!(mgrs_step(span, cells), step, "{span} m, {cells} cells"); + } + } + + /// Zoomed in on zone 33U, the MGRS grid draws 100 km, 10 km, 1 km, then 100 m lines (finest), + /// the 100 km ones (the central meridian's 500 km easting among them) major, the finer minor; + /// zoomed out over several zones, 100 km lines only, all major. + #[test] + fn the_mgrs_grid_steps_by_scale_with_its_100_km_lines_major() { + let tr = rustgis_data::raster::Crs::from_epsg(32633).unwrap().transformer().unwrap(); + for (res, step) in [(100.0, 1e4), (10.0, 1e3), (1.0, 100.0), (0.1, 100.0)] { + let (m, view) = mgrs_view(15.0, 49.5, res); + let g = lines(&m, &view).unwrap(); + let minor: Vec<_> = g.minor.iter().filter_map(|l| grid_value(l, &tr)).collect(); + let major: Vec<_> = g.major.iter().filter_map(|l| grid_value(l, &tr)).collect(); + assert!(!minor.is_empty() && minor.len() == g.minor.len(), "{res}: {} of {}", minor.len(), g.minor.len()); + for (_, v) in &minor { + let whole = |s: f64| (v / s - (v / s).round()).abs() < 1e-6; + assert!(whole(step) && !whole(1e5), "{res}: {v} at {step}"); + } + assert!(major.iter().any(|(e, v)| *e && (v - 500_000.0).abs() < 0.01), "{res}: {major:?}"); + assert!(major.iter().all(|(_, v)| (v / 1e5 - (v / 1e5).round()).abs() < 1e-6), "{res}: {major:?}"); + } + // About 7° across: zones 32 to 34, so 100 km lines only. + let (m, view) = mgrs_view(15.0, 49.5, 1000.0); + let g = lines(&m, &view).unwrap(); + assert!(g.minor.is_empty() && g.major.len() > 20, "{} minor, {} major", g.minor.len(), g.major.len()); + } + + /// Other graticules draw no major lines and no labels. + #[test] + fn other_graticules_keep_one_weight_and_no_labels() { + let (mut m, view) = mgrs_view(15.0, 49.5, 10.0); + assert!(!labels_on(&m, &view).is_empty()); + for t in [GraticuleType::Measured, GraticuleType::Utm] { + m.graticule_type = t; + let g = lines(&m, &view).unwrap(); + assert!(g.major.is_empty() && !g.minor.is_empty(), "{t:?}"); + assert!(labels_on(&m, &view).is_empty(), "{t:?}"); + } + m.graticule_type = GraticuleType::Degrees; + assert!(lines(&m, &view).is_none() && labels_on(&m, &view).is_empty()); + } + + /// The MGRS grid keeps to each grid zone designation as UTM's does: near Salzburg each zone's + /// lines stay on its side of 12° E; in southern Norway 32V reaches west of 6° E, so zone 32's + /// lines cross 6° E; across the antimeridian zone 60's edge at 180° is drawn, major. + #[test] + fn mgrs_lines_keep_to_their_grid_zone_designation() { + let seen = over(11.6, 47.3, 12.4, 47.7); + let g = zones(Coord::new(12.0, 47.5), &seen, &seen, true); + let all: Vec<_> = g.major.iter().chain(&g.minor).collect(); + for l in &all { + assert!(l.iter().all(|c| c.x <= 12.0 + 1e-9) || l.iter().all(|c| c.x >= 12.0 - 1e-9), "across 12° E: {l:?}"); + } + assert!(all.iter().any(|l| l.iter().all(|c| c.x < 12.0)) && all.iter().any(|l| l.iter().all(|c| c.x > 12.0))); + // Southern Norway: no edge at 6° E in band V, and zone 32's grid across it. + let seen = over(5.5, 59.8, 6.5, 60.2); + let g = zones(Coord::new(6.0, 60.0), &seen, &seen, true); + assert!(!g.major.iter().any(|l| l.iter().all(|c| (c.x - 6.0).abs() < 1e-9))); + let tr = rustgis_data::raster::Crs::from_epsg(32632).unwrap().transformer().unwrap(); + let grid: Vec<_> = g.minor.iter().filter(|l| grid_value(l, &tr).is_some()).collect(); + assert!(grid.len() > 4 && grid.iter().any(|l| l.iter().any(|c| c.x < 6.0) && l.iter().any(|c| c.x > 6.0)), "{}", grid.len()); + // Svalbard's band X: its edges at 9°, 21° and 33° E, none at 12° E. + let seen = over(0.0, 74.0, 40.0, 82.0); + let g = zones(Coord::new(20.0, 78.0), &seen, &seen, true); + let edge = |lon: f64| g.major.iter().any(|l| l.iter().all(|c| (c.x - lon).abs() < 1e-9) && l.iter().any(|c| c.y > 76.0)); + assert!(edge(9.0) && edge(21.0) && edge(33.0) && !edge(12.0)); + // Fiji, across the antimeridian. + let seen: Vec = + over(179.4, -17.6, 180.6, -17.0).into_iter().map(|c| Coord::new(if c.x > 180.0 { c.x - 360.0 } else { c.x }, c.y)).collect(); + let g = zones(Coord::new(179.9, -17.3), &seen, &seen, true); + assert!(g.major.iter().any(|l| l.iter().all(|c| (c.x - 180.0).abs() < 1e-9))); + let inner = g.minor.iter().chain(&g.major).filter(|l| !l.iter().all(|c| (c.x - l[0].x).abs() < 1e-9)).count(); + assert!(inner > 4, "{inner}"); + } + + /// The 100 km squares are named by their letters at their places, checked against + /// GeographicLib's GeoConvert (`GeoConvert -m -p 0`): 48.5° N 14.5° E is 33U VP, 47.8° N + /// 14.5° E 33T VN, 52° N 15° E 33U WT. With two grid zone designations in view each name + /// carries its own; with one, the letters alone. + #[test] + fn mgrs_squares_are_named_by_their_letters() { + let (m, view) = mgrs_view(14.5, 48.2, 500.0); + let got = labels_on(&m, &view); + let texts: Vec<&str> = got.iter().map(|(t, _, _)| t.as_str()).collect(); + assert!(texts.contains(&"33U VP") && texts.contains(&"33T VN"), "{texts:?}"); + name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); + let (m, view) = mgrs_view(15.0, 52.0, 300.0); + let got = labels_on(&m, &view); + let texts: Vec<&str> = got.iter().map(|(t, _, _)| t.as_str()).collect(); + assert!(texts.contains(&"WT") && texts.iter().all(|t| t.len() == 2), "{texts:?}"); + name_their_places(&m, &view, &got, |r| format!("{}{}", r.column, r.row)); + // Zoomed in to a few hundred meters, within one square (52° N 15.3° E: 33U WT). + let (m, view) = mgrs_view(15.3, 52.0, 0.5); + let got = labels_on(&m, &view); + assert_eq!(got.iter().map(|(t, _, _)| t.as_str()).collect::>(), ["WT"]); + let (_, x, y) = &got[0]; + assert!((f64::from(*x) - 400.0).abs() < 1.0 && (f64::from(*y) - 300.0).abs() < 1.0, "in the middle: {x}, {y}"); + } + + /// Zoomed out, the grid zone designations are named, not the squares, on a flat map and on a + /// globe; across the antimeridian on a globe both zone 60's and zone 1's squares are named + /// (60K ZF and 01K AA by GeoConvert at 17.3° S, 179.9° E and W). + #[test] + fn zoomed_out_mgrs_names_its_grid_zone_designations() { + let (mut m, view) = mgrs_view(15.0, 48.0, 20_000.0); + let got = labels_on(&m, &view); + assert!(got.len() > 10 && got.iter().any(|(t, _, _)| t == "33U"), "{got:?}"); + name_their_places(&m, &view, &got, gzd); + m.projection = rustgis_map::Projection::Globe; + let camera = rustgis_map::camera::Camera::new(rustgis_geom::lonlat_to_merc(Coord::new(15.0, 48.0)), 20_000.0); + let view = View { camera, ..view }; + let got = labels_on(&m, &view); + assert!(got.len() > 10 && got.iter().any(|(t, _, _)| t == "33U"), "{got:?}"); + name_their_places(&m, &view, &got, gzd); + let camera = rustgis_map::camera::Camera::new(rustgis_geom::lonlat_to_merc(Coord::new(179.9, -17.3)), 300.0); + let view = View { camera, ..view }; + let got = labels_on(&m, &view); + let texts: Vec<&str> = got.iter().map(|(t, _, _)| t.as_str()).collect(); + assert!(texts.contains(&"60K ZF") && texts.contains(&"01K AA"), "{texts:?}"); + name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); + } + + /// A square cut too small for its name isn't named: with five points of zone 34 at the view's + /// right edge only zone 33's squares are, with two hundred zone 34's too. + #[test] + fn a_square_cut_too_small_is_not_named() { + let per_pt = 50.0 / 111_319.490_793; + let (m, view) = mgrs_view(18.0 - 395.0 * per_pt, 49.5, 50.0); + let got = labels_on(&m, &view); + assert!(!got.is_empty() && got.iter().all(|(t, _, _)| t.starts_with("33U ")), "{got:?}"); + let (m, view) = mgrs_view(18.0 - 200.0 * per_pt, 49.5, 50.0); + let got = labels_on(&m, &view); + assert!(got.iter().any(|(t, _, _)| t.starts_with("34U ")) && got.iter().any(|(t, _, _)| t.starts_with("33U ")), "{got:?}"); + name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); + } + + /// A view of 33U with a narrow strip of 34U at its right edge (north up and turned), or of + /// 33T at its bottom, names its squares with their grid zone designations. + #[test] + fn a_narrow_strip_of_another_grid_zone_designation_prefixes_the_names() { + let per_pt = 50.0 / 111_319.490_793; + for bearing in [0.0, 30.0] { + for (lon, lat) in [(18.0 - 360.0 * per_pt, 49.5), (15.0, 48.0 + 270.0 * per_pt * 0.66)] { + let (m, mut view) = mgrs_view(lon, lat, 50.0); + view.camera.bearing = bearing; + let got = labels_on(&m, &view); + assert!(!got.is_empty() && got.iter().all(|(t, _, _)| t.len() == 6), "{bearing}: {got:?}"); + name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); + } + } + } + + /// A view centered past 84° N, where no UTM zone is, names the band X squares it shows (the + /// view reaches down to about 83.9° N). + #[test] + fn a_view_centered_past_84_north_names_band_x_squares() { + let (m, view) = mgrs_view(15.0, 84.3, 1500.0); + let got = labels_on(&m, &view); + assert!(!got.is_empty() && got.iter().all(|(t, _, _)| t.len() == 2), "{got:?}"); + name_their_places(&m, &view, &got, |r| format!("{}{}", r.column, r.row)); + } } diff --git a/crates/render/src/mesh.rs b/crates/render/src/mesh.rs index f44fec783f..e41cbf0a06 100644 --- a/crates/render/src/mesh.rs +++ b/crates/render/src/mesh.rs @@ -560,18 +560,19 @@ pub(crate) fn collect_basemap( Ok(()) } -/// The graticule lines (already in map units). +/// The graticule lines (already in map units), `width` points wide. pub(crate) fn collect_graticule( cmds: &mut Vec, lines: &[Vec], ext: &Extent, grat: Rgba, + width: f32, ppp: f32, map_per_px: f64, ) -> Result<(), TessError> { let origin = origin_for(ext, map_per_px)?; let (mut v, mut i) = (Vec::new(), Vec::new()); - extend_mesh(&mut v, &mut i, stroke_lines(lines, origin, premul(grat), 0.6 * ppp, map_per_px, NO_LIMIT))?; + extend_mesh(&mut v, &mut i, stroke_lines(lines, origin, premul(grat), width * ppp, map_per_px, NO_LIMIT))?; if !i.is_empty() { cmds.push(DrawCmd::Mesh { origin, vertices: v, indices: i }); } diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 8135fb6670..a2bec040fb 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -4825,6 +4825,7 @@ fn shown_layers(session: &rustgis_engine::Session) -> u64 { &map.graticule_crs, ) .hash(&mut h); + (map.graticule_on_top, map.graticule_color).hash(&mut h); for l in &map.layers { (l.id, l.visible).hash(&mut h); } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 6ca0fd42b7..814025e204 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1881,8 +1881,8 @@ fn analysis_groups(app: &mut RustGisApp, ui: &mut Ui) { }); } -/// View › Display › Graticule's menu: the graticule's type (choosing one shows it), and the -/// measured grid's coordinate system. +/// View › Display › Graticule's menu: the graticule's type (choosing one shows it), whether its +/// lines go over the layers, their color, and the measured grid's coordinate system. fn graticule_menu(ui: &mut Ui, app: &mut RustGisApp) { use rustgis_engine::map::graticule::GraticuleType; let (on, kind) = (app.session.map().graticule, app.session.map().graticule_type); @@ -1895,6 +1895,41 @@ fn graticule_menu(ui: &mut Ui, app: &mut RustGisApp) { } } ui.separator(); + // Under the layers, filled ones hide the lines; over them, only the labels are on top. + let mut on_top = app.session.map().graticule_on_top; + if ui + .checkbox(&mut on_top, tl!("Draw on top of layers")) + .on_hover_text(tl!("Draw the grid lines over the map's layers, under the labels; off: under the layers")) + .changed() + && let Err(e) = app.run("map.graticule", json!({"onTop": on_top})) + { + app.session.notify(e, true); + } + let set = app.session.map().graticule_color.is_some(); + let current = app.session.map().graticule_rgba(); + ui.horizontal(|ui| { + let name = ui.label(tl!("Grid color")); + // Named by its label, for a screen reader. The saved color's RGB is kept at no opacity + // (`rgba_button`), so raising only the opacity keeps the color. + let (resp, picked) = crate::widgets::rgba_button(ui, current); + let resp = resp.on_hover_text(tl!("The grid's color and opacity")).labelled_by(name.id); + if let Some(picked) = picked { + crate::widgets::one_step_per_press(app, &resp); + if let Err(e) = app.run("map.graticule", json!({"color": picked.hex8()})) { + app.session.notify(e, true); + } + } + if ui + .add_enabled(set, egui::Button::new(tl!("Default"))) + .on_hover_text(tl!("The basemap's grid color")) + .on_disabled_hover_text(tl!("The grid already has the basemap's color")) + .clicked() + && let Err(e) = app.run("map.graticule", json!({"color": null})) + { + app.session.notify(e, true); + } + }); + ui.separator(); let name = ui.label(tl!("Measured grid's coordinate system")); ui.vertical(|ui| { let recent = app.ui.recent_crs.clone(); @@ -1960,12 +1995,12 @@ fn view_tab(app: &mut RustGisApp, ui: &mut Ui) { app, "graticule", "Graticule", - "Show or hide the graticule over the basemap: latitudes and longitudes, a measured grid or the UTM zones.", + "Show or hide the graticule over the basemap: latitudes and longitudes, a measured grid, the UTM zones or the MGRS grid.", "map.graticule", Value::Null, g, "Graticule options", - "What the graticule draws: latitudes and longitudes, a measured grid or the UTM zones.", + "What the graticule draws: latitudes and longitudes, a measured grid, the UTM zones or the MGRS grid.", true, graticule_menu, ); @@ -5712,6 +5747,11 @@ mod tests { h.get_by_label("UTM Zones").click(); h.run(); assert!(h.state().session.map().graticule && h.state().session.map().graticule_type == GraticuleType::Utm); + h.get_by_label("Graticule options").click(); + h.run(); + h.get_by_label("MGRS").click(); + h.run(); + assert!(h.state().session.map().graticule && h.state().session.map().graticule_type == GraticuleType::Mgrs); // A system typed as an EPSG code: clicking into the field keeps the menu open. h.get_by_label("Graticule options").click(); h.run(); @@ -5752,6 +5792,69 @@ mod tests { assert_eq!(h.state().ui.recent_crs.first().map(String::as_str), Some("EPSG:32633")); } + /// View › Display › Graticule's menu: "Draw on top of layers" puts the lines over the layers + /// and back, without showing or hiding the grid; "Default" is offered only once a color is set, + /// and takes the grid back to the basemap's. + #[test] + fn the_graticule_menu_draws_it_on_top_and_resets_its_color() { + use egui_kittest::kittest::NodeT; + let mut h = tab_harness(RustGisApp::with_sample(), view_tab); + let on = h.state().session.map().graticule; + assert!(!h.state().session.map().graticule_on_top); + h.get_by_label("Graticule options").click(); + h.run(); + assert!(h.get_by_label("Default").accesskit_node().is_disabled(), "no color set yet"); + // The color button, named by its label. + h.get_by_role_and_label(egui::accesskit::Role::ColorWell, "Grid color"); + h.get_by_label("Draw on top of layers").click(); + h.run(); + assert!(h.state().session.map().graticule_on_top); + assert_eq!(h.state().session.map().graticule, on); + // Still open: unticked again. + h.get_by_label("Draw on top of layers").click(); + h.run(); + assert!(!h.state().session.map().graticule_on_top); + h.state_mut().session.run("map.graticule", &json!({"color": "#FF000080"})).unwrap(); + h.run(); + h.get_by_label("Default").click(); + h.run(); + assert_eq!(h.state().session.map().graticule_color, None); + } + + /// The graticule menu's color picker keeps a saved color's RGB at no opacity: raising only the + /// opacity of `#33669900` saves `#33669980`, not black at that opacity. Drives the same + /// `rgba_button` the menu calls, fed the color the menu feeds it (`graticule_rgba`), typing the + /// opacity into the picker's A number, then saves what it picked through `map.graticule` as the + /// menu does. (The picker is driven on its own: kittest closes the menu on the click that opens + /// the picker's popup.) + #[test] + fn the_graticule_color_keeps_its_rgb_when_only_the_opacity_is_raised() { + let mut app = RustGisApp::with_sample(); + app.session.run("map.graticule", &json!({"color": "#33669900"})).unwrap(); + let current = app.session.map().graticule_rgba(); + assert_eq!(current.hex8(), "#33669900"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, picked: &mut Option| { + if let (_, Some(c)) = crate::widgets::rgba_button(ui, current) { + *picked = Some(c); + } + }, + None, + ); + h.get_by_role(egui::accesskit::Role::ColorWell).click(); + h.run(); + // A transparent picker edits linear values; the picker's numbers are R, G, B, A. + h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(3).unwrap().focus(); + h.run(); + h.event(egui::Event::Text("0.5".into())); + h.run(); + h.key_press(egui::Key::Enter); + h.run(); + let picked = h.state().expect("the picker gave a color"); + app.session.run("map.graticule", &json!({"color": picked.hex8()})).unwrap(); + assert_eq!(app.session.map().graticule_rgba().hex8(), "#33669980"); + } + /// The language list names every language in English while the interface is English, with the /// language's own name as the tooltip; in another language each keeps its own name, or its /// English one where no font can draw it. diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index d52c154523..45076c9d66 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -875,13 +875,40 @@ picking one shows it: southern Norway's and Svalbard's wider zones. Once no more than eight zone-and-band areas are in view, each also gets its own eastings and northings, at the same interval in all of them and cut at the zone's edges. - -The grids have no labels on the map; the status bar reads coordinates in UTM or MGRS. Like the +- **MGRS**: the Military Grid Reference System's grid (`"mgrs"` in the command): the same zones + and bands as grid zone designations, drawn heavier. Once no more than eight are in view, each gets + its own grid at a power of ten that suits the scale, between three and thirty lines across the + view: 100 km, then 10 km, 1 km and, zoomed in closest, 100 m (100 km while more than four grid + zone designations show). The 100 km lines, the edges of the 100 km squares, stay heavier than the + finer ones. Zoomed out, each grid zone designation is named (`33U`); once the 100 km squares are + large enough on the screen, each is named by its letters (`VP`), with its grid zone designation + (`33U VP`) when more than one is in view. A zone or square cut too small for its name isn't + named, and the names aren't drawn on a tilted view. Nothing is drawn yet north of 84° N or south + of 80° S, where MGRS uses UPS. + +Only the MGRS grid is labeled on the map; the status bar reads coordinates in UTM or MGRS. Like the latitudes and longitudes, they aren't drawn on the copies of the world a flat map shows past ±180°. The type and system are saved with the map; a project whose measured grid names a system this version can't use (one in degrees, or a PROJ string the web app can't read) opens without it, and says so. +Two more settings in the same menu apply to every type, and are saved with the map: + +- **Draw on top of layers** (`"onTop"` in the command; off by default, and `null` goes back to + it): by default the grid lines are drawn with the basemap, under the map's layers and web tile + layers, so a filled layer hides them. With it on, they are drawn over every layer and tile + layer, still under the labels. They then also draw over the highlights of selected features. + The MGRS names are labels, so they're drawn over the layers either way, as the layers' own + labels are: a filled layer can hide the lines under a name but not the name. They go with the + lines when the grid's opacity is 0, and pause with the labels. +- **Grid color** (`"color"`: `"#RRGGBB"` or `"#RRGGBBAA"`, with its opacity): the lines' color. By + default it is the basemap's own grid color, which is faint; **Default** (`null` or `""` in the + command) goes back to it. The MGRS names take the same color, fully opaque. Major and minor + lines keep their widths. + +Neither setting shows or hides the grid. A project that uses either needs a RustGIS that knows +it: an older one refuses to open it rather than drop the setting. + **Global** shows a globe; **Local** a flat view centred where you are (azimuthal equidistant; not in the web app, which doesn't include that projection). **Wireframe** draws polygons as outlines; **Raise Priority** and **Lower Priority** change a diff --git a/schema/fixtures/graticule_mgrs.rgis b/schema/fixtures/graticule_mgrs.rgis new file mode 100644 index 0000000000..5498a807b2 --- /dev/null +++ b/schema/fixtures/graticule_mgrs.rgis @@ -0,0 +1 @@ +{"requires":["graticule-mgrs","graticule-on-top","graticule-color"],"format":2,"name":"graticule_mgrs","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"graticule_type":"mgrs","graticule_on_top":true,"graticule_color":[48,48,48,153],"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":1}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 99bc90e282..f17a948cd0 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1095,6 +1095,9 @@ "layout-element-background", "classified-point-size", "picture-markers", + "graticule-mgrs", + "graticule-on-top", + "graticule-color", "layout-element-ink", "layout-element-wrap", "layout-chart-data", @@ -1187,6 +1190,9 @@ "layout-element-background", "classified-point-size", "picture-markers", + "graticule-mgrs", + "graticule-on-top", + "graticule-color", "layout-element-ink", "layout-element-wrap", "layout-chart-data",