diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 836b9af776..a8b0dfb51a 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -611,21 +611,9 @@ fn dist_m(a: Coord, b: Coord) -> f64 { rustgis_geom::haversine_m(a, b) } -/// Elevation (bilinear) at a longitude/latitude point. +/// Elevation (bilinear) at a longitude/latitude point ([`Raster::bilinear`]). pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { - let w = r.transformer().from_lonlat(ll)?; - let (x, y) = r.transform.to_pixel(w); - let (x, y) = (x - 0.5, y - 0.5); - let (c0, r0) = (x.floor() as i64, y.floor() as i64); - let (fx, fy) = (x - c0 as f64, y - r0 as f64); - let v = |c: i64, rr: i64| r.value(b, c, rr).map(f64::from); - let (a, b2, c, d) = (v(c0, r0), v(c0 + 1, r0), v(c0, r0 + 1), v(c0 + 1, r0 + 1)); - match (a, b2, c, d) { - (Some(a), Some(b2), Some(c), Some(d)) => { - Some(a * (1.0 - fx) * (1.0 - fy) + b2 * fx * (1.0 - fy) + c * (1.0 - fx) * fy + d * fx * fy) - } - _ => v(x.round() as i64, y.round() as i64), - } + r.bilinear(b, ll) } /// An elevation profile along a path: (distance from the start in metres, point, elevation). diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 435eab9865..7426564699 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1350,6 +1350,26 @@ impl Raster { if wrapped < w { wrapped } else { c } } + /// The value of `band` at a longitude/latitude point, read bilinearly between the four cell + /// centres around it, in the raster's own system: the nearest cell's where one of the four is + /// no-data or off the grid, and `None` where that one is too. A grid stored from 0 to 360° is + /// read at a western longitude in its columns past 180° ([`Raster::wrap_col`]). The elevation profiles read + /// this (`profile.*`, and a layout's profiles beside a map frame, #2863). + pub fn bilinear(&self, band: usize, lonlat: Coord) -> Option { + let w = self.transformer.from_lonlat(lonlat)?; + let (x, y) = self.transform.to_pixel(w); + let (x, y) = (self.wrap_col(x) - 0.5, y - 0.5); + let (c0, r0) = (x.floor() as i64, y.floor() as i64); + let (fx, fy) = (x - c0 as f64, y - r0 as f64); + let v = |c: i64, r: i64| self.value(band, c, r).map(f64::from); + match (v(c0, r0), v(c0 + 1, r0), v(c0, r0 + 1), v(c0 + 1, r0 + 1)) { + (Some(a), Some(b), Some(c), Some(d)) => { + Some(a * (1.0 - fx) * (1.0 - fy) + b * fx * (1.0 - fy) + c * (1.0 - fx) * fy + d * fx * fy) + } + _ => v(x.round() as i64, y.round() as i64), + } + } + /// Cell size in the raster's units (x, y). pub fn cell_size(&self) -> (f64, f64) { (self.transform.pixel_width.abs(), self.transform.pixel_height.abs()) @@ -2767,6 +2787,19 @@ pub(crate) mod tests { assert!(grid(-0.25, 720, 0.5, Crs::LonLat).wrap_col(f64::NAN).is_nan()); } + /// A grid stored from 0 to 360° is read bilinearly at a western longitude in its columns past + /// 180°, as `pixel_at` finds it (#1109), not as off the grid (#2863). + #[test] + fn a_western_place_on_a_grid_past_180_is_read_bilinearly() { + let gt = GeoTransform { origin_x: -0.25, origin_y: 77.25, pixel_width: 0.5, pixel_height: -0.5 }; + let data = (0..720 * 309).map(|i| (i % 720) as f32).collect(); + let r = Raster::new("g", 720, 309, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let at = |lon: f64| r.bilinear(0, Coord::new(lon, 0.0)); + assert!(at(100.0).is_some_and(|v| (v - 200.0).abs() < 1e-6), "{:?}", at(100.0)); + assert!(at(-100.0).is_some_and(|v| (v - 520.0).abs() < 1e-6), "260°: {:?}", at(-100.0)); + assert!(at(-100.1).is_some_and(|v| (v - 519.8).abs() < 1e-6), "259.9°: {:?}", at(-100.1)); + } + #[test] fn geographic_extent_uses_greenwich_not_the_native_prime_meridian() { let crs = Crs::parse("+proj=longlat +datum=WGS84 +pm=paris +no_defs").unwrap(); diff --git a/crates/engine/src/tests/layout_profiles.rs b/crates/engine/src/tests/layout_profiles.rs index d4945a81f6..52321fa9c9 100644 --- a/crates/engine/src/tests/layout_profiles.rs +++ b/crates/engine/src/tests/layout_profiles.rs @@ -1,6 +1,9 @@ -//! Profiles beside a layout's map frame (#2863 part 2): the commands and what they say. +//! Profiles beside a layout's map frame (#2863 part 2): the commands, what they say, and how a +//! profile agrees with `profile.create`. use crate::{Session, sample}; +use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; +use rustgis_geom::Coord; use rustgis_map::layout::{ElementKind, Profile, ProfileSide}; use serde_json::json; @@ -46,3 +49,57 @@ fn a_box_given_to_a_profile_is_said_not_kept() { s.run("layout.update", &json!({"element": frame, "x": 20})).unwrap(); assert!(s.notices_since(mark).is_empty(), "the frame takes its profile along"); } + +/// The Mantiqueira of #2863: a vertical section line of a UTM 23S frame through the Pedra da Mina, +/// whose profile `profile.create` gave again within 0.11 m over 1,600 samples of the Copernicus DEM. +/// On a relief of that frame, the profile's samples and `profile.create`'s between the line's ends, +/// as many, agree as closely: a vertical line of a UTM frame strays little from the straight line +/// of longitude and latitude between its ends. +#[test] +fn the_mantiqueira_profile_agrees_with_profile_create() { + let mut s = Session::new(sample::world_project()); + s.run("map.projection", &json!({"type": "EPSG:31983"})).unwrap(); + let crs = Crs::from_epsg(31983).unwrap(); + let to = crs.transformer().unwrap(); + let mid = to.from_lonlat(Coord::new(-44.715, -22.412)).unwrap(); + let (cols, rows, cell) = (1600usize, 1000usize, 30.0); + let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell); + // Ridges and valleys a few kilometres across, some 2,000 m of relief, as the Mantiqueira's. + let z = |e: f64, n: f64| 1500.0 + 600.0 * (e / 2_300.0).sin() * (n / 1_700.0).cos() + 300.0 * ((e + n) / 900.0).sin(); + let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect(); + let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell }; + let r = Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").unwrap(); + s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif")); + s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "blank"})).unwrap(); + s.run("layout.addFrame", &json!({})).unwrap(); + let frame = s.project.layouts[0].first_frame().unwrap(); + s.run( + "layout.update", + &json!({"element": frame, "x": 30, "y": 34, "w": 186, "h": 112, "center": [-44.715, -22.412], "scale": 200_000}), + ) + .unwrap(); + s.run("layout.addElement", &json!({"kind": "section", "direction": "vertical", "at": [-44.8429, -22.4282]})).unwrap(); + let id = put_profile(&mut s, frame, ProfileSide::Right); + let ElementKind::Profile(p) = &s.project.layouts[0].element(id).unwrap().kind else { panic!("a profile") }; + let (samples, _) = rustgis_render::layout::profile_samples(&s.project.layouts[0], &s.project.maps, p).unwrap(); + // The line's ends on the ground, as the frame shows them. + let map = &s.project.maps[0]; + let ElementKind::MapFrame { center, scale, .. } = &s.project.layouts[0].element(frame).unwrap().kind else { panic!("a frame") }; + let cam = rustgis_map::layout::frame_camera(map, *center, *scale, 0.0, 0.0); + let (fw, fh) = (186.0 * rustgis_map::layout::PT_PER_MM, 112.0 * rustgis_map::layout::PT_PER_MM); + let (x, _) = cam.try_to_screen(map.to_map(Coord::new(-44.8429, -22.4282)).unwrap(), fw, fh).unwrap(); + let ends: Vec<[f64; 2]> = + [0.0, fh].iter().map(|y| map.to_lonlat(cam.try_to_map(x, *y, fw, fh).unwrap()).unwrap()).map(|c| [c.x, c.y]).collect(); + let n = samples.values.len(); + assert!(n > 700, "a sample a cell: {n}"); + let got = s.run("profile.create", &json!({"layer": "DEM", "points": ends, "samples": n})).unwrap(); + let theirs: Vec = got["samples"].as_array().unwrap().iter().map(|r| r["elevation"].as_f64().unwrap()).collect(); + assert_eq!(theirs.len(), n); + let off = samples.values.iter().zip(&theirs).map(|(a, b)| (a.unwrap() - b).abs()).fold(0.0, f64::max); + assert!(off < 0.5, "{off} m apart"); + // Its length is the frame's height on the ground (112 mm at 1:200,000, the UTM scale factor + // aside) on the ellipsoid; profile.create's, on the sphere, a few tenths of a percent longer. + let (ours, theirs) = (*samples.metres.last().unwrap(), got["length"].as_f64().unwrap()); + assert!((ours / 22_400.0 - 1.0).abs() < 0.002, "{ours} m"); + assert!((theirs / ours - 1.0).abs() < 0.006, "{theirs} m against {ours} m"); +} diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index d860ec84e0..f72558528d 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -2064,10 +2064,12 @@ fn a_profile_keeps_to_its_frames_side() { assert_eq!(l.fit_profiles(), 0, "already beside it"); // Saved with only what isn't its default; read back as saved; a repaired one needs nothing more. let text = serde_json::to_string(&l).unwrap(); - let saved = text.split("\"Profile\":").nth(1).unwrap(); - for left_out in ["\"band\"", "\"min\"", "\"max\"", "\"units\"", "\"guides\"", "\"color\"", "\"title\"", "\"unit\""] { - assert!(!saved.contains(left_out), "{left_out} in {saved}"); + let value: serde_json::Value = serde_json::from_str(&text).unwrap(); + let saved = value["elements"].as_array().unwrap().iter().find_map(|e| e["kind"]["Profile"].as_object()).unwrap(); + for left_out in ["band", "min", "max", "units", "guides", "color", "title", "unit"] { + assert!(!saved.contains_key(left_out), "{left_out} in {saved:?}"); } + assert!(saved.contains_key("section"), "the profile's own object: {saved:?}"); let back: Layout = serde_json::from_str(&text).unwrap(); assert_eq!(back, l); assert!(l.clamp().is_empty()); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index fa02cac924..9ad468cab4 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -28,6 +28,7 @@ mod grid; mod legend; mod losses; mod north; +mod profile; mod scale_bar; mod section; mod swatch; @@ -43,6 +44,7 @@ pub use grid::*; pub use legend::*; pub use losses::*; use north::*; +pub use profile::*; pub use scale_bar::*; pub use section::*; use swatch::*; @@ -692,7 +694,7 @@ fn draw_page( None => placeholder(&mut pm, r, "Chart", ppp), } } - // What it reads and draws comes in its own steps (#2863 parts 2b to 2d). + // What it reads is worked out from 2b (`profile_samples`); it is said in 2c and drawn in 2d (#2863). ElementKind::Profile(_) => placeholder(&mut pm, r, "Profile", ppp), ElementKind::Rectangle { fill, outline, width, radius, dash } => { // Square corners filled as before, so an existing layout draws to the same pixels. diff --git a/crates/render/src/layout/profile.rs b/crates/render/src/layout/profile.rs new file mode 100644 index 0000000000..881efcc9e0 --- /dev/null +++ b/crates/render/src/layout/profile.rs @@ -0,0 +1,125 @@ +//! A raster's profile beside its map frame (#2863 part 2): its samples along a section line, read +//! at each one's point of the page line through the frame's projection. + +use rustgis_map::layout::{MAX_PROFILE_SAMPLES, Profile}; + +use super::*; + +/// What a profile reads along its section line ([`profile_samples`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ProfileSamples { + /// Each sample's place along the frame's side, in the frame's points from its left (or top). + pub along: Vec, + /// Each sample's metres along the ground from the section line's start (its A end), on the + /// WGS 84 ellipsoid, between one sample and the next. + pub metres: Vec, + /// The band's value at each sample; `None` where it has no data. + pub values: Vec>, + /// The raster's cells along the section line, when there are more than the samples read + /// ([`MAX_PROFILE_SAMPLES`]). + pub cells: Option, +} + +impl ProfileSamples { + /// The least and most of the values read, if any. + pub fn range(&self) -> Option<(f64, f64)> { + let mut it = self.values.iter().flatten().copied(); + let first = it.next()?; + Some(it.fold((first, first), |(lo, hi), v| (lo.min(v), hi.max(v)))) + } +} + +/// How many points of the line a profile probes to count the raster's cells it crosses. +const CELL_PROBES: usize = 64; + +/// A profile's frame, section line and raster in `layout` over `maps`, and what it reads along +/// the line: a sample per cell of the raster it crosses (at most [`MAX_PROFILE_SAMPLES`]), each at +/// its point of the line on the page, taken back through the frame's projection to the ground and +/// read bilinearly there ([`rustgis_data::raster::Raster::bilinear`]), with no smoothing. +/// `Err` says why it draws nothing. +pub fn profile_samples(layout: &Layout, maps: &[Map], p: &Profile) -> Result<(ProfileSamples, Section), String> { + let frame = layout.element(p.frame).ok_or("its map frame is missing")?; + let ElementKind::MapFrame { map, center, scale, bearing, pitch, shape, sections, .. } = &frame.kind else { + return Err("its map frame is missing".into()); + }; + let map = map_index(maps, map).and_then(|i| maps.get(i)).ok_or("its frame's map is missing")?; + let section = Section::find(sections, &p.section) + .and_then(|i| sections.get(i)) + .ok_or_else(|| format!("its frame has no section line '{}'", p.section))?; + if !p.side.suits(section.line) { + return Err(format!( + "a {} section line's profile goes {}, not {}", + section.line.code(), + if p.side.is_horizontal() { "left or right of its frame" } else { "under or over its frame" }, + p.side.code() + )); + } + let cam = frame_camera(map, *center, *scale, *bearing, *pitch); + if map.projection.is_globe() || cam.pitch.abs() > 1e-9 { + return Err("its frame is tilted or on the globe, where a line straight on the page isn't a section of the ground".into()); + } + let layer = map + .layer_by_name(&p.layer) + .filter(|l| l.is_raster()) + .ok_or_else(|| format!("the frame's map has no raster layer '{}'", p.layer))?; + let rl = layer.raster.as_ref().ok_or_else(|| format!("the frame's map has no raster layer '{}'", p.layer))?; + if rl.in_place || rl.tiled { + return Err(format!("its layer '{}' is read in place, a part at a time, not held whole", layer.name)); + } + let r = rl.data.as_ref().ok_or_else(|| format!("its layer '{}' has no pixels read", layer.name))?; + if r.overview.is_some() { + return Err(format!("its layer '{}' holds only an overview of its file", layer.name)); + } + if !r.georeferenced { + return Err(format!("its layer '{}' isn't placed on the ground", layer.name)); + } + let band = usize::try_from(p.band).ok().and_then(|b| b.checked_sub(1)).unwrap_or(usize::MAX); + if band >= r.bands.len() { + return Err(format!("its layer '{}' has no band {} (it has {})", layer.name, p.band, r.bands.len())); + } + let (fw, fh) = (frame.w * PT_PER_MM, frame.h * PT_PER_MM); + let [start, end] = section_ends(map, &cam, (fw, fh), shape, section.line) + .map_err(|why| format!("its section line '{}' isn't drawn: {why}", section.name))?; + // Along the line and across it: a vertical line is worked out with the axes swapped. + let vertical = matches!(section.line, SectionLine::Vertical(_)); + let swap = |(x, y): (f64, f64)| if vertical { (y, x) } else { (x, y) }; + let ((a, across), (b, _)) = (swap(start), swap(end)); + let lonlat = |along: f64| { + let (x, y) = swap((along, across)); + cam.try_to_map(x, y, fw, fh).and_then(|m| map.to_lonlat(m)).filter(|c| c.x.is_finite() && c.y.is_finite()) + }; + // The cells the line crosses, counted along it in the raster's own grid. + let cell = |c: Coord| r.transformer().from_lonlat(c).map(|w| r.transform.to_pixel(w)); + let probes: Vec<(f64, f64)> = + (0..=CELL_PROBES).filter_map(|i| lonlat(a + (b - a) * i as f64 / CELL_PROBES as f64).and_then(cell)).collect(); + // A geographic grid's columns either side of 180° are a turn apart: a step between them is + // the short way round. + let turn = r.transformer().is_geographic().then(|| 360.0 / r.transform.pixel_width.abs()); + let step = |d: f64| turn.map_or(d, |t| (d + t / 2.0).rem_euclid(t) - t / 2.0); + let crossed: f64 = probes.windows(2).map(|w| if let [p, q] = w { step(q.0 - p.0).hypot(q.1 - p.1) } else { 0.0 }).sum(); + let cells = if crossed.is_finite() { crossed.ceil() as usize } else { 0 }; + let n = cells.saturating_add(1).clamp(2, MAX_PROFILE_SAMPLES); + let mut out = ProfileSamples { cells: (cells.saturating_add(1) > MAX_PROFILE_SAMPLES).then_some(cells), ..ProfileSamples::default() }; + let (mut metres, mut last) = (0.0, None); + for i in 0..n { + let along = a + (b - a) * i as f64 / (n - 1) as f64; + // Off the ground there is no distance from A to measure. + let at = + lonlat(along).ok_or_else(|| format!("its section line '{}' runs off the ground of the frame's projection", section.name))?; + if let Some(p) = last { + metres += rustgis_geom::wgs84_distance_m(p, at); + } + last = Some(at); + out.along.push(along); + out.metres.push(metres); + out.values.push(r.bilinear(band, at)); + } + if out.values.iter().all(Option::is_none) { + return Err(format!("its layer '{}' has no data along section line '{}'", layer.name, section.name)); + } + Ok((out, section.clone())) +} + +#[cfg(test)] +#[path = "profile_tests.rs"] +mod tests; diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs new file mode 100644 index 0000000000..0fff37af5d --- /dev/null +++ b/crates/render/src/layout/profile_tests.rs @@ -0,0 +1,198 @@ +use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; +use rustgis_map::Projection; +use rustgis_map::layout::{FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH, INDICATOR_COLOR, INDICATOR_WIDTH, ProfileSide}; + +use super::*; + +/// The Mantiqueira frame of #2863: 186 × 112 mm at 1:200,000 round the Agulhas Negras, in UTM 23S. +const CENTER: Coord = Coord::new(-44.715, -22.412); +const AGULHAS_NEGRAS: Coord = Coord::new(-44.6615, -22.3802); +const PEDRA_DA_MINA: Coord = Coord::new(-44.8429, -22.4282); +const UTM: &str = "EPSG:31983"; +const FRAME_MM: (f64, f64, f64, f64) = (30.0, 34.0, 186.0, 112.0); + +/// A 30 m grid in UTM 23S over the frame and round it, each cell `z` of its centre's easting and +/// northing. +fn dem(z: impl Fn(f64, f64) -> f64) -> Raster { + let crs = Crs::from_epsg(31983).unwrap(); + let mid = crs.transformer().unwrap().from_lonlat(CENTER).unwrap(); + let (cols, rows, cell) = (1600usize, 1000usize, 30.0); + let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell); + let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect(); + let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell }; + Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").unwrap() +} + +/// A map in UTM 23S with `dem` as its layer "DEM". +fn utm_map(dem: Raster) -> Map { + let mut map = Map::new("m"); + map.projection = Projection::Custom(UTM.into()); + map.add_raster("DEM", rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + map +} + +fn frame_kind(sections: Vec
, bearing: f64, pitch: f64) -> ElementKind { + ElementKind::MapFrame { + map: "m".into(), + center: CENTER, + scale: 200_000.0, + shape: FrameShape::Rectangle, + grid: None, + sections, + extent_of: None, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: FRAME_BORDER_COLOR, + border_width: FRAME_BORDER_WIDTH, + bearing, + pitch, + } +} + +/// A page with the Mantiqueira frame, its section line `line` named A, and a profile of "DEM" along +/// it on `side`; the profile's id. +fn page(line: SectionLine, side: ProfileSide, (bearing, pitch): (f64, f64)) -> (Layout, u32) { + let mut l = Layout::new("L", 297.0, 210.0); + let frame = l.add("Map", FRAME_MM, frame_kind(vec![Section::new("A".into(), line)], bearing, pitch)); + let p = Profile { title: String::new(), ..Profile::new(frame, "A".into(), "DEM".into(), side) }; + let id = l.add("Profile", p.rect(FRAME_MM), ElementKind::Profile(p)); + (l, id) +} + +fn profile_of(l: &Layout, id: u32) -> &Profile { + match l.element(id).map(|e| &e.kind) { + Some(ElementKind::Profile(p)) => p, + _ => panic!("a profile"), + } +} + +/// A profile is read along the page's line through the frame's projection, not along a straight line +/// of longitude and latitude: on a grid whose value is its northing, a horizontal section line of a +/// UTM frame reads one value end to end, and a vertical one on a grid of eastings too. Its samples +/// run from the frame's one edge to the other, a cell of 30 m apart, their distances adding up to +/// the frame's width on the ground. +#[test] +fn a_profile_is_read_along_the_line_on_the_page() { + let fw = FRAME_MM.2 * PT_PER_MM; + for (line, z, side) in [ + (SectionLine::Horizontal(AGULHAS_NEGRAS), (|_, n| n - 7_500_000.0) as fn(f64, f64) -> f64, ProfileSide::Bottom), + (SectionLine::Vertical(PEDRA_DA_MINA), |e, _| e - 500_000.0, ProfileSide::Right), + ] { + let maps = vec![utm_map(dem(z))]; + let (l, id) = page(line, side, (0.0, 0.0)); + let (s, section) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + assert_eq!(section.name, "A"); + let (lo, hi) = s.range().unwrap(); + assert!(hi - lo < 0.05, "{line:?}: {lo} to {hi}"); + let length = if side.is_horizontal() { fw } else { FRAME_MM.3 * PT_PER_MM }; + let (first, last) = (s.along.first().copied().unwrap(), s.along.last().copied().unwrap()); + assert!(first.abs() < 1e-6 && (last - length).abs() < 1e-6, "{first} {last}"); + let ground = length / PT_PER_MM * 200.0; + let total = s.metres.last().copied().unwrap(); + assert!((total / ground - 1.0).abs() < 0.005, "{total} m for {ground} m"); + let n = s.values.len() as f64; + assert!((n - ground / 30.0).abs() < 0.02 * n, "{n} samples"); + assert!(s.cells.is_none() && s.values.iter().all(Option::is_some)); + } + // A turned frame reads the line the page shows: turned a quarter, its horizontal runs north to + // south, its northings falling a metre a metre of ground where the grid (30 km from north to + // south) has them. + let maps = vec![utm_map(dem(|_, n| n))]; + let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (90.0, 0.0)); + let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + let read: Vec<(f64, f64)> = s.metres.iter().zip(&s.values).filter_map(|(m, v)| Some((*m, (*v)?))).collect(); + assert!(read.len() > 900, "{} read", read.len()); + for w in read.windows(2) { + let [(m0, v0), (m1, v1)] = w else { continue }; + assert!(((v0 - v1) / (m1 - m0) - 1.0).abs() < 0.01, "{m0}: {v0}, {m1}: {v1}"); + } +} + +/// The page's line, not a straight line between its ends' longitudes and latitudes: between the +/// ends of the horizontal section line of the Mantiqueira, a straight line of longitude and +/// latitude strays metres off the line on the page, which a profile doesn't (#2863). +#[test] +fn the_page_line_is_not_a_straight_line_of_longitude_and_latitude() { + let maps = vec![utm_map(dem(|_, n| n))]; + let (l, id) = page(SectionLine::Horizontal(AGULHAS_NEGRAS), ProfileSide::Bottom, (0.0, 0.0)); + let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + let map = maps.first().unwrap(); + let cam = frame_camera(map, CENTER, 200_000.0, 0.0, 0.0); + let (fw, fh) = (FRAME_MM.2 * PT_PER_MM, FRAME_MM.3 * PT_PER_MM); + let (_, y) = cam.try_to_screen(map.to_map(AGULHAS_NEGRAS).unwrap(), fw, fh).unwrap(); + let ll = |x: f64| map.to_lonlat(cam.try_to_map(x, y, fw, fh).unwrap()).unwrap(); + let (a, b) = (ll(0.0), ll(fw)); + let r = &map.layers.first().unwrap().raster.as_ref().unwrap().data.clone().unwrap(); + let chord = (0..=100).map(|i| { + let t = f64::from(i) / 100.0; + r.bilinear(0, Coord::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)).unwrap() + }); + let along = s.values.first().copied().flatten().unwrap(); + let off = chord.map(|v| (v - along).abs()).fold(0.0, f64::max); + assert!(off > 1.0, "the chord strays {off} m"); + assert!(s.values.iter().flatten().all(|v| (v - along).abs() < 0.05)); +} + +/// A gap of no data along the line leaves a gap in the samples, which breaks the curve: two runs, +/// each drawn. +#[test] +fn a_gap_in_the_data_is_a_gap_in_the_samples() { + let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; + let maps = vec![utm_map(dem(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }))]; + let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); + let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + let runs = s.values.windows(2).filter(|w| w[0].is_some() != w[1].is_some()).count(); + assert_eq!(runs, 2, "a gap in the middle"); +} + +/// A band of 0 is no band: refused, not read as the first (#2863). +#[test] +fn a_band_of_0_is_refused() { + let maps = vec![utm_map(dem(|_, n| n))]; + let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); + let p = Profile { band: 0, ..profile_of(&l, id).clone() }; + let why = profile_samples(&l, &maps, &p).err().unwrap_or_default(); + assert!(why.contains("no band 0"), "{why}"); +} + +/// A section line running off the ground of the frame's projection, as past the edge of a +/// sinusoidal world, has no distance from its end A there: refused with that reason, not measured +/// from wherever the ground begins (#2863). +#[test] +fn a_line_off_the_ground_is_refused() { + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 1.0, pixel_height: -1.0 }; + let world = Raster::new("w", 360, 180, vec![vec![1.0; 360 * 180]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let mut map = Map::new("m"); + map.projection = Projection::Custom("ESRI:54008".into()); + map.add_raster("DEM", rustgis_map::RasterLayer::from_path(world, "w.tif")); + let maps = vec![map]; + let (mut l, id) = page(SectionLine::Horizontal(Coord::new(0.0, 60.0)), ProfileSide::Bottom, (0.0, 0.0)); + let frame = profile_of(&l, id).frame; + if let Some(ElementKind::MapFrame { center, scale, .. }) = l.element_mut(frame).map(|e| &mut e.kind) { + (*center, *scale) = (Coord::new(0.0, 45.0), 200_000_000.0); + } + let why = profile_samples(&l, &maps, profile_of(&l, id)).err().unwrap_or_default(); + assert!(why.contains("off the ground"), "{why}"); +} + +/// A line across the antimeridian counts the cells it crosses, not a turn of the grid between its +/// columns on either side of 180°: over Fiji, a frame of UTM 60S at 1:200,000 on a 0.05° grid +/// stored from 179° to 181° crosses about eight cells, read one a cell (#2863). +#[test] +fn a_line_across_the_antimeridian_counts_the_cells_it_crosses() { + let gt = GeoTransform { origin_x: 179.0, origin_y: -16.0, pixel_width: 0.05, pixel_height: -0.05 }; + let fiji = Raster::new("f", 40, 40, vec![vec![1.0; 40 * 40]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let mut map = Map::new("m"); + map.projection = Projection::Custom("EPSG:32760".into()); + map.add_raster("DEM", rustgis_map::RasterLayer::from_path(fiji, "f.tif")); + let maps = vec![map]; + let at = Coord::new(180.0, -17.0); + let (mut l, id) = page(SectionLine::Horizontal(at), ProfileSide::Bottom, (0.0, 0.0)); + let frame = profile_of(&l, id).frame; + if let Some(ElementKind::MapFrame { center, .. }) = l.element_mut(frame).map(|e| &mut e.kind) { + *center = at; + } + let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + assert!(s.cells.is_none() && (5..=20).contains(&s.values.len()), "{} samples, {:?} cells", s.values.len(), s.cells); + assert!(s.values.iter().all(|v| v.is_some_and(|v| (v - 1.0).abs() < 1e-9)), "{:?}", s.values); +}