diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 6ee1e40fbe..ee2632cb96 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -692,6 +692,7 @@ impl Canvas { } } out.copyright = r.copyright.clone(); + out.white_is_zero = r.white_is_zero; out.keep_rounded_mark(r); Ok(out) } diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index 405a87bcd0..717bb924cf 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -247,6 +247,8 @@ pub struct Layout { /// a colour table too short for its pixels. One line each, for a window to say (AGENTS.md, /// Never silent); drawing in place shows the file grey without them, as before. pub lost: crate::loss::Notes, + /// The file says 0 is white, as [`super::Raster::white_is_zero`]. + pub white_is_zero: bool, /// Who holds the rights to the picture (its Copyright tag), as [`super::Raster::copyright`]. pub copyright: Option, /// The file is in strips, not tiles (#2592): each level's tiles are its strips, as wide as the @@ -364,6 +366,7 @@ fn read_layout(r: Sparse) -> Result { // An RGB image with more bands (shown to the decoder as grey, see `Unpaletted`): every band, // the first three red, green and blue. let wide_rgb = rd.first_is_wide_rgb(); + let white_is_zero = rd.first_white_is_zero(); let mut dec = Decoder::new(rd).map_err(err)?.with_limits(limits()); let Some(geo) = super::geotiff::cog_geo(&mut dec)? else { return Ok(Parse::NotTiled("a rotated image, or one without coordinates, is read whole".into())); @@ -670,6 +673,7 @@ fn read_layout(r: Sparse) -> Result { palette, described, lost, + white_is_zero, copyright, strips, }))) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index 7251976f81..b8a2f993f8 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -131,6 +131,8 @@ struct Plan { palette: Option>, /// Classes (a palette's, or few whole numbers): overviews take a pixel, never an average. categorical: bool, + /// Grey with 0 as white ([`Raster::white_is_zero`]). + white_is_zero: bool, } /// Whether band `b` holds whole numbers of a 16-bit type, and its no-data value (if any) is one. @@ -183,6 +185,7 @@ fn plan(r: &Raster, band: usize) -> Result { nodata_int: int_nodata(max), palette: None, categorical: false, + white_is_zero: false, }); } } @@ -196,13 +199,23 @@ fn plan(r: &Raster, band: usize) -> Result { nodata_int: None, palette: None, categorical: false, + white_is_zero: false, }); } if matches!(r.color, ColorHint::GrayAlpha) && r.bands.len() >= 2 { let sample = sample_of(&[0, 1]).unwrap_or(Sample::Float); let max = if sample == Sample::Byte { 255.0 } else { 65_535.0 }; let nodata_int = if sample == Sample::Float { None } else { int_nodata(max) }; - return Ok(Plan { bands: vec![0, 1], sample, rgb: false, alpha: Some(1), nodata_int, palette: None, categorical: false }); + return Ok(Plan { + bands: vec![0, 1], + sample, + rgb: false, + alpha: Some(1), + nodata_int, + palette: None, + categorical: false, + white_is_zero: r.white_is_zero, + }); } let b = r.bands.get(band).ok_or_else(|| err(format!("the raster has no band {}", band + 1)))?; if let ColorHint::Palette(colors) = &r.color { @@ -227,6 +240,7 @@ fn plan(r: &Raster, band: usize) -> Result { nodata_int, palette: Some(colors.clone()), categorical: true, + white_is_zero: false, }); } let all_valid = b.stats.count == r.width as usize * r.height as usize; @@ -246,6 +260,7 @@ fn plan(r: &Raster, band: usize) -> Result { nodata_int: if sample == Sample::Float { None } else { int_nodata(max) }, palette: None, categorical, + white_is_zero: r.white_is_zero, }) } @@ -517,6 +532,8 @@ fn entries(r: &Raster, plan: &Plan, lv: &Level, first: bool, geo: &GeoKeys, big: 3 } else if plan.rgb { 2 + } else if plan.white_is_zero { + 0 } else { 1 }], @@ -789,7 +806,7 @@ pub(super) struct Strips { /// Samples to a pixel, interleaved. pub spp: u16, pub sample: Sample, - /// PhotometricInterpretation: 1 for grey, 2 for RGB. + /// PhotometricInterpretation: 1 for grey (0 when 0 is white), 2 for RGB. pub photometric: u16, /// The ExtraSamples values of the samples past the grey or colour ones (none to leave it out). pub extra: Vec, @@ -1204,7 +1221,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { Self::most_bands() ))); } - let plan = stream_plan(bytes, template.nodata, n, &template.color); + let plan = stream_plan(bytes, template.nodata, n, &template.color, template.white_is_zero); // With alpha, alpha says which pixels have a value, as [`write_to`] writes it: no no-data // value is written, a pixel with none is see-through, its colours what they are (a black // one stays black), and an integer template's alpha is held on a float's scale, opaque @@ -1557,6 +1574,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { if level > 0 { r.overview = Some((full.w, full.h)); } + r.white_is_zero = self.plan.white_is_zero; for (b, tb) in r.bands.iter_mut().zip(&t.bands) { b.name.clone_from(&tb.name); b.wavelength = tb.wavelength; @@ -1568,8 +1586,8 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { /// What a [`TileStream`] writes: `n` bands of 32-bit floats, or with `bytes` one band of bytes /// whose no-data value is `nodata`, averaged in its overviews; red, green and blue first for an /// RGB `color` of three bands or more (the fourth alpha when it says so), grey and alpha first for -/// grey and alpha, else grey, the further bands nothing in particular. -fn stream_plan(bytes: bool, nodata: Option, n: usize, color: &ColorHint) -> Plan { +/// grey and alpha, else grey (0 as white with `white_is_zero`), the further bands nothing in particular. +fn stream_plan(bytes: bool, nodata: Option, n: usize, color: &ColorHint, white_is_zero: bool) -> Plan { let (sample, nodata_int) = match bytes { true => (Sample::Byte, nodata.filter(|d| (0.0..=255.0).contains(d)).map(|d| d as u16)), false => (Sample::Float, None), @@ -1579,7 +1597,7 @@ fn stream_plan(bytes: bool, nodata: Option, n: usize, color: &ColorHint) -> ColorHint::GrayAlpha if n >= 2 => (false, Some(1)), _ => (false, None), }; - Plan { bands: (0..n).collect(), sample, rgb, alpha, nodata_int, palette: None, categorical: false } + Plan { bands: (0..n).collect(), sample, rgb, alpha, nodata_int, palette: None, categorical: false, white_is_zero } } /// How a [`TileStream`] holds a pixel's value in its file: `given` (the template's no-data, or diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index b3121ed957..88b76de069 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -812,6 +812,9 @@ fn samples(dec: &mut Decoder) -> usize { /// every sample is decoded. The only change is the PhotometricInterpretation value (→ 1) in each /// such image's IFD, in memory. /// +/// So is a grey image whose 0 is white (MinIsWhite, 0): the `tiff` crate inverts its samples, and +/// they are read as stored, the picture inverted as it is drawn (`Raster::white_is_zero`, #2761). +/// /// It also shows a SampleFormat of 4 ("undefined", which CBERS-4 scenes have) as 1, unsigned, as /// libtiff and GDAL read it: the `tiff` crate refuses to decode it (#2593). pub(crate) struct Unpaletted { @@ -823,6 +826,8 @@ pub(crate) struct Unpaletted { /// Whether the first image is an RGB image with samples past the colour ones (shown to the /// decoder as grey): its first three samples are red, green and blue, every sample read. first_wide_rgb: bool, + /// Whether the first image is grey with 0 as white. + first_white_is_zero: bool, pos: u64, } @@ -834,13 +839,13 @@ const MAX_ENTRIES: u64 = 4096; /// samples past the colour ones (which the decoder would leave out, or refuse), walking the IFD /// chain (classic and BigTIFF). A file it can't walk has none: the decoder reports what's wrong. /// Each SampleFormat value of 4 (undefined) is patched to 1 too, in the entry or in the array it -/// points to (#2593). Returns the patches, whether the first image is a palette image, and whether -/// it is such an RGB image. -fn palette_patches(r: &mut R) -> (Vec<(u64, [u8; 2])>, bool, bool) { +/// points to (#2593). Returns the patches, whether the first image is a palette image, whether it is +/// such an RGB image, and whether it is grey with 0 as white. +fn palette_patches(r: &mut R) -> (Vec<(u64, [u8; 2])>, bool, bool, bool) { use std::io::SeekFrom; let mut patches = Vec::new(); // Whether the first image is one of them, and whether it is an RGB image with more samples. - let (mut first, mut first_wide) = (false, false); + let (mut first, mut first_wide, mut first_white) = (false, false, false); let mut walk = || -> Option<()> { let mut head = [0u8; 16]; r.seek(SeekFrom::Start(0)).ok()?; @@ -922,6 +927,10 @@ fn palette_patches(r: &mut R) -> (Vec<(u64, [u8; 2])>, bool, boo patches.push((at, one)); first |= k == 0; } + Some((at, 0)) => { + patches.push((at, one)); + first_white |= k == 0; + } // An RGB image whose fourth sample isn't alpha, or with five or more: RGBI // orthophotos, multispectral images. Some((at, 2)) if samples > 4 || (samples == 4 && !matches!(extra, Some(1 | 2))) => { @@ -949,7 +958,7 @@ fn palette_patches(r: &mut R) -> (Vec<(u64, [u8; 2])>, bool, boo Some(()) }; let _ = walk(); - (patches, first, first_wide) + (patches, first, first_wide, first_white) } /// Any reader, boxed: the decoder is compiled once for every kind of source (a file, bytes in @@ -972,6 +981,12 @@ impl Unpaletted { self.first_palette } + /// Whether the first image is grey with 0 as white (PhotometricInterpretation 0), shown as + /// grey with 0 as black. + pub(crate) fn first_white_is_zero(&self) -> bool { + self.first_white_is_zero + } + /// Whether the first image is an RGB image with more samples than its colours. pub(crate) fn first_is_wide_rgb(&self) -> bool { self.first_wide_rgb @@ -980,9 +995,9 @@ impl Unpaletted { impl Unpaletted { fn new(mut inner: R) -> std::io::Result { - let (patches, first_palette, first_wide_rgb) = palette_patches(&mut inner); + let (patches, first_palette, first_wide_rgb, first_white_is_zero) = palette_patches(&mut inner); inner.seek(std::io::SeekFrom::Start(0))?; - Ok(Unpaletted { inner, patches, first_palette, first_wide_rgb, pos: 0 }) + Ok(Unpaletted { inner, patches, first_palette, first_wide_rgb, first_white_is_zero, pos: 0 }) } } @@ -1801,6 +1816,7 @@ fn read_image( // overviews of it. let palette = r.first_is_palette(); let wide_rgb = r.first_is_wide_rgb(); + let white_is_zero = r.first_white_is_zero(); let limits = limits(); let mut dec = Decoder::new(r).map_err(err)?.with_limits(limits.clone()); let (full_w, full_h) = dec.dimensions().map_err(err)?; @@ -2102,6 +2118,7 @@ fn read_image( if !geo.referenced { let mut r = Raster::new(name, w, h, bands, super::unreferenced(w, h), Crs::LonLat, geo.nodata, color, data_type)?; r.georeferenced = false; + r.white_is_zero = white_is_zero; r.overview = overview; r.step = decimate_by.max(1); r.rounded = rounded; @@ -2197,6 +2214,7 @@ fn read_image( None => (w, h, overview), }; let mut r = Raster::new(name, w, h, bands, transform, crs, geo.nodata, color, data_type)?; + r.white_is_zero = white_is_zero; r.overview = overview; // A turned image is resampled to a grid of its own: its pixels are no longer the file's. r.step = if geo.affine.is_none() { decimate_by.max(1) } else { 1 }; @@ -2456,7 +2474,7 @@ fn encode(r: &Raster, band: usize, every: bool, out: &mut (impl std::io::Write + h, spp: u16::try_from(colour + extra.len()).map_err(|_| err("a TIFF holds at most 65,535 bands"))?, sample, - photometric: if rgb { 2 } else { 1 }, + photometric: if rgb { 2 } else { u16::from(!r.white_is_zero) }, extra, classes: matches!(written, [b] if r.bands.get(*b).is_some_and(few_classes)), tags: geo_entries(r, &geo, written, nodata_tag()), @@ -5456,6 +5474,65 @@ mod tests { out } + /// A grey image whose 0 is white has its values as stored, whole and in place, whichever + /// decoder reads its chunks, and no-data matched with them; the flag says how to draw it (#2761). + #[test] + fn white_is_zero_values_are_read_as_stored() { + use super::super::cog; + let data: Vec = (0..40 * 16).map(|i| (i * 7 % 251) as u8).collect(); + let mut bytes = grey8(40, 16, &data, None); + set_photometric(&mut bytes, 0); + let r = read(std::io::Cursor::new(&bytes), "w").unwrap(); + assert!(r.white_is_zero && r.color == ColorHint::Gray); + assert_eq!(r.bands[0].data, data.iter().map(|v| f32::from(*v)).collect::>()); + let header = Sparse::default().with(0, bytes.clone()); + let cog::Parse::Done(mut layout) = cog::layout(&header).unwrap() else { panic!("not read in place") }; + assert!(layout.white_is_zero); + layout.nodata = Some(f64::from(data[1])); + let (at, n) = (layout.levels[0].offsets[0] as usize, layout.levels[0].counts[0] as usize); + let strip = cog::decode_tile(&header, &layout, 0, 0, bytes[at..at + n].to_vec()).unwrap(); + assert_eq!(strip[0][2], f32::from(data[2])); + assert!(strip[0][1].is_nan(), "no-data is a stored value"); + // LZW, by our decoder too, which refused such an image before. + let pixel = |x: u32, y: u32| (x * 3 + y) as f32; + let mut lzw = lzw_tiled(300, 170, 128, 1, pixel); + set_photometric(&mut lzw, 0); + let r = read(std::io::Cursor::new(&lzw), "w").unwrap(); + assert!(r.white_is_zero); + assert_eq!(r.value(0, 299, 169), Some(pixel(299, 169))); + let mut dec = Decoder::new(reader(std::io::Cursor::new(&lzw)).unwrap()).unwrap(); + let DecodingResult::F32(ours) = super::super::lzw::chunk(&mut dec, 0).unwrap() else { panic!("not Float32") }; + assert_eq!(ours[129], pixel(1, 1)); + // Every overview too, whether it says 0 is white or, as some writers have it, isn't. + for overview in [0, 1] { + let mut two = std::io::Cursor::new(Vec::new()); + { + use tiff::encoder::{TiffEncoder, colortype}; + let mut enc = TiffEncoder::new(&mut two).unwrap(); + for (side, photometric) in [(64u32, 0u16), (32, overview)] { + let mut img = enc.new_image::(side, side).unwrap(); + let e = img.encoder(); + if side == 32 { + e.write_tag(Tag::NewSubfileType, 1u32).unwrap(); + } + e.write_tag(Tag::PhotometricInterpretation, photometric).unwrap(); + img.write_data(&(0..side * side).map(|i| (i % 251) as u8).collect::>()).unwrap(); + } + } + let r = read_limited(reader(std::io::Cursor::new(two.into_inner())).unwrap(), "o", 2_000, None).unwrap(); + assert_eq!((r.width, r.white_is_zero, r.value(0, 3, 0)), (32, true, Some(3.0)), "overview {overview}"); + } + // Written again, plain or cloud-optimised, the file says so still, and holds the values. + let r = read(std::io::Cursor::new(&bytes), "w").unwrap(); + for out in [write(&r, 0).unwrap(), super::super::cogwrite::write(&r, 0).unwrap()] { + let back = read(std::io::Cursor::new(&out), "back").unwrap(); + assert!(back.white_is_zero); + assert_eq!(back.bands[0].data, r.bands[0].data); + } + // 0 as black says nothing. + assert!(!read(std::io::Cursor::new(&grey8(40, 16, &data, None)), "b").unwrap().white_is_zero); + } + /// The chunks a sparse file leaves out are no-data read whole, with one thread or several, /// whole or every k-th pixel, compressed or not, and the image keeps its type (#2761). #[test] diff --git a/crates/data/src/raster/lzw.rs b/crates/data/src/raster/lzw.rs index b6b6f8355f..b5cda20bd7 100644 --- a/crates/data/src/raster/lzw.rs +++ b/crates/data/src/raster/lzw.rs @@ -44,10 +44,6 @@ pub(crate) fn chunk(dec: &mut Decoder, index: u32) -> Result< let planar = tag(dec, Tag::PlanarConfiguration) == Some(2); let samples = if planar { 1 } else { spp }; let predictor = tag(dec, Tag::Predictor).unwrap_or(1); - // WhiteIsZero samples are inverted by the crate; left to it. - if tag(dec, Tag::PhotometricInterpretation) == Some(0) { - return Err(err("WhiteIsZero LZW images aren't supported")); - } // Where the chunk is in its plane, and how much of it is image. let across = w.div_ceil(cw); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 4a91e30699..6cbb4cacb0 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -849,6 +849,9 @@ pub struct Raster { /// when this raster is exported; a raster made from it (clipped, reprojected) starts /// without. pub copyright: Option, + /// The file says 0 is white (a TIFF's MinIsWhite): the values are as stored, and a stretch of + /// them is drawn the other way round. A raster with other values made from it starts without. + pub white_is_zero: bool, transformer: Transformer, extent: Extent, } @@ -1030,6 +1033,7 @@ impl Raster { rounded: Vec::new(), rounded_some: Vec::new(), copyright: None, + white_is_zero: false, transformer, extent: Extent::EMPTY, }; @@ -1294,6 +1298,7 @@ impl Raster { let exact = (r.transform.pixel_width.abs() / (f64::from(self.step) * file_cell) - 1.0).abs() < 1e-9; r.step = if exact { self.step } else { 1 }; (r.source, r.lost, r.copyright) = (self.source, self.lost, self.copyright); + r.white_is_zero = self.white_is_zero; (r.rounded, r.rounded_some) = (self.rounded, self.rounded_some); r }; diff --git a/crates/data/src/raster/world.rs b/crates/data/src/raster/world.rs index 3f6033644a..e1b8350793 100644 --- a/crates/data/src/raster/world.rs +++ b/crates/data/src/raster/world.rs @@ -394,10 +394,12 @@ mod tests { let mut r = crate::raster::read_path_unplaced(&dir.join("p.png"), None, None).unwrap(); r.bands[0].name = "landcover".into(); r.bands[0].classes = vec!["water".into(), "forest".into()]; + r.white_is_zero = true; let wf = WorldFile::parse("0\n-1\n-1\n0\n11.5\n49.5\n").unwrap(); let r = r.placed_by_world_file(&wf, crate::raster::Crs::LonLat).map_err(|(_, e)| e).unwrap(); assert_eq!((r.width, r.height), (2, 4)); assert_eq!((r.bands[0].name.as_str(), r.bands[0].classes.len()), ("landcover", 2)); + assert!(r.white_is_zero, "0 stays white"); std::fs::remove_dir_all(&dir).unwrap(); } diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index b6f5db6f84..144c3060e9 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -235,6 +235,8 @@ fn copied(r: &Raster) -> Result>, String> { .map_err(|e| e.to_string()) } +/// `r`'s pixels, given as `bands`, on another grid: its bands' names and wavelengths, and which way +/// round its grey is drawn, are kept; what its file said it lost, and its overview, aren't. fn rebuild(r: &Raster, transform: GeoTransform, crs: Crs, bands: Vec>) -> Result { let mut out = Raster::new(r.name.clone(), r.width, r.height, bands, transform, crs, r.nodata, r.color.clone(), r.data_type.clone()) .map_err(|e| e.to_string())?; @@ -242,6 +244,7 @@ fn rebuild(r: &Raster, transform: GeoTransform, crs: Crs, bands: Vec>) o.name = i.name.clone(); o.wavelength = i.wavelength; } + out.white_is_zero = r.white_is_zero; Ok(out) } @@ -2015,6 +2018,7 @@ fn resample_whole(r: &super::workflows::Input, factor: u32, out: String) -> Resu let nodata = r.nodata.or(Some(NODATA as f64)); let color = if matches!(r.color, ColorHint::Palette(_)) { ColorHint::Gray } else { r.color.clone() }; let mut out = Raster::new(out, w, h, bands, gt, r.crs, nodata, color, r.data_type.clone()).map_err(|e| e.to_string())?; + out.white_is_zero = r.white_is_zero; // A block's mean is of the same band: its name and wavelength are the input's. out.bands.iter_mut().zip(&r.bands).for_each(|(o, i)| { o.name = i.name.clone(); @@ -2107,6 +2111,7 @@ fn resample_in_blocks( let t = first.ok_or_else(|| format!("{}: it has no pixels", reading.layer()))?; let mut res = Raster::new(out, w, h, res, t.transform, t.crs, t.nodata, t.color.clone(), t.data_type.clone()).map_err(|e| e.to_string())?; + res.white_is_zero = t.white_is_zero; res.bands.iter_mut().zip(&t.bands).for_each(|(o, i)| { o.name.clone_from(&i.name); o.wavelength = i.wavelength; @@ -2276,6 +2281,7 @@ fn resampled_as(read: &rustgis_data::raster::PartRead, k: u32, out: &str) -> Res o.name.clone_from(&i.name); o.wavelength = i.wavelength; }); + t.white_is_zero = r.white_is_zero; Ok(t) } @@ -2417,6 +2423,9 @@ impl Tiles { )); } let first = self.rs.first().unwrap_or(&r); + if r.white_is_zero != first.white_is_zero { + return Err(other_way_round((first, 1), (&r, self.rs.len() + 1))); + } mosaic_matches(first, &r)?; // Snapped to whole cells only when it is already within a hundredth of one. let (c, rr) = first.transform.to_pixel(r.transform.to_world(0.0, 0.0)); @@ -2510,6 +2519,7 @@ impl Tiles { o.wavelength = i.wavelength; }); out.copyright = first.copyright.clone(); + out.white_is_zero = first.white_is_zero; // The first input's metadata accompanies its pixels; report other credits rather than // silently dropping them or attributing every input to the first one's owner. let credits = rs @@ -2643,6 +2653,17 @@ pub(crate) fn mosaic_rasters_work(s: &Session, p: &Value) -> Result String { + let ((white, w), (black, k)) = if a.white_is_zero { ((a, at), (b, bt)) } else { ((b, bt), (a, at)) }; + format!( + "{}'s values (input {w}) take 0 as white and {}'s (input {k}) as black, so one mosaic can't hold both: invert input {w} \ + first, subtracting its values from the top of their scale in Raster Calculator (255 for 8-bit values)", + white.name, black.name + ) +} + /// Whether `r` can join a mosaic on `first`'s grid: one coordinate system, cell size and band count. fn mosaic_matches(first: &Raster, r: &Raster) -> Result<(), String> { first.require_coordinates()?; @@ -2735,6 +2756,7 @@ fn clip_window( band.name = r.bands.get(i).map_or_else(|| "Alpha".to_string(), |b| b.name.clone()); band.wavelength = r.bands.get(i).and_then(|b| b.wavelength); } + out.white_is_zero = r.white_is_zero; // Some of the values rounded when the file was read may be in the window: how many isn't known. out.keep_rounded_mark(r); // What reading the input left out was said, with its code, when the input was read: a clip, @@ -2909,6 +2931,7 @@ fn edit_pixels(s: &mut Session, p: &Value) -> CmdResult { o.name = i.name.clone(); o.wavelength = i.wavelength; }); + out.white_is_zero = r.white_is_zero; // The edit may have overwritten some of the values rounded when the file was read. out.keep_rounded_mark(&r); replace(s, &layer, out)?; @@ -3290,6 +3313,11 @@ 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", crs)?; // Colour only when every image is colour. A mosaic of 8-bit images stays 8-bit (means @@ -3312,6 +3340,7 @@ pub(crate) fn mosaic_work(s: &Session, p: &Value) -> Result = (!messages.is_empty()).then(|| { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 07b48408fa..b53befd3cc 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6946,6 +6946,7 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: let mut r = rustgis_data::raster::Raster::new(&name, width, height, bands, transform, layout.crs, layout.nodata, color, layout.data_type) .map_err(|e| named(e.to_string()))?; + r.white_is_zero = layout.white_is_zero; if rounded.iter().any(|n| *n > 0) { r.rounded = rounded; } diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index be165858e5..2e36a87267 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -164,7 +164,7 @@ fn channel_range(rl: &RasterLayer, r: &Raster, i: usize) -> Option<(f64, f64)> { let band = *rl.style.renderer.bands().get(i)?; let masked = rl.masked_stats(); let stats = masked.as_ref().and_then(|m| m.get(i)).or_else(|| r.bands.get(band).map(|b| &b.stats))?; - let n = Normalizer::for_channel(rl.style.stretch, i, stats, &r.data_type); + let n = Normalizer::drawn(&rl.style, r, i, stats); Some((n.lo, n.hi)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b06bfe54b..545aafe7fc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54564,6 +54564,57 @@ fn a_plugin_command_runs_again_when_its_window_is_added() { assert!(s.take_url_requests().is_empty() && !s.plugin_retries_waiting()); } +/// A file whose 0 is white keeps its stored values and stays drawn that way round however its +/// pixels get there: read in place, as a window, georeferenced, and kept in the project (#2761). +#[test] +fn a_white_is_zero_raster_stays_one() { + use rustgis_data::raster::cog::{Example, example_with}; + let (base, _) = serve_ranges(example_with(&Example { photometric: 0, ..Example::default() })); + let url = format!("{base}/scene.tif"); + let mut s = Session::new(Project::default()); + s.run("layer.addUrl", &json!({"url": url, "name": "Scene"})).unwrap(); + s.run("layer.addUrl", &json!({"url": url, "name": "Window", "window": {"bbox": [10.25, 45.5, 10.5, 45.75]}})).unwrap(); + let data = |s: &Session, name: &str| s.map().layer_by_name(name).and_then(|l| l.raster.as_ref()?.data.clone()).unwrap(); + // The window's corner is pixel (256, 256), (x + y) % 256; stored, not 255 less. + assert_eq!((data(&s, "Window").value(0, 0, 0), data(&s, "Window").value(0, 10, 5)), (Some(0.0), Some(15.0))); + assert!(data(&s, "Scene").white_is_zero && data(&s, "Window").white_is_zero); + s.run("raster.georeference", &json!({"layer": "Window", "extent": [0, 0, 1, 1], "crs": 4326})).unwrap(); + /// The folder, gone with the test however it ends. + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = Dir(std::env::temp_dir().join(format!("rustgis-white-{}-{now}", std::process::id()))); + std::fs::create_dir(&dir.0).unwrap(); + let project = dir.0.join("p.rgis").display().to_string(); + for reopened in [false, true] { + if reopened { + s.run("project.saveAs", &json!({"path": project})).unwrap(); + s.run("project.open", &json!({"path": project})).unwrap(); + } + let w = data(&s, "Window"); + assert_eq!((w.white_is_zero, w.value(0, 10, 5), w.transform.origin_y), (true, Some(15.0), 1.0), "reopened: {reopened}"); + } + // What keeps its values keeps it too; a mosaic doesn't mix the two ways round. + s.run("raster.process", &json!({"layer": "Window", "operation": "clip", "extent": [0.1, 0.1, 0.9, 0.9], "name": "Clip"})).unwrap(); + s.run("raster.process", &json!({"layer": "Window", "operation": "resample", "factor": 4, "name": "Coarse"})).unwrap(); + s.run("raster.project", &json!({"layer": "Window", "crs": 3857, "name": "Warped"})).unwrap(); + s.run("raster.mosaic", &json!({"inputs": ["Window", "Clip"], "name": "Both"})).unwrap(); + let box_ = json!([[0.1, 0.1], [0.2, 0.1], [0.2, 0.2], [0.1, 0.2]]); + s.run("raster.editPixels", &json!({"layer": "Window", "polygon": box_, "value": 9})).unwrap(); + for name in ["Clip", "Coarse", "Warped", "Both", "Window"] { + assert!(data(&s, name).white_is_zero, "{name}"); + } + let mut black = (*data(&s, "Clip")).clone(); + black.white_is_zero = false; + s.map_mut().add_raster("Black", rustgis_map::RasterLayer::from_path(black, "black.tif")); + let e = s.run("raster.mosaic", &json!({"inputs": ["Window", "Black"], "name": "Mixed"})).unwrap_err(); + assert!(e.contains("invert input 1 first") && e.contains("(input 2)") && e.contains("0 as white") && e.contains("as black"), "{e}"); +} + /// A window's read needs no session: on a thread, as the app reads it, then added when it lands /// (#1330). What can't be a window is refused before the read starts, and an error names the /// address without its keys. diff --git a/crates/map/src/layout/colorbar.rs b/crates/map/src/layout/colorbar.rs index 96aa67c9f5..f42f770f29 100644 --- a/crates/map/src/layout/colorbar.rs +++ b/crates/map/src/layout/colorbar.rs @@ -92,7 +92,7 @@ pub fn color_scale(rl: &RasterLayer) -> Option { let at = |v: f64| colorizer.key_color(&[v as f32], shade).map(Rgba); match &style.renderer { RasterRenderer::Stretch { .. } | RasterRenderer::ShadedRelief { ramp: Some(_), .. } => { - let n = Normalizer::new(style.stretch, stats, &r.data_type); + let n = Normalizer::drawn(&style, r, 0, stats); let (lo, hi) = (n.lo, n.hi); let colors = (0..RAMP_SAMPLES) .map(|i| at(lo + (hi - lo) * i as f64 / (RAMP_SAMPLES - 1) as f64).unwrap_or(Rgba::new(0, 0, 0, 0))) diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index c34aec5678..ad949e0493 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -106,6 +106,10 @@ pub struct RasterLayer { /// what the pixels lost. #[serde(skip)] look_lost: Option, + /// Whether its style has been checked by [`RasterLayer::say_stored_values`] since the layer was + /// opened with a project (one made this session has nothing to check). + #[serde(skip)] + values_checked: bool, /// Settings of the tile layer this one was opened from that a raster layer hasn't (see /// [`RasterLayer::dropped_unsaid`]). #[serde(skip)] @@ -326,7 +330,7 @@ impl RasterLayer { // An SRTM tile or DTED file takes no subdataset or coordinate system: the ones the layer // had were said to be ignored as it was read, and aren't kept. let elevation = rustgis_data::raster::is_elevation_name(path); - Ok(RasterLayer { + let mut layer = RasterLayer { path: Some(path.into()), in_place: false, tiled, @@ -352,10 +356,16 @@ impl RasterLayer { failures: 0, lost_said: false, look_lost: None, + // One opened with its file missing is checked now, with the file found. + values_checked: self.values_checked, dropped: Vec::new(), written: None, anonymous: false, - }) + }; + if let Some(data) = layer.data.clone() { + layer.say_stored_values(&data); + } + Ok(layer) } /// Checks a fresh candidate without changing the configured renderer or its palette. @@ -404,6 +414,7 @@ impl RasterLayer { failures: 0, lost_said: false, look_lost: None, + values_checked: true, dropped: Vec::new(), written: None, anonymous: false, @@ -462,6 +473,7 @@ impl RasterLayer { failures: 0, lost_said: false, look_lost: None, + values_checked: true, dropped: Vec::new(), written: None, anonymous: false, @@ -508,6 +520,7 @@ impl RasterLayer { failures: 0, lost_said: false, look_lost: None, + values_checked: true, dropped: Vec::new(), written: None, anonymous: false, @@ -764,6 +777,7 @@ impl RasterLayer { Ok(r) => { self.forget_ignored_options(); self.style.repair(&r); + self.say_stored_values(&r); self.data = Some(Arc::new(r)); self.pixels_said = false; self.lost_said = false; @@ -845,6 +859,17 @@ impl RasterLayer { lost } + /// Leaves a notice, as a saved layer's pixels are read, when its style names values of a file + /// whose 0 is white: RustGIS read such values inverted before 0.10, and a project doesn't say + /// which its style's are. A stretch worked out from the pixels draws as it did. + fn say_stored_values(&mut self, r: &Raster) { + if !std::mem::replace(&mut self.values_checked, true) && r.white_is_zero && self.style.names_values() { + let said = "its file says 0 is white: RustGIS before 0.10 inverted its values, and they are now read as stored. If its ranges, \ + classes or mask were set before 0.10, set them again"; + self.look_lost = Some(self.look_lost.take().map_or_else(|| said.to_string(), |l| format!("{l}; {said}"))); + } + } + /// Why a layer read in place couldn't be read, the first time it is asked for after the read /// failed, so it is said once (a project, an import or the browser read it after adding it). pub fn error_unsaid(&mut self) -> Option { @@ -888,6 +913,7 @@ impl RasterLayer { } else { self.style.repair(&raster); } + self.say_stored_values(&raster); self.data = Some(raster); self.error = None; self.failed_at = None; @@ -963,6 +989,7 @@ impl RasterLayer { failures: _, lost_said: _, look_lost: _, + values_checked: _, dropped: _, written: _, anonymous: _, @@ -2403,6 +2430,15 @@ impl RasterStyle { } } + /// Whether the style holds values of the raster's own (fixed bounds, classes, a mask), or + /// lights them as heights: what draws otherwise when the values are the other way round. A + /// stretch worked out from the pixels draws the same ([`Normalizer::drawn`]). + fn names_values(&self) -> bool { + !matches!(self.renderer, RasterRenderer::Stretch { .. } | RasterRenderer::Rgb { .. }) + || matches!(self.stretch, Stretch::Custom { .. }) + || self.mask != RasterMask::default() + } + /// The default look, as the file's PhotometricInterpretation says: the file's colours, RGB for /// colour images and for grey ones of exactly three bands (most remote sensing images are /// grey, whatever their bands: three are taken as red, green and blue), unique values for a @@ -2561,6 +2597,39 @@ impl Normalizer { Normalizer { lo, hi, cdf } } + /// The normaliser `style` draws `r`'s channel `channel` with, from its band's statistics `s`. + /// Where 0 is white ([`Raster::white_is_zero`]) a stretch's ramp is turned round, and so is + /// what isn't alike at both ends, so it draws as it would the values mirrored: a percent clip's + /// low end is the dark one, and equalization counts from the top. + pub fn drawn(style: &RasterStyle, r: &Raster, channel: usize, s: &BandStats) -> Normalizer { + if !r.white_is_zero || !matches!(style.renderer, RasterRenderer::Stretch { .. }) { + return Normalizer::for_channel(style.stretch, channel, s, &r.data_type); + } + let mut n = Normalizer::for_channel(style.stretch, channel, s, &r.data_type); + if matches!(style.stretch, Stretch::PercentClip { .. }) { + // From the statistics of the values mirrored about 0: a percentile counts up from the + // low end, so one counted down isn't another percentage counted up where values tie. + let mirrored = BandStats { + min: -s.max, + max: -s.min, + mean: -s.mean, + histogram: s.histogram.iter().rev().copied().collect(), + categories: None, + ..*s + }; + let m = Normalizer::for_channel(style.stretch, channel, &mirrored, &r.data_type); + (n.lo, n.hi) = (-m.hi, -m.lo); + } + if let Some(cdf) = &mut n.cdf { + // The share of the cells below each bin, not up to it. + cdf.rotate_right(1); + if let Some(first) = cdf.first_mut() { + *first = 0.0; + } + } + n + } + /// `v` scaled to 0–1 (clamped). pub fn t(&self, v: f64) -> f64 { let span = self.hi - self.lo; @@ -2611,12 +2680,13 @@ impl<'a> Colorizer<'a> { .enumerate() .map(|(i, b)| { let s = view_stats.and_then(|v| v.get(i)).or_else(|| r.bands.get(*b).map(|b| &b.stats)); - s.map(|s| Normalizer::for_channel(style.stretch, i, s, &r.data_type)).unwrap_or(Normalizer { lo: 0.0, hi: 1.0, cdf: None }) + s.map(|s| Normalizer::drawn(style, r, i, s)).unwrap_or(Normalizer { lo: 0.0, hi: 1.0, cdf: None }) }) .collect(); let ramp_lut = match &style.renderer { RasterRenderer::Stretch { ramp, invert, .. } => { - (0..256).map(|i| ramp.at(if *invert { 1.0 - i as f64 / 255.0 } else { i as f64 / 255.0 }).0).collect() + let invert = *invert != r.white_is_zero; + (0..256).map(|i| ramp.at(if invert { 1.0 - i as f64 / 255.0 } else { i as f64 / 255.0 }).0).collect() } RasterRenderer::ShadedRelief { ramp: Some(ramp), .. } => (0..256).map(|i| ramp.at(i as f64 / 255.0).0).collect(), _ => Vec::new(), @@ -2824,9 +2894,9 @@ impl RasterLayer { let mask = &self.style.mask; match &self.style.renderer { RasterRenderer::Stretch { band, ramp, invert } => { - let n = stats(*band).map(|s| Normalizer::new(self.style.stretch, s, &r.data_type)); + let n = stats(*band).map(|s| Normalizer::drawn(&self.style, r, 0, s)); let (lo, hi) = n.map(|n| (n.lo, n.hi)).unwrap_or((0.0, 1.0)); - vec![RasterLegend::Ramp { ramp: ramp.clone(), invert: *invert, high: fmt_num(hi), low: fmt_num(lo) }] + vec![RasterLegend::Ramp { ramp: ramp.clone(), invert: *invert != r.white_is_zero, high: fmt_num(hi), low: fmt_num(lo) }] } RasterRenderer::ShadedRelief { ramp: Some(ramp), band, .. } => { let s = stats(*band).map(|s| (s.min, s.max)).unwrap_or((0.0, 1.0)); @@ -3052,6 +3122,7 @@ impl RasterLayer { failures: _, lost_said: _, look_lost: _, + values_checked: _, dropped: _, written: _, anonymous: _, @@ -3452,6 +3523,124 @@ mod tests { assert!(rl.lost_unsaid().is_empty()); } + /// A layer saved before its pixels arrived takes its address's range when they do, which may + /// be of the inverted values: said (#2761). + #[test] + fn an_address_range_saved_before_its_pixels_is_said() { + let mut r = dem(); + r.white_is_zero = true; + let mut rl = RasterLayer::from_path(dem(), "scene.tif"); + (rl.restyle, rl.look) = (true, Some(AddressLook { bands: Vec::new(), range: Some((1.0, 2.0)) })); + (rl.values_checked, rl.data) = (false, None); + rl.land(Ok(Arc::new(r))); + assert!(matches!(rl.style.stretch, Stretch::Custom { .. })); + assert!(rl.lost_unsaid().iter().any(|n| format!("{n:?}").contains("0 is white"))); + } + + /// However it is stretched, a raster whose 0 is white draws each value as one whose 0 is black + /// draws it mirrored, as it was drawn when its values were inverted as they were read (#2761). + #[test] + fn white_is_zero_draws_as_the_mirrored_values() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 0.0, pixel_width: 1.0, pixel_height: -1.0 }; + let of = |v: Vec| Raster::new("g", v.len() as u32, 1, vec![v], gt, Crs::LonLat, None, ColorHint::Gray, "UInt8").unwrap(); + let spread: Vec = (0..2000).map(|i| ((i * i) % 211 + 20) as f32).collect(); + // Nine cells in ten one value, and two values alone. + let skewed: Vec = (0..2000).map(|i| if i % 10 > 0 { 5.0 } else { (i % 250) as f32 }).collect(); + let two: Vec = (0..2000).map(|i| if i % 10 > 0 { 0.0 } else { 255.0 }).collect(); + for values in [spread, skewed, two] { + let mirrored = of(values.iter().map(|v| 255.0 - v).collect()); + let mut white = of(values.clone()); + white.white_is_zero = true; + for stretch in [ + Stretch::None, + Stretch::MinMax, + Stretch::PercentClip { low: 0.5, high: 0.5 }, + Stretch::PercentClip { low: 0.0, high: 25.0 }, + Stretch::PercentClip { low: 10.0, high: 0.0 }, + Stretch::StandardDeviation { n: 1.0 }, + Stretch::HistogramEqualize, + ] { + for invert in [false, true] { + let mut style = RasterStyle::default_for(&white); + style.renderer = RasterRenderer::Stretch { band: 0, ramp: Ramp::gray(), invert }; + style.stretch = stretch; + let (a, b) = (Colorizer::new(&style, &white, None), Colorizer::new(&style, &mirrored, None)); + for v in &values { + let (a, b) = (a.color(&[*v], None).unwrap()[0], b.color(&[255.0 - v], None).unwrap()[0]); + assert!(a.abs_diff(b) <= 1, "{stretch:?}, inverted {invert}, value {v}: {a}, not {b}"); + } + } + } + } + } + + /// A layer opened with its file missing is checked when the file is found: its style's values are + /// said once, and not again by another repair (#2761). + #[test] + fn a_repaired_layer_says_its_values_are_stored() { + let mut r = dem(); + r.white_is_zero = true; + let path = std::env::temp_dir().join(format!("rustgis-repaired-white-{}.tif", std::process::id())); + std::fs::write(&path, rustgis_data::raster::geotiff::write(&r, 0).unwrap()).unwrap(); + let mut rl = RasterLayer::from_path(r, "gone.tif"); + rl.style.stretch = Stretch::custom(1.0, 2.0); + // As a project opens it, its file missing. + (rl.values_checked, rl.data) = (false, None); + let said = |rl: &mut RasterLayer| rl.lost_unsaid().iter().any(|n| format!("{n:?}").contains("0 is white")); + let mut found = rl.relinked(path.to_str().unwrap(), None).unwrap(); + assert!(said(&mut found)); + assert!(!said(&mut found.relinked(path.to_str().unwrap(), None).unwrap())); + std::fs::remove_file(&path).unwrap(); + } + + /// A file whose 0 is white draws its lowest value white, its legend the same way round, and an + /// inverted ramp the other way; a saved style that names values is said to need a look, one + /// worked out from the pixels isn't (#2761). + #[test] + fn white_is_zero_is_drawn_the_other_way_round() { + let mut r = dem(); + r.white_is_zero = true; + let (lo, hi) = (r.bands[0].stats.min as f32, r.bands[0].stats.max as f32); + let mut style = RasterStyle::default_for(&r); + style.renderer = RasterRenderer::Stretch { band: 0, ramp: Ramp::gray(), invert: false }; + style.stretch = Stretch::MinMax; + let drawn = |style: &RasterStyle, r: &Raster| { + let c = Colorizer::new(style, r, None); + [lo, hi].map(|v| c.color(&[v], None).unwrap()[0]) + }; + let mut plain = r.clone(); + plain.white_is_zero = false; + let [dark, light] = drawn(&style, &plain); + assert!(dark < light); + assert_eq!(drawn(&style, &r), [light, dark]); + let mut rl = RasterLayer::from_path(r.clone(), "w.tif"); + rl.style = style.clone(); + assert!(matches!(rl.legend()[0], RasterLegend::Ramp { invert: true, .. })); + style.invert_ramp(); + assert_eq!(drawn(&style, &r), [dark, light]); + // Read again for a saved project: said for fixed bounds alone. + for (stretch, said) in [ + (Stretch::MinMax, false), + (Stretch::PercentClip { low: 2.0, high: 2.0 }, false), + (Stretch::PercentClip { low: 0.0, high: 25.0 }, false), + (Stretch::HistogramEqualize, false), + (Stretch::custom(1.0, 2.0), true), + ] { + for (raster, white) in [(&r, true), (&plain, false)] { + rl.style.stretch = stretch; + rl.data = None; + rl.look_lost = None; + // As a project opens it. + rl.values_checked = false; + rl.land(Ok(Arc::new(raster.clone()))); + assert_eq!(rl.lost_unsaid().iter().any(|n| format!("{n:?}").contains("0 is white")), said && white); + // Read again this session: not said again. + rl.land(Ok(Arc::new(raster.clone()))); + assert_eq!(rl.look_lost, None); + } + } + } + /// A project file may ask for any band number: the one past the last `usize` is said by /// number, not overflowed. #[test] diff --git a/crates/render/src/value_mask.rs b/crates/render/src/value_mask.rs index 5a2df05660..22fccf8085 100644 --- a/crates/render/src/value_mask.rs +++ b/crates/render/src/value_mask.rs @@ -37,7 +37,8 @@ pub(crate) fn shares(rl: &RasterLayer, mask: &ValueMask, view: &View, place: Pla // raster has a value. let grey = |lo: f64, hi: f64, invert: bool| { let style = RasterStyle { - renderer: RasterRenderer::Stretch { band: 0, ramp: ramp.clone(), invert }, + // By its values, whichever way round the raster is drawn (`Raster::white_is_zero`). + renderer: RasterRenderer::Stretch { band: 0, ramp: ramp.clone(), invert: invert != data.white_is_zero }, stretch: Stretch::Custom { min: lo, max: hi, bands: None }, dra: false, resampling: rl.style.resampling, @@ -98,7 +99,9 @@ mod tests { let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 1.0, pixel_height: -1.0 }; for v in [-1e-10, 0.0, 1e-10, 10.0, 17.5, 19.0, 20.0, 30.0, 41.0, 42.5, 50.0] { let r = Raster::new("v", 10, 10, vec![vec![v as f32; 100]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); - let rl = RasterLayer::from_path(r, "v.tif"); + let mut white = r.clone(); + white.white_is_zero = true; + let (rl, white) = (RasterLayer::from_path(r, "v.tif"), RasterLayer::from_path(white, "v.tif")); for (min, max, inside, feather) in [ (Some(20.0), Some(40.0), true, 5.0), (Some(20.0), None, false, 5.0), @@ -112,6 +115,8 @@ mod tests { ] { let mask = ValueMask { raster: "v".into(), min, max, inside, feather }; let got = shares(&rl, &mask, &view, Place::Flat(&Flat::Mercator, "mercator"), 4, 4, true).unwrap(); + let place = Place::Flat(&Flat::Mercator, "mercator"); + assert_eq!(shares(&white, &mask, &view, place, 4, 4, true).unwrap(), got, "0 as white: {v} in {mask:?}"); let want = (mask.share(v) * 255.0).round(); assert!(got.iter().all(|s| (f64::from(*s) - want).abs() <= 2.0), "{v} in {mask:?}: {got:?}, not {want}"); } diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 4e34530855..ff56125d5d 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -1555,6 +1555,7 @@ fn draw(info: Arc, url: String, look: &Look, stretch: &[(f32, f32)], z: u8 alpha: info.alpha.and_then(|a| shown.iter().rposition(|b| *b == a)), alpha_max: rustgis_data::raster::alpha_max(info.layout.data_type), palette: info.palette(look).map(<[[u8; 4]]>::to_vec), + invert: info.layout.white_is_zero, aef: look.aef, stretch: stretch.to_vec(), }; @@ -1581,6 +1582,8 @@ struct Pen { alpha_max: f32, /// A palette image's colours, by value (no stretch). palette: Option>, + /// Grey is drawn the other way round (the file says 0 is white). + invert: bool, aef: bool, stretch: Vec<(f32, f32)>, } @@ -1628,7 +1631,7 @@ fn paint(pen: &Pen, spots: &[Option<(u32, usize)>], wanted: &[u32], tiles: &[Pic if !g.is_finite() { continue; } - let g = scale(0, g); + let g = if pen.invert { 255 - scale(0, g) } else { scale(0, g) }; [g, g, g, a] }; if let Some(out) = rgba.get_mut(k * 4..k * 4 + 4) { @@ -3028,7 +3031,7 @@ mod tests { red[1] = f32::NAN; let tile: Picked = vec![(Arc::new(vec![red].into()), 0), (chunk(20.0), 0), (chunk(30.0), 0)]; let spots: Vec> = (0..(SIZE * SIZE) as usize).map(|k| if k < 2 { Some((7, k)) } else { None }).collect(); - let pen = Pen { rgb: true, alpha: None, alpha_max: 255.0, palette: None, aef: false, stretch: vec![(0.0, 40.0); 3] }; + let pen = Pen { rgb: true, alpha: None, alpha_max: 255.0, palette: None, invert: false, aef: false, stretch: vec![(0.0, 40.0); 3] }; let out = paint(&pen, &spots, &[7], &[tile]).unwrap(); let px = &out[crate::cache::RAW.len() + 8..]; assert_eq!(&px[..4], &[64, 128, 191, 255]); @@ -3063,12 +3066,18 @@ mod tests { let px = |out: Vec| out[crate::cache::RAW.len() + 8..crate::cache::RAW.len() + 8 + 12].to_vec(); // A 16-bit pan band and its 16-bit alpha band: opaque, half, hidden. let tile: Picked = vec![(chunk(vec![500.0, 1000.0, 1000.0, 0.0]), 0), (chunk(vec![65535.0, 32768.0, 0.0, 0.0]), 0)]; - let pen = Pen { rgb: false, alpha: Some(1), alpha_max: 65535.0, palette: None, aef: false, stretch: vec![(0.0, 1000.0)] }; - assert_eq!(px(paint(&pen, &spots, &[7], &[tile]).unwrap()), [128, 128, 128, 255, 255, 255, 255, 128, 0, 0, 0, 0]); + let pen = + Pen { rgb: false, alpha: Some(1), alpha_max: 65535.0, palette: None, invert: false, aef: false, stretch: vec![(0.0, 1000.0)] }; + let drawn = |pen: &Pen| px(paint(pen, &spots, &[7], std::slice::from_ref(&tile)).unwrap()); + assert_eq!(drawn(&pen), [128, 128, 128, 255, 255, 255, 255, 128, 0, 0, 0, 0]); + // 0 as white: the grey the other way round, not its alpha (#2761). + let white = Pen { invert: true, ..pen }; + assert_eq!(drawn(&white), [127, 127, 127, 255, 0, 0, 0, 128, 0, 0, 0, 0]); // A palette image: each value its colour, a transparent one or one past the table nothing. let tile: Picked = vec![(chunk(vec![1.0, 2.0, 9.0, 0.0]), 0)]; let table = vec![[0, 0, 0, 255], [200, 10, 20, 255], [0, 0, 0, 0]]; - let pen = Pen { rgb: false, alpha: None, alpha_max: 255.0, palette: Some(table), aef: false, stretch: vec![(0.0, 255.0)] }; + let pen = + Pen { rgb: false, alpha: None, alpha_max: 255.0, palette: Some(table), invert: false, aef: false, stretch: vec![(0.0, 255.0)] }; let out = px(paint(&pen, &spots, &[7], &[tile]).unwrap()); assert_eq!(&out[..4], &[200, 10, 20, 255]); assert_eq!(&out[4..8], &[0, 0, 0, 0], "a transparent colour"); diff --git a/crates/tiles/src/cog/raster.rs b/crates/tiles/src/cog/raster.rs index 58d05554f6..cc6516cb84 100644 --- a/crates/tiles/src/cog/raster.rs +++ b/crates/tiles/src/cog/raster.rs @@ -74,6 +74,9 @@ pub fn overview_blocking(url: &str) -> Result { rx.recv_timeout(rustgis_data::raster::IN_PLACE_WAIT).map_err(|_| format!("{}: no answer in two minutes", split(url).0))? } +/// Reads the level a layer holds ([`overview_level`]), every band, its tiles asked for together, +/// as a raster with what the header says of it; `done` is given it, or why it can't be read. A +/// file on this computer that changes meanwhile is an error, as its tiles would be of two files. fn read_overview(info: Arc, url: String, done: Box) + Send>) { let Some(coarsest) = info.layout.levels.last() else { done(Err(format!("{url}: the GeoTIFF has no image"))); @@ -155,6 +158,7 @@ fn read_overview(info: Arc, url: String, done: Box