Skip to content

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

M4.4: collapse transformations + slip

Brandon Thomasadf5db639761
diff --git a/crates/engine/src/commands/layer.rs b/crates/engine/src/commands/layer.rs
index 09a50660c..38a09b07f 100644
--- a/crates/engine/src/commands/layer.rs
+++ b/crates/engine/src/commands/layer.rs
@@ -629,6 +629,57 @@ fn timing(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
+/// Slip edit: move a layer's source (footage or precomp) under its fixed in and out points, like
+/// dragging the source-duration bar in After Effects. `delta` in seconds or `frames`; positive
+/// moves the source later. Clamped so the source still covers the in–out span. Keyframes and
+/// layer markers are in layer time, so they travel with the source.
+fn slip(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let fr = comp.frame_rate;
+ let delta = match (p.get("frames").and_then(Value::as_i64), f_p(p, "delta")) {
+ (Some(f), _) => fr.tick_of(f),
+ (None, Some(d)) => fr.snap_nearest(Tick::from_seconds_f64(d)),
+ _ => return Err(bad("layer.slip", "delta (seconds) or frames required")),
+ };
+ // Allowed shift per layer: the source span [lo, hi] in comp time must keep covering in..out.
+ let mut shifts: Vec<(LayerId, Tick)> = Vec::new();
+ for l in comp.layers.iter().filter(|l| ids.contains(&l.id)) {
+ if l.props.get("timeRemap").is_some() {
+ continue;
+ }
+ let dur = match &l.source {
+ LayerSource::Footage { item } => match s.project.item(*item).map(|i| &i.kind) {
+ Some(ItemKind::Footage(f)) if f.kind != effectcraft_project::FootageKind::Still => Some(Tick(f.duration.0 * f.loop_count.max(1) as i64)),
+ _ => None,
+ },
+ LayerSource::Comp { item } => s.project.comp(*item).map(|c| c.duration),
+ _ => None,
+ };
+ let Some(dur) = dur else { continue };
+ let (a, b) = (l.comp_time(Tick::ZERO), l.comp_time(dur));
+ let (lo, hi) = (a.min(b), a.max(b));
+ let (min_d, max_d) = (l.out_point - hi, l.in_point - lo);
+ if min_d > max_d {
+ continue;
+ }
+ shifts.push((l.id, delta.max(min_d).min(max_d)));
+ }
+ if shifts.is_empty() {
+ return Err(bad("layer.slip", "select a footage or precomp layer (without time remapping)"));
+ }
+ s.edit("Slip Edit", merge_p(p), |proj, _| {
+ let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ for (id, d) in &shifts {
+ if let Some(l) = comp.layer_mut(*id) {
+ l.start_time += *d;
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({"slipped": shifts.iter().map(|(id, d)| json!({"layer": id.0, "delta": d.seconds()})).collect::<Vec<_>>()}))
+}
+
fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, ids) = layers_p(s, p)?;
let how = str_p(p, "to").unwrap_or("front").to_string();
@@ -970,6 +1021,17 @@ pub fn specs() -> Vec<CommandSpec> {
has_layers,
timing
),
+ cmd!("layer.slip", "Slip Edit", [], None, "{layers?, delta? (seconds) | frames?, merge?}", has_layers, slip),
+ cmd!("layer.slipBack", "Slip Edit 1 Frame Earlier", [], Some("Alt+PageUp"), "{layers?}", has_layers, |s, p| {
+ let mut p = p.clone();
+ p["frames"] = json!(-1);
+ slip(s, &p)
+ }),
+ cmd!("layer.slipForward", "Slip Edit 1 Frame Later", [], Some("Alt+PageDown"), "{layers?}", has_layers, |s, p| {
+ let mut p = p.clone();
+ p["frames"] = json!(1);
+ slip(s, &p)
+ }),
cmd!("layer.arrange", "Arrange", ["Layer", "Arrange"], None, "{layers?, to: front|forward|backward|back, index?}", has_layers, arrange),
cmd!("layer.precompose", "Pre-compose...", ["Layer"], Some("Cmd+Shift+C"), "{layers?, name?}", has_layers, precompose),
cmd!(
diff --git a/crates/engine/src/tests_fidelity.rs b/crates/engine/src/tests_fidelity.rs
index d1b63e2d8..e5e84c03d 100644
--- a/crates/engine/src/tests_fidelity.rs
+++ b/crates/engine/src/tests_fidelity.rs
@@ -26,3 +26,58 @@ fn project_colour_settings_are_undoable() {
assert_eq!(s.execute("file.cycleBitDepth", json!({})).unwrap(), json!(want));
}
}
+
+#[test]
+fn footage_colour_profile_is_interpreted() {
+ let mut s = Session::default();
+ let id = s.execute("file.importPlaceholder", json!({"name": "clip", "width": 64, "height": 36, "frameRate": 24, "duration": 2})).unwrap();
+ let item = id["item"].as_u64().or_else(|| id.as_u64()).map(effectcraft_project::ItemId).unwrap_or_else(|| *s.project.items.keys().last().unwrap());
+ let profile = |s: &Session| match &s.project.item(item).unwrap().kind {
+ effectcraft_project::ItemKind::Footage(f) => f.color_profile,
+ _ => panic!("not footage"),
+ };
+ s.execute("file.interpretFootage", json!({"items": [item.0], "colorProfile": "rec2020"})).unwrap();
+ assert_eq!(profile(&s), Some(ColorSpace::Rec2020));
+ s.execute("file.interpretFootage", json!({"items": [item.0], "colorProfile": "auto"})).unwrap();
+ assert_eq!(profile(&s), None);
+ assert!(s.undo());
+ assert_eq!(profile(&s), Some(ColorSpace::Rec2020));
+}
+
+#[test]
+fn slip_moves_the_source_under_fixed_in_and_out() {
+ use effectcraft_time::Tick;
+ let mut s = Session::default();
+ s.execute("comp.new", json!({"name": "Main", "width": 100, "height": 100, "frameRate": 30, "duration": 10})).unwrap();
+ let nested = s.execute("comp.new", json!({"name": "Nested", "duration": 4, "open": false})).unwrap()["comp"].as_u64().unwrap();
+ s.execute("layer.addItem", json!({"item": nested})).unwrap();
+ let id = s.active_comp().unwrap().layers[0].id.0;
+ // Trim to 1 s .. 3 s of a 4 s source.
+ s.execute("layer.timing", json!({"layers": [id], "in": 1.0, "out": 3.0})).unwrap();
+ let get = |s: &Session| s.active_comp().unwrap().layers[0].clone();
+ let before = get(&s);
+ assert_eq!((before.start_time, before.in_point.seconds(), before.out_point.seconds()), (Tick::ZERO, 1.0, 3.0));
+ // Slip the source 0.5 s later: in/out stay, the source (start) moves.
+ s.execute("layer.slip", json!({"layers": [id], "delta": 0.5})).unwrap();
+ let l = get(&s);
+ assert_eq!((l.start_time.seconds(), l.in_point, l.out_point), (0.5, before.in_point, before.out_point));
+ // The source time at comp 2 s is now 1.5 s.
+ assert_eq!(l.layer_time(Tick::from_seconds_f64(2.0)).seconds(), 1.5);
+ // Clamped so the source still covers in..out: at most start = in (1 s).
+ let r = s.execute("layer.slip", json!({"layers": [id], "delta": 5.0})).unwrap();
+ assert_eq!(get(&s).start_time.seconds(), 1.0);
+ assert_eq!(r["slipped"][0]["delta"], json!(0.5));
+ // Alt+PageUp / Alt+PageDown nudge by a frame.
+ s.execute("layer.slipBack", json!({"layers": [id]})).unwrap();
+ assert!((get(&s).start_time.seconds() - (1.0 - 1.0 / 30.0)).abs() < 1e-9);
+ s.execute("layer.slipForward", json!({"layers": [id]})).unwrap();
+ assert_eq!(get(&s).start_time.seconds(), 1.0);
+ // Undo walks back through the slips.
+ assert!(s.undo() && s.undo() && s.undo() && s.undo());
+ assert_eq!(get(&s).start_time, Tick::ZERO);
+ assert_eq!(crate::find_command("layer.slipBack").and_then(|c| c.shortcut), Some("Alt+PageUp"));
+ assert_eq!(crate::find_command("layer.slipForward").and_then(|c| c.shortcut), Some("Alt+PageDown"));
+ // Layers without a source duration can't slip.
+ s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap();
+ assert!(s.execute("layer.slip", json!({"delta": 0.5})).is_err());
+}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index b200386e5..05c05efa5 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -21,7 +21,7 @@ use std::sync::Arc;
pub use cache::{CacheStats, LayerCache};
use effectcraft_color::BlendMode;
use effectcraft_effects::{Buf, EffectCtx, EffectEnv, EffectHost, LayerPixels, Params};
-use effectcraft_geom::{Mat3, vec2};
+use effectcraft_geom::{Mat3, Mat4, vec2};
use effectcraft_project::{Comp, Footage, FootageKind, FrameBlend, GroupKind, ItemId, ItemKind, Layer, LayerSource, MatteKind, Project, Quality, Sampling};
pub use effectcraft_raster::Image;
use effectcraft_raster::{WarpOpts, composite_warp};
@@ -160,6 +160,24 @@ pub struct Renderer<'a> {
depth: usize,
/// The project's colour pipeline (bit depth, working space, linear blending).
pub(crate) pipe: color::Pipe,
+ /// Collapsed precomp being drawn into its parent: nested comp pixels → parent comp pixels
+ /// (before the output scale).
+ outer: Option<Mat3>,
+ /// Opacity of the collapsed precomp layers this comp is drawn through.
+ opacity_mul: f32,
+ /// Collapsed precomp: nested 3D layers join the parent's 3D space.
+ pub(crate) collapse3d: Option<Collapse3d<'a>>,
+}
+
+/// How a collapsed precomp's 3D layers are placed in the parent (see `Renderer::collapse_into`).
+#[derive(Clone, Copy)]
+pub(crate) struct Collapse3d<'a> {
+ /// Nested comp world → parent world (the precomp layer's world transform).
+ pub world: Mat4,
+ /// The parent's camera.
+ pub cam: three_d::CameraState,
+ /// The outermost comp's context (its lights light the nested layers).
+ pub parent: EvalCtx<'a>,
}
/// Time spent on one layer of one frame (milliseconds).
@@ -179,12 +197,139 @@ pub struct LayerTiming {
impl<'a> Renderer<'a> {
pub fn new(project: &'a Project, footage: &'a dyn FootageSource, opts: RenderOpts) -> Renderer<'a> {
- Renderer { project, footage, expr: None, opts, cache: None, profile: None, depth: 0, pipe: color::Pipe::of(&project.settings) }
+ Renderer {
+ project,
+ footage,
+ expr: None,
+ opts,
+ cache: None,
+ profile: None,
+ depth: 0,
+ pipe: color::Pipe::of(&project.settings),
+ outer: None,
+ opacity_mul: 1.0,
+ collapse3d: None,
+ }
}
/// A renderer for nested work (precomps, layers read by effects): one level deeper.
fn nested(&self) -> Renderer<'a> {
- Renderer { depth: self.depth + 1, ..*self }
+ Renderer { depth: self.depth + 1, outer: None, opacity_mul: 1.0, collapse3d: None, ..*self }
+ }
+
+ /// The nested comp of a precomp layer whose transformations collapse into this comp: the
+ /// Collapse Transformations switch is on and the layer has no masks, effects or layer
+ /// styles (those force a flattened render of the precomp, as in After Effects).
+ pub(crate) fn collapsed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<ItemId> {
+ if !layer.switches.collapse || layer.switches.adjustment || self.depth > 12 {
+ return None;
+ }
+ let LayerSource::Comp { item } = &layer.source else { return None };
+ if self.project.comp_contains(*item, ctx.comp_id) || self.project.comp(*item).is_none() {
+ return None;
+ }
+ if layer.masks().is_some_and(|m| !m.children.is_empty()) {
+ return None;
+ }
+ if layer.switches.effects && layer.effects().is_some_and(|fx| fx.groups().any(|g| g.enabled)) {
+ return None;
+ }
+ if styles::active(ctx, layer) {
+ return None;
+ }
+ Some(*item)
+ }
+
+ /// A renderer and context that draw a collapsed precomp's layers straight into this comp:
+ /// their transforms are concatenated with the precomp layer's (one resample, no
+ /// rasterisation at the precomp's bounds), their opacity multiplied by `opacity`, and their
+ /// 3D layers use this comp's camera and lights.
+ pub(crate) fn collapse_into(&self, ctx: &EvalCtx<'a>, layer: &Layer, item: ItemId, opacity: f32) -> Option<(Renderer<'a>, EvalCtx<'a>)> {
+ let nc = self.project.comp(item)?;
+ let nctx = EvalCtx { comp_id: item, comp: nc, time: ctx.source_time(layer), ..*ctx };
+ let (l2c, _) = ctx.layer_to_comp(layer);
+ let outer = Some(self.outer.map_or(l2c, |o| o * l2c));
+ let world = ctx.world_matrix(layer);
+ let c3 = Collapse3d {
+ world: self.collapse3d.map_or(world, |c| c.world * world),
+ cam: three_d::compose::camera_for(self, ctx),
+ parent: self.collapse3d.map_or(*ctx, |c| c.parent),
+ };
+ Some((Renderer { depth: self.depth + 1, outer, opacity_mul: opacity, collapse3d: Some(c3), ..*self }, nctx))
+ }
+
+ pub(crate) fn opacity_mul(&self) -> f32 {
+ self.opacity_mul
+ }
+
+ /// Draw a collapsed 2D precomp layer: nested layers blend straight into `canvas` with their
+ /// own modes (Normal precomp, no matte); otherwise they are drawn into an isolated buffer
+ /// that then takes the precomp layer's track matte, Preserve Transparency and blend mode.
+ fn draw_collapsed(&self, ctx: &EvalCtx<'a>, layer: &Layer, item: ItemId, canvas: &mut Image) {
+ let opacity = ctx.opacity(layer) as f32 * self.opacity_mul;
+ if opacity <= 0.0 {
+ return;
+ }
+ let matte = layer.track_matte.is_some_and(|tm| tm.layer != layer.id && ctx.comp.layer(tm.layer).is_some());
+ if layer.blend_mode == BlendMode::Normal && !matte && !layer.preserve_transparency {
+ if let Some((sub, nctx)) = self.collapse_into(ctx, layer, item, opacity) {
+ sub.draw_comp(&nctx, canvas);
+ }
+ return;
+ }
+ let Some((sub, nctx)) = self.collapse_into(ctx, layer, item, 1.0) else { return };
+ let mut iso = Image::new(canvas.width, canvas.height);
+ sub.draw_comp(&nctx, &mut iso);
+ self.composite_iso(ctx, layer, iso, canvas, opacity);
+ }
+
+ /// Rasterisation scale of a layer's source: the output scale, or — for Continuously
+ /// Rasterize text and shape layers — the output scale times the layer's on-screen scale
+ /// (quarter-octave steps, rounded up, so vector content is drawn at its final size and
+ /// stays sharp when scaled up).
+ pub fn raster_scale(&self, ctx: &EvalCtx, layer: &Layer) -> f64 {
+ let s = self.opts.scale;
+ if !layer.switches.collapse || !matches!(layer.source, LayerSource::Text | LayerSource::Shape) {
+ return s;
+ }
+ let (l2c, _) = ctx.layer_to_comp(layer);
+ let m = self.outer.map_or(l2c, |o| o * l2c);
+ let a = layer.transform().map(|tr| ctx.v3(layer, tr, "anchor", [0.0; 3])).unwrap_or([0.0; 3]);
+ let p0 = m.apply(vec2(a[0], a[1]));
+ let px = m.apply(vec2(a[0] + 1.0, a[1]));
+ let py = m.apply(vec2(a[0], a[1] + 1.0));
+ let k = ((px.x - p0.x).hypot(px.y - p0.y)).max((py.x - p0.x).hypot(py.y - p0.y));
+ if !k.is_finite() || k <= 1e-6 {
+ return s;
+ }
+ let mut k = 2f64.powf((k.log2() * 4.0).ceil() / 4.0).clamp(1.0 / 16.0, 64.0);
+ // Keep the buffer within about 16 million pixels.
+ if let Some(b) = content_bounds(ctx, layer) {
+ let area = ((b[2] - b[0]) * (b[3] - b[1])).max(1.0) * s * s;
+ k = k.min((16.0e6 / area).sqrt().max(1.0));
+ }
+ s * k
+ }
+
+ /// Draw a Wireframe-quality layer: its bounds as a one-pixel outline.
+ fn draw_wireframe(&self, ctx: &EvalCtx, layer: &Layer, canvas: &mut Image) {
+ let Some(b) = content_bounds(ctx, layer) else { return };
+ let s = self.opts.scale;
+ let (l2c, _) = ctx.layer_to_comp(layer);
+ let m = Mat3::scale(vec2(s, s)) * self.outer.map_or(l2c, |o| o * l2c);
+ let c = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])].map(|(x, y)| m.apply(vec2(x, y)));
+ let (w, h) = (canvas.width as i64, canvas.height as i64);
+ for i in 0..4 {
+ let (p, q) = (c[i], c[(i + 1) % 4]);
+ let n = ((q.x - p.x).abs().max((q.y - p.y).abs()) * 2.0).ceil().clamp(1.0, 1.0e5) as usize;
+ for j in 0..=n {
+ let t = j as f64 / n as f64;
+ let (x, y) = ((p.x + (q.x - p.x) * t).floor() as i64, (p.y + (q.y - p.y) * t).floor() as i64);
+ if x >= 0 && y >= 0 && x < w && y < h {
+ canvas.set(x as u32, y as u32, [1.0, 1.0, 1.0, 1.0]);
+ }
+ }
+ }
}
fn ctx(&self, comp_id: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> {
@@ -238,7 +383,10 @@ impl<'a> Renderer<'a> {
three_d::compose::draw_run(self, ctx, &visible[i..j], canvas);
i = j;
} else {
- self.draw_layer(ctx, visible[i], canvas);
+ match self.collapsed(ctx, visible[i]) {
+ Some(item) => self.draw_collapsed(ctx, visible[i], item, canvas),
+ None => self.draw_layer(ctx, visible[i], canvas),
+ }
i += 1;
}
// 8/16 bpc: the comp is an integer buffer after every layer.
@@ -363,8 +511,8 @@ impl<'a> Renderer<'a> {
}
Some(buf)
}
- LayerSource::Text => Some(self.authored(text::render(ctx, layer, s))),
- LayerSource::Shape => layer.props.sub("contents").map(|c| self.authored(shapes::render(ctx, layer, c, s))),
+ LayerSource::Text => Some(self.authored(text::render(ctx, layer, self.raster_scale(ctx, layer)))),
+ LayerSource::Shape => layer.props.sub("contents").map(|c| self.authored(shapes::render(ctx, layer, c, self.raster_scale(ctx, layer)))),
_ => None,
}
}
@@ -480,7 +628,7 @@ impl<'a> Renderer<'a> {
}
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));
+ let key = self.cache.and_then(|_| cache::layer_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft));
if let (Some(c), Some(k)) = (self.cache, key)
&& let Some(b) = c.get(k)
{
@@ -501,7 +649,7 @@ impl<'a> Renderer<'a> {
/// (what Time effects read at neighbouring times). Served from / stored in the layer cache
/// under its own key, so scrubbing reuses frames rendered for earlier output frames.
pub fn layer_input(&self, ctx: &EvalCtx, layer: &Layer, effects: usize) -> Option<Arc<Buf>> {
- let key = self.cache.and_then(|_| cache::input_key(ctx, layer, self.opts.scale, self.opts.draft, effects));
+ let key = self.cache.and_then(|_| cache::input_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, effects));
if let (Some(c), Some(k)) = (self.cache, key)
&& let Some(b) = c.get(k)
{
@@ -565,7 +713,10 @@ impl<'a> Renderer<'a> {
}
fn sampling(&self, layer: &Layer) -> effectcraft_raster::Sampling {
- if self.opts.draft || layer.switches.quality == Quality::Draft {
+ if layer.switches.quality == Quality::Draft {
+ // Draft quality: no interpolation (nearest neighbour), as After Effects' Draft.
+ effectcraft_raster::Sampling::Nearest
+ } else if self.opts.draft {
effectcraft_raster::Sampling::Bilinear
} else if layer.switches.sampling == Sampling::Bicubic {
effectcraft_raster::Sampling::Bicubic
@@ -578,6 +729,7 @@ impl<'a> Renderer<'a> {
fn buf_matrix(&self, ctx: &EvalCtx, layer: &Layer, buf: &Buf) -> Mat3 {
let s = self.opts.scale;
let (l2c, _) = ctx.layer_to_comp(layer);
+ let l2c = self.outer.map_or(l2c, |o| o * l2c);
Mat3::scale(vec2(s, s)) * l2c * Mat3::scale(vec2(1.0 / buf.scale, 1.0 / buf.scale)) * Mat3::translate(vec2(-buf.offset[0], -buf.offset[1]))
}
@@ -610,7 +762,11 @@ impl<'a> Renderer<'a> {
}
fn draw_layer(&self, ctx: &EvalCtx, layer: &Layer, canvas: &mut Image) {
- let opacity = ctx.opacity(layer) as f32;
+ let opacity = ctx.opacity(layer) as f32 * self.opacity_mul;
+ if layer.switches.quality == Quality::Wireframe && !layer.switches.adjustment {
+ self.draw_wireframe(ctx, layer, canvas);
+ return;
+ }
if opacity <= 0.0 && !layer.switches.adjustment {
return;
}
@@ -825,6 +981,8 @@ pub fn kurbo_path(sp: &effectcraft_keyframe::ShapePath) -> kurbo::BezPath {
#[cfg(test)]
mod tests_audio_fx;
#[cfg(test)]
+mod tests_collapse;
+#[cfg(test)]
mod tests_color;
#[cfg(test)]
mod tests_frame_blend;
diff --git a/crates/render/src/tests_collapse.rs b/crates/render/src/tests_collapse.rs
new file mode 100644
index 000000000..d3cf954cf
--- /dev/null
+++ b/crates/render/src/tests_collapse.rs
@@ -0,0 +1,202 @@
+//! Collapse Transformations, Continuously Rasterize and the Quality switch.
+
+use effectcraft_color::{BlendMode, Label};
+use effectcraft_keyframe::Value;
+use effectcraft_project::build::{self, Ids};
+use effectcraft_project::{BitDepth, Comp, ItemId, ItemKind, Layer, LayerSource, Project, Quality, Solid};
+use effectcraft_time::{FrameRate, Tick};
+
+use crate::{Image, render_frame};
+
+fn project() -> Project {
+ let mut p = Project::default();
+ p.settings.bit_depth = BitDepth::Bpc32;
+ p
+}
+
+fn solid(p: &mut Project, comp: &Comp, color: [f32; 3], size: (u32, u32), pos: [f64; 3]) -> Layer {
+ let sid = p.add_item("S", Label::Red, None, ItemKind::Solid(Solid { color, width: size.0, height: size.1, pixel_aspect: 1.0 }));
+ let mut l = build::layer(p, comp, "S", LayerSource::Solid { item: sid }, size, None);
+ l.props.prop_mut("transform/position").unwrap().value = Value::Vec3(pos);
+ l
+}
+
+fn set(l: &mut Layer, path: &str, v: Value) {
+ l.props.prop_mut(path).unwrap().value = v;
+}
+
+fn max_diff(a: &Image, b: &Image) -> f32 {
+ a.data.iter().zip(&b.data).flat_map(|(p, q)| (0..4).map(move |c| (p[c] - q[c]).abs())).fold(0.0, f32::max)
+}
+
+/// Outer 200×100 comp: a grey background, and either a precomp (scaled 150%, rotated) of two
+/// solids — the top one in Add mode — or the same two solids parented to a null that carries the
+/// precomp layer's transform (the manual flattening).
+fn scene(collapse: bool, flatten: bool) -> (Project, ItemId) {
+ let mut p = project();
+ let outer = Comp::new(200, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
+ let inner = Comp::new(100, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
+ let mut a = solid(&mut p, &inner, [0.6, 0.1, 0.1], (40, 40), [40.0, 50.0, 0.0]);
+ let mut b = solid(&mut p, &inner, [0.1, 0.3, 0.6], (40, 40), [60.0, 50.0, 0.0]);
+ b.blend_mode = BlendMode::Add;
+ let bg = solid(&mut p, &outer, [0.3, 0.3, 0.3], (200, 100), [100.0, 50.0, 0.0]);
+ let xf = |l: &mut Layer| {
+ set(l, "transform/anchor", Value::Vec3([50.0, 50.0, 0.0]));
+ set(l, "transform/position", Value::Vec3([100.0, 50.0, 0.0]));
+ set(l, "transform/scale", Value::Vec3([150.0, 150.0, 100.0]));
+ set(l, "transform/rotation", Value::Scalar(20.0));
+ };
+ let cid;
+ if flatten {
+ let mut null = build::layer(&mut p, &outer, "Null", LayerSource::Null, (100, 100), None);
+ xf(&mut null);
+ a.parent = Some(null.id);
+ b.parent = Some(null.id);
+ let mut c = outer.clone();
+ c.layers = vec![null, b, a, bg];
+ cid = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(c.into()));
+ } else {
+ let mut inner = inner;
+ inner.layers = vec![b, a];
+ let iid = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into()));
+ let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: iid }, (100, 100), None);
+ xf(&mut pre);
+ pre.switches.collapse = collapse;
+ let mut c = outer.clone();
+ c.layers = vec![pre, bg];
+ cid = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(c.into()));
+ }
+ (p, cid)
+}
+
+#[test]
+fn collapsed_precomp_equals_manual_flattening() {
+ let (p, cid) = scene(false, true);
+ let flat = render_frame(&p, cid, Tick::ZERO, 1.0);
+ let (p, cid) = scene(true, false);
+ let collapsed = render_frame(&p, cid, Tick::ZERO, 1.0);
+ assert!(max_diff(&flat, &collapsed) < 1e-4, "collapsed differs from flattening by {}", max_diff(&flat, &collapsed));
+ // Without collapsing, Add only sees the precomp's own layers (not the grey below), and the
+ // precomp is resampled twice.
+ let (p, cid) = scene(false, false);
+ let nested = render_frame(&p, cid, Tick::ZERO, 1.0);
+ assert!(max_diff(&flat, &nested) > 0.2);
+ // Opacity of the collapsed layer fades every nested layer.
+ let (mut p, cid) = scene(true, false);
+ set(&mut p.comp_mut(cid).unwrap().layers[0], "transform/opacity", Value::Scalar(50.0));
+ let half = render_frame(&p, cid, Tick::ZERO, 1.0);
+ let (x, y) = (100, 50);
+ let (bg, full) = (0.3, collapsed.get(x, y)[0]);
+ assert!((half.get(x, y)[0] - (bg + (full - bg) * 0.5)).abs() < 0.03, "{:?} vs {full}", half.get(x, y));
+}
+
+#[test]
+fn masks_on_a_collapsed_layer_force_a_flattened_render() {
+ let (mut p, cid) = scene(true, false);
+ let (p2, cid2) = scene(false, false);
+ // Add a mask covering everything: the layer renders like an uncollapsed precomp.
+ let mut next = p.next_id;
+ let mask = build::mask(
+ &mut Ids(&mut next),
+ "Mask 1",
+ effectcraft_keyframe::ShapePath::rect([50.0, 50.0], 4000.0, 4000.0),
+ effectcraft_project::MaskMode::Add,
+ [255, 255, 0],
+ );
+ p.next_id = next;
+ p.comp_mut(cid).unwrap().layers[0].props.sub_mut("masks").unwrap().children.push(mask.into());
+ let a = render_frame(&p, cid, Tick::ZERO, 1.0);
+ let b = render_frame(&p2, cid2, Tick::ZERO, 1.0);
+ assert!(max_diff(&a, &b) < 1e-4, "{}", max_diff(&a, &b));
+}
+
+#[test]
+fn collapsed_3d_layers_join_the_parent_scene() {
+ // Parent: a red 3D solid at z = 0 above (in the stack) a collapsed 3D precomp holding a
+ // blue 3D solid at z = −200 (nearer the camera). Collapsed, depth sorting puts blue in front;
+ // uncollapsed, the precomp is one plane at z = 0 drawn below the red.
+ let run = |collapse: bool| {
+ let mut p = project();
+ let outer = Comp::new(200, 200, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
+ let inner = Comp::new(200, 200, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
+ let mut blue = solid(&mut p, &inner, [0.0, 0.0, 1.0], (60, 60), [100.0, 100.0, -200.0]);
+ blue.switches.three_d = true;
+ let mut inner = inner;
+ inner.layers = vec![blue];
+ let iid = p.add_item("Inner", Label::Sandstone, None, ItemKind::Comp(inner.into()));
+ let mut pre = build::layer(&mut p, &outer, "Inner", LayerSource::Comp { item: iid }, (200, 200), None);
+ pre.switches.three_d = true;
+ pre.switches.collapse = collapse;
+ let mut red = solid(&mut p, &outer, [1.0, 0.0, 0.0], (100, 100), [100.0, 100.0, 0.0]);
+ red.switches.three_d = true;
+ let mut c = outer;
+ c.layers = vec![red, pre];
+ let cid = p.add_item("Outer", Label::Sandstone, None, ItemKind::Comp(c.into()));
+ render_frame(&p, cid, Tick::ZERO, 1.0).get(100, 100)
+ };
+ let c = run(true);
+ assert!(c[2] > 0.99 && c[0] < 0.01, "collapsed: blue in front {c:?}");
+ let n = run(false);
+ assert!(n[0] > 0.99 && n[2] < 0.01, "uncollapsed: red on top {n:?}");
+}
+
+/// Pixels along row `y` from `x0` to `x1` with partial coverage (an edge's width).
+fn edge_width(img: &Image, y: i64, x0: i64, x1: i64) -> usize {
+ (x0..x1).filter(|&x| (0.02..0.98).contains(&img.get(x, y)[3])).count()
+}
+
+#[test]
+fn continuously_rasterized_shape_stays_sharp_when_scaled_up() {
+ let run = |cr: bool| {
+ let mut p = project();
+ let comp = Comp::new(200, 200, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
+ let mut l = build::layer(&mut p, &comp, "Shape", LayerSource::Shape, (200, 200), None);
+ let mut next = p.next_id;
+ let mut ids = Ids(&mut next);
+ let rect = build::shape_rect(&mut ids, [10.0, 10.0], [0.0, 0.0], 0.0);
+ let fill = build::shape_fill(&mut ids, [1.0, 1.0, 1.0, 1.0]);
+ let g = build::shape_group(&mut ids, "Rectangle 1", vec![rect, fill]);
+ p.next_id = next;
+ l.props.sub_mut("contents").unwrap().children.push(g.into());
+ set(&mut l, "transform/anchor", Value::Vec3([0.0, 0.0, 0.0]));
+ set(&mut l, "transform/position", Value::Vec3([100.3, 100.3, 0.0]));
+ set(&mut l, "transform/scale", Value::Vec3([800.0, 800.0, 100.0]));
+ l.switches.collapse = cr;
+ let mut c = comp;
+ c.layers = vec![l];
+ let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(c.into()));
+ render_frame(&p, cid, Tick::ZERO, 1.0)
+ };
+ // The 10 px square scaled 800% spans 60.3..140.3.
+ let soft = run(false);
+ let sharp = run(true);
+ let ws = edge_width(&soft, 100, 50, 75);
+ let wc = edge_width(&sharp, 100, 50, 75);
+ assert!(ws >= 4, "bitmap scaling blurs the edge: {ws}");
+ assert!(wc <= 1, "continuously rasterized edge: {wc}");
+ assert!(sharp.get(100, 100)[3] > 0.99 && sharp.get(55, 100)[3] < 0.01);
+}
+
+#[test]
+fn wireframe_quality_draws_the_layer_bounds() {
+ let mut p = project();
+ let comp = Comp::new(100, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
+ let mut l = solid(&mut p, &comp, [1.0, 0.0, 0.0], (40, 40), [50.0, 50.0, 0.0]);
+ l.switches.quality = Quality::Wireframe;
+ let mut c = comp;
+ c.layers = vec![l];
+ let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(c.into()));
+ let img = render_frame(&p, cid, Tick::ZERO, 1.0);
+ assert_eq!(img.get(50, 50)[3], 0.0, "no fill");
+ assert_eq!(img.get(30, 50), [1.0, 1.0, 1.0, 1.0], "outline");
+ // Draft quality samples nearest-neighbour: no partial pixels at a half-pixel offset.
+ let mut p = project();
+ let comp = Comp::new(100, 100, FrameRate::FPS_30, Tick::from_seconds_f64(2.0));
+ let mut l = solid(&mut p, &comp, [1.0, 1.0, 1.0], (40, 40), [50.5, 50.0, 0.0]);
+ l.switches.quality = Quality::Draft;
+ let mut c = comp;
+ c.layers = vec![l];
+ let cid = p.add_item("Comp", Label::Sandstone, None, ItemKind::Comp(c.into()));
+ let img = render_frame(&p, cid, Tick::ZERO, 1.0);
+ assert!(img.data.iter().all(|q| q[3] == 0.0 || q[3] == 1.0));
+}
diff --git a/crates/render/src/three_d/compose.rs b/crates/render/src/three_d/compose.rs
index 421587bc7..53ba8cdbc 100644
--- a/crates/render/src/three_d/compose.rs
+++ b/crates/render/src/three_d/compose.rs
@@ -150,6 +150,10 @@ fn unproject(g: &Geo, sx: f64, sy: f64) -> Option<(f64, f64, f64)> {
/// The camera a renderer uses at a context time (view override only for the top-level comp).
pub(crate) fn camera_for(r: &Renderer, ctx: &EvalCtx) -> CameraState {
+ // Collapsed precomps see through the parent's camera.
+ if let Some(c) = r.collapse3d {
+ return c.cam;
+ }
match r.opts.view {
Some(v) if r.depth == 0 => v,
_ => active_camera(ctx),
@@ -200,7 +204,8 @@ fn prepare_with<'a>(
let comp = (ctx.comp.width as f64, ctx.comp.height as f64);
let s = r.opts.scale;
let cam = camera_for(r, ctx);
- let world = ctx.world_matrix(layer) * local;
+ let outer = r.collapse3d.map_or(Mat4::IDENTITY, |c| c.world);
+ let world = outer * ctx.world_matrix(layer) * local;
// Depth of field: blur the layer by its circle of confusion at its centre.
if let Some(dof) = cam.dof.filter(|_| !ctx.comp.draft_3d && !r.opts.draft) {
let b = buf_bounds(&buf);
@@ -234,7 +239,7 @@ fn prepare_with<'a>(
let f = phase + angle * i as f64 / (n - 1) as f64;
let sub = ctx.at(ctx.time + Tick::from_seconds_f64(f * fd));
let c = camera_for(r, &sub);
- geo(&c, sub.world_matrix(layer) * local, &buf, comp, s, out)
+ geo(&c, outer * sub.world_matrix(layer) * local, &buf, comp, s, out)
})
.collect()
};
@@ -253,7 +258,7 @@ fn prepare_with<'a>(
bicubic: matches!(r.sampling(layer), effectcraft_raster::Sampling::Bicubic),
buf,
geos,
- opacity: ctx.opacity(layer) as f32,
+ opacity: ctx.opacity(layer) as f32 * r.opacity_mul(),
draw: in_run && mat.casts_shadows != 2,
mat,
matte: None,
@@ -319,12 +324,18 @@ pub(crate) fn draw_run(r: &Renderer, ctx: &EvalCtx, run: &[&Layer], canvas: &mut
return;
}
let out = (canvas.width, canvas.height);
- let lights = scene_lights(ctx);
+ // A collapsed precomp's 3D layers are lit by the outer comp's lights.
+ let lights = scene_lights(&r.collapse3d.map_or(*ctx, |c| c.parent));
let mut items: Vec<Item> = run
.par_iter()
.enumerate()
- .filter(|(_, l)| ctx.opacity(l) > 0.0)
+ .filter(|(_, l)| ctx.opacity(l) > 0.0 && l.switches.quality != effectcraft_project::Quality::Wireframe)
.flat_map_iter(|(i, l)| {
+ // Stack order with room for a collapsed precomp's layers in between.
+ let i = i * 1024;
+ if let Some(item) = r.collapsed(ctx, l) {
+ return collapsed_items(r, ctx, l, item, i, out);
+ }
let mut its = prepare_all(r, ctx, l, i, out, true);
if !its.is_empty() {
let m = matte_for(r, ctx, l, out);
@@ -351,6 +362,49 @@ pub(crate) fn draw_run(r: &Renderer, ctx: &EvalCtx, run: &[&Layer], canvas: &mut
items.sort_by_key(|i| i.order);
let casters: Vec<&Item> = items.iter().chain(extra.iter()).filter(|i| i.mat.casts_shadows != 0 && !i.geos.is_empty()).collect();
composite(canvas, &items, &lights, &casters, run[0].id.0 as u32);
+ for l in run.iter().filter(|l| l.switches.quality == effectcraft_project::Quality::Wireframe) {
+ r.draw_layer(ctx, l, canvas);
+ }
+}
+
+/// A collapsed 3D precomp layer inside a 3D run: its nested layers become planes in this comp's
+/// 3D space (world = precomp layer's world × nested world), depth-sorted with the run, so they
+/// intersect the parent's 3D layers; nested 2D layers lie on the precomp layer's plane in stack
+/// order. (Nested adjustment layers are skipped here.)
+fn collapsed_items<'a>(
+ r: &Renderer<'a>,
+ ctx: &EvalCtx<'a>,
+ layer: &'a Layer,
+ item: effectcraft_project::ItemId,
+ order: usize,
+ out: (u32, u32),
+) -> Vec<Item<'a>> {
+ let op = ctx.opacity(layer) as f32 * r.opacity_mul();
+ let Some((sub, nctx)) = r.collapse_into(ctx, layer, item, op) else { return vec![] };
+ let t = nctx.time;
+ let any_solo = nctx.comp.layers.iter().any(|l| l.switches.solo && l.source.is_av() && l.is_active_at(t));
+ let nested: Vec<&'a Layer> = nctx
+ .comp
+ .layers
+ .iter()
+ .rev()
+ .filter(|l| l.is_active_at(t) && l.has_video() && !l.switches.adjustment && (!any_solo || l.switches.solo) && (r.opts.guides || !l.switches.guide))
+ .collect();
+ let mut items = Vec::new();
+ for (k, l) in nested.into_iter().enumerate() {
+ if nctx.opacity(l) <= 0.0 {
+ continue;
+ }
+ let mut its = prepare_all(&sub, &nctx, l, order + 1 + k.min(1022), out, true);
+ if !its.is_empty() {
+ let m = matte_for(&sub, &nctx, l, out);
+ for it in &mut its {
+ it.matte = m.clone();
+ }
+ }
+ items.extend(its);
+ }
+ items
}
/// Per-pixel depth-sorted compositing of prepared planes.
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index ab85e8eb1..be891090f 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -953,8 +953,40 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
{
let xs = tm.x(layer.start_time.seconds());
let xe = tm.x(layer.comp_time(d).seconds());
- let ghost = Rect::from_min_max(pos2(xs, r.min.y + 9.0), pos2(xe, r.max.y - 9.0));
+ let ghost = Rect::from_min_max(pos2(xs.min(xe), r.min.y + 9.0), pos2(xs.max(xe), r.max.y - 9.0));
gp.rect_filled(ghost, 1.0, lc.gamma_multiply(0.18));
+ // Dragging the source bar outside the in/out span slips the source.
+ for (side, gr) in [
+ ("l", Rect::from_min_max(ghost.min, pos2(bar.min.x, ghost.max.y))),
+ ("r", Rect::from_min_max(pos2(bar.max.x, ghost.min.y), ghost.max)),
+ ] {
+ if gr.width() < 2.0 {
+ continue;
+ }
+ let gresp = ui.interact(gr, egui::Id::new(("ghost", side, layer.id.0)), Sense::drag()).on_hover_text("Drag to slip the source");
+ app.auto.add(&format!("timeline.layer.{}.source{}", layer.id.0, side), gr, "Slip");
+ if gresp.hovered() || gresp.dragged() {
+ ctx.set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
+ }
+ let acc_id = egui::Id::new(("slip-acc", layer.id.0));
+ if gresp.dragged() {
+ let mut acc: f32 = ctx.data(|d| d.get_temp(acc_id).unwrap_or(0.0));
+ acc += gresp.drag_delta().x;
+ let frames = ((acc as f64 / pps) / fd).trunc() as i64;
+ if frames != 0 {
+ acc -= (frames as f64 * fd * pps) as f32;
+ actions.push((
+ "layer.slip".into(),
+ json!({"layers": [layer.id.0], "frames": frames, "merge": format!("slip-{}", layer.id.0)}),
+ ));
+ }
+ ctx.data_mut(|d| d.insert_temp(acc_id, acc));
+ }
+ if gresp.drag_stopped() {
+ ctx.data_mut(|d| d.remove::<f32>(acc_id));
+ ui_actions.push(UiAct::EndMerge);
+ }
+ }
}
app.auto.add(&format!("timeline.layer.{}.bar", layer.id.0), bar, &layer.name);
// Interactions: move body, trim edges.
diff --git a/docs/architecture.md b/docs/architecture.md
index b78865817..dc95f35b5 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -103,6 +103,30 @@ groups into `Params` keys (`effects::flatten_params`). Commands: `paint.*`, `pup
Half, Third and Quarter resolution render proportionally fewer pixels end to end.
+**Colour and bit depth** (`crates/render/src/color.rs`, `crates/color/src/space.rs`). Pixels are
+`f32`, but 8 and 16 bpc projects clamp and quantise each layer after its source and masks and
+after every effect, and the comp after every layer (16 bpc uses 0..32768), so over-range values
+(Add, Screen, Exposure…) only survive in 32 bpc; blend modes without HDR support clamp their
+inputs in 32 bpc. With a working space (sRGB, Rec. 709, Rec. 2020, Display P3; matrices derived
+from the published primaries), footage is converted from its colour profile (stream metadata or
+Interpret Footage, else sRGB) and the top-level comp is converted to the sRGB display. Linearize
+Working Space runs everything in linear light; Blend Colors Using 1.0 Gamma linearises only for
+blending. Layer cache keys include these settings.
+
+**Frame blending**: footage and precomp layers whose source time falls between source frames
+(rate conform, stretch, remap) blend the two neighbouring frames, by cross-fade (Frame Mix) or by
+hierarchical block-matching optical flow and a bidirectional warp (Pixel Motion,
+`raster::flow`).
+
+**Collapse Transformations**: a collapsed precomp layer without masks, effects or styles draws
+its nested layers straight into the parent with concatenated transforms (one resample), so
+nested blend modes and adjustment layers act on the parent's layers; nested 3D layers use the
+parent's camera and lights and, when the precomp layer is 3D, are depth-sorted with the parent's
+3D run. Masks, effects or styles force a flattened render. On text and shape layers the switch is
+Continuously Rasterize: the source is rasterised at its on-screen scale. Quality: Draft samples
+nearest-neighbour, Wireframe draws the layer bounds. Slip edit (`layer.slip`, Alt+PageUp/Down,
+dragging the source bar in the timeline) moves the source under fixed in/out points.
+
**Motion tracking** (Animation ▸ Track Motion / Stabilize Motion, Window ▸ Tracker): a tracker
is a `Tracker` group under the layer's Motion Trackers group, with Track Point groups (Feature
Center, Feature Size, Search Offset, Search Size, Confidence, Attach Point, Attach Point Offset)