Merge main into M7 3D branch

Resolve conflicts with perf (layer cache / Arc<Buf>), export (RenderOpts.view: None
for output), timeline (separate dimensions + one-node POI visibility), mask/pen
viewer gestures (alongside camera tools and view-aware layer matrices), key
dialogs (alongside Camera/Light Settings), render queue + MCP command modules.
3D path tangent honours separated position; DOF blurs a per-frame copy so cached
layer buffers stay shared. New test: cached renders match uncached after camera,
focus, light and 3D view changes. Fix a clone-on-copy lint from main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-01 23:24:08 -04:00
co-authored by Claude Opus 5.5
128 changed files with 23915 additions and 686 deletions
+84 -4
View File
@@ -16,7 +16,10 @@
//! - `ui.timeline.locate {layer, time?}`: screen point of a layer bar (at a comp time)
//! - `ui.playback {action: play|stop|toggle}`
//! - `ui.screenshot {path?, panel?, id?}`: PNG of the window (or one panel / element)
//! - `render.frame {comp?, time?, max_side?, path?, base64?}`: PNG of a comp frame rendered by the session
//! - `ui.resize {width, height}` / `ui.focus` / `app.quit`
//!
//! The full reference with examples is `docs/control-protocol.md`.
use std::sync::mpsc::Sender;
@@ -86,13 +89,24 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
match req.method.as_str() {
"engine.execute" | "ui.menu.invoke" => {
let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
let params = p.get("params").cloned().unwrap_or(json!({}));
match crate::menus::invoke(app, ctx, id, params) {
let params = p.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({}));
// `engine.execute` runs engine commands exactly as headless (never opens a dialog, e.g.
// `comp.new {}` creates a default comp); UI-only ids (`tool.*`, `view.*`, `window.*`,
// `playback.*` …) and `ui.menu.invoke` go through the menu dispatcher like a click.
let r = if req.method == "engine.execute" && effectcraft_engine::find_command(id).is_some() {
app.session.execute_checked(id, params).map_err(|e| e.to_string())
} else {
crate::menus::invoke(app, ctx, id, params)
};
match r {
Ok(v) => ok(v),
Err(e) => err(e),
Err(e) => {
app.ui.status = e.clone();
err(e)
}
}
}
"engine.commands" => match app.session.execute("command.list", json!({})) {
"engine.commands" => match app.session.execute("command.list", json!({"filter": p.get("filter"), "enabledOnly": p.get("enabledOnly")})) {
Ok(v) => ok(v),
Err(e) => err(e),
},
@@ -301,6 +315,7 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
app.raise_for_control(ctx);
Outcome::Screenshot { path: s("path").map(str::to_string), crop }
}
"render.frame" => render_frame(app, p),
"ui.resize" => {
let w = p.get("width").and_then(Value::as_f64).unwrap_or(1600.0) as f32;
let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0) as f32;
@@ -320,6 +335,61 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
}
}
/// `render.frame {comp?, time?, max_side?, path?, base64?}`: render a comp frame through the session
/// (independent of the viewer zoom/resolution) and return it as PNG, written to `path` (default a
/// temp file) or inline as base64 when `base64: true`.
fn render_frame(app: &EffectcraftApp, p: &Value) -> Outcome {
let s = &app.session;
let cid = match s.resolve_comp(p.get("comp")) {
Ok(c) => c,
Err(e) => return err(e),
};
let t = p.get("time").or(p.get("seconds")).and_then(Value::as_f64).map(effectcraft_time::Tick::from_seconds_f64).unwrap_or_else(|| s.time());
let max_side = p.get("max_side").or(p.get("maxSide")).and_then(Value::as_u64).unwrap_or(0) as u32;
let (w, h, rgba) = match s.render_rgba8(cid, t, max_side) {
Ok(r) => r,
Err(e) => return err(e),
};
let png = match encode_png(&rgba, w, h) {
Ok(p) => p,
Err(e) => return err(e),
};
let mut out = json!({"comp": cid.0, "time": t.seconds(), "width": w, "height": h});
if p.get("base64").and_then(Value::as_bool) == Some(true) {
out["png"] = json!(base64(&png));
return ok(out);
}
let path = p
.get("path")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| std::env::temp_dir().join(format!("effectcraft-frame-{}.png", std::process::id())).to_string_lossy().to_string());
match std::fs::write(&path, png) {
Ok(()) => {
out["path"] = json!(path);
ok(out)
}
Err(e) => err(format!("cannot write {path}: {e}")),
}
}
/// Standard base64 (RFC 4648, padded).
pub fn base64(data: &[u8]) -> String {
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut s = String::with_capacity(data.len().div_ceil(3) * 4);
for c in data.chunks(3) {
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
for i in 0..4 {
if i <= c.len() {
s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
s.push('=');
}
}
}
s
}
pub fn inspect(app: &EffectcraftApp, ctx: &egui::Context) -> Value {
let size = ctx.content_rect().size();
json!({
@@ -417,3 +487,13 @@ pub fn encode_png(rgba: &[u8], w: u32, h: u32) -> Result<Vec<u8>, String> {
chunk(&mut out, b"IEND", &[]);
Ok(out)
}
#[cfg(test)]
mod tests {
#[test]
fn base64_rfc4648_vectors() {
for (i, o) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")] {
assert_eq!(super::base64(i.as_bytes()), o);
}
}
}
+18 -16
View File
@@ -240,19 +240,12 @@ pub fn workspace(name: &str) -> DockNode {
),
tabs(&[Timeline, RenderQueue], 0),
),
// Default: Project/Effect Controls | Composition | Info, Audio, Preview, Effects & Presets…
_ => vsplit(
Ratio(0.56),
hsplit(
FixedA(300.0),
tabs(&[Project, EffectControls], 0),
hsplit(
FixedB(290.0),
tabs(&[Composition, Layer], 0),
vsplit(Ratio(0.42), tabs(&[Info, Audio, Preview], 2), tabs(&[EffectsPresets, Properties, Character, Paragraph, Align], 0)),
),
),
tabs(&[Timeline, RenderQueue], 0),
// Default (as in After Effects): Project/Effect Controls | Composition over the Timeline,
// and a full-height right column with Preview above the Properties panel.
_ => hsplit(
FixedB(300.0),
vsplit(Ratio(0.56), hsplit(FixedA(300.0), tabs(&[Project, EffectControls], 0), tabs(&[Composition, Layer], 0)), tabs(&[Timeline, RenderQueue], 0)),
vsplit(FixedA(250.0), tabs(&[Preview, Info, Audio], 0), tabs(&[Properties, EffectsPresets, Character, Paragraph, Align], 0)),
),
}
}
@@ -411,7 +404,15 @@ pub fn layout(ui: &mut egui::Ui, node: &mut DockNode, rect: Rect, t: &Tokens, pa
}
/// Draw a group's frame + tab strip. Returns actions (tab clicks, panel menu, focus).
pub fn draw_group_chrome(ui: &mut egui::Ui, g: &Group, focused: PanelKind, t: &Tokens, reg: &mut crate::automation::Registry) -> Vec<DockAction> {
/// `title` gives a tab's label, which may name the comp or layer it shows (After Effects style).
pub fn draw_group_chrome(
ui: &mut egui::Ui,
g: &Group,
focused: PanelKind,
t: &Tokens,
reg: &mut crate::automation::Registry,
title: &dyn Fn(PanelKind) -> String,
) -> Vec<DockAction> {
let mut actions = Vec::new();
let painter = ui.painter().clone();
painter.rect_filled(g.rect, t.radius, t.panel_bg);
@@ -429,7 +430,8 @@ pub fn draw_group_chrome(ui: &mut egui::Ui, g: &Group, focused: PanelKind, t: &T
let text_y = strip.min.y + 16.0;
for (i, p) in g.panels.iter().enumerate() {
let is_active = i == g.active;
let galley = painter.layout_no_wrap(p.title().to_string(), Tokens::ui(12.0), if is_active { t.tab_text_active } else { t.tab_text });
let label = title(*p);
let galley = painter.layout_no_wrap(label.clone(), Tokens::ui(12.0), if is_active { t.tab_text_active } else { t.tab_text });
let menu_w = if is_active { 20.0 } else { 0.0 };
let w = galley.size().x + 16.0 + menu_w;
if x + w > strip.max.x - 20.0 && i > g.active {
@@ -445,7 +447,7 @@ pub fn draw_group_chrome(ui: &mut egui::Ui, g: &Group, focused: PanelKind, t: &T
}
let tab = Rect::from_min_size(pos2(x, strip.min.y), vec2(w, t.tab_h));
let resp = ui.interact(tab, egui::Id::new(("tab", g.path.clone(), i)), Sense::click());
reg.add(&format!("panel.tab.{}", p.id()), tab, p.title());
reg.add(&format!("panel.tab.{}", p.id()), tab, &label);
let label_x = tab.min.x + 8.0;
let label_w = galley.size().x;
let col = if is_active || resp.hovered() { t.tab_text_active } else { t.tab_text };
+91 -11
View File
@@ -8,8 +8,9 @@ use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use effectcraft_engine::project::{ItemId, Project};
use effectcraft_engine::render::{ExprHost, FootageSource, RenderOpts, Renderer};
use effectcraft_engine::render::{ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
use effectcraft_engine::time::Tick;
use rayon::prelude::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FrameKey {
@@ -51,14 +52,18 @@ pub struct RenderSource {
pub project: Arc<Project>,
pub footage: Arc<dyn FootageSource>,
pub expr: Option<Arc<dyn ExprHost>>,
pub layer_cache: Arc<LayerCache>,
}
pub struct Frames {
cache: Arc<Mutex<Cache>>,
/// Keys queued or rendering.
inflight: Arc<Mutex<HashSet<FrameKey>>>,
/// Pending jobs, picked by priority when a pool thread frees up (the viewer's frame first).
queue: Arc<Mutex<Queue>>,
pool: rayon::ThreadPool,
ctx: Option<egui::Context>,
/// Last render time per frame (ms), for the Info panel / perf readout.
/// Render time of the last viewer (urgent) frame in ms, for the Info panel / perf readout.
pub last_ms: Arc<Mutex<f64>>,
}
@@ -68,6 +73,7 @@ impl Default for Frames {
Frames {
cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, budget: 3 << 30 })),
inflight: Arc::new(Mutex::new(HashSet::new())),
queue: Arc::new(Mutex::new(Queue::default())),
pool: rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("ec-frame-{i}")).build().expect("frame pool"),
ctx: None,
last_ms: Arc::new(Mutex::new(0.0)),
@@ -80,7 +86,7 @@ impl Default for Frames {
pub fn to_color_image(img: &effectcraft_engine::render::Image) -> egui::ColorImage {
let px: Vec<egui::Color32> = img
.data
.iter()
.par_iter()
.map(|p| {
let a = p[3].clamp(0.0, 1.0);
let c = |v: f32| (v.clamp(0.0, a) * 255.0 + 0.5) as u8;
@@ -125,36 +131,92 @@ impl Frames {
}
}
/// Queue a frame (no-op if cached or already rendering).
/// Queue a prefetch frame (no-op if cached or already queued/rendering).
pub fn request(&self, src: &RenderSource, key: FrameKey, comp: ItemId, t: Tick, opts: RenderOpts) {
self.request_with(src, key, comp, t, opts, false);
}
/// Queue the frame the viewer is showing: it jumps ahead of every prefetch job.
pub fn request_urgent(&self, src: &RenderSource, key: FrameKey, comp: ItemId, t: Tick, opts: RenderOpts) {
self.request_with(src, key, comp, t, opts, true);
}
/// An urgent (viewer) frame is queued or rendering.
pub fn urgent_pending(&self) -> bool {
self.queue.lock().map(|q| q.urgent_running > 0 || q.jobs.iter().any(|j| j.urgent)).unwrap_or(false)
}
fn request_with(&self, src: &RenderSource, key: FrameKey, comp: ItemId, t: Tick, opts: RenderOpts, urgent: bool) {
if self.is_cached(&key) {
return;
}
let Ok(mut q) = self.queue.lock() else { return };
// Jobs for an older project revision can never be shown: drop them.
let before = q.jobs.len();
q.jobs.retain(|j| j.key.revision >= key.revision);
let dropped = before - q.jobs.len();
if dropped > 0
&& let Ok(mut inf) = self.inflight.lock()
{
inf.retain(|k| k.revision >= key.revision || q.running.contains(k));
}
if urgent {
// Only the newest viewer frame is urgent; earlier ones become prefetch.
for j in q.jobs.iter_mut() {
j.urgent = j.key == key;
}
}
{
let Ok(mut inf) = self.inflight.lock() else { return };
if !inf.insert(key) {
return;
}
}
let src = src.clone();
q.seq += 1;
let seq = q.seq;
q.jobs.push(Job { key, src: src.clone(), comp, t, opts, urgent, seq });
drop(q);
let queue = self.queue.clone();
let cache = self.cache.clone();
let inflight = self.inflight.clone();
let ctx = self.ctx.clone();
let last = self.last_ms.clone();
// One spawn per job; each spawn renders whichever queued job matters most right now.
self.pool.spawn(move || {
let job = {
let Ok(mut q) = queue.lock() else { return };
// Urgent first (newest), then prefetch in request order.
let best = q.jobs.iter().enumerate().max_by_key(|(_, j)| (j.urgent, if j.urgent { j.seq as i64 } else { -(j.seq as i64) })).map(|(i, _)| i);
let Some(i) = best else { return };
let job = q.jobs.swap_remove(i);
q.running.insert(job.key);
if job.urgent {
q.urgent_running += 1;
}
job
};
let t0 = std::time::Instant::now();
let mut r = Renderer::new(&src.project, src.footage.as_ref(), opts);
r.expr = src.expr.as_deref();
let img = r.comp_frame(comp, t);
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
r.expr = job.src.expr.as_deref();
r.cache = Some(&job.src.layer_cache);
let img = r.comp_frame(job.comp, job.t);
let ci = Arc::new(to_color_image(&img));
if let Ok(mut l) = last.lock() {
if job.urgent
&& let Ok(mut l) = last.lock()
{
*l = t0.elapsed().as_secs_f64() * 1000.0;
}
if let Ok(mut c) = cache.lock() {
c.insert(key, ci);
c.insert(job.key, ci);
}
if let Ok(mut inf) = inflight.lock() {
inf.remove(&key);
inf.remove(&job.key);
}
if let Ok(mut q) = queue.lock() {
q.running.remove(&job.key);
if job.urgent {
q.urgent_running -= 1;
}
}
if let Some(ctx) = ctx {
ctx.request_repaint();
@@ -162,3 +224,21 @@ impl Frames {
});
}
}
struct Job {
key: FrameKey,
src: RenderSource,
comp: ItemId,
t: Tick,
opts: RenderOpts,
urgent: bool,
seq: u64,
}
#[derive(Default)]
struct Queue {
jobs: Vec<Job>,
running: HashSet<FrameKey>,
urgent_running: usize,
seq: u64,
}
+69 -5
View File
@@ -43,6 +43,9 @@ pub enum Dialog {
CommandPalette,
CameraSettings,
LightSettings,
KeyVelocity,
KeyInterpolation,
TimeStretch,
}
/// Host hooks provided by the native app (file pickers etc.).
@@ -164,7 +167,12 @@ impl EffectcraftApp {
}
pub fn render_source(&self) -> RenderSource {
RenderSource { project: self.session.project.clone(), footage: self.session.footage.clone(), expr: self.session.expr.clone() }
RenderSource {
project: self.session.project.clone(),
footage: self.session.footage.clone(),
expr: self.session.expr.clone(),
layer_cache: self.session.layer_cache.clone(),
}
}
/// The render scale used by the viewer right now.
@@ -195,13 +203,26 @@ impl EffectcraftApp {
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, 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);
}
}
// ---------------------------------------------------------------- playback
@@ -243,7 +264,15 @@ impl EffectcraftApp {
let (wa, wb) = (fr.frame_at(c.work_area.0), fr.frame_at(c.work_area.1 - c.frame_duration()));
// Prefetch ahead.
let cur = fr.frame_at(self.session.time());
let ahead = (self.frames_parallelism() * 2).max(4) as i64;
// While paused (scrubbing, editing) the viewer's frame comes first: prefetch only a few
// frames, and only once it is done, so prefetch never delays what is on screen.
let ahead = if self.playback.playing {
(self.frames_parallelism() * 2).max(4) as i64
} else if self.frames.urgent_pending() {
0
} else {
(self.frames_parallelism() / 2).max(2) as i64
};
let mut queued = self.frames.inflight();
for k in 0..ahead * 3 {
if queued >= ahead as usize {
@@ -330,6 +359,12 @@ impl EffectcraftApp {
}
control::Outcome::AfterInput => self.input_waiters.push(reply),
control::Outcome::Screenshot { path, crop } => {
// A covered or minimized window presents no frames (macOS skips its redraws), so
// a screenshot would never arrive and nothing would tick its timeout.
if ctx.input(|i| i.viewport().occluded == Some(true) || i.viewport().minimized == Some(true)) {
let _ = reply.send(json!({"ok": false, "error": "window is covered or minimized: call ui.focus first (render.frame renders comp pixels without the window)"}));
continue;
}
let token = self.next_token;
self.next_token += 1;
let settle = now + 0.35;
@@ -417,6 +452,10 @@ impl EffectcraftApp {
let ctx = ui.ctx().clone();
self.auto.begin_frame();
self.frames.set_context(&ctx);
if self.session.render_job.is_some() {
self.session.poll_render();
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
self.handle_events(&ctx);
if let Some(rx) = self.command_inbox.take() {
while let Ok(id) = rx.try_recv() {
@@ -478,14 +517,31 @@ impl EffectcraftApp {
}
}
/// Tab labels that name what the panel shows, as After Effects does: "Composition Intro",
/// "Effect Controls Title", "Properties: Title", and the Timeline tab named after its comp.
fn tab_titles(&self) -> Vec<(PanelKind, String)> {
let mut out = Vec::new();
let Some(comp) = self.session.active_comp() else { return out };
let cname = self.session.active_comp_id().and_then(|id| self.session.project.item(id)).map(|i| i.name.clone()).unwrap_or_default();
out.push((PanelKind::Composition, format!("Composition {cname}")));
out.push((PanelKind::Timeline, cname));
if let Some(l) = self.session.state.selected_layers.first().and_then(|id| comp.layer(*id)) {
out.push((PanelKind::EffectControls, format!("Effect Controls {}", l.name)));
out.push((PanelKind::Properties, format!("Properties: {}", l.name)));
}
out
}
fn dock_area(&mut self, ui: &mut egui::Ui, body: egui::Rect) {
let t = self.tokens;
let mut dock = std::mem::replace(&mut self.ui.dock, dock::DockNode::Tabs { panels: vec![], active: 0 });
let mut groups = Vec::new();
dock::layout(ui, &mut dock, body, &t, "", &mut groups, &mut self.auto);
let mut actions = Vec::new();
let titles = self.tab_titles();
let title = |p: PanelKind| titles.iter().find(|(k, _)| *k == p).map(|(_, s)| s.clone()).unwrap_or_else(|| p.title().to_string());
for g in &groups {
actions.extend(dock::draw_group_chrome(ui, g, self.ui.focused, &t, &mut self.auto));
actions.extend(dock::draw_group_chrome(ui, g, self.ui.focused, &t, &mut self.auto, &title));
}
self.ui.dock = dock;
for g in &groups {
@@ -511,6 +567,14 @@ impl EffectcraftApp {
}
}
impl EffectcraftApp {
/// Take the pending synthetic input (from `ui.click`, `ui.key`, …). Hosts that don't call
/// [`eframe::App::raw_input_hook`] (the headless test harness) feed these in themselves.
pub fn take_synthetic_input(&mut self) -> Vec<egui::Event> {
std::mem::take(&mut self.synthetic)
}
}
impl eframe::App for EffectcraftApp {
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
if !self.synthetic.is_empty() {
+22
View File
@@ -249,6 +249,9 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
"app.compSettings" | "comp.settings" if params.as_object().is_none_or(|m| m.is_empty()) => {
crate::panels::dialogs::open_comp_settings(app)?;
}
"keys.velocity" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_velocity(app)?,
"keys.interpolation" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_interpolation(app)?,
"layer.timeStretch" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_time_stretch(app)?,
"app.solidSettings" | "layer.newSolid" if params.as_object().is_none_or(|m| m.is_empty()) => {
crate::panels::dialogs::open_new_solid(app)?;
}
@@ -260,6 +263,25 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
{
return file_dialog(app, id);
}
if id == "renderQueue.render" && params.get("wait").is_none() {
// The UI renders in the background; the panel shows progress.
let mut p = params.clone();
if let Some(m) = p.as_object_mut() {
m.insert("wait".into(), json!(false));
} else {
p = json!({"wait": false});
}
app.show_panel(PanelKind::RenderQueue);
return app.session.execute(id, p).map_err(|e| e.to_string());
}
if id == "renderQueue.add" {
let r = app.session.execute(id, params).map_err(|e| e.to_string());
match &r {
Ok(_) => app.show_panel(PanelKind::RenderQueue),
Err(e) => app.ui.status = e.clone(),
}
return r;
}
if id == "layer.rename" && params.get("name").is_none() {
crate::panels::timeline::begin_rename(app, ctx);
return Ok(Value::Null);
+357
View File
@@ -0,0 +1,357 @@
//! Composition Settings dialog (also New Composition), laid out like After Effects': name, then
//! Basic / Advanced / 3D Renderer tabs, Preview checkbox, Cancel / OK.
use effectcraft_engine::time::{FrameRate, format_timecode_frames, parse_timecode};
use egui::{Color32, vec2};
use serde_json::json;
use crate::theme::Tokens;
/// AE's composition presets: (name, width, height, pixel aspect, fps). "Custom" is implicit.
pub const PRESETS: &[(&str, u32, u32, f64, f64)] = &[
("Social Media Portrait HD · 1080x1920 · 30 fps", 1080, 1920, 1.0, 30.0),
("Social Media Landscape HD · 1920x1080 · 30 fps", 1920, 1080, 1.0, 30.0),
("Social Media Square · 1080x1080 · 30 fps", 1080, 1080, 1.0, 30.0),
("Social Media Portrait · 1080x1350 · 30 fps", 1080, 1350, 1.0, 30.0),
("NTSC DV", 720, 480, 0.9091, 29.97),
("NTSC DV Widescreen", 720, 480, 1.2121, 29.97),
("NTSC D1", 720, 486, 0.9091, 29.97),
("NTSC D1 Widescreen", 720, 486, 1.2121, 29.97),
("NTSC D1 Square Pix", 720, 540, 1.0, 29.97),
("NTSC D1 Widescreen Square Pix", 872, 486, 1.0, 29.97),
("PAL D1/DV", 720, 576, 1.0940, 25.0),
("PAL D1/DV Widescreen", 720, 576, 1.4587, 25.0),
("PAL D1/DV Square Pix", 788, 576, 1.0, 25.0),
("PAL D1/DV Widescreen Square Pix", 1050, 576, 1.0, 25.0),
("HDV/HDTV 720 29.97", 1280, 720, 1.0, 29.97),
("HDV/HDTV 720 25", 1280, 720, 1.0, 25.0),
("DVCPRO HD 720 23.976", 960, 720, 1.3333, 23.976),
("DVCPRO HD 720 25", 960, 720, 1.3333, 25.0),
("DVCPRO HD 720 29.97", 960, 720, 1.3333, 29.97),
("HDTV 1080 24", 1920, 1080, 1.0, 24.0),
("HDTV 1080 25", 1920, 1080, 1.0, 25.0),
("HDTV 1080 29.97", 1920, 1080, 1.0, 29.97),
("HDV 1080 25", 1440, 1080, 1.3333, 25.0),
("HDV 1080 29.97", 1440, 1080, 1.3333, 29.97),
("DVCPRO HD 1080 25", 1440, 1080, 1.3333, 25.0),
("DVCPRO HD 1080 29.97", 1280, 1080, 1.5, 29.97),
("Cineon Half", 1828, 1332, 1.0, 24.0),
("Cineon Full", 3656, 2664, 1.0, 24.0),
("Film (2K)", 2048, 1556, 1.0, 24.0),
("Film (4K)", 4096, 3112, 1.0, 24.0),
("UHD 4K 23.976", 3840, 2160, 1.0, 23.976),
("UHD 4K 25", 3840, 2160, 1.0, 25.0),
("UHD 4K 29.97", 3840, 2160, 1.0, 29.97),
("UHD 8K 23.976", 7680, 4320, 1.0, 23.976),
("UHD 8K 25", 7680, 4320, 1.0, 25.0),
("UHD 8K 29.97", 7680, 4320, 1.0, 29.97),
];
/// AE's Pixel Aspect Ratio choices.
pub const PIXEL_ASPECTS: &[(&str, f64)] = &[
("Square Pixels", 1.0),
("D1/DV NTSC (0.91)", 0.9091),
("D1/DV NTSC Widescreen (1.21)", 1.2121),
("D1/DV PAL (1.09)", 1.0940),
("D1/DV PAL Widescreen (1.46)", 1.4587),
("Anamorphic 2:1 (2)", 2.0),
("HDV 1080/DVCPRO HD 720 (1.33)", 1.3333),
("DVCPRO HD 1080 (1.5)", 1.5),
];
const FRAME_RATES: &[f64] = &[8.0, 10.0, 12.0, 12.5, 15.0, 23.976, 24.0, 25.0, 29.97, 30.0, 48.0, 50.0, 59.94, 60.0, 120.0];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Tab {
#[default]
Basic,
Advanced,
Renderer,
}
/// The dialog's working copy.
#[derive(Clone, Debug)]
pub struct CompDraft {
pub name: String,
pub width: u32,
pub height: u32,
pub pixel_aspect: f64,
pub fps: f64,
pub duration: f64,
pub start: f64,
pub bg: [f32; 3],
pub lock_aspect: bool,
pub anchor: u8,
pub shutter_angle: f64,
pub shutter_phase: f64,
pub samples: u32,
pub advanced_3d: bool,
pub tab: Tab,
/// Timecode text being edited (start, duration).
pub start_tc: Option<String>,
pub dur_tc: Option<String>,
}
impl Default for CompDraft {
fn default() -> Self {
CompDraft {
name: "Comp 1".into(),
width: 1920,
height: 1080,
pixel_aspect: 1.0,
fps: 29.97,
duration: 10.0,
start: 0.0,
bg: [0.0, 0.0, 0.0],
lock_aspect: true,
anchor: 4,
shutter_angle: 180.0,
shutter_phase: -90.0,
samples: 16,
advanced_3d: false,
tab: Tab::Basic,
start_tc: None,
dur_tc: None,
}
}
}
/// `16:9 (1.78)`: the nearest small whole-number ratio and its decimal.
pub fn aspect_label(w: f64, h: f64) -> String {
let r = w / h.max(1.0);
let best = (1..=32u32).map(|b| ((r * b as f64).round() as u32, b)).filter(|(a, _)| *a > 0).find(|(a, b)| (*a as f64 / *b as f64 - r).abs() < 0.006);
match best {
Some((a, b)) => format!("{a}:{b} ({r:.2})"),
None => format!("{r:.2}"),
}
}
/// AE's name for a background color when it is one of the obvious ones.
fn color_name(c: [f32; 3]) -> &'static str {
match c.map(|v| (v * 255.0).round() as u8) {
[0, 0, 0] => "Black",
[255, 255, 255] => "White",
_ => "",
}
}
/// AE prints the hour without a leading zero: `0;00;10;00`.
fn ae_timecode(smpte: &str) -> String {
let (neg, rest) = smpte.strip_prefix('-').map_or((false, smpte), |r| (true, r));
let rest = rest.strip_prefix('0').filter(|r| r.as_bytes().first().is_some_and(u8::is_ascii_digit)).unwrap_or(rest);
format!("{}{rest}", if neg { "-" } else { "" })
}
fn timecode_field(ui: &mut egui::Ui, buf: &mut Option<String>, secs: &mut f64, rate: FrameRate, min_frames: i64) {
let df = rate.supports_drop_frame();
// Durations are whole frames in AE: 10 s at 29.97 fps is 0;00;10;00, not 9;29.
let shown = ae_timecode(&format_timecode_frames((*secs * rate.as_f64()).round() as i64, rate, df));
let mut text = buf.clone().unwrap_or_else(|| shown.clone());
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(96.0).font(Tokens::mono(12.0)));
if r.changed() {
*buf = Some(text.clone());
}
if r.lost_focus() {
if let Ok(f) = parse_timecode(&text, rate, df, 0) {
*secs = rate.tick_of(f.max(min_frames)).seconds();
}
*buf = None;
}
let base = format!("Base {}{}", rate.timecode_base(), if df { "drop" } else { "" });
ui.label(egui::RichText::new(format!("is {shown} {base}")).color(Color32::GRAY));
}
/// Draw the dialog. Returns `Some(params)` when OK is pressed, `Some(Null)` on Cancel.
pub fn show(ui: &mut egui::Ui, d: &mut CompDraft, t: &Tokens) -> Option<serde_json::Value> {
let mut out = None;
ui.horizontal(|ui| {
ui.label("Composition Name:");
ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(300.0));
});
ui.add_space(8.0);
ui.horizontal(|ui| {
for (tab, label) in [(Tab::Basic, "Basic"), (Tab::Advanced, "Advanced"), (Tab::Renderer, "3D Renderer")] {
if ui.selectable_label(d.tab == tab, label).clicked() {
d.tab = tab;
}
}
});
ui.separator();
let rate = FrameRate::from_f64(d.fps);
match d.tab {
Tab::Basic => {
egui::Grid::new("comp-basic").num_columns(2).spacing([12.0, 9.0]).show(ui, |ui| {
ui.label("Preset:");
let current = PRESETS
.iter()
.find(|(_, w, h, par, f)| *w == d.width && *h == d.height && (par - d.pixel_aspect).abs() < 1e-3 && (f - d.fps).abs() < 1e-3)
.map(|p| p.0)
.unwrap_or("Custom");
egui::ComboBox::from_id_salt("comp-preset").width(300.0).selected_text(current).show_ui(ui, |ui| {
for (name, w, h, par, f) in PRESETS {
if ui.selectable_label(*name == current, *name).clicked() {
(d.width, d.height, d.pixel_aspect, d.fps) = (*w, *h, *par, *f);
}
}
});
ui.end_row();
ui.label("Width:");
ui.horizontal(|ui| {
let (ow, oh) = (d.width, d.height);
ui.add(egui::DragValue::new(&mut d.width).range(4..=30000).suffix(" px"));
let lbl = format!("Lock Aspect Ratio to {}", aspect_label(ow as f64, oh as f64));
ui.checkbox(&mut d.lock_aspect, lbl);
if d.lock_aspect && ow != d.width && ow > 0 {
d.height = ((d.width as f64) * oh as f64 / ow as f64).round().max(4.0) as u32;
}
});
ui.end_row();
ui.label("Height:");
let (ow, oh) = (d.width, d.height);
ui.add(egui::DragValue::new(&mut d.height).range(4..=30000).suffix(" px"));
if d.lock_aspect && oh != d.height && oh > 0 {
d.width = ((d.height as f64) * ow as f64 / oh as f64).round().max(4.0) as u32;
}
ui.end_row();
ui.label("Pixel Aspect Ratio:");
ui.horizontal(|ui| {
let cur = PIXEL_ASPECTS
.iter()
.find(|(_, v)| (v - d.pixel_aspect).abs() < 1e-3)
.map(|p| p.0.to_string())
.unwrap_or_else(|| format!("{:.2}", d.pixel_aspect));
egui::ComboBox::from_id_salt("comp-par").width(220.0).selected_text(cur).show_ui(ui, |ui| {
for (name, v) in PIXEL_ASPECTS {
if ui.selectable_label((v - d.pixel_aspect).abs() < 1e-3, *name).clicked() {
d.pixel_aspect = *v;
}
}
});
ui.label(
egui::RichText::new(format!("Frame Aspect Ratio: {}", aspect_label(d.width as f64 * d.pixel_aspect, d.height as f64)))
.color(Color32::GRAY),
);
});
ui.end_row();
ui.label("Frame Rate:");
ui.horizontal(|ui| {
let txt = format!("{:.3}", d.fps).trim_end_matches('0').trim_end_matches('.').to_string();
egui::ComboBox::from_id_salt("comp-fps").width(80.0).selected_text(txt).show_ui(ui, |ui| {
for f in FRAME_RATES {
if ui.selectable_label((d.fps - f).abs() < 1e-3, format!("{f}")).clicked() {
d.fps = *f;
}
}
});
ui.label("frames per second");
if rate.supports_drop_frame() {
ui.label(egui::RichText::new("Drop Frame").color(Color32::GRAY));
}
});
ui.end_row();
ui.label("");
let mb = d.width as f64 * d.height as f64 * 4.0 / (1024.0 * 1024.0);
ui.label(egui::RichText::new(format!("{} x {}, {mb:.1}MB per 8bpc frame", d.width, d.height)).color(Color32::GRAY));
ui.end_row();
ui.label("Start Timecode:");
ui.horizontal(|ui| timecode_field(ui, &mut d.start_tc, &mut d.start, rate, i64::MIN / 4));
ui.end_row();
ui.label("Duration:");
ui.horizontal(|ui| timecode_field(ui, &mut d.dur_tc, &mut d.duration, rate, 1));
ui.end_row();
ui.label("Background Color:");
ui.horizontal(|ui| {
ui.color_edit_button_rgb(&mut d.bg);
ui.label(color_name(d.bg));
});
ui.end_row();
});
}
Tab::Advanced => {
egui::Grid::new("comp-adv").num_columns(2).spacing([12.0, 9.0]).show(ui, |ui| {
ui.label("Anchor:");
egui::Grid::new("comp-anchor").spacing([2.0, 2.0]).show(ui, |ui| {
for i in 0..9u8 {
let on = d.anchor == i;
let b = egui::Button::new(if on { "●" } else { "" }).min_size(vec2(22.0, 22.0)).fill(if on { t.accent } else { t.field_bg });
if ui.add(b).clicked() {
d.anchor = i;
}
if i % 3 == 2 {
ui.end_row();
}
}
});
ui.end_row();
ui.label(egui::RichText::new("Motion Blur").strong());
ui.end_row();
ui.label("Shutter Angle:");
ui.add(egui::DragValue::new(&mut d.shutter_angle).range(0.0..=720.0).suffix("°"));
ui.end_row();
ui.label("Shutter Phase:");
ui.add(egui::DragValue::new(&mut d.shutter_phase).range(-360.0..=360.0).suffix("°"));
ui.end_row();
ui.label("Samples Per Frame:");
ui.add(egui::DragValue::new(&mut d.samples).range(2..=64));
ui.end_row();
});
}
Tab::Renderer => {
ui.horizontal(|ui| {
ui.label("Renderer:");
egui::ComboBox::from_id_salt("comp-renderer").selected_text(if d.advanced_3d { "Advanced 3D" } else { "Classic 3D" }).show_ui(ui, |ui| {
ui.selectable_value(&mut d.advanced_3d, false, "Classic 3D");
ui.selectable_value(&mut d.advanced_3d, true, "Advanced 3D");
});
});
}
}
ui.add_space(14.0);
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
out = Some(params(d));
}
if ui.button("Cancel").clicked() {
out = Some(serde_json::Value::Null);
}
});
});
out
}
/// `comp.new` / `comp.settings` parameters for the draft.
pub fn params(d: &CompDraft) -> serde_json::Value {
json!({
"name": d.name, "width": d.width, "height": d.height, "pixelAspect": d.pixel_aspect, "frameRate": d.fps,
"duration": d.duration, "startTime": d.start, "background": [d.bg[0], d.bg[1], d.bg[2]], "anchor": d.anchor,
"shutterAngle": d.shutter_angle, "shutterPhase": d.shutter_phase, "motionBlurSamples": d.samples,
"renderer": if d.advanced_3d { "advanced3D" } else { "classic3D" },
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn aspect_labels_match_ae() {
assert_eq!(aspect_label(1920.0, 1080.0), "16:9 (1.78)");
assert_eq!(aspect_label(1080.0, 1080.0), "1:1 (1.00)");
assert_eq!(aspect_label(1080.0, 1350.0), "4:5 (0.80)");
assert_eq!(aspect_label(720.0 * 0.9091, 480.0), "15:11 (1.36)");
}
#[test]
fn ae_timecode_drops_hour_padding() {
assert_eq!(ae_timecode("00;00;10;00"), "0;00;10;00");
assert_eq!(ae_timecode("12:00:00:00"), "12:00:00:00");
assert_eq!(ae_timecode("-00:00:01:00"), "-0:00:01:00");
}
#[test]
fn presets_resolve_by_value() {
let p = PRESETS.iter().find(|p| p.0 == "HDTV 1080 29.97").unwrap();
assert_eq!((p.1, p.2), (1920, 1080));
}
}
+74 -112
View File
@@ -8,22 +8,7 @@ use crate::icons::{self, Icon};
use crate::theme::Tokens;
use crate::{Dialog, EffectcraftApp};
#[derive(Clone, Debug)]
pub struct CompDraft {
pub name: String,
pub width: u32,
pub height: u32,
pub fps: f64,
pub duration: f64,
pub bg: [f32; 3],
pub lock_aspect: bool,
}
impl Default for CompDraft {
fn default() -> Self {
CompDraft { name: "Comp 1".into(), width: 1920, height: 1080, fps: 29.97, duration: 10.0, bg: [0.0, 0.0, 0.0], lock_aspect: true }
}
}
pub use super::comp_settings::CompDraft;
#[derive(Clone, Debug, Default)]
pub struct DialogState {
@@ -36,6 +21,9 @@ pub struct DialogState {
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) {
@@ -52,10 +40,16 @@ pub fn open_comp_settings(app: &mut EffectcraftApp) -> Result<(), String> {
name: app.session.project.item(cid).map(|i| i.name.clone()).unwrap_or_default(),
width: c.width,
height: c.height,
pixel_aspect: c.pixel_aspect,
fps: c.frame_rate.as_f64(),
duration: c.duration.seconds(),
start: c.display_start.seconds(),
bg: c.background,
lock_aspect: true,
shutter_angle: c.shutter_angle,
shutter_phase: c.shutter_phase,
samples: c.motion_blur_samples,
advanced_3d: c.renderer == effectcraft_engine::project::Renderer::Advanced3D,
..Default::default()
};
app.dialog_state.editing_existing = true;
app.dialog = Some(Dialog::CompSettings);
@@ -99,6 +93,9 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context) {
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),
}
}
@@ -176,93 +173,25 @@ fn about(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
}
fn comp_settings(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens, existing: bool) {
let mut close = false;
let mut ok = false;
let mut d = app.dialog_state.comp.clone();
modal(ctx, if existing { "Composition Settings" } else { "Composition Settings — New" }, vec2(520.0, 420.0), t, |ui| {
egui::Grid::new("comp-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
ui.label("Composition Name");
ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(260.0));
ui.end_row();
ui.label("Preset");
egui::ComboBox::from_id_salt("comp-preset").selected_text(format!("{}x{} {:.2}", d.width, d.height, d.fps)).show_ui(ui, |ui| {
for (label, w, h, f) in [
("HD · 1920x1080 · 29.97 fps", 1920, 1080, 29.97),
("HD · 1920x1080 · 25 fps", 1920, 1080, 25.0),
("HD · 1920x1080 · 23.976 fps", 1920, 1080, 23.976),
("HD · 1280x720 · 29.97 fps", 1280, 720, 29.97),
("UHD 4K · 3840x2160 · 29.97 fps", 3840, 2160, 29.97),
("Social 9:16 · 1080x1920 · 30 fps", 1080, 1920, 30.0),
("Social 1:1 · 1080x1080 · 30 fps", 1080, 1080, 30.0),
("Social 4:5 · 1080x1350 · 30 fps", 1080, 1350, 30.0),
("Cinema 4K · 4096x2160 · 24 fps", 4096, 2160, 24.0),
] {
if ui.selectable_label(false, label).clicked() {
d.width = w;
d.height = h;
d.fps = f;
}
}
});
ui.end_row();
ui.label("Width / Height");
ui.horizontal(|ui| {
let ow = d.width;
ui.add(egui::DragValue::new(&mut d.width).range(4..=30000).suffix(" px"));
ui.label("×");
let oh = d.height;
ui.add(egui::DragValue::new(&mut d.height).range(4..=30000).suffix(" px"));
ui.checkbox(&mut d.lock_aspect, "Lock aspect");
if d.lock_aspect && ow != d.width && ow > 0 {
d.height = ((d.width as f64) * oh as f64 / ow as f64).round().max(4.0) as u32;
}
});
ui.end_row();
ui.label("Frame Rate");
egui::ComboBox::from_id_salt("comp-fps").selected_text(format!("{:.3}", d.fps).trim_end_matches('0').trim_end_matches('.').to_string()).show_ui(
ui,
|ui| {
for f in [23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 120.0] {
if ui.selectable_label((d.fps - f).abs() < 1e-3, format!("{f}")).clicked() {
d.fps = f;
}
}
},
);
ui.end_row();
ui.label("Duration");
ui.add(egui::DragValue::new(&mut d.duration).range(0.04..=86400.0).speed(0.1).suffix(" s"));
ui.end_row();
ui.label("Background Color");
ui.color_edit_button_rgb(&mut d.bg);
ui.end_row();
});
ui.add_space(18.0);
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
ok = true;
}
if ui.button("Cancel").clicked() {
close = true;
}
});
});
let mut result = None;
modal(ctx, "Composition Settings", vec2(600.0, 470.0), t, |ui| {
result = super::comp_settings::show(ui, &mut d, t);
});
if ui_enter(ctx) {
ok = true;
if result.is_none() && ui_enter(ctx) {
result = Some(super::comp_settings::params(&d));
}
app.dialog_state.comp = d.clone();
if ok {
let params = json!({"name": d.name, "width": d.width, "height": d.height, "frameRate": d.fps, "duration": d.duration, "background": [d.bg[0], d.bg[1], d.bg[2]]});
let r = if existing { app.session.execute("comp.settings", params) } else { app.session.execute("comp.new", params) };
if let Err(e) = r {
app.ui.status = e.to_string();
app.dialog_state.comp = d;
match result {
Some(serde_json::Value::Null) => app.dialog = None,
Some(params) => {
let r = if existing { app.session.execute("comp.settings", params) } else { app.session.execute("comp.new", params) };
if let Err(e) = r {
app.ui.status = e.to_string();
}
app.dialog = None;
}
close = true;
}
if close {
app.dialog = None;
None => {}
}
}
@@ -276,23 +205,55 @@ fn solid(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut name = app.dialog_state.solid_name.clone();
let mut col = app.dialog_state.solid_color;
let mut size = app.dialog_state.solid_size;
modal(ctx, "Solid Settings", vec2(420.0, 300.0), t, |ui| {
egui::Grid::new("solid-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
ui.label("Name");
ui.add(egui::TextEdit::singleline(&mut name).desired_width(220.0));
ui.end_row();
ui.label("Size");
let comp_size = app.session.active_comp().map(|c| (c.width, c.height)).unwrap_or((1920, 1080));
let lock_id = egui::Id::new("solid-lock-aspect");
let mut lock = ctx.data(|d| d.get_temp::<bool>(lock_id)).unwrap_or(true);
modal(ctx, "Solid Settings", vec2(460.0, 360.0), t, |ui| {
ui.horizontal(|ui| {
ui.label("Name:");
ui.add(egui::TextEdit::singleline(&mut name).desired_width(320.0));
});
ui.add_space(8.0);
ui.label(egui::RichText::new("Size").strong());
egui::Grid::new("solid-grid").num_columns(2).spacing([14.0, 8.0]).show(ui, |ui| {
let (ow, oh) = (size[0], size[1]);
ui.label("Width:");
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut size[0]).range(1..=30000));
ui.label("×");
ui.add(egui::DragValue::new(&mut size[1]).range(1..=30000));
ui.add(egui::DragValue::new(&mut size[0]).range(1..=30000).suffix(" px"));
ui.checkbox(&mut lock, format!("Lock Aspect Ratio to {}", super::comp_settings::aspect_label(ow as f64, oh as f64)));
});
ui.end_row();
ui.label("Color");
ui.color_edit_button_rgb(&mut col);
ui.label("Height:");
ui.add(egui::DragValue::new(&mut size[1]).range(1..=30000).suffix(" px"));
ui.end_row();
if lock && ow > 0 && oh > 0 {
if size[0] != ow {
size[1] = ((size[0] as f64) * oh as f64 / ow as f64).round().max(1.0) as u32;
} else if size[1] != oh {
size[0] = ((size[1] as f64) * ow as f64 / oh as f64).round().max(1.0) as u32;
}
}
});
ui.add_space(18.0);
let pct = |a: u32, b: u32| 100.0 * a as f64 / b.max(1) as f64;
ui.label(
egui::RichText::new(format!(
"Width: {:.1}% of comp\nHeight: {:.1}% of comp\nFrame Aspect Ratio: {}",
pct(size[0], comp_size.0),
pct(size[1], comp_size.1),
super::comp_settings::aspect_label(size[0] as f64, size[1] as f64)
))
.color(Color32::GRAY),
);
ui.add_space(4.0);
if ui.button("Make Comp Size").clicked() {
size = [comp_size.0, comp_size.1];
}
ui.add_space(8.0);
ui.horizontal(|ui| {
ui.label("Color:");
ui.color_edit_button_rgb(&mut col);
});
ui.add_space(14.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
ok = true;
@@ -302,6 +263,7 @@ fn solid(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
}
});
});
ctx.data_mut(|d| d.insert_temp(lock_id, lock));
app.dialog_state.solid_name = name.clone();
app.dialog_state.solid_color = col;
app.dialog_state.solid_size = size;
+71 -68
View File
@@ -1,5 +1,4 @@
//! Effect Controls (the selected layer's effects with all parameters) and the Properties panel
//! (essential properties: transform + text/shape basics).
//! Effect Controls: the selected layer's effects with all parameters.
use effectcraft_engine::keyframe::Value;
use effectcraft_engine::project::{GroupKind, Layer, Node, ParamUi, PropGroup, Property};
@@ -90,24 +89,18 @@ fn prop_row(
if let Some(nv) = nv {
set(actions, json!(nv));
}
// Slider track for slider params.
if let ParamUi::Slider { slider_min, slider_max, .. } = prop.ui {
let tr = Rect::from_min_max(pos2(vr.max.x + 10.0, cy - 2.0), pos2(r.max.x - 12.0, cy + 2.0));
if tr.width() > 40.0 {
p.rect_filled(tr, 2.0, t.field_bg);
let f = ((v - slider_min) / (slider_max - slider_min)).clamp(0.0, 1.0) as f32;
p.rect_filled(Rect::from_min_max(tr.min, pos2(tr.min.x + tr.width() * f, tr.max.y)), 2.0, t.accent.gamma_multiply(0.7));
let knob = pos2(tr.min.x + tr.width() * f, cy);
p.circle_filled(knob, 5.0, t.text);
let sresp = ui.interact(tr.expand2(vec2(4.0, 6.0)), egui::Id::new(("ec-slider", uid)), Sense::click_and_drag());
app.auto.add(&format!("effectControls.prop.{uid}.slider"), tr, &prop.name);
if (sresp.dragged() || sresp.clicked())
&& let Some(pt) = sresp.interact_pointer_pos()
{
let f = ((pt.x - tr.min.x) / tr.width()).clamp(0.0, 1.0) as f64;
set(actions, json!(slider_min + (slider_max - slider_min) * f));
// AE hides a slider param's slider until its twirl is opened (see `slider_row`).
if matches!(prop.ui, ParamUi::Slider { .. }) {
let open = app.ui.fx_slider_open.contains(&uid);
let tw = Rect::from_center_size(pos2(swr.min.x - 9.0, cy), vec2(10.0, 10.0));
if widgets::twirl(ui, tw, open, egui::Id::new(("ec-stw", uid)), &t).clicked() {
if open {
app.ui.fx_slider_open.remove(&uid);
} else {
app.ui.fx_slider_open.insert(uid);
}
}
app.auto.add(&format!("effectControls.prop.{uid}.twirl"), tw, &prop.name);
}
}
Value::Vec2(_) | Value::Vec3(_) => {
@@ -140,13 +133,6 @@ fn prop_row(
if crate::header::color_popup(ui, pop, sr.left_bottom(), &mut rgb) {
set(actions, json!([rgb[0], rgb[1], rgb[2], 1.0]));
}
p.text(
pos2(sr.max.x + 8.0, cy),
Align2::LEFT_CENTER,
effectcraft_engine::color::Rgba::from_array([c[0] as f32, c[1] as f32, c[2] as f32, 1.0]).to_hex(),
Tokens::mono(11.0),
t.text_dim,
);
}
Value::Bool(b) => {
let cr = Rect::from_min_size(pos2(vx, cy - 8.0), vec2(16.0, 16.0));
@@ -188,6 +174,48 @@ fn prop_row(
}
}
/// The twirled-open slider under a slider param: track, knob and the slider range's ends.
#[allow(clippy::too_many_arguments)]
fn slider_row(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
prop: &Property,
ectx: &EvalCtx,
r: Rect,
x0: f32,
actions: &mut Actions,
) {
let t = app.tokens;
let ParamUi::Slider { slider_min, slider_max, decimals, .. } = prop.ui else { return };
let Value::Scalar(v) = ectx.value(layer, prop) else { return };
let uid = prop.uid;
let tr = Rect::from_min_max(pos2(r.min.x + x0, r.min.y + 8.0), pos2(r.max.x - 16.0, r.min.y + 12.0));
if tr.width() < 40.0 {
return;
}
p.rect_filled(tr, 2.0, t.field_bg);
let f = ((v - slider_min) / (slider_max - slider_min)).clamp(0.0, 1.0) as f32;
p.rect_filled(Rect::from_min_max(tr.min, pos2(tr.min.x + tr.width() * f, tr.max.y)), 2.0, t.accent.gamma_multiply(0.7));
p.circle_filled(pos2(tr.min.x + tr.width() * f, tr.center().y), 5.0, t.text);
let dec = decimals as usize;
p.text(pos2(tr.min.x, tr.max.y + 4.0), Align2::LEFT_TOP, format!("{slider_min:.dec$}"), Tokens::ui(10.5), t.text_dim);
p.text(pos2(tr.max.x, tr.max.y + 4.0), Align2::RIGHT_TOP, format!("{slider_max:.dec$}"), Tokens::ui(10.5), t.text_dim);
let sresp = ui.interact(tr.expand2(vec2(4.0, 6.0)), egui::Id::new(("ec-slider", uid)), Sense::click_and_drag());
app.auto.add(&format!("effectControls.prop.{uid}.slider"), tr, &prop.name);
if (sresp.dragged() || sresp.clicked())
&& let Some(pt) = sresp.interact_pointer_pos()
{
let f = ((pt.x - tr.min.x) / tr.width()).clamp(0.0, 1.0) as f64;
actions.push((
"prop.set".into(),
json!({"layer": layer.id.0, "prop": uid, "value": slider_min + (slider_max - slider_min) * f, "merge": format!("ec-{uid}")}),
));
}
}
#[allow(clippy::too_many_arguments)]
fn group_rows(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
@@ -213,6 +241,11 @@ fn group_rows(
continue;
}
prop_row(app, ui, p, layer, pr, ectx, r, 24.0 + 14.0 * depth as f32, actions);
if app.ui.fx_slider_open.contains(&pr.uid) {
let sr = Rect::from_min_size(pos2(rect.min.x, *y), vec2(rect.width(), 34.0));
*y += 34.0;
slider_row(app, ui, p, layer, pr, ectx, sr, 24.0 + 14.0 * depth as f32 + 22.0, actions);
}
}
Node::Group(sg) => {
*y += 24.0;
@@ -292,7 +325,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
bp.text(pos2(tw.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, &g.name, Tokens::semibold(12.0), t.text);
let reset = Rect::from_min_size(pos2(r.max.x - 92.0, r.min.y + 4.0), vec2(40.0, 18.0));
let reset = Rect::from_min_size(pos2(r.max.x - 96.0, r.min.y + 4.0), vec2(40.0, 18.0));
let rresp = ui.interact(reset, egui::Id::new(("ec-reset", g.uid)), Sense::click());
bp.text(reset.center(), Align2::CENTER_CENTER, "Reset", Tokens::ui(11.5), if rresp.hovered() { t.hot_text } else { t.text_dim });
app.auto.add(&format!("effectControls.effect.{}.reset", g.uid), reset, "Reset");
@@ -310,11 +343,19 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
let rm = Rect::from_min_size(pos2(r.max.x - 28.0, r.min.y + 4.0), vec2(18.0, 18.0));
if widgets::icon_button(ui, rm, Icon::Close, false, &t, egui::Id::new(("ec-rm", g.uid))).on_hover_text("Remove effect").clicked() {
actions.push(("effect.remove".into(), json!({"layer": layer.id.0, "effect": g.uid})));
// About…: the effect's name and category (AE's About dialog).
let about = Rect::from_min_size(pos2(r.max.x - 50.0, r.min.y + 4.0), vec2(44.0, 18.0));
let aresp = ui.interact(about, egui::Id::new(("ec-about", g.uid)), Sense::click());
bp.text(about.center(), Align2::CENTER_CENTER, "About...", Tokens::ui(11.5), if aresp.hovered() { t.hot_text } else { t.text_dim });
app.auto.add(&format!("effectControls.effect.{}.about", g.uid), about, "About");
let apop = egui::Id::new(("ec-about-pop", g.uid));
if aresp.clicked() {
widgets::open_popup(ui, apop);
}
if let Some(spec) = g.kind_effect().and_then(effectcraft_engine::effects::find) {
let lines = vec![spec.name.to_string(), format!("Category: {}", spec.category), "EffectCraft built-in effect (MIT OR Apache-2.0)".to_string()];
let _ = widgets::popup_menu(ui, apop, about.left_bottom(), &lines, None);
}
app.auto.add(&format!("effectControls.effect.{}.remove", g.uid), rm, "Remove");
let hresp =
ui.interact(Rect::from_min_max(pos2(tw.max.x, r.min.y), pos2(reset.min.x - 4.0, r.max.y)), egui::Id::new(("ec-hdr", g.uid)), Sense::click());
app.auto.add(&format!("effectControls.effect.{}", g.uid), r, &g.name);
@@ -376,41 +417,3 @@ impl EffectKind for PropGroup {
}
}
}
/// Properties panel: the selected layer's transform (and text basics), always visible.
pub fn properties(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
let ctx = ui.ctx().clone();
let Some(layer) = selected_layer(app) else {
p.text(rect.center(), Align2::CENTER_CENTER, "Select a layer", Tokens::ui(12.0), t.text_faint);
return;
};
let Some(cid) = app.session.active_comp_id() else { return };
let comp = app.session.project.comp(cid).cloned().unwrap_or_else(|| effectcraft_engine::project::Comp::new(1, 1, Default::default(), Default::default()));
let snap_project = app.session.project.clone();
let snap_expr = app.session.expr.clone();
let ectx = EvalCtx { project: &snap_project, comp_id: cid, comp: &comp, time: app.session.time(), expr: snap_expr.as_deref() };
let mut y = rect.min.y + 8.0;
p.text(pos2(rect.min.x + 10.0, y + 8.0), Align2::LEFT_CENTER, &layer.name, Tokens::semibold(13.0), t.text);
p.text(pos2(rect.min.x + 10.0, y + 24.0), Align2::LEFT_CENTER, layer.source.type_name(), Tokens::ui(11.0), t.text_dim);
y += 40.0;
let mut actions: Actions = vec![];
if let Some(tr) = layer.transform().cloned() {
p.text(pos2(rect.min.x + 10.0, y + 10.0), Align2::LEFT_CENTER, "Layer Transform", Tokens::semibold(12.0), t.text);
y += 24.0;
for pr in tr.props() {
if pr.three_d_only && !layer.is_3d() {
continue;
}
let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), 24.0));
prop_row(app, ui, &p, &layer, pr, &ectx, r, 16.0, &mut actions);
y += 24.0;
}
}
for (id, params) in actions {
if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) {
app.ui.status = e;
}
}
}
+452
View File
@@ -0,0 +1,452 @@
//! The Graph Editor (Timeline ▸ Shift+F3): value graph and speed graph of the selected (or all
//! animated) properties, keyframes you can drag in time and value, Bezier/influence handles on
//! selected keys, auto-zoom / fit, and the bottom button bar (graph type, show selected,
//! auto-zoom, fit, separate dimensions, hold/linear/auto Bezier, Easy Ease family).
//!
//! Every edit is an engine command (`keys.set`, `keys.setEase`, `keys.select`, `keys.*`).
use effectcraft_engine::KeyRef;
use effectcraft_engine::keyframe::{Interp, Value, side_ease};
use effectcraft_engine::project::{Comp, Layer, LayerId, Property};
use effectcraft_engine::render::EvalCtx;
use effectcraft_engine::time::Tick;
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde_json::json;
use super::timeline::TMap;
use crate::EffectcraftApp;
use crate::theme::Tokens;
type Actions = Vec<(String, serde_json::Value)>;
const DIM_COLORS: [Color32; 4] =
[Color32::from_rgb(0xe0, 0x55, 0x55), Color32::from_rgb(0x5c, 0xc8, 0x5c), Color32::from_rgb(0x50, 0x8c, 0xf0), Color32::from_rgb(0xe8, 0xc8, 0x40)];
const PROP_COLORS: [Color32; 6] = [
Color32::from_rgb(0xe8, 0xc8, 0x40),
Color32::from_rgb(0xd0, 0x70, 0xe0),
Color32::from_rgb(0x40, 0xc8, 0xc8),
Color32::from_rgb(0xf0, 0x90, 0x40),
Color32::from_rgb(0x9c, 0xd8, 0x50),
Color32::from_rgb(0xf0, 0x70, 0x90),
];
struct Handle {
out: bool,
/// Comp seconds / graph value of the handle end.
t: f64,
v: f64,
/// Original speed (sign is kept when dragging in the speed graph).
speed: f64,
/// Segment duration (layer seconds) the influence is relative to.
dur: f64,
}
struct KeyPt {
idx: usize,
time: Tick,
/// Comp seconds.
t: f64,
v: f64,
sel: bool,
handles: Vec<Handle>,
}
struct Curve<'a> {
layer: &'a Layer,
prop: &'a Property,
dim: usize,
color: Color32,
pts: Vec<(f64, f64)>,
keys: Vec<KeyPt>,
/// Values editable in the value graph (not spatial / combined dimensions).
editable: bool,
}
/// Properties shown: the selected ones, or every animated property of the selected layers.
fn shown_props(app: &EffectcraftApp, comp: &Comp) -> Vec<(LayerId, u64)> {
let st = &app.session.state;
let numeric = |pr: &Property| !pr.value.components().is_empty() && pr.value.interpolates();
if app.ui.timeline.graph_show_selected && !st.selected_props.is_empty() {
return st.selected_props.iter().filter(|(l, u)| comp.layer(*l).and_then(|l| l.props.find(*u)).is_some_and(numeric)).copied().collect();
}
let mut v = vec![];
for l in comp.layers.iter().filter(|l| st.selected_layers.contains(&l.id)) {
l.props.walk("", &mut |_, pr| {
if (pr.is_animated() || pr.has_expression()) && numeric(pr) {
v.push((l.id, pr.uid));
}
});
}
v
}
fn shown_dims(l: &Layer, pr: &Property) -> usize {
let n = pr.value.components().len();
if pr.shown_dims > 0 && !l.is_3d() { (pr.shown_dims as usize).min(n) } else { n.min(4) }
}
/// Build the curves for the visible time span.
fn curves<'a>(app: &EffectcraftApp, comp: &'a Comp, ectx: &EvalCtx, tm: TMap, plot: Rect, speed: bool) -> Vec<Curve<'a>> {
let sel = &app.session.state.selected_keys;
let n = ((plot.width() / 2.0) as usize).max(2);
let mut out = vec![];
for (pi, (lid, uid)) in shown_props(app, comp).into_iter().enumerate() {
let Some(l) = comp.layer(lid) else { continue };
let Some(pr) = l.props.find(uid) else { continue };
let spatial = pr.spatial && matches!(pr.value, Value::Vec2(_) | Value::Vec3(_));
let dims = if speed && spatial { 1 } else { shown_dims(l, pr) };
for d in 0..dims {
let color = if dims > 1 { DIM_COLORS[d % 4] } else { PROP_COLORS[pi % PROP_COLORS.len()] };
let mut pts = Vec::with_capacity(n);
for i in 0..n {
let x = plot.min.x + plot.width() * i as f32 / (n - 1) as f32;
let ct = tm.t(x);
let tt = Tick::from_seconds_f64(ct);
let v = if speed {
let lt = l.layer_time(tt);
if spatial {
effectcraft_engine::keyframe::speed(&pr.keys, lt, true)
} else {
effectcraft_engine::keyframe::velocity(&pr.keys, lt, false).get(d).copied().unwrap_or(0.0).abs()
}
} else {
ectx.at(tt).value(l, pr).components().get(d).copied().unwrap_or(0.0)
};
pts.push((ct, v));
}
let mut keys = vec![];
for (i, k) in pr.keys.iter().enumerate() {
let ks = sel.contains(&KeyRef { layer: lid, prop: uid, time: k.time });
let kt = l.comp_time(k.time).seconds();
let ed = if spatial { 0 } else { d };
let mut handles = vec![];
let mut side_speeds = vec![];
for out_side in [false, true] {
let Some(e) = side_ease(&pr.keys, i, ed, pr.spatial, out_side) else { continue };
let j = if out_side { i + 1 } else { i - 1 };
let dur = (pr.keys[j].time.seconds() - k.time.seconds()).abs();
side_speeds.push(e.speed.abs());
let dt = e.influence * dur * if out_side { 1.0 } else { -1.0 };
let (hv, show) = if speed { (e.speed.abs(), true) } else { (k.value.components().get(d).copied().unwrap_or(0.0) + e.speed * dt, !spatial) };
let bezier = if out_side { k.out_interp == Interp::Bezier } else { k.in_interp == Interp::Bezier };
if ks && show && (bezier || speed) {
handles.push(Handle { out: out_side, t: kt + dt, v: hv, speed: e.speed, dur });
}
}
let v = if speed {
if side_speeds.is_empty() { 0.0 } else { side_speeds.iter().sum::<f64>() / side_speeds.len() as f64 }
} else {
k.value.components().get(d).copied().unwrap_or(0.0)
};
keys.push(KeyPt { idx: i, time: k.time, t: kt, v, sel: ks, handles });
}
out.push(Curve { layer: l, prop: pr, dim: d, color, pts, keys, editable: !spatial });
}
}
out
}
fn text_button(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, x: &mut f32, y: f32, label: &str, on: bool, id: &str, tip: &str) -> bool {
let t = app.tokens;
let w = p.layout_no_wrap(label.to_string(), Tokens::ui(11.0), t.text).size().x + 14.0;
let r = Rect::from_min_size(pos2(*x, y - 9.0), vec2(w, 18.0));
let resp = ui.interact(r, egui::Id::new(("graph-btn", id)), Sense::click()).on_hover_text(tip);
p.rect_filled(
r,
3.0,
if on {
t.accent.gamma_multiply(0.55)
} else if resp.hovered() {
t.hover
} else {
Color32::from_rgb(0x2c, 0x2c, 0x2c)
},
);
p.text(r.center(), Align2::CENTER_CENTER, label, Tokens::ui(11.0), if on { Color32::WHITE } else { t.text });
app.auto.add(&format!("timeline.graph.{id}"), r, tip);
*x += w + 4.0;
resp.clicked()
}
/// Draw the Graph Editor into `area` (the right side of the Timeline) and queue edits.
pub(crate) fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, comp: &Comp, ectx: &EvalCtx, tm: TMap, area: Rect, actions: &mut Actions) {
let t = app.tokens;
let ctx = ui.ctx().clone();
let footer_h = 28.0;
let plot = Rect::from_min_max(area.min + vec2(0.0, 6.0), pos2(area.max.x, area.max.y - footer_h));
let bar = Rect::from_min_max(pos2(area.min.x, area.max.y - footer_h), area.max);
// Background first so keys and handles (added later) sit on top for hit-testing.
let bg = ui.interact(plot, egui::Id::new("graph-bg"), Sense::click_and_drag());
p.rect_filled(area, 0.0, Color32::from_rgb(0x1d, 0x1d, 0x1d));
app.auto.add("timeline.graph", plot, &app.ui.timeline.graph_mode.clone());
let speed = app.ui.timeline.graph_mode == "speed";
let cs = curves(app, comp, ectx, tm, plot, speed);
// Vertical range: auto-zoom to the curves + handles, or the stored manual range.
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
for c in &cs {
for (_, v) in &c.pts {
lo = lo.min(*v);
hi = hi.max(*v);
}
for k in &c.keys {
for v in std::iter::once(k.v).chain(k.handles.iter().map(|h| h.v)) {
lo = lo.min(v);
hi = hi.max(v);
}
}
}
if !lo.is_finite() {
(lo, hi) = (0.0, 100.0);
}
if speed {
lo = lo.min(0.0);
}
if (hi - lo).abs() < 1e-9 {
hi = lo + 1.0;
}
let pad = (hi - lo) * 0.08;
let auto = (lo - pad, hi + pad);
// While a key or handle is being dragged the scale stays put (no feedback loop).
let drag_id = egui::Id::new("graph-dragging");
let dragging = ctx.data(|d| d.get_temp::<bool>(drag_id)).unwrap_or(false) && ctx.input(|i| i.pointer.any_down());
let (lo, hi) = if app.ui.timeline.graph_auto_zoom && !dragging { auto } else { app.ui.timeline.graph_range.unwrap_or(auto) };
if app.ui.timeline.graph_auto_zoom && !dragging {
app.ui.timeline.graph_range = Some((lo, hi));
}
let ymap = |v: f64| plot.max.y - ((v - lo) / (hi - lo)) as f32 * plot.height();
let vmap = |y: f32| lo + (plot.max.y - y) as f64 / plot.height() as f64 * (hi - lo);
// Grid + value labels.
let pc = p.with_clip_rect(plot);
let step = nice_step((hi - lo) / 6.0);
let mut gv = (lo / step).ceil() * step;
while gv <= hi {
let y = ymap(gv);
pc.line_segment([pos2(plot.min.x, y), pos2(plot.max.x, y)], Stroke::new(1.0, Color32::from_white_alpha(12)));
pc.text(pos2(plot.min.x + 4.0, y - 1.0), Align2::LEFT_BOTTOM, fmt(gv, step), Tokens::ui(10.0), t.text_faint);
gv += step;
}
if cs.is_empty() {
p.text(plot.center(), Align2::CENTER_CENTER, "Select animated properties to show them in the Graph Editor", Tokens::ui(12.0), t.text_faint);
}
// Curves.
for c in &cs {
let pts: Vec<Pos2> = c.pts.iter().map(|(ct, v)| pos2(tm.x(*ct), ymap(*v))).collect();
pc.add(egui::Shape::line(pts, Stroke::new(1.5, c.color)));
}
// Keys and handles.
let mut key_screens: Vec<(serde_json::Value, Pos2)> = vec![];
let fr = comp.frame_rate;
for c in &cs {
let (lid, uid, d) = (c.layer.id, c.prop.uid, c.dim);
for k in &c.keys {
let kp = pos2(tm.x(k.t), ymap(k.v));
if !plot.expand(6.0).contains(kp) {
continue;
}
let kjson = json!({"layer": lid.0, "prop": uid, "time": k.time.seconds()});
key_screens.push((kjson.clone(), kp));
// Handles (selected keys).
for h in &k.handles {
let hp = pos2(tm.x(h.t), ymap(h.v));
pc.line_segment([kp, hp], Stroke::new(1.0, Color32::from_rgb(0xd8, 0xd8, 0x60)));
pc.circle_filled(hp, 3.5, Color32::from_rgb(0xd8, 0xd8, 0x60));
let side = if h.out { "out" } else { "in" };
let hr = Rect::from_center_size(hp, vec2(10.0, 10.0));
let hresp = ui.interact(hr, egui::Id::new(("ghandle", uid, d, k.idx, side)), Sense::drag());
app.auto.add(&format!("timeline.graph.handle.{uid}.{d}.{}.{side}", k.idx), hr, "Bezier handle");
if hresp.dragged()
&& let Some(pt) = hresp.interact_pointer_pos()
{
ctx.data_mut(|dd| dd.insert_temp(drag_id, true));
let mut dt = (tm.t(pt.x) - k.t) * if h.out { 1.0 } else { -1.0 };
dt = dt.max(h.dur * 0.001);
let influence = (dt / h.dur.max(1e-9) * 100.0).clamp(0.1, 100.0);
let sp = if speed {
let mag = vmap(pt.y).max(0.0);
if h.speed < 0.0 { -mag } else { mag }
} else {
let dv = vmap(pt.y) - k.v;
dv / dt * if h.out { 1.0 } else { -1.0 }
};
let mut params = json!({"layer": lid.0, "prop": uid, "time": k.time.seconds(), "side": side, "speed": sp, "influence": influence, "merge": format!("ghandle-{uid}-{}", k.idx)});
if c.editable {
params["dim"] = json!(d);
}
actions.push(("keys.setEase".into(), params));
}
if hresp.drag_stopped() {
ctx.data_mut(|dd| dd.insert_temp(drag_id, false));
actions.push(("__endMerge".into(), json!({})));
}
}
// The key itself.
let col = if k.sel { t.keyframe_selected } else { Color32::from_gray(0xe0) };
pc.rect_filled(Rect::from_center_size(kp, vec2(7.0, 7.0)), 0.0, col);
pc.rect_stroke(Rect::from_center_size(kp, vec2(7.0, 7.0)), 0.0, Stroke::new(1.0, c.color), StrokeKind::Outside);
let kr = Rect::from_center_size(kp, vec2(11.0, 11.0));
let kresp = ui.interact(kr, egui::Id::new(("gkey", uid, d, k.idx)), Sense::click_and_drag());
app.auto.add(&format!("timeline.graph.key.{uid}.{d}.{}", k.idx), kr, &c.prop.name);
let shift = ui.input(|i| i.modifiers.shift);
if (kresp.clicked() || kresp.drag_started()) && (!k.sel || shift) {
actions.push(("keys.select".into(), json!({"keys": [kjson.clone()], "add": shift})));
}
if kresp.dragged()
&& let Some(pt) = kresp.interact_pointer_pos()
{
ctx.data_mut(|dd| dd.insert_temp(drag_id, true));
let merge = format!("gkey-{uid}-{}", k.idx);
let nt = c.layer.layer_time(fr.snap_nearest(Tick::from_seconds_f64(tm.t(pt.x).max(0.0))));
let mut params = json!({"layer": lid.0, "prop": uid, "time": k.time.seconds(), "newTime": nt.seconds(), "merge": merge});
if !speed && c.editable {
let mut comps = c.prop.keys[k.idx].value.components();
if d < comps.len() {
comps[d] = vmap(pt.y);
}
params["value"] = if comps.len() == 1 { json!(comps[0]) } else { json!(comps) };
}
actions.push(("keys.set".into(), params));
}
if kresp.drag_stopped() {
ctx.data_mut(|dd| dd.insert_temp(drag_id, false));
actions.push(("__endMerge".into(), json!({})));
}
}
}
// Background: click deselects keys, drag box-selects.
if bg.clicked() {
actions.push(("keys.select".into(), json!({"keys": []})));
}
if bg.dragged()
&& let (Some(o), Some(cur)) = (ctx.input(|i| i.pointer.press_origin()), bg.interact_pointer_pos())
{
let br = Rect::from_two_pos(o, cur);
pc.rect_filled(br, 0.0, t.accent.gamma_multiply(0.12));
pc.rect_stroke(br, 0.0, Stroke::new(1.0, t.accent), StrokeKind::Middle);
ctx.data_mut(|d| d.insert_temp(egui::Id::new("graph-box"), br));
}
if bg.drag_stopped()
&& let Some(br) = ctx.data(|d| d.get_temp::<Rect>(egui::Id::new("graph-box")))
{
ctx.data_mut(|d| d.remove::<Rect>(egui::Id::new("graph-box")));
let keys: Vec<serde_json::Value> = key_screens.iter().filter(|(_, sp)| br.contains(*sp)).map(|(k, _)| k.clone()).collect();
actions.push(("keys.select".into(), json!({"keys": keys, "add": ui.input(|i| i.modifiers.shift)})));
}
// Wheel over the graph with Alt/Ctrl zooms the value axis (turns auto-zoom off).
if ui.rect_contains_pointer(plot) {
let (dy, zoom) = ui.input(|i| (i.smooth_scroll_delta.y, i.modifiers.ctrl || i.modifiers.command));
if zoom && dy.abs() > 0.0 {
let k = (-dy as f64 / 200.0).exp();
let mid = (lo + hi) / 2.0;
app.ui.timeline.graph_auto_zoom = false;
app.ui.timeline.graph_range = Some((mid - (mid - lo) * k, mid + (hi - mid) * k));
}
}
// Button bar.
p.rect_filled(bar, 0.0, t.panel_bg);
p.line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, t.separator));
let y = bar.center().y;
let mut x = bar.min.x + 8.0;
let tl = &app.ui.timeline;
let (is_value, show_sel, auto_on) = (tl.graph_mode != "speed", tl.graph_show_selected, tl.graph_auto_zoom);
if text_button(app, ui, p, &mut x, y, "Value", is_value, "valueGraph", "Edit Value Graph") {
app.ui.timeline.graph_mode = "value".into();
}
if text_button(app, ui, p, &mut x, y, "Speed", !is_value, "speedGraph", "Edit Speed Graph") {
app.ui.timeline.graph_mode = "speed".into();
}
x += 6.0;
if text_button(app, ui, p, &mut x, y, "Selected", show_sel, "showSelected", "Show Selected Properties (else all animated properties)") {
app.ui.timeline.graph_show_selected = !show_sel;
}
if text_button(app, ui, p, &mut x, y, "Auto-zoom", auto_on, "autoZoom", "Auto-zoom graph height") {
app.ui.timeline.graph_auto_zoom = !auto_on;
}
if text_button(app, ui, p, &mut x, y, "Fit", false, "fit", "Fit all graphs to view") {
app.ui.timeline.graph_auto_zoom = true;
app.ui.timeline.pps = None;
}
if text_button(app, ui, p, &mut x, y, "Fit Selection", false, "fitSelection", "Fit selection to view") {
fit_selection(app, &cs, tm, plot);
}
x += 6.0;
let pos_sel = app.session.state.selected_props.iter().find_map(|(l, u)| {
let layer = comp.layer(*l)?;
let tr = layer.transform()?;
(tr.get("position").is_some_and(|p| p.uid == *u) || ["positionX", "positionY", "positionZ"].iter().any(|m| tr.get(m).is_some_and(|p| p.uid == *u)))
.then_some(l.0)
});
if text_button(app, ui, p, &mut x, y, "Separate Dimensions", false, "separateDimensions", "Separate Dimensions (Position)")
&& let Some(l) = pos_sel.or(app.session.state.selected_layers.first().map(|l| l.0))
{
actions.push(("prop.separateDimensions".into(), json!({"layer": l})));
}
x += 6.0;
for (label, cmd, params, tip) in [
("Hold", "keys.interpolation", json!({"interpolation": "hold"}), "Convert selected keyframes to Hold"),
("Linear", "keys.interpolation", json!({"interpolation": "linear"}), "Convert selected keyframes to Linear"),
("Auto Bezier", "keys.interpolation", json!({"interpolation": "autoBezier"}), "Convert selected keyframes to Auto Bezier"),
("Easy Ease", "keys.easyEase", json!({}), "Easy Ease (F9)"),
("Ease In", "keys.easyEaseIn", json!({}), "Easy Ease In (Shift+F9)"),
("Ease Out", "keys.easyEaseOut", json!({}), "Easy Ease Out (Ctrl+Shift+F9)"),
] {
let id = cmd.trim_start_matches("keys.").to_string() + label.split_whitespace().next().unwrap_or("");
if text_button(app, ui, p, &mut x, y, label, false, &id, tip) {
actions.push((cmd.into(), params));
}
}
}
/// Zoom time and value to the selected keys (and their handles).
fn fit_selection(app: &mut EffectcraftApp, cs: &[Curve], tm: TMap, plot: Rect) {
let mut t0 = f64::INFINITY;
let mut t1 = f64::NEG_INFINITY;
let mut v0 = f64::INFINITY;
let mut v1 = f64::NEG_INFINITY;
for c in cs {
for k in c.keys.iter().filter(|k| k.sel) {
for (t, v) in std::iter::once((k.t, k.v)).chain(k.handles.iter().map(|h| (h.t, h.v))) {
t0 = t0.min(t);
t1 = t1.max(t);
v0 = v0.min(v);
v1 = v1.max(v);
}
}
}
if !t0.is_finite() {
return;
}
let span = (t1 - t0).max(0.2);
let pps = (plot.width() as f64 * 0.8 / span).clamp(5.0, 4000.0);
app.ui.timeline.pps = Some(pps);
app.ui.timeline.start = (t0 - span * 0.1).max(0.0);
let pad = ((v1 - v0) * 0.15).max(1.0);
app.ui.timeline.graph_auto_zoom = false;
app.ui.timeline.graph_range = Some((v0 - pad, v1 + pad));
let _ = tm;
}
fn nice_step(raw: f64) -> f64 {
let raw = raw.abs().max(1e-9);
let mag = 10f64.powf(raw.log10().floor());
let n = raw / mag;
mag * if n < 1.5 {
1.0
} else if n < 3.5 {
2.0
} else if n < 7.5 {
5.0
} else {
10.0
}
}
fn fmt(v: f64, step: f64) -> String {
let dec = if step >= 1.0 { 0 } else { (-step.log10()).ceil() as usize };
let s = format!("{v:.dec$}");
if s.trim_start_matches('-').chars().all(|c| c == '0' || c == '.') { s.trim_start_matches('-').to_string() } else { s }
}
+23 -2
View File
@@ -62,11 +62,32 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let tc = crate::panels::timecode(&app.session, &c, app.session.time());
p.text(pos2(x0, y), Align2::LEFT_CENTER, if sel.is_empty() { "No layer selected".to_string() } else { sel.join(", ") }, Tokens::semibold(12.0), t.text);
p.text(pos2(x0, y + 18.0), Align2::LEFT_CENTER, format!("Time: {tc}"), Tokens::ui(12.0), t.text_dim);
// One layer selected: Duration, In and Out like AE's Info panel.
let mut ly = y + 36.0;
if let [id] = app.session.state.selected_layers.as_slice()
&& let Some(l) = c.layer(*id)
{
let tc = |t| crate::panels::timecode(&app.session, &c, t);
let lines = [
// A length, so no start-timecode offset.
format!("Duration: {}", {
let fr = c.frame_rate;
let n = fr.frame_at(l.out_point) - fr.frame_at(l.in_point);
let s = effectcraft_engine::time::format_timecode_frames(n, fr, fr.supports_drop_frame());
if fr.supports_drop_frame() { s } else { s.replace(';', ":") }
}),
format!("In: {}, Out: {}", tc(l.in_point), tc(effectcraft_engine::time::Tick(l.out_point.0 - c.frame_duration().0))),
];
for line in lines {
p.text(pos2(x0, ly), Align2::LEFT_CENTER, line, Tokens::ui(12.0), t.text_dim);
ly += 18.0;
}
}
let ms = app.frames.last_ms.lock().map(|v| *v).unwrap_or(0.0);
p.text(pos2(x0, y + 36.0), Align2::LEFT_CENTER, format!("Render: {ms:.0} ms • UI {:.0} fps", app.fps), Tokens::ui(11.5), t.text_faint);
p.text(pos2(x0, ly), Align2::LEFT_CENTER, format!("Render: {ms:.0} ms • UI {:.0} fps", app.fps), Tokens::ui(11.5), t.text_faint);
if !app.session.state.selected_keys.is_empty() {
p.text(
pos2(x0, y + 54.0),
pos2(x0, ly + 18.0),
Align2::LEFT_CENTER,
format!("{} keyframes selected", app.session.state.selected_keys.len()),
Tokens::ui(11.5),
+287
View File
@@ -0,0 +1,287 @@
//! Animation dialogs: Keyframe Velocity, Keyframe Interpolation and Time Stretch. Each one is
//! pre-filled from the engine (`keys.info`, the layer) and commits through one engine command.
use egui::{Color32, vec2};
use serde_json::{Value, json};
use crate::theme::Tokens;
use crate::{Dialog, EffectcraftApp};
#[derive(Clone, Debug, Default)]
pub struct VelocityDraft {
pub dims: usize,
pub units: String,
pub name: String,
pub in_speed: Vec<f64>,
pub in_inf: Vec<f64>,
pub out_speed: Vec<f64>,
pub out_inf: Vec<f64>,
/// Which sides exist (first key has no incoming side, last none outgoing).
pub has_in: bool,
pub has_out: bool,
pub continuous: bool,
}
#[derive(Clone, Debug, Default)]
pub struct InterpDraft {
/// Index into TEMPORAL / SPATIAL / ROVING (0 = Current Settings).
pub temporal: usize,
pub spatial: usize,
pub roving: usize,
pub has_spatial: bool,
pub count: usize,
}
#[derive(Clone, Debug, Default)]
pub struct StretchDraft {
pub percent: f64,
pub duration: f64,
/// 0 = Layer In-point, 1 = Current Frame, 2 = Layer Out-point.
pub hold: usize,
pub orig_duration: f64,
pub orig_percent: f64,
}
pub const TEMPORAL: [(&str, &str); 6] = [
("Current Settings", ""),
("Linear", "linear"),
("Bezier", "bezier"),
("Continuous Bezier", "continuousBezier"),
("Auto Bezier", "autoBezier"),
("Hold", "hold"),
];
pub const SPATIAL: [(&str, &str); 5] =
[("Current Settings", ""), ("Linear", "linear"), ("Bezier", "bezier"), ("Continuous Bezier", "continuousBezier"), ("Auto Bezier", "autoBezier")];
pub const ROVING: [&str; 3] = ["Current Settings", "Lock To Time", "Rove Across Time"];
fn num(v: &Value) -> f64 {
v.as_f64().unwrap_or(0.0)
}
/// Animation ▸ Keyframe Velocity… (⇧⌘K) with keys selected.
pub fn open_velocity(app: &mut EffectcraftApp) -> Result<(), String> {
let info = app.session.execute("keys.info", json!({})).map_err(|e| e.to_string())?;
let first = info.as_array().and_then(|a| a.first()).ok_or("select keyframes first")?;
let dims = first["dims"].as_u64().unwrap_or(1).max(1) as usize;
let side = |k: &str| -> (Vec<f64>, Vec<f64>, bool) {
let a = first[k].as_array().cloned().unwrap_or_default();
let has = a.iter().any(|e| !e.is_null());
let sp = (0..dims).map(|d| a.get(d).map(|e| num(&e["speed"])).unwrap_or(0.0)).collect();
let inf = (0..dims).map(|d| a.get(d).map(|e| num(&e["influence"])).filter(|v| *v > 0.0).unwrap_or(33.33)).collect();
(sp, inf, has)
};
let (in_speed, in_inf, has_in) = side("inEase");
let (out_speed, out_inf, has_out) = side("outEase");
app.dialog_state.velocity = VelocityDraft {
dims,
units: first["units"].as_str().unwrap_or("units/sec").into(),
name: first["name"].as_str().unwrap_or("").into(),
in_speed,
in_inf,
out_speed,
out_inf,
has_in,
has_out,
continuous: first["continuous"].as_bool().unwrap_or(false),
};
app.dialog = Some(Dialog::KeyVelocity);
Ok(())
}
/// Animation ▸ Keyframe Interpolation… (⌥⌘K).
pub fn open_interpolation(app: &mut EffectcraftApp) -> Result<(), String> {
let info = app.session.execute("keys.info", json!({})).map_err(|e| e.to_string())?;
let a = info.as_array().cloned().unwrap_or_default();
if a.is_empty() {
return Err("select keyframes first".into());
}
app.dialog_state.interp = InterpDraft { has_spatial: a.iter().any(|k| !k["spatial"].is_null()), count: a.len(), ..Default::default() };
app.dialog = Some(Dialog::KeyInterpolation);
Ok(())
}
/// Layer ▸ Time ▸ Time Stretch…
pub fn open_time_stretch(app: &mut EffectcraftApp) -> Result<(), String> {
let lid = *app.session.state.selected_layers.first().ok_or("select a layer first")?;
let l = app.session.active_comp().and_then(|c| c.layer(lid)).ok_or("no layer")?;
let dur = (l.out_point - l.in_point).seconds();
app.dialog_state.stretch = StretchDraft { percent: l.stretch, duration: dur, hold: 0, orig_duration: dur, orig_percent: l.stretch };
app.dialog = Some(Dialog::TimeStretch);
Ok(())
}
fn buttons(ui: &mut egui::Ui, app: &mut EffectcraftApp, t: &Tokens, prefix: &str) -> (bool, bool) {
let (mut ok, mut cancel) = (false, false);
ui.add_space(14.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let r = ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent));
app.auto.add(&format!("{prefix}.ok"), r.rect, "OK");
ok = r.clicked();
let r = ui.button("Cancel");
app.auto.add(&format!("{prefix}.cancel"), r.rect, "Cancel");
cancel = r.clicked();
});
(ok, cancel)
}
fn drag(ui: &mut egui::Ui, app: &mut EffectcraftApp, id: &str, v: &mut f64, speed: f64, range: std::ops::RangeInclusive<f64>, suffix: &str, enabled: bool) {
let r = ui.add_enabled(enabled, egui::DragValue::new(v).speed(speed).range(range).max_decimals(2).suffix(suffix));
app.auto.add(id, r.rect, id);
}
pub fn velocity(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut d = app.dialog_state.velocity.clone();
let (mut ok, mut cancel) = (false, false);
let title = if d.name.is_empty() { "Keyframe Velocity".to_string() } else { format!("Keyframe Velocity: {}", d.name) };
let h = 250.0 + 2.0 * 26.0 * d.dims as f32;
super::dialogs::modal(ctx, &title, vec2(440.0, h), t, |ui| {
for (label, out) in [("Incoming Velocity", false), ("Outgoing Velocity", true)] {
ui.label(egui::RichText::new(label).font(Tokens::medium(12.5)));
let enabled = if out { d.has_out } else { d.has_in };
egui::Grid::new(("vel", out)).num_columns(3).spacing([12.0, 6.0]).show(ui, |ui| {
for dim in 0..d.dims {
let tag = if d.dims > 1 { format!("Dimension {}", ["X", "Y", "Z", "W"][dim.min(3)]) } else { String::new() };
ui.label(egui::RichText::new(tag).color(t.text_dim));
let side = if out { "out" } else { "in" };
ui.horizontal(|ui| {
ui.label("Speed:");
let v = if out { &mut d.out_speed[dim] } else { &mut d.in_speed[dim] };
drag(ui, app, &format!("dialog.velocity.{side}Speed.{dim}"), v, 1.0, -1e7..=1e7, "", enabled);
ui.label(egui::RichText::new(&d.units).color(t.text_dim));
});
ui.horizontal(|ui| {
ui.label("Influence:");
let v = if out { &mut d.out_inf[dim] } else { &mut d.in_inf[dim] };
drag(ui, app, &format!("dialog.velocity.{side}Influence.{dim}"), v, 0.2, 0.1..=100.0, " %", enabled);
});
ui.end_row();
}
});
ui.add_space(8.0);
}
let r = ui.checkbox(&mut d.continuous, "Continuous (Lock Outgoing to Incoming)");
app.auto.add("dialog.velocity.continuous", r.rect, "Continuous");
if d.continuous {
d.out_speed = d.in_speed.clone();
}
(ok, cancel) = buttons(ui, app, t, "dialog.velocity");
});
app.dialog_state.velocity = d.clone();
if ok || super::dialogs::ui_enter(ctx) {
let mut params = json!({"continuous": d.continuous});
if d.has_in {
params["inSpeed"] = json!(d.in_speed);
params["inInfluence"] = json!(d.in_inf);
}
if d.has_out {
params["outSpeed"] = json!(d.out_speed);
params["outInfluence"] = json!(d.out_inf);
}
if let Err(e) = app.session.execute("keys.velocity", params) {
app.ui.status = e.to_string();
}
cancel = true;
}
if cancel {
app.dialog = None;
}
}
fn combo(ui: &mut egui::Ui, app: &mut EffectcraftApp, id: &str, sel: &mut usize, opts: &[&str], enabled: bool) {
ui.add_enabled_ui(enabled, |ui| {
let r = egui::ComboBox::from_id_salt(id).width(200.0).selected_text(opts[*sel]).show_ui(ui, |ui| {
for (i, o) in opts.iter().enumerate() {
ui.selectable_value(sel, i, *o);
}
});
app.auto.add(id, r.response.rect, id);
});
}
pub fn interpolation(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut d = app.dialog_state.interp.clone();
let (mut ok, mut cancel) = (false, false);
super::dialogs::modal(ctx, "Keyframe Interpolation", vec2(440.0, 250.0), t, |ui| {
egui::Grid::new("interp-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
ui.label("Temporal Interpolation:");
combo(ui, app, "dialog.interpolation.temporal", &mut d.temporal, &TEMPORAL.map(|x| x.0), true);
ui.end_row();
ui.label("Spatial Interpolation:");
combo(ui, app, "dialog.interpolation.spatial", &mut d.spatial, &SPATIAL.map(|x| x.0), d.has_spatial);
ui.end_row();
ui.label("Roving:");
combo(ui, app, "dialog.interpolation.roving", &mut d.roving, &ROVING, d.has_spatial);
ui.end_row();
});
ui.add_space(6.0);
ui.label(egui::RichText::new(format!("{} keyframe{} selected", d.count, if d.count == 1 { "" } else { "s" })).color(t.text_dim));
(ok, cancel) = buttons(ui, app, t, "dialog.interpolation");
});
app.dialog_state.interp = d.clone();
if ok || super::dialogs::ui_enter(ctx) {
let mut params = json!({});
if d.temporal > 0 {
params["interpolation"] = json!(TEMPORAL[d.temporal].1);
}
if d.spatial > 0 && d.has_spatial {
params["spatial"] = json!(SPATIAL[d.spatial].1);
}
if d.roving > 0 && d.has_spatial {
params["roving"] = json!(d.roving == 2);
}
if params.as_object().is_some_and(|m| !m.is_empty())
&& let Err(e) = app.session.execute("keys.interpolation", params)
{
app.ui.status = e.to_string();
}
cancel = true;
}
if cancel {
app.dialog = None;
}
}
pub fn time_stretch(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
let mut d = app.dialog_state.stretch.clone();
let (mut ok, mut cancel) = (false, false);
super::dialogs::modal(ctx, "Time Stretch", vec2(420.0, 300.0), t, |ui| {
ui.label(egui::RichText::new("Stretch").font(Tokens::medium(12.5)));
egui::Grid::new("stretch-grid").num_columns(2).spacing([14.0, 8.0]).show(ui, |ui| {
ui.label("Original Duration:");
ui.label(format!("{:.2} s", d.orig_duration));
ui.end_row();
ui.label("Stretch Factor:");
let before = d.percent;
drag(ui, app, "dialog.timeStretch.percent", &mut d.percent, 0.5, -10000.0..=10000.0, " %", true);
if (before - d.percent).abs() > 1e-9 && d.orig_percent.abs() > 1e-9 {
d.duration = d.orig_duration * d.percent.abs() / d.orig_percent.abs();
}
ui.end_row();
ui.label("New Duration:");
let before = d.duration;
drag(ui, app, "dialog.timeStretch.duration", &mut d.duration, 0.05, 0.01..=100000.0, " s", true);
if (before - d.duration).abs() > 1e-9 && d.orig_duration > 1e-9 {
d.percent = d.orig_percent.signum() * d.orig_percent.abs() * d.duration / d.orig_duration;
}
ui.end_row();
});
ui.add_space(10.0);
ui.label(egui::RichText::new("Hold In Place").font(Tokens::medium(12.5)));
for (i, l) in ["Layer In-point", "Current Frame", "Layer Out-point"].into_iter().enumerate() {
let r = ui.radio_value(&mut d.hold, i, l);
app.auto.add(&format!("dialog.timeStretch.hold.{i}"), r.rect, l);
}
(ok, cancel) = buttons(ui, app, t, "dialog.timeStretch");
});
app.dialog_state.stretch = d.clone();
if ok || super::dialogs::ui_enter(ctx) {
let hold = ["in", "current", "out"][d.hold.min(2)];
if let Err(e) = app.session.execute("layer.timeStretch", json!({"percent": d.percent, "hold": hold})) {
app.ui.status = e.to_string();
}
cancel = true;
}
if cancel {
app.dialog = None;
}
}
+2 -22
View File
@@ -1,7 +1,6 @@
//! Smaller panels: Preview, Audio, History, Markers, Wiggler, Render Queue, the Home screen and
//! placeholders.
//! Smaller panels: Preview, Audio, History, Markers, Wiggler, the Home screen and placeholders.
use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};
use egui::{Align2, Color32, Rect, Sense, pos2, vec2};
use serde_json::json;
use crate::dock::PanelKind;
@@ -185,25 +184,6 @@ pub fn wiggler(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.auto.add("wiggler.apply", b, "Apply");
}
/// Render Queue: comps queued for export with output settings.
pub fn render_queue(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
let hdr = Rect::from_min_size(rect.min, vec2(rect.width(), 40.0));
p.text(pos2(hdr.min.x + 14.0, hdr.center().y), Align2::LEFT_CENTER, "Render Queue", Tokens::semibold(13.0), t.text);
let b = Rect::from_min_size(pos2(hdr.max.x - 100.0, hdr.min.y + 8.0), vec2(84.0, 24.0));
let _ = widgets::text_button(ui, b, "Render", true, &t, egui::Id::new("rq-render"));
app.auto.add("renderQueue.render", b, "Render");
p.line_segment([hdr.left_bottom(), hdr.right_bottom()], Stroke::new(1.0, t.separator));
p.text(
pos2(rect.min.x + 14.0, hdr.max.y + 20.0),
Align2::LEFT_CENTER,
"Composition ▸ Add to Render Queue (⌃⌘M) to queue a render.",
Tokens::ui(12.0),
t.text_faint,
);
}
/// Home screen: new/open, recent, and community links.
pub fn start_screen(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
+9 -7
View File
@@ -1,12 +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;
@@ -33,11 +38,8 @@ pub fn timecode(session: &Session, comp: &Comp, t: Tick) -> String {
let fr = comp.frame_rate;
match session.project.settings.time_display {
TimeDisplayStyle::Frames => format!("{:05}", fr.frame_at(t) + session.project.settings.frame_start),
TimeDisplayStyle::Timecode => {
let df = fr.supports_drop_frame();
let s = effectcraft_engine::time::format_timecode_frames(fr.frame_at(t + comp.display_start), fr, df);
if df { s } else { s.replace(';', ":") }
}
// AE's display: `0:00:02:15` (non-drop-frame counting, as AE shows new comps).
TimeDisplayStyle::Timecode => effectcraft_engine::time::format_timecode_ae(fr.frame_at(t + comp.display_start), fr, false),
}
}
@@ -59,12 +61,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
PanelKind::Character => text_panels::character(app, ui, rect),
PanelKind::Paragraph => text_panels::paragraph(app, ui, rect),
PanelKind::Align => text_panels::align(app, ui, rect),
PanelKind::Properties => effect_controls::properties(app, ui, rect),
PanelKind::Properties => properties::show(app, ui, rect),
PanelKind::Audio => misc::audio(app, ui, rect),
PanelKind::History => misc::history(app, ui, rect),
PanelKind::Markers => misc::markers(app, ui, rect),
PanelKind::Wiggler => misc::wiggler(app, ui, rect),
PanelKind::RenderQueue => misc::render_queue(app, ui, rect),
PanelKind::RenderQueue => render_queue::show(app, ui, rect),
other => misc::placeholder(app, ui, rect, other),
}
}
+118 -17
View File
@@ -23,10 +23,48 @@ fn item_icon(it: &Item) -> Icon {
}
}
fn fmt_dur(secs: f64, fps: f64) -> String {
let f = (secs * fps).round() as i64;
/// Duration as AE prints it in the Project panel header: `0:00:10:00` (h:mm:ss:ff).
pub fn fmt_dur(secs: f64, fps: f64) -> String {
let fpsi = fps.round().max(1.0) as i64;
format!("0;{:02};{:02};{:02}", f / fpsi / 60, (f / fpsi) % 60, f % fpsi)
let f = (secs * fps).round() as i64;
let s = f / fpsi;
format!("{}:{:02}:{:02}:{:02}", s / 3600, (s / 60) % 60, s % 60, f % fpsi)
}
/// File size the way AE's Size column shows it (`512 KB`, `12.3 MB`).
pub fn fmt_size(bytes: u64) -> String {
const K: f64 = 1024.0;
let b = bytes as f64;
if b < K * K {
format!("{} KB", (b / K).ceil() as u64)
} else if b < K * K * K {
format!("{:.1} MB", b / (K * K))
} else {
format!("{:.2} GB", b / (K * K * K))
}
}
/// Footage file size on disk (comps, solids and folders have none).
fn file_size(it: &Item) -> Option<u64> {
match &it.kind {
ItemKind::Footage(f) => std::fs::metadata(&f.path).ok().map(|m| m.len()),
_ => None,
}
}
/// Sort siblings by the Project panel's sort column; ties fall back to the name.
pub fn sort_items(items: &mut [&Item], col: &str, desc: bool) {
let name = |i: &Item| i.name.to_lowercase();
items.sort_by(|a, b| {
let o = match col {
"type" => a.type_name().cmp(b.type_name()),
"size" => file_size(a).cmp(&file_size(b)),
"fps" => a.frame_rate().map(|r| r.as_f64()).partial_cmp(&b.frame_rate().map(|r| r.as_f64())).unwrap_or(std::cmp::Ordering::Equal),
_ => std::cmp::Ordering::Equal,
}
.then_with(|| name(a).cmp(&name(b)));
if desc { o.reverse() } else { o }
});
}
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
@@ -82,13 +120,41 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
// Column header.
let hdr = Rect::from_min_size(pos2(rect.min.x, sr.max.y + 6.0), vec2(rect.width(), 20.0));
p.line_segment([hdr.left_bottom(), hdr.right_bottom()], Stroke::new(1.0, t.separator));
let name_w = (rect.width() * 0.48).max(140.0);
let name_w = (rect.width() * 0.40).max(120.0);
let col_type = rect.min.x + name_w + 30.0;
let col_size = col_type + 76.0;
p.text(pos2(rect.min.x + 26.0, hdr.center().y), Align2::LEFT_CENTER, "Name", Tokens::ui(11.0), t.text_dim);
let col_size = col_type + 80.0;
let col_fps = col_size + 52.0;
// Clickable headers sort (click again to reverse), with AE's ▲/▼ indicator.
let cols = [
("name", "Name", rect.min.x + 26.0, name_w - 26.0),
("type", "Type", col_type, 76.0),
("size", "Size", col_size, 48.0),
("fps", "Frame Rate", col_fps, 70.0),
];
for (key, label, x, w) in cols {
let hr = Rect::from_min_size(pos2(x - 4.0, hdr.min.y), vec2(w, hdr.height()));
let resp = ui.interact(hr, egui::Id::new(("proj-sort", key)), Sense::click());
p.with_clip_rect(hr).text(pos2(x, hdr.center().y), Align2::LEFT_CENTER, label, Tokens::ui(11.0), if resp.hovered() { t.text } else { t.text_dim });
if app.ui.project_sort == key {
let c = pos2(hr.max.x - 10.0, hdr.center().y);
let d = if app.ui.project_sort_desc { 1.0 } else { -1.0 };
p.add(egui::Shape::convex_polygon(
vec![pos2(c.x - 4.0, c.y - 2.0 * d), pos2(c.x + 4.0, c.y - 2.0 * d), pos2(c.x, c.y + 2.5 * d)],
t.text_dim,
Stroke::NONE,
));
}
app.auto.add(&format!("project.sort.{key}"), hr, label);
if resp.clicked() {
if app.ui.project_sort == key {
app.ui.project_sort_desc = !app.ui.project_sort_desc;
} else {
app.ui.project_sort = key.to_string();
app.ui.project_sort_desc = false;
}
}
}
icons::paint(&p, Rect::from_center_size(pos2(rect.min.x + name_w + 14.0, hdr.center().y), vec2(10.0, 10.0)), Icon::Keyframe, t.text_dim);
p.text(pos2(col_type, hdr.center().y), Align2::LEFT_CENTER, "Type", Tokens::ui(11.0), t.text_dim);
p.text(pos2(col_size, hdr.center().y), Align2::LEFT_CENTER, "Size", Tokens::ui(11.0), t.text_dim);
// Rows.
let footer_h = 28.0;
let list = Rect::from_min_max(pos2(rect.min.x, hdr.max.y), pos2(rect.max.x, rect.max.y - footer_h));
@@ -97,7 +163,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let query = app.ui.project_search.to_lowercase();
let mut rows: Vec<(ItemId, usize)> = vec![];
fn walk(app: &EffectcraftApp, folder: Option<ItemId>, depth: usize, q: &str, out: &mut Vec<(ItemId, usize)>) {
for it in app.session.project.children(folder) {
let mut kids = app.session.project.children(folder);
sort_items(&mut kids, &app.ui.project_sort, app.ui.project_sort_desc);
for it in kids {
if !q.is_empty() && !it.is_folder() && !it.name.to_lowercase().contains(q) {
continue;
}
@@ -140,17 +208,22 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
icons::paint(
&lp,
Rect::from_center_size(pos2(x0 + 18.0, r.center().y), vec2(14.0, 14.0)),
item_icon(&it),
if it.is_folder() { Color32::from_rgb(0xd8, 0xc0, 0x60) } else { t.text_dim },
icons::paint(&lp, Rect::from_center_size(pos2(x0 + 18.0, r.center().y), vec2(14.0, 14.0)), item_icon(&it), t.text_dim);
let name_clip = Rect::from_min_max(pos2(x0 + 30.0, r.min.y), pos2(r.min.x + name_w + 6.0, r.max.y)).intersect(list);
lp.with_clip_rect(name_clip).text(
pos2(x0 + 30.0, r.center().y),
Align2::LEFT_CENTER,
&it.name,
Tokens::ui(12.0),
if selected { Color32::WHITE } else { t.text },
);
lp.text(pos2(x0 + 30.0, r.center().y), Align2::LEFT_CENTER, &it.name, Tokens::ui(12.0), if selected { Color32::WHITE } else { t.text });
lp.rect_filled(Rect::from_center_size(pos2(r.min.x + name_w + 14.0, r.center().y), vec2(10.0, 10.0)), 2.0, Tokens::label(it.label));
lp.text(pos2(col_type, r.center().y), Align2::LEFT_CENTER, it.type_name(), Tokens::ui(11.5), t.text_dim);
if let Some((w, h)) = it.dimensions() {
lp.text(pos2(col_size, r.center().y), Align2::LEFT_CENTER, format!("{w} x {h}"), Tokens::ui(11.5), t.text_dim);
if let Some(b) = file_size(&it) {
lp.text(pos2(col_size, r.center().y), Align2::LEFT_CENTER, fmt_size(b), Tokens::ui(11.5), t.text_dim);
}
if let Some(fr) = it.frame_rate() {
lp.text(pos2(col_fps + 66.0, r.center().y), Align2::RIGHT_CENTER, format!("{:.2}", fr.as_f64()), Tokens::ui(11.5), t.text_dim);
}
let resp = ui.interact(r.intersect(list), egui::Id::new(("pitem", id.0)), Sense::click_and_drag());
app.auto.add(&format!("project.item.{}", id.0), r, &it.name);
@@ -260,3 +333,31 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ae_duration_and_size_formats() {
assert_eq!(fmt_dur(10.0, 29.97), "0:00:10:00");
assert_eq!(fmt_dur(3725.48, 25.0), "1:02:05:12");
assert_eq!(fmt_size(1000), "1 KB");
assert_eq!(fmt_size(5 * 1024 * 1024 + 300_000), "5.3 MB");
}
#[test]
fn folders_sort_with_items_by_name() {
let mut p = effectcraft_engine::project::Project::default();
let l = effectcraft_engine::color::Label::Yellow;
p.add_item("Solids", l, None, ItemKind::Folder);
p.add_item("Precomps", l, None, ItemKind::Folder);
p.add_item("EffectCraft Intro", l, None, ItemKind::Folder);
let mut kids = p.children(None);
sort_items(&mut kids, "name", false);
let names: Vec<&str> = kids.iter().map(|i| i.name.as_str()).collect();
assert_eq!(names, ["EffectCraft Intro", "Precomps", "Solids"]);
sort_items(&mut kids, "name", true);
assert_eq!(kids[0].name, "Solids");
}
}
+508
View File
@@ -0,0 +1,508 @@
//! Properties panel: the selected layer's essential properties in one context-sensitive stack,
//! like After Effects' Properties panel. Sections appear by layer type:
//!
//! - **Layer Transform** (all layers but cameras/lights): keyframe navigator (◀ ◆ ▶) or
//! stopwatch, scrubbable values, linked Scale, `Nx+N°` Rotation, Reset.
//! - **Text** (text layers): font family/style, size, leading, tracking, stroke width, fill and
//! stroke with enable checkboxes; "More" opens the Character panel.
//! - **Paragraph** (text layers): the seven alignment buttons; "More" opens the Paragraph panel.
//! - **Text Animation** (text layers): Add Animator menu.
use effectcraft_engine::keyframe::{Justify, TextDoc, Value};
use effectcraft_engine::project::{Layer, LayerSource, Property};
use effectcraft_engine::render::EvalCtx;
use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};
use serde_json::json;
use crate::dock::PanelKind;
use crate::icons::{self, Icon};
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
type Actions = Vec<(String, serde_json::Value)>;
const ROW_H: f32 = 22.0;
const PAD: f32 = 12.0;
/// Text Animation › Add Animator entries: (menu label, `layer.addTextAnimator` property).
const ANIMATORS: &[(&str, &str)] = &[
("Anchor Point", "anchor"),
("Position", "position"),
("Scale", "scale"),
("Skew", "skew"),
("Rotation", "rotation"),
("Opacity", "opacity"),
("Fill Color", "fillColor"),
("Stroke Color", "strokeColor"),
("Stroke Width", "strokeWidth"),
("Tracking", "tracking"),
("Line Spacing", "lineSpacing"),
("Character Offset", "characterOffset"),
("Blur", "blur"),
];
/// AE's seven Paragraph alignment buttons: (justify, `layer.setText` key).
const ALIGNS: [(Justify, &str); 7] = [
(Justify::Left, "left"),
(Justify::Center, "center"),
(Justify::Right, "right"),
(Justify::JustifyLastLeft, "justifyLeft"),
(Justify::JustifyLastCenter, "justifyCenter"),
(Justify::JustifyLastRight, "justifyRight"),
(Justify::JustifyAll, "justifyAll"),
];
/// Value text the way AE prints it: whole numbers without decimals, otherwise one decimal.
fn decimals(v: f64) -> usize {
if (v - v.round()).abs() < 1e-6 { 0 } else { 1 }
}
/// Rotation as AE shows it: revolutions and remaining degrees (`1x+30°`, `-0x-45°`).
pub fn split_rotation(deg: f64) -> (i64, f64) {
let rev = (deg / 360.0).trunc();
(rev as i64, deg - rev * 360.0)
}
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
let ctx = ui.ctx().clone();
let comp = app.session.active_comp().cloned();
let layer = comp.as_ref().and_then(|c| app.session.state.selected_layers.first().and_then(|id| c.layer(*id)).cloned());
let (Some(comp), Some(cid), Some(layer)) = (comp, app.session.active_comp_id(), layer) else {
p.text(rect.center(), Align2::CENTER_CENTER, "Select a layer to see its properties", Tokens::ui(12.0), t.text_faint);
return;
};
let project = app.session.project.clone();
let expr = app.session.expr.clone();
let now = app.session.time();
let ectx = EvalCtx { project: &project, comp_id: cid, comp: &comp, time: now, expr: expr.as_deref() };
let x0 = rect.min.x + PAD;
let w = rect.width() - 2.0 * PAD;
// Vertical scrolling: content height is known after drawing, so clamp with last frame's.
let scroll_id = egui::Id::new("props-scroll");
let (mut scroll, content_h): (f32, f32) = ui.data(|d| d.get_temp(scroll_id)).unwrap_or((0.0, 0.0));
if ui.rect_contains_pointer(rect) {
scroll -= ui.input(|i| i.smooth_scroll_delta.y);
}
scroll = scroll.clamp(0.0, (content_h - rect.height()).max(0.0));
let top = rect.min.y + 8.0 - scroll;
let mut y = top;
let mut actions: Actions = vec![];
// ---------------------------------------------------------------- Layer Transform
if let Some(tr) = layer.transform().cloned() {
section_header(app, ui, &p, x0, w, y, "Layer Transform", "properties.transform");
let rr = Rect::from_min_size(pos2(x0 + w - 40.0, y), vec2(40.0, ROW_H));
let resp = ui.interact(rr, egui::Id::new("props-reset"), Sense::click());
p.text(rr.right_center(), Align2::RIGHT_CENTER, "Reset", Tokens::ui(12.0), if resp.hovered() { t.accent_hover } else { t.accent });
app.auto.add("properties.transform.reset", rr, "Reset Transform");
if resp.clicked() {
for pr in tr.props() {
actions.push(("prop.reset".into(), json!({"layer": layer.id.0, "prop": pr.uid})));
}
}
y += ROW_H + 2.0;
for pr in tr.props() {
if pr.three_d_only && !layer.is_3d() {
continue;
}
transform_row(app, ui, &p, &layer, pr, &ectx, Rect::from_min_size(pos2(x0, y), vec2(w, ROW_H)), &mut actions);
y += ROW_H;
}
y += 10.0;
}
// ---------------------------------------------------------------- Text / Paragraph / Animation
if matches!(layer.source, LayerSource::Text)
&& let Some(doc) = effectcraft_engine::render::text::source_text(&ectx, &layer)
{
divider(&p, x0, w, y - 4.0, &t);
y = text_section(app, ui, &p, &layer, &doc, x0, w, y + 4.0, &mut actions);
divider(&p, x0, w, y - 4.0, &t);
y = paragraph_section(app, ui, &p, &layer, &doc, x0, w, y + 4.0, &mut actions);
divider(&p, x0, w, y - 4.0, &t);
section_header(app, ui, &p, x0, w, y + 4.0, "Text Animation", "properties.textAnimation");
y += ROW_H + 10.0;
let br = Rect::from_min_size(pos2(x0, y), vec2(116.0, 24.0));
let resp = ui.interact(br, egui::Id::new("props-add-animator"), Sense::click());
p.rect_stroke(br, 4.0, Stroke::new(1.0, if resp.hovered() { t.text_dim } else { t.field_border }), egui::StrokeKind::Inside);
icons::paint(&p, Rect::from_center_size(pos2(br.min.x + 14.0, br.center().y), vec2(10.0, 10.0)), Icon::Plus, t.text);
p.text(pos2(br.min.x + 26.0, br.center().y), Align2::LEFT_CENTER, "Add Animator", Tokens::ui(12.0), t.text);
app.auto.add("properties.addAnimator", br, "Add Animator");
let pop = egui::Id::new("props-add-animator-pop");
if resp.clicked() {
widgets::open_popup(ui, pop);
}
let labels: Vec<String> = ANIMATORS.iter().map(|(l, _)| l.to_string()).collect();
if let Some(i) = widgets::popup_menu(ui, pop, br.left_bottom(), &labels, None) {
actions.push(("layer.addTextAnimator".into(), json!({"layer": layer.id.0, "property": ANIMATORS[i].1})));
}
y += 24.0;
}
y += 40.0;
let content_h = y - top;
ui.data_mut(|d| d.insert_temp(scroll_id, (scroll, content_h)));
if content_h > rect.height() {
// Thin scroll indicator.
let frac = rect.height() / content_h;
let bar_h = (rect.height() * frac).max(24.0);
let by = rect.min.y + (rect.height() - bar_h) * (scroll / (content_h - rect.height()).max(1.0));
p.rect_filled(Rect::from_min_size(pos2(rect.max.x - 5.0, by), vec2(3.0, bar_h)), 1.5, t.text_faint.gamma_multiply(0.6));
}
for (id, params) in actions {
if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) {
app.ui.status = e;
}
}
}
fn section_header(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, x0: f32, w: f32, y: f32, title: &str, auto: &str) {
let t = app.tokens;
p.text(pos2(x0, y + ROW_H / 2.0), Align2::LEFT_CENTER, title, Tokens::semibold(12.0), t.text);
let r = Rect::from_min_size(pos2(x0, y), vec2(w, ROW_H));
let _ = ui;
app.auto.add(auto, r, title);
}
fn divider(p: &egui::Painter, x0: f32, w: f32, y: f32, t: &Tokens) {
p.line_segment([pos2(x0 - 4.0, y), pos2(x0 + w + 4.0, y)], Stroke::new(1.0, t.separator));
}
fn triangle(p: &egui::Painter, c: egui::Pos2, left: bool, col: Color32) {
let (dx, h) = (if left { -3.5 } else { 3.5 }, 4.0);
p.add(egui::Shape::convex_polygon(vec![pos2(c.x + dx, c.y), pos2(c.x - dx, c.y - h), pos2(c.x - dx, c.y + h)], col, Stroke::NONE));
}
/// One transform row: keyframe navigator or stopwatch, name, value fields.
#[allow(clippy::too_many_arguments)]
fn transform_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, layer: &Layer, pr: &Property, ectx: &EvalCtx, r: Rect, actions: &mut Actions) {
let t = app.tokens;
let cy = r.center().y;
let uid = pr.uid;
let lid = layer.id.0;
let base = format!("properties.prop.{uid}");
if pr.is_animated() {
// ◀ ◆ ▶: previous key, add/remove key at the CTI, next key.
let now = ectx.time;
let half = ectx.comp.frame_duration().0 / 2;
let on_key = pr.keys.iter().any(|k| (layer.comp_time(k.time).0 - now.0).abs() <= half);
let cells = [("prev", r.min.x + 4.0), ("key", r.min.x + 16.0), ("next", r.min.x + 28.0)];
for (what, cx) in cells {
let cr = Rect::from_center_size(pos2(cx, cy), vec2(12.0, 16.0));
let resp = ui.interact(cr, egui::Id::new(("props-nav", uid, what)), Sense::click());
let col = if resp.hovered() { t.text } else { t.text_dim };
match what {
"prev" => triangle(p, cr.center(), true, col),
"next" => triangle(p, cr.center(), false, col),
_ => {
let kr = Rect::from_center_size(cr.center(), vec2(10.0, 10.0));
if on_key {
icons::paint(p, kr, Icon::Keyframe, t.keyframe);
} else {
let c = kr.center();
let d = 4.5;
p.add(egui::Shape::closed_line(
vec![pos2(c.x, c.y - d), pos2(c.x + d, c.y), pos2(c.x, c.y + d), pos2(c.x - d, c.y)],
Stroke::new(1.0, col),
));
}
}
}
app.auto.add(&format!("{base}.{what}Key"), cr, &pr.name);
if resp.clicked() {
match what {
"prev" => actions.push(("time.go".into(), json!({"to": "prevKey", "prop": uid}))),
"next" => actions.push(("time.go".into(), json!({"to": "nextKey", "prop": uid}))),
_ => actions.push(("prop.toggleKey".into(), json!({"layer": lid, "prop": uid}))),
}
}
}
} else {
let swr = Rect::from_center_size(pos2(r.min.x + 16.0, cy), vec2(14.0, 14.0));
let resp = ui.interact(swr, egui::Id::new(("props-sw", uid)), Sense::click());
icons::paint(p, swr, Icon::Stopwatch, if resp.hovered() { t.text } else { t.text_dim });
app.auto.add(&format!("{base}.stopwatch"), swr, &pr.name);
if resp.clicked() {
actions.push(("prop.toggleAnimation".into(), json!({"layer": lid, "prop": uid})));
}
}
p.text(pos2(r.min.x + 42.0, cy), Align2::LEFT_CENTER, &pr.name, Tokens::ui(12.0), t.text);
let vx = r.min.x + (r.width() * 0.5).max(130.0);
let merge = format!("props-{uid}");
let set = |actions: &mut Actions, v: serde_json::Value| actions.push(("prop.set".into(), json!({"layer": lid, "prop": uid, "value": v, "merge": merge})));
let value = ectx.value(layer, pr);
let is_scale = pr.name == "Scale";
let pct = is_scale || pr.name == "Opacity";
let suffix = if pct { "%" } else { "" };
match &value {
Value::Scalar(v) if pr.name == "Rotation" || pr.name.ends_with(" Rotation") => {
let (rev, deg) = split_rotation(*v);
let g = p.layout_no_wrap(format!("{rev}x{}", if deg < 0.0 { "" } else { "+" }), Tokens::ui(12.0), t.hot_text);
let gw = g.size().x;
p.galley(pos2(vx + 2.0, cy - g.size().y / 2.0), g, t.hot_text);
let (vr, nv, _) =
widgets::hot_number_at(ui, pos2(vx + gw, cy - 9.0), egui::Id::new(("props-v", uid)), deg, 0.5, (-1e9, 1e9), decimals(deg), "°", &t);
app.auto.add(&format!("{base}.value"), vr, &pr.name);
if let Some(nv) = nv {
set(actions, json!(rev as f64 * 360.0 + nv));
}
}
Value::Scalar(v) => {
let range = if pr.name == "Opacity" { (0.0, 100.0) } else { (-1e9, 1e9) };
let (vr, nv, _) = widgets::hot_number_at(ui, pos2(vx, cy - 9.0), egui::Id::new(("props-v", uid)), *v, 0.5, range, decimals(*v), suffix, &t);
app.auto.add(&format!("{base}.value"), vr, &pr.name);
if let Some(nv) = nv {
set(actions, json!(nv));
}
}
Value::Vec2(_) | Value::Vec3(_) => {
let c = value.components();
let n = if pr.shown_dims > 0 && !(layer.is_3d() && c.len() == 3) { pr.shown_dims as usize } else { c.len() };
let mut x = vx;
let link_id = egui::Id::new(("props-scale-link", lid));
let linked = is_scale && ui.data(|d| d.get_temp::<bool>(link_id)).unwrap_or(true);
if is_scale {
// Constrain Proportions toggle, left of the values.
let lr = Rect::from_center_size(pos2(x - 12.0, cy), vec2(12.0, 12.0));
let resp = ui.interact(lr, link_id.with("btn"), Sense::click());
icons::paint(p, lr, Icon::Link, if linked { t.accent } else { t.text_faint });
app.auto.add(&format!("{base}.constrain"), lr, "Constrain Proportions");
if resp.clicked() {
ui.data_mut(|d| d.insert_temp(link_id, !linked));
}
}
for d in 0..n.min(c.len()) {
let (vr, nv, _) =
widgets::hot_number_at(ui, pos2(x, cy - 9.0), egui::Id::new(("props-v", uid, d)), c[d], 1.0, (-1e9, 1e9), decimals(c[d]), suffix, &t);
app.auto.add(&format!("{base}.value.{d}"), vr, &pr.name);
if let Some(nv) = nv {
let mut nc = c.clone();
if linked && c[d].abs() > 1e-9 {
let k = nv / c[d];
for v in nc.iter_mut().take(n) {
*v *= k;
}
}
nc[d] = nv;
set(actions, json!(nc));
}
x = vr.max.x + 10.0;
}
}
_ => {}
}
}
/// Text section; returns the y below it.
#[allow(clippy::too_many_arguments)]
fn text_section(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
doc: &TextDoc,
x0: f32,
w: f32,
mut y: f32,
actions: &mut Actions,
) -> f32 {
let t = app.tokens;
let lid = layer.id.0;
let set = |actions: &mut Actions, v: serde_json::Value| {
let mut v = v;
v["layer"] = json!(lid);
actions.push(("layer.setText".into(), v));
};
section_header(app, ui, p, x0, w, y, "Text", "properties.text");
y += ROW_H + 4.0;
// Font family and style.
let fr = Rect::from_min_size(pos2(x0, y), vec2(w, 22.0));
let pop = egui::Id::new("props-font-pop");
if widgets::dropdown(ui, fr, &doc.font, &t, egui::Id::new("props-font")).clicked() {
widgets::open_popup(ui, pop);
}
app.auto.add("properties.text.font", fr, "Font family");
let fams: Vec<String> = effectcraft_engine::text_families();
if let Some(i) = widgets::popup_menu(ui, pop, fr.left_bottom(), &fams, fams.iter().position(|f| *f == doc.font)) {
set(actions, json!({"font": fams[i]}));
}
y += 28.0;
let sr = Rect::from_min_size(pos2(x0, y), vec2(w, 22.0));
let spop = egui::Id::new("props-style-pop");
if widgets::dropdown(ui, sr, &doc.style, &t, egui::Id::new("props-style")).clicked() {
widgets::open_popup(ui, spop);
}
app.auto.add("properties.text.style", sr, "Font style");
let styles: Vec<String> = ["Regular", "Medium", "SemiBold", "Bold", "Italic"].iter().map(|s| s.to_string()).collect();
if let Some(i) = widgets::popup_menu(ui, spop, sr.left_bottom(), &styles, styles.iter().position(|s| *s == doc.style)) {
set(actions, json!({"style": styles[i]}));
}
y += 32.0;
// Size / leading, tracking / stroke width.
let col2 = x0 + w / 2.0;
let field = |app: &mut EffectcraftApp, ui: &mut egui::Ui, x: f32, y: f32, glyph: &str, key: &str, v: f64, range: (f64, f64), suffix: &str| {
p.text(pos2(x, y + 9.0), Align2::LEFT_CENTER, glyph, Tokens::semibold(11.0), t.text_dim);
let (r, nv, _) = widgets::hot_number_at(ui, pos2(x + 26.0, y), egui::Id::new(("props-text", key)), v, 0.5, range, decimals(v), suffix, &t);
app.auto.add(&format!("properties.text.{key}"), r, key);
nv
};
if let Some(v) = field(app, ui, x0, y, "T", "size", doc.size, (1.0, 2000.0), " px") {
set(actions, json!({"size": v, "merge": "props-text-size"}));
}
match doc.leading {
Some(l) => {
if let Some(v) = field(app, ui, col2, y, "A", "leading", l, (0.0, 5000.0), " px") {
set(actions, json!({"leading": v, "merge": "props-text-leading"}));
}
}
None => {
// Auto Leading: click to switch to an explicit value (120% of the size).
p.text(pos2(col2, y + 9.0), Align2::LEFT_CENTER, "A", Tokens::semibold(11.0), t.text_dim);
let r = Rect::from_min_size(pos2(col2 + 26.0, y), vec2(40.0, 18.0));
let resp = ui.interact(r, egui::Id::new("props-leading-auto"), Sense::click());
p.text(pos2(r.min.x + 2.0, r.center().y), Align2::LEFT_CENTER, "Auto", Tokens::ui(12.0), if resp.hovered() { t.accent_hover } else { t.hot_text });
app.auto.add("properties.text.leading", r, "leading");
if resp.clicked() {
set(actions, json!({"leading": (doc.size * 1.2).round()}));
}
}
}
y += 26.0;
if let Some(v) = field(app, ui, x0, y, "VA", "tracking", doc.tracking, (-1000.0, 10000.0), "") {
set(actions, json!({"tracking": v.round(), "merge": "props-text-tracking"}));
}
if let Some(v) = field(app, ui, col2, y, "W", "strokeWidth", doc.stroke_width, (0.0, 500.0), " px") {
set(actions, json!({"strokeWidth": v, "merge": "props-text-strokeWidth"}));
}
y += 28.0;
// Fill and Stroke, each with an enable checkbox, swatch and label.
for (i, (key, label, on, c)) in [("fill", "Fill", doc.apply_fill, doc.fill), ("stroke", "Stroke", doc.apply_stroke, doc.stroke)].into_iter().enumerate() {
let ry = y + i as f32 * 24.0;
let cr = Rect::from_min_size(pos2(x0, ry + 2.0), vec2(14.0, 14.0));
if widgets::checkbox(ui, cr, on, &t, egui::Id::new(("props-apply", key))).clicked() {
let k = if key == "fill" { "applyFill" } else { "applyStroke" };
set(actions, json!({k: !on}));
}
app.auto.add(&format!("properties.text.{key}.enabled"), cr, label);
let sw = Rect::from_min_size(pos2(x0 + 24.0, ry + 1.0), vec2(16.0, 16.0));
let pop = egui::Id::new(("props-color-pop", key));
if widgets::swatch(ui, sw, c, egui::Id::new(("props-color", key)), &t).clicked() {
widgets::open_popup(ui, pop);
}
app.auto.add(&format!("properties.text.{key}"), sw, label);
let mut rgb = [c[0], c[1], c[2]];
if crate::header::color_popup(ui, pop, sw.left_bottom(), &mut rgb) {
set(actions, json!({key: [rgb[0], rgb[1], rgb[2]], "merge": format!("props-text-{key}")}));
}
p.text(pos2(sw.max.x + 8.0, sw.center().y), Align2::LEFT_CENTER, label, Tokens::ui(12.0), t.text);
}
y += 52.0;
y = more_button(app, ui, p, x0, y, "props-text-more", "properties.text.more", PanelKind::Character);
y + 10.0
}
/// Paragraph section; returns the y below it.
#[allow(clippy::too_many_arguments)]
fn paragraph_section(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
doc: &TextDoc,
x0: f32,
w: f32,
mut y: f32,
actions: &mut Actions,
) -> f32 {
let t = app.tokens;
section_header(app, ui, p, x0, w, y, "Paragraph", "properties.paragraph");
y += ROW_H + 4.0;
for (i, (j, key)) in ALIGNS.into_iter().enumerate() {
let r = Rect::from_min_size(pos2(x0 + i as f32 * 26.0, y), vec2(22.0, 22.0));
let on = doc.justify == j;
let resp = ui.interact(r, egui::Id::new(("props-para", key)), Sense::click());
p.rect_filled(
r,
3.0,
if on {
t.pressed
} else if resp.hovered() {
t.hover
} else {
Color32::TRANSPARENT
},
);
paint_align_glyph(p, r, j, if on { t.text } else { t.text_dim });
app.auto.add(&format!("properties.paragraph.{key}"), r, key);
if resp.clicked() {
actions.push(("layer.setText".into(), json!({"layer": layer.id.0, "justify": key})));
}
}
y += 30.0;
y = more_button(app, ui, p, x0, y, "props-para-more", "properties.paragraph.more", PanelKind::Paragraph);
y + 10.0
}
/// Four lines showing an alignment: last line short for the "justify last …" modes.
fn paint_align_glyph(p: &egui::Painter, r: Rect, j: Justify, c: Color32) {
let full = r.width() - 8.0;
for k in 0..4 {
let ly = r.min.y + 6.0 + k as f32 * 3.5;
let last = k == 3;
let lw = match j {
Justify::Left | Justify::Center | Justify::Right => {
if k % 2 == 1 {
full * 0.6
} else {
full
}
}
Justify::JustifyAll => full,
_ if last => full * 0.55,
_ => full,
};
let lx = match j {
Justify::Center | Justify::JustifyLastCenter => r.center().x - lw / 2.0,
Justify::Right | Justify::JustifyLastRight => r.max.x - 4.0 - lw,
_ => r.min.x + 4.0,
};
p.line_segment([pos2(lx, ly), pos2(lx + lw, ly)], Stroke::new(1.2, c));
}
}
/// "··· More" button that opens the full panel; returns the y below it.
#[allow(clippy::too_many_arguments)]
fn more_button(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, x0: f32, y: f32, id: &str, auto: &str, panel: PanelKind) -> f32 {
let t = app.tokens;
let r = Rect::from_min_size(pos2(x0, y), vec2(64.0, 22.0));
let resp = ui.interact(r, egui::Id::new(id), Sense::click());
p.rect_filled(r, 4.0, if resp.hovered() { t.hover } else { t.field_bg });
p.text(pos2(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, "···", Tokens::semibold(12.0), t.text);
p.text(pos2(r.min.x + 26.0, r.center().y), Align2::LEFT_CENTER, "More", Tokens::ui(12.0), t.text);
app.auto.add(auto, r, "More");
if resp.clicked() {
app.show_panel(panel);
}
y + 28.0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rotation_splits_like_ae() {
assert_eq!(split_rotation(0.0), (0, 0.0));
assert_eq!(split_rotation(390.0), (1, 30.0));
assert_eq!(split_rotation(-45.0), (0, -45.0));
assert_eq!(split_rotation(-725.0), (-2, -5.0));
}
#[test]
fn decimals_hide_whole_numbers() {
assert_eq!(decimals(960.0), 0);
assert_eq!(decimals(960.5), 1);
}
}
+504
View File
@@ -0,0 +1,504 @@
//! Render Queue panel, laid out like After Effects': a Current Render strip (progress bar,
//! elapsed / estimated remaining, Stop and Render buttons), the queue list (twirl, Render
//! checkbox, label, #, Comp Name, Status, Started, Render Time) with expandable Render Settings,
//! Output Module and Output To rows, and a status footer.
//!
//! Every control dispatches an engine `renderQueue.*` command (so agents can do the same) and
//! registers an automation id: `renderQueue.render`, `renderQueue.stop`,
//! `renderQueue.item.<n>.{row,twirl,render,renderSettings,outputModule,outputTo,outputPath}`.
use effectcraft_engine::project::render_queue::{AudioOutput, Channels, OutputFormat, ProResProfile, RenderQuality, RenderQueueItem, RenderStatus, TimeSpan};
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde_json::{Value, json};
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
const TOP_H: f32 = 74.0;
const HEAD_H: f32 = 22.0;
const ROW_H: f32 = 24.0;
const FOOT_H: f32 = 24.0;
/// `h:mm:ss` for a duration in seconds.
pub fn hms(secs: f64) -> String {
let s = secs.max(0.0).round() as u64;
format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
}
/// Unix seconds → `YYYY-MM-DD hh:mm:ss` (UTC).
pub fn utc_stamp(unix: u64) -> String {
let days = (unix / 86_400) as i64;
let rem = unix % 86_400;
// Civil-from-days (proleptic Gregorian).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}", rem / 3600, rem / 60 % 60, rem % 60)
}
fn status_color(t: &Tokens, s: &RenderStatus) -> Color32 {
match s {
RenderStatus::Done => Color32::from_rgb(0x6c, 0xc0, 0x6c),
RenderStatus::Rendering => t.accent_hover,
RenderStatus::Failed(_) | RenderStatus::NeedsOutput => t.danger,
RenderStatus::UserStopped => t.warning,
RenderStatus::Unqueued => t.text_faint,
RenderStatus::Queued => t.text,
}
}
/// Render Settings menu: (label, params).
fn settings_menu(it: &RenderQueueItem) -> Vec<(String, Value)> {
let s = &it.settings;
let mark = |on: bool, l: &str| if on { format!("✓ {l}") } else { format!(" {l}") };
let mut v = vec![
(mark(s.quality == RenderQuality::Best, "Best Settings"), json!({"quality": "best"})),
(mark(s.quality == RenderQuality::Draft, "Draft Settings"), json!({"quality": "draft"})),
("-".into(), Value::Null),
];
for (l, k) in [("Full", "full"), ("Half", "half"), ("Third", "third"), ("Quarter", "quarter")] {
v.push((mark(s.resolution_label() == l, &format!("Resolution: {l}")), json!({"resolution": k})));
}
v.push(("-".into(), Value::Null));
v.push((mark(s.time_span == TimeSpan::WorkArea, "Time Span: Work Area Only"), json!({"timeSpan": "workArea"})));
v.push((mark(s.time_span == TimeSpan::LengthOfComp, "Time Span: Length of Comp"), json!({"timeSpan": "comp"})));
v.push(("-".into(), Value::Null));
v.push((mark(s.frame_rate.is_none(), "Frame Rate: Use comp's frame rate"), json!({"frameRate": null})));
for fps in [12.0, 15.0, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 60.0] {
let on = s.frame_rate.is_some_and(|r| (r.as_f64() - fps).abs() < 0.01);
v.push((mark(on, &format!("Frame Rate: {fps}")), json!({"frameRate": fps})));
}
v.push(("-".into(), Value::Null));
v.push((mark(s.motion_blur, "Motion Blur: On for Checked Layers"), json!({"motionBlur": !s.motion_blur})));
v.push((mark(s.skip_existing, "Skip Existing Files"), json!({"skipExisting": !s.skip_existing})));
v
}
/// Output Module menu: (label, params).
fn output_menu(it: &RenderQueueItem, available: &[OutputFormat]) -> Vec<(String, Value)> {
let o = &it.output;
let mark = |on: bool, l: &str| if on { format!("✓ {l}") } else { format!(" {l}") };
let mut v = Vec::new();
for f in OutputFormat::ALL {
if available.contains(&f) {
v.push((mark(o.format == f, &format!("Format: {}", f.label())), json!({"format": format!("{f:?}")})));
}
}
v.push(("-".into(), Value::Null));
v.push((mark(o.channels == Channels::Rgb, "Channels: RGB"), json!({"channels": "rgb"})));
if o.format.supports_alpha() {
v.push((mark(o.channels == Channels::Rgba, "Channels: RGB + Alpha"), json!({"channels": "rgba"})));
}
match o.format {
OutputFormat::ProRes => {
v.push(("-".into(), Value::Null));
for p in ProResProfile::ALL {
v.push((mark(o.prores_profile == p, p.label()), json!({"proresProfile": format!("{p:?}")})));
}
}
OutputFormat::H264 => {
v.push(("-".into(), Value::Null));
for kbps in [2_000, 5_000, 10_000, 20_000, 40_000] {
v.push((mark(o.bitrate_kbps == kbps, &format!("Bitrate: {} Mbps", kbps / 1000)), json!({"bitrate": kbps})));
}
}
OutputFormat::JpegSequence => {
v.push(("-".into(), Value::Null));
for q in [60u8, 80, 90, 100] {
v.push((mark(o.quality == q, &format!("Quality: {q}")), json!({"quality": q})));
}
}
OutputFormat::Gif => {
v.push(("-".into(), Value::Null));
v.push((mark(o.gif_loop, "Loop Forever"), json!({"loop": !o.gif_loop})));
}
_ => {}
}
if o.format.supports_audio() {
v.push(("-".into(), Value::Null));
for (a, l) in [(AudioOutput::Auto, "auto"), (AudioOutput::On, "on"), (AudioOutput::Off, "off")] {
let label = match a {
AudioOutput::Auto => "Audio Output: Auto",
AudioOutput::On => "Audio Output: On (48 kHz stereo)",
AudioOutput::Off => "Audio Output: Off",
};
v.push((mark(o.audio == a, label), json!({"audio": l})));
}
}
v
}
const OUTPUT_TEMPLATES: [&str; 4] = [
"[compName].[fileExtension]",
"[compName]_[width]x[height].[fileExtension]",
"[projectName]_[compName].[fileExtension]",
"[compName]/[compName].[fileExtension]",
];
fn output_to_menu(it: &RenderQueueItem) -> Vec<(String, Value)> {
let mut v: Vec<(String, Value)> = OUTPUT_TEMPLATES
.iter()
.map(|t| {
let t = if it.output.format.is_sequence() { t.replace(".[fileExtension]", "_[#####].[fileExtension]") } else { t.to_string() };
(t.clone(), json!({"path": t}))
})
.collect();
v.push(("-".into(), Value::Null));
v.push(("Choose File…".into(), json!({"choose": true})));
v
}
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
let queue: Vec<RenderQueueItem> = app.session.project.render_queue.clone();
let progress = app.session.render_progress();
let rendering = app.session.is_rendering();
let available = app.session.exporter.as_ref().map(|e| e.formats()).unwrap_or_default();
let mut actions: Vec<(&'static str, Value)> = Vec::new();
let state_id = egui::Id::new("rq-ui");
let (mut open, mut selected): (Vec<u64>, Option<u64>) = ui.data(|d| d.get_temp(state_id).unwrap_or_default());
// ---------------------------------------------------------- Current Render strip
let top = Rect::from_min_size(rect.min, vec2(rect.width(), TOP_H));
p.rect_filled(top, 0.0, t.tl_ruler_bg);
let x0 = rect.min.x + 12.0;
p.text(pos2(x0, top.min.y + 16.0), Align2::LEFT_CENTER, "Current Render", Tokens::semibold(12.5), t.text);
let cur_item = progress.as_ref().and_then(|p| p.current).and_then(|id| queue.iter().find(|i| i.id == id));
let cur_name = cur_item.and_then(|i| app.session.project.item(i.comp)).map(|i| i.name.clone());
if let Some(pr) = &progress {
let rem = pr.remaining.map(hms).unwrap_or_else(|| "–".into());
p.text(
pos2(top.max.x - 12.0, top.min.y + 16.0),
Align2::RIGHT_CENTER,
format!("Elapsed: {} Est. Remain: {rem}", hms(pr.item_elapsed)),
Tokens::ui(11.5),
t.text_dim,
);
}
let bw = 76.0;
let render_b = Rect::from_min_size(pos2(top.max.x - 12.0 - bw, top.min.y + 34.0), vec2(bw, 26.0));
let stop_b = Rect::from_min_size(pos2(render_b.min.x - 8.0 - bw, render_b.min.y), vec2(bw, 26.0));
let can_render = !rendering && queue.iter().any(RenderQueueItem::is_queued) && !available.is_empty();
if widgets::text_button(ui, render_b, "Render", can_render, &t, egui::Id::new("rq-render")).clicked() && can_render {
actions.push(("renderQueue.render", json!({"wait": false})));
}
app.auto.add("renderQueue.render", render_b, "Render");
if rendering {
if widgets::text_button(ui, stop_b, "Stop", false, &t, egui::Id::new("rq-stop")).clicked() {
actions.push(("renderQueue.stop", json!({})));
}
app.auto.add("renderQueue.stop", stop_b, "Stop");
}
// Progress bar.
let bar =
Rect::from_min_max(pos2(x0, render_b.min.y + 4.0), pos2(if rendering { stop_b.min.x - 16.0 } else { render_b.min.x - 16.0 }, render_b.max.y - 4.0));
p.rect_filled(bar, 3.0, t.field_bg);
p.rect_stroke(bar, 3.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
let frac = progress.as_ref().filter(|p| p.total > 0).map(|p| (p.done as f32 / p.total as f32).clamp(0.0, 1.0)).unwrap_or(0.0);
if frac > 0.0 {
let fill = Rect::from_min_size(bar.min, vec2(bar.width() * frac, bar.height()));
p.rect_filled(fill, 3.0, t.accent);
}
let bar_text = match (&progress, &cur_name) {
(Some(pr), Some(n)) if rendering => format!("Rendering “{n}” {} / {} frames", pr.done, pr.total),
_ => {
let n = queue.iter().filter(|i| i.is_queued()).count();
if available.is_empty() {
"Export is not available in this build".to_string()
} else if n == 0 {
"Composition ▸ Add to Render Queue (Ctrl/⌘ M) to queue a render".to_string()
} else {
format!("{n} item(s) queued")
}
}
};
p.text(pos2(bar.min.x + 8.0, bar.center().y), Align2::LEFT_CENTER, bar_text, Tokens::ui(11.5), t.text);
app.auto.add("renderQueue.progress", bar, &format!("{:.0}%", frac * 100.0));
// ---------------------------------------------------------- column header
let head = Rect::from_min_size(pos2(rect.min.x, top.max.y), vec2(rect.width(), HEAD_H));
p.rect_filled(head, 0.0, t.panel_bg);
p.line_segment([head.left_bottom(), head.right_bottom()], Stroke::new(1.0, t.separator));
// Columns: twirl | Render | label | # | Comp Name | Status | Started | Render Time
let cx_twirl = rect.min.x + 4.0;
let cx_render = cx_twirl + 20.0;
let cx_label = cx_render + 48.0;
let cx_num = cx_label + 20.0;
let cx_name = cx_num + 28.0;
let w_time = 92.0;
let w_started = 156.0;
let w_status = 112.0;
let cx_time = (rect.max.x - w_time).max(cx_name + 120.0);
let cx_started = cx_time - w_started;
let cx_status = cx_started - w_status;
let hy = head.center().y;
for (x, l) in [(cx_render, "Render"), (cx_num, "#"), (cx_name, "Comp Name"), (cx_status, "Status"), (cx_started, "Started"), (cx_time, "Render Time")] {
p.text(pos2(x + 2.0, hy), Align2::LEFT_CENTER, l, Tokens::ui(11.0), t.text_dim);
}
for x in [cx_render, cx_label, cx_num, cx_name, cx_status, cx_started, cx_time] {
p.line_segment([pos2(x - 3.0, head.min.y + 4.0), pos2(x - 3.0, head.max.y - 4.0)], Stroke::new(1.0, t.separator));
}
// ---------------------------------------------------------- items
let list = Rect::from_min_max(pos2(rect.min.x, head.max.y), pos2(rect.max.x, rect.max.y - FOOT_H));
let lp = p.with_clip_rect(list);
let mut y = list.min.y;
if queue.is_empty() {
lp.text(pos2(list.center().x, list.min.y + 30.0), Align2::CENTER_CENTER, "The render queue is empty.", Tokens::ui(12.0), t.text_faint);
}
let editing_id = egui::Id::new("rq-edit-output");
let mut editing: Option<(u64, String)> = ui.data(|d| d.get_temp(editing_id));
for (k, it) in queue.iter().enumerate() {
let n = k + 1;
let aid = |s: &str| format!("renderQueue.item.{n}.{s}");
let row = Rect::from_min_size(pos2(list.min.x, y), vec2(list.width(), ROW_H));
y += ROW_H;
let is_sel = selected == Some(it.id);
lp.rect_filled(
row,
0.0,
if is_sel {
t.row_selected
} else if k % 2 == 0 {
t.row
} else {
t.row_alt
},
);
let row_resp = ui.interact(row, egui::Id::new(("rq-row", it.id)), Sense::click());
if row_resp.clicked() {
selected = Some(it.id);
app.ui.focused = crate::dock::PanelKind::RenderQueue;
}
let item_id = it.id;
row_resp.context_menu(|ui| {
if ui.button("Duplicate").clicked() {
actions.push(("renderQueue.duplicate", json!({"item": item_id})));
ui.close();
}
if ui.button("Remove").clicked() {
actions.push(("renderQueue.remove", json!({"item": item_id})));
ui.close();
}
if k > 0 && ui.button("Move Up").clicked() {
actions.push(("renderQueue.move", json!({"item": item_id, "to": n - 1})));
ui.close();
}
if n < queue.len() && ui.button("Move Down").clicked() {
actions.push(("renderQueue.move", json!({"item": item_id, "to": n + 1})));
ui.close();
}
});
app.auto.add(&aid("row"), row, &format!("#{n}"));
let is_open = open.contains(&it.id);
let tw = Rect::from_center_size(pos2(cx_twirl + 8.0, row.center().y), vec2(14.0, 14.0));
if widgets::twirl(ui, tw, is_open, egui::Id::new(("rq-twirl", it.id)), &t).clicked() {
if is_open {
open.retain(|i| *i != it.id);
} else {
open.push(it.id);
}
}
app.auto.add(&aid("twirl"), tw, "Twirl");
let cb = Rect::from_center_size(pos2(cx_render + 20.0, row.center().y), vec2(18.0, 18.0));
if widgets::checkbox(ui, cb, it.render, &t, egui::Id::new(("rq-cb", it.id))).clicked() && !rendering {
actions.push(("renderQueue.setRender", json!({"item": it.id, "render": !it.render})));
}
app.auto.add(&aid("render"), cb, if it.render { "Render: on" } else { "Render: off" });
let comp_item = app.session.project.item(it.comp);
let label_col = comp_item.map(|i| Tokens::label(i.label)).unwrap_or(t.text_faint);
lp.rect_filled(Rect::from_center_size(pos2(cx_label + 6.0, row.center().y), vec2(10.0, 10.0)), 2.0, label_col);
lp.text(pos2(cx_num + 2.0, row.center().y), Align2::LEFT_CENTER, n.to_string(), Tokens::ui(12.0), t.text_dim);
let name = comp_item.map(|i| i.name.clone()).unwrap_or_else(|| "(missing composition)".into());
lp.text(pos2(cx_name + 2.0, row.center().y), Align2::LEFT_CENTER, &name, Tokens::ui(12.0), t.text);
let status = if rendering && progress.as_ref().and_then(|p| p.current) == Some(it.id) {
let pr = progress.as_ref().expect("progress");
format!("Rendering {:.0}%", if pr.total > 0 { pr.done as f64 * 100.0 / pr.total as f64 } else { 0.0 })
} else {
it.status.label().to_string()
};
let st_rect = Rect::from_min_size(pos2(cx_status, row.min.y), vec2(w_status, ROW_H));
lp.text(pos2(cx_status + 2.0, row.center().y), Align2::LEFT_CENTER, &status, Tokens::ui(12.0), status_color(&t, &it.status));
if let RenderStatus::Failed(e) = &it.status {
ui.interact(st_rect, egui::Id::new(("rq-st", it.id)), Sense::hover()).on_hover_text(e);
}
app.auto.add(&aid("status"), st_rect, &status);
if let Some(s) = it.started {
lp.text(pos2(cx_started + 2.0, row.center().y), Align2::LEFT_CENTER, utc_stamp(s), Tokens::ui(11.5), t.text_dim);
} else {
lp.text(pos2(cx_started + 2.0, row.center().y), Align2::LEFT_CENTER, "-", Tokens::ui(11.5), t.text_faint);
}
let rt = if progress.as_ref().and_then(|p| p.current) == Some(it.id) && rendering {
progress.as_ref().map(|p| hms(p.item_elapsed)).unwrap_or_default()
} else {
it.render_time.map(|s| if s < 60.0 { format!("{s:.1} s") } else { hms(s) }).unwrap_or_else(|| "-".into())
};
lp.text(pos2(cx_time + 2.0, row.center().y), Align2::LEFT_CENTER, rt, Tokens::ui(11.5), t.text_dim);
if !is_open {
continue;
}
// Expanded: Render Settings / Output Module + Output To.
let ix = cx_name;
for sub in 0..2 {
let r = Rect::from_min_size(pos2(list.min.x, y), vec2(list.width(), ROW_H));
y += ROW_H;
lp.rect_filled(r, 0.0, t.panel_bg);
let (label, summary, key, menu): (&str, String, &str, Vec<(String, Value)>) = if sub == 0 {
("Render Settings:", it.settings.summary(), "renderSettings", settings_menu(it))
} else {
("Output Module:", it.output.summary(), "outputModule", output_menu(it, &available))
};
lp.text(pos2(cx_num - 6.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::ui(11.5), t.text_dim);
let dd = Rect::from_min_size(pos2(ix + 70.0, r.min.y + 3.0), vec2(220.0, ROW_H - 6.0));
let did = egui::Id::new(("rq-dd", it.id, sub));
if widgets::dropdown(ui, dd, &summary, &t, did).clicked() && !rendering {
widgets::open_popup(ui, did);
}
let labels: Vec<String> = menu.iter().map(|(l, _)| l.clone()).collect();
if let Some(i) = widgets::popup_menu(ui, did, dd.left_bottom(), &labels, None) {
let mut params = menu[i].1.clone();
params["item"] = json!(it.id);
actions.push((if sub == 0 { "renderQueue.setRenderSettings" } else { "renderQueue.setOutputModule" }, params));
}
app.auto.add(&aid(key), dd, &summary);
if sub == 0 {
let comp = app.session.project.comp(it.comp);
if let Some(c) = comp {
let (w, h) = it.settings.output_size(c);
let (a, b) = it.settings.span(c);
let info = format!(
"{w}×{h} · {:.3} fps · {:.2}s – {:.2}s · {} frames",
it.settings.rate(c).as_f64(),
a.seconds(),
b.seconds(),
it.settings.frame_count(c)
);
lp.text(pos2(dd.max.x + 14.0, r.center().y), Align2::LEFT_CENTER, info, Tokens::ui(11.0), t.text_faint);
}
continue;
}
// Output To.
let ox = dd.max.x + 14.0;
lp.text(pos2(ox, r.center().y), Align2::LEFT_CENTER, "Output To:", Tokens::ui(11.5), t.text_dim);
let odd = Rect::from_min_size(pos2(ox + 62.0, r.min.y + 3.0), vec2(22.0, ROW_H - 6.0));
let oid = egui::Id::new(("rq-out", it.id));
if widgets::dropdown(ui, odd, "", &t, oid).clicked() && !rendering {
widgets::open_popup(ui, oid);
}
app.auto.add(&aid("outputTo"), odd, "Output To");
let omenu = output_to_menu(it);
let olabels: Vec<String> = omenu.iter().map(|(l, _)| l.clone()).collect();
if let Some(i) = widgets::popup_menu(ui, oid, odd.left_bottom(), &olabels, None) {
if omenu[i].1.get("choose").is_some() {
let default = app.session.resolve_output(it).unwrap_or_default();
let picked = app
.hooks
.pick_save
.as_ref()
.and_then(|f| f(std::path::Path::new(&default).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default().as_str()));
match picked {
Some(path) => actions.push(("renderQueue.setOutput", json!({"item": it.id, "path": path}))),
None if app.hooks.pick_save.is_none() => editing = Some((it.id, it.output.output.clone())),
None => {}
}
} else {
let mut params = omenu[i].1.clone();
params["item"] = json!(it.id);
actions.push(("renderQueue.setOutput", params));
}
}
let path_rect = Rect::from_min_max(pos2(odd.max.x + 6.0, r.min.y + 2.0), pos2(r.max.x - 8.0, r.max.y - 2.0));
if editing.as_ref().is_some_and(|(id, _)| *id == it.id) {
let mut buf = editing.as_ref().map(|(_, b)| b.clone()).unwrap_or_default();
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(path_rect));
let resp = child.add(egui::TextEdit::singleline(&mut buf).desired_width(path_rect.width()).font(Tokens::ui(11.5)));
if resp.lost_focus() {
if ui.input(|i| i.key_pressed(egui::Key::Enter)) && !buf.trim().is_empty() {
actions.push(("renderQueue.setOutput", json!({"item": it.id, "path": buf.trim()})));
}
editing = None;
} else {
resp.request_focus();
editing = Some((it.id, buf));
}
} else {
let shown = app.session.resolve_output(it).unwrap_or_else(|| "Not yet specified".into());
let resp = ui.interact(path_rect, egui::Id::new(("rq-path", it.id)), Sense::click());
let col = if resp.hovered() { t.accent_hover } else { t.hot_text };
lp.with_clip_rect(path_rect.intersect(list)).text(pos2(path_rect.min.x, r.center().y), Align2::LEFT_CENTER, &shown, Tokens::ui(11.5), col);
if resp.clicked() && !rendering {
editing = Some((it.id, it.output.output.clone()));
}
resp.on_hover_text(format!("Template: {}\nClick to edit", it.output.output));
app.auto.add(&aid("outputPath"), path_rect, &shown);
}
}
}
ui.data_mut(|d| match &editing {
Some(e) => {
d.insert_temp(editing_id, e.clone());
}
None => d.remove::<(u64, String)>(editing_id),
});
// Delete removes the selected item when the panel has focus.
if app.ui.focused == crate::dock::PanelKind::RenderQueue
&& editing.is_none()
&& !rendering
&& let Some(id) = selected
&& ui.input(|i| i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace))
&& !ui.ctx().egui_wants_keyboard_input()
{
actions.push(("renderQueue.remove", json!({"item": id})));
selected = None;
}
// ---------------------------------------------------------- footer
let foot = Rect::from_min_max(pos2(rect.min.x, rect.max.y - FOOT_H), rect.max);
p.rect_filled(foot, 0.0, t.tl_ruler_bg);
p.line_segment([foot.left_top(), foot.right_top()], Stroke::new(1.0, t.separator));
let msg = match &progress {
Some(pr) if rendering => format!("Message: Rendering {} of {}", (pr.items_done + 1).min(pr.items_total), pr.items_total),
_ => {
let done = queue.iter().filter(|i| i.status == RenderStatus::Done).count();
format!("Message: {done} of {} done", queue.len())
}
};
p.text(pos2(foot.min.x + 12.0, foot.center().y), Align2::LEFT_CENTER, msg, Tokens::ui(11.0), t.text_dim);
let started = queue.iter().filter(|i| i.started.is_some()).count();
let total: f64 = queue.iter().filter_map(|i| i.render_time).sum();
p.text(
pos2(foot.max.x - 12.0, foot.center().y),
Align2::RIGHT_CENTER,
format!("Renders Started: {started} Total Time Elapsed: {}", hms(progress.as_ref().filter(|_| rendering).map(|p| p.elapsed).unwrap_or(total))),
Tokens::ui(11.0),
t.text_dim,
);
open.retain(|id| queue.iter().any(|i| i.id == *id));
ui.data_mut(|d| d.insert_temp(state_id, (open, selected)));
let ctx = ui.ctx().clone();
for (id, params) in actions {
if let Err(e) = crate::menus::invoke(app, &ctx, id, params) {
app.ui.status = e;
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn stamps() {
assert_eq!(super::utc_stamp(0), "1970-01-01 00:00:00");
assert_eq!(super::utc_stamp(1_700_000_000), "2023-11-14 22:13:20");
assert_eq!(super::hms(3725.4), "1:02:05");
}
}
+28 -10
View File
@@ -57,16 +57,21 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
actions.push(json!({"style": styles[i]}));
}
y += 34.0;
// Numeric fields in a 2-column grid.
let fields: [(&str, &str, f64, (f64, f64), &str); 6] = [
// Numeric fields in AE's two-column grid.
let fields: [(&str, &str, f64, (f64, f64), &str); 8] = [
("size", "T", doc.size, (1.0, 2000.0), " px"),
("leading", "A", doc.leading.unwrap_or(doc.size * 1.2), (0.0, 5000.0), " px"),
("tracking", "VA", doc.tracking, (-1000.0, 10000.0), ""),
("strokeWidth", "≡", doc.stroke_width, (0.0, 500.0), " px"),
("strokeWidth", "W", doc.stroke_width, (0.0, 500.0), " px"),
("vScale", "↕T", doc.v_scale, (1.0, 1000.0), " %"),
("hScale", "↔T", doc.h_scale, (1.0, 1000.0), " %"),
("baselineShift", "A↑", doc.baseline_shift, (-1000.0, 1000.0), " px"),
("hScale", "↔", doc.h_scale, (1.0, 1000.0), "%"),
("", "", 0.0, (0.0, 0.0), ""),
];
for (i, (key, glyph, v, range, suffix)) in fields.into_iter().enumerate() {
if key.is_empty() {
continue;
}
let col = i % 2;
let row = i / 2;
let fx = x0 + col as f32 * (w / 2.0);
@@ -77,13 +82,25 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if let Some(nv) = nv
&& enabled
{
let k = if key == "baselineShift" || key == "hScale" { "tracking" } else { key };
if k == key {
actions.push(json!({key: nv, "merge": format!("char-{key}")}));
}
actions.push(json!({key: nv, "merge": format!("char-{key}")}));
}
}
y += 3.0 * 28.0 + 8.0;
// Stroke Over Fill / Fill Over Stroke (bottom-right cell).
{
let fx = x0 + w / 2.0;
let fy = y + 3.0 * 28.0;
let dr = Rect::from_min_size(pos2(fx, fy), vec2(w / 2.0, 20.0));
let labels = vec!["Fill Over Stroke".to_string(), "Stroke Over Fill".to_string()];
let pop = egui::Id::new("char-stroke-order-pop");
if widgets::dropdown(ui, dr, &labels[doc.stroke_over_fill as usize], &t, egui::Id::new("char-stroke-order")).clicked() && enabled {
widgets::open_popup(ui, pop);
}
app.auto.add("character.strokeOverFill", dr, "Stroke order");
if let Some(i) = widgets::popup_menu(ui, pop, dr.left_bottom(), &labels, Some(doc.stroke_over_fill as usize)) {
actions.push(json!({"strokeOverFill": i == 1}));
}
}
y += 4.0 * 28.0 + 8.0;
// Fill / stroke swatches.
p.text(pos2(x0, y + 10.0), Align2::LEFT_CENTER, "Fill", Tokens::ui(11.5), t.text_dim);
let fs = Rect::from_min_size(pos2(x0 + 34.0, y), vec2(26.0, 20.0));
@@ -107,7 +124,8 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
y += 32.0;
// Style toggles.
let toggles = [("fauxBold", "T", doc.faux_bold), ("fauxItalic", "T", doc.faux_italic), ("allCaps", "TT", doc.all_caps)];
let toggles =
[("fauxBold", "T", doc.faux_bold), ("fauxItalic", "T", doc.faux_italic), ("allCaps", "TT", doc.all_caps), ("smallCaps", "Tт", doc.small_caps)];
for (i, (key, label, on)) in toggles.into_iter().enumerate() {
let r = Rect::from_min_size(pos2(x0 + i as f32 * 34.0, y), vec2(30.0, 24.0));
let resp = ui.interact(r, egui::Id::new(("char-t", key)), Sense::click());
+228 -111
View File
@@ -21,8 +21,54 @@ use crate::{EffectcraftApp, widgets};
#[derive(Clone, Debug)]
enum RowKind {
Layer,
Group { uid: u64, name: String, open: bool, has_children: bool, fx: Option<bool> },
Prop { uid: u64 },
Group {
uid: u64,
name: String,
open: bool,
has_children: bool,
fx: Option<bool>,
},
Prop {
uid: u64,
},
/// Inline expression editor under a property with an expression.
Expr {
uid: u64,
lines: usize,
},
}
/// Row height (expression editors grow with their text).
fn row_height(row: &Row, rh: f32) -> f32 {
match row.kind {
RowKind::Expr { lines, .. } => rh * lines.clamp(1, 8) as f32 + 6.0,
_ => rh,
}
}
/// Insert an expression editor row after every property that has an expression.
fn with_expr_rows(rows: Vec<Row>, comp: &Comp, closed: &std::collections::BTreeSet<u64>) -> Vec<Row> {
let mut out = Vec::with_capacity(rows.len());
for r in rows {
let extra = match r.kind {
RowKind::Prop { uid } if !closed.contains(&uid) => comp.layer(r.layer).and_then(|l| l.props.find(uid)).and_then(|p| p.expr.as_ref()).map(|e| Row {
layer: r.layer,
depth: r.depth,
kind: RowKind::Expr { uid, lines: e.text.lines().count().max(1) },
}),
_ => None,
};
out.push(r);
out.extend(extra);
}
out
}
/// A pick-whip drag in progress: (parent = 0 / property = 1, layer, prop uid, start point).
type PickWhip = (u8, u64, u64, Pos2);
fn pick_whip_id() -> egui::Id {
egui::Id::new("tl-pickwhip")
}
#[derive(Clone, Debug)]
@@ -65,17 +111,17 @@ fn cols(x0: f32, width: f32, show_modes: bool) -> Cols {
/// Timeline horizontal mapping.
#[derive(Clone, Copy, Debug)]
struct TMap {
x0: f32,
start: f64,
pps: f64,
pub(crate) struct TMap {
pub x0: f32,
pub start: f64,
pub pps: f64,
}
impl TMap {
fn x(&self, secs: f64) -> f32 {
pub fn x(&self, secs: f64) -> f32 {
self.x0 + ((secs - self.start) * self.pps) as f32
}
fn t(&self, x: f32) -> f64 {
pub fn t(&self, x: f32) -> f64 {
self.start + (x - self.x0) as f64 / self.pps
}
}
@@ -144,6 +190,10 @@ fn prop_visible(p: &Property, layer: &Layer) -> bool {
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
}
@@ -171,7 +221,7 @@ fn build_rows(app: &EffectcraftApp, comp: &Comp) -> Vec<Row> {
}
if let Some(kind) = tl.reveal.first() {
let (group, props): (&str, Vec<&str>) = match kind.as_str() {
"position" => ("transform", vec!["position"]),
"position" => ("transform", vec!["position", "positionX", "positionY", "positionZ"]),
"scale" => ("transform", vec!["scale"]),
"rotation" => ("transform", vec!["rotation", "rotationX", "rotationY", "orientation"]),
"opacity" => ("transform", vec!["opacity"]),
@@ -325,7 +375,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let ruler_h = 34.0;
let colhdr_h = 22.0;
let footer_h = 24.0;
let left_w = (rect.width() * 0.5).clamp(420.0, 860.0);
let fixed = AV_W + LABEL_W + NUM_W + SW * 8.0 + if app.ui.timeline.show_modes { 92.0 + 112.0 } else { 0.0 } + 116.0 + 6.0;
let left_w = (fixed + 190.0).clamp(420.0, (rect.width() * 0.62).max(420.0));
let cw = cols(rect.min.x, left_w, app.ui.timeline.show_modes);
let graph_x0 = rect.min.x + left_w + 1.0;
let graph_x1 = rect.max.x - 10.0;
@@ -349,7 +400,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let tc_rect = Rect::from_min_size(pos2(rect.min.x + 12.0, top + 6.0), vec2(150.0, 24.0));
let tc_resp = ui.interact(tc_rect, egui::Id::new("tl-timecode"), Sense::click_and_drag());
p.text(tc_rect.left_center(), Align2::LEFT_CENTER, &tc, Tokens::semibold(20.0), t.timecode);
let sub = format!("{} ({:.2} fps)", fr.frame_at(time), fr.as_f64());
let sub = format!("{:05} ({:.2} fps)", fr.frame_at(time) + app.session.project.settings.frame_start, fr.as_f64());
p.text(pos2(tc_rect.min.x, tc_rect.max.y + 8.0), Align2::LEFT_CENTER, sub, Tokens::ui(10.5), t.text_faint);
app.auto.add("timeline.timecode", tc_rect, &tc);
if tc_resp.dragged() {
@@ -461,14 +512,26 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
draw_run(a, b);
}
// Ticks + labels.
let secs_per_label = [0.0333, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0].into_iter().find(|s| s * pps >= 70.0).unwrap_or(60.0);
// Label spacing in whole frames (AE: `00:15f`-style seconds:frames labels).
let fps_i = fr.as_f64().round().max(1.0) as i64;
let half = (fps_i / 2).max(1);
let label_frames = [1, 2, 5, 10, half, fps_i, 2 * fps_i, 5 * fps_i, 10 * fps_i, 30 * fps_i, 60 * fps_i]
.into_iter()
.find(|f| *f as f64 * fd * pps >= 52.0)
.unwrap_or(60 * fps_i);
let secs_per_label = label_frames as f64 * fd;
let first = (tm.start / secs_per_label).floor() * secs_per_label;
let mut s = first;
let pr = p.with_clip_rect(Rect::from_min_max(pos2(graph_x0, ruler.min.y), ruler.max));
while s <= tm.t(graph_x1) + secs_per_label {
let x = tm.x(s);
pr.line_segment([pos2(x, ruler.max.y - 10.0), pos2(x, ruler.max.y)], Stroke::new(1.0, t.tl_ruler_tick));
let label = if secs_per_label < 1.0 { format!("{:02}f", fr.frame_at(Tick::from_seconds_f64(s + 1e-9))) } else { format!("{:02}s", s.round() as i64) };
let fno = (s / fd).round() as i64;
let label = if fno >= 60 * fps_i * 60 {
format!("{}:{:02}:{:02}f", fno / (fps_i * 60), (fno / fps_i) % 60, fno % fps_i)
} else {
format!("{:02}:{:02}f", fno / fps_i, fno % fps_i)
};
pr.text(pos2(x + 3.0, ruler.max.y - 16.0), Align2::LEFT_CENTER, label, Tokens::ui(10.0), t.tl_ruler_text);
for k in 1..5 {
let xx = tm.x(s + secs_per_label * k as f64 / 5.0);
@@ -523,9 +586,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let _ = cw.end;
// ---- rows.
let rows = build_rows(app, &comp);
let rows = with_expr_rows(build_rows(app, &comp), &comp, &app.ui.timeline.expr_closed);
let rh = t.row_h;
let total_h = rows.len() as f32 * rh;
let total_h: f32 = rows.iter().map(|r| row_height(r, rh)).sum();
let max_scroll = (total_h - rows_rect.height() + rh).max(0.0);
if ui.rect_contains_pointer(rows_rect) {
let (dy, dx, zoom) = ui.input(|i| (i.smooth_scroll_delta.y, i.smooth_scroll_delta.x, i.modifiers.alt));
@@ -551,16 +614,27 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mut ui_actions: Vec<UiAct> = Vec::new();
let idx_of = |id: LayerId| comp.index_of(id).unwrap_or(0);
let graph_on = app.ui.timeline.graph_editor;
let full_clip = ui.clip_rect();
let left_clip = full_clip.intersect(Rect::from_min_max(pos2(rect.min.x, rows_rect.min.y), pos2(graph_x0 - 1.0, rows_rect.max.y)));
let right_clip = full_clip.intersect(Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max));
// Registered before the rows so keys, bars and editors on top of it get the pointer first.
let empty_rect = if graph_on { Rect::NOTHING } else { Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max) };
let empty = ui.interact(empty_rect, egui::Id::new("tl-graph-bg"), Sense::click_and_drag());
let mut hit_rows: Vec<(Rect, Row)> = vec![];
for (ri, row) in rows.iter().enumerate() {
let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), rh));
y += rh;
// Outline widgets never spill into the time graph (narrow timelines).
ui.set_clip_rect(left_clip);
let hh = row_height(row, rh);
let r = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), hh));
y += hh;
if r.max.y < rows_rect.min.y || r.min.y > rows_rect.max.y {
continue;
}
hit_rows.push((r, row.clone()));
let Some(layer) = comp.layer(row.layer) else { continue };
let is_sel = selected.contains(&layer.id);
let left = Rect::from_min_max(r.min, pos2(graph_x0 - 1.0, r.max.y));
let cy = r.center().y;
let cy = r.min.y + rh / 2.0;
match &row.kind {
RowKind::Layer => {
lp.rect_filled(
@@ -742,7 +816,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
// Parent.
let pr_rect = Rect::from_min_size(pos2(cw.parent + 2.0, cy - 9.0), vec2(110.0, 18.0));
let pw_rect = Rect::from_center_size(pos2(cw.parent + 9.0, cy), vec2(15.0, 15.0));
let pw = ui.interact(pw_rect, egui::Id::new(("parent-whip", layer.id.0)), Sense::drag()).on_hover_text("Parent pick whip: drag onto a layer");
icons::paint(&lp, pw_rect.shrink(1.0), Icon::PickWhip, if pw.hovered() || pw.dragged() { t.text } else { t.text_dim });
app.auto.add(&format!("timeline.layer.{}.pickWhip", layer.id.0), pw_rect, "Parent pick whip");
if pw.drag_started() {
let pw_state: PickWhip = (0, layer.id.0, 0, pw_rect.center());
ctx.data_mut(|d| d.insert_temp(pick_whip_id(), pw_state));
}
let pr_rect = Rect::from_min_size(pos2(cw.parent + 20.0, cy - 9.0), vec2(94.0, 18.0));
let plabel = layer.parent.and_then(|p| comp.layer(p)).map(|l| format!("{}. {}", idx_of(l.id), l.name)).unwrap_or_else(|| "None".into());
let presp = widgets::dropdown(ui, pr_rect, &plabel, &t, egui::Id::new(("parent", layer.id.0)));
app.auto.add(&format!("timeline.layer.{}.parent", layer.id.0), pr_rect, "Parent");
@@ -758,6 +840,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
actions.push(("layer.setParent".into(), json!({"layers": [layer.id.0], "parent": par})));
}
// Layer bar.
ui.set_clip_rect(right_clip);
if !graph_on {
let x_in = tm.x(layer.in_point.seconds());
let x_out = tm.x(layer.out_point.seconds());
@@ -876,6 +959,75 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
ui_actions.push(UiAct::ToggleGroup(*uid));
}
}
RowKind::Expr { uid, lines } => {
let Some(prop) = layer.props.find(*uid) else { continue };
let Some(ex) = prop.expr.clone() else { continue };
lp.rect_filled(left, 0.0, t.row_alt);
let indent = cw.name + 6.0 + 14.0 * row.depth as f32;
lp.text(pos2(indent + 12.0, cy), Align2::LEFT_CENTER, "Expression:", Tokens::ui(11.5), t.text_dim);
lp.text(pos2(indent + 82.0, cy), Align2::LEFT_CENTER, &prop.name, Tokens::ui(11.5), t.text);
// "=" enable switch and the property pick whip (AE's expression controls).
let en_r = Rect::from_center_size(pos2(cw.switches + 10.0, cy), vec2(16.0, 16.0));
let en = ui.interact(en_r, egui::Id::new(("expr-en", uid)), Sense::click()).on_hover_text("Enable Expression");
lp.rect_stroke(en_r.shrink(1.0), 2.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
let expr_col = Color32::from_rgb(0xe8, 0x7c, 0x5c);
lp.text(
en_r.center(),
Align2::CENTER_CENTER,
if ex.enabled { "=" } else { "≠" },
Tokens::semibold(13.0),
if ex.enabled { expr_col } else { t.text_dim },
);
app.auto.add(&format!("timeline.prop.{uid}.exprEnable"), en_r, "Enable Expression");
if en.clicked() {
actions.push(("prop.setExpression".into(), json!({"layer": layer.id.0, "prop": uid, "enabled": !ex.enabled})));
}
let pw_rect = Rect::from_center_size(pos2(cw.switches + 30.0, cy), vec2(15.0, 15.0));
let pw = ui.interact(pw_rect, egui::Id::new(("expr-whip", uid)), Sense::drag()).on_hover_text("Expression pick whip: drag onto a property");
icons::paint(&lp, pw_rect.shrink(1.0), Icon::PickWhip, if pw.hovered() || pw.dragged() { t.text } else { t.text_dim });
app.auto.add(&format!("timeline.prop.{uid}.pickWhip"), pw_rect, "Expression pick whip");
if pw.drag_started() {
let pw_state: PickWhip = (1, layer.id.0, *uid, pw_rect.center());
ctx.data_mut(|d| d.insert_temp(pick_whip_id(), pw_state));
}
// Syntax errors: warning in the outline (the expression is disabled).
if let Some(check) = app.session.expr_check
&& let Err(e) = check(&ex.text)
{
let wr = Rect::from_center_size(pos2(cw.switches + 50.0, cy), vec2(14.0, 14.0));
lp.text(wr.center(), Align2::CENTER_CENTER, "⚠", Tokens::ui(12.0), Color32::from_rgb(0xf0, 0xa0, 0x30));
let _ = ui.interact(wr, egui::Id::new(("expr-err", uid)), Sense::hover()).on_hover_text(e);
}
// The editor in the time-graph area.
ui.set_clip_rect(right_clip);
gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, Color32::from_rgb(0x1a, 0x1a, 0x1a));
let er = Rect::from_min_max(pos2(graph_x0 + 8.0, r.min.y + 3.0), pos2(rect.max.x - 14.0, r.max.y - 3.0));
let buf_id = egui::Id::new(("expr-buf", uid));
let mut buf: String = ctx.data(|d| d.get_temp(buf_id)).unwrap_or_else(|| ex.text.clone());
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(er));
let resp = child.add(
egui::TextEdit::multiline(&mut buf)
.id(egui::Id::new(("expr-edit", uid)))
.font(Tokens::mono(11.5))
.text_color(if ex.enabled { expr_col } else { t.text_dim })
.desired_width(er.width())
.desired_rows((*lines).clamp(1, 8))
.frame(egui::Frame::NONE),
);
app.auto.add(&format!("timeline.prop.{uid}.expression"), er, &prop.name);
let commit = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && (i.modifiers.command || i.modifiers.ctrl));
if commit {
resp.surrender_focus();
}
if resp.has_focus() && !commit {
ctx.data_mut(|d| d.insert_temp(buf_id, buf));
} else {
if (resp.lost_focus() || commit) && buf.trim_end() != ex.text {
actions.push(("prop.setExpression".into(), json!({"layer": layer.id.0, "prop": uid, "expression": buf.trim_end()})));
}
ctx.data_mut(|d| d.remove::<String>(buf_id));
}
}
RowKind::Prop { uid } => {
let Some(prop) = layer.props.find(*uid) else { continue };
let sel_prop = app.session.state.selected_props.contains(&(layer.id, *uid));
@@ -965,8 +1117,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let value = ectx.value(layer, prop);
let vx = (cw.switches + 4.0).max(name_x + 120.0);
value_editor(app, ui, &lp, layer, prop, &value, pos2(vx, cy), &mut actions);
ui.set_clip_rect(right_clip);
// Expression text row hint.
if let Some(e) = prop.expr.as_ref().filter(|e| e.enabled) {
if let Some(e) = prop.expr.as_ref().filter(|e| e.enabled && app.ui.timeline.expr_closed.contains(uid)) {
gp.text(
pos2(graph_x0 + 8.0, cy),
Align2::LEFT_CENTER,
@@ -1005,15 +1158,32 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
kresp.context_menu(|ui| {
for (lbl, cmd, params) in [
("Copy", "keys.copy", json!({})),
("Paste", "keys.paste", json!({})),
("-", "", json!({})),
("Keyframe Interpolation…", "keys.interpolation", json!({})),
("Keyframe Velocity…", "keys.velocity", json!({})),
("Toggle Hold Keyframe", "keys.toggleHold", json!({})),
("Rove Across Time", "keys.interpolation", json!({"roving": !k.roving})),
("-", "", json!({})),
("Easy Ease", "keys.easyEase", json!({})),
("Easy Ease In", "keys.easyEaseIn", json!({})),
("Easy Ease Out", "keys.easyEaseOut", json!({})),
("Toggle Hold Keyframe", "keys.toggleHold", json!({})),
("Time-Reverse Keyframes", "keys.timeReverse", json!({})),
("-", "", json!({})),
("Linear", "keys.interpolation", json!({"interpolation": "linear"})),
("Bezier", "keys.interpolation", json!({"interpolation": "bezier"})),
("Auto Bezier", "keys.interpolation", json!({"autoBezier": true})),
("Auto Bezier", "keys.interpolation", json!({"interpolation": "autoBezier"})),
("Select All Keyframes", "keys.selectAll", json!({})),
("Delete", "keys.delete", json!({})),
] {
if lbl == "-" {
ui.separator();
continue;
}
if lbl == "Rove Across Time" && !prop.spatial {
continue;
}
if ui.button(lbl).clicked() {
if !ks {
actions.push(("keys.select".into(), json!({"keys": [{"layer": layer.id.0, "prop": uid, "time": k.time.seconds()}]})));
@@ -1043,12 +1213,35 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
ui.set_clip_rect(full_clip);
// Pick whips: a line follows the pointer; releasing over a row links to it.
if let Some((kind, src_layer, src_prop, start)) = ctx.data(|d| d.get_temp::<PickWhip>(pick_whip_id())) {
let ptr = ctx.input(|i| i.pointer.latest_pos()).unwrap_or(start);
let fg = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("tl-pickwhip-line")));
fg.line_segment([start, ptr], Stroke::new(1.5, t.accent));
fg.circle_stroke(ptr, 4.0, Stroke::new(1.5, t.accent));
let target = hit_rows.iter().find(|(r, _)| r.contains(ptr)).map(|(r, row)| (*r, row.clone()));
if let Some((tr, _)) = &target {
fg.rect_stroke(Rect::from_min_max(tr.min, pos2(graph_x0 - 1.0, tr.max.y)), 0.0, Stroke::new(1.0, t.accent), StrokeKind::Inside);
}
if ctx.input(|i| !i.pointer.any_down()) {
ctx.data_mut(|d| d.remove::<PickWhip>(pick_whip_id()));
match (kind, target) {
(0, Some((_, row))) if row.layer.0 != src_layer => {
actions.push(("layer.setParent".into(), json!({"layers": [src_layer], "parent": row.layer.0})));
}
(1, Some((_, Row { layer, kind: RowKind::Prop { uid }, .. }))) if uid != src_prop => {
actions.push(("prop.pickWhip".into(), json!({"layer": src_layer, "prop": src_prop, "target": {"layer": layer.0, "prop": uid}})));
}
_ => {}
}
}
}
// Graph editor.
if graph_on {
graph_editor(app, ui, &gp, &comp, &ectx, tm, Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max));
super::graph::show(app, ui, &gp, &comp, &ectx, tm, Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max), &mut actions);
}
// Empty-area click in the graph: deselect keys; drag: box-select keys.
let empty = ui.interact(Rect::from_min_max(pos2(graph_x0, rows_rect.min.y), rows_rect.max), egui::Id::new("tl-graph-bg"), Sense::click_and_drag());
if empty.clicked() {
actions.push(("keys.select".into(), json!({"keys": []})));
}
@@ -1068,7 +1261,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mut yy = rows_rect.min.y - app.ui.timeline.scroll_y;
for row in &rows {
let cy = yy + rh / 2.0;
yy += rh;
yy += row_height(row, rh);
if let RowKind::Prop { uid } = row.kind
&& cy >= br.min.y
&& cy <= br.max.y
@@ -1144,8 +1337,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
p.rect_stroke(rows_rect, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);
if ctx.input(|i| i.pointer.any_released()) {
let hover_y = ctx.input(|i| i.pointer.hover_pos()).map(|p| p.y).unwrap_or(0.0);
let row_i = ((hover_y - rows_rect.min.y + app.ui.timeline.scroll_y) / rh).floor() as usize;
let target = rows.get(row_i).map(|r| r.layer);
let target = hit_rows.iter().find(|(r, _)| hover_y >= r.min.y && hover_y < r.max.y).map(|(_, row)| row.layer);
match payload.as_ref() {
crate::panels::DragPayload::Item(id) => actions.push(("layer.addItem".into(), json!({"item": id}))),
crate::panels::DragPayload::Effect(e) => {
@@ -1192,6 +1384,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
for (id, params) in actions {
if id == "__endMerge" {
app.session.history.merge_key = None;
continue;
}
if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) {
app.ui.status = e;
}
@@ -1261,7 +1457,11 @@ fn layer_context_menu(resp: &egui::Response, layer: &Layer, actions: &mut Vec<(S
item(ui, "Flip Vertical", "layer.transform", json!({"layers": [id], "op": "flipV"}));
});
ui.menu_button("Time", |ui| {
item(ui, "Time-Reverse Layer", "layer.timeStretch", json!({"layers": [id], "op": "reverse"}));
item(ui, "Enable Time Remapping", "layer.enableTimeRemap", json!({"layers": [id]}));
item(ui, "Time-Reverse Layer", "layer.timeReverse", json!({"layers": [id]}));
item(ui, "Time Stretch…", "layer.timeStretch", json!({}));
item(ui, "Freeze Frame", "layer.freezeFrame", json!({"layers": [id]}));
item(ui, "Freeze on Last Frame", "layer.freezeOnLastFrame", json!({"layers": [id]}));
});
ui.menu_button("Blending Mode", |ui| {
for m in BlendMode::ALL {
@@ -1416,86 +1616,3 @@ fn value_editor(
}
}
}
/// Value graph of the selected properties (numeric dimensions over time) with key markers.
fn graph_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, comp: &Comp, ectx: &EvalCtx, tm: TMap, area: Rect) {
let t = app.tokens;
let props: Vec<(LayerId, u64)> = if app.session.state.selected_props.is_empty() {
// Default: animated properties of selected layers.
let mut v = vec![];
for l in comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id)) {
l.props.walk("", &mut |_, pr| {
if pr.is_animated() && !pr.value.components().is_empty() {
v.push((l.id, pr.uid));
}
});
}
v
} else {
app.session.state.selected_props.clone()
};
p.rect_filled(area, 0.0, Color32::from_rgb(0x1e, 0x1e, 0x1e));
// Grid.
for i in 1..8 {
let y = area.min.y + area.height() * i as f32 / 8.0;
p.line_segment([pos2(area.min.x, y), pos2(area.max.x, y)], Stroke::new(1.0, Color32::from_white_alpha(10)));
}
if props.is_empty() {
p.text(area.center(), Align2::CENTER_CENTER, "Select animated properties to show them in the Graph Editor", Tokens::ui(12.0), t.text_faint);
return;
}
let colors =
[Color32::from_rgb(0xe0, 0x50, 0x50), Color32::from_rgb(0x60, 0xd0, 0x60), Color32::from_rgb(0x50, 0x8c, 0xf0), Color32::from_rgb(0xe8, 0xc8, 0x40)];
// Sample all curves over the visible span; normalise to a common range.
let n = ((area.width() / 2.0) as usize).max(2);
let mut curves: Vec<(Vec<Vec<f64>>, &Layer, &Property)> = vec![];
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
for (lid, uid) in &props {
let Some(l) = comp.layer(*lid) else { continue };
let Some(pr) = l.props.find(*uid) else { continue };
let mut dims: Vec<Vec<f64>> = vec![];
for i in 0..n {
let x = area.min.x + area.width() * i as f32 / (n - 1) as f32;
let tt = Tick::from_seconds_f64(tm.t(x));
let v = ectx.at(tt).value(l, pr).components();
if dims.is_empty() {
dims = vec![Vec::with_capacity(n); v.len().min(3)];
}
for (d, c) in v.iter().take(dims.len()).enumerate() {
dims[d].push(*c);
lo = lo.min(*c);
hi = hi.max(*c);
}
}
curves.push((dims, l, pr));
}
if !lo.is_finite() || !hi.is_finite() {
return;
}
if (hi - lo).abs() < 1e-9 {
hi = lo + 1.0;
}
let pad = (hi - lo) * 0.1;
let (lo, hi) = (lo - pad, hi + pad);
let ymap = |v: f64| area.max.y - ((v - lo) / (hi - lo)) as f32 * area.height();
for (dims, l, pr) in &curves {
for (d, vals) in dims.iter().enumerate() {
let pts: Vec<Pos2> = vals.iter().enumerate().map(|(i, v)| pos2(area.min.x + area.width() * i as f32 / (n - 1) as f32, ymap(*v))).collect();
p.add(egui::Shape::line(pts, Stroke::new(1.5, colors[d % colors.len()])));
}
for k in &pr.keys {
let x = tm.x(l.comp_time(k.time).seconds());
for (d, v) in k.value.components().iter().take(dims.len()).enumerate() {
let c = pos2(x, ymap(*v));
p.rect_filled(Rect::from_center_size(c, vec2(6.0, 6.0)), 0.0, Color32::WHITE);
p.rect_stroke(Rect::from_center_size(c, vec2(6.0, 6.0)), 0.0, Stroke::new(1.0, colors[d % colors.len()]), StrokeKind::Outside);
}
}
}
// Value labels.
for i in 0..=4 {
let v = lo + (hi - lo) * i as f64 / 4.0;
p.text(pos2(area.min.x + 4.0, ymap(v)), Align2::LEFT_BOTTOM, format!("{v:.1}"), Tokens::ui(10.0), t.text_faint);
}
let _ = ui;
}
+202 -19
View File
@@ -71,7 +71,6 @@ enum Gesture {
start_scale: [f64; 3],
start_local: [f64; 2],
inv: Mat3,
uniform: bool,
},
Rotate {
layer: LayerId,
@@ -97,6 +96,48 @@ enum Gesture {
Marquee {
start: Pos2,
},
/// Dragging selected mask vertices (comp-space point of the previous frame, comp → layer).
Vertices {
last: [f64; 2],
inv: Mat3,
},
/// Dragging a vertex's Bezier tangent (both sides symmetric unless Alt breaks them).
Tangent {
layer: LayerId,
mask: u64,
index: usize,
out: bool,
vertex: [f64; 2],
inv: Mat3,
},
/// Pen tool: pulling the tangents of the vertex just placed.
Pen {
layer: LayerId,
mask: u64,
index: usize,
vertex: [f64; 2],
inv: Mat3,
press: Pos2,
},
}
/// Pen tool path in progress: (layer, mask uid).
fn pen_id() -> egui::Id {
egui::Id::new("viewer-pen")
}
/// Mask vertex / tangent hit targets drawn this frame.
#[derive(Clone, Copy)]
struct VertexHit {
layer: LayerId,
mask: u64,
index: usize,
pos: Pos2,
/// None = the vertex itself, Some(out?) = a tangent handle.
tangent: Option<bool>,
/// Layer-space vertex position and layer → comp matrix.
vertex: [f64; 2],
l2c: Mat3,
}
const HANDLE: f32 = 7.0;
@@ -238,11 +279,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
// Frame.
let ppp = ctx.pixels_per_point();
let scale = app.viewer_scale(zoom, ppp);
if !app.playback.playing {
// Queue the frame on screen before any prefetch.
app.request_frame_urgent(cid, comp.frame_rate.frame_at(app.session.time()), scale);
}
crate::tick_playback(app, &ctx, scale);
let time = app.session.time();
let frame = comp.frame_rate.frame_at(time);
let key = app.frame_key(cid, frame, scale);
app.request_frame(cid, frame, scale);
app.request_frame_urgent(cid, frame, scale);
if let Some(img) = app.frames.get(&key) {
let stale = app.viewer_tex.as_ref().is_none_or(|(_, k)| *k != key);
if stale {
@@ -301,6 +346,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let ectx = EvalCtx { project: &snap_project, comp_id: cid, comp: &comp, time, expr: snap_expr.as_deref() };
let selected = app.session.state.selected_layers.clone();
let mut handle_hits: Vec<(LayerId, usize, Pos2)> = Vec::new();
let mut vertex_hits: Vec<VertexHit> = Vec::new();
let sel_vertices = app.session.state.selected_vertices.clone();
// Pen path in progress ends when the tool changes or its mask is gone.
if app.ui.tool != Tool::Pen || ui.input(|i| i.key_pressed(egui::Key::Escape) || i.key_pressed(egui::Key::Enter)) {
ui.data_mut(|d| d.remove::<(LayerId, u64)>(pen_id()));
}
if app.ui.viewer.show_layer_controls {
for l in comp.layers.iter().filter(|l| selected.contains(&l.id) && l.is_active_at(time)) {
let col = Tokens::label(l.label);
@@ -350,14 +401,37 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if sp.closed && !pts.is_empty() {
pts.push(pts[0]);
}
painter.add(egui::Shape::line(pts, Stroke::new(1.0, Color32::from_rgb(color[0], color[1], color[2]))));
for v in &sp.vertices {
let c = m.apply(gv2(v[0], v[1]));
painter.rect_filled(
Rect::from_center_size(map.to_screen([c.x, c.y]), vec2(5.0, 5.0)),
0.0,
Color32::from_rgb(color[0], color[1], color[2]),
);
let mc = Color32::from_rgb(color[0], color[1], color[2]);
painter.add(egui::Shape::line(pts, Stroke::new(1.0, mc)));
let scr = |p: [f64; 2]| {
let c = m.apply(gv2(p[0], p[1]));
map.to_screen([c.x, c.y])
};
for (i, v) in sp.vertices.iter().enumerate() {
let s = scr(*v);
let selected = sel_vertices.iter().any(|x| x.layer == l.id && x.mask == g.uid && x.index == i);
// Selected vertices: filled with their tangent handles; others hollow.
if selected {
for (out, tg) in [(false, sp.in_tangents.get(i)), (true, sp.out_tangents.get(i))] {
let Some(tg) = tg.filter(|t| t[0] != 0.0 || t[1] != 0.0) else { continue };
let h = scr([v[0] + tg[0], v[1] + tg[1]]);
painter.line_segment([s, h], Stroke::new(1.0, mc));
painter.circle_filled(h, 3.0, mc);
vertex_hits.push(VertexHit { layer: l.id, mask: g.uid, index: i, pos: h, tangent: Some(out), vertex: *v, l2c: m });
}
painter.rect_filled(Rect::from_center_size(s, vec2(6.0, 6.0)), 0.0, mc);
} else {
painter.rect_filled(Rect::from_center_size(s, vec2(6.0, 6.0)), 0.0, Color32::from_black_alpha(160));
painter.rect_stroke(Rect::from_center_size(s, vec2(6.0, 6.0)), 0.0, Stroke::new(1.0, mc), StrokeKind::Inside);
}
app.auto.add(&format!("viewer.mask.{}.vertex.{i}", g.uid), Rect::from_center_size(s, vec2(8.0, 8.0)), &g.name);
vertex_hits.push(VertexHit { layer: l.id, mask: g.uid, index: i, pos: s, tangent: None, vertex: *v, l2c: m });
}
// Pen rubber band from the last vertex to the pointer.
if ui.data(|d| d.get_temp::<(LayerId, u64)>(pen_id())) == Some((l.id, g.uid))
&& let (Some(last), Some(hp)) = (sp.vertices.last(), ui.input(|i| i.pointer.hover_pos()))
{
painter.line_segment([scr(*last), hp], Stroke::new(1.0, mc.gamma_multiply(0.6)));
}
}
}
@@ -462,10 +536,31 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
let mods = ui.input(|i| i.modifiers);
let space_pan = ui.input(|i| i.key_down(egui::Key::Space)) && !ctx.egui_wants_keyboard_input();
// Pen tool: each press places a vertex (dragging pulls Bezier tangents); pressing on the
// first vertex closes the path.
if app.ui.tool == Tool::Pen
&& !space_pan
&& resp.hovered()
&& ui.input(|i| i.pointer.primary_pressed())
&& let Some(pos) = ui.input(|i| i.pointer.press_origin())
{
pen_press(app, ui, &ectx, &map, &vertex_hits, pos);
}
// A pen click (press + release without a drag) ends its tangent gesture on release.
if ui.input(|i| i.pointer.primary_released())
&& matches!(ui.data(|d| d.get_temp::<Gesture>(egui::Id::new("viewer-gesture"))), Some(Gesture::Pen { .. }))
&& !resp.drag_stopped()
{
ui.data_mut(|d| d.remove::<Gesture>(egui::Id::new("viewer-gesture")));
}
let vertex_at = |pos: Pos2, tangents: bool| -> Option<VertexHit> {
vertex_hits.iter().rev().filter(|h| h.tangent.is_some() == tangents).find(|h| h.pos.distance(pos) < 6.0).copied()
};
if resp.drag_started()
&& let Some(pos) = resp.interact_pointer_pos()
{
let cpt = map.to_comp(pos);
let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(pos);
let tool = if space_pan || resp.dragged_by(egui::PointerButton::Middle) { Tool::Hand } else { app.ui.tool };
let g = match tool {
Tool::Hand => Some(Gesture::Pan { start_pan: app.ui.viewer.pan }),
@@ -496,6 +591,22 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}),
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,13 +617,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
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], [f64; 3], [f64; 3])> = app
@@ -560,14 +665,13 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let _ = app.session.execute("prop.set", json!({"layer": lid.0, "path": "transform/position", "value": v, "merge": merge}));
}
}
Gesture::Scale { layer, start_scale, start_local, inv, uniform, .. } => {
Gesture::Scale { layer, start_scale, start_local, inv, .. } => {
let lp = inv.apply(gv2(cpt[0], cpt[1]));
// Local point relative to the anchor in *unscaled* layer space.
let a = comp.layer(layer).and_then(|l| l.transform().map(|tr| ectx.v3(l, tr, "anchor", [0.0; 3]))).unwrap_or([0.0; 3]);
let cur = [lp.x - a[0], lp.y - a[1]];
let fx = if start_local[0].abs() > 1e-6 { cur[0] / start_local[0] } else { 1.0 };
let fy = if start_local[1].abs() > 1e-6 { cur[1] / start_local[1] } else { 1.0 };
let _ = uniform;
let (fx, fy) = if mods.shift {
let f = (fx + fy) / 2.0;
(f, f)
@@ -644,6 +748,32 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let r = Rect::from_two_pos(a, pos);
painter.rect_stroke(r, 0.0, Stroke::new(1.0, t.accent), StrokeKind::Middle);
}
Gesture::Vertices { last, inv } => {
let d = inv.apply_vec(gv2(cpt[0] - last[0], cpt[1] - last[1]));
if d.x != 0.0 || d.y != 0.0 {
let _ = app.session.execute("mask.moveVertices", json!({"delta": [d.x, d.y], "merge": merge}));
}
ui.data_mut(|dd| dd.insert_temp(gid, Gesture::Vertices { last: cpt, inv }));
}
Gesture::Tangent { layer, mask, index, out, vertex, inv } => {
let lp = inv.apply(gv2(cpt[0], cpt[1]));
let t = [lp.x - vertex[0], lp.y - vertex[1]];
let mut params = json!({"layer": layer.0, "mask": mask, "index": index, "merge": merge});
params[if out { "out" } else { "in" }] = json!(t);
if !mods.alt {
params[if out { "in" } else { "out" }] = json!([-t[0], -t[1]]);
}
let _ = app.session.execute("mask.setVertex", params);
}
Gesture::Pen { layer, mask, index, vertex, inv, press } => {
if pos.distance(press) > 3.0 {
let lp = inv.apply(gv2(cpt[0], cpt[1]));
let t = [lp.x - vertex[0], lp.y - vertex[1]];
let _ = app
.session
.execute("mask.setVertex", json!({"layer": layer.0, "mask": mask, "index": index, "out": t, "in": [-t[0], -t[1]], "merge": merge}));
}
}
Gesture::Marquee { start } => {
let r = Rect::from_two_pos(start, pos);
painter.rect_filled(r, 0.0, t.accent.gamma_multiply(0.12));
@@ -700,6 +830,13 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
ui.data_mut(|d| d.insert_temp(egui::Id::new("viewer-text-edit"), (v["layer"].as_u64().unwrap_or(0), "Text".to_string())));
}
}
Tool::Pen => {}
Tool::Selection if vertex_at(pos, false).is_some() => {
if let Some(h) = vertex_at(pos, false) {
let me = json!({"layer": h.layer.0, "mask": h.mask, "index": h.index});
let _ = app.session.execute("mask.selectVertices", json!({"vertices": [me], "add": mods.shift, "toggle": mods.shift}));
}
}
_ => {
if pick(app, &ectx, cpt, mods.shift).is_none() {
let _ = app.session.execute("edit.deselectAll", json!({}));
@@ -708,6 +845,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
if resp.double_clicked()
&& app.ui.tool != Tool::Pen
&& let Some(pos) = resp.interact_pointer_pos()
{
let cpt = map.to_comp(pos);
@@ -827,6 +965,51 @@ fn draw_rigs(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap,
}
}
/// 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 = 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
+44 -1
View File
@@ -249,6 +249,28 @@ pub struct TimelineState {
pub open_groups: BTreeSet<u64>,
/// "Reveal" filter: only show these property match ids (P/S/R/T/A…) — empty = normal.
pub reveal: Vec<String>,
/// Graph Editor: `value` or `speed` graph.
#[serde(default = "value_graph")]
pub graph_mode: String,
/// Show only the selected properties (else every animated property of the selected layers).
#[serde(default = "yes")]
pub graph_show_selected: bool,
/// Auto-zoom the graph height to the visible curves.
#[serde(default = "yes")]
pub graph_auto_zoom: bool,
/// Manual graph value range (when auto-zoom is off).
#[serde(default)]
pub graph_range: Option<(f64, f64)>,
/// Properties whose inline expression editor is collapsed.
#[serde(default)]
pub expr_closed: BTreeSet<u64>,
}
fn value_graph() -> String {
"value".into()
}
fn yes() -> bool {
true
}
impl Default for TimelineState {
@@ -258,16 +280,25 @@ impl Default for TimelineState {
pps: None,
scroll_y: 0.0,
columns_w: 560.0,
show_modes: true,
show_modes: false,
graph_editor: false,
search: String::new(),
open_layers: BTreeSet::new(),
open_groups: BTreeSet::new(),
reveal: vec![],
graph_mode: value_graph(),
graph_show_selected: true,
graph_auto_zoom: true,
graph_range: None,
expr_closed: BTreeSet::new(),
}
}
}
fn default_project_sort() -> String {
"name".into()
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UiState {
pub tool: Tool,
@@ -286,8 +317,17 @@ pub struct UiState {
pub effects_open: BTreeSet<String>,
pub project_search: String,
pub project_open_folders: BTreeSet<u64>,
/// Project panel sort column (`name`, `type`, `size`, `fps`) and direction, as in AE's
/// clickable column headers. Folders sort with everything else.
#[serde(default = "default_project_sort")]
pub project_sort: String,
#[serde(default)]
pub project_sort_desc: bool,
/// Effect Controls twirl state (group uids that are collapsed).
pub fx_closed: BTreeSet<u64>,
/// Slider params whose slider row is twirled open (AE hides sliders by default).
#[serde(default)]
pub fx_slider_open: BTreeSet<u64>,
/// Shape tool options.
pub fill_color: [f32; 3],
pub stroke_color: [f32; 3],
@@ -318,7 +358,10 @@ impl Default for UiState {
effects_open: BTreeSet::new(),
project_search: String::new(),
project_open_folders: BTreeSet::new(),
project_sort: default_project_sort(),
project_sort_desc: false,
fx_closed: BTreeSet::new(),
fx_slider_open: BTreeSet::new(),
fill_color: [0.24, 0.55, 0.96],
stroke_color: [1.0, 1.0, 1.0],
stroke_width: 0.0,