Merge branch 'worktree-agent-a549a3d1a8812e372'
# Conflicts: # apps/effectcraft-cli/src/main.rs # crates/host/src/lib.rs # crates/render/src/lib.rs
This commit is contained in:
@@ -41,6 +41,9 @@ pub enum Dialog {
|
||||
CompSettings,
|
||||
SolidSettings,
|
||||
CommandPalette,
|
||||
KeyVelocity,
|
||||
KeyInterpolation,
|
||||
TimeStretch,
|
||||
}
|
||||
|
||||
/// Host hooks provided by the native app (file pickers etc.).
|
||||
|
||||
@@ -245,6 +245,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)?;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use serde_json::json;
|
||||
|
||||
use crate::icons::{self, Icon};
|
||||
use crate::theme::Tokens;
|
||||
use crate::{Dialog, EffectcraftApp, widgets};
|
||||
use crate::{Dialog, EffectcraftApp};
|
||||
|
||||
pub use super::comp_settings::CompDraft;
|
||||
|
||||
@@ -19,6 +19,9 @@ pub struct DialogState {
|
||||
pub solid_size: [u32; 2],
|
||||
pub palette_query: String,
|
||||
pub palette_sel: usize,
|
||||
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) {
|
||||
@@ -63,7 +66,7 @@ pub fn open_new_solid(app: &mut EffectcraftApp) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn modal(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui)) {
|
||||
pub(crate) fn modal(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui)) {
|
||||
// Dim the app.
|
||||
let screen = ctx.content_rect();
|
||||
ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("modal-dim"))).rect_filled(screen, 0.0, Color32::from_black_alpha(120));
|
||||
@@ -86,6 +89,9 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context) {
|
||||
Dialog::NewComp | Dialog::CompSettings => comp_settings(app, ctx, &t, d == Dialog::CompSettings),
|
||||
Dialog::SolidSettings => solid(app, ctx, &t),
|
||||
Dialog::CommandPalette => palette(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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,7 +191,7 @@ fn comp_settings(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens, exis
|
||||
}
|
||||
}
|
||||
|
||||
fn ui_enter(ctx: &egui::Context) -> bool {
|
||||
pub(crate) fn ui_enter(ctx: &egui::Context) -> bool {
|
||||
!ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Enter))
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ pub mod comp_settings;
|
||||
pub mod dialogs;
|
||||
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;
|
||||
@@ -35,11 +37,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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -240,10 +240,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if resp.double_clicked() {
|
||||
match &it.kind {
|
||||
ItemKind::Comp(_) => actions.push(("comp.open".into(), json!({"comp": id.0}))),
|
||||
ItemKind::Folder => {
|
||||
if !app.ui.project_open_folders.remove(&id.0) {
|
||||
app.ui.project_open_folders.insert(id.0);
|
||||
}
|
||||
ItemKind::Folder if !app.ui.project_open_folders.remove(&id.0) => {
|
||||
app.ui.project_open_folders.insert(id.0);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -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)]
|
||||
@@ -42,7 +88,6 @@ struct Cols {
|
||||
label: f32,
|
||||
num: f32,
|
||||
name: f32,
|
||||
name_w: f32,
|
||||
switches: f32,
|
||||
mode: f32,
|
||||
trkmat: f32,
|
||||
@@ -61,22 +106,22 @@ fn cols(x0: f32, width: f32, show_modes: bool) -> Cols {
|
||||
let mode = switches + SW * 8.0 + 6.0;
|
||||
let trkmat = mode + if show_modes { 92.0 } else { 0.0 };
|
||||
let parent = trkmat + if show_modes { 112.0 } else { 0.0 };
|
||||
Cols { av, label, num, name, name_w, switches, mode, trkmat, parent, end: parent + 116.0 }
|
||||
Cols { av, label, num, name, switches, mode, trkmat, parent, end: parent + 116.0 }
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
@@ -141,6 +186,10 @@ fn prop_visible(p: &Property, layer: &Layer) -> bool {
|
||||
if p.two_d_only && layer.is_3d() {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -168,7 +217,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"]),
|
||||
@@ -322,7 +371,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;
|
||||
@@ -346,7 +396,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() {
|
||||
@@ -439,7 +489,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let fd = comp.frame_duration().seconds();
|
||||
let cy0 = ruler.min.y + 11.0;
|
||||
let mut run: Option<(i64, i64)> = None;
|
||||
let mut draw_run = |a: i64, b: i64| {
|
||||
let draw_run = |a: i64, b: i64| {
|
||||
let x0 = tm.x(a as f64 * fd);
|
||||
let x1 = tm.x((b + 1) as f64 * fd);
|
||||
p.rect_filled(Rect::from_min_max(pos2(x0, cy0), pos2(x1, cy0 + 2.5)), 0.0, t.cache_green);
|
||||
@@ -458,14 +508,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);
|
||||
@@ -520,9 +582,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));
|
||||
@@ -548,16 +610,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(
|
||||
@@ -739,7 +812,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");
|
||||
@@ -755,6 +836,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());
|
||||
@@ -785,10 +867,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if lin.hovered() || lout.hovered() || lin.dragged() || lout.dragged() {
|
||||
ctx.set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
|
||||
}
|
||||
if body.clicked() || body.drag_started() {
|
||||
if !is_sel {
|
||||
actions.push(("layer.select".into(), json!({"layers": [layer.id.0], "add": ui.input(|i| i.modifiers.shift)})));
|
||||
}
|
||||
if (body.clicked() || body.drag_started()) && !is_sel {
|
||||
actions.push(("layer.select".into(), json!({"layers": [layer.id.0], "add": ui.input(|i| i.modifiers.shift)})));
|
||||
}
|
||||
layer_context_menu(&body, layer, &mut actions);
|
||||
let drag_key = format!("bar-{}", layer.id.0);
|
||||
@@ -875,6 +955,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));
|
||||
@@ -961,8 +1110,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,
|
||||
@@ -1001,15 +1151,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()}]})));
|
||||
@@ -1039,17 +1206,40 @@ 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": []})));
|
||||
}
|
||||
if let (true, Some(origin), Some(cur)) =
|
||||
(empty.dragged(), empty.interact_pointer_pos().map(|_| ctx.input(|i| i.pointer.press_origin())).flatten(), empty.interact_pointer_pos())
|
||||
(empty.dragged(), empty.interact_pointer_pos().and_then(|_| ctx.input(|i| i.pointer.press_origin())), empty.interact_pointer_pos())
|
||||
{
|
||||
let br = Rect::from_two_pos(origin, cur);
|
||||
gp.rect_filled(br, 0.0, t.accent.gamma_multiply(0.12));
|
||||
@@ -1064,7 +1254,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
|
||||
@@ -1140,8 +1330,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) => {
|
||||
@@ -1188,6 +1377,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;
|
||||
}
|
||||
@@ -1257,7 +1450,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 {
|
||||
@@ -1412,86 +1609,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;
|
||||
}
|
||||
|
||||
@@ -55,13 +55,82 @@ pub fn last_fit(ctx: &egui::Context) -> f32 {
|
||||
/// What a drag in the viewer is doing.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Gesture {
|
||||
Move { layers: Vec<(LayerId, [f64; 3], Mat3)>, start: [f64; 2] },
|
||||
Scale { layer: LayerId, anchor_screen: Pos2, start_scale: [f64; 3], start_local: [f64; 2], inv: Mat3, uniform: bool },
|
||||
Rotate { layer: LayerId, center: Pos2, start_angle: f64, start_rot: f64 },
|
||||
Anchor { layer: LayerId, start_anchor: [f64; 3], start_pos: [f64; 3], start: [f64; 2], inv: Mat3, l2p: Mat3 },
|
||||
Pan { start_pan: [f32; 2] },
|
||||
Create { tool: Tool, start: [f64; 2] },
|
||||
Marquee { start: Pos2 },
|
||||
Move {
|
||||
layers: Vec<(LayerId, [f64; 3], Mat3)>,
|
||||
start: [f64; 2],
|
||||
},
|
||||
Scale {
|
||||
layer: LayerId,
|
||||
start_scale: [f64; 3],
|
||||
start_local: [f64; 2],
|
||||
inv: Mat3,
|
||||
},
|
||||
Rotate {
|
||||
layer: LayerId,
|
||||
center: Pos2,
|
||||
start_angle: f64,
|
||||
start_rot: f64,
|
||||
},
|
||||
Anchor {
|
||||
layer: LayerId,
|
||||
start_anchor: [f64; 3],
|
||||
start_pos: [f64; 3],
|
||||
start: [f64; 2],
|
||||
inv: Mat3,
|
||||
l2p: Mat3,
|
||||
},
|
||||
Pan {
|
||||
start_pan: [f32; 2],
|
||||
},
|
||||
Create {
|
||||
tool: Tool,
|
||||
start: [f64; 2],
|
||||
},
|
||||
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;
|
||||
@@ -251,6 +320,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);
|
||||
@@ -300,14 +375,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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -399,10 +497,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 }),
|
||||
@@ -432,6 +551,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::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();
|
||||
@@ -440,17 +575,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let (l2c, _) = ectx.layer_to_comp(&layer);
|
||||
let inv = l2c.inverse()?;
|
||||
let a = ectx.v3(&layer, tr, "anchor", [0.0; 3]);
|
||||
let ac = l2c.apply(gv2(a[0], a[1]));
|
||||
let lp = inv.apply(gv2(cpt[0], cpt[1]));
|
||||
let _ = hi;
|
||||
Some(Gesture::Scale {
|
||||
layer: lid,
|
||||
anchor_screen: map.to_screen([ac.x, ac.y]),
|
||||
start_scale: ectx.v3(&layer, tr, "scale", [100.0; 3]),
|
||||
start_local: [lp.x - a[0], lp.y - a[1]],
|
||||
inv,
|
||||
uniform: hi < 4,
|
||||
})
|
||||
Some(Gesture::Scale { layer: lid, start_scale: ectx.v3(&layer, tr, "scale", [100.0; 3]), start_local: [lp.x - a[0], lp.y - a[1]], inv })
|
||||
})
|
||||
} else if let Some(l) = pick(app, &ectx, cpt, mods.shift) {
|
||||
let layers: Vec<(LayerId, [f64; 3], Mat3)> = app
|
||||
@@ -495,14 +622,14 @@ 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 (fx, fy) = if mods.shift || uniform && start_local[0].abs() > 1e-6 && start_local[1].abs() > 1e-6 && mods.shift {
|
||||
let (fx, fy) = if mods.shift {
|
||||
let f = (fx + fy) / 2.0;
|
||||
(f, f)
|
||||
} else {
|
||||
@@ -564,6 +691,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));
|
||||
@@ -620,6 +773,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!({}));
|
||||
@@ -628,6 +788,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);
|
||||
@@ -654,6 +815,51 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
bottom_bar(app, ui, bar, zoom, fit, time, &comp);
|
||||
}
|
||||
|
||||
/// Pen tool press at `pos`: start a mask on the selected layer, add a vertex, or close the path.
|
||||
fn pen_press(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, map: &ViewerMap, hits: &[VertexHit], pos: Pos2) {
|
||||
let gid = egui::Id::new("viewer-gesture");
|
||||
let current: Option<(LayerId, u64)> = ui.data(|d| d.get_temp(pen_id()));
|
||||
let target = current.map(|c| c.0).or_else(|| {
|
||||
app.session.state.selected_layers.iter().copied().find(|id| ectx.comp.layer(*id).is_some_and(|l| l.masks().is_some() && !l.switches.locked))
|
||||
});
|
||||
let Some(lid) = target else {
|
||||
app.ui.status = "Select a layer to draw a mask with the Pen tool".into();
|
||||
return;
|
||||
};
|
||||
let Some(layer) = ectx.comp.layer(lid) else { return };
|
||||
let l2c = ectx.layer_to_comp(layer).0;
|
||||
let 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
|
||||
@@ -851,7 +1057,7 @@ fn bottom_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, zoom: f32,
|
||||
app.ui.viewer.res = Resolution::ALL[i];
|
||||
}
|
||||
x = r.max.x + 6.0;
|
||||
if tog(ui, &mut app.auto, &mut x, Icon::Region, false, "roi", "Region of Interest") {}
|
||||
let _ = tog(ui, &mut app.auto, &mut x, Icon::Region, false, "roi", "Region of Interest");
|
||||
if tog(ui, &mut app.auto, &mut x, Icon::Checker, app.ui.viewer.transparency_grid, "transparency", "Toggle Transparency Grid") {
|
||||
app.ui.viewer.transparency_grid = !app.ui.viewer.transparency_grid;
|
||||
}
|
||||
|
||||
@@ -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,12 +280,17 @@ 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user