From ba51d9f89dcee7560fce92e9b631055a9f3b1908 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Fri, 20 Nov 2026 04:07:10 -0500 Subject: [PATCH] Resolve omitted numeric arguments and keep function formals read-only --- crates/nodes/src/function/compile.rs | 19 +++++- crates/nodes/src/function/function_call.rs | 2 +- crates/nodes/src/function/program.rs | 17 +++-- crates/nodes/src/function/tests.rs | 79 ++++++++++++++++++++++ docs/parity-fixes.md | 20 ++++++ docs/sbs-root-nodes.md | 2 +- 6 files changed, 130 insertions(+), 9 deletions(-) diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs index 928ed16..34b62a7 100644 --- a/crates/nodes/src/function/compile.rs +++ b/crates/nodes/src/function/compile.rs @@ -1,5 +1,5 @@ use super::{Program, catalog, instruction::Instruction}; -use materialcraft_core::FunctionGraph; +use materialcraft_core::{FunctionGraph, ValueType}; use std::collections::{BTreeMap, BTreeSet}; pub fn compile(graph: &FunctionGraph, seed: u32) -> Result { @@ -154,10 +154,23 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu return Err(format!("{}: input `{}` has the wrong type", instance.graph, port.identifier)); } } - let inputs = ports.iter().filter(|(_, input)| input.is_some()).map(|(name, _)| (*name).to_string()).collect(); + let inputs: Vec<_> = ports.iter().filter(|(_, input)| input.is_some()).map(|(name, _)| (*name).to_string()).collect(); + let mut defaults = instance.defaults.clone(); + if !inputs.is_empty() { + // Once a call supplies arguments, an omitted numeric argument reads its typed zero. + for (name, input) in &ports { + if input.is_none() + && let Some(value) = defaults.get_mut(*name) + && let Some(kind) = ValueType::of(value) + && kind != ValueType::String + { + *value = kind.default_value(); + } + } + } let exports = program.instructions.iter().any(|instruction| instruction.definition.id == "set" || instruction.call.as_ref().is_some_and(|call| call.exports)); - Some(super::function_call::FunctionCall { program, inputs, defaults: instance.defaults.clone(), argument_factors: None, exports }) + Some(super::function_call::FunctionCall { program, inputs, defaults, argument_factors: None, exports }) } else { None }; diff --git a/crates/nodes/src/function/function_call.rs b/crates/nodes/src/function/function_call.rs index 6eb6cc5..8297936 100644 --- a/crates/nodes/src/function/function_call.rs +++ b/crates/nodes/src/function/function_call.rs @@ -31,7 +31,7 @@ impl CallBindings<'_> { } let mut frame = Some(self); while let Some(current) = frame { - if current.caller_assignments.contains_key(name) && current.parent.is_none_or(|parent| !parent.call.defaults.contains_key(name)) { + if current.caller_assignments.contains_key(name) { return true; } frame = current.parent; diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index fea3f13..2751884 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -159,6 +159,12 @@ impl Program { state.steps.push(Store(index)); match instruction.definition.id { + "set" if matches!(&instruction.value, Some(Value::Text(name)) if bindings.is_some_and(|scope| scope.call.defaults.contains_key(name))) => + { + // A formal is read-only. Even side effects in the unused operand are skipped. + let kind = materialcraft_core::ValueType::from_code(instruction.type_code).ok_or("unknown function assignment type")?; + state.values.push(kind.default_value()); + } "ifelse" => { state.steps.push(Branch(index)); state.steps.push(Enter(self.input(index, 0)?)); @@ -213,10 +219,13 @@ impl Program { let result = call.program.run(context, storage, remaining_steps, Some(&child)); state.random = storage.random; if call.exports && result.is_ok() { - // Set publishes into the caller's scope; arguments and defaults stay local - storage.assignments.retain(|name, _| !call.defaults.contains_key(name)); - state.variables.extend(storage.assignments.clone()); - state.assignments.extend(storage.assignments.clone()); + // A free assignment can pass through a caller with a formal of the same name. + for (name, value) in &storage.assignments { + if bindings.is_none_or(|scope| !scope.call.defaults.contains_key(name)) { + state.variables.insert(name.clone(), value.clone()); + } + state.assignments.insert(name.clone(), value.clone()); + } } result diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 3e68495..a152cee 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -1820,6 +1820,85 @@ fn a_loop_evaluates_its_condition_and_body_again_on_every_iteration() { assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3)); } +#[test] +fn writing_a_function_argument_keeps_its_wire_and_a_nested_free_assignment() { + fn call(body: FunctionGraph, argument: &str, wire: Option) -> FunctionGraph { + let mut graph = FunctionGraph::default(); + let input = wire.map(|value| graph.add_constant(Value::Float(value))); + let result = graph.add("instance", &[], None); + let node = graph.nodes.last_mut().unwrap(); + node.instance = Some(materialcraft_core::GraphInstance { + label: String::new(), + package: String::new(), + graph: "assign_scalar".into(), + inputs: vec![materialcraft_core::GraphPort { identifier: argument.into(), type_code: 256 }], + outputs: vec![materialcraft_core::GraphPort { identifier: "output".into(), type_code: 256 }], + defaults: BTreeMap::from([(argument.into(), Value::Float(0.0))]), + }); + node.inputs = vec![input]; + node.source = Some(Ok(std::sync::Arc::new(body))); + graph.output = Some(result); + graph + } + + let mut write = FunctionGraph::default(); + let value = write.add_constant(Value::Float(0.4375)); + write.output = Some(write.add("set", &[value], Some(Value::Text("amount".into())))); + let direct = call(write.clone(), "amount", Some(0.625)); + assert_eq!(evaluate(&direct, &BTreeMap::new()), Ok(Value::Float(0.0))); + + let mut effect = FunctionGraph::default(); + let value = effect.add_constant(Value::Float(0.4375)); + let operand = effect.add("set", &[value], Some(Value::Text("effect".into()))); + effect.output = Some(effect.add("set", &[operand], Some(Value::Text("amount".into())))); + let mut direct = call(effect, "amount", Some(0.625)); + let entered = direct.output.unwrap(); + let read = direct.add("get_float1", &[], Some(Value::Text("effect".into()))); + direct.output = Some(direct.add("sequence", &[entered, read], None)); + assert_eq!(evaluate(&direct, &BTreeMap::new()), Ok(Value::Float(0.0))); + + let mut parent = call(write, "unused", None); + let write = parent.output.unwrap(); + let argument = parent.add("get_float1", &[], Some(Value::Text("amount".into()))); + parent.output = Some(parent.add("sequence", &[write, argument], None)); + let mut outer = call(parent, "amount", Some(0.625)); + let returned = outer.output.unwrap(); + let shared = outer.add("get_float1", &[], Some(Value::Text("amount".into()))); + outer.output = Some(outer.add("vector2", &[returned, shared], None)); + assert_eq!(evaluate(&outer, &BTreeMap::new()), Ok(Value::Float2([0.625, 0.4375]))); +} + +#[test] +fn a_partially_wired_call_reads_typed_zero_from_its_other_numeric_argument() { + let mut body = FunctionGraph::default(); + body.output = Some(body.add("get_float3", &[], Some(Value::Text("position".into())))); + let mut graph = FunctionGraph::default(); + let size = graph.add_constant(Value::Float(0.0)); + let position = graph.add_constant(Value::Float3([-0.25, 0.5, 0.75])); + let call = graph.add("instance", &[], None); + graph.output = Some(call); + let node = graph.nodes.last_mut().unwrap(); + node.instance = Some(materialcraft_core::GraphInstance { + label: String::new(), + package: String::new(), + graph: "read_position".into(), + inputs: vec![ + materialcraft_core::GraphPort { identifier: "size".into(), type_code: 256 }, + materialcraft_core::GraphPort { identifier: "position".into(), type_code: 1024 }, + ], + outputs: vec![materialcraft_core::GraphPort { identifier: "output".into(), type_code: 1024 }], + defaults: BTreeMap::from([("size".into(), Value::Float(0.5)), ("position".into(), Value::Float3([1.0; 3]))]), + }); + node.source = Some(Ok(std::sync::Arc::new(body))); + node.inputs = vec![Some(size), None]; + let variables = BTreeMap::from([("position".into(), Value::Float3([0.875; 3]))]); + assert_eq!(evaluate(&graph, &variables), Ok(Value::Float3([0.0; 3]))); + graph.nodes.last_mut().unwrap().inputs[1] = Some(position); + assert_eq!(evaluate(&graph, &variables), Ok(Value::Float3([-0.25, 0.5, 0.75]))); + graph.nodes.last_mut().unwrap().inputs = vec![None, None]; + assert_eq!(evaluate(&graph, &variables), Ok(Value::Float3([1.0; 3]))); +} + #[test] fn defined_arguments_follow_wires_through_nested_calls() { fn caller(body: FunctionGraph, wired: bool) -> FunctionGraph { diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index d2b2f0d..93303f8 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -510,6 +510,26 @@ Draw an unrotated, white, single stamp on black with maximum blending and no til Every reference Gaussian pixel outside its paired disc was zero in both sweeps, 29,406/29,406 and 127,365/127,365. The probes leave equality at exactly r² = 1 unresolved. The implementation applies the cutoff only above one. Differences in the interior remain. On the earlier whole-root matrices, Alveolus still matches 332,280/334,336 pixels and the pattern variant 201,876/203,264. Their maximum U8/U16/F16/F32 errors are 0/1,000/0/3.05175781e−5 and 0/2/0/1.52587891e−5 respectively. The two brick-generator Tile helpers each retain 114,688/114,688 LUM16 pixels across four renders. The boundary regression failed before the fix. All 262 release node tests, formatting, strict workspace Clippy, layers and WebAssembly passed. +### Numeric arguments in partially wired calls + +The cube intersection in `shape_splatter_compute_normal` declares position (1,1,1). On the shape-2 field that exposed the [wire-presence discrepancy](#wire-presence-inside-a-called-function), leave position open or explicitly wire (0,0,0), (1,1,1) or (.125,−.0625,.25). Keep the other connections and compare both the cube stage and the whole normal output. The reference open and zero cases agree at all 4,608 pixels of each output. Wiring the declared (1,1,1) reproduced the earlier local result. The evaluator now uses the typed zero for omitted numeric arguments when the call has a wire. The 24 comparisons match 36,864/36,864 RGBA32F pixels, maximum error zero. The nine boolean, signed integer and float types covered by the [argument controls](#connectable-numeric-arguments-in-saved-function-graphs) now match in 54/54 typed outputs, maximum error zero. + +A Set targeting the currently called function's own argument returns its typed zero and skips its operand. A Set to a free name in a child can reach an outer caller even when the intervening function has a formal of the same name. Wire .625 to the intervening formal and have the child assign .4375. The intervening function reads .625 and its caller reads .4375. Put another free Set in the operand of a formal assignment and observe it after the call in both a pixel and a value graph. All 5,120/5,120 F32 pixels and 8/8 typed outputs in the operand controls match, maximum error zero. Of the 224 earlier [wire and scope tests](#wire-presence-inside-a-called-function), 220 now match. The four remaining outputs read a wholly open argument with an authored default of .1875. MaterialCraft retains its live source-default behavior for such calls. Separate nested controls also find a free read of an enclosing formal where the reference reads zero. The two new evaluator regressions failed before the changes. All 262 release node tests, strict workspace Clippy, formatting, layers and WebAssembly passed. + +| Whole normal root | Renders | Exact pixels / compared | Maximum finite error | +|---|---:|---:|---:| +| Previous default, changed and precision cases | 19 | 142,592/142,592 | 0 | +| Independent rectangular and stepped fields | 10 | 11,520/11,520, previously 9,811 | 0 | +| Single-setting and displacement controls on the shape-2 field | 31 | 63,488/63,488, previously 32,726 | 0 | +| Twelve shape modes at four output formats | 48 | 48,968/49,152, previously 45,000 | 1.19209290e−7 in F32 | +| Total | 108 | 266,568/266,752 | 1.19209290e−7 | + +The saved graph also matches all 11,520 pixels on the independent fields. The seven saved diagnostic outputs match 34,048/34,048 pixels on the original stage controls. Stored NaN payloads agree on all 26 lanes in the original half-float case, 7,680 lanes on the independent fields, 36,864 in the single-setting controls and 33,792 across the twelve-mode sweep. Each of U8, U16 and F16 matches 12,288/12,288 pixels in the twelve-mode sweep. F32 matches 12,104/12,288. + +To reproduce the twelve-mode sweep, take mode j = 0…11. Cycle output size through 16×32, 32×16, 32×32 and 64×32. For input t = 0…7 and channel c, compute q = ((79x + 173y + 11xy + 109t + 37c + 53j) mod 1021)/1020 and b = (floor(x/3) + 2floor(y/2) + t + c + j) mod 5. Use .8125+.09375q if b=0, .125+.1875q if b=1, otherwise .4375+.125q. In the six RGBA inputs use alpha zero if (x+3y+7t+j) mod 11 is zero, otherwise one if b=2, otherwise .71875+.125q. Store the eight procedural inputs in U8, U16 or F32 according to j mod 3, rounding integer inputs to nearest. For output format index p = 0…3 in U8, U16, F16, F32 order use seed 167057+19j+p. Set the shape to j, normal format to j mod 2, displacement on when j mod 3 = 0, rotation to ((j mod 5)−2)×.0625, extrusion height to .375+j/32, nonsquare expansion on when j mod 4 = 1, pattern count to 1+(j mod 3), and atlas size to (2+(j mod 2),2). + +The one remaining mismatch in this sweep is the 64×32 F32 shape-3 render, with 1,864/2,048 pixels exact. On the same eight inputs, setting only the shape to 3 gives 1,856/2,048 exact. Each of the other eleven modes matches all 2,048 pixels with the same inputs and remaining settings. Across five stage controls the sampled input, active flag, ray distance, atlas index, cube normal and stored object normal each match 10,240/10,240 pixels. The vector before encoding matches 7,372/10,240, maximum error 2.38418579e−7. The root remains in progress. + ## 2026-11-19 root comparisons ### Texture sampling in pattern functions diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index ea035b8..e72d775 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -553,7 +553,7 @@ Reduced Sharpen now matches 16,704/16,704 pixels on the held-out signed field an | [shape_splatter_v2.sbs/mipmap_tools/Mipmap_N_from_O_color](../assets/sbs/shape_splatter_v2.sbs) | 1 | Yes | [Parity · 18 renders, all 287,232 pixels exact](parity-fixes.md#marked-variable-reads-in-path-and-mipmap-graphs) | | [shape_splatter_v2.sbs/poisson_disc/poisson_disc_iteration](../assets/sbs/shape_splatter_v2.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) | | [shape_splatter_v2.sbs/scanline_to_z_order](../assets/sbs/shape_splatter_v2.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) | -| [shape_splatter_v2.sbs/shape_splatter_compute_normal](../assets/sbs/shape_splatter_v2.sbs) | 10 | Yes | [In progress · 152,403/154,112 pixels in 29 renders, shape 2 differs](parity-fixes.md#wire-presence-inside-a-called-function) | +| [shape_splatter_v2.sbs/shape_splatter_compute_normal](../assets/sbs/shape_splatter_v2.sbs) | 10 | Yes | [In progress · 266,568/266,752 pixels across 108 renders, 184 F32 pixels differ on shape 3](parity-fixes.md#numeric-arguments-in-partially-wired-calls) | | [shape_splatter_v2_companion.sbs/shape_splatter_to_mask](../assets/sbs/shape_splatter_v2_companion.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) | | [skew.sbs/skew](../assets/sbs/skew.sbs) | 1 | No | [Parity · 13 cases, 163,840 exact pixels](parity-fixes.md#height-distance-texture-mapping-skew-and-weave) | | [skew.sbs/skew_grayscale](../assets/sbs/skew.sbs) | 1 | No | [Parity · 13 cases, 163,840 exact pixels](parity-fixes.md#height-distance-texture-mapping-skew-and-weave) |