Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

Merge main into M9.13 (GPU kernels defer CPU-only controls via catalog::gpu_supported)

Brandon Thomas225f31bf50e0
diff --cc crates/effects/src/blur2.rs
index 639f57b65,3b84d2830..e4f2b0348
--- a/crates/effects/src/blur2.rs
+++ b/crates/effects/src/blur2.rs
@@@ -277,6 -277,23 +277,30 @@@ fn iris_spans(r: f64, sides: u32, rotat
spans
}
+ /// Camera Lens Blur's iris spans at blur radius `r` pixels (shape, rotation, roundness and
+ /// aspect ratio applied) and the iris' horizontal reach (shared with the GPU kernel).
+ pub fn camera_lens_spans(ctx: &EffectCtx, r: f64) -> (Vec<(i64, i64, i64)>, f64) {
+ let shape = ctx.params.e("irisProperties/irisShape");
+ let sides = if shape >= 8 { 0 } else { shape + 3 };
- let mut spans = iris_spans(r, sides, ctx.params.f("irisProperties/irisRotation"), ctx.params.f("irisProperties/irisRoundness").clamp(0.0, 100.0) / 100.0);
++ let roundness = ctx.params.f("irisProperties/irisRoundness").clamp(0.0, 100.0) / 100.0;
+ // Aspect Ratio stretches the iris horizontally (> 1) or squeezes it (< 1).
+ let aspect = ctx.params.f("irisProperties/irisAspectRatio");
++ let mut spans = iris_spans(r, sides, ctx.params.f("irisProperties/irisRotation"), roundness);
+ if aspect > 0.0 && (aspect - 1.0).abs() > 1e-6 {
+ for s in spans.iter_mut() {
+ s.1 = (s.1 as f64 * aspect).round() as i64;
+ s.2 = (s.2 as f64 * aspect).round() as i64;
+ }
+ }
+ (spans, r * aspect.max(1.0))
+ }
+
++/// Whether Camera Lens Blur needs more than plain iris spans (Diffraction Fringe or a Blur
++/// Map): the GPU kernel handles the plain blur only.
++pub fn camera_lens_plain(ctx: &EffectCtx) -> bool {
++ ctx.params.f("irisProperties/diffractionFringe") <= 0.0 && ctx.params.get("blurMap/blurMapLayer").and_then(|v| v.as_layer()).is_none()
++}
++
fn camera_lens_blur(ctx: &EffectCtx, mut b: Buf) -> Buf {
let r = ctx.params.f("blurRadius").max(0.0) * b.scale;
if r < 0.5 {
diff --cc crates/effects/src/catalog.rs
index 2303cc55c,4ec20906d..f41b4b2e4
--- a/crates/effects/src/catalog.rs
+++ b/crates/effects/src/catalog.rs
@@@ -7,59 -7,51 +7,105 @@@ use crate::{CATEGORIES, registry}
/// Effects whose implementation is known to fall short of the reference behaviour:
/// `(effect id, what is missing)`. Everything else in the registry is implemented in full as far
/// as the public behaviour documentation describes it.
-pub const PARTIAL: &[(&str, &str)] = &[
- ("ec.blur.cameralens", "no Diffraction Fringe or Blur Map layer"),
- ("ec.channel.minimax", "no Don't Shrink Edges option"),
- ("ec.channel.combiner", "no Saturation Multiplied target"),
- ("ec.3d.channelextract", "no anti-alias option"),
- ("ec.color.huesaturation", "no per-range Channel Control"),
- ("ec.color.levels", "master channel only (no Channel popup)"),
- ("ec.color.curves", "no Channel popup"),
- ("ec.color.colorama", "no Add Phase, editable Output Cycle, Modify, Pixel Selection or Masking"),
- ("ec.color.lumetri", "no HSL Secondary, hue/saturation curves, HDR mode or look files"),
- ("ec.color.selectivecolor", "simplified Colors / Details layout"),
- ("ec.distort.turbulentdisplace", "no locked pinning variants"),
- ("ec.distort.opticscompensation", "no Optimal Pixels"),
- ("ec.distort.transform", "no shutter-angle motion blur"),
- ("ec.distort.reshape", "no correspondence points"),
- ("ec.distort.rollingshutterrepair", "Pixel Motion Detail has no effect"),
- ("ec.generate.fill", "no Fill Mask / All Masks / feather"),
- ("ec.generate.advancedlightning", "no Alpha Obstacle; most Expert Settings missing"),
- ("ec.generate.radiowaves", "no Image Contours or Mask wave types, Parameters Are Set At, reflection or stroke profile"),
- ("ec.generate.scribble", "no caps, joins or Start/End Apply To"),
- ("ec.generate.cellpattern", "HQ variants render like the standard ones"),
- ("ec.key.innerouter", "one additional mask per side; no cleanup strokes"),
- ("ec.key.advancedspill", "no Tolerance, Desaturate or Spill Color Correction"),
- ("ec.keying.keylight", "no Source Crops X/Y Method or Edge Colour; no colour suppression / balancing"),
- ("ec.matte.refinesoft", "no Reduce Chatter or motion blur"),
- ("ec.matte.refinehard", "no Reduce Chatter or motion blur"),
- ("ec.obsolete.pathtext", "no kerning, shear/scale, line spacing, fade time or jitter"),
- ("ec.noise.addgrain", "no preview region, presets, channel balance or temporal controls"),
- ("ec.noise.matchgrain", "no preview region, presets, sampling or temporal controls"),
- ("ec.noise.removegrain", "no preview region, sampling or temporal filtering"),
- ("ec.vr.digitalglitch", "reduced control set"),
- ("ec.vr.converter", "common layouts only"),
- ("ec.time.timewarp", "Pixel Motion blends frames (no optical flow); no matte, warp or crop controls"),
- ("ec.sim.carddance", "no camera system, corner pins or lighting/material controls"),
- ("ec.sim.shatter", "no custom shatter map, gradient, textures or extrusion rendering"),
- ("ec.sim.caustics", "no Sky group or light type"),
- ("ec.sim.foam", "no wobble, pop velocity, custom bubble texture, environment map or flow map"),
- ("ec.sim.particleplayground", "no Particle Exploder, Ephemeral Property Mapper, Affects groups or text particles"),
- ("ec.sim.waveworld", "no wireframe controls, dry-area rendering or ground group"),
- ("ec.stylize.glow", "no Glow Operation or arbitrary colour map"),
- ("ec.stylize.cartoon", "no Edge Enhancement"),
- ("ec.transition.cardwipe", "2D flip only; no back layer picker, camera, lighting or jitter"),
- ("ec.transition.blockdissolve", "no Soft Edges option"),
+pub const PARTIAL: &[(&str, &str)] = &[];
+
+/// Whether Effect Controls shows parameter (or twirl-down group) `param` (spec id path,
+/// `group/param`) of an instance of effect `effect`, given the instance's current values
+/// (`value(spec id)`). After Effects shows only the controls a popup selects: Levels' channel,
+/// Hue/Saturation's Channel Control, the camera system of the card effects, and so on. Every
+/// parameter stays animatable and addressable; this is presentation only.
+pub fn param_shown(effect: &str, param: &str, value: &dyn Fn(&str) -> Option<effectcraft_keyframe::Value>) -> bool {
+ let e = |id: &str| value(id).map(|v| v.as_enum()).unwrap_or(0);
+ let b = |id: &str| value(id).is_some_and(|v| v.as_bool());
+ match effect {
+ "ec.color.levels" => {
+ let ch = e("channel") as usize;
+ for (i, pre) in crate::color_fx::LEVELS_CHANNEL_PREFIX.iter().enumerate() {
+ if param.starts_with(pre) {
+ return ch == i + 1;
+ }
+ }
+ let master = ["inBlack", "inWhite", "gamma", "outBlack", "outWhite", "clipToOutputBlack", "clipToOutputWhite"];
+ !master.contains(&param) || ch == 0
+ }
+ "ec.color.huesaturation" => {
+ let ch = e("channelControl") as usize;
+ for (i, (pre, _, _)) in crate::color_fx::HUESAT_RANGES.iter().enumerate() {
+ if param.starts_with(pre) {
+ return ch == i + 1;
+ }
+ }
+ match param {
+ "hue" | "saturation" | "lightness" => ch == 0,
+ "colorizeSaturation" | "colorizeLightness" => b("colorize"),
+ _ => true,
+ }
+ }
+ "ec.color.selectivecolor" => match param.strip_prefix("details/") {
+ Some(rest) => {
+ let g = rest.split('/').next().unwrap_or("");
+ crate::color2::SC_GROUPS.iter().position(|x| *x == g).is_none_or(|i| i == e("colors") as usize)
+ }
+ None => true,
+ },
+ "ec.sim.carddance" | "ec.transition.cardwipe" => crate::card3d::shown(param, &e).unwrap_or(true),
+ "ec.sim.shatter" => match param {
+ "shape/customShatterMap" | "shape/whiteTilesFixed" => e("shape/pattern") == 5,
+ _ => crate::card3d::shown(param, &e).unwrap_or(true),
+ },
+ _ => {
+ let _ = b("");
+ true
+ }
+ }
+}
+
++/// Controls of GPU-accelerated effects that only the CPU implements: while any of them is away
++/// from its default the effect renders on the CPU. (Prefixes ending in `/` cover a whole group.)
++const CPU_ONLY_CONTROLS: &[(&str, &[&str])] = &[
++ (
++ "ec.color.lumetri",
++ &["highDynamicRange", "basicCorrection/inputLut", "creative/look", "curves/rgbCurves/", "curves/hueSaturationCurves/", "hslSecondary/"],
++ ),
++ (
++ "ec.color.colorama",
++ &["inputPhase/addPhase", "outputCycle/usePresetPalette", "modify/", "pixelSelection/matchingMode", "masking/maskingMode", "masking/compositeOverLayer"],
++ ),
++ (
++ "ec.keying.keylight",
++ &[
++ "foregroundColourCorrection/colourSuppression",
++ "foregroundColourCorrection/suppressionAmount",
++ "foregroundColourCorrection/colourBalanceSaturation",
++ "edgeColourCorrection/edgeColourSuppression",
++ "edgeColourCorrection/edgeSuppressionAmount",
++ "edgeColourCorrection/edgeColourBalanceSaturation",
++ "sourceCrops/xMethod",
++ "sourceCrops/yMethod",
++ "sourceCrops/edgeColourAlpha",
++ ],
++ ),
++ ("ec.noise.addgrain", &["viewingMode", "preset", "color/redBalance", "color/greenBalance", "color/blueBalance", "previewRegion/"]),
++ ("ec.blur.cameralens", &["irisProperties/diffractionFringe", "blurMap/blurMapLayer"]),
+ ];
+
++/// Whether the GPU kernel of effect `id` covers the instance's current settings (see
++/// [`CPU_ONLY_CONTROLS`]; plus Cell Pattern's HQ variants and Turbulent Displace's locked
++/// pinning).
++pub fn gpu_supported(id: &str, ctx: &crate::EffectCtx) -> bool {
++ match id {
++ "ec.generate.cellpattern" if (6..=10).contains(&ctx.params.e("cellPattern")) => return false,
++ "ec.distort.turbulentdisplace" if ctx.params.e("pinning") >= 8 => return false,
++ _ => {}
++ }
++ let Some((_, controls)) = CPU_ONLY_CONTROLS.iter().find(|(e, _)| *e == id) else { return true };
++ let Some(spec) = crate::find(id) else { return true };
++ spec.params
++ .iter()
++ .filter(|ps| controls.iter().any(|c| if c.ends_with('/') { ps.id.starts_with(c) } else { ps.id == *c }))
++ .all(|ps| ctx.params.get(ps.id).is_none_or(|v| *v == crate::default_value(ps, ctx.layer_size)))
++}
++
/// Implementation status of effect `id` (`Implemented` or `Partial: …`).
pub fn status(id: &str) -> String {
match PARTIAL.iter().find(|(e, _)| *e == id) {
@@@ -130,34 -122,6 +176,60 @@@ mod tests
assert!(have == want, "docs/effects.md is stale: UPDATE_DOCS=1 cargo test -p effectcraft-effects --lib effects_doc_is_current");
}
++ #[test]
++ fn cpu_only_controls_keep_effects_off_the_gpu() {
++ use effectcraft_keyframe::Value;
++ let ctx_with = |id: &str, set: &[(&str, Value)]| {
++ let s = crate::find(id).unwrap();
++ let mut values: std::collections::HashMap<String, Value> =
++ s.params.iter().map(|p| (p.id.to_string(), crate::default_value(p, [64.0, 64.0]))).collect();
++ for (k, v) in set {
++ values.insert(k.to_string(), v.clone());
++ }
++ crate::Params { values }
++ };
++ let ok = |id: &str, set: &[(&str, Value)]| {
++ let params = ctx_with(id, set);
++ let ctx = crate::EffectCtx { params: &params, time: 0.0, layer_size: [64.0, 64.0], seed: 0, adjustment: false, env: Default::default() };
++ super::gpu_supported(id, &ctx)
++ };
++ assert!(ok("ec.color.lumetri", &[]));
++ assert!(!ok("ec.color.lumetri", &[("hslSecondary/correction/saturation", Value::Scalar(50.0))]));
++ assert!(!ok("ec.noise.addgrain", &[("preset", Value::Enum(2))]));
++ assert!(ok("ec.generate.cellpattern", &[("cellPattern", Value::Enum(3))]));
++ assert!(!ok("ec.generate.cellpattern", &[("cellPattern", Value::Enum(9))]));
++ assert!(!ok("ec.distort.turbulentdisplace", &[("pinning", Value::Enum(9))]));
++ assert!(ok("ec.blur.gaussian", &[]));
++ }
++
+ #[test]
+ fn popups_choose_the_shown_controls() {
+ use effectcraft_keyframe::Value;
+ let with = |pairs: &'static [(&'static str, u32)]| move |id: &str| pairs.iter().find(|(k, _)| *k == id).map(|(_, v)| Value::Enum(*v));
+ let shown = |e: &str, p: &str, pairs: &'static [(&'static str, u32)]| super::param_shown(e, p, &with(pairs));
+ // Levels: RGB shows the master controls only; Red shows the red ones.
+ assert!(shown("ec.color.levels", "inBlack", &[]));
+ assert!(!shown("ec.color.levels", "redInBlack", &[]));
+ assert!(shown("ec.color.levels", "redInBlack", &[("channel", 1)]));
+ assert!(!shown("ec.color.levels", "inBlack", &[("channel", 1)]));
+ assert!(shown("ec.color.levels", "channel", &[("channel", 1)]));
+ // Hue/Saturation: Master or one colour range.
+ assert!(shown("ec.color.huesaturation", "hue", &[]));
+ assert!(shown("ec.color.huesaturation", "bluesHue", &[("channelControl", 5)]));
+ assert!(!shown("ec.color.huesaturation", "redsHue", &[("channelControl", 5)]));
+ // Card effects: the camera system's group.
+ assert!(shown("ec.sim.carddance", "cameraPosition", &[]));
+ assert!(!shown("ec.sim.carddance", "cornerPins", &[]));
+ assert!(shown("ec.transition.cardwipe", "cornerPins/upperLeftCorner", &[("cameraSystem", 1)]));
+ assert!(!shown("ec.sim.shatter", "shape/customShatterMap", &[]));
+ // Selective Color: the chosen range's Details group.
+ assert!(shown("ec.color.selectivecolor", "details/reds", &[]));
+ assert!(!shown("ec.color.selectivecolor", "details/blues/bluesCyan", &[]));
+ assert!(shown("ec.color.selectivecolor", "details", &[]));
+ // Everything else is always shown.
+ assert!(shown("ec.blur.gaussian", "blurriness", &[]));
+ }
+
#[test]
fn partial_notes_name_registered_effects() {
for (id, note) in super::PARTIAL {
diff --cc crates/effects/src/keylight.rs
index 92a7d74f8,96a4483ac..4ccfea429
--- a/crates/effects/src/keylight.rs
+++ b/crates/effects/src/keylight.rs
@@@ -126,104 -126,6 +126,109 @@@ fn correct(c: [f32; 3], sat: f32, contr
c.map(|v| ((v - 0.5) * contrast + 0.5) * bright)
}
+/// Colour Suppression choices.
+const SUPPRESS: [&str; 7] = ["None", "Red", "Green", "Blue", "Cyan", "Magenta", "Yellow"];
+/// Source Crops' X / Y Method choices.
+const CROP_METHODS: [&str; 4] = ["Colour", "Repeat", "Reflect", "Wrap"];
+
+/// (colour, balance 0..1, amount 0..1) of a Colour Suppression setting.
+fn suppression(ctx: &EffectCtx, kind: &str, bal: &str, amt: &str) -> (u32, f32, f32) {
+ (ctx.params.e(kind), (ctx.params.get(bal).map(Value::as_f64).unwrap_or(50.0) / 100.0) as f32, (ctx.params.f(amt) / 100.0) as f32)
+}
+
+/// Colour Suppression: remove the excess of a primary (over a Balance-weighted mix of the other
+/// two) or of a secondary (the smaller of its two primaries over the third).
+fn suppress(mut c: [f32; 3], (kind, bal, amt): (u32, f32, f32)) -> [f32; 3] {
+ if kind == 0 || amt <= 0.0 {
+ return c;
+ }
+ match kind {
+ 1..=3 => {
+ let k = kind as usize - 1;
+ let (a, b) = ((k + 1) % 3, (k + 2) % 3);
+ let limit = c[a] * bal + c[b] * (1.0 - bal);
+ c[k] -= (c[k] - limit).max(0.0) * amt;
+ }
+ _ => {
+ // Cyan = G + B over R, Magenta = R + B over G, Yellow = R + G over B.
+ let third = match kind {
+ 4 => 0,
+ 5 => 1,
+ _ => 2,
+ };
+ let (a, b) = ((third + 1) % 3, (third + 2) % 3);
+ let excess = (c[a].min(c[b]) - c[third]).max(0.0) * amt;
+ c[a] -= excess;
+ c[b] -= excess;
+ }
+ }
+ c
+}
+
+/// (tint offset) of a Colour Balancing wheel: hue (degrees) and saturation (0..1).
+fn balance(ctx: &EffectCtx, hue: &str, sat: &str) -> [f32; 3] {
+ let s = (ctx.params.f(sat) / 100.0) as f32;
+ if s <= 0.0 {
+ return [0.0; 3];
+ }
+ let (r, g, b) = effectcraft_color::hsl_to_rgb((ctx.params.f(hue) / 360.0).rem_euclid(1.0) as f32, 1.0, 0.5);
+ let l = luminance(r, g, b);
+ [(r - l) * s * 0.5, (g - l) * s * 0.5, (b - l) * s * 0.5]
+}
+
+/// Colour Balancing: shift the colour towards the wheel's hue, keeping its luminance.
+fn colour_balance(c: [f32; 3], tint: [f32; 3]) -> [f32; 3] {
+ if tint == [0.0; 3] {
+ return c;
+ }
+ [c[0] + tint[0], c[1] + tint[1], c[2] + tint[2]].map(|v| v.max(0.0))
+}
+
+/// The layer with Source Crops applied: inside the crop the picture, outside it the Edge Colour
+/// (X / Y Method Colour) or the kept picture repeated, reflected or wrapped.
+fn crop_source(ctx: &EffectCtx, b: &Buf) -> Image {
+ let pr = ctx.params;
+ let crops = [pr.f("sourceCrops/cropLeft"), pr.f("sourceCrops/cropRight"), pr.f("sourceCrops/cropTop"), pr.f("sourceCrops/cropBottom")].map(|v| v / 100.0);
+ if crops.iter().all(|c| *c <= 0.0) {
+ return b.img.clone();
+ }
+ let (lw, lh) = (ctx.layer_size[0] * b.scale, ctx.layer_size[1] * b.scale);
+ let (x0, x1) = (b.offset[0] + crops[0] * lw, b.offset[0] + (1.0 - crops[1]) * lw);
+ let (y0, y1) = (b.offset[1] + crops[2] * lh, b.offset[1] + (1.0 - crops[3]) * lh);
+ let methods = [pr.e("sourceCrops/xMethod"), pr.e("sourceCrops/yMethod")];
+ let ec = pr.color("sourceCrops/edgeColour");
+ let ea = (pr.f("sourceCrops/edgeColourAlpha") / 100.0) as f32;
++ if methods == [0, 0] && ea <= 0.0 {
++ // Transparent edge colour: the borders are cut from the result instead (keying sees
++ // the whole picture).
++ return b.img.clone();
++ }
+ let edge = premul([ec[0], ec[1], ec[2]], ea);
+ // Fold a coordinate into [lo, hi) by a method; None = outside with Colour.
+ let fold = |v: f64, lo: f64, hi: f64, m: u32| -> Option<f64> {
+ let span = (hi - lo).max(1.0);
+ if v >= lo && v < hi {
+ return Some(v);
+ }
+ match m {
+ 1 => Some(v.clamp(lo, hi - 0.5)),
+ 2 => {
+ let t = (v - lo).rem_euclid(2.0 * span);
+ Some(lo + if t >= span { 2.0 * span - t - 0.5 } else { t })
+ }
+ 3 => Some(lo + (v - lo).rem_euclid(span)),
+ _ => None,
+ }
+ };
+ crate::util::gen_image(b.img.width, b.img.height, |x, y| {
+ let (fx, fy) = (x as f64 + 0.5, y as f64 + 0.5);
+ match (fold(fx, x0, x1, methods[0]), fold(fy, y0, y1, methods[1])) {
+ (Some(sx), Some(sy)) => b.img.get_clamped(sx.floor() as i64, sy.floor() as i64),
+ _ => edge,
+ }
+ })
+}
+
fn key_light(ctx: &EffectCtx, mut b: Buf) -> Buf {
let pr = ctx.params;
let view = pr.e("view");
diff --cc crates/effects/src/lib.rs
index 95dc6418b,c81cb8dbd..6f6716306
--- a/crates/effects/src/lib.rs
+++ b/crates/effects/src/lib.rs
@@@ -61,17 -64,22 +65,26 @@@ pub mod warp_stab
use std::collections::HashMap;
use std::sync::OnceLock;
-pub use color_fx::{exposure_settings, levels_clip};
+pub use card3d::{CompLight, CompScene};
+pub use color_fx::{
+ HUESAT_CHANNELS, LEVELS_CHANNELS, exposure_settings, fill_uses_masks, huesat_ranges_identity, levels_channel_ids, levels_channels_identity, levels_clip,
+};
pub use color2::Curve;
+pub use distort::transform_shutter;
+ pub use distort2::parse_mesh;
use effectcraft_keyframe::Value;
use effectcraft_project::build::Ids;
use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property};
pub use effectcraft_raster::{AuxChannels, Image};
-pub use misc::{INVERT_ALPHA, INVERT_CHANNELS};
+pub use misc::{INVERT_ALPHA, INVERT_CHANNELS, glow_operation};
+ pub use sim::particle_state;
+ pub use sim3::playground_state;
+ // CPU helpers the GPU kernels share (effectcraft-gpu).
-pub use blur2::camera_lens_spans;
++pub use blur2::{camera_lens_plain, camera_lens_spans};
+ pub use generate::gen_mode;
+ pub use generate2::pattern_kind as cell_pattern_kind;
+ pub use noise::GrainLook;
+ pub use transition::place_layer;
/// Effect categories in Effects & Presets order.
pub const CATEGORIES: &[&str] = &[
@@@ -265,16 -273,11 +278,21 @@@ pub trait EffectHost: Sync
fn aux(&self) -> Option<std::sync::Arc<AuxChannels>> {
None
}
+ /// The composition's camera and first light relative to the effect's layer (Card
+ /// Dance / Shatter / Card Wipe's Comp Camera and First Comp Light). `None` when unknown.
+ fn comp_scene(&self) -> Option<CompScene> {
+ None
+ }
+ /// The running effect's own parameters evaluated at another **layer time** (Radio Waves'
+ /// Parameters Are Set At: Birth). `None` when unavailable.
+ fn params_at(&self, _layer_time: f64) -> Option<Params> {
+ None
+ }
+ /// A particle simulation backend (GPU particles; see [`psim`]). `None` = simulate on the
+ /// CPU.
+ fn particles(&self) -> Option<&dyn psim::ParticleSim> {
+ None
+ }
}
/// Extra context the renderer may supply (all optional; `Default` is "nothing known").
diff --cc crates/effects/src/sim3.rs
index a8763d850,f7425df7c..888ebd7da
--- a/crates/effects/src/sim3.rs
+++ b/crates/effects/src/sim3.rs
@@@ -559,59 -276,15 +559,60 @@@ fn image_key(img: &Image) -> u64
h.finish()
}
+fn mapper_from(ctx: &EffectCtx, group: &str, ephemeral: bool) -> Option<Mapper> {
+ let pr = ctx.params;
+ let map = ctx.layer_param(&format!("{group}/useLayerAsMap"), true).map(|lp| MapImg::from(ctx, lp))?;
+ let ch = |c: &str| {
+ (
+ pr.e(&format!("{group}/map{c}To")),
+ if ephemeral { pr.e(&format!("{group}/{}Operator", c.to_lowercase())) } else { 0 },
+ pr.f(&format!("{group}/{}Min", c.to_lowercase())) as f32,
+ pr.f(&format!("{group}/{}Max", c.to_lowercase())) as f32,
+ )
+ };
+ Some(Mapper { map, chans: [ch("Red"), ch("Green"), ch("Blue")], affects: Affects::from(ctx, group) })
+}
+
+/// Draw a map layer frame as a particle: centred on (x, y) buffer px, rotated `angle` degrees
+/// and scaled, over `out`.
+fn blit_layer(out: &mut Image, lp: &crate::LayerPixels, x: f64, y: f64, angle: f64, scale: [f64; 2], buf_scale: f64, alpha: f32) {
+ let (w, h) = (lp.size[0] * scale[0].abs() * buf_scale, lp.size[1] * scale[1].abs() * buf_scale);
+ let r = (w * w + h * h).sqrt() * 0.5 + 1.0;
+ let (x0, x1) = ((x - r).floor().max(0.0) as i64, (x + r).ceil().min(out.width as f64) as i64);
+ let (y0, y1) = ((y - r).floor().max(0.0) as i64, (y + r).ceil().min(out.height as f64) as i64);
+ if x0 >= x1 || y0 >= y1 || scale[0] == 0.0 || scale[1] == 0.0 {
+ return;
+ }
+ let (sa, ca) = angle.to_radians().sin_cos();
+ for py in y0..y1 {
+ for px in x0..x1 {
+ let (dx, dy) = ((px as f64 + 0.5 - x) / buf_scale, (py as f64 + 0.5 - y) / buf_scale);
+ // Undo rotation, then scale; into map layer pixels around its centre.
+ let (u, v) = ((dx * ca + dy * sa) / scale[0] + lp.size[0] * 0.5, (-dx * sa + dy * ca) / scale[1] + lp.size[1] * 0.5);
+ if u < 0.0 || v < 0.0 || u >= lp.size[0] || v >= lp.size[1] {
+ continue;
+ }
+ let s = lp.buf.img.sample_bilinear(u * lp.buf.scale + lp.buf.offset[0], v * lp.buf.scale + lp.buf.offset[1]);
+ if s[3] <= 0.0 {
+ continue;
+ }
+ let d = out.get(px, py);
+ let k = 1.0 - s[3] * alpha;
+ out.set(px as u32, py as u32, [s[0] * alpha + d[0] * k, s[1] * alpha + d[1] * k, s[2] * alpha + d[2] * k, s[3] * alpha + d[3] * k]);
+ }
+ }
+}
+
- fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
+ /// Particle Playground's producers and forces.
+ fn pg_of(ctx: &EffectCtx) -> Pg {
let pr = ctx.params;
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
let grav_dir = (pr.f("gravity/gravityDirection") as f32).to_radians();
let gf = pr.f("gravity/gravityForce") as f32;
let wall = (pr.f("wall/wallBoundary").round() as usize).checked_sub(1).and_then(|i| ctx.env.masks.get(i)).map(|m| m.points.clone());
- let mapper = if pr.b("mapperEnabled") { ctx.layer_param("persistentPropertyMapper/useLayerAsMap", true).map(|lp| MapImg::from(ctx, lp)) } else { None };
+ let persistent = if pr.b("mapperEnabled") { mapper_from(ctx, "persistentPropertyMapper", false) } else { None };
+ let ephemeral = mapper_from(ctx, "ephemeralPropertyMapper", true);
- let pg = Pg {
+ Pg {
cannon: pr.b("cannonEnabled"),
pos: { pr.v2("cannon/cannonPosition").map(|v| v as f32) },
barrel_angle: pr.f("cannon/barrelAngle") as f32,
@@@ -622,23 -295,47 +623,103 @@@
vel_spread: pr.f("cannon/velocityRandomSpread") as f32,
color: pr.color("cannon/cannonColor"),
radius: pr.f("cannon/cannonParticleRadius").max(0.0) as f32,
+ cannon_text: pr.s("options/cannonText").chars().collect(),
+ pex_radius: pr.f("particleExploder/radiusOfNewParticles").max(0.0) as f32,
+ pex_dispersion: pr.f("particleExploder/velocityDispersion") as f32,
+ pex_affects: Affects::from(ctx, "particleExploder"),
gravity: [grav_dir.sin() * gf, -grav_dir.cos() * gf],
grav_spread: (pr.f("gravity/gravityForceRandomSpread") / 100.0).max(0.0) as f32,
+ grav_affects: Affects::from(ctx, "gravity"),
repel: pr.f("repel/repelForce") as f32 * 100.0,
repel_radius: pr.f("repel/repelForceRadius").max(0.0) as f32,
+ repel_affects: Affects::from(ctx, "repel"),
wall,
- mapper,
- map_to: [
- (pr.e("persistentPropertyMapper/mapRedTo"), pr.f("persistentPropertyMapper/redMin") as f32, pr.f("persistentPropertyMapper/redMax") as f32),
- (pr.e("persistentPropertyMapper/mapGreenTo"), pr.f("persistentPropertyMapper/greenMin") as f32, pr.f("persistentPropertyMapper/greenMax") as f32),
- (pr.e("persistentPropertyMapper/mapBlueTo"), pr.f("persistentPropertyMapper/blueMin") as f32, pr.f("persistentPropertyMapper/blueMax") as f32),
- ],
+ wall_affects: Affects::from(ctx, "wall"),
+ persistent,
+ ephemeral,
seed: (pr.f("randomSeed") as u32).wrapping_mul(0x9e37_79b9) ^ ctx.seed,
bounds: [-lw * 2.0, -lh * 2.0, lw * 3.0, lh * 3.0],
+ }
+ }
+
++impl Pg {
++ /// Only a cannon with gravity: every particle moves on its own (what the host's particle
++ /// backend can simulate).
++ fn cannon_only(&self) -> bool {
++ self.cannon
++ && !(self.repel != 0.0 && self.repel_radius > 0.0)
++ && self.wall.is_none()
++ && self.persistent.is_none()
++ && self.ephemeral.is_none()
++ && self.pex_radius <= 0.0
++ && self.grav_affects.is_all()
++ }
++}
++
++impl Affects {
++ /// Affects everything (the defaults).
++ fn is_all(&self) -> bool {
++ self.from == 0 && self.selection.is_none() && self.chars.is_empty() && self.age == 0.0
++ }
++}
++
++/// Particle Playground cannons with gravity only, simulated by the host's particle backend.
++fn pg_accelerated(ctx: &EffectCtx, key: u64, pg: &Pg) -> Option<std::sync::Arc<PgState>> {
++ let backend = ctx.env.host?.particles()?;
++ let steps = steps_at(ctx.time);
++ let births = crate::psim::births(pg.rate, steps, 60_000)?;
++ let desc = crate::psim::CannonDesc {
++ pos: pg.pos,
++ barrel_angle: pg.barrel_angle,
++ barrel_radius: pg.barrel_radius,
++ dir_spread: pg.dir_spread,
++ vel: pg.vel,
++ vel_spread: pg.vel_spread,
++ gravity: pg.gravity,
++ grav_spread: pg.grav_spread,
++ seed: pg.seed,
++ bounds: pg.bounds,
+ };
++ let req = crate::psim::SimRequest { key, steps, births: &births, system: crate::psim::ParticleSystem::Cannon(desc) };
++ let parts = backend.simulate(&req)?;
++ Some(std::sync::Arc::new(PgState {
++ parts: parts
++ .into_iter()
++ .map(|q| {
++ let born = pg.spawn(q.id);
++ PgParticle { p: [q.p[0], q.p[1]], v: [q.v[0], q.v[1]], ..born }
++ })
++ .collect(),
++ carry: 0.0,
++ next_id: births.len() as u32,
++ }))
++}
++
+ /// The live particles of a Particle Playground whose cannon is the only producer and force
+ /// besides gravity, at `ctx.time`: from the host's particle backend when it has one (GPU
+ /// particles), else from the CPU simulation (`None` for other set-ups). For comparing the two.
+ pub fn playground_state(ctx: &EffectCtx) -> Option<Vec<crate::psim::SimParticle>> {
+ let pg = pg_of(ctx);
+ let pr = ctx.params;
+ let grid = pr.b("gridEnabled") && pr.f("grid/particlesAcross").round() > 0.0 && pr.f("grid/particlesDown").round() > 0.0;
+ let exploder = pr.b("exploderEnabled") && pr.get("layerExploder/explodeLayer").and_then(Value::as_layer).is_some();
- if !pg.cannon || grid || exploder || (pg.repel != 0.0 && pg.repel_radius > 0.0) || pg.wall.is_some() || pg.mapper.is_some() {
++ if !pg.cannon_only() || grid || exploder {
+ return None;
+ }
+ let key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 0x7067);
+ let st = pg_accelerated(ctx, key, &pg).unwrap_or_else(|| PG_CACHE.run(key, steps_at(ctx.time), PgState::default, |st, _| pg.step(st)));
+ Some(
+ st.parts
+ .iter()
+ .map(|q| crate::psim::SimParticle { p: [q.p[0], q.p[1], 0.0], v: [q.v[0], q.v[1], 0.0], age: 0.0, life: 0.0, rnd: 0.0, id: q.id })
+ .collect(),
+ )
+ }
+
+ fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
+ let pr = ctx.params;
+ let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
+ let pg = pg_of(ctx);
// Initial particles: Grid and Layer Exploder.
let grid_on = pr.b("gridEnabled");
let across = pr.f("grid/particlesAcross").max(0.0).round() as u32;
@@@ -730,82 -407,32 +811,85 @@@
}
st
};
- let st = PG_CACHE.run(key, steps_at(ctx.time), init, |st, _| pg.step(st));
+ // A cannon with gravity only: every particle moves on its own (GPU particles).
- let independent = pg.cannon
- && !(grid_on && across > 0 && down > 0)
- && exploder.is_none()
- && !(pg.repel != 0.0 && pg.repel_radius > 0.0)
- && pg.wall.is_none()
- && pg.mapper.is_none();
++ let independent = pg.cannon_only() && !(grid_on && across > 0 && down > 0) && exploder.is_none();
+ let gpu = if independent { pg_accelerated(ctx, key, &pg) } else { None };
+ let st = gpu.unwrap_or_else(|| PG_CACHE.run(key, steps_at(ctx.time), init, |st, _| pg.step(st)));
+ // Render: what the ephemeral mapper changes shows for this frame only.
+ let parts: Vec<PgParticle> = st.parts.iter().map(|q| pg.ephemeral(q)).collect();
+ let auto_orient = pr.b("options/autoOrientRotation");
let s = b.scale as f32;
- let sprites: Vec<Sprite> = st
- .parts
- .iter()
- .map(|q| {
- let (x, y) = b.to_px([q.p[0] as f64, q.p[1] as f64]);
- let c = match &layer_map {
- Some(m) => {
- let mc = m.at(q.origin[0], q.origin[1]);
- [mc[0], mc[1], mc[2], mc[3] * q.c[3]]
+ // Layer Map: affected particles show the map layer (at a time set by the offset type).
+ let map_id = if pr.b("layerMapEnabled") { pr.get("layerMap/layerMapLayer").and_then(Value::as_layer) } else { None };
+ let map_affects = Affects::from(ctx, "layerMap");
+ let offset_type = pr.e("layerMap/timeOffsetType");
+ let offset = pr.f("layerMap/timeOffset");
+ let fps = ctx.fps();
+ let mut frames: std::collections::HashMap<i64, Option<crate::LayerPixels>> = std::collections::HashMap::new();
+ let mut sprites: Vec<Sprite> = vec![];
+ let mut blits: Vec<(PgParticle, i64)> = vec![];
+ for q in &parts {
+ let (x, y) = b.to_px([q.p[0] as f64, q.p[1] as f64]);
+ let angle = if auto_orient && (q.v[0] != 0.0 || q.v[1] != 0.0) { q.v[1].atan2(q.v[0]).to_degrees() + 90.0 } else { q.angle };
+ if let (Some(_), true) = (map_id, map_affects.weight(q) > 0.5) {
+ let rnd = hash1(q.id, 41, seed) as f64;
+ let t = match offset_type {
+ 1 => offset,
+ 2 => ctx.env.comp_time + offset * rnd,
+ 3 => offset * rnd,
+ _ => ctx.env.comp_time + offset,
+ } + q.toff as f64;
+ let frame = (t * fps).round() as i64;
+ blits.push((PgParticle { angle, ..*q }, frame));
+ continue;
+ }
+ let sc = (q.scale[0] + q.scale[1]) * 0.5;
+ match char::from_u32(q.ch).filter(|c| q.ch != 0 && *c != ' ') {
+ Some(c) => {
+ // A text particle: the character's strokes, Font Size tall, rotated.
+ let size = (q.r * sc * s) as f64;
+ let u = size * 0.7 / 6.0;
+ let wgt = (size * 0.045).max(0.35) as f32;
+ let (sa, ca) = (angle as f64).to_radians().sin_cos();
+ let tr = |g: [f64; 2]| {
+ let (gx, gy) = ((g[0] - 2.0) * u * q.scale[0] as f64 / sc.max(1e-6) as f64, (g[1] - 3.0) * u * q.scale[1] as f64 / sc.max(1e-6) as f64);
+ [x + gx * ca - gy * sa, y + gx * sa + gy * ca]
+ };
+ for stroke in crate::textfx::glyph_strokes(c) {
+ if stroke.len() == 1 {
+ let p0 = tr(stroke[0]);
+ sprites.push(Sprite::new(p0[0] as f32, p0[1] as f32, wgt, q.c, Shape::Disc));
+ }
+ for w2 in stroke.windows(2) {
+ let (a0, a1) = (tr(w2[0]), tr(w2[1]));
+ sprites.push(Sprite::new(a0[0] as f32, a0[1] as f32, wgt, q.c, Shape::Line { dx: (a1[0] - a0[0]) as f32, dy: (a1[1] - a0[1]) as f32 }));
+ }
}
- None => q.c,
- };
- Sprite::new(x as f32, y as f32, q.r * s, c, Shape::Disc)
- })
- .collect();
- let fx = splat(b.img.width, b.img.height, &sprites, Acc::Over);
+ }
+ None => sprites.push(Sprite::new(x as f32, y as f32, q.r * sc * s, q.c, Shape::Disc)),
+ }
+ }
+ let mut fx = splat(b.img.width, b.img.height, &sprites, Acc::Over);
+ if let (Some(id), Some(host)) = (map_id, ctx.env.host) {
+ let me = pr.get(&crate::layer_source_id("layerMap/layerMapLayer")).is_none_or(|v| v.as_enum() != 0);
+ for (q, frame) in &blits {
+ if !frames.contains_key(frame) && frames.len() >= 32 {
+ // Too many distinct times: reuse the nearest fetched frame.
+ if let Some(k) = frames.keys().min_by_key(|k| (*k - frame).abs()).copied()
+ && let Some(Some(lp)) = frames.get(&k)
+ {
+ let (x, y) = b.to_px([q.p[0] as f64, q.p[1] as f64]);
+ blit_layer(&mut fx, lp, x, y, q.angle as f64, [q.scale[0] as f64, q.scale[1] as f64], b.scale, q.c[3]);
+ }
+ continue;
+ }
+ let lp = frames.entry(*frame).or_insert_with(|| host.layer_at(id, *frame as f64 / fps, me));
+ if let Some(lp) = lp {
+ let (x, y) = b.to_px([q.p[0] as f64, q.p[1] as f64]);
+ blit_layer(&mut fx, lp, x, y, q.angle as f64, [q.scale[0] as f64, q.scale[1] as f64], b.scale, q.c[3]);
+ }
+ }
+ }
// Particles replace the layer's own pixels.
b.img = combine(&b.img, &fx, 5);
b
diff --cc crates/gpu/src/effects.rs
index d0a60dcee,2ef75c48c..3691ae17e
--- a/crates/gpu/src/effects.rs
+++ b/crates/gpu/src/effects.rs
@@@ -62,7 -62,49 +62,53 @@@ pub(crate) fn run_chain(e: &mut Enc, ch
Some(Buf { img, offset: b.offset, scale: b.scale })
}
+ /// An effect stack running on a GPU-resident image (adjustment layers): GPU chains stay on
+ /// the device; CPU effects read the image back, run, and upload the result.
+ pub(crate) struct GpuFx<'e, 'g> {
+ e: &'e mut Enc<'g>,
+ b: Option<GBuf>,
+ levels: Option<f32>,
+ }
+
+ impl<'e, 'g> GpuFx<'e, 'g> {
+ pub fn new(e: &'e mut Enc<'g>, img: GpuImage, offset: [f64; 2], scale: f64, levels: Option<f32>) -> Self {
+ GpuFx { e, b: Some(GBuf { img, offset, scale }), levels }
+ }
+
+ /// The result: (image, offset, scale); `None` when a step failed.
+ pub fn finish(self) -> Option<(GpuImage, [f64; 2], f64)> {
+ self.b.map(|b| (b.img, b.offset, b.scale))
+ }
+ }
+
+ impl effectcraft_render::FxTarget for GpuFx<'_, '_> {
+ fn gpu(&mut self, steps: &[FxStep]) -> bool {
+ let Some(b) = &self.b else { return false };
+ let mut cur = GBuf { img: b.img.clone(), offset: b.offset, scale: b.scale };
+ for step in steps {
+ let Some(next) = apply(self.e, step.spec.id, &step.ctx, cur) else { return false };
+ cur = next;
+ if let Some(l) = self.levels {
+ cur.img = ops::quantize(self.e, &cur.img, l);
+ }
+ }
+ self.b = Some(cur);
+ true
+ }
+
+ fn cpu(&mut self, f: &mut dyn FnMut(Buf) -> Buf) {
+ let Some(b) = self.b.take() else { return };
+ let Some(img) = self.e.download(&b.img) else { return };
+ let out = f(Buf { img, offset: b.offset, scale: b.scale });
+ self.b = self.e.g.upload_image(&out.img).map(|img| GBuf { img, offset: out.offset, scale: out.scale });
+ }
+ }
+
fn apply(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
++ // Controls the kernels do not implement render on the CPU.
++ if !effectcraft_effects::catalog::gpu_supported(id, ctx) {
++ return None;
++ }
match id {
"ec.blur.gaussian" => gaussian(e, ctx, b),
"ec.blur.fastbox" => box_blur(e, ctx, b),
diff --cc crates/gpu/src/fx_color.rs
index 000000000,824f9a501..ee6ab7e8f
mode 000000,100644..100644
--- a/crates/gpu/src/fx_color.rs
+++ b/crates/gpu/src/fx_color.rs
@@@ -1,0 -1,396 +1,396 @@@
+ //! GPU effects, colour family (kernels in `shaders/fx_color.wgsl`): the CPU effects' exact
+ //! steps with the pixel loops as compute kernels.
+ //!
+ //! Colour Balance, Vibrance, Black & White, Tritone, Colorama, Channel Mixer, Selective Color
+ //! and Linear Color Key are one per-pixel pass (`fxc_point`); Lumetri Color is a per-pixel pass
+ //! plus, with Sharpen, a luminance plane blurred like `util::gauss_plane`; Key Light runs its
+ //! matte pipeline (pre-blur, clip, rollback, despot, shrink / grow, softness, edge band) as
+ //! plane passes. Key Light with an Inside / Outside mask, or Hard Colour replacement after
+ //! Screen Softness, and Colorama with Interpolate Palette off run on the CPU.
+
+ use effectcraft_color::{luminance, rgb_to_hsl};
+ use effectcraft_effects::EffectCtx;
+
+ use crate::context::{Enc, GpuImage, Params};
+ use crate::effects::{GBuf, gaussian_blur};
+
+ /// Compute entry points in `fx_color.wgsl`.
+ pub(crate) const KERNELS: &[&str] = &[
+ "fxc_point",
+ "fxc_lumetri",
+ "fxc_luma",
+ "fxc_sharpen",
+ "fxc_morph",
+ "fxc_lerp",
+ "fxc_kl_raw",
+ "fxc_kl_rollback",
+ "fxc_kl_pack",
+ "fxc_kl_band",
+ "fxc_kl_edge",
+ "fxc_kl_final",
+ ];
+
+ /// Effect ids implemented here.
+ pub(crate) const IDS: &[&str] = &[
+ "ec.color.colorbalance",
+ "ec.color.vibrance",
+ "ec.color.lumetri",
+ "ec.color.blackwhite",
+ "ec.color.tritone",
+ "ec.color.colorama",
+ "ec.color.channelmixer",
+ "ec.color.selectivecolor",
+ "ec.key.linearcolor",
+ "ec.keying.keylight",
+ ];
+
+ /// Run effect `id` (one of [`IDS`]); `None` = this parameter combination runs on the CPU.
+ pub(crate) fn apply(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
+ match id {
+ "ec.color.lumetri" => lumetri(e, ctx, b),
+ "ec.keying.keylight" => key_light(e, ctx, b),
+ _ => point(e, id, ctx, b),
+ }
+ }
+
+ fn rgb(c: [f32; 4]) -> [f32; 4] {
+ [c[0], c[1], c[2], 0.0]
+ }
+
+ /// Same selective colour ids as `color2::SC_IDS`.
+ const SC_IDS: [[&str; 4]; 9] = [
- ["redsCyan", "redsMagenta", "redsYellow", "redsBlack"],
- ["yellowsCyan", "yellowsMagenta", "yellowsYellow", "yellowsBlack"],
- ["greensCyan", "greensMagenta", "greensYellow", "greensBlack"],
- ["cyansCyan", "cyansMagenta", "cyansYellow", "cyansBlack"],
- ["bluesCyan", "bluesMagenta", "bluesYellow", "bluesBlack"],
- ["magentasCyan", "magentasMagenta", "magentasYellow", "magentasBlack"],
- ["whitesCyan", "whitesMagenta", "whitesYellow", "whitesBlack"],
- ["neutralsCyan", "neutralsMagenta", "neutralsYellow", "neutralsBlack"],
- ["blacksCyan", "blacksMagenta", "blacksYellow", "blacksBlack"],
++ ["details/reds/redsCyan", "details/reds/redsMagenta", "details/reds/redsYellow", "details/reds/redsBlack"],
++ ["details/yellows/yellowsCyan", "details/yellows/yellowsMagenta", "details/yellows/yellowsYellow", "details/yellows/yellowsBlack"],
++ ["details/greens/greensCyan", "details/greens/greensMagenta", "details/greens/greensYellow", "details/greens/greensBlack"],
++ ["details/cyans/cyansCyan", "details/cyans/cyansMagenta", "details/cyans/cyansYellow", "details/cyans/cyansBlack"],
++ ["details/blues/bluesCyan", "details/blues/bluesMagenta", "details/blues/bluesYellow", "details/blues/bluesBlack"],
++ ["details/magentas/magentasCyan", "details/magentas/magentasMagenta", "details/magentas/magentasYellow", "details/magentas/magentasBlack"],
++ ["details/whites/whitesCyan", "details/whites/whitesMagenta", "details/whites/whitesYellow", "details/whites/whitesBlack"],
++ ["details/neutrals/neutralsCyan", "details/neutrals/neutralsMagenta", "details/neutrals/neutralsYellow", "details/neutrals/neutralsBlack"],
++ ["details/blacks/blacksCyan", "details/blacks/blacksMagenta", "details/blacks/blacksYellow", "details/blacks/blacksBlack"],
+ ];
+
+ fn point(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
+ let pr = ctx.params;
+ let f = |k: &str| pr.f(k) as f32;
+ let mut p = Params::default();
+ let mut data = None;
+ match id {
+ "ec.color.colorbalance" => {
+ let g = |k: &str| f(k) / 100.0;
+ p.u[0] = [1, pr.b("preserveLuminosity") as u32, 0, 0];
+ p.f[0] = [g("shadowRed"), g("shadowGreen"), g("shadowBlue"), 0.0];
+ p.f[1] = [g("midRed"), g("midGreen"), g("midBlue"), 0.0];
+ p.f[2] = [g("hiRed"), g("hiGreen"), g("hiBlue"), 0.0];
+ }
+ "ec.color.vibrance" => {
+ p.u[0][0] = 2;
+ p.f[0] = [f("vibrance") / 100.0, f("saturation") / 100.0, 0.0, 0.0];
+ }
+ "ec.color.blackwhite" => {
+ let w = ["reds", "yellows", "greens", "cyans", "blues", "magentas"].map(|k| f(k) / 100.0);
+ let tc = pr.color("tintColor");
+ let (th, ts, _) = rgb_to_hsl(tc[0], tc[1], tc[2]);
+ p.u[0] = [3, pr.b("tint") as u32, 0, 0];
+ p.f[0] = [w[0], w[1], w[2], w[3]];
+ p.f[1] = [w[4], w[5], 0.0, 0.0];
+ p.f[2] = [th, ts, 0.0, 0.0];
+ }
+ "ec.color.tritone" => {
+ p.u[0][0] = 4;
+ p.f[0] = rgb(pr.color("highlights"));
+ p.f[1] = rgb(pr.color("midtones"));
+ p.f[2] = rgb(pr.color("shadows"));
+ p.f[3][0] = 1.0 - f("blend") / 100.0;
+ }
+ "ec.color.colorama" => {
+ let smooth = pr.get("outputCycle/interpolatePalette").is_none_or(|v| v.as_bool());
+ // The posterized palette is discontinuous: phases on a step (common with 8 bpc
+ // input) can round to the other side in the GPU's float maths, so it runs on the CPU.
+ if !smooth {
+ return None;
+ }
+ p.u[0] = [5, pr.e("inputPhase/mode"), smooth as u32, 0];
+ p.f[0] = [pr.f("outputCycle/cycles").max(0.0) as f32, f("inputPhase/phaseShift") / 360.0, 1.0 - f("blend") / 100.0, 0.0];
+ }
+ "ec.color.channelmixer" => {
+ let g = |k: &str| f(k) / 100.0;
+ p.u[0] = [6, pr.b("monochrome") as u32, 0, 0];
+ p.f[0] = [g("rr"), g("rg"), g("rb"), g("rc")];
+ p.f[1] = [g("gr"), g("gg"), g("gb"), g("gc")];
+ p.f[2] = [g("br"), g("bg"), g("bb"), g("bc")];
+ }
+ "ec.color.selectivecolor" => {
+ let adj: Vec<f32> = SC_IDS.iter().flat_map(|ids| ids.map(|k| f(k) / 100.0)).collect();
+ if adj.iter().all(|v| *v == 0.0) {
+ return Some(b);
+ }
+ p.u[0] = [7, (pr.e("method") == 0) as u32, 0, 0];
+ data = Some(e.data(&adj));
+ }
+ "ec.key.linearcolor" => {
+ let view = pr.e("view");
+ if view == 1 {
+ return Some(b);
+ }
+ let k = pr.color("keyColor");
+ let s = k[0] + k[1] + k[2];
+ let kc = if s <= 1e-6 { [1.0 / 3.0, 1.0 / 3.0] } else { [k[0] / s, k[1] / s] };
+ let (kh, _, _) = rgb_to_hsl(k[0], k[1], k[2]);
+ p.u[0] = [8, pr.e("matchColors"), (pr.e("keyOperation") == 1) as u32, view];
+ p.f[0] = [k[0], k[1], k[2], f("tolerance") / 100.0];
+ p.f[1] = [f("softness") / 100.0, kc[0], kc[1], kh];
+ }
+ _ => return None,
+ }
+ let out = e.image(b.img.width, b.img.height);
+ e.pixels("fxc_point", &p, &b.img, None, &out, data.as_ref());
+ Some(GBuf { img: out, ..b })
+ }
+
+ /// color3::tint_offset.
+ fn tint_offset(c: [f32; 4]) -> [f32; 3] {
+ let l = (c[0] + c[1] + c[2]) / 3.0;
+ [c[0] - l, c[1] - l, c[2] - l]
+ }
+
+ fn lumetri(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
+ let pr = ctx.params;
+ let f = |k: &str| (pr.f(k) / 100.0) as f32;
+ let mut d: Vec<f32> = vec![
+ f("basicCorrection/whiteBalance/temperature"),
+ f("basicCorrection/whiteBalance/tint"),
+ 2f32.powf(pr.f("basicCorrection/tone/exposure") as f32),
+ f("basicCorrection/tone/contrast"),
+ f("basicCorrection/tone/highlights"),
+ f("basicCorrection/tone/shadows"),
+ f("basicCorrection/tone/whites"),
+ f("basicCorrection/tone/blacks"),
+ f("basicCorrection/saturation"),
+ f("creative/lookIntensity"),
+ f("creative/adjustments/fadedFilm"),
+ f("creative/adjustments/vibrance"),
+ f("creative/adjustments/creativeSaturation"),
+ (0.5 + 0.25 * f("creative/adjustments/tintBalance")).clamp(0.05, 0.95),
+ ];
+ d.extend(tint_offset(pr.color("creative/adjustments/shadowTint")));
+ d.extend(tint_offset(pr.color("creative/adjustments/highlightTint")));
+ for c in ["Master", "Red", "Green", "Blue"] {
+ for part in ["Shadows", "Midtones", "Highlights"] {
+ d.push(f(&format!("curves/curve{c}{part}")));
+ }
+ }
+ for w in ["shadowsWheel", "midtonesWheel", "highlightsWheel"] {
+ d.extend(tint_offset(pr.color(&format!("colorWheels/{w}"))));
+ }
+ let (lx, ly) = (b.offset[0], b.offset[1]);
+ let (lw, lh) = (ctx.layer_size[0] * b.scale, ctx.layer_size[1] * b.scale);
+ d.extend([
+ pr.f("vignette/vignetteAmount") as f32,
+ f("vignette/vignetteMidpoint") * 0.9,
+ f("vignette/vignetteRoundness"),
+ f("vignette/vignetteFeather"),
+ (lx + lw * 0.5) as f32,
+ (ly + lh * 0.5) as f32,
+ lw as f32,
+ lh as f32,
+ (lw / lh.max(1e-6)) as f32,
+ ]);
+ debug_assert_eq!(d.len(), 50);
+ let buf = e.data(&d);
+ let out = e.image(b.img.width, b.img.height);
+ e.pixels("fxc_lumetri", &Params::default(), &b.img, None, &out, Some(&buf));
+ let sharpen = f("creative/adjustments/sharpen");
+ if sharpen == 0.0 {
+ return Some(GBuf { img: out, ..b });
+ }
+ let luma = e.image(out.width, out.height);
+ e.pixels("fxc_luma", &Params::default(), &out, None, &luma, None);
+ let blurred = gaussian_blur(e, &luma, b.scale, b.scale, true);
+ let mut p = Params::default();
+ p.f[0][0] = sharpen * 2.0;
+ let sharp = e.image(out.width, out.height);
+ e.pixels("fxc_sharpen", &p, &out, Some(&blurred), &sharp, None);
+ Some(GBuf { img: sharp, ..b })
+ }
+
+ // ---------------------------------------------------------------- planes
+
+ /// util::morph_plane with the same radius on both axes; `modes` = per-channel operation
+ /// (0 erode, 1 dilate, 2 keep).
+ fn morph(e: &mut Enc, img: &GpuImage, r: u32, modes: [u32; 4]) -> GpuImage {
+ if r == 0 {
+ return img.clone();
+ }
+ let mut cur = img.clone();
+ for vertical in [0, 1] {
+ let mut p = Params::default();
+ p.u[0] = [r, vertical, 0, 0];
+ p.u[1] = modes;
+ let out = e.image(cur.width, cur.height);
+ e.pixels("fxc_morph", &p, &cur, None, &out, None);
+ cur = out;
+ }
+ cur
+ }
+
+ /// util::morph_frac (blend between the two nearest integer radii).
+ fn morph_frac(e: &mut Enc, img: &GpuImage, radius: f64, modes: [u32; 4]) -> GpuImage {
+ if radius <= 0.0 {
+ return img.clone();
+ }
+ let r0 = radius.floor() as u32;
+ let t = (radius - r0 as f64) as f32;
+ let a = morph(e, img, r0, modes);
+ if t < 1e-4 {
+ return a;
+ }
+ let b = morph(e, img, r0 + 1, modes);
+ let mut p = Params::default();
+ p.f[0][0] = t;
+ let out = e.image(img.width, img.height);
+ e.pixels("fxc_lerp", &p, &a, Some(&b), &out, None);
+ out
+ }
+
+ const ERODE_X: [u32; 4] = [0, 2, 2, 2];
+ const DILATE_X: [u32; 4] = [1, 2, 2, 2];
+
+ // ---------------------------------------------------------------- Key Light
+
+ /// keylight::primary.
+ fn primary(s: [f32; 3]) -> [u32; 3] {
+ let pi: usize = if s[1] >= s[0] && s[1] >= s[2] {
+ 1
+ } else if s[2] >= s[0] {
+ 2
+ } else {
+ 0
+ };
+ let (a, b) = match pi {
+ 0 => (1, 2),
+ 1 => (0, 2),
+ _ => (0, 1),
+ };
+ let ix = if s[a] >= s[b] { [pi, a, b] } else { [pi, b, a] };
+ ix.map(|i| i as u32)
+ }
+
+ fn neutralise(c: [f32; 3], bias: [f32; 3]) -> [f32; 3] {
+ let l = luminance(bias[0], bias[1], bias[2]).max(1e-4);
+ [0, 1, 2].map(|i| c[i] * l / bias[i].max(1e-4))
+ }
+
+ fn key_light(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option<GBuf> {
+ let pr = ctx.params;
+ let view = pr.e("view");
+ if view == 0 {
+ return Some(b);
+ }
+ // Inside / Outside masks (polygon coverage) run on the CPU.
+ let has_mask = |id: &str| pr.e(id).checked_sub(1).is_some_and(|i| ctx.env.masks.get(i as usize).is_some());
+ if has_mask("insideMask/insideMask") || has_mask("outsideMask/outsideMask") {
+ return None;
+ }
+ let sc = pr.color("screenColour");
+ let screen = [sc[0], sc[1], sc[2]];
+ let ix = primary(screen);
+ let (pi, o1, o2) = (ix[0] as usize, ix[1] as usize, ix[2] as usize);
+ let gain = pr.f("screenGain") as f32 / 100.0;
+ let bal = pr.f("screenBalance") as f32 / 100.0;
+ let dbias = pr.color("despillBias");
+ let abias = if pr.b("lockBiasesTogether") { dbias } else { pr.color("alphaBias") };
+ let (dbias, abias) = ([dbias[0], dbias[1], dbias[2]], [abias[0], abias[1], abias[2]]);
+ let s_alpha = neutralise(screen, abias);
+ let sd = (s_alpha[pi] - (bal * s_alpha[o1] + (1.0 - bal) * s_alpha[o2])).max(1e-3);
+ let cb = pr.f("screenMatte/clipBlack") as f32 / 100.0;
+ let cw = pr.f("screenMatte/clipWhite") as f32 / 100.0;
+ let rollback = pr.f("screenMatte/clipRollback") * b.scale;
+ let preblur = pr.f("screenPreblur") * b.scale;
+ let sg = pr.f("screenMatte/screenShrinkGrow") * b.scale;
+ let soft = pr.f("screenMatte/screenSoftness") * b.scale;
+ let despot_b = pr.f("screenMatte/screenDespotBlack") * b.scale;
+ let despot_w = pr.f("screenMatte/screenDespotWhite") * b.scale;
+ // Hard Colour replaces wherever the screen matte exceeds the raw matte by any amount; after
+ // Screen Softness's blur that compares float-rounded sums, so it runs on the CPU.
+ if pr.e("screenMatte/replaceMethod") == 2 && soft > 0.0 {
+ return None;
+ }
+ let (w, h) = (b.img.width, b.img.height);
+
+ let key_src = if preblur > 0.0 { gaussian_blur(e, &b.img, preblur * 0.5, preblur * 0.5, true) } else { b.img.clone() };
+ let mut p = Params::default();
+ p.u[0] = [ix[0], ix[1], ix[2], 0];
+ p.f[0] = [abias[0], abias[1], abias[2], sd];
+ p.f[1] = [gain, bal, cb, cw];
+ let raw = e.image(w, h);
+ e.pixels("fxc_kl_raw", &p, &key_src, None, &raw, None);
+ let mut m = raw.clone();
+ if rollback > 0.0 {
+ let sg_img = morph_frac(e, &m, rollback, [0, 1, 2, 2]);
+ let out = e.image(w, h);
+ e.pixels("fxc_kl_rollback", &Params::default(), &sg_img, Some(&raw), &out, None);
+ m = out;
+ }
+ if despot_b > 0.0 {
+ let d = morph_frac(e, &m, despot_b, DILATE_X);
+ m = morph_frac(e, &d, despot_b, ERODE_X);
+ }
+ if despot_w > 0.0 {
+ let d = morph_frac(e, &m, despot_w, ERODE_X);
+ m = morph_frac(e, &d, despot_w, DILATE_X);
+ }
+ if sg < 0.0 {
+ m = morph_frac(e, &m, -sg, ERODE_X);
+ } else if sg > 0.0 {
+ m = morph_frac(e, &m, sg, DILATE_X);
+ }
+ if soft > 0.0 {
+ m = gaussian_blur(e, &m, soft * 0.5, soft * 0.5, true);
+ }
+ let mut planes = e.image(w, h);
+ e.pixels("fxc_kl_pack", &Params::default(), &m, Some(&raw), &planes, None);
+ let src_alpha_mode = pr.e("insideMask/sourceAlpha");
+ if pr.b("edgeColourCorrection/enableEdgeColourCorrection") {
+ let grow = pr.f("edgeColourCorrection/edgeGrow") * b.scale;
+ let hard = (pr.f("edgeColourCorrection/edgeHardness") / 100.0) as f32;
+ let esoft = pr.f("edgeColourCorrection/edgeSoftness") * b.scale;
+ let mut p = Params::default();
+ p.u[0][0] = src_alpha_mode;
+ let mut band = e.image(w, h);
+ e.pixels("fxc_kl_band", &p, &b.img, Some(&planes), &band, None);
+ if grow > 0.0 {
+ band = morph_frac(e, &band, grow, DILATE_X);
+ }
+ if esoft > 0.0 {
+ band = gaussian_blur(e, &band, esoft * 0.5, esoft * 0.5, true);
+ }
+ let mut p = Params::default();
+ p.f[0][0] = hard;
+ let out = e.image(w, h);
+ e.pixels("fxc_kl_edge", &p, &planes, Some(&band), &out, None);
+ planes = out;
+ }
+ let pc = |k: &str| pr.f(k) as f32 / 100.0;
+ let l0 = (luminance(dbias[0], dbias[1], dbias[2]) / dbias[pi].max(1e-4)).max(1e-4);
+ let mut p = Params::default();
+ p.u[0] = [ix[0], ix[1], ix[2], view];
+ p.u[1] = [
+ pr.e("screenMatte/replaceMethod"),
+ pr.b("foregroundColourCorrection/enableColourCorrection") as u32,
+ pr.b("unpremultiplyResult") as u32,
+ src_alpha_mode,
+ ];
+ p.f[0] = [screen[0], screen[1], screen[2], bal];
+ p.f[1] = [dbias[0], dbias[1], dbias[2], l0];
+ p.f[2] = pr.color("screenMatte/replaceColour");
+ p.f[3] =
+ [pc("foregroundColourCorrection/saturation"), pc("foregroundColourCorrection/contrast") + 1.0, pc("foregroundColourCorrection/brightness") + 1.0, 0.0];
+ p.f[4] = [pc("edgeColourCorrection/edgeSaturation"), pc("edgeColourCorrection/edgeContrast") + 1.0, pc("edgeColourCorrection/edgeBrightness") + 1.0, 0.0];
+ p.f[5] = ["sourceCrops/cropLeft", "sourceCrops/cropRight", "sourceCrops/cropTop", "sourceCrops/cropBottom"].map(|k| (pr.f(k) / 100.0) as f32);
+ p.f[6] = [b.offset[0] as f32, b.offset[1] as f32, b.scale as f32, 0.0];
+ p.f[7] = [ctx.layer_size[0].max(1e-9) as f32, ctx.layer_size[1].max(1e-9) as f32, 0.0, 0.0];
+ let out = e.image(w, h);
+ e.pixels("fxc_kl_final", &p, &b.img, Some(&planes), &out, None);
+ Some(GBuf { img: out, ..b })
+ }
diff --cc crates/gpu/src/tests_fx_color.rs
index 000000000,8fb455b8a..28e80278b
mode 000000,100644..100644
--- a/crates/gpu/src/tests_fx_color.rs
+++ b/crates/gpu/src/tests_fx_color.rs
@@@ -1,0 -1,163 +1,177 @@@
+ //! GPU colour-family effects vs the CPU effects (the oracle): direct on a buffer at full and
+ //! half resolution, as adjustment, and composited at 8 and 32 bpc.
+
+ use effectcraft_keyframe::Value;
+
+ use crate::tests::{c, effect_case, n};
+
+ fn e(v: u32) -> Value {
+ Value::Enum(v)
+ }
+
+ fn on() -> Value {
+ Value::Bool(true)
+ }
+
+ #[test]
+ fn color_balance_vibrance_tritone_mixer() {
+ effect_case("ec.color.colorbalance", &[("shadowRed", n(40.0)), ("midGreen", n(-30.0)), ("hiBlue", n(60.0))]);
+ effect_case("ec.color.colorbalance", &[("shadowBlue", n(-50.0)), ("midRed", n(70.0)), ("hiGreen", n(25.0)), ("preserveLuminosity", on())]);
+ effect_case("ec.color.vibrance", &[("vibrance", n(60.0)), ("saturation", n(-20.0))]);
+ effect_case("ec.color.vibrance", &[("vibrance", n(-40.0)), ("saturation", n(35.0))]);
+ effect_case("ec.color.tritone", &[("midtones", c(0.6, 0.3, 0.5)), ("shadows", c(0.0, 0.1, 0.3)), ("blend", n(30.0))]);
+ effect_case("ec.color.tritone", &[("highlights", c(1.0, 0.9, 0.6))]);
+ effect_case("ec.color.channelmixer", &[("rr", n(80.0)), ("rg", n(30.0)), ("gb", n(-40.0)), ("bc", n(10.0)), ("br", n(50.0))]);
+ effect_case("ec.color.channelmixer", &[("rr", n(40.0)), ("rg", n(40.0)), ("rb", n(20.0)), ("rc", n(-5.0)), ("monochrome", on())]);
+ }
+
+ #[test]
+ fn black_white_colorama_selective_color() {
+ effect_case("ec.color.blackwhite", &[]);
+ effect_case("ec.color.blackwhite", &[("reds", n(120.0)), ("blues", n(-50.0)), ("cyans", n(200.0)), ("tint", on())]);
+ effect_case("ec.color.colorama", &[]);
+ effect_case("ec.color.colorama", &[("inputPhase/mode", e(4)), ("inputPhase/phaseShift", n(75.0)), ("outputCycle/cycles", n(2.5)), ("blend", n(40.0))]);
+ effect_case("ec.color.colorama", &[("inputPhase/mode", e(8)), ("outputCycle/cycles", n(1.3))]);
- effect_case("ec.color.selectivecolor", &[("redsCyan", n(60.0)), ("bluesYellow", n(-40.0)), ("neutralsBlack", n(20.0)), ("whitesMagenta", n(30.0))]);
+ effect_case(
+ "ec.color.selectivecolor",
- &[("method", e(1)), ("greensMagenta", n(50.0)), ("yellowsCyan", n(-30.0)), ("blacksYellow", n(40.0)), ("magentasBlack", n(25.0))],
++ &[
++ ("details/reds/redsCyan", n(60.0)),
++ ("details/blues/bluesYellow", n(-40.0)),
++ ("details/neutrals/neutralsBlack", n(20.0)),
++ ("details/whites/whitesMagenta", n(30.0)),
++ ],
++ );
++ effect_case(
++ "ec.color.selectivecolor",
++ &[
++ ("method", e(1)),
++ ("details/greens/greensMagenta", n(50.0)),
++ ("details/yellows/yellowsCyan", n(-30.0)),
++ ("details/blacks/blacksYellow", n(40.0)),
++ ("details/magentas/magentasBlack", n(25.0)),
++ ],
+ );
+ }
+
+ #[test]
+ fn lumetri() {
+ effect_case(
+ "ec.color.lumetri",
+ &[
+ ("basicCorrection/whiteBalance/temperature", n(30.0)),
+ ("basicCorrection/whiteBalance/tint", n(-20.0)),
+ ("basicCorrection/tone/exposure", n(0.5)),
+ ("basicCorrection/tone/contrast", n(25.0)),
+ ("basicCorrection/tone/highlights", n(-40.0)),
+ ("basicCorrection/tone/shadows", n(30.0)),
+ ("basicCorrection/tone/whites", n(10.0)),
+ ("basicCorrection/tone/blacks", n(-15.0)),
+ ("basicCorrection/saturation", n(130.0)),
+ ],
+ );
+ effect_case(
+ "ec.color.lumetri",
+ &[
+ ("creative/lookIntensity", n(80.0)),
+ ("creative/adjustments/fadedFilm", n(30.0)),
+ ("creative/adjustments/vibrance", n(40.0)),
+ ("creative/adjustments/creativeSaturation", n(70.0)),
+ ("creative/adjustments/shadowTint", c(0.3, 0.5, 0.7)),
+ ("creative/adjustments/highlightTint", c(0.7, 0.55, 0.4)),
+ ("creative/adjustments/tintBalance", n(-30.0)),
+ ("curves/curveMasterMidtones", n(30.0)),
+ ("curves/curveRedShadows", n(-20.0)),
+ ("curves/curveBlueHighlights", n(40.0)),
+ ],
+ );
+ effect_case(
+ "ec.color.lumetri",
+ &[
+ ("colorWheels/shadowsWheel", c(0.4, 0.5, 0.6)),
+ ("colorWheels/highlightsWheel", c(0.6, 0.5, 0.45)),
+ ("vignette/vignetteAmount", n(-2.0)),
+ ("vignette/vignetteMidpoint", n(30.0)),
+ ("vignette/vignetteRoundness", n(40.0)),
+ ("creative/adjustments/sharpen", n(50.0)),
+ ],
+ );
+ effect_case(
+ "ec.color.lumetri",
+ &[
+ ("vignette/vignetteAmount", n(1.5)),
+ ("vignette/vignetteRoundness", n(-60.0)),
+ ("vignette/vignetteFeather", n(20.0)),
+ ("creative/adjustments/sharpen", n(-40.0)),
+ ],
+ );
+ }
+
+ #[test]
+ fn linear_color_key() {
+ effect_case("ec.key.linearcolor", &[("keyColor", c(0.6, 0.5, 0.4)), ("tolerance", n(15.0)), ("softness", n(20.0))]);
+ effect_case("ec.key.linearcolor", &[("keyColor", c(0.2, 0.8, 0.3)), ("matchColors", e(1)), ("keyOperation", e(1)), ("view", e(2))]);
+ effect_case("ec.key.linearcolor", &[("keyColor", c(0.7, 0.3, 0.6)), ("matchColors", e(2)), ("tolerance", n(5.0)), ("softness", n(30.0))]);
+ }
+
+ #[test]
+ fn key_light() {
+ let screen = ("screenColour", c(0.3, 0.75, 0.35));
+ effect_case("ec.keying.keylight", std::slice::from_ref(&screen));
+ effect_case(
+ "ec.keying.keylight",
+ &[
+ // A low gain against a pure screen keeps the raw matte away from 0 (the screen
+ // removal divides by it; near 0 it amplifies the blurs' float rounding).
+ ("screenColour", c(0.0, 1.0, 0.0)),
+ ("screenGain", n(60.0)),
+ ("screenBalance", n(30.0)),
+ ("screenPreblur", n(3.0)),
+ ("screenMatte/clipBlack", n(10.0)),
+ ("screenMatte/clipWhite", n(80.0)),
+ ("screenMatte/clipRollback", n(2.5)),
+ ("screenMatte/screenSoftness", n(3.0)),
+ ("screenMatte/replaceMethod", e(3)),
+ ("screenMatte/replaceColour", c(0.6, 0.4, 0.3)),
+ ("unpremultiplyResult", Value::Bool(false)),
+ ],
+ );
+ effect_case(
+ "ec.keying.keylight",
+ &[
+ ("screenColour", c(0.2, 0.4, 0.8)),
+ ("lockBiasesTogether", Value::Bool(false)),
+ ("alphaBias", c(0.5, 0.45, 0.6)),
+ ("despillBias", c(0.55, 0.5, 0.45)),
+ ("screenMatte/clipWhite", n(70.0)),
+ ("screenMatte/screenDespotBlack", n(2.0)),
+ ("screenMatte/screenDespotWhite", n(1.5)),
+ ("screenMatte/screenShrinkGrow", n(-1.5)),
+ ("screenMatte/replaceMethod", e(2)),
+ ("foregroundColourCorrection/enableColourCorrection", on()),
+ ("foregroundColourCorrection/saturation", n(120.0)),
+ ("foregroundColourCorrection/contrast", n(15.0)),
+ ("edgeColourCorrection/enableEdgeColourCorrection", on()),
+ ("edgeColourCorrection/edgeSoftness", n(2.0)),
+ ("edgeColourCorrection/edgeHardness", n(30.0)),
+ ("edgeColourCorrection/edgeBrightness", n(-20.0)),
+ ("sourceCrops/cropLeft", n(13.0)),
+ ("sourceCrops/cropBottom", n(7.0)),
+ ("insideMask/sourceAlpha", e(1)),
+ ],
+ );
+ // Soft Colour without Screen Softness (after the blur, the screen-removed foreground of
+ // nearly transparent pixels, divided by a raw matte near 1e-4, amplifies float rounding).
+ effect_case(
+ "ec.keying.keylight",
+ &[
+ screen.clone(),
+ ("screenMatte/clipBlack", n(15.0)),
+ ("screenMatte/clipRollback", n(1.5)),
+ ("screenMatte/replaceColour", c(0.6, 0.4, 0.3)),
+ ("insideMask/sourceAlpha", e(0)),
+ ],
+ );
+ for view in [1, 2, 4, 7, 9] {
+ effect_case("ec.keying.keylight", &[screen.clone(), ("view", e(view)), ("screenMatte/screenShrinkGrow", n(1.0)), ("screenMatte/replaceMethod", e(1))]);
+ }
+ }
diff --cc docs/effects.md
index fb9901480,fd29541be..e35ae5f6f
--- a/docs/effects.md
+++ b/docs/effects.md
@@@ -3,11 -3,11 +3,11 @@@
<!-- Generated from the effect registry (crates/effects/src/catalog.rs); do not edit by hand.
Regenerate: UPDATE_DOCS=1 cargo test -p effectcraft-effects --lib effects_doc_is_current -->
- EffectCraft ships 303 effects with 2955 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over.
-EffectCraft ships 306 effects with 2488 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over.
++EffectCraft ships 306 effects with 3009 parameters in total, grouped into the same categories as the Effects & Presets panel. Every effect is our own implementation, written from public behaviour descriptions and standard image-processing literature. Parameter names, order, popup options, units, defaults and ranges follow the reference application so that projects, expressions and muscle memory carry over.
- - **GPU**: 24 effects also run on the GPU compositor with identical results.
- - **32**: 303 effects process 32-bit float (HDR, overbright) pixels without clamping.
- - **Status**: 303 implemented in full, 0 partial (what is missing is listed).
+ - **GPU**: 59 effects also run on the GPU compositor with identical results.
+ - **32**: 306 effects process 32-bit float (HDR, overbright) pixels without clamping.
-- **Status**: 264 implemented in full, 42 partial (what is missing is listed).
++- **Status**: 306 implemented in full, 0 partial (what is missing is listed).
Effects are addressed by id (`ec.<category>.<name>`) or display name in commands, scripts and the control channel, and every parameter by its id (`effects/#1/blurriness`).
@@@ -49,9 -49,9 +49,9 @@@
| Bilateral Blur | `ec.blur.bilateral` | 3 | | 32 | Implemented |
| CC Cross Blur | `ec.blur.cccross` | 3 | | 32 | Implemented |
| CC Radial Blur | `ec.blur.ccradial` | 4 | | 32 | Implemented |
- | CC Radial Fast Blur | `ec.blur.ccradialfast` | 3 | | 32 | Implemented |
+ | CC Radial Fast Blur | `ec.blur.ccradialfast` | 3 | GPU | 32 | Implemented |
| CC Vector Blur | `ec.blur.ccvector` | 4 | | 32 | Implemented |
- | Camera Lens Blur | `ec.blur.cameralens` | 16 | | 32 | Implemented |
-| Camera Lens Blur | `ec.blur.cameralens` | 10 | GPU | 32 | Partial: no Diffraction Fringe or Blur Map layer |
++| Camera Lens Blur | `ec.blur.cameralens` | 16 | GPU | 32 | Implemented |
| Camera-Shake Deblur | `ec.blur.camerashakedeblur` | 8 | | 32 | Implemented |
| Channel Blur | `ec.blur.channel` | 6 | | 32 | Implemented |
| Compound Blur | `ec.blur.compound` | 4 | | 32 | Implemented |
@@@ -102,28 -102,28 +102,28 @@@
| Color Balance (HLS) | `ec.color.colorbalancehls` | 3 | | 32 | Implemented |
| Color Link | `ec.color.colorlink` | 6 | | 32 | Implemented |
| Color Stabilizer | `ec.color.colorstabilizer` | 6 | | 32 | Implemented |
- | Colorama | `ec.color.colorama` | 20 | | 32 | Implemented |
-| Colorama | `ec.color.colorama` | 5 | GPU | 32 | Partial: no Add Phase, editable Output Cycle, Modify, Pixel Selection or Masking |
-| Curves | `ec.color.curves` | 0 | GPU | 32 | Partial: no Channel popup |
++| Colorama | `ec.color.colorama` | 20 | GPU | 32 | Implemented |
+| Curves | `ec.color.curves` | 0 | GPU | 32 | Implemented |
| Equalize | `ec.color.equalize` | 2 | | 32 | Implemented |
| Exposure | `ec.color.exposure` | 14 | GPU | 32 | Implemented |
| Gamma/Pedestal/Gain | `ec.color.gammapedestalgain` | 10 | | 32 | Implemented |
-| Hue/Saturation | `ec.color.huesaturation` | 7 | GPU | 32 | Partial: no per-range Channel Control |
+| Hue/Saturation | `ec.color.huesaturation` | 50 | GPU | 32 | Implemented |
| Leave Color | `ec.color.leavecolor` | 5 | | 32 | Implemented |
-| Levels | `ec.color.levels` | 7 | GPU | 32 | Partial: master channel only (no Channel popup) |
+| Levels | `ec.color.levels` | 36 | GPU | 32 | Implemented |
| Levels (Individual Controls) | `ec.color.levelsic` | 27 | | 32 | Implemented |
- | Lumetri Color | `ec.color.lumetri` | 66 | | 32 | Implemented |
-| Lumetri Color | `ec.color.lumetri` | 38 | GPU | 32 | Partial: no HSL Secondary, hue/saturation curves, HDR mode or look files |
++| Lumetri Color | `ec.color.lumetri` | 66 | GPU | 32 | Implemented |
| OCIO CDL Transform | `ec.color.ociocdl` | 12 | | 32 | Implemented |
- | OCIO Color Space Transform | `ec.color.ociocolorspace` | 4 | | 32 | Implemented |
- | OCIO Display Transform | `ec.color.ociodisplay` | 5 | | 32 | Implemented |
+ | OCIO Color Space Transform | `ec.color.ociocolorspace` | 7 | | 32 | Implemented |
+ | OCIO Display Transform | `ec.color.ociodisplay` | 9 | | 32 | Implemented |
| OCIO File Transform | `ec.color.ociofile` | 4 | | 32 | Implemented |
| OCIO Look Transform | `ec.color.ociolook` | 6 | | 32 | Implemented |
| PS Arbitrary Map | `ec.color.psarbitrarymap` | 2 | | 32 | Implemented |
| Photo Filter | `ec.color.photofilter` | 4 | | 32 | Implemented |
- | Selective Color | `ec.color.selectivecolor` | 38 | | 32 | Implemented |
-| Selective Color | `ec.color.selectivecolor` | 37 | GPU | 32 | Partial: simplified Colors / Details layout |
++| Selective Color | `ec.color.selectivecolor` | 38 | GPU | 32 | Implemented |
| Shadow/Highlight | `ec.color.shadowhighlight` | 14 | | 32 | Implemented |
| Tint | `ec.color.tint` | 3 | GPU | 32 | Implemented |
- | Tritone | `ec.color.tritone` | 4 | | 32 | Implemented |
- | Vibrance | `ec.color.vibrance` | 2 | | 32 | Implemented |
+ | Tritone | `ec.color.tritone` | 4 | GPU | 32 | Implemented |
+ | Vibrance | `ec.color.vibrance` | 2 | GPU | 32 | Implemented |
| Video Limiter | `ec.color.videolimiter` | 5 | | 32 | Implemented |
## Distort
@@@ -148,23 -148,23 +148,23 @@@
| CC Tiler | `ec.distort.cctiler` | 3 | | 32 | Implemented |
| Corner Pin | `ec.distort.cornerpin` | 4 | | 32 | Implemented |
| Detail-preserving Upscale | `ec.distort.upscale` | 4 | | 32 | Implemented |
- | Displacement Map | `ec.distort.displacementmap` | 8 | | 32 | Implemented |
+ | Displacement Map | `ec.distort.displacementmap` | 8 | GPU | 32 | Implemented |
| Liquify | `ec.distort.liquify` | 12 | | 32 | Implemented |
| Magnify | `ec.distort.magnify` | 10 | | 32 | Implemented |
- | Mesh Warp | `ec.distort.meshwarp` | 3 | | 32 | Implemented |
+ | Mesh Warp | `ec.distort.meshwarp` | 3 | GPU | 32 | Implemented |
| Mirror | `ec.distort.mirror` | 2 | | 32 | Implemented |
| Offset | `ec.distort.offset` | 2 | | 32 | Implemented |
-| Optics Compensation | `ec.distort.opticscompensation` | 5 | | 32 | Partial: no Optimal Pixels |
+| Optics Compensation | `ec.distort.opticscompensation` | 6 | | 32 | Implemented |
| Polar Coordinates | `ec.distort.polar` | 2 | | 32 | Implemented |
| Puppet | `ec.distort.puppet` | 1 | | 32 | Implemented |
-| Reshape | `ec.distort.reshape` | 6 | | 32 | Partial: no correspondence points |
+| Reshape | `ec.distort.reshape` | 6 | | 32 | Implemented |
- | Ripple | `ec.distort.ripple` | 7 | | 32 | Implemented |
+ | Ripple | `ec.distort.ripple` | 7 | GPU | 32 | Implemented |
-| Rolling Shutter Repair | `ec.distort.rollingshutterrepair` | 5 | | 32 | Partial: Pixel Motion Detail has no effect |
+| Rolling Shutter Repair | `ec.distort.rollingshutterrepair` | 5 | | 32 | Implemented |
| Smear | `ec.distort.smear` | 8 | | 32 | Implemented |
| Spherize | `ec.distort.spherize` | 2 | | 32 | Implemented |
-| Transform | `ec.distort.transform` | 10 | GPU | 32 | Partial: no shutter-angle motion blur |
-| Turbulent Displace | `ec.distort.turbulentdisplace` | 11 | GPU | 32 | Partial: no locked pinning variants |
+| Transform | `ec.distort.transform` | 12 | GPU | 32 | Implemented |
- | Turbulent Displace | `ec.distort.turbulentdisplace` | 11 | | 32 | Implemented |
- | Twirl | `ec.distort.twirl` | 3 | | 32 | Implemented |
++| Turbulent Displace | `ec.distort.turbulentdisplace` | 11 | GPU | 32 | Implemented |
+ | Twirl | `ec.distort.twirl` | 3 | GPU | 32 | Implemented |
| Twirl (Legacy) | `ec.distort.twirllegacy` | 3 | | 32 | Implemented |
| Warp | `ec.distort.warp` | 5 | | 32 | Implemented |
| Warp Stabilizer | `ec.distort.warpstabilizer` | 20 | | 32 | Implemented |
@@@ -187,8 -188,8 +188,8 @@@
| Effect | Id | Params | GPU | 32 | Status |
|---|---|---:|:-:|:-:|---|
- | 4-Color Gradient | `ec.generate.fourcolor` | 12 | | 32 | Implemented |
+ | 4-Color Gradient | `ec.generate.fourcolor` | 12 | GPU | 32 | Implemented |
-| Advanced Lightning | `ec.generate.advancedlightning` | 16 | | 32 | Partial: no Alpha Obstacle; most Expert Settings missing |
+| Advanced Lightning | `ec.generate.advancedlightning` | 24 | | 32 | Implemented |
| Audio Spectrum | `ec.generate.audiospectrum` | 23 | | 32 | Implemented |
| Audio Waveform | `ec.generate.audiowaveform` | 17 | | 32 | Implemented |
| Beam | `ec.generate.beam` | 11 | | 32 | Implemented |
@@@ -197,19 -198,19 +198,19 @@@
| CC Light Rays | `ec.generate.cclightrays` | 8 | | 32 | Implemented |
| CC Light Sweep | `ec.generate.cclightsweep` | 9 | | 32 | Implemented |
| CC Threads | `ec.generate.ccthreads` | 8 | | 32 | Implemented |
- | Cell Pattern | `ec.generate.cellpattern` | 14 | | 32 | Implemented |
- | Checkerboard | `ec.generate.checkerboard` | 10 | | 32 | Implemented |
-| Cell Pattern | `ec.generate.cellpattern` | 14 | GPU | 32 | Partial: HQ variants render like the standard ones |
++| Cell Pattern | `ec.generate.cellpattern` | 14 | GPU | 32 | Implemented |
+ | Checkerboard | `ec.generate.checkerboard` | 10 | GPU | 32 | Implemented |
| Circle | `ec.generate.circle` | 11 | | 32 | Implemented |
| Ellipse | `ec.generate.ellipse` | 8 | | 32 | Implemented |
| Eyedropper Fill | `ec.generate.eyedropperfill` | 5 | | 32 | Implemented |
-| Fill | `ec.generate.fill` | 3 | GPU | 32 | Partial: no Fill Mask / All Masks / feather |
+| Fill | `ec.generate.fill` | 7 | GPU | 32 | Implemented |
| Fractal | `ec.generate.fractal` | 21 | | 32 | Implemented |
| Gradient Ramp | `ec.generate.gradientramp` | 7 | GPU | 32 | Implemented |
- | Grid | `ec.generate.grid` | 12 | | 32 | Implemented |
+ | Grid | `ec.generate.grid` | 12 | GPU | 32 | Implemented |
| Lens Flare | `ec.generate.lensflare` | 4 | | 32 | Implemented |
| Paint Bucket | `ec.generate.paintbucket` | 11 | | 32 | Implemented |
-| Radio Waves | `ec.generate.radiowaves` | 17 | | 32 | Partial: no Image Contours or Mask wave types, Parameters Are Set At, reflection or stroke profile |
-| Scribble | `ec.generate.scribble` | 21 | | 32 | Partial: no caps, joins or Start/End Apply To |
+| Radio Waves | `ec.generate.radiowaves` | 31 | | 32 | Implemented |
+| Scribble | `ec.generate.scribble` | 25 | | 32 | Implemented |
| Stroke | `ec.generate.stroke` | 11 | | 32 | Implemented |
| Vegas | `ec.generate.vegas` | 26 | | 32 | Implemented |
| Write-on | `ec.generate.writeon` | 10 | | 32 | Implemented |
@@@ -241,10 -242,10 +242,10 @@@
| Color Range | `ec.key.colorrange` | 8 | | 32 | Implemented |
| Difference Matte | `ec.key.differencematte` | 6 | | 32 | Implemented |
| Extract | `ec.key.extract` | 6 | | 32 | Implemented |
-| Inner/Outer Key | `ec.key.innerouter` | 10 | | 32 | Partial: one additional mask per side; no cleanup strokes |
+| Inner/Outer Key | `ec.key.innerouter` | 88 | | 32 | Implemented |
| Key Cleaner | `ec.key.keycleaner` | 4 | | 32 | Implemented |
- | Key Light | `ec.keying.keylight` | 56 | | 32 | Implemented |
- | Linear Color Key | `ec.key.linearcolor` | 6 | | 32 | Implemented |
-| Key Light | `ec.keying.keylight` | 42 | GPU | 32 | Partial: no Source Crops X/Y Method or Edge Colour; no colour suppression / balancing |
++| Key Light | `ec.keying.keylight` | 56 | GPU | 32 | Implemented |
+ | Linear Color Key | `ec.key.linearcolor` | 6 | GPU | 32 | Implemented |
| Screen Key | `ec.key.screen` | 11 | | 32 | Implemented |
| Unmult | `ec.key.unmult` | 6 | | 32 | Implemented |
@@@ -263,14 -264,14 +264,14 @@@
| Effect | Id | Params | GPU | 32 | Status |
|---|---|---:|:-:|:-:|---|
- | Add Grain | `ec.noise.addgrain` | 32 | | 32 | Implemented |
-| Add Grain | `ec.noise.addgrain` | 22 | GPU | 32 | Partial: no preview region, presets, channel balance or temporal controls |
++| Add Grain | `ec.noise.addgrain` | 32 | GPU | 32 | Implemented |
| Curl Noise | `ec.noise.curlnoise` | 10 | | 32 | Implemented |
| Dust & Scratches | `ec.noise.dustscratches` | 3 | | 32 | Implemented |
| Fractal Noise | `ec.noise.fractal` | 26 | GPU | 32 | Implemented |
-| Match Grain | `ec.noise.matchgrain` | 25 | | 32 | Partial: no preview region, presets, sampling or temporal controls |
+| Match Grain | `ec.noise.matchgrain` | 37 | | 32 | Implemented |
| Median | `ec.noise.median` | 2 | | 32 | Implemented |
| Median (Legacy) | `ec.noise.medianlegacy` | 2 | | 32 | Implemented |
- | Noise | `ec.noise.noise` | 3 | | 32 | Implemented |
+ | Noise | `ec.noise.noise` | 3 | GPU | 32 | Implemented |
| Noise Alpha | `ec.noise.noisealpha` | 8 | | 32 | Implemented |
| Noise HLS | `ec.noise.noisehls` | 6 | | 32 | Implemented |
| Noise HLS Auto | `ec.noise.noisehlsauto` | 6 | | 32 | Implemented |
@@@ -351,12 -352,12 +352,12 @@@
| CC Threshold | `ec.stylize.ccthreshold` | 4 | | 32 | Implemented |
| CC Threshold RGB | `ec.stylize.ccthresholdrgb` | 7 | | 32 | Implemented |
| CC Vignette | `ec.stylize.ccvignette` | 4 | | 32 | Implemented |
-| Cartoon | `ec.stylize.cartoon` | 11 | | 32 | Partial: no Edge Enhancement |
+| Cartoon | `ec.stylize.cartoon` | 12 | | 32 | Implemented |
| Color Emboss | `ec.stylize.coloremboss` | 4 | | 32 | Implemented |
- | Emboss | `ec.stylize.emboss` | 4 | | 32 | Implemented |
- | Find Edges | `ec.stylize.findedges` | 2 | | 32 | Implemented |
+ | Emboss | `ec.stylize.emboss` | 4 | GPU | 32 | Implemented |
+ | Find Edges | `ec.stylize.findedges` | 2 | GPU | 32 | Implemented |
-| Glow | `ec.stylize.glow` | 13 | GPU | 32 | Partial: no Glow Operation or arbitrary colour map |
+| Glow | `ec.stylize.glow` | 14 | GPU | 32 | Implemented |
- | Mosaic | `ec.stylize.mosaic` | 3 | | 32 | Implemented |
+ | Mosaic | `ec.stylize.mosaic` | 3 | GPU | 32 | Implemented |
| Motion Tile | `ec.stylize.motiontile` | 8 | | 32 | Implemented |
| Posterize | `ec.stylize.posterize` | 1 | | 32 | Implemented |
| Roughen Edges | `ec.stylize.roughenedges` | 13 | | 32 | Implemented |
@@@ -400,12 -401,12 +401,12 @@@
| CC Scale Wipe | `ec.transition.ccscalewipe` | 3 | | 32 | Implemented |
| CC Twister | `ec.transition.cctwister` | 5 | | 32 | Implemented |
| CC WarpoMatic | `ec.transition.ccwarpomatic` | 8 | | 32 | Implemented |
-| Card Wipe | `ec.transition.cardwipe` | 12 | | 32 | Partial: 2D flip only; no back layer picker, camera, lighting or jitter |
+| Card Wipe | `ec.transition.cardwipe` | 44 | | 32 | Implemented |
- | Gradient Wipe | `ec.transition.gradientwipe` | 5 | | 32 | Implemented |
+ | Gradient Wipe | `ec.transition.gradientwipe` | 5 | GPU | 32 | Implemented |
| Iris Wipe | `ec.transition.iriswipe` | 7 | | 32 | Implemented |
- | Linear Wipe | `ec.transition.linearwipe` | 3 | | 32 | Implemented |
- | Radial Wipe | `ec.transition.radialwipe` | 5 | | 32 | Implemented |
- | Venetian Blinds | `ec.transition.venetian` | 4 | | 32 | Implemented |
+ | Linear Wipe | `ec.transition.linearwipe` | 3 | GPU | 32 | Implemented |
+ | Radial Wipe | `ec.transition.radialwipe` | 5 | GPU | 32 | Implemented |
+ | Venetian Blinds | `ec.transition.venetian` | 4 | GPU | 32 | Implemented |
## Utility