diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 7e91f234c4..1eca2b8dc1 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1063,8 +1063,8 @@ pub fn class_means(r: &Raster, bands: &[usize], polygons: &[(String, Vec Result>, String> { let mut out = (0..bands).map(|_| new_band(cols, rows, NODATA)).collect::, _>>()?; if cols == 0 { return Ok(out); } + // A cell of a projected grid is found in an image in the same system by its coordinates, and + // in any other through longitude/latitude. + let to = if crs == Crs::LonLat { None } else { Some(crs.transformer()?) }; + let own = |r: &Raster, c: Coord| { + let (cc, rr) = r.transform.to_pixel(c); + let (cc, rr) = (r.wrap_col(cc).floor(), rr.floor()); + (cc >= 0.0 && rr >= 0.0 && cc < f64::from(r.width) && rr < f64::from(r.height)).then_some((cc as i64, rr as i64)) + }; // Each row as a slice of every band, for one thread to fill. let mut by_band: Vec<_> = out.iter_mut().map(|b| b.chunks_mut(cols)).collect(); let lines: Vec> = (0..rows).map(|_| by_band.iter_mut().filter_map(Iterator::next).collect()).collect(); @@ -1093,9 +1102,17 @@ pub fn mosaic( |at: &mut Vec>, row, mut line: Vec<&mut [f32]>| { for col in 0..cols { let c = Coord::new(extent.min_x + (col as f64 + 0.5) * cell, extent.max_y - (row as f64 + 0.5) * cell); + // The cell's longitude/latitude, worked out only for an image in another system. + let mut lonlat: Option> = None; // Where the cell falls in each image, once for all bands. at.clear(); - at.extend(images.iter().map(|r| r.pixel_at(c))); + for r in images { + at.push(match &to { + Some(_) if r.crs == crs => own(r, c), + Some(t) => (*lonlat.get_or_insert_with(|| t.to_lonlat(c))).and_then(|ll| r.pixel_at(ll)), + None => r.pixel_at(c), + }); + } for (bi, band) in line.iter_mut().enumerate() { let vals = images.iter().zip(at.iter()).filter_map(|(r, a)| a.and_then(|(cc, rr)| r.value(bi, cc, rr))); let v = if mean { @@ -2001,7 +2018,7 @@ mod tests { weighted_overlay(&[(r.bands[0].data.clone(), 1.0)]).map(|v| v.len()), classify_min_distance(r, &[0, 1], &means).map(|v| v.len()), class_means(r, &[0, 1], &polygons).map(|c| c.len()), - mosaic(&[r], &r.extent(), 0.001, (w as usize, h as usize), 2, true).map(|b| b.len()), + mosaic(&[r], &r.extent(), 0.001, (w as usize, h as usize), 2, true, Crs::LonLat).map(|b| b.len()), ] }; let run = crate::control::Control::new(); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 3523c9fa52..9626fbcbfe 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -24,9 +24,17 @@ pub struct Workspace { /// "ortho" (an orthomosaic of images) or "reality" (a surface model from elevation rasters). pub kind: String, pub images: Vec, - /// Output cell size in degrees (the finest image's when unset). + /// Output cell size in degrees (the finest image's when unset), for a mosaic made in degrees. #[serde(default)] pub cell_size: Option, + /// The coordinate system the mosaic is made in: a projected one, or longitude/latitude for + /// degrees. `None`: the projected system all its images are in, else degrees. An older + /// version reads only `cell_size` and makes the mosaic in degrees. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub crs: Option, + /// The output cell size in `crs`'s units when it is projected (the finest image's when unset). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub projected_cell_size: Option, /// Where images overlap: "first" (the first image wins) or "mean". #[serde(default = "first")] pub method: String, @@ -85,20 +93,32 @@ pub fn commands() -> Vec { .view() .params(r#"{"clear"?: bool}"#), C::new("imagery.workspace", "New Workspace", "Imagery › Ortho Mapping", new_workspace).inputs(workspace_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"kind": "ortho"|"reality", "name"?: string, "images": [raster layers], "cellSize"?: degrees, "method"?: "first"|"mean"}"#, + r#"{"kind": "ortho"|"reality", "name"?: string, "images": [raster layers], "crs"?: projected coordinate system ("EPSG:32616") to make the mosaic in or "EPSG:4326" for degrees (default the projected system all the images are in, else degrees), "cellSize"?: in the crs's units or degrees without a crs (default the finest image's), "method"?: "first"|"mean"}"#, ), C::new("imagery.workspaceOptions", "Workspace Options", "Imagery › Ortho Mapping", |s, p| { let n = ps(p, "name").ok_or("name is required")?; - let w = s.project.workspaces.iter_mut().find(|w| w.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no workspace '{n}'"))?; - if p.get("cellSize").is_some() { - w.cell_size = cell_size(p)?; - } + let (at, mut w) = s + .project + .workspaces + .iter() + .enumerate() + .find(|(_, w)| w.name.eq_ignore_ascii_case(n)) + .map(|(at, w)| (at, w.clone())) + .ok_or_else(|| format!("no workspace '{n}'"))?; if ps(p, "method").is_some() { w.method = method(p, "first")?; } - serde_json::to_value(&*w).map_err(|e| e.to_string()) + let note = set_grid(p, &mut w)?; + let v = serde_json::to_value(&w).map_err(|e| e.to_string())?; + if let Some(note) = note { + s.notify(format!("{}: its coordinate system: {note}", w.name), false); + } + if let Some(slot) = s.project.workspaces.get_mut(at) { + *slot = w; + } + Ok(v) }).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"name": workspace, "cellSize"?: degrees|null, "method"?: "first"|"mean"}"#), + .params(r#"{"name": workspace, "crs"?: projected coordinate system ("EPSG:32616") or "EPSG:4326" for degrees|null (none: the images' projected system, else degrees), "cellSize"?: in the crs's units or degrees without a crs|null, "method"?: "first"|"mean"}"#), C::new("imagery.mosaic", "Build Mosaic", "Imagery › Ortho Mapping", mosaic).inputs(workspace_mosaic_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": workspace, "ran"?: (internal: a raster the app has worked out)}"#), C::new("imagery.mesh", "Export Mesh", "Imagery › Reality Mapping", mesh).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() @@ -1824,16 +1844,63 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { Ok(out) } -/// A workspace's cell size (degrees, or null for the finest image's), checked the same way when -/// a workspace is made and when its options change. -fn cell_size(p: &Value) -> Result, String> { - match p.get("cellSize") { - None | Some(Value::Null) => Ok(None), - Some(_) => f(p, "cellSize") - .filter(|c| *c > 0.0 && *c < 10.0) - .map(Some) - .ok_or_else(|| "cellSize is degrees, above 0 and below 10".to_string()), +/// Sets what `p` gives of a workspace's coordinate system (`crs`) and cell size, checked the same +/// way when a workspace is made and when its options change. Both are read before either is set, +/// so a bad one changes nothing. A cell size is in the units of the system the workspace then +/// has: a projected one's, else degrees. Another system starts without a projected cell size. +/// Returns the note on a coordinate system read with a compatibility caveat. +fn set_grid(p: &Value, w: &mut Workspace) -> Result, String> { + let mut note = None; + let crs = match p.get("crs") { + None => w.crs, + Some(Value::Null) => None, + Some(Value::String(t)) if t.trim().is_empty() => None, + Some(v @ (Value::String(_) | Value::Number(_))) => { + let text = match v { + // A form's number comes as a float: 32616.0 is EPSG:32616. + Value::Number(n) => match n.as_f64().filter(|c| c.fract() == 0.0) { + Some(c) => format!("EPSG:{c}"), + None => format!("EPSG:{n}"), + }, + _ => v.as_str().unwrap_or_default().trim().to_string(), + }; + if Crs::parse(&text).is_ok_and(|c| c == Crs::LonLat) { + Some(Crs::LonLat) + } else { + let (crs, compatibility) = rustgis_analysis::projected_crs(&text).map_err(|e| match Crs::parse(&text) { + // Degrees are asked for with EPSG:4326; that can't help any other refusal. + Ok(c) if c.is_geographic() => format!("{e}; EPSG:4326 makes it in degrees"), + _ => e, + })?; + note = compatibility; + Some(crs) + } + } + Some(_) => return Err("crs is a projected coordinate system (such as \"EPSG:32616\"), \"EPSG:4326\" for degrees, or null".into()), + }; + let projected = crs.filter(|c| *c != Crs::LonLat); + let size = match p.get("cellSize") { + None => None, + Some(Value::Null) => Some(None), + Some(_) => Some(Some(match projected { + Some(c) => { + f(p, "cellSize").filter(|v| *v > 0.0).ok_or_else(|| format!("cellSize is a size above 0, in {}'s units", c.label()))? + } + None => f(p, "cellSize") + .filter(|v| *v > 0.0 && *v < 10.0) + .ok_or("cellSize is degrees, above 0 and below 10; give a projected crs to set it in metres or feet")?, + })), + }; + if crs != w.crs { + w.projected_cell_size = None; } + w.crs = crs; + match size { + Some(size) if projected.is_some() => w.projected_cell_size = size, + Some(size) => w.cell_size = size, + None => {} + } + Ok(note) } /// A workspace's mosaic method: first or mean. @@ -1844,6 +1911,8 @@ fn method(p: &Value, default: &str) -> Result { } } +/// `imagery.workspace`: a new workspace of `images`, under a name no other workspace has (a +/// number added when it is taken), with its method, coordinate system and cell size. fn new_workspace(s: &mut Session, p: &Value) -> CmdResult { let kind = ps(p, "kind").ok_or("kind is required")?; if !matches!(kind, "ortho" | "reality") { @@ -1865,12 +1934,15 @@ fn new_workspace(s: &mut Session, p: &Value) -> CmdResult { nm = format!("{base} {i}"); } let method = method(p, if kind == "reality" { "mean" } else { "first" })?; - let cell_size = cell_size(p)?; - s.project.workspaces.push(Workspace { name: nm.clone(), kind: kind.into(), images, cell_size, method }); + let mut w = Workspace { name: nm.clone(), kind: kind.into(), images, cell_size: None, crs: None, projected_cell_size: None, method }; + if let Some(note) = set_grid(p, &mut w)? { + s.notify(format!("{nm}: its coordinate system: {note}"), false); + } + s.project.workspaces.push(w); Ok(json!({"workspace": nm})) } -/// Mosaics a workspace's images onto one longitude/latitude grid. +/// Mosaics a workspace's images onto one grid, in the coordinate system [`mosaic_crs`] gives. fn mosaic(s: &mut Session, p: &Value) -> CmdResult { super::workflows::made_or_ran(s, p, "imagery.mosaic") } @@ -1880,22 +1952,57 @@ fn mosaic(s: &mut Session, p: &Value) -> CmdResult { pub(crate) fn mosaic_work(s: &Session, p: &Value) -> Result { let w = workspace_of(s, p)?.clone(); let imgs: Vec> = w.images.iter().map(|i| raster_named(s, i)).collect::>()?; - let mut e = Extent::EMPTY; for r in &imgs { r.require_coordinates()?; - e = e.union(&r.extent()); } - let finest = imgs + let (crs, crs_note) = mosaic_crs(&w, &imgs)?; + // The images' footprints and the finest image's pixel, in the system. + let (e, finest, cell) = if crs == Crs::LonLat { + let e = imgs.iter().fold(Extent::EMPTY, |e, r| e.union(&r.extent())); + let finest = imgs + .iter() + .map(|r| { + let (cx, _) = r.cell_size_m(); + cx / (111_320.0 * r.extent().center().y.to_radians().cos().abs().max(0.01)) + }) + .fold(f64::INFINITY, f64::min); + (e, finest, w.cell_size) + } else { + let mut e = Extent::EMPTY; + let mut finest = f64::INFINITY; + for r in &imgs { + let ([x0, y0, x1, y1], pixel) = warp::footprint_in(r, crs)?; + e = e.union(&Extent::new(x0, y0, x1, y1)); + finest = finest.min(pixel); + } + (e, finest, w.projected_cell_size) + }; + // A size from a project file is checked here: the options refuse others. + let cell = match cell { + Some(c) if c.is_finite() && c > 0.0 => c, + Some(c) => return Err(format!("the workspace's cell size, {c}, isn't a size above 0: set it in the workspace options")), + None => finest, + } + .max(1e-7); + // A projected grid's cell corners fall on those of the finest image already in its system, so + // that image's pixels line up with the cells it is copied to. + let anchor = imgs .iter() - .map(|r| { - let (cx, _) = r.cell_size_m(); - cx / (111_320.0 * r.extent().center().y.to_radians().cos().abs().max(0.01)) - }) - .fold(f64::INFINITY, f64::min); - let cell = w.cell_size.unwrap_or(finest).max(1e-7); + .filter(|r| crs != Crs::LonLat && r.crs == crs) + .min_by(|a, b| a.transform.pixel_width.abs().total_cmp(&b.transform.pixel_width.abs())); + let e = match anchor { + Some(r) => { + let (ox, oy) = (r.transform.origin_x, r.transform.origin_y); + let west = ox + ((e.min_x - ox) / cell).floor() * cell; + let north = oy + ((e.max_y - oy) / cell).ceil() * cell; + Extent::new(west, e.min_y, e.max_x, north) + } + None => e, + }; let (cols, rows) = ((e.width() / cell).ceil().max(1.0) as usize, (e.height() / cell).ceil().max(1.0) as usize); if cols.saturating_mul(rows) > rasterops::max_pixels() / 2 { - return Err(format!("the mosaic would be {cols} × {rows} cells; set a larger cell size in the workspace options")); + let made_in = crs_note.as_deref().map(|n| format!(" ({n})")).unwrap_or_default(); + return Err(format!("the mosaic would be {cols} × {rows} cells; set a larger cell size in the workspace options{made_in}")); } let nb = imgs.iter().map(|r| r.band_count()).min().unwrap_or(1).min(if w.kind == "reality" { 1 } else { 4 }); // The images with bands left out, the first five named. @@ -1912,7 +2019,7 @@ pub(crate) fn mosaic_work(s: &Session, p: &Value) -> Result = Vec::new(); + let mut messages: Vec = crs_note.into_iter().collect(); if !omitted.is_empty() { // The count is of every image left out; only the first five are named. let more = if omitted_count > omitted.len() { "; …" } else { "" }; @@ -1937,10 +2044,13 @@ pub(crate) fn mosaic_work(s: &Session, p: &Value) -> Result = imgs.iter().map(|r| &**r).collect(); - let mut bands = rasterops::mosaic(&refs, &e, cell, (cols, rows), nb, w.method == "mean")?; + let mut bands = rasterops::mosaic(&refs, &e, cell, (cols, rows), nb, w.method == "mean", crs)?; // Colour only when every image is colour. A mosaic of 8-bit images stays 8-bit (means // rounded), so it displays as they do; anything else is Float32. let all_rgb = imgs.iter().all(|r| matches!(r.color, ColorHint::Rgb { .. })); @@ -1958,14 +2068,104 @@ pub(crate) fn mosaic_work(s: &Session, p: &Value) -> Result = (!messages.is_empty()).then(|| { + Box::new(move |s: &mut Session, _: &mut Value| { + for message in messages { + s.notify(format!("{name}: {message}"), false); + } + }) as super::workflows::Then + }); + super::workflows::made_then(out, Some(extra), then) })) } +/// The coordinate system a workspace's mosaic is made in, and a note when the workspace didn't +/// set it: the one set, else the projected system all its images are in, else degrees. A +/// workspace with a cell size in degrees and no system stays in degrees, as that size was asked +/// for in degrees. +fn mosaic_crs(w: &Workspace, imgs: &[Arc]) -> Result<(Crs, Option), String> { + match w.crs { + Some(Crs::LonLat) => return Ok((Crs::LonLat, None)), + // Set through the options, which refuse others; a project file can hold anything. + Some(c) => { + return match rustgis_analysis::layer_raster_crs(Some(c)) { + // A size kept from degrees isn't one in this system's units. + Some(Ok(c)) => Ok(( + c, + w.cell_size.filter(|_| w.projected_cell_size.is_none()).map(|d| { + format!( + "its cell size ({d}) is in degrees, so the finest image's pixel was taken for a mosaic in {0}; set cellSize in {0}'s units", + c.label() + ) + }), + )), + Some(Err(why)) => Err(format!("the workspace's coordinate system is {why}: set another crs in the workspace options")), + None => Err(format!( + "the workspace's coordinate system, {}, is in degrees: set crs to EPSG:4326 for degrees, or to a projected system", + c.label() + )), + }; + } + None => {} + } + let shared = imgs.first().map(|r| r.crs).filter(|c| imgs.iter().all(|r| r.crs == *c)); + let note = match shared.map(|c| rustgis_analysis::layer_raster_crs(Some(c))) { + Some(Some(Ok(c))) => match w.cell_size { + None => { + let made = + format!("made in {}, the coordinate system its images are in; set crs to EPSG:4326 to make it in degrees", c.label()); + return Ok((c, Some(made))); + } + Some(d) => format!( + "made in degrees, as its cell size ({d}) is in degrees, though its images are in {0}; set crs to {0}, with a cell size in its units, to make it there", + c.label() + ), + }, + Some(Some(Err(why))) => { + format!("made in degrees, though its images are in {why}; set a projected crs to make it in metres or feet") + } + // Images in WGS 84 degrees: degrees, nothing assumed. + Some(None) if shared == Some(Crs::LonLat) => return Ok((Crs::LonLat, None)), + // In another geographic system (NAD83, say): WGS 84 degrees, said. + Some(None) => format!( + "made in WGS 84 degrees (EPSG:4326), though its images are in {}; set a projected crs to make it in metres or feet", + shared.map(Crs::label).unwrap_or_default() + ), + None => { + // Named: the projected systems, else the geographic ones other than WGS 84. + let distinct = |keep: &dyn Fn(Crs) -> bool| { + let mut systems: Vec = Vec::new(); + for c in imgs.iter().map(|r| r.crs).filter(|c| keep(*c)) { + if !systems.contains(&c.label()) { + systems.push(c.label()); + } + } + let more = if systems.len() > 5 { ", …" } else { "" }; + systems.truncate(5); + (!systems.is_empty()).then(|| format!("{}{more}", systems.join(", "))) + }; + match (distinct(&|c| !c.is_geographic()), distinct(&|c| c.is_geographic() && c != Crs::LonLat)) { + (Some(projected), geographic) => { + let all = geographic.map_or(projected.clone(), |g| format!("{projected}, {g}")); + format!( + "made in WGS 84 degrees (EPSG:4326), as its images are in different coordinate systems (some in {all}); set crs to make it in a projected one" + ) + } + (None, Some(geographic)) => format!( + "made in WGS 84 degrees (EPSG:4326), though its images are in different geographic systems (some in {geographic}); set a projected crs to make it in metres or feet" + ), + (None, None) => return Ok((Crs::LonLat, None)), + } + } + }; + Ok((Crs::LonLat, Some(note))) +} + /// A surface model as a triangle mesh (Wavefront OBJ), in metres from its south-west corner. fn mesh(s: &mut Session, p: &Value) -> CmdResult { if ps(p, "path").is_some_and(|path| !path.to_ascii_lowercase().ends_with(".obj")) { diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 0ce7040894..6b19b655cb 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -154,6 +154,13 @@ pub(crate) fn made(raster: Raster, extra: Option) -> Result Ok(made_layer(name, layer, extra, None)) } +/// [`made`], with what is done once the layer is added (`then`). +pub(crate) fn made_then(raster: Raster, extra: Option, then: Option) -> Result { + let mut m = made(raster, extra)?; + m.then = then; + Ok(m) +} + /// A layer made (styled, say), to be added as `name`. pub(crate) fn made_layer(name: String, layer: rustgis_map::RasterLayer, extra: Option, then: Option) -> Made { Made { name, layer, extra, then, ran: None, continuation: None } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index aa1f2f304e..2e2650f07e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -39897,6 +39897,129 @@ fn rgbi_mosaics_keep_nir_without_alpha_and_reject_mixed_band_roles() { assert_eq!((r.band_count(), r.color.clone()), (4, ColorHint::Rgb { alpha: false })); } +/// An ortho workspace's mosaic is made in the projected system its images share unless it sets +/// one, and says so; images in different systems, or a cell size in degrees, keep degrees and say +/// why; "EPSG:4326" asks for degrees, another geographic system is refused (#1743 step 3). +#[test] +fn ortho_mosaic_is_made_in_its_images_projected_system() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + use rustgis_map::raster::RasterLayer; + let mut s = Session::new(Project::default()); + let utm = Crs::Epsg(32616); + let add = |s: &mut Session, name: &str, gt: GeoTransform, crs: Crs, value: f32| { + let r = Raster::new(name, 10, 10, vec![vec![value; 100]], gt, crs, None, ColorHint::Gray, "Float32").unwrap(); + let bytes = geotiff::write(&r, 0).unwrap(); + s.map_mut().add_raster(name, RasterLayer::from_bytes(r, format!("{name}.tif"), bytes)); + }; + // Two 100 m squares side by side in UTM zone 16N, and one in degrees nearby. + let at = |x: f64| GeoTransform { origin_x: x, origin_y: 3_900_100.0, pixel_width: 10.0, pixel_height: -10.0 }; + add(&mut s, "west", at(500_000.0), utm, 1.0); + add(&mut s, "east", at(500_100.0), utm, 2.0); + let degrees = GeoTransform { origin_x: -87.0, origin_y: 35.24, pixel_width: 0.0001, pixel_height: -0.0001 }; + add(&mut s, "nearby", degrees, Crs::LonLat, 3.0); + let build = |s: &mut Session, name: &str| { + let mark = s.notice_mark(); + let v = s.run("imagery.mosaic", &json!({"name": name})).unwrap(); + let notices: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let r = s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().data.clone().unwrap(); + (r, v, notices) + }; + // The images' system: their cells exactly, and it is said. + s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Fields", "images": ["west", "east"]})).unwrap(); + let (r, v, notices) = build(&mut s, "Fields"); + assert_eq!((r.crs, r.width, r.height, r.transform.pixel_width), (utm, 20, 10, 10.0), "{v}"); + assert_eq!((r.value(0, 0, 0), r.value(0, 15, 9)), (Some(1.0), Some(2.0))); + let made = format!("made in {}, the coordinate system its images are in; set crs to EPSG:4326", utm.label()); + assert!(v["messages"][0].as_str().unwrap().contains(&made), "{v}"); + assert!(notices.iter().any(|n| n.starts_with("Fields: made in")), "{notices:?}"); + // A system set, with a cell size in its units: nothing assumed, nothing said. + s.run("imagery.workspaceOptions", &json!({"name": "Fields", "crs": "EPSG:32616", "cellSize": 20})).unwrap(); + let (r, v, notices) = build(&mut s, "Fields"); + assert_eq!((r.crs, r.width, r.height), (utm, 10, 5), "{v}"); + assert!(v.get("messages").is_none() && notices.is_empty(), "{v} {notices:?}"); + // Degrees asked for: the degree cell size, nothing said. + s.run("imagery.workspaceOptions", &json!({"name": "Fields", "crs": "EPSG:4326", "cellSize": 0.0005})).unwrap(); + let (r, v, notices) = build(&mut s, "Fields"); + assert_eq!(r.crs, Crs::LonLat); + assert!(v.get("messages").is_none() && notices.is_empty(), "{v} {notices:?}"); + // Back to none, with that cell size in degrees: degrees, and why. + s.run("imagery.workspaceOptions", &json!({"name": "Fields", "crs": null})).unwrap(); + let (r, v, _) = build(&mut s, "Fields"); + assert_eq!(r.crs, Crs::LonLat); + assert!(v["messages"][0].as_str().unwrap().contains("as its cell size (0.0005) is in degrees"), "{v}"); + // Another system drops the projected cell size; a geographic one other than degrees is refused. + s.run("imagery.workspaceOptions", &json!({"name": "Fields", "crs": "EPSG:32616", "cellSize": 20})).unwrap(); + s.run("imagery.workspaceOptions", &json!({"name": "Fields", "crs": 3857})).unwrap(); + let w = s.project.workspaces.iter().find(|w| w.name == "Fields").unwrap(); + assert_eq!((w.crs, w.projected_cell_size, w.cell_size), (Some(Crs::WebMercator), None, Some(0.0005))); + // The degree size it keeps isn't used in that system, and that is said. + let (r, v, _) = build(&mut s, "Fields"); + assert_eq!(r.crs, Crs::WebMercator); + assert!(v["messages"][0].as_str().unwrap().contains("its cell size (0.0005) is in degrees"), "{v}"); + let e = s.run("imagery.workspaceOptions", &json!({"name": "Fields", "crs": "EPSG:4269"})).unwrap_err(); + assert!(e.contains("EPSG:4326 makes it in degrees"), "{e}"); + assert_eq!(s.project.workspaces.iter().find(|w| w.name == "Fields").unwrap().crs, Some(Crs::WebMercator)); + // Images in different systems: degrees, naming the projected one. + s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Mixed", "images": ["west", "nearby"]})).unwrap(); + let (r, v, _) = build(&mut s, "Mixed"); + assert_eq!(r.crs, Crs::LonLat); + let m = v["messages"][0].as_str().unwrap(); + assert!(m.contains("different coordinate systems") && m.contains(&utm.label()), "{m}"); + // A projected system set over them: the degree image is found through longitude/latitude, + // over the west square it overlaps but for its eastern strip. + s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Over", "images": ["nearby", "west"], "crs": "EPSG:32616"})).unwrap(); + let (r, v, notices) = build(&mut s, "Over"); + assert_eq!(r.crs, utm, "{v}"); + assert!(v.get("messages").is_none() && notices.is_empty(), "{v} {notices:?}"); + let values: Vec = r.bands[0].data.iter().copied().filter(|v| *v != rustgis_analysis::rasterops::NODATA).collect(); + assert!(values.contains(&3.0) && values.contains(&1.0), "{values:?}"); + // Images in another geographic system: WGS 84 degrees, and that is said. + add(&mut s, "nad83", degrees, Crs::Epsg(4269), 4.0); + s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Datum", "images": ["nad83"]})).unwrap(); + let (r, v, _) = build(&mut s, "Datum"); + assert_eq!(r.crs, Crs::LonLat); + let m = v["messages"][0].as_str().unwrap(); + assert!(m.contains("made in WGS 84 degrees (EPSG:4326), though its images are in EPSG:4269"), "{m}"); + s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Datums", "images": ["nad83", "nearby"]})).unwrap(); + let (_, v, _) = build(&mut s, "Datums"); + assert!(v["messages"][0].as_str().unwrap().contains("different geographic systems (some in EPSG:4269)"), "{v}"); + // Projected and other geographic systems mixed: both named, and the degrees are WGS 84's. + s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Both", "images": ["west", "nad83"]})).unwrap(); + let (_, v, _) = build(&mut s, "Both"); + let m = v["messages"][0].as_str().unwrap(); + assert!(m.contains("WGS 84 degrees") && m.contains(&utm.label()) && m.contains("EPSG:4269"), "{m}"); + // Images in degrees: degrees, nothing said. + s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Plain", "images": ["nearby"]})).unwrap(); + let (r, v, notices) = build(&mut s, "Plain"); + assert_eq!(r.crs, Crs::LonLat); + assert!(v.get("messages").is_none() && notices.is_empty(), "{v} {notices:?}"); + // A grid's corners fall on the finest image's in its system, however far off the others are, + // and a whole number sent as a float is an EPSG code. + let off = GeoTransform { origin_x: 499_993.7, origin_y: 3_900_103.0, pixel_width: 20.0, pixel_height: -20.0 }; + add(&mut s, "off", off, utm, 5.0); + s.run("imagery.workspace", &json!({"kind": "ortho", "name": "Snapped", "images": ["off", "west"], "crs": 32616.0})).unwrap(); + let (r, v, _) = build(&mut s, "Snapped"); + assert_eq!((r.crs, r.transform.pixel_width), (utm, 10.0), "{v}"); + let corner = (r.transform.origin_x - 500_000.0) / 10.0; + assert!((corner - corner.round()).abs() < 1e-9 && r.transform.origin_x <= 499_993.7, "{:?}", r.transform); + assert_eq!( + r.value(0, ((500_005.0 - r.transform.origin_x) / 10.0) as i64, ((r.transform.origin_y - 3_900_095.0) / 10.0) as i64), + Some(5.0) + ); + let e = s.run("imagery.workspaceOptions", &json!({"name": "Snapped", "crs": "EPSG:4978"})).unwrap_err(); + assert!(!e.contains("EPSG:4326"), "{e}"); + // A cell size a damaged project holds is refused, not replaced. + let at = s.project.workspaces.iter().position(|w| w.name == "Over").unwrap(); + s.project.workspaces[at].projected_cell_size = Some(-5.0); + let e = s.run("imagery.mosaic", &json!({"name": "Over"})).unwrap_err(); + assert!(e.contains("cell size, -5, isn't a size above 0"), "{e}"); + // The system and its cell size save with the project. + s.run("imagery.workspaceOptions", &json!({"name": "Fields", "cellSize": 30})).unwrap(); + let p = crate::Project::from_json(&serde_json::to_string(&s.project).unwrap()).unwrap(); + let w = p.workspaces.iter().find(|w| w.name == "Fields").unwrap(); + assert_eq!((w.crs, w.projected_cell_size, w.cell_size), (Some(Crs::WebMercator), Some(30.0), Some(0.0005))); +} + /// Add Data's and Load All's reads made before the command runs (the desktop app's, on a thread /// of their own) are the ones the command takes: it adds what they read, without reading again. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 2f56d306aa..f48f897710 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -61,6 +61,12 @@ pub struct Workflow { /// The system the Wizard's layer was read in, and the one its surface is made in from it /// ([`rustgis_engine::analysis::layer_raster_crs`]), kept so it is worked out once. pub layer_system: Option<(rustgis_engine::data::raster::Crs, Option)>, + /// The coordinate system typed for a new ortho or reality workspace; empty: the images' + /// projected system, else degrees. + pub workspace_crs: String, + /// The projected system that text last read as (`None`: none, or degrees), so a cell size + /// typed for one system is cleared when another is typed, not at each keystroke. + pub workspace_system: Option, /// The projected coordinate system typed for the environment's Set Coordinate System. pub env_crs: String, /// The cell size typed for the environment, apart from the Wizard's, which is the run's own. @@ -1247,18 +1253,60 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } }); } - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut app.workflow.number).hint_text(tl!("cell size °")).desired_width(80.0)); - if ui.button(tl!("New Workspace From Visible Rasters")).clicked() { - let images: Vec = - app.session.map().layers.iter().filter(|l| l.is_raster() && l.visible).map(|l| l.name.clone()).collect(); - let mut p = json!({"kind": kind, "images": images}); - if let Ok(c) = app.workflow.number.trim().parse::() { - p["cellSize"] = json!(c); - } - run(app, "imagery.workspace", p); + // The hints say the grid the workspace gets: without a system, a cell size is in + // degrees and keeps the mosaic in degrees, as in older projects. + // Read once as it's typed (below), not each frame. + let degrees = app.workflow.workspace_system.is_none(); + let crs_hint = if app.workflow.number.trim().is_empty() { + tl!("the images' projected system, else degrees") + } else { + tl!("degrees, as the cell size is in degrees") + }; + let system_label = ui.label(tl!("Coordinate system")); + let system = ui + .add(egui::TextEdit::singleline(&mut app.workflow.workspace_crs).hint_text(crs_hint).desired_width(f32::INFINITY)) + .labelled_by(system_label.id) + .on_hover_text(tl!("A projected system such as EPSG:32616, or EPSG:4326 for degrees")); + // A cell size typed for another system isn't sent in this one's units: it is cleared + // once the text reads as another system, and kept while it reads as none yet. + if system.changed() { + let typed = app.workflow.workspace_crs.trim(); + let now = if typed.is_empty() { + Some(None) + } else { + rustgis_engine::data::raster::Crs::parse(typed) + .ok() + .map(|c| Some(c).filter(|c| *c != rustgis_engine::data::raster::Crs::LonLat)) + }; + if let Some(now) = now + && now != app.workflow.workspace_system + { + app.workflow.workspace_system = now; + app.workflow.number.clear(); } + } + ui.horizontal(|ui| { + let hint = if degrees { tl!("cell size °") } else { tl!("cell size") }; + let size_label = ui.label(tl!("Cell size")); + ui.add(egui::TextEdit::singleline(&mut app.workflow.number).hint_text(hint).desired_width(80.0)) + .labelled_by(size_label.id) + .on_hover_text(tl!("In the coordinate system's units, or degrees without one")); }); + // On a line of its own: beside the cell size, its label ran past the pane's edge. + if ui.button(tl!("New Workspace From Visible Rasters")).clicked() { + let images: Vec = + app.session.map().layers.iter().filter(|l| l.is_raster() && l.visible).map(|l| l.name.clone()).collect(); + let mut p = json!({"kind": kind, "images": images}); + if !app.workflow.workspace_crs.trim().is_empty() { + p["crs"] = json!(app.workflow.workspace_crs.trim()); + } + // Text that isn't a number goes as it is, for the command to say why. + let size = app.workflow.number.trim(); + if !size.is_empty() { + p["cellSize"] = size.parse::().ok().filter(|c| c.is_finite()).map_or_else(|| json!(size), |c| json!(c)); + } + run(app, "imagery.workspace", p); + } if kind == "reality" { combo(ui, "wf_mesh", "Layer", &mut app.workflow.layer, &rasters); if ui.button(tl!("Export Mesh (OBJ)…")).clicked() { diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 105d9edded..99cf94caae 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1477,6 +1477,14 @@ The Imagery tab's groups open their tools in the Workflows pane. The tab belongs - **Ortho Mapping** and **Reality Mapping** workspaces mosaic georeferenced images into an orthomosaic, or elevation rasters into a surface model that exports as a 3D mesh (OBJ). + A workspace's mosaic is made in the projected coordinate system all its images are in, on cells + the size of the finest image's pixel, and the run says so. Set `crs` (`imagery.workspace`, + `imagery.workspaceOptions`) to make it in another projected system, or `"EPSG:4326"` for + degrees; its `cellSize` is then in that system's units. Without a `crs`, a workspace stays in + degrees, saying why, when its images are in different coordinate systems or when it has a cell + size in degrees (as older projects do). A mosaic in degrees is in WGS 84 (EPSG:4326): when its + images are in another geographic system (NAD83, say), the run says so. A geographic `crs` other + than EPSG:4326 is refused. - **Georeference** places a raster from control points (column, row, longitude, latitude) or stretches it over the map view. Those only shift and scale a north-up grid, as RustGIS's geotransform has no rotation. With `transform` (`raster.georeference`) the points are fitted by any