diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index 2579dd63..5153de19 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -1,5 +1,5 @@ use crate::{Cache, MAX_DEPTH, NodeOutput, Options, Port, cook, identifier}; -use materialcraft_core::{Graph, Node, OutputFormat, Package, Value}; +use materialcraft_core::{Graph, Node, Package, Value}; use std::{collections::BTreeMap, sync::Mutex}; pub(crate) fn resolve<'a>(registry: &'a Package, current: &'a Package, node: &Node) -> Option<(&'a Package, usize, &'a Graph)> { @@ -42,7 +42,7 @@ pub(crate) fn cook_instance( node: &Node, input_ports: &[Port], output_ports: &[Port], - inputs: &[Option<(&NodeOutput, OutputFormat)>], + inputs: &[Option<(&NodeOutput, crate::ResolvedBaseParameters)>], params: &BTreeMap, fixed: &[String], base: crate::resolved_base_parameters::ResolvedBaseParameters, @@ -105,10 +105,11 @@ pub(crate) fn cook_instance( source_options.literal_inputs.retain(|name| name != &port.id); continue; } - let Some((output, format)) = input else { continue }; - if let Some((image, texture_format)) = output.texture(*format) { + let Some((output, source_base)) = input else { continue }; + if let Some((image, texture_format)) = output.texture(source_base.format) { source_options.inputs.insert(port.id.clone(), image.clone()); source_options.input_formats.insert(port.id.clone(), texture_format); + source_options.input_bases.insert(port.id.clone(), *source_base); if matches!(output, NodeOutput::BaseLevel(_)) { source_options.base_level_inputs.insert(port.id.clone()); } @@ -136,15 +137,8 @@ pub(crate) fn cook_instance( .and_then(|node| cooked.nodes.get(&node.id)) .ok_or_else(|| format!("the source output `{}` is missing", port.id))?; let output = result.outputs.first().ok_or_else(|| format!("the source output `{}` is empty", port.id))?; - let source_base = result.base; - let port_base = crate::ResolvedBaseParameters { - size: source_base.size, - size_underflow: source_base.size_underflow, - dynamic_size: source_base.dynamic_size, - format: source_base.format, - pixel_size: source_base.pixel_size, - ..base - }; + // Images carry their source properties across the boundary. The caller owns the random seed. + let port_base = crate::ResolvedBaseParameters { seed: base.seed, ..result.base }; Ok((output.clone(), port_base)) }) .collect() diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index 7af69afe..179068bf 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -66,7 +66,7 @@ pub(crate) fn cook_node( let source = connection.and_then(|connection| { let result = cooked.nodes.get(&connection.from)?; let index = prepared.ports(connection.from).1.iter().position(|output| output.id == connection.from_port)?; - Some((result.outputs.get(index)?, result.key ^ hash_of(&index), result.output_base(index)?.format)) + Some((result.outputs.get(index)?, result.key ^ hash_of(&index), result.output_base(index)?)) }); input_keys.push(source.as_ref().map_or(0, |source| source.1)); let output = source.map(|source| source.0); @@ -100,16 +100,23 @@ pub(crate) fn cook_node( { *level = wired.map_or(matches!(output, Some(NodeOutput::BaseLevel(_))), |(_, _, base_level)| base_level); } - let stored = source.and_then(|(output, _, format)| output.texture(format)); + let stored = source.and_then(|(output, _, base)| output.texture(base.format)); let image = wired.map(|(image, format, _)| (image, format)).or(stored); inputs.push(image.map(|(image, _)| image.clone())); input_formats.push(image.map_or(OutputFormat::F32, |(_, format)| format)); } - incoming.push(source.map(|(output, _, format)| (output, format))); + incoming.push(source.map(|(output, _, base)| (output, base))); } - let input_base = prepared.input_base(node.id, cooked); + let input_base = prepared.input_base(node.id, cooked).or_else(|| { + if !matches!(node.def.as_str(), "input_color" | "input_grayscale") { + return None; + } + let source = options.input_bases.get(&identifier(node))?; + // A bridge has its own working dimensions and precision. Its sampling properties follow the wire. + Some(crate::ResolvedBaseParameters { pixel_size: source.pixel_size, pixel_ratio: source.pixel_ratio, tiling: source.tiling, ..prepared.parent_base }) + }); let (mut base, base_values, base_error) = match crate::resolved_base_parameters::evaluate(&node.base, input_base, prepared.parent_base, &mut variables, &fixed) { Ok((base, values)) => (base, values, None), @@ -340,8 +347,8 @@ pub(crate) fn cook_node( // 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) }; // A Blend that selects a compatible texture retains its available sampling levels. - if let Some((NodeOutput::BaseLevel(source), format)) = selected - && format == base.format + if let Some((NodeOutput::BaseLevel(source), source_base)) = selected + && source_base.format == base.format && source.kind() == image.kind() && (source.width(), source.height()) == (w, h) { diff --git a/crates/eval/src/node_result.rs b/crates/eval/src/node_result.rs index 5dc215e9..f79b465f 100644 --- a/crates/eval/src/node_result.rs +++ b/crates/eval/src/node_result.rs @@ -10,7 +10,7 @@ pub struct NodeResult { pub parameters: std::collections::BTreeMap, /// One image per output port (empty when the cook failed) pub outputs: Arc>, - /// Instance ports carry the dimensions, format and pixel size of their source. + /// Instance ports carry the dimensions, format and sampling properties of their source. pub output_bases: Option>, pub error: Option, /// Cook time in milliseconds (0 when served from the cache) diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs index 39a2df6a..77903f25 100644 --- a/crates/eval/src/options.rs +++ b/crates/eval/src/options.rs @@ -17,6 +17,8 @@ pub struct Options<'a> { pub inputs: BTreeMap, /// Upstream storage precision for caller-supplied images. Unspecified floating inputs use full precision. pub input_formats: BTreeMap, + /// Resolved source properties for each image wired to a graph instance. + pub input_bases: BTreeMap, /// Caller textures which have only their base level when passed through an instance. pub base_level_inputs: BTreeSet, /// Original storage of decoded external files. Wired graph inputs use their upstream format. @@ -48,6 +50,7 @@ impl<'a> Options<'a> { only: None, inputs: BTreeMap::new(), input_formats: BTreeMap::new(), + input_bases: BTreeMap::new(), base_level_inputs: BTreeSet::new(), bitmap_formats: BTreeMap::new(), overrides: BTreeMap::new(), diff --git a/crates/eval/tests/instance_image_properties.rs b/crates/eval/tests/instance_image_properties.rs new file mode 100644 index 00000000..d5949c10 --- /dev/null +++ b/crates/eval/tests/instance_image_properties.rs @@ -0,0 +1,62 @@ +use materialcraft_core::{FunctionGraph, Graph, OutputFormat, Package, ParameterInheritance, Value}; +use materialcraft_eval::{Cache, Options, cook}; +use std::sync::Mutex; + +#[test] +fn each_instance_image_pin_preserves_its_own_sampling_properties() { + let mut parent = Graph::new("Caller"); + let mut child = Graph::new("Two fields"); + for graph in [&mut parent, &mut child] { + graph.size = [6; 2]; + graph.format = OutputFormat::U16; + } + let instance = parent.add_node("graph_instance", [0.0; 2]); + parent.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text("Two fields".into())); + let mut filters = Vec::new(); + for (name, size, tiling, ratio) in [("first", [2.0, 0.5], [false, true], 0), ("second", [0.5, 2.0], [true, false], 1)] { + let mut noise = FunctionGraph::default(); + let unit = noise.add_constant(Value::Float(1.0)); + noise.output = Some(noise.add("rand", &[unit], None)); + let source = parent.add_node("pixel_processor", [0.0; 2]); + let field = parent.node_mut(source).unwrap(); + field.params.insert("function".into(), Value::Function(Box::new(noise))); + field.params.insert("color_mode".into(), Value::Bool(false)); + field.base.pixel_size_mode = ParameterInheritance::Absolute; + field.base.pixel_size = size; + field.base.tiling_mode = ParameterInheritance::Absolute; + field.base.tiling = tiling; + field.base.pixel_ratio_mode = ParameterInheritance::Absolute; + field.base.pixel_ratio = ratio; + parent.connect(source, "output", instance, name).unwrap(); + + let input = child.add_node("input_grayscale", [0.0; 2]); + child.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text(name.into())); + let inside = child.add_node("blur", [0.0; 2]); + child.node_mut(inside).unwrap().params.insert("intensity".into(), Value::Float(12.0)); + child.connect(input, "output", inside, "input").unwrap(); + let output = child.add_node("output", [0.0; 2]); + child.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text(name.into())); + child.connect(inside, "output", output, "input").unwrap(); + + let flat = parent.add_node("blur", [0.0; 2]); + parent.node_mut(flat).unwrap().params.insert("intensity".into(), Value::Float(12.0)); + parent.connect(source, "output", flat, "input").unwrap(); + let receiver = parent.add_node("blur", [0.0; 2]); + parent.node_mut(receiver).unwrap().params.insert("intensity".into(), Value::Float(0.0)); + parent.connect(instance, name, receiver, "input").unwrap(); + filters.push((receiver, flat, size, tiling, ratio)); + } + let mut package = Package::new("Image pin properties"); + package.graphs.extend([parent, child]); + let cache = Mutex::new(Cache::default()); + for cached in [false, true] { + let cooked = cook(&package, 0, &Options::new(&|_| None), &cache); + assert_eq!(cooked.nodes[&instance].error, None); + assert_eq!(cooked.nodes[&instance].cached, cached); + for &(receiver, flat, size, tiling, ratio) in &filters { + let base = cooked.nodes[&receiver].base; + assert_eq!((base.pixel_size, base.tiling, base.pixel_ratio), (size, tiling, ratio)); + assert_eq!(cooked.image(receiver, 0).unwrap().data(), cooked.image(flat, 0).unwrap().data()); + } + } +} diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 10b750af..05d4fea0 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -114,6 +114,24 @@ A discarded draw leaves the next random value available. A write, a draw used el Two further controls put a three-iteration loop on the discarded side of Sequence. Its body either discards Random(1) or assigns the draw. The reference returns the first draw after either loop. These cases still differ in MaterialCraft. Across both loops and four settings, FX-Map matches 0/2,048, maximum 0.386968136, Pixel Processor matches 0/2,048, maximum 0.961201191 and Value Processor matches 0/8, maximum 0.662862062. Seven further controls outside those two loops, including an empty loop, produce 7,168/7,168, maximum 0 in FX-Map, 7,168/7,168, maximum 0 in Pixel Processor and 24/28, maximum 0.45432511 in Value Processor. The four scalar differences occur when a false conditional arm shares a draw with another expression. Random expressions passed as graph arguments are also under separate investigation. +### Sampling properties on graph inputs and outputs + +Connect an original half-size U16 Random(1) field to Blur. Compare a flat graph with the same connection across an instance output. Set tiling on the field to none, horizontal, vertical or both, then repeat with an absolute override on Blur. Use intensity 12. For the pixel-ratio cases, set the source ratio to stretch (0) or square (1) and drive Blur intensity with the float conversion of the inherited pixel ratio multiplied by 12. + +For an instance input, wire two original fields to separately named grayscale bridges. Give the fields pixel sizes (2,.5) and (.5,2) and use intensity 4 inside the child. In separate controls use unit pixel sizes and opposite one-axis tiling modes, or pixel ratios 0 and 1. Read each pin in turn. Test absolute settings on the input bridge. Render at parent sizes 64² and 128² with seed 0, 128 × 64 with seed 17 and 64 × 128 with seed 12071. Compare the stored output of the matching flat graph, the child inside an instance and an ordinary save reopened in the reference desktop. + +| Nested U16 control | Previous exact pixels · maximum error | Corrected original exact pixels · maximum error | Corrected reopen exact pixels · maximum error | +|---|---:|---:|---:| +| Output tiling 0, 1, 2, 3 and explicit override | 43,568/46,080 · 16278 | 46,080/46,080 · 0 | 46,080/46,080 · 0 | +| Output pixel ratio 0, 1 and explicit override | 18,432/27,648 · 50328 | 27,648/27,648 · 0 | 27,648/27,648 · 0 | +| Input pixel size, each of two pins | 9,216/18,432 · 34253 | 18,432/18,432 · 0 | 18,432/18,432 · 0 | +| Input tiling, both pins and their absolute overrides | 35,632/36,864 · 16278 | 36,864/36,864 · 0 | 36,864/36,864 · 0 | +| Input pixel ratio, both pins and their absolute overrides | 27,648/36,864 · 50328 | 36,864/36,864 · 0 | 36,864/36,864 · 0 | + +Across the 36 flat and nested graphs, the original and the ordinary save each match 331,776/331,776 U16 pixels. The desktop original and reopen agree at every pixel. Both input pins now retain their own sampling settings. A downstream filter reads the settings from the selected child output. The same previous pixel-size matrix still matches 110,592/110,592 on each pass. + +Repeat the no-tiling output, stretch-ratio output, first tiling input and second ratio input with Blur explicitly storing U8, F16 and F32. Each storage format matches 73,728/73,728 pixels on the original and 73,728/73,728 on the ordinary save, maximum error 0. The desktop flat and nested comparisons and all original-versus-reopen comparisons give the same exact counts. Bricks 01 Base Color repeats its 4,096/4,096 at 64², 16,379/16,384 at 128² and 4,094/4,096 with changed luminance and seed at 64². Its last two maximum byte errors are 1. + ### Pixel size on graph instance outputs At 128² and seed 0, the Gaussian source in Bricks 01 returns a 64² U16 field with pixel size (2,2). The input to Blur matches the reference in all 4,096 pixels. The filter intensity is 1.61. The instance previously returned the caller's unit pixel size to downstream filters. Blur then copied the field and matched just 53/4,096, maximum U16 error 21,379. diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 84b1159b..e6aa8d44 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -41,6 +41,8 @@ Nested Curvature, Curvature Smooth and Normal Sobel each match 2,304/2,304 origi Ordinary SBS saves preserve graph seed inheritance across 22 nested graphs. The original and reopened random fields each match 22,528/22,528 pixels. BNW Spots 1 and Clouds 1 and 2 each match 9,216/9,216 pixels across four output formats in the two nested settings. [Seed settings, whole graphs and renderer repeats](parity-fixes.md#graph-random-seed-inheritance-on-save-and-in-nested-graphs) +An image wired through a graph instance retains its per-pin pixel size, tiling and pixel ratio. All 331,776/331,776 U16 pixels match on original and reopened flat and nested graphs. U8, F16 and F32 each match a further 73,728/73,728 pixels on both passes. [Sampling settings, overrides and raw comparisons](parity-fixes.md#sampling-properties-on-graph-inputs-and-outputs) + The Bricks 01 material provides a separate 2D display check. The corrected preview matches all 258 tested encoded RGB channels. The headless 2D PNG also matches every pixel of a 16² uniform-color control in both display modes. With the shared pattern and instance pixel-size fixes, default Base Color matches 4,096/4,096 raw pixels at 64² and 16,379/16,384 at 128², maximum byte errors 0 and 1. At 256² the raw outputs match 65,508/65,536, maximum 1. [Child output pixel size and whole-material measurements](parity-fixes.md#pixel-size-on-graph-instance-outputs) [Color swatches](parity-fixes.md#stored-graph-color-in-the-2d-view) · [Whole-material measurements](parity-fixes.md#selected-channels-in-pattern-expressions) Original Sequence controls and their ordinary saves each match 11,264/11,264 pixels in each of three image contexts and 44/44 typed Value Processor results. A further 72/72 typed values match across seeds and dimensions. Discarded loops and shared draws in scalar conditionals have remaining differences. [Procedure, exact counts and maximum errors](parity-fixes.md#sequence-evaluation-and-scalar-random-values)