diff --git a/crates/nodes/src/function/branch_assignments.rs b/crates/nodes/src/function/branch_assignments.rs new file mode 100644 index 00000000..904f8829 --- /dev/null +++ b/crates/nodes/src/function/branch_assignments.rs @@ -0,0 +1,53 @@ +use super::Program; + +/// A pixel branch evaluates a shared assignment in the enclosing scope. An assignment +/// private to one arm stays there, including when two alternatives inside that arm use it. +pub(super) fn identify(program: &mut Program) { + let instructions = &program.instructions; + if !instructions.iter().any(|op| op.definition.id == "ifelse") + || !instructions.iter().any(|op| op.definition.id == "set" || op.call.as_ref().is_some_and(|call| call.exports)) + { + return; + } + + let mut writes = Vec::with_capacity(instructions.len()); + for op in instructions { + // The loop owns its assignments and refreshes their registers on each iteration. + let assigns = op.definition.id != "while" + && (op.definition.id == "set" || op.call.as_ref().is_some_and(|call| call.exports) || op.inputs.iter().any(|&input| writes[input])); + writes.push(assigns); + } + + let mut paths = vec![0_u8; instructions.len()]; + for branch in 0..instructions.len() { + let op = &program.instructions[branch]; + let [_, yes, no] = op.inputs.as_slice() else { continue }; + if op.definition.id != "ifelse" || !(writes[*yes] || writes[*no]) { + continue; + } + paths.fill(0); + paths[program.output] = 4; + paths[*yes] |= 1; + paths[*no] |= 2; + let mut shared = Vec::new(); + // Instructions follow their inputs. Reach a register from each arm and from + // other consumers before deciding whether it belongs at this branch. + for index in (0..=program.output).rev() { + let path = paths[index]; + if path == 0 || index == branch || !writes[index] { + continue; + } + if path.count_ones() > 1 { + // Evaluate the whole shared expression in order. Pulling individual Sets + // out of a shared sequence or conditional could execute a skipped write. + shared.push(index); + } else { + for &input in &program.instructions[index].inputs { + paths[input] |= path; + } + } + } + shared.reverse(); + program.instructions[branch].control_registers = shared; + } +} diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs index 34b62a7e..2d300eb4 100644 --- a/crates/nodes/src/function/compile.rs +++ b/crates/nodes/src/function/compile.rs @@ -271,6 +271,7 @@ fn mark_literals(program: &mut Program, mut arguments: BTreeSet<&str>, pixel: Op } let readers = pixel.and_then(|context| super::pixel_condition::live_readers(program, context)); super::product_sum::identify(&mut program.instructions, readers.as_deref()); + super::branch_assignments::identify(program); super::branch_random::identify(program); super::returned_product::identify(program, returned) } diff --git a/crates/nodes/src/function/instruction.rs b/crates/nodes/src/function/instruction.rs index e6603911..a058683a 100644 --- a/crates/nodes/src/function/instruction.rs +++ b/crates/nodes/src/function/instruction.rs @@ -14,7 +14,7 @@ pub(crate) struct Instruction { pub(super) pixel_product_sum: Option, /// Registers for max(lower, min(value, upper)) with literal scalar bounds. pub(super) pixel_interval: Option>, - /// A loop refreshes its condition and body. A pixel branch first samples its shared draws. + /// A loop refreshes its condition and body. A pixel branch first evaluates its shared effects. pub control_registers: Vec, pub call: Option, } diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index 8ab1aa13..f978ef35 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -10,6 +10,7 @@ const DEFAULT_LOOP_LIMIT: i32 = 32; mod arithmetic; mod binary_exponential; +mod branch_assignments; mod branch_random; mod catalog; mod compile; diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index c9876124..b163f3ff 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -271,10 +271,10 @@ impl Program { state.steps.push(Enter(self.input(index, slot)?)); if context.scope == super::FunctionScope::PixelProcessor { - for &draw in self.instruction(index)?.control_registers.iter().rev() { - if state.registers.get(draw).is_some_and(Option::is_none) { + for &shared in self.instruction(index)?.control_registers.iter().rev() { + if state.registers.get(shared).is_some_and(Option::is_none) { state.steps.push(Discard); - state.steps.push(Enter(draw)); + state.steps.push(Enter(shared)); } } } diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 427a629e..7f963fa9 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -1342,6 +1342,52 @@ fn branches_are_lazy_and_sequence_orders_side_effects() { assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17)); } +#[test] +fn pixel_branches_share_an_assignment_across_nested_alternatives() { + let mut graph = FunctionGraph::default(); + let name = Some(Value::Text("stored".into())); + let initial = graph.add_constant(Value::Float(0.40625)); + let init = graph.add("set", &[initial], name.clone()); + let uv = graph.add("get_float2", &[], Some(Value::Text("$pos".into()))); + let x = graph.add("swizzle1", &[uv], Some(Value::Int(0))); + let write = graph.add("set", &[x], name.clone()); + let after_write = graph.add("get_float1", &[], name.clone()); + let shared = graph.add("sequence", &[write, after_write], None); + let one = graph.add_constant(Value::Float(1.0)); + let half = graph.add_constant(Value::Float(0.5)); + let upper = graph.add_constant(Value::Float(1.5)); + let first = graph.add("add", &[shared, one], None); + let second = graph.add("mul", &[shared, half], None); + let last = graph.add("get_float1", &[], name); + let selector = graph.add("get_float1", &[], Some(Value::Text("selector".into()))); + let low = graph.add("lr", &[selector, half], None); + let middle = graph.add("lr", &[selector, upper], None); + let inner = graph.add("ifelse", &[middle, second, last], None); + let across_arms = graph.add("ifelse", &[low, first, inner], None); + let siblings = graph.add("ifelse", &[low, first, second], None); + let within_arm = graph.add("ifelse", &[middle, siblings, last], None); + let chosen = graph.add("ifelse", &[low, shared, last], None); + let across_operands = graph.add("add", &[chosen, second], None); + + for (root, expected) in [(across_arms, [1.03125, 0.015625, 0.03125]), (within_arm, [1.03125, 0.015625, 0.40625]), (across_operands, [0.046875; 3])] { + graph.output = Some(graph.add("sequence", &[init, root], None)); + let program = compile(&graph, 0).unwrap(); + for (selector, expected) in [0.0, 1.0, 2.0].into_iter().zip(expected) { + let variables = BTreeMap::from([("selector".into(), Value::Float(selector))]); + let context = EvaluationContext { + scope: super::FunctionScope::PixelProcessor, + position: [0.03125; 2], + size: [16.0; 2], + images: &[], + image_formats: &[], + tile: true, + variables: &variables, + }; + assert_eq!(program.evaluate_pixel(&context, &mut EvaluationState::default()), Ok(Value::Float(expected)), "root {root}, selector {selector}"); + } + } +} + #[test] fn time_and_tiling_variables_have_typed_defaults_and_host_overrides() { for (name, operation, default, supplied) in diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index e57d06a4..c4297647 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -139,6 +139,31 @@ In index order set scale to (8,3,7,2,5,11,9,4,8,13,6,15) and `d` to (0,.15625,.6 For the 3D Voronoi cross-application comparison, also repeat indices 1, 2, 3, 4 and 6 with F32 and zero distortion. Across both tables and 82 original settings, U8 matches **20,028/24,064** (maximum 162), U16 **53,820/57,856** (41,505), F16 **20,028/24,064** (.633056641) and F32 **64,060/68,096** (.633334696). In the shuffled-table random-color case at 32 × 64, 32/2,048 pixels agree in each format. The four roots remain in progress. The writer regression failed on the earlier exporter. All 125 format release tests, formatting, strict workspace Clippy, dependency layers and WebAssembly checks passed. +### Shared pixel assignments in Voronoi color selection + +In a pixel function, both arms of a conditional can use the same assignment, a sequence containing it, or a called function that exports it. MaterialCraft now evaluates that shared expression after the condition and before the selected arm. Uses in two alternatives inside a single arm stay inside that arm. A loop evaluates its own assignments on each iteration. + +For a minimal reproduction, initialize a scalar to .40625. Define one shared expression that stores the horizontal pixel coordinate in the scalar and reads it back. For selector values below .5 return that expression plus 1. For values below 1.5 return half the same expression. Otherwise read the scalar. At the first pixel center of a 16² image the last alternative previously returned .40625. Both applications now return .03125. When the first two alternatives are siblings inside one arm of an outer conditional, the other arm returns .40625. + +Fourteen original graphs used a single assignment, a sequence or a called function, a shared or independent expression in sibling or nested alternatives, and a final read after the conditional. Use selectors 0, 1, 2 and 7 at 16² F32 with seeds 0, 43, 373 and 1921. For spatial conditions substitute three times the vertical pixel coordinate. Seven additional graphs tested an operand outside the branch on either side of an addition, a following sequence, an inner conditional, two ordered writes, a two-iteration loop and a write in the condition. Use 16², 32 × 16, 16 × 32 and 32² F32 with those four selectors, then 32 × 16 U16 at 2, 16 × 32 F16 at 7 and 16² U8 at 2. Add the case index and 31 times the graph index to seed 463361. + +Across the 105 controls the old evaluator matched 22,424/39,424 pixels. U8 matched 712/1,792 with maximum 143, U16 matched 1,344/3,584 with maximum 37887, F16 matched 1,360/3,584 with maximum 0.578125, F32 matched 19,008/30,464 with maximum 0.578125. The current evaluator matches **39,424/39,424**, maximum zero in every format. + +Use the two original U16 lookup tables, 36 settings and five undistorted F32 cases described in the [saved function measurements](#package-ownership-of-saved-function-calls). For each root the 82 original comparisons include both lookup tables and all four output formats. The 24 saved-package comparisons reopen the file in both applications. + +| Root (inventory index) | Distinct settings | U8 exact / total · max | U16 exact / total · max | F16 exact / total · max | F32 exact / total · max | +|---|---:|---:|---:|---:|---:| +| 3D Voronoi (304) | 82 | 24,064/24,064 · 0 | 57,856/57,856 · 0 | 24,064/24,064 · 0 | 68,096/68,096 · 0 | +| 2D Voronoi (306) | 82 | 24,064/24,064 · 0 | 57,856/57,856 · 0 | 24,064/24,064 · 0 | 68,096/68,096 · 0 | + +Each root also matched **57,344/57,344** pixels after saving, with 12,800 U8, 32,256 U16, 4,096 F16 and 8,192 F32 pixels. Maximum error was zero. In the original shuffled-table, 32 × 64 random-color case, the previous evaluator matched 32/2,048 pixels in 3D and 0/2,048 in 2D in each format. Each now matches all 2,048. The 2D and 3D fractal versions also match in that setting with both tables and all four formats, 16,384/16,384 pixels per root. + +For each nonfractal root, 38 further comparisons matched **32,256/32,256**, maximum zero. These include the [seven shuffled-table settings](#voronoi-distortion-and-shared-noise-inputs) and the 16², 32² and signed 16² F32 cases repeated with the affine table. For the other 28 renders, start at index 7 of the 36-setting matrix. Repeat with zero distortion, graph seeds 0 and 37, graph-derived color seed with the original seed and zero, and explicit color seeds 0, 1, 42 and 257. At 16² repeat all seven styles, all four distance modes, with inversion disabled and with zero distortion. Repeat random color on default controls with seed 37 and graph-derived or explicit color seed 1477. + +An independent 3D control used six 1024 × 16 U16 tables filled with 0, 65535, horizontal ramp, vertical ramp, four times the row-major texel index, and the affine table. At 16² F32/seed 37 use the original position field and defaults, random color, explicit color seed 1477, scale 2 with zero disorder, scale 3 with distortion .2, and style 4 with distortion .15. Also repeat random color with the default seed, explicit seed 1477 and zero disorder at scale 1 on constant U16 RGB positions (0,0,0), (32768,16384,32768), (13107,26214,39321) and (65535,65535,65535). All **27,648/27,648** pixels across 108 renders agreed, maximum zero. + +The 2D and 3D nonfractal roots reach measured parity with the same procedural tables in both applications. The [stock-table measurements](#voronoi-distortion-and-shared-noise-inputs) still apply to the separate bundled resources. Three distorted 32² stock renders per root used different table contents. The two fractal roots remain in progress pending the wider comparisons. The shared-assignment release regression failed before the change and passed afterward. All 321 node release tests, formatting, strict workspace Clippy, dependency layers and WebAssembly checks 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 6ef973f2..d702e19c 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -35,7 +35,7 @@ A graph may accept input pins and still be a root under the dependency criterion Statuses: **Not checked**, **In progress**, **Parity** (exact pixels or typed values for the linked measured cases), or **Too hard** (reason recorded). Function calls do not count as regular graph dependencies. -The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **410 Parity**, **136 In progress** and **0 Too hard**. The November 17–21 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons) · [November 19 measurements](parity-fixes.md#2026-11-19-root-comparisons) · [November 20 measurements](parity-fixes.md#2026-11-20-root-comparisons) · [November 21 measurements](parity-fixes.md#2026-11-21-root-comparisons) +The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **412 Parity**, **134 In progress** and **0 Too hard**. The November 17–21 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons) · [November 19 measurements](parity-fixes.md#2026-11-19-root-comparisons) · [November 20 measurements](parity-fixes.md#2026-11-20-root-comparisons) · [November 21 measurements](parity-fixes.md#2026-11-21-root-comparisons) [Pattern tiling axes and copy bounds across 215 renders](parity-fixes.md#tiling-axes-and-pattern-copy-bounds) · [Grayscale sampler measurements](parity-fixes.md#grayscale-sampling-of-color-inputs) · [Value sampling across 240 typed comparisons](parity-fixes.md#value-processor-texture-filtering) · [Five saved graphs reopened in the reference](parity-fixes.md#saved-filter-graphs-and-scalar-levels-controls) @@ -403,10 +403,10 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [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) · [Saved function calls and linked noise packages](parity-fixes.md#package-ownership-of-saved-function-calls) | -| [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) · [Saved function calls and linked noise packages](parity-fixes.md#package-ownership-of-saved-function-calls) | -| [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) · [Saved function calls and linked noise packages](parity-fixes.md#package-ownership-of-saved-function-calls) | -| [noise_voronoi.sbs/voronoi_fractal](../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) · [Saved function calls and linked noise packages](parity-fixes.md#package-ownership-of-saved-function-calls) | +| [noise_voronoi.sbs/3d_voronoi](../assets/sbs/noise_voronoi.sbs) | 1 | No | [Parity · 174,080 exact pixels in 82 shared-lookup renders, bundled defaults differ](parity-fixes.md#shared-pixel-assignments-in-voronoi-color-selection) · [Saved graph comparisons](parity-fixes.md#package-ownership-of-saved-function-calls) · [Stock 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) · [Saved function calls and linked noise packages](parity-fixes.md#package-ownership-of-saved-function-calls) · [Random-color assignments](parity-fixes.md#shared-pixel-assignments-in-voronoi-color-selection) | +| [noise_voronoi.sbs/voronoi](../assets/sbs/noise_voronoi.sbs) | 0 | No | [Parity · 174,080 exact pixels in 82 shared-lookup renders, bundled defaults differ](parity-fixes.md#shared-pixel-assignments-in-voronoi-color-selection) · [Saved graph comparisons](parity-fixes.md#package-ownership-of-saved-function-calls) · [Stock tables](parity-fixes.md#voronoi-distortion-and-shared-noise-inputs) | +| [noise_voronoi.sbs/voronoi_fractal](../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) · [Saved function calls and linked noise packages](parity-fixes.md#package-ownership-of-saved-function-calls) · [Random-color assignments](parity-fixes.md#shared-pixel-assignments-in-voronoi-color-selection) | | [non_square_transform.sbs/non_square_transform](../assets/sbs/non_square_transform.sbs) | 1 | No | [Parity · 204,032 exact pixels in 23 renders](parity-fixes.md#rotated-transforms-and-fractional-texture-coordinates) | | [non_square_transform.sbs/non_square_transform_greyscale](../assets/sbs/non_square_transform.sbs) | 1 | No | [Parity · 204,032 exact pixels in 23 renders](parity-fixes.md#rotated-transforms-and-fractional-texture-coordinates) | | [non_uniform_blur.sbs/non_uniform_blur_grayscale_sample](../assets/sbs/non_uniform_blur.sbs) | 2 | Yes | [Parity · 19 cases, 175,360 exact pixels](parity-fixes.md#directional-warp-orientation-and-input-precision) |