diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index e70a0a6c3b..2bd3b8cdfc 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -400,6 +400,9 @@ fn entries(r: &Raster, plan: &Plan, lv: &Level, first: bool, geo: &GeoKeys, big: } e.push(shorts(339, &vec![format; spp])); if first { + if let Some(c) = r.copyright.as_deref().map(super::tag_text).filter(|c| !c.is_empty()) { + e.push(ascii(33432, &c)); + } let gt = r.transform; e.push(doubles(33550, &[gt.pixel_width.abs(), gt.pixel_height.abs(), 0.0])); e.push(doubles(33922, &[0.0, 0.0, 0.0, gt.origin_x, gt.origin_y, 0.0])); diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index ae118606e4..f150e8af33 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -466,6 +466,13 @@ fn same_projection(a: &str, b: &str) -> bool { }) } +/// Whether a raster in `crs` can be written as a GeoTIFF: an EPSG system always, a user-defined +/// one when it came with GeoKeys or its PROJ definition can be said as them (see +/// [`keys_from_proj4`]). +pub fn describes(crs: Crs) -> bool { + crs.custom_def().is_none_or(|d| !d.geokeys.is_empty() || keys_from_proj4(&d.proj4, &d.label).is_some()) +} + /// GeoKeys for a user-defined projection from its PROJ definition (one read from WKT, which /// came with no keys), the inverse of [`custom_crs`]: the key directory, its double parameters and /// its ASCII parameters. `None` for a projection the keys can't say. @@ -1221,6 +1228,15 @@ pub(super) fn read_limited_with_nodata( }, Err(e) => Some(super::pam::Pam::losing(format!("it doesn't decode ({e}): band and class names are left out"))), }; + // Who holds the rights to the picture, kept as it reads so an export of it says so too (the + // writers make it the ASCII a tag holds, and the exports say what that changed); one that + // doesn't read as text is left out, and said. + let (copyright, copyright_lost) = match dec.find_tag(Tag::Copyright).map(|v| v.map(|v| v.into_string())) { + Ok(None) => (None, None), + Ok(Some(Ok(c))) => (Some(c.trim().to_string()), None), + Ok(Some(Err(e))) => (None, Some(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out"))), + Err(e) => (None, Some(format!("its Copyright tag: it can't be read ({e}), so it is left out"))), + }; let spp = samples(&mut dec); let bytes = sample_bytes(&mut dec); // The decoded image is held at its own pixel size before conversion to f32, so bound bytes @@ -1436,6 +1452,8 @@ pub(super) fn read_limited_with_nodata( r.georeferenced = false; r.overview = overview; r.rounded = rounded; + r.copyright = copyright.filter(|c| !c.is_empty()); + r.lost.extend(copyright_lost); r.lost.extend(table_lost); if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); @@ -1487,6 +1505,8 @@ pub(super) fn read_limited_with_nodata( let mut r = Raster::new(name, w, h, bands, transform, crs, geo.nodata, color, data_type)?; r.overview = overview; r.rounded = rounded; + r.copyright = copyright.filter(|c| !c.is_empty()); + r.lost.extend(copyright_lost); r.lost.extend(super::planetary::note_of(crs)); r.lost.extend(table_lost); if let Some(p) = &described { @@ -1520,7 +1540,10 @@ pub(super) fn geo_keys(r: &Raster) -> Result { Some(d) if d.geokeys.is_empty() => { return Err(err(format!("{}: a coordinate system without GeoTIFF keys can't be written", d.label))); } - Some(d) => d.geokeys.clone(), + // The tiepoint is written at the corner of the first pixel, so the raster type is area: a + // system first read from a point file (whose grid was moved to the corner on reading) is + // written as one too, or readers would place it half a pixel off. + Some(d) => as_area(&d.geokeys), None => vec![ 1, 1, @@ -1543,6 +1566,20 @@ pub(super) fn geo_keys(r: &Raster) -> Result { Ok(GeoKeys { keys, custom }) } +/// GeoKey directory `keys` with the raster type (1025) as area (1), as the writers' corner +/// tiepoint says. +fn as_area(keys: &[u16]) -> Vec { + let mut keys = keys.to_vec(); + // After the 4-short header, 4 shorts a key: its id, where its value is (0: in place), its + // count and its value. + for entry in keys.get_mut(4..).into_iter().flat_map(|k| k.as_chunks_mut::<4>().0) { + if let [1025, 0, _, value] = entry { + *value = 1; + } + } + keys +} + /// Whether band `b` is written as bytes: whole numbers within 0–255 (or no valid pixels at all), /// and a no-data value that is one too. pub(super) fn fits_bytes(r: &Raster, b: usize) -> bool { @@ -1623,6 +1660,7 @@ fn encode(r: &Raster, band: usize) -> Result> { // Each branch below names the bands it writes as samples (`$written`): their names, and the // first one's class names (the red band's, for a colour file), go to GDAL's metadata tag, // read back on open. + let copyright = r.copyright.as_deref().map(super::tag_text).filter(|c| !c.is_empty()); macro_rules! tags { ($img:expr, $written:expr) => {{ let classes = super::gdal_metadata_of(r, $written); @@ -1648,6 +1686,9 @@ fn encode(r: &Raster, band: usize) -> Result> { if let Some(xml) = &classes { e.write_tag(Tag::Unknown(42112), xml.as_str()).map_err(err)?; } + if let Some(c) = ©right { + e.write_tag(Tag::Copyright, c.as_str()).map_err(err)?; + } if let Some(nd) = r.nodata { e.write_tag(Tag::GdalNodata, nd.to_string().as_str()).map_err(err)?; } @@ -1721,6 +1762,73 @@ mod tests { use super::*; use crate::raster::tests::small; + /// Who holds the rights (the Copyright tag) is written by both writers and read back, as the + /// ASCII a TIFF tag holds (`©` as `(c)`, control characters as spaces, others as `?`); a + /// raster without it writes none. + #[test] + fn copyright_round_trips() { + let mut r = small(); + assert_eq!(read(std::io::Cursor::new(write(&r, 0).unwrap()), "none").unwrap().copyright, None); + r.copyright = Some("© OpenStreetMap contributors | Bundesamt für Landestopografie\0\n".into()); + let want = Some("(c) OpenStreetMap contributors | Bundesamt f?r Landestopografie".to_string()); + // One written as ?; the NUL and line break at the end are trimmed, not counted. + assert_eq!(super::super::tag_text_changes(r.copyright.as_deref().unwrap()), (1, 1, 0)); + // Inside, a line break and U+0085 (a control character outside ASCII) are spaces. + assert_eq!(super::super::tag_text_changes("a\nb\u{85}c ü"), (0, 1, 2)); + assert_eq!( + super::super::tag_text_note("© a\nb ü").as_deref(), + Some( + "the Copyright tag holds ASCII only, so it is written with 1 © or ® as (c) or (R), 1 character as ?, 1 control character as a space" + ) + ); + assert_eq!(super::super::tag_text_note("plain"), None); + assert_eq!(super::super::tag_text_note(""), None); + // Nothing a tag can hold: no tag is written, and that is said. + assert_eq!( + super::super::tag_text_note("\0\n").as_deref(), + Some("the credits hold nothing a Copyright tag can, so the file has none") + ); + let mut blank = small(); + blank.copyright = Some("\0\n".into()); + assert_eq!(read(std::io::Cursor::new(write(&blank, 0).unwrap()), "none").unwrap().copyright, None); + // A Copyright tag that isn't text (bytes, not ASCII) is left out, and said. + let mut buf = std::io::Cursor::new(Vec::new()); + { + let mut enc = tiff::encoder::TiffEncoder::new(&mut buf).unwrap(); + let mut img = enc.new_image::(2, 2).unwrap(); + img.encoder().write_tag(Tag::Copyright, &[0xA9u8, 0x20, 0x58][..]).unwrap(); + img.write_data(&[1, 2, 3, 4]).unwrap(); + } + let odd = read(std::io::Cursor::new(buf.into_inner()), "odd").unwrap(); + assert_eq!(odd.copyright, None); + assert!(odd.lost.iter().any(|l| l.starts_with("its Copyright tag: it isn't ASCII text")), "{:?}", odd.lost); + assert_eq!(super::super::tag_text("a\nb\u{85}c ü"), "a b c ?"); + // A scan (a TIFF with no GeoTIFF tags) keeps it too. + let mut buf = std::io::Cursor::new(Vec::new()); + { + let mut enc = tiff::encoder::TiffEncoder::new(&mut buf).unwrap(); + let mut img = enc.new_image::(2, 2).unwrap(); + img.encoder().write_tag(Tag::Copyright, "(c) Scan").unwrap(); + img.write_data(&[1, 2, 3, 4]).unwrap(); + } + let scan = read(std::io::Cursor::new(buf.into_inner()), "scan").unwrap(); + assert_eq!((scan.georeferenced, scan.copyright.as_deref()), (false, Some("(c) Scan"))); + assert_eq!(read(std::io::Cursor::new(write(&r, 0).unwrap()), "tif").unwrap().copyright, want); + let cog = super::super::cogwrite::write(&r, 0).unwrap(); + assert_eq!(read(std::io::Cursor::new(cog), "cog").unwrap().copyright, want); + } + + /// A user-defined system's keys are written with the raster type as area, as the corner + /// tiepoint is: one first read from a point file isn't placed half a pixel off. + #[test] + fn custom_keys_are_written_as_area() { + let point = [1u16, 1, 0, 3, 1024, 0, 1, 1, 1025, 0, 1, 2, 3072, 0, 1, 32767]; + assert_eq!(as_area(&point), [1, 1, 0, 3, 1024, 0, 1, 1, 1025, 0, 1, 1, 3072, 0, 1, 32767]); + // A key whose value is elsewhere (not in place) is left alone, as is a short directory. + assert_eq!(as_area(&[1, 1, 0, 1, 1025, 34737, 1, 2]), [1, 1, 0, 1, 1025, 34737, 1, 2]); + assert_eq!(as_area(&[1, 1]), [1, 1]); + } + #[test] fn float_colour_round_trip() { let r = small(); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index ab4b75bc58..76053e3ce5 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -580,6 +580,11 @@ pub struct Raster { /// values with more digits than `f32` holds), by band; empty when none did. NaN and no-data /// values aren't counted. pub rounded: Vec, + /// Who holds the rights to the picture (the TIFF Copyright tag): the credits a map's tile + /// layers ask for, on a GeoTIFF of the view. Read from a GeoTIFF that has it, and written + /// when this raster is exported; a raster made from it (clipped, reprojected) starts + /// without. + pub copyright: Option, transformer: Transformer, extent: Extent, } @@ -608,6 +613,54 @@ pub(crate) fn gdal_metadata_of(r: &Raster, bands: &[usize]) -> Option { pam::gdal_metadata(&names, first) } +/// Text for a TIFF ASCII tag, which holds 7-bit ASCII only: control characters (a NUL would end +/// it early) as spaces, `©` and `®` as `(c)` and `(R)`, any other character outside ASCII as `?` +/// ([`tag_text_changes`] counts them), trimmed. +pub fn tag_text(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '©' => out.push_str("(c)"), + '®' => out.push_str("(R)"), + c if c.is_control() => out.push(' '), + c if c.is_ascii() => out.push(c), + _ => out.push('?'), + } + } + out.trim().to_string() +} + +/// What [`tag_text`] changes in `s` (the trimmed ends not counted): how many `©` and `®` it +/// writes as `(c)` and `(R)`, how many characters as `?`, and how many control characters as +/// spaces, line breaks and tabs among them. +pub fn tag_text_changes(s: &str) -> (usize, usize, usize) { + let inner = s.trim_matches(|c: char| c.is_control() || c.is_ascii_whitespace()); + let symbols = inner.chars().filter(|c| matches!(c, '©' | '®')).count(); + let questioned = inner.chars().filter(|c| !c.is_ascii() && !c.is_control() && !matches!(c, '©' | '®')).count(); + (symbols, questioned, inner.chars().filter(|c| c.is_control()).count()) +} + +/// What writing `s` to a TIFF ASCII tag ([`tag_text`]) changes, for an export to say: `None` +/// when it is written as it is (or is empty); that no tag is written when nothing of it is left. +pub fn tag_text_note(s: &str) -> Option { + // Nothing a tag can hold (control characters only): the writers write no tag. + if tag_text(s).is_empty() { + return (!s.is_empty()).then(|| "the credits hold nothing a Copyright tag can, so the file has none".to_string()); + } + let (symbols, questioned, spaced) = tag_text_changes(s); + let count = |n: usize, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") }; + let parts: Vec = [ + (symbols, count(symbols, "© or ® as (c) or (R)", "©s or ®s as (c) or (R)")), + (questioned, count(questioned, "character as ?", "characters as ?")), + (spaced, count(spaced, "control character as a space", "control characters as spaces")), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(_, part)| part) + .collect(); + (!parts.is_empty()).then(|| format!("the Copyright tag holds ASCII only, so it is written with {}", parts.join(", "))) +} + /// How many of the names [`gdal_metadata_of`] writes for `bands` hold a character XML can't (a /// control character), which is written as a space: for a writer to say. pub fn gdal_metadata_changed(r: &Raster, bands: &[usize]) -> usize { @@ -701,6 +754,7 @@ impl Raster { georeferenced: true, lost: Vec::new(), rounded: Vec::new(), + copyright: None, transformer, extent: Extent::EMPTY, }; diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index e696b5cbe8..0c670b2184 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -992,6 +992,10 @@ fn write_geotiff(r: &Raster, bi: usize, cog: bool, path: &str) -> Result 0 { note.push_str(&format!("; {spaced} band or class name(s) held control characters, written as spaces")); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 9f347ef027..85be749aa3 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -1,4 +1,4 @@ -//! Publish tab: export the map as PNG and layers as GeoJSON, CSV, FlatGeobuf, GeoPackage, +//! Publish tab: export the map as PNG or GeoTIFF and layers as GeoJSON, CSV, FlatGeobuf, GeoPackage, //! GeoParquet, Shapefile, KML/KMZ or GPX. use std::path::Path; @@ -26,7 +26,7 @@ pub fn commands() -> Vec { super::exports::write_here(s, p, "share.exportMap") }).inputs(map_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .params(r#"{"path": "*.png", "width"?: px, "height"?: px, "dpi"?: 96..600}"#), + .params(r#"{"path": "*.png|*.tif|*.tiff", "width"?: "points (pixels at 96 dpi), the view fitted in it", "height"?: points, "dpi"?: "48..600 (default 96)", "fit"?: "true to lower the dpi until a side fits 8192 pixels, saying so", "cog"?: "true for a cloud-optimised GeoTIFF"}"#), C::new("share.exportLayer", "Export Features", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportLayer")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_layer) @@ -148,6 +148,33 @@ fn report_table(s: &mut Session, path: &str, gpkg: &GpkgTable, table: Option Result, String> { + let view = export_view(s.map().camera, s.view_size, None, None, Some(dpi)); + let fitted = fitted_dpi(&view, dpi, false); + let png = map_png(s, None, None, Some(fitted.unwrap_or(dpi)))?; + // A view past 8000 points is cut to its middle, as Export Map's is: said too, with where a + // size can be given (this image takes none). + let (vw, vh) = s.view_size; + if vw > MOST_POINTS || vh > MOST_POINTS { + s.notify( + format!( + "The map image: the view is {vw:.0} × {vh:.0} points, more than the {MOST_POINTS:.0} a side an image holds, so it is cut to its middle: Export Map (share.exportMap) with a width or height of at most {MOST_POINTS:.0} draws it whole" + ), + false, + ); + } + if let Some(lower) = fitted { + s.notify( + format!("The map is drawn at {lower} DPI, the most an image of this view holds ({} pixels a side)", rustgis_render::MAX_SIDE), + false, + ); + } + Ok(png) +} + /// Renders the active map at the current view (or a requested size) to PNG bytes. pub fn map_png(s: &mut Session, width: Option, height: Option, dpi: Option) -> Result, String> { let view_size = s.view_size; @@ -157,25 +184,135 @@ pub fn map_png(s: &mut Session, width: Option, height: Option, dpi: Op /// Renders `map` at its camera in a view of `(vw, vh)` points (or a requested size) to PNG bytes. fn png_of( map: &mut rustgis_map::Map, - (vw, vh): (f64, f64), + view_size: (f64, f64), width: Option, height: Option, dpi: Option, ) -> Result, String> { + let view = export_view(map.camera, view_size, width, height, dpi); + // Past the canvas's limit the picture would be cut off at its top left: refused instead. + fits_pixels(&view, false)?; + rustgis_render::render_png(map, &view) +} + +/// Refuses an export of `view` with a side past the [`rustgis_render::MAX_SIDE`] pixels a canvas +/// holds, saying how many it would be (and, for the box around a `turned` view, that the box is +/// why). +fn fits_pixels(view: &View, turned: bool) -> Result<(), String> { + let (pw, ph) = ((view.width * view.pixels_per_point).round(), (view.height * view.pixels_per_point).round()); + let most = f64::from(rustgis_render::MAX_SIDE); + if pw <= most && ph <= most { + return Ok(()); + } + let why = if turned { " (the box around the turned view; or set the bearing to 0)" } else { "" }; + Err(format!("{pw} × {ph} pixels{why} is more than the {most} a side an export draws: give a smaller width, height or dpi")) +} + +/// The most characters of the credits a GeoTIFF export's notice shows; its answer has them all. +const CREDITS_SHOWN: usize = 200; + +/// The most points a side an export of the map draws; a larger view is cut to its middle. +pub const MOST_POINTS: f64 = 8000.0; + +/// What [`export_view`]'s limit of [`MOST_POINTS`] a side does to an export to `path` of a view +/// of `(vw, vh)` points, for it to say: with no size given, a larger view is cut to its middle; +/// a size given past the limit is drawn at the limit: the view still fits whole, with less ground +/// around it than the size asked for. +fn size_notes( + path: &str, + (vw, vh): (f64, f64), + width: Option, + height: Option, +) -> Vec<(rustgis_data::diagnostics::Severity, String)> { + let fin = |v: Option| v.filter(|x| x.is_finite()); + let (width, height) = (fin(width), fin(height)); + let mut notes = Vec::new(); + let note = |text: String| (rustgis_data::diagnostics::Severity::Info, format!("{path}: {text}")); + if width.is_none() && height.is_none() && (vw > MOST_POINTS || vh > MOST_POINTS) { + notes.push(note(format!( + "the view is {vw:.0} × {vh:.0} points, more than the {MOST_POINTS:.0} a side an export holds, so it is cut to its middle: give a width or height of at most {MOST_POINTS:.0} to draw it whole" + ))); + } + for (name, v) in [("width", width), ("height", height)] { + if let Some(v) = v.filter(|v| *v > MOST_POINTS) { + notes.push(note(format!( + "a {name} of {v:.0} points is more than the {MOST_POINTS:.0} an export holds, so it is drawn at {MOST_POINTS:.0}, holding less ground than asked (the whole view still fits): a higher dpi gives more pixels" + ))); + } + if let Some(v) = v.filter(|v| *v < LEAST_POINTS) { + notes.push(note(format!( + "a {name} of {v} points is less than the {LEAST_POINTS:.0} an export draws, so it is drawn at {LEAST_POINTS:.0}" + ))); + } + } + notes +} + +/// The fewest points a side an export of the map draws. +const LEAST_POINTS: f64 = 16.0; +/// The DPI an export of the map draws at, at least and at most. +const DPI_RANGE: (f64, f64) = (48.0, 600.0); + +/// What the DPI range does to an export to `path` asked at `dpi`, for it to say. +fn dpi_note(path: &str, dpi: Option) -> Option<(rustgis_data::diagnostics::Severity, String)> { + let dpi = dpi.filter(|d| d.is_finite())?; + let (least, most) = DPI_RANGE; + let drawn = dpi.clamp(least, most); + (drawn != dpi).then(|| { + ( + rustgis_data::diagnostics::Severity::Info, + format!("{path}: a dpi of {dpi} is outside {least:.0} to {most:.0}, so it is drawn at {drawn:.0}"), + ) + }) +} + +/// With `fit`, the DPI an export of the view (at `dpi`) is lowered to so that no side passes the +/// [`rustgis_render::MAX_SIDE`] pixels a canvas holds, a GeoTIFF of a turned view counting the +/// box around it: the most whole DPI that fits, `None` when `dpi` already does. +fn fitted_dpi(view: &View, dpi: f64, tif: bool) -> Option { + let (w, h) = + if tif && is_turned(view.camera.bearing) { view.camera.rotated_size(view.width, view.height) } else { (view.width, view.height) }; + let side = w.max(h); + let most = f64::from(rustgis_render::MAX_SIDE); + // As the export sizes its canvas: a turned GeoTIFF's box rounded out, else rounded. + let px = side * view.pixels_per_point; + let px = if tif && is_turned(view.camera.bearing) { px.ceil() } else { px.round() }; + if !side.is_finite() || side <= 0.0 || px <= most { + return None; + } + // Never above the DPI asked, nor below the least: `max` keeps the bounds in order (clamp + // panics otherwise) for a caller asking below it. + Some((most * 96.0 / side).floor().clamp(DPI_RANGE.0, dpi.max(DPI_RANGE.0))) +} + +/// Whether a view at `bearing` is turned (not north up). +fn is_turned(bearing: f64) -> bool { + let b = bearing.rem_euclid(360.0); + b.min(360.0 - b) > 1e-9 +} + +/// The view an export of the map at `camera` draws, in a view of `(vw, vh)` points: a requested +/// size keeps the same ground extent, and `dpi` sets the pixels per point. +fn export_view( + camera: rustgis_map::camera::Camera, + (vw, vh): (f64, f64), + width: Option, + height: Option, + dpi: Option, +) -> View { // NaN would pass through `clamp`; non-finite values fall back to the defaults. let fin = |v: Option| v.filter(|x| x.is_finite()); let (width, height, dpi) = (fin(width), fin(height), fin(dpi)); - let w = width.unwrap_or(vw).clamp(16.0, 8000.0); - let h = height.unwrap_or(vh).clamp(16.0, 8000.0); - let ppp = (dpi.unwrap_or(96.0) / 96.0).clamp(0.5, 6.0); - let mut camera = map.camera; + let w = width.unwrap_or(vw).clamp(LEAST_POINTS, MOST_POINTS); + let h = height.unwrap_or(vh).clamp(LEAST_POINTS, MOST_POINTS); + let ppp = dpi.unwrap_or(96.0).clamp(DPI_RANGE.0, DPI_RANGE.1) / 96.0; + let mut camera = camera; // Keep the same ground extent when the size differs from the view. if width.is_some() || height.is_some() { camera.res *= (vw / w).max(vh / h); camera.clamp(); } - let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; - rustgis_render::render_png(map, &view) + View { width: w, height: h, pixels_per_point: ppp, camera, sky: false } } /// The map view on one PDF page (for printing): the page is the view's shape at 96 points per @@ -200,11 +337,42 @@ pub fn map_pdf(s: &mut Session, dpi: f64) -> Result, String> { Ok(rustgis_render::pdf::write(&[page], &s.map().name)) } -/// `share.exportMap`: draws the active map as it is now to a PNG. It draws a copy of the map, so +/// `share.exportMap`: draws the active map as it is now to a PNG, or a GeoTIFF for a `.tif` or +/// `.tiff` path ([`geotiff_work`]). It draws a copy of the map, so /// the map can move meanwhile; a cancelled export stops waiting for tiles and writes nothing. pub(crate) fn map_work(s: &Session, p: &Value) -> Result { let path = ps(p, "path").ok_or("path is required")?.to_string(); let (width, height, dpi) = (f(p, "width"), f(p, "height"), f(p, "dpi")); + let ext = Path::new(&path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + let cog = match p.get("cog") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or("cog must be true or false")?, + }; + let tif = matches!(ext.as_str(), "tif" | "tiff"); + let fit = match p.get("fit") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or("fit must be true or false")?, + }; + let mut sized = size_notes(&path, s.view_size, width, height); + sized.extend(dpi_note(&path, dpi)); + // `fit`: a view too large for the DPI asked is drawn at the most that fits, and says so. + let asked = dpi.filter(|d| d.is_finite()).unwrap_or(96.0).clamp(DPI_RANGE.0, DPI_RANGE.1); + let dpi = match fit.then(|| fitted_dpi(&export_view(s.map().camera, s.view_size, width, height, Some(asked)), asked, tif)).flatten() { + Some(lower) => { + sized.push(( + rustgis_data::diagnostics::Severity::Info, + format!("{path}: drawn at {lower} DPI, the most an export of this view holds ({} pixels a side)", rustgis_render::MAX_SIDE), + )); + Some(lower) + } + None => dpi, + }; + if tif { + return geotiff_work(s, path, export_view(s.map().camera, s.view_size, width, height, dpi), cog, sized); + } + if cog { + return Err("cog is for a GeoTIFF (.tif or .tiff) export".into()); + } let (mut map, view_size) = (s.map().detached(), s.view_size); Ok(Box::new(move || { let written = (|| { @@ -213,10 +381,170 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { rustgis_data::io::write_atomic(Path::new(&path), &png).map_err(|e| format!("{path}: {e}"))?; Ok(json!({"path": path, "bytes": png.len()})) })(); - super::exports::drawn(std::slice::from_ref(&map), Vec::new(), written, path) + // What the size limit did is said of a file written. + let sized = if written.is_ok() { sized } else { Vec::new() }; + super::exports::drawn(std::slice::from_ref(&map), sized, written, path) })) } +/// `share.exportMap` to a GeoTIFF: the view drawn as data (its layers and labels, without the +/// scale bar and credits, which sit on the screen), RGB (a drawn view is opaque), placed on the +/// ground in the map's projection, the credits in its Copyright tag. What may have left gaps in +/// it (tiles still on their way, tile layers that failed) is said: on the ground a gap looks like +/// data. A turned view is drawn north up over the box around it, and says so; a tilted view, the +/// globe and a map of another body are refused, as no grid of square pixels in one coordinate +/// system holds them. +fn geotiff_work( + s: &Session, + path: String, + view: View, + cog: bool, + sized: Vec<(rustgis_data::diagnostics::Severity, String)>, +) -> Result { + let m = s.map(); + let crs = map_crs(m)?; + if view.camera.pitch.abs() > 1e-6 { + return Err(format!( + "the map is tilted {:.0}°: a GeoTIFF needs it looking straight down (pitch 0), or export a PNG", + view.camera.pitch + )); + } + let mut view = view; + let mut notices = Vec::new(); + let bearing = view.camera.bearing; + let turned = is_turned(bearing); + if turned { + // North up over the box around the turned view: everything it shows, and more at the + // corners. + // In points whose pixels, once rounded, still cover the box. + let (bw, bh) = view.camera.rotated_size(view.width, view.height); + let ppp = view.pixels_per_point; + view.width = (bw * ppp).ceil() / ppp; + view.height = (bh * ppp).ceil() / ppp; + view.camera.bearing = 0.0; + notices.push(( + rustgis_data::diagnostics::Severity::Info, + format!("{path}: the map is turned {bearing:.0}°, so the GeoTIFF is drawn north up over the box around the view"), + )); + } + // A turned view's box is larger than the view: said, as the fix differs. + fits_pixels(&view, turned)?; + let name = m.name.clone(); + let mut map = m.detached(); + Ok(Box::new(move || { + let mut notices = notices; + let written = (|| { + let placed = rustgis_render::render_placed(&mut map, &view)?; + rustgis_data::progress::check().map_err(|e| e.to_string())?; + for gap in &placed.gaps { + notices.push((rustgis_data::diagnostics::Severity::Warning, format!("{path}: {gap}"))); + } + let credits = placed.credits; + // The drawn picture is dropped once its bands are made, before the raster's + // statistics and the file's encoding. + let mut r = placed_raster(&name, placed.pixmap, &view, crs)?; + r.copyright = (!credits.is_empty()).then(|| credits.join(" | ")); + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let (bytes, tiled) = if cog { + // Tiles go to the file as they are made; its tiling is in the answer, as Export + // Raster gives it. + let c = rustgis_data::raster::cogwrite::write_file(&r, 0, Path::new(&path)).map_err(|e| format!("{path}: {e}"))?; + (c.bytes, Some(json!({"overviews": c.levels.len().saturating_sub(1), "bigTiff": c.big}))) + } else { + let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| format!("{path}: {e}"))?; + rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; + (bytes.len() as u64, None) + }; + let mut out = json!({"path": path, "width": r.width, "height": r.height, "crs": crs.label(), "bytes": bytes}); + if let Some(t) = tiled { + out["cog"] = t; + } + if let Some(c) = &r.copyright { + out["copyright"] = json!(c); + if let Some(note) = rustgis_data::raster::tag_text_note(c) { + // Quoted (control characters escaped, so a service's credits can't reach a + // terminal raw) and cut short: the answer holds them whole. + let shown: String = c.chars().take(CREDITS_SHOWN).collect(); + let more = if c.chars().count() > CREDITS_SHOWN { "…" } else { "" }; + notices.push((rustgis_data::diagnostics::Severity::Info, format!("{path}: {note} (the credits: {shown:?}{more})"))); + } + } + Ok(out) + })(); + // What the size limit did is said of a file written, first. + if written.is_ok() { + notices.splice(0..0, sized); + } + super::exports::drawn(std::slice::from_ref(&map), notices, written, path) + })) +} + +/// The coordinate system a GeoTIFF of map `m`'s view is in: its flat projection's. +fn map_crs(m: &rustgis_map::Map) -> Result { + let body = m.body(); + if !body.is_earth() { + return Err(format!("a map of {} can't be saved as a GeoTIFF yet: export a PNG", body.name)); + } + match &m.projection { + rustgis_map::Projection::Globe => { + Err("the globe can't be saved as a GeoTIFF: switch to a flat projection (View › Projection), or export a PNG".into()) + } + rustgis_map::Projection::WebMercator => Ok(Crs::WebMercator), + rustgis_map::Projection::Custom(code) => { + let (proj4, label) = rustgis_map::projection::lookup(code)?; + // An EPSG system is written by its code; any other by its definition. + if let Some(n) = label.strip_prefix("EPSG:").and_then(|n| n.parse::().ok()) + && let Some(crs) = Crs::from_epsg(n) + { + return Ok(crs); + } + let shown = label.clone(); + let def = rustgis_data::raster::crs::CustomCrs { proj4, label, geokeys: Vec::new(), doubles: Vec::new(), ascii: String::new() }; + let crs = Crs::custom(def)?; + if !rustgis_data::raster::geotiff::describes(crs) { + return Err(format!( + "the map's projection, {shown}, can't be described in a GeoTIFF: switch the map to an EPSG projection, or export a PNG" + )); + } + Ok(crs) + } + } +} + +/// The drawn view `pm` as an RGB raster placed on the ground: the view's centre at the image's +/// centre, each pixel `res / pixels_per_point` map units a side. A drawn view is opaque (its +/// background is filled), so it has no alpha band. While the bands are filled the picture is +/// held too, 16 bytes a pixel in all (about 1 GiB at 8192 a side); a machine that can't hold +/// them gets an error, not a crash. +fn placed_raster(name: &str, pm: tiny_skia::Pixmap, view: &View, crs: Crs) -> Result { + let (w, h) = (pm.width(), pm.height()); + let mut bands: Vec> = (0..3) + .map(|_| rustgis_data::raster::grid::(w as usize, h as usize)) + .collect::>() + .map_err(|e| format!("{name}: {e}"))?; + for px in pm.pixels() { + // tiny-skia keeps colours premultiplied; a file keeps them straight. + let c = px.demultiply(); + for (band, v) in bands.iter_mut().zip([c.red(), c.green(), c.blue()]) { + band.push(f32::from(v)); + } + } + drop(pm); + let cam = view.camera; + let cell = cam.res / view.pixels_per_point; + // The renderer puts the centre at half the view's width in points, times the pixels per + // point, unrounded: the corner is half the view from it, whatever whole number of pixels the + // picture is. + let transform = rustgis_data::raster::GeoTransform { + origin_x: cam.center.x - view.width / 2.0 * cam.res, + origin_y: cam.center.y + view.height / 2.0 * cam.res, + pixel_width: cell, + pixel_height: -cell, + }; + let color = rustgis_data::raster::ColorHint::Rgb { alpha: false }; + rustgis_data::raster::Raster::new(name, w, h, bands, transform, crs, None, color, "UInt8").map_err(|e| e.to_string()) +} + /// `share.exportLayer`: writes a layer to a file by its extension. A streamed layer exports its /// whole source, a chunk at a time where the source and format allow (see `data::export`). Says /// what the file couldn't hold: features without drawable geometry, a missing `.prj`, Z or M diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c488a4749c..cd31710330 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33084,3 +33084,322 @@ fn topology_refuses_latitudes_past_the_poles() { } } } + +/// `share.exportMap` to a `.tif` writes the view placed on the ground (#1561): in the map's +/// projection, each pixel where the view drew it, RGB; a turned view north up over its box, and +/// says so; a tilted view, the globe and junk refused. +#[test] +fn export_map_to_geotiff_places_the_view_on_the_ground() { + use rustgis_data::raster::{Crs, geotiff}; + use rustgis_geom::{Coord, lonlat_to_merc}; + let mut s = world(); + s.map_mut().basemap = rustgis_map::Basemap::Blank; + // The export's size is the view's, so its pixel is the camera's resolution. + s.view_size = (400.0, 300.0); + s.run("map.goToXY", &json!({"lon": 5.0, "lat": 47.0, "scale": 20_000_000})).unwrap(); + let dir = std::env::temp_dir().join(format!("rustgis-map-tif-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("view.tif"); + let read = |p: &std::path::Path| geotiff::read(std::io::Cursor::new(std::fs::read(p).unwrap()), "view").unwrap(); + let out = s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 400, "height": 300})).unwrap(); + assert_eq!((out["width"].as_u64(), out["height"].as_u64(), out["crs"].as_str()), (Some(400), Some(300), Some("EPSG:3857"))); + let r = read(&path); + // RGB: a drawn view is opaque. + assert_eq!((r.width, r.height, r.crs, r.bands.len()), (400, 300, Crs::WebMercator, 3)); + // Its grid is the view's: the centre in the middle, the camera's resolution a pixel. + let cam = s.map().camera; + let t = r.transform; + assert!((t.pixel_width - cam.res).abs() < 1e-6 * cam.res && (t.pixel_height + cam.res).abs() < 1e-6 * cam.res, "{t:?}"); + assert!((t.origin_x + 200.0 * cam.res - cam.center.x).abs() < 1e-3 && (t.origin_y - 150.0 * cam.res - cam.center.y).abs() < 1e-3); + // Land and sea where they are: the pixel at a place inland differs from one at sea. + let at = |r: &rustgis_data::raster::Raster, lon: f64, lat: f64| { + let m = lonlat_to_merc(Coord::new(lon, lat)); + let (c, row) = ( + ((m.x - r.transform.origin_x) / r.transform.pixel_width) as usize, + ((m.y - r.transform.origin_y) / r.transform.pixel_height) as usize, + ); + let i = row * r.width as usize + c; + r.bands.iter().map(|b| b.data[i]).collect::>() + }; + let (land, sea) = (at(&r, 10.0, 50.0), at(&r, -20.0, 45.0)); + assert_ne!(land, sea, "land {land:?}, sea {sea:?}"); + // The same view exported twice is the same picture: a turned one is a different grid. + s.run("map.setBearing", &json!({"bearing": 30})).unwrap(); + let turned = dir.join("turned.tif"); + let out = s.run("share.exportMap", &json!({"path": turned.display().to_string(), "width": 400, "height": 300})).unwrap(); + let r2 = read(&turned); + assert!(r2.width > 400 && r2.height > 300, "{} × {}", r2.width, r2.height); + assert!(s.notices.iter().any(|n| n.text.contains("turned 30°")), "{out}"); + // North up over the box: the same place lands on the same ground. + assert_eq!(at(&r2, 10.0, 50.0), land); + assert!((r2.transform.pixel_width - cam.res).abs() < 1e-6 * cam.res); + // At 100 DPI the box isn't a whole number of pixels: the picture still covers all of it. + let at100 = dir.join("turned-100.tif"); + s.run("share.exportMap", &json!({"path": at100.display().to_string(), "width": 400, "height": 300, "dpi": 100})).unwrap(); + let r3 = read(&at100); + let (bw, bh) = s.map().camera.rotated_size(400.0, 300.0); + let cell = r3.transform.pixel_width; + assert!( + f64::from(r3.width) * cell >= bw * cam.res - 1e-6 && f64::from(r3.height) * cell >= bh * cam.res - 1e-6, + "{} × {}", + r3.width, + r3.height + ); + s.run("map.setBearing", &json!({"bearing": 0})).unwrap(); + // `cog` writes a cloud-optimised one; it's for a GeoTIFF only. + let cog = dir.join("view-cog.tif"); + let out = s.run("share.exportMap", &json!({"path": cog.display().to_string(), "width": 400, "height": 300, "cog": true})).unwrap(); + assert!(out["bytes"].as_u64().unwrap() > 0); + // Written by the tiled writer: its tiling is in the answer, as Export Raster gives it. + assert!(out["cog"]["overviews"].is_u64() && out["cog"]["bigTiff"] == false, "{out}"); + assert_eq!(read(&cog).width, 400); + let png = dir.join("view.png"); + let e = s.run("share.exportMap", &json!({"path": png.display().to_string(), "cog": true})).unwrap_err(); + assert!(e.contains("cog is for a GeoTIFF"), "{e}"); + let e = s.run("share.exportMap", &json!({"path": cog.display().to_string(), "cog": "yes"})).unwrap_err(); + assert!(e.contains("cog must be true or false"), "{e}"); + // A view past 8000 points (no size given) is cut to its middle, and says so, as a PNG does; + // one that fits says nothing. + let n = s.notices.len(); + s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("cut to its middle"))); + s.view_size = (9000.0, 300.0); + for file in ["wide.tif", "wide.png"] { + let n = s.notices.len(); + s.run("share.exportMap", &json!({"path": dir.join(file).display().to_string()})).unwrap(); + assert!(s.notices[n..].iter().any(|x| x.text.contains("9000 × 300 points") && x.text.contains("cut to its middle")), "{file}"); + } + // A size given draws the whole view, so nothing is cut. + let n = s.notices.len(); + s.run("share.exportMap", &json!({"path": dir.join("fit.tif").display().to_string(), "width": 4000})).unwrap(); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("cut to its middle") || x.text.contains("points is more than"))); + // The whole 9000-point view in 4000 points: each pixel 2.25 of the camera's, the same centre. + let fit = read(&dir.join("fit.tif")); + let cam = s.map().camera; + assert_eq!((fit.width, fit.height), (4000, 300)); + assert!((fit.transform.pixel_width - 2.25 * cam.res).abs() < 1e-6 * cam.res, "{:?}", fit.transform); + assert!((fit.transform.origin_x + 2000.0 * fit.transform.pixel_width - cam.center.x).abs() < 1e-3); + // Square pixels, and the centre down the middle too. + assert!((fit.transform.pixel_height + fit.transform.pixel_width).abs() < 1e-9 * cam.res, "{:?}", fit.transform); + assert!((fit.transform.origin_y + 150.0 * fit.transform.pixel_height - cam.center.y).abs() < 1e-3); + s.view_size = (400.0, 300.0); + // A size given past the limit is drawn at the limit, and says so. + let n = s.notices.len(); + let out = s.run("share.exportMap", &json!({"path": dir.join("big.tif").display().to_string(), "width": 9000, "height": 150})).unwrap(); + assert_eq!(out["width"], 8000); + assert!( + s.notices[n..].iter().any(|x| x.text.contains("a width of 9000 points") && x.text.contains("drawn at 8000")), + "{:?}", + &s.notices[n..] + ); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("height of"))); + // `fit` lowers the DPI to what fits 8192 pixels a side, and says so; one that fits stays. + let fitted = |s: &mut Session, file: &str| { + let n = s.notices.len(); + let out = s.run("share.exportMap", &json!({"path": dir.join(file).display().to_string(), "dpi": 192, "fit": true})).unwrap(); + let said = + s.notices[n..].iter().find_map(|x| x.text.split("drawn at ").nth(1).and_then(|t| t.split(' ').next()).map(str::to_string)); + (out, said) + }; + s.view_size = (1200.0, 800.0); + assert_eq!(fitted(&mut s, "small.tif").1, None); + assert_eq!(fitted(&mut s, "small.png").1, None); + s.view_size = (5000.0, 3000.0); + // 8192 × 96 / 5000 = 157.3: whole DPI, down. + let (out, said) = fitted(&mut s, "wide.tif"); + assert_eq!((said.as_deref(), out["width"].as_u64()), (Some("157"), Some(8177))); + assert_eq!(fitted(&mut s, "wide.png").1.as_deref(), Some("157")); + // Past 8000 points the view is clamped first: 16000 wide fits 98 DPI. + s.view_size = (16000.0, 3000.0); + assert_eq!(fitted(&mut s, "huge.tif").1.as_deref(), Some("98")); + // A GeoTIFF of a turned view counts its box (3000 points square turned 45° is 4243); a PNG + // is drawn turned in the view's own size. + s.view_size = (3000.0, 3000.0); + assert_eq!(fitted(&mut s, "square.tif").1, None); + s.run("map.setBearing", &json!({"bearing": 45})).unwrap(); + assert_eq!(fitted(&mut s, "square-turned.tif").1.as_deref(), Some("185")); + assert_eq!(fitted(&mut s, "square-turned.png").1, None); + // A box just past 8192 pixels (8192.2) is rounded out, as the GeoTIFF's canvas is: lowered to + // 95 DPI, and written. + s.view_size = (5792.76, 5792.76); + let n = s.notices.len(); + let out = s.run("share.exportMap", &json!({"path": dir.join("edge.tif").display().to_string(), "dpi": 96, "fit": true})).unwrap(); + assert!(s.notices[n..].iter().any(|x| x.text.contains("drawn at 95 DPI")), "{out}"); + s.run("map.setBearing", &json!({"bearing": 0})).unwrap(); + // The app's download and clipboard copy (no size given) fit too: 5000 points at 192 DPI is + // drawn at 157, and said. + s.view_size = (5000.0, 3000.0); + let n = s.notices.len(); + let png = crate::cmd::share::map_png_fitted(&mut s, 192.0).unwrap(); + assert_eq!(rustgis_render::decode_png(&png).map(|p| p.width()), Some(8177)); + assert!(s.notices[n..].iter().any(|x| x.text.contains("drawn at 157 DPI"))); + let n = s.notices.len(); + s.view_size = (400.0, 300.0); + crate::cmd::share::map_png_fitted(&mut s, 192.0).unwrap(); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("DPI") || x.text.contains("cut"))); + // A view past 8000 points is cut to its middle, and said. + s.view_size = (9000.0, 300.0); + let n = s.notices.len(); + let png = crate::cmd::share::map_png_fitted(&mut s, 96.0).unwrap(); + assert_eq!(rustgis_render::decode_png(&png).map(|p| (p.width(), p.height())), Some((8000, 300))); + assert!( + s.notices[n..].iter().any(|x| x.text.contains("cut to its middle") && x.text.contains("share.exportMap")), + "{:?}", + &s.notices[n..] + ); + // A DPI below the least is drawn at 48 (export_view clamps it before the fit looks at it). + s.view_size = (6000.0, 300.0); + crate::cmd::share::map_png_fitted(&mut s, 30.0).unwrap(); + s.view_size = (400.0, 300.0); + let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "fit": "yes"})).unwrap_err(); + assert!(e.contains("fit must be true or false"), "{e}"); + // A size below 16 points, and a dpi outside 48 to 600, are drawn at the limit, and say so. + let n = s.notices.len(); + let out = s + .run("share.exportMap", &json!({"path": dir.join("tiny.tif").display().to_string(), "width": 5, "height": 100, "dpi": 30})) + .unwrap(); + assert_eq!(out["width"], 8); + let said: Vec<&str> = s.notices[n..].iter().map(|x| x.text.as_str()).collect(); + assert!(said.iter().any(|t| t.contains("a width of 5 points is less than the 16")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("a dpi of 30 is outside 48 to 600, so it is drawn at 48")), "{said:?}"); + assert!(!said.iter().any(|t| t.contains("height of")), "{said:?}"); + // 600 DPI is 6.25 pixels a point, as the command says, not cut to 576. + let fine = dir.join("fine.tif"); + let out = s.run("share.exportMap", &json!({"path": fine.display().to_string(), "width": 100, "height": 100, "dpi": 600})).unwrap(); + assert_eq!((out["width"].as_u64(), out["height"].as_u64()), (Some(625), Some(625))); + // A PNG past the canvas's 8192 pixels a side is refused too, not cut off at its top left. + let e = s.run("share.exportMap", &json!({"path": dir.join("big.png").display().to_string(), "width": 5000, "dpi": 192})).unwrap_err(); + assert!(e.contains("10000") && e.contains("8192"), "{e}"); + // Too many pixels a side is refused, saying how many. + let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 8000, "dpi": 192})).unwrap_err(); + assert!(e.contains("16000") && e.contains("8192") && !e.contains("turned"), "{e}"); + // A tilted map and the globe are refused, and write nothing. + let none = dir.join("none.tif"); + s.run("map.setPitch", &json!({"pitch": 40})).unwrap(); + let e = s.run("share.exportMap", &json!({"path": none.display().to_string()})).unwrap_err(); + assert!(e.contains("tilted 40°"), "{e}"); + s.run("map.setPitch", &json!({"pitch": 0})).unwrap(); + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + let e = s.run("share.exportMap", &json!({"path": none.display().to_string()})).unwrap_err(); + assert!(e.contains("globe can't be saved as a GeoTIFF"), "{e}"); + s.run("map.projection", &json!({"type": "mercator"})).unwrap(); + // So is a map of another body, whose ground no Earth system holds. + s.run("map.body", &json!({"name": "mars", "basemap": false})).unwrap(); + let e = s.run("share.exportMap", &json!({"path": none.display().to_string()})).unwrap_err(); + assert!(e.contains("a map of Mars can't be saved as a GeoTIFF"), "{e}"); + assert!(!none.exists()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A GeoTIFF of a map in another projection is in that projection: an EPSG one by its code, +/// another by its definition; one the GeoTIFF keys can't say is refused. +#[test] +fn export_map_to_geotiff_keeps_the_maps_projection() { + use rustgis_data::raster::{Crs, geotiff}; + let mut s = world(); + s.map_mut().basemap = rustgis_map::Basemap::Blank; + s.run("map.goToXY", &json!({"lon": 7.45, "lat": 46.95, "scale": 2_000_000})).unwrap(); + let dir = std::env::temp_dir().join(format!("rustgis-map-tif-crs-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let read = |p: &std::path::Path| geotiff::read(std::io::Cursor::new(std::fs::read(p).unwrap()), "view").unwrap(); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + let lv95 = dir.join("lv95.tif"); + let out = s.run("share.exportMap", &json!({"path": lv95.display().to_string(), "width": 200, "height": 200})).unwrap(); + assert_eq!(out["crs"], "EPSG:2056"); + let r = read(&lv95); + assert_eq!(r.crs, Crs::Epsg(2056)); + // Bern's centre in LV95 metres (about 2 600 000, 1 200 000) is near the middle of the image. + let (cx, cy) = (r.transform.origin_x + 100.0 * r.transform.pixel_width, r.transform.origin_y + 100.0 * r.transform.pixel_height); + assert!((cx - 2_600_000.0).abs() < 5_000.0 && (cy - 1_200_000.0).abs() < 5_000.0, "{cx} {cy}"); + // A local view (azimuthal equidistant about Bern) by its definition. + s.run("map.projection", &json!({"type": "local:7.45,46.95"})).unwrap(); + let local = dir.join("local.tif"); + s.run("share.exportMap", &json!({"path": local.display().to_string(), "width": 200, "height": 200})).unwrap(); + let r = read(&local); + assert!(r.crs.custom_def().is_some_and(|d| d.proj4.contains("+proj=aeqd")), "{:?}", r.crs); + // One the GeoTIFF keys can't say is refused before anything is drawn, saying what to do. + s.run("map.projection", &json!({"type": "mollweide"})).unwrap(); + let moll = dir.join("moll.tif"); + let e = s.run("share.exportMap", &json!({"path": moll.display().to_string()})).unwrap_err(); + assert!(e.contains("can't be described in a GeoTIFF") && e.contains("export a PNG"), "{e}"); + assert!(!moll.exists()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A tile layer's pictures are in a GeoTIFF of the view where they lie, and its credits in the +/// file's Copyright tag (#1561). +#[test] +fn export_map_to_geotiff_draws_tile_layers_and_keeps_their_credits() { + use rustgis_data::raster::geotiff; + let dir = std::env::temp_dir().join(format!("rustgis-map-tif-tiles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let archive = dir.join("red.mbtiles"); + let mut red = tiny_skia::Pixmap::new(256, 256).unwrap(); + red.fill(tiny_skia::Color::from_rgba8(255, 0, 0, 255)); + let c = rusqlite::Connection::open(&archive).unwrap(); + c.execute_batch( + "CREATE TABLE metadata (name text, value text); CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob); + INSERT INTO metadata VALUES ('name', 'Red'), ('format', 'png'), ('minzoom', '0'), ('maxzoom', '0'), ('attribution', '© Röd');", + ) + .unwrap(); + c.execute("INSERT INTO tiles VALUES (0, 0, 0, ?1)", [red.encode_png().unwrap()]).unwrap(); + drop(c); + let mut s = Session::new(Project::default()); + s.map_mut().basemap = rustgis_map::Basemap::Blank; + s.view_size = (300.0, 200.0); + s.run("layer.addData", &json!({"path": archive.display().to_string()})).unwrap(); + s.run("map.goToXY", &json!({"lon": 10.0, "lat": 20.0, "scale": 50_000_000})).unwrap(); + let path = dir.join("tiles.tif"); + let out = s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + // The answer has the credits whole; the tag holds ASCII, and the export says what it changed. + assert_eq!(out["copyright"], "© Röd"); + let r = geotiff::read(std::io::Cursor::new(std::fs::read(&path).unwrap()), "tiles").unwrap(); + assert_eq!(r.copyright.as_deref(), Some("(c) R?d")); + assert!( + s.notices.iter().any(|n| n.text.contains("written with 1 © or ® as (c) or (R), 1 character as ? (the credits: \"© Röd\")")), + "{:?}", + s.notices + ); + // The tiles had all come: nothing says the picture has gaps. + assert!(!s.notices.iter().any(|n| n.text.contains("export again once")), "{:?}", s.notices); + // The middle pixel is the tile's red. + let i = 100 * r.width as usize + 150; + let px: Vec = r.bands.iter().map(|b| b.data[i]).collect(); + assert_eq!(px, [255.0, 0.0, 0.0]); + // ASCII credits say nothing; a © alone says it is written as (c). + let n = s.notices.len(); + s.map_mut().tiles[0].attribution = "(c) Red".into(); + s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + assert!(!s.notices[n..].iter().any(|n| n.text.contains("Copyright tag")), "{:?}", &s.notices[n..]); + let n = s.notices.len(); + s.map_mut().tiles[0].attribution = "© Red".into(); + s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + assert!(s.notices[n..].iter().any(|n| n.text.contains("written with 1 © or ® as (c) or (R) (the credits")), "{:?}", &s.notices[n..]); + // A tile layer that can't be drawn (its archive gone) leaves a gap that would pass for data: + // said, as a warning. + let broken = dir.join("broken.mbtiles"); + let c = rusqlite::Connection::open(&broken).unwrap(); + c.execute_batch( + "CREATE TABLE metadata (name text, value text); CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob); + INSERT INTO metadata VALUES ('name', 'Broken'), ('format', 'png'), ('minzoom', '0'), ('maxzoom', '0'); + INSERT INTO tiles VALUES (0, 0, 0, x'00010203');", + ) + .unwrap(); + drop(c); + s.map_mut().tiles.clear(); + s.run("layer.addData", &json!({"path": broken.display().to_string()})).unwrap(); + // Its file gone before the map is drawn. + let gone = s.map().tiles[0].url.clone(); + std::fs::remove_file(&broken).unwrap(); + s.map_mut().tiles[0].url = gone.replace("broken", "gone"); + let n = s.notices.len(); + s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + // Said as a tile layer that couldn't be drawn, or (where the reader is slower to give up) + // tiles still on their way: either way a warning that parts are empty. + assert!( + s.notices[n..].iter().any(|n| n.severity == rustgis_data::diagnostics::Severity::Warning && n.text.contains("empty")), + "{:?}", + &s.notices[n..] + ); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5f1d9da013..a9059418e5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5714,6 +5714,62 @@ pub fn render_drawing(map: &mut Map, view: &View) -> Option { /// Renders a map with its labels, a scale bar and a north arrow to PNG bytes. pub fn render_png(map: &mut Map, view: &View) -> Result, String> { + let r = render_exported(map, view)?; + let mut pm = Canvas::from_pixmap(r.pixmap); + for l in r.unplaced.iter().chain(&r.labels) { + text::draw(&mut pm, l, view.pixels_per_point as f32); + } + text::scale_bar(&mut pm, view, map.ground_res_at(&view.camera)); + draw_attribution(&mut pm, &r.attribution, view.pixels_per_point as f32); + pm.into_pixmap().encode_png().map_err(|e| e.to_string()) +} + +/// A map drawn as data ([`render_placed`]), with what it holds besides its pixels. +pub struct Placed { + /// The pixels, premultiplied as tiny-skia keeps them. + pub pixmap: Pixmap, + /// The credits the map's tile layers ask for, for the file to keep. + pub credits: Vec, + /// Why parts of it may be empty: tiles or streamed data still on their way when the wait + /// ran out, tile layers that couldn't be drawn. In a picture placed on the ground a gap looks + /// like data, so an export says these. + pub gaps: Vec, +} + +/// A map drawn as data, for an image placed on the ground (a GeoTIFF of the view): its layers +/// and labels (the unplaced ones too, when the map shows them, as [`render_png`] draws them), +/// without the scale bar and the credits, which sit on the screen, not the ground. Refuses what +/// [`render_png`] refuses. +pub fn render_placed(map: &mut Map, view: &View) -> Result { + let r = render_exported(map, view)?; + let mut gaps = Vec::new(); + if r.tiles_pending { + gaps.push("some tiles were still on their way when the export stopped waiting, so parts of tile layers are empty: export again once the map has drawn them".to_string()); + } + if r.data_pending { + gaps.push( + "streamed layers were still reading the view, so some features are missing: export again once the map has drawn them" + .to_string(), + ); + } + if let Some(first) = r.tile_errors.first() { + let n = r.tile_errors.len(); + gaps.push(if n == 1 { + format!("a tile layer couldn't be drawn, so its part is empty: {first}") + } else { + format!("{n} tile layers couldn't be drawn, so their parts are empty; the first: {first}") + }); + } + let mut pm = Canvas::from_pixmap(r.pixmap); + for l in r.unplaced.iter().chain(&r.labels) { + text::draw(&mut pm, l, view.pixels_per_point as f32); + } + Ok(Placed { pixmap: pm.into_pixmap(), credits: r.attribution, gaps }) +} + +/// The map drawn whole for an export, or why it can't be written: a raster read in place whose +/// tiles haven't come, or that is drawn from less than the view needs. +fn render_exported(map: &mut Map, view: &View) -> Result { let r = render_complete(map, view).ok_or("could not allocate the image")?; // A raster read in place drawn from less than the view needs isn't written: its tiles still // on their way (the browser can't wait; natively the wait ran out), or a coarser level or @@ -5730,13 +5786,7 @@ pub fn render_png(map: &mut Map, view: &View) -> Result, String> { }); return Err(format!("{why}, so the image isn't written")); } - let mut pm = Canvas::from_pixmap(r.pixmap); - for l in r.unplaced.iter().chain(&r.labels) { - text::draw(&mut pm, l, view.pixels_per_point as f32); - } - text::scale_bar(&mut pm, view, map.ground_res_at(&view.camera)); - draw_attribution(&mut pm, &r.attribution, view.pixels_per_point as f32); - pm.into_pixmap().encode_png().map_err(|e| e.to_string()) + Ok(r) } /// The tile layers' credits, small, in the bottom-right corner. diff --git a/crates/ui-egui/src/exportjob.rs b/crates/ui-egui/src/exportjob.rs index 7c6015eccb..fdf13b81c9 100644 --- a/crates/ui-egui/src/exportjob.rs +++ b/crates/ui-egui/src/exportjob.rs @@ -158,4 +158,26 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + /// The ribbon's Export Map to a `.tif` writes a GeoTIFF on a thread like the PNG, at 192 DPI + /// where that fits (the engine's `fit`). + #[test] + fn export_map_to_a_geotiff_runs_on_a_thread() { + let mut app = RustGisApp::with_sample(); + app.session.view_size = (400.0, 300.0); + let dir = std::env::temp_dir().join(format!("rustgis-export-tif-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("map.tif"); + crate::dialogs::PICKED.with(|c| *c.borrow_mut() = Some(path.display().to_string())); + assert_eq!(app.run("ui.exportMap", Value::Null).unwrap()["started"], "Export Map"); + let end = std::time::Instant::now() + std::time::Duration::from_secs(120); + while land(&mut app) { + assert!(std::time::Instant::now() < end, "Export Map never landed"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let r = rustgis_engine::data::raster::geotiff::read(std::io::Cursor::new(std::fs::read(&path).unwrap()), "map").unwrap(); + // 400 × 300 points at 192 DPI. + assert_eq!((r.width, r.height, r.bands.len()), (800, 600, 3)); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 16127dce29..aba70cf030 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3543,10 +3543,9 @@ impl RustGisApp { } "ui.captureMap" => { let session = &mut self.session; - let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::share::map_png(session, None, None, Some(192.0)) - })) - .unwrap_or_else(|_| Err("the capture failed unexpectedly".into()))?; + let png = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) + .unwrap_or_else(|_| Err("the capture failed unexpectedly".into()))?; let pm = rustgis_engine::render::decode_png(&png).ok_or("could not draw the map")?; let size = [pm.width() as usize, pm.height() as usize]; self.ui.copy_image = Some(egui::ColorImage::from_rgba_premultiplied(size, pm.data())); @@ -3871,10 +3870,9 @@ impl RustGisApp { "ui.exportMap" if self.services.download.is_some() => { // The same last-resort panic guard `Session::run` gives commands. let session = &mut self.session; - let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::share::map_png(session, None, None, Some(192.0)) - })) - .unwrap_or_else(|_| Err("Export Map failed unexpectedly".into())); + let png = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) + .unwrap_or_else(|_| Err("Export Map failed unexpectedly".into())); let png = match png { Ok(p) => p, Err(e) => { @@ -3959,17 +3957,20 @@ impl RustGisApp { } "ui.exportMap" => { let name = format!("{}.png", self.session.map().name); - if let Some(path) = dialogs::pick_save(&name, &["png"], tl!("PNG image")) { + // A .tif is the view placed on the ground (a GeoTIFF), without the scale bar. + if let Some(path) = dialogs::pick_save(&name, &["png", "tif", "tiff"], tl!("PNG image or GeoTIFF")) { + // 192 DPI, or the most a view too large for it holds (the export says so). + let args = json!({"path": path, "dpi": 192, "fit": true}); // Drawn on a thread of its own, with progress and Cancel in the status bar; // here while a style added with its own view loads, as the command waits for // it to move the map there first. #[cfg(not(target_arch = "wasm32"))] if self.session.style_view.is_none() { - return exportjob::start(self, "share.exportMap", json!({"path": path, "dpi": 192})); + return exportjob::start(self, "share.exportMap", args); } #[cfg(not(target_arch = "wasm32"))] exportjob::idle(self)?; - return self.run("share.exportMap", json!({"path": path, "dpi": 192})); + return self.run("share.exportMap", args); } } "ui.exportLayer" => { diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 501084c1e5..cf41c86c1f 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -581,6 +581,7 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | GeoJSON, KML, GPX, CSV, CSV with WKT | Analyze › Workflows › Data Interop (`data.convert`; `"format": "geojson"`, `"kml"`, `"gpx"`, `"csv"` or `"wkt"`) | Returns text when `"path"` is omitted; writes a file on desktop when it is given. | | GeoTIFF / Cloud-optimised GeoTIFF | Data › Export Raster (`share.exportRaster`) | Untiled GeoTIFF by default; `"cog": true` writes 512-pixel tiles, Deflate compression and overviews. Writes the loaded raster's resolution (an overview when that is what was opened), the selected band or its colour bands. The web app's Export Raster downloads an ordinary GeoTIFF. | | PNG | Publish › Export Map (`share.exportMap`) | Configurable DPI, with labels, scale bar and tile credits. | +| GeoTIFF of the map view | Publish › Export Map to `.tif` (`share.exportMap`) | The view as an RGB GeoTIFF in the map's projection, with labels but no scale bar; tile credits in the Copyright tag; `"cog": true` for a cloud-optimised one. Flat, untilted maps of the Earth only (see [Exporting](sharing.md#exporting)). | | PDF | Layouts, reports, presentations and the map view (Print Map), as vectors | | | Wavefront OBJ, STL, glTF | Publish › Export To 3D, Share As › Web Scene | Polygons extruded by a field. STL is binary and triangles only (no lines). | | Web map, OGC API Features, MapLibre style | Publish › Share As | Open-format files that need no server: see [Sharing](sharing.md). | diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index ff5fd9dbb8..1d4b3c3e5b 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -4,7 +4,33 @@ **Publish › Output › Export Map** writes the map view as a PNG with labels, the scale bar and tile credits. The ribbon exports at 192 DPI; `share.exportMap` accepts `width` and `height` -in pixels and a `dpi` value (96 by default). **Print Map** opens a PDF of the map view, kept as +in points, with the whole view fitted in them, and a `dpi` value (96 by default). A point is a +pixel at 96 DPI, so `"width": 400` at 192 DPI is an image 800 pixels wide. + +Export Map to a `.tif` path writes the view as a GeoTIFF instead: an RGB image placed on the +ground in the map's projection, so another GIS opens it where it belongs. It holds the layers, +tile and WMS layers included, and the labels, but not the scale bar or the credits. The credits go +into the file's Copyright tag, which holds plain ASCII: `©` and `®` are written as `(c)` and `(R)`, +other characters as `?` and control characters as spaces, and the export says which. Its answer +gives them in full as `copyright`. `"cog": true` writes a +cloud-optimised GeoTIFF. A turned map is drawn north up over the box around the view (and says +so). A tilted map, the globe and a map of another body are refused: export a PNG of those. One +side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`; this holds for a +PNG too, which is refused past it rather than cut off. With `"fit": true` an export too large for +its `dpi` is drawn at the most that fits, and says so; the ribbon exports that way, at 192 DPI. +`dpi` runs from 48 to 600 and a side from 16 points; a value outside is drawn at the limit, and +said. An export holds +at most 8000 points a side, PNG or GeoTIFF: with no `width` or `height`, a larger view is cut to +its middle; a `width` or `height` past 8000 is drawn at 8000, holding less ground than asked (the whole +view still fits). Either way the +export says so. In a GeoTIFF, +tiles still on their way when the export stops waiting, streamed layers still reading the view, +and tile layers that can't be drawn leave gaps that would pass for data, so its export warns +about them. The web app's Export Map downloads a PNG. A projection +whose parameters GeoTIFF's keys can't hold (Mollweide, for example) is refused too: +switch the map to an EPSG projection first. + +**Print Map** opens a PDF of the map view, kept as vectors as a layout's PDF is (see Layouts), in the system viewer on desktop; **Capture To Clipboard** copies a map image. **Export To 3D** writes a layer as a Wavefront OBJ or binary STL model with polygons extruded by a field (`share.export3d` writes STL when `path` ends in `.stl`). STL diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index 324e1b8eb0..eaf2ad832d 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -553,8 +553,12 @@ animation, and a layer whose only time is `current`: rustgis-cli run --cmd 'service.add={"url":"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/1.0.0/WMTSCapabilities.xml","layer":"MODIS_Terra_CorrectedReflectance_TrueColor","time":"2024-06-01"}' --cmd 'share.exportMap={"path":"gibs.png"}' rustgis-cli run --cmd 'service.add={"url":"https://wms.geo.admin.ch/?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0","layer":"ch.swisstopo.pixelkarte-farbe-pk25.noscale"}' --cmd 'map.goToXY={"lon":7.4474,"lat":46.948,"scale":25000}' --cmd 'time.set={"interval":15}' --cmd 'time.export={"path":"bern.gif"}' rustgis-cli run --cmd 'service.add={"url":"https://wmts.geo.admin.ch/EPSG/3857/1.0.0/WMTSCapabilities.xml","layer":"ch.swisstopo.pixelkarte-farbe"}' --cmd 'share.exportMap={"path":"map.png"}' +rustgis-cli run --cmd 'service.add={"url":"https://wmts.geo.admin.ch/EPSG/2056/1.0.0/WMTSCapabilities.xml","layer":"ch.swisstopo.pixelkarte-farbe"}' --cmd 'map.projection={"type":"EPSG:2056"}' --cmd 'map.goToXY={"lon":7.4474,"lat":46.948,"scale":20000}' --cmd 'share.exportMap={"path":"bern-lv95.tif"}' ``` +The last writes the view as a GeoTIFF in Swiss LV95 (EPSG:2056), placed on the ground, with the +service's credits in its Copyright tag (see [Exporting](sharing.md#exporting)). + ## United States **Home › Add › Web Data › United States** holds services covering the United States: the