From 234d7e5272361eb388fc43026723959dade0d88f Mon Sep 17 00:00:00 2001 From: choupeanut Date: Sun, 22 Nov 2026 21:59:20 +0800 Subject: [PATCH 1/8] fix(data): an RGBA GeoTIFF with a NaN colour under an opaque alpha is written as floats, not opaque 0 (#2665) --- crates/data/src/raster/geotiff.rs | 51 ++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 916d8a0da1..fff67c06a8 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -2004,10 +2004,24 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { // The fourth sample of a colour file says what it is: alpha, or data (as RGB and near-infrared). let fourth = || vec![if matches!(r.color, ColorHint::Rgb { alpha: true }) { 2 } else { 0 }]; // Without alpha or a no-data marker, byte samples cannot keep NaN holes (for example the - // cells outside a reprojected RGBI image). Keep those samples as floats instead. - let byte_holes = r.nodata.is_none() - && matches!(r.color, ColorHint::Rgb { alpha: false }) - && written_bands(r, band).iter().any(|b| r.bands.get(*b).is_some_and(|b| b.stats.count < (w as usize) * (h as usize))); + // cells outside a reprojected RGBI image). Keep those samples as floats instead. With alpha, + // a hole its alpha hides is fine (the cell is see-through), but one under an opaque alpha + // would be written as an opaque 0. Looked at only when the byte branch is reached. + let byte_holes = || { + r.nodata.is_none() + && match r.color { + ColorHint::Rgb { alpha: false } => { + written_bands(r, band).iter().any(|b| r.bands.get(*b).is_some_and(|b| b.stats.count < (w as usize) * (h as usize))) + } + ColorHint::Rgb { alpha: true } => (0..3).any(|b| { + r.bands + .get(b) + .zip(r.see_through_cells(b)) + .is_some_and(|(band, hidden)| band.data.iter().enumerate().any(|(i, v)| !v.is_finite() && !hidden(i))) + }), + _ => false, + } + }; let all: Vec = (0..r.bands.len()).collect(); if every && written_bands(r, band).len() < all.len() { // More bands than colour (or one grey band) takes: each a 32-bit float sample, the first @@ -2052,7 +2066,7 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { wide!(|v: f32| v, Sample::Float, f32::to_le_bytes) } } else if rgb - && !byte_holes + && !byte_holes() && (!written_bands(r, band).contains(&3) || fits_bytes(r, 3)) && let (Some(red), Some(green), Some(blue)) = (bytes(0), bytes(1), bytes(2)) { @@ -2722,6 +2736,33 @@ mod tests { } } + /// An 8-bit RGBA raster with no no-data value keeps a NaN colour under an opaque alpha (as + /// floats, not as an opaque 0); a NaN the alpha already hides, and a clean raster, stay bytes. + #[test] + fn rgba_nan_colour_under_opaque_alpha_is_not_written_as_zero() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; + let rgba = |red: [f32; 3], alpha: [f32; 3]| { + let bands = vec![red.to_vec(), vec![5.0; 3], vec![6.0; 3], alpha.to_vec()]; + Raster::new("rgba", 3, 1, bands, gt, Crs::LonLat, None, ColorHint::Rgb { alpha: true }, "UInt8").unwrap() + }; + let nan = f32::NAN; + for (case, r, floats) in [ + ("NaN under an opaque alpha", rgba([1.0, nan, 2.0], [255.0; 3]), true), + ("NaN under a clear alpha", rgba([1.0, nan, 2.0], [255.0, 0.0, 255.0]), false), + ("no NaN", rgba([1.0, 3.0, 2.0], [255.0; 3]), false), + ] { + for (writer, bytes) in [("write", write(&r, 0).unwrap()), ("write_all", write_all(&r).unwrap())] { + let back = read(std::io::Cursor::new(bytes), "back").unwrap(); + let expected = if floats { "Float32" } else { "UInt8" }; + assert_eq!(back.data_type, expected, "{case}, {writer}"); + if floats { + assert!(back.bands[0].data[1].is_nan(), "{case}, {writer}: {:?}", back.bands[0].data); + assert_eq!(back.bands[0].data[0], 1.0, "{case}, {writer}"); + } + } + } + } + #[test] fn rgbi_byte_export_does_not_turn_nir_into_alpha() { let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; From 4237d193189f762494126b6793a7ea895416b89f Mon Sep 17 00:00:00 2001 From: choupeanut Date: Sun, 22 Nov 2026 22:11:07 +0800 Subject: [PATCH 2/8] fix(data): address review of the RGBA NaN fix: cover grey and RGB, fall back to counts, check last (#2665) --- crates/data/src/raster/cogwrite.rs | 5 ++- crates/data/src/raster/geotiff.rs | 69 +++++++++++++++++++----------- docs/user-guide/data.md | 3 +- 3 files changed, 49 insertions(+), 28 deletions(-) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index ce78a846b2..71e6f45ae2 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -137,8 +137,9 @@ fn fits_shorts(r: &Raster, b: usize) -> bool { r.data_type == "UInt16" && nodata_ok && ((s.min >= 0.0 && s.max <= 65_535.0) || s.count == 0) } -/// Chooses the file's samples like [`super::geotiff::write`] does: a colour raster's colour bands -/// (as bytes when they are bytes, alpha kept), otherwise `band` alone. 16-bit rasters stay 16-bit, +/// Chooses the file's samples like [`super::geotiff::write`] does, except that a colour cell with +/// no value under an opaque alpha is written see-through here (its alpha 0), not as floats there: +/// a colour raster's colour bands (as bytes when they are bytes, alpha kept), otherwise `band` alone. 16-bit rasters stay 16-bit, /// and a grey byte raster is written as bytes when no pixel needs a no-data value the bytes can't /// hold. Grey with alpha keeps both bands; a palette raster keeps its colour table. fn plan(r: &Raster, band: usize) -> Result { diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index fff67c06a8..8ebb677f1e 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -2006,19 +2006,21 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { // Without alpha or a no-data marker, byte samples cannot keep NaN holes (for example the // cells outside a reprojected RGBI image). Keep those samples as floats instead. With alpha, // a hole its alpha hides is fine (the cell is see-through), but one under an opaque alpha - // would be written as an opaque 0. Looked at only when the byte branch is reached. + // would be written as an opaque 0. A pass over the bands: the byte branch asks it last. let byte_holes = || { + let counted = + || written_bands(r, band).iter().any(|b| r.bands.get(*b).is_some_and(|b| b.stats.count < (w as usize) * (h as usize))); r.nodata.is_none() - && match r.color { - ColorHint::Rgb { alpha: false } => { - written_bands(r, band).iter().any(|b| r.bands.get(*b).is_some_and(|b| b.stats.count < (w as usize) * (h as usize))) - } - ColorHint::Rgb { alpha: true } => (0..3).any(|b| { + && match (&r.color, r.color.alpha(r.bands.len())) { + (ColorHint::Rgb { alpha: false }, _) => counted(), + (ColorHint::Rgb { alpha: true }, Some((_, colour))) => colour.into_iter().any(|b| { r.bands .get(b) .zip(r.see_through_cells(b)) .is_some_and(|(band, hidden)| band.data.iter().enumerate().any(|(i, v)| !v.is_finite() && !hidden(i))) }), + // No alpha band to hide a hole (alpha declared on three bands). + (ColorHint::Rgb { alpha: true }, None) => counted(), _ => false, } }; @@ -2066,9 +2068,9 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { wide!(|v: f32| v, Sample::Float, f32::to_le_bytes) } } else if rgb - && !byte_holes() && (!written_bands(r, band).contains(&3) || fits_bytes(r, 3)) && let (Some(red), Some(green), Some(blue)) = (bytes(0), bytes(1), bytes(2)) + && !byte_holes() { let alpha = if written_bands(r, band).contains(&3) { bytes(3) } else { None }; let n = (w as usize) * (h as usize); @@ -2736,28 +2738,45 @@ mod tests { } } - /// An 8-bit RGBA raster with no no-data value keeps a NaN colour under an opaque alpha (as - /// floats, not as an opaque 0); a NaN the alpha already hides, and a clean raster, stay bytes. + /// An 8-bit raster with no no-data value keeps a NaN cell as a NaN, in floats, never as 0: grey + /// with a second band (`write_all`), RGB without alpha, and RGBA with a NaN colour under an + /// opaque alpha (`write` and `write_all`). A NaN colour the alpha hides, and a raster with no + /// NaN, stay bytes. An RGBA raster written as floats keeps its alpha band and colour hint. #[test] - fn rgba_nan_colour_under_opaque_alpha_is_not_written_as_zero() { + fn nan_cells_of_byte_rasters_without_no_data_are_not_written_as_zero() { let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; - let rgba = |red: [f32; 3], alpha: [f32; 3]| { - let bands = vec![red.to_vec(), vec![5.0; 3], vec![6.0; 3], alpha.to_vec()]; - Raster::new("rgba", 3, 1, bands, gt, Crs::LonLat, None, ColorHint::Rgb { alpha: true }, "UInt8").unwrap() - }; let nan = f32::NAN; - for (case, r, floats) in [ - ("NaN under an opaque alpha", rgba([1.0, nan, 2.0], [255.0; 3]), true), - ("NaN under a clear alpha", rgba([1.0, nan, 2.0], [255.0, 0.0, 255.0]), false), - ("no NaN", rgba([1.0, 3.0, 2.0], [255.0; 3]), false), - ] { - for (writer, bytes) in [("write", write(&r, 0).unwrap()), ("write_all", write_all(&r).unwrap())] { + let raster = |bands: Vec>, color| Raster::new("nan", 3, 1, bands, gt, Crs::LonLat, None, color, "UInt8").unwrap(); + let rgb = |red: [f32; 3], blue: [f32; 3]| vec![red.to_vec(), vec![5.0; 3], blue.to_vec()]; + let rgba = |red: [f32; 3], blue: [f32; 3], alpha: [f32; 3]| { + let mut bands = rgb(red, blue); + bands.push(alpha.to_vec()); + raster(bands, ColorHint::Rgb { alpha: true }) + }; + let cases = [ + ("two bands, NaN", raster(vec![vec![1.0, nan, 2.0], vec![3.0; 3]], ColorHint::Gray), true), + ("two bands, no NaN", raster(vec![vec![1.0, 4.0, 2.0], vec![3.0; 3]], ColorHint::Gray), false), + ("RGB, NaN", raster(rgb([1.0, nan, 2.0], [6.0; 3]), ColorHint::Rgb { alpha: false }), true), + ("RGB, no NaN", raster(rgb([1.0, 4.0, 2.0], [6.0; 3]), ColorHint::Rgb { alpha: false }), false), + ("RGBA, NaN under an opaque alpha", rgba([1.0, nan, 2.0], [6.0, 6.0, nan], [255.0; 3]), true), + ("RGBA, NaN under a clear alpha", rgba([1.0, nan, 2.0], [6.0, nan, 6.0], [255.0, 0.0, 255.0]), false), + ("RGBA, no NaN", rgba([1.0, 4.0, 2.0], [6.0; 3], [255.0; 3]), false), + ]; + for (case, r, floats) in &cases { + for (writer, bytes) in [("write", write(r, 0).unwrap()), ("write_all", write_all(r).unwrap())] { + // `write` keeps one band of a two-band grey raster: only `write_all` is asked of it. + if writer == "write" && r.bands.len() == 2 { + continue; + } let back = read(std::io::Cursor::new(bytes), "back").unwrap(); - let expected = if floats { "Float32" } else { "UInt8" }; - assert_eq!(back.data_type, expected, "{case}, {writer}"); - if floats { - assert!(back.bands[0].data[1].is_nan(), "{case}, {writer}: {:?}", back.bands[0].data); - assert_eq!(back.bands[0].data[0], 1.0, "{case}, {writer}"); + let at = format!("{case}, {writer}"); + assert_eq!(back.data_type, if *floats { "Float32" } else { "UInt8" }, "{at}"); + assert_eq!((back.band_count(), &back.color), (r.band_count(), &r.color), "{at}"); + if *floats { + for (b, band) in r.bands.iter().enumerate() { + let same = |(a, b): (&f32, &f32)| a == b || (a.is_nan() && b.is_nan()); + assert!(band.data.iter().zip(&back.bands[b].data).all(same), "{at}, band {b}: {:?}", back.bands[b].data); + } } } } diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 97cf491880..f7ac2f50a1 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1576,7 +1576,8 @@ and the MCP server see it too. A GeoTIFF read in place that is added before its (the desktop app, the browser) answers `"reading": true`, sized by its header when that is in, and with `null` for its size and bands until then. `share.exportRaster` writes an untiled GeoTIFF, in strips of rows, with an 8-bit grey band (a -hillshade, say) as bytes and another single band as 32-bit floats; with `"cog": true` it writes a +hillshade, say) as bytes and another single band as 32-bit floats (so is an RGBA raster with a NaN +colour that isn't see-through; a cloud-optimised file makes that cell see-through instead); with `"cog": true` it writes a cloud-optimised one: 512-pixel tiles, overviews (each half the size of the last, down to one tile), and every directory ahead of the tiles, so a reader fetches the header once and then only the tiles it needs. Both compress with Deflate after a predictor: the floating-point one for decimal values, From 77404e303d3d638ed47fab56bc46a61e19967eab Mon Sep 17 00:00:00 2001 From: choupeanut Date: Sun, 22 Nov 2026 22:17:38 +0800 Subject: [PATCH 3/8] docs(data): reword the COG plan doc and the export paragraph's RGBA remark (#2665) --- crates/data/src/raster/cogwrite.rs | 10 +++++----- docs/user-guide/data.md | 16 ++++++++-------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index 71e6f45ae2..84f8f32229 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -137,11 +137,11 @@ fn fits_shorts(r: &Raster, b: usize) -> bool { r.data_type == "UInt16" && nodata_ok && ((s.min >= 0.0 && s.max <= 65_535.0) || s.count == 0) } -/// Chooses the file's samples like [`super::geotiff::write`] does, except that a colour cell with -/// no value under an opaque alpha is written see-through here (its alpha 0), not as floats there: -/// a colour raster's colour bands (as bytes when they are bytes, alpha kept), otherwise `band` alone. 16-bit rasters stay 16-bit, -/// and a grey byte raster is written as bytes when no pixel needs a no-data value the bytes can't -/// hold. Grey with alpha keeps both bands; a palette raster keeps its colour table. +/// Chooses the file's samples like [`super::geotiff::write`] does, except for a colour cell with +/// no value under an opaque alpha: it is written see-through here (its alpha 0), not as floats +/// there. A colour raster's colour bands are written (as bytes when they are bytes, alpha kept), +/// otherwise `band` alone. 16-bit rasters stay 16-bit, and a grey byte raster is written as bytes +/// when no pixel needs a no-data value the bytes can't hold. Grey with alpha keeps both bands; a palette raster keeps its colour table. fn plan(r: &Raster, band: usize) -> Result { let int_nodata = |max: f64| r.nodata.filter(|d| (0.0..=max).contains(d) && d.fract() == 0.0).map(|d| d as u16); // The type of a set of bands: bytes, else 16-bit when that is what they are, else floats. diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index f7ac2f50a1..9758027255 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1577,14 +1577,14 @@ and the MCP server see it too. A GeoTIFF read in place that is added before its with `null` for its size and bands until then. `share.exportRaster` writes an untiled GeoTIFF, in strips of rows, with an 8-bit grey band (a hillshade, say) as bytes and another single band as 32-bit floats (so is an RGBA raster with a NaN -colour that isn't see-through; a cloud-optimised file makes that cell see-through instead); with `"cog": true` it writes a -cloud-optimised one: 512-pixel tiles, overviews (each half the size of the last, down to one tile), -and every directory ahead of the tiles, so a reader fetches the header once and then only the tiles -it needs. Both compress with Deflate after a predictor: the floating-point one for decimal values, -differences along the row for whole numbers, none for classes. Overviews are averaged, except for a -single band of classes (a palette raster's, a band with class names, or a band written as 8- or -16-bit whole numbers with a few distinct values), whose overviews take a pixel so that no class is -invented; colour and grey-with-alpha files are always averaged. A palette keeps its colour table, +colour that isn't see-through); with `"cog": true` it writes a cloud-optimised one: 512-pixel +tiles, overviews (each half the size of the last, down to one tile), and every directory ahead of +the tiles, so a reader fetches the header once and then only the tiles it needs. A cloud-optimised +file makes that RGBA raster's NaN cell see-through instead. Both compress with Deflate after a +predictor: the floating-point one for decimal values, differences along the row for whole numbers, +none for classes. Overviews are averaged, except for a single band of classes (a palette raster's, +a band with class names, or a band written as 8- or 16-bit whole numbers with a few distinct +values), whose overviews take a pixel so that no class is invented; colour and grey-with-alpha files are always averaged. A palette keeps its colour table, though not the table's transparency, which a TIFF colour table can't hold (GDAL drops it too). Either file is classic TIFF when it would fit in 4 GiB even uncompressed and BigTIFF when it might not. From dd4d33b549d60c3e07c7a8ed6f943298d8c44705 Mon Sep 17 00:00:00 2001 From: choupeanut Date: Mon, 23 Nov 2026 09:46:36 +0800 Subject: [PATCH 4/8] data: keep the opacity of an RGBA raster written as floats (#2665) --- crates/data/src/raster/cogwrite.rs | 15 +++++- crates/data/src/raster/geotiff.rs | 83 +++++++++++++++++++++++++++--- crates/data/src/raster/mod.rs | 8 ++- docs/user-guide/data.md | 7 +-- 4 files changed, 101 insertions(+), 12 deletions(-) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index 84f8f32229..f14564b5cb 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -326,6 +326,8 @@ fn tile_samples(r: &Raster, plan: &Plan, lv: &Level, tx: u32, ty: u32) -> Vec Vec raw.push(if v.is_nan() { int_pad as u8 } else { v.round().clamp(0.0, 255.0) as u8 }), Sample::Short => { let n = if v.is_nan() { int_pad } else { v.round().clamp(0.0, 65_535.0) as u16 }; raw.extend_from_slice(&n.to_le_bytes()); } - Sample::Float => raw.extend_from_slice(&(if v.is_nan() { float_pad } else { *v }).to_le_bytes()), + Sample::Float => { + let v = if v.is_nan() { + float_pad + } else if plan.alpha == Some(i) { + v / opaque + } else { + *v + }; + raw.extend_from_slice(&v.to_le_bytes()); + } } } } diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 8ebb677f1e..a4f60f9d95 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1926,6 +1926,8 @@ pub fn written_bands(r: &Raster, band: usize) -> Vec { /// Writes a raster as a Deflate-compressed GeoTIFF: a colour raster's colour bands (RGB(A) bytes /// when they are 8-bit, else 32-bit floats, alpha kept), so it reads back in colour; otherwise /// `band` (0-based), as bytes when it is an 8-bit band of whole bytes, else as 32-bit floats. +/// An integer raster's alpha, when written as floats, is divided by its opaque value (1 is opaque +/// in a float file). /// `band` is for rasters that aren't colour ones: a colour raster always writes its colour bands, /// as its 8-bit form did before. The strips go through the predictors and Deflate effort of the /// COG writer ([`super::cogwrite::write_strips`]). A cancelled run stops it (with @@ -2055,17 +2057,19 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { crate::progress::check()?; } // Every band holds `n` values (checked above), so none is filled in. - data.extend(r.bands.iter().map(|b| $sample(b.data.get(i).copied().unwrap_or(f32::NAN)))); + data.extend(r.bands.iter().enumerate().map(|(bi, b)| $sample(bi, b.data.get(i).copied().unwrap_or(f32::NAN)))); } put(image(&all[..], $kind, extras)?, &data, $le, &mut out)?; }}; } if as_bytes { let nodata = r.nodata.map_or(0, |d| d as u8); - let byte = |v: f32| if r.is_valid(v) { v.clamp(0.0, 255.0) as u8 } else { nodata }; + let byte = |_: usize, v: f32| if r.is_valid(v) { v.clamp(0.0, 255.0) as u8 } else { nodata }; wide!(byte, Sample::Byte, u8::to_le_bytes) } else { - wide!(|v: f32| v, Sample::Float, f32::to_le_bytes) + // A float file's alpha is opaque at 1: an integer raster's is divided by its opaque value. + let (opaque, alpha_band) = (super::alpha_max(&r.data_type), alpha.then_some(if rgb { 3 } else { 1 })); + wide!(|bi: usize, v: f32| if Some(bi) == alpha_band { v / opaque } else { v }, Sample::Float, f32::to_le_bytes) } } else if rgb && (!written_bands(r, band).contains(&3) || fits_bytes(r, 3)) @@ -2089,14 +2093,17 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { } } else if rgb && let (Some(red), Some(green), Some(blue)) = (r.bands.first(), r.bands.get(1), r.bands.get(2)) { // Colour bands that aren't bytes (three embedding dimensions): kept as 32-bit floats, with - // their alpha band when they have one. + // their alpha band when they have one. A float file's alpha is opaque at 1, so an integer + // raster's alpha (255 for bytes) is divided by its opaque value, to stay as see-through. let n = (w as usize) * (h as usize); let at = |b: &crate::raster::Band, i: usize| b.data.get(i).copied().unwrap_or(f32::NAN); + // Only a declared alpha: the fourth band of an RGBI image is data. + let opaque = if matches!(r.color, ColorHint::Rgb { alpha: true }) { super::alpha_max(&r.data_type) } else { 1.0 }; match r.bands.get(3).filter(|_| written_bands(r, band).contains(&3)) { Some(alpha) => { let mut data = Vec::with_capacity(n * 4); for i in 0..n { - data.extend([at(red, i), at(green, i), at(blue, i), at(alpha, i)]); + data.extend([at(red, i), at(green, i), at(blue, i), at(alpha, i) / opaque]); } put(image(&[0, 1, 2, 3], Sample::Float, fourth())?, &data, f32::to_le_bytes, &mut out)?; } @@ -2773,7 +2780,9 @@ mod tests { assert_eq!(back.data_type, if *floats { "Float32" } else { "UInt8" }, "{at}"); assert_eq!((back.band_count(), &back.color), (r.band_count(), &r.color), "{at}"); if *floats { - for (b, band) in r.bands.iter().enumerate() { + // An alpha band is on the float scale: `rgba_written_as_floats_keeps_its_opacity`. + let alpha = if r.color == (ColorHint::Rgb { alpha: true }) { Some(3) } else { None }; + for (b, band) in r.bands.iter().enumerate().filter(|(b, _)| Some(*b) != alpha) { let same = |(a, b): (&f32, &f32)| a == b || (a.is_nan() && b.is_nan()); assert!(band.data.iter().zip(&back.bands[b].data).all(same), "{at}, band {b}: {:?}", back.bands[b].data); } @@ -2782,6 +2791,68 @@ mod tests { } } + /// An RGBA raster written as floats keeps how see-through each pixel is: its alpha is on the + /// float scale (1 is opaque) once read back, whatever scale the integer raster had. The + /// colours stay as they are (a float raster is stretched by its own range when drawn). + #[test] + fn rgba_written_as_floats_keeps_its_opacity() { + use super::super::cogwrite; + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; + let rgba = |data_type: &str, red: [f32; 3], alpha: [f32; 3]| { + let bands = vec![red.to_vec(), vec![5.0; 3], vec![6.0; 3], alpha.to_vec()]; + Raster::new("rgba", 3, 1, bands, gt, Crs::LonLat, None, ColorHint::Rgb { alpha: true }, data_type).unwrap() + }; + // The opacity (0-255) the map draws a pixel with: its alpha over the type's opaque value. + let opacity = + |r: &Raster, i: usize| ((r.bands[3].data[i] / crate::raster::alpha_max(&r.data_type)).clamp(0.0, 1.0) * 255.0).round(); + let nan = f32::NAN; + let cases = [ + ("UInt8, NaN colour", rgba("UInt8", [1.0, nan, 2.0], [255.0, 128.0, 255.0])), + ("UInt16", rgba("UInt16", [1000.0, 2000.0, 3000.0], [65535.0, 32768.0, 65535.0])), + ("Int16", rgba("Int16", [100.0, -200.0, 300.0], [32767.0, 16384.0, 32767.0])), + ("Float32", rgba("Float32", [0.1, 0.2, 0.3], [1.0, 0.5, 1.0])), + ("UInt8, five bands, NaN colour", { + let mut r = rgba("UInt8", [1.0, nan, 2.0], [255.0, 128.0, 255.0]); + r.bands.push(r.bands[1].clone()); + r + }), + ]; + for (case, r) in &cases { + let mut files = vec![("write", write(r, 0).unwrap()), ("write_all", write_all(r).unwrap())]; + // The COG writer makes a cell with a NaN colour fully see-through, by design. + if !case.contains("NaN") { + files.push(("cog", cogwrite::write(r, 0).unwrap())); + } + for (writer, bytes) in files { + let back = read(std::io::Cursor::new(bytes), "back").unwrap(); + let at = format!("{case}, {writer}"); + // `write` keeps the colour bands and alpha; `write_all` every band. + let kept = if writer == "write" { 4 } else { r.band_count() }; + assert_eq!((back.band_count(), &back.color), (kept, &ColorHint::Rgb { alpha: true }), "{at}"); + for i in 0..3 { + assert_eq!(opacity(&back, i), opacity(r, i), "{at}, pixel {i}: alpha {:?}", back.bands[3].data); + } + } + } + // Grey with alpha, past what `write` keeps (`write_all`): the same. + let grey = Raster::new( + "grey", + 3, + 1, + vec![vec![1.0, nan, 2.0], vec![255.0, 128.0, 255.0]], + gt, + Crs::LonLat, + None, + ColorHint::GrayAlpha, + "UInt8", + ) + .unwrap(); + let back = read(std::io::Cursor::new(write_all(&grey).unwrap()), "back").unwrap(); + let opaque = crate::raster::alpha_max(&back.data_type); + assert_eq!((back.band_count(), &back.color), (2, &ColorHint::GrayAlpha)); + assert_eq!(back.bands[1].data.iter().map(|a| (a / opaque * 255.0).round()).collect::>(), [255.0, 128.0, 255.0]); + } + #[test] fn rgbi_byte_export_does_not_turn_nir_into_alpha() { let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index d34d67e62b..ad555a373a 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -2188,7 +2188,13 @@ pub(crate) mod tests { let cog = geotiff::read(std::io::Cursor::new(cogwrite::write(&r, 0).unwrap()), "cog").unwrap(); assert_eq!((back.data_type.as_str(), cog.data_type.as_str()), ("Float32", "Float32")); } - assert_eq!(back.bands.iter().map(stats).collect::>(), r.bands.iter().map(stats).collect::>(), "{data_type}"); + // The alpha band's top is its type's opaque value: a 16-bit one, written as floats, + // is opaque at 1 (its pixels are divided by 65535). + let mut same: Vec<_> = r.bands.iter().map(stats).collect(); + if let Some(a) = same.get_mut(3) { + a.2 = f64::from(alpha_max(&back.data_type)); + } + assert_eq!(back.bands.iter().map(stats).collect::>(), same, "{data_type}"); } // As the map draws it: an alpha under half a 256th of opaque is see-through (16 bits: 100 // of 65535), one above it isn't (200). diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 9758027255..306ad62d04 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1580,9 +1580,10 @@ hillshade, say) as bytes and another single band as 32-bit floats (so is an RGBA colour that isn't see-through); with `"cog": true` it writes a cloud-optimised one: 512-pixel tiles, overviews (each half the size of the last, down to one tile), and every directory ahead of the tiles, so a reader fetches the header once and then only the tiles it needs. A cloud-optimised -file makes that RGBA raster's NaN cell see-through instead. Both compress with Deflate after a -predictor: the floating-point one for decimal values, differences along the row for whole numbers, -none for classes. Overviews are averaged, except for a single band of classes (a palette raster's, +file makes that RGBA raster's NaN cell see-through instead. An integer raster's alpha written as +floats is scaled to 0–1 (1 is opaque), so each pixel keeps how see-through it was. Both compress +with Deflate after a predictor: the floating-point one for decimal values, differences along the +row for whole numbers, none for classes. Overviews are averaged, except for a single band of classes (a palette raster's, a band with class names, or a band written as 8- or 16-bit whole numbers with a few distinct values), whose overviews take a pixel so that no class is invented; colour and grey-with-alpha files are always averaged. A palette keeps its colour table, though not the table's transparency, which a TIFF colour table can't hold (GDAL drops it too). From de1c4f900681f7998f2300c0bb84877b159711fe Mon Sep 17 00:00:00 2001 From: choupeanut Date: Mon, 23 Nov 2026 10:14:30 +0800 Subject: [PATCH 5/8] data: scale only valid alpha when writing floats (#2665) --- crates/data/src/raster/cogwrite.rs | 24 +++++++-------- crates/data/src/raster/geotiff.rs | 47 +++++++++++++++++++++++++----- crates/data/src/raster/mod.rs | 8 ++--- docs/user-guide/data.md | 17 ++++++----- 4 files changed, 64 insertions(+), 32 deletions(-) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index f14564b5cb..c32425eba9 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -34,6 +34,9 @@ //! //! The untiled GeoTIFF ([`super::geotiff::write`]) is written here too, by [`write_strips`]: one //! image in strips of rows, with the same predictors, Deflate effort and threads, and no overviews. +//! +//! Alpha: a float file's alpha is opaque at 1, so the alpha of an integer raster written as floats +//! is divided by its opaque value (255 for bytes), as the untiled writer does. use std::io::{Seek, SeekFrom, Write}; use std::ops::Range; @@ -326,7 +329,6 @@ fn tile_samples(r: &Raster, plan: &Plan, lv: &Level, tx: u32, ty: u32) -> Vec Vec raw.push(if v.is_nan() { int_pad as u8 } else { v.round().clamp(0.0, 255.0) as u8 }), Sample::Short => { let n = if v.is_nan() { int_pad } else { v.round().clamp(0.0, 65_535.0) as u16 }; raw.extend_from_slice(&n.to_le_bytes()); } - Sample::Float => { - let v = if v.is_nan() { - float_pad - } else if plan.alpha == Some(i) { - v / opaque - } else { - *v - }; - raw.extend_from_slice(&v.to_le_bytes()); - } + Sample::Float => raw.extend_from_slice(&(if v.is_nan() { float_pad } else { *v }).to_le_bytes()), } } } diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index a4f60f9d95..00c8c52e12 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1923,12 +1923,18 @@ pub fn written_bands(r: &Raster, band: usize) -> Vec { (0..if fourth { 4 } else { 3 }).collect() } +/// An alpha cell `v` of `r` as a float file holds it: a float file's alpha is opaque at 1, so an +/// integer raster's is divided by its `opaque` value (see [`super::alpha_max`]). A cell with no +/// value (NaN, or the no-data value the file's tag names) stays as it is, so it still has none. +pub(super) fn float_alpha(r: &Raster, opaque: f32, v: f32) -> f32 { + if r.is_valid(v) { v / opaque } else { v } +} + /// Writes a raster as a Deflate-compressed GeoTIFF: a colour raster's colour bands (RGB(A) bytes /// when they are 8-bit, else 32-bit floats, alpha kept), so it reads back in colour; otherwise /// `band` (0-based), as bytes when it is an 8-bit band of whole bytes, else as 32-bit floats. /// An integer raster's alpha, when written as floats, is divided by its opaque value (1 is opaque -/// in a float file). -/// `band` is for rasters that aren't colour ones: a colour raster always writes its colour bands, +/// in a float file; see [`float_alpha`]). `band` is for rasters that aren't colour ones: a colour raster always writes its colour bands, /// as its 8-bit form did before. The strips go through the predictors and Deflate effort of the /// COG writer ([`super::cogwrite::write_strips`]). A cancelled run stops it (with /// [`DataError::Cancelled`]) within a strip. @@ -1940,7 +1946,8 @@ pub fn write(r: &Raster, band: usize) -> Result> { /// when that keeps them all. Otherwise: 8-bit samples when the raster is `UInt8` and every valid /// value is a whole number in 0–255 (an empty cell only where no-data can mark it), else 32-bit /// float samples (RGB first for a colour raster, and alpha after them when it has one). [`read`] -/// reads them back as the same bands. +/// reads them back as the same bands. An integer raster's alpha, when written as floats, is divided +/// by its opaque value, as [`write`] does. pub fn write_all(r: &Raster) -> Result> { encode(r, 0, true) } @@ -2067,9 +2074,8 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { let byte = |_: usize, v: f32| if r.is_valid(v) { v.clamp(0.0, 255.0) as u8 } else { nodata }; wide!(byte, Sample::Byte, u8::to_le_bytes) } else { - // A float file's alpha is opaque at 1: an integer raster's is divided by its opaque value. let (opaque, alpha_band) = (super::alpha_max(&r.data_type), alpha.then_some(if rgb { 3 } else { 1 })); - wide!(|bi: usize, v: f32| if Some(bi) == alpha_band { v / opaque } else { v }, Sample::Float, f32::to_le_bytes) + wide!(|bi: usize, v: f32| if Some(bi) == alpha_band { float_alpha(r, opaque, v) } else { v }, Sample::Float, f32::to_le_bytes) } } else if rgb && (!written_bands(r, band).contains(&3) || fits_bytes(r, 3)) @@ -2093,8 +2099,7 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { } } else if rgb && let (Some(red), Some(green), Some(blue)) = (r.bands.first(), r.bands.get(1), r.bands.get(2)) { // Colour bands that aren't bytes (three embedding dimensions): kept as 32-bit floats, with - // their alpha band when they have one. A float file's alpha is opaque at 1, so an integer - // raster's alpha (255 for bytes) is divided by its opaque value, to stay as see-through. + // their alpha band when they have one, scaled by [`float_alpha`]. let n = (w as usize) * (h as usize); let at = |b: &crate::raster::Band, i: usize| b.data.get(i).copied().unwrap_or(f32::NAN); // Only a declared alpha: the fourth band of an RGBI image is data. @@ -2103,7 +2108,7 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { Some(alpha) => { let mut data = Vec::with_capacity(n * 4); for i in 0..n { - data.extend([at(red, i), at(green, i), at(blue, i), at(alpha, i) / opaque]); + data.extend([at(red, i), at(green, i), at(blue, i), float_alpha(r, opaque, at(alpha, i))]); } put(image(&[0, 1, 2, 3], Sample::Float, fourth())?, &data, f32::to_le_bytes, &mut out)?; } @@ -2853,6 +2858,32 @@ mod tests { assert_eq!(back.bands[1].data.iter().map(|a| (a / opaque * 255.0).round()).collect::>(), [255.0, 128.0, 255.0]); } + /// An alpha cell equal to the no-data value is no value, and stays one when written as floats: + /// it isn't scaled to 1 (opaque); the cells beside it are. (The COG writer has no no-data tag + /// beside an alpha band: its alpha says which pixels have no value.) + #[test] + fn alpha_equal_to_no_data_stays_no_data_when_written_as_floats() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; + let rgba = |extra: usize| { + let mut bands = vec![vec![100.0; 3], vec![200.0; 3], vec![300.0; 3], vec![32767.0, 16384.0, 32767.0]]; + bands.extend(vec![vec![5.0; 3]; extra]); + Raster::new("rgba", 3, 1, bands, gt, Crs::LonLat, Some(32767.0), ColorHint::Rgb { alpha: true }, "Int16").unwrap() + }; + for (case, r) in [("four bands", rgba(0)), ("five bands", rgba(1))] { + let mut files = vec![("write_all", write_all(&r).unwrap())]; + if r.band_count() == 4 { + files.push(("write", write(&r, 0).unwrap())); + } + for (writer, bytes) in files { + let back = read(std::io::Cursor::new(bytes), "back").unwrap(); + let at = format!("{case}, {writer}"); + assert_eq!(back.value(3, 0, 0), None, "{at}: {:?}", back.bands[3].data); + assert_eq!(back.value(3, 2, 0), None, "{at}"); + assert!(back.value(3, 1, 0).is_some_and(|a| (a - 0.5).abs() < 1e-3), "{at}: {:?}", back.bands[3].data); + } + } + } + #[test] fn rgbi_byte_export_does_not_turn_nir_into_alpha() { let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index ad555a373a..73758f5922 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -2188,11 +2188,11 @@ pub(crate) mod tests { let cog = geotiff::read(std::io::Cursor::new(cogwrite::write(&r, 0).unwrap()), "cog").unwrap(); assert_eq!((back.data_type.as_str(), cog.data_type.as_str()), ("Float32", "Float32")); } - // The alpha band's top is its type's opaque value: a 16-bit one, written as floats, - // is opaque at 1 (its pixels are divided by 65535). + // The alpha band's top is its type's opaque value: a 16-bit one, written as floats, is + // opaque at 1 (its pixels are divided by 65535). let mut same: Vec<_> = r.bands.iter().map(stats).collect(); - if let Some(a) = same.get_mut(3) { - a.2 = f64::from(alpha_max(&back.data_type)); + if let Some(a) = same.get_mut(3).filter(|_| data_type == "UInt16") { + a.2 = 1.0; } assert_eq!(back.bands.iter().map(stats).collect::>(), same, "{data_type}"); } diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 306ad62d04..b375439726 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1581,14 +1581,15 @@ colour that isn't see-through); with `"cog": true` it writes a cloud-optimised o tiles, overviews (each half the size of the last, down to one tile), and every directory ahead of the tiles, so a reader fetches the header once and then only the tiles it needs. A cloud-optimised file makes that RGBA raster's NaN cell see-through instead. An integer raster's alpha written as -floats is scaled to 0–1 (1 is opaque), so each pixel keeps how see-through it was. Both compress -with Deflate after a predictor: the floating-point one for decimal values, differences along the -row for whole numbers, none for classes. Overviews are averaged, except for a single band of classes (a palette raster's, -a band with class names, or a band written as 8- or 16-bit whole numbers with a few distinct -values), whose overviews take a pixel so that no class is invented; colour and grey-with-alpha files are always averaged. A palette keeps its colour table, -though not the table's transparency, which a TIFF colour table can't hold (GDAL drops it too). -Either file is classic TIFF when it would fit in 4 GiB even uncompressed and BigTIFF when it might -not. +floats is scaled to 0–1 (1 is opaque), so each pixel keeps how see-through it was; a cell with no +value stays without one. Both compress with Deflate after a predictor: the floating-point one for +decimal values, differences along the row for whole numbers, none for classes. Overviews are +averaged, except for a single band of classes (a palette raster's, a band with class names, or a +band written as 8- or 16-bit whole numbers with a few distinct values), whose overviews take a +pixel so that no class is invented; colour and grey-with-alpha files are always averaged. A palette +keeps its colour table, though not the table's transparency, which a TIFF colour table can't +hold (GDAL drops it too). Either file is classic TIFF when it would fit in 4 GiB even uncompressed +and BigTIFF when it might not. Exported to a file, a cloud-optimised one is written tile by tile, never held whole in memory (the browser builds it in memory to download it). GeoTIFFs may be regular or cloud-optimised: grey, RGB(A), palette (coloured by the file's colour From 256a1ca43c6ee3708ae103fa6bccacc02bd065fa Mon Sep 17 00:00:00 2001 From: choupeanut Date: Mon, 23 Nov 2026 10:15:53 +0800 Subject: [PATCH 6/8] docs(data): a cloud-optimised file keeps only NaN as no value (#2665) --- docs/user-guide/data.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index b375439726..34c3f4e3e6 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1581,8 +1581,8 @@ colour that isn't see-through); with `"cog": true` it writes a cloud-optimised o tiles, overviews (each half the size of the last, down to one tile), and every directory ahead of the tiles, so a reader fetches the header once and then only the tiles it needs. A cloud-optimised file makes that RGBA raster's NaN cell see-through instead. An integer raster's alpha written as -floats is scaled to 0–1 (1 is opaque), so each pixel keeps how see-through it was; a cell with no -value stays without one. Both compress with Deflate after a predictor: the floating-point one for +floats is scaled to 0–1 (1 is opaque), so each pixel keeps how see-through it was; in a GeoTIFF, a cell with +no value stays without one (a cloud-optimised file keeps only NaN as no value). Both compress with Deflate after a predictor: the floating-point one for decimal values, differences along the row for whole numbers, none for classes. Overviews are averaged, except for a single band of classes (a palette raster's, a band with class names, or a band written as 8- or 16-bit whole numbers with a few distinct values), whose overviews take a From 48004452584fdc964046b28f1489f0834f8a68fd Mon Sep 17 00:00:00 2001 From: choupeanut Date: Mon, 23 Nov 2026 20:54:27 +0800 Subject: [PATCH 7/8] data: keep an opaque alpha apart from the no-data value when writing floats (#2665) --- crates/data/src/raster/geotiff.rs | 78 +++++++++++++++++++++++++++---- docs/user-guide/data.md | 21 +++++---- 2 files changed, 80 insertions(+), 19 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 00c8c52e12..cbe1b64397 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1923,18 +1923,32 @@ pub fn written_bands(r: &Raster, band: usize) -> Vec { (0..if fourth { 4 } else { 3 }).collect() } -/// An alpha cell `v` of `r` as a float file holds it: a float file's alpha is opaque at 1, so an -/// integer raster's is divided by its `opaque` value (see [`super::alpha_max`]). A cell with no -/// value (NaN, or the no-data value the file's tag names) stays as it is, so it still has none. -pub(super) fn float_alpha(r: &Raster, opaque: f32, v: f32) -> f32 { - if r.is_valid(v) { v / opaque } else { v } +/// A cell `v` of `r` as a float file holds it beside an alpha band. A float file's alpha is opaque +/// at 1, so an integer raster's alpha (`is_alpha`) is divided by its `opaque` value (see +/// [`super::alpha_max`]). A cell with no value stays without one: as it is, or as NaN when +/// `nan_cells` (see [`alpha_hits_no_data`]). +fn float_cell(r: &Raster, opaque: f32, nan_cells: bool, is_alpha: bool, v: f32) -> f32 { + if !r.is_valid(v) { + if nan_cells { f32::NAN } else { v } + } else if is_alpha { + v / opaque + } else { + v + } +} + +/// Whether a valid cell of `alpha`, divided by `opaque`, would become the no-data value the file's +/// tag names (an opaque alpha is 1; a no-data value of 1, or of 0.5 and a half-see-through alpha +/// of the right size). Then no-data is written as NaN, with the tag `nan`, in every band. +fn alpha_hits_no_data(r: &Raster, opaque: f32, alpha: &[f32]) -> bool { + r.nodata.is_some() && alpha.iter().any(|&v| r.is_valid(v) && !r.is_valid(v / opaque)) } /// Writes a raster as a Deflate-compressed GeoTIFF: a colour raster's colour bands (RGB(A) bytes /// when they are 8-bit, else 32-bit floats, alpha kept), so it reads back in colour; otherwise /// `band` (0-based), as bytes when it is an 8-bit band of whole bytes, else as 32-bit floats. /// An integer raster's alpha, when written as floats, is divided by its opaque value (1 is opaque -/// in a float file; see [`float_alpha`]). `band` is for rasters that aren't colour ones: a colour raster always writes its colour bands, +/// in a float file; see [`float_cell`]). `band` is for rasters that aren't colour ones: a colour raster always writes its colour bands, /// as its 8-bit form did before. The strips go through the predictors and Deflate effort of the /// COG writer ([`super::cogwrite::write_strips`]). A cancelled run stops it (with /// [`DataError::Cancelled`]) within a strip. @@ -1997,6 +2011,8 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { // metadata tag, read back on open. Grey or RGB samples come first, then those `extra` says // what they are (unassociated alpha, 2, or data, 0). A single band of classes takes no // predictor. + // Set when no-data is written as NaN (see [`alpha_hits_no_data`]): the tag then says so. + let nan_tag = std::cell::Cell::new(false); let image = |written: &[usize], sample: Sample, extra: Vec| -> Result { let colour = if rgb { 3 } else { 1 }; Ok(Strips { @@ -2007,7 +2023,7 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { photometric: if rgb { 2 } else { 1 }, extra, classes: matches!(written, [b] if r.bands.get(*b).is_some_and(few_classes)), - tags: geo_entries(r, &geo, written, r.nodata.map(|d| d.to_string())), + tags: geo_entries(r, &geo, written, if nan_tag.get() { Some("nan".to_string()) } else { r.nodata.map(|d| d.to_string()) }), }) }; // The fourth sample of a colour file says what it is: alpha, or data (as RGB and near-infrared). @@ -2075,7 +2091,9 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { wide!(byte, Sample::Byte, u8::to_le_bytes) } else { let (opaque, alpha_band) = (super::alpha_max(&r.data_type), alpha.then_some(if rgb { 3 } else { 1 })); - wide!(|bi: usize, v: f32| if Some(bi) == alpha_band { float_alpha(r, opaque, v) } else { v }, Sample::Float, f32::to_le_bytes) + let nan_cells = alpha_band.and_then(|a| r.bands.get(a)).is_some_and(|b| alpha_hits_no_data(r, opaque, &b.data)); + nan_tag.set(nan_cells); + wide!(|bi: usize, v: f32| float_cell(r, opaque, nan_cells, Some(bi) == alpha_band, v), Sample::Float, f32::to_le_bytes) } } else if rgb && (!written_bands(r, band).contains(&3) || fits_bytes(r, 3)) @@ -2099,16 +2117,19 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { } } else if rgb && let (Some(red), Some(green), Some(blue)) = (r.bands.first(), r.bands.get(1), r.bands.get(2)) { // Colour bands that aren't bytes (three embedding dimensions): kept as 32-bit floats, with - // their alpha band when they have one, scaled by [`float_alpha`]. + // their alpha band when they have one, scaled by [`float_cell`]. let n = (w as usize) * (h as usize); let at = |b: &crate::raster::Band, i: usize| b.data.get(i).copied().unwrap_or(f32::NAN); // Only a declared alpha: the fourth band of an RGBI image is data. let opaque = if matches!(r.color, ColorHint::Rgb { alpha: true }) { super::alpha_max(&r.data_type) } else { 1.0 }; match r.bands.get(3).filter(|_| written_bands(r, band).contains(&3)) { Some(alpha) => { + let nan_cells = alpha_hits_no_data(r, opaque, &alpha.data); + nan_tag.set(nan_cells); + let cell = |is_alpha: bool, v: f32| float_cell(r, opaque, nan_cells, is_alpha, v); let mut data = Vec::with_capacity(n * 4); for i in 0..n { - data.extend([at(red, i), at(green, i), at(blue, i), float_alpha(r, opaque, at(alpha, i))]); + data.extend([cell(false, at(red, i)), cell(false, at(green, i)), cell(false, at(blue, i)), cell(true, at(alpha, i))]); } put(image(&[0, 1, 2, 3], Sample::Float, fourth())?, &data, f32::to_le_bytes, &mut out)?; } @@ -2884,6 +2905,43 @@ mod tests { } } + /// A float file's alpha is scaled to 0–1, so an opaque alpha (1) must not become the no-data + /// value the file's tag names (here 1): a valid cell stays valid and an invalid one stays + /// invalid, in every band, whatever the tag says. The COG writer has no tag beside an alpha + /// band, so its opaque alpha can't hit one. + #[test] + fn scaled_alpha_does_not_become_the_no_data_value() { + use super::super::cogwrite; + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; + let rgba = |extra: usize| { + // Pixel 0: valid, opaque. 1: valid, half see-through. 2: no red (1 is no-data), opaque. + // 3: opaque colours, an alpha that is the no-data value. + let mut bands = vec![vec![100.0, 200.0, 1.0, 100.0], vec![100.0; 4], vec![300.0; 4], vec![32767.0, 16384.0, 32767.0, 1.0]]; + bands.extend(vec![vec![5.0; 4]; extra]); + Raster::new("rgba", 4, 1, bands, gt, Crs::LonLat, Some(1.0), ColorHint::Rgb { alpha: true }, "Int16").unwrap() + }; + for (case, r) in [("four bands", rgba(0)), ("five bands", rgba(1))] { + let mut files = vec![("write_all", write_all(&r).unwrap())]; + if r.band_count() == 4 { + files.push(("write", write(&r, 0).unwrap())); + } + for (writer, bytes) in files { + let back = read(std::io::Cursor::new(bytes), "back").unwrap(); + let at = format!("{case}, {writer}"); + let alpha = |i| back.value(3, i, 0); + assert!(alpha(0).is_some_and(|a| (a - 1.0).abs() < 1e-6), "{at}: {:?}", back.bands[3].data); + assert!(alpha(1).is_some_and(|a| (a - 0.5).abs() < 1e-3), "{at}"); + assert!(alpha(2).is_some_and(|a| (a - 1.0).abs() < 1e-6), "{at}"); + assert_eq!(alpha(3), None, "{at}"); + assert_eq!((back.value(0, 0, 0), back.value(0, 2, 0)), (Some(100.0), None), "{at}"); + assert_eq!(back.value(2, 0, 0), Some(300.0), "{at}"); + } + } + let back = read(std::io::Cursor::new(cogwrite::write(&rgba(0), 0).unwrap()), "cog").unwrap(); + assert_eq!(back.nodata, None); + assert!(back.value(3, 0, 0).is_some_and(|a| (a - 1.0).abs() < 1e-6) && back.value(3, 2, 0).is_some()); + } + #[test] fn rgbi_byte_export_does_not_turn_nir_into_alpha() { let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 34c3f4e3e6..8bc749cdab 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1581,15 +1581,18 @@ colour that isn't see-through); with `"cog": true` it writes a cloud-optimised o tiles, overviews (each half the size of the last, down to one tile), and every directory ahead of the tiles, so a reader fetches the header once and then only the tiles it needs. A cloud-optimised file makes that RGBA raster's NaN cell see-through instead. An integer raster's alpha written as -floats is scaled to 0–1 (1 is opaque), so each pixel keeps how see-through it was; in a GeoTIFF, a cell with -no value stays without one (a cloud-optimised file keeps only NaN as no value). Both compress with Deflate after a predictor: the floating-point one for -decimal values, differences along the row for whole numbers, none for classes. Overviews are -averaged, except for a single band of classes (a palette raster's, a band with class names, or a -band written as 8- or 16-bit whole numbers with a few distinct values), whose overviews take a -pixel so that no class is invented; colour and grey-with-alpha files are always averaged. A palette -keeps its colour table, though not the table's transparency, which a TIFF colour table can't -hold (GDAL drops it too). Either file is classic TIFF when it would fit in 4 GiB even uncompressed -and BigTIFF when it might not. +floats is scaled to 0–1 (1 is opaque), so each pixel keeps how see-through it was. In a GeoTIFF a +cell with no value stays without one; if a scaled alpha would equal the no-data value (a no-data +value of 1, say), the no-data cells are written as NaN and the tag is `nan`. A cloud-optimised file +writes the raster's own no-data value as its tag (NaN for a float raster without one that has +cells with no value), and with an alpha band no tag, making those cells see-through. Both compress +with Deflate after a predictor: the floating-point one for decimal values, differences along the +row for whole numbers, none for classes. Overviews are averaged, except for a single band of +classes (a palette raster's, a band with class names, or a band written as 8- or 16-bit whole +numbers with a few distinct values), whose overviews take a pixel so that no class is invented; +colour and grey-with-alpha files are always averaged. A palette keeps its colour table, though not +the table's transparency, which a TIFF colour table can't hold (GDAL drops it too). Either file is +classic TIFF when it would fit in 4 GiB even uncompressed and BigTIFF when it might not. Exported to a file, a cloud-optimised one is written tile by tile, never held whole in memory (the browser builds it in memory to download it). GeoTIFFs may be regular or cloud-optimised: grey, RGB(A), palette (coloured by the file's colour From d7701a2ba1849764f3ca75f29704e93b72e3006b Mon Sep 17 00:00:00 2001 From: choupeanut Date: Mon, 23 Nov 2026 21:08:17 +0800 Subject: [PATCH 8/8] data: skip the no-data scan where alpha can't collide (#2665) --- crates/data/src/raster/geotiff.rs | 7 +++++-- docs/user-guide/data.md | 19 ++++++++++--------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index cbe1b64397..e11505d094 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1941,7 +1941,9 @@ fn float_cell(r: &Raster, opaque: f32, nan_cells: bool, is_alpha: bool, v: f32) /// tag names (an opaque alpha is 1; a no-data value of 1, or of 0.5 and a half-see-through alpha /// of the right size). Then no-data is written as NaN, with the tag `nan`, in every band. fn alpha_hits_no_data(r: &Raster, opaque: f32, alpha: &[f32]) -> bool { - r.nodata.is_some() && alpha.iter().any(|&v| r.is_valid(v) && !r.is_valid(v / opaque)) + // An alpha already on the float scale (`opaque` 1: a float raster, or no declared alpha) isn't + // changed, so can't collide: no scan. + r.nodata.is_some() && opaque != 1.0 && alpha.iter().any(|&v| r.is_valid(v) && !r.is_valid(v / opaque)) } /// Writes a raster as a Deflate-compressed GeoTIFF: a colour raster's colour bands (RGB(A) bytes @@ -2013,6 +2015,7 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { // predictor. // Set when no-data is written as NaN (see [`alpha_hits_no_data`]): the tag then says so. let nan_tag = std::cell::Cell::new(false); + let nodata_tag = || if nan_tag.get() { Some("nan".to_string()) } else { r.nodata.map(|d| d.to_string()) }; let image = |written: &[usize], sample: Sample, extra: Vec| -> Result { let colour = if rgb { 3 } else { 1 }; Ok(Strips { @@ -2023,7 +2026,7 @@ fn encode(r: &Raster, band: usize, every: bool) -> Result> { photometric: if rgb { 2 } else { 1 }, extra, classes: matches!(written, [b] if r.bands.get(*b).is_some_and(few_classes)), - tags: geo_entries(r, &geo, written, if nan_tag.get() { Some("nan".to_string()) } else { r.nodata.map(|d| d.to_string()) }), + tags: geo_entries(r, &geo, written, nodata_tag()), }) }; // The fourth sample of a colour file says what it is: alpha, or data (as RGB and near-infrared). diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 8bc749cdab..aa0a6403d5 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1584,15 +1584,16 @@ file makes that RGBA raster's NaN cell see-through instead. An integer raster's floats is scaled to 0–1 (1 is opaque), so each pixel keeps how see-through it was. In a GeoTIFF a cell with no value stays without one; if a scaled alpha would equal the no-data value (a no-data value of 1, say), the no-data cells are written as NaN and the tag is `nan`. A cloud-optimised file -writes the raster's own no-data value as its tag (NaN for a float raster without one that has -cells with no value), and with an alpha band no tag, making those cells see-through. Both compress -with Deflate after a predictor: the floating-point one for decimal values, differences along the -row for whole numbers, none for classes. Overviews are averaged, except for a single band of -classes (a palette raster's, a band with class names, or a band written as 8- or 16-bit whole -numbers with a few distinct values), whose overviews take a pixel so that no class is invented; -colour and grey-with-alpha files are always averaged. A palette keeps its colour table, though not -the table's transparency, which a TIFF colour table can't hold (GDAL drops it too). Either file is -classic TIFF when it would fit in 4 GiB even uncompressed and BigTIFF when it might not. +writes the raster's own no-data value as its tag when the samples can hold it (a palette raster uses +an unused index; NaN for a float raster without one that has cells with no value), and with an alpha +band no tag, making those cells see-through. Both compress with Deflate after a predictor: the +floating-point one for decimal values, differences along the row for whole numbers, none for +classes. Overviews are averaged, except for a single band of classes (a palette raster's, a band +with class names, or a band written as 8- or 16-bit whole numbers with a few distinct values), whose +overviews take a pixel so that no class is invented; colour and grey-with-alpha files are always +averaged. A palette keeps its colour table, though not the table's transparency, which a TIFF colour +table can't hold (GDAL drops it too). Either file is classic TIFF when it would fit in 4 GiB even +uncompressed and BigTIFF when it might not. Exported to a file, a cloud-optimised one is written tile by tile, never held whole in memory (the browser builds it in memory to download it). GeoTIFFs may be regular or cloud-optimised: grey, RGB(A), palette (coloured by the file's colour