diff --git a/crates/engine/examples/held_bench.rs b/crates/engine/examples/held_bench.rs index d953e8cadb..8281fc7b70 100644 --- a/crates/engine/examples/held_bench.rs +++ b/crates/engine/examples/held_bench.rs @@ -1,6 +1,6 @@ //! Times a large line layer held in longitude/latitude against the same layer held in UTM 32N //! (#2032 C2): holding it, converting it back for a tool, the first frame, a change of -//! projection, panning and zooming: +//! projection, panning and zooming, and drawing on a map in UTM 32N: //! `cargo run --release -p rustgis-engine --example held_bench -- [vertices, default 1000000]`. use rustgis_data::raster::Crs; use rustgis_data::{Coord, Dataset, Geometry, GeometryType}; @@ -32,7 +32,7 @@ fn ms(t: Instant) -> f64 { fn main() -> Result<(), String> { let vertices: usize = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(1_000_000); println!("{vertices} vertices; times in ms"); - println!("{:<34}{:>12}{:>12}", "", "lon/lat", "UTM 32N"); + println!("{:<34}{:>12}{:>12}", "layer held in", "lon/lat", "UTM 32N"); let mut rows: Vec<(&str, [f64; 2])> = Vec::new(); let mut put = |what: &'static str, i: usize, v: f64| match rows.iter_mut().find(|r| r.0 == what) { Some(r) => r.1[i] = v, @@ -75,6 +75,16 @@ fn main() -> Result<(), String> { let camera = s.map().camera; put("first frame after projection change", i, frame(&mut s, camera)?); put("next frame (EPSG:3035)", i, frame(&mut s, camera)?); + // On a map in UTM 32N, the held layer's own system: drawn as it is. + s.run("map.projection", &json!({"type": "epsg:32632"}))?; + s.run("layer.zoomTo", &json!({"layer": "lines"}))?; + let mut camera = s.map().camera; + put("first frame (on a UTM 32N map)", i, frame(&mut s, camera)?); + put("next frame (on a UTM 32N map)", i, frame(&mut s, camera)?); + camera.res /= 4.0; + put("zoom in 4x (on a UTM 32N map)", i, frame(&mut s, camera)?); + // What the map keeps for drawing it there, beside its rows (MB, not ms). + put("drawing copies, MB (UTM 32N map)", i, s.map().layers[0].view_cache_bytes() as f64 / 1e6); } for (what, [a, b]) in rows { println!("{what:<34}{a:>12.1}{b:>12.1}"); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3dc5453da9..e22a5d774d 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -139,11 +139,9 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id | [name|id] (default: the layer selection), "to": position (0 = top; past the end, the bottom). Several keep their order, the topmost landing at "to" as one layer would, and go only to the top or the bottom (one in a group, to its group's): with 4 layers and 2 of them, 2 or more is the bottom, 1 is refused}"#), C::new("layer.zoomTo", "Zoom To Layer", "Layers", |s, p| { let ids = layer_ids(s, p)?; - let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.shown_extent())); - if e.is_empty() { + if s.zoom_to_layers(&ids, rustgis_map::ExtentOf::Shown).is_none() { return Err(if ids.len() > 1 { "the layers have no features" } else { "the layer has no features" }.into()); } - s.zoom_to(&e); Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"layer"?: name|id | [name|id] (default: the layer selection; zooms to all of them)}"#) .view() @@ -3457,10 +3455,7 @@ fn add_source_read( } } if zoom.unwrap_or(empty_before) { - let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent())); - if !e.is_empty() { - s.zoom_to(&e); - } + s.zoom_to_layers(&ids, rustgis_map::ExtentOf::All); } if let Some(note) = attribute_note { s.notify(format!("{label}: {note}"), false); @@ -4259,10 +4254,7 @@ fn add_live(s: &mut Session, p: &Value, db: &rustgis_data::source::duckdb::Datab return Err(with_left(error, &said)); } if empty_before { - let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent())); - if !e.is_empty() { - s.zoom_to(&e); - } + s.zoom_to_layers(&ids, rustgis_map::ExtentOf::All); } // Empty tables (common in a PostGIS database: its TIGER geocoder's) are left out quietly. if empty > 0 { @@ -4475,10 +4467,7 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: & s.notify(rustgis_data::source::gdal::in_lonlat_notes(&names), false); } if empty_before { - let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent())); - if !e.is_empty() { - s.zoom_to(&e); - } + s.zoom_to_layers(&ids, rustgis_map::ExtentOf::All); } if ids.is_empty() { return Err(format!("{label}: none of its layers could be added")); @@ -6839,17 +6828,16 @@ fn added_download(s: &mut Session, p: &Value, mut r: Value, mark_source: bool, u /// whether the view framed them (not when none had an extent, or the map's projection doesn't /// reach it). fn zoom_to_added(s: &mut Session, r: &Value) -> bool { - let ids = r.get("layers").and_then(Value::as_array).into_iter().flatten().chain(r.get("layer")); - let e = ids + let ids: Vec = r + .get("layers") + .and_then(Value::as_array) + .into_iter() + .flatten() + .chain(r.get("layer")) .filter_map(Value::as_u64) .filter_map(|i| u32::try_from(i).ok()) - .filter_map(|id| s.map().layer(id).map(|l| l.extent())) - .filter(|e| !e.is_empty()) - .fold(rustgis_geom::Extent::EMPTY, |a, e| a.union(&e)); - if e.is_empty() { - return false; - } - s.zoom_to(&e) + .collect(); + s.zoom_to_layers(&ids, rustgis_map::ExtentOf::All).unwrap_or(false) } pub(crate) fn add_data_text(s: &mut Session, p: &Value) -> CmdResult { @@ -6907,10 +6895,8 @@ pub(crate) fn add_read( stand(l, &x); } } - if zoom.unwrap_or(empty_before) - && let Some(e) = s.map().layer(id).map(|l| l.extent()) - { - s.zoom_to(&e); + if zoom.unwrap_or(empty_before) { + s.zoom_to_layers(&[id], rustgis_map::ExtentOf::All); } Ok(json!({"layer": id, "features": n})) } diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 235419f966..ac4f702156 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -317,9 +317,10 @@ pub(crate) fn follow_renamed_map(s: &mut Session, old: &str, new: &str) { } fn zoom_full(s: &mut Session, _: &Value) -> CmdResult { - let e = s.map().shown_extent(); - let e = if e.is_empty() { Extent::new(-170.0, -58.0, 180.0, 78.0) } else { e }; - s.zoom_to(&e); + let ids = s.shown_layer_ids(); + if s.zoom_to_layers(&ids, rustgis_map::ExtentOf::Shown).is_none() { + s.zoom_to(&Extent::new(-170.0, -58.0, 180.0, 78.0)); + } Ok(Value::Null) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index e39cb0f505..3c1f5aa56e 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -59,11 +59,10 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"layer"?: name|id (default: the active layer)}"#) .when(need_layer), C::new("select.zoomTo", "Zoom To Selection", "Home › Selection", |s, _| { - let e = s.map().selection_extent(); - if e.is_empty() { + let ids: Vec = s.map().layers.iter().filter(|l| !l.selection.is_empty()).map(|l| l.id).collect(); + if s.zoom_to_layers(&ids, rustgis_map::ExtentOf::Selected).is_none() { return Err("nothing with a shape is selected".into()); } - s.zoom_to(&e); Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .view() diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 29b4d17548..5df340214b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -4154,6 +4154,47 @@ impl Session { true } + /// Fits the camera to the layers `ids` ([`rustgis_map::ExtentOf`] says which of their + /// features): on a flat map in a coordinate system that holds one of them in its own + /// coordinates ([`rustgis_map::Layer::in_map_units`]), around their places in map coordinates, + /// those layers' exactly as held, with nothing converted; else as [`Session::zoom_to`] does, + /// around their longitude/latitude extent. `None` when they have nothing to zoom to; else + /// whether it did. + pub fn zoom_to_layers(&mut self, ids: &[u32], of: rustgis_map::ExtentOf) -> Option { + let m = self.map(); + let layers: Vec<&rustgis_map::Layer> = ids.iter().filter_map(|id| m.layer(*id)).collect(); + // In map coordinates first, where a layer's are its own: its longitude/latitude extent, + // which converts every place, isn't worked out for it then. + if !m.projection.is_globe() { + let flat = m.flat(); + if layers.iter().any(|l| l.in_map_units(&flat)) { + let boxed = layers.iter().fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent_on(&flat, of))); + // None of it on this map (a layer in its system with nothing to frame, another + // wholly beyond the map), or a single point, which has no size to fit: framed in + // longitude/latitude, which says when the map can't show it. + if boxed.width() > 0.0 || boxed.height() > 0.0 { + let (w, h) = self.view_size; + if !self.map_mut().fit_map_extent(&boxed, w, h) { + return Some(false); + } + self.record_extent(); + return Some(true); + } + } + } + let lonlat = layers.iter().fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent_of(of))); + if lonlat.is_empty() { + return None; + } + Some(self.zoom_to(&lonlat)) + } + + /// The layers on the active map it shows, by id, top first: what Full Extent zooms to. + pub fn shown_layer_ids(&self) -> Vec { + let m = self.map(); + m.layers.iter().filter(|l| m.shows(l)).map(|l| l.id).collect() + } + pub fn title(&self) -> String { self.project.name.clone() } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 7d14918f81..1ffac1bc9a 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -158,6 +158,71 @@ fn a_held_layer_has_the_same_extent_and_zoom() { assert!((a.x - b.x).abs() < 5.0 && (a.y - b.y).abs() < 5.0, "{a:?} vs {b:?}"); } +/// On a map in a layer's own system, Zoom To Layer, Zoom To Selection and Full Extent frame its +/// features as they are held, in map coordinates, with nothing converted: the view is centred on +/// the middle of their own box exactly (through longitude/latitude it is the centre of the drawn +/// box of their longitude/latitude box, metres away on UTM's turned grid). +#[test] +fn zooming_on_a_map_in_the_layers_system_frames_its_own_box() { + let mut s = session(UTM); + s.view_size = (800.0, 600.0); + s.run("map.projection", &json!({"type": "EPSG:32632"})).unwrap(); + let own = |s: &Session, rows: &[usize]| { + let ds = &s.map().layer_by_name("Parcels").unwrap().dataset; + rows.iter().filter_map(|r| ds.features[*r].geometry.as_ref()).fold(rustgis_geom::Extent::EMPTY, |e, g| e.union(&g.extent())) + }; + let centred = |s: &Session, e: &rustgis_geom::Extent, what: &str| { + let c = s.map().camera.center; + assert!((c.x - e.center().x).abs() < 1e-6 && (c.y - e.center().y).abs() < 1e-6, "{what}: {c:?} vs {:?}", e.center()); + }; + s.run("layer.zoomTo", &json!({"layer": "Parcels"})).unwrap(); + centred(&s, &own(&s, &(0..9).collect::>()), "layer"); + // The road runs at a slant: the drawn box of its longitude/latitude box is turned against + // UTM's grid and larger than its own, so the way through longitude/latitude centres elsewhere. + s.run("layer.zoomTo", &json!({"layer": "Roads"})).unwrap(); + let road = s.map().layer_by_name("Roads").unwrap(); + let road_own = road.dataset.extent(); + centred(&s, &road_own, "road"); + let via = s.map().flat().extent(&road.extent()).center(); + assert!((via.x - road_own.center().x).hypot(via.y - road_own.center().y) > 1.0, "{via:?} vs {:?}", road_own.center()); + s.run("select.rows", &json!({"layer": "Parcels", "rows": [0, 4]})).unwrap(); + s.run("select.zoomTo", &json!({})).unwrap(); + centred(&s, &own(&s, &[0, 4]), "selection"); + // Full Extent: Wells, Roads and Parcels together, all held in UTM. + s.run("map.zoomFull", &json!({})).unwrap(); + let full = ["Wells", "Roads", "Parcels"] + .iter() + .fold(rustgis_geom::Extent::EMPTY, |e, name| e.union(&s.map().layer_by_name(name).unwrap().dataset.extent())); + centred(&s, &full, "full extent"); +} + +/// A layer in the map's system with nothing to frame doesn't make another layer, which the map +/// can't show, look empty: zooming to both says the map can't show it, as zooming to that layer +/// alone does. +#[test] +fn zooming_to_an_empty_layer_in_the_maps_system_and_one_beyond_the_map_says_so() { + let mut s = Session::new(Project::default()); + s.view_size = (800.0, 600.0); + let mut empty = Dataset::new("Empty", GeometryType::Point, vec![]); + empty.held_in = UTM; + s.map_mut().add_dataset(empty); + let mut far = Dataset::new("Far", GeometryType::Point, vec![]); + far.push(Some(Geometry::Point(Coord::new(50.0, 48.8))), vec![]); + s.map_mut().add_dataset(far); + s.run("map.projection", &json!({"type": "EPSG:32632"})).unwrap(); + let alone = s.run("layer.zoomTo", &json!({"layer": "Far"})); + let mark = s.notice_mark(); + let both = s.run("layer.zoomTo", &json!({"layer": ["Empty", "Far"]})); + assert_eq!(both.is_ok(), alone.is_ok(), "{both:?} vs {alone:?}"); + if let Err(e) = &both { + assert!(!e.contains("no features"), "{e}"); + } + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + // 50°E is some 3,000 km east of UTM 32N's central meridian, beyond what the map shows. + assert!(s.map().flat().forward_checked(Coord::new(50.0, 48.8)).is_none()); + assert!(said.iter().any(|t| t == crate::BEYOND_PROJECTION), "{said:?}"); +} + /// Selecting by a box, a point, a radius and a polygon picks the same features. #[test] fn a_held_layer_is_selected_alike() { diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index b357c03dc6..d54e0f5209 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1156,7 +1156,8 @@ impl Layer { /// vertex index, which only the source geometry has. pub fn projected_in(&mut self, flat: &projection::Flat, key: &str) -> &[Option] { if !self.is_cached(key) { - if !matches!(flat, projection::Flat::Mercator) { + // Display copies made for another map are of no use on this one. + if self.display_rows(flat).is_none() { self.display_levels.clear(); } self.fill_projected(key, flat); @@ -1336,9 +1337,11 @@ impl Layer { /// Every failure clears the active display; recent reusable levels may remain cached. pub fn prepare_display(&mut self, flat: &projection::Flat, tol: f64, whole_layer_eligible: bool) -> bool { self.display = None; - // The display copies are made from longitude/latitude rows ([`lod::display`]). - let lonlat = self.dataset.coord_crs() == Crs::LonLat; - let Some(level) = lod::level(tol).filter(|_| lonlat && matches!(flat, projection::Flat::Mercator)) else { return false }; + // The display copies are made from longitude/latitude rows on Web Mercator, and from rows + // held in the map's own system on that map, as they are ([`lod::display`]): no other is + // made, as converting a whole layer each level would cost what the copy saves. + let Some(rows) = self.display_rows(flat) else { return false }; + let Some(level) = lod::level(tol) else { return false }; self.trim_thinned_levels(self.lod_budget()); let used: usize = self.thinned.iter().filter_map(|(_, c)| c.as_ref()).map(|c| lod::cache_bytes(c)).sum(); let budget = self.lod_budget().saturating_sub(used); @@ -1355,7 +1358,7 @@ impl Layer { self.display_rejected.insert(0, hit); return false; } - let Some(display) = lod::display(&self.dataset.features, self.geometry_rev, level, budget, whole_layer_eligible) else { + let Some(display) = lod::display(&self.dataset.features, rows, self.geometry_rev, level, budget, whole_layer_eligible) else { self.display_rejected.insert(0, attempt); self.display_rejected.truncate(lod::LEVELS_KEPT); return false; @@ -1368,6 +1371,19 @@ impl Layer { true } + /// Where its rows are on a map in `flat`, when display copies are made from them there + /// ([`Layer::prepare_display`]): longitude/latitude rows on Web Mercator, rows held in the map's + /// own system on that map; `None` on any other. + fn display_rows(&self, flat: &projection::Flat) -> Option { + let crs = self.dataset.coord_crs(); + match flat { + projection::Flat::Mercator if crs == Crs::LonLat => Some(lod::Rows::LonLat), + projection::Flat::Mercator if crs == Crs::WebMercator => Some(lod::Rows::MapUnits), + _ if flat.direct_system() == Some(crs) => Some(lod::Rows::MapUnits), + _ => None, + } + } + /// Shared optional LOD storage remaining after original rows and exact projection caches. fn lod_budget(&self) -> usize { self.source.as_ref().map_or(lod::CACHE_BYTES, |s| { @@ -1439,7 +1455,7 @@ impl Layer { // Projected and thinned at once from longitude/latitude rows; from any other // system, the projected geometry is thinned. let copy = if matches!(flat, projection::Flat::Mercator) && self.dataset.coord_crs() == Crs::LonLat { - lod::project_budgeted(&self.dataset.features, level, budget) + lod::project_budgeted(&self.dataset.features, lod::Rows::LonLat, level, budget) } else { lod::thin_budgeted(&self.projected, t, budget) }; @@ -1545,6 +1561,21 @@ impl Layer { fits } + /// Lets go of a projected copy made for another map than `key`'s, and its thinned levels: a + /// frame drawn there from display copies alone ([`Layer::prepare_display`]) has no use for it, + /// and it would stay, a copy of the layer's geometry, until that map came back. + pub fn release_projected_other_than(&mut self, key: &str) { + if !self.projected.is_empty() && self.projected_for != key { + self.projected = Default::default(); + self.projected_extents = Default::default(); + self.projected_vertices = 0; + self.thinned = Default::default(); + self.projected_rev = u64::MAX; + self.projected_for.clear(); + self.projected_crs = None; + } + } + /// Takes the rows of `kept`, a chunk of a streamed layer drawn before (a copy of this layer /// with other rows), and the geometry drawing made of them: projected, and thinned for /// display. Sharing them costs a pointer; this layer keeps its own look. What drawing makes @@ -1712,11 +1743,60 @@ impl Layer { self.dataset.lonlat_extent_of(rows.into_iter().filter_map(|r| self.dataset.features.get(r)).filter_map(|f| f.geometry.as_ref())) } + /// Whether a map in `flat` holds its features' coordinates as its own map coordinates: a + /// layer of features held in the system the map is drawn in ([`projection::Flat::direct_system`]), + /// its rows all at hand (not read in place, nor a raster). + pub fn in_map_units(&self, flat: &projection::Flat) -> bool { + self.raster.is_none() && self.source.is_none() && flat.direct_system().is_some_and(|map| map == self.dataset.coord_crs()) + } + + /// Its [`ExtentOf`] extent in the map coordinates of `flat`: on a map in the layer's own + /// system ([`Layer::in_map_units`]), the box around those features exactly as they are held, + /// with nothing converted; else its longitude/latitude extent drawn on the map + /// ([`projection::Flat::extent`]). + pub fn extent_on(&self, flat: &projection::Flat, of: ExtentOf) -> Extent { + if self.in_map_units(flat) { + let boxed = |rows: &mut dyn Iterator| { + rows.filter_map(|r| self.dataset.features.geometry(r)).fold(Extent::EMPTY, |e, g| e.union(&g.extent())) + }; + return match of { + ExtentOf::All => self.dataset.extent(), + ExtentOf::Shown => match self.query_rows(&self.dataset) { + Some(shown) => boxed(&mut shown.iter().enumerate().filter_map(|(r, v)| v.then_some(r))), + None => self.dataset.extent(), + }, + ExtentOf::Selected => boxed(&mut self.selection.iter().copied()), + }; + } + let lonlat = self.extent_of(of); + if lonlat.is_empty() { Extent::EMPTY } else { flat.extent(&lonlat) } + } + + /// Its [`ExtentOf`] extent in longitude/latitude. + pub fn extent_of(&self, of: ExtentOf) -> Extent { + match of { + ExtentOf::All => self.extent(), + ExtentOf::Shown => self.shown_extent(), + ExtentOf::Selected => self.selection_extent(), + } + } + pub fn opacity(&self) -> f32 { (1.0 - self.transparency / 100.0).clamp(0.0, 1.0) } } +/// Which of a layer's features an extent is around ([`Layer::extent_of`], [`Layer::extent_on`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExtentOf { + /// All of them ([`Layer::extent`]). + All, + /// Those its definition query lets through ([`Layer::shown_extent`]). + Shown, + /// Its selected ones ([`Layer::selection_extent`]). + Selected, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Bookmark { pub name: String, @@ -3343,6 +3423,17 @@ impl Map { true } + /// Points the flat map at an extent in its own map coordinates with a margin, as + /// [`Map::fit_lonlat`] does one in longitude/latitude. Whether it did: not for an empty extent + /// or view. + pub fn fit_map_extent(&mut self, m: &Extent, w: f64, h: f64) -> bool { + if m.is_empty() || w <= 1.0 || h <= 1.0 { + return false; + } + self.camera.fit_extent(&m.padded(0.06, 0.0), w, h); + true + } + /// Switches projection, keeping the centre and the ground scale. /// Bookmarks move with it, so they still show the same place. pub fn set_projection(&mut self, p: Projection) { @@ -4361,6 +4452,41 @@ mod tests { assert!(!m.layer(id).unwrap().is_cached("mercator")); } + /// A layer held in the system its map is drawn in gets display copies made from its own rows, + /// simplified as they are, with nothing converted and no full copy of it on the map; a map in + /// another system makes none (it draws the projected copy, as before), and a projection made + /// there drops those copies. + #[test] + fn a_held_layer_gets_display_copies_on_a_map_in_its_own_system() { + let utm = Crs::Epsg(32632); + let n = lod::THIN_ABOVE + 1000; + let mut d = Dataset::new("zigzag", GeometryType::Polyline, vec![]); + // Some 100 km east from 9°E at 48°N, zigzagging a metre either side. + let run: Vec = (0..n) + .map(|i| Coord::new(500_000.0 + 100_000.0 * i as f64 / n as f64, 5_316_000.0 + if i % 2 == 0 { 1.0 } else { -1.0 })) + .collect(); + d.push(Some(Geometry::Line(vec![run.clone()])), vec![]); + d.held_in = utm; + let mut l = Layer::new(1, d); + let own = projection::Flat::of(&Projection::Custom("EPSG:32632".into())); + assert!(l.prepare_display(&own, 1_000.0, false)); + assert!(l.projected_cache().is_empty(), "no copy of the whole layer on the map"); + let (g, extents) = l.display_cache().unwrap(); + let Some(Geometry::Line(parts)) = &g[0] else { panic!("a line") }; + assert!(lod::vertices(g[0].as_ref().unwrap()) < n / 40, "{}", lod::vertices(g[0].as_ref().unwrap())); + // Its ends exactly as held. + assert_eq!((parts[0][0], *parts[0].last().unwrap()), (run[0], *run.last().unwrap())); + assert_eq!(extents, &[l.dataset.features[0].geometry.as_ref().unwrap().extent()]); + // On a map in another system, and on Web Mercator, none is made. + let other = projection::Flat::of(&Projection::Custom("EPSG:25832".into())); + assert!(!l.prepare_display(&other, 1_000.0, false)); + assert!(!l.prepare_display(&projection::Flat::Mercator, 1_000.0, false)); + // Drawn there, the copies made for its own system go. + assert!(l.prepare_display(&own, 1_000.0, false)); + l.projected_in(&other, "etrs"); + assert!(l.display_levels.is_empty()); + } + #[test] fn display_projection_is_lazy_shared_bounded_and_invalidated() { let flat = projection::Flat::Mercator; @@ -4392,7 +4518,7 @@ mod tests { l.clear_cache(); assert!(l.display_cache().is_none()); assert_eq!(l.view_cache_bytes(), rustgis_data::source::memory::features_bytes(&original)); - assert!(lod::display(&original, 0, 12, 1, false).is_none()); + assert!(lod::display(&original, lod::Rows::LonLat, 0, 12, 1, false).is_none()); assert!(!long_line(100).prepare_display(&flat, 12_000.0, false)); assert_eq!(l.dataset.features, original); } @@ -4566,10 +4692,10 @@ mod tests { #[test] fn geometry_only_lod_does_not_charge_for_unused_extents() { let l = long_line(100); - let copy = lod::project_budgeted(&l.dataset.features, 20, usize::MAX).unwrap(); + let copy = lod::project_budgeted(&l.dataset.features, lod::Rows::LonLat, 20, usize::MAX).unwrap(); let budget = lod::cache_bytes(©); - assert_eq!(lod::project_budgeted(&l.dataset.features, 20, budget).unwrap(), copy); - assert!(lod::display(&l.dataset.features, 0, 20, budget, true).is_none()); + assert_eq!(lod::project_budgeted(&l.dataset.features, lod::Rows::LonLat, 20, budget).unwrap(), copy); + assert!(lod::display(&l.dataset.features, lod::Rows::LonLat, 0, 20, budget, true).is_none()); } /// Tilted bands and zoom reversals reuse bounded display levels shared by snapshots. @@ -4633,7 +4759,7 @@ mod tests { l.projected(); assert_eq!(l.display_levels.len(), 1); let base = l.view_memory.base(&l.dataset.features, &l.projected, &l.projected_extents); - let copy = lod::project_budgeted(&l.dataset.features, lod::level(24_000.0).unwrap(), usize::MAX).unwrap(); + let copy = lod::project_budgeted(&l.dataset.features, lod::Rows::LonLat, lod::level(24_000.0).unwrap(), usize::MAX).unwrap(); let extra = lod::cache_bytes(©); let mut source = source::SourceLayer::default(); source.byte_budget = base + display_bytes + extra; diff --git a/crates/map/src/lod.rs b/crates/map/src/lod.rs index 6ed46da2bf..05d2d2d52d 100644 --- a/crates/map/src/lod.rs +++ b/crates/map/src/lod.rs @@ -90,11 +90,23 @@ pub fn project_thinned(g: &Geometry, flat: &crate::projection::Flat, tol: f64) - simplify_mapped(g, tol, Some(&|c: Coord| flat.forward_checked(c).unwrap_or(Coord::new(f64::NAN, f64::NAN)))) } -/// Builds a Mercator display level without ever constructing the full projected geometry. -/// Original extents are transformed separately so thinning cannot change culling or splats. -/// Both the geometry and its extent table fit in the optional display-cache budget. +/// Where a display level's rows are on the map ([`display`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Rows { + /// In longitude/latitude, on a Web Mercator map: projected as they are simplified. + LonLat, + /// In the map's own coordinates (a layer held in the system the map is drawn in): simplified + /// as they are, with nothing converted. + MapUnits, +} + +/// Builds a display level without ever constructing the full projected geometry: from rows in +/// longitude/latitude on a Web Mercator map, or from rows already in the map's coordinates +/// ([`Rows`]). Original extents are transformed separately so thinning cannot change culling or +/// splats. Both the geometry and its extent table fit in the optional display-cache budget. pub(crate) fn display( features: &[rustgis_data::Feature], + rows: Rows, revision: u64, level: i32, budget: usize, @@ -107,18 +119,20 @@ pub(crate) fn display( return None; } let extent_bytes = features.len().checked_mul(std::mem::size_of::())?; - let geometries = project_budgeted(features, level, budget.checked_sub(extent_bytes)?)?; + let budget = budget.checked_sub(extent_bytes)?; + let geometries = project_budgeted(features, rows, level, budget)?; let all: usize = features.iter().filter_map(|f| f.geometry.as_ref()).map(vertices).sum(); let kept: usize = geometries.iter().flatten().map(vertices).sum(); if !whole_layer_eligible && kept as f64 > all as f64 * (1.0 - MIN_SAVING) { return None; } - // Mercator is monotone in both axes; two opposite corners bound every source vertex. + // Mercator is monotone in both axes; two opposite corners bound every source vertex. Rows in + // map coordinates already have their extents there. let extents = features .iter() .map(|f| { let e = f.geometry.as_ref().map_or(rustgis_geom::Extent::EMPTY, Geometry::extent); - if e.is_empty() { + if e.is_empty() || rows == Rows::MapUnits { e } else { rustgis_geom::Extent::from_points( @@ -132,11 +146,21 @@ pub(crate) fn display( Some(Display { revision, level, whole_layer_eligible, geometries, extents, bytes }) } -/// Builds only Mercator display geometry within `budget`. Callers apply their own eligibility -/// and saving rules; exact consumers already have extents and need no second extent table. -pub(crate) fn project_budgeted(features: &[rustgis_data::Feature], level: i32, budget: usize) -> Option>> { +/// Builds only display geometry within `budget`: Mercator from rows in longitude/latitude, the +/// rows simplified as they are when they are in the map's coordinates ([`Rows`]). Callers apply +/// their own eligibility and saving rules; exact consumers already have extents and need no second +/// extent table. +pub(crate) fn project_budgeted(features: &[rustgis_data::Feature], rows: Rows, level: i32, budget: usize) -> Option>> { let tol = tolerance(level); - map_budgeted(features, budget, |f| f.geometry.as_ref(), |g| project_thinned(g, &crate::projection::Flat::Mercator, tol)) + map_budgeted( + features, + budget, + |f| f.geometry.as_ref(), + |g| match rows { + Rows::LonLat => project_thinned(g, &crate::projection::Flat::Mercator, tol), + Rows::MapUnits => simplify(g, tol), + }, + ) } /// Heap allocation held by a geometry's vectors (the enum itself is in its containing array). diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 856104e762..317e4731f6 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5319,6 +5319,10 @@ fn render_frame( // In longitude/latitude, which the globe draws (none for a layer held there). layer.lonlat_in(); } + if display_only { + // A copy for the map it was drawn on before is of no use here. + layer.release_projected_other_than(&key); + } if globe.is_none() && !display_only { if complete_source { layer.projected_in(&flat, &key); @@ -7617,13 +7621,41 @@ fn square_lines( continue; } let Some(layer) = map.layer_by_name(&name) else { continue }; - if layer.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat { + let crs = layer.dataset.coord_crs(); + let drawing = if ctx.globe.is_none() && crs != rustgis_data::raster::Crs::LonLat { flat.held(crs).ok() } else { None }; + // A label squared to it reads its places in longitude/latitude, which count what can't be + // given there ([`note_held_read`]): not on a map in its own system, which reads none. + if crs != rustgis_data::raster::Crs::LonLat && !drawing.as_ref().is_some_and(|d| d.is_identity()) { held.insert(name.clone(), layer.id); } let mut runs = Vec::new(); - // Read in longitude/latitude, whatever system the layer holds its coordinates in; a - // feature that can't be given there squares nothing (nor any, in a system that can't be - // converted), as the map draws none of it. + // On the flat map, a layer held in another system than longitude/latitude is read in map + // coordinates as the map draws it ([`rustgis_map::projection::Flat::held`]): as it is on + // a map in its own system, by the direct operation on one in another, so a label squares + // to the line where it is drawn; a place the map can't show breaks the line there. + if ctx.globe.is_none() && crs != rustgis_data::raster::Crs::LonLat { + // A system that can't be converted squares nothing, as the map draws none of it. + let Some(drawing) = &drawing else { continue }; + for g in layer.dataset.features.rows().filter_map(|r| r.geometry()) { + // On a map in its own system, as it is, with no copy. A place that can't be given + // in longitude/latitude (`HeldDrawing::geometry`'s flag) is what the held read + // counts ([`note_held_read`]); one the map doesn't show breaks the line here, as + // the map's own drawing leaves it out, uncounted there too. + let drawn = + if drawing.is_identity() { std::borrow::Cow::Borrowed(g) } else { std::borrow::Cow::Owned(drawing.geometry(g).0) }; + for part in outline_parts(&drawn) { + let points: Vec> = + part.iter().map(|m| m.is_finite().then(|| ctx.view.to_screen(*m)).map(|(x, y)| (x as f32, y as f32))).collect(); + runs.extend( + points.split(Option::is_none).map(|r| r.iter().flatten().copied().collect()).filter_map(square_labels::Run::new), + ); + } + } + out.insert(name, runs); + continue; + } + // Else read in longitude/latitude; a feature that can't be given there squares nothing + // (nor any, in a system that can't be converted), as the map draws none of it. let Ok(to) = layer.dataset.shown_conversion() else { continue }; for g in layer.dataset.features.iter().filter_map(|f| rustgis_data::Dataset::converted_to_lonlat(&to, f.geometry.as_ref()?)) { let (parts, rings): (Vec<&Vec>, bool) = match &*g { @@ -7649,6 +7681,22 @@ fn square_lines( out } +/// A line's parts and a polygon's rings, each ring closed as its outline is drawn; none for points. +fn outline_parts(g: &Geometry) -> Vec> { + match g { + Geometry::Line(parts) => parts.iter().map(|p| std::borrow::Cow::Borrowed(p.as_slice())).collect(), + Geometry::Polygon(polys) => polys + .iter() + .flatten() + .map(|r| match (r.first(), r.last()) { + (Some(a), Some(b)) if a != b => std::borrow::Cow::Owned(r.iter().chain([a]).copied().collect()), + _ => std::borrow::Cow::Borrowed(r.as_slice()), + }) + .collect(), + _ => Vec::new(), + } +} + /// A line's runs on the globe in screen points: bent along great circles and cut at the horizon, /// as [`Ctx::globe_line`] strokes it. fn globe_runs(g: &Globe, part: &[Coord]) -> Vec> { @@ -9736,6 +9784,40 @@ mod tests { assert!(far.angle.is_none() && far.y < fy as f32, "as auto: {:?} {} {fy}", far.angle, far.y); } + /// On a map in a line layer's own system, a label squares to the line as the map holds it, + /// read in map coordinates with nothing converted: a slanting coast held in UTM 32N, on a map + /// in UTM 32N, turns the label square to it there. + #[test] + fn a_label_squares_to_a_line_held_in_the_maps_system() { + let utm = rustgis_data::raster::Crs::Epsg(32632); + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + m.set_projection(rustgis_map::Projection::Custom("EPSG:32632".into())); + // A coast slanting at 45° in UTM, a kilometre long. + let mut d = Dataset::new("coast", GeometryType::Polyline, vec![]); + d.push(Some(Geometry::Line(vec![vec![Coord::new(500_000.0, 5_300_000.0), Coord::new(501_000.0, 5_301_000.0)]])), vec![]); + d.held_in = utm; + m.add_dataset(d); + // A beach 50 m north-west of the coast's middle, held in UTM too. + let mut d = Dataset::new("beaches", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(500_464.6, 5_300_535.4))), vec![Value::Text("Beach".into())]); + d.held_in = utm; + let pts = m.add_dataset(d); + let l = m.layer_mut(pts).unwrap(); + l.labels.enabled = true; + l.labels.default.placement = LabelPlacement::Perpendicular; + l.labels.default.square_to = + Some(rustgis_map::SquareTo { layer: "coast".into(), within: 20.0, side: rustgis_map::SquareSide::Away }); + let camera = Camera { center: Coord::new(500_500.0, 5_300_500.0), res: 5.0, bearing: 0.0, pitch: 0.0 }; + m.camera = camera; + let view = View { width: 300.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }; + let labels = render(&mut m, &view).unwrap().labels; + let beach = labels.iter().find(|l| l.text == "Beach").expect("labelled"); + let a = beach.angle.expect("turned").to_degrees(); + // The coast runs up to the right on the screen (y down: along -45°); square to it, 45°. + assert!((a.rem_euclid(180.0) - 45.0).abs() < 0.5, "{a}"); + } + /// A drawing that panics (a command's panic is caught) leaves nothing noted: reads outside a /// drawing are noted nowhere after it, as before it. #[test] diff --git a/crates/render/src/lod_tests.rs b/crates/render/src/lod_tests.rs index 5620c4cd9d..b249243c4c 100644 --- a/crates/render/src/lod_tests.rs +++ b/crates/render/src/lod_tests.rs @@ -239,3 +239,32 @@ fn lod_landcover_whole_frame_benchmark() { assert!(first.pixmap.data().as_chunks::<4>().0.iter().any(|p| p != background), "benchmark must contain rendered polygons"); } } + +/// The land cover held in UTM zone 37S, drawn on a map in that system: plain drawing takes display +/// copies simplified from its own rows, with no full copy of the layer on the map, and draws what +/// the full geometry draws. +#[test] +fn lod_display_of_a_layer_held_in_the_maps_system() { + let utm = rustgis_data::raster::Crs::Epsg(32737); + let mut map = landcover(84); + // Drawn on Web Mercator first, with labels, which need the projected copy. + map.layers[0].dataset.hold_in(utm).unwrap(); + map.layers[0].labels.enabled = true; + let e = map.layers[0].extent(); + let mercator = + View { width: 420.0, height: 320.0, pixels_per_point: 1.0, sky: false, camera: Camera::new(lonlat_to_merc(e.center()), 100.0) }; + render(&mut map, &mercator).unwrap(); + assert!(!map.layers[0].projected_cache().is_empty()); + map.layers[0].labels.enabled = false; + map.set_projection(rustgis_map::Projection::Custom("EPSG:32737".into())); + let mut full = unthinned(&map); + let e = map.layers[0].dataset.extent(); + let view = + View { width: 420.0, height: 320.0, pixels_per_point: 1.0, sky: false, camera: Camera::new(e.center(), e.width() / 420.0 * 1.2) }; + let expected = render(&mut full, &view).unwrap(); + let got = render(&mut map, &view).unwrap(); + assert!(map.layers[0].projected_cache().is_empty(), "plain drawing keeps no copy of the layer, nor Web Mercator's"); + assert!(map.layers[0].display_cache().is_some()); + let (mean, _) = difference(&expected.pixmap, &got.pixmap); + assert!(mean < 3.0, "mean channel difference {mean}"); +} diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 375a17fda8..3ee8c63f41 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -6,7 +6,7 @@ //! and well under a pixel off for projected ones. Values are then sampled (nearest or bilinear), //! optionally re-stretched from the pixels in view (DRA), and coloured. -use rustgis_data::raster::{BandStats, ColorHint, Raster}; +use rustgis_data::raster::{BandStats, ColorHint, Raster, Reprojection}; use rustgis_geom::{Coord, Extent, extent_to_merc, lonlat_to_merc}; use rustgis_map::Globe; use rustgis_map::projection::Flat; @@ -28,7 +28,7 @@ pub(crate) enum Place<'a> { Flat(&'a Flat, &'a str), } -fn source(r: &Raster, view: &View, place: Place, k: f64, dx: f64, dy: f64) -> Option<(f64, f64)> { +fn source(r: &Raster, view: &View, place: Place, direct: Option<&Reprojection>, k: f64, dx: f64, dy: f64) -> Option<(f64, f64)> { let ppp = view.pixels_per_point / k; let (sx, sy) = (dx / ppp, dy / ppp); let n = match place { @@ -36,11 +36,16 @@ fn source(r: &Raster, view: &View, place: Place, k: f64, dx: f64, dy: f64) -> Op Place::Flat(Flat::Mercator, _) => r.transformer().from_merc(view.camera.to_map(sx, sy, view.width, view.height))?, Place::Flat(flat, key) => { let m = view.camera.to_map(sx, sy, view.width, view.height); + let map = flat.direct_system(); // A raster already in the map's coordinate system needs no reprojection. - if key.strip_prefix("EPSG:").and_then(|c| c.parse::().ok()) == Some(r.crs.epsg()) { + if map == Some(r.crs) || key.strip_prefix("EPSG:").and_then(|c| c.parse::().ok()) == Some(r.crs.epsg()) { m } else { - r.transformer().from_lonlat(flat.inverse(m)?)? + // Through longitude/latitude, where the map shows the place; on a map in a + // coordinate system, then by the direct operation between the two (the datum + // transformation PROJ picks for the pair), as a held layer's features are drawn. + let via = r.transformer().from_lonlat(flat.inverse(m)?)?; + direct.map_or(via, |to| to.point_near(m, via)) } } }; @@ -48,6 +53,19 @@ fn source(r: &Raster, view: &View, place: Place, k: f64, dx: f64, dy: f64) -> Op (c.is_finite() && row.is_finite()).then_some((c, row)) } +/// The direct operation from the map's system to the raster's, on a flat map in a coordinate +/// system ([`Flat::direct_system`]) other than the raster's: each map place is looked up in the +/// raster by it where it lands near the place through WGS 84 ([`Reprojection::point_near`]), as a +/// held layer's features are drawn. Built once a draw, on the drawing's own thread (which says the +/// grids it uses, and fetches the operation again for grids that arrive), and shared by the +/// threads that sample it; `None` elsewhere, or for a pair with no operation between them, which +/// is sampled through WGS 84 as before. +fn direct_of(r: &Raster, place: Place) -> Option { + let Place::Flat(flat, _) = place else { return None }; + let map = flat.direct_system().filter(|m| *m != r.crs)?; + map.to(r.crs).ok() +} + /// A whole geographic turn has exactly this many columns. Compare the grid's span rather /// than truncating `360 / pixel_width`: a regional grid can end partway through that column. pub(crate) fn full_turn_width(r: &Raster) -> Option { @@ -334,7 +352,9 @@ fn in_view(r: &Raster, view: &View, place: Place, width: u32, height: u32, full_ let k = if view.pixels_per_point >= 1.5 && !full_res { view.pixels_per_point } else { 1.0 }; let (vw, vh) = (f64::from(width) / k, f64::from(height) / k); let n = WINDOW_GRID; - let at = |i: usize, j: usize| source(r, view, place, k, vw * i as f64 / (n - 1) as f64, vh * j as f64 / (n - 1) as f64); + let direct = direct_of(r, place); + let at = + |i: usize, j: usize| source(r, view, place, direct.as_ref(), k, vw * i as f64 / (n - 1) as f64, vh * j as f64 / (n - 1) as f64); let grid: Vec> = (0..n * n).map(|p| at(p % n, p / n)).collect(); let (mut c0, mut c1, mut r0, mut r1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); let (rw, rh) = (f64::from(r.width), f64::from(r.height)); @@ -402,6 +422,7 @@ fn draw_with( // for full resolution, as exports are): a quarter of the work at 2×. let k = if view.pixels_per_point >= 1.5 && !full_res { view.pixels_per_point } else { 1.0 }; let (w, h) = ((pm.width() as f64 / k).ceil(), (pm.height() as f64 / k).ceil()); + let direct = direct_of(r, place); let ppp = view.pixels_per_point / k; // The raster's bounds on screen, clipped to the view. let ((ax, ay), (bx, by)) = match place { @@ -435,7 +456,14 @@ fn draw_with( (view.to_screen(Coord::new(e.min_x, e.max_y)), view.to_screen(Coord::new(e.max_x, e.min_y))) } Place::Flat(flat, _) => { - let e = flat.extent(&r.extent()); + // Its place through WGS 84, and by the direct operation where it is drawn by one: a + // pixel on the edge is drawn wherever either puts it. + let mut e = flat.extent(&r.extent()); + if let Some(to) = direct.as_ref().and_then(|_| r.crs.to(flat.direct_system()?).ok()) { + let t = r.transform; + let own = Extent::from_points(t.to_world(0.0, 0.0), t.to_world(f64::from(r.width), f64::from(r.height))); + e = e.union(&to.extent(&own)); + } if e.is_empty() { return; } @@ -474,7 +502,7 @@ fn draw_with( each_chunk(grid_threads, grid.chunks_mut(grid_rows * gw).enumerate(), |(i, chunk)| { for (j, cell) in chunk.iter_mut().enumerate() { let (gx, gy) = (j % gw, i * grid_rows + j / gw); - *cell = source(r, view, place, k, (x0 + gx * STEP) as f64, (y0 + gy * STEP) as f64); + *cell = source(r, view, place, direct.as_ref(), k, (x0 + gx * STEP) as f64, (y0 + gy * STEP) as f64); } }); @@ -516,6 +544,7 @@ fn draw_with( r, view, place, + direct: direct.as_ref(), k, rotated: rotated.then_some((centre, sin, cos)), x0, @@ -713,6 +742,8 @@ struct Pass1<'a> { r: &'a Raster, view: &'a View, place: Place<'a>, + /// The direct operation from the map's system to the raster's ([`direct_of`]). + direct: Option<&'a Reprojection>, k: f64, /// A rotated raster's centre on screen and the sine and cosine of its back-rotation. rotated: Option<((f64, f64), f64, f64)>, @@ -796,7 +827,15 @@ impl Pass1<'_> { // Back-rotate the screen pixel about the centre, then find its source exactly. Some((centre, sin, cos)) => { let (ddx, ddy) = (px as f64 + 0.5 - centre.0, py as f64 + 0.5 - centre.1); - source(r, self.view, self.place, self.k, centre.0 + ddx * cos - ddy * sin, centre.1 + ddx * sin + ddy * cos) + source( + r, + self.view, + self.place, + self.direct, + self.k, + centre.0 + ddx * cos - ddy * sin, + centre.1 + ddx * sin + ddy * cos, + ) } None => { let u = dx as f64 + 0.5; @@ -806,7 +845,7 @@ impl Pass1<'_> { (Some(a), Some(b)) if (a.0 - b.0).abs() <= self.seam => Some((lerp(a.0, b.0, fx), lerp(a.1, b.1, fx))), // Near the edge of the projection's valid area, or across a seam: // transform this pixel exactly. - _ => source(r, self.view, self.place, self.k, px as f64 + 0.5, py as f64 + 0.5), + _ => source(r, self.view, self.place, self.direct, self.k, px as f64 + 0.5, py as f64 + 0.5), } } }; @@ -1635,6 +1674,27 @@ mod tests { assert!(at(-5.0).1 > at(-100.0).1 && at(5.0).1 < at(80.0).1, "{:?} {:?}", at(-5.0), at(5.0)); } + /// A raster in Gauss-Krüger zone 3 on DHDN (EPSG:31467) on a map in ETRS89 UTM 32N + /// (EPSG:25832): each map place is looked up in the raster by the direct operation between the + /// two, as a held layer's features are drawn, not through WGS 84 (0.37 m off there). PROJ 9.9.0: + /// echo "513223.740371 5403015.206314" | cs2cs -f %.6f EPSG:25832 EPSG:31467 + /// -> 5404737.597295 3513304.512454 ("DHDN to ETRS89 (2)", northing first) + #[test] + fn a_raster_on_a_datum_pair_is_drawn_by_the_direct_operation() { + let gt = GeoTransform { origin_x: 3_513_000.0, origin_y: 5_405_000.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new("gk", 1000, 1000, vec![vec![1.0; 1_000_000]], gt, Crs::Epsg(31467), None, ColorHint::Gray, "Float32").unwrap(); + let flat = Flat::of(&rustgis_map::Projection::Custom("EPSG:25832".into())); + let camera = Camera { center: Coord::new(513_223.740371, 5_403_015.206314), res: 1.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 2.0, height: 2.0, pixels_per_point: 1.0, camera, sky: false }; + let place = Place::Flat(&flat, "EPSG:25832"); + let (c, row) = source(&r, &view, place, direct_of(&r, place).as_ref(), 1.0, 1.0, 1.0).unwrap(); + let (x, y) = (3_513_000.0 + c, 5_405_000.0 - row); + assert!((x - 3_513_304.512454).abs() < 1e-3 && (y - 5_404_737.597295).abs() < 1e-3, "{x} {y}"); + // The way through WGS 84 lands elsewhere. + let via = r.transformer().from_lonlat(flat.inverse(camera.center).unwrap()).unwrap(); + assert!((via.x - x).hypot(via.y - y) > 0.1, "{via:?}"); + } + /// A lon/lat grid on a map centred on the Pacific: across 180°, where the source longitude /// jumps from one end of the grid to the other, no strip of values from elsewhere shows. #[test] diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 7826b529f6..5563a51c3e 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -196,11 +196,14 @@ status bar. Remote FlatGeobuf date/time columns stay ISO text with a notice so opening them can keep reading by range without downloading every feature. -Vector geometry is stored as WGS 84 longitude/latitude. Data in another supported coordinate -system is converted as it is read; Shapefiles use their `.prj`, and formats such as GeoPackage, -GeoParquet and FlatGeobuf carry their coordinate system in the file. Rasters keep their own -coordinate system and are reprojected as they draw. The map uses Web Mercator by default, but -**View › Projection** can change it; see [Maps](maps.md). +A layer keeps its file's own coordinates and coordinate system; Shapefiles use their `.prj`, and +formats such as GeoPackage, GeoParquet and FlatGeobuf carry their coordinate system in the file. +Rasters keep theirs too. The map uses Web Mercator by default, but **View › Projection** can +change it; see [Maps](maps.md). On a map in a coordinate system, a layer or raster in that system +is drawn as it is, and one in another system by the transformation PROJ picks between the two +(between two datums, the one for that pair, not one through WGS 84). There, Zoom To Layer, Zoom To +Selection and Full Extent frame a layer in the map's system by its own coordinates, and its +simplified drawing at small scales is made from them, with nothing converted. Coordinate systems are read and transformed as PROJ 9.9.0 does, through terrio-crs. A few EPSG and ESRI codes PROJ 9.9.0 dropped or can't compute (EPSG:3752 and 22700, ESRI:10820 and 65162)