mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-28 17:19:17 +01:00
Read bitmap channels using their file transfer by default
This commit is contained in:
1 parent
cd07f60cfb
commit
96db706116
15 files changed
+239
-36
No files matched your search
@@ -1,13 +1,14 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use craft_texture::Image;
|
||||
use materialcraft_nodes::BitmapColorSpace;
|
||||
|
||||
const DEFAULT_LIMIT_BYTES: usize = 128 << 20;
|
||||
const MAX_ENTRIES: usize = 128;
|
||||
|
||||
/// Decoded bitmaps are expendable: resources and active cooks own their source and output data.
|
||||
pub(crate) struct DecodedImages {
|
||||
images: HashMap<(u64, bool), (Image, u64)>,
|
||||
images: HashMap<(u64, BitmapColorSpace), (Image, u64)>,
|
||||
bytes: usize,
|
||||
limit: usize,
|
||||
tick: u64,
|
||||
@@ -24,7 +25,7 @@ impl DecodedImages {
|
||||
Self { images: HashMap::new(), bytes: 0, limit, tick: 0 }
|
||||
}
|
||||
|
||||
pub fn get(&mut self, key: &(u64, bool)) -> Option<Image> {
|
||||
pub fn get(&mut self, key: &(u64, BitmapColorSpace)) -> Option<Image> {
|
||||
self.tick = self.tick.saturating_add(1);
|
||||
self.images.get_mut(key).map(|(image, used)| {
|
||||
*used = self.tick;
|
||||
@@ -32,7 +33,7 @@ impl DecodedImages {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, key: (u64, bool), image: Image) {
|
||||
pub fn insert(&mut self, key: (u64, BitmapColorSpace), image: Image) {
|
||||
if let Some((old, _)) = self.images.remove(&key) {
|
||||
self.bytes = self.bytes.saturating_sub(bytes(&old));
|
||||
}
|
||||
@@ -82,16 +83,17 @@ mod tests {
|
||||
let mut cache = DecodedImages::new(128);
|
||||
let image = Image::filled(4, 4, Kind::Gray, [0.5; 4]);
|
||||
let weak = Arc::downgrade(image.shared_data());
|
||||
cache.insert((0, false), image);
|
||||
cache.insert((0, BitmapColorSpace::Srgb), image);
|
||||
for key in 1..1_000 {
|
||||
cache.insert((key, key % 2 == 0), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
|
||||
let space = if key % 2 == 0 { BitmapColorSpace::Linear } else { BitmapColorSpace::Srgb };
|
||||
cache.insert((key, space), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
|
||||
|
||||
assert!(cache.bytes <= 128);
|
||||
assert!(cache.images.len() <= 2);
|
||||
}
|
||||
|
||||
assert!(weak.upgrade().is_none());
|
||||
assert!(cache.get(&(999, false)).is_some());
|
||||
assert!(cache.get(&(999, BitmapColorSpace::Srgb)).is_some());
|
||||
|
||||
cache.retain_resources(&HashSet::new());
|
||||
|
||||
@@ -103,21 +105,21 @@ mod tests {
|
||||
fn large_images_bypass_the_cache_and_recent_reads_survive_eviction() {
|
||||
let mut cache = DecodedImages::new(128);
|
||||
for key in 0..2 {
|
||||
cache.insert((key, false), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
|
||||
cache.insert((key, BitmapColorSpace::Srgb), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
|
||||
}
|
||||
|
||||
assert!(cache.get(&(0, false)).is_some());
|
||||
assert!(cache.get(&(0, BitmapColorSpace::Srgb)).is_some());
|
||||
|
||||
cache.insert((2, false), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
|
||||
cache.insert((2, BitmapColorSpace::Srgb), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
|
||||
|
||||
assert!(cache.get(&(1, false)).is_none());
|
||||
assert!(cache.get(&(1, BitmapColorSpace::Srgb)).is_none());
|
||||
|
||||
let large = Image::filled(16, 16, Kind::Gray, [0.5; 4]);
|
||||
let weak = Arc::downgrade(large.shared_data());
|
||||
cache.insert((3, false), large);
|
||||
cache.insert((3, BitmapColorSpace::Srgb), large);
|
||||
|
||||
assert!(weak.upgrade().is_none());
|
||||
assert!(cache.get(&(0, false)).is_some());
|
||||
assert!(cache.get(&(0, BitmapColorSpace::Srgb)).is_some());
|
||||
|
||||
cache.clear();
|
||||
|
||||
|
||||
@@ -396,14 +396,14 @@ impl Session {
|
||||
let hashes = resources.iter().map(|(_, bytes)| bytes.content_hash()).collect();
|
||||
decoded.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes);
|
||||
move |requested: &str| {
|
||||
let (name, linear) = craft_texture::split_resource_key(requested);
|
||||
let (name, space) = materialcraft_nodes::BitmapColorSpace::split_resource_key(requested);
|
||||
let (_, bytes) = resources.iter().find(|(name_candidate, _)| name_candidate == name)?;
|
||||
let key = (bytes.content_hash(), linear);
|
||||
let key = (bytes.content_hash(), space);
|
||||
if let Some(image) = decoded.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
return Some(image);
|
||||
}
|
||||
|
||||
let image = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?;
|
||||
let image = materialcraft_formats::decode_with_color_space(bytes.as_slice(), space).ok()?;
|
||||
decoded.lock().unwrap_or_else(PoisonError::into_inner).insert(key, image.clone());
|
||||
Some(image)
|
||||
}
|
||||
|
||||
@@ -23,6 +23,38 @@ fn the_resource_decoder_reads_data_maps_as_stored() {
|
||||
assert!((data.get(0, 0, false)[2] - 1.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmap_nodes_read_default_colors_from_the_file_and_keep_explicit_data_reads() {
|
||||
use materialcraft_core::{Graph, OutputFormat, ResourceBytes, Value};
|
||||
|
||||
let field = Image::filled(16, 16, Kind::Color, [64.0, 128.0, 192.0, 97.0].map(|v| v / 255.0));
|
||||
let png = encode(&field, "png", Depth::U8, false).unwrap();
|
||||
for (gamma_chunk, expected) in [(false, [64, 128, 192, 97]), (true, [136, 186, 224, 97])] {
|
||||
let mut bytes = png.clone();
|
||||
if gamma_chunk {
|
||||
// Insert a unit gAMA chunk, including its CRC, immediately after IHDR.
|
||||
bytes.splice(33..33, *b"\0\0\0\x04gAMA\0\x01\x86\xa0\x31\xe8\x96\x5f");
|
||||
}
|
||||
let mut package = Package::new("Bitmap file colors");
|
||||
package.resources.push(Resource::new("field", "field.png", ResourceBytes::new(bytes)));
|
||||
let mut graph = Graph::new("File and data reads");
|
||||
graph.size = [4, 4];
|
||||
graph.format = OutputFormat::U8;
|
||||
let bitmap = graph.add_node("bitmap", [0.0; 2]);
|
||||
let data = graph.add_node("bitmap", [0.0, 80.0]);
|
||||
for id in [bitmap, data] {
|
||||
graph.node_mut(id).unwrap().params.insert("resource".into(), Value::Text("field".into()));
|
||||
}
|
||||
graph.node_mut(data).unwrap().params.insert("colour_space".into(), Value::Enum(1));
|
||||
package.graphs.push(graph);
|
||||
let mut session = Session::new(package);
|
||||
let cook = session.cook();
|
||||
let pixel = |id| cook.image(id, 0).unwrap().get(0, 0, false).map(|v| (v * 255.0).round() as u8);
|
||||
assert_eq!(pixel(bitmap), expected);
|
||||
assert_eq!(pixel(data), [64, 128, 192, 97]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod merge_tests {
|
||||
use crate::Session;
|
||||
|
||||
@@ -6,8 +6,7 @@ use materialcraft_nodes::CookContext;
|
||||
/// Odd-sized normalized PNG resources use the same stored and sampled levels as bound rasters.
|
||||
pub(super) fn resize_bitmap(context: &CookContext, package: &Package) -> Option<NodeOutput> {
|
||||
let grayscale = !context.b("color_mode");
|
||||
let linear = context.i("colour_space") == 1;
|
||||
if !grayscale && !linear {
|
||||
if !grayscale && context.bitmap_color_space() == materialcraft_nodes::BitmapColorSpace::Srgb {
|
||||
return None;
|
||||
}
|
||||
let name = context.text("resource");
|
||||
@@ -18,7 +17,7 @@ pub(super) fn resize_bitmap(context: &CookContext, package: &Package) -> Option<
|
||||
if info.grayscale != grayscale || (width.is_power_of_two() && height.is_power_of_two()) || (width, height) == (context.w, context.h) {
|
||||
return None;
|
||||
}
|
||||
let image = (context.resource)(&craft_texture::resource_key(name, linear))?;
|
||||
let image = context.bitmap_resource(name)?;
|
||||
let kind = if grayscale { Kind::Gray } else { Kind::Color };
|
||||
resize(&image, (context.w, context.h), kind, info.format, context.format)
|
||||
}
|
||||
|
||||
@@ -67,8 +67,8 @@ pub(crate) fn cook_instance(
|
||||
let root_resource = options.resource_root.unwrap_or(options.resource);
|
||||
let resource = |name: &str| match &node.instance {
|
||||
Some(instance) if !instance.package.is_empty() => {
|
||||
let (name, linear) = craft_texture::split_resource_key(name);
|
||||
root_resource(&craft_texture::resource_key(&format!("{}\0{name}", instance.package), linear))
|
||||
let (name, space) = materialcraft_nodes::BitmapColorSpace::split_resource_key(name);
|
||||
root_resource(&space.resource_key(&format!("{}\0{name}", instance.package)))
|
||||
}
|
||||
_ => (options.resource)(name),
|
||||
};
|
||||
|
||||
@@ -1189,7 +1189,10 @@ fn linear_input_images_and_bitmap_nodes_request_data_reads() {
|
||||
(c.image(i, 0).unwrap().data()[0], c.image(b, 0).unwrap().data()[0])
|
||||
};
|
||||
|
||||
assert_eq!(first(&p), (0.2, 0.2), "default is sRGB, as before");
|
||||
assert_eq!(first(&p), (0.2, 0.5), "the bitmap defaults to file channels");
|
||||
|
||||
p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(0));
|
||||
assert_eq!(first(&p), (0.2, 0.2), "an explicit sRGB read still decodes the color");
|
||||
|
||||
p.graphs[0].input_images_linear.insert("n".into());
|
||||
p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(1));
|
||||
|
||||
+75
-12
@@ -1,13 +1,19 @@
|
||||
use crate::{Depth, FormatError, Result, guard};
|
||||
use craft_texture::{Image, Kind, Limits, MAX_SIDE, linear_to_srgb, srgb_to_linear};
|
||||
use materialcraft_nodes::BitmapColorSpace;
|
||||
use std::io::Cursor;
|
||||
|
||||
const MAX_DECODE_BYTES: u64 = 1 << 30;
|
||||
|
||||
/// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale files stay grayscale)
|
||||
pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
decode_with_color_space(bytes, if linear { BitmapColorSpace::Linear } else { BitmapColorSpace::Srgb })
|
||||
}
|
||||
|
||||
/// Decode a bitmap using its file transfer or an explicit interpretation of its stored channels.
|
||||
pub fn decode_with_color_space(bytes: &[u8], space: BitmapColorSpace) -> Result<Image> {
|
||||
if bytes.starts_with(b"DDS ") {
|
||||
return guard(|| crate::dds_image::decode(bytes, linear), || FormatError::Image("DDS decoder failed".into()));
|
||||
return guard(|| crate::dds_image::decode(bytes, space == BitmapColorSpace::Linear), || FormatError::Image("DDS decoder failed".into()));
|
||||
}
|
||||
|
||||
const SVG_SNIFF_BYTES: usize = 4096;
|
||||
@@ -15,7 +21,7 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
return guard(|| crate::svg::decode(bytes), || FormatError::Image("SVG decoder failed".into()));
|
||||
}
|
||||
|
||||
match decode_raster(bytes, linear) {
|
||||
match decode_raster(bytes, space) {
|
||||
Err(error) if bytes.starts_with(&[0x76, 0x2f, 0x31, 0x01]) => {
|
||||
guard(|| decode_luminance_exr(bytes, error), || FormatError::Image("EXR decoder failed".into()))
|
||||
}
|
||||
@@ -36,17 +42,42 @@ fn decode_luminance_exr(bytes: &[u8], original_error: FormatError) -> Result<Ima
|
||||
Image::from_data(decoded.width(), decoded.height(), Kind::Gray, data, &Limits::default()).map_err(|error| FormatError::Image(error.to_string()))
|
||||
}
|
||||
|
||||
fn decode_raster(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
fn raster_limits() -> image::Limits {
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(MAX_SIDE);
|
||||
limits.max_image_height = Some(MAX_SIDE);
|
||||
limits.max_alloc = Some(MAX_DECODE_BYTES);
|
||||
limits
|
||||
}
|
||||
|
||||
fn png_channel_table(bytes: &[u8], maximum: u32) -> Option<Vec<f32>> {
|
||||
let metadata = craft_image_codecs::png_probe::color_chunks(bytes)?;
|
||||
if metadata.srgb {
|
||||
return None;
|
||||
}
|
||||
// Recover the five-place file gamma before rounding the correction exponent.
|
||||
let gamma = (f64::from(metadata.gamma?) * 100_000.0).round() / 100_000.0;
|
||||
let ratio = gamma * 2.2;
|
||||
let exponent = (100_000.0 / ratio).round() / 100_000.0;
|
||||
if (ratio * 100_000.0).round() >= 95_000.0 && exponent >= 0.95 {
|
||||
return None;
|
||||
}
|
||||
let levels = f64::from(maximum);
|
||||
Some((0..=maximum).map(|v| ((f64::from(v) / levels).powf(exponent) * levels).round() as f32 / maximum as f32).collect())
|
||||
}
|
||||
|
||||
fn mapped_channel(table: &[f32], value: f32) -> f32 {
|
||||
let last = table.len().saturating_sub(1) as f32;
|
||||
table.get((value * last).round() as usize).copied().unwrap_or(value)
|
||||
}
|
||||
|
||||
fn decode_raster(bytes: &[u8], space: BitmapColorSpace) -> Result<Image> {
|
||||
let open = || -> Result<image::ImageReader<Cursor<&[u8]>>> {
|
||||
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Image(e.to_string()))?;
|
||||
if reader.format().is_none() {
|
||||
reader.set_format(image::ImageFormat::Tga);
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(MAX_SIDE);
|
||||
limits.max_image_height = Some(MAX_SIDE);
|
||||
limits.max_alloc = Some(MAX_DECODE_BYTES);
|
||||
reader.limits(limits);
|
||||
reader.limits(raster_limits());
|
||||
Ok(reader)
|
||||
};
|
||||
let failed = || FormatError::Image("the decoder failed on this file".into());
|
||||
@@ -55,24 +86,56 @@ fn decode_raster(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
e => FormatError::Image(e.to_string()),
|
||||
};
|
||||
|
||||
let (w, h) = guard(|| open()?.into_dimensions().map_err(image_error), failed)?;
|
||||
let (input_format, (w, h)) = guard(
|
||||
|| {
|
||||
let reader = open()?;
|
||||
Ok((reader.format(), reader.into_dimensions().map_err(image_error)?))
|
||||
},
|
||||
failed,
|
||||
)?;
|
||||
if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE {
|
||||
return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels")));
|
||||
}
|
||||
|
||||
let png =
|
||||
if space == BitmapColorSpace::FromFile && input_format == Some(image::ImageFormat::Png) { materialcraft_core::png_raster_info(bytes) } else { None };
|
||||
let stored = match space {
|
||||
BitmapColorSpace::Linear => true,
|
||||
BitmapColorSpace::Srgb => false,
|
||||
BitmapColorSpace::FromFile => {
|
||||
png.is_some()
|
||||
|| matches!(input_format, Some(image::ImageFormat::Jpeg | image::ImageFormat::Bmp | image::ImageFormat::Tiff | image::ImageFormat::Tga))
|
||||
}
|
||||
};
|
||||
let decoded = guard(|| open()?.decode().map_err(image_error), failed)?;
|
||||
let table = png.and_then(|info| {
|
||||
let maximum = if info.format == materialcraft_core::OutputFormat::U8 { 255 } else { 65535 };
|
||||
png_channel_table(bytes, maximum)
|
||||
});
|
||||
let gray = matches!(decoded.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16);
|
||||
let float = matches!(decoded.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F);
|
||||
if gray {
|
||||
let luminance = decoded.into_luma16();
|
||||
let data: Vec<f32> = luminance.pixels().map(|p| p.0[0] as f32 / 65535.0).collect();
|
||||
let data: Vec<f32> = luminance
|
||||
.pixels()
|
||||
.map(|p| {
|
||||
let value = f32::from(p.0[0]) / 65535.0;
|
||||
table.as_ref().map_or(value, |levels| mapped_channel(levels, value))
|
||||
})
|
||||
.collect();
|
||||
return Image::from_data(w, h, Kind::Gray, data, &Limits::default())
|
||||
.map(|image| image.with_integer_sampling(true))
|
||||
.map_err(|e| FormatError::Image(e.to_string()));
|
||||
}
|
||||
|
||||
let mut data = decoded.into_rgba32f().into_raw();
|
||||
if !(float || linear) {
|
||||
if let Some(table) = table {
|
||||
for px in data.as_chunks_mut::<4>().0 {
|
||||
for channel in &mut px[..3] {
|
||||
*channel = mapped_channel(&table, *channel);
|
||||
}
|
||||
}
|
||||
} else if !(float || stored) {
|
||||
for px in data.as_chunks_mut::<4>().0 {
|
||||
for c in px.iter_mut().take(3) {
|
||||
*c = srgb_to_linear(*c);
|
||||
@@ -81,7 +144,7 @@ fn decode_raster(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
}
|
||||
|
||||
Image::from_data(w, h, Kind::Color, data, &Limits::default())
|
||||
.map(|image| image.with_integer_sampling(linear && !float))
|
||||
.map(|image| image.with_integer_sampling(stored && !float))
|
||||
.map_err(|e| FormatError::Image(e.to_string()))
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ pub use file::write_atomic;
|
||||
pub use file::{output_name, safe_file_name};
|
||||
pub use format_error::FormatError;
|
||||
pub(crate) use guard::guard;
|
||||
pub use image::{decode, encode};
|
||||
pub use image::{decode, decode_with_color_space, encode};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, FormatError>;
|
||||
pub(crate) const MAX_JSON: u64 = 64 << 20;
|
||||
|
||||
@@ -2,6 +2,23 @@ use craft_texture::{Image, Kind};
|
||||
use materialcraft_formats::{BITMAP_EXTENSIONS, BITMAP_FORMATS, Depth, decode, encode};
|
||||
use std::io::Cursor;
|
||||
|
||||
#[test]
|
||||
fn grayscale_png_file_gamma_uses_the_measured_word_boundaries() {
|
||||
let words = [1136, 3683, 4236];
|
||||
let field = Image::gray(3, 1, |x, _| words[x as usize] as f32 / 65535.0);
|
||||
let plain = encode(&field, "png", Depth::U16, false).unwrap();
|
||||
for (gamma, crc, expected) in
|
||||
[(43_181u32, 0x459c_89f9u32, [918, 3165, 3667]), (43_182, 0xdc95_d843, words), (47_847, 0xab61_51a4, words), (47_848, 0x3bde_4c35, [1391, 4253, 4858])]
|
||||
{
|
||||
let mut bytes = plain.clone();
|
||||
let chunk = [4u32.to_be_bytes(), *b"gAMA", gamma.to_be_bytes(), crc.to_be_bytes()].concat();
|
||||
bytes.splice(33..33, chunk);
|
||||
let image = materialcraft_formats::decode_with_color_space(&bytes, materialcraft_nodes::BitmapColorSpace::FromFile).unwrap();
|
||||
let stored: Vec<_> = image.data().iter().map(|v| (v * 65535.0).round() as u16).collect();
|
||||
assert_eq!(stored, expected, "file gamma {gamma}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmap_filters_are_specific_and_match_supported_extensions() {
|
||||
let extensions: std::collections::BTreeSet<_> = BITMAP_FORMATS.iter().flat_map(|(_, extensions)| extensions.iter().copied()).collect();
|
||||
|
||||
@@ -9,7 +9,7 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
.atomic()
|
||||
.generator()
|
||||
.resource("resource", "Bitmap resource")
|
||||
.choice("colour_space", "Color space", &["sRGB", "Linear"], 0)
|
||||
.choice("colour_space", "Color space", &["sRGB", "Linear", "From file"], 2)
|
||||
.boolean("color_mode", "Color output", true)
|
||||
.any_out()
|
||||
.cook(bitmap)
|
||||
@@ -18,7 +18,7 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
fn bitmap(context: &CookContext) -> CookResult {
|
||||
let name = context.text("resource");
|
||||
let color = context.b("color_mode");
|
||||
let image = match (context.resource)(&craft_texture::resource_key(name, context.i("colour_space") == 1)) {
|
||||
let image = match context.bitmap_resource(name) {
|
||||
Some(image)
|
||||
if image.integer_sampling()
|
||||
&& ((image.width(), image.height()) != (context.w, context.h) || (!color && image.kind() == Kind::Color))
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/// How a bitmap node interprets the channels stored in a package resource.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub enum BitmapColorSpace {
|
||||
Srgb,
|
||||
Linear,
|
||||
FromFile,
|
||||
}
|
||||
|
||||
impl BitmapColorSpace {
|
||||
pub fn from_index(index: i32) -> Self {
|
||||
match index {
|
||||
1 => Self::Linear,
|
||||
2 => Self::FromFile,
|
||||
_ => Self::Srgb,
|
||||
}
|
||||
}
|
||||
|
||||
/// File-based reads have their own cache entry. Existing data and color requests use the shared texture format.
|
||||
pub fn resource_key(self, name: &str) -> String {
|
||||
match self {
|
||||
Self::FromFile => format!("\u{1}F{name}"),
|
||||
_ => craft_texture::resource_key(name, self == Self::Linear),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn split_resource_key(key: &str) -> (&str, Self) {
|
||||
if let Some(name) = key.strip_prefix("\u{1}F") {
|
||||
(name, Self::FromFile)
|
||||
} else {
|
||||
let (name, linear) = craft_texture::split_resource_key(key);
|
||||
(name, if linear { Self::Linear } else { Self::Srgb })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::BitmapColorSpace;
|
||||
|
||||
#[test]
|
||||
fn bitmap_resource_keys_preserve_package_paths_and_literal_prefixes() {
|
||||
for name in ["field", "\u{1}Ffield", "\u{1}Lfield", "child.sbs\0field"] {
|
||||
for space in [BitmapColorSpace::FromFile, BitmapColorSpace::Srgb, BitmapColorSpace::Linear] {
|
||||
let key = space.resource_key(name);
|
||||
assert_eq!(BitmapColorSpace::split_resource_key(&key), (name, space));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,17 @@ pub struct CookContext<'a> {
|
||||
}
|
||||
|
||||
impl CookContext<'_> {
|
||||
pub fn bitmap_color_space(&self) -> crate::BitmapColorSpace {
|
||||
crate::BitmapColorSpace::from_index(self.i("colour_space"))
|
||||
}
|
||||
|
||||
/// A decoder that only accepts the two original request types can still supply the stored channels.
|
||||
pub fn bitmap_resource(&self, name: &str) -> Option<Image> {
|
||||
let space = self.bitmap_color_space();
|
||||
let image = (self.resource)(&space.resource_key(name));
|
||||
if image.is_none() && space == crate::BitmapColorSpace::FromFile { (self.resource)(&craft_texture::resource_key(name, true)) } else { image }
|
||||
}
|
||||
|
||||
pub fn tiling_axes(&self) -> [bool; 2] {
|
||||
self.vars.get("$tiling").and_then(Value::as_i32).map_or([self.tile; 2], |mask| [mask & 1 != 0, mask & 2 != 0])
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod output_precision;
|
||||
pub mod pattern;
|
||||
mod raster;
|
||||
|
||||
mod bitmap_color_space;
|
||||
mod cook_context;
|
||||
pub mod graph_interface;
|
||||
mod image_input;
|
||||
@@ -23,6 +24,7 @@ mod port_kind;
|
||||
mod random;
|
||||
mod texture_sampler;
|
||||
|
||||
pub use bitmap_color_space::BitmapColorSpace;
|
||||
pub use catalog::{catalog, categories, find};
|
||||
pub use cook_context::{CookContext, GraphVariables};
|
||||
pub use image_input::{MAX_IMAGE_INPUTS, image_input_prefix};
|
||||
|
||||
@@ -541,6 +541,29 @@ The patch graph calls functions in the shape package. Save the patch graph and t
|
||||
|
||||
Keeping the shape dependency pointed at the unconverted inventory source gave **36,657/41,216** matching pixels between the original and reopened reference renders, maximum 65,535 U16 levels. The reference could not open that unconverted local patch package directly. In a separate 16² default, changed 64² and seam 128² comparison, resolving only the shape dependency to its available native package restored all **20,736/20,736** reference pixels. Resolving only the math dependency gave 18,013/20,736, maximum 1 in F32. Both image bridges matched their original source fields in all three observed renders. At 16² the first discrepancy was the pixel processor, with 240/256 exact and maximum .739467438. These measurements distinguish dependency resolution on reopen from the small F32 differences in the working graph.
|
||||
|
||||
### Bitmap file transfer and stored channel precision
|
||||
|
||||
A Bitmap with an omitted color interpretation reads the stored RGB levels for the measured PNG, BMP, TGA, TIFF and JPEG files. Floating-point EXR retains its linear levels. A PNG gamma tag can change the stored color or gray levels before resizing. The session caches file-default, explicit linear and explicit sRGB reads independently, including resources from linked packages. Saving an original graph with an omitted interpretation preserves that omission.
|
||||
|
||||
Generate a 64 × 32 RGB image with 8 × 8 blocks. Set X and Y to the integer block coordinates. Compute channels modulo 256 using 71X + 43Y + 19, 99X + 107Y + 13 and 149X + 23Y + 53. Encode each file from those pixels. Use JPEG quality 96 with full chroma resolution and use channel/255 for floating-point EXR. Render each format with the interpretation omitted and with an explicit linear read, at native size in U8, U16, F16 and F32 and at 16² in F32. Use seed 555013 + file index for native size and 555827 + index for the reduction, in PNG, BMP, TGA, TIFF, JPEG, EXR order. File-default reads improved from 8,448/50,688 exact pixels (maximum 18,815 U16 levels) to 50,688/50,688. The explicit reads matched another 50,688/50,688.
|
||||
|
||||
For the PNG profile controls use the [modular RGBA fields](#stored-levels-of-linear-color-bitmap-resources). Take the byte field with no tag, an sRGB tag, gAMA 100000, gAMA 45455, and an embedded standard sRGB profile. Render at 64 × 32, 32² and 16 × 64 in all four formats with seeds 497107, 497108 and 497113. Those 60 renders improved from 0/81,920 (maximum 43,948 U16 levels) to 81,920/81,920. For independent byte and word controls, set gAMA to 30000, 40000, 43000, 44000, 45455, 47000, 48000, 50000, 60000, 80000 and 100000. Render at native size in four formats and at 16² in F32. The eleven matching-depth boundary probes use 43178, 43181, 43182, 43230, 43291, 47725, 47727, 47728, 47784, 47846 and 47848. For the [grayscale fields](#stored-levels-when-resizing-a-grayscale-bitmap-resource) use the 64 × 32 modular byte and word fields described there, at native size in all four formats with no tag and gAMA 30000, 43181, 43182, 45455, 47847, 47848, 60000 and 100000.
|
||||
|
||||
For file gamma g and channel maximum M, the observed transfer rounds 1/(2.2g) to five decimal places. Keep source levels when 2.2g rounded to five places and the rounded exponent are both at least .95. Otherwise store round(M × (channel/M)^exponent) at the original channel depth. Alpha keeps its stored level. At gAMA 43181, 43182, 47847 and 47848 the format regression checks the two edges of the identity interval. A separate session regression exposed the earlier read of (64,128,192,97) as (13,55,134,97).
|
||||
|
||||
| Stored output | Original renders | Exact pixels / total | Reopened renders | Exact pixels / total | Maximum error |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| LUM16 | 18 | 36,864/36,864 | 6 | 12,288/12,288 | 0 |
|
||||
| LUM16F | 18 | 36,864/36,864 | 6 | 12,288/12,288 | 0 |
|
||||
| LUM32F | 18 | 36,864/36,864 | 6 | 12,288/12,288 | 0 |
|
||||
| LUM8 | 18 | 36,864/36,864 | 6 | 12,288/12,288 | 0 |
|
||||
| RGBA16 | 61 | 114,688/114,688 | 18 | 36,864/36,864 | 0 |
|
||||
| RGBA16F | 50 | 92,160/92,160 | 18 | 36,864/36,864 | 0 |
|
||||
| RGBA32F | 85 | 101,120/101,120 | 33 | 40,704/40,704 | 0 |
|
||||
| RGBA8 | 61 | 114,688/114,688 | 21 | 39,936/39,936 | 0 |
|
||||
|
||||
Bitmap file-default and explicit data reads matched all 570,112 pixels across 329 renders. Reopening 24 saved packages matched another 203,520/203,520 pixels and reproduced each original buffer in both applications. One of the original packages was saved by the reference editor before the five direct renders. These measurements cover the generated files and the listed metadata. Other ICC profiles, palette transparency and file-default DDS remain unmeasured. All 790 release tests across the engine, evaluator, format and node crates passed, along with formatting, strict workspace Clippy, dependency layers and WebAssembly.
|
||||
|
||||
## 2026-11-20 root comparisons
|
||||
|
||||
### Hue, saturation, lightness and Replace Color
|
||||
|
||||
@@ -49,6 +49,8 @@ Odd-sized grayscale bitmap resources match 116,736/116,736 pixels directly and 9
|
||||
|
||||
Linear RGBA bitmap resources match 108,544/108,544 pixels on two procedural fields. [Exact counts by format and saved-package results](parity-fixes.md#stored-levels-of-linear-color-bitmap-resources)
|
||||
|
||||
Bitmap file-default and explicit data reads matched all 570,112 pixels across 329 renders. Reopening 24 saved packages matched another 203,520/203,520 pixels and reproduced each original buffer in both applications. [Measurements and saved packages](parity-fixes.md#bitmap-file-transfer-and-stored-channel-precision)
|
||||
|
||||
Grayscale bitmap stamps matched every stored F32 word across the 120 composites, 312 individual-stamp renders and 60 reopened renders. The wider background controls have separate measured differences. [Measurements and saved packages](parity-fixes.md#stored-coverage-before-grayscale-bitmap-stamp-opacity)
|
||||
|
||||
Odd-sized linear RGBA bitmaps matched 100,352/100,352 direct pixels and 45,056/45,056 pixels after downstream sampling. [Measurements and saved packages](parity-fixes.md#odd-sized-linear-color-bitmap-resources)
|
||||
|
||||
Reference in new issue
Block a user