diff --git a/crates/eval/src/external_image.rs b/crates/eval/src/external_image.rs index 4e52f62b..2b84042d 100644 --- a/crates/eval/src/external_image.rs +++ b/crates/eval/src/external_image.rs @@ -1,8 +1,9 @@ +use crate::NodeOutput; use craft_texture::{Image, Kind, Limits, MAX_SIDE}; use materialcraft_core::OutputFormat; /// 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 { +pub(super) fn resize(image: &Image, size: (u32, u32), kind: Kind, source: OutputFormat, output: OutputFormat) -> Option { let size = craft_texture::clamp_size(size.0, size.1); let (width, height) = (image.width(), image.height()); if (width.is_power_of_two() && height.is_power_of_two()) || (width, height) == size || width.max(height) > MAX_SIDE || image.kind() != kind { @@ -37,16 +38,30 @@ pub(super) fn resize(image: &Image, size: (u32, u32), kind: Kind, source: Output } if output == OutputFormat::F16 { return match source { - OutputFormat::U8 => Some(filtered.map(kind, |p| p.map(|v| crate::output_precision::store_half(v / 255.0))).with_integer_sampling(false)), - OutputFormat::U16 => word_to_half(&filtered), + OutputFormat::U8 => { + let texture = filtered.map(kind, |p| p.map(|v| v / 255.0)).with_integer_sampling(true); + let stored = crate::output_precision::apply(texture.clone(), OutputFormat::F16); + Some(NodeOutput::BoundBitmap { stored, texture, texture_format: source }) + } + OutputFormat::U16 => word_to_half(&filtered).map(NodeOutput::Image), // Float rasters are filtered at full precision before the half writer diffuses its rounding error. _ => diffuse(&filtered, |original, received| { let stored = nearest_positive_half(original + received); (stored, original - stored) - }), + }) + .map(NodeOutput::Image), }; } - Some(if let Some(maximum) = maximum { filtered.map(kind, |p| p.map(|v| v / maximum)).with_integer_sampling(output_levels.is_some()) } else { filtered }) + let Some(maximum) = maximum else { return Some(NodeOutput::Image(filtered)) }; + let stored = filtered.map(kind, |p| p.map(|v| v / maximum)).with_integer_sampling(output_levels.is_some()); + if input_levels.is_some() && output_levels.is_none_or(|levels| levels > maximum) { + // A wider bridge can report the same normalized values as the source, yet interpolation + // still rounds the weighted sum to normalized integer levels. + let texture = stored.clone().with_integer_sampling(true); + Some(NodeOutput::BoundBitmap { stored, texture, texture_format: source }) + } else { + Some(NodeOutput::Image(stored)) + } } fn nearest_positive_half(value: f32) -> f32 { diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index 2533d9ed..064c66d3 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -86,15 +86,12 @@ pub(crate) fn cook_instance( source_options.only = Some(source_graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect()); source_options.overrides = params.iter().filter(|(k, _)| source_graph.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); for (port, input) in input_ports.iter().zip(inputs) { - match input { - Some((NodeOutput::Image(image), format)) => { - source_options.inputs.insert(port.id.clone(), image.clone()); - source_options.input_formats.insert(port.id.clone(), *format); - } - Some((NodeOutput::Value(value), _)) => { - source_options.overrides.insert(port.id.clone(), value.clone()); - } - None => {} + let Some((output, format)) = input else { continue }; + if let Some((image, texture_format)) = output.texture(*format) { + source_options.inputs.insert(port.id.clone(), image.clone()); + source_options.input_formats.insert(port.id.clone(), texture_format); + } else if let Some(value) = output.as_value() { + source_options.overrides.insert(port.id.clone(), value.clone()); } } let cooked = cook(source, source_graph_index, &source_options, cache); diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index 6ab5a9fc..be94cd6f 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -83,7 +83,7 @@ pub(crate) fn cook_node( } else { None }; - let stored = output.and_then(NodeOutput::as_image).map(|image| (image, source.map_or(OutputFormat::F32, |source| source.2))); + let stored = source.and_then(|(output, _, format)| output.texture(format)); let image = wired.or(stored); inputs.push(image.map(|(image, _)| image.clone())); input_formats.push(image.map_or(OutputFormat::F32, |(_, format)| format)); @@ -219,16 +219,17 @@ pub(crate) fn cook_node( } else if node.def == "value_processor" { evaluate_value(¶meters, variables, seed, [w, h], &inputs, &input_formats, tile).map(|value| vec![NodeOutput::Value(value)]) } else if matches!(node.def.as_str(), "output" | "dot") - && let Some(Some((NodeOutput::Value(value), _))) = incoming.first() + && let Some(Some((output, _))) = incoming.first() + && (output.as_value().is_some() || matches!(output, NodeOutput::BoundBitmap { stored, .. } if (stored.width(), stored.height()) == (w, h))) { - Ok(vec![NodeOutput::Value(value.clone())]) + Ok(vec![(*output).clone()]) } else if let Some((image, upstream, bitmap)) = input_image { let kind = if node.def == "input_grayscale" { Kind::Gray } else { Kind::Color }; let format = upstream.unwrap_or(OutputFormat::F32); let external = if wired { None } else { crate::external_image::resize(&image, (w, h), kind, bitmap.unwrap_or(format), base.format) }; let tiling = if wired { base.tiling } else { [false; 2] }; - let image = external.unwrap_or_else(|| cook_bound_image(image, (w, h), kind, format, base.format, tiling)); - Ok(vec![NodeOutput::Image(image)]) + let output = external.unwrap_or_else(|| NodeOutput::Image(cook_bound_image(image, (w, h), kind, format, base.format, tiling))); + Ok(vec![output]) } else if node.def == materialcraft_core::MISSING_NODE { let name = if node.label.is_empty() { "this node" } else { node.label.as_str() }; diff --git a/crates/eval/src/node_output.rs b/crates/eval/src/node_output.rs index 15d6e66b..449a6913 100644 --- a/crates/eval/src/node_output.rs +++ b/crates/eval/src/node_output.rs @@ -1,30 +1,48 @@ use craft_texture::Image; -use materialcraft_core::Value; +use materialcraft_core::{OutputFormat, Value}; +use std::sync::Arc; #[derive(Clone, Debug, PartialEq)] pub enum NodeOutput { Image(Image), + /// A bound bitmap can report its bridge precision while filters sample its original integer texture. + BoundBitmap { + stored: Image, + texture: Image, + texture_format: OutputFormat, + }, Value(Value), } impl NodeOutput { pub fn as_image(&self) -> Option<&Image> { match self { - Self::Image(image) => Some(image), + Self::Image(image) | Self::BoundBitmap { stored: image, .. } => Some(image), Self::Value(_) => None, } } pub fn as_value(&self) -> Option<&Value> { match self { - Self::Image(_) => None, + Self::Image(_) | Self::BoundBitmap { .. } => None, Self::Value(value) => Some(value), } } - pub(crate) fn memory_bytes(&self) -> usize { + pub(crate) fn texture(&self, declared: OutputFormat) -> Option<(&Image, OutputFormat)> { match self { - Self::Image(image) => image.data().len().saturating_mul(size_of::()), + Self::BoundBitmap { texture, texture_format, .. } => Some((texture, *texture_format)), + Self::Image(image) => Some((image, declared)), + Self::Value(_) => None, + } + } + + pub(crate) fn memory_bytes(&self) -> usize { + let bytes = |image: &Image| image.data().len().saturating_mul(size_of::()); + match self { + Self::Image(image) => bytes(image), + Self::BoundBitmap { stored, texture, .. } if Arc::ptr_eq(stored.shared_data(), texture.shared_data()) => bytes(stored), + Self::BoundBitmap { stored, texture, .. } => bytes(stored).saturating_add(bytes(texture)), Self::Value(Value::Text(text)) => size_of::().saturating_add(text.len()), Self::Value(_) => size_of::(), } diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index a0aa9f49..d395c810 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -454,6 +454,50 @@ fn bitmap_growth_maps_the_origin_and_half_texel_offset_separately() { assert_eq!(result.image(input, 0).unwrap().get_gray(0, 7, false).to_bits(), 0x3c73_7400); } +#[test] +fn filters_sample_bound_integer_bitmaps_at_the_source_depth() { + use OutputFormat::{F16, F32, U8, U16}; + use materialcraft_core::{OutputFormat, ParameterInheritance}; + + let mut graph = Graph::new("Source precision"); + graph.size = [5, 5]; + graph.format = F32; + let input = graph.add_node("input_grayscale", [0.0; 2]); + let transform = graph.add_node("transformation", [0.0; 2]); + let output = graph.add_node("output", [0.0; 2]); + let node = graph.node_mut(transform).unwrap(); + node.base.format_mode = ParameterInheritance::Absolute; + node.base.format = F32; + node.params.insert("offset".into(), Value::Float2([15.0 / 1024.0, -21.0 / 1024.0])); + graph.connect(input, "output", transform, "input").unwrap(); + graph.connect(input, "output", output, "input").unwrap(); + let mut package = Package::new("Integer input"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + for (depth, bridge, expected) in [(U8, F16, 0x3eee_4eee), (U8, F32, 0x3eee_4eee), (U16, F32, 0x3eee_92ef), (U16, F16, 0x3eee_8000)] { + let node = package.graphs[0].node_mut(input).unwrap(); + node.base.format_mode = ParameterInheritance::Absolute; + node.base.format = bridge; + let mut options = Options::new(&no_res); + options.bitmap_formats.insert("input".into(), depth); + let image = Image::gray(32, 17, |x, y| { + let level = if x % 2 == 0 { 9 } else { 243 }; + if depth == U8 { level as f32 / 255.0 } else { (level * 257 + (7 * x + 3 * y) % 251) as f32 / 65535.0 } + }); + options.inputs.insert("input".into(), image.with_integer_sampling(true)); + for _ in 0..2 { + let result = cook(&package, 0, &options, &cache); + assert!(result.nodes.values().all(|node| node.error.is_none())); + assert_eq!(result.image(transform, 0).unwrap().get_gray(0, 0, false).to_bits(), expected); + if depth == U8 && bridge == F16 { + for id in [input, output] { + assert_eq!(result.image(id, 0).unwrap().get_gray(0, 0, false).to_bits(), 0x3d10_8000); + } + } + } + } +} + #[test] fn bitmap_half_storage_uses_the_original_integer_channel_depth() { use materialcraft_core::OutputFormat::{F16, U8, U16}; diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 669d5396..195b6989 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -1167,6 +1167,23 @@ For Worley, Dissolve, the four diffusion passes, six flood-fill outputs and both For Worley also set size (.75,1.25,1.5), Minkowski number .6875, border width .1875 and roundness .3125. Set optional diffusion controls where exposed. For Flood Fill 2 color use HSL adjustment (.125,−.1875,.25) and random range (.375,.625,.1875). For its grayscale equivalent use luminance adjustment −.1875 and random range .625. The random flood-fill outputs and fast white noise have no additional exposed numeric changes in these controls. Each residual flood-fill difference is at most one U16 level or .0000152587891 in F32. Uniform noise selects the measured per-texel stream. The later [conditional draw comparison](#conditional-pixel-draws-and-white-noise-v2) resolves the Gaussian differences in White Noise v2. +### Sampling integer bitmap inputs through wider bridges + +An input node can have distinct readback and sampling precision. With a constant byte level 9 in a 32×17 grayscale PNG, a 32² F16 input bridge reports 3d108000 expanded to F32. A directly connected half output gives the same bits. A separate F32 filter sampling that bridge at a texel center returns 3d109091, the F32 value of 9/255. The filter also uses integer interpolation for off-center reads. A word bitmap converted to half supplies its stored half texture. A word bitmap through F32 still interpolates the normalized word texture. + +| Original controls | Renders | Exact output pixels / compared | Maximum error | +|---|---:|---:|---:| +| Two source depths and four bridge formats through a translated bilinear transform | 48 | 49,152/49,152 | 0 | +| Centered and offset filters through a half bridge | 144 | 147,456/147,456 | 0 | +| Off-center reads through U8, F16 and F32 bridges | 72 | 73,728/73,728 | 0 | +| Direct output wired to the same three bridge formats | 36 | 36,864/36,864 | 0 | + +For the first row use a 32² F32 output, seed 469, identity transform, bilinear filtering and offset (15/1024,−21/1024). Use grayscale or RGBA PNG files with zero-based channel c. On a 32×17 image use level 9 when x+c is even and 243 otherwise. On a 17×23 image use (47x+73y+13xy+31c+113) mod 256. On a 47×33 image use (11x+7c+223) mod 256. For 16-bit files, expand each level b to 257b and add (7x+3y+11c) mod 251 when b < 255. On the alternating grayscale image, the F32 word at (0,0) is 3eee4eee for the 8-bit source through all four bridges. For the word source, the same pixel gives 3eee8eef, 3eee92ef, 3eee8000 and 3eee92ef through U8, U16, F16 and F32 respectively. + +For the second row use each half bridge with an identity transform at texel centers, a translated nearest transform, a blur at intensity zero, and a bilinear pixel sampler using the translation above. For each combination of filter and grayscale or RGBA, use the [original PNG fields](#source-image-depth-and-the-three-noise-upscalers) at all three sizes for bytes. For words use the 32×17 constant with levels (9,89,142,199)×257 and the 17×23 and 47×33 word hash. Add 32×17 constants at byte levels 1, 9, 31, 127, 143 and 250 and at their word equivalents. The fields use seed 157 and the constants use seed 379. For the last two rows use the three byte fields, the 32×17 word field and the constant 9 at both depths. Compare a translated bilinear transform, an offset bilinear pixel sampler and a direct wire. The filters render at F32. For the wire, read the declared output storage. + +All 106 earlier integer-to-half cases also match at the downstream output, **108,544/108,544 pixels**, including all 26,624 byte pixels. The half readbacks match at the same locations. The two curvature roots and three noise upscalers retain all 2,444,800 pixels in 103 renders. The [float-source integer conversion](#enlarging-bitmap-rows-and-converting-integer-images-to-half) still differs at 18 U8 and 14 U16 pixels on the signed and stepped controls, by at most one level each. + ### Enlarging bitmap rows and converting integer images to half | External source and destination | Renders | Exact bridge pixels / compared | Exact F32 output pixels / compared | Maximum F32 output error | @@ -1190,7 +1207,7 @@ For the PNG fields use the [byte and word recipes](#source-image-depth-and-the-t Filter both axes at the source integer precision. A byte value b reports the half of b/255 rounded toward zero at the bridge. At byte level 9, that is 3d108000 expanded to F32. A word source uses the [three-row diffusion weights](#non-power-of-two-float-image-inputs-and-curvature) in word units with one new random sample per interleaved channel. Start the generator at 1, multiply by 48271 modulo 2147483647, and divide by 2147483647 for a unit draw r. Truncate original word + received error + 16(r−.5) and clamp to the word range. Values 0 through 2 read and reconstruct as zero. Value 3 reads as 2/65536 and reconstructs as 3. For larger values q, store the half of q/65535 rounded toward zero, and reconstruct as min(65535,65536×stored). Propagate original minus reconstructed. For word level 2313 the first three expanded channel words are 3d100000, 3d102000 and 3d10c000. -The reference F32 consumer of these byte sources reads the unrounded filtered byte divided by 255. Its half bridge readback and the consumer value are distinct. This discrepancy accounts for all 22,527 differing downstream pixels in the two byte rows. The float-input to U8 and U16 controls retain 18,414/18,432 and 18,418/18,432 exact pixels, with maximum errors of one stored level. Both curvature roots retain 176,384/176,384 across 20 renders each. Each of the three noise upscalers retains 697,344/697,344 across 21. +The reference F32 consumer of these byte sources reads the unrounded filtered byte divided by 255. Its half bridge readback and the consumer value are distinct. This discrepancy accounted for all 22,527 differing downstream pixels in the two byte rows. The [subsequent sampling controls](#sampling-integer-bitmap-inputs-through-wider-bridges) resolve them. The float-input to U8 and U16 controls retain 18,414/18,432 and 18,418/18,432 exact pixels, with maximum errors of one stored level. Both curvature roots retain 176,384/176,384 across 20 renders each. Each of the three noise upscalers retains 697,344/697,344 across 21. ### Float bitmap reduction and half output diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 60a1ab07..580ff185 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -170,8 +170,8 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard | [crop.sbs/crop_grayscale](../assets/sbs/crop.sbs) | 1 | No | [Parity · 48 renders, all 377,344 pixels across both outputs exact](parity-fixes.md#half-precision-crop-area-and-input-sizes) | | [crystal_1.sbs/crystal_1](../assets/sbs/crystal_1.sbs) | 0 | Yes | [In progress · 19 renders, 99,700/172,288 exact pixels](parity-fixes.md#filtering-unequal-inputs-to-a-blend) | | [crystal_2.sbs/crystal_2](../assets/sbs/crystal_2.sbs) | 0 | Yes | [In progress · 19 renders, 113/172,288 exact pixels](parity-fixes.md#random-draws-in-pattern-properties-and-iterations) | -| [curvature.sbs/curvature](../assets/sbs/curvature.sbs) | 1 | No | [Parity · 20 renders, 176,384 exact pixels](parity-fixes.md#enlarging-bitmap-rows-and-converting-integer-images-to-half) | -| [curvature_smooth.sbs/curvature_smooth](../assets/sbs/curvature_smooth.sbs) | 1 | Yes | [Parity · 20 renders, 176,384 exact pixels](parity-fixes.md#enlarging-bitmap-rows-and-converting-integer-images-to-half) | +| [curvature.sbs/curvature](../assets/sbs/curvature.sbs) | 1 | No | [Parity · 20 renders, 176,384 exact pixels](parity-fixes.md#sampling-integer-bitmap-inputs-through-wider-bridges) | +| [curvature_smooth.sbs/curvature_smooth](../assets/sbs/curvature_smooth.sbs) | 1 | Yes | [Parity · 20 renders, 176,384 exact pixels](parity-fixes.md#sampling-integer-bitmap-inputs-through-wider-bridges) | | [curvature_smooth_v2.sbs/compute_curvature_v2](../assets/sbs/curvature_smooth_v2.sbs) | 2 | Yes | [Parity: 6 cases](parity-fixes.md#verified-cases) | | [diffusion.sbs/impl/pass_RGBA](../assets/sbs/diffusion.sbs) | 4 | Yes | [Parity · 19 renders, 143,872 exact pixels](parity-fixes.md#per-pixel-random-initialization) | | [diffusion.sbs/impl/pass_UV](../assets/sbs/diffusion.sbs) | 1 | Yes | [Parity · 19 renders, 143,872 exact pixels](parity-fixes.md#per-pixel-random-initialization) | @@ -352,9 +352,9 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard | [noise_perlin_noise.sbs/perlin_noise](../assets/sbs/noise_perlin_noise.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [noise_perlin_noise_v2.sbs/perlin_noise](../assets/sbs/noise_perlin_noise_v2.sbs) | 0 | No | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | | [noise_plasma.sbs/plasma](../assets/sbs/noise_plasma.sbs) | 0 | No | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) | -| [noise_upscale_1.sbs/noise_upscale_1](../assets/sbs/noise_upscale_1.sbs) | 1 | No | [Parity · 21 renders, 697,344 exact pixels](parity-fixes.md#enlarging-bitmap-rows-and-converting-integer-images-to-half) | -| [noise_upscale_2.sbs/noise_upscale_2](../assets/sbs/noise_upscale_2.sbs) | 1 | No | [Parity · 21 renders, 697,344 exact pixels](parity-fixes.md#enlarging-bitmap-rows-and-converting-integer-images-to-half) | -| [noise_upscale_3.sbs/noise_upscale_3](../assets/sbs/noise_upscale_3.sbs) | 2 | No | [Parity · 21 renders, 697,344 exact pixels](parity-fixes.md#enlarging-bitmap-rows-and-converting-integer-images-to-half) | +| [noise_upscale_1.sbs/noise_upscale_1](../assets/sbs/noise_upscale_1.sbs) | 1 | No | [Parity · 21 renders, 697,344 exact pixels](parity-fixes.md#sampling-integer-bitmap-inputs-through-wider-bridges) | +| [noise_upscale_2.sbs/noise_upscale_2](../assets/sbs/noise_upscale_2.sbs) | 1 | No | [Parity · 21 renders, 697,344 exact pixels](parity-fixes.md#sampling-integer-bitmap-inputs-through-wider-bridges) | +| [noise_upscale_3.sbs/noise_upscale_3](../assets/sbs/noise_upscale_3.sbs) | 2 | No | [Parity · 21 renders, 697,344 exact pixels](parity-fixes.md#sampling-integer-bitmap-inputs-through-wider-bridges) | | [noise_voronoi.sbs/3d_voronoi](../assets/sbs/noise_voronoi.sbs) | 1 | No | [In progress · 37 renders, 152,320/155,392 exact pixels with stock and shared tables](parity-fixes.md#voronoi-distortion-and-shared-noise-inputs) | | [noise_voronoi.sbs/3d_voronoi_fractal](../assets/sbs/noise_voronoi.sbs) | 1 | No | [In progress · 37 renders, 152,163/155,392 exact pixels with stock and shared tables](parity-fixes.md#voronoi-distortion-and-shared-noise-inputs) | | [noise_voronoi.sbs/voronoi](../assets/sbs/noise_voronoi.sbs) | 0 | No | [In progress · 37 renders, 152,320/155,392 exact pixels with stock and shared tables](parity-fixes.md#voronoi-distortion-and-shared-noise-inputs) |