diff --git a/crates/nodes/src/function/evaluation_state.rs b/crates/nodes/src/function/evaluation_state.rs index 3e2ff0db..c18b0a65 100644 --- a/crates/nodes/src/function/evaluation_state.rs +++ b/crates/nodes/src/function/evaluation_state.rs @@ -32,3 +32,47 @@ impl EvaluationState { &self.assignments } } + +/// A loop can change the random stream, the variables it writes and the assignments its caller sees. +pub(crate) struct LoopCheckpoint { + random: crate::random::FunctionRandom, + writes: Vec<(String, Value, Option)>, +} + +impl LoopCheckpoint { + pub(super) fn capture(state: &EvaluationState) -> Option> { + let mut writes = Vec::with_capacity(state.assignments.len()); + for (name, value) in &state.assignments { + let visible = state.variables.get(name); + materialcraft_core::ValueType::of(value)?; + if let Some(visible) = visible { + materialcraft_core::ValueType::of(visible)?; + } + writes.push((name.clone(), value.clone(), visible.cloned())); + } + Some(Box::new(Self { random: state.random, writes })) + } + + pub(super) fn unchanged(&self, state: &EvaluationState) -> bool { + self.random == state.random + && self.writes.len() == state.assignments.len() + && self.writes.iter().zip(&state.assignments).all(|((name, written, visible), (current, value))| { + name == current && same_loop_value(Some(written), Some(value)) && same_loop_value(visible.as_ref(), state.variables.get(name)) + }) + } +} + +fn same_loop_value(left: Option<&Value>, right: Option<&Value>) -> bool { + match (left, right) { + (None, None) => true, + (Some(a), Some(b)) if std::mem::discriminant(a) == std::mem::discriminant(b) => match a { + // A later operation can distinguish signed zero or inspect a float's bits. + Value::Float(_) | Value::Float2(_) | Value::Float3(_) | Value::Float4(_) | Value::Color(_) => { + a.as_vec4().map(|v| v.map(f32::to_bits)) == b.as_vec4().map(|v| v.map(f32::to_bits)) + } + Value::Bool(_) | Value::Int(_) | Value::Int2(_) | Value::Int3(_) | Value::Int4(_) | Value::Text(_) | Value::Enum(_) => a == b, + _ => false, + }, + _ => false, + } +} diff --git a/crates/nodes/src/function/evaluation_step.rs b/crates/nodes/src/function/evaluation_step.rs index 03765b37..e9cd0efb 100644 --- a/crates/nodes/src/function/evaluation_step.rs +++ b/crates/nodes/src/function/evaluation_step.rs @@ -1,5 +1,7 @@ use materialcraft_core::Value; +use super::evaluation_state::LoopCheckpoint; + pub(crate) enum EvaluationStep { Enter(usize), Store(usize), @@ -8,6 +10,6 @@ pub(crate) enum EvaluationStep { Discard, Sequence(usize), LoopStart(usize), - LoopCondition { instruction: usize, iteration: u32, last: Value }, - LoopBody { instruction: usize, iteration: u32 }, + LoopCondition { instruction: usize, iteration: u32, last: Value, checkpoint: Option> }, + LoopBody { instruction: usize, iteration: u32, checkpoint: Option> }, } diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index 7b0282c9..a6040551 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -353,24 +353,31 @@ impl Program { let last = materialcraft_core::ValueType::from_code(self.instruction(index)?.type_code) .map_or(initializer, materialcraft_core::ValueType::default_value); self.clear_loop_results(index, state)?; - state.steps.push(LoopCondition { instruction: index, iteration: 0, last }); + state.steps.push(LoopCondition { instruction: index, iteration: 0, last, checkpoint: None }); state.steps.push(Enter(self.input(index, 1)?)); } - LoopCondition { instruction: index, iteration, last } => { + LoopCondition { instruction: index, iteration, last, checkpoint } => { let exit = value_type::boolean(&state.values.pop().ok_or("missing loop condition")?)?; let maximum = self.instruction(index)?.value.as_ref().and_then(Value::as_i32).unwrap_or(super::DEFAULT_LOOP_LIMIT); - if exit || (maximum >= 0 && iteration >= maximum as u32) { + if exit || (maximum >= 0 && iteration >= maximum as u32) || checkpoint.is_some_and(|previous| previous.unchanged(state)) { state.values.push(last); } else { + // Compare consecutive visits at exponentially spaced intervals. A finite loop + // in identical state repeats the same body and condition up to its declared end. + let checkpoint = if maximum > 0 && (maximum as u32).saturating_sub(iteration) > 1 && iteration.is_power_of_two() { + super::evaluation_state::LoopCheckpoint::capture(state) + } else { + None + }; self.clear_loop_results(index, state)?; - state.steps.push(LoopBody { instruction: index, iteration: iteration.saturating_add(1) }); + state.steps.push(LoopBody { instruction: index, iteration: iteration.saturating_add(1), checkpoint }); state.steps.push(Enter(self.input(index, 2)?)); } } - LoopBody { instruction: index, iteration } => { + LoopBody { instruction: index, iteration, checkpoint } => { let last = state.values.pop().ok_or("missing loop body result")?; self.clear_loop_results(index, state)?; - state.steps.push(LoopCondition { instruction: index, iteration, last }); + state.steps.push(LoopCondition { instruction: index, iteration, last, checkpoint }); state.steps.push(Enter(self.input(index, 1)?)); } } diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index a88db775..6d5daf65 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -1708,6 +1708,60 @@ fn loops_recompute_state_and_have_a_budget() { assert!(evaluate(&graph, &BTreeMap::new()).unwrap_err().contains("budget")); } +#[test] +fn finite_loop_returns_the_settled_value_and_preserves_its_assignments() { + let mut graph = FunctionGraph::default(); + let zero = graph.add_constant(Value::Int(0)); + let one = graph.add_constant(Value::Int(1)); + let limit = graph.add_constant(Value::Int(5)); + let never = graph.add_constant(Value::Bool(false)); + let counter = Some(Value::Text("counter".into())); + let init = graph.add("set", &[zero], counter.clone()); + let read = graph.add("get_integer1", &[], counter.clone()); + let increment = graph.add("add", &[read, one], None); + let bounded = graph.add("min", &[increment, limit], None); + let write = graph.add("set", &[bounded], counter.clone()); + let result = graph.add("while", &[init, never, write], Some(Value::Int(65_536))); + graph.output = Some(result); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(5)); + + let after = graph.add("get_integer1", &[], counter); + graph.output = Some(graph.add("sequence", &[result, after], None)); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(5)); +} + +#[test] +fn finite_loop_distinguishes_the_sign_of_zero_in_its_state() { + let mut graph = FunctionGraph::default(); + let zero = graph.add_constant(Value::Float(0.0)); + let never = graph.add_constant(Value::Bool(false)); + let sign = Some(Value::Text("sign".into())); + let init = graph.add("set", &[zero], sign.clone()); + let value = graph.add("get_float1", &[], sign.clone()); + let negate = graph.add("neg", &[value], None); + let write = graph.add("set", &[negate], sign); + graph.output = Some(graph.add("while", &[init, never, write], Some(Value::Int(65)))); + let result = evaluate(&graph, &BTreeMap::new()).unwrap().as_f32().unwrap(); + assert_eq!(result.to_bits(), (-0.0_f32).to_bits()); +} + +#[test] +fn finite_loop_preserves_each_random_draw_with_a_constant_body_result() { + let mut graph = FunctionGraph::default(); + let one = graph.add_constant(Value::Float(1.0)); + let never = graph.add_constant(Value::Bool(false)); + let draw = graph.add("rand", &[one], None); + let body = graph.add("sequence", &[draw, one], None); + let result = graph.add("while", &[one, never, body], Some(Value::Int(65))); + let next_draw = graph.add("rand", &[one], None); + graph.output = Some(graph.add("sequence", &[result, next_draw], None)); + let mut expected = crate::random::FunctionRandom::uniform(7); + for _ in 0..65 { + expected.draw(); + } + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(expected.draw())); +} + #[test] fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() { let mut graph = FunctionGraph::constant(Value::Float(1.0)); diff --git a/crates/nodes/src/random.rs b/crates/nodes/src/random.rs index 5c3ff562..970aea7b 100644 --- a/crates/nodes/src/random.rs +++ b/crates/nodes/src/random.rs @@ -1,4 +1,4 @@ -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] pub(crate) struct FunctionRandom { state: u32, multiplier: u32, diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index c2ab4bdb..c21adfc0 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -1856,6 +1856,29 @@ Independently author a function with a two-, three- or four-channel slider argum Each application reproduced its own original buffers after reopening all 14 packages. Four earlier families covering scalar calls, channel arithmetic, swizzles and conditionals retain their original per-render counts and maxima. Across the 958 recorded settings for roots 373–376, 441, 488 and 491, all per-render counts and maxima are unchanged. Color Tile Generator still matches 621,344/765,184 pixels across 331 settings. Its per-channel tint order remains open. The packed-argument regression reproduced the wrong sequence with a color-widget default. All 418 node and evaluator release tests and the formatting, workspace Clippy, layer and WebAssembly checks passed. +### Finite loops that reach a fixed point in path-length graphs + +A finite function loop can reach a state that repeats on every remaining iteration. At a pair of consecutive condition checks the evaluator compares the random stream, the written variable names, the values visible inside the function and the assignments visible to its caller. Identical state gives the same subsequent body and condition. The evaluator returns the last body result. It samples these pairs at powers of two to avoid copying state on every iteration of a changing loop. Float comparisons preserve the component bits, including the sign of zero. + +For a small reproduction of [the path-length cases](#skipped-loops-and-path-buffers), start with a zero RGBA F32 image. At (0,0) store (1,1/W,1/H,1/W) and at (1,0) store (N+1,1,1,1/W), where W and H are the input dimensions. On row 1 use the first N positions of (.21875,.34375), (.75,.390625), (.640625,.796875), (.390625,.84375), (.125,.546875), then duplicate the first position. Set blue to 1 and alpha to −.25 for the first point, −.125 for the duplicate and −1 for interior points. Use (W,H,N) of (4,4,1), (4,4,2), (8,8,3) and (16,16,5). Set scale to (1.25,.8125). Test no passthrough with intermediate lengths off and on at F32, passthrough with intermediate lengths on at F32, then intermediate lengths on with passthrough off at U16, F16 and U8. The seed is 128101 + 11N + the zero-based setting index. + +In the 8² three-vertex test, the reference header at (1,0) stores 3.816796064376831. Starting at iteration 1, the observed cursor and sampled position are both (0,0). The length, sampled texel and exported assignments are identical on consecutive visits. MaterialCraft gives the same F32 word at this pixel with an experimental cap of 1, 2, 3, 4, 8, 16, 32 or 64. The authored loop allows 65,536 iterations. A selected-pixel trace also found continuing sums in the resized-input cases below. + +For an independent field use (W,H,N) of (4,8,2), (8,4,3), (8,16,4), (16,8,5), (16,16,7) and (32,16,8). In geometry j from zero, set vertex h to (((11h²+9h+5j+13) mod 101)/112, ((7h²+19h+13j+7) mod 109)/128). Retain the same header, alpha flags and duplicated closing vertex. Test defaults at F32, intermediate lengths on with passthrough off and scale (.6875+.03125j,1.4375−.0625j) at all four formats, and passthrough on with intermediate lengths on at F32. Use seed 129011 + 61j + 7m, with modes m = 0, 1, 2. Independently wire geometries 0, 2 and 4 through parent graphs at all four output formats. + +| Whole path-length graph | Attempted | Earlier comparable | Earlier exact pixels / compared · max | Current comparable | Current exact pixels / compared · max | +|---|---:|---:|---:|---:|---:| +| Previously published direct inputs | 9 | 9 | 774/774 · 0 | 9 | 774/774 · 0 | +| Transformed vertices with a 16² source | 6 | 1 | 256/256 · 0 | 1 | 256/256 · 0 | +| Path headers at the requested size | 6 | 0 | 0/0 · 0 | 6 | 8,448/8,448 · 0 | +| One, two, three and five distinct vertices | 24 | 15 | 228/228 · 0 | 24 | 1,764/1,764 · 0 | +| Independent square and rectangular path buffers | 36 | 14 | 838/838 · 0 | 36 | 5,446/5,446 · 0 | +| Three independently authored graph parents | 12 | 4 | 128/128 · 0 | 12 | 1,664/1,664 · 0 | + +Across the 93 settings, 45 formerly rejected renders now match. All 18,352 compared pixels match, with maximum zero. Five renders still exceed the execution budget when a 16² seven-vertex input is resized for 32² or 64² output. At (1,0) in the 32² F32 case the reference stores 75,845.5859375. The running sum changes across iterations here. An error image supplies no comparable samples. + +The full saved package retains its nested graph and input connections. Both applications reproduced their respective originals in ten reopened settings (2,161/2,161 cross-application pixels, maximum 0). Three saved parents add 12 reopened settings (1,664/1,664 pixels, maximum 0). The previously captured finite and skipped loop controls retain 28/28 exact typed values and 10,240/10,240 exact pixel values. Three regressions cover a settled counter, a constant body result with advancing random draws and alternating signed zero. All 421 node and evaluator release tests passed, along with formatting, strict workspace Clippy, dependency layers and WebAssembly. + ## 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 17e40173..275887d2 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -465,7 +465,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [panorama_straighten_horizon.sbs/panorama_straighten_horizon](../assets/sbs/panorama_straighten_horizon.sbs) | 1 | No | [Parity · 26 renders, all 212,480 pixels exact](parity-fixes.md#panoramic-line-light-and-horizon-across-the-seam) | | [paper_path.sbs/paper_path](../assets/sbs/paper_path.sbs) | 0 | Yes | [Parity · 446,720/446,720 pixels across 45 distinct settings](parity-fixes.md#reopened-paper-fiber-gaussian-and-shape-generators) | | [parquet_1.sbs/parquet_1](../assets/sbs/parquet_1.sbs) | 0 | Yes | [Parity · 25 renders, 289,024 exact pixels](parity-fixes.md#parquet-1-and-outstanding-inventory-controls) | -| [paths_tools.sbs/Impl/compute_paths_lengths](../assets/sbs/paths_tools.sbs) | 1 | Yes | [In progress · 1,029 exact pixels, intermediate lengths reach the execution limit](parity-fixes.md#skipped-loops-and-path-buffers) | +| [paths_tools.sbs/Impl/compute_paths_lengths](../assets/sbs/paths_tools.sbs) | 1 | Yes | [In progress · 18,352/18,352 exact pixels in 88 of 93 settings, five resized buffers exceed the work budget](parity-fixes.md#finite-loops-that-reach-a-fixed-point-in-path-length-graphs) | | [paths_tools.sbs/Impl/facets_to_paths_impl_link_template](../assets/sbs/paths_tools.sbs) | 1 | Yes | [Parity · 18 renders, all 57,600 pixels exact](parity-fixes.md#marked-variable-reads-in-path-and-mipmap-graphs) | | [paths_tools.sbs/Impl/facets_to_paths_impl_stitch_template](../assets/sbs/paths_tools.sbs) | 1 | Yes | [Parity · 18 renders, all 57,600 pixels exact](parity-fixes.md#marked-variable-reads-in-path-and-mipmap-graphs) | | [paths_tools.sbs/Impl/get_number_of_valid_paths](../assets/sbs/paths_tools.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |