Keep discarded pattern branches lazy under compile-time conditions

This commit is contained in:
chasse20 committed 2026-11-27 01:04:19 -05:00
1 parent 84aa71a6c2
commit 02f2e7dbf8
6 files changed
+138 -16

No files matched your search

+5 -1
View File
@@ -62,7 +62,11 @@ fn shared_inputs(
let mut effects = Vec::new();
let mut plans = BTreeMap::new();
for (branch, op) in instructions.iter().enumerate().filter(|(i, op)| op.definition.id == "ifelse" && !excluded.contains(i)) {
let &[_, yes, no] = op.inputs.as_slice() else { continue };
let &[condition, yes, no] = op.inputs.as_slice() else { continue };
// A branch folded before a stamp runs cannot schedule draws from its discarded arm.
if components.is_some() && instructions[condition].pattern_literal {
continue;
}
paths.fill(0);
effects.clear();
// Record the order of first use through each arm.
@@ -230,3 +230,78 @@ fn a_later_random_call_preserves_the_draws_in_a_sequence_assignment() {
}
}
}
#[test]
fn a_pattern_conditional_with_a_literal_test_leaves_unused_draws_for_later() {
// A stored choice shares an expression with a later use. Only the inner switch is exposed.
for (reversed, unwired) in [(false, false), (true, false), (false, true)] {
let mut graph = FunctionGraph::default();
let name = Some(Value::Text("chosen".into()));
let inner = graph.add("get_bool", &[], Some(Value::Text("inner".into())));
let one = graph.add_constant(Value::Float(1.0));
let [a, t, e] = std::array::from_fn(|_| graph.add("rand", &[one], None));
let fallback = graph.add_constant(Value::Float(0.3125));
let theta = graph.add("ifelse", &[inner, t, fallback], None);
let shared = graph.add("add", &[a, theta], None);
let fixed = graph.add_constant(Value::Float(0.1875));
let choice = if reversed {
let yes = graph.add_constant(Value::Bool(true));
graph.add("ifelse", &[yes, fixed, shared], None)
} else {
let low = if unwired { graph.add("get_float1", &[], Some(Value::Text("outer".into()))) } else { graph.add_constant(Value::Float(0.25)) };
let high = graph.add_constant(Value::Float(0.5));
let no = graph.add("gt", &[low, high], None);
graph.add("ifelse", &[no, shared, fixed], None)
};
let saved = graph.add("set", &[choice], name.clone());
let read = graph.add("get_float1", &[], name);
let half = graph.add_constant(Value::Float(0.5));
let quarter = graph.add_constant(Value::Float(0.25));
let eighth = graph.add_constant(Value::Float(0.125));
let next = graph.add("mul", &[e, half], None);
let later = graph.add("mul", &[shared, quarter], None);
let value = graph.add("mul", &[read, eighth], None);
let sum = graph.add("add", &[next, later], None);
let result = graph.add("add", &[sum, value], None);
graph.output = Some(graph.add("sequence", &[saved, result], None));
if unwired {
let callee = std::mem::take(&mut graph);
let inner = graph.add("get_bool", &[], Some(Value::Text("inner".into())));
graph.output = Some(graph.add("instance", &[inner], None));
let call = graph.nodes.last_mut().unwrap();
call.inputs.insert(0, None);
call.instance = Some(materialcraft_core::GraphInstance {
graph: "nested_choice".into(),
label: String::new(),
package: String::new(),
inputs: vec![
materialcraft_core::GraphPort { identifier: "outer".into(), type_code: 256 },
materialcraft_core::GraphPort { identifier: "inner".into(), type_code: 4 },
],
outputs: Vec::new(),
defaults: BTreeMap::from([("outer".into(), Value::Float(0.0)), ("inner".into(), Value::Bool(false))]),
});
call.source = Some(Ok(std::sync::Arc::new(callee)));
}
for (seed, words) in [(11_038_009, [0x3e570414, 0x3e64b294]), (9_766_418, [0x3ee92f65, 0x3f171545]), (22_858_730, [0x3f30619c, 0x3f365b11])] {
let program = compile(&graph, seed).unwrap();
for (flag, word) in [false, true].into_iter().zip(words) {
let variables = BTreeMap::from([("inner".into(), Value::Bool(flag))]);
let context = EvaluationContext {
scope: FunctionScope::FxMap,
position: [0.5; 2],
size: [16.0; 2],
images: &[],
image_formats: &[],
tile: true,
variables: &variables,
};
assert_eq!(
program.evaluate(&context, &mut EvaluationState::default()).unwrap(),
Value::Float(f32::from_bits(word)),
"{seed}, {flag}, {reversed}, {unwired}"
);
}
}
}
}
+33 -13
View File
@@ -19,7 +19,7 @@ pub(super) fn compile_program(
) -> Result<Program, String> {
let mut remaining = super::MAX_EXPANDED_NODES;
let mut program = compile_nested(graph, seed, 0, &mut remaining)?;
mark_literals(&mut program, literal_inputs.iter().map(|name| (name.as_str(), ())).collect());
mark_literals(&mut program, literal_inputs.iter().map(|name| (name.as_str(), Constant::Literal)).collect());
super::reciprocal::identify_products(&mut program, BTreeMap::new());
plan_pixel_operations(&mut program, pixel, true);
super::assigned_product::identify(&mut program);
@@ -127,6 +127,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
value: Some(value),
type_code,
literal: true,
pattern_literal: true,
literal_divisor: false,
reciprocal_factor: None,
pixel_product_sum: None,
@@ -267,24 +268,43 @@ pub(super) fn remove_written_arguments<T>(program: &Program, arguments: &mut BTr
}
}
fn mark_literals(program: &mut Program, mut arguments: BTreeMap<&str, ()>) {
// A pure expression is fixed only as far as its least constant operand.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Constant {
Varying,
PatternDefault,
Literal,
}
fn mark_literals(program: &mut Program, mut arguments: BTreeMap<&str, Constant>) -> Constant {
remove_written_arguments(program, &mut arguments);
let mut literals = Vec::with_capacity(program.instructions.len());
for op in &mut program.instructions {
let literal = |index: &usize| literals.get(*index) == Some(&true);
let source = |index: &usize| literals.get(*index).copied().unwrap_or(Constant::Varying);
let id = op.definition.id;
op.literal_divisor = id == "div" && op.inputs.get(1).is_some_and(literal);
if let Some(call) = &mut op.call {
let bound = call.inputs.iter().zip(&op.inputs).filter(|(_, index)| literal(index)).map(|(name, _)| (name.as_str(), ())).collect();
mark_literals(&mut call.program, bound);
op.literal = call.program.output_is_literal();
op.literal_divisor = id == "div" && op.inputs.get(1).is_some_and(|i| source(i) == Constant::Literal);
let constant = if let Some(call) = &mut op.call {
let mut bound: BTreeMap<_, _> = call.defaults.keys().map(|name| (name.as_str(), Constant::PatternDefault)).collect();
for (name, input) in call.inputs.iter().zip(&op.inputs) {
bound.insert(name.as_str(), source(input));
}
mark_literals(&mut call.program, bound)
} else if id.starts_with("const_") {
Constant::Literal
} else if id.starts_with("get_")
&& let Some(materialcraft_core::Value::Text(name)) = &op.value
{
arguments.get(name.as_str()).copied().unwrap_or(Constant::Varying)
} else if op.depends_only_on_operands() {
op.inputs.iter().map(source).min().unwrap_or(Constant::Varying)
} else {
op.literal = id.starts_with("const_")
|| (id.starts_with("get_") && matches!(&op.value, Some(materialcraft_core::Value::Text(name)) if arguments.contains_key(name.as_str())))
|| (op.depends_only_on_operands() && op.inputs.iter().all(literal));
}
literals.push(op.literal);
Constant::Varying
};
op.literal = constant == Constant::Literal;
op.pattern_literal = constant != Constant::Varying;
literals.push(constant);
}
literals.get(program.output).copied().unwrap_or(Constant::Varying)
}
fn plan_pixel_operations(program: &mut Program, pixel: Option<&super::EvaluationContext<'_>>, root: bool) -> super::returned_product::Lanes {
+3
View File
@@ -9,6 +9,8 @@ pub(crate) struct Instruction {
pub type_code: u32,
/// Pure expression with only literal inputs. Its arithmetic rounds before pixel evaluation.
pub literal: bool,
/// A pattern condition also folds when its inputs come from unwired function arguments.
pub(super) pattern_literal: bool,
/// A constant denominator folds to its rounded reciprocal even with a varying numerator.
pub(super) literal_divisor: bool,
/// Original scalar divisor retained when a pixel expression divides by its reciprocal.
@@ -30,6 +32,7 @@ impl Instruction {
value,
type_code,
literal: false,
pattern_literal: false,
literal_divisor: false,
reciprocal_factor: None,
pixel_product_sum: None,
+20
View File
@@ -59,6 +59,26 @@ The first pass classifies all 546 roots: 166 Parity and 380 Too hard. These meas
## 2026-11-27 root comparisons
### Compile-time conditions before a shared pattern draw
A quadrant can use the same random value in an optional assignment and in a later calculation. With a compile-time condition, the discarded arm consumes no draws. If the condition reads an exposed variable, the reference can schedule the shared value while it evaluates the assignment. An unwired argument of a called function behaves as a constant in this comparison. MaterialCraft now keeps this distinction when compiling pattern branches.
Use a full-coverage additive square over black at 16² F32. Give its opacity function three separate Random(1) nodes A, T and E. Form L = A + (inner ? T : .3125). In the first input of a Sequence, store S = outer ? L : .1875. In the second, return (E × .5 + L × .25) + S × .125. Render both inner switch values at seeds 0, 113 and 137. Keep the pattern seed offset at its default. For the direct and called forms of T use Random(1) and a zero-argument function returning that draw. For the packed form, pack A and the inner result as Float2, then sum X and Y.
| F32 cases | Settings | Earlier exact pixels | Earlier max error | Current exact pixels on each route | Current max error |
|---|---:|---:|---:|---:|---:|
| Folded condition on a direct or called draw | 12 | 1,536/3,072 | 0.143974781 | 3,072/3,072 | 0 |
| Reversed literal, negation and constant comparison | 18 | 0/4,608 | 0.143974781 | 4,608/4,608 | 0 |
| Literal wire, open argument and constant-returning call | 18 | 0/4,608 | 0.143974781 | 4,608/4,608 | 0 |
| Exposed or partly exposed condition | 24 | 3,072/6,144 | 0.151002526 | 3,072/6,144 | 0.151002526 |
| Nested exposed conditions | 48 | 7,680/12,288 | 0.151002526 | 7,680/12,288 | 0.151002526 |
For the fixed conditions, use literal false, swap arms with literal true, negate literal true, or compare .25 > .5. In a called function test its scalar outer argument with > .5 and pass literal zero, leave it open at its zero default, or wire a function returning literal zero. For exposed controls use a public outer value, or AND it with false in each operand order. Exercise both exposed switches in the direct, called and packed forms. The originals on one processor, on eight and the one-processor reopens of ordinary MaterialCraft saves gave identical reference words.
At seed 113, with the inner switch off, a fixed outer condition yields F32 word `3ee92f65`. An outer condition reading a public value yields `3f19b678` when it takes the same arm. With the inner switch on, the words are `3f171545` and `3f3bbfde`. The 48 fixed settings rose from 1,536 to **12,288/12,288** pixels. Both exposed series still have differences in the order of draws across nested choices.
The two older circular roots retained 190,720/190,720 pixels apiece in 62 settings per root. The two roots in `pattern_splatter_circular.sbs` retained 13/54 exact settings each. The 221 grayscale Tile Generator settings and 175 archived settings on 35 other qualified roots retained 1,350,656/1,350,656 pixels. The 141 stored-vector cases, 90 pure-call controls and raw output words of 56 Pixel Processor programs also held. [Whole circular comparisons](#circular-splatter-geometry-and-the-order-of-random-draws) · [Older circular color settings](#splatter-circular-color-and-assignments-before-a-later-function-call)
### Splatter Circular Color and assignments before a later function call
Splatter Circular Color in `splatter_circular.sbs` matches all **190,720/190,720** pixels in **62 distinct whole settings**, up from 185,121 pixels and 31 complete settings at `4080c38`. Both reference processor counts and the one-processor reopen of the ordinary MaterialCraft SBS save gave the counts below. The 19 established reference captures reproduced their archives in 142,592/142,592 pixels. The grayscale root retained 190,720/190,720 across its own 62 settings on all three routes.
+2 -2
View File
@@ -593,8 +593,8 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug
| [pattern_polygon_2.sbs/polygon_2](../assets/sbs/pattern_polygon_2.sbs) | 0 | No | [Parity · 332,032/332,032 pixels across 39 distinct settings](parity-fixes.md#reopened-gaussian-polygon-and-weave-pattern-generators) · [Earlier measurements](parity-fixes.md#paper-brick-fiber-mesh-polygon-and-shape-roots) |
| [pattern_shape.sbs/hemisphere](../assets/sbs/pattern_shape.sbs) | 0 | No | [Parity · 25 settings, 173,568/173,568 original and reopened pixels exact](parity-fixes.md#graph-output-size-functions-and-signed-offsets) |
| [pattern_shape.sbs/shape_base](../assets/sbs/pattern_shape.sbs) | 0 | Yes | [Parity · 68 settings, 344,064/344,064 original and reopened pixels exact](parity-fixes.md#graph-output-size-functions-and-signed-offsets) |
| [pattern_splatter_circular.sbs/splatter_circular](../assets/sbs/pattern_splatter_circular.sbs) | 7 | No | [In progress · 179,684/186,368 exact pixels across 54 settings on both processor counts and ordinary saves](parity-fixes.md#circular-splatter-geometry-and-the-order-of-random-draws) · [Earlier comparison · 130,917/132,096 exact pixels in 9 renders](parity-fixes.md#other-roots-using-uniform-arc-tangents) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_splatter_circular.sbs/splatter_circular_color](../assets/sbs/pattern_splatter_circular.sbs) | 7 | No | [In progress · 175,089/186,368 exact pixels across 54 settings on both processor counts and ordinary saves](parity-fixes.md#circular-splatter-geometry-and-the-order-of-random-draws) · [Earlier comparison · 130,678/132,096 exact pixels in 9 renders](parity-fixes.md#other-roots-using-uniform-arc-tangents) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_splatter_circular.sbs/splatter_circular](../assets/sbs/pattern_splatter_circular.sbs) | 7 | No | [In progress · 179,684/186,368 exact pixels across 54 settings on both processor counts and ordinary saves](parity-fixes.md#circular-splatter-geometry-and-the-order-of-random-draws) · [Compile-time and public switch comparisons](parity-fixes.md#compile-time-conditions-before-a-shared-pattern-draw) · [Earlier comparison · 130,917/132,096 exact pixels in 9 renders](parity-fixes.md#other-roots-using-uniform-arc-tangents) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_splatter_circular.sbs/splatter_circular_color](../assets/sbs/pattern_splatter_circular.sbs) | 7 | No | [In progress · 175,089/186,368 exact pixels across 54 settings on both processor counts and ordinary saves](parity-fixes.md#circular-splatter-geometry-and-the-order-of-random-draws) · [Compile-time and public switch comparisons](parity-fixes.md#compile-time-conditions-before-a-shared-pattern-draw) · [Earlier comparison · 130,678/132,096 exact pixels in 9 renders](parity-fixes.md#other-roots-using-uniform-arc-tangents) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_stripes.sbs/stripes](../assets/sbs/pattern_stripes.sbs) | 0 | No | [Parity · 762,880/762,880 pixels across 83 distinct settings](parity-fixes.md#pixel-ratio-in-rectangular-directional-filters) |
| [pattern_tile_generator.sbs/tile_generator](../assets/sbs/pattern_tile_generator.sbs) | 7 | No | [Parity · 757,504/757,504 pixels across 221 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#beveled-square-gradient-and-wave-stamps) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) · [conditional draws and returned channels](parity-fixes.md#shared-random-draws-in-pattern-branches-and-returned-color-channels) · [packed arguments and returned draws](parity-fixes.md#returned-channels-of-a-packed-argument-in-pattern-functions) |
| [pattern_tile_generator.sbs/tile_generator_color](../assets/sbs/pattern_tile_generator.sbs) | 7 | No | [In progress · 621,344/765,184 pixels across 331 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) · [conditional draws and returned channels](parity-fixes.md#shared-random-draws-in-pattern-branches-and-returned-color-channels) · [packed arguments and returned draws](parity-fixes.md#returned-channels-of-a-packed-argument-in-pattern-functions) |