From c7505fcafc0bb2823e7070dbbbe141aa0303f92b Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:00:59 +0530 Subject: [PATCH 1/7] #3464: raster: Gaussian blur as if the image went on with transparency gaussian_blur's box passes drop what they spread past the buffer's edge, so a blur wider than its buffer comes out far too faint: three boxes of radius 15000 on a 4096-pixel line keep about 3 % of the centre value per axis. gaussian_blur_unbounded gives the same three boxes as if the image continued with transparency, at O(length) per line whatever the sigma: each box is a difference of prefix sums, so three are eight terms of the third prefix sum, which is a polynomial past the line's ends. The sums are f64. The test compares it with gaussian_blur on a buffer padded past the blur's reach, up to sigma 15000 along each axis. --- crates/raster/src/blur.rs | 148 ++++++++++++++++++++++++++++++++++++++ crates/raster/src/lib.rs | 2 +- 2 files changed, 149 insertions(+), 1 deletion(-) diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index 76e51f865..e8e98281a 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -182,6 +182,111 @@ pub fn gaussian_blur(img: &Image, sigma_x: f64, sigma_y: f64, repeat: bool) -> I box_passes(img, &rx, &ry, repeat) } +/// [`gaussian_blur`] with transparent edges, as if the image went on with transparency on +/// every side: what a box pass spreads past the edge still feeds the passes after it, where +/// [`gaussian_blur`] drops it. For blurs that reach past the buffer holding them (an effect's +/// padding cut to its pixel budget), which [`gaussian_blur`] leaves far too faint once the +/// boxes are wider than the buffer. A line costs O(length) whatever the sigma. +pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image { + let (w, h) = (img.width as usize, img.height as usize); + let mut out = img.clone(); + if w == 0 || h == 0 { + return out; + } + if let Some(r) = unbounded_radii(sigma_x) { + out.data.par_chunks_mut(w).for_each(|row| boxes_unbounded(row, r)); + } + if let Some(r) = unbounded_radii(sigma_y) { + let cols: Vec> = (0..w) + .into_par_iter() + .map(|x| { + let mut col: Vec = out.data.iter().skip(x).step_by(w).copied().collect(); + boxes_unbounded(&mut col, r); + col + }) + .collect(); + out.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { + for (o, col) in row.iter_mut().zip(&cols) { + if let Some(v) = col.get(y) { + *o = *v; + } + } + }); + } + out +} + +/// [`gaussian_blur`]'s three box radii for `sigma`, or `None` where it doesn't blur (and for +/// a sigma that isn't finite). +fn unbounded_radii(sigma: f64) -> Option<[i64; 3]> { + if !(sigma > 0.05 && sigma.is_finite()) { + return None; + } + match box_radii(sigma, 3).as_slice() { + &[a, b, c] => Some([a, b, c].map(|r| i64::try_from(r).unwrap_or(i64::MAX / 8))), + _ => None, + } +} + +/// Three transparent-edged box passes of radii `r` over `line`, as if it went on with zeros. +/// +/// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so three are +/// eight signed terms of the third prefix sum `S3`. Past the line's ends the prefix sums are +/// polynomials: `S3(m) = 0` before it, and after it, `j = m − n + 1` steps on, +/// `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2` with `T` the line's total. The sums are +/// `f64`: the eight terms cancel to a value `(2r + 1)³` times smaller. +fn boxes_unbounded(line: &mut [Px], r: [i64; 3]) { + let n = line.len(); + let Ok(n_i) = i64::try_from(n) else { return }; + if n == 0 { + return; + } + let mut s3 = Vec::with_capacity(n); + let (mut s1, mut s2, mut acc) = ([0.0f64; 4], [0.0f64; 4], [0.0f64; 4]); + for p in line.iter() { + for c in 0..4 { + s1[c] += f64::from(p[c]); + s2[c] += s1[c]; + acc[c] += s2[c]; + } + s3.push(acc); + } + let (total, s2_end, s3_end) = (s1, s2, acc); + let at = |m: i64| -> [f64; 4] { + if m < 0 { + return [0.0; 4]; + } + if let Some(v) = usize::try_from(m).ok().and_then(|i| s3.get(i)) { + return *v; + } + let j = (m - n_i + 1) as f64; + std::array::from_fn(|c| s3_end[c] + j * s2_end[c] + total[c] * j * (j + 1.0) / 2.0) + }; + // The eight shifts and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. + let mut terms = [(0i64, 1.0f64); 8]; + for (k, t) in terms.iter_mut().enumerate() { + for (b, &ri) in r.iter().enumerate() { + if k >> b & 1 == 0 { + t.0 = t.0.saturating_add(ri); + } else { + t.0 = t.0.saturating_sub(ri.saturating_add(1)); + t.1 = -t.1; + } + } + } + let norm: f64 = r.iter().map(|&ri| (2 * ri + 1) as f64).product(); + for (x, o) in (0i64..).zip(line.iter_mut()) { + let mut v = [0.0f64; 4]; + for &(shift, sign) in &terms { + let s = at(x.saturating_add(shift)); + for c in 0..4 { + v[c] += sign * s[c]; + } + } + *o = v.map(|v| (v / norm) as f32); + } +} + /// Below this sigma (pixels) three integer-radius box passes are too coarse (sigma under ~0.6 is /// a no-op and the result steps between a few shapes), so [`gaussian_blur_exact`] is used instead. const EXACT_SIGMA_BELOW: f64 = 3.0; @@ -520,4 +625,47 @@ mod tests { assert_eq!(r.len(), 3); assert!(r.iter().all(|&v| (7..=10).contains(&v)), "{r:?}"); } + + /// #3464: [`gaussian_blur_unbounded`] is [`gaussian_blur`] on the image padded with enough + /// transparency to hold every pass, cropped back: what a pass spreads past the edge comes + /// back in the passes after it. Sigmas far wider than the image too, along each axis. + #[test] + fn unbounded_gaussian_matches_a_buffer_padded_past_its_reach() { + let pattern = |w: u32, h: u32| { + let mut img = Image::new(w, h); + for (i, p) in img.data.iter_mut().enumerate() { + let v = ((i * 7919) % 101) as f32 / 101.0; + *p = [v, v * 0.5, 1.0 - v, (v + 0.3).min(1.0)]; + } + img + }; + let cases = [ + (pattern(23, 17), 4.0f64, 0.0f64, 1e-4), + (pattern(23, 17), 0.0, 6.0, 1e-4), + (pattern(23, 17), 7.5, 3.2, 1e-4), + (pattern(23, 17), 60.0, 45.0, 1e-4), + // The reference's f32 running sums drift over its 90 000-pixel line (by 1.5e-4 of + // the value against an f64 evaluation, which this matches to 1e-9). + (pattern(40, 1), 15000.0, 0.0, 1e-3), + (pattern(1, 40), 0.0, 15000.0, 1e-3), + ]; + for (img, sx, sy, tol) in cases { + // Three boxes of radius about σ each reach at most 3σ + 2. Padded by hand, along + // the blurred axes only (`Image::padded` pads both and caps a side at 30000). + let reach = |s: f64| if s > 0.0 { (s * 3.0 + 4.0).ceil() as u32 } else { 0 }; + let (px, py) = (reach(sx), reach(sy)); + let mut big = Image::new(img.width + 2 * px, img.height + 2 * py); + for y in 0..img.height { + for x in 0..img.width { + big.set(x + px, y + py, img.get(x as i64, y as i64)); + } + } + let want = gaussian_blur(&big, sx, sy, false).crop(px as i64, py as i64, img.width, img.height); + let got = gaussian_blur_unbounded(&img, sx, sy); + let peak = want.data.iter().flatten().fold(0.0f32, |m, v| m.max(v.abs())); + for (a, b) in got.data.iter().flatten().zip(want.data.iter().flatten()) { + assert!((a - b).abs() <= tol * peak.max(1e-6), "σ ({sx}, {sy}) on {}×{}: {a} vs {b} (peak {peak})", img.width, img.height); + } + } + } } diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index e18a24c63..b94874944 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -17,7 +17,7 @@ pub mod yuv; use effectcraft_color::{BlendMode, blend_pixel}; use rayon::prelude::*; -pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_is_exact, radial_blur}; +pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_is_exact, radial_blur}; pub use channels3d::AuxChannels; pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_changed, composite_warp_reference, resample}; From 89030900074f47eacf96fdbb82e41aed7eec662f Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:08:36 +0530 Subject: [PATCH 2/7] #3464: Drop Shadow: keep the whole blur when the padding budget cuts the margin Drop Shadow pads its buffer by Distance + 1.5 x Softness, but the pixel budget (#2261) cuts that margin for a large Softness: from about 870 on a 1080p layer. The box passes then dropped what they spread past the edge, so the shadow came out too faint: at the centre of a 64 x 48 layer, 0.11 of the Gaussian at Softness 8000. With a cut margin the CPU now blurs as if the buffer went on with transparency (the Gaussian is unchanged, sigma = Softness / 2). The GPU hands that case to the CPU and keeps every margin that fits, so those results are unchanged. Measured on an M-series Mac: 1080p at Softness 30000 takes 0.10 s, and a 4096 x 4096 layer (an 8192 x 8192 buffer) takes 0.99 s on the CPU. The pad is computed once for both paths (drop_shadow_pad) and saturates instead of overflowing on a huge Softness. --- crates/effects/src/lib.rs | 4 ++-- crates/effects/src/misc.rs | 44 +++++++++++++++++++++++++++++++++++--- crates/gpu/src/effects.rs | 6 +++++- crates/gpu/src/tests.rs | 33 ++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 6 deletions(-) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 5da2035ac..13bd8bf93 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -92,8 +92,8 @@ use effectcraft_project::build::Ids; use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property}; pub use effectcraft_raster::{AuxChannels, Image}; pub use misc::{ - GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma, radial_wipe_sigma, - radial_wipe_wedge, venetian_cover, venetian_origin, + GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, drop_shadow_pad, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma, + radial_wipe_sigma, radial_wipe_wedge, venetian_cover, venetian_origin, }; pub use sim::particle_state; pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state}; diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 9c7131657..7e5f5c1c6 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -3,7 +3,7 @@ use effectcraft_color::luminance; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; -use effectcraft_raster::{Image, gaussian_blur, hash_noise}; +use effectcraft_raster::{Image, gaussian_blur, gaussian_blur_unbounded, hash_noise}; use rayon::prelude::*; use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider}; @@ -283,6 +283,12 @@ fn glow(ctx: &EffectCtx, mut b: Buf) -> Buf { b } +/// The margin Drop Shadow asks for around a layer: its Distance and its blur's reach (three +/// boxes of radius about σ = Softness / 2), both in buffer pixels. Shared with the GPU path. +pub fn drop_shadow_pad(dist: f64, soft: f64) -> u32 { + ((dist + soft * 1.5).ceil() as u32).saturating_add(2) +} + fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { let color = ctx.params.color("color"); let opacity = ctx.params.f("opacity") as f32 / 100.0; @@ -290,9 +296,17 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { let dist = ctx.params.f("distance") * b.scale; let soft = ctx.params.f("softness") * b.scale; let only = ctx.params.b("shadowOnly"); - let pad = (dist + soft * 1.5).ceil() as u32 + 2; + let pad = drop_shadow_pad(dist, soft); + // Whether the buffer holds the whole blur. The pixel budget (#2261) cuts the margin of a + // large Softness (After Effects' range reaches 30000, #3464); the blur then goes on past the + // buffer's edge rather than dropping what reaches it, which would leave the shadow far too + // faint. An adjustment layer's buffer is the composition, as before. + let mut holds_blur = true; if !ctx.adjustment { + let (w0, h0) = (b.img.width, b.img.height); b.pad(pad); + let need = pad.saturating_mul(2); + holds_blur = b.img.width.saturating_sub(w0) >= need && b.img.height.saturating_sub(h0) >= need; } let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist); let mut sh = Image::new(b.img.width, b.img.height); @@ -304,7 +318,7 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { } }); if soft > 0.0 { - sh = gaussian_blur(&sh, soft / 2.0, soft / 2.0, false); + sh = if holds_blur { gaussian_blur(&sh, soft / 2.0, soft / 2.0, false) } else { gaussian_blur_unbounded(&sh, soft / 2.0, soft / 2.0) }; } if !only { sh.data.par_iter_mut().zip(b.img.data.par_iter()).for_each(|(s, o)| { @@ -1036,6 +1050,30 @@ mod tests { assert_ne!(row(2.0), row(2.4)); } + /// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2) + /// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share + /// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the + /// boxes spread past the buffer left it at 0.2 of that at 8000 and 0.001 at 30000. + #[test] + fn drop_shadow_keeps_its_blur_past_the_padding_budget() { + let (w, h) = (64u32, 48u32); + for softness in [500.0, 4000.0, 8000.0, 30000.0] { + let layer = effectcraft_raster::Image::filled(w, h, [1.0, 1.0, 1.0, 1.0]); + let vals = [("softness", num(softness)), ("opacity", num(100.0)), ("distance", num(0.0)), ("shadowOnly", Value::Bool(true))]; + let out = run_fx("ec.perspective.dropshadow", &vals, layer, 0.0, EffectEnv::default()); + assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "softness {softness}"); + let sigma = softness / 2.0; + let share = |len: u32| { + let sum: f64 = (0..len).map(|i| (-((f64::from(i) + 0.5 - f64::from(len) / 2.0) / sigma).powi(2) / 2.0).exp()).sum(); + sum / (sigma * (2.0 * std::f64::consts::PI).sqrt()) + }; + let want = share(w) * share(h); + let at = |v: f64, half: u32| (v + f64::from(half)) as i64; + let got = f64::from(out.img.get(at(out.offset[0], w / 2), at(out.offset[1], h / 2))[3]); + assert!((0.85..1.02).contains(&(got / want)), "softness {softness}: centre alpha {got}, Gaussian {want}"); + } + } + #[test] fn fractional_box_blur_radius_is_continuous() { let row = |v| blurred_row("ec.blur.fastbox", "radius", v); diff --git a/crates/gpu/src/effects.rs b/crates/gpu/src/effects.rs index fd5a97c38..8bbae69c4 100644 --- a/crates/gpu/src/effects.rs +++ b/crates/gpu/src/effects.rs @@ -411,8 +411,12 @@ fn drop_shadow(e: &mut Enc, ctx: &EffectCtx, mut b: GBuf) -> Option { let dist = ctx.params.f("distance") * b.scale; let soft = ctx.params.f("softness") * b.scale; let only = ctx.params.b("shadowOnly"); - let pad = (dist + soft * 1.5).ceil() as u32 + 2; + let pad = effectcraft_effects::drop_shadow_pad(dist, soft); if !ctx.adjustment { + // A margin cut to the pixel budget: the CPU blurs on past the buffer's edge (#3464). + if soft > 0.0 && effectcraft_effects::pad_within_budget(b.img.width, b.img.height, pad) < pad { + return None; + } b.pad(e, pad)?; } let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 1d2782262..0959aa4de 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -760,6 +760,39 @@ fn box_blur_horizontal_rows_match_cpu_beyond_256() { } } +/// #3464: Drop Shadow's Softness reaches 30000. While the padded buffer holds the blur the GPU +/// runs it (1000, the old maximum, on a 70 × 44 layer); once the pixel budget cuts the padding +/// the CPU blurs past the buffer's edge, so the GPU hands the effect over and the render still +/// matches, with and without Shadow Only. +#[test] +fn drop_shadow_large_softness_matches_cpu() { + effect_case("ec.perspective.dropshadow", &[("distance", n(6.0)), ("softness", n(1000.0)), ("opacity", n(100.0))]); + let Some(g) = gpu() else { return }; + for only in [false, true] { + let vals = [("distance", n(6.0)), ("softness", n(30000.0)), ("opacity", n(100.0)), ("shadowOnly", Value::Bool(only))]; + let spec = effectcraft_effects::find("ec.perspective.dropshadow").unwrap(); + let mut params = effectcraft_effects::Params { + values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, [70.0, 44.0]))).collect(), + }; + for (k, v) in &vals { + params.values.insert(k.to_string(), v.clone()); + } + let ctx = effectcraft_effects::EffectCtx { params: ¶ms, time: 0.0, layer_size: [70.0, 44.0], seed: 11, adjustment: false, env: Default::default() }; + let buf = effectcraft_effects::Buf { img: pattern(7, 70, 44), offset: [0.0, 0.0], scale: 1.0 }; + let step = effectcraft_render::FxStep { spec, ctx }; + assert!(effectcraft_render::Accelerator::effects(g, &[step], &buf, None).is_none(), "the GPU hands a cut margin to the CPU"); + for depth in [BitDepth::Bpc8, BitDepth::Bpc32] { + let mut s = Scene::new(depth); + let bg = s.solid([0.15, 0.1, 0.2], 97, 61); + s.push(bg); + let mut l = s.footage(70, 44); + s.effect(&mut l, "ec.perspective.dropshadow", &vals); + s.push(l); + check(&format!("drop shadow 30000 only {only} {depth:?}"), compare_at(&s, opts(), Tick::ZERO), 0.0); + } + } +} + #[test] fn gpu_effects_match_cpu() { // Sigma 3 px and up and even radii, so the half-scale pass stays on the GPU too (#1939). From f149b65c579d796c46ddfd0b975a7c1a7eb6a311 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:11:46 +0530 Subject: [PATCH 3/7] #3464: Drop Shadow: Softness takes After Effects' range Softness took 0..1000, so prop.set and the value editors clamped values After Effects accepts: its recorded definition for ADBE Drop Shadow allows 0..30000 in the same pixels (the .aep mapping is plain). The hard range is now 0..30000; the default (0) and the slider (0..250) are unchanged. Projects saved with the old range take the new one on open. The .aep range guard loses its allow-list row, and the engine test sets both ends through prop.set, undo / redo, save / reopen and an old project. Keyframe text keeps no unit for it (only 0..100 sliders read as percent). --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/misc.rs | 10 +++++++++- crates/engine/src/tests/effect_ranges.rs | 1 + docs/effects-parity.md | 1 + 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 338e00fc5..dd67bd493 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -727,7 +727,6 @@ mod tests { ("ec.blur.channel", "blueBlurriness", 3462), ("ec.blur.channel", "alphaBlurriness", 3462), ("ec.obsolete.gaussianlegacy", "blurriness", 3463), - ("ec.perspective.dropshadow", "softness", 3464), ("ec.blur.compound", "maximumBlur", 3465), ("ec.blur.sharpen", "amount", 3466), ("ec.blur.radial", "amount", 3467), diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 7e5f5c1c6..f56310ece 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -885,7 +885,7 @@ pub fn specs() -> Vec { p("opacity", "Opacity", num(50.0), slider(0.0, 100.0, 0.0, 100.0, 0)), p("direction", "Direction", num(135.0), ParamUi::Angle), p("distance", "Distance", num(5.0), slider(0.0, 32000.0, 0.0, 120.0, 1)), - p("softness", "Softness", num(0.0), slider(0.0, 1000.0, 0.0, 250.0, 1)), + p("softness", "Softness", num(0.0), slider(0.0, 30000.0, 0.0, 250.0, 1)), p("shadowOnly", "Shadow Only", Value::Bool(false), ParamUi::Checkbox), ], drop_shadow, @@ -1050,6 +1050,14 @@ mod tests { assert_ne!(row(2.0), row(2.4)); } + /// #3464: Softness takes After Effects' valid range, 0..30000; the slider still shows 0..250. + #[test] + fn drop_shadow_softness_takes_the_after_effects_range() { + let spec = crate::find("ec.perspective.dropshadow").unwrap(); + let ui = &spec.params.iter().find(|p| p.id == "softness").unwrap().ui; + assert_eq!(*ui, slider(0.0, 30000.0, 0.0, 250.0, 1)); + } + /// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2) /// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share /// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 7deaaa911..1e2eb5fac 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -60,6 +60,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), + (3464, "ec.perspective.dropshadow", "softness", 0.0, 30000.0), ]; fn path(effect: &str, param: &str) -> String { diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b07c624f8..a7f1d6afb 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Drop Shadow: Softness takes After Effects' recorded valid range, 0..30000 (default and 0..250 slider unchanged). Past the padding budget the shadow keeps its blur (σ = Softness / 2) and is cut at the buffer's edge (CPU and GPU) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 0bd722b1a5365b5ab54c4f8ac2609b936d9b5936 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:24:11 +0530 Subject: [PATCH 4/7] #3464: raster: unbounded blur skips zero radii and caps sigma A zero-radius box is an identity, but as a difference of prefix sums it kept their rounding error; those boxes are now left out (one to three boxes, of the matching prefix-sum order). A sigma above 1e7 blurs as 1e7, wider than any buffer, so box_radii's i64 arithmetic can't overflow on a huge or infinite sigma. --- crates/raster/src/blur.rs | 109 +++++++++++++++++++++++--------------- 1 file changed, 66 insertions(+), 43 deletions(-) diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index e8e98281a..6ca4aa174 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -194,14 +194,14 @@ pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image return out; } if let Some(r) = unbounded_radii(sigma_x) { - out.data.par_chunks_mut(w).for_each(|row| boxes_unbounded(row, r)); + out.data.par_chunks_mut(w).for_each(|row| boxes_unbounded(row, &r)); } if let Some(r) = unbounded_radii(sigma_y) { let cols: Vec> = (0..w) .into_par_iter() .map(|x| { let mut col: Vec = out.data.iter().skip(x).step_by(w).copied().collect(); - boxes_unbounded(&mut col, r); + boxes_unbounded(&mut col, &r); col }) .collect(); @@ -216,65 +216,71 @@ pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image out } -/// [`gaussian_blur`]'s three box radii for `sigma`, or `None` where it doesn't blur (and for -/// a sigma that isn't finite). -fn unbounded_radii(sigma: f64) -> Option<[i64; 3]> { - if !(sigma > 0.05 && sigma.is_finite()) { +/// Above this sigma (pixels) [`gaussian_blur_unbounded`] blurs as if it were this: far wider +/// than any buffer ([`crate::MAX_PADDED_SIDE`]), and small enough for [`box_radii`]'s `i64` +/// arithmetic (which overflows near 9e8). +const UNBOUNDED_SIGMA_MAX: f64 = 1e7; + +/// [`gaussian_blur`]'s box radii for `sigma` without the zero ones (each an identity), or +/// `None` where it doesn't blur (and for a sigma that isn't a number). +fn unbounded_radii(sigma: f64) -> Option> { + if sigma.is_nan() || sigma <= 0.05 { return None; } - match box_radii(sigma, 3).as_slice() { - &[a, b, c] => Some([a, b, c].map(|r| i64::try_from(r).unwrap_or(i64::MAX / 8))), - _ => None, - } + let radii: Vec = box_radii(sigma.min(UNBOUNDED_SIGMA_MAX), 3).into_iter().filter_map(|r| i64::try_from(r).ok()).filter(|&r| r > 0).collect(); + (!radii.is_empty()).then_some(radii) } -/// Three transparent-edged box passes of radii `r` over `line`, as if it went on with zeros. +/// Transparent-edged box passes of radii `r` (one to three, none zero) over `line`, as if it +/// went on with zeros. /// -/// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so three are -/// eight signed terms of the third prefix sum `S3`. Past the line's ends the prefix sums are -/// polynomials: `S3(m) = 0` before it, and after it, `j = m − n + 1` steps on, -/// `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2` with `T` the line's total. The sums are -/// `f64`: the eight terms cancel to a value `(2r + 1)³` times smaller. -fn boxes_unbounded(line: &mut [Px], r: [i64; 3]) { - let n = line.len(); +/// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so `k` boxes +/// are `2^k` signed terms of the `k`-th prefix sum `Sk`. Before the line every `Sk` is 0; past +/// it, `j = m − n + 1` steps on with `T` the line's total, they are polynomials: +/// `S1(m) = T`, `S2(m) = S2(n − 1) + j·T`, `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2`. +/// The sums are `f64`. `Sk` grows like `n^k`, so the cancelling terms leave a rounding error +/// near `ε·n^k / (2r + 1)^k` of the values: under 1e-8 for any line a blur too wide for its +/// buffer runs on. +fn boxes_unbounded(line: &mut [Px], r: &[i64]) { + let (n, k) = (line.len(), r.len()); let Ok(n_i) = i64::try_from(n) else { return }; - if n == 0 { + if n == 0 || !(1..=3).contains(&k) { return; } - let mut s3 = Vec::with_capacity(n); - let (mut s1, mut s2, mut acc) = ([0.0f64; 4], [0.0f64; 4], [0.0f64; 4]); + // sums[o] = the (o + 1)-th prefix sum so far. + let mut sums = [[0.0f64; 4]; 3]; + let mut sk = Vec::with_capacity(n); for p in line.iter() { for c in 0..4 { - s1[c] += f64::from(p[c]); - s2[c] += s1[c]; - acc[c] += s2[c]; + sums[0][c] += f64::from(p[c]); + sums[1][c] += sums[0][c]; + sums[2][c] += sums[1][c]; } - s3.push(acc); + sk.push(sums[k - 1]); } - let (total, s2_end, s3_end) = (s1, s2, acc); let at = |m: i64| -> [f64; 4] { if m < 0 { return [0.0; 4]; } - if let Some(v) = usize::try_from(m).ok().and_then(|i| s3.get(i)) { + if let Some(v) = usize::try_from(m).ok().and_then(|i| sk.get(i)) { return *v; } let j = (m - n_i + 1) as f64; - std::array::from_fn(|c| s3_end[c] + j * s2_end[c] + total[c] * j * (j + 1.0) / 2.0) + std::array::from_fn(|c| match k { + 1 => sums[0][c], + 2 => sums[1][c] + j * sums[0][c], + _ => sums[2][c] + j * sums[1][c] + sums[0][c] * j * (j + 1.0) / 2.0, + }) }; - // The eight shifts and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. - let mut terms = [(0i64, 1.0f64); 8]; - for (k, t) in terms.iter_mut().enumerate() { - for (b, &ri) in r.iter().enumerate() { - if k >> b & 1 == 0 { - t.0 = t.0.saturating_add(ri); - } else { - t.0 = t.0.saturating_sub(ri.saturating_add(1)); - t.1 = -t.1; - } - } - } - let norm: f64 = r.iter().map(|&ri| (2 * ri + 1) as f64).product(); + // The shifts and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. + let terms: Vec<(i64, f64)> = (0..1usize << k) + .map(|bits| { + r.iter().enumerate().fold((0i64, 1.0f64), |(shift, sign), (b, &ri)| { + if bits >> b & 1 == 0 { (shift.saturating_add(ri), sign) } else { (shift.saturating_sub(ri.saturating_add(1)), -sign) } + }) + }) + .collect(); + let norm: f64 = r.iter().map(|&ri| 2.0 * ri as f64 + 1.0).product(); for (x, o) in (0i64..).zip(line.iter_mut()) { let mut v = [0.0f64; 4]; for &(shift, sign) in &terms { @@ -626,6 +632,20 @@ mod tests { assert!(r.iter().all(|&v| (7..=10).contains(&v)), "{r:?}"); } + /// #3464: a sigma past any buffer, or infinite, blurs as the widest one does: finite, no + /// overflow in the radii. A NaN sigma leaves the axis alone. + #[test] + fn unbounded_gaussian_takes_any_sigma() { + let mut img = Image::new(9, 7); + img.set(4, 3, [1.0, 0.5, 0.25, 1.0]); + let wide = gaussian_blur_unbounded(&img, 1e7, 1e7); + for (sx, sy) in [(f64::INFINITY, f64::INFINITY), (1e300, 1e12)] { + assert_eq!(gaussian_blur_unbounded(&img, sx, sy).data, wide.data, "σ ({sx}, {sy})"); + } + assert!(wide.data.iter().flatten().all(|v| v.is_finite())); + assert_eq!(gaussian_blur_unbounded(&img, f64::NAN, f64::NAN).data, img.data); + } + /// #3464: [`gaussian_blur_unbounded`] is [`gaussian_blur`] on the image padded with enough /// transparency to hold every pass, cropped back: what a pass spreads past the edge comes /// back in the passes after it. Sigmas far wider than the image too, along each axis. @@ -644,8 +664,11 @@ mod tests { (pattern(23, 17), 0.0, 6.0, 1e-4), (pattern(23, 17), 7.5, 3.2, 1e-4), (pattern(23, 17), 60.0, 45.0, 1e-4), - // The reference's f32 running sums drift over its 90 000-pixel line (by 1.5e-4 of - // the value against an f64 evaluation, which this matches to 1e-9). + // Zero radii (an identity) and one non-zero box among them. + (pattern(23, 17), 0.5, 0.0, 1e-6), + (pattern(23, 17), 0.0, 1.1, 1e-5), + // The reference's f32 running sums drift over its 90 000-pixel line (by about 1.5e-4 + // of the value). (pattern(40, 1), 15000.0, 0.0, 1e-3), (pattern(1, 40), 0.0, 15000.0, 1e-3), ]; From cec04744f34947165df1b7fe2748f72da686f567 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:24:11 +0530 Subject: [PATCH 5/7] #3464: Drop Shadow: test a huge Softness; say what the GPU test checks A Softness far past the range (an expression can set one) overflowed the padding's u32 before drop_shadow_pad saturated it; the new test panicked there in a debug build and renders a finite shadow now. The GPU test's comment and the parity row now say that a cut margin renders on the CPU, and the CPU test quotes the measured 0.11 at Softness 8000. --- crates/effects/src/misc.rs | 13 ++++++++++++- crates/gpu/src/tests.rs | 6 +++--- docs/effects-parity.md | 2 +- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index f56310ece..660cee46a 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -1058,10 +1058,21 @@ mod tests { assert_eq!(*ui, slider(0.0, 30000.0, 0.0, 250.0, 1)); } + /// #3464: a Softness far past the range (an expression can set one) used to overflow the + /// padding's `u32` (a panic in debug builds). It renders, finite. + #[test] + fn drop_shadow_takes_a_huge_softness() { + for softness in [1e12, f64::INFINITY] { + let layer = effectcraft_raster::Image::filled(8, 8, [1.0, 1.0, 1.0, 1.0]); + let out = run_fx("ec.perspective.dropshadow", &[("softness", num(softness))], layer, 0.0, EffectEnv::default()); + assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "softness {softness}"); + } + } + /// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2) /// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share /// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the - /// boxes spread past the buffer left it at 0.2 of that at 8000 and 0.001 at 30000. + /// boxes spread past the buffer left it at 0.11 of that at 8000. #[test] fn drop_shadow_keeps_its_blur_past_the_padding_budget() { let (w, h) = (64u32, 48u32); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 0959aa4de..09bc226c7 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -761,9 +761,9 @@ fn box_blur_horizontal_rows_match_cpu_beyond_256() { } /// #3464: Drop Shadow's Softness reaches 30000. While the padded buffer holds the blur the GPU -/// runs it (1000, the old maximum, on a 70 × 44 layer); once the pixel budget cuts the padding -/// the CPU blurs past the buffer's edge, so the GPU hands the effect over and the render still -/// matches, with and without Shadow Only. +/// runs it and matches the CPU (1000, the old maximum, on a 70 × 44 layer). Once the pixel +/// budget cuts the padding only the CPU blurs past the buffer's edge, so the GPU declines the +/// effect; the render then takes it on the CPU at 8 and 32 bpc, with and without Shadow Only. #[test] fn drop_shadow_large_softness_matches_cpu() { effect_case("ec.perspective.dropshadow", &[("distance", n(6.0)), ("softness", n(1000.0)), ("opacity", n(100.0))]); diff --git a/docs/effects-parity.md b/docs/effects-parity.md index a7f1d6afb..9ab7601bd 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,7 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| -| 2026-11-17 | minor | Drop Shadow: Softness takes After Effects' recorded valid range, 0..30000 (default and 0..250 slider unchanged). Past the padding budget the shadow keeps its blur (σ = Softness / 2) and is cut at the buffer's edge (CPU and GPU) | +| 2026-11-17 | minor | Drop Shadow: Softness takes After Effects' recorded valid range, 0..30000 (default and 0..250 slider unchanged). Where the padding budget cuts the margin, the shadow keeps its full blur (σ = Softness / 2) up to the buffer's edge, where it is cut; that case renders on the CPU | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From ce0c4c8a75a953cfe6806a199db345c99ec61417 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 17:30:44 +0530 Subject: [PATCH 6/7] #3464: Drop Shadow: blur before moving when the margin is cut With the padding cut to its budget, a Distance larger than what's left of the margin moved the layer out of the buffer before the blur, so the blur had nothing to spread back in: a 64 x 48 layer moved 3000 px at Softness 8000 left no shadow at all. The cut-margin path now samples only the fraction of the move and lets the blur move the rest: raster::gaussian_blur_unbounded_at evaluates the transparent-edged blur of the image at a whole-pixel shift, through a window the size of the buffer, so content outside the window still reaches into it. Margins that fit are unchanged. The blur's intermediate rows are freed before the output is allocated, so it holds at most three buffers at once. On an M-series Mac a 4096 x 4096 layer at Softness 30000 takes 0.51 s, and 1080p 0.13 s. --- crates/effects/src/misc.rs | 62 ++++++++++++++---- crates/raster/src/blur.rs | 130 +++++++++++++++++++++++++------------ crates/raster/src/lib.rs | 2 +- 3 files changed, 137 insertions(+), 57 deletions(-) diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 660cee46a..c0568a970 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -3,7 +3,7 @@ use effectcraft_color::luminance; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; -use effectcraft_raster::{Image, gaussian_blur, gaussian_blur_unbounded, hash_noise}; +use effectcraft_raster::{Image, gaussian_blur, gaussian_blur_unbounded_at, hash_noise}; use rayon::prelude::*; use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider}; @@ -298,9 +298,10 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { let only = ctx.params.b("shadowOnly"); let pad = drop_shadow_pad(dist, soft); // Whether the buffer holds the whole blur. The pixel budget (#2261) cuts the margin of a - // large Softness (After Effects' range reaches 30000, #3464); the blur then goes on past the - // buffer's edge rather than dropping what reaches it, which would leave the shadow far too - // faint. An adjustment layer's buffer is the composition, as before. + // large Softness (After Effects' range reaches 30000, #3464); the shadow is then blurred + // before it is moved, as if the buffer went on with transparency, rather than dropping what + // the move or the blur takes past the buffer's edge, which would leave it far too faint or + // gone. An adjustment layer's buffer is the composition, as before. let mut holds_blur = true; if !ctx.adjustment { let (w0, h0) = (b.img.width, b.img.height); @@ -309,17 +310,27 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { holds_blur = b.img.width.saturating_sub(w0) >= need && b.img.height.saturating_sub(h0) >= need; } let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist); - let mut sh = Image::new(b.img.width, b.img.height); let src = &b.img; - sh.rows_mut().for_each(|(y, row)| { - for (x, px) in row.iter_mut().enumerate() { - let a = src.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy)[3] * opacity * color[3]; - *px = [color[0] * a, color[1] * a, color[2] * a, a]; - } - }); - if soft > 0.0 { - sh = if holds_blur { gaussian_blur(&sh, soft / 2.0, soft / 2.0, false) } else { gaussian_blur_unbounded(&sh, soft / 2.0, soft / 2.0) }; - } + let shadow = |sh: &mut Image, (dx, dy): (f64, f64)| { + sh.rows_mut().for_each(|(y, row)| { + for (x, px) in row.iter_mut().enumerate() { + let a = src.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy)[3] * opacity * color[3]; + *px = [color[0] * a, color[1] * a, color[2] * a, a]; + } + }); + }; + let mut sh = if soft > 0.0 && !holds_blur { + // Only the fraction of the move is sampled (into one more column and row); the blur + // moves the rest. + let (ix, iy) = (dx.floor(), dy.floor()); + let mut near = Image::new(src.width.saturating_add(1), src.height.saturating_add(1)); + shadow(&mut near, (dx - ix, dy - iy)); + gaussian_blur_unbounded_at(&near, soft / 2.0, soft / 2.0, [ix as i64, iy as i64], src.width, src.height) + } else { + let mut sh = Image::new(src.width, src.height); + shadow(&mut sh, (dx, dy)); + if soft > 0.0 { gaussian_blur(&sh, soft / 2.0, soft / 2.0, false) } else { sh } + }; if !only { sh.data.par_iter_mut().zip(b.img.data.par_iter()).for_each(|(s, o)| { let k = 1.0 - o[3]; @@ -1069,6 +1080,29 @@ mod tests { } } + /// #3464: with the margin cut, a Distance that takes the whole layer past the buffer's edge + /// still leaves the shadow's blur inside it. A 64 × 48 layer moved 3000 px right, Softness + /// 8000: at the layer's centre the shadow is the Gaussian's share there (it was 0 when the + /// layer was moved out of the buffer before the blur). + #[test] + fn drop_shadow_moved_past_a_cut_margin_keeps_its_blur() { + let (w, h, dist, softness) = (64u32, 48u32, 3000.0, 8000.0); + let layer = effectcraft_raster::Image::filled(w, h, [1.0, 1.0, 1.0, 1.0]); + let vals = [("softness", num(softness)), ("opacity", num(100.0)), ("distance", num(dist)), ("direction", num(90.0)), ("shadowOnly", Value::Bool(true))]; + let out = run_fx("ec.perspective.dropshadow", &vals, layer, 0.0, EffectEnv::default()); + assert!(out.offset[0] + f64::from(w) + dist > f64::from(out.img.width), "the move takes the layer past the buffer"); + let sigma = softness / 2.0; + // The Gaussian's share of a `len`-pixel side, at `d` pixels from its centre. + let share = |len: u32, d: f64| { + let sum: f64 = (0..len).map(|i| (-((f64::from(i) + 0.5 - f64::from(len) / 2.0 + d) / sigma).powi(2) / 2.0).exp()).sum(); + sum / (sigma * (2.0 * std::f64::consts::PI).sqrt()) + }; + let want = share(w, dist) * share(h, 0.0); + let at = |v: f64, half: u32| (v + f64::from(half)) as i64; + let got = f64::from(out.img.get(at(out.offset[0], w / 2), at(out.offset[1], h / 2))[3]); + assert!((0.85..1.1).contains(&(got / want)), "centre alpha {got}, Gaussian {want}"); + } + /// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2) /// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share /// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index 6ca4aa174..cc6fe35df 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -188,31 +188,42 @@ pub fn gaussian_blur(img: &Image, sigma_x: f64, sigma_y: f64, repeat: bool) -> I /// padding cut to its pixel budget), which [`gaussian_blur`] leaves far too faint once the /// boxes are wider than the buffer. A line costs O(length) whatever the sigma. pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image { - let (w, h) = (img.width as usize, img.height as usize); - let mut out = img.clone(); - if w == 0 || h == 0 { - return out; + gaussian_blur_unbounded_at(img, sigma_x, sigma_y, [0, 0], img.width, img.height) +} + +/// [`gaussian_blur_unbounded`] of `img` moved by `shift` pixels, seen through a `width` × +/// `height` window at the origin: output `(x, y)` is the blurred plane at +/// `(x − shift[0], y − shift[1])`. Nothing is cut before the blur, so the tails of content +/// that lands outside the window still reach into it. +pub fn gaussian_blur_unbounded_at(img: &Image, sigma_x: f64, sigma_y: f64, shift: [i64; 2], width: u32, height: u32) -> Image { + let (w, h, ow, oh) = (img.width as usize, img.height as usize, width as usize, height as usize); + if w == 0 || h == 0 || ow == 0 || oh == 0 { + return Image::new(width, height); } - if let Some(r) = unbounded_radii(sigma_x) { - out.data.par_chunks_mut(w).for_each(|row| boxes_unbounded(row, &r)); - } - if let Some(r) = unbounded_radii(sigma_y) { - let cols: Vec> = (0..w) - .into_par_iter() - .map(|x| { - let mut col: Vec = out.data.iter().skip(x).step_by(w).copied().collect(); - boxes_unbounded(&mut col, &r); - col - }) - .collect(); - out.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { - for (o, col) in row.iter_mut().zip(&cols) { - if let Some(v) = col.get(y) { - *o = *v; - } + let (rx, ry) = (unbounded_radii(sigma_x).unwrap_or_default(), unbounded_radii(sigma_y).unwrap_or_default()); + // Horizontal: each source row into a row of the window's width. + let mut rows = vec![[0.0f32; 4]; ow.saturating_mul(h)]; + rows.par_chunks_mut(ow).zip(img.data.par_chunks(w)).for_each(|(o, src)| boxes_unbounded(src, &rx, shift[0], o)); + // Vertical: each of those columns into a column of the window's height. + let cols: Vec> = (0..ow) + .into_par_iter() + .map(|x| { + let col: Vec = rows.iter().skip(x).step_by(ow).copied().collect(); + let mut o = vec![[0.0f32; 4]; oh]; + boxes_unbounded(&col, &ry, shift[1], &mut o); + o + }) + .collect(); + // At most three buffers at once: the rows go before the output comes. + drop(rows); + let mut out = Image::new(width, height); + out.data.par_chunks_mut(ow).enumerate().for_each(|(y, row)| { + for (o, col) in row.iter_mut().zip(&cols) { + if let Some(v) = col.get(y) { + *o = *v; } - }); - } + } + }); out } @@ -231,32 +242,36 @@ fn unbounded_radii(sigma: f64) -> Option> { (!radii.is_empty()).then_some(radii) } -/// Transparent-edged box passes of radii `r` (one to three, none zero) over `line`, as if it -/// went on with zeros. +/// Transparent-edged box passes of radii `r` (up to three, none zero) over `line`, as if it +/// went on with zeros, moved by `shift`: `out[x]` is the blurred line at `x − shift`. /// /// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so `k` boxes -/// are `2^k` signed terms of the `k`-th prefix sum `Sk`. Before the line every `Sk` is 0; past -/// it, `j = m − n + 1` steps on with `T` the line's total, they are polynomials: -/// `S1(m) = T`, `S2(m) = S2(n − 1) + j·T`, `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2`. -/// The sums are `f64`. `Sk` grows like `n^k`, so the cancelling terms leave a rounding error -/// near `ε·n^k / (2r + 1)^k` of the values: under 1e-8 for any line a blur too wide for its -/// buffer runs on. -fn boxes_unbounded(line: &mut [Px], r: &[i64]) { +/// are `2^k` signed terms of the `k`-th prefix sum `Sk` (`S0` is the line). Before the line +/// every `Sk` is 0; past it, `j = m − n + 1` steps on with `T` the line's total, they are +/// polynomials: `S0(m) = 0`, `S1(m) = T`, `S2(m) = S2(n − 1) + j·T`, +/// `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2`. The sums are `f64`. `Sk` grows like `n^k`, +/// so the cancelling terms leave a rounding error near `ε·n^k / (2r + 1)^k` of the values: +/// under 1e-8 for any line a blur too wide for its buffer runs on. +fn boxes_unbounded(line: &[Px], r: &[i64], shift: i64, out: &mut [Px]) { let (n, k) = (line.len(), r.len()); let Ok(n_i) = i64::try_from(n) else { return }; - if n == 0 || !(1..=3).contains(&k) { + if n == 0 || k > 3 { return; } // sums[o] = the (o + 1)-th prefix sum so far. let mut sums = [[0.0f64; 4]; 3]; let mut sk = Vec::with_capacity(n); - for p in line.iter() { + for p in line { + let v = p.map(f64::from); for c in 0..4 { - sums[0][c] += f64::from(p[c]); + sums[0][c] += v[c]; sums[1][c] += sums[0][c]; sums[2][c] += sums[1][c]; } - sk.push(sums[k - 1]); + sk.push(match k { + 0 => v, + _ => sums[k - 1], + }); } let at = |m: i64| -> [f64; 4] { if m < 0 { @@ -267,24 +282,25 @@ fn boxes_unbounded(line: &mut [Px], r: &[i64]) { } let j = (m - n_i + 1) as f64; std::array::from_fn(|c| match k { + 0 => 0.0, 1 => sums[0][c], 2 => sums[1][c] + j * sums[0][c], _ => sums[2][c] + j * sums[1][c] + sums[0][c] * j * (j + 1.0) / 2.0, }) }; - // The shifts and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. + // The offsets and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. let terms: Vec<(i64, f64)> = (0..1usize << k) .map(|bits| { - r.iter().enumerate().fold((0i64, 1.0f64), |(shift, sign), (b, &ri)| { - if bits >> b & 1 == 0 { (shift.saturating_add(ri), sign) } else { (shift.saturating_sub(ri.saturating_add(1)), -sign) } + r.iter().enumerate().fold((0i64.saturating_sub(shift), 1.0f64), |(at, sign), (b, &ri)| { + if bits >> b & 1 == 0 { (at.saturating_add(ri), sign) } else { (at.saturating_sub(ri.saturating_add(1)), -sign) } }) }) .collect(); let norm: f64 = r.iter().map(|&ri| 2.0 * ri as f64 + 1.0).product(); - for (x, o) in (0i64..).zip(line.iter_mut()) { + for (x, o) in (0i64..).zip(out.iter_mut()) { let mut v = [0.0f64; 4]; - for &(shift, sign) in &terms { - let s = at(x.saturating_add(shift)); + for &(offset, sign) in &terms { + let s = at(x.saturating_add(offset)); for c in 0..4 { v[c] += sign * s[c]; } @@ -632,6 +648,36 @@ mod tests { assert!(r.iter().all(|&v| (7..=10).contains(&v)), "{r:?}"); } + /// #3464: moving the image before [`gaussian_blur_unbounded`] and blurring it moved with + /// [`gaussian_blur_unbounded_at`] agree, also when the move puts all of it outside the window + /// (its tails still reach in) and along an axis that isn't blurred. + #[test] + fn unbounded_gaussian_at_a_shift_matches_blurring_the_moved_image() { + let mut img = Image::new(6, 5); + for (i, p) in img.data.iter_mut().enumerate() { + let v = ((i * 37) % 11) as f32 / 11.0; + *p = [v, 0.5 * v, 1.0 - v, 1.0]; + } + let (ow, oh) = (14u32, 9u32); + for (sx, sy, shift) in [(3.0, 2.0, [4i64, 2i64]), (5.0, 0.0, [-3, 1]), (12.0, 12.0, [-20, 16]), (8.0, 8.0, [25, -12])] { + let got = gaussian_blur_unbounded_at(&img, sx, sy, shift, ow, oh); + // The moved image in a canvas large enough to hold it and the window, blurred. + let off = [40i64, 40i64]; + let mut canvas = Image::new(100, 100); + for y in 0..img.height { + for x in 0..img.width { + let (cx, cy) = (i64::from(x) + shift[0] + off[0], i64::from(y) + shift[1] + off[1]); + canvas.set(cx as u32, cy as u32, img.get(i64::from(x), i64::from(y))); + } + } + let want = gaussian_blur_unbounded(&canvas, sx, sy).crop(off[0], off[1], ow, oh); + assert!(got.data.iter().flatten().any(|v| *v > 1e-4), "{shift:?}: something reaches the window"); + for (a, b) in got.data.iter().flatten().zip(want.data.iter().flatten()) { + assert!((a - b).abs() <= 1e-5, "σ ({sx}, {sy}) {shift:?}: {a} vs {b}"); + } + } + } + /// #3464: a sigma past any buffer, or infinite, blurs as the widest one does: finite, no /// overflow in the radii. A NaN sigma leaves the axis alone. #[test] diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index b94874944..900416808 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -17,7 +17,7 @@ pub mod yuv; use effectcraft_color::{BlendMode, blend_pixel}; use rayon::prelude::*; -pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_is_exact, radial_blur}; +pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_blur_unbounded_at, gaussian_is_exact, radial_blur}; pub use channels3d::AuxChannels; pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_changed, composite_warp_reference, resample}; From 44663c5e9f1f9bb4798d490c59da6ffa0f48b8c7 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 17:58:30 +0530 Subject: [PATCH 7/7] #3464: raster: an unbounded blur is exactly 0 where it doesn't reach Outside the boxes' combined reach of the moved line the result is 0, but boxes_unbounded still evaluated the prefix-sum polynomials there, and far past the line their cancelling terms left a rounding residue (about 5 for a one-pixel line moved a billion pixels). Those positions are now 0 without evaluating anything. Also wraps the raster re-export line rustfmt asks for. --- crates/raster/src/blur.rs | 21 +++++++++++++++++++++ crates/raster/src/lib.rs | 4 +++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index cc6fe35df..489b32755 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -297,7 +297,15 @@ fn boxes_unbounded(line: &[Px], r: &[i64], shift: i64, out: &mut [Px]) { }) .collect(); let norm: f64 = r.iter().map(|&ri| 2.0 * ri as f64 + 1.0).product(); + // The boxes read the line within `reach` of `x − shift`. Outside that the result is 0, and + // the polynomials far past the line would only cancel to their rounding error. + let reach = r.iter().fold(0i64, |s, &ri| s.saturating_add(ri)); for (x, o) in (0i64..).zip(out.iter_mut()) { + let c = x.saturating_sub(shift); + if c.saturating_add(reach) < 0 || c.saturating_sub(reach) >= n_i { + *o = [0.0; 4]; + continue; + } let mut v = [0.0f64; 4]; for &(offset, sign) in &terms { let s = at(x.saturating_add(offset)); @@ -678,6 +686,19 @@ mod tests { } } + /// #3464: a window the blur doesn't reach stays exactly transparent, however far the move + /// (far past the line, the cancelling polynomials left a rounding residue of about 5). + #[test] + fn unbounded_gaussian_at_a_far_shift_is_exactly_transparent() { + let img = Image::filled(1, 1, [1.0, 1.0, 1.0, 1.0]); + for shift in [[-1_000_000_030i64, 0i64], [0, 1_000_000_030], [i64::MIN, i64::MAX]] { + let out = gaussian_blur_unbounded_at(&img, 1.5, 1.5, shift, 4, 3); + assert!(out.data.iter().flatten().all(|v| *v == 0.0), "{shift:?}"); + } + // Next to the window the tail still reaches in. + assert!(gaussian_blur_unbounded_at(&img, 1.5, 1.5, [-1, 0], 4, 3).get(0, 0)[3] > 0.0); + } + /// #3464: a sigma past any buffer, or infinite, blurs as the widest one does: finite, no /// overflow in the radii. A NaN sigma leaves the axis alone. #[test] diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 900416808..1708f40f6 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -17,7 +17,9 @@ pub mod yuv; use effectcraft_color::{BlendMode, blend_pixel}; use rayon::prelude::*; -pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_blur_unbounded_at, gaussian_is_exact, radial_blur}; +pub use blur::{ + box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_blur_unbounded_at, gaussian_is_exact, radial_blur, +}; pub use channels3d::AuxChannels; pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_changed, composite_warp_reference, resample};