PhotoCraft: An open-source, photo editor written by scratch in pure Rust
feat(filters): Clouds and Difference Clouds as smart filters; render filters work within a smart object
Matthias Schlich50a011ae9ec7
diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rsindex 49ab15871..ae1bf0006 100644--- a/crates/algo/src/lib.rs+++ b/crates/algo/src/lib.rs@@ -410,6 +410,14 @@ pub enum FilterParams {},// ---- Render ----+ /// Clouds (or Difference Clouds, which subtracts them from the pixels) between two straight+ /// sRGB RGBA colours; the cloud size follows the bounds.+ Clouds {+ seed: u32,+ difference: bool,+ foreground: [f32; 4],+ background: [f32; 4],+ },/// Variance 1–64, strength 1–64; colours straight sRGB RGBA.Fibers {variance: f32,@@ -604,7 +612,7 @@ impl FilterParams {/// the reference bounds even where the layer is transparent, as Photoshop's does on an/// empty layer, while still reading no neighbourhood.pub fn renders_from_nothing(&self) -> bool {- matches!(self, FilterParams::Fibers { .. })+ matches!(self, FilterParams::Fibers { .. } | FilterParams::Clouds { difference: false, .. })}/// Human-readable name.@@ -651,6 +659,8 @@ impl FilterParams {FilterParams::Displace { .. } => "Displace",FilterParams::Shear { .. } => "Shear",FilterParams::ZigZag { .. } => "ZigZag",+ FilterParams::Clouds { difference: false, .. } => "Clouds",+ FilterParams::Clouds { difference: true, .. } => "Difference Clouds",FilterParams::Fibers { .. } => "Fibers",FilterParams::LensFlare { .. } => "Lens Flare",FilterParams::LightingEffects { .. } => "Lighting Effects",@@ -695,7 +705,7 @@ fn halo_ext(p: &FilterParams) -> Halo {FilterParams::Wind { method, .. } => r(stylize2::wind_reach(*method)),FilterParams::Displace { .. } | FilterParams::Shear { .. } | FilterParams::ZigZag { .. } | FilterParams::SpinBlur { .. } => Halo::Bounds,// Generators and per-pixel renders only need the bounds geometry (always in the context).- FilterParams::Fibers { .. } | FilterParams::LensFlare { .. } => Halo::Radius(0),+ FilterParams::Fibers { .. } | FilterParams::LensFlare { .. } | FilterParams::Clouds { .. } => Halo::Radius(0),FilterParams::LightingEffects { .. } => r(1.0),FilterParams::Relight { intensity, .. } if *intensity == 0.0 => Halo::Radius(0),FilterParams::Relight { .. } => Halo::Radius(relight::halo_radius_max()),@@ -815,6 +825,7 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f}FilterParams::Shear { points, undefined } => distort2::shear(src, out, ctx, points, *undefined),FilterParams::ZigZag { amount, ridges, style } => distort2::zigzag(src, out, ctx, *amount, *ridges, *style),+ FilterParams::Clouds { seed, difference, foreground, background } => render::clouds(src, out, ctx, *seed, *difference, (*foreground, *background)),FilterParams::Fibers { variance, strength, seed, foreground, background } => {render::fibers(src, out, ctx, *variance, *strength, *seed, (*foreground, *background))}diff --git a/crates/algo/src/render.rs b/crates/algo/src/render.rsindex baba88f93..d6e5d0e8a 100644--- a/crates/algo/src/render.rs+++ b/crates/algo/src/render.rs@@ -1,4 +1,4 @@-//! Render: Fibers, Lens Flare, Lighting Effects.+//! Render: Clouds, Difference Clouds, Fibers, Lens Flare, Lighting Effects.use photocraft_geom::Rect;@@ -18,6 +18,55 @@ fn value_noise(x: f32, y: f32, seed: u32) -> f32 {top + (bot - top) * sy}+fn cloud_hash(x: i32, y: i32, seed: u32) -> f32 {+ let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f);+ h ^= h >> 13;+ h = h.wrapping_mul(0x5bd1_e995);+ h ^= h >> 15;+ (h & 0x00ff_ffff) as f32 / 0x00ff_ffff as f32+}++/// Smooth value noise, summed over octaves (fBm), in 0..1.+fn clouds_value(x: f32, y: f32, base: f32, seed: u32) -> f32 {+ let (mut sum, mut amp, mut freq, mut norm) = (0.0, 1.0, 1.0 / base, 0.0);+ for o in 0..8u32 {+ let (fx, fy) = (x * freq, y * freq);+ let (ix, iy) = (fx.floor() as i32, fy.floor() as i32);+ let (tx, ty) = (fx - ix as f32, fy - iy as f32);+ let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty));+ let s = seed.wrapping_add(o * 7919);+ let top = cloud_hash(ix, iy, s) + (cloud_hash(ix + 1, iy, s) - cloud_hash(ix, iy, s)) * sx;+ let bot = cloud_hash(ix, iy + 1, s) + (cloud_hash(ix + 1, iy + 1, s) - cloud_hash(ix, iy + 1, s)) * sx;+ sum += (top + (bot - top) * sy) * amp;+ norm += amp;+ amp *= 0.5;+ freq *= 2.0;+ }+ // Stretch the bell-shaped sum so the clouds use the full foreground→background range.+ ((sum / norm - 0.5) * 2.2 + 0.5).clamp(0.0, 1.0)+}++/// Clouds between the foreground and background colours; Difference Clouds subtracts them from+/// the pixels (alpha kept). The cloud size is a quarter of the bounds' longer side.+pub(crate) fn clouds(src: &Image, out: Rect, ctx: &Ctx, seed: u32, difference: bool, colours: ([f32; 4], [f32; 4])) -> Vec<f32> {+ let n = src.ch;+ let (fg, bg) = colours;+ let base = (ctx.bounds.width().max(ctx.bounds.height()) as f32 / 4.0).clamp(16.0, 512.0);+ let mut res = src.crop(out);+ for (i, px) in res.chunks_exact_mut(n).enumerate() {+ let (x, y) = xy(out, i);+ let t = clouds_value(x as f32, y as f32, base, seed);+ let c: [f32; 3] = std::array::from_fn(|k| fg[k] + (bg[k] - fg[k]) * t);+ if difference {+ let p = rgba(ctx, px);+ set_rgba(ctx, px, [(p[0] - c[0]).abs(), (p[1] - c[1]).abs(), (p[2] - c[2]).abs(), p[3]]);+ } else {+ set_rgba(ctx, px, [c[0], c[1], c[2], 1.0]);+ }+ }+ res+}+/// Fibers: vertical fibrous streaks between the foreground and background/// colours. Variance sets how quickly the colour varies across fibres (and/// how short they are); strength stretches each fibre vertically.diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rsindex 3a27c99be..85a65587f 100644--- a/crates/engine/src/extra_cmds.rs+++ b/crates/engine/src/extra_cmds.rs@@ -278,57 +278,6 @@ fn average(s: &mut Session, p: &Value) -> Result<Value> {})}-fn hash(x: i32, y: i32, seed: u32) -> f32 {- let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f);- h ^= h >> 13;- h = h.wrapping_mul(0x5bd1_e995);- h ^= h >> 15;- (h & 0x00ff_ffff) as f32 / 0x00ff_ffff as f32-}--/// Smooth value noise, summed over octaves (fBm), in 0..1.-pub(crate) fn clouds_value(x: f32, y: f32, base: f32, seed: u32) -> f32 {- let (mut sum, mut amp, mut freq, mut norm) = (0.0, 1.0, 1.0 / base, 0.0);- for o in 0..8u32 {- let (fx, fy) = (x * freq, y * freq);- let (ix, iy) = (fx.floor() as i32, fy.floor() as i32);- let (tx, ty) = (fx - ix as f32, fy - iy as f32);- let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty));- let s = seed.wrapping_add(o * 7919);- let top = hash(ix, iy, s) + (hash(ix + 1, iy, s) - hash(ix, iy, s)) * sx;- let bot = hash(ix, iy + 1, s) + (hash(ix + 1, iy + 1, s) - hash(ix, iy + 1, s)) * sx;- sum += (top + (bot - top) * sy) * amp;- norm += amp;- amp *= 0.5;- freq *= 2.0;- }- // Stretch the bell-shaped sum so the clouds use the full foreground→background range.- ((sum / norm - 0.5) * 2.2 + 0.5).clamp(0.0, 1.0)-}--/// Filter › Render › Clouds / Difference Clouds, between the foreground and background colours.-fn clouds(s: &mut Session, p: &Value, difference: bool) -> Result<Value> {- let (fg, bg) = (s.tools.foreground, s.tools.background);- let seed = p.get("seed").and_then(Value::as_u64).unwrap_or(0) as u32;- let size = s.active().map_or(256.0, |d| d.doc.size.width.max(d.doc.size.height) as f32);- let base = (size / 4.0).clamp(16.0, 512.0);- map_pixels(s, if difference { "Difference Clouds" } else { "Clouds" }, p, |area, px, _| {- let w = area.width() as usize;- for (i, p) in px.iter_mut().enumerate() {- let (x, y) = ((area.x0 + (i % w) as i32) as f32, (area.y0 + (i / w) as i32) as f32);- let t = clouds_value(x, y, base, seed);- let c: [f32; 3] = std::array::from_fn(|k| fg[k] + (bg[k] - fg[k]) * t);- if difference {- for k in 0..3 {- p[k] = (p[k] - c[k]).abs();- }- } else {- *p = [c[0], c[1], c[2], 1.0];- }- }- })-}-// ---------- transform presets ----------/// The presets' params: like Free Transform, they follow the Channels and Layers panel target.@@ -1017,8 +966,6 @@ pub fn specs() -> Vec<CommandSpec> {show_only),spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, average),- spec!("filter.render.clouds", "Clouds", &["Filter", "Render"], None, r##"{"seed":u32=0}"##, has_pixels, |s, p| clouds(s, p, false)),- spec!("filter.render.differenceClouds", "Difference Clouds", &["Filter", "Render"], None, r##"{"seed":u32=0}"##, has_pixels, |s, p| clouds(s, p, true)),]}diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rsindex dae5e9b98..58522f8d6 100644--- a/crates/engine/src/filters_ext.rs+++ b/crates/engine/src/filters_ext.rs@@ -173,6 +173,12 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {},},// ---- Render ----+ "filter.render.clouds" | "filter.render.differenceClouds" => FilterParams::Clouds {+ seed: seed(p),+ difference: id == "filter.render.differenceClouds",+ foreground: colour(p, "foreground", BLACK),+ background: colour(p, "background", WHITE),+ },"filter.render.fibers" => FilterParams::Fibers {variance: f(p, "variance", 16.0).clamp(1.0, 64.0),strength: f(p, "strength", 4.0).clamp(1.0, 64.0),@@ -400,7 +406,8 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {/// Ids whose rendering uses the foreground/background colours.fn uses_colours(id: &str) -> bool {- matches!(id, "filter.render.fibers" | "filter.stylize.tiles" | "filter.pixelate.pointillize") || crate::gallery_cmds::uses_colours(id)+ matches!(id, "filter.render.clouds" | "filter.render.differenceClouds" | "filter.render.fibers" | "filter.stylize.tiles" | "filter.pixelate.pointillize")+ || crate::gallery_cmds::uses_colours(id)}/// Fills in session state a filter reads (the current colours) as explicit params, so the@@ -614,6 +621,8 @@ pub fn specs() -> Vec<CommandSpec> {r##"{"amount":-100..100=10,"ridges":0..20=5,"style":"pondRipples|outFromCenter|aroundCenter"}"##),// Render+ cmd!("filter.render.clouds", "Clouds", ["Filter", "Render"], r##"{"seed":u32=0,"foreground":json,"background":json}"##),+ cmd!("filter.render.differenceClouds", "Difference Clouds", ["Filter", "Render"], r##"{"seed":u32=0,"foreground":json,"background":json}"##),cmd!("filter.render.fibers","Fibers…",diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rsindex e2c1cf2bf..4f9c8c148 100644--- a/crates/engine/src/smart_cmds.rs+++ b/crates/engine/src/smart_cmds.rs@@ -307,7 +307,7 @@ pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) ->// Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters.let extent = canvas.union(&placed.content_bounds());for f in sm.smart_filters.iter().filter(|f| f.visible) {- cur = apply_smart_filter(f, &cur, canvas, extent);+ cur = apply_smart_filter(f, &cur, filter_bounds(f, placed, canvas), extent);}match sm.filter_mask.as_ref().filter(|m| m.enabled) {Some(m) => photocraft_compose::filter_mask::mix(placed, &cur, m),@@ -315,6 +315,21 @@ pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) ->}}+/// The reference bounds of smart filter `f`. Render filters work within the smart object, as+/// Photoshop's do: Lens Flare's centre is a fraction of the object, and Clouds and Fibers fill it+/// and size their pattern by it. The object is its placed content's bounds (which leaves out+/// fully transparent edges of the source); the other filters use the canvas, as on a layer.+fn filter_bounds(f: &SmartFilter, placed: &Surface, canvas: Rect) -> Rect {+ match placed.content_bounds() {+ b if renders_in_object(f) && !b.is_empty() => b,+ _ => canvas,+ }+}++fn renders_in_object(f: &SmartFilter) -> bool {+ matches!(f.command.as_str(), "filter.render.clouds" | "filter.render.differenceClouds" | "filter.render.fibers" | "filter.render.lensFlare")+}+/// One visible smart filter over `cur`, blended with its blend mode and opacity.fn apply_smart_filter(f: &SmartFilter, cur: &Surface, canvas: Rect, extent: Rect) -> Surface {// Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone.@@ -410,7 +425,8 @@ fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Result<Option<Sufor (i, (f, key)) in filters.iter().zip(&keys).enumerate().skip(done) {ctx.check()?;ctx.progress(i as f32 / n, "");- cur = Stage { surface: apply_smart_filter(f, &cur.surface, canvas, cur.extent), extent: cur.extent };+ let bounds = if renders_in_object(f) { filter_bounds(f, &placed()?.surface, canvas) } else { canvas };+ cur = Stage { surface: apply_smart_filter(f, &cur.surface, bounds, cur.extent), extent: cur.extent };stack_cache::put(*key, &cur);}ctx.progress(1.0, "");diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rsindex 1caaff6ce..d98a00085 100644--- a/crates/engine/src/smart_cmds/tests.rs+++ b/crates/engine/src/smart_cmds/tests.rs@@ -1108,3 +1108,61 @@ fn displace_smart_filter_reads_its_map_path_on_re_render() {}std::fs::remove_dir_all(&dir).ok();}++/// Clouds and Difference Clouds on a smart object are smart filters, as in Photoshop, and keep+/// the colours they were drawn with: re-rendering after the colours change gives the same clouds.+#[test]+fn clouds_on_a_smart_object_are_smart_filters_with_their_colours() {+ for depth in DEPTHS {+ let mut s = session(depth);+ paint(&mut s);+ s.execute("filter.convertForSmartFilters", json!({})).unwrap();+ s.tools.foreground = [1.0, 0.0, 0.0, 1.0];+ s.tools.background = [0.0, 0.0, 1.0, 1.0];+ s.execute("filter.render.clouds", json!({"seed": 5})).unwrap();+ s.execute("filter.render.differenceClouds", json!({"seed": 9})).unwrap();+ let sm = active_smart(&s);+ let commands: Vec<&str> = sm.smart_filters.iter().map(|f| f.command.as_str()).collect();+ assert_eq!(commands, ["filter.render.clouds", "filter.render.differenceClouds"]);+ assert_eq!(sm.smart_filters[0].params["foreground"], json!([1.0, 0.0, 0.0, 1.0]));+ assert_eq!(sm.smart_filters[1].params["background"], json!([0.0, 0.0, 1.0, 1.0]));+ // Red-to-blue clouds, and their difference, have no green: they fill the object (painted+ // from (-6, 5) to (40, 38)) over the white background.+ let rendered = flat(&s);+ let object: Vec<[f32; 4]> = (5..38).flat_map(|y| (0..40).map(move |x| (y * W + x) as usize)).map(|i| rendered[i]).collect();+ assert!(object.iter().all(|p| p[1] < 0.02), "depth {depth}");+ assert!(max_diff(&object, &vec![object[0]; object.len()]) > 0.05, "the clouds vary");+ s.tools.foreground = [0.0, 1.0, 0.0, 1.0];+ s.execute("layer.smartFilter.setParams", json!({"index": 1, "params": {"seed": 9}})).unwrap();+ assert!(max_diff(&flat(&s), &rendered) < 1e-6, "depth {depth}: same params, same clouds");+ s.undo();+ s.undo();+ assert_eq!(active_smart(&s).smart_filters.len(), 1);+ }+}++/// Render filters on a smart object work within the object, as in Photoshop (and as PSD stores+/// them): Lens Flare's centre is a fraction of the object's bounds, not of the canvas.+#[test]+fn lens_flare_centres_on_the_smart_object() {+ let mut s = session(8);+ let block = Rect::new(32, 24, W, H);+ s.edit("setup", |doc, active| {+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ let fmt = surf.format();+ let px = photocraft_raster::from_rgba(&fmt, [0.1, 0.1, 0.1, 1.0]);+ surf.write_region(block, &px.repeat((block.width() * block.height()) as usize));+ Ok(())+ })+ .unwrap();+ convert(&mut s);+ s.execute("filter.render.lensFlare", json!({"centerX": 0.5, "centerY": 0.5, "lens": "prime105"})).unwrap();+ // The centre of the brightest pixels inside the object (the canvas around it is white).+ let px = flat(&s);+ let inside: Vec<(i32, i32, f32)> =+ (block.y0..block.y1).flat_map(|y| (block.x0..block.x1).map(move |x| (x, y))).map(|(x, y)| (x, y, px[(y * W + x) as usize][1])).collect();+ let peak = inside.iter().map(|p| p.2).fold(0.0, f32::max);+ let core: Vec<_> = inside.iter().filter(|p| p.2 >= peak - 0.02).collect();+ let (x, y) = (core.iter().map(|p| p.0).sum::<i32>() / core.len() as i32, core.iter().map(|p| p.1).sum::<i32>() / core.len() as i32);+ assert!((x - 48).abs() <= 1 && (y - 36).abs() <= 1, "flare at {x},{y}, the object's centre is 48,36");+}