M9.4: layer styles render + commands

Layer Styles (Drop Shadow, Inner Shadow, Outer/Inner Glow, Bevel and Emboss, Satin,
Color/Gradient Overlay, Stroke) and Blending Options (Global Light, Fill Opacity, R/G/B,
Knockout, Blend Interior Styles as Group) as a layerStyles property group with AE names,
order and defaults. Rendered in layer space after effects (exterior passes composite with
their own blend modes below the body), cached per pass, scaled with render resolution.
Commands layer.style.* (menu Layer > Layer Styles), Global Light shared per comp, timeline
eye switches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 00:00:00 -04:00
co-authored by Claude Opus 5.5
parent d73f199f38
commit 8f966a99f7
11 changed files with 2207 additions and 27 deletions
+21 -1
View File
@@ -224,8 +224,9 @@ pub fn layer_key(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool) -> Optio
hash_debug(&mut h, &layer.source);
hash_debug(&mut h, &layer.switches);
for c in &layer.props.children {
// Transform is applied later; Layer Styles are keyed separately (see [`styles_key`]).
if let Node::Group(g) = c
&& g.match_id == "transform"
&& (g.match_id == "transform" || g.match_id == effectcraft_project::styles::GROUP)
{
continue;
}
@@ -243,3 +244,22 @@ pub fn layer_key(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool) -> Optio
}
Some(h.finish())
}
/// Cache key for the styled layer (content key + the Layer Styles group: structure, eye
/// switches, values, keyframes, expressions and their values at the context time — Global Light
/// included, as every layer mirrors it in its Blending Options).
pub fn styles_key(ctx: &EvalCtx, layer: &Layer, content_key: u64) -> u64 {
let mut h = KeyHasher(content_key ^ 0x9e37_79b9_7f4a_7c15);
if let Some(g) = layer.layer_styles() {
hash_debug(&mut h, g);
hash_values(&mut h, ctx, layer, g);
}
h.finish()
}
/// A sub-key of `key` (styled layer passes, flattened buffer).
pub fn derive(key: u64, i: u64) -> u64 {
let mut h = KeyHasher(key);
i.hash(&mut h);
h.finish()
}
+136 -22
View File
@@ -11,6 +11,7 @@ pub mod cache;
pub mod eval;
pub mod masks;
pub mod shapes;
pub mod styles;
pub mod text;
pub mod three_d;
@@ -53,7 +54,7 @@ impl EffectHost for FxHost<'_, '_, '_> {
}
let sub = Renderer { depth: self.r.depth + 1, ..*self.r };
// The cached layer buffer is shared; effects get their own copy.
let buf = if masks_and_effects { (*sub.layer_buf(self.ctx, other)?).clone() } else { sub.source(self.ctx, other)? };
let buf = if masks_and_effects { (*sub.content_buf(self.ctx, other)?).clone() } else { sub.source(self.ctx, other)? };
let size = source_size(self.r.project, other);
let size = if size.0 == 0 { [self.ctx.comp.width as f64, self.ctx.comp.height as f64] } else { [size.0 as f64, size.1 as f64] };
Some(LayerPixels { buf, size })
@@ -262,13 +263,32 @@ impl<'a> Renderer<'a> {
}
}
/// Fully processed layer buffer (source → masks → effects).
/// Fully processed layer buffer (source → masks → effects → layer styles, flattened).
/// Served from the layer cache when the layer's content key matches.
pub fn layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {
self.layer_buf_timed(ctx, layer, None)
let st = self.styled(ctx, layer, None)?;
if st.passes.is_empty() {
return Some(st.body);
}
let key = st.key.map(|k| cache::derive(k, 0xf1a7));
if let (Some(c), Some(k)) = (self.cache, key)
&& let Some(b) = c.get(k)
{
return Some(b);
}
let flat = Arc::new(styles::Styled { passes: st.passes.iter().map(|(b, m)| ((**b).clone(), *m)).collect(), body: (*st.body).clone() }.flatten());
if let (Some(c), Some(k)) = (self.cache, key) {
c.insert(k, flat.clone());
}
Some(flat)
}
fn layer_buf_timed(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option<Arc<Buf>> {
/// Layer pixels after source → masks → effects (no layer styles).
pub fn content_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {
self.content_buf_timed(ctx, layer, None).map(|(b, _)| b)
}
fn content_buf_timed(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option<(Arc<Buf>, Option<u64>)> {
let key = self.cache.and_then(|_| cache::layer_key(ctx, layer, self.opts.scale, self.opts.draft));
if let (Some(c), Some(k)) = (self.cache, key)
&& let Some(b) = c.get(k)
@@ -276,7 +296,7 @@ impl<'a> Renderer<'a> {
if let Some(t) = timing.as_deref_mut() {
t.cached = true;
}
return Some(b);
return Some((b, key));
}
let mut buf = self.source(ctx, layer)?;
masks::apply(ctx, layer, &mut buf);
@@ -284,7 +304,42 @@ impl<'a> Renderer<'a> {
if let (Some(c), Some(k)) = (self.cache, key) {
c.insert(k, buf.clone());
}
Some(buf)
Some((buf, key))
}
/// The layer with its styles: exterior passes and body (cached per pass).
fn styled(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option<StyledLayer> {
let (content, ckey) = self.content_buf_timed(ctx, layer, timing.as_deref_mut())?;
if !styles::active(ctx, layer) {
return Some(StyledLayer { passes: vec![], body: content.clone(), content, key: None, plain: true });
}
let modes = styles::pass_modes(ctx, layer);
let key = ckey.map(|k| cache::styles_key(ctx, layer, k));
if let (Some(c), Some(k)) = (self.cache, key)
&& let Some(body) = c.get(k)
{
let passes: Option<Vec<_>> = modes.iter().enumerate().map(|(i, m)| c.get(cache::derive(k, i as u64 + 1)).map(|b| (b, *m))).collect();
if let Some(passes) = passes {
return Some(StyledLayer { passes, body, content, key, plain: false });
}
}
let t0 = std::time::Instant::now();
let size = source_size(self.project, layer);
let layer_size = if size.0 == 0 { [ctx.comp.width as f64, ctx.comp.height as f64] } else { [size.0 as f64, size.1 as f64] };
let st = styles::render(ctx, layer, &content, layer_size);
if let Some(t) = timing {
t.cached = false;
t.effects.push(("layerStyles".into(), t0.elapsed().as_secs_f64() * 1e3));
}
let body = Arc::new(st.body);
let passes: Vec<_> = st.passes.into_iter().map(|(b, m)| (Arc::new(b), m)).collect();
if let (Some(c), Some(k)) = (self.cache, key) {
c.insert(k, body.clone());
for (i, (b, _)) in passes.iter().enumerate() {
c.insert(cache::derive(k, i as u64 + 1), b.clone());
}
}
Some(StyledLayer { passes, body, content, key, plain: false })
}
fn sampling(&self, layer: &Layer) -> effectcraft_raster::Sampling {
@@ -341,34 +396,79 @@ impl<'a> Renderer<'a> {
self.draw_adjustment(ctx, layer, canvas, opacity);
return;
}
let Some(prof) = self.profile else {
if let Some(buf) = self.layer_buf(ctx, layer) {
self.composite_layer(ctx, layer, &buf, canvas, opacity);
}
return;
};
let mut timing = LayerTiming { depth: self.depth, layer: layer.name.clone(), ..Default::default() };
let mut timing = self.profile.map(|_| LayerTiming { depth: self.depth, layer: layer.name.clone(), ..Default::default() });
let t0 = std::time::Instant::now();
let Some(buf) = self.layer_buf_timed(ctx, layer, Some(&mut timing)) else { return };
let Some(st) = self.styled(ctx, layer, timing.as_mut()) else { return };
let t1 = std::time::Instant::now();
self.composite_layer(ctx, layer, &buf, canvas, opacity);
timing.process_ms = (t1 - t0).as_secs_f64() * 1e3;
timing.composite_ms = t1.elapsed().as_secs_f64() * 1e3;
if let Ok(mut v) = prof.lock() {
v.push(timing);
if st.plain {
self.composite_layer(ctx, layer, &st.body, canvas, opacity);
} else {
self.composite_styled(ctx, layer, &st, canvas, opacity);
}
if let (Some(prof), Some(mut timing)) = (self.profile, timing) {
timing.process_ms = (t1 - t0).as_secs_f64() * 1e3;
timing.composite_ms = t1.elapsed().as_secs_f64() * 1e3;
if let Ok(mut v) = prof.lock() {
v.push(timing);
}
}
}
/// Composite a styled layer: exterior passes with their own modes, then the body with the
/// layer's mode; the layer's opacity fades the whole stack. Knockout clears what is below the
/// layer's content; switched-off R/G/B channels keep the values below.
fn composite_styled(&self, ctx: &EvalCtx, layer: &Layer, st: &StyledLayer, canvas: &mut Image, opacity: f32) {
let bl = styles::blending(ctx, layer);
let matte = layer.track_matte.is_some_and(|tm| tm.layer != layer.id && ctx.comp.layer(tm.layer).is_some());
if matte || layer.preserve_transparency {
let mut iso = Image::new(canvas.width, canvas.height);
for (b, m) in &st.passes {
self.place(ctx, layer, b, &mut iso, *m, 1.0);
}
self.place(ctx, layer, &st.body, &mut iso, BlendMode::Normal, 1.0);
self.composite_iso(ctx, layer, iso, canvas, opacity);
return;
}
let mut tmp = canvas.clone();
if bl.knockout > 0 {
let mut k = Image::new(canvas.width, canvas.height);
self.place(ctx, layer, &st.content, &mut k, BlendMode::Normal, 1.0);
tmp.data.par_iter_mut().zip(k.data.par_iter()).for_each(|(p, q)| {
let keep = 1.0 - q[3].clamp(0.0, 1.0);
for c in p.iter_mut() {
*c *= keep;
}
});
}
for (b, m) in &st.passes {
self.place(ctx, layer, b, &mut tmp, *m, 1.0);
}
self.place(ctx, layer, &st.body, &mut tmp, layer.blend_mode, 1.0);
let ch = bl.channels;
canvas.data.par_iter_mut().zip(tmp.data.par_iter()).for_each(|(c, t)| {
for i in 0..4 {
let v = if i < 3 && !ch[i] { c[i] } else { t[i] };
c[i] += (v - c[i]) * opacity;
}
});
}
fn composite_layer(&self, ctx: &EvalCtx, layer: &Layer, buf: &Buf, canvas: &mut Image, opacity: f32) {
let matte = layer.track_matte.and_then(|tm| ctx.comp.layer(tm.layer).filter(|m| m.id != layer.id).map(|m| (m, tm.kind)));
let preserve = layer.preserve_transparency;
if matte.is_none() && !preserve {
let matte = layer.track_matte.is_some_and(|tm| tm.layer != layer.id && ctx.comp.layer(tm.layer).is_some());
if !matte && !layer.preserve_transparency {
self.place(ctx, layer, buf, canvas, layer.blend_mode, opacity);
return;
}
// Render in isolation, then matte / preserve transparency, then blend.
let mut iso = Image::new(canvas.width, canvas.height);
self.place(ctx, layer, buf, &mut iso, BlendMode::Normal, 1.0);
self.composite_iso(ctx, layer, iso, canvas, opacity);
}
/// Apply the track matte / preserve transparency to an isolated layer render, then blend.
fn composite_iso(&self, ctx: &EvalCtx, layer: &Layer, mut iso: Image, canvas: &mut Image, opacity: f32) {
let matte = layer.track_matte.and_then(|tm| ctx.comp.layer(tm.layer).filter(|m| m.id != layer.id).map(|m| (m, tm.kind)));
let preserve = layer.preserve_transparency;
if let Some((m, kind)) = matte {
let mut mimg = Image::new(canvas.width, canvas.height);
if m.is_active_at(ctx.time)
@@ -420,6 +520,18 @@ impl<'a> Renderer<'a> {
}
}
/// A layer ready to composite (see [`Renderer::styled`]).
struct StyledLayer {
passes: Vec<(Arc<Buf>, BlendMode)>,
body: Arc<Buf>,
/// Pre-style pixels (knockout shape).
content: Arc<Buf>,
/// Styled cache key.
key: Option<u64>,
/// No layer styles: composite `body` the usual way.
plain: bool,
}
/// Convenience: render one frame of a comp with no footage source.
pub fn render_frame(project: &Project, comp: ItemId, t: Tick, scale: f64) -> Image {
Renderer::new(project, &NoFootage, RenderOpts { scale, ..Default::default() }).comp_frame(comp, t)
@@ -429,6 +541,8 @@ pub fn render_frame(project: &Project, comp: ItemId, t: Tick, scale: f64) -> Ima
mod tests;
#[cfg(test)]
mod tests_remap;
#[cfg(test)]
mod tests_styles;
/// Layer-space bounds `[x0, y0, x1, y1]` of a layer's content at the context time (source size
/// for solids/footage/precomps, glyph bounds for text, painted bounds for shapes). Used for viewer
+741
View File
@@ -0,0 +1,741 @@
//! Layer Styles rendering (Photoshop-style layer effects, as After Effects renders them).
//!
//! Styles run in layer space after masks and effects and before the transform. The layer's
//! processed pixels (the *content*) become:
//!
//! * **exterior passes** — Drop Shadow, then Outer Glow — separate buffers composited onto the
//! comp *below* the layer, each with its own blend mode (so a Multiply shadow multiplies the
//! layers underneath, as in AE);
//! * the **body** — the content scaled by Fill Opacity, then the interior styles in Photoshop's
//! stacking order (Gradient Overlay, Color Overlay, Satin, Inner Glow, Inner Shadow), each
//! clipped to the content's alpha and blended with its mode, then Stroke and Bevel and Emboss.
//! With *Blend Interior Styles as Group* the interior styles are faded by Fill Opacity too.
//!
//! The compositor applies the layer's opacity to the whole stack, and Advanced Blending's
//! Knockout and R/G/B channel switches at composite time (see `Renderer::composite_styled`).
//! Every distance is in layer pixels and scales with the render resolution (Half, Quarter…).
//!
//! Shapes come from a signed distance field of the content alpha (exact Euclidean distance
//! transform, Felzenszwalb–Huttenlocher) for spread/choke, strokes, precise glows and bevel
//! profiles, and from the shared separable Gaussian (`effects::util::gauss_plane`) for soft
//! shadows and glows. All per-pixel work is parallel (rayon).
use effectcraft_color::{BlendMode, blend_pixel};
use effectcraft_effects::Buf;
use effectcraft_effects::util::{Plane, gauss_plane};
use effectcraft_keyframe::{Gradient, Value};
use effectcraft_project::styles::{self as st, style_blend_mode};
use effectcraft_project::{Layer, PropGroup};
use effectcraft_raster::{Image, hash_noise};
use rayon::prelude::*;
use crate::eval::EvalCtx;
/// Largest padding (buffer pixels) styles may add on each side.
const MAX_PAD: f64 = 2048.0;
/// A styled layer: exterior passes (bottom first, each with its blend mode) and the body.
#[derive(Clone, Debug)]
pub struct Styled {
pub passes: Vec<(Buf, BlendMode)>,
pub body: Buf,
}
impl Styled {
/// Everything composited into one buffer (for 3D layers, track mattes and layer references).
pub fn flatten(&self) -> Buf {
if self.passes.is_empty() {
return self.body.clone();
}
let mut img = Image::new(self.body.img.width, self.body.img.height);
for (p, m) in &self.passes {
img.blend_from(&p.img, *m, 1.0, 0);
}
img.blend_from(&self.body.img, BlendMode::Normal, 1.0, 0);
Buf { img, offset: self.body.offset, scale: self.body.scale }
}
}
/// Advanced Blending options evaluated at a time.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Blending {
pub fill: f32,
/// Red, green, blue channel switches.
pub channels: [bool; 3],
/// 0 None, 1 Shallow, 2 Deep.
pub knockout: u32,
pub interior_group: bool,
}
impl Default for Blending {
fn default() -> Self {
Blending { fill: 1.0, channels: [true; 3], knockout: 0, interior_group: false }
}
}
/// The layer's Layer Styles group when styles are switched on.
pub fn group(layer: &Layer) -> Option<&PropGroup> {
layer.layer_styles().filter(|g| g.enabled && layer.can_have_styles())
}
/// Evaluated Advanced Blending (defaults when the layer has no styles).
pub fn blending(ctx: &EvalCtx, layer: &Layer) -> Blending {
let Some(adv) = group(layer).and_then(|g| g.sub(st::BLENDING)).and_then(|b| b.sub("advancedBlending")) else { return Blending::default() };
Blending {
fill: (ctx.f(layer, adv, "fillOpacity", 100.0) / 100.0).clamp(0.0, 1.0) as f32,
channels: [ctx.b(layer, adv, "red"), ctx.b(layer, adv, "green"), ctx.b(layer, adv, "blue")],
knockout: ctx.e(layer, adv, "knockout"),
interior_group: ctx.b(layer, adv, "blendInteriorAsGroup"),
}
}
/// Global light (angle, altitude) in degrees for the layer.
fn global_light(ctx: &EvalCtx, layer: &Layer, g: &PropGroup) -> (f64, f64) {
match g.sub(st::BLENDING) {
Some(bo) => (ctx.f(layer, bo, "globalLightAngle", st::DEFAULT_ANGLE), ctx.f(layer, bo, "globalLightAltitude", st::DEFAULT_ALTITUDE)),
None => (st::DEFAULT_ANGLE, st::DEFAULT_ALTITUDE),
}
}
/// Does the layer need the styled path (any style on, or non-default blending)?
pub fn active(ctx: &EvalCtx, layer: &Layer) -> bool {
let Some(g) = group(layer) else { return false };
g.groups().any(|s| s.enabled && s.match_id != st::BLENDING) || blending(ctx, layer) != Blending::default()
}
/// Blend modes of the exterior passes [`render`] produces (Drop Shadow, then Outer Glow).
pub fn pass_modes(ctx: &EvalCtx, layer: &Layer) -> Vec<BlendMode> {
let Some(g) = group(layer) else { return vec![] };
["dropShadow", "outerGlow"].iter().filter_map(|id| g.sub(id).filter(|s| s.enabled)).map(|s| style_blend_mode(ctx.e(layer, s, "blendMode"))).collect()
}
// ------------------------------------------------------------------------------------------
// Evaluated styles
struct Shadow {
mode: BlendMode,
color: [f32; 3],
opacity: f32,
offset: [f64; 2],
spread: f64,
size: f64,
noise: f32,
knocks_out: bool,
}
struct Glow {
mode: BlendMode,
opacity: f32,
noise: f32,
gradient: Option<Gradient>,
color: [f32; 3],
precise: bool,
center: bool,
spread: f64,
size: f64,
range: f64,
jitter: f32,
}
struct Bevel {
style: u32,
technique: u32,
depth: f64,
down: bool,
size: f64,
soften: f64,
angle: f64,
altitude: f64,
hl: (BlendMode, [f32; 3], f32),
sh: (BlendMode, [f32; 3], f32),
}
struct Satin {
mode: BlendMode,
color: [f32; 3],
opacity: f32,
offset: [f64; 2],
size: f64,
invert: bool,
}
struct Overlay {
mode: BlendMode,
color: [f32; 3],
opacity: f32,
}
struct GradOverlay {
mode: BlendMode,
opacity: f32,
gradient: Gradient,
angle: f64,
style: u32,
reverse: bool,
align: bool,
scale: f64,
offset: [f64; 2],
}
struct Stroke {
mode: BlendMode,
color: [f32; 3],
size: f64,
opacity: f32,
position: u32,
}
#[derive(Default)]
struct Styles {
drop: Option<Shadow>,
inner_shadow: Option<Shadow>,
outer_glow: Option<Glow>,
inner_glow: Option<Glow>,
bevel: Option<Bevel>,
satin: Option<Satin>,
color: Option<Overlay>,
gradient: Option<GradOverlay>,
stroke: Option<Stroke>,
}
fn rgb(c: [f32; 4]) -> [f32; 3] {
[c[0], c[1], c[2]]
}
/// Light direction → shadow offset (the shadow falls away from the light).
fn offset(angle: f64, distance: f64) -> [f64; 2] {
let a = angle.to_radians();
[-distance * a.cos(), distance * a.sin()]
}
fn evaluate(ctx: &EvalCtx, layer: &Layer, g: &PropGroup) -> Styles {
let (ga, galt) = global_light(ctx, layer, g);
let mut s = Styles::default();
for sg in g.groups().filter(|x| x.enabled) {
let f = |m: &str, d: f64| ctx.f(layer, sg, m, d);
let pct = |m: &str, d: f64| (ctx.f(layer, sg, m, d) / 100.0).clamp(0.0, 1.0);
let mode = |m: &str| style_blend_mode(ctx.e(layer, sg, m));
let col = |m: &str| rgb(ctx.color(layer, sg, m));
let ang = || if ctx.b(layer, sg, "useGlobalLight") { ga } else { f("angle", st::DEFAULT_ANGLE) };
let grad = || match ctx.group_value(layer, sg, "colors") {
Some(Value::Gradient(g)) => g,
_ => Gradient::default(),
};
match sg.match_id.as_str() {
"dropShadow" | "innerShadow" => {
let inner = sg.match_id == "innerShadow";
let sh = Shadow {
mode: mode("blendMode"),
color: col("color"),
opacity: pct("opacity", 75.0) as f32,
offset: offset(ang(), f("distance", 5.0).max(0.0)),
spread: pct(if inner { "choke" } else { "spread" }, 0.0),
size: f("size", 5.0).clamp(0.0, 250.0),
noise: pct("noise", 0.0) as f32,
knocks_out: !inner && ctx.b(layer, sg, "knocksOut"),
};
if inner {
s.inner_shadow = Some(sh);
} else {
s.drop = Some(sh);
}
}
"outerGlow" | "innerGlow" => {
let inner = sg.match_id == "innerGlow";
let gl = Glow {
mode: mode("blendMode"),
opacity: pct("opacity", 75.0) as f32,
noise: pct("noise", 0.0) as f32,
gradient: (ctx.e(layer, sg, "colorType") == 1).then(grad),
color: col("color"),
precise: ctx.e(layer, sg, "technique") == 1,
center: inner && ctx.e(layer, sg, "source") == 0,
spread: pct(if inner { "choke" } else { "spread" }, 0.0),
size: f("size", 5.0).clamp(0.0, 250.0),
range: pct("range", 50.0).max(0.01),
jitter: pct("jitter", 0.0) as f32,
};
if inner {
s.inner_glow = Some(gl);
} else {
s.outer_glow = Some(gl);
}
}
"bevelEmboss" => {
let gl = ctx.b(layer, sg, "useGlobalLight");
s.bevel = Some(Bevel {
style: ctx.e(layer, sg, "style"),
technique: ctx.e(layer, sg, "technique"),
depth: f("depth", 100.0).clamp(1.0, 1000.0) / 100.0,
down: ctx.e(layer, sg, "direction") == 1,
size: f("size", 5.0).clamp(0.0, 250.0),
soften: f("soften", 0.0).clamp(0.0, 16.0),
angle: if gl { ga } else { f("angle", st::DEFAULT_ANGLE) },
altitude: if gl { galt } else { f("altitude", st::DEFAULT_ALTITUDE) }.clamp(0.0, 90.0),
hl: (mode("highlightMode"), col("highlightColor"), pct("highlightOpacity", 75.0) as f32),
sh: (mode("shadowMode"), col("shadowColor"), pct("shadowOpacity", 75.0) as f32),
});
}
"satin" => {
s.satin = Some(Satin {
mode: mode("blendMode"),
color: col("color"),
opacity: pct("opacity", 50.0) as f32,
offset: offset(f("angle", 19.0), f("distance", 11.0).clamp(0.0, 250.0)),
size: f("size", 14.0).clamp(0.0, 250.0),
invert: ctx.b(layer, sg, "invert"),
});
}
"colorOverlay" => s.color = Some(Overlay { mode: mode("blendMode"), color: col("color"), opacity: pct("opacity", 100.0) as f32 }),
"gradientOverlay" => {
s.gradient = Some(GradOverlay {
mode: mode("blendMode"),
opacity: pct("opacity", 100.0) as f32,
gradient: grad(),
angle: f("angle", 90.0),
style: ctx.e(layer, sg, "style"),
reverse: ctx.b(layer, sg, "reverse"),
align: ctx.b(layer, sg, "alignWithLayer"),
scale: f("scale", 100.0).clamp(10.0, 150.0) / 100.0,
offset: ctx.v2(layer, sg, "offset", [0.0; 2]),
});
}
"stroke" => {
s.stroke = Some(Stroke {
mode: mode("blendMode"),
color: col("color"),
size: f("size", 3.0).clamp(0.0, 250.0),
opacity: pct("opacity", 100.0) as f32,
position: ctx.e(layer, sg, "position"),
});
}
_ => {}
}
}
s
}
/// Layer-space margin the styles reach beyond the content.
fn reach(s: &Styles) -> f64 {
let soft = |size: f64| size * 1.6;
let mut r: f64 = 0.0;
if let Some(d) = &s.drop {
r = r.max(d.offset[0].abs().max(d.offset[1].abs()) + soft(d.size));
}
if let Some(d) = &s.inner_shadow {
r = r.max(d.offset[0].abs().max(d.offset[1].abs()) + soft(d.size));
}
if let Some(g) = &s.outer_glow {
r = r.max(soft(g.size));
}
if let Some(g) = &s.inner_glow {
r = r.max(soft(g.size));
}
if let Some(b) = &s.bevel {
r = r.max(b.size + b.soften * 2.0);
}
if let Some(st) = &s.stroke {
r = r.max(st.size);
}
if let Some(sa) = &s.satin {
r = r.max(sa.offset[0].abs().max(sa.offset[1].abs()) + soft(sa.size));
}
r
}
// ------------------------------------------------------------------------------------------
// Distance fields
/// "Infinite" squared distance (finite so parabola intersections stay exact in f64).
const FAR: f64 = 1e10;
/// 1D squared Euclidean distance transform (Felzenszwalb & Huttenlocher) of `f` into `d`.
fn dt1d(f: &[f32], d: &mut [f32]) {
let n = f.len();
if n == 0 {
return;
}
let fv = |i: usize| (f[i] as f64).min(FAR);
let mut v = vec![0usize; n];
let mut z = vec![0f64; n + 1];
let mut k = 0usize;
z[0] = f64::NEG_INFINITY;
z[1] = f64::INFINITY;
let cross = |q: usize, p: usize| ((fv(q) + (q * q) as f64) - (fv(p) + (p * p) as f64)) / (2.0 * (q as f64 - p as f64));
for q in 1..n {
let mut s = cross(q, v[k]);
while k > 0 && s <= z[k] {
k -= 1;
s = cross(q, v[k]);
}
k += 1;
v[k] = q;
z[k] = s;
z[k + 1] = f64::INFINITY;
}
k = 0;
for (q, dq) in d.iter_mut().enumerate() {
while z[k + 1] < q as f64 {
k += 1;
}
let dx = q as f64 - v[k] as f64;
*dq = (dx * dx + fv(v[k])) as f32;
}
}
/// Euclidean distance (pixels) from every pixel to the nearest pixel where `seed` is true.
fn edt(w: usize, h: usize, seed: impl Fn(usize) -> bool + Sync) -> Plane {
let f = Plane { w, h, data: (0..w * h).into_par_iter().map(|i| if seed(i) { 0.0 } else { FAR as f32 }).collect() };
let rows = f.map_rows(dt1d);
let cols = rows.transpose().map_rows(dt1d).transpose();
cols.map(|v| v.sqrt())
}
/// Signed distance to the content edge in pixels (negative inside), anti-aliased at the edge:
/// a partially covered pixel with alpha `a` sits at `0.5 - a`.
fn sdf(alpha: &Plane) -> Plane {
let (w, h) = (alpha.w, alpha.h);
let to_in = edt(w, h, |i| alpha.data[i] >= 0.5);
let to_out = edt(w, h, |i| alpha.data[i] < 0.5);
Plane {
w,
h,
data: (0..w * h)
.into_par_iter()
.map(|i| {
let a = alpha.data[i];
if a > 0.0 && a < 1.0 {
0.5 - a
} else if a >= 0.5 {
-(to_out.data[i] - 0.5)
} else {
to_in.data[i] - 0.5
}
})
.collect(),
}
}
/// Coverage of the content grown by `r` pixels (negative `r` shrinks).
#[inline]
fn grown(sdf: f32, r: f32) -> f32 {
(r + 0.5 - sdf).clamp(0.0, 1.0)
}
// ------------------------------------------------------------------------------------------
// Helpers
/// Soft shape: content grown by `spread` of `size`, blurred by the rest (`inverse` = the
/// outside of the content, for inner shadows/glows).
fn soft_shape(alpha: &Plane, d: &Lazy, size: f64, spread: f64, inverse: bool) -> Plane {
let hard = size * spread;
let base = if hard > 0.01 {
let sd = d.get(alpha);
let r = hard as f32;
if inverse { sd.map(|v| grown(-v, r)) } else { sd.map(|v| grown(v, r)) }
} else if inverse {
alpha.map(|a| 1.0 - a)
} else {
alpha.clone()
};
let sigma = (size - hard).max(0.0) / 2.0;
if sigma > 0.05 { gauss_plane(&base, sigma, sigma) } else { base }
}
/// Bilinear read of `p` displaced by `off` pixels (the plane moves by `off`).
#[inline]
fn shifted(p: &Plane, x: usize, y: usize, off: [f64; 2]) -> f32 {
p.sample(x as f64 + 0.5 - off[0], y as f64 + 0.5 - off[1])
}
struct Lazy(std::sync::OnceLock<Plane>);
impl Lazy {
fn get(&self, alpha: &Plane) -> &Plane {
self.0.get_or_init(|| sdf(alpha))
}
}
#[inline]
fn noisy(a: f32, noise: f32, x: usize, y: usize, seed: u32) -> f32 {
if noise <= 0.0 { a } else { a * (1.0 - noise * hash_noise(x as u32, y as u32, seed)) }
}
/// Blend a straight colour with coverage `a` onto every pixel of `img` (`f(x, y)` → (colour, a)).
fn blend_into(img: &mut Image, mode: BlendMode, seed: u32, f: impl Fn(usize, usize) -> ([f32; 3], f32) + Sync) {
let w = img.width as usize;
img.data.par_chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| {
for (x, d) in row.iter_mut().enumerate() {
let (c, a) = f(x, y);
if a <= 0.0 {
continue;
}
let src = [c[0] * a, c[1] * a, c[2] * a, a];
let n = if mode == BlendMode::Dissolve { hash_noise(x as u32, y as u32, seed) } else { 0.5 };
*d = blend_pixel(mode, *d, src, n);
}
});
}
/// A pass image filled with a straight colour at coverage `f(x, y)`.
fn pass_image(w: usize, h: usize, f: impl Fn(usize, usize) -> ([f32; 3], f32) + Sync) -> Image {
let mut img = Image::new(w as u32, h as u32);
img.data.par_chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| {
for (x, d) in row.iter_mut().enumerate() {
let (c, a) = f(x, y);
let a = a.clamp(0.0, 1.0);
*d = [c[0] * a, c[1] * a, c[2] * a, a];
}
});
img
}
/// Glow intensity → (colour, alpha) for colour or gradient glows.
fn glow_color(g: &Glow, v: f32, x: usize, y: usize) -> ([f32; 3], f32) {
let v = v.clamp(0.0, 1.0).powf((0.5 / g.range) as f32);
match &g.gradient {
None => (g.color, v),
Some(gr) => {
let j = if g.jitter > 0.0 { (hash_noise(x as u32, y as u32, 77) - 0.5) * g.jitter } else { 0.0 };
let c = gr.sample((1.0 - v + j) as f64);
([c[0], c[1], c[2]], c[3] * (v * 8.0).min(1.0))
}
}
}
/// Glow intensity (0..1) from the content (`inner` glows read the inverse).
fn glow_intensity(alpha: &Plane, d: &Lazy, g: &Glow, s: f64, inner: bool) -> Plane {
let size = g.size * s;
if g.precise {
let sd = d.get(alpha);
let hard = (size * g.spread) as f32;
let soft = (size as f32 - hard).max(0.5);
return sd.map(|v| {
let v = if inner { -v } else { v };
(1.0 - (v - hard).max(0.0) / soft).clamp(0.0, 1.0)
});
}
soft_shape(alpha, d, size, g.spread, inner).map(|v| (v * 2.0).min(1.0))
}
// ------------------------------------------------------------------------------------------
// Rendering
/// Render the layer's styles around its processed `content` (layer size `layer_size` in layer
/// pixels, for Gradient Overlay without Align with Layer).
pub fn render(ctx: &EvalCtx, layer: &Layer, content: &Buf, layer_size: [f64; 2]) -> Styled {
let Some(g) = group(layer) else { return Styled { passes: vec![], body: content.clone() } };
let styles = evaluate(ctx, layer, g);
let bl = blending(ctx, layer);
let s = content.scale.max(1e-6);
let pad = ((reach(&styles) * s).ceil() + 2.0).min(MAX_PAD) as u32;
let mut buf = content.clone();
if content.img.is_empty() {
return Styled { passes: vec![], body: buf };
}
buf.pad(pad);
let (w, h) = (buf.img.width as usize, buf.img.height as usize);
let alpha = Plane::alpha(&buf.img);
let d = Lazy(std::sync::OnceLock::new());
let seed = layer.id.0 as u32;
// ---- exterior passes
let mut passes = vec![];
if let Some(ds) = &styles.drop {
let shape = soft_shape(&alpha, &d, ds.size * s, ds.spread, false);
let off = [ds.offset[0] * s, ds.offset[1] * s];
let img = pass_image(w, h, |x, y| {
let mut a = shifted(&shape, x, y, off) * ds.opacity;
if ds.knocks_out {
a *= 1.0 - alpha.data[y * w + x];
}
(ds.color, noisy(a, ds.noise, x, y, seed))
});
passes.push((Buf { img, offset: buf.offset, scale: buf.scale }, ds.mode));
}
if let Some(gl) = &styles.outer_glow {
let v = glow_intensity(&alpha, &d, gl, s, false);
let img = pass_image(w, h, |x, y| {
let i = y * w + x;
let (c, a) = glow_color(gl, v.data[i], x, y);
// The glow sits outside the content (knocked out under it).
(c, noisy(a * gl.opacity * (1.0 - alpha.data[i]), gl.noise, x, y, seed ^ 0x5a5a))
});
passes.push((Buf { img, offset: buf.offset, scale: buf.scale }, gl.mode));
}
// ---- body
let mut body = buf.img.clone();
if !bl.interior_group && bl.fill < 1.0 {
body.scale_alpha(bl.fill);
}
let cov = |i: usize| alpha.data[i];
if let Some(go) = &styles.gradient {
let (cx, cy, hw, hh) = gradient_frame(go, &buf, &alpha, layer_size);
let (ux, uy) = (go.angle.to_radians().cos(), -go.angle.to_radians().sin());
let ext = ((hw * ux).abs() + (hh * uy).abs()).max(1e-3) * go.scale;
let radius = hw.max(hh).max(1e-3) * go.scale;
blend_into(&mut body, go.mode, seed, |x, y| {
let (px, py) = (x as f64 + 0.5 - cx, y as f64 + 0.5 - cy);
let along = px * ux + py * uy;
let across = -px * uy + py * ux;
let mut t = match go.style {
1 => (px * px + py * py).sqrt() / radius,
2 => {
let a = (-py).atan2(px) - go.angle.to_radians();
(a / std::f64::consts::TAU).rem_euclid(1.0)
}
3 => along.abs() / ext,
4 => (along.abs() + across.abs()) / ext,
_ => 0.5 + along / (2.0 * ext),
};
if go.reverse {
t = 1.0 - t;
}
let c = go.gradient.sample(t.clamp(0.0, 1.0));
([c[0], c[1], c[2]], c[3] * go.opacity * cov(y * w + x))
});
}
if let Some(co) = &styles.color {
blend_into(&mut body, co.mode, seed, |x, y| (co.color, co.opacity * cov(y * w + x)));
}
if let Some(sa) = &styles.satin {
let b = gauss_plane(&alpha, sa.size * s / 2.0, sa.size * s / 2.0);
let off = [sa.offset[0] * s, sa.offset[1] * s];
blend_into(&mut body, sa.mode, seed, |x, y| {
let v = (shifted(&b, x, y, off) - shifted(&b, x, y, [-off[0], -off[1]])).abs().min(1.0);
let v = if sa.invert { 1.0 - v } else { v };
(sa.color, v * sa.opacity * cov(y * w + x))
});
}
if let Some(gl) = &styles.inner_glow {
let v = glow_intensity(&alpha, &d, gl, s, true);
blend_into(&mut body, gl.mode, seed, |x, y| {
let i = y * w + x;
let e = if gl.center { 1.0 - v.data[i] } else { v.data[i] };
let (c, a) = glow_color(gl, e, x, y);
(c, noisy(a * gl.opacity * cov(i), gl.noise, x, y, seed ^ 0x3c3c))
});
}
if let Some(is) = &styles.inner_shadow {
let shape = soft_shape(&alpha, &d, is.size * s, is.spread, true);
let off = [is.offset[0] * s, is.offset[1] * s];
blend_into(&mut body, is.mode, seed, |x, y| {
let a = shifted(&shape, x, y, off).min(1.0) * is.opacity * cov(y * w + x);
(is.color, noisy(a, is.noise, x, y, seed ^ 0x1234))
});
}
if bl.interior_group && bl.fill < 1.0 {
body.scale_alpha(bl.fill);
}
if let Some(sk) = &styles.stroke {
let sd = d.get(&alpha);
let size = (sk.size * s) as f32;
let (r_out, r_in) = match sk.position {
1 => (0.0, size),
2 => (size / 2.0, size / 2.0),
_ => (size, 0.0),
};
// Inside part: blended over the body within the content.
if r_in > 0.0 {
blend_into(&mut body, sk.mode, seed, |x, y| {
let i = y * w + x;
let ring = (alpha.data[i] - grown(sd.data[i], -r_in)).max(0.0);
(sk.color, ring * sk.opacity)
});
}
// Outside part: covers exactly what the content leaves uncovered.
if r_out > 0.0 {
body.data.par_iter_mut().enumerate().for_each(|(i, p)| {
let ring = (grown(sd.data[i], r_out) - alpha.data[i]).max(0.0) * sk.opacity;
if ring > 0.0 {
let src = [sk.color[0] * ring, sk.color[1] * ring, sk.color[2] * ring, ring];
for c in 0..4 {
p[c] += src[c];
}
}
});
}
}
if let Some(bv) = &styles.bevel {
bevel(&mut body, &alpha, &d, bv, s, seed);
}
Styled { passes, body: Buf { img: body, offset: buf.offset, scale: buf.scale } }
}
/// Gradient Overlay frame in buffer pixels: centre and half extents.
fn gradient_frame(go: &GradOverlay, buf: &Buf, alpha: &Plane, layer_size: [f64; 2]) -> (f64, f64, f64, f64) {
let s = buf.scale;
let (x0, y0, x1, y1) = if go.align {
let img = Image { width: alpha.w as u32, height: alpha.h as u32, data: alpha.data.iter().map(|&a| [0.0, 0.0, 0.0, a]).collect() };
match img.alpha_bounds() {
Some((a, b, c, d)) => (a as f64, b as f64, c as f64, d as f64),
None => (0.0, 0.0, 1.0, 1.0),
}
} else {
let (a, b) = buf.to_px([0.0, 0.0]);
let (c, d) = buf.to_px(layer_size);
(a, b, c, d)
};
((x0 + x1) / 2.0 + go.offset[0] * s, (y0 + y1) / 2.0 + go.offset[1] * s, (x1 - x0) / 2.0, (y1 - y0) / 2.0)
}
/// Bevel and Emboss: a height field from the content edge, lit by a directional light.
fn bevel(body: &mut Image, alpha: &Plane, d: &Lazy, bv: &Bevel, s: f64, seed: u32) {
let size = (bv.size * s).max(0.5) as f32;
let sd = d.get(alpha);
let w = alpha.w;
// Height profile 0..1 and the region the bevel paints.
let style = bv.style;
let mut height = sd.map(|v| match style {
0 => (1.0 - v.max(0.0) / size).clamp(0.0, 1.0),
2 | 4 => (0.5 - v / (2.0 * size)).clamp(0.0, 1.0),
3 => (v.abs() / size).clamp(0.0, 1.0),
_ => (-v / size + 0.5 / size).clamp(0.0, 1.0),
});
// The distance field is exact at pixel centres only; smoothing the profile removes the
// stair-steps on diagonal edges that lighting would otherwise amplify. Smooth rounds the
// profile over the bevel size; Chisel Hard keeps it crisp, Chisel Soft slightly softer.
let sigma = match bv.technique {
0 => (size as f64 / 4.0).max(1.0),
2 => 1.5,
_ => 0.75,
};
height = gauss_plane(&height, sigma, sigma);
if bv.soften > 0.0 {
let sg = bv.soften * s / 2.0;
height = gauss_plane(&height, sg, sg);
}
let sign = if bv.down { -1.0 } else { 1.0 };
let k = (size as f64 * bv.depth) as f32 * sign;
let (th, al) = (bv.angle.to_radians(), bv.altitude.to_radians());
let light = [(al.cos() * th.cos()) as f32, (-al.cos() * th.sin()) as f32, al.sin() as f32];
let flat = light[2];
let region = |i: usize| -> f32 {
let a = alpha.data[i];
match style {
0 => (grown(sd.data[i], size) - a).max(0.0),
1 => a,
_ => grown(sd.data[i], size),
}
};
let shade = |x: usize, y: usize| -> (f32, f32) {
let hx = |xx: i64| height.get_clamped(xx, y as i64);
let hy = |yy: i64| height.get_clamped(x as i64, yy);
let gx = (hx(x as i64 + 1) - hx(x as i64 - 1)) * 0.5 * k;
let gy = (hy(y as i64 + 1) - hy(y as i64 - 1)) * 0.5 * k;
let n = [-gx, -gy, 1.0];
let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt();
let dot = (n[0] * light[0] + n[1] * light[1] + n[2] * light[2]) / len;
let hl = ((dot - flat) / (1.0 - flat).max(1e-4)).clamp(0.0, 1.0);
let shd = ((flat - dot) / flat.max(1e-4)).clamp(0.0, 1.0);
(hl, shd)
};
blend_into(body, bv.sh.0, seed, |x, y| {
let (_, shd) = shade(x, y);
(bv.sh.1, shd * bv.sh.2 * region(y * w + x))
});
blend_into(body, bv.hl.0, seed, |x, y| {
let (hl, _) = shade(x, y);
(bv.hl.1, hl * bv.hl.2 * region(y * w + x))
});
}
+416
View File
@@ -0,0 +1,416 @@
//! Layer Styles pixel tests.
use effectcraft_color::Label;
use effectcraft_keyframe::{Gradient, Keyframe, Value};
use effectcraft_project::build::{self, Ids};
use effectcraft_project::styles::{self as st, GROUP};
use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, Project, Solid};
use effectcraft_time::{FrameRate, Tick};
use crate::{Image, NoFootage, RenderOpts, Renderer, render_frame};
const NORMAL: u32 = 0;
const MULTIPLY: u32 = 3;
fn setup() -> (Project, ItemId, Comp) {
let mut p = Project::default();
let comp = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(comp.clone().into()));
(p, cid, comp)
}
fn solid(p: &mut Project, comp: &Comp, color: [f32; 3], w: u32, h: u32) -> Layer {
let sid = p.add_item("Solid", Label::Red, None, ItemKind::Solid(Solid { color, width: w, height: h, pixel_aspect: 1.0 }));
build::layer(p, comp, "Solid", LayerSource::Solid { item: sid }, (w, h), None)
}
fn add(p: &mut Project, comp: &Comp, l: &mut Layer, style: &str) {
let mut next = p.next_id;
st::add_style(l, &mut Ids(&mut next), style, &comp.global_light, true).unwrap();
p.next_id = next;
}
fn set(l: &mut Layer, path: &str, v: Value) {
l.props.prop_mut(&format!("{GROUP}/{path}")).unwrap_or_else(|| panic!("no {path}")).value = v;
}
/// A 40×40 square of `color` centred in a 200×100 comp (x 80..120, y 30..70) over an optional
/// full-frame background.
fn scene(color: [f32; 3], bg: Option<[f32; 3]>, f: impl FnOnce(&mut Project, &Comp, &mut Layer)) -> (Project, ItemId) {
let (mut p, cid, comp) = setup();
let mut l = solid(&mut p, &comp, color, 40, 40);
f(&mut p, &comp, &mut l);
let mut layers = vec![l];
if let Some(bg) = bg {
layers.push(solid(&mut p, &comp, bg, 200, 100));
}
p.comp_mut(cid).unwrap().layers = layers;
(p, cid)
}
fn render(p: &Project, cid: ItemId) -> Image {
render_frame(p, cid, Tick::ZERO, 1.0)
}
fn near(a: f32, b: f32, tol: f32) -> bool {
(a - b).abs() <= tol
}
#[test]
fn drop_shadow_offset_colour_and_opacity() {
let (p, cid) = scene([1.0; 3], Some([0.5; 3]), |p, c, l| {
add(p, c, l, "dropShadow");
set(l, "dropShadow/size", Value::Scalar(0.0));
set(l, "dropShadow/distance", Value::Scalar(10.0));
set(l, "dropShadow/opacity", Value::Scalar(100.0));
set(l, "dropShadow/blendMode", Value::Enum(NORMAL));
});
let img = render(&p, cid);
// Global light 120° → the shadow falls down-right by (5, 8.66).
assert!(near(img.get(123, 75)[0], 0.0, 0.02), "shadow: {:?}", img.get(123, 75));
assert!(near(img.get(82, 75)[0], 0.5, 0.01), "left of the shadow stays grey");
assert!(near(img.get(100, 50)[0], 1.0, 0.01), "layer on top");
assert!(near(img.get(100, 20)[0], 0.5, 0.01), "above the layer");
// 75 % Multiply (the default mode) over grey: 0.5 × (1 − 0.75).
let (p, cid) = scene([1.0; 3], Some([0.5; 3]), |p, c, l| {
add(p, c, l, "dropShadow");
set(l, "dropShadow/size", Value::Scalar(0.0));
set(l, "dropShadow/distance", Value::Scalar(10.0));
set(l, "dropShadow/color", Value::Color([0.0, 0.0, 0.0, 1.0]));
});
let img = render(&p, cid);
assert!(near(img.get(123, 75)[0], 0.125, 0.02), "{:?}", img.get(123, 75));
// Coloured shadow on a transparent comp extends the layer's bounds.
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "dropShadow");
set(l, "dropShadow/size", Value::Scalar(0.0));
set(l, "dropShadow/distance", Value::Scalar(10.0));
set(l, "dropShadow/opacity", Value::Scalar(50.0));
set(l, "dropShadow/blendMode", Value::Enum(NORMAL));
set(l, "dropShadow/color", Value::Color([0.0, 0.0, 1.0, 1.0]));
});
let img = render(&p, cid);
let px = img.straight(123, 75);
assert!(near(px[3], 0.5, 0.02) && near(px[2], 1.0, 0.01) && px[0] < 0.01, "{px:?}");
}
#[test]
fn soft_shadow_falls_off() {
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "dropShadow");
set(l, "dropShadow/size", Value::Scalar(10.0));
set(l, "dropShadow/distance", Value::Scalar(0.0));
set(l, "dropShadow/opacity", Value::Scalar(100.0));
});
let img = render(&p, cid);
let a1 = img.get(121, 50)[3];
let a5 = img.get(125, 50)[3];
let a20 = img.get(140, 50)[3];
assert!(a1 > a5 && a5 > a20, "{a1} {a5} {a20}");
assert!(a20 < 0.01);
}
#[test]
fn stroke_positions() {
let render_stroke = |pos: u32| {
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "stroke");
set(l, "stroke/size", Value::Scalar(4.0));
set(l, "stroke/position", Value::Enum(pos));
});
render(&p, cid)
};
let red = |px: [f32; 4]| px[0] > 0.98 && px[1] < 0.02 && px[3] > 0.98;
let white = |px: [f32; 4]| px[0] > 0.98 && px[1] > 0.98 && px[3] > 0.98;
// Outside: 4 px ring beyond the right edge (x = 120).
let o = render_stroke(0);
assert!(red(o.get(122, 50)) && red(o.get(123, 50)), "{:?}", o.get(122, 50));
assert!(o.get(126, 50)[3] < 0.01);
assert!(white(o.get(118, 50)));
// Inside: the ring is within the layer.
let i = render_stroke(1);
assert!(red(i.get(118, 50)) && red(i.get(117, 50)));
assert!(white(i.get(110, 50)));
assert!(i.get(122, 50)[3] < 0.01);
// Centre: 2 px on each side.
let c = render_stroke(2);
assert!(red(c.get(119, 50)) && red(c.get(120, 50)) && red(c.get(121, 50)));
assert!(white(c.get(116, 50)));
assert!(c.get(124, 50)[3] < 0.01);
}
#[test]
fn colour_overlay_blend_modes() {
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "colorOverlay");
set(l, "colorOverlay/color", Value::Color([0.0, 0.0, 1.0, 1.0]));
set(l, "colorOverlay/opacity", Value::Scalar(50.0));
});
let px = render(&p, cid).get(100, 50);
assert!(near(px[0], 0.5, 0.01) && near(px[2], 1.0, 0.01), "{px:?}");
let (p, cid) = scene([0.5, 1.0, 1.0], None, |p, c, l| {
add(p, c, l, "colorOverlay");
set(l, "colorOverlay/color", Value::Color([1.0, 0.5, 0.0, 1.0]));
set(l, "colorOverlay/blendMode", Value::Enum(MULTIPLY));
});
let img = render(&p, cid);
let px = img.get(100, 50);
assert!(near(px[0], 0.5, 0.01) && near(px[1], 0.5, 0.01) && near(px[2], 0.0, 0.01), "{px:?}");
// Overlays stay inside the layer.
assert!(img.get(130, 50)[3] < 0.01);
}
#[test]
fn gradient_overlay_follows_angle() {
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "gradientOverlay");
});
let img = render(&p, cid);
// 90°: black at the bottom, white at the top.
let top = img.get(100, 31)[0];
let bottom = img.get(100, 68)[0];
assert!(top > 0.9 && bottom < 0.1, "{top} {bottom}");
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "gradientOverlay");
set(l, "gradientOverlay/angle", Value::Scalar(0.0));
set(l, "gradientOverlay/reverse", Value::Bool(true));
});
let img = render(&p, cid);
assert!(img.get(81, 50)[0] > 0.9 && img.get(118, 50)[0] < 0.1);
}
fn bevel_scene(angle: f64) -> Image {
let (p, cid) = scene([0.5; 3], None, |p, c, l| {
add(p, c, l, "bevelEmboss");
set(l, "bevelEmboss/size", Value::Scalar(6.0));
set(l, "blendingOptions/globalLightAngle", Value::Scalar(angle));
});
render(&p, cid)
}
#[test]
fn bevel_lights_the_side_facing_the_light() {
// Light from the upper left (120°): left and top edges brighten, right and bottom darken.
let img = bevel_scene(120.0);
let (l, r, t, b, mid) = (img.get(82, 50)[0], img.get(117, 50)[0], img.get(100, 32)[0], img.get(100, 67)[0], img.get(100, 50)[0]);
assert!(l > 0.6 && t > 0.6, "highlights {l} {t}");
assert!(r < 0.4 && b < 0.4, "shadows {r} {b}");
assert!(near(mid, 0.5, 0.02), "flat centre {mid}");
// Light from the lower right (−60°) swaps them.
let img = bevel_scene(-60.0);
assert!(img.get(82, 50)[0] < 0.4 && img.get(117, 50)[0] > 0.6);
}
#[test]
fn global_light_drives_linked_styles() {
let shadow_at = |use_global: bool| {
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "dropShadow");
set(l, "dropShadow/size", Value::Scalar(0.0));
set(l, "dropShadow/distance", Value::Scalar(10.0));
set(l, "dropShadow/opacity", Value::Scalar(100.0));
set(l, "dropShadow/useGlobalLight", Value::Bool(use_global));
set(l, "dropShadow/angle", Value::Scalar(90.0));
set(l, "blendingOptions/globalLightAngle", Value::Scalar(0.0));
});
render(&p, cid)
};
// Global light at 0° (from the right): shadow to the left.
let g = shadow_at(true);
assert!(g.get(75, 50)[3] > 0.98 && g.get(100, 75)[3] < 0.01);
// Own angle 90° (from above): shadow below.
let o = shadow_at(false);
assert!(o.get(100, 75)[3] > 0.98 && o.get(75, 50)[3] < 0.01);
}
#[test]
fn glows_and_inner_shadow() {
let (p, cid) = scene([0.0, 0.0, 0.0], None, |p, c, l| {
add(p, c, l, "outerGlow");
add(p, c, l, "innerGlow");
set(l, "outerGlow/opacity", Value::Scalar(100.0));
set(l, "outerGlow/size", Value::Scalar(8.0));
set(l, "innerGlow/opacity", Value::Scalar(100.0));
set(l, "innerGlow/size", Value::Scalar(8.0));
});
let img = render(&p, cid);
let out_near = img.straight(121, 50);
assert!(out_near[3] > 0.6 && out_near[0] > 0.9 && out_near[2] < 0.9, "glow colour {out_near:?}");
assert!(img.get(140, 50)[3] < 0.02, "glow fades");
let edge = img.get(119, 50);
let centre = img.get(100, 50);
assert!(edge[0] > 0.6 && centre[0] < 0.05, "inner glow from the edge {edge:?} {centre:?}");
// Inner glow from the centre instead.
let (p, cid) = scene([0.0; 3], None, |p, c, l| {
add(p, c, l, "innerGlow");
set(l, "innerGlow/source", Value::Enum(0));
set(l, "innerGlow/opacity", Value::Scalar(100.0));
});
let img = render(&p, cid);
assert!(img.get(100, 50)[0] > 0.9 && img.get(119, 50)[0] < 0.6);
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "innerShadow");
set(l, "innerShadow/size", Value::Scalar(0.0));
set(l, "innerShadow/opacity", Value::Scalar(100.0));
set(l, "innerShadow/blendMode", Value::Enum(NORMAL));
});
let img = render(&p, cid);
// Light from the upper left: the shadow lines the top-left inside edges.
assert!(img.get(81, 50)[0] < 0.05 && img.get(100, 32)[0] < 0.05, "{:?}", img.get(81, 50));
assert!(img.get(117, 50)[0] > 0.95 && img.get(100, 66)[0] > 0.95);
assert!(img.get(76, 50)[3] < 0.01, "inner shadow stays inside");
}
#[test]
fn satin_shades_inside() {
let (p, cid) = scene([1.0; 3], None, |p, c, l| add(p, c, l, "satin"));
let img = render(&p, cid);
let vals: Vec<f32> = (82..118).map(|x| img.get(x, 50)[0]).collect();
let min = vals.iter().cloned().fold(1.0, f32::min);
assert!(min < 0.9, "satin darkens somewhere: {min}");
assert!(img.get(130, 50)[3] < 0.01);
}
#[test]
fn fill_opacity_knockout_and_channels() {
// Fill 0: the content disappears but the stroke stays.
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "stroke");
set(l, "blendingOptions/advancedBlending/fillOpacity", Value::Scalar(0.0));
});
let img = render(&p, cid);
assert!(img.get(100, 50)[3] < 0.01 && img.get(122, 50)[0] > 0.98);
// Interior styles ignore Fill Opacity unless blended as a group.
let overlay = |group: bool| {
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "colorOverlay");
set(l, "blendingOptions/advancedBlending/fillOpacity", Value::Scalar(0.0));
set(l, "blendingOptions/advancedBlending/blendInteriorAsGroup", Value::Bool(group));
});
render(&p, cid).get(100, 50)
};
assert!(overlay(false)[3] > 0.98 && overlay(true)[3] < 0.01);
// Knockout with Fill 0 punches through the background.
let (p, cid) = scene([1.0; 3], Some([0.5; 3]), |p, c, l| {
add(p, c, l, "stroke");
set(l, "blendingOptions/advancedBlending/fillOpacity", Value::Scalar(0.0));
set(l, "blendingOptions/advancedBlending/knockout", Value::Enum(2));
});
let img = render(&p, cid);
assert!(img.get(100, 50)[3] < 0.01 && img.get(150, 50)[3] > 0.99);
// Red channel off: the white layer leaves red from below.
let (p, cid) = scene([1.0; 3], Some([0.0; 3]), |p, c, l| {
add(p, c, l, "stroke");
set(l, "blendingOptions/advancedBlending/red", Value::Bool(false));
});
let px = render(&p, cid).get(100, 50);
assert!(px[0] < 0.01 && px[1] > 0.99 && px[2] > 0.99, "{px:?}");
}
#[test]
fn eye_switch_and_group_switch() {
let (mut p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "stroke");
});
assert!(render(&p, cid).get(122, 50)[3] > 0.98);
p.comp_mut(cid).unwrap().layers[0].props.group_mut(&format!("{GROUP}/stroke")).unwrap().enabled = false;
assert!(render(&p, cid).get(122, 50)[3] < 0.01);
p.comp_mut(cid).unwrap().layers[0].props.group_mut(&format!("{GROUP}/stroke")).unwrap().enabled = true;
p.comp_mut(cid).unwrap().layers[0].props.group_mut(GROUP).unwrap().enabled = false;
assert!(render(&p, cid).get(122, 50)[3] < 0.01);
}
#[test]
fn styles_respect_render_scale() {
let (p, cid) = scene([1.0; 3], None, |p, c, l| {
add(p, c, l, "dropShadow");
add(p, c, l, "stroke");
set(l, "dropShadow/size", Value::Scalar(0.0));
set(l, "dropShadow/distance", Value::Scalar(20.0));
set(l, "dropShadow/opacity", Value::Scalar(100.0));
set(l, "stroke/size", Value::Scalar(4.0));
});
let full = render_frame(&p, cid, Tick::ZERO, 1.0);
let half = render_frame(&p, cid, Tick::ZERO, 0.5);
// Shadow offset (10, 17.3): at half resolution the shadow sits at half the distance.
assert!(full.get(125, 85)[3] > 0.98);
assert!(half.get(62, 42)[3] > 0.98 && half.get(55, 25)[3] > 0.98);
// Stroke 4 px → 2 px at half.
assert!(half.get(61, 25)[0] > 0.98 && half.get(61, 25)[1] < 0.05);
assert!(half.get(64, 25)[3] < 0.01 || half.get(64, 25)[1] < 0.05);
}
#[test]
fn animated_style_properties() {
let (mut p, cid) = scene([1.0; 3], None, |p, c, l| add(p, c, l, "stroke"));
let l = &mut p.comp_mut(cid).unwrap().layers[0];
l.props.prop_mut(&format!("{GROUP}/stroke/size")).unwrap().keys =
vec![Keyframe::new(Tick::ZERO, Value::Scalar(2.0)), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Scalar(10.0))];
let a = render_frame(&p, cid, Tick::ZERO, 1.0);
let b = render_frame(&p, cid, Tick::from_seconds_f64(1.0), 1.0);
assert!(a.get(126, 50)[3] < 0.01 && b.get(126, 50)[3] > 0.98);
}
fn render_cached(p: &Project, cid: ItemId, cache: &crate::LayerCache) -> Image {
let mut r = Renderer::new(p, &NoFootage, RenderOpts::default());
r.cache = Some(cache);
r.comp_frame(cid, Tick::ZERO)
}
#[test]
fn style_edits_invalidate_the_cache() {
let (mut p, cid) = scene([1.0; 3], Some([0.5; 3]), |p, c, l| {
add(p, c, l, "dropShadow");
add(p, c, l, "stroke");
});
let cache = crate::LayerCache::default();
let a = render_cached(&p, cid, &cache);
assert_eq!(a.data, render(&p, cid).data);
let again = render_cached(&p, cid, &cache);
assert_eq!(a.data, again.data);
// Change a style value: the styled layer re-renders, its content (and the background) come
// from the cache.
let hits0 = cache.stats().hits;
let l = &mut p.comp_mut(cid).unwrap().layers[0];
l.props.prop_mut(&format!("{GROUP}/stroke/color")).unwrap().value = Value::Color([0.0, 1.0, 0.0, 1.0]);
let b = render_cached(&p, cid, &cache);
assert_eq!(b.data, render(&p, cid).data);
assert_ne!(a.data, b.data);
assert!(cache.stats().hits >= hits0 + 2, "content + background reused");
// Global light change (linked) also invalidates.
let l = &mut p.comp_mut(cid).unwrap().layers[0];
l.props.prop_mut(&format!("{GROUP}/blendingOptions/globalLightAngle")).unwrap().value = Value::Scalar(0.0);
let c = render_cached(&p, cid, &cache);
assert_eq!(c.data, render(&p, cid).data);
assert_ne!(b.data, c.data);
// Eye switch off.
p.comp_mut(cid).unwrap().layers[0].props.group_mut(&format!("{GROUP}/dropShadow")).unwrap().enabled = false;
let d = render_cached(&p, cid, &cache);
assert_eq!(d.data, render(&p, cid).data);
assert_ne!(c.data, d.data);
}
#[test]
fn gradient_glow_uses_gradient() {
let (p, cid) = scene([0.0; 3], None, |p, c, l| {
add(p, c, l, "outerGlow");
set(l, "outerGlow/colorType", Value::Enum(1));
set(l, "outerGlow/opacity", Value::Scalar(100.0));
set(
l,
"outerGlow/colors",
Value::Gradient(Gradient { colors: vec![(0.0, [1.0, 0.0, 0.0, 1.0]), (1.0, [0.0, 0.0, 1.0, 1.0])], opacities: vec![(0.0, 1.0), (1.0, 0.0)] }),
);
});
let img = render(&p, cid);
let px = img.straight(121, 50);
assert!(px[0] > px[2], "near the edge the glow takes the gradient's start colour {px:?}");
}