From fff40a89b68f94852ae0dd182036e09c30bc3a47 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sat, 21 Nov 2026 03:12:27 -0500 Subject: [PATCH] Preserve source precision when resizing odd grayscale bitmaps --- crates/core/src/lib.rs | 2 +- crates/core/src/resource.rs | 24 ++++++++++++++++----- crates/eval/src/external_image.rs | 20 +++++++++++++++++- crates/eval/src/node_execution.rs | 26 ++++++++++++++--------- crates/eval/src/tests.rs | 35 +++++++++++++++++++++++++++++++ docs/parity-fixes.md | 19 +++++++++++++++++ docs/sbs-root-nodes.md | 2 ++ 7 files changed, 111 insertions(+), 17 deletions(-) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index f55d949c..89eb041f 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -79,7 +79,7 @@ pub use pattern_node::PatternNode; pub use pattern_node_kind::PatternNodeKind; pub use pin::Pin; pub use preset::Preset; -pub use resource::{Resource, png_sample_format}; +pub use resource::{PngRasterInfo, Resource, png_raster_info, png_sample_format}; pub use resource_bytes::ResourceBytes; pub use size_mode::SizeMode; pub use value::Value; diff --git a/crates/core/src/resource.rs b/crates/core/src/resource.rs index e7231ae6..1d7875a0 100644 --- a/crates/core/src/resource.rs +++ b/crates/core/src/resource.rs @@ -36,10 +36,24 @@ fn default_folder() -> String { /// Original normalized channel precision of a grayscale or truecolor PNG resource. /// The decoded float values alone cannot distinguish a byte from the equivalent repeated-byte word. pub fn png_sample_format(bytes: &[u8]) -> Option { + png_raster_info(bytes).map(|info| info.format) +} + +/// Raster properties declared in the header of a normalized grayscale or truecolor PNG. +pub struct PngRasterInfo { + pub size: [u32; 2], + pub format: OutputFormat, + pub grayscale: bool, +} + +pub fn png_raster_info(bytes: &[u8]) -> Option { let header = bytes.strip_prefix(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR")?; - match header.get(8..10)? { - [8, 0 | 2 | 4 | 6] => Some(OutputFormat::U8), - [16, 0 | 2 | 4 | 6] => Some(OutputFormat::U16), - _ => None, - } + let format = match header.get(8..10)? { + [8, 0 | 2 | 4 | 6] => OutputFormat::U8, + [16, 0 | 2 | 4 | 6] => OutputFormat::U16, + _ => return None, + }; + let width = u32::from_be_bytes(*header.first_chunk()?); + let height = u32::from_be_bytes(*header.get(4..)?.first_chunk()?); + Some(PngRasterInfo { size: [width, height], format, grayscale: matches!(header.get(9), Some(0 | 4)) }) } diff --git a/crates/eval/src/external_image.rs b/crates/eval/src/external_image.rs index 2b84042d..b80079d8 100644 --- a/crates/eval/src/external_image.rs +++ b/crates/eval/src/external_image.rs @@ -1,6 +1,24 @@ use crate::NodeOutput; use craft_texture::{Image, Kind, Limits, MAX_SIDE}; -use materialcraft_core::OutputFormat; +use materialcraft_core::{OutputFormat, Package}; +use materialcraft_nodes::CookContext; + +/// An embedded odd-sized grayscale PNG uses the same stored and sampled levels as a bound raster. +pub(super) fn resize_bitmap(context: &CookContext, package: &Package) -> Option { + if context.b("color_mode") { + return None; + } + let name = context.text("resource"); + let resource = package.resource(name)?; + let info = materialcraft_core::png_raster_info(resource.bytes.as_slice())?; + let [width, height] = info.size; + // Check the header first so ordinary power-of-two bitmaps still request their decoded image only once. + if !info.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, context.i("colour_space") == 1))?; + resize(&image, (context.w, context.h), Kind::Gray, info.format, context.format) +} /// Non-power-of-two external rasters filter each axis directly, storing the result between passes. pub(super) fn resize(image: &Image, size: (u32, u32), kind: Kind, source: OutputFormat, output: OutputFormat) -> Option { diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index a1375c06..5dbcc2fa 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -298,16 +298,22 @@ pub(crate) fn cook_node( resource: options.resource, vars: &bindings, }; - (definition.cook)(&context).map(|images| { - images - .into_iter() - .map(|image| { - // Bridges retain their source pixels; filters store their declared precision - let image = if matches!(node.def.as_str(), "output" | "dot") { image } else { crate::output_precision::apply(image, base.format) }; - NodeOutput::Image(image) - }) - .collect() - }) + if node.def == "bitmap" + && let Some(output) = crate::external_image::resize_bitmap(&context, package) + { + Ok(vec![output]) + } else { + (definition.cook)(&context).map(|images| { + images + .into_iter() + .map(|image| { + // Bridges retain their source pixels; filters store their declared precision + let image = if matches!(node.def.as_str(), "output" | "dot") { image } else { crate::output_precision::apply(image, base.format) }; + NodeOutput::Image(image) + }) + .collect() + }) + } } else { Err(format!("unknown node `{}`", node.def)) }; diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 1aa5a3e2..938b0287 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -689,6 +689,41 @@ fn bound_float_bitmap_diffuses_half_rounding_after_resizing() { assert_eq!(image.get(2, 0, false), [1.0 + 1.0 / 1024.0, 0.0, 0.125, 0.125 + 1.0 / 8192.0]); } +#[test] +fn bitmap_node_filters_odd_rasters_at_their_original_channel_depth() { + use materialcraft_core::{OutputFormat, Resource, ResourceBytes}; + + let mut graph = Graph::new("Odd bitmap"); + graph.size = [5, 5]; + graph.format = OutputFormat::U16; + let bitmap = graph.add_node("bitmap", [0.0; 2]); + let node = graph.node_mut(bitmap).unwrap(); + node.params.insert("resource".into(), Value::Text("field".into())); + node.params.insert("color_mode".into(), Value::Bool(false)); + let mut package = Package::new("Grayscale bitmap"); + package.graphs.push(graph); + for (depth, expected) in [(8_u8, [11308, 30326, 40349, 49087]), (16, [419, 4749, 33094, 35028])] { + let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + header.extend_from_slice(&37_u32.to_be_bytes()); + header.extend_from_slice(&23_u32.to_be_bytes()); + header.extend([depth, 0, 0, 0, 0]); + package.resources = vec![Resource::new("field", "field.png", ResourceBytes::new(header))]; + let field = Image::gray(37, 23, |x, y| { + if depth == 8 { + ((83 * x + 151 * y + 11 * x * y + 29) % 256) as f32 / 255.0 + } else { + ((573 * x + 149 * y + 97 * x * y + 317) % 65536) as f32 / 65535.0 + } + }) + .with_integer_sampling(true); + let resource = |_: &str| Some(field.clone()); + let result = cook(&package, 0, &Options::new(&resource), &Mutex::new(Cache::default())); + let image = result.image(bitmap, 0).unwrap(); + let levels = [(0, 0), (3, 7), (16, 16), (31, 31)].map(|(x, y)| (image.get_gray(x, y, false) * 65535.0).round() as u16); + assert_eq!(levels, expected); + } +} + #[test] fn bound_float_image_filters_an_odd_impulse_on_each_axis() { let mut graph = Graph::new("Impulse"); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 8f373053..30c5c5c7 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -320,6 +320,25 @@ One group order per capture reproduces **442,368/442,368** pixels over all 27 re In the default graph the four MaterialCraft contributions at (99,47), in its traversal order, are .05887965112924576, .031324971467256546, .02835862897336483 and .03313484787940979. Their accumulation order accounts for the U16 boundary at that coordinate. The observed changes between captures prevent a single fixed image from matching every repeat. These reordered images explain the disagreement. The original renderer counts above and the [125-setting root comparison](#gaussian-generators-and-spots-through-1024-pixels-per-side) remain the parity measurements. +### Original channel precision of odd-sized grayscale bitmap resources + +The grayscale Bitmap node and a graph input bound to the same 37 × 23 PNG produced identical stored pixels in the reference app. MaterialCraft previously resized the embedded resource with a single bilinear lookup. The bitmap now uses the existing two-pass raster filter. It retains the source byte or word depth during resizing, including when a downstream node samples a wider output. + +Generate the U8 and U16 modular fields at 37 × 23 and use the ten output sizes and seed formula in the [stored-level comparison](#stored-levels-when-resizing-a-grayscale-bitmap-resource), with field indices 5 and 4 respectively. All 80 embedded Bitmap outputs and all 80 graph input outputs now match. The following counts are for the embedded Bitmap. + +| Output | Renders | Exact before / total · maximum | Exact after / total · maximum | +|---|---:|---:|---:| +| LUM8 | 20 | 15,093/29,184 · 85 | 29,184/29,184 · 0 | +| LUM16 | 20 | 4,548/29,184 · 21878 | 29,184/29,184 · 0 | +| LUM16F | 20 | 5,057/29,184 · 0.333740234 | 29,184/29,184 · 0 | +| LUM32F | 20 | 16/29,184 · 0.333839174 | 29,184/29,184 · 0 | + +At 32² U16, read (0,0), (3,7), (16,16) and (31,31). The byte field stores 11,308, 30,326, 40,349 and 49,087. The word field stores 419, 4,749, 33,094 and 35,028. The two source precisions are distinguishable even when the output format is identical. The 160 power-of-two controls still reproduce all 233,472 pixels. + +For a downstream check connect each original resource through a Bitmap or a bound image input to a Pixel Processor. Set the upstream format in turn to U8, U16, F16 and F32. Request a bilinear color sample at the pixel center plus (.01318359375, −.02734375). Render to F32 at 32², 16 × 32 and 64 × 16, then to U8, U16 and F16 at 32². Use seed 507011 + 43i + j for zero-based upstream format i and output case j. All 96 renders match **90,112/90,112 RGBA pixels**, maximum zero. This includes 40,960 F32 pixels and 16,384 in each other format. + +MaterialCraft wrote six packages spanning direct and downstream reads. Reopening in both apps reproduced the original 37,888/37,888 pixels across 40 saved settings and matched across applications in all four formats, maximum zero. The regression failed on the previous evaluator and passed with the fix. Eight core and 56 evaluator release tests passed. Formatting, strict workspace Clippy, dependency layers and WebAssembly passed. + ## 2026-11-20 root comparisons ### Hue, saturation, lightness and Replace Color diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index d9815b63..6910dace 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -45,6 +45,8 @@ Both unit-region stamp sweeps match every F32 pixel, 1,392,640 across 200 render Filtered F32 pixel reads now match 41,664/41,664 pixels across 150 renders. The nearest and directly wired controls preserve subnormal inputs. [Sampler measurements and capture timings](parity-fixes.md#subnormal-values-in-filtered-pixel-reads) +Odd-sized grayscale bitmap resources match 116,736/116,736 pixels directly and 90,112/90,112 across downstream sampling controls. [Bitmap and saved-package measurements](parity-fixes.md#original-channel-precision-of-odd-sized-grayscale-bitmap-resources) + Enlarged RGBA pattern backgrounds now match 71,680/71,680 pixels across 280 independent renders. The earlier source-storage tests still differ at 121 grayscale zero signs. [Background sign measurements](parity-fixes.md#signs-of-zero-in-enlarged-color-backgrounds) The 32²-to-16² signed threshold controls match 2,048/2,048 pixels. [Floating texture filter measurements](parity-fixes.md#signed-zero-in-floating-point-texture-filtering)