From eeaa77c08162964474fa31e27c990494857e2901 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 15 Nov 2026 13:54:31 -0500 Subject: [PATCH] Share bounded DDS float surface decoding Adapt MaterialCraft DDS backend integration from cc052aeaa8c61fbe6975674b6d5e28bb3c597b9d; retain float precision and first-surface behavior, keep transfer policy app-local. --- Cargo.lock | 36 ++++++++++++++++ crates/texture/Cargo.toml | 9 ++++ crates/texture/src/dds.rs | 87 +++++++++++++++++++++++++++++++++++++++ crates/texture/src/lib.rs | 3 ++ 4 files changed, 135 insertions(+) create mode 100644 crates/texture/src/dds.rs diff --git a/Cargo.lock b/Cargo.lock index b3325f790..087416480 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -340,6 +340,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "async-broadcast" version = "0.7.2" @@ -2758,6 +2764,8 @@ dependencies = [ name = "craft-texture" version = "0.1.0" dependencies = [ + "bytemuck", + "dds", "rayon", "thiserror 2.0.21", ] @@ -3295,6 +3303,19 @@ dependencies = [ "generic-array", ] +[[package]] +name = "dds" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068" +dependencies = [ + "astc-decode", + "bitflags 2.13.2", + "glam", + "resize", + "zerocopy", +] + [[package]] name = "der" version = "0.7.10" @@ -4543,6 +4564,12 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glam" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" + [[package]] name = "glifo" version = "0.1.1" @@ -8136,6 +8163,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "resize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71725ecd5e0197b54fe859055b108688472ab6a358f8fbe5cee4a556b1b5bfea" +dependencies = [ + "rgb", +] + [[package]] name = "resvg" version = "0.45.1" diff --git a/crates/texture/Cargo.toml b/crates/texture/Cargo.toml index 78868dd87..173abb0b0 100644 --- a/crates/texture/Cargo.toml +++ b/crates/texture/Cargo.toml @@ -9,6 +9,7 @@ repository.workspace = true [features] default = [] +dds = ["dep:dds", "dep:bytemuck"] parallel = ["dep:rayon"] [lints] @@ -17,3 +18,11 @@ workspace = true [dependencies] rayon = { workspace = true, optional = true } thiserror = { workspace = true } + +# Same decoder used by MaterialCraft; no parallel backend enabled. +dds = { version = "0.2.0", default-features = false, optional = true } +bytemuck = { workspace = true, optional = true } + +[dev-dependencies] +dds = { version = "0.2.0", default-features = false } +bytemuck = { workspace = true } diff --git a/crates/texture/src/dds.rs b/crates/texture/src/dds.rs new file mode 100644 index 000000000..cbada515e --- /dev/null +++ b/crates/texture/src/dds.rs @@ -0,0 +1,87 @@ +//! First-surface DDS decoding to unmodified RGBA floats. +//! +//! Adapted from MaterialCraft `dds_image.rs` (originally chasse20, cc052aeaa8c61fbe6975674b6d5e28bb3c597b9d). +//! Uses the same `dds` backend and first-surface semantics, including the first cube face or +//! volume slice. This is not a whole-resource decoder. Transfer functions and image policy +//! belong to callers. [`Limits`] bounds the output float plane, not backend scratch buffers. + +use crate::{ImageError, Kind, Limits}; + +#[derive(Debug, thiserror::Error)] +pub enum DecodeError { + #[error(transparent)] + Image(#[from] ImageError), + #[error("DDS decode failed: {0}")] + Decode(String), +} + +/// Unmodified backend output. Alpha and out-of-range float values are not clamped. +#[derive(Debug)] +pub struct Surface { + pub width: u32, + pub height: u32, + pub rgba: Vec, + /// Exactly the backend's `Precision::F32` classification, as used by MaterialCraft. + pub source_precision_is_f32: bool, +} + +/// Decode the first surface after validating dimensions, pixels and output-byte limits. +/// The output reservation is fallible; no second full-sized float plane is created. +pub fn decode_first(bytes: &[u8], limits: &Limits) -> Result { + let error = |e: ::dds::DecodingError| DecodeError::Decode(e.to_string()); + let mut decoder = ::dds::Decoder::new(std::io::Cursor::new(bytes)).map_err(error)?; + let size = decoder.main_size(); + let len = limits.check(size.width, size.height, Kind::Color)?; + let mut rgba = Vec::new(); + rgba.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(size.width, size.height))?; + rgba.resize(len, 0.0_f32); + let view = ::dds::ImageViewMut::new(bytemuck::cast_slice_mut(&mut rgba), size, ::dds::ColorFormat::RGBA_F32) + .ok_or_else(|| DecodeError::Decode("invalid DDS output dimensions".into()))?; + decoder.read_surface(view).map_err(error)?; + Ok(Surface { width: size.width, height: size.height, rgba, source_precision_is_f32: decoder.format().precision() == ::dds::Precision::F32 }) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn bytes(format: ::dds::Format, payload: &[u8]) -> Vec { + let mut bytes = Vec::new(); + ::dds::Header::new_image(1, 1, format).write(&mut bytes).unwrap(); + bytes.extend_from_slice(payload); + bytes + } + + #[test] + fn rgba8_keeps_transfer_and_alpha_unmodified() { + let data = bytes(::dds::Format::R8G8B8A8_UNORM, &[128, 64, 255, 32]); + let image = decode_first(&data, &Limits::default()).unwrap(); + assert_eq!((image.width, image.height), (1, 1)); + assert!(!image.source_precision_is_f32); + for (actual, expected) in image.rgba.iter().zip([128.0 / 255.0, 64.0 / 255.0, 1.0, 32.0 / 255.0]) { + assert!((actual - expected).abs() < 1e-6); + } + } + + #[test] + fn float_hdr_and_negative_values_survive() { + let values = [-0.5_f32, 2.0, 0.25, 0.75]; + let payload: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + let image = decode_first(&bytes(::dds::Format::R32G32B32A32_FLOAT, &payload), &Limits::default()).unwrap(); + assert!(image.source_precision_is_f32); + assert_eq!(image.rgba, values); + } + + #[test] + fn checks_output_budget_and_truncation() { + let data = bytes(::dds::Format::R8G8B8A8_UNORM, &[1, 2, 3, 4]); + let mut limits = Limits::default(); + limits.max_bytes = 15; + assert!(matches!(decode_first(&data, &limits), Err(DecodeError::Image(ImageError::TooLarge(1, 1))))); + limits.max_bytes = 16; + assert!(decode_first(&data, &limits).is_ok()); + assert!(decode_first(&data[..data.len() - 1], &limits).is_err()); + assert!(decode_first(&[], &limits).is_err()); + } +} diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs index 2aaef3e8b..e33b68d88 100644 --- a/crates/texture/src/lib.rs +++ b/crates/texture/src/lib.rs @@ -29,6 +29,9 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(any(feature = "dds", test))] +pub mod dds; + use std::sync::Arc; #[cfg(feature = "parallel")]