EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Merge main into M7 3D branch
Brandon Thomas83aabf0a8770
diff --cc apps/effectcraft-cli/src/main.rsindex 71c7c4f6e,7e5ce9d1a..43e758378--- a/apps/effectcraft-cli/src/main.rs+++ b/apps/effectcraft-cli/src/main.rs@@@ -28,63 -224,443 +224,443 @@@ fn tool(b: &mut Backend, name: &str, a}}- fn opt<'a>(args: &'a [String], k: &str) -> Option<&'a str> {- args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)+ /// Print a result: compact JSON with `--json`, else pretty JSON.+ fn emit(v: &Value, json_out: bool) {+ if json_out {+ println!("{v}");+ } else {+ println!("{}", serde_json::to_string_pretty(v).unwrap_or_default());+ }}- fn main() {- let args: Vec<String> = std::env::args().skip(1).collect();- let Some(cmd) = args.first().cloned() else { usage() };- let rest = &args[1..];- let mut s = Session::default();- match cmd.as_str() {- "frame" => {- open(&mut s, rest);- if let Some(c) = opt(rest, "--comp") {- let _ = s.execute("comp.open", json!({"comp": c}));- }- let cid = s.active_comp_id().unwrap_or_else(|| {- eprintln!("no composition");- std::process::exit(1)+ fn run(cmd: &str, args: &Args, json_out: bool) -> Result<(), Failure> {+ match cmd {+ "render" => render(args, json_out)?,+ "bench" => bench_cmd(args)?,+ "info" => {+ let mut b = backend(args, true)?;+ let p = tool(&mut b, "get_project", json!({}))?;+ let comp = tool(&mut b, "get_comp", json!({})).ok();+ let info = json!({+ "version": env!("CARGO_PKG_VERSION"),+ "mode": if b.is_bridge() { "bridge" } else { "headless" },+ "commands": effectcraft_engine::command_specs().len(),+ "effects": effectcraft_engine::effects::registry().len(),+ "project": p,+ "activeComp": comp,});- let comp = s.project.comp(cid).cloned().unwrap_or_else(|| std::process::exit(1));- let t = if let Some(f) = opt(rest, "--frame").and_then(|f| f.parse().ok()) {- comp.frame_rate.tick_of(f)+ if json_out {+ emit(&info, true);} else {- opt(rest, "--time").and_then(|v| v.parse().ok()).map(Tick::from_seconds_f64).unwrap_or(s.time())+ println!(+ "EffectCraft {} ({}), {} commands, {} effects",+ info["version"].as_str().unwrap_or(""),+ info["mode"].as_str().unwrap_or(""),+ info["commands"],+ info["effects"]+ );+ println!("project: {}", p["path"].as_str().unwrap_or("(unsaved)"));+ for i in p["items"].as_array().into_iter().flatten() {+ println!(" item {:>3} {:<12} {}", i["id"], i["type"].as_str().unwrap_or(""), i["name"].as_str().unwrap_or(""));+ }+ if let Some(c) = comp {+ println!(+ "active comp {} \"{}\" {}x{} @ {} fps, {} s",+ c["id"],+ c["name"].as_str().unwrap_or(""),+ c["width"],+ c["height"],+ c["frameRate"],+ c["duration"]+ );+ for l in c["layers"].as_array().into_iter().flatten() {+ println!(" #{:<3} id {:<4} {:<10} {}", l["index"], l["id"], l["type"].as_str().unwrap_or(""), l["name"].as_str().unwrap_or(""));+ }+ }+ }+ }+ "commands" => {+ let mut b = backend(args, false)?;+ let v = tool(&mut b, "list_commands", json!({"filter": args.opt("--filter"), "enabled_only": args.flag("--enabled")}))?;+ if json_out {+ emit(&v, true);+ } else {+ for c in v.as_array().into_iter().flatten() {+ println!(+ "{:<36} {:<36} {:<16} {}",+ c["id"].as_str().unwrap_or(""),+ c["label"].as_str().unwrap_or(""),+ c["shortcut"].as_str().unwrap_or(""),+ c["params"].as_str().unwrap_or("")+ );+ }+ }+ }+ "exec" => {+ let Some(id) = args.pos.first().cloned() else { return usage_err("exec needs a command id") };+ let params = match (args.opt("--params"), args.pos.get(1).map(String::as_str)) {+ (Some(p), _) | (None, Some(p)) => serde_json::from_str(p).map_err(|e| Failure::Usage(format!("params are not valid JSON: {e}")))?,+ (None, None) => json!({}),};- let scale = opt(rest, "--scale").and_then(|v| v.parse().ok()).unwrap_or(1.0);- let out = opt(rest, "--out").unwrap_or("frame.png");- let t0 = std::time::Instant::now();- let img = s.render(cid, t, RenderOpts { scale, ..Default::default() });- let el = t0.elapsed();- let bg = comp.background;- let rgba = img.to_rgba8_over(bg);- image::save_buffer(out, &rgba, img.width, img.height, image::ColorType::Rgba8).unwrap_or_else(|e| {- eprintln!("cannot write {out}: {e}");- std::process::exit(1)- });- eprintln!("rendered {}x{} at {:.3}s in {:.1} ms → {out}", img.width, img.height, t.seconds(), el.as_secs_f64() * 1000.0);+ let mut b = backend(args, true)?;+ let r = b.exec(&id, params)?;+ let saved = maybe_save(&mut b, args)?;+ emit(&with_saved(r, saved), json_out);}"run" => {- open(&mut s, rest);- let pairs: Vec<&String> = rest.iter().filter(|a| !a.ends_with(".ecproj") && *a != "--demo").collect();- for ch in pairs.chunks(2) {- let params: Value = ch.get(1).and_then(|p| serde_json::from_str(p).ok()).unwrap_or(json!({}));- match s.execute(ch[0], params) {- Ok(v) => println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default()),- Err(e) => {- eprintln!("{}: {e}", ch[0]);- std::process::exit(1)+ if args.pos.is_empty() {+ return usage_err("run needs <command-id> [<json>] pairs");+ }+ let pairs = args.pos.clone();+ let mut b = backend(args, true)?;+ let mut results = vec![];+ let mut i = 0;+ while i < pairs.len() {+ let id = &pairs[i];+ let params = match pairs.get(i + 1).filter(|p| p.trim_start().starts_with('{')) {+ Some(p) => {+ i += 1;+ serde_json::from_str(p).map_err(|e| Failure::Usage(format!("{id}: params are not valid JSON: {e}")))?}+ None => json!({}),+ };+ i += 1;+ let r = b.exec(id, params).map_err(|e| Failure::Error(format!("{id}: {e}")))?;+ if !json_out {+ emit(&r, false);}+ results.push(json!({"command": id, "result": r}));+ }+ let saved = maybe_save(&mut b, args)?;+ if json_out {+ emit(&with_saved(json!(results), saved), true);}}- "commands" => {- for c in effectcraft_engine::command_specs() {- println!("{:<36} {:<40} {}", c.id, c.label, c.shortcut.unwrap_or(""));+ "props" => {+ let [comp, layer] = positional::<2>(args, "props <comp> <layer>")?;+ let mut b = backend(args, true)?;+ let a = json!({"comp": reference(&comp), "layer": reference(&layer), "flat": args.flag("--flat") || !json_out, "time": args.num("--time")?, "depth": args.num("--depth")?});+ let v = tool(&mut b, "get_layer", a)?;+ if json_out {+ emit(&v, true);+ } else {+ println!("layer {} \"{}\" ({}) at {} s", v["id"], v["name"].as_str().unwrap_or(""), v["type"].as_str().unwrap_or(""), v["time"]);+ for p in v["properties"].as_array().into_iter().flatten() {+ let mut extra = String::new();+ if let Some(k) = p.get("keys") {+ extra += &format!(" [{k} keys]");+ }+ if let Some(e) = p.get("expression").and_then(Value::as_str) {+ extra += &format!(" expr: {e}");+ }+ println!(" {:<44} {:<8} {}{extra}", p["path"].as_str().unwrap_or(""), p["type"].as_str().unwrap_or(""), p["value"]);+ }+ }+ }+ "get" => {+ let [comp, layer, path] = positional::<3>(args, "get <comp> <layer> <path>")?;+ let mut b = backend(args, true)?;+ let v = tool(&mut b, "get_property", json!({"comp": reference(&comp), "layer": reference(&layer), "path": path, "time": args.num("--time")?}))?;+ emit(&v, json_out);+ }+ "set" => {+ let expr = args.opt("--expression").map(str::to_string);+ let need = if expr.is_some() { 3 } else { 4 };+ if args.pos.len() < need {+ return usage_err("set <comp> <layer> <path> <value> [--time S] [--expression E]");+ }+ let (comp, layer, path) = (args.pos[0].clone(), args.pos[1].clone(), args.pos[2].clone());+ let value = args.pos.get(3).map(|v| value_arg(v));+ let mut b = backend(args, true)?;+ let a =+ json!({"comp": reference(&comp), "layer": reference(&layer), "path": path, "value": value, "time": args.num("--time")?, "expression": expr});+ let v = tool(&mut b, "set_property", a)?;+ let saved = maybe_save(&mut b, args)?;+ emit(&with_saved(v, saved), json_out);+ }+ "render-frame" | "frame" => {+ let mut b = backend(args, true)?;+ let comp = args.opt("--comp").and_then(reference);+ let mut time = args.num("--time")?;+ let mut max_side = args.num("--max-side")?.map(|m| m as u32).unwrap_or(0);+ let needs_info = args.opt("--frame").is_some() || args.opt("--scale").is_some();+ if needs_info {+ let c = tool(&mut b, "get_comp", json!({"comp": comp}))?;+ if let Some(f) = args.num("--frame")? {+ time = Some(f / c["frameRate"].as_f64().unwrap_or(30.0));+ }+ if let Some(k) = args.num("--scale")? {+ let long = c["width"].as_f64().unwrap_or(0.0).max(c["height"].as_f64().unwrap_or(0.0));+ max_side = (long * k).round().max(1.0) as u32;+ }+ }+ let out = args.opt("--out").unwrap_or("frame.png").to_string();+ let t0 = std::time::Instant::now();+ let f = b.render(comp.as_ref(), time, max_side)?;+ let ms = t0.elapsed().as_secs_f64() * 1000.0;+ std::fs::write(&out, &f.png).map_err(|e| format!("cannot write {out}: {e}"))?;+ let info = json!({"path": out, "comp": f.comp, "time": f.time, "width": f.width, "height": f.height, "ms": (ms * 10.0).round() / 10.0});+ if json_out {+ emit(&info, true);+ } else {+ eprintln!("rendered {}x{} at {:.3}s in {ms:.1} ms -> {out}", f.width, f.height, f.time);+ }+ }+ "mcp" => {+ let b = backend(args, false)?;+ McpServer::new(b).serve_stdio().map_err(|e| e.to_string())?;+ }+ other => return usage_err(&format!("unknown subcommand `{other}`")),+ }+ Ok(())+ }++ fn positional<const N: usize>(args: &Args, usage: &str) -> Result<[String; N], Failure> {+ if args.pos.len() < N {+ return usage_err(usage);+ }+ Ok(std::array::from_fn(|i| args.pos[i].clone()))+ }++ fn with_saved(v: Value, saved: Option<String>) -> Value {+ match saved {+ None => v,+ Some(p) => json!({"result": v, "saved": p}),+ }+ }++ /// `render`: queue `--comp` (or the active comp) with the given settings unless `--queue`, then+ /// render the queue with a progress line on stderr. Fails if any item fails.+ fn render(args: &Args, json_out: bool) -> Result<(), Failure> {+ use effectcraft_engine::project::render_queue::RenderStatus;+ if args.opt("--bridge").is_some() {+ return usage_err("render runs headless; use `exec renderQueue.add` / `renderQueue.render` with --bridge");+ }+ let mut s = effectcraft_host::session();+ match &args.project {+ Some(p) => s.execute("file.open", json!({"path": p})).map_err(|e| Failure::Error(e.to_string()))?,+ None => s.execute("file.openDemoProject", json!({})).map_err(|e| Failure::Error(e.to_string()))?,+ };+ let err = |e: effectcraft_engine::EngineError| Failure::Error(e.to_string());+ if !args.flag("--queue") {+ let Some(out) = args.opt("--out") else { return usage_err("render: --out FILE is required (or --queue)") };+ let mut p = json!({"output": out});+ if let Some(c) = args.opt("--comp") {+ p["comp"] = json!(c);+ }+ let ext = std::path::Path::new(out).extension().map(|e| e.to_string_lossy().to_string());+ if let Some(f) = args.opt("--format").map(str::to_string).or(ext) {+ p["format"] = json!(f);+ }+ match (args.num("--start")?, args.num("--end")?) {+ (None, None) => p["timeSpan"] = json!(if args.flag("--work-area") { "workArea" } else { "comp" }),+ (a, b) => {+ p["start"] = json!(a.unwrap_or(0.0));+ if let Some(b) = b {+ p["end"] = json!(b);+ }+ }+ }+ if let Some(v) = args.num("--fps")? {+ p["frameRate"] = json!(v);+ }+ if let Some(r) = args.opt("--resolution").or(args.opt("--scale")) {+ p["resolution"] = r.parse::<f64>().map(|v| json!(v)).unwrap_or(json!(r));+ }+ for (flag, key) in [("--quality", "quality"), ("--channels", "channels"), ("--prores", "proresProfile"), ("--audio", "audio")] {+ if let Some(v) = args.opt(flag) {+ p[key] = json!(v);+ }+ }+ if let Some(v) = args.num("--jpeg-quality")? {+ p["quality"] = json!(v);+ }+ if let Some(v) = args.num("--bitrate")? {+ p["bitrate"] = json!(v);+ }+ // Render exactly this item: unqueue whatever the project's queue already holds.+ for k in 0..s.project.render_queue.len() {+ let _ = s.execute("renderQueue.setRender", json!({"index": k + 1, "render": false}));+ }+ let r = s.execute("renderQueue.add", p).map_err(err)?;+ eprintln!(+ "{} → {} ({}×{}, {} frames, {})",+ r["compName"].as_str().unwrap_or("?"),+ r["outputPath"].as_str().unwrap_or("?"),+ r["width"],+ r["height"],+ r["frames"],+ r["outputModuleSummary"].as_str().unwrap_or("")+ );+ }+ s.execute("renderQueue.render", json!({"wait": false})).map_err(err)?;+ let tty = std::io::IsTerminal::is_terminal(&std::io::stderr());+ while s.is_rendering() {+ std::thread::sleep(std::time::Duration::from_millis(100));+ if tty && let Some(p) = s.render_progress() {+ let left = p.remaining.map(|r| format!(", ~{r:.1}s left")).unwrap_or_default();+ eprint!(+ "+ [{}/{}] frame {}/{} {:.1}s{left}\x1b[K",+ (p.items_done + 1).min(p.items_total),+ p.items_total,+ p.done,+ p.total,+ p.item_elapsed+ );+ }+ s.poll_render();+ }+ s.poll_render();+ if tty {+ eprintln!();+ }+ let mut results = vec![];+ let mut failed = vec![];+ for it in s.project.render_queue.iter().filter(|i| i.render && i.started.is_some()) {+ let name = s.project.item(it.comp).map(|i| i.name.clone()).unwrap_or_else(|| "?".into());+ match &it.status {+ RenderStatus::Done => {+ eprintln!("done: {name} → {} in {:.2}s", it.last_output.as_deref().unwrap_or("?"), it.render_time.unwrap_or(0.0));+ results.push(json!({"comp": name, "output": it.last_output, "seconds": it.render_time}));}+ RenderStatus::Failed(e) => failed.push(format!("{name}: {e}")),+ other => failed.push(format!("{name}: {}", other.label())),}- _ => usage(),}+ if !failed.is_empty() {+ return Err(Failure::Error(failed.join("; ")));+ }+ if json_out {+ emit(&json!({"rendered": results}), true);+ }+ Ok(())+ }++ /// `bench`: time one frame N times without the layer cache (per-layer and per-effect breakdown),+ /// and optionally `--play N` consecutive frames with and without the cache.+ fn bench_cmd(args: &Args) -> Result<(), Failure> {+ let mut s = effectcraft_host::session();+ match &args.project {+ Some(p) => s.execute("file.open", json!({"path": p})),+ None => s.execute("file.openDemoProject", json!({})),+ }+ .map_err(|e| Failure::Error(e.to_string()))?;+ if let Some(c) = args.opt("--comp") {+ s.execute("comp.open", json!({"comp": c})).map_err(|e| Failure::Error(e.to_string()))?;+ }+ let cid = s.active_comp_id().ok_or_else(|| Failure::Error("no composition".into()))?;+ let t = Tick::from_seconds_f64(args.num("--time")?.unwrap_or(3.0));+ let opts = RenderOpts { scale: args.num("--scale")?.unwrap_or(1.0), ..Default::default() };- bench(&s, cid, t, opts.clone(), args.num("--n")?.unwrap_or(10.0).max(1.0) as usize);++ bench(&s, cid, t, opts, args.num("--n")?.unwrap_or(10.0).max(1.0) as usize);+ if let Some(n) = args.num("--play")? {+ bench_play(&s, cid, t, opts, n.max(1.0) as usize);+ }+ Ok(())+ }++ // ---------------------------------------------------------------- benchmark helpers++ use effectcraft_engine::Session;+ use effectcraft_engine::project::ItemId;+ use effectcraft_render::{LayerCache, LayerTiming, RenderOpts, Renderer};+ use effectcraft_time::Tick;++ fn median(v: &mut [f64]) -> f64 {+ v.sort_by(f64::total_cmp);+ if v.is_empty() { 0.0 } else { v[v.len() / 2] }+ }++ fn min(v: &[f64]) -> f64 {+ v.iter().copied().fold(f64::INFINITY, f64::min)+ }++ /// CPU time of the whole process (all threads) in ms: a load-independent measure of work.+ fn cpu_ms() -> f64 {+ cpu_time::ProcessTime::try_now().map(|t| t.as_duration().as_secs_f64() * 1e3).unwrap_or(0.0)+ }++ /// One frame: (wall ms, CPU ms, per-layer timings).+ fn render_timed(s: &Session, cid: ItemId, t: Tick, opts: RenderOpts, cache: Option<&LayerCache>) -> (f64, f64, Vec<LayerTiming>) {+ let prof = std::sync::Mutex::new(Vec::<LayerTiming>::new());+ let mut r = Renderer::new(&s.project, s.footage.as_ref(), opts);+ r.expr = s.expr.as_deref();+ r.cache = cache;+ r.profile = Some(&prof);+ let c0 = cpu_ms();+ let t0 = std::time::Instant::now();+ let img = r.comp_frame(cid, t);+ let ms = t0.elapsed().as_secs_f64() * 1e3;+ let cpu = cpu_ms() - c0;+ std::hint::black_box(&img);+ (ms, cpu, prof.into_inner().unwrap_or_default())+ }++ type LayerRow = (usize, String, Vec<f64>, Vec<f64>, Vec<(String, Vec<f64>)>);++ /// `frame --bench N`: render the same frame N times without the layer cache (the full cost of a+ /// frame) and print min/median frame time plus min per-layer and per-effect times.+ fn bench(s: &Session, cid: ItemId, t: Tick, opts: RenderOpts, n: usize) {+ let mut totals = Vec::with_capacity(n);+ let mut cpus = Vec::with_capacity(n);+ let mut per_layer: Vec<LayerRow> = Vec::new();+ for _ in 0..n {+ let (ms, cpu, prof) = render_timed(s, cid, t, opts, None);+ totals.push(ms);+ cpus.push(cpu);+ for (i, lt) in prof.into_iter().enumerate() {+ if per_layer.len() <= i {+ per_layer.push((lt.depth, lt.layer.clone(), vec![], vec![], vec![]));+ }+ let e = &mut per_layer[i];+ e.2.push(lt.process_ms);+ e.3.push(lt.composite_ms);+ for (j, (id, ms)) in lt.effects.into_iter().enumerate() {+ if e.4.len() <= j {+ e.4.push((id, vec![]));+ }+ e.4[j].1.push(ms);+ }+ }+ }+ eprintln!(+ "bench (no cache): {n} runs at scale {}: wall min {:.2} ms, median {:.2} ms; CPU (all threads) min {:.2} ms",+ opts.scale,+ min(&totals),+ median(&mut totals),+ min(&cpus)+ );+ for (d, name, p, c, fx) in per_layer {+ eprintln!(" {:indent$}{name:<28} process {:8.2} ms composite {:8.2} ms (min)", "", min(&p), min(&c), indent = d * 2);+ for (id, v) in fx {+ eprintln!(" {:indent$} fx {id:<30} {:8.2} ms", "", min(&v), indent = d * 2);+ }+ }+ }++ /// `frame --bench-play N`: render N consecutive frames from `t` as playback does, without and+ /// with the layer cache, and print per-frame times.+ fn bench_play(s: &Session, cid: ItemId, t: Tick, opts: RenderOpts, n: usize) {+ let Some(comp) = s.project.comp(cid) else { return };+ let f0 = comp.frame_rate.frame_at(t);+ let cache = LayerCache::default();+ for (label, c) in [("no cache", None), ("layer cache", Some(&cache))] {+ let runs: Vec<(f64, f64)> = (0..n as i64)+ .map(|i| {+ let (ms, cpu, _) = render_timed(s, cid, comp.frame_rate.tick_of(f0 + i), opts, c);+ (ms, cpu)+ })+ .collect();+ let mut v: Vec<f64> = runs.iter().map(|r| r.0).collect();+ let mean = v.iter().sum::<f64>() / n as f64;+ let cpu = runs.iter().map(|r| r.1).sum::<f64>() / n as f64;+ eprintln!(+ "bench-play ({label}): {n} frames at scale {}: wall mean {mean:.2} ms, median {:.2} ms, min {:.2} ms; CPU mean {cpu:.2} ms",+ opts.scale,+ median(&mut v),+ min(&v)+ );+ }+ let st = cache.stats();+ eprintln!(" layer cache: {} hits, {} misses, {} entries, {:.1} MB", st.hits, st.misses, st.entries, st.bytes as f64 / 1e6);}diff --cc crates/engine/src/commands/layer.rsindex dba27cca9,93542b858..94559f83c--- a/crates/engine/src/commands/layer.rs+++ b/crates/engine/src/commands/layer.rs@@@ -813,42 -873,8 +896,14 @@@ fn transform_op(s: &mut Session, p: &VaOk(Value::Null)}- fn time_stretch(s: &mut Session, p: &Value) -> Result<Value> {- let (cid, ids) = layers_p(s, p)?;- let reverse = str_p(p, "op") == Some("reverse");- let pct = f_p(p, "percent");- s.edit(if reverse { "Time-Reverse Layer" } else { "Time Stretch" }, None, |proj, _| {- let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;- for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id)) {- let old = l.stretch;- let new = if reverse { -old } else { pct.unwrap_or(old) };- if new.abs() < 1.0 {- continue;- }- // Keep the in point fixed: the layer's source span scales around it.- let lin = l.layer_time(l.in_point);- let lout = l.layer_time(l.out_point);- l.stretch = new;- if reverse {- l.start_time = l.in_point + Tick((lout.0 as f64 * new.abs() / 100.0) as i64);- } else {- l.start_time = l.in_point - Tick((lin.0 as f64 * new / 100.0) as i64);- l.out_point = l.comp_time(lout);- }- }- Ok(())- })?;- Ok(Value::Null)- }-fn layer_settings(s: &mut Session, p: &Value) -> Result<Value> {let (cid, lid) = layer_p(s, p, "layer.settings")?;+ // Cameras and lights open their own settings (Camera Settings / Light Settings).+ match s.project.comp(cid).and_then(|c| c.layer(lid)).map(|l| l.source.clone()) {+ Some(LayerSource::Camera) => return s.execute("layer.cameraSettings", with_layer(p, lid)),+ Some(LayerSource::Light { .. }) => return s.execute("layer.lightSettings", with_layer(p, lid)),+ _ => {}+ }let color = color_p(p, "color");let w = p.get("width").and_then(Value::as_u64).map(|v| v as u32);let h = p.get("height").and_then(Value::as_u64).map(|v| v as u32);diff --cc crates/engine/src/commands/mod.rsindex 42b5d1225,5b9c7c879..4abdc7a8e--- a/crates/engine/src/commands/mod.rs+++ b/crates/engine/src/commands/mod.rs@@@ -7,9 -8,12 +8,13 @@@ mod effectmod file;mod help;mod layer;+ mod layer_time;+ mod link;+ mod mask;mod prop;mod query;+ mod render_queue;+mod three_d;mod time;use std::sync::OnceLock;@@@ -69,10 -73,14 +74,15 @@@ pub fn command_specs() -> &'static [Comv.extend(edit::specs());v.extend(comp::specs());v.extend(layer::specs());+ v.extend(three_d::specs());+ v.extend(layer_time::specs());v.extend(prop::specs());+ v.extend(anim::specs());+ v.extend(link::specs());+ v.extend(mask::specs());v.extend(effect::specs());v.extend(time::specs());+ v.extend(render_queue::specs());v.extend(help::specs());v.extend(query::specs());vdiff --cc crates/engine/src/demo.rsindex f356bf59c,64ccb1043..6be2e12bb--- a/crates/engine/src/demo.rs+++ b/crates/engine/src/demo.rs@@@ -12,10 -10,10 +12,11 @@@ use effectcraft_project::{Comp, ItemIduse effectcraft_time::{FrameRate, Tick};pub const MAIN_COMP: &str = "EffectCraft Intro";+pub const SHOWCASE_3D: &str = "3D Showcase";+ /// Seconds → the nearest frame of the demo's 29.97 fps comps (AE keeps times frame-aligned).fn t(s: f64) -> Tick {- Tick::from_seconds_f64(s)+ FrameRate::FPS_29_97.snap_nearest(Tick::from_seconds_f64(s))}fn hex(h: &str) -> [f64; 4] {diff --cc crates/engine/src/lib.rsindex 1f4be7ca5,264866c7e..7dd18722c--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@ -337,7 -405,7 +417,9 @@@ mod rq_tests#[cfg(test)]mod tests;#[cfg(test)]+mod tests_3d;++#[cfg(test)]+ mod tests_timeline;/// Font families available to text layers (bundled + scanned system fonts).pub fn text_families() -> Vec<String> {diff --cc crates/export/src/lib.rsindex 000000000,051183a6f..d87e0858emode 000000,100644..100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@@ -1,0 -1,350 +1,352 @@@+ //! Render Queue jobs: render a composition's time span and write it through an output module.+ //!+ //! | Format | Container / files | Video | Alpha | Audio |+ //! |---|---|---|---|---|+ //! | H.264 | MP4 | FilmCraft H.264 High, 8-bit 4:2:0 BT.709 limited, VBR | no | AAC-LC (FilmCraft), stereo |+ //! | ProRes | QuickTime MOV | FilmCraft ProRes 422 Proxy/LT/422/HQ, 10-bit; 4444/4444 XQ 4:4:4 | 4444 (16-bit alpha coding) | 16-bit PCM, stereo |+ //! | PNG / JPEG / TIFF sequence | one file per frame | 8-bit | PNG, TIFF | — |+ //! | OpenEXR sequence | one file per frame | 32-bit float, linear light, premultiplied | yes | — |+ //! | Animated GIF | GIF89a | 256-colour palette per frame (NeuQuant) | 1-bit | — |+ //!+ //! Frames are rendered in parallel batches (rayon; one batch ≈ one frame per core) and handed to+ //! the encoder in order. Progress is reported after each batch through a callback that can cancel+ //! the job by returning `false`. Codecs and the MP4/MOV muxer are FilmCraft's pure-Rust crates+ //! (plan ADR 0001); nothing outside this crate touches them.+ //!+ //! H.264 requires even dimensions: odd output sizes are cropped by one pixel (padded when the+ //! output is a single pixel wide/high).++ mod encode;++ use std::path::Path;+ use std::time::Instant;++ use effectcraft_project::render_queue::{AudioOutput, Channels, OutputFormat, OutputModule, RenderQuality, RenderSettings, sequence_path};+ use effectcraft_project::{Comp, ItemId, Project};+ use effectcraft_raster::Image;+ use effectcraft_render::{ExprHost, FootageSource, RenderOpts, Renderer};+ use effectcraft_time::Tick;+ use rayon::prelude::*;++ pub use effectcraft_project::render_queue;++ #[derive(Debug, thiserror::Error)]+ pub enum ExportError {+ #[error("composition not found")]+ NoComp,+ #[error("cancelled")]+ Cancelled,+ #[error("i/o: {0}")]+ Io(String),+ #[error("encode: {0}")]+ Encode(String),+ #[error("{0}")]+ Unsupported(String),+ }++ pub type Result<T> = std::result::Result<T, ExportError>;++ fn io(e: impl std::fmt::Display) -> ExportError {+ ExportError::Io(e.to_string())+ }++ /// One export: a comp, its Render Settings and Output Module, and the resolved output path.+ pub struct Job<'a> {+ pub project: &'a Project,+ pub footage: &'a dyn FootageSource,+ pub expr: Option<&'a dyn ExprHost>,+ pub comp: ItemId,+ pub settings: &'a RenderSettings,+ pub output: &'a OutputModule,+ /// Output file. For image sequences a run of `#` (or `[#####]`) becomes the frame number; a+ /// path without one gets `_NNNNN` before the extension.+ pub path: &'a str,+ }++ /// Progress after a batch of frames.+ #[derive(Clone, Copy, Debug, Default)]+ pub struct Progress {+ pub done: u64,+ pub total: u64,+ pub elapsed: f64,+ }++ impl Progress {+ pub fn fraction(&self) -> f64 {+ if self.total == 0 { 0.0 } else { self.done as f64 / self.total as f64 }+ }+ /// Estimated seconds remaining.+ pub fn remaining(&self) -> Option<f64> {+ (self.done > 0).then(|| self.elapsed / self.done as f64 * self.total.saturating_sub(self.done) as f64)+ }+ }++ /// What an export produced.+ #[derive(Clone, Debug, PartialEq)]+ pub struct Report {+ /// The movie file, or the first file of a sequence.+ pub path: String,+ pub frames: u64,+ pub width: u32,+ pub height: u32,+ pub seconds: f64,+ pub bytes: u64,+ pub audio: bool,+ }++ /// Formats this build can write (all of them; kept as the hook for optional encoders).+ pub fn available_formats() -> Vec<OutputFormat> {+ OutputFormat::ALL.to_vec()+ }++ /// The size of the written frames for a job (H.264 rounds to even).+ pub fn output_size(comp: &Comp, settings: &RenderSettings, output: &OutputModule) -> (u32, u32) {+ let (w, h) = settings.output_size(comp);+ output.format.coded_size(w, h)+ }++ /// Whether the job writes an audio track.+ pub fn wants_audio(job: &Job) -> bool {+ job.output.format.supports_audio()+ && match job.output.audio {+ AudioOutput::On => true,+ AudioOutput::Off => false,+ AudioOutput::Auto => effectcraft_render::audio::comp_has_audio(job.project, job.comp),+ }+ }++ /// Run the export (blocking). `progress` is called after every batch; returning `false` cancels.+ pub fn export(job: &Job, progress: &mut dyn FnMut(&Progress) -> bool) -> Result<Report> {+ let comp = job.project.comp(job.comp).ok_or(ExportError::NoComp)?;+ let t0 = Instant::now();+ let total = job.settings.frame_count(comp);+ let mut st = State { t0, total, done: 0, progress };+ st.advance(0)?;+ if let Some(dir) = Path::new(job.path).parent().filter(|d| !d.as_os_str().is_empty()) {+ std::fs::create_dir_all(dir).map_err(io)?;+ }+ let (w, h) = output_size(comp, job.settings, job.output);+ let mut report = match job.output.format {+ OutputFormat::H264 | OutputFormat::ProRes => encode::movie(job, comp, w, h, &mut st)?,+ OutputFormat::Gif => gif_export(job, comp, w, h, &mut st)?,+ f if f.is_sequence() => sequence(job, comp, w, h, &mut st)?,+ f => return Err(ExportError::Unsupported(f.label().into())),+ };+ report.seconds = t0.elapsed().as_secs_f64();+ report.frames = total;+ (report.width, report.height) = (w, h);+ Ok(report)+ }++ pub(crate) struct State<'p> {+ t0: Instant,+ total: u64,+ done: u64,+ progress: &'p mut dyn FnMut(&Progress) -> bool,+ }++ impl State<'_> {+ fn snapshot(&self) -> Progress {+ Progress { done: self.done, total: self.total, elapsed: self.t0.elapsed().as_secs_f64() }+ }+ /// Count `n` more frames; `Err(Cancelled)` when the callback says stop.+ pub(crate) fn advance(&mut self, n: u64) -> Result<()> {+ self.done += n;+ let p = self.snapshot();+ if (self.progress)(&p) { Ok(()) } else { Err(ExportError::Cancelled) }+ }+ }++ /// Frames per parallel batch.+ pub(crate) fn batch_size() -> u64 {+ rayon::current_num_threads().clamp(2, 16) as u64+ }++ /// Render output frame `i` of the job at the settings' resolution.+ pub(crate) fn render_frame(job: &Job, comp: &Comp, i: u64) -> Image {+ let t: Tick = job.settings.frame_time(comp, i);+ let opts = RenderOpts {+ scale: job.settings.resolution.clamp(0.01, 4.0),+ motion_blur: job.settings.motion_blur,+ guides: false,+ draft: job.settings.quality == RenderQuality::Draft,++ // Output renders always look through the comp's active camera.++ view: None,+ };+ let mut r = Renderer::new(job.project, job.footage, opts);+ r.expr = job.expr;+ r.comp_frame(job.comp, t)+ }++ /// 8-bit RGBA of the requested channels (RGB: over the comp background, opaque; RGBA: straight),+ /// cropped/padded to `w`×`h`.+ pub(crate) fn rgba8(img: &Image, comp: &Comp, channels: Channels, w: u32, h: u32) -> Vec<u8> {+ let px = match channels {+ Channels::Rgb => img.to_rgba8_over(comp.background),+ Channels::Rgba => img.to_rgba8(),+ };+ fit(px, img.width, img.height, w, h)+ }++ fn fit(px: Vec<u8>, iw: u32, ih: u32, w: u32, h: u32) -> Vec<u8> {+ if iw == w && ih == h {+ return px;+ }+ let mut out = vec![0u8; (w * h * 4) as usize];+ for y in 0..h.min(ih) as usize {+ let n = w.min(iw) as usize * 4;+ out[y * w as usize * 4..y * w as usize * 4 + n].copy_from_slice(&px[y * iw as usize * 4..y * iw as usize * 4 + n]);+ }+ out+ }++ /// The comp frame number of output frame 0 (sequence numbering follows comp frames, like AE).+ fn first_frame_number(job: &Job, comp: &Comp) -> i64 {+ job.settings.first_frame(comp)+ }++ fn sequence(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {+ let f0 = first_frame_number(job, comp);+ let fmt = job.output.format;+ let channels = if fmt.supports_alpha() { job.output.channels } else { Channels::Rgb };+ let batch = batch_size();+ let mut bytes = 0u64;+ let mut i = 0;+ while i < st.total {+ let end = (i + batch).min(st.total);+ let written: Vec<Result<u64>> = (i..end)+ .into_par_iter()+ .map(|k| {+ let path = sequence_path(job.path, f0 + k as i64);+ if job.settings.skip_existing && Path::new(&path).exists() {+ return Ok(0);+ }+ let img = render_frame(job, comp, k);+ write_still(&path, fmt, &img, comp, channels, w, h, job.output.quality)?;+ Ok(std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0))+ })+ .collect();+ for r in written {+ bytes += r?;+ }+ st.advance(end - i)?;+ i = end;+ }+ Ok(Report { path: sequence_path(job.path, f0), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false })+ }++ #[allow(clippy::too_many_arguments)]+ fn write_still(path: &str, fmt: OutputFormat, img: &Image, comp: &Comp, channels: Channels, w: u32, h: u32, quality: u8) -> Result<()> {+ use image::{ExtendedColorType, ImageEncoder, ImageFormat};+ let file = || std::fs::File::create(path).map(std::io::BufWriter::new).map_err(io);+ match fmt {+ OutputFormat::ExrSequence => {+ // Linear light, premultiplied (the EXR convention); RGB keeps alpha = 1 over the background.+ let lin = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };+ let mut data = Vec::with_capacity((w * h * 4) as usize);+ for y in 0..h {+ for x in 0..w {+ let p = if x < img.width && y < img.height { img.data[img.idx(x, y)] } else { [0.0; 4] };+ let (c, a) = match channels {+ Channels::Rgba => {+ let a = p[3].clamp(0.0, 1.0);+ let s = |c: f32| if a > 0.0 { lin((c / a).clamp(0.0, 1.0)) * a } else { 0.0 };+ ([s(p[0]), s(p[1]), s(p[2])], a)+ }+ Channels::Rgb => {+ let k = 1.0 - p[3].clamp(0.0, 1.0);+ let c = |i: usize| lin((p[i] + comp.background[i] * k).clamp(0.0, 1.0));+ ([c(0), c(1), c(2)], 1.0)+ }+ };+ data.extend_from_slice(&[c[0], c[1], c[2], a]);+ }+ }+ let buf = image::Rgba32FImage::from_raw(w, h, data).ok_or_else(|| ExportError::Encode("exr buffer".into()))?;+ image::DynamicImage::ImageRgba32F(buf).save_with_format(path, ImageFormat::OpenExr).map_err(|e| ExportError::Encode(e.to_string()))+ }+ OutputFormat::JpegSequence => {+ let px = rgba8(img, comp, Channels::Rgb, w, h);+ let rgb: Vec<u8> = px.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect();+ image::codecs::jpeg::JpegEncoder::new_with_quality(file()?, quality.clamp(1, 100))+ .write_image(&rgb, w, h, ExtendedColorType::Rgb8)+ .map_err(|e| ExportError::Encode(e.to_string()))+ }+ OutputFormat::PngSequence | OutputFormat::TiffSequence => {+ let px = rgba8(img, comp, channels, w, h);+ let (data, ct) = match channels {+ Channels::Rgba => (px, ExtendedColorType::Rgba8),+ Channels::Rgb => (px.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect(), ExtendedColorType::Rgb8),+ };+ if fmt == OutputFormat::PngSequence {+ image::codecs::png::PngEncoder::new(file()?).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))+ } else {+ // The TIFF encoder needs Seek.+ let f = std::fs::File::create(path).map_err(io)?;+ image::codecs::tiff::TiffEncoder::new(std::io::BufWriter::new(f)).write_image(&data, w, h, ct).map_err(|e| ExportError::Encode(e.to_string()))+ }+ }+ f => Err(ExportError::Unsupported(format!("{} is not a still format", f.label()))),+ }+ }++ fn gif_export(job: &Job, comp: &Comp, w: u32, h: u32, st: &mut State) -> Result<Report> {+ if w > u16::MAX as u32 || h > u16::MAX as u32 {+ return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into()));+ }+ let file = std::fs::File::create(job.path).map_err(io)?;+ let mut enc = gif::Encoder::new(std::io::BufWriter::new(file), w as u16, h as u16, &[]).map_err(|e| ExportError::Encode(e.to_string()))?;+ enc.set_repeat(if job.output.gif_loop { gif::Repeat::Infinite } else { gif::Repeat::Finite(0) }).map_err(|e| ExportError::Encode(e.to_string()))?;+ let rate = job.settings.rate(comp);+ // GIF delays are in 1/100 s: carry the rounding error so long animations keep their timing.+ let cs_per_frame = 100.0 * rate.den as f64 / rate.num as f64;+ let mut clock = 0.0f64;+ let mut emitted = 0u64;+ let batch = batch_size();+ let mut i = 0;+ while i < st.total {+ let end = (i + batch).min(st.total);+ let frames: Vec<gif::Frame<'static>> = (i..end)+ .into_par_iter()+ .map(|k| {+ let img = render_frame(job, comp, k);+ let mut px = rgba8(&img, comp, job.output.channels, w, h);+ gif::Frame::from_rgba_speed(w as u16, h as u16, &mut px, 10)+ })+ .collect();+ for mut f in frames {+ clock += cs_per_frame;+ let d = (clock.round() as u64).saturating_sub(emitted).max(1);+ emitted += d;+ f.delay = d.min(u16::MAX as u64) as u16;+ if job.output.channels == Channels::Rgba {+ f.dispose = gif::DisposalMethod::Background;+ }+ enc.write_frame(&f).map_err(|e| ExportError::Encode(e.to_string()))?;+ }+ st.advance(end - i)?;+ i = end;+ }+ drop(enc);+ let bytes = std::fs::metadata(job.path).map(|m| m.len()).unwrap_or(0);+ Ok(Report { path: job.path.to_string(), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false })+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn fit_crops_and_pads() {+ let px: Vec<u8> = (0..3 * 3 * 4).map(|v| v as u8).collect();+ let c = fit(px.clone(), 3, 3, 2, 2);+ assert_eq!(c.len(), 16);+ assert_eq!(&c[0..8], &px[0..8]);+ assert_eq!(&c[8..16], &px[12..20]);+ let p = fit(px, 3, 3, 4, 4);+ assert_eq!(p.len(), 64);+ assert_eq!(&p[12..16], &[0, 0, 0, 0]);+ assert_eq!(OutputFormat::H264.coded_size(1, 101), (2, 100));+ assert_eq!(OutputFormat::Gif.coded_size(1, 101), (1, 101));+ }+ }diff --cc crates/render/src/eval.rsindex 4e158dc55,547e2e0ab..7271d36ac--- a/crates/render/src/eval.rs+++ b/crates/render/src/eval.rs@@@ -71,11 -96,10 +96,11 @@@ impl<'a> EvalCtx<'a>pub fn local_matrix(&self, layer: &Layer) -> Mat4 {let Some(tr) = layer.transform() else { return Mat4::IDENTITY };let three = layer.is_3d();- let pos = self.v3(layer, tr, "position", [0.0; 3]);+ let pos = self.position(layer, tr);let rz = self.f(layer, tr, "rotation", 0.0);if layer.is_camera() || layer.is_light() {- return Mat4::translate(Vec3::from(pos)) * Mat4::rotate_z(rz);+ // Children of cameras/lights follow their position and full rotation.+ return Mat4::translate(Vec3::from(pos)) * crate::three_d::camera::rig_rotation(self, layer);}let anchor = self.v3(layer, tr, "anchor", [0.0; 3]);let mut scale = self.v3(layer, tr, "scale", [100.0; 3]);diff --cc crates/render/src/three_d/camera.rsindex 95c45d986,000000000..fb307b8c2mode 100644,000000..100644--- a/crates/render/src/three_d/camera.rs+++ b/crates/render/src/three_d/camera.rs@@@ -1,509 -1,0 +1,510 @@@+//! Cameras: the comp's active camera (camera layers or the default 50 mm comp camera), the 3D+//! views of the viewer (Front/Left/Top/Back/Right/Bottom orthographic views and three custom+//! perspective views) and the camera-tool math (orbit, pan, dolly) shared by the engine commands.+//!+//! Conventions: world space is comp space (x right, y down, z into the screen). Camera space has+//! x right, y down and z forward (depth). The perspective projection maps camera space to comp+//! pixels as `x' = zoom·x/z + w/2`; orthographic views use `x' = zoom·x + w/2`.++use std::collections::BTreeMap;++use effectcraft_geom::{Mat4, Vec2, Vec3, vec2, vec3};+use effectcraft_project::{AutoOrient, Layer};+use serde::{Deserialize, Serialize};++use crate::EvalCtx;++/// Closest a perspective camera renders (camera-space z, pixels).+pub const NEAR: f64 = 1.0;++/// Depth of field settings of a camera.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct Dof {+ /// Distance from the eye to the plane in focus (pixels).+ pub focus: f64,+ /// Aperture diameter (pixels).+ pub aperture: f64,+ /// Blur Level (1.0 = 100%).+ pub blur_level: f64,+}++impl Dof {+ /// Circle-of-confusion diameter (comp pixels) for a point at camera depth `z`.+ pub fn coc(&self, z: f64) -> f64 {+ if z <= NEAR || self.focus <= 0.0 {+ return 0.0;+ }+ self.aperture * (z - self.focus).abs() / z * self.blur_level+ }+}++/// An evaluated camera.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct CameraState {+ /// World → camera space (rigid).+ pub view: Mat4,+ /// Eye position in world space.+ pub eye: Vec3,+ /// Perspective: distance from the eye to the image plane (pixels). Orthographic: pixels per+ /// world unit.+ pub zoom: f64,+ pub ortho: bool,+ pub dof: Option<Dof>,+}++impl CameraState {+ /// World → comp pixels (homogeneous: divide by `w` for perspective cameras).+ pub fn projection(&self, comp_w: f64, comp_h: f64) -> Mat4 {+ if self.ortho {+ let z = self.zoom;+ Mat4([[z, 0.0, 0.0, comp_w * 0.5], [0.0, z, 0.0, comp_h * 0.5], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) * self.view+ } else {+ effectcraft_geom::camera_matrix(comp_w, comp_h, self.eye, self.view, self.zoom)+ }+ }+ /// Camera-space depth of a world point.+ pub fn depth(&self, p: Vec3) -> f64 {+ self.view.apply(p).z+ }+ /// Unit view direction (world).+ pub fn forward(&self) -> Vec3 {+ let m = &self.view.0;+ vec3(m[2][0], m[2][1], m[2][2])+ }+ pub fn right(&self) -> Vec3 {+ let m = &self.view.0;+ vec3(m[0][0], m[0][1], m[0][2])+ }+ pub fn down(&self) -> Vec3 {+ let m = &self.view.0;+ vec3(m[1][0], m[1][1], m[1][2])+ }+ /// Project a world point to comp pixels; None when behind a perspective camera.+ pub fn project(&self, comp_w: f64, comp_h: f64, p: Vec3) -> Option<Vec2> {+ let c = self.view.apply(p);+ if self.ortho {+ return Some(vec2(self.zoom * c.x + comp_w * 0.5, self.zoom * c.y + comp_h * 0.5));+ }+ if c.z < NEAR {+ return None;+ }+ Some(vec2(self.zoom * c.x / c.z + comp_w * 0.5, self.zoom * c.y / c.z + comp_h * 0.5))+ }+ /// Direction from a shaded point towards the viewer.+ pub fn to_viewer(&self, p: Vec3) -> Vec3 {+ if self.ortho { -self.forward() } else { (self.eye - p).normalize() }+ }+}++/// View matrix from an eye, a forward direction and a screen-down hint.+pub fn basis_view(eye: Vec3, forward: Vec3, down_hint: Vec3) -> Mat4 {+ let f = forward.normalize();+ let f = if f.length() == 0.0 { vec3(0.0, 0.0, 1.0) } else { f };+ let mut d = down_hint - f * down_hint.dot(f);+ if d.length() < 1e-9 {+ d = if f.y.abs() < 0.99 { vec3(0.0, 1.0, 0.0) } else { vec3(0.0, 0.0, -1.0) };+ d = d - f * d.dot(f);+ }+ let d = d.normalize();+ let r = d.cross(f).normalize();+ Mat4([[r.x, r.y, r.z, 0.0], [d.x, d.y, d.z, 0.0], [f.x, f.y, f.z, 0.0], [0.0, 0.0, 0.0, 1.0]]) * Mat4::translate(-eye)+}++/// Orientation angles (degrees, AE order X→Y→Z with Z = 0) that point +z along `dir`.+pub fn orientation_for(dir: Vec3) -> [f64; 3] {+ let d = dir.normalize();+ let x = (-d.y).clamp(-1.0, 1.0).asin().to_degrees();+ let y = d.x.atan2(d.z).to_degrees();+ [norm360(x), norm360(y), 0.0]+}++fn norm360(a: f64) -> f64 {+ let r = a.rem_euclid(360.0);+ if (r - 360.0).abs() < 1e-9 { 0.0 } else { r }+}++/// AE's camera presets (35 mm film width 36 mm): (name, focal length mm).+pub const PRESETS: [(&str, f64); 9] =+ [("15mm", 15.0), ("20mm", 20.0), ("24mm", 24.0), ("28mm", 28.0), ("35mm", 35.0), ("50mm", 50.0), ("80mm", 80.0), ("135mm", 135.0), ("200mm", 200.0)];++/// Film width the presets assume (mm, measured horizontally).+pub const FILM_SIZE_MM: f64 = 36.0;++/// Zoom (pixels) for a focal length on a comp `comp_w` pixels wide.+pub fn zoom_for_focal(comp_w: f64, focal_mm: f64) -> f64 {+ comp_w * focal_mm / FILM_SIZE_MM+}++/// Focal length (mm) of a zoom value.+pub fn focal_for_zoom(comp_w: f64, zoom: f64) -> f64 {+ zoom * FILM_SIZE_MM / comp_w.max(1.0)+}++/// Horizontal angle of view (degrees) of a zoom value.+pub fn angle_of_view(comp_w: f64, zoom: f64) -> f64 {+ 2.0 * (comp_w * 0.5 / zoom.max(1e-9)).atan().to_degrees()+}++/// Default aperture (pixels) of the presets: 25.3 mm at a 1920-pixel-wide comp, proportional.+pub fn default_aperture(comp_w: f64) -> f64 {+ 25.3 * comp_w / 1920.0+}++/// The comp camera used when there is no camera layer: the 50 mm preset at (w/2, h/2, −zoom)+/// looking at the comp centre, which shows the z = 0 plane at 100%.+pub fn default_camera(comp_w: f64, comp_h: f64) -> CameraState {+ let zoom = effectcraft_geom::default_camera_zoom(comp_w);+ let eye = vec3(comp_w / 2.0, comp_h / 2.0, -zoom);+ CameraState { view: basis_view(eye, vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0)), eye, zoom, ortho: false, dof: None }+}++/// Whether a camera layer is two-node (auto-orients towards its Point of Interest).+pub fn is_two_node(layer: &Layer) -> bool {+ layer.auto_orient == AutoOrient::TowardsPointOfInterest && layer.transform().is_some_and(|t| t.get("poi").is_some())+}++/// Rotation of a camera/light layer from its Orientation and X/Y/Z Rotation (layer → parent).+pub fn layer_rotation(ctx: &EvalCtx, layer: &Layer) -> Mat4 {+ let Some(tr) = layer.transform() else { return Mat4::IDENTITY };+ let o = ctx.v3(layer, tr, "orientation", [0.0; 3]);+ let rx = ctx.f(layer, tr, "rotationX", 0.0);+ let ry = ctx.f(layer, tr, "rotationY", 0.0);+ let rz = ctx.f(layer, tr, "rotation", 0.0);+ Mat4::orientation(Vec3::from(o)) * Mat4::rotate_z(rz) * Mat4::rotate_y(ry) * Mat4::rotate_x(rx)+}++/// World matrix of a layer's parent chain (identity when unparented).+pub fn parent_world(ctx: &EvalCtx, layer: &Layer) -> Mat4 {+ match layer.parent.and_then(|p| ctx.comp.layer(p)) {+ Some(p) => ctx.world_matrix(p),+ None => Mat4::IDENTITY,+ }+}++/// Rotation (local → parent) of a frame whose +z is `fwd` and whose +y is as close to+/// `down_hint` as possible.+pub fn basis_rotation(fwd: Vec3, down_hint: Vec3) -> Mat4 {+ let m = basis_view(Vec3::ZERO, fwd, down_hint).0;+ Mat4([[m[0][0], m[1][0], m[2][0], 0.0], [m[0][1], m[1][1], m[2][1], 0.0], [m[0][2], m[1][2], m[2][2], 0.0], [0.0, 0.0, 0.0, 1.0]])+}++/// Local rotation (layer → parent) of a camera or light: auto-orient towards the Point of+/// Interest (two-node), then Orientation and X/Y/Z Rotation.+pub fn rig_rotation(ctx: &EvalCtx, layer: &Layer) -> Mat4 {+ let rot = layer_rotation(ctx, layer);+ match layer.transform().filter(|_| is_two_node(layer)) {+ Some(tr) => {+ let (w, h) = (ctx.comp.width as f64, ctx.comp.height as f64);+ let pos = Vec3::from(ctx.v3(layer, tr, "position", [w / 2.0, h / 2.0, -1000.0]));+ let poi = Vec3::from(ctx.v3(layer, tr, "poi", [w / 2.0, h / 2.0, 0.0]));+ basis_rotation(poi - pos, vec3(0.0, 1.0, 0.0)) * rot+ }+ None => rot,+ }+}++// ---------------------------------------------------------------- auto-orient++/// Direction of travel of a layer's position (parent space) at the context time.+fn path_tangent(ctx: &EvalCtx, layer: &Layer) -> Option<Vec3> {+ let tr = layer.transform()?;- let p = tr.get("position")?;- if p.keys.len() < 2 && !p.has_expression() {++ // Position (or its separated X/Y/Z dimensions) must be animated.++ let moving = ["position", "positionX", "positionY", "positionZ"].iter().any(|m| tr.get(m).is_some_and(|p| p.keys.len() > 1 || p.has_expression()));++ if !moving {+ return None;+ }+ let dt = effectcraft_time::Tick::from_seconds_f64(0.005);+ let a = Vec3::from(ctx.at(ctx.time - dt).v3(layer, tr, "position", [0.0; 3]));+ let b = Vec3::from(ctx.at(ctx.time + dt).v3(layer, tr, "position", [0.0; 3]));+ let d = b - a;+ (d.length() > 1e-9).then(|| d.normalize())+}++/// Auto-Orient ▸ Orient Along Path for 2D layers: extra Z rotation in degrees.+pub fn auto_orient_2d(ctx: &EvalCtx, layer: &Layer) -> f64 {+ if layer.auto_orient != AutoOrient::AlongPath {+ return 0.0;+ }+ path_tangent(ctx, layer).map(|t| t.y.atan2(t.x).to_degrees()).unwrap_or(0.0)+}++/// Whether `id` is `layer` or one of its parents.+fn in_parent_chain(ctx: &EvalCtx, layer: &Layer, id: effectcraft_project::LayerId) -> bool {+ let mut cur = Some(layer);+ let mut guard = 0;+ while let Some(l) = cur {+ if l.id == id || guard > 64 {+ return true;+ }+ guard += 1;+ cur = l.parent.and_then(|p| ctx.comp.layer(p));+ }+ false+}++/// Auto-orient for 3D layers: the rotation that replaces Orientation (Along Path: the layer's x+/// axis follows the motion path; Towards Camera: the layer faces the active camera).+pub fn auto_orient_3d(ctx: &EvalCtx, layer: &Layer, pos: Vec3) -> Option<Mat4> {+ match layer.auto_orient {+ AutoOrient::AlongPath => {+ let t = path_tangent(ctx, layer)?;+ // x = tangent, y ≈ down, z = x × y.+ let mut y = vec3(0.0, 1.0, 0.0) - t * t.y;+ if y.length() < 1e-9 {+ y = vec3(0.0, 0.0, 1.0) - t * t.z;+ }+ let y = y.normalize();+ let z = t.cross(y);+ Some(Mat4([[t.x, y.x, z.x, 0.0], [t.y, y.y, z.y, 0.0], [t.z, y.z, z.z, 0.0], [0.0, 0.0, 0.0, 1.0]]))+ }+ AutoOrient::TowardsCamera => {+ // A camera parented (through any chain) to this layer would recurse.+ if ctx.comp.active_camera(ctx.time).is_some_and(|c| in_parent_chain(ctx, c, layer.id)) {+ return None;+ }+ let eye = active_camera(ctx).eye;+ let e = parent_world(ctx, layer).inverse().unwrap_or(Mat4::IDENTITY).apply(eye);+ let d = pos - e;+ (d.length() > 1e-9).then(|| basis_rotation(d, vec3(0.0, 1.0, 0.0)))+ }+ _ => None,+ }+}++/// (eye, forward, down) in world space of a camera or light layer.+pub fn layer_frame(ctx: &EvalCtx, layer: &Layer) -> (Vec3, Vec3, Vec3) {+ let (w, h) = (ctx.comp.width as f64, ctx.comp.height as f64);+ let Some(tr) = layer.transform() else { return (vec3(w / 2.0, h / 2.0, -1000.0), vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0)) };+ let parent = parent_world(ctx, layer);+ let pos = Vec3::from(ctx.v3(layer, tr, "position", [w / 2.0, h / 2.0, -1000.0]));+ let local = rig_rotation(ctx, layer);+ let eye = parent.apply(pos);+ let fwd = parent.apply_vec(local.apply_vec(vec3(0.0, 0.0, 1.0))).normalize();+ let down = parent.apply_vec(local.apply_vec(vec3(0.0, 1.0, 0.0))).normalize();+ (eye, fwd, down)+}++/// Evaluate a camera layer.+pub fn layer_camera(ctx: &EvalCtx, cam: &Layer) -> CameraState {+ let w = ctx.comp.width as f64;+ let (eye, fwd, down) = layer_frame(ctx, cam);+ let opts = cam.props.sub("cameraOptions");+ let zoom = opts.map(|g| ctx.f(cam, g, "zoom", 1000.0)).unwrap_or(1000.0).max(1e-3);+ let dof = opts.filter(|g| ctx.b(cam, g, "dof")).map(|g| Dof {+ focus: ctx.f(cam, g, "focusDistance", zoom),+ aperture: ctx.f(cam, g, "aperture", default_aperture(w)).max(0.0),+ blur_level: ctx.f(cam, g, "blurLevel", 100.0).max(0.0) / 100.0,+ });+ CameraState { view: basis_view(eye, fwd, down), eye, zoom, ortho: false, dof }+}++/// The comp's active camera at the context time (topmost active camera layer, else the default).+pub fn active_camera(ctx: &EvalCtx) -> CameraState {+ match ctx.comp.active_camera(ctx.time) {+ Some(cam) => layer_camera(ctx, cam),+ None => default_camera(ctx.comp.width as f64, ctx.comp.height as f64),+ }+}++// ---------------------------------------------------------------- 3D views++/// The viewer's 3D views (View ▸ Switch 3D View).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]+pub enum View3D {+ #[default]+ ActiveCamera,+ Front,+ Left,+ Top,+ Back,+ Right,+ Bottom,+ Custom1,+ Custom2,+ Custom3,+}++impl View3D {+ pub const ALL: [View3D; 10] = [+ View3D::ActiveCamera,+ View3D::Front,+ View3D::Left,+ View3D::Top,+ View3D::Back,+ View3D::Right,+ View3D::Bottom,+ View3D::Custom1,+ View3D::Custom2,+ View3D::Custom3,+ ];+ pub fn label(self) -> &'static str {+ match self {+ View3D::ActiveCamera => "Active Camera",+ View3D::Front => "Front",+ View3D::Left => "Left",+ View3D::Top => "Top",+ View3D::Back => "Back",+ View3D::Right => "Right",+ View3D::Bottom => "Bottom",+ View3D::Custom1 => "Custom View 1",+ View3D::Custom2 => "Custom View 2",+ View3D::Custom3 => "Custom View 3",+ }+ }+ /// Stable id used by commands (`activeCamera`, `front`, `custom1`…).+ pub fn id(self) -> &'static str {+ match self {+ View3D::ActiveCamera => "activeCamera",+ View3D::Front => "front",+ View3D::Left => "left",+ View3D::Top => "top",+ View3D::Back => "back",+ View3D::Right => "right",+ View3D::Bottom => "bottom",+ View3D::Custom1 => "custom1",+ View3D::Custom2 => "custom2",+ View3D::Custom3 => "custom3",+ }+ }+ pub fn from_id(s: &str) -> Option<View3D> {+ let k: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();+ View3D::ALL.into_iter().find(|v| v.id().eq_ignore_ascii_case(&k) || v.label().replace(' ', "").eq_ignore_ascii_case(&k))+ }+ pub fn is_ortho(self) -> bool {+ matches!(self, View3D::Front | View3D::Left | View3D::Top | View3D::Back | View3D::Right | View3D::Bottom)+ }+}++/// A view camera: eye, point of interest, screen-down hint, zoom (perspective) or scale (ortho).+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct ViewCam {+ pub eye: [f64; 3],+ pub poi: [f64; 3],+ pub down: [f64; 3],+ pub zoom: f64,+ pub ortho: bool,+}++impl ViewCam {+ pub fn state(&self) -> CameraState {+ let eye = Vec3::from(self.eye);+ let poi = Vec3::from(self.poi);+ CameraState { view: basis_view(eye, poi - eye, Vec3::from(self.down)), eye, zoom: self.zoom, ortho: self.ortho, dof: None }+ }+}++/// Default camera of a view for a `w`×`h` comp.+pub fn default_view_cam(v: View3D, w: f64, h: f64) -> ViewCam {+ let c = vec3(w / 2.0, h / 2.0, 0.0);+ let zoom = effectcraft_geom::default_camera_zoom(w);+ let far = 10_000.0;+ let ortho = |fwd: Vec3, down: Vec3| ViewCam { eye: arr(c - fwd * far), poi: arr(c), down: arr(down), zoom: 0.5, ortho: true };+ let custom = |yaw: f64, pitch: f64| {+ // Orbit the default camera around the comp centre (yaw about y, then pitch).+ let off = Mat4::rotate_y(yaw).apply_vec(Mat4::rotate_x(pitch).apply_vec(vec3(0.0, 0.0, -zoom * 1.6)));+ ViewCam { eye: arr(c + off), poi: arr(c), down: [0.0, 1.0, 0.0], zoom, ortho: false }+ };+ match v {+ View3D::ActiveCamera | View3D::Front => ortho(vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0)),+ View3D::Back => ortho(vec3(0.0, 0.0, -1.0), vec3(0.0, 1.0, 0.0)),+ View3D::Left => ortho(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0)),+ View3D::Right => ortho(vec3(-1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0)),+ View3D::Top => ortho(vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, -1.0)),+ View3D::Bottom => ortho(vec3(0.0, -1.0, 0.0), vec3(0.0, 0.0, 1.0)),+ // Custom views look down at the comp from above-left, above and above-right.+ View3D::Custom1 => custom(30.0, -20.0),+ View3D::Custom2 => custom(0.0, -35.0),+ View3D::Custom3 => custom(-30.0, -20.0),+ }+}++pub fn arr(v: Vec3) -> [f64; 3] {+ [v.x, v.y, v.z]+}++/// Per-comp 3D view state of the viewer (current view + edited view cameras).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct Views3D {+ pub current: View3D,+ /// The view before the last switch (View ▸ Switch to Last 3D View).+ #[serde(default)]+ pub last: View3D,+ /// Edited view cameras (views not present use their defaults).+ #[serde(default)]+ pub cams: BTreeMap<View3D, ViewCam>,+}++impl Views3D {+ pub fn cam(&self, v: View3D, w: f64, h: f64) -> ViewCam {+ self.cams.get(&v).copied().unwrap_or_else(|| default_view_cam(v, w, h))+ }+ /// Camera override for rendering: None for the active camera view.+ pub fn override_camera(&self, w: f64, h: f64) -> Option<CameraState> {+ (self.current != View3D::ActiveCamera).then(|| self.cam(self.current, w, h).state())+ }+}++// ---------------------------------------------------------------- camera tools++/// A camera as edited by the tools: position, point of interest, zoom (two-node form).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Rig {+ pub eye: Vec3,+ pub poi: Vec3,+ pub zoom: f64,+ pub ortho: bool,+}++impl Rig {+ pub fn from_view(v: &ViewCam) -> Rig {+ Rig { eye: Vec3::from(v.eye), poi: Vec3::from(v.poi), zoom: v.zoom, ortho: v.ortho }+ }+ fn frame(&self) -> (Vec3, Vec3, Vec3) {+ let s =+ CameraState { view: basis_view(self.eye, self.poi - self.eye, vec3(0.0, 1.0, 0.0)), eye: self.eye, zoom: self.zoom, ortho: self.ortho, dof: None };+ (s.forward(), s.right(), s.down())+ }+ /// Orbit the eye around the point of interest: `yaw` about world Y, `pitch` about the+ /// camera's right axis (degrees). Pitch is limited short of straight up/down.+ pub fn orbit(&mut self, yaw: f64, pitch: f64) {+ if self.ortho {+ return;+ }+ let off = self.eye - self.poi;+ let dist = off.length().max(1e-6);+ let cur_pitch = (off.y / dist).clamp(-1.0, 1.0).asin().to_degrees();+ let new_pitch = (cur_pitch + pitch).clamp(-89.0, 89.0);+ let horiz = vec3(off.x, 0.0, off.z);+ let hl = horiz.length();+ let az = if hl > 1e-9 { off.x.atan2(-off.z).to_degrees() } else { 0.0 } + yaw;+ let (sp, cp) = new_pitch.to_radians().sin_cos();+ let (sa, ca) = az.to_radians().sin_cos();+ self.eye = self.poi + vec3(sa * cp, sp, -ca * cp) * dist;+ }+ /// Pan in the image plane by (`dx`, `dy`) comp pixels (as seen at the point of interest).+ pub fn pan(&mut self, dx: f64, dy: f64) {+ let (_, r, d) = self.frame();+ let k = if self.ortho { 1.0 / self.zoom.max(1e-9) } else { (self.poi - self.eye).length() / self.zoom.max(1e-9) };+ let delta = r * (-dx * k) + d * (-dy * k);+ self.eye += delta;+ self.poi += delta;+ }+ /// Dolly along the view direction by `amount` pixels (positive = towards the POI). With+ /// `with_poi` the point of interest travels too (camera layers: Track Z); otherwise the+ /// eye stops short of the POI. Orthographic views scale instead.+ pub fn dolly(&mut self, amount: f64, with_poi: bool) {+ if self.ortho {+ self.zoom = (self.zoom * (amount / 500.0).exp()).clamp(0.01, 100.0);+ return;+ }+ let (f, _, _) = self.frame();+ if with_poi {+ self.eye += f * amount;+ self.poi += f * amount;+ } else {+ let dist = (self.poi - self.eye).length();+ let d = amount.min(dist - 1.0);+ self.eye += f * d;+ }+ }+}diff --cc crates/render/src/three_d/compose.rsindex 0d00d6694,000000000..388dab744mode 100644,000000..100644--- a/crates/render/src/three_d/compose.rs+++ b/crates/render/src/three_d/compose.rs@@@ -1,488 -1,0 +1,494 @@@+//! The Classic 3D compositor for a run of consecutive 3D layers.+//!+//! Each layer is a textured plane: its processed buffer (source → masks → effects, DOF-blurred)+//! mapped through `projection · world`. Rendering is per output pixel (rows in parallel): every+//! plane covering the pixel is inverse-mapped through its homography (exact perspective-correct+//! texture coordinates, bilinear/bicubic sampling), its camera depth taken from the plane+//! equation, and the fragment shaded by the comp's lights. The pixel's fragments are then sorted+//! far→near (coplanar fragments keep layer-stack order) and blended with each layer's mode and+//! opacity. Sorting per pixel handles intersecting layers exactly, and blend modes and partial+//! transparency still compose in depth order, as in AE's Classic 3D renderer.+//!+//! Shadows are ray-cast against the shadow-casting planes (exact for planar layers, including+//! alpha-shaped and coloured shadows through Light Transmission); Shadow Diffusion softens them+//! with a penumbra that grows with the distance between caster and receiver.+++use std::sync::Arc;+++use effectcraft_color::{BlendMode, blend_pixel};+use effectcraft_effects::Buf;+use effectcraft_geom::{Mat3, Mat4, Vec3, vec3};+use effectcraft_project::{Layer, LightKind, MatteKind};+use effectcraft_raster::{Image, Px, hash_noise};+use effectcraft_time::Tick;+use rayon::prelude::*;++use super::camera::{CameraState, NEAR, active_camera};+use super::light::{LightState, Material, lights_at, shade};+use crate::{EvalCtx, Renderer};++/// One position of a plane (several with motion blur).+#[derive(Clone, Copy, Debug)]+pub(crate) struct Geo {+ /// Output pixel → homogeneous layer coordinates.+ hinv: Mat3,+ /// Camera-space depth as a function of layer (u, v): `d0·u + d1·v + d2`.+ depth: [f64; 3],+ world: Mat4,+ normal: Vec3,+ /// Output pixel bounds [x0, y0, x1, y1) covered by the plane.+ bbox: [i64; 4],+ cam: CameraState,+}++/// A prepared 3D layer.+pub(crate) struct Item<'a> {+ pub layer: &'a Layer,+ /// Position in the layer stack (higher = above).+ order: usize,- buf: Buf,++ buf: Arc<Buf>,+ bicubic: bool,+ geos: Vec<Geo>,+ mat: Material,+ opacity: f32,+ /// Drawn (false for "Casts Shadows: Only" and shadow-only casters outside the run).+ draw: bool,+ /// Screen-space track matte factor (output size).+ matte: Option<Vec<f32>>,+ preserve: bool,+ /// World → layer (for shadow rays) and the buffer's layer-space bounds.+ winv: Mat4,+ bounds: [f64; 4],+ bbox: [i64; 4],+}++impl Item<'_> {+ #[inline]+ fn texel(&self, u: f64, v: f64) -> Px {+ let x = u * self.buf.scale + self.buf.offset[0];+ let y = v * self.buf.scale + self.buf.offset[1];+ if self.bicubic { self.buf.img.sample_bicubic(x, y) } else { self.buf.img.sample_bilinear(x, y) }+ }+}++/// Build the plane geometry of a layer for a camera.+fn geo(cam: &CameraState, world: Mat4, buf: &Buf, comp: (f64, f64), scale: f64, out: (u32, u32)) -> Option<Geo> {+ let proj = Mat4::scale(vec3(scale, scale, 1.0)) * cam.projection(comp.0, comp.1);+ let full = proj * world;+ let h = full.plane_to_mat3();+ let hinv = h.inverse()?;+ let cv = cam.view * world;+ let depth = [cv.0[2][0], cv.0[2][1], cv.0[2][3]];+ let normal = world.apply_vec(vec3(1.0, 0.0, 0.0)).cross(world.apply_vec(vec3(0.0, 1.0, 0.0)));+ if normal.length() < 1e-12 {+ return None;+ }+ let normal = normal.normalize();+ let b = buf_bounds(buf);+ let corners = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])];+ let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+ let mut behind = 0;+ let mut full_frame = false;+ for (u, v) in corners {+ let z = depth[0] * u + depth[1] * v + depth[2];+ if !cam.ortho && z < NEAR {+ behind += 1;+ full_frame = true;+ continue;+ }+ let p = full.apply(vec3(u, v, 0.0));+ x0 = x0.min(p.x);+ y0 = y0.min(p.y);+ x1 = x1.max(p.x);+ y1 = y1.max(p.y);+ }+ if behind == 4 {+ return None;+ }+ let (ow, oh) = (out.0 as i64, out.1 as i64);+ let bbox = if full_frame {+ [0, 0, ow, oh]+ } else {+ [((x0.floor() as i64) - 2).max(0), ((y0.floor() as i64) - 2).max(0), ((x1.ceil() as i64) + 2).min(ow), ((y1.ceil() as i64) + 2).min(oh)]+ };+ if bbox[0] >= bbox[2] || bbox[1] >= bbox[3] {+ return None;+ }+ Some(Geo { hinv, depth, world, normal, bbox, cam: *cam })+}++/// Layer-space rectangle covered by a buffer.+fn buf_bounds(buf: &Buf) -> [f64; 4] {+ let s = buf.scale.max(1e-9);+ [-buf.offset[0] / s, -buf.offset[1] / s, (buf.img.width as f64 - buf.offset[0]) / s, (buf.img.height as f64 - buf.offset[1]) / s]+}++/// Inverse-map an output pixel centre onto a plane: (u, v, camera depth).+#[inline]+fn unproject(g: &Geo, sx: f64, sy: f64) -> Option<(f64, f64, f64)> {+ let h = &g.hinv.0;+ let qz = h[2][0] * sx + h[2][1] * sy + h[2][2];+ if !g.cam.ortho && qz <= 0.0 {+ return None;+ }+ if qz.abs() < 1e-300 {+ return None;+ }+ let u = (h[0][0] * sx + h[0][1] * sy + h[0][2]) / qz;+ let v = (h[1][0] * sx + h[1][1] * sy + h[1][2]) / qz;+ let z = g.depth[0] * u + g.depth[1] * v + g.depth[2];+ if !g.cam.ortho && z < NEAR {+ return None;+ }+ Some((u, v, z))+}++/// 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 {+ match r.opts.view {+ Some(v) if r.depth == 0 => v,+ _ => active_camera(ctx),+ }+}++/// Number of motion-blur sub-samples for a layer.+fn mb_samples(r: &Renderer, ctx: &EvalCtx, layer: &Layer) -> usize {+ if r.opts.motion_blur && ctx.comp.enable_motion_blur && layer.switches.motion_blur {+ if r.opts.draft { 4 } else { ctx.comp.motion_blur_samples.clamp(2, 64) as usize }+ } else {+ 1+ }+}++/// Prepare a layer (buffer, geometry, material). `None` when it shows nothing.+pub(crate) fn prepare<'a>(r: &Renderer, ctx: &EvalCtx<'a>, layer: &'a Layer, order: usize, out: (u32, u32), in_run: bool) -> Option<Item<'a>> {+ let mut buf = r.layer_buf(ctx, layer)?;+ if buf.img.is_empty() {+ return None;+ }+ 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);+ // 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);+ let centre = world.apply(vec3((b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5, 0.0));+ let z = cam.depth(centre);+ let coc = dof.coc(z);+ // Comp pixels on screen per layer pixel at that depth.+ let k = cam.zoom / z.max(NEAR) * world.apply_vec(vec3(1.0, 0.0, 0.0)).length().max(1e-9);+ let radius = coc * 0.5 / k * buf.scale;+ if radius > 0.3 {+ let sigma = radius / 1.5;+ let pad = (sigma * 3.0).ceil() as u32 + 1;+ let padded = buf.img.padded(pad);- buf.img = effectcraft_raster::gaussian_blur(&padded, sigma, sigma, false);- buf.offset = [buf.offset[0] + pad as f64, buf.offset[1] + pad as f64];++ // The (cached, shared) layer buffer stays untouched; the blurred copy is per frame.++ buf = Arc::new(Buf {++ img: effectcraft_raster::gaussian_blur(&padded, sigma, sigma, false),++ offset: [buf.offset[0] + pad as f64, buf.offset[1] + pad as f64],++ scale: buf.scale,++ });+ }+ }+ let n = if in_run { mb_samples(r, ctx, layer) } else { 1 };+ let geos: Vec<Geo> = if n <= 1 {+ geo(&cam, world, &buf, comp, s, out).into_iter().collect()+ } else {+ let fd = ctx.comp.frame_duration().seconds();+ let angle = ctx.comp.shutter_angle / 360.0;+ let phase = ctx.comp.shutter_phase / 360.0;+ (0..n)+ .filter_map(|i| {+ 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), &buf, comp, s, out)+ })+ .collect()+ };+ if geos.is_empty() && in_run {+ return None;+ }+ let mut bbox = [i64::MAX, i64::MAX, i64::MIN, i64::MIN];+ for g in &geos {+ bbox = [bbox[0].min(g.bbox[0]), bbox[1].min(g.bbox[1]), bbox[2].max(g.bbox[2]), bbox[3].max(g.bbox[3])];+ }+ let mat = Material::of(ctx, layer);+ let bounds = buf_bounds(&buf);+ Some(Item {+ layer,+ order,+ bicubic: matches!(r.sampling(layer), effectcraft_raster::Sampling::Bicubic),+ buf,+ geos,+ opacity: ctx.opacity(layer) as f32,+ draw: in_run && mat.casts_shadows != 2,+ mat,+ matte: None,+ preserve: layer.preserve_transparency,+ winv: world.inverse().unwrap_or(Mat4::IDENTITY),+ bounds,+ bbox,+ })+}++/// Screen-space track matte factor for a layer, or None.+fn matte_for(r: &Renderer, ctx: &EvalCtx, layer: &Layer, out: (u32, u32)) -> Option<Vec<f32>> {+ let tm = layer.track_matte?;+ let m = ctx.comp.layer(tm.layer).filter(|m| m.id != layer.id)?;+ let mut img = Image::new(out.0, out.1);+ if m.is_active_at(ctx.time) {+ if m.is_3d() {+ // Render the matte plane alone (its own matte is ignored).+ let mut solo = m.clone();+ solo.track_matte = None;+ solo.preserve_transparency = false;+ solo.blend_mode = BlendMode::Normal;+ if let Some(it) = prepare(r, ctx, &solo, 0, out, true) {+ let lights = scene_lights(ctx);+ composite(&mut img, &[it], &lights, &[], m.id.0 as u32);+ }+ } else if let Some(mb) = r.layer_buf(ctx, m) {+ r.place(ctx, m, &mb, &mut img, BlendMode::Normal, ctx.opacity(m) as f32);+ }+ }+ Some(+ img.data+ .par_iter()+ .map(|q| {+ match tm.kind {+ MatteKind::Alpha => q[3],+ MatteKind::AlphaInverted => 1.0 - q[3],+ MatteKind::Luma => effectcraft_color::luminance(q[0], q[1], q[2]),+ MatteKind::LumaInverted => 1.0 - effectcraft_color::luminance(q[0], q[1], q[2]),+ }+ .clamp(0.0, 1.0)+ })+ .collect(),+ )+}++/// Lights used for shading: none in Draft 3D (which also turns off shadows and depth of field).+fn scene_lights(ctx: &EvalCtx) -> Vec<LightState> {+ if ctx.comp.draft_3d { vec![] } else { lights_at(ctx) }+}++/// Draw a run of consecutive 3D layers (bottom-to-top order) into `canvas`.+pub(crate) fn draw_run(r: &Renderer, ctx: &EvalCtx, run: &[&Layer], canvas: &mut Image) {+ // 3D adjustment layers act on everything below them in the stack (like 2D ones): split.+ if let Some(k) = run.iter().position(|l| l.switches.adjustment) {+ draw_run(r, ctx, &run[..k], canvas);+ r.draw_layer(ctx, run[k], canvas);+ draw_run(r, ctx, &run[k + 1..], canvas);+ return;+ }+ if run.is_empty() {+ return;+ }+ let out = (canvas.width, canvas.height);+ let lights = scene_lights(ctx);+ let mut items: Vec<Item> = run+ .par_iter()+ .enumerate()+ .filter(|(_, l)| ctx.opacity(l) > 0.0)+ .filter_map(|(i, l)| {+ let mut it = prepare(r, ctx, l, i, out, true)?;+ it.matte = matte_for(r, ctx, l, out);+ Some(it)+ })+ .collect();+ // Shadow casters outside this run (other 3D layers of the comp).+ let mut extra: Vec<Item> = vec![];+ if lights.iter().any(|l| l.casts_shadows && l.kind != LightKind::Ambient) {+ let in_run: Vec<_> = run.iter().map(|l| l.id).collect();+ extra = ctx+ .comp+ .layers+ .par_iter()+ .filter(|l| l.switches.three_d && l.has_video() && l.is_active_at(ctx.time) && !in_run.contains(&l.id) && !l.switches.adjustment)+ .filter(|l| Material::of(ctx, l).casts_shadows != 0)+ .filter_map(|l| prepare(r, ctx, l, 0, out, false))+ .collect();+ }+ 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);+}++/// Per-pixel depth-sorted compositing of prepared planes.+fn composite(canvas: &mut Image, items: &[Item], lights: &[LightState], casters: &[&Item], seed: u32) {+ let w = canvas.width as usize;+ canvas.rows_mut().for_each(|(y, row)| {+ let yi = y as i64;+ let active: Vec<&Item> = items.iter().filter(|it| it.draw && yi >= it.bbox[1] && yi < it.bbox[3]).collect();+ if active.is_empty() {+ return;+ }+ let mut frags: Vec<(f64, usize, Px, usize)> = Vec::with_capacity(active.len());+ for x in 0..w {+ let xi = x as i64;+ frags.clear();+ for (k, it) in active.iter().enumerate() {+ if xi < it.bbox[0] || xi >= it.bbox[2] {+ continue;+ }+ if let Some((z, px)) = fragment(it, x as f64 + 0.5, y as f64 + 0.5, lights, casters) {+ let px = match &it.matte {+ Some(m) => {+ let f = m[y * w + x];+ [px[0] * f, px[1] * f, px[2] * f, px[3] * f]+ }+ None => px,+ };+ if px[3] > 0.0 || px[0] != 0.0 || px[1] != 0.0 || px[2] != 0.0 {+ frags.push((z, it.order, px, k));+ }+ }+ }+ if frags.is_empty() {+ continue;+ }+ // Far → near; (near-)coplanar fragments in stack order (lower layer first).+ for i in 1..frags.len() {+ let mut j = i;+ while j > 0 && before(&frags[j], &frags[j - 1]) {+ frags.swap(j, j - 1);+ j -= 1;+ }+ }+ let mut d = row[x];+ for (_, _, px, k) in &frags {+ let it = active[*k];+ let mut s = *px;+ let op = it.opacity * if it.preserve { d[3] } else { 1.0 };+ for c in s.iter_mut() {+ *c *= op;+ }+ let mode = it.layer.blend_mode;+ let n = if matches!(mode, BlendMode::Dissolve | BlendMode::DancingDissolve) {+ hash_noise(x as u32, y as u32, seed ^ it.layer.id.0 as u32)+ } else {+ 0.5+ };+ d = blend_pixel(mode, d, s, n);+ }+ row[x] = d;+ }+ });+}++#[inline]+fn before(a: &(f64, usize, Px, usize), b: &(f64, usize, Px, usize)) -> bool {+ let tol = 1e-6 * a.0.abs().max(b.0.abs()).max(1.0);+ if (a.0 - b.0).abs() <= tol { a.1 < b.1 } else { a.0 > b.0 }+}++/// Shaded premultiplied fragment of a plane at an output pixel centre, with its depth.+fn fragment(it: &Item, sx: f64, sy: f64, lights: &[LightState], casters: &[&Item]) -> Option<(f64, Px)> {+ let n = it.geos.len();+ let mut acc = [0.0f32; 4];+ let mut depth = None;+ for g in &it.geos {+ let Some((u, v, z)) = unproject(g, sx, sy) else { continue };+ let t = it.texel(u, v);+ if t[3] <= 1e-6 {+ continue;+ }+ depth.get_or_insert(z);+ let px = shade_texel(it, g, u, v, t, lights, casters);+ for c in 0..4 {+ acc[c] += px[c];+ }+ }+ let depth = depth?;+ if n > 1 {+ let k = 1.0 / n as f32;+ for c in acc.iter_mut() {+ *c *= k;+ }+ }+ Some((depth, acc))+}++fn shade_texel(it: &Item, g: &Geo, u: f64, v: f64, t: Px, lights: &[LightState], casters: &[&Item]) -> Px {+ if lights.is_empty() || !it.mat.accepts_lights {+ if it.mat.accepts_shadows == 2 {+ return [0.0; 4];+ }+ return t;+ }+ let a = t[3];+ let rgb = [t[0] / a, t[1] / a, t[2] / a];+ let p = g.world.apply(vec3(u, v, 0.0));+ let shadow = |li: usize, p: Vec3| -> [f32; 3] {+ let l = &lights[li];+ let mut tr = [1.0f32; 3];+ for c in casters {+ if std::ptr::eq(*c, it) || c.layer.id == it.layer.id {+ continue;+ }+ let o = occlusion(c, p, l);+ for k in 0..3 {+ tr[k] *= o[k];+ }+ }+ tr+ };+ let (lit, shadow_amt) = shade(rgb, p, g.normal, g.cam.to_viewer(p), &it.mat, lights, &shadow);+ if it.mat.accepts_shadows == 2 {+ return [0.0, 0.0, 0.0, a * shadow_amt];+ }+ [lit[0] * a, lit[1] * a, lit[2] * a, a]+}++/// RGB transmittance of light `l` reaching `p` past caster `c` (1 = unoccluded).+fn occlusion(c: &Item, p: Vec3, l: &LightState) -> [f32; 3] {+ const FAR: f64 = 1.0e6;+ let a = c.winv.apply(p);+ let target = if l.kind == LightKind::Parallel { p - l.dir * FAR } else { l.pos };+ let b = c.winv.apply(target);+ if a.z == b.z || a.z.signum() == b.z.signum() {+ return [1.0; 3];+ }+ let t = a.z / (a.z - b.z);+ if t <= 1e-6 || t >= 1.0 - 1e-9 {+ return [1.0; 3];+ }+ let hit = a + (b - a) * t;+ // Penumbra radius (layer pixels) from Shadow Diffusion: grows with receiver–caster distance.+ let seg = (target - p).length();+ let d_pc = seg * t;+ let d_cl = if l.kind == LightKind::Parallel { 1000.0 } else { (seg * (1.0 - t)).max(1.0) };+ let r = l.shadow_diffusion * (d_pc / d_cl).min(4.0);+ let bd = &c.bounds;+ if hit.x < bd[0] - r || hit.y < bd[1] - r || hit.x > bd[2] + r || hit.y > bd[3] + r {+ return [1.0; 3];+ }+ let mut px = [0.0f32; 4];+ if r * c.buf.scale < 0.5 {+ px = c.texel(hit.x, hit.y);+ } else {+ for j in -1..=1 {+ for i in -1..=1 {+ let q = c.texel(hit.x + i as f64 * r * 0.66, hit.y + j as f64 * r * 0.66);+ for k in 0..4 {+ px[k] += q[k] / 9.0;+ }+ }+ }+ }+ let alpha = (px[3] * c.opacity).clamp(0.0, 1.0);+ if alpha <= 0.0 {+ return [1.0; 3];+ }+ let tr = c.mat.light_transmission;+ let dark = l.shadow_darkness as f32;+ let mut out = [1.0f32; 3];+ for k in 0..3 {+ let straight = if px[3] > 0.0 { (px[k] / px[3]).clamp(0.0, 1.0) } else { 0.0 };+ let pass = (1.0 - alpha) + alpha * tr * straight;+ out[k] = 1.0 - dark * (1.0 - pass);+ }+ out+}diff --cc crates/render/src/three_d/tests_orient.rsindex f5841d087,000000000..79e91f9ccmode 100644,000000..100644--- a/crates/render/src/three_d/tests_orient.rs+++ b/crates/render/src/three_d/tests_orient.rs@@@ -1,88 -1,0 +1,130 @@@+//! Auto-orient (along path / towards camera) and camera parenting.++use effectcraft_color::Label;+use effectcraft_geom::vec3;+use effectcraft_keyframe::{Keyframe, Value};+use effectcraft_project::build;+use effectcraft_project::{AutoOrient, Comp, ItemId, ItemKind, Layer, LayerSource, Project, Solid};+use effectcraft_time::{FrameRate, Tick};++use super::active_camera;+use crate::EvalCtx;++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, three_d: bool, pos: [f64; 3]) -> Layer {+ let sid = p.add_item("S", Label::Red, None, ItemKind::Solid(Solid { color: [1.0; 3], width: 10, height: 10, pixel_aspect: 1.0 }));+ let mut l = build::layer(p, comp, "S", LayerSource::Solid { item: sid }, (10, 10), None);+ l.switches.three_d = three_d;+ l.props.prop_mut("transform/position").unwrap().value = Value::Vec3(pos);+ l+}++#[test]+fn orient_towards_camera_faces_the_eye() {+ let (mut p, cid, comp) = setup();+ let mut l = solid(&mut p, &comp, true, [600.0, -200.0, 300.0]);+ l.auto_orient = AutoOrient::TowardsCamera;+ p.comp_mut(cid).unwrap().layers.push(l);+ let c = p.comp(cid).unwrap();+ let ctx = EvalCtx::new(&p, cid, c, Tick::ZERO);+ let w = ctx.world_matrix(&c.layers[0]);+ let n = w.apply_vec(vec3(0.0, 0.0, 1.0)).normalize();+ let eye = active_camera(&ctx).eye;+ let to_layer = (w.apply(vec3(5.0, 5.0, 0.0)) - eye).normalize();+ assert!((n - to_layer).length() < 1e-6, "{n:?} vs {to_layer:?}");+}++#[test]+fn orient_along_path_2d_follows_motion() {+ let (mut p, cid, comp) = setup();+ let mut l = solid(&mut p, &comp, false, [50.0, 10.0, 0.0]);+ l.auto_orient = AutoOrient::AlongPath;+ l.props.prop_mut("transform/position").unwrap().keys =+ vec![Keyframe::new(Tick::ZERO, Value::Vec3([50.0, 10.0, 0.0])), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Vec3([50.0, 90.0, 0.0]))];+ p.comp_mut(cid).unwrap().layers.push(l);+ let c = p.comp(cid).unwrap();+ let ctx = EvalCtx::new(&p, cid, c, Tick::from_seconds_f64(0.5));+ let x_axis = ctx.world_matrix(&c.layers[0]).apply_vec(vec3(1.0, 0.0, 0.0));+ // Moving straight down (+y): the layer's x axis points down the screen.+ assert!(x_axis.x.abs() < 1e-6 && (x_axis.y - 1.0).abs() < 1e-6, "{x_axis:?}");+}++#[test]+fn layers_parented_to_a_camera_follow_its_rotation() {+ let (mut p, cid, comp) = setup();+ let mut cam = build::layer(&mut p, &comp, "Camera", LayerSource::Camera, (200, 100), None);+ cam.auto_orient = AutoOrient::Off;+ cam.props.prop_mut("transform/position").unwrap().value = Value::Vec3([0.0, 0.0, 0.0]);+ cam.props.prop_mut("transform/orientation").unwrap().value = Value::Vec3([0.0, 90.0, 0.0]);+ let mut child = solid(&mut p, &comp, true, [0.0, 0.0, 100.0]);+ child.parent = Some(cam.id);+ let c = p.comp_mut(cid).unwrap();+ c.layers.push(cam);+ c.layers.push(child);+ let c = p.comp(cid).unwrap();+ let ctx = EvalCtx::new(&p, cid, c, Tick::ZERO);+ // 100 px in front of a camera turned to +x is at x = 100 (anchor at the solid's centre).+ let at = ctx.world_matrix(&c.layers[1]).apply(vec3(5.0, 5.0, 0.0));+ assert!((at - vec3(100.0, 0.0, 0.0)).length() < 1e-6, "{at:?}");+}++#[test]+fn camera_parented_to_towards_camera_layer_does_not_recurse() {+ let (mut p, cid, comp) = setup();+ let mut l = solid(&mut p, &comp, true, [100.0, 50.0, 0.0]);+ l.auto_orient = AutoOrient::TowardsCamera;+ let mut cam = build::layer(&mut p, &comp, "Camera", LayerSource::Camera, (200, 100), None);+ cam.parent = Some(l.id);+ let c = p.comp_mut(cid).unwrap();+ c.layers.push(cam);+ c.layers.push(l);+ let _ = crate::render_frame(&p, cid, Tick::ZERO, 0.5);+}++++/// The layer cache holds layer pixels only; camera, lights, DOF and the view override act at++/// compositing time, so cached renders must match uncached ones after any of them change.++#[test]++fn layer_cache_is_independent_of_camera_lights_and_view() {++ let (mut p, cid, comp) = setup();++ let mut cam = build::layer(&mut p, &comp, "Camera", LayerSource::Camera, (200, 100), None);++ cam.props.prop_mut("cameraOptions/dof").unwrap().value = Value::Bool(true);++ cam.props.prop_mut("cameraOptions/aperture").unwrap().value = Value::Scalar(40.0);++ let light = build::layer(&mut p, &comp, "Light", LayerSource::Light { kind: effectcraft_project::LightKind::Point }, (200, 100), None);++ let a = solid(&mut p, &comp, true, [80.0, 50.0, 0.0]);++ let b = solid(&mut p, &comp, true, [120.0, 50.0, 150.0]);++ let c = p.comp_mut(cid).unwrap();++ c.layers.extend([cam, light, a, b]);++ let cache = crate::LayerCache::new(64 << 20);++ let render = |p: &Project, cached: bool, view: Option<super::CameraState>| {++ let opts = crate::RenderOpts { view, motion_blur: false, ..Default::default() };++ let mut r = crate::Renderer::new(p, &crate::NoFootage, opts);++ if cached {++ r.cache = Some(&cache);++ }++ r.comp_frame(cid, Tick::ZERO)++ };++ let check = |p: &Project, view: Option<super::CameraState>| {++ let warm = render(p, true, view);++ assert_eq!(render(p, true, view), warm);++ assert_eq!(render(p, false, view), warm, "cached render differs from uncached");++ warm++ };++ let first = check(&p, None);++ // Move the camera, refocus, change the light: cached pixels must follow.++ let c = p.comp_mut(cid).unwrap();++ c.layers[0].props.prop_mut("transform/position").unwrap().value = Value::Vec3([40.0, 20.0, -250.0]);++ c.layers[0].props.prop_mut("cameraOptions/focusDistance").unwrap().value = Value::Scalar(400.0);++ c.layers[1].props.prop_mut("lightOptions/intensity").unwrap().value = Value::Scalar(40.0);++ let second = check(&p, None);++ assert_ne!(first, second, "camera/light changes re-render");++ let top = super::default_view_cam(super::View3D::Top, 200.0, 100.0).state();++ let third = check(&p, Some(top));++ assert_ne!(third, second);++ assert!(cache.stats().hits > 0, "the cache was actually used");++}diff --cc crates/ui-egui/src/lib.rsindex a8e3f0851,fc7990027..606136057--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -41,8 -41,9 +41,11 @@@ pub enum DialogCompSettings,SolidSettings,CommandPalette,+ CameraSettings,+ LightSettings,+ KeyVelocity,+ KeyInterpolation,+ TimeStretch,}/// Host hooks provided by the native app (file pickers etc.).@@@ -177,31 -183,29 +185,44 @@@ impl EffectcraftApp}pub fn frame_key(&self, comp: ItemId, frame: i64, scale: f64) -> FrameKey {- FrameKey { revision: self.session.revision, comp: comp.0, frame, scale: (scale * 1000.0).round() as u32 }+ FrameKey { revision: self.session.revision, comp: comp.0, frame, scale: (scale * 1000.0).round() as u32, view: self.view_hash(comp) }+ }++ /// Hash of the comp viewer's 3D view camera (0 for the active camera view).+ pub fn view_hash(&self, comp: ItemId) -> u64 {+ use std::hash::{Hash, Hasher};+ let Some(cam) = self.session.view_camera(comp) else { return 0 };+ let mut h = std::collections::hash_map::DefaultHasher::new();+ for row in cam.view.0 {+ for v in row {+ v.to_bits().hash(&mut h);+ }+ }+ cam.zoom.to_bits().hash(&mut h);+ cam.ortho.hash(&mut h);+ h.finish() | 1}- /// Request a frame render (no-op if cached/in flight).+ /// Request a prefetch frame render (no-op if cached/in flight).pub fn request_frame(&self, comp: ItemId, frame: i64, scale: f64) {+ self.request_frame_with(comp, frame, scale, false);+ }++ /// Request the frame on screen: rendered before any queued prefetch.+ pub fn request_frame_urgent(&self, comp: ItemId, frame: i64, scale: f64) {+ self.request_frame_with(comp, frame, scale, true);+ }++ fn request_frame_with(&self, comp: ItemId, frame: i64, scale: f64, urgent: bool) {let Some(c) = self.session.project.comp(comp) else { return };let key = self.frame_key(comp, frame, scale);let t = c.frame_rate.tick_of(frame);- let opts = RenderOpts { scale, motion_blur: true, guides: true, draft: self.ui.viewer.fast_preview };+ let opts = RenderOpts { scale, motion_blur: true, guides: true, draft: self.ui.viewer.fast_preview, view: self.session.view_camera(comp) };- self.frames.request(&self.render_source(), key, comp, t, opts);+ if urgent {+ self.frames.request_urgent(&self.render_source(), key, comp, t, opts);+ } else {+ self.frames.request(&self.render_source(), key, comp, t, opts);+ }}// ---------------------------------------------------------------- playbackdiff --cc crates/ui-egui/src/panels/dialogs.rsindex a189d496d,6d5c8e423..e277af46a--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@@ -34,8 -19,9 +19,11 @@@ pub struct DialogStatepub solid_size: [u32; 2],pub palette_query: String,pub palette_sel: usize,+ pub camera: super::dialogs_3d::CameraDraft,+ pub light: super::dialogs_3d::LightDraft,+ pub velocity: super::key_dialogs::VelocityDraft,+ pub interp: super::key_dialogs::InterpDraft,+ pub stretch: super::key_dialogs::StretchDraft,}pub fn open_new_comp(app: &mut EffectcraftApp) {@@@ -97,8 -89,9 +91,11 @@@ pub fn show(app: &mut EffectcraftApp, cDialog::NewComp | Dialog::CompSettings => comp_settings(app, ctx, &t, d == Dialog::CompSettings),Dialog::SolidSettings => solid(app, ctx, &t),Dialog::CommandPalette => palette(app, ctx, &t),+ Dialog::CameraSettings => super::dialogs_3d::camera(app, ctx, &t),+ Dialog::LightSettings => super::dialogs_3d::light(app, ctx, &t),+ Dialog::KeyVelocity => super::key_dialogs::velocity(app, ctx, &t),+ Dialog::KeyInterpolation => super::key_dialogs::interpolation(app, ctx, &t),+ Dialog::TimeStretch => super::key_dialogs::time_stretch(app, ctx, &t),}}diff --cc crates/ui-egui/src/panels/mod.rsindex 63f83d2b5,5321d8498..8cd26cb5e--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@@ -1,12 -1,16 +1,17 @@@//! Panel bodies.+ pub mod comp_settings;pub mod dialogs;+pub mod dialogs_3d;pub mod effect_controls;pub mod effects_presets;+ pub mod graph;pub mod info;+ pub mod key_dialogs;pub mod misc;pub mod project;+ pub mod properties;+ pub mod render_queue;pub mod text_panels;pub mod timeline;pub mod viewer;diff --cc crates/ui-egui/src/panels/timeline.rsindex b63f53071,c83c9de8f..a7ff23385--- a/crates/ui-egui/src/panels/timeline.rs+++ b/crates/ui-egui/src/panels/timeline.rs@@@ -140,10 -186,10 +186,14 @@@ fn prop_visible(p: &Property, layer: &Lif p.two_d_only && layer.is_3d() {return false;}+ // One-node cameras (and lights with auto-orient off) have no Point of Interest.+ if p.match_id == "poi" && (layer.is_camera() || layer.is_light()) && layer.auto_orient != effectcraft_engine::project::AutoOrient::TowardsPointOfInterest {+ return false;+ }+ // Separate Dimensions: X/Y/Z Position replace Position.+ if p.match_id == "position" && layer.transform().is_some_and(|tr| tr.get("positionX").is_some() && tr.get("position").is_some_and(|q| q.uid == p.uid)) {+ return false;+ }true}diff --cc crates/ui-egui/src/panels/viewer.rsindex 8757fd960,2147741d7..3989b8cb4--- a/crates/ui-egui/src/panels/viewer.rs+++ b/crates/ui-egui/src/panels/viewer.rs@@@ -495,7 -551,22 +590,23 @@@ pub fn show(app: &mut EffectcraftApp, u})}),t if t.is_shape() => Some(Gesture::Create { tool: t, start: cpt }),+ Tool::Orbit | Tool::PanCamera | Tool::Dolly => Some(Gesture::Camera { tool }),+ Tool::Selection if vertex_at(press, true).is_some() => vertex_at(press, true).map(|h| Gesture::Tangent {+ layer: h.layer,+ mask: h.mask,+ index: h.index,+ out: h.tangent == Some(true),+ vertex: h.vertex,+ inv: h.l2c.inverse().unwrap_or(Mat3::IDENTITY),+ }),+ Tool::Selection if vertex_at(press, false).is_some() => vertex_at(press, false).map(|h| {+ let me = json!({"layer": h.layer.0, "mask": h.mask, "index": h.index});+ let selected = app.session.state.selected_vertices.iter().any(|v| v.layer == h.layer && v.mask == h.mask && v.index == h.index);+ if !selected {+ let _ = app.session.execute("mask.selectVertices", json!({"vertices": [me], "add": mods.shift}));+ }+ Gesture::Vertices { last: cpt, inv: h.l2c.inverse().unwrap_or(Mat3::IDENTITY) }+ }),Tool::Selection => {if let Some((lid, hi, _)) = handle_hits.iter().find(|(_, _, h)| h.distance(pos) < HANDLE + 2.0).cloned() {let layer = comp.layer(lid).cloned();@@@ -506,16 -577,10 +617,10 @@@let a = ectx.v3(&layer, tr, "anchor", [0.0; 3]);let lp = inv.apply(gv2(cpt[0], cpt[1]));let _ = hi;- Some(Gesture::Scale {- layer: lid,- start_scale: ectx.v3(&layer, tr, "scale", [100.0; 3]),- start_local: [lp.x - a[0], lp.y - a[1]],- inv,- uniform: hi < 4,- })+ Some(Gesture::Scale { layer: lid, start_scale: ectx.v3(&layer, tr, "scale", [100.0; 3]), start_local: [lp.x - a[0], lp.y - a[1]], inv })})} else if let Some(l) = pick(app, &ectx, cpt, mods.shift) {- let layers: Vec<(LayerId, [f64; 3], Mat3)> = app+ let layers: Vec<(LayerId, [f64; 3], [f64; 3], [f64; 3])> = app.session.state.selected_layers@@@ -734,99 -815,51 +872,144 @@@bottom_bar(app, ui, bar, zoom, fit, time, &comp);}+/// Parent-space position change per comp pixel of drag (x and y) for a layer: 2D layers map+/// through the parent transform; 3D layers move in the view plane at their depth.+fn drag_axes(ctx: &EvalCtx, l: &Layer) -> ([f64; 3], [f64; 3]) {+ if !l.is_3d() {+ let inv = parent_inverse(ctx, l);+ let a = inv.apply_vec(gv2(1.0, 0.0));+ let b = inv.apply_vec(gv2(0.0, 1.0));+ return ([a.x, a.y, 0.0], [b.x, b.y, 0.0]);+ }+ let cam = cam_state(ctx);+ let anchor = l.transform().map(|tr| ctx.v3(l, tr, "anchor", [0.0; 3])).unwrap_or([0.0; 3]);+ let wp = ctx.world_matrix(l).apply(anchor.into());+ let k = if cam.ortho { 1.0 / cam.zoom.max(1e-9) } else { cam.depth(wp).max(1.0) / cam.zoom.max(1e-9) };+ let pinv = match l.parent.and_then(|p| ctx.comp.layer(p)) {+ Some(p) => ctx.world_matrix(p).inverse().unwrap_or_default(),+ None => effectcraft_engine::geom::Mat4::IDENTITY,+ };+ let a = pinv.apply_vec(cam.right() * k);+ let b = pinv.apply_vec(cam.down() * k);+ ([a.x, a.y, a.z], [b.x, b.y, b.z])+}++/// Wireframes of cameras (frustum, point of interest) and lights (position, direction) as seen+/// through the current 3D view.+fn draw_rigs(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap, ectx: &EvalCtx, selected: &[LayerId]) {+ use effectcraft_engine::geom::Vec3;+ use effectcraft_engine::project::{LayerSource, LightKind};+ let cam = cam_state(ectx);+ let (w, h) = (ectx.comp.width as f64, ectx.comp.height as f64);+ let active = ectx.comp.active_camera(ectx.time).map(|c| c.id);+ let through_active = VIEW_CAM.with(|c| c.get()).is_none();+ let proj = |p: Vec3| cam.project(w, h, p).map(|v| map.to_screen([v.x, v.y]));+ let seg = |a: Vec3, b: Vec3, stroke: Stroke| {+ if let (Some(x), Some(y)) = (proj(a), proj(b)) {+ painter.line_segment([x, y], stroke);+ }+ };+ for l in ectx.comp.layers.iter().filter(|l| (l.is_camera() || l.is_light()) && l.is_active_at(ectx.time)) {+ let sel = selected.contains(&l.id);+ let col = Tokens::label(l.label).gamma_multiply(if sel { 1.0 } else { 0.6 });+ let stroke = Stroke::new(if sel { 1.5 } else { 1.0 }, col);+ let (eye, fwd, down) = three_d::camera::layer_frame(ectx, l);+ let poi = |l: &Layer| -> Option<Vec3> {+ let pr = l.transform()?.get("poi").filter(|_| three_d::camera::is_two_node(l))?;+ Some(three_d::camera::parent_world(ectx, l).apply(ectx.value(l, pr).as_vec3().into()))+ };+ if l.is_camera() {+ if through_active && Some(l.id) == active {+ continue;+ }+ let zoom = l.props.prop("cameraOptions/zoom").map(|p| ectx.value(l, p).as_f64()).unwrap_or(1000.0);+ let right = down.cross(fwd);+ // Frustum to a plane at a quarter of the zoom distance.+ let k = 0.25;+ let c = eye + fwd * (zoom * k);+ let corners = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].map(|(sx, sy)| c + right * (sx * w * 0.5 * k) + down * (sy * h * 0.5 * k));+ for i in 0..4 {+ seg(eye, corners[i], stroke);+ seg(corners[i], corners[(i + 1) % 4], stroke);+ }+ if let Some(poi) = poi(l) {+ seg(eye, poi, Stroke::new(1.0, col.gamma_multiply(0.6)));+ if let Some(s) = proj(poi) {+ painter.circle_stroke(s, 4.0, stroke);+ }+ }+ if let Some(s) = proj(eye) {+ app.auto.add(&format!("viewer.camera.{}", l.id.0), Rect::from_center_size(s, vec2(14.0, 14.0)), &l.name);+ }+ } else {+ let LayerSource::Light { kind } = l.source else { continue };+ if kind == LightKind::Ambient {+ continue;+ }+ let Some(s) = proj(eye) else { continue };+ painter.circle_stroke(s, 6.0, stroke);+ for i in 0..8 {+ let a = i as f32 * std::f32::consts::FRAC_PI_4;+ let d = vec2(a.cos(), a.sin());+ painter.line_segment([s + d * 8.0, s + d * 12.0], stroke);+ }+ if matches!(kind, LightKind::Spot | LightKind::Parallel) {+ let target = poi(l).unwrap_or(eye + fwd * 300.0);+ seg(eye, target, Stroke::new(1.0, col.gamma_multiply(0.7)));+ if let Some(q) = proj(target) {+ painter.circle_stroke(q, 3.0, stroke);+ }+ }+ app.auto.add(&format!("viewer.light.{}", l.id.0), Rect::from_center_size(s, vec2(16.0, 16.0)), &l.name);+ }+ }+}++ /// Pen tool press at `pos`: start a mask on the selected layer, add a vertex, or close the path.+ fn pen_press(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, map: &ViewerMap, hits: &[VertexHit], pos: Pos2) {+ let gid = egui::Id::new("viewer-gesture");+ let current: Option<(LayerId, u64)> = ui.data(|d| d.get_temp(pen_id()));+ let target = current.map(|c| c.0).or_else(|| {+ app.session.state.selected_layers.iter().copied().find(|id| ectx.comp.layer(*id).is_some_and(|l| l.masks().is_some() && !l.switches.locked))+ });+ let Some(lid) = target else {+ app.ui.status = "Select a layer to draw a mask with the Pen tool".into();+ return;+ };+ let Some(layer) = ectx.comp.layer(lid) else { return };- let l2c = ectx.layer_to_comp(layer).0;++ let l2c = l2c(ectx, layer).0;+ let Some(inv) = l2c.inverse() else { return };+ let c = map.to_comp(pos);+ let lp = inv.apply(gv2(c[0], c[1]));+ let lp = [lp.x, lp.y];+ let still_there = current.is_some_and(|(l, m)| layer.masks().is_some_and(|ms| ms.find_group(m).is_some()) && l == lid);+ if let (true, Some((_, mask))) = (still_there, current) {+ let count = hits.iter().filter(|h| h.layer == lid && h.mask == mask && h.tangent.is_none()).count();+ let first = hits.iter().find(|h| h.layer == lid && h.mask == mask && h.index == 0 && h.tangent.is_none());+ if count >= 2 && first.is_some_and(|f| f.pos.distance(pos) < 8.0) {+ let _ = app.session.execute("mask.setClosed", json!({"layer": lid.0, "mask": mask, "closed": true}));+ ui.data_mut(|d| {+ d.remove::<(LayerId, u64)>(pen_id());+ d.remove::<Gesture>(gid);+ });+ return;+ }+ if let Ok(v) = app.session.execute("mask.addVertex", json!({"layer": lid.0, "mask": mask, "point": lp})) {+ let index = v.as_u64().unwrap_or(0) as usize;+ ui.data_mut(|d| d.insert_temp(gid, Gesture::Pen { layer: lid, mask, index, vertex: lp, inv, press: pos }));+ }+ return;+ }+ if let Ok(v) = app.session.execute("mask.new", json!({"layer": lid.0, "vertices": [lp]}))+ && let Some(mask) = v["mask"].as_u64()+ {+ ui.data_mut(|d| {+ d.insert_temp(pen_id(), (lid, mask));+ d.insert_temp(gid, Gesture::Pen { layer: lid, mask, index: 0, vertex: lp, inv, press: pos });+ });+ }+ }+/// Topmost layer under a comp point (selects it; shift toggles). Returns the hit layer.fn pick(app: &mut EffectcraftApp, ectx: &EvalCtx, cpt: [f64; 2], toggle: bool) -> Option<LayerId> {let hit = ectx