diff --git a/crates/nodes/src/pattern/evaluation.rs b/crates/nodes/src/pattern/evaluation.rs index 19e8b815..cda74889 100644 --- a/crates/nodes/src/pattern/evaluation.rs +++ b/crates/nodes/src/pattern/evaluation.rs @@ -46,6 +46,34 @@ struct TerminalSiblings { discarded: bool, } +fn uniform_deep_draws(root: Option, nodes: &PatternNodes) -> bool { + let mut pending: Vec<_> = root.into_iter().map(|id| (id, 0_u8)).collect(); + let mut seen = BTreeSet::new(); + let mut order = None; + while let Some((id, depth)) = pending.pop() { + if !seen.insert((id, depth)) { + continue; + } + let Some(&(node, _, _)) = nodes.get(&id) else { return false }; + let quadrant = node.kind == PatternNodeKind::Quadrant; + if quadrant { + let literal = |name: &str| node.parameters.get(name).map_or(Some(0), Value::as_i32); + let Some(shape) = literal("patterntype") else { return false }; + if shape != 0 { + // A drawing first-level quadrant can require reordering across outer iterations. + let Some(blend @ 0..=2) = literal("blendingmode") else { return false }; + let rank = (shape, blend != 0); + if depth < 2 || !(2..=16).contains(&shape) || *order.get_or_insert(rank) != rank { + return false; + } + } + } + let child_depth = (depth + u8::from(quadrant)).min(2); + pending.extend(node.children.iter().flatten().map(|&child| (child, child_depth))); + } + order.is_some() +} + fn quadrant_mode(kind: PatternNodeKind, name: &str) -> bool { kind == PatternNodeKind::Quadrant && matches!(name, "patterntype" | "blendingmode" | "imagefiltering" | "imagepremul" | "randominherited") } @@ -281,6 +309,10 @@ fn evaluate(context: &CookContext, base_level_only: &[bool], visit_limit: usize, let mut remaining = visit_limit; let mut discard_allowance = visit_limit; let mut full_evaluations = visit_limit.saturating_mul(5); + let mut stream_allowance = visit_limit; + let stream_chunk = (visit_limit / 4).clamp(1, 4_096); + let mut uniform_order = None; + let mut raster_work = raster::RasterWork::new(); let grayscale = !context.b("color_mode"); let mut repeated_roots = None; let mut repeated_six_level: Option = None; @@ -491,7 +523,7 @@ fn evaluate(context: &CookContext, base_level_only: &[bool], visit_limit: usize, } // Evaluate every property before discarding a stamp. Its assignments can reach // later visits. Keep the first stamp so raster setup still validates depth weights. - let missed = !stamps.is_empty() && grid.as_ref().is_some_and(|grid| grid.misses(&stamp)); + let missed = (!stamps.is_empty() || raster_work.background.is_some()) && grid.as_ref().is_some_and(|grid| grid.misses(&stamp)); if underfilled .as_mut() .is_some_and(|runs| !runs.draw(&stamp, opacities.as_deref().unwrap_or_default(), grid.as_ref(), stamps.len(), !missed)) @@ -628,6 +660,27 @@ fn evaluate(context: &CookContext, base_level_only: &[bool], visit_limit: usize, discard_allowance -= 1; remaining += 1; } + // Once every subtree ordering has been ruled out, equal-ranked analytic stamps can be + // composited immediately in traversal order. Reuse their storage and preserve all F32 adds. + if stamps.len() >= stream_chunk + && max_depth > 6 + && mixed_depth_runs.is_none() + && terminal_quadrants.is_none() + && sparse_runs.is_none() + && underfilled.is_none() + && seven_level_runs.is_none() + && repeated_six_level.is_none() + && *uniform_order.get_or_insert_with(|| uniform_deep_draws(graph.root, &nodes)) + { + let released = stamps.len().min(stream_allowance); + raster_work.credit_streamed_stamps(released); + let group = [super::pattern_stamp::DrawRun::whole(&stamps)]; + let image = raster::render(context, &group, &opacities, nonfinite_gray_opacity, base_level_only, runtime_image_selector, &mut raster_work)?; + raster_work.background = Some(image); + stream_allowance -= released; + remaining = remaining.saturating_add(released); + stamps.clear(); + } if children.len() + pending.len() + usize::from(repeated.is_some()) > remaining { return Err("pattern graph exceeded its execution budget".into()); } @@ -674,7 +727,14 @@ fn evaluate(context: &CookContext, base_level_only: &[bool], visit_limit: usize, .or_else(|| underfilled.and_then(|runs| runs.finish(&stamps))) .or_else(|| repeated_six_level.and_then(|runs| runs.finish(&stamps, repeated_roots.unwrap_or_default()))) .or_else(|| repeated_roots.and_then(|repeats| super::repeated_quadrants::runs(context, &stamps, repeats, max_depth))); - let image = - raster::render(context, mixed_groups.as_deref().unwrap_or(&groups), opacities, nonfinite_gray_opacity, base_level_only, runtime_image_selector)?; + let image = raster::render( + context, + mixed_groups.as_deref().unwrap_or(&groups), + &opacities, + nonfinite_gray_opacity, + base_level_only, + runtime_image_selector, + &mut raster_work, + )?; Ok((image, variables.bound_draw)) } diff --git a/crates/nodes/src/pattern/raster.rs b/crates/nodes/src/pattern/raster.rs index 4f5ff552..72b269e6 100644 --- a/crates/nodes/src/pattern/raster.rs +++ b/crates/nodes/src/pattern/raster.rs @@ -18,17 +18,37 @@ const MAX_SAMPLES: u64 = 256_000_000; const MAX_STAMP_COPIES: u64 = 1_048_576; pub(super) const MIN_STAMP_SIZE: f32 = 1e-8; +pub(super) struct RasterWork { + pub background: Option, + samples_left: u64, + copies_left: u64, +} + +impl RasterWork { + pub fn new() -> Self { + Self { background: None, samples_left: MAX_SAMPLES, copies_left: MAX_STAMP_COPIES } + } + + pub fn credit_streamed_stamps(&mut self, stamps: usize) { + // A released stamp covers one copy. Extra tile copies share the original cook-wide allowance. + self.copies_left = self.copies_left.saturating_add(stamps as u64); + } +} + pub(super) fn render( context: &CookContext, groups: &[DrawRun<'_>], - opacities: Result, String>, + opacities: &Result, String>, nonfinite_gray_opacity: bool, base_level_only: &[bool], runtime_image_selector: bool, + work: &mut RasterWork, ) -> Result { let (width, height) = craft_texture::clamp_size(context.w, context.h); let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; - let background = if context.input(0).is_some_and(|image| image.kind() != kind) { + let background = if let Some(previous) = work.background.take() { + previous + } else if context.input(0).is_some_and(|image| image.kind() != kind) { Image::filled(width, height, kind, [0.0; 4]) } else { resized_input(context, 0, InputResize::PatternBackground).unwrap_or_else(|| { @@ -44,14 +64,12 @@ pub(super) fn render( } let channels = kind.channels(); - let opacities = opacities?; + let opacities = opacities.as_ref().map_err(Clone::clone)?; let integer_sampling = background.integer_sampling(); let mut data = Arc::clone(background.shared_data()); drop(background); let pixels = Arc::make_mut(&mut data); - let mut budget = MAX_SAMPLES; - let mut copies_left = MAX_STAMP_COPIES; let render_region = Region::new(context.v4("render_region"))?; let span = render_region.period(); let pixel_size = [span[0] / width as f32, span[1] / height as f32]; @@ -149,7 +167,7 @@ pub(super) fn render( if selected == 0 { continue; } - copies_left = copies_left.checked_sub(selected).ok_or("pattern repetition exceeds its budget")?; + work.copies_left = work.copies_left.checked_sub(selected).ok_or("pattern repetition exceeds its budget")?; let columns = repeats[0].centers(); let mut copy = 0_u64; 'rows: for y_center in repeats[1].centers() { @@ -168,7 +186,7 @@ pub(super) fn render( if samples == 0 { continue; } - budget = budget.checked_sub(samples).ok_or("pattern rendering exceeded its pixel budget")?; + work.samples_left = work.samples_left.checked_sub(samples).ok_or("pattern rendering exceeded its pixel budget")?; let planes = PixelPlanes::new(&frame, &render_region, center, stamp.size, [width, height]); if let Some(sampler) = &mut texture { sampler.start_copy(); diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index 36c2fa48..b9e2c14a 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -1890,6 +1890,34 @@ fn terminal_quadrants_charge_the_first_discard_of_each_sibling_group() { assert!(render_with_visit_limit(&graph, 64).unwrap_err().contains("execution budget")); } +#[test] +fn streamed_analytic_draws_keep_the_accumulated_pixels_and_bounded_work() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + for _ in 0..6 { + let parent = graph.nodes.len() - 1; + let child = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[parent].children[0] = Some(child); + } + let outer = graph.add(PatternNodeKind::Iterate).unwrap(); + let inner = graph.add(PatternNodeKind::Iterate).unwrap(); + let square = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[6].children[0] = Some(outer); + graph.nodes[7].children[1] = Some(inner); + graph.nodes[8].children[1] = Some(square); + graph.nodes[7].parameters.insert("numberadded".into(), Value::Int(4)); + graph.nodes[8].parameters.insert("numberadded".into(), Value::Int(24)); + let leaf = &mut graph.nodes[9].parameters; + leaf.insert("patterntype".into(), Value::Int(2)); + leaf.insert("patternsize".into(), Value::Float2([512.0; 2])); + leaf.insert("opacity".into(), Value::Float(0.01)); + let expected = (0..96).fold(0.0_f32, |background, _| background + 0.01_f32); + assert_eq!(render_with_visit_limit(&graph, 256).unwrap()[0].data(), &[expected; 16]); + assert_eq!(render_with_visit_limit(&graph, 64).unwrap()[0].data(), &[expected; 16]); + + graph.nodes[7].parameters.insert("numberadded".into(), Value::Int(12)); + assert!(render_with_visit_limit(&graph, 64).unwrap_err().contains("execution budget")); +} + #[test] fn repeated_terminal_misses_cover_uncached_misses_in_the_next_branch() { let mut graph = PatternGraph::with_root(PatternNodeKind::Iterate); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index e3e802bd..ef0659cb 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -59,6 +59,32 @@ The first pass classifies all 546 roots: 166 Parity and 380 Too hard. These meas ## 2026-11-26 root comparisons +### Streaming equal-ranked analytic stamps through one output image + +Directional Noise 3 now renders 17 of the first 19 established whole-graph settings. Revision `3d3aec1` rendered 15 of those 19. The two recovered settings both use seed zero and U16. For the changed setting, set scale to 2, disorder to .37, angle to .125 and angle random to .2. Leave every other exposed parameter at its default. Save each setting normally, reopen it directly in both applications and capture the one-processor reference again. Each saved file gave the same raw MaterialCraft output as its source. [Earlier whole-graph comparison](#reused-properties-across-adjacent-groups-of-terminal-quadrants) + +| Recovered setting | Original on one · maximum | Original on eight · maximum | Ordinary save on one · maximum | +|---|---:|---:|---:| +| 256², defaults | 65,371/65,536 · 2 | 65,406/65,536 · 3 | 65,358/65,536 · 3 | +| 128², changed | 16,345/16,384 · 2 | 16,350/16,384 · 2 | 16,339/16,384 · 2 | + +Recook all 19 starting settings. At both processor counts, compare to the raw output at the requested storage precision. All eight settings recovered in the previous evaluator change kept their raw MaterialCraft pixels. The remaining F32 settings that exceed the execution budget are 64 × 32, seed 103858, and 32², seed 103860. For the first, use scale 2, disorder .6875, non-square expansion on, angle −.21875 and angle random .40625. For the second, use scale 3, disorder .125, non-square expansion off, angle .375 and angle random .03125. + +| Storage | Completed settings | One processor · maximum | Eight processors · maximum | +|---|---:|---:|---:| +| U8 | 2 | 5,120/5,120 · 0 | 5,120/5,120 · 0 | +| U16 | 7 | 121,539/121,856 · 2 | 121,590/121,856 · 3 | +| F16 | 3 | 7,167/7,168 · 0.000244140625 | 7,168/7,168 · 0 | +| F32 | 5 | 7,383/7,424 · 2.7358532e−05 | 7,410/7,424 · 2.65836716e−05 | + +Across those 17 completed outputs, 141,209/141,568 pixels matched on one processor and 141,288/141,568 on eight. Five and six whole buffers respectively were exact. + +The shared evaluator can composite deep analytic draws in chunks once it has ruled out every subtree ordering and verified a single draw rank throughout the reachable graph. A chunk retains the F32 output image for the next chunk. Pixel and tile-copy work is counted across the entire render. Released draws receive bounded credit against the traversal and copy limits. The regression uses seven empty quadrants followed by two nested iterations. Four outer iterations of 24 additive full-coverage squares agree bit-for-bit at work allowances of 64 and 256. The earlier evaluator rejected the allowance of 64. Twelve outer iterations still exceed that allowance. + +For the independent depth and storage control, attach 80 × 70 iterations beneath seven empty quadrants. Each iteration emits two successive square quadrants, the second on the first child slot of the first. Disable tiling. Use a .125 background, roughness zero, opacity one, sizes (512,512) for both squares and scalar tint expressions 2⁻¹³ and −2⁻¹⁴. In the second graph use (128,128) for the child. For the RGBA control use that smaller child and swatches (.25,.5,.75,2⁻¹³) and (.75,.25,.5,2⁻¹⁴). In each graph render 16² with seed 19 and 32 × 16 with seed 113 in U8, U16, F16 and F32. Reopen ordinary saves in both applications. The grayscale graphs matched 12,288/12,288 pixels and the RGBA graph matched 6,144/6,144 against the reference and the prior release. Maximum error was zero across all 48 buffers. + +On the 128² default, alternate the earlier and changed single-worker release runners in A/B/B/A order, starting each cook in a new process. All four raw buffers were identical. Median process peak working set was 232.5 MiB before and 184.4 MiB after, a reduction of 20.7%. Median cook durations were 15.13 s and 15.17 s. + ### Two depth-seven draws at a stored rounding boundary At (30,57) in Noise BNW Spots 3, the two applications evaluate both contributing stamps to exactly the same F32 values. The order of their additions explains the one-level U16 difference. Use 64², scale 2, disorder .37, seed 42 and the other exposed defaults. Read the deep pattern directly with F32 storage. Its background is .5. Keep the pattern geometry and set the tints to zero on the depths outside the group under test. [Original and repeated whole-graph observations](#reusing-terminal-quadrant-properties-in-dense-rectangular-renders) diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index a4ee262a..c1a479a4 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -43,7 +43,7 @@ Six upstream filters now match 27,648/27,648 original and 27,648/27,648 reopened Dirt 3 and Dirt Gradient have each produced all 60 established originals across the recorded passes. A signed pair of depth-seven contributions isolates the stable one-level Spots 3 difference at (30,57). [Dirt-family comparisons](parity-fixes.md#rectangular-dirt-family-settings-recovered-by-the-shared-evaluator) · [Spots 3 draw order](parity-fixes.md#two-depth-seven-draws-at-a-stored-rounding-boundary) -Directional Noise 3 now renders 15 of the first 19 whole settings. Directional Noise 1 v2 renders all 60 originals and all 12 ordinary saves. Both still have pixel differences. [Recovered Directional Noise 3 settings](parity-fixes.md#reused-properties-across-adjacent-groups-of-terminal-quadrants) · [Complete Directional Noise 1 v2 comparison](parity-fixes.md#complete-render-coverage-in-the-second-version-of-directional-noise-1) +Directional Noise 3 now renders 17 of the first 19 whole settings. Of 141,568 completed pixels, 141,209 matched on one processor and 141,288 on eight. [Storage breakdown and two ordinary saves](parity-fixes.md#streaming-equal-ranked-analytic-stamps-through-one-output-image) Directional Noise 1 v2 renders all 60 originals and all 12 ordinary saves. Both still have pixel differences. [Recovered Directional Noise 3 settings](parity-fixes.md#reused-properties-across-adjacent-groups-of-terminal-quadrants) · [Complete Directional Noise 1 v2 comparison](parity-fixes.md#complete-render-coverage-in-the-second-version-of-directional-noise-1) Noise BNW Spots 3 v2 renders two more originals and one more ordinary save at 128 × 512. Noise Clouds 1 now renders all 60 originals and 15 saves, with 43, 37 and 9 complete images exact on the one-processor, eight-processor and reopened comparisons respectively. [Tall Spots 3 v2 render](parity-fixes.md#sample-coverage-of-narrow-and-circular-quadrant-stamps) · [Complete Clouds 1 comparison](parity-fixes.md#complete-rectangular-render-coverage-in-the-first-clouds-graph) @@ -444,7 +444,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [noise_directional_noise_1_v2.sbs/directional_noise_1](../assets/sbs/noise_directional_noise_1_v2.sbs) | 0 | No | [In progress · 60/60 originals and 12/12 saves render, 626,333/734,464 original pixels on one processor and 633,052 on eight](parity-fixes.md#complete-render-coverage-in-the-second-version-of-directional-noise-1) · [Earlier comparison · 56/60 whole settings rendered, 618,970/726,272 pixels on one processor, 625,683 on eight](parity-fixes.md#sixty-whole-settings-for-three-directional-and-dirt-noise-packages) · [Earlier comparison · 133,251/142,592 pixels in 18 comparable renders](parity-fixes.md#directional-noise-and-scratch-pattern-sources) | | [noise_directional_noise_2.sbs/directional_noise_2](../assets/sbs/noise_directional_noise_2.sbs) | 0 | Yes | [In progress · 103,497/107,776 pixels in 11 comparable renders](parity-fixes.md#directional-noise-and-scratch-pattern-sources) | | [noise_directional_noise_2_v2.sbs/directional_noise_2](../assets/sbs/noise_directional_noise_2_v2.sbs) | 0 | No | [In progress · 105,116/107,776 pixels in 11 comparable renders](parity-fixes.md#directional-noise-and-scratch-pattern-sources) | -| [noise_directional_noise_3.sbs/directional_noise_3](../assets/sbs/noise_directional_noise_3.sbs) | 0 | Yes | [In progress · 15/19 original settings have rendered, eight additional settings and three ordinary saves compared](parity-fixes.md#reused-properties-across-adjacent-groups-of-terminal-quadrants) · [Earlier comparison · 7/19 whole renders completed, 7,168/7,424 exact pixels](parity-fixes.md#discarding-pattern-stamps-that-miss-every-output-sample) · [Original stage comparisons](parity-fixes.md#directional-noise-and-scratch-pattern-sources) | +| [noise_directional_noise_3.sbs/directional_noise_3](../assets/sbs/noise_directional_noise_3.sbs) | 0 | Yes | [In progress · 17/19 established originals render, 141,209/141,568 pixels on one and 141,288 on eight](parity-fixes.md#streaming-equal-ranked-analytic-stamps-through-one-output-image) · [Earlier comparison · 15/19 original settings have rendered, eight additional settings and three ordinary saves compared](parity-fixes.md#reused-properties-across-adjacent-groups-of-terminal-quadrants) · [Earlier comparison · 7/19 whole renders completed, 7,168/7,424 exact pixels](parity-fixes.md#discarding-pattern-stamps-that-miss-every-output-sample) · [Original stage comparisons](parity-fixes.md#directional-noise-and-scratch-pattern-sources) | | [noise_directional_noise_3_v2.sbs/directional_noise_3](../assets/sbs/noise_directional_noise_3_v2.sbs) | 0 | No | [In progress · 2/19 whole renders completed, 1,280/1,280 exact pixels](parity-fixes.md#discarding-pattern-stamps-that-miss-every-output-sample) · [Original stage comparisons](parity-fixes.md#directional-noise-and-scratch-pattern-sources) | | [noise_directional_noise_4.sbs/directional_noise_4](../assets/sbs/noise_directional_noise_4.sbs) | 0 | Yes | [In progress · 134,015/144,640 pixels in 19 comparable renders](parity-fixes.md#directional-noise-and-scratch-pattern-sources) | | [noise_directional_noise_4_v2.sbs/directional_noise_4](../assets/sbs/noise_directional_noise_4_v2.sbs) | 0 | No | [In progress · 134,664/144,640 pixels in 19 comparable renders](parity-fixes.md#directional-noise-and-scratch-pattern-sources) |