From 1aacaf05263ae0da0fe1efef7b9d3bd7269decc3 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 04:27:58 -0500 Subject: [PATCH] Order first-level spot draws by quadrant and active iteration --- crates/nodes/src/pattern/evaluation.rs | 19 +++- crates/nodes/src/pattern/mod.rs | 1 + .../nodes/src/pattern/repeated_quadrants.rs | 73 ++++++++++++ crates/nodes/src/pattern/tests.rs | 1 + .../src/pattern/tests/repeated_quadrants.rs | 107 ++++++++++++++++++ crates/nodes/src/pattern/tile_runs.rs | 2 +- docs/parity-fixes.md | 20 ++++ docs/sbs-root-nodes.md | 2 +- 8 files changed, 222 insertions(+), 3 deletions(-) create mode 100644 crates/nodes/src/pattern/repeated_quadrants.rs create mode 100644 crates/nodes/src/pattern/tests/repeated_quadrants.rs diff --git a/crates/nodes/src/pattern/evaluation.rs b/crates/nodes/src/pattern/evaluation.rs index de9acad9..10e5cbfc 100644 --- a/crates/nodes/src/pattern/evaluation.rs +++ b/crates/nodes/src/pattern/evaluation.rs @@ -122,6 +122,7 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo let mut remaining = MAX_VISITS; let mut discard_allowance = MAX_VISITS; let grayscale = !context.b("color_mode"); + let mut repeated_roots = None; let mut seven_level_runs = (grayscale && opacity_depth == 7).then(SevenLevelRuns::default); let mut sparse_runs = if grayscale && opacity_depth == 8 { super::tile_runs::SparseQuadrantRuns::new(context) } else { None }; let mut mixed_depth_runs = if grayscale && matches!(opacity_depth, 8 | 9) { MixedDepthRuns::new(context, opacity_depth) } else { None }; @@ -241,6 +242,12 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo match node.kind { PatternNodeKind::Dot => {} PatternNodeKind::Quadrant => { + if visit.depth == 0 + && let Some(active) = &mut repeated_roots + { + // A switch on the repeated branch may omit an entire quadrant tree. + *active += 1; + } let offset = vector("branchoffset"); visit.center = [visit.center[0] + offset[0], visit.center[1] + offset[1]]; if image_pattern { @@ -336,6 +343,13 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo PatternNodeKind::Iterate => { let count = u32::try_from(integer("numberadded")).map_err(|_| "iteration count cannot be negative")?; + if grayscale + && Some(node.id) == graph.root + && node.children.first() == Some(&None) + && !graph.nodes.iter().any(|other| other.id != node.id && other.kind == PatternNodeKind::Iterate) + { + repeated_roots = Some(0_usize); + } if let Some(Some(child)) = node.children.first() { let mut first = visit.clone(); first.node = *child; @@ -399,6 +413,9 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo groups[0] = prefix; } let groups = groups.map(super::pattern_stamp::DrawRun::whole); - let mixed_groups = mixed_depth_runs.and_then(|runs| runs.finish(&stamps)).or_else(|| sparse_runs.and_then(|runs| runs.finish(&stamps))); + let mixed_groups = mixed_depth_runs + .and_then(|runs| runs.finish(&stamps)) + .or_else(|| sparse_runs.and_then(|runs| runs.finish(&stamps))) + .or_else(|| repeated_roots.and_then(|repeats| super::repeated_quadrants::runs(context, &stamps, repeats, max_depth))); Ok(vec![raster::render(context, mixed_groups.as_deref().unwrap_or(&groups), opacities, nonfinite_gray_opacity, base_level_only, runtime_image_selector)?]) } diff --git a/crates/nodes/src/pattern/mod.rs b/crates/nodes/src/pattern/mod.rs index f01bdee6..b8022e32 100644 --- a/crates/nodes/src/pattern/mod.rs +++ b/crates/nodes/src/pattern/mod.rs @@ -9,6 +9,7 @@ mod pattern_stamp; mod pattern_visit; mod raster; mod region; +mod repeated_quadrants; mod shape; mod tile_runs; mod variables; diff --git a/crates/nodes/src/pattern/repeated_quadrants.rs b/crates/nodes/src/pattern/repeated_quadrants.rs new file mode 100644 index 00000000..fea545cb --- /dev/null +++ b/crates/nodes/src/pattern/repeated_quadrants.rs @@ -0,0 +1,73 @@ +use super::{ + footprint::Footprint, + pattern_stamp::{DrawRun, PatternStamp}, + region::Region, + tile_runs::COPIES_PER_BATCH, +}; +use crate::CookContext; + +pub(super) fn runs<'a>(context: &CookContext, stamps: &'a [PatternStamp], repeats: usize, depth: u32) -> Option>> { + if !(6..=10).contains(&depth) || repeats == 0 { + return None; + } + let first_level = repeats.checked_mul(4)?; + if first_level > COPIES_PER_BATCH as usize || first_level > stamps.len() { + return None; + } + let first = stamps.iter().find(|stamp| stamp.depth == 1)?; + if !(2..=16).contains(&first.pattern) { + return None; + } + + let axes = context.tiling_axes(); + let render = Region::new(context.v4("render_region")).ok()?; + let tiling = Region::tiling(context.v4("tiling_region"), axes, context.b("cull_outside")).ok()?; + let mut submitted = 0_u64; + let mut indices = Vec::with_capacity(first_level); + for (index, stamp) in stamps.iter().enumerate() { + if stamp.depth == 0 { + return None; + } + if stamp.depth == 1 { + if stamp.pattern != first.pattern || stamp.blend != 0 || indices.len() == first_level { + return None; + } + let frame = Footprint::new(stamp).ok()?; + let center = tiling.copy_origin(stamp.center, axes); + let [x, y] = tiling.repeats(&render, center, frame.radius, axes).ok()?; + submitted = submitted.checked_add(x.count.checked_mul(y.count)?)?; + if submitted > u64::from(COPIES_PER_BATCH) { + return None; + } + indices.push(index); + } else if stamp.pattern == first.pattern { + // A shared shape also needs the submission order of its deeper draws. + return None; + } + } + // Without a nested Iterate, four retained first-level stamps per repetition + // account for every child, including the two slots belonging to the lower row. + if indices.len() != first_level { + return None; + } + + // Other shapes keep their relative order. The raster sorts each shape separately. + let mut runs = Vec::new(); + let mut start = 0; + for &index in &indices { + if start < index { + runs.push(DrawRun::whole(stamps.get(start..index)?)); + } + start = index + 1; + } + if let Some(rest) = stamps.get(start..).filter(|rest| !rest.is_empty()) { + runs.push(DrawRun::whole(rest)); + } + for slot in (0..4).rev() { + for iteration in indices.as_chunks::<4>().0 { + let index = *iteration.get(slot)?; + runs.push(DrawRun::whole(stamps.get(index..=index)?)); + } + } + Some(runs) +} diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index eac4a602..0695d68c 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -3,6 +3,7 @@ use materialcraft_core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}; use std::collections::BTreeMap; mod paired_batches; +mod repeated_quadrants; mod sparse_quadrants; fn coverage(shape: i32, x: f32, y: f32, variation: f32) -> f32 { diff --git a/crates/nodes/src/pattern/tests/repeated_quadrants.rs b/crates/nodes/src/pattern/tests/repeated_quadrants.rs new file mode 100644 index 00000000..e1f692d0 --- /dev/null +++ b/crates/nodes/src/pattern/tests/repeated_quadrants.rs @@ -0,0 +1,107 @@ +use super::*; +use materialcraft_core::OutputFormat; + +fn select_iteration(graph: &mut FunctionGraph, number: u32, iteration: i32, gain: f32, otherwise: u32) -> u32 { + let expected = graph.add_constant(Value::Float(iteration as f32)); + let selected = graph.add("eq", &[number, expected], None); + let value = graph.add_constant(Value::Float(gain)); + graph.add("ifelse", &[selected, value, otherwise], None) +} + +fn field(slot: usize, markers: [i32; 3], negative: f32, positive: f32) -> Value { + let mut graph = FunctionGraph::default(); + let number = graph.add("get_float1", &[], Some(Value::Text("$number".into()))); + let zero = graph.add_constant(Value::Float(0.0)); + let result = match slot { + 0 => select_iteration(&mut graph, number, markers[0], negative, zero), + 1 => { + let later = select_iteration(&mut graph, number, markers[1], positive, zero); + select_iteration(&mut graph, number, markers[0], negative, later) + } + 3 => select_iteration(&mut graph, number, markers[2], positive, zero), + _ => zero, + }; + graph.output = Some(result); + Value::Function(Box::new(graph)) +} + +fn active_iterations(iterations: &[i32]) -> Value { + let mut graph = FunctionGraph::default(); + let number = graph.add("get_float1", &[], Some(Value::Text("$number".into()))); + let mut selected = graph.add_constant(Value::Bool(false)); + for &iteration in iterations { + let value = graph.add_constant(Value::Float(iteration as f32)); + let matches = graph.add("eq", &[number, value], None); + selected = graph.add("or", &[selected, matches], None); + } + graph.output = Some(selected); + Value::Function(Box::new(graph)) +} + +#[test] +fn deep_repeated_quadrants_submit_first_level_shapes_by_slot_then_iteration() { + let definition = find("fx_map").unwrap(); + let tiny = f32::EPSILON * 0.25; + let sparse = [2, 6]; + let four = [0, 3, 5, 8]; + for (depth, repeats, active) in [(5, 2, &[][..]), (6, 2, &[][..]), (10, 4, &[][..]), (5, 9, &sparse), (6, 9, &sparse), (9, 9, &[0, 1]), (10, 9, &four)] { + let markers = if active.is_empty() { [0, 1, repeats - 1] } else { [active[0], active[1], active[active.len() - 1]] }; + for reversed in [false, true] { + let (negative, positive) = if reversed { (tiny, -1.0) } else { (-1.0, tiny) }; + let mut graph = PatternGraph::with_root(PatternNodeKind::Iterate); + let first = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[0].parameters.insert("numberadded".into(), Value::Int(repeats)); + let branch = if active.is_empty() { + first + } else { + let switch = graph.add(PatternNodeKind::Switch).unwrap(); + let node = &mut graph.nodes[(switch - 1) as usize]; + node.children[1] = Some(first); + node.parameters.insert("switch".into(), active_iterations(active)); + switch + }; + graph.nodes[0].children[1] = Some(branch); + let mut next = None; + for _ in 2..=depth { + let id = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[(id - 1) as usize].children[0] = next; + next = Some(id); + } + for (slot, offset) in [[0.0, 0.0], [0.0, 0.0], [0.5, -0.5], [-0.5, -0.5]].into_iter().enumerate() { + let id = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[(first - 1) as usize].children[slot] = Some(id); + let node = &mut graph.nodes[(id - 1) as usize]; + node.children[0] = next; + node.parameters = additive_square(0.0, [0.0; 2], offset); + node.parameters.insert("patternsize".into(), Value::Float2([0.125; 2])); + node.parameters.insert("opacity".into(), field(slot, markers, negative, positive)); + } + let params = resolve_params( + definition, + &BTreeMap::from([ + ("pattern".into(), Value::PatternGraph(Box::new(graph))), + ("roughness".into(), Value::Float(0.0)), + ("color_mode".into(), Value::Bool(false)), + ("background".into(), Value::Color([1.0; 4])), + ]), + ); + let vars = BTreeMap::from([("$tiling".into(), Value::Int(0))]); + let context = CookContext { + w: 32, + h: 32, + seed: 200153, + format: OutputFormat::F32, + tile: false, + inputs: &[], + input_formats: &[], + params: ¶ms, + resource: &|_| None, + vars: &vars, + }; + let output = (definition.cook)(&context).unwrap().remove(0); + let left = if (depth < 6) != reversed { tiny } else { 0.0 }; + let right = if reversed { 0.0 } else { tiny }; + assert_eq!([output.get_gray(8, 8, false), output.get_gray(24, 8, false)], [left, right], "depth {depth}, repeats {repeats}, reversed {reversed}"); + } + } +} diff --git a/crates/nodes/src/pattern/tile_runs.rs b/crates/nodes/src/pattern/tile_runs.rs index a603ec79..f65b0baa 100644 --- a/crates/nodes/src/pattern/tile_runs.rs +++ b/crates/nodes/src/pattern/tile_runs.rs @@ -20,7 +20,7 @@ const DEPTH_FOUR_PARENTS: usize = 64; const PAIRED_SUBTREE_PARENTS: usize = 2 * DEPTH_THREE_PARENTS; const FIRST_PAIR_END: usize = 48 * DEPTH_THREE_PARENTS + PAIRED_SUBTREE_PARENTS; // Paired interior squares change order when the preceding draws fill 5,460 tile copies. -const COPIES_PER_BATCH: u32 = 5460; +pub(super) const COPIES_PER_BATCH: u32 = 5460; pub(super) struct TileCopies { window: Region, diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 82567c39..2711e55e 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -266,6 +266,26 @@ For the regression, use the [same square tree and per-subtree distribution](#ind All nine horizontal generator settings now match 175,104/175,104 pixels, gaining 19,043 exact pixels. The untiled and neighboring generator controls match 525,312/525,312. Both-axis tiling still matches 42,464/175,104, maximum 1.34110451e−7. Across the [111 whole-root settings](#individual-tile-copies-after-two-full-horizontal-batches), one processor matches 2,862,824/2,863,360 pixels and eight match 2,862,731/2,863,360. Maximum error is zero in U8, two codes in U16, .00048828125 in F16 and 1.96099281e−5 or 2.03251839e−5 in F32 on one or eight processors respectively. For 28 reopened whole-root settings, both applications reproduce their original buffers and agree with each other on 430,274/430,336 pixels. Dirt Gradient remains in progress. All 434 node and evaluator release tests passed, together with formatting, strict workspace Clippy, dependency layers and WebAssembly. +### First-level draw order in repeated spot quadrants + +Number the four children of a quadrant from zero in traversal order. In a repeated tree with a unique first-level shape, the shape draws in child order 3, 2, 1, 0 once the visited subdivision depth reaches six. Each child retains ascending iteration order. Depths one through five retain traversal order. A switch can skip a whole tree within the repeated branch. Count the root quadrants that are visited when dividing the first-level draws into groups of four. The measured implementation covers depths six through ten, a single root iterator without an initial branch, four retained first-level additive shapes per active iteration, and at most 5,460 first-level tile copies. A shape also used by deeper draws needs its joint submission order. + +Use an original white F32 canvas with square marks at (.25,.25) and (.75,.25). Give the first mark −1 on child 0 in the first active iteration and 2⁻²⁵ on child 3 in the last. At the second mark use child 1 for both gains in the first and second active iterations. Swap both gains and repeat. Use 32² at seed 200153 and 64 × 32 at seed 200363. Compare depths 5 and 6 with two repetitions and depth 10 with four. Repeat depth 6 with eight reference processors. All 16 images match 24,576/24,576 pixels. For nine requested repetitions, use active iterations 2 and 6 at depths 5 and 6, iterations 0 and 1 at depth 9, and 0, 3, 5 and 8 at depth 10. Repeat the two gain assignments, sizes and eight-processor depth-six controls. All 20 images match 30,720/30,720 pixels. The prior renderer returned 2⁻²⁵ on the first deep readout where the reference returned zero. Using the requested iteration count also failed the nine-repetition regression. + +At 128², give every first-level stamp an individually addressable destination and sign. Compare adjacent pairs in both gain assignments. Sweep depths one through ten and repeat counts from one through eight, then 16, 32, 64 and 128. The widest case distinguishes 512 stamps. Place additional small, nonzero shapes outside the readout, including four-way descendants down to depth seven. Across six such controlled configurations at depths 3, 6 and 10, all 48 F32 images match 786,432/786,432 pixels. In the first Noise BNW Spots 1 graph, isolate the first-level shape while retaining the deeper branch structure. The five completed F32 settings improve from 6,178/8,192 to 8,192/8,192. At 64 × 32 with scale 3, the diagnostic graph exceeds the visit budget after its deeper shapes are disabled. With all shapes enabled, all six diagnostics render and agree on 8,618/10,240 pixels, maximum 2.38418579e−7. Reopen the five completed isolates and six gated-square settings from MaterialCraft saves. Both applications reproduce their own pixels and agree on 17,408/17,408. + +For the whole-root comparison, recapture the 62 distinct settings from the existing default, precision, seed, scale, roughness and disorder sweeps. Add a four-size series at 16 × 32, 64 × 32, 32 × 64 and 64². Start with defaults, then set scale to 3, 1, 2 and both disorder and roughness to .34375, .1875, .53125. Enable non-square expansion on the two middle sizes. Use seed 194395 + 47j for zero-based row j. Render U16 and F32 at every size, adding U8 and F16 at the middle sizes. Include the separate 12-format series at 16 × 32, 32 × 16, 32² and 64 × 32, with defaults then disorder .34375, .78125 and .5625, scale 1, 2 and 1, and roughness .25 + .625 × disorder. Its seeds are zero then 153113 + 37 × 236 + 109j. Compare defaults and changed controls at their declared output dimensions. [Earlier spot-graph sweeps](#connected-quadrant-depth-and-amplified-spot-patterns) + +| Comparison | U8 exact / total · max | U16 exact / total · max | F16 exact / total · max | F32 exact / total · max | +|---|---:|---:|---:|---:| +| One processor | 108,800/108,800 · 0 | 328,291/328,448 · 1 | 108,798/108,800 · 0.00048828125 | 236,852/295,680 · 3.57627869e−7 | +| Eight processors | 108,799/108,800 · 1 | 328,292/328,448 · 1 | 108,800/108,800 · 0 | 242,269/295,680 · 2.38418579e−7 | +| Saved packages, one processor | 90,112/90,112 · 0 | 93,670/93,696 · 1 | 6,400/6,400 · 0 | 5,902/6,144 · 2.38418579e−7 | + +All 86 distinct whole-root settings render. The one-processor result gains 57,860 exact pixels, reaching 782,741/841,728. Eight processors gain 58,793, reaching 788,160/841,728. The maximum single-processor F32 difference increases from 2.38418579e−7 to 3.57627869e−7. MaterialCraft reproduces all 196,352 of its original pixels across 19 reopened settings. The reference reproduces 196,348/196,352, maximum 5.96046448e−8. The two applications agree on 196,084/196,352 reopened pixels. The joint order of the deeper shape draws remains open. + +In eight interleaved single-processor release measurements, render the 32² scale-2 setting at seed 113, the 16 × 32 default and the 64² changed setting. Median total process CPU time for the three cooks, including package loading and readback, changed from 12.203 to 12.469 seconds. All 435 node and evaluator release tests passed together with formatting, strict workspace Clippy, dependency layers and WebAssembly. + ## 2026-11-21 root comparisons ### Connected quadrant depth and amplified spot patterns diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index a01742d9..2ee27706 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -359,7 +359,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [multiangle_to_normal.sbs/angle_weight](../assets/sbs/multiangle_to_normal.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) | | [noise_anisotropic_noise.sbs/anisotropic_noise](../assets/sbs/noise_anisotropic_noise.sbs) | 0 | Yes | [Parity · 18 renders, all 171,264 pixels exact](parity-fixes.md#quarter-turn-directional-blur) | | [noise_anisotropic_noise_v2.sbs/anisotropic_noise_v2](../assets/sbs/noise_anisotropic_noise_v2.sbs) | 0 | No | [Parity · 18 renders, all 171,264 pixels exact](parity-fixes.md#high-pass-anisotropic-noise-and-triangle-grid-controls) | -| [noise_bnw_spots_1.sbs/bnw_spots_1](../assets/sbs/noise_bnw_spots_1.sbs) | 0 | Yes | [In progress · 642,601/796,672 pixels across 60 distinct settings](parity-fixes.md#connected-quadrant-depth-and-amplified-spot-patterns) · [Zero roughness exact in U16 and F32](parity-fixes.md#grayscale-pattern-output-at-zero-roughness) · [Draw order, 18 changed-format comparisons](parity-fixes.md#draw-order-for-overlapping-procedural-grayscale-stamps) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) | +| [noise_bnw_spots_1.sbs/bnw_spots_1](../assets/sbs/noise_bnw_spots_1.sbs) | 0 | Yes | [In progress · 782,741/841,728 pixels on one processor, 788,160/841,728 on eight across 86 settings](parity-fixes.md#first-level-draw-order-in-repeated-spot-quadrants) · [Earlier 60-setting comparison](parity-fixes.md#connected-quadrant-depth-and-amplified-spot-patterns) · [Zero roughness exact in U16 and F32](parity-fixes.md#grayscale-pattern-output-at-zero-roughness) · [Draw order, 18 changed-format comparisons](parity-fixes.md#draw-order-for-overlapping-procedural-grayscale-stamps) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) | | [noise_bnw_spots_1_v2.sbs/bnw_spots_1](../assets/sbs/noise_bnw_spots_1_v2.sbs) | 0 | No | [In progress · 752,311/760,832 pixels across 55 distinct settings](parity-fixes.md#connected-quadrant-depth-and-amplified-spot-patterns) · [Zero roughness exact in U16 and F32](parity-fixes.md#grayscale-pattern-output-at-zero-roughness) · [Draw order, 18 changed-format comparisons](parity-fixes.md#draw-order-for-overlapping-procedural-grayscale-stamps) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) | | [noise_bnw_spots_3.sbs/bnw_spots_3](../assets/sbs/noise_bnw_spots_3.sbs) | 0 | Yes | [In progress · 32² now exact, 64² precision differences](parity-fixes.md#deep-pattern-samples-in-custom-render-and-tiling-regions) · [Earlier matrix](parity-fixes.md#bnw-spots-3-and-cells-1-pattern-sources) · [64² precision and remaining traversal limits](parity-fixes.md#precision-of-two-dense-noise-generators-in-custom-regions) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) | | [noise_bnw_spots_3_v2.sbs/bnw_spots_3](../assets/sbs/noise_bnw_spots_3_v2.sbs) | 0 | No | [In progress · 106,559/107,776 pixels, 13 execution-limit cases](parity-fixes.md#bnw-spots-3-and-cells-1-pattern-sources) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) · [bounded stage counts at scale two](parity-fixes.md#four-cloud-noise-generators-and-repeated-saved-file-comparisons) |