Merge main into M13.4 (codec completion)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -55,6 +55,87 @@ pub enum Outcome {
|
||||
path: Option<String>,
|
||||
crop: Option<[f32; 4]>,
|
||||
},
|
||||
/// Reply once background jobs end (a `wait: true` command whose job runs in a worker).
|
||||
AwaitJobs(JobWaiter),
|
||||
}
|
||||
|
||||
/// A `wait: true` engine command whose job was sent to the session's offload (the browser's
|
||||
/// Web Workers) instead of blocking the UI thread: the reply goes out when the job ends.
|
||||
pub struct JobWaiter {
|
||||
pub command: String,
|
||||
pub params: Value,
|
||||
/// The command's own result (with `wait: false`).
|
||||
pub result: Value,
|
||||
/// Ids of the jobs it started (`jobs.list` ids: `render`, `track`, `roto`…).
|
||||
pub jobs: Vec<String>,
|
||||
/// Length of [`effectcraft_engine::Session::offload_log`] when it started.
|
||||
pub log_len: usize,
|
||||
}
|
||||
|
||||
/// Commands that block with `wait` (and its default).
|
||||
fn waits(command: &str, params: &Value) -> bool {
|
||||
let default = command == "renderQueue.render";
|
||||
params.get("wait").and_then(Value::as_bool).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Run an engine command. A waiting command (`wait: true`) whose job the session offloads
|
||||
/// runs with `wait: false` instead, and the reply waits for the job ([`Outcome::AwaitJobs`]),
|
||||
/// so the browser's UI keeps drawing while it runs.
|
||||
fn execute_engine(app: &mut EffectcraftApp, id: &str, params: Value) -> Result<Outcome, String> {
|
||||
if !app.session.offloads() || !waits(id, ¶ms) {
|
||||
return app.session.execute_checked(id, params).map(ok).map_err(|e| e.to_string());
|
||||
}
|
||||
let before: Vec<String> = app.session.jobs().into_iter().map(|j| j.id).collect();
|
||||
let log_len = app.session.offload_log.len();
|
||||
let mut p = params.clone();
|
||||
p["wait"] = json!(false);
|
||||
let result = app.session.execute_checked(id, p).map_err(|e| e.to_string())?;
|
||||
let jobs: Vec<String> = app.session.jobs().into_iter().map(|j| j.id).filter(|j| !before.contains(j)).collect();
|
||||
if jobs.is_empty() {
|
||||
return Ok(ok(result));
|
||||
}
|
||||
Ok(Outcome::AwaitJobs(JobWaiter { command: id.to_string(), params, result, jobs, log_len }))
|
||||
}
|
||||
|
||||
impl JobWaiter {
|
||||
/// Whether its jobs are still running.
|
||||
pub fn pending(&self, app: &EffectcraftApp) -> bool {
|
||||
app.session.jobs().iter().any(|j| self.jobs.contains(&j.id))
|
||||
}
|
||||
|
||||
/// The reply: what the blocking command would have returned (`running: false`, the final
|
||||
/// progress, render items and analysis status), or the job's error.
|
||||
pub fn finish(self, app: &mut EffectcraftApp) -> Value {
|
||||
let s = &mut app.session;
|
||||
s.poll_render();
|
||||
let errors: Vec<String> = s.offload_log.iter().skip(self.log_len).filter_map(|(_, e)| e.clone()).collect();
|
||||
if let Some(e) = errors.first() {
|
||||
return json!({"ok": false, "error": e});
|
||||
}
|
||||
let mut r = self.result;
|
||||
if r.get("running").is_some() {
|
||||
r["running"] = json!(false);
|
||||
}
|
||||
if self.command == "renderQueue.render" {
|
||||
let ids: Vec<Value> = r["items"].as_array().map(|a| a.iter().map(|i| i["id"].clone()).collect()).unwrap_or_default();
|
||||
if let Ok(list) = s.execute("renderQueue.list", json!({})) {
|
||||
r["items"] =
|
||||
json!(list["items"].as_array().map(|a| a.iter().filter(|i| ids.contains(&i["id"])).cloned().collect::<Vec<_>>()).unwrap_or_default());
|
||||
}
|
||||
r["rendering"] = json!(s.is_rendering());
|
||||
}
|
||||
let prefix = self.command.split('.').next().unwrap_or("");
|
||||
if matches!(prefix, "warp" | "camera" | "roto")
|
||||
&& r.get("layer").is_some()
|
||||
&& let Ok(st) = s.execute(&format!("{prefix}.status"), json!({"layer": r["layer"], "effect": r["effect"]}))
|
||||
{
|
||||
r["status"] = st;
|
||||
}
|
||||
if r.get("progress").is_some() {
|
||||
r["progress"] = Value::Null;
|
||||
}
|
||||
json!({"ok": true, "result": r})
|
||||
}
|
||||
}
|
||||
|
||||
fn ok(v: Value) -> Outcome {
|
||||
@@ -94,12 +175,12 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
// `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())
|
||||
execute_engine(app, id, params)
|
||||
} else {
|
||||
crate::menus::invoke(app, ctx, id, params)
|
||||
crate::menus::invoke(app, ctx, id, params).map(ok)
|
||||
};
|
||||
match r {
|
||||
Ok(v) => ok(v),
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
app.ui.status = e.clone();
|
||||
err(e)
|
||||
|
||||
@@ -44,10 +44,14 @@ pub enum PanelKind {
|
||||
Metadata,
|
||||
Progress,
|
||||
ContentAwareFill,
|
||||
/// Window ▸ Create Nulls From Paths (our own panel).
|
||||
CreateNullsFromPaths,
|
||||
/// Window ▸ VR Comp Editor (our own panel).
|
||||
VrCompEditor,
|
||||
}
|
||||
|
||||
impl PanelKind {
|
||||
pub const ALL: [PanelKind; 32] = [
|
||||
pub const ALL: [PanelKind; 34] = [
|
||||
PanelKind::Project,
|
||||
PanelKind::EffectControls,
|
||||
PanelKind::Composition,
|
||||
@@ -80,6 +84,8 @@ impl PanelKind {
|
||||
PanelKind::Metadata,
|
||||
PanelKind::Progress,
|
||||
PanelKind::ContentAwareFill,
|
||||
PanelKind::CreateNullsFromPaths,
|
||||
PanelKind::VrCompEditor,
|
||||
];
|
||||
pub fn title(self) -> &'static str {
|
||||
match self {
|
||||
@@ -116,6 +122,8 @@ impl PanelKind {
|
||||
PanelKind::Metadata => "Metadata",
|
||||
PanelKind::Progress => "Progress",
|
||||
PanelKind::ContentAwareFill => "Content-Aware Fill",
|
||||
PanelKind::CreateNullsFromPaths => "Create Nulls From Paths",
|
||||
PanelKind::VrCompEditor => "VR Comp Editor",
|
||||
}
|
||||
}
|
||||
pub fn id(self) -> String {
|
||||
@@ -342,7 +350,20 @@ pub fn workspace(name: &str) -> DockNode {
|
||||
tabs(&[Composition, Layer, Footage], 0),
|
||||
right(
|
||||
&[Info, Preview, Audio, Align, Character, Paragraph, LumetriScopes],
|
||||
&[EffectsPresets, Properties, Tracker, Wiggler, Smoother, MotionSketch, Paint, Brushes, Markers, ContentAwareFill],
|
||||
&[
|
||||
EffectsPresets,
|
||||
Properties,
|
||||
Tracker,
|
||||
Wiggler,
|
||||
Smoother,
|
||||
MotionSketch,
|
||||
Paint,
|
||||
Brushes,
|
||||
Markers,
|
||||
ContentAwareFill,
|
||||
CreateNullsFromPaths,
|
||||
VrCompEditor,
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -701,6 +722,18 @@ pub enum DockAction {
|
||||
PanelMenu(PanelKind, egui::Pos2),
|
||||
/// A tab started being dragged (re-dock or undock).
|
||||
BeginDrag(PanelKind),
|
||||
/// The tab's lock was toggled (Composition / Timeline viewer lock).
|
||||
ToggleLock(PanelKind),
|
||||
}
|
||||
|
||||
/// After Effects-style extras on a tab that shows a composition (Composition, Timeline): a close
|
||||
/// button (×), the item's label colour as a small square and the viewer lock.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TabDeco {
|
||||
pub swatch: egui::Color32,
|
||||
pub locked: bool,
|
||||
/// Close button and lock (Composition, Timeline); Effect Controls shows just the swatch.
|
||||
pub viewer: bool,
|
||||
}
|
||||
|
||||
/// Lay out the tree into group rects (with `gap` gutters) and handle gutter dragging.
|
||||
@@ -786,6 +819,7 @@ pub fn draw_group_chrome(
|
||||
t: &Tokens,
|
||||
reg: &mut crate::automation::Registry,
|
||||
title: &dyn Fn(PanelKind) -> String,
|
||||
decos: &[(PanelKind, TabDeco)],
|
||||
) -> Vec<DockAction> {
|
||||
let mut actions = Vec::new();
|
||||
let painter = ui.painter().clone();
|
||||
@@ -812,7 +846,14 @@ pub fn draw_group_chrome(
|
||||
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;
|
||||
let deco = decos.iter().find(|(k, _)| k == p).map(|(_, d)| *d);
|
||||
// × (active tab only), swatch and lock before the label.
|
||||
let deco_w = match deco {
|
||||
Some(d) if d.viewer => (if is_active { 16.0 } else { 0.0 }) + 14.0 + 16.0,
|
||||
Some(_) => 14.0,
|
||||
None => 0.0,
|
||||
};
|
||||
let w = galley.size().x + 16.0 + menu_w + deco_w;
|
||||
if x + w > strip.max.x - 20.0 && i > g.active {
|
||||
let r = Rect::from_min_size(pos2(strip.max.x - 22.0, strip.min.y + 6.0), vec2(18.0, 20.0));
|
||||
let resp = ui.interact(r, egui::Id::new(("tab-overflow", g.path.clone())), Sense::click());
|
||||
@@ -830,7 +871,44 @@ pub fn draw_group_chrome(
|
||||
actions.push(DockAction::BeginDrag(*p));
|
||||
}
|
||||
reg.add(&format!("panel.tab.{}", p.id()), tab, &label);
|
||||
let label_x = tab.min.x + 8.0;
|
||||
let mut label_x = tab.min.x + 8.0;
|
||||
if let Some(d) = deco {
|
||||
let mut dx = tab.min.x + 6.0;
|
||||
if is_active && d.viewer {
|
||||
let cr = Rect::from_center_size(pos2(dx + 5.0, text_y), vec2(10.0, 10.0));
|
||||
let cresp = ui.interact(cr.expand(2.0), egui::Id::new(("tab-close", g.path.clone(), i)), Sense::click());
|
||||
let cc = if cresp.hovered() { t.tab_text_active } else { t.tab_text };
|
||||
let k = 3.5;
|
||||
painter.line_segment([cr.center() + vec2(-k, -k), cr.center() + vec2(k, k)], Stroke::new(1.2, cc));
|
||||
painter.line_segment([cr.center() + vec2(-k, k), cr.center() + vec2(k, -k)], Stroke::new(1.2, cc));
|
||||
reg.add(&format!("panel.tab.{}.close", p.id()), cr, "Close");
|
||||
if cresp.clicked() {
|
||||
actions.push(DockAction::Close(*p));
|
||||
}
|
||||
dx += 16.0;
|
||||
}
|
||||
let sw = Rect::from_center_size(pos2(dx + 5.0, text_y), vec2(9.0, 9.0));
|
||||
painter.rect_filled(sw, 1.0, d.swatch);
|
||||
dx += 14.0;
|
||||
label_x = dx;
|
||||
if d.viewer {
|
||||
let lr = Rect::from_center_size(pos2(dx + 6.0, text_y), vec2(12.0, 12.0));
|
||||
let lresp = ui.interact(lr.expand(2.0), egui::Id::new(("tab-lock", g.path.clone(), i)), Sense::click());
|
||||
let lc = if d.locked {
|
||||
t.tab_text_active
|
||||
} else if lresp.hovered() {
|
||||
t.tab_text
|
||||
} else {
|
||||
t.text_faint
|
||||
};
|
||||
icons::paint(&painter, lr, Icon::Lock, lc);
|
||||
reg.add(&format!("panel.tab.{}.lock", p.id()), lr, if d.locked { "Unlock" } else { "Lock" });
|
||||
if lresp.clicked() {
|
||||
actions.push(DockAction::ToggleLock(*p));
|
||||
}
|
||||
label_x = dx + 16.0;
|
||||
}
|
||||
}
|
||||
let label_w = galley.size().x;
|
||||
let col = if is_active || resp.hovered() { t.tab_text_active } else { t.tab_text };
|
||||
painter.galley_with_override_text_color(pos2(label_x, text_y - galley.size().y / 2.0), galley, col);
|
||||
|
||||
@@ -35,6 +35,26 @@ impl EffectcraftApp {
|
||||
out
|
||||
}
|
||||
|
||||
/// The Composition and Timeline tabs' close button, label-colour swatch and viewer lock.
|
||||
fn tab_decos(&self) -> Vec<(PanelKind, dock::TabDeco)> {
|
||||
let Some(cid) = self.session.active_comp_id() else { return vec![] };
|
||||
let swatch = match self.session.project.item(cid).map(|i| i.label) {
|
||||
Some(l) if l != effectcraft_engine::color::Label::None => self.tokens.label(l),
|
||||
_ => self.tokens.text_faint,
|
||||
};
|
||||
let mut v: Vec<(PanelKind, dock::TabDeco)> = [PanelKind::Composition, PanelKind::Timeline]
|
||||
.into_iter()
|
||||
.map(|p| (p, dock::TabDeco { swatch, locked: self.ui.locked_tabs.contains(&p.id()), viewer: true }))
|
||||
.collect();
|
||||
// Effect Controls carries the selected layer's label colour.
|
||||
if let Some(l) = self.session.active_comp().and_then(|c| self.session.state.selected_layers.first().and_then(|id| c.layer(*id)))
|
||||
&& l.label != effectcraft_engine::color::Label::None
|
||||
{
|
||||
v.push((PanelKind::EffectControls, dock::TabDeco { swatch: self.tokens.label(l.label), locked: false, viewer: false }));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Settings ▸ Appearance ▸ Use Label Color for Related Tabs: the Composition and Timeline
|
||||
/// tabs carry their comp's label colour, Effect Controls and Properties the layer's.
|
||||
fn label_tab_marks(&self, ui: &egui::Ui) {
|
||||
@@ -44,12 +64,9 @@ impl EffectcraftApp {
|
||||
let Some(cid) = self.session.active_comp_id() else { return };
|
||||
let comp_label = self.session.project.item(cid).map(|i| i.label);
|
||||
let layer_label = self.session.active_comp().and_then(|c| self.session.state.selected_layers.first().and_then(|l| c.layer(*l))).map(|l| l.label);
|
||||
for (p, label) in [
|
||||
(PanelKind::Composition, comp_label),
|
||||
(PanelKind::Timeline, comp_label),
|
||||
(PanelKind::EffectControls, layer_label),
|
||||
(PanelKind::Properties, layer_label),
|
||||
] {
|
||||
// (the Composition, Timeline and Effect Controls tabs carry their swatch already)
|
||||
let _ = comp_label;
|
||||
for (p, label) in [(PanelKind::Properties, layer_label)] {
|
||||
let (Some(label), Some(e)) = (label, self.auto.find(&format!("panel.tab.{}", p.id()))) else { continue };
|
||||
if label == effectcraft_engine::color::Label::None {
|
||||
continue;
|
||||
@@ -131,9 +148,10 @@ impl EffectcraftApp {
|
||||
dock::layout(ui, &mut dock, body, &t, "", &mut groups, &mut self.auto);
|
||||
let mut actions = Vec::new();
|
||||
let titles = self.tab_titles();
|
||||
let decos = self.tab_decos();
|
||||
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, &title));
|
||||
actions.extend(dock::draw_group_chrome(ui, g, self.ui.focused, &t, &mut self.auto, &title, &decos));
|
||||
}
|
||||
self.label_tab_marks(ui);
|
||||
if maximized.is_none() {
|
||||
@@ -174,6 +192,11 @@ impl EffectcraftApp {
|
||||
DockAction::BeginDrag(p) => ctx.data_mut(|d| {
|
||||
d.insert_temp(drag_id(), p);
|
||||
}),
|
||||
DockAction::ToggleLock(p) => {
|
||||
if !self.ui.locked_tabs.remove(&p.id()) {
|
||||
self.ui.locked_tabs.insert(p.id().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.tab_drag(&ctx, &groups, &float_groups);
|
||||
@@ -213,7 +236,8 @@ impl EffectcraftApp {
|
||||
active: f.active.min(f.panels.len().saturating_sub(1)),
|
||||
stacked: None,
|
||||
};
|
||||
actions.extend(dock::draw_group_chrome(ui, &g, self.ui.focused, &t, &mut self.auto, title));
|
||||
let decos = self.tab_decos();
|
||||
actions.extend(dock::draw_group_chrome(ui, &g, self.ui.focused, &t, &mut self.auto, title, &decos));
|
||||
ui.painter().rect_stroke(r, t.radius, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
|
||||
if let Some(p) = g.panels.get(g.active).copied() {
|
||||
self.panel_body(ui, p, g.content);
|
||||
|
||||
+182
-23
@@ -4,8 +4,10 @@
|
||||
//! never waits for the compositor. Results land in a memory-budgeted cache keyed by (project
|
||||
//! revision, comp, frame, scale); the timeline draws the cached range as the green cache bar.
|
||||
//!
|
||||
//! wasm32 has no threads: jobs wait in the same priority queue and [`Frames::pump`] renders them
|
||||
//! on the UI thread between egui frames, within a time budget.
|
||||
//! wasm32 has no threads: jobs wait in the same priority queue and [`Frames::pump`] hands them
|
||||
//! to a [`RemoteFrames`] (the browser's frame worker, a second engine instance fed with project
|
||||
//! diffs, `effectcraft_engine::remote`) or, without one, renders them on the UI thread between
|
||||
//! egui frames, within a time budget.
|
||||
//!
|
||||
//! With the disk cache on (Settings ▸ Media & Disk Cache), every CPU-rendered frame is also
|
||||
//! written to disk under a content key (the comp's content hash, frame, scale, view and render
|
||||
@@ -163,6 +165,38 @@ fn frame_disk_key(keys: &ContentKeys, project: &Project, key: &FrameKey, opts_ha
|
||||
disk_cache::frame_key(content, key.frame, key.scale, key.view ^ opts_hash)
|
||||
}
|
||||
|
||||
/// A frame for a [`RemoteFrames`] renderer.
|
||||
pub struct RemoteJob {
|
||||
pub project: Arc<Project>,
|
||||
pub revision: u64,
|
||||
pub comp: ItemId,
|
||||
pub t: Tick,
|
||||
pub opts: RenderOpts,
|
||||
}
|
||||
|
||||
/// Premultiplied RGBA8 pixels from a [`RemoteFrames`] renderer.
|
||||
pub struct RemoteFrame {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<u8>,
|
||||
/// Render time (ms).
|
||||
pub ms: f64,
|
||||
}
|
||||
|
||||
/// Called once with a remote frame (or why there is none).
|
||||
pub type RemoteDone = Box<dyn FnOnce(Result<RemoteFrame, String>) + Send>;
|
||||
|
||||
/// Renders viewer frames elsewhere (the browser's frame worker), so the UI thread never does.
|
||||
pub trait RemoteFrames: Send + Sync {
|
||||
/// Frames it can render at the same time (0 when it is not usable: frames then render on
|
||||
/// the UI thread again).
|
||||
fn slots(&self) -> usize;
|
||||
/// Start rendering `job`; `done` runs when the frame arrives.
|
||||
fn start(&self, job: RemoteJob, done: RemoteDone);
|
||||
/// Drop cached intermediate results (Edit ▸ Purge).
|
||||
fn purge(&self) {}
|
||||
}
|
||||
|
||||
pub struct Frames {
|
||||
cache: Arc<Mutex<Cache>>,
|
||||
/// Keys queued or rendering.
|
||||
@@ -175,6 +209,9 @@ pub struct Frames {
|
||||
/// Render time of the last viewer (urgent) frame in ms, for the Info panel / perf readout.
|
||||
pub last_ms: Arc<Mutex<f64>>,
|
||||
content_keys: ContentKeys,
|
||||
/// Where frames render instead of the UI thread (wasm32), and how many it is rendering.
|
||||
remote: Option<Arc<dyn RemoteFrames>>,
|
||||
remote_busy: Arc<Mutex<usize>>,
|
||||
}
|
||||
|
||||
impl Default for Frames {
|
||||
@@ -190,6 +227,8 @@ impl Default for Frames {
|
||||
ctx: None,
|
||||
last_ms: Arc::new(Mutex::new(0.0)),
|
||||
content_keys: Arc::default(),
|
||||
remote: None,
|
||||
remote_busy: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -270,6 +309,9 @@ impl Frames {
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
if let Some(r) = &self.remote {
|
||||
r.purge();
|
||||
}
|
||||
if let Ok(mut c) = self.cache.lock() {
|
||||
c.map.clear();
|
||||
c.order.clear();
|
||||
@@ -324,7 +366,7 @@ impl Frames {
|
||||
q.jobs.push(Job { key, src: src.clone(), comp, t, opts, urgent, seq });
|
||||
drop(q);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if self.remote.is_none() {
|
||||
let w = self.worker();
|
||||
// One spawn per job; each spawn renders whichever queued job matters most right now.
|
||||
self.pool.spawn(move || {
|
||||
@@ -349,13 +391,102 @@ impl Frames {
|
||||
}
|
||||
}
|
||||
|
||||
/// Render queued frames on this thread, most important first, until the queue is empty or
|
||||
/// `budget` has passed (at least one frame). Returns whether frames are still queued. Only
|
||||
/// wasm32 needs this (native frames render on the pool); elsewhere it does nothing.
|
||||
/// Render frames with `remote` from now on (`None`: on this thread again).
|
||||
pub fn set_remote(&mut self, remote: Option<Arc<dyn RemoteFrames>>) {
|
||||
self.remote = remote;
|
||||
}
|
||||
|
||||
/// Whether frames go to a usable [`RemoteFrames`].
|
||||
pub fn remote_active(&self) -> bool {
|
||||
self.remote.as_ref().is_some_and(|r| r.slots() > 0)
|
||||
}
|
||||
|
||||
/// Frames the remote renderer renders at once (0 without one).
|
||||
pub fn remote_slots(&self) -> usize {
|
||||
self.remote.as_ref().map(|r| r.slots()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Frames being rendered remotely.
|
||||
pub fn remote_busy(&self) -> usize {
|
||||
self.remote_busy.lock().map(|b| *b).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Hand queued frames to the remote renderer while it has free slots, most important first
|
||||
/// (the viewer's frame, then prefetch in request order; a viewer frame requested while every
|
||||
/// slot is busy goes to the first one that frees up). Frames that the GPU compositor can keep
|
||||
/// on the GPU render here instead (no readback). Returns how many were started.
|
||||
pub fn dispatch_remote(&self) -> usize {
|
||||
let Some(remote) = self.remote.clone() else { return 0 };
|
||||
let slots = remote.slots();
|
||||
let w = self.worker();
|
||||
let mut started = 0;
|
||||
loop {
|
||||
let busy = self.remote_busy();
|
||||
if busy >= slots {
|
||||
break;
|
||||
}
|
||||
let job = {
|
||||
let Ok(mut q) = self.queue.lock() else { break };
|
||||
let Some(i) = Queue::best(&q.jobs) else { break };
|
||||
let job = q.jobs.swap_remove(i);
|
||||
q.running.insert(job.key);
|
||||
if job.urgent {
|
||||
q.urgent_running += 1;
|
||||
}
|
||||
job
|
||||
};
|
||||
if job.src.gpu.is_some() && job.src.gpu_display {
|
||||
let t0 = web_time::Instant::now();
|
||||
if let Some(img) = w.render_gpu(&job) {
|
||||
w.finish(&job, img, t0);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Ok(mut b) = self.remote_busy.lock() {
|
||||
*b += 1;
|
||||
}
|
||||
started += 1;
|
||||
let (key, urgent) = (job.key, job.urgent);
|
||||
let fw = self.worker();
|
||||
let busy = self.remote_busy.clone();
|
||||
let t0 = web_time::Instant::now();
|
||||
let rj = RemoteJob { project: job.src.project.clone(), revision: key.revision, comp: job.comp, t: job.t, opts: job.opts };
|
||||
remote.start(
|
||||
rj,
|
||||
Box::new(move |r: Result<RemoteFrame, String>| {
|
||||
if let Ok(mut b) = busy.lock() {
|
||||
*b = b.saturating_sub(1);
|
||||
}
|
||||
match r {
|
||||
Ok(f) => {
|
||||
let img = egui::ColorImage::from_rgba_premultiplied([f.width as usize, f.height as usize], &f.rgba);
|
||||
fw.finish_key(key, urgent, FrameImage::Cpu(Arc::new(img)), t0);
|
||||
}
|
||||
Err(e) => {
|
||||
// Not rendered (a stale revision, a lost worker): the viewer asks again.
|
||||
log::debug!("remote frame: {e}");
|
||||
fw.release(key, urgent);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
started
|
||||
}
|
||||
|
||||
/// Render queued frames, most important first. With a usable [`RemoteFrames`] they are only
|
||||
/// handed over ([`Frames::dispatch_remote`]); otherwise they render on this thread until the
|
||||
/// queue is empty or `budget` has passed (at least one frame). Returns whether frames are
|
||||
/// still queued or rendering remotely. Only wasm32 needs this (native frames render on the
|
||||
/// pool); elsewhere it does nothing.
|
||||
pub fn pump(&self, budget: std::time::Duration) -> bool {
|
||||
if cfg!(not(target_arch = "wasm32")) {
|
||||
return false;
|
||||
}
|
||||
if self.remote_active() {
|
||||
self.dispatch_remote();
|
||||
return self.queue.lock().map(|q| !q.jobs.is_empty()).unwrap_or(false) || self.remote_busy() > 0;
|
||||
}
|
||||
let t0 = web_time::Instant::now();
|
||||
let w = self.worker();
|
||||
while w.run_next() {
|
||||
@@ -380,12 +511,10 @@ struct Worker {
|
||||
impl Worker {
|
||||
/// Render the queued job that matters most right now. `false` when the queue was empty.
|
||||
fn run_next(&self) -> bool {
|
||||
let Worker { queue, cache, inflight, ctx, last, content_keys } = self;
|
||||
let Worker { queue, content_keys, .. } = self;
|
||||
let job = {
|
||||
let Ok(mut q) = queue.lock() else { return false };
|
||||
// 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 false };
|
||||
let Some(i) = Queue::best(&q.jobs) else { return false };
|
||||
let job = q.jobs.swap_remove(i);
|
||||
q.running.insert(job.key);
|
||||
if job.urgent {
|
||||
@@ -407,27 +536,50 @@ impl Worker {
|
||||
ci
|
||||
}
|
||||
};
|
||||
if job.urgent
|
||||
&& let Ok(mut l) = last.lock()
|
||||
{
|
||||
self.finish(&job, ci, t0);
|
||||
true
|
||||
}
|
||||
|
||||
/// Store a finished frame and release its job.
|
||||
fn finish(&self, job: &Job, img: FrameImage, t0: web_time::Instant) {
|
||||
self.finish_key(job.key, job.urgent, img, t0);
|
||||
}
|
||||
|
||||
fn finish_key(&self, key: FrameKey, urgent: bool, img: FrameImage, t0: web_time::Instant) {
|
||||
if urgent && let Ok(mut l) = self.last.lock() {
|
||||
*l = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
}
|
||||
if let Ok(mut c) = cache.lock() {
|
||||
c.insert(job.key, ci);
|
||||
if let Ok(mut c) = self.cache.lock() {
|
||||
c.insert(key, img);
|
||||
}
|
||||
if let Ok(mut inf) = inflight.lock() {
|
||||
inf.remove(&job.key);
|
||||
self.release(key, urgent);
|
||||
}
|
||||
|
||||
/// The job of `key` is no longer queued or running (rendered or dropped).
|
||||
fn release(&self, key: FrameKey, urgent: bool) {
|
||||
if let Ok(mut inf) = self.inflight.lock() {
|
||||
inf.remove(&key);
|
||||
}
|
||||
if let Ok(mut q) = queue.lock() {
|
||||
q.running.remove(&job.key);
|
||||
if job.urgent {
|
||||
q.urgent_running -= 1;
|
||||
if let Ok(mut q) = self.queue.lock() {
|
||||
q.running.remove(&key);
|
||||
if urgent {
|
||||
q.urgent_running = q.urgent_running.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
if let Some(ctx) = ctx {
|
||||
if let Some(ctx) = &self.ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The frame on the GPU, kept there for the viewer, if the compositor can do it alone.
|
||||
fn render_gpu(&self, job: &Job) -> Option<FrameImage> {
|
||||
let g = job.src.gpu.as_ref()?;
|
||||
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);
|
||||
r.accel = Some(g as &dyn effectcraft_engine::render::Accelerator);
|
||||
r.active_accel()?;
|
||||
g.render_display(&r, job.comp, job.t).map(|f| FrameImage::Gpu(Arc::new(f)))
|
||||
}
|
||||
|
||||
fn render_job(&self, job: &Job) -> FrameImage {
|
||||
@@ -465,3 +617,10 @@ struct Queue {
|
||||
urgent_running: usize,
|
||||
seq: u64,
|
||||
}
|
||||
|
||||
impl Queue {
|
||||
/// The job that matters most: urgent first (newest), then prefetch in request order.
|
||||
fn best(jobs: &[Job]) -> Option<usize> {
|
||||
jobs.iter().enumerate().max_by_key(|(_, j)| (j.urgent, if j.urgent { j.seq as i64 } else { -(j.seq as i64) })).map(|(i, _)| i)
|
||||
}
|
||||
}
|
||||
|
||||
+282
-44
@@ -110,6 +110,20 @@ pub struct Playback {
|
||||
pub shown: u64,
|
||||
pub waiting: bool,
|
||||
pub fps: f64,
|
||||
/// The Preview panel shortcut that started this preview and what it plays.
|
||||
pub shortcut: effectcraft_engine::preview::PreviewShortcut,
|
||||
pub plan: Option<effectcraft_engine::preview::PreviewPlan>,
|
||||
/// Cache Before Playback: rendering the range before the clock starts.
|
||||
pub caching: bool,
|
||||
/// Resolution override while playing (pixel step), `None` = the viewer's.
|
||||
pub res: Option<u32>,
|
||||
/// Include Overlays / Include Layer Controls.
|
||||
pub overlays: bool,
|
||||
pub layer_controls: bool,
|
||||
/// Full Screen: the maximized panel to restore when the preview stops.
|
||||
pub restore_max: Option<Option<PanelKind>>,
|
||||
/// Audio-only previews: the frame under the audible sample (the current time stays put).
|
||||
pub audio_frame: Option<i64>,
|
||||
}
|
||||
|
||||
pub struct EffectcraftApp {
|
||||
@@ -129,6 +143,8 @@ pub struct EffectcraftApp {
|
||||
pub(crate) deferred: Vec<(ControlRequest, f64)>,
|
||||
pub(crate) synthetic: Vec<egui::Event>,
|
||||
pub(crate) input_waiters: Vec<Sender<serde_json::Value>>,
|
||||
/// Control requests waiting for an offloaded job (`wait: true` in the browser).
|
||||
pub(crate) job_waiters: Vec<(control::JobWaiter, Sender<serde_json::Value>)>,
|
||||
queued_screenshots: Vec<(u64, f64, u32)>,
|
||||
pending_screenshots: Vec<(u64, Option<String>, Option<[f32; 4]>, Sender<serde_json::Value>, f64)>,
|
||||
next_token: u64,
|
||||
@@ -196,6 +212,7 @@ impl EffectcraftApp {
|
||||
deferred: vec![],
|
||||
synthetic: vec![],
|
||||
input_waiters: vec![],
|
||||
job_waiters: vec![],
|
||||
queued_screenshots: vec![],
|
||||
pending_screenshots: vec![],
|
||||
next_token: 1,
|
||||
@@ -419,6 +436,19 @@ impl EffectcraftApp {
|
||||
|
||||
/// The render scale used by the viewer right now.
|
||||
pub fn viewer_scale(&self, zoom: f32, ppp: f32) -> f64 {
|
||||
// The preview's Resolution (when not Auto) while it plays.
|
||||
if self.playback.playing
|
||||
&& let Some(f) = self.playback.res
|
||||
{
|
||||
let r = match f {
|
||||
1 => state::Resolution::Full,
|
||||
2 => state::Resolution::Half,
|
||||
3 => state::Resolution::Third,
|
||||
4 => state::Resolution::Quarter,
|
||||
n => state::Resolution::Custom(n.min(40) as u8),
|
||||
};
|
||||
return r.scale(zoom, ppp);
|
||||
}
|
||||
if self.playback.playing && self.ui.viewer.res == state::Resolution::Auto {
|
||||
// Keep previews snappy: half the displayed size, but no lower than Settings ▸
|
||||
// Previews ▸ Adaptive Resolution Limit.
|
||||
@@ -510,64 +540,163 @@ impl EffectcraftApp {
|
||||
// ---------------------------------------------------------------- playback
|
||||
|
||||
pub fn play(&mut self, now: f64) {
|
||||
let sc = self.session.prefs.preview.current;
|
||||
self.play_with(now, sc);
|
||||
}
|
||||
|
||||
/// Start the preview of a Preview panel shortcut (its range, play-from, rate, skip,
|
||||
/// resolution, loop, caching, full screen and include options).
|
||||
pub fn play_with(&mut self, now: f64, sc: effectcraft_engine::preview::PreviewShortcut) {
|
||||
let Some(c) = self.session.active_comp().cloned() else { return };
|
||||
let mut t = self.session.time();
|
||||
let (wa, wb) = c.work_area;
|
||||
if t >= wb - c.frame_duration() || t < wa {
|
||||
t = wa;
|
||||
let preset = self.session.prefs.preview.get(sc).clone();
|
||||
let plan = effectcraft_engine::preview::plan(&preset, &c, self.session.time());
|
||||
let fr = c.frame_rate;
|
||||
if plan.video {
|
||||
self.session.set_time(fr.tick_of(plan.first));
|
||||
}
|
||||
let restore_max = preset.full_screen.then_some(self.ui.maximized);
|
||||
if preset.full_screen && self.ui.dock.contains(PanelKind::Composition) {
|
||||
self.ui.maximized = Some(PanelKind::Composition);
|
||||
}
|
||||
self.session.set_time(t);
|
||||
self.playback = Playback {
|
||||
playing: true,
|
||||
start_wall: now,
|
||||
start_time: t,
|
||||
start_frame: c.frame_rate.frame_at(t),
|
||||
start_time: fr.tick_of(plan.first),
|
||||
start_frame: plan.first,
|
||||
shown: 0,
|
||||
waiting: false,
|
||||
fps: c.frame_rate.as_f64(),
|
||||
fps: plan.fps,
|
||||
shortcut: sc,
|
||||
plan: Some(plan),
|
||||
caching: plan.cache_first && plan.video,
|
||||
res: preset.resolution.factor(preset.custom_resolution),
|
||||
overlays: preset.include_overlays,
|
||||
layer_controls: preset.include_layer_controls,
|
||||
restore_max,
|
||||
audio_frame: (!plan.video).then_some(plan.first),
|
||||
};
|
||||
self.start_audio(t);
|
||||
if !self.playback.caching {
|
||||
self.start_audio(fr.tick_of(plan.first));
|
||||
}
|
||||
}
|
||||
|
||||
/// Start audio preview from comp time `t` when the Preview panel includes audio, the comp
|
||||
/// has something audible and an output device opens.
|
||||
/// Start audio preview from comp time `t` when the preview includes audio at the comp's
|
||||
/// frame rate, the comp has something audible and an output device opens.
|
||||
fn start_audio(&mut self, t: Tick) {
|
||||
self.audio = None;
|
||||
self.meter.clipped = [false; 2];
|
||||
if !self.ui.preview_audio {
|
||||
let Some(pl) = self.playback.plan else { return };
|
||||
if !pl.audio {
|
||||
return;
|
||||
}
|
||||
let Some(cid) = self.session.active_comp_id() else { return };
|
||||
let Some(c) = self.session.project.comp(cid).cloned() else { return };
|
||||
// A preview at another frame rate plays slower or faster than real time: silent.
|
||||
if (pl.fps - c.frame_rate.as_f64()).abs() > 0.01 {
|
||||
return;
|
||||
}
|
||||
if !effectcraft_engine::render::audio::comp_has_audio(&self.session.project, cid) {
|
||||
return;
|
||||
}
|
||||
let out = audio::AudioOutput::from_prefs(&self.session.prefs);
|
||||
let Some(dev) = self.hooks.audio_device.as_ref().and_then(|f| f(&out)) else { return };
|
||||
let mix = self.session.prefs.audio.preview_sample_rate;
|
||||
match audio::AudioPlayback::start(dev, self.render_source(), cid, t, c.work_area.0, c.work_area.1, self.ui.preview_loop, mix) {
|
||||
let fr = c.frame_rate;
|
||||
match audio::AudioPlayback::start(dev, self.render_source(), cid, t, fr.tick_of(pl.start), fr.tick_of(pl.end + 1), pl.looping, mix) {
|
||||
Ok(a) => self.audio = Some(a),
|
||||
Err(e) => log::warn!("audio preview: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) {
|
||||
self.playback.playing = false;
|
||||
let was = std::mem::replace(&mut self.playback.playing, false);
|
||||
self.audio = None;
|
||||
self.playback.caching = false;
|
||||
if !was {
|
||||
return;
|
||||
}
|
||||
if let Some(m) = self.playback.restore_max.take() {
|
||||
self.ui.maximized = m;
|
||||
}
|
||||
let Some(pl) = self.playback.plan else { return };
|
||||
let move_time = self.session.prefs.preview.get(self.playback.shortcut).move_time_to_preview_time;
|
||||
if !move_time {
|
||||
self.session.set_time(pl.origin);
|
||||
} else if let Some(f) = self.playback.audio_frame
|
||||
&& let Some(c) = self.session.active_comp()
|
||||
{
|
||||
let t = c.frame_rate.tick_of(f);
|
||||
self.session.set_time(t);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toggle_play(&mut self, now: f64) {
|
||||
if self.playback.playing { self.stop() } else { self.play(now) }
|
||||
let sc = self.session.prefs.preview.current;
|
||||
self.toggle_play_with(now, sc);
|
||||
}
|
||||
|
||||
/// RAM preview: advance at the comp frame rate when frames are cached; otherwise hold and
|
||||
/// keep rendering ahead (the green cache bar fills, then playback runs in real time).
|
||||
/// A preview shortcut pressed: start its preview, or stop the running one. While Cache
|
||||
/// Before Playback is still rendering, "If caching, play cached frames" plays what is
|
||||
/// cached so far instead of stopping.
|
||||
pub fn toggle_play_with(&mut self, now: f64, sc: effectcraft_engine::preview::PreviewShortcut) {
|
||||
if !self.playback.playing {
|
||||
self.play_with(now, sc);
|
||||
return;
|
||||
}
|
||||
if self.playback.caching && self.session.prefs.preview.get(self.playback.shortcut).play_cached_frames && self.play_cached(now) {
|
||||
return;
|
||||
}
|
||||
self.stop();
|
||||
}
|
||||
|
||||
/// Cut the caching preview down to the frames cached from its first frame on and play them.
|
||||
fn play_cached(&mut self, now: f64) -> bool {
|
||||
let (Some(mut pl), Some(cid)) = (self.playback.plan, self.session.active_comp_id()) else { return false };
|
||||
let scale = self.viewer_shown.as_ref().map(|(_, k)| k.scale as f64 / 1000.0).unwrap_or(1.0);
|
||||
let mut last = None;
|
||||
let mut f = pl.first;
|
||||
while f <= pl.end && self.frames.is_cached(&self.frame_key(cid, f, scale)) {
|
||||
last = Some(f);
|
||||
f += pl.step;
|
||||
}
|
||||
let Some(last) = last else { return false };
|
||||
pl.end = last;
|
||||
pl.start = pl.first;
|
||||
self.playback.plan = Some(pl);
|
||||
self.playback.caching = false;
|
||||
self.playback.start_wall = now;
|
||||
self.playback.start_frame = pl.first;
|
||||
let t = self.session.active_comp().map(|c| c.frame_rate.tick_of(pl.first)).unwrap_or_default();
|
||||
self.start_audio(t);
|
||||
true
|
||||
}
|
||||
|
||||
/// The viewer shows grids, guides and safe margins (hidden while a preview without
|
||||
/// Include Overlays plays).
|
||||
pub fn overlays_visible(&self) -> bool {
|
||||
!self.playback.playing || self.playback.overlays
|
||||
}
|
||||
|
||||
/// The viewer shows layer handles and paths (View ▸ Show Layer Controls, and Include Layer
|
||||
/// Controls while a preview plays).
|
||||
pub fn layer_controls_visible(&self) -> bool {
|
||||
self.ui.viewer.show_layer_controls && (!self.playback.playing || self.playback.layer_controls)
|
||||
}
|
||||
|
||||
/// RAM preview: advance at the preview's frame rate when frames are cached; otherwise hold
|
||||
/// and keep rendering ahead (the green cache bar fills, then playback runs in real time).
|
||||
fn advance_playback(&mut self, ctx: &egui::Context, scale: f64) {
|
||||
let Some(cid) = self.session.active_comp_id() else { return };
|
||||
let Some(c) = self.session.project.comp(cid).cloned() else { return };
|
||||
let now = ctx.input(|i| i.time);
|
||||
let fr = c.frame_rate;
|
||||
let (wa, wb) = (fr.frame_at(c.work_area.0), fr.frame_at(c.work_area.1 - c.frame_duration()));
|
||||
let plan = self.playback.plan.filter(|_| self.playback.playing);
|
||||
let (wa, wb) = match plan {
|
||||
Some(p) => (p.start, p.end),
|
||||
None => (fr.frame_at(c.work_area.0), fr.frame_at(c.work_area.1 - c.frame_duration())),
|
||||
};
|
||||
let looping = plan.is_none_or(|p| p.looping);
|
||||
let video = plan.is_none_or(|p| p.video);
|
||||
// Prefetch ahead.
|
||||
let cur = fr.frame_at(self.session.time());
|
||||
// While paused (scrubbing, editing) the viewer's frame comes first: prefetch only a few
|
||||
@@ -580,17 +709,53 @@ impl EffectcraftApp {
|
||||
(self.frames_parallelism() / 2).max(2) as i64
|
||||
};
|
||||
let mut queued = self.frames.inflight();
|
||||
if self.playback.caching
|
||||
&& let Some(p) = plan
|
||||
{
|
||||
// Cache Before Playback: the whole range in play order, then start the clock.
|
||||
let mut all = true;
|
||||
let n = (p.end - p.start) / p.step + 1;
|
||||
let order: Vec<i64> = (0..n).filter_map(|k| p.frame_after(p.first, k)).collect();
|
||||
for f in order {
|
||||
let key = self.frame_key(cid, f, scale);
|
||||
if self.frames.is_cached(&key) {
|
||||
continue;
|
||||
}
|
||||
all = false;
|
||||
if queued < ahead as usize {
|
||||
self.request_frame(cid, f, scale);
|
||||
queued += 1;
|
||||
}
|
||||
}
|
||||
self.playback.waiting = !all;
|
||||
if all {
|
||||
self.playback.caching = false;
|
||||
self.playback.start_wall = now;
|
||||
self.playback.start_frame = p.first;
|
||||
self.session.set_time(fr.tick_of(p.first));
|
||||
self.start_audio(fr.tick_of(p.first));
|
||||
}
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
let step = plan.map_or(1, |p| p.step);
|
||||
for k in 0..ahead * 3 {
|
||||
if queued >= ahead as usize {
|
||||
if queued >= ahead as usize || !video {
|
||||
break;
|
||||
}
|
||||
let mut f = cur + k;
|
||||
if f > wb {
|
||||
if !self.ui.preview_loop {
|
||||
break;
|
||||
let f = match plan {
|
||||
Some(p) => match p.frame_after(cur, k) {
|
||||
Some(f) => f,
|
||||
None => break,
|
||||
},
|
||||
None => {
|
||||
let mut f = cur + k;
|
||||
if f > wb {
|
||||
f = wa + (f - wb - 1).rem_euclid((wb - wa + 1).max(1));
|
||||
}
|
||||
f
|
||||
}
|
||||
f = wa + (f - wb - 1).rem_euclid((wb - wa + 1).max(1));
|
||||
}
|
||||
};
|
||||
let key = self.frame_key(cid, f, scale);
|
||||
if !self.frames.is_cached(&key) {
|
||||
self.request_frame(cid, f, scale);
|
||||
@@ -607,33 +772,61 @@ impl EffectcraftApp {
|
||||
if !self.playback.playing {
|
||||
return;
|
||||
}
|
||||
let snap = |f: i64| wa + (f - wa).div_euclid(step) * step;
|
||||
// Audio clock drives playback: show the frame under the audible sample (frames that
|
||||
// are not rendered yet are dropped, never delayed).
|
||||
if let Some(a) = &self.audio {
|
||||
if a.finished() {
|
||||
self.session.set_time(fr.tick_of(wb));
|
||||
if video {
|
||||
self.session.set_time(fr.tick_of(wb));
|
||||
} else {
|
||||
self.playback.audio_frame = Some(wb);
|
||||
}
|
||||
self.stop();
|
||||
return;
|
||||
}
|
||||
let target = audio::frame_of_sample(a.clock(), a.rate, fr).clamp(wa, wb);
|
||||
self.playback.waiting = !self.frames.is_cached(&self.frame_key(cid, target, scale));
|
||||
if target != cur {
|
||||
self.session.set_time(fr.tick_of(target));
|
||||
self.playback.shown += 1;
|
||||
let target = snap(audio::frame_of_sample(a.clock(), a.rate, fr).clamp(wa, wb));
|
||||
if !video {
|
||||
self.playback.audio_frame = Some(target);
|
||||
} else {
|
||||
self.playback.waiting = !self.frames.is_cached(&self.frame_key(cid, target, scale));
|
||||
if target != cur {
|
||||
self.session.set_time(fr.tick_of(target));
|
||||
self.playback.shown += 1;
|
||||
}
|
||||
}
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
let elapsed = now - self.playback.start_wall;
|
||||
let mut target = self.playback.start_frame + (elapsed * fr.as_f64()).floor() as i64;
|
||||
if target > wb {
|
||||
if self.ui.preview_loop {
|
||||
target = wa + (target - wa).rem_euclid((wb - wa + 1).max(1));
|
||||
} else {
|
||||
self.session.set_time(fr.tick_of(wb));
|
||||
self.stop();
|
||||
return;
|
||||
let n = ((elapsed * self.playback.fps) / step as f64).floor() as i64;
|
||||
let target = match plan {
|
||||
Some(p) => p.frame_after(self.playback.start_frame, n),
|
||||
None => {
|
||||
let t = self.playback.start_frame + n;
|
||||
if t <= wb {
|
||||
Some(t)
|
||||
} else if looping {
|
||||
Some(wa + (t - wa).rem_euclid((wb - wa + 1).max(1)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let Some(target) = target else {
|
||||
if video {
|
||||
self.session.set_time(fr.tick_of(wb));
|
||||
} else {
|
||||
self.playback.audio_frame = Some(wb);
|
||||
}
|
||||
self.stop();
|
||||
return;
|
||||
};
|
||||
if !video {
|
||||
// Audio-only preview without an audio device: the clock runs, the time stays.
|
||||
self.playback.audio_frame = Some(target);
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
let key = self.frame_key(cid, target, scale);
|
||||
if self.frames.is_cached(&key) {
|
||||
@@ -645,8 +838,7 @@ impl EffectcraftApp {
|
||||
} else {
|
||||
// Not cached yet: hold the clock at the current frame (cache first, then play).
|
||||
self.playback.waiting = true;
|
||||
let next = cur + 1;
|
||||
let next = if next > wb { wa } else { next };
|
||||
let next = plan.and_then(|p| p.frame_after(cur, 1)).unwrap_or(if cur + 1 > wb { wa } else { cur + 1 });
|
||||
if self.frames.is_cached(&self.frame_key(cid, next, scale)) {
|
||||
self.session.set_time(fr.tick_of(next));
|
||||
}
|
||||
@@ -658,8 +850,9 @@ impl EffectcraftApp {
|
||||
|
||||
fn frames_parallelism(&self) -> usize {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
// frames render one at a time on the UI thread (`Frames::pump`)
|
||||
return 1;
|
||||
// frame workers render one frame each; without them frames render one at a time
|
||||
// on the UI thread (`Frames::pump`)
|
||||
return self.frames.remote_slots().max(1);
|
||||
}
|
||||
std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4)
|
||||
}
|
||||
@@ -692,6 +885,10 @@ impl EffectcraftApp {
|
||||
}
|
||||
}
|
||||
control::Outcome::AfterInput => self.input_waiters.push(reply),
|
||||
control::Outcome::AwaitJobs(w) => {
|
||||
self.job_waiters.push((w, reply));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
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.
|
||||
@@ -708,6 +905,28 @@ impl EffectcraftApp {
|
||||
}
|
||||
}
|
||||
self.control_rx = Some(rx);
|
||||
self.finish_job_waiters(ctx);
|
||||
}
|
||||
|
||||
/// Reply to the control requests whose offloaded jobs ended.
|
||||
fn finish_job_waiters(&mut self, ctx: &egui::Context) {
|
||||
if self.job_waiters.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.session.poll_render();
|
||||
self.session.poll_offload();
|
||||
let waiters = std::mem::take(&mut self.job_waiters);
|
||||
for (w, reply) in waiters {
|
||||
if w.pending(self) {
|
||||
self.job_waiters.push((w, reply));
|
||||
} else {
|
||||
let v = w.finish(self);
|
||||
let _ = reply.send(v);
|
||||
}
|
||||
}
|
||||
if !self.job_waiters.is_empty() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
fn issue_screenshots(&mut self, ctx: &egui::Context) {
|
||||
@@ -772,7 +991,9 @@ impl EffectcraftApp {
|
||||
for ev in self.session.drain_events() {
|
||||
match ev {
|
||||
effectcraft_engine::Event::OpenComp(_) => {
|
||||
self.ui.dock.activate(PanelKind::Composition);
|
||||
if !self.ui.locked_tabs.contains(&PanelKind::Composition.id()) {
|
||||
self.ui.dock.activate(PanelKind::Composition);
|
||||
}
|
||||
self.ui.timeline.pps = None;
|
||||
}
|
||||
effectcraft_engine::Event::Toast { message, .. } => self.toast = Some((message, ctx.input(|i| i.time))),
|
||||
@@ -905,6 +1126,23 @@ impl EffectcraftApp {
|
||||
if self.session.prefs.auto_save.enabled {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs(30));
|
||||
}
|
||||
// File ▸ Watch Folder: look for new projects every 10 seconds.
|
||||
if self.session.state.watch_folder.is_some() {
|
||||
let key = egui::Id::new("watchFolder.lastPoll");
|
||||
let last: f64 = ctx.data(|d| d.get_temp(key)).unwrap_or(0.0);
|
||||
if now - last >= 10.0 {
|
||||
ctx.data_mut(|d| d.insert_temp(key, now));
|
||||
match self.session.execute("file.watchFolder.poll", serde_json::json!({})) {
|
||||
Ok(r) => {
|
||||
if let Some(n) = r["rendered"].as_array().map(Vec::len).filter(|n| *n > 0) {
|
||||
self.ui.status = format!("Watch Folder: rendered {n} project(s)");
|
||||
}
|
||||
}
|
||||
Err(e) => self.ui.status = e.to_string(),
|
||||
}
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the pending synthetic input (from `ui.click`, `ui.key`, …). Hosts that don't call
|
||||
|
||||
@@ -27,7 +27,10 @@ macro_rules! uic {
|
||||
|
||||
/// UI-only commands (not in the AE menus; shortcuts and the command palette).
|
||||
pub const UI_COMMANDS: &[UiCommand] = &[
|
||||
uic!("playback.ramPreview", "Play Current Preview", [], Some("Num0")),
|
||||
uic!("playback.ramPreview", "Preview (Numpad 0)", [], Some("Num0")),
|
||||
uic!("playback.preview.shiftSpacebar", "Preview (Shift+Spacebar)", [], Some("Shift+Space")),
|
||||
uic!("playback.preview.shiftNumpad0", "Preview (Shift+Numpad 0)", [], Some("Shift+Num0")),
|
||||
uic!("playback.preview.altNumpad0", "Preview (Alt+Numpad 0)", [], Some("Alt+Num0")),
|
||||
uic!("playback.stop", "Stop", [], None),
|
||||
uic!("view.fit", "Fit", [], Some("Shift+/")),
|
||||
uic!("view.actualSize", "100%", [], Some("/")),
|
||||
@@ -290,7 +293,12 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
|
||||
let timing = |app: &mut EffectcraftApp, op: &str| app.session.execute("layer.timing", json!({"op": op})).map_err(|e| e.to_string());
|
||||
match id {
|
||||
"playback.ramPreview" => {
|
||||
app.toggle_play(now);
|
||||
app.toggle_play_with(now, effectcraft_engine::preview::PreviewShortcut::Numpad0);
|
||||
return Ok(json!({"playing": app.playback.playing}));
|
||||
}
|
||||
"playback.preview.shiftSpacebar" | "playback.preview.shiftNumpad0" | "playback.preview.altNumpad0" => {
|
||||
let sc = effectcraft_engine::preview::PreviewShortcut::parse(id.trim_start_matches("playback.preview.")).ok_or("unknown preview shortcut")?;
|
||||
app.toggle_play_with(now, sc);
|
||||
return Ok(json!({"playing": app.playback.playing}));
|
||||
}
|
||||
"playback.stop" => {
|
||||
@@ -534,8 +542,14 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
|
||||
Value::Null
|
||||
}
|
||||
"playback.toggle" => {
|
||||
app.toggle_play(now);
|
||||
json!({"playing": app.playback.playing})
|
||||
// The play button and Spacebar: `{shortcut?}` picks which Preview panel shortcut's
|
||||
// options to play with (default Spacebar).
|
||||
let sc = match p.get("shortcut").and_then(Value::as_str) {
|
||||
Some(k) => effectcraft_engine::preview::PreviewShortcut::parse(k).ok_or_else(|| format!("unknown preview shortcut `{k}`"))?,
|
||||
None => effectcraft_engine::preview::PreviewShortcut::Spacebar,
|
||||
};
|
||||
app.toggle_play_with(now, sc);
|
||||
json!({"playing": app.playback.playing, "shortcut": sc.id()})
|
||||
}
|
||||
"playback.cacheWhenIdle" => {
|
||||
let r = toggle(&mut app.ui.cache_when_idle, &p);
|
||||
@@ -543,8 +557,11 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
|
||||
r
|
||||
}
|
||||
"playback.audio" => {
|
||||
let r = toggle(&mut app.ui.preview_audio, &p);
|
||||
if !app.ui.preview_audio {
|
||||
// Include Audio of the shortcut shown in the Preview panel.
|
||||
let mut on = app.session.prefs.preview.active().include_audio;
|
||||
let r = toggle(&mut on, &p);
|
||||
app.session.execute("playback.settings.set", json!({"includeAudio": on})).map_err(|e| e.to_string())?;
|
||||
if !on {
|
||||
app.audio = None;
|
||||
}
|
||||
r
|
||||
@@ -801,6 +818,12 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
|
||||
crate::panels::dialogs::open_form(app, "file.interpretFootage", &json!({}));
|
||||
Value::Null
|
||||
}
|
||||
// Help ▸ In-App Tutorials: the Home screen's Learn tab.
|
||||
"help.inAppTutorials" => {
|
||||
app.ui.start_screen = true;
|
||||
app.ui.home_learn = true;
|
||||
Value::Null
|
||||
}
|
||||
"effect.manage" | "anim.browsePresets" => {
|
||||
app.show_panel(PanelKind::EffectsPresets);
|
||||
Value::Null
|
||||
@@ -831,6 +854,9 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
|
||||
"file.save" if app.session.path.is_none() => ("path", Ask::Save("Untitled Project.ecproj")),
|
||||
"file.saveAs" | "file.saveCopy" => ("path", Ask::Save("Untitled Project.ecproj")),
|
||||
"comp.saveFrameAs" => ("path", Ask::Save("Frame.png")),
|
||||
"comp.saveFrameAsPsd" => ("path", Ask::Save("Frame.psd")),
|
||||
"comp.saveFrameAsExr" => ("path", Ask::Save("Frame.exr")),
|
||||
"file.watchFolder" if params.get("stop").is_none() => ("folder", Ask::Save("Watch Folder")),
|
||||
"anim.savePreset" => ("path", Ask::Save("Preset.ecpreset")),
|
||||
"anim.applyPreset" => ("path", Ask::Open(&["ecpreset", "json"])),
|
||||
"view.exportGuides" => ("path", Ask::Save("Guides.json")),
|
||||
@@ -955,7 +981,7 @@ pub(crate) fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option<bool>
|
||||
"view.snapToGrid" => Some(v.snap_grid),
|
||||
"view.layerControls" => Some(v.show_layer_controls),
|
||||
"playback.cacheWhenIdle" => Some(app.ui.cache_when_idle),
|
||||
"playback.audio" => Some(app.ui.preview_audio),
|
||||
"playback.audio" => Some(app.session.prefs.preview.active().include_audio),
|
||||
"view.res.full" | "view.res.half" | "view.res.third" | "view.res.quarter" => {
|
||||
Some(v.res.label().eq_ignore_ascii_case(e.command.trim_start_matches("view.res.")))
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ pub fn state_key(app: &EffectcraftApp) -> u64 {
|
||||
let v = &app.ui.viewer;
|
||||
(v.rulers, v.guides, v.snap_guides, v.lock_guides, v.grid, v.snap_grid, v.show_layer_controls, v.pasteboard).hash(&mut h);
|
||||
v.res.label().hash(&mut h);
|
||||
(app.ui.cache_when_idle, app.ui.preview_audio, &app.ui.workspace, app.dialog.is_some()).hash(&mut h);
|
||||
(app.ui.cache_when_idle, app.session.prefs.preview.active().include_audio, &app.ui.workspace, app.dialog.is_some()).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
//! - layer parameters have a layer popup and a Source / Masks / Effects & Masks popup; mask
|
||||
//! ("Path") parameters list the layer's masks;
|
||||
//! - Curves has its graph editor, Levels its histogram with input/output triangles, Auto
|
||||
//! Levels a histogram.
|
||||
//! Levels a histogram; Lumetri's curves, Colorama's output cycle, Glow's colour map and
|
||||
//! Reshape's correspondence points have visual editors ([`super::fx_editors`]).
|
||||
|
||||
use effectcraft_engine::geom::Mat3;
|
||||
use effectcraft_engine::keyframe::Value;
|
||||
@@ -40,7 +41,7 @@ fn selected_layer(app: &EffectcraftApp) -> Option<Layer> {
|
||||
|
||||
/// An undo-merge key for one gesture on `id`: a new key each time a drag starts, so separate
|
||||
/// drags are separate undo steps while one drag is one step.
|
||||
fn gesture_key(ui: &egui::Ui, id: egui::Id, started: bool) -> String {
|
||||
pub(super) fn gesture_key(ui: &egui::Ui, id: egui::Id, started: bool) -> String {
|
||||
let kid = id.with("gesture");
|
||||
let n: u64 = if started {
|
||||
let n = ui.data(|d| d.get_temp::<u64>(kid)).unwrap_or(0) + 1;
|
||||
@@ -441,6 +442,37 @@ fn dial_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, layer: &Layer, prop: &P
|
||||
}
|
||||
}
|
||||
|
||||
/// The effect instance a row belongs to, for conditional visibility
|
||||
/// ([`effectcraft_engine::effects::catalog::param_shown`]): effect id, the instance's root
|
||||
/// group and the spec-id path of the group being drawn (`""` or `cameraPosition/`).
|
||||
struct FxScope<'a> {
|
||||
effect: &'a str,
|
||||
root: &'a PropGroup,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl<'a> FxScope<'a> {
|
||||
fn sub(&self, m: &str) -> FxScope<'a> {
|
||||
FxScope { effect: self.effect, root: self.root, path: format!("{}{m}/", self.path) }
|
||||
}
|
||||
/// Whether child `m` of the current group is shown.
|
||||
fn shown(&self, layer: &Layer, ectx: &EvalCtx, m: &str) -> bool {
|
||||
let root = self.root;
|
||||
let value = |id: &str| -> Option<Value> {
|
||||
let mut g = root;
|
||||
let mut parts = id.split('/').peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if parts.peek().is_none() {
|
||||
return g.get(part).map(|p| ectx.value(layer, p));
|
||||
}
|
||||
g = g.sub(part)?;
|
||||
}
|
||||
None
|
||||
};
|
||||
effectcraft_engine::effects::catalog::param_shown(self.effect, &format!("{}{m}", self.path), &value)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn group_rows(
|
||||
app: &mut EffectcraftApp,
|
||||
@@ -452,6 +484,7 @@ fn group_rows(
|
||||
rect: Rect,
|
||||
y: &mut f32,
|
||||
depth: usize,
|
||||
fx: &FxScope,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
let t = app.tokens;
|
||||
@@ -459,7 +492,7 @@ fn group_rows(
|
||||
let r = Rect::from_min_size(pos2(rect.min.x, *y), vec2(rect.width(), ROW));
|
||||
match c {
|
||||
Node::Prop(pr) => {
|
||||
if matches!(pr.ui, ParamUi::Hidden) || pr.three_d_only && !layer.is_3d() {
|
||||
if matches!(pr.ui, ParamUi::Hidden) || pr.three_d_only && !layer.is_3d() || !fx.shown(layer, ectx, &pr.match_id) {
|
||||
continue;
|
||||
}
|
||||
*y += ROW;
|
||||
@@ -486,7 +519,7 @@ fn group_rows(
|
||||
}
|
||||
Node::Group(sg) => {
|
||||
// Paint strokes live in the Timeline only (AE's Paint shows Paint on Transparent).
|
||||
if effectcraft_engine::effects::paint::is_paint(g) {
|
||||
if effectcraft_engine::effects::paint::is_paint(g) || !fx.shown(layer, ectx, &sg.match_id) {
|
||||
continue;
|
||||
}
|
||||
*y += ROW;
|
||||
@@ -503,7 +536,17 @@ fn group_rows(
|
||||
p.text(pos2(tw.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, &sg.name, Tokens::ui(12.0), t.text);
|
||||
}
|
||||
if open {
|
||||
group_rows(app, ui, p, layer, sg, ectx, rect, y, depth + 1, actions);
|
||||
let sub = fx.sub(&sg.match_id);
|
||||
// A visual editor for the group's hidden parameters (Lumetri curves, …).
|
||||
let eh = super::fx_editors::inline_height(fx.effect, &sub.path, rect.width());
|
||||
if eh > 0.0 {
|
||||
let er = Rect::from_min_size(pos2(rect.min.x, *y), vec2(rect.width(), eh));
|
||||
*y += eh;
|
||||
if er.max.y >= rect.min.y && er.min.y <= rect.max.y {
|
||||
super::fx_editors::inline_editor(app, ui, p, layer, fx.root, sg, fx.effect, &sub.path, ectx, er, actions);
|
||||
}
|
||||
}
|
||||
group_rows(app, ui, p, layer, sg, ectx, rect, y, depth + 1, &sub, actions);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -570,8 +613,9 @@ fn roto_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, l
|
||||
// Curves / Levels editors
|
||||
|
||||
/// Height of the custom editor shown under an effect's header (0 when none).
|
||||
fn editor_height(effect: &str, width: f32) -> f32 {
|
||||
fn editor_height(effect: &str, g: &PropGroup, width: f32) -> f32 {
|
||||
match effect {
|
||||
super::fx_editors::GLOW | super::fx_editors::RESHAPE => super::fx_editors::header_height(effect, g, width),
|
||||
"ec.color.curves" => 34.0 + curves_size(width) + 26.0,
|
||||
effectcraft_engine::effects::warp_stab::ID => 50.0,
|
||||
effectcraft_engine::effects::camera_tracker::ID => super::camera_tracker_ui::EDITOR_HEIGHT,
|
||||
@@ -642,12 +686,24 @@ fn channel_popup(
|
||||
fn curves_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, layer: &Layer, g: &PropGroup, ectx: &EvalCtx, r: Rect, actions: &mut Actions) {
|
||||
let t = app.tokens;
|
||||
let euid = g.uid;
|
||||
let ch = app.ui.fx_curve_channel.get(&euid).copied().unwrap_or(0).min(4);
|
||||
// The channel lives in the effect's hidden Channel parameter (UI state for instances
|
||||
// saved before it existed).
|
||||
let chan_prop = g.get("channel");
|
||||
let ch = match chan_prop {
|
||||
Some(pr) => ectx.value(layer, pr).as_enum() as usize,
|
||||
None => app.ui.fx_curve_channel.get(&euid).copied().unwrap_or(0),
|
||||
}
|
||||
.min(4);
|
||||
let x0 = r.min.x + 30.0;
|
||||
let cy = r.min.y + 17.0;
|
||||
let names: Vec<&str> = fw::CURVE_CHANNELS.iter().map(|c| c.1).collect();
|
||||
if let Some(n) = channel_popup(app, ui, p, x0, cy, ch, &names, egui::Id::new(("ec-cch", euid)), &format!("effectControls.effect.{euid}.curves.channel")) {
|
||||
app.ui.fx_curve_channel.insert(euid, n);
|
||||
match chan_prop {
|
||||
Some(pr) => actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": pr.uid, "value": n}))),
|
||||
None => {
|
||||
app.ui.fx_curve_channel.insert(euid, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
let pencil = app.ui.fx_curve_pencil.contains(&euid);
|
||||
let mr = Rect::from_min_size(pos2(x0 + 146.0, cy - 9.0), vec2(56.0, 18.0));
|
||||
@@ -696,7 +752,7 @@ fn curves_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter,
|
||||
/// Levels parameter ids for a channel: input black, input white, gamma, output black, output white.
|
||||
fn levels_ids(effect: &str, ch: usize) -> [String; 5] {
|
||||
if effect == "ec.color.levels" {
|
||||
return ["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].map(String::from);
|
||||
return effectcraft_engine::effects::levels_channel_ids(ch);
|
||||
}
|
||||
// Levels (Individual Controls) nests each channel's controls in its twirl-down group.
|
||||
let pre = fw::LEVELS_CHANNELS[ch.min(4)].0;
|
||||
@@ -721,7 +777,13 @@ fn levels_editor(
|
||||
let euid = g.uid;
|
||||
let x0 = r.min.x + 30.0;
|
||||
let cy = r.min.y + 17.0;
|
||||
let ch = if effect == "ec.color.levelsic" { app.ui.fx_levels_channel.get(&euid).copied().unwrap_or(0).min(4) } else { 0 };
|
||||
// Levels keeps its channel in the Channel parameter; Levels (Individual Controls) shows
|
||||
// every channel and the popup only picks the histogram.
|
||||
let ch = if effect == "ec.color.levelsic" {
|
||||
app.ui.fx_levels_channel.get(&euid).copied().unwrap_or(0).min(4)
|
||||
} else {
|
||||
g.get("channel").map(|pr| ectx.value(layer, pr).as_enum() as usize).unwrap_or(0).min(4)
|
||||
};
|
||||
if effect == "ec.color.levelsic" {
|
||||
let names: Vec<&str> = fw::LEVELS_CHANNELS.iter().map(|c| c.1).collect();
|
||||
if let Some(n) = channel_popup(app, ui, p, x0, cy, ch, &names, egui::Id::new(("ec-lch", euid)), &format!("effectControls.effect.{euid}.levels.channel"))
|
||||
@@ -944,7 +1006,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
item(ui, "Move Down", fi + 1 < fx.len(), "effect.reorder", json!({"layer": lid, "effect": g.uid, "index": fi + 2}));
|
||||
});
|
||||
if open {
|
||||
let eh = editor_height(effect, body.width());
|
||||
let eh = editor_height(effect, g, body.width());
|
||||
if eh > 0.0 {
|
||||
let er = Rect::from_min_size(pos2(body.min.x, y), vec2(body.width(), eh));
|
||||
y += eh;
|
||||
@@ -955,11 +1017,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
effectcraft_engine::effects::camera_tracker::ID => super::camera_tracker_ui::editor(app, ui, &bp, &layer, g, er, &mut actions),
|
||||
effectcraft_engine::effects::roto::ID => roto_editor(app, ui, &bp, &layer, g, er, &mut actions),
|
||||
"ec.color.levels" | "ec.color.levelsic" => levels_editor(app, ui, &bp, &layer, g, effect, &ectx, er, &mut actions),
|
||||
super::fx_editors::GLOW | super::fx_editors::RESHAPE => {
|
||||
super::fx_editors::header_editor(app, ui, &bp, &layer, g, effect, &ectx, er, &mut actions)
|
||||
}
|
||||
_ => histogram_only(app, ui, &bp, g, er),
|
||||
}
|
||||
}
|
||||
}
|
||||
group_rows(app, ui, &bp, &layer, g, &ectx, body, &mut y, 0, &mut actions);
|
||||
let scope = FxScope { effect: effect.as_str(), root: g, path: String::new() };
|
||||
group_rows(app, ui, &bp, &layer, g, &ectx, body, &mut y, 0, &scope, &mut actions);
|
||||
}
|
||||
y += 4.0;
|
||||
}
|
||||
@@ -1078,10 +1144,14 @@ pub fn viewer_hook(
|
||||
} else if app.ui.viewer.show_layer_controls {
|
||||
// ⊕ controls for the point parameters of the selected effects.
|
||||
let sel = app.session.state.selected_props.clone();
|
||||
for layer in ectx.comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id) && l.is_active_at(ectx.time)) {
|
||||
let selected = app.session.state.selected_layers.clone();
|
||||
for layer in ectx.comp.layers.iter().filter(|l| selected.contains(&l.id) && l.is_active_at(ectx.time)) {
|
||||
let Some(fx) = layer.effects() else { continue };
|
||||
let m = l2c(ectx, layer);
|
||||
for g in fx.groups().filter(|g| g.enabled && sel.iter().any(|(l, u)| *l == layer.id && *u == g.uid)) {
|
||||
if matches!(&g.kind, GroupKind::Effect { effect } if effect == super::fx_editors::RESHAPE) {
|
||||
super::fx_editors::reshape_overlay(app, ui, painter, map, ectx, layer, g, &m, &mut actions);
|
||||
}
|
||||
let pts: Vec<&Property> = g.props().filter(|p| matches!(p.ui, ParamUi::Point)).collect();
|
||||
let screen: Vec<egui::Pos2> = pts
|
||||
.iter()
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! be exposed) and the template name.
|
||||
//! - The controls: drag a property name from the timeline onto the list (or Animation ▸ Add
|
||||
//! Property to Essential Graphics); each shows as a text / colour / slider / checkbox / point /
|
||||
//! angle / dropdown control editing the source property; rename by double-clicking the name;
|
||||
//! angle / dropdown control editing the source property (Add Selected As: Source Text as a font
|
||||
//! control, Scale as one uniform slider); rename by double-clicking the name;
|
||||
//! reorder with ▲▼, remove with ✕; groups and comments from Add Formatting; Media
|
||||
//! Replacement for the selected footage layer.
|
||||
//! - **Export Template…** writes an open `.ectemplate`.
|
||||
@@ -134,6 +135,19 @@ fn body(app: &mut EffectcraftApp, ui: &mut egui::Ui) -> (Actions, Actions) {
|
||||
}
|
||||
});
|
||||
app.auto.add("essential.addFormatting", r.response.rect, "Add Formatting");
|
||||
// The selected property as a Font control (Source Text) or a uniform Scale slider.
|
||||
let has_sel = !app.session.state.selected_props.is_empty();
|
||||
let r = ui.add_enabled_ui(has_sel, |ui| {
|
||||
ui.menu_button("Add Selected As", |ui| {
|
||||
for (label, as_type) in [("Font Control", "font"), ("Uniform Scale", "scale")] {
|
||||
if ui.button(label).clicked() {
|
||||
actions.push(("essential.addProperty".into(), json!({"as": as_type})));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
app.auto.add("essential.addAs", r.response.rect, "Add Selected As");
|
||||
let footage_layer = app.session.active_comp().and_then(|c| {
|
||||
app.session.state.selected_layers.iter().filter_map(|l| c.layer(*l)).find(|l| matches!(l.source, LayerSource::Footage { .. })).map(|l| l.id.0)
|
||||
});
|
||||
@@ -184,7 +198,7 @@ fn controls(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, list: &[Eg
|
||||
match src {
|
||||
Some((layer, lt, p)) => {
|
||||
let v = p.value_at(lt);
|
||||
if let Some(nv) = value_widget(app, ui, &format!("essential.control.{}.value", c.id), &p, &v) {
|
||||
if let Some(nv) = value_widget(app, ui, &format!("essential.control.{}.value", c.id), essential::effective_type(c, &p), &p, &v) {
|
||||
actions.push((
|
||||
"prop.set".into(),
|
||||
json!({"comp": cid.0, "layer": layer, "prop": p.uid, "value": nv, "merge": format!("eg-{}", c.id)}),
|
||||
@@ -245,8 +259,8 @@ fn name_label(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, c: &EgCo
|
||||
}
|
||||
|
||||
/// The editor for a control's value; returns the new value (JSON for `prop.set`).
|
||||
fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, p: &Property, v: &KV) -> Option<Value> {
|
||||
let ty = essential::control_type(p)?;
|
||||
fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Option<ControlType>, p: &Property, v: &KV) -> Option<Value> {
|
||||
let ty = ty?;
|
||||
let mut out = None;
|
||||
let rect;
|
||||
match ty {
|
||||
@@ -319,6 +333,48 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, p: &Pro
|
||||
}
|
||||
rect = r.rect;
|
||||
}
|
||||
ControlType::Font => {
|
||||
// Family (from the installed fonts), style and size; the text stays as it is.
|
||||
let KV::Text(doc) = v else { return None };
|
||||
let fams = effectcraft_engine::text::fonts::families();
|
||||
let mut d = (**doc).clone();
|
||||
let mut changed = false;
|
||||
let r1 = egui::ComboBox::from_id_salt(("eg-font", auto)).selected_text(&d.font).width(110.0).show_ui(ui, |ui| {
|
||||
for (f, _) in &fams {
|
||||
if ui.selectable_label(*f == d.font, f).clicked() {
|
||||
d.font = f.clone();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
let styles: Vec<String> = fams.iter().find(|(f, _)| *f == d.font).map(|(_, st)| st.clone()).unwrap_or_default();
|
||||
let r2 = egui::ComboBox::from_id_salt(("eg-style", auto)).selected_text(&d.style).width(70.0).show_ui(ui, |ui| {
|
||||
for st in &styles {
|
||||
if ui.selectable_label(*st == d.style, st).clicked() {
|
||||
d.style = st.clone();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
let r3 = ui.add(egui::DragValue::new(&mut d.size).speed(0.5).range(1.0..=2000.0).suffix(" px").max_decimals(1));
|
||||
app.auto.add(&format!("{auto}.font"), r1.response.rect, "Font");
|
||||
app.auto.add(&format!("{auto}.style"), r2.response.rect, "Style");
|
||||
app.auto.add(&format!("{auto}.size"), r3.rect, "Size");
|
||||
if changed || r3.changed() {
|
||||
out = serde_json::to_value(&d).ok();
|
||||
}
|
||||
rect = r1.response.rect.union(r3.rect);
|
||||
}
|
||||
ControlType::Scale => {
|
||||
// One percentage for every axis.
|
||||
let comps = v.components();
|
||||
let mut x = comps.first().copied().unwrap_or(100.0);
|
||||
let r = ui.add(egui::DragValue::new(&mut x).speed(0.5).suffix("%").max_decimals(1));
|
||||
if r.changed() {
|
||||
out = Some(json!(vec![x; comps.len().max(1)]));
|
||||
}
|
||||
rect = r.rect;
|
||||
}
|
||||
ControlType::Slider | ControlType::Media => {
|
||||
let mut x = v.as_f64();
|
||||
let r = match p.ui {
|
||||
@@ -389,7 +445,7 @@ fn instance(app: &mut EffectcraftApp, ui: &mut egui::Ui, actions: &mut Actions)
|
||||
}
|
||||
_ => {
|
||||
let v = p.value_at(lt);
|
||||
if let Some(nv) = value_widget(app, ui, &auto, &p, &v) {
|
||||
if let Some(nv) = value_widget(app, ui, &auto, essential::effective_type(c, &p), &p, &v) {
|
||||
actions.push((
|
||||
"essential.set".into(),
|
||||
json!({"layer": layer.id.0, "control": c.id, "value": nv, "merge": format!("egi-{}-{}", layer.id.0, c.id)}),
|
||||
|
||||
@@ -118,6 +118,16 @@ fn is_layered(p: &Value) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The import includes a PDF or Illustrator file (which may have several pages).
|
||||
fn is_pdf(p: &Value) -> bool {
|
||||
let pdf = |v: &Value| v.as_str().is_some_and(|s| matches!(s.rsplit('.').next().map(str::to_ascii_lowercase).as_deref(), Some("pdf" | "ai")));
|
||||
match p.get("paths").or(p.get("path")) {
|
||||
Some(Value::Array(a)) => a.iter().any(pdf),
|
||||
Some(v) => pdf(v),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
|
||||
let s = &app.session;
|
||||
let comp = s.active_comp();
|
||||
@@ -136,6 +146,14 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
|
||||
1,
|
||||
)],
|
||||
),
|
||||
// PDF / Illustrator files: Import Kind and the page.
|
||||
"file.import" if !has(p, &["importAs", "page"]) && is_pdf(p) => (
|
||||
"Import PDF / Illustrator File".into(),
|
||||
vec![
|
||||
Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], 0),
|
||||
Field::num("page", "Page", 1.0),
|
||||
],
|
||||
),
|
||||
// Puppet tool ▸ Record Options.
|
||||
"puppet.recordOptions" if !has(p, &["speed", "smoothing", "useDraftDeformation", "showMesh"]) => {
|
||||
let o = &s.state.puppet;
|
||||
|
||||
@@ -0,0 +1,932 @@
|
||||
//! Visual editors for effect parameters stored as hidden or text parameters (Effect Controls):
|
||||
//!
|
||||
//! - Lumetri Color ▸ Curves ▸ RGB Curves: master / red / green / blue curve graphs (channel
|
||||
//! swatches like After Effects'), and ▸ Hue Saturation Curves: Hue vs Sat, Hue vs Hue, Hue vs
|
||||
//! Luma, Luma vs Sat and Sat vs Sat graphs over their colour gradients (y = ½ is neutral);
|
||||
//! - Colorama ▸ Output Cycle: the palette wheel, with draggable colour stops (click the ring to
|
||||
//! add one, Alt-click or drag one off to remove it, select one to pick its colour); editing a
|
||||
//! preset palette turns it into Custom;
|
||||
//! - Glow: the colour map (A & B Colors: a preview strip of the gradient over glow brightness;
|
||||
//! Arbitrary Map: red / green / blue curve graphs and the resulting strip);
|
||||
//! - Reshape: correspondence point list buttons here, and on the Composition viewer the source
|
||||
//! and destination mask outlines with draggable correspondence handles ([`reshape_overlay`]).
|
||||
//!
|
||||
//! Every edit is a `prop.set` engine command (undoable; one drag = one undo step) and every
|
||||
//! handle registers an automation id.
|
||||
|
||||
use effectcraft_engine::effects::{ColoramaPalette, OffsetCurve};
|
||||
use effectcraft_engine::geom::Mat3;
|
||||
use effectcraft_engine::keyframe::Value;
|
||||
use effectcraft_engine::project::{Layer, PropGroup};
|
||||
use effectcraft_engine::render::EvalCtx;
|
||||
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use super::effect_controls::gesture_key;
|
||||
use super::fx_widgets as fw;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{EffectcraftApp, widgets};
|
||||
|
||||
type Actions = Vec<(String, serde_json::Value)>;
|
||||
|
||||
pub const LUMETRI: &str = "ec.color.lumetri";
|
||||
pub const COLORAMA: &str = "ec.color.colorama";
|
||||
pub const GLOW: &str = "ec.stylize.glow";
|
||||
pub const RESHAPE: &str = "ec.distort.reshape";
|
||||
|
||||
fn str_value(layer: &Layer, ectx: &EvalCtx, g: &PropGroup, id: &str) -> String {
|
||||
match g.get(id).map(|p| ectx.value(layer, p)) {
|
||||
Some(Value::Str(s)) => s,
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_str(actions: &mut Actions, layer: &Layer, g: &PropGroup, id: &str, v: String, merge: Option<String>) {
|
||||
let Some(p) = g.get(id) else { return };
|
||||
let mut a = json!({"layer": layer.id.0, "prop": p.uid, "value": v});
|
||||
if let Some(m) = merge {
|
||||
a["merge"] = json!(m);
|
||||
}
|
||||
actions.push(("prop.set".into(), a));
|
||||
}
|
||||
|
||||
/// Register automation ids for a curve's control points (`<prefix>.point.<i>`).
|
||||
fn register_points(app: &mut EffectcraftApp, prefix: &str, gr: Rect, pts: &[[f32; 2]]) {
|
||||
for (i, q) in pts.iter().enumerate() {
|
||||
let s = pos2(gr.min.x + q[0] * gr.width(), gr.max.y - q[1] * gr.height());
|
||||
app.auto.add(&format!("{prefix}.point.{i}"), Rect::from_center_size(s, vec2(9.0, 9.0)), &format!("Point {}", i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
/// Small coloured tabs (`names[i]`, swatch `cols[i]`); returns the clicked one.
|
||||
fn tabs(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
x0: f32,
|
||||
cy: f32,
|
||||
cur: usize,
|
||||
names: &[&str],
|
||||
cols: &[Color32],
|
||||
id: &str,
|
||||
) -> Option<usize> {
|
||||
let t = app.tokens;
|
||||
let mut x = x0;
|
||||
let mut out = None;
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let w = if cols.is_empty() { 16.0 + name.chars().count() as f32 * 6.2 } else { 20.0 };
|
||||
let r = Rect::from_min_size(pos2(x, cy - 9.0), vec2(w, 18.0));
|
||||
let resp = ui.interact(r, egui::Id::new((id, i)), Sense::click());
|
||||
let sel = i == cur;
|
||||
if sel {
|
||||
p.rect_filled(r, 3.0, t.row_selected);
|
||||
} else if resp.hovered() {
|
||||
p.rect_filled(r, 3.0, t.hover);
|
||||
}
|
||||
match cols.get(i) {
|
||||
Some(c) => {
|
||||
p.circle_filled(r.center(), 5.5, *c);
|
||||
if sel {
|
||||
p.circle_stroke(r.center(), 7.0, Stroke::new(1.0, t.text));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
p.text(r.center(), Align2::CENTER_CENTER, *name, Tokens::ui(11.0), if sel { t.text } else { t.text_dim });
|
||||
}
|
||||
}
|
||||
app.auto.add(&format!("{id}.{i}"), r, name);
|
||||
if resp.clicked() {
|
||||
out = Some(i);
|
||||
}
|
||||
resp.on_hover_text(*name);
|
||||
x += w + 4.0;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn reset_link(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, r: Rect, id: &str) -> bool {
|
||||
let t = app.tokens;
|
||||
let resp = ui.interact(r, egui::Id::new(id), Sense::click());
|
||||
p.text(r.center(), Align2::CENTER_CENTER, "Reset", Tokens::ui(11.5), if resp.hovered() { t.hot_text } else { t.text_dim });
|
||||
app.auto.add(id, r, "Reset");
|
||||
resp.clicked()
|
||||
}
|
||||
|
||||
fn graph_size(width: f32) -> f32 {
|
||||
(width - 72.0).clamp(120.0, 256.0)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Inline editors (inside a parameter group)
|
||||
|
||||
/// Height of the editor shown at the top of group `path` (spec-id path with a trailing `/`)
|
||||
/// of `effect` (0 when none).
|
||||
pub fn inline_height(effect: &str, path: &str, width: f32) -> f32 {
|
||||
match (effect, path) {
|
||||
(LUMETRI, "curves/rgbCurves/") => 30.0 + graph_size(width) + 22.0,
|
||||
(LUMETRI, "curves/hueSaturationCurves/") => 30.0 + graph_size(width) * 0.6 + 34.0,
|
||||
(COLORAMA, "outputCycle/") => 30.0 + wheel_size(width) + 34.0,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the editor of group `g` (at `path`) in `r`. `root`: the effect's group.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn inline_editor(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
layer: &Layer,
|
||||
root: &PropGroup,
|
||||
g: &PropGroup,
|
||||
effect: &str,
|
||||
path: &str,
|
||||
ectx: &EvalCtx,
|
||||
r: Rect,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
match (effect, path) {
|
||||
(LUMETRI, "curves/rgbCurves/") => rgb_curves(app, ui, p, layer, root, g, ectx, r, actions),
|
||||
(LUMETRI, "curves/hueSaturationCurves/") => huesat_curves(app, ui, p, layer, root, g, ectx, r, actions),
|
||||
(COLORAMA, "outputCycle/") => colorama_wheel(app, ui, p, layer, root, g, ectx, r, actions),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
const RGB_CURVES: [(&str, &str); 4] = [("master", "Master"), ("red", "Red"), ("green", "Green"), ("blue", "Blue")];
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn rgb_curves(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
layer: &Layer,
|
||||
root: &PropGroup,
|
||||
g: &PropGroup,
|
||||
ectx: &EvalCtx,
|
||||
r: Rect,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
let t = app.tokens;
|
||||
let euid = root.uid;
|
||||
let prefix = format!("effectControls.effect.{euid}.lumetri.rgbCurves");
|
||||
let ch = app.ui.fx_curve_channel.get(&g.uid).copied().unwrap_or(0).min(3);
|
||||
let x0 = r.min.x + 38.0;
|
||||
let cy = r.min.y + 15.0;
|
||||
let cols = [Color32::from_gray(0xe8), Color32::from_rgb(0xf0, 0x50, 0x50), Color32::from_rgb(0x50, 0xd0, 0x60), Color32::from_rgb(0x50, 0x80, 0xff)];
|
||||
let names: Vec<&str> = RGB_CURVES.iter().map(|c| c.1).collect();
|
||||
if let Some(n) = tabs(app, ui, p, x0, cy, ch, &names, &cols, &format!("{prefix}.channel")) {
|
||||
app.ui.fx_curve_channel.insert(g.uid, n);
|
||||
}
|
||||
let id = RGB_CURVES[ch].0;
|
||||
let cur = fw::CurvePoints::parse(&str_value(layer, ectx, g, id));
|
||||
let size = graph_size(r.width());
|
||||
if reset_link(app, ui, p, Rect::from_min_size(pos2(x0 + size - 44.0, cy - 9.0), vec2(44.0, 18.0)), &format!("{prefix}.reset")) {
|
||||
set_str(actions, layer, g, id, fw::CurvePoints::identity().format(), None);
|
||||
}
|
||||
let gr = Rect::from_min_size(pos2(x0, r.min.y + 30.0), vec2(size, size));
|
||||
let gid = egui::Id::new(("lumetri-rgb", euid, ch));
|
||||
let (resp, edit) = fw::curves_graph(ui, gr, &cur, ch, false, gid, &t);
|
||||
app.auto.add(&format!("{prefix}.graph"), gr, "RGB Curves");
|
||||
register_points(app, &prefix, gr, &cur.0);
|
||||
let key = gesture_key(ui, gid, resp.drag_started() || resp.clicked());
|
||||
if let Some(np) = edit.changed {
|
||||
set_str(actions, layer, g, id, np.format(), Some(key));
|
||||
}
|
||||
p.text(pos2(gr.min.x, gr.max.y + 11.0), Align2::LEFT_CENTER, "Click adds a point; drag one off to remove", Tokens::ui(10.5), t.text_faint);
|
||||
}
|
||||
|
||||
/// A hue / saturation curve's points (`x,y` in 0..1, y = ½ neutral), any count (empty = flat).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct OffsetPoints(pub Vec<[f32; 2]>);
|
||||
|
||||
impl OffsetPoints {
|
||||
pub fn parse(s: &str) -> OffsetPoints {
|
||||
let mut v: Vec<[f32; 2]> = s
|
||||
.split(|c: char| c.is_whitespace() || c == ';')
|
||||
.filter_map(|tk| {
|
||||
let (x, y) = tk.split_once(',')?;
|
||||
let (x, y) = (x.trim().parse::<f32>().ok()?, y.trim().parse::<f32>().ok()?);
|
||||
(x.is_finite() && y.is_finite()).then_some([x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)])
|
||||
})
|
||||
.collect();
|
||||
v.sort_by(|a, b| a[0].total_cmp(&b[0]));
|
||||
OffsetPoints(v)
|
||||
}
|
||||
pub fn format(&self) -> String {
|
||||
let f = |v: f32| {
|
||||
let s = format!("{v:.4}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.').to_string();
|
||||
if s.is_empty() || s == "-0" { "0".into() } else { s }
|
||||
};
|
||||
self.0.iter().map(|q| format!("{},{}", f(q[0]), f(q[1]))).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
pub fn insert(&mut self, x: f32, y: f32) -> usize {
|
||||
let i = self.0.partition_point(|q| q[0] < x);
|
||||
self.0.insert(i, [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)]);
|
||||
i
|
||||
}
|
||||
/// Move point `i`, keeping the order.
|
||||
pub fn move_point(&mut self, i: usize, x: f32, y: f32) {
|
||||
let n = self.0.len();
|
||||
if i >= n {
|
||||
return;
|
||||
}
|
||||
let lo = if i == 0 { 0.0 } else { self.0[i - 1][0] + 0.002 };
|
||||
let hi = if i + 1 == n { 1.0 } else { self.0[i + 1][0] - 0.002 };
|
||||
self.0[i] = [x.clamp(lo, hi.max(lo)), y.clamp(0.0, 1.0)];
|
||||
}
|
||||
pub fn hit(&self, x: f32, y: f32, r: [f32; 2]) -> Option<usize> {
|
||||
self.0
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, q)| (i, ((q[0] - x) / r[0]).hypot((q[1] - y) / r[1])))
|
||||
.filter(|(_, d)| *d <= 1.0)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lumetri's hue / saturation curves: parameter id, tab name, x axis (0 hue, 1 luma, 2 sat),
|
||||
/// whether x wraps around.
|
||||
const HUESAT: [(&str, &str, u8, bool); 5] = [
|
||||
("hueVsSat", "Hue vs Sat", 0, true),
|
||||
("hueVsHue", "Hue vs Hue", 0, true),
|
||||
("hueVsLuma", "Hue vs Luma", 0, true),
|
||||
("lumaVsSat", "Luma vs Sat", 1, false),
|
||||
("satVsSat", "Sat vs Sat", 2, false),
|
||||
];
|
||||
|
||||
fn hue_color(h: f32) -> Color32 {
|
||||
let c = egui::ecolor::Hsva::new(h.rem_euclid(1.0), 0.85, 0.9, 1.0);
|
||||
Color32::from(c)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn huesat_curves(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
layer: &Layer,
|
||||
root: &PropGroup,
|
||||
g: &PropGroup,
|
||||
ectx: &EvalCtx,
|
||||
r: Rect,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
let t = app.tokens;
|
||||
let euid = root.uid;
|
||||
let prefix = format!("effectControls.effect.{euid}.lumetri.hueSatCurves");
|
||||
let k = app.ui.fx_curve_channel.get(&g.uid).copied().unwrap_or(0).min(4);
|
||||
let x0 = r.min.x + 38.0;
|
||||
let cy = r.min.y + 15.0;
|
||||
let names: Vec<&str> = HUESAT.iter().map(|c| c.1).collect();
|
||||
if let Some(n) = tabs(app, ui, p, x0, cy, k, &names, &[], &format!("{prefix}.curve")) {
|
||||
app.ui.fx_curve_channel.insert(g.uid, n);
|
||||
}
|
||||
let (id, name, axis, periodic) = HUESAT[k];
|
||||
let cur = OffsetPoints::parse(&str_value(layer, ectx, g, id));
|
||||
let size = graph_size(r.width());
|
||||
let gr = Rect::from_min_size(pos2(x0, r.min.y + 30.0), vec2(size, size * 0.6));
|
||||
// Background: the x axis' colours (hue spectrum, grey ramp) as a band, the neutral line.
|
||||
p.rect_filled(gr, 0.0, Color32::from_rgb(0x1c, 0x1c, 0x1c));
|
||||
let n = 48;
|
||||
for i in 0..n {
|
||||
let f = (i as f32 + 0.5) / n as f32;
|
||||
let c = match axis {
|
||||
0 => hue_color(f),
|
||||
1 => Color32::from_gray((f * 255.0) as u8),
|
||||
_ => Color32::from(egui::ecolor::Hsva::new(0.0, f, 0.85, 1.0)),
|
||||
};
|
||||
let x = gr.min.x + gr.width() * i as f32 / n as f32;
|
||||
let band = Rect::from_min_max(pos2(x, gr.max.y - 8.0), pos2(x + gr.width() / n as f32 + 0.5, gr.max.y));
|
||||
p.rect_filled(band, 0.0, c);
|
||||
p.rect_filled(Rect::from_min_max(pos2(band.min.x, gr.min.y), pos2(band.max.x, gr.max.y - 8.0)), 0.0, c.gamma_multiply(0.12));
|
||||
}
|
||||
let to_s = |x: f32, y: f32| pos2(gr.min.x + x * gr.width(), gr.max.y - y * gr.height());
|
||||
p.line_segment([to_s(0.0, 0.5), to_s(1.0, 0.5)], Stroke::new(1.0, Color32::from_white_alpha(60)));
|
||||
p.rect_stroke(gr, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
|
||||
let curve = OffsetCurve::parse(&cur.format(), periodic);
|
||||
let line: Vec<Pos2> = (0..=96)
|
||||
.map(|i| {
|
||||
let x = i as f32 / 96.0;
|
||||
to_s(x, 0.5 + curve.as_ref().map(|c| c.at(x)).unwrap_or(0.0))
|
||||
})
|
||||
.collect();
|
||||
p.add(egui::Shape::line(line, Stroke::new(1.5, Color32::from_gray(0xe8))));
|
||||
let gid = egui::Id::new(("lumetri-hs", euid, k));
|
||||
let resp = ui.interact(gr.expand(6.0), gid, Sense::click_and_drag());
|
||||
app.auto.add(&format!("{prefix}.graph"), gr, name);
|
||||
let drag_id = gid.with("drag");
|
||||
let dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id));
|
||||
for (i, q) in cur.0.iter().enumerate() {
|
||||
let s = to_s(q[0], q[1]);
|
||||
let hr = Rect::from_center_size(s, vec2(7.0, 7.0));
|
||||
p.circle_filled(s, 3.5, if dragging == Some(i) { Color32::WHITE } else { Color32::from_rgb(0x1c, 0x1c, 0x1c) });
|
||||
p.circle_stroke(s, 3.5, Stroke::new(1.2, Color32::WHITE));
|
||||
app.auto.add(&format!("{prefix}.point.{i}"), hr, &format!("Point {}", i + 1));
|
||||
}
|
||||
let to_g = |s: Pos2| [((s.x - gr.min.x) / gr.width()).clamp(0.0, 1.0), ((gr.max.y - s.y) / gr.height()).clamp(0.0, 1.0)];
|
||||
let hit_r = [7.0 / gr.width(), 7.0 / gr.height()];
|
||||
let mut changed: Option<OffsetPoints> = None;
|
||||
let alt = ui.input(|i| i.modifiers.alt);
|
||||
// One undo step per click or drag.
|
||||
let key = gesture_key(ui, gid, resp.drag_started() || resp.clicked());
|
||||
if resp.drag_started()
|
||||
&& let Some(pt) = ui.input(|i| i.pointer.press_origin())
|
||||
{
|
||||
let q = to_g(pt);
|
||||
let i = match cur.hit(q[0], q[1], hit_r) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let mut np = cur.clone();
|
||||
let i = np.insert(q[0], q[1]);
|
||||
changed = Some(np);
|
||||
i
|
||||
}
|
||||
};
|
||||
ui.data_mut(|d| d.insert_temp(drag_id, i));
|
||||
} else if resp.dragged()
|
||||
&& let (Some(i), Some(pt)) = (dragging, resp.interact_pointer_pos())
|
||||
{
|
||||
let q = to_g(pt);
|
||||
let mut np = cur.clone();
|
||||
np.move_point(i, q[0], q[1]);
|
||||
if np != cur {
|
||||
changed = Some(np);
|
||||
}
|
||||
}
|
||||
if resp.drag_stopped() {
|
||||
if let (Some(i), Some(pt)) = (dragging, resp.interact_pointer_pos())
|
||||
&& !gr.expand(14.0).contains(pt)
|
||||
&& i < cur.0.len()
|
||||
{
|
||||
let mut np = cur.clone();
|
||||
np.0.remove(i);
|
||||
changed = Some(np);
|
||||
}
|
||||
ui.data_mut(|d| d.remove::<usize>(drag_id));
|
||||
}
|
||||
if resp.clicked()
|
||||
&& let Some(pt) = resp.interact_pointer_pos()
|
||||
{
|
||||
let q = to_g(pt);
|
||||
let mut np = cur.clone();
|
||||
match cur.hit(q[0], q[1], hit_r) {
|
||||
Some(i) if alt => {
|
||||
np.0.remove(i);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
np.insert(q[0], q[1]);
|
||||
}
|
||||
}
|
||||
if np != cur {
|
||||
changed = Some(np);
|
||||
}
|
||||
}
|
||||
if let Some(np) = changed {
|
||||
set_str(actions, layer, g, id, np.format(), Some(key));
|
||||
}
|
||||
if reset_link(app, ui, p, Rect::from_min_size(pos2(gr.max.x - 44.0, gr.max.y + 4.0), vec2(44.0, 18.0)), &format!("{prefix}.reset")) {
|
||||
set_str(actions, layer, g, id, String::new(), None);
|
||||
}
|
||||
p.text(pos2(gr.min.x, gr.max.y + 13.0), Align2::LEFT_CENTER, "Click adds a point (½ height = no change)", Tokens::ui(10.5), t.text_faint);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Colorama output cycle
|
||||
|
||||
fn wheel_size(width: f32) -> f32 {
|
||||
(width - 90.0).clamp(110.0, 200.0)
|
||||
}
|
||||
|
||||
/// Colorama's palette as stops: (position, straight RGBA).
|
||||
pub fn format_palette(stops: &[(f32, [f32; 4])]) -> String {
|
||||
let f = |v: f32| {
|
||||
let s = format!("{v:.4}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.').to_string();
|
||||
if s.is_empty() || s == "-0" { "0".into() } else { s }
|
||||
};
|
||||
stops
|
||||
.iter()
|
||||
.map(|(pos, c)| {
|
||||
let rgb = format!("{},{},{}", f(c[0]), f(c[1]), f(c[2]));
|
||||
if (c[3] - 1.0).abs() > 1e-4 { format!("{}:{rgb},{}", f(*pos), f(c[3])) } else { format!("{}:{rgb}", f(*pos)) }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn rgba8(c: [f32; 4]) -> Color32 {
|
||||
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
Color32::from_rgb(b(c[0]), b(c[1]), b(c[2]))
|
||||
}
|
||||
|
||||
/// Phase (0..1, clockwise from the top) of a point around `c`.
|
||||
fn phase_at(c: Pos2, q: Pos2) -> f32 {
|
||||
let a = (q.x - c.x).atan2(-(q.y - c.y));
|
||||
(a / std::f32::consts::TAU).rem_euclid(1.0)
|
||||
}
|
||||
|
||||
fn wheel_point(c: Pos2, radius: f32, phase: f32) -> Pos2 {
|
||||
let a = phase * std::f32::consts::TAU;
|
||||
pos2(c.x + radius * a.sin(), c.y - radius * a.cos())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn colorama_wheel(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
layer: &Layer,
|
||||
root: &PropGroup,
|
||||
g: &PropGroup,
|
||||
ectx: &EvalCtx,
|
||||
r: Rect,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
let t = app.tokens;
|
||||
let euid = root.uid;
|
||||
let prefix = format!("effectControls.effect.{euid}.colorama");
|
||||
let preset = g.get("usePresetPalette").map(|pr| ectx.value(layer, pr).as_enum()).unwrap_or(0);
|
||||
let custom = preset as usize == effectcraft_engine::effects::COLORAMA_PRESETS.len() - 1;
|
||||
let interp = g.get("interpolatePalette").is_none_or(|pr| ectx.value(layer, pr).as_bool());
|
||||
let pal = if custom { ColoramaPalette::parse(&str_value(layer, ectx, g, "palette")) } else { None }.unwrap_or_else(|| ColoramaPalette::preset(preset));
|
||||
let x0 = r.min.x + 38.0;
|
||||
let label = if custom { "Custom palette" } else { effectcraft_engine::effects::COLORAMA_PRESETS.get(preset as usize).copied().unwrap_or("Preset") };
|
||||
p.text(pos2(x0, r.min.y + 15.0), Align2::LEFT_CENTER, format!("Output Cycle: {label}"), Tokens::ui(11.5), t.text_dim);
|
||||
let size = wheel_size(r.width());
|
||||
let c = pos2(x0 + size / 2.0, r.min.y + 30.0 + size / 2.0);
|
||||
let (outer, inner) = (size / 2.0 - 8.0, size / 2.0 - 26.0);
|
||||
// The ring: palette colours around the wheel.
|
||||
let n = 96;
|
||||
for i in 0..n {
|
||||
let (a0, a1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
|
||||
let col = rgba8(pal.eval((a0 + a1) * 0.5, interp));
|
||||
let quad = vec![wheel_point(c, inner, a0), wheel_point(c, outer, a0), wheel_point(c, outer, a1 + 0.002), wheel_point(c, inner, a1 + 0.002)];
|
||||
p.add(egui::Shape::convex_polygon(quad, col, Stroke::NONE));
|
||||
}
|
||||
p.circle_stroke(c, outer, Stroke::new(1.0, Color32::from_black_alpha(160)));
|
||||
p.circle_stroke(c, inner, Stroke::new(1.0, Color32::from_black_alpha(160)));
|
||||
let wid = egui::Id::new(("colorama-wheel", euid));
|
||||
let ring = Rect::from_center_size(c, vec2(outer * 2.0 + 40.0, outer * 2.0 + 40.0));
|
||||
let resp = ui.interact(ring, wid, Sense::click_and_drag());
|
||||
app.auto.add(&format!("{prefix}.wheel"), ring, "Output Cycle");
|
||||
let sel_id = wid.with("sel");
|
||||
let drag_id = wid.with("drag");
|
||||
let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0);
|
||||
if sel >= pal.stops.len() {
|
||||
sel = 0;
|
||||
}
|
||||
let dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id));
|
||||
// Stops: triangles on the outside of the ring.
|
||||
let mut stop_rects = vec![];
|
||||
for (i, (ph, col)) in pal.stops.iter().enumerate() {
|
||||
let tip = wheel_point(c, outer + 2.0, *ph);
|
||||
let a = wheel_point(c, outer + 12.0, *ph - 0.018);
|
||||
let b = wheel_point(c, outer + 12.0, *ph + 0.018);
|
||||
let fill = rgba8(*col);
|
||||
p.add(egui::Shape::convex_polygon(
|
||||
vec![tip, a, b],
|
||||
fill,
|
||||
Stroke::new(if i == sel || dragging == Some(i) { 1.6 } else { 1.0 }, if i == sel { Color32::WHITE } else { Color32::from_gray(0x80) }),
|
||||
));
|
||||
let hr = Rect::from_center_size(wheel_point(c, outer + 8.0, *ph), vec2(14.0, 14.0));
|
||||
app.auto.add(&format!("{prefix}.stop.{i}"), hr, &format!("Stop {}", i + 1));
|
||||
stop_rects.push(hr);
|
||||
}
|
||||
let hit = |q: Pos2| -> Option<usize> {
|
||||
stop_rects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, hr)| hr.expand(3.0).contains(q))
|
||||
.min_by(|a, b| a.1.center().distance(q).total_cmp(&b.1.center().distance(q)))
|
||||
.map(|(i, _)| i)
|
||||
};
|
||||
let mut new_stops: Option<Vec<(f32, [f32; 4])>> = None;
|
||||
let alt = ui.input(|i| i.modifiers.alt);
|
||||
// One undo step per click or drag (a colour pick is its own step).
|
||||
let key = gesture_key(ui, wid, resp.drag_started() || resp.clicked() || !resp.dragged());
|
||||
if resp.drag_started()
|
||||
&& let Some(q) = ui.input(|i| i.pointer.press_origin())
|
||||
&& let Some(i) = hit(q)
|
||||
{
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(drag_id, i);
|
||||
d.insert_temp(sel_id, i);
|
||||
});
|
||||
} else if resp.dragged()
|
||||
&& let (Some(i), Some(q)) = (dragging, resp.interact_pointer_pos())
|
||||
&& i < pal.stops.len()
|
||||
{
|
||||
let mut st = pal.stops.clone();
|
||||
st[i].0 = phase_at(c, q);
|
||||
new_stops = Some(st);
|
||||
}
|
||||
if resp.drag_stopped() {
|
||||
if let (Some(i), Some(q)) = (dragging, resp.interact_pointer_pos())
|
||||
&& q.distance(c) > outer + 40.0
|
||||
&& pal.stops.len() > 1
|
||||
&& i < pal.stops.len()
|
||||
{
|
||||
let mut st = pal.stops.clone();
|
||||
st.remove(i);
|
||||
new_stops = Some(st);
|
||||
}
|
||||
ui.data_mut(|d| d.remove::<usize>(drag_id));
|
||||
}
|
||||
if resp.clicked()
|
||||
&& let Some(q) = resp.interact_pointer_pos()
|
||||
{
|
||||
match hit(q) {
|
||||
Some(i) if alt && pal.stops.len() > 1 => {
|
||||
let mut st = pal.stops.clone();
|
||||
st.remove(i);
|
||||
new_stops = Some(st);
|
||||
}
|
||||
Some(i) => {
|
||||
ui.data_mut(|d| d.insert_temp(sel_id, i));
|
||||
}
|
||||
// A click on the ring adds a stop with the colour there (and selects it).
|
||||
None if (inner - 4.0..=outer + 4.0).contains(&q.distance(c)) => {
|
||||
let ph = phase_at(c, q);
|
||||
let mut st = pal.stops.clone();
|
||||
st.push((ph, pal.eval(ph, interp)));
|
||||
st.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let k = st.iter().position(|s| s.0 == ph).unwrap_or(0);
|
||||
ui.data_mut(|d| d.insert_temp(sel_id, k));
|
||||
new_stops = Some(st);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
// The selected stop's colour.
|
||||
let sr = Rect::from_min_size(pos2(x0, c.y + size / 2.0 + 8.0), vec2(30.0, 16.0));
|
||||
if let Some((ph, col)) = pal.stops.get(sel).copied() {
|
||||
let pop = wid.with("color");
|
||||
if widgets::swatch(ui, sr, col, wid.with("swatch"), &t).clicked() {
|
||||
widgets::open_popup(ui, pop);
|
||||
}
|
||||
app.auto.add(&format!("{prefix}.color"), sr, "Stop color");
|
||||
p.text(pos2(sr.max.x + 8.0, sr.center().y), Align2::LEFT_CENTER, format!("Stop {} at {:.0}°", sel + 1, ph * 360.0), Tokens::ui(11.0), t.text_dim);
|
||||
let mut rgb = [col[0], col[1], col[2]];
|
||||
if crate::header::color_popup(ui, pop, sr.left_bottom(), &mut rgb) {
|
||||
let mut st = pal.stops.clone();
|
||||
st[sel].1 = [rgb[0], rgb[1], rgb[2], col[3]];
|
||||
new_stops = Some(st);
|
||||
}
|
||||
}
|
||||
p.text(
|
||||
pos2(sr.min.x, sr.max.y + 9.0),
|
||||
Align2::LEFT_CENTER,
|
||||
"Click the ring to add a colour; Alt-click a stop (or drag it off) to remove it",
|
||||
Tokens::ui(10.5),
|
||||
t.text_faint,
|
||||
);
|
||||
if let Some(mut st) = new_stops {
|
||||
st.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
// Editing a preset makes it the custom palette (both in one undo step).
|
||||
if !custom && let Some(pr) = g.get("usePresetPalette") {
|
||||
actions.push((
|
||||
"prop.set".into(),
|
||||
json!({"layer": layer.id.0, "prop": pr.uid, "value": effectcraft_engine::effects::COLORAMA_PRESETS.len() - 1, "merge": key}),
|
||||
));
|
||||
}
|
||||
set_str(actions, layer, g, "palette", format_palette(&st), Some(key));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Header editors (under the effect's title)
|
||||
|
||||
/// Height of the editor under `effect`'s header (`g`: the instance), 0 when none.
|
||||
pub fn header_height(effect: &str, g: &PropGroup, width: f32) -> f32 {
|
||||
match effect {
|
||||
GLOW => match g.get("colors").map(|p| p.value.as_enum()) {
|
||||
Some(2) => 30.0 + graph_size(width) + 40.0,
|
||||
Some(1) => 34.0,
|
||||
_ => 0.0,
|
||||
},
|
||||
RESHAPE => 50.0,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn header_editor(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
layer: &Layer,
|
||||
g: &PropGroup,
|
||||
effect: &str,
|
||||
ectx: &EvalCtx,
|
||||
r: Rect,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
match effect {
|
||||
GLOW => glow_map(app, ui, p, layer, g, ectx, r, actions),
|
||||
RESHAPE => reshape_buttons(app, ui, p, layer, g, ectx, r, actions),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Glow's Arbitrary Map: "red | green | blue" Curves point lists.
|
||||
pub fn split_map(s: &str) -> [fw::CurvePoints; 3] {
|
||||
let mut parts = s.split('|');
|
||||
std::array::from_fn(|_| parts.next().map(fw::CurvePoints::parse).unwrap_or_else(fw::CurvePoints::identity))
|
||||
}
|
||||
|
||||
pub fn join_map(m: &[fw::CurvePoints; 3]) -> String {
|
||||
m.iter().map(|c| c.format()).collect::<Vec<_>>().join(" | ")
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn glow_map(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, layer: &Layer, g: &PropGroup, ectx: &EvalCtx, r: Rect, actions: &mut Actions) {
|
||||
let t = app.tokens;
|
||||
let euid = g.uid;
|
||||
let prefix = format!("effectControls.effect.{euid}.glow");
|
||||
let mode = g.get("colors").map(|pr| ectx.value(layer, pr).as_enum()).unwrap_or(0);
|
||||
let x0 = r.min.x + 38.0;
|
||||
let num = |id: &str| g.get(id).map(|pr| ectx.value(layer, pr).as_f64()).unwrap_or(0.0);
|
||||
let looping = g.get("colorLooping").map(|pr| ectx.value(layer, pr).as_enum()).unwrap_or(2);
|
||||
let (loops, phase, mid) = (num("colorLoops") as f32, (num("colorPhase") / 360.0) as f32, (num("abMidpoint") / 100.0) as f32);
|
||||
let map = split_map(&str_value(layer, ectx, g, "arbitraryMap"));
|
||||
let color_at = |l: f32| -> Color32 {
|
||||
let tt = effectcraft_engine::effects::glow_ab_t(l, looping, loops, phase, mid);
|
||||
if mode == 2 {
|
||||
Color32::from_rgb(
|
||||
(map[0].eval(tt).clamp(0.0, 1.0) * 255.0) as u8,
|
||||
(map[1].eval(tt).clamp(0.0, 1.0) * 255.0) as u8,
|
||||
(map[2].eval(tt).clamp(0.0, 1.0) * 255.0) as u8,
|
||||
)
|
||||
} else {
|
||||
let col = |id: &str| match g.get(id).map(|pr| ectx.value(layer, pr)) {
|
||||
Some(Value::Color(c)) => c,
|
||||
_ => [0.0; 4],
|
||||
};
|
||||
let (a, b) = (col("colorA"), col("colorB"));
|
||||
let m = |i: usize| ((a[i] + (b[i] - a[i]) * tt as f64).clamp(0.0, 1.0) * 255.0) as u8;
|
||||
Color32::from_rgb(m(0), m(1), m(2))
|
||||
}
|
||||
};
|
||||
let size = graph_size(r.width());
|
||||
let strip_y = if mode == 2 { r.min.y + 30.0 + size + 12.0 } else { r.min.y + 8.0 };
|
||||
let strip = Rect::from_min_size(pos2(x0, strip_y), vec2(size, 12.0));
|
||||
let n = 64;
|
||||
for i in 0..n {
|
||||
let f = (i as f32 + 0.5) / n as f32;
|
||||
let x = strip.min.x + strip.width() * i as f32 / n as f32;
|
||||
p.rect_filled(Rect::from_min_max(pos2(x, strip.min.y), pos2(x + strip.width() / n as f32 + 0.5, strip.max.y)), 0.0, color_at(f));
|
||||
}
|
||||
p.rect_stroke(strip, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
|
||||
app.auto.add(&format!("{prefix}.colorMap"), strip, "Glow colour map");
|
||||
p.text(pos2(strip.max.x + 8.0, strip.center().y), Align2::LEFT_CENTER, "Colour map", Tokens::ui(10.5), t.text_faint);
|
||||
if mode != 2 {
|
||||
return;
|
||||
}
|
||||
let ch = app.ui.fx_curve_channel.get(&euid).copied().unwrap_or(0).min(2);
|
||||
let cols = [Color32::from_rgb(0xf0, 0x50, 0x50), Color32::from_rgb(0x50, 0xd0, 0x60), Color32::from_rgb(0x50, 0x80, 0xff)];
|
||||
if let Some(n) = tabs(app, ui, p, x0, r.min.y + 15.0, ch, &["Red", "Green", "Blue"], &cols, &format!("{prefix}.channel")) {
|
||||
app.ui.fx_curve_channel.insert(euid, n);
|
||||
}
|
||||
if reset_link(app, ui, p, Rect::from_min_size(pos2(x0 + size - 44.0, r.min.y + 6.0), vec2(44.0, 18.0)), &format!("{prefix}.reset")) {
|
||||
let mut m = map.clone();
|
||||
m[ch] = fw::CurvePoints::identity();
|
||||
set_str(actions, layer, g, "arbitraryMap", join_map(&m), None);
|
||||
}
|
||||
let gr = Rect::from_min_size(pos2(x0, r.min.y + 30.0), vec2(size, size));
|
||||
let gid = egui::Id::new(("glow-map", euid, ch));
|
||||
let (resp, edit) = fw::curves_graph(ui, gr, &map[ch], ch + 1, false, gid, &t);
|
||||
app.auto.add(&format!("{prefix}.graph"), gr, "Arbitrary Map");
|
||||
register_points(app, &prefix, gr, &map[ch].0);
|
||||
let key = gesture_key(ui, gid, resp.drag_started() || resp.clicked());
|
||||
if let Some(np) = edit.changed {
|
||||
let mut m = map.clone();
|
||||
m[ch] = np;
|
||||
set_str(actions, layer, g, "arbitraryMap", join_map(&m), Some(key));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Reshape
|
||||
|
||||
/// Reshape's correspondence pairs (source, destination outline fractions), in stored order.
|
||||
pub fn parse_pairs(s: &str) -> Vec<(f64, f64)> {
|
||||
s.split_whitespace()
|
||||
.filter_map(|tk| {
|
||||
let (a, b) = tk.split_once(',')?;
|
||||
Some((a.trim().parse::<f64>().ok()?.rem_euclid(1.0), b.trim().parse::<f64>().ok()?.rem_euclid(1.0)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn format_pairs(v: &[(f64, f64)]) -> String {
|
||||
let f = |x: f64| {
|
||||
let s = format!("{x:.4}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.').to_string();
|
||||
if s.is_empty() { "0".into() } else { s }
|
||||
};
|
||||
v.iter().map(|(a, b)| format!("{},{}", f(*a), f(*b))).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// A new pair in the widest gap between the destination fractions (the source fraction
|
||||
/// interpolated between its neighbours'), or (0, 0) for the first.
|
||||
pub fn add_pair(v: &[(f64, f64)]) -> (f64, f64) {
|
||||
if v.is_empty() {
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
let mut s: Vec<(f64, f64)> = v.to_vec();
|
||||
s.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
let n = s.len();
|
||||
let (mut best, mut gap) = (0, -1.0);
|
||||
for i in 0..n {
|
||||
let g = (s[(i + 1) % n].1 - s[i].1).rem_euclid(1.0);
|
||||
let g = if n == 1 { 1.0 } else { g };
|
||||
if g > gap {
|
||||
gap = g;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
let (a, b) = (s[best], s[(best + 1) % n]);
|
||||
let ds = if n == 1 { 1.0 } else { (b.0 - a.0).rem_euclid(1.0) };
|
||||
((a.0 + ds * 0.5).rem_euclid(1.0), (a.1 + gap * 0.5).rem_euclid(1.0))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn reshape_buttons(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
layer: &Layer,
|
||||
g: &PropGroup,
|
||||
ectx: &EvalCtx,
|
||||
r: Rect,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
let t = app.tokens;
|
||||
let euid = g.uid;
|
||||
let pairs = parse_pairs(&str_value(layer, ectx, g, "correspondencePoints"));
|
||||
let b1 = Rect::from_min_size(pos2(r.min.x + 24.0, r.min.y + 4.0), vec2(84.0, 22.0));
|
||||
let b2 = Rect::from_min_size(pos2(b1.max.x + 8.0, b1.min.y), vec2(96.0, 22.0));
|
||||
let b3 = Rect::from_min_size(pos2(b2.max.x + 8.0, b1.min.y), vec2(56.0, 22.0));
|
||||
if widgets::text_button(ui, b1, "Add Point", false, &t, egui::Id::new(("reshape-add", euid))).clicked() {
|
||||
let mut v = pairs.clone();
|
||||
v.push(add_pair(&pairs));
|
||||
set_str(actions, layer, g, "correspondencePoints", format_pairs(&v), None);
|
||||
}
|
||||
app.auto.add(&format!("effectControls.effect.{euid}.reshape.add"), b1, "Add Point");
|
||||
if widgets::text_button(ui, b2, "Remove Point", false, &t, egui::Id::new(("reshape-remove", euid))).clicked() && !pairs.is_empty() {
|
||||
let mut v = pairs.clone();
|
||||
v.pop();
|
||||
set_str(actions, layer, g, "correspondencePoints", format_pairs(&v), None);
|
||||
}
|
||||
app.auto.add(&format!("effectControls.effect.{euid}.reshape.remove"), b2, "Remove Point");
|
||||
if widgets::text_button(ui, b3, "Clear", false, &t, egui::Id::new(("reshape-clear", euid))).clicked() && !pairs.is_empty() {
|
||||
set_str(actions, layer, g, "correspondencePoints", String::new(), None);
|
||||
}
|
||||
app.auto.add(&format!("effectControls.effect.{euid}.reshape.clear"), b3, "Clear");
|
||||
let status = if pairs.is_empty() {
|
||||
"Correspondence: automatic (select the effect to edit points on the viewer)".to_string()
|
||||
} else {
|
||||
format!("{} correspondence point(s): drag them along the mask outlines in the viewer", pairs.len())
|
||||
};
|
||||
p.text(pos2(r.min.x + 24.0, r.min.y + 38.0), Align2::LEFT_CENTER, status, Tokens::ui(11.5), t.text_dim);
|
||||
}
|
||||
|
||||
/// Arc-length fraction (0..1) of the point of a polyline nearest to `q`.
|
||||
pub fn nearest_fraction(pts: &[[f64; 2]], closed: bool, q: [f64; 2]) -> f64 {
|
||||
let n = pts.len();
|
||||
if n < 2 {
|
||||
return 0.0;
|
||||
}
|
||||
let total = effectcraft_engine::effects::util::poly_length(pts, closed).max(1e-9);
|
||||
let segs = if closed { n } else { n - 1 };
|
||||
let (mut best, mut best_s, mut acc) = (f64::INFINITY, 0.0, 0.0);
|
||||
for i in 0..segs {
|
||||
let (a, b) = (pts[i], pts[(i + 1) % n]);
|
||||
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
let l = l2.sqrt();
|
||||
let tt = if l2 > 0.0 { (((q[0] - a[0]) * dx + (q[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let d = (a[0] + dx * tt - q[0]).hypot(a[1] + dy * tt - q[1]);
|
||||
if d < best {
|
||||
best = d;
|
||||
best_s = acc + l * tt;
|
||||
}
|
||||
acc += l;
|
||||
}
|
||||
(best_s / total).rem_euclid(1.0)
|
||||
}
|
||||
|
||||
/// The Composition viewer's Reshape controls while the effect is selected: the source (yellow)
|
||||
/// and destination (cyan) mask outlines and each correspondence pair as a line between its two
|
||||
/// handles; dragging a handle slides it along its outline (one undo step per drag).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn reshape_overlay(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
painter: &egui::Painter,
|
||||
map: &super::viewer::ViewerMap,
|
||||
ectx: &EvalCtx,
|
||||
layer: &Layer,
|
||||
g: &PropGroup,
|
||||
m: &Mat3,
|
||||
actions: &mut Actions,
|
||||
) {
|
||||
let shapes = effectcraft_engine::render::masks::shapes(ectx, layer);
|
||||
let mask = |id: &str| -> Option<(Vec<[f64; 2]>, bool)> {
|
||||
let i = g.get(id).map(|pr| ectx.value(layer, pr).as_enum()).unwrap_or(0) as usize;
|
||||
let s = shapes.get(i.checked_sub(1)?)?;
|
||||
(s.points.len() >= 2).then(|| (s.points.clone(), s.closed))
|
||||
};
|
||||
let (Some(src), Some(dst)) = (mask("sourceMask"), mask("destinationMask")) else { return };
|
||||
let to_screen = |q: [f64; 2]| map.to_screen(fw::layer_to_comp(m, q));
|
||||
let outline = |pts: &[[f64; 2]], closed: bool, col: Color32| {
|
||||
let mut v: Vec<Pos2> = pts.iter().map(|q| to_screen(*q)).collect();
|
||||
if closed && let Some(f) = v.first().copied() {
|
||||
v.push(f);
|
||||
}
|
||||
painter.add(egui::Shape::dashed_line(&v, Stroke::new(1.0, col), 5.0, 3.0));
|
||||
};
|
||||
let (ys, cs) = (Color32::from_rgb(0xff, 0xd8, 0x40), Color32::from_rgb(0x40, 0xd8, 0xff));
|
||||
outline(&src.0, src.1, ys);
|
||||
outline(&dst.0, dst.1, cs);
|
||||
let at = |pts: &[[f64; 2]], closed: bool, f: f64| {
|
||||
let len = effectcraft_engine::effects::util::poly_length(pts, closed);
|
||||
effectcraft_engine::effects::util::poly_point_at(pts, closed, f * len).0
|
||||
};
|
||||
let raw = match g.get("correspondencePoints").map(|pr| ectx.value(layer, pr)) {
|
||||
Some(Value::Str(s)) => s,
|
||||
_ => String::new(),
|
||||
};
|
||||
let pairs = parse_pairs(&raw);
|
||||
let ctx = ui.ctx().clone();
|
||||
for (i, (fs, fd)) in pairs.iter().enumerate() {
|
||||
let (ps, pd) = (to_screen(at(&src.0, src.1, *fs)), to_screen(at(&dst.0, dst.1, *fd)));
|
||||
painter.line_segment([ps, pd], Stroke::new(1.0, Color32::from_white_alpha(150)));
|
||||
for (end, s, col) in [(0usize, ps, ys), (1, pd, cs)] {
|
||||
let hr = Rect::from_center_size(s, vec2(12.0, 12.0));
|
||||
let id = egui::Id::new(("reshape-pt", g.uid, i, end));
|
||||
let resp = ui.interact(hr, id, Sense::drag());
|
||||
let hot = resp.hovered() || resp.dragged();
|
||||
painter.rect_filled(Rect::from_center_size(s, vec2(7.0, 7.0)), 0.0, if hot { Color32::WHITE } else { col });
|
||||
painter.rect_stroke(Rect::from_center_size(s, vec2(7.0, 7.0)), 0.0, Stroke::new(1.0, Color32::BLACK), StrokeKind::Outside);
|
||||
let which = if end == 0 { "source" } else { "dest" };
|
||||
app.auto.add(&format!("viewer.reshape.{}.{which}.{i}", g.uid), hr, &format!("Correspondence point {} ({which})", i + 1));
|
||||
if hot {
|
||||
ctx.set_cursor_icon(egui::CursorIcon::Move);
|
||||
}
|
||||
if resp.dragged()
|
||||
&& let Some(pos) = resp.interact_pointer_pos()
|
||||
&& let Some(lp) = fw::comp_to_layer(m, map.to_comp(pos))
|
||||
{
|
||||
let mut v = pairs.clone();
|
||||
if end == 0 {
|
||||
v[i].0 = nearest_fraction(&src.0, src.1, lp);
|
||||
} else {
|
||||
v[i].1 = nearest_fraction(&dst.0, dst.1, lp);
|
||||
}
|
||||
let key = gesture_key(ui, id, resp.drag_started());
|
||||
if let Some(pr) = g.get("correspondencePoints") {
|
||||
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": pr.uid, "value": format_pairs(&v), "merge": key})));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn offset_points_and_palettes_round_trip() {
|
||||
let p = OffsetPoints::parse("0.5,0.75 0.1,0.5");
|
||||
assert_eq!(p.0, vec![[0.1, 0.5], [0.5, 0.75]]);
|
||||
assert_eq!(OffsetPoints::parse(&p.format()), p);
|
||||
assert!(OffsetPoints::parse("").0.is_empty());
|
||||
let stops = vec![(0.0, [1.0, 0.0, 0.0, 1.0]), (0.5, [0.0, 0.25, 1.0, 0.5])];
|
||||
let s = format_palette(&stops);
|
||||
assert_eq!(s, "0:1,0,0 0.5:0,0.25,1,0.5");
|
||||
assert_eq!(ColoramaPalette::parse(&s).unwrap().stops, stops);
|
||||
let m = split_map("0,0 1,0.5 | | 0,1 1,0");
|
||||
assert_eq!(m[1], fw::CurvePoints::identity());
|
||||
assert_eq!(split_map(&join_map(&m)), m);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reshape_pairs_and_outline_fractions() {
|
||||
assert_eq!(parse_pairs("0.25,0 1.5,0.5"), vec![(0.25, 0.0), (0.5, 0.5)]);
|
||||
assert_eq!(format_pairs(&[(0.25, 0.0), (0.5, 0.125)]), "0.25,0 0.5,0.125");
|
||||
assert_eq!(add_pair(&[]), (0.0, 0.0));
|
||||
assert_eq!(add_pair(&[(0.1, 0.0)]), (0.6, 0.5));
|
||||
let (s, d) = add_pair(&[(0.0, 0.0), (0.2, 0.25)]);
|
||||
assert!((d - 0.625).abs() < 1e-9 && (s - 0.6).abs() < 1e-9, "{s} {d}");
|
||||
// A 10×10 square (closed): the point nearest (10, 5) is 3/8 of the way round.
|
||||
let sq = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]];
|
||||
assert!((nearest_fraction(&sq, true, [12.0, 5.0]) - 0.375).abs() < 1e-9);
|
||||
assert!(nearest_fraction(&sq, true, [-1.0, -1.0]).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -65,13 +65,13 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let p = ui.painter().with_clip_rect(rect);
|
||||
p.rect_filled(rect, 0.0, t.panel_bg);
|
||||
if !mb::available() {
|
||||
p.text(rect.center(), Align2::CENTER_CENTER, "The Media Browser needs the desktop app (use File ▸ Import here)", Tokens::ui(12.0), t.text_faint);
|
||||
let Some(b) = app.session.media_browser() else {
|
||||
p.text(rect.center(), Align2::CENTER_CENTER, "The Media Browser is not available here (use File ▸ Import)", Tokens::ui(12.0), t.text_faint);
|
||||
app.auto.add("mediaBrowser.unavailable", rect, "Media Browser unavailable");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let st = app.session.state.media_browser.clone();
|
||||
let dir = st.folder.clone().unwrap_or_else(mb::home);
|
||||
let dir = st.folder.clone().unwrap_or_else(|| b.home());
|
||||
// Listing cached per folder for a second.
|
||||
let lid = egui::Id::new(("mb-list", dir.clone(), st.importable_only));
|
||||
let now = ctx.input(|i| i.time);
|
||||
@@ -79,7 +79,7 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let entries = match listing {
|
||||
Some((at, l)) if now - at < 1.0 => l,
|
||||
_ => {
|
||||
let l = mb::list(&dir, st.importable_only);
|
||||
let l = b.list(&dir, st.importable_only);
|
||||
ctx.data_mut(|d| d.insert_temp(lid, (now, l.clone())));
|
||||
l
|
||||
}
|
||||
@@ -104,6 +104,20 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if only != st.importable_only {
|
||||
kit::exec(app, "mediaBrowser.go", json!({"path": dir, "importableOnly": only}));
|
||||
}
|
||||
// The browser's own actions (web: Open Folder…, Add Files…), right-aligned.
|
||||
let mut ax = rect.max.x - 8.0;
|
||||
for (id, label) in b.actions().iter().rev() {
|
||||
let w = 14.0 + label.chars().count() as f32 * 6.4;
|
||||
ax -= w;
|
||||
if ax < x + 96.0 {
|
||||
break;
|
||||
}
|
||||
if kit::button(app, ui, Rect::from_min_size(pos2(ax, y), vec2(w, 20.0)), &format!("mediaBrowser.action.{id}"), label, false) {
|
||||
kit::exec(app, "mediaBrowser.action", json!({"action": id}));
|
||||
ctx.data_mut(|d| d.remove::<(f64, Result<Vec<mb::Entry>, String>)>(lid));
|
||||
}
|
||||
ax -= 6.0;
|
||||
}
|
||||
// The path on its own row.
|
||||
let _ = x;
|
||||
let py = y + 24.0;
|
||||
@@ -114,7 +128,7 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
p.line_segment([side.right_top(), side.right_bottom()], Stroke::new(1.0, t.separator));
|
||||
p.text(pos2(side.min.x + 10.0, side.min.y + 10.0), Align2::LEFT_CENTER, "Favorites", Tokens::semibold(11.5), t.text_dim);
|
||||
let mut fy = side.min.y + 22.0;
|
||||
let mut places: Vec<(String, String)> = vec![("Home".into(), mb::home())];
|
||||
let mut places: Vec<(String, String)> = b.places();
|
||||
places.extend(
|
||||
st.favorites.iter().map(|f| (std::path::Path::new(f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone()), f.clone())),
|
||||
);
|
||||
|
||||
@@ -13,12 +13,24 @@ pub fn placeholder(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, p: P
|
||||
ui.painter().text(rect.center(), Align2::CENTER_CENTER, format!("{} — coming soon", p.title()), Tokens::ui(12.0), t.text_faint);
|
||||
}
|
||||
|
||||
/// Preview panel: transport controls and RAM preview options.
|
||||
/// Preview panel: transport controls, the shortcut whose options are shown, and that
|
||||
/// shortcut's options (each Preview shortcut keeps its own; see `effectcraft_engine::preview`).
|
||||
/// Every change runs `playback.settings.set`.
|
||||
pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
use effectcraft_engine::preview::{PlayFrom, PreviewRange, PreviewResolution, PreviewShortcut};
|
||||
let t = app.tokens;
|
||||
let ctx = ui.ctx().clone();
|
||||
let p = ui.painter().with_clip_rect(rect);
|
||||
let y = rect.min.y + 12.0;
|
||||
// The panel scrolls when it is shorter than its controls (the default workspace shows just
|
||||
// the transport row, as in After Effects).
|
||||
let scroll_id = egui::Id::new("preview-scroll");
|
||||
let mut scroll: f32 = ctx.data(|d| d.get_temp(scroll_id).unwrap_or(0.0));
|
||||
if ui.rect_contains_pointer(rect) {
|
||||
scroll = (scroll - ui.input(|i| i.smooth_scroll_delta.y)).max(0.0);
|
||||
}
|
||||
let panel_clip = ui.clip_rect();
|
||||
ui.set_clip_rect(rect.intersect(panel_clip));
|
||||
let y = rect.min.y + 12.0 - scroll;
|
||||
let bw = 30.0;
|
||||
let total = bw * 5.0 + 16.0;
|
||||
let mut x = rect.center().x - total / 2.0;
|
||||
@@ -29,55 +41,258 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
(Icon::StepFwd, "time.nextFrame", "Next Frame"),
|
||||
(Icon::Last, "time.end", "Last Frame"),
|
||||
];
|
||||
let current = app.session.prefs.preview.current;
|
||||
for (icon, cmd, tip) in buttons {
|
||||
let r = Rect::from_min_size(pos2(x, y), vec2(bw, 28.0));
|
||||
let icon = if cmd == "playback.toggle" && app.playback.playing { Icon::Pause } else { icon };
|
||||
if widgets::icon_button(ui, r, icon, cmd == "playback.toggle" && app.playback.playing, &t, egui::Id::new(("pv", cmd))).on_hover_text(tip).clicked() {
|
||||
let _ = crate::menus::invoke(app, &ctx, cmd, json!({}));
|
||||
// The play button plays with the options of the shortcut shown below.
|
||||
let params = if cmd == "playback.toggle" { json!({"shortcut": current.id()}) } else { json!({}) };
|
||||
let _ = crate::menus::invoke(app, &ctx, cmd, params);
|
||||
}
|
||||
app.auto.add(&format!("preview.{}", tip.replace([' ', '/'], "")), r, tip);
|
||||
x += bw + 4.0;
|
||||
}
|
||||
let mut yy = y + 44.0;
|
||||
let row = |p: &egui::Painter, yy: f32, k: &str, v: &str| {
|
||||
p.text(pos2(rect.min.x + 12.0, yy), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim);
|
||||
p.text(pos2(rect.min.x + 130.0, yy), Align2::LEFT_CENTER, v, Tokens::ui(12.0), t.text);
|
||||
let o = app.session.prefs.preview.get(current).clone();
|
||||
let mut changes: Vec<serde_json::Value> = vec![];
|
||||
let x0 = rect.min.x + 12.0;
|
||||
let xv = rect.min.x + 92.0;
|
||||
let wv = (rect.max.x - xv - 12.0).clamp(80.0, 240.0);
|
||||
let label = |yy: f32, k: &str| {
|
||||
p.text(pos2(x0, yy), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim);
|
||||
};
|
||||
row(&p, yy, "Shortcut", "Spacebar");
|
||||
yy += 22.0;
|
||||
let lr = Rect::from_min_size(pos2(rect.min.x + 10.0, yy - 8.0), vec2(16.0, 16.0));
|
||||
if widgets::checkbox(ui, lr, app.ui.preview_loop, &t, egui::Id::new("pv-loop")).clicked() {
|
||||
app.ui.preview_loop = !app.ui.preview_loop;
|
||||
let mut yy = y + 46.0;
|
||||
|
||||
// Shortcut.
|
||||
label(yy, "Shortcut");
|
||||
let names: Vec<String> = PreviewShortcut::ALL.iter().map(|s| s.label().to_string()).collect();
|
||||
if let Some(i) = dropdown_row(
|
||||
app,
|
||||
ui,
|
||||
Rect::from_min_size(pos2(xv, yy - 10.0), vec2(wv, 20.0)),
|
||||
"shortcut",
|
||||
current.label(),
|
||||
&names,
|
||||
PreviewShortcut::ALL.iter().position(|s| *s == current),
|
||||
) {
|
||||
let s = PreviewShortcut::ALL[i];
|
||||
changes.push(json!({"shortcut": s.id(), "current": s.id()}));
|
||||
}
|
||||
app.auto.add("preview.loop", lr, "Loop");
|
||||
p.text(pos2(lr.max.x + 6.0, yy), Align2::LEFT_CENTER, "Loop", Tokens::ui(12.0), t.text);
|
||||
let ar = Rect::from_min_size(pos2(rect.min.x + 90.0, yy - 8.0), vec2(16.0, 16.0));
|
||||
if widgets::checkbox(ui, ar, app.ui.preview_audio, &t, egui::Id::new("pv-audio")).clicked() {
|
||||
let _ = crate::menus::invoke(app, &ctx, "playback.audio", json!({}));
|
||||
}
|
||||
app.auto.add("preview.audio", ar, "Include Audio");
|
||||
p.text(pos2(ar.max.x + 6.0, yy), Align2::LEFT_CENTER, "Include Audio", Tokens::ui(12.0), t.text);
|
||||
yy += 24.0;
|
||||
row(&p, yy, "Range", "Work Area Extended By Current Time");
|
||||
yy += 22.0;
|
||||
row(&p, yy, "Play From", "Current Time");
|
||||
yy += 22.0;
|
||||
let comp = app.session.active_comp().cloned();
|
||||
row(&p, yy, "Frame Rate", &comp.as_ref().map(|c| format!("({:.2})", c.frame_rate.as_f64())).unwrap_or_default());
|
||||
yy += 22.0;
|
||||
row(&p, yy, "Resolution", app.ui.viewer.res.label());
|
||||
yy += 26.0;
|
||||
if let Some(c) = comp {
|
||||
|
||||
// Include Video / Audio / Overlays / Layer Controls, Loop, Cache Before Playback.
|
||||
let checks: [(&str, &str, bool); 6] = [
|
||||
("includeVideo", "Video", o.include_video),
|
||||
("includeAudio", "Audio", o.include_audio),
|
||||
("includeOverlays", "Overlays", o.include_overlays),
|
||||
("includeLayerControls", "Layer Controls", o.include_layer_controls),
|
||||
("loop", "Loop", o.loop_),
|
||||
("cacheBeforePlayback", "Cache Before Playback", o.cache_before_playback),
|
||||
];
|
||||
for (i, (key, text, on)) in checks.into_iter().enumerate() {
|
||||
let col = if i < 4 { i % 2 } else { 0 };
|
||||
let row = if i < 4 { i / 2 } else { i - 2 };
|
||||
let cx = x0 + col as f32 * 110.0 - 2.0;
|
||||
let cy = yy + row as f32 * 22.0;
|
||||
if check_row(app, ui, &p, pos2(cx, cy), key, text, on) {
|
||||
changes.push(json!({"shortcut": current.id(), key: !on}));
|
||||
}
|
||||
}
|
||||
yy += 4.0 * 22.0 + 6.0;
|
||||
|
||||
// Range (and the pre/post-roll of Play Around Current Time).
|
||||
label(yy, "Range");
|
||||
let ranges: Vec<String> = PreviewRange::ALL.iter().map(|r| r.label().to_string()).collect();
|
||||
let range_ids = ["workArea", "workAreaExtended", "entireDuration", "aroundCurrentTime"];
|
||||
if let Some(i) = dropdown_row(
|
||||
app,
|
||||
ui,
|
||||
Rect::from_min_size(pos2(xv, yy - 10.0), vec2(wv, 20.0)),
|
||||
"range",
|
||||
o.range.label(),
|
||||
&ranges,
|
||||
PreviewRange::ALL.iter().position(|r| *r == o.range),
|
||||
) {
|
||||
changes.push(json!({"shortcut": current.id(), "range": range_ids[i]}));
|
||||
}
|
||||
yy += 24.0;
|
||||
if o.range == PreviewRange::AroundCurrentTime {
|
||||
for (k, (key, text, v)) in [("preRoll", "Pre-roll", o.pre_roll), ("postRoll", "Post-roll", o.post_roll)].into_iter().enumerate() {
|
||||
let lx = xv + k as f32 * 100.0;
|
||||
p.text(pos2(lx, yy), Align2::LEFT_CENTER, text, Tokens::ui(11.5), t.text_dim);
|
||||
let (r, nv, _) = widgets::hot_number_at(ui, pos2(lx + 52.0, yy - 9.0), egui::Id::new(("pv-roll", key)), v, 0.05, (0.0, 600.0), 1, "s", &t);
|
||||
app.auto.add(&format!("preview.{key}"), r, text);
|
||||
if let Some(nv) = nv {
|
||||
changes.push(json!({"shortcut": current.id(), key: nv}));
|
||||
}
|
||||
}
|
||||
yy += 22.0;
|
||||
}
|
||||
|
||||
// Play From.
|
||||
label(yy, "Play From");
|
||||
let froms: Vec<String> = PlayFrom::ALL.iter().map(|f| f.label().to_string()).collect();
|
||||
if let Some(i) = dropdown_row(
|
||||
app,
|
||||
ui,
|
||||
Rect::from_min_size(pos2(xv, yy - 10.0), vec2(wv, 20.0)),
|
||||
"playFrom",
|
||||
o.play_from.label(),
|
||||
&froms,
|
||||
PlayFrom::ALL.iter().position(|f| *f == o.play_from),
|
||||
) {
|
||||
changes.push(json!({"shortcut": current.id(), "playFrom": (["rangeStart", "currentTime"][i])}));
|
||||
}
|
||||
yy += 26.0;
|
||||
|
||||
// Frame Rate, Skip, Resolution.
|
||||
let comp_fps = app.session.active_comp().map(|c| c.frame_rate.as_f64());
|
||||
label(yy, "Frame Rate");
|
||||
const RATES: [f64; 12] = [8.0, 10.0, 12.0, 12.5, 15.0, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 60.0];
|
||||
let auto = format!("({:.2}) Auto", comp_fps.unwrap_or(0.0));
|
||||
let mut rates = vec![auto.clone()];
|
||||
rates.extend(RATES.iter().map(|r| fmt_rate(*r)));
|
||||
let rate_text = o.frame_rate.map(fmt_rate).unwrap_or(auto);
|
||||
let rate_cur = match o.frame_rate {
|
||||
None => Some(0),
|
||||
Some(r) => RATES.iter().position(|x| (x - r).abs() < 1e-3).map(|i| i + 1),
|
||||
};
|
||||
if let Some(i) = dropdown_row(app, ui, Rect::from_min_size(pos2(xv, yy - 10.0), vec2(96.0, 20.0)), "frameRate", &rate_text, &rates, rate_cur) {
|
||||
let v = if i == 0 { json!("auto") } else { json!(RATES[i - 1]) };
|
||||
changes.push(json!({"shortcut": current.id(), "frameRate": v}));
|
||||
}
|
||||
let sx = xv + 106.0;
|
||||
p.text(pos2(sx, yy), Align2::LEFT_CENTER, "Skip", Tokens::ui(12.0), t.text_dim);
|
||||
let (r, nv, _) = widgets::hot_number_at(ui, pos2(sx + 30.0, yy - 9.0), egui::Id::new("pv-skip"), o.skip as f64, 0.1, (0.0, 99.0), 0, "", &t);
|
||||
app.auto.add("preview.skip", r, "Skip");
|
||||
if let Some(nv) = nv {
|
||||
changes.push(json!({"shortcut": current.id(), "skip": nv.round() as u32}));
|
||||
}
|
||||
yy += 24.0;
|
||||
label(yy, "Resolution");
|
||||
let ress: Vec<String> = PreviewResolution::ALL.iter().map(|r| r.label().to_string()).collect();
|
||||
let res_ids = ["auto", "full", "half", "third", "quarter", "custom"];
|
||||
if let Some(i) = dropdown_row(
|
||||
app,
|
||||
ui,
|
||||
Rect::from_min_size(pos2(xv, yy - 10.0), vec2(96.0, 20.0)),
|
||||
"resolution",
|
||||
o.resolution.label(),
|
||||
&ress,
|
||||
PreviewResolution::ALL.iter().position(|r| *r == o.resolution),
|
||||
) {
|
||||
changes.push(json!({"shortcut": current.id(), "resolution": res_ids[i]}));
|
||||
}
|
||||
if o.resolution == PreviewResolution::Custom {
|
||||
let (r, nv, _) =
|
||||
widgets::hot_number_at(ui, pos2(xv + 106.0, yy - 9.0), egui::Id::new("pv-custom-res"), o.custom_resolution as f64, 0.1, (1.0, 40.0), 0, "", &t);
|
||||
app.auto.add("preview.customResolution", r, "Custom Resolution");
|
||||
if let Some(nv) = nv {
|
||||
changes.push(json!({"shortcut": current.id(), "customResolution": nv.round() as u32}));
|
||||
}
|
||||
}
|
||||
yy += 24.0;
|
||||
if check_row(app, ui, &p, pos2(x0 - 2.0, yy), "fullScreen", "Full Screen", o.full_screen) {
|
||||
changes.push(json!({"shortcut": current.id(), "fullScreen": !o.full_screen}));
|
||||
}
|
||||
yy += 24.0;
|
||||
|
||||
// What stopping does.
|
||||
p.text(pos2(x0, yy), Align2::LEFT_CENTER, format!("On ({}) stop:", current.label()), Tokens::ui(11.5), t.text_dim);
|
||||
yy += 20.0;
|
||||
if check_row(app, ui, &p, pos2(x0 - 2.0, yy), "playCachedFrames", "If caching, play cached frames", o.play_cached_frames) {
|
||||
changes.push(json!({"shortcut": current.id(), "playCachedFrames": !o.play_cached_frames}));
|
||||
}
|
||||
yy += 22.0;
|
||||
if check_row(app, ui, &p, pos2(x0 - 2.0, yy), "moveTimeToPreviewTime", "Move time to preview time", o.move_time_to_preview_time) {
|
||||
changes.push(json!({"shortcut": current.id(), "moveTimeToPreviewTime": !o.move_time_to_preview_time}));
|
||||
}
|
||||
yy += 24.0;
|
||||
for c in changes {
|
||||
if let Err(e) = app.session.execute("playback.settings.set", c) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// Cache bar over the preview range.
|
||||
if let Some(c) = app.session.active_comp().cloned() {
|
||||
let cid = app.session.active_comp_id().map(|i| i.0).unwrap_or(0);
|
||||
let scale = app.viewer_shown.as_ref().map(|(_, k)| k.scale).unwrap_or(1000);
|
||||
let cached = app.frames.cached_frames(app.session.revision, cid, scale).len();
|
||||
let total = c.frame_rate.frame_at(c.work_area.1) - c.frame_rate.frame_at(c.work_area.0);
|
||||
let pl = match app.playback.plan.filter(|_| app.playback.playing) {
|
||||
Some(pl) => pl,
|
||||
None => effectcraft_engine::preview::plan(&o, &c, app.session.time()),
|
||||
};
|
||||
let cached_set = app.frames.cached_frames(app.session.revision, cid, scale);
|
||||
let total = pl.frames().count();
|
||||
let cached = pl.frames().filter(|f| cached_set.binary_search(f).is_ok()).count();
|
||||
let bar = Rect::from_min_size(pos2(rect.min.x + 12.0, yy), vec2(rect.width() - 24.0, 6.0));
|
||||
p.rect_filled(bar, 3.0, t.field_bg);
|
||||
let f = (cached as f32 / total.max(1) as f32).min(1.0);
|
||||
p.rect_filled(Rect::from_min_size(bar.min, vec2(bar.width() * f, bar.height())), 3.0, t.cache_green);
|
||||
p.text(pos2(bar.min.x, bar.max.y + 12.0), Align2::LEFT_CENTER, format!("{cached} / {total} frames cached"), Tokens::ui(11.0), t.text_faint);
|
||||
let status = if app.playback.playing && app.playback.caching { " — caching before playback" } else { "" };
|
||||
p.text(pos2(bar.min.x, bar.max.y + 12.0), Align2::LEFT_CENTER, format!("{cached} / {total} frames cached{status}"), Tokens::ui(11.0), t.text_faint);
|
||||
}
|
||||
ui.set_clip_rect(panel_clip);
|
||||
let content = yy + 30.0 - (rect.min.y - scroll);
|
||||
let max = (content - rect.height()).max(0.0);
|
||||
scroll = scroll.min(max);
|
||||
ctx.data_mut(|d| d.insert_temp(scroll_id, scroll));
|
||||
if max > 0.0 {
|
||||
// A thin scroll indicator on the right edge.
|
||||
let h = (rect.height() * rect.height() / content).max(12.0);
|
||||
let top = rect.min.y + (rect.height() - h) * (scroll / max);
|
||||
p.rect_filled(Rect::from_min_size(pos2(rect.max.x - 5.0, top), vec2(3.0, h)), 1.5, t.text_faint.gamma_multiply(0.6));
|
||||
app.auto.add("preview.scroll", Rect::from_min_size(pos2(rect.max.x - 6.0, rect.min.y), vec2(6.0, rect.height())), "Preview scroll");
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_rate(r: f64) -> String {
|
||||
if (r - r.round()).abs() < 1e-6 { format!("{r:.0}") } else { format!("{r}") }
|
||||
}
|
||||
|
||||
/// A checkbox with its label; returns true when clicked.
|
||||
fn check_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, at: egui::Pos2, key: &str, text: &str, on: bool) -> bool {
|
||||
let t = app.tokens;
|
||||
let r = Rect::from_min_size(pos2(at.x, at.y - 8.0), vec2(16.0, 16.0));
|
||||
let clicked = widgets::checkbox(ui, r, on, &t, egui::Id::new(("pv-check", key))).clicked();
|
||||
p.text(pos2(r.max.x + 5.0, at.y), Align2::LEFT_CENTER, text, Tokens::ui(12.0), t.text);
|
||||
app.auto.add(&format!("preview.{key}"), r, text);
|
||||
clicked
|
||||
}
|
||||
|
||||
/// A dropdown with its popup list (automation ids `preview.<key>` and `preview.<key>.<i>`);
|
||||
/// returns the chosen index.
|
||||
fn dropdown_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, r: Rect, key: &str, text: &str, items: &[String], current: Option<usize>) -> Option<usize> {
|
||||
let t = app.tokens;
|
||||
let pid = egui::Id::new(("pv-pop", key));
|
||||
if widgets::dropdown(ui, r, text, &t, pid.with("btn")).clicked() {
|
||||
let open: bool = ui.data(|d| d.get_temp(pid.with("open")).unwrap_or(false));
|
||||
ui.data_mut(|d| d.insert_temp(pid.with("open"), !open));
|
||||
}
|
||||
app.auto.add(&format!("preview.{key}"), r, text);
|
||||
let open: bool = ui.data(|d| d.get_temp(pid.with("open")).unwrap_or(false));
|
||||
if !open {
|
||||
return None;
|
||||
}
|
||||
let mut chosen = None;
|
||||
let area = egui::Area::new(pid.with("area")).order(egui::Order::Foreground).fixed_pos(r.left_bottom() + vec2(0.0, 2.0)).show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width(r.width().max(140.0));
|
||||
for (i, label) in items.iter().enumerate() {
|
||||
let resp = ui.selectable_label(current == Some(i), label.as_str());
|
||||
app.auto.add(&format!("preview.{key}.{i}"), resp.rect, label);
|
||||
if resp.clicked() {
|
||||
chosen = Some(i);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let outside =
|
||||
ui.input(|i| i.pointer.any_pressed()) && !area.response.contains_pointer() && !r.contains(ui.input(|i| i.pointer.interact_pos()).unwrap_or_default());
|
||||
if chosen.is_some() || outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
ui.data_mut(|d| d.insert_temp(pid.with("open"), false));
|
||||
}
|
||||
chosen
|
||||
}
|
||||
|
||||
/// Audio panel: L/R VU meters (dBFS, 0 to -48) with peak hold and clip indicators, fed by the
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod expr_editor;
|
||||
pub mod flowchart;
|
||||
pub mod footage_panel;
|
||||
pub mod forms;
|
||||
pub mod fx_editors;
|
||||
pub mod fx_widgets;
|
||||
pub mod graph;
|
||||
pub mod graph_tools;
|
||||
@@ -28,6 +29,7 @@ pub mod media_panels;
|
||||
pub mod misc;
|
||||
pub mod paint_panels;
|
||||
pub mod panel_kit;
|
||||
pub mod path_vr_panels;
|
||||
pub mod precomp;
|
||||
pub mod project;
|
||||
pub mod properties;
|
||||
@@ -117,6 +119,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
|
||||
PanelKind::Metadata => media_panels::metadata(app, ui, rect),
|
||||
PanelKind::Progress => media_panels::progress(app, ui, rect),
|
||||
PanelKind::ContentAwareFill => content_fill_panel::show(app, ui, rect),
|
||||
PanelKind::CreateNullsFromPaths => path_vr_panels::create_nulls(app, ui, rect),
|
||||
PanelKind::VrCompEditor => path_vr_panels::vr_editor(app, ui, rect),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Two built-in panels After Effects ships as scripts, written from scratch as panels:
|
||||
//!
|
||||
//! - **Create Nulls From Paths** (Window ▸ Create Nulls From Paths): with a mask or shape path (or
|
||||
//! a layer that has one) selected, Points Follow Nulls / Nulls Follow Points / Trace Path
|
||||
//! (`paths.*` commands; Trace Path can loop).
|
||||
//! - **VR Comp Editor** (Window ▸ VR Comp Editor): the project's VR environments (Composition ▸ VR
|
||||
//! ▸ Create VR Environment); pick one and edit its 360 view's camera orientation (pan, tilt,
|
||||
//! roll) with `comp.vr.setView`; open its output.
|
||||
//!
|
||||
//! Automation ids: `createNulls.pointsFollowNulls`, `createNulls.nullsFollowPoints`,
|
||||
//! `createNulls.tracePath`, `createNulls.loop`, `vrEditor.env.<output id>`, `vrEditor.pan`,
|
||||
//! `vrEditor.tilt`, `vrEditor.roll`, `vrEditor.reset`, `vrEditor.open`.
|
||||
|
||||
use egui::{Rect, RichText};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::EffectcraftApp;
|
||||
|
||||
fn run(app: &mut EffectcraftApp, ctx: &egui::Context, actions: Vec<(&str, Value)>) {
|
||||
for (id, p) in actions {
|
||||
match crate::menus::invoke(app, ctx, id, p) {
|
||||
Ok(_) => {}
|
||||
Err(e) => app.ui.status = e,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn area(ui: &mut egui::Ui, rect: Rect) -> egui::Ui {
|
||||
ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink(10.0)).layout(egui::Layout::top_down(egui::Align::Min)))
|
||||
}
|
||||
|
||||
/// Window ▸ Create Nulls From Paths.
|
||||
pub fn create_nulls(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let t = app.tokens;
|
||||
let ctx = ui.ctx().clone();
|
||||
let mut ui = area(ui, rect);
|
||||
let loop_id = egui::Id::new("createNulls.loop");
|
||||
let mut looping: bool = ui.data(|d| d.get_temp(loop_id)).unwrap_or(false);
|
||||
let ready = app.session.is_enabled("paths.nullsFollowPoints") && !app.session.state.selected_layers.is_empty();
|
||||
ui.label(RichText::new("Select a layer with a mask or shape path (or the path property).").color(t.text_dim).small());
|
||||
ui.add_space(6.0);
|
||||
let mut acts = vec![];
|
||||
for (id, label, tip) in [
|
||||
("paths.pointsFollowNulls", "Points Follow Nulls", "A null on each vertex; move the nulls to reshape the path"),
|
||||
("paths.nullsFollowPoints", "Nulls Follow Points", "A null on each vertex that follows the (animated) path"),
|
||||
("paths.tracePath", "Trace Path", "A null moving along the path, driven by its Progress slider"),
|
||||
] {
|
||||
let r = ui.add_enabled(ready, egui::Button::new(label).min_size(egui::vec2(170.0, 24.0))).on_hover_text(tip);
|
||||
let auto = format!("createNulls.{}", id.trim_start_matches("paths."));
|
||||
app.auto.add(&auto, r.rect, label);
|
||||
if r.clicked() {
|
||||
acts.push((id, if id == "paths.tracePath" { json!({"loop": looping}) } else { json!({}) }));
|
||||
}
|
||||
}
|
||||
let r = ui.checkbox(&mut looping, "Loop (Trace Path)");
|
||||
app.auto.add("createNulls.loop", r.rect, "Loop");
|
||||
ui.data_mut(|d| d.insert_temp(loop_id, looping));
|
||||
run(app, &ctx, acts);
|
||||
}
|
||||
|
||||
/// Window ▸ VR Comp Editor.
|
||||
pub fn vr_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let t = app.tokens;
|
||||
let ctx = ui.ctx().clone();
|
||||
let mut ui = area(ui, rect);
|
||||
let envs = app.session.execute("comp.vr.environments", json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default();
|
||||
if envs.is_empty() {
|
||||
ui.label(RichText::new("No VR environments yet. Create one with Composition ▸ VR ▸ Create VR Environment…").color(t.text_faint));
|
||||
return;
|
||||
}
|
||||
let sel_id = egui::Id::new("vrEditor.selected");
|
||||
let active = app.session.state.active_comp.map(|c| c.0);
|
||||
let mut sel: u64 = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0);
|
||||
// Default: the active comp's environment, else the first.
|
||||
let owns = |e: &Value, c: u64| e["output"] == c || e["cubeMap"] == c || e["faces"].as_array().is_some_and(|f| f.iter().any(|x| x["comp"] == c));
|
||||
if !envs.iter().any(|e| e["output"] == sel) {
|
||||
sel = active.and_then(|c| envs.iter().find(|e| owns(e, c))).or(envs.first()).and_then(|e| e["output"].as_u64()).unwrap_or(0);
|
||||
}
|
||||
let mut acts = vec![];
|
||||
ui.label(RichText::new("VR Environments").strong());
|
||||
for e in &envs {
|
||||
let out = e["output"].as_u64().unwrap_or(0);
|
||||
let r = ui.selectable_label(out == sel, e["name"].as_str().unwrap_or(""));
|
||||
app.auto.add(&format!("vrEditor.env.{out}"), r.rect, e["name"].as_str().unwrap_or(""));
|
||||
if r.clicked() {
|
||||
sel = out;
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(sel_id, sel));
|
||||
let Some(env) = envs.iter().find(|e| e["output"] == sel) else { return };
|
||||
ui.separator();
|
||||
ui.label(RichText::new("360 View Orientation").strong());
|
||||
let view: Vec<f64> = env["view"].as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
|
||||
let signed = |a: f64| if a > 180.0 { a - 360.0 } else { a };
|
||||
let (mut tilt, mut pan, mut roll) =
|
||||
(signed(view.first().copied().unwrap_or(0.0)), signed(view.get(1).copied().unwrap_or(0.0)), signed(view.get(2).copied().unwrap_or(0.0)));
|
||||
let mut changed = false;
|
||||
for (label, auto, v) in [("Pan", "vrEditor.pan", &mut pan), ("Tilt", "vrEditor.tilt", &mut tilt), ("Roll", "vrEditor.roll", &mut roll)] {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(label);
|
||||
let r = ui.add(egui::Slider::new(v, -180.0..=180.0).suffix("°").max_decimals(1));
|
||||
app.auto.add(auto, r.rect, label);
|
||||
changed |= r.changed();
|
||||
});
|
||||
}
|
||||
if changed {
|
||||
acts.push(("comp.vr.setView", json!({"comp": sel, "pan": pan, "tilt": tilt, "roll": roll})));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let r = ui.button("Reset");
|
||||
app.auto.add("vrEditor.reset", r.rect, "Reset");
|
||||
if r.clicked() {
|
||||
acts.push(("comp.vr.setView", json!({"comp": sel, "orientation": [0.0, 0.0, 0.0]})));
|
||||
}
|
||||
let r = ui.button("Open Output");
|
||||
app.auto.add("vrEditor.open", r.rect, "Open Output");
|
||||
if r.clicked() {
|
||||
acts.push(("comp.open", json!({"comp": sel})));
|
||||
}
|
||||
});
|
||||
ui.label(RichText::new("All six face cameras turn together; the scene is not changed.").color(t.text_faint).small());
|
||||
run(app, &ctx, acts);
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
//! computed; what the user does goes back through the `scriptui.click` / `scriptui.set` /
|
||||
//! `scriptui.close` commands, which run the script's handlers. Every control registers an
|
||||
//! automation id `scriptui.<window>.<control>` (and `scriptui.<window>.<name>` when the script
|
||||
//! named it).
|
||||
//! named it). Controls with an `onDraw` handler are painted from their draw list; edit texts and
|
||||
//! sliders send live `changing` updates (onChanging) while typing / dragging.
|
||||
|
||||
use effectcraft_engine::scriptui::{ScriptWindow, Widget, WidgetKind, WindowKind, layout};
|
||||
use effectcraft_engine::scriptui::{DrawOp, PathSeg, ScriptWindow, Widget, WidgetKind, WindowKind, layout};
|
||||
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, UiBuilder, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -16,6 +17,8 @@ use crate::theme::Tokens;
|
||||
enum Act {
|
||||
Click(u32, u32),
|
||||
Set(u32, u32, Value),
|
||||
/// A live update (each keystroke / slider step): fires onChanging.
|
||||
Changing(u32, u32, Value),
|
||||
Close(u32),
|
||||
}
|
||||
|
||||
@@ -78,6 +81,27 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
|
||||
register(app, win, w, rect);
|
||||
let id = egui::Id::new(("sui", win, w.id));
|
||||
let tip = |r: egui::Response| if w.help_tip.is_empty() { r } else { r.on_hover_text(&w.help_tip) };
|
||||
// onDraw: the script paints the control. Without drawOSControl() its paint replaces the
|
||||
// default look (buttons and toggles still respond to clicks); with it, it goes on top.
|
||||
let custom = w.handlers.iter().any(|h| h == "onDraw");
|
||||
let os = w.draw.iter().any(|d| matches!(d, DrawOp::Os));
|
||||
if custom && !os {
|
||||
if w.kind.is_container() {
|
||||
paint_draw(ui, rect, &w.draw, &t);
|
||||
draw_children(app, ui, origin, win, w, acts);
|
||||
return;
|
||||
}
|
||||
let clickable = matches!(w.kind, WidgetKind::Button | WidgetKind::IconButton | WidgetKind::Checkbox | WidgetKind::RadioButton);
|
||||
let r = ui.interact(rect, id, if clickable && w.enabled { Sense::click() } else { Sense::hover() });
|
||||
paint_draw(ui, rect, &w.draw, &t);
|
||||
if tip(r).clicked() && clickable {
|
||||
acts.push(Act::Click(win, w.id));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if custom && w.kind.is_container() {
|
||||
paint_draw(ui, rect, &w.draw, &t);
|
||||
}
|
||||
match w.kind {
|
||||
WidgetKind::Group | WidgetKind::Tab | WidgetKind::Window | WidgetKind::TabbedPanel => draw_children(app, ui, origin, win, w, acts),
|
||||
WidgetKind::Panel => {
|
||||
@@ -112,8 +136,16 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
|
||||
let te = te.id(id).interactive(!w.read_only).font(Tokens::ui(12.0));
|
||||
let r = ui.add_enabled_ui(w.enabled, |ui| ui.put(rect, te)).inner;
|
||||
let r = tip(r);
|
||||
if r.lost_focus() && buf != w.text {
|
||||
// Live updates already sent the text: the commit still runs onChange.
|
||||
let dirty_id = id.with("dirty");
|
||||
let dirty = ui.data(|d| d.get_temp::<bool>(dirty_id)).unwrap_or(false);
|
||||
if r.lost_focus() && (buf != w.text || dirty) {
|
||||
acts.push(Act::Set(win, w.id, json!(buf)));
|
||||
ui.data_mut(|d| d.remove::<bool>(dirty_id));
|
||||
} else if r.changed() && w.handlers.iter().any(|h| h == "onChanging") {
|
||||
// Each keystroke reaches the script's onChanging (onChange runs on commit).
|
||||
acts.push(Act::Changing(win, w.id, json!(buf)));
|
||||
ui.data_mut(|d| d.insert_temp(dirty_id, true));
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, buf));
|
||||
}
|
||||
@@ -145,6 +177,10 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
|
||||
.inner;
|
||||
let r = tip(r);
|
||||
if r.dragged() {
|
||||
// Live: each step of the drag reaches the script (onChanging).
|
||||
if r.changed() {
|
||||
acts.push(Act::Changing(win, w.id, json!(v)));
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(id, v));
|
||||
} else {
|
||||
ui.data_mut(|d| d.remove::<f64>(id));
|
||||
@@ -203,6 +239,45 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
|
||||
ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
if custom && !w.kind.is_container() {
|
||||
paint_draw(ui, rect, &w.draw, &t);
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint an onDraw draw list in `rect` (control coordinates → screen).
|
||||
fn paint_draw(ui: &egui::Ui, rect: Rect, ops: &[DrawOp], t: &Tokens) {
|
||||
let p = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
let col = |c: &Option<[f32; 4]>, theme: Color32| match c {
|
||||
Some(c) => egui::Rgba::from_rgba_unmultiplied(c[0], c[1], c[2], c[3]).into(),
|
||||
None => theme,
|
||||
};
|
||||
let at = |x: f64, y: f64| rect.min + vec2(x as f32, y as f32);
|
||||
for op in ops {
|
||||
match op {
|
||||
DrawOp::Fill { color, path } => {
|
||||
let c = col(color, t.field_bg);
|
||||
for (pts, _) in PathSeg::polylines(path, 48) {
|
||||
let pts: Vec<egui::Pos2> = pts.iter().map(|q| at(q[0], q[1])).collect();
|
||||
p.add(egui::Shape::convex_polygon(pts, c, Stroke::NONE));
|
||||
}
|
||||
}
|
||||
DrawOp::Stroke { color, width, path } => {
|
||||
let s = Stroke::new(*width as f32, col(color, t.text));
|
||||
for (pts, closed) in PathSeg::polylines(path, 48) {
|
||||
let pts: Vec<egui::Pos2> = pts.iter().map(|q| at(q[0], q[1])).collect();
|
||||
p.add(if closed { egui::Shape::closed_line(pts, s) } else { egui::Shape::line(pts, s) });
|
||||
}
|
||||
}
|
||||
DrawOp::Text { text, color, x, y, size, .. } => {
|
||||
p.text(at(*x, *y), Align2::LEFT_TOP, text, Tokens::ui(*size as f32), col(color, t.text));
|
||||
}
|
||||
DrawOp::Image { x, y, w, h } => {
|
||||
let r = Rect::from_min_size(at(*x, *y), vec2(*w as f32, *h as f32));
|
||||
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
|
||||
}
|
||||
DrawOp::Os => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checkboxes and radio buttons sit at the left of their (possibly filled) bounds.
|
||||
@@ -216,6 +291,7 @@ fn perform(app: &mut EffectcraftApp, ctx: &egui::Context, acts: Vec<Act>) {
|
||||
let (cmd, p) = match a {
|
||||
Act::Click(w, id) => ("scriptui.click", json!({"window": w, "widget": id})),
|
||||
Act::Set(w, id, v) => ("scriptui.set", json!({"window": w, "widget": id, "value": v})),
|
||||
Act::Changing(w, id, v) => ("scriptui.set", json!({"window": w, "widget": id, "value": v, "changing": true})),
|
||||
Act::Close(w) => ("scriptui.close", json!({"window": w})),
|
||||
};
|
||||
match crate::menus::invoke(app, ctx, cmd, p) {
|
||||
|
||||
@@ -7,7 +7,6 @@ use effectcraft_engine::render::EvalCtx;
|
||||
use egui::{Align2, Rect, Sense, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::icons::{self, Icon};
|
||||
use crate::theme::Tokens;
|
||||
use crate::{EffectcraftApp, widgets};
|
||||
|
||||
@@ -257,6 +256,29 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
p.text(pos2(cr.max.x + 6.0, y + 7.0), Align2::LEFT_CENTER, label, Tokens::ui(11.0), t.text_dim);
|
||||
}
|
||||
}
|
||||
// Variable Font Axes: one value per axis of a variable font (`character.axis.<tag>`).
|
||||
let face = effectcraft_engine::text::resolve(&doc.font, &doc.style).face;
|
||||
let axes = effectcraft_engine::text::variable::font_axes(face);
|
||||
if !axes.is_empty() {
|
||||
y += 26.0;
|
||||
p.text(pos2(x0, y + 7.0), Align2::LEFT_CENTER, "Variable Font Axes", Tokens::semibold(11.0), t.text_dim);
|
||||
for (i, a) in axes.iter().enumerate() {
|
||||
let (col, row) = (i % 2, i / 2);
|
||||
let fx = x0 + col as f32 * (w / 2.0);
|
||||
let fy = y + 20.0 + row as f32 * 24.0;
|
||||
let tag = a.tag.trim_end().to_string();
|
||||
let v = doc.variations.iter().find(|(t2, _)| t2.trim_end() == tag).map(|(_, v)| *v).unwrap_or(a.default);
|
||||
p.text(pos2(fx, fy + 9.0), Align2::LEFT_CENTER, &tag, Tokens::semibold(10.5), t.text_dim);
|
||||
let (r, nv, _) =
|
||||
widgets::hot_number_at(ui, pos2(fx + 34.0, fy), egui::Id::new(("char-axis", &tag)), v as f64, 1.0, (a.min as f64, a.max as f64), 0, "", &t);
|
||||
app.auto.add(&format!("character.axis.{tag}"), r, &a.name);
|
||||
if let Some(nv) = nv
|
||||
&& enabled
|
||||
{
|
||||
actions.push(json!({"variations": {tag.clone(): nv}, "merge": format!("char-axis-{tag}")}));
|
||||
}
|
||||
}
|
||||
}
|
||||
match &target {
|
||||
None => {
|
||||
p.text(pos2(rect.center().x, rect.max.y - 20.0), Align2::CENTER_CENTER, "Select a text layer", Tokens::ui(11.0), t.text_faint);
|
||||
@@ -568,90 +590,131 @@ fn font_popup(app: &EffectcraftApp, ui: &mut egui::Ui, id: egui::Id, pos: egui::
|
||||
chosen
|
||||
}
|
||||
|
||||
/// Align panel: align selected layers to the composition (or to the selection).
|
||||
/// Align panel: Align Layers to Selection / Composition, the six align buttons and the six
|
||||
/// Distribute Layers buttons. Buttons run `layer.align {edge, to}` and `layer.distribute
|
||||
/// {mode}` on the selected layers.
|
||||
pub fn align(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let t = app.tokens;
|
||||
let p = ui.painter().with_clip_rect(rect);
|
||||
let x0 = rect.min.x + 10.0;
|
||||
let y = rect.min.y + 10.0;
|
||||
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Align Layers to: Composition", Tokens::ui(11.5), t.text_dim);
|
||||
let mut y = rect.min.y + 10.0;
|
||||
p.text(pos2(x0, y + 10.0), Align2::LEFT_CENTER, "Align Layers to:", Tokens::ui(11.5), t.text_dim);
|
||||
let dr = Rect::from_min_size(pos2(x0 + 100.0, y), vec2(110.0, 20.0));
|
||||
let to_sel = app.ui.align_to_selection;
|
||||
let pid = egui::Id::new("align-to-pop");
|
||||
if widgets::dropdown(ui, dr, if to_sel { "Selection" } else { "Composition" }, &t, pid.with("btn")).clicked() {
|
||||
widgets::open_popup(ui, pid);
|
||||
}
|
||||
app.auto.add("align.to", dr, if to_sel { "Selection" } else { "Composition" });
|
||||
if let Some(i) =
|
||||
widgets::popup_menu(ui, pid, dr.left_bottom() + vec2(0.0, 2.0), &["Selection".to_string(), "Composition".to_string()], Some(if to_sel { 0 } else { 1 }))
|
||||
{
|
||||
app.ui.align_to_selection = i == 0;
|
||||
}
|
||||
y += 28.0;
|
||||
let ops = ["left", "hcenter", "right", "top", "vcenter", "bottom"];
|
||||
for (i, op) in ops.iter().enumerate() {
|
||||
let r = Rect::from_min_size(pos2(x0 + i as f32 * 34.0 + if i >= 3 { 12.0 } else { 0.0 }, y + 24.0), vec2(30.0, 28.0));
|
||||
let resp = ui.interact(r, egui::Id::new(("align", *op)), Sense::click());
|
||||
p.rect_filled(r, 3.0, if resp.hovered() { t.hover } else { t.field_bg });
|
||||
// Glyph: a bar (alignment edge) and two boxes.
|
||||
let c = r.center();
|
||||
let st = egui::Stroke::new(1.3, t.text);
|
||||
match *op {
|
||||
"left" | "hcenter" | "right" => {
|
||||
let ex = match *op {
|
||||
"left" => r.min.x + 7.0,
|
||||
"right" => r.max.x - 7.0,
|
||||
_ => c.x,
|
||||
};
|
||||
p.line_segment([pos2(ex, r.min.y + 5.0), pos2(ex, r.max.y - 5.0)], st);
|
||||
let off = |w: f32| match *op {
|
||||
"left" => ex,
|
||||
"right" => ex - w,
|
||||
_ => ex - w / 2.0,
|
||||
};
|
||||
p.rect_filled(Rect::from_min_size(pos2(off(14.0), c.y - 7.0), vec2(14.0, 5.0)), 1.0, t.text_dim);
|
||||
p.rect_filled(Rect::from_min_size(pos2(off(9.0), c.y + 2.0), vec2(9.0, 5.0)), 1.0, t.text_dim);
|
||||
}
|
||||
_ => {
|
||||
let ey = match *op {
|
||||
"top" => r.min.y + 6.0,
|
||||
"bottom" => r.max.y - 6.0,
|
||||
_ => c.y,
|
||||
};
|
||||
p.line_segment([pos2(r.min.x + 5.0, ey), pos2(r.max.x - 5.0, ey)], st);
|
||||
let off = |h: f32| match *op {
|
||||
"top" => ey,
|
||||
"bottom" => ey - h,
|
||||
_ => ey - h / 2.0,
|
||||
};
|
||||
p.rect_filled(Rect::from_min_size(pos2(c.x - 8.0, off(14.0)), vec2(5.0, 14.0)), 1.0, t.text_dim);
|
||||
p.rect_filled(Rect::from_min_size(pos2(c.x + 3.0, off(9.0)), vec2(5.0, 9.0)), 1.0, t.text_dim);
|
||||
let mut run: Option<(&str, &str)> = None;
|
||||
for (row, kind) in ["align", "distribute"].into_iter().enumerate() {
|
||||
if row == 1 {
|
||||
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Distribute Layers:", Tokens::ui(11.5), t.text_dim);
|
||||
y += 20.0;
|
||||
}
|
||||
for (i, op) in ops.iter().enumerate() {
|
||||
let r = Rect::from_min_size(pos2(x0 + i as f32 * 34.0 + if i >= 3 { 12.0 } else { 0.0 }, y), vec2(30.0, 28.0));
|
||||
let resp = ui.interact(r, egui::Id::new((kind, *op)), Sense::click());
|
||||
p.rect_filled(r, 3.0, if resp.hovered() { t.hover } else { t.field_bg });
|
||||
align_glyph(&p, r, op, row == 1, &t);
|
||||
let tip = align_tip(kind, op);
|
||||
app.auto.add(&format!("{kind}.{op}"), r, &tip);
|
||||
if resp.on_hover_text(tip).clicked() {
|
||||
run = Some((kind, op));
|
||||
}
|
||||
}
|
||||
app.auto.add(&format!("align.{op}"), r, op);
|
||||
if resp.clicked() {
|
||||
align_layers(app, op);
|
||||
y += 34.0;
|
||||
}
|
||||
if let Some((kind, op)) = run {
|
||||
let r = if kind == "align" {
|
||||
let to = if app.ui.align_to_selection { "selection" } else { "composition" };
|
||||
app.session.execute("layer.align", json!({"edge": op, "to": to}))
|
||||
} else {
|
||||
app.session.execute("layer.distribute", json!({"mode": op}))
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
}
|
||||
let _ = icons::paint;
|
||||
let _ = Icon::Grid;
|
||||
}
|
||||
|
||||
/// Move selected layers so their content bounds align to the comp.
|
||||
pub fn align_layers(app: &mut EffectcraftApp, op: &str) {
|
||||
let Some(cid) = app.session.active_comp_id() else { return };
|
||||
let Some(comp) = app.session.project.comp(cid).cloned() else { return };
|
||||
let time = app.session.time();
|
||||
let mut moves = vec![];
|
||||
{
|
||||
let ectx = EvalCtx { project: &app.session.project, comp_id: cid, comp: &comp, time, expr: app.session.expr.as_deref(), footage: None };
|
||||
for l in comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id)) {
|
||||
let Some(b) = effectcraft_engine::render::content_bounds(&ectx, l) else { continue };
|
||||
let (m, _) = ectx.layer_to_comp(l);
|
||||
let pts = [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]].map(|p| m.apply(effectcraft_engine::geom::vec2(p[0], p[1])));
|
||||
let (x0, x1) = (pts.iter().map(|p| p.x).fold(f64::INFINITY, f64::min), pts.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max));
|
||||
let (y0, y1) = (pts.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), pts.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max));
|
||||
let (cw, ch) = (comp.width as f64, comp.height as f64);
|
||||
let (dx, dy) = match op {
|
||||
"left" => (-x0, 0.0),
|
||||
"right" => (cw - x1, 0.0),
|
||||
"hcenter" => (cw / 2.0 - (x0 + x1) / 2.0, 0.0),
|
||||
"top" => (0.0, -y0),
|
||||
"bottom" => (0.0, ch - y1),
|
||||
_ => (0.0, ch / 2.0 - (y0 + y1) / 2.0),
|
||||
};
|
||||
let pos = l.transform().map(|tr| ectx.v3(l, tr, "position", [0.0; 3])).unwrap_or([0.0; 3]);
|
||||
moves.push((l.id.0, [pos[0] + dx, pos[1] + dy, pos[2]]));
|
||||
fn align_tip(kind: &str, op: &str) -> String {
|
||||
let what = match op {
|
||||
"left" => "Left",
|
||||
"hcenter" => "Horizontal Center",
|
||||
"right" => "Right",
|
||||
"top" => "Top",
|
||||
"vcenter" => "Vertical Center",
|
||||
_ => "Bottom",
|
||||
};
|
||||
if kind == "align" { format!("Align {what}") } else { format!("Distribute {what}") }
|
||||
}
|
||||
|
||||
/// Button glyph: the alignment edge as a line and two boxes (distribute: three boxes spread,
|
||||
/// the line through each).
|
||||
fn align_glyph(p: &egui::Painter, r: Rect, op: &str, distribute: bool, t: &Tokens) {
|
||||
let c = r.center();
|
||||
let st = egui::Stroke::new(1.3, t.text);
|
||||
let horizontal = matches!(op, "left" | "hcenter" | "right");
|
||||
if distribute {
|
||||
for k in 0..3 {
|
||||
let f = (k as f32 - 1.0) * 7.0;
|
||||
if horizontal {
|
||||
let bx = c.x + f;
|
||||
let ex = match op {
|
||||
"left" => bx - 2.5,
|
||||
"right" => bx + 2.5,
|
||||
_ => bx,
|
||||
};
|
||||
p.rect_filled(Rect::from_center_size(pos2(bx, c.y), vec2(5.0, 10.0 + k as f32 * 2.0)), 1.0, t.text_dim);
|
||||
p.line_segment([pos2(ex, r.min.y + 5.0), pos2(ex, r.max.y - 5.0)], st);
|
||||
} else {
|
||||
let by = c.y + f;
|
||||
let ey = match op {
|
||||
"top" => by - 2.5,
|
||||
"bottom" => by + 2.5,
|
||||
_ => by,
|
||||
};
|
||||
p.rect_filled(Rect::from_center_size(pos2(c.x, by), vec2(10.0 + k as f32 * 2.0, 5.0)), 1.0, t.text_dim);
|
||||
p.line_segment([pos2(r.min.x + 5.0, ey), pos2(r.max.x - 5.0, ey)], st);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (id, v) in moves {
|
||||
let _ = app.session.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": v}));
|
||||
if horizontal {
|
||||
let ex = match op {
|
||||
"left" => r.min.x + 7.0,
|
||||
"right" => r.max.x - 7.0,
|
||||
_ => c.x,
|
||||
};
|
||||
p.line_segment([pos2(ex, r.min.y + 5.0), pos2(ex, r.max.y - 5.0)], st);
|
||||
let off = |w: f32| match op {
|
||||
"left" => ex,
|
||||
"right" => ex - w,
|
||||
_ => ex - w / 2.0,
|
||||
};
|
||||
p.rect_filled(Rect::from_min_size(pos2(off(14.0), c.y - 7.0), vec2(14.0, 5.0)), 1.0, t.text_dim);
|
||||
p.rect_filled(Rect::from_min_size(pos2(off(9.0), c.y + 2.0), vec2(9.0, 5.0)), 1.0, t.text_dim);
|
||||
} else {
|
||||
let ey = match op {
|
||||
"top" => r.min.y + 6.0,
|
||||
"bottom" => r.max.y - 6.0,
|
||||
_ => c.y,
|
||||
};
|
||||
p.line_segment([pos2(r.min.x + 5.0, ey), pos2(r.max.x - 5.0, ey)], st);
|
||||
let off = |h: f32| match op {
|
||||
"top" => ey,
|
||||
"bottom" => ey - h,
|
||||
_ => ey - h / 2.0,
|
||||
};
|
||||
p.rect_filled(Rect::from_min_size(pos2(c.x - 8.0, off(14.0)), vec2(5.0, 14.0)), 1.0, t.text_dim);
|
||||
p.rect_filled(Rect::from_min_size(pos2(c.x + 3.0, off(9.0)), vec2(5.0, 9.0)), 1.0, t.text_dim);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -519,7 +519,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
app.auto.add("viewer.area", area, "Composition viewer");
|
||||
|
||||
// Guides.
|
||||
if app.ui.viewer.safe_margins {
|
||||
let overlays = app.overlays_visible();
|
||||
if overlays && app.ui.viewer.safe_margins {
|
||||
let g = &app.session.prefs.grids;
|
||||
let (act, title) = (1.0 - g.action_safe as f32 / 100.0, 1.0 - g.title_safe as f32 / 100.0);
|
||||
for (k, a) in [(act, 120u8), (title, 160)] {
|
||||
@@ -530,7 +531,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
painter.line_segment([c - vec2(10.0, 0.0), c + vec2(10.0, 0.0)], Stroke::new(1.0, Color32::from_white_alpha(140)));
|
||||
painter.line_segment([c - vec2(0.0, 10.0), c + vec2(0.0, 10.0)], Stroke::new(1.0, Color32::from_white_alpha(140)));
|
||||
}
|
||||
if app.ui.viewer.grid {
|
||||
if overlays && app.ui.viewer.grid {
|
||||
// Settings ▸ Grids & Guides: gridline spacing, subdivisions and colour.
|
||||
let g = &app.session.prefs.grids;
|
||||
let [r, gg, b] = hex_rgb(&g.grid_color).unwrap_or([120, 160, 255]);
|
||||
@@ -567,7 +568,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
vt::proportional_grid(app, &painter, comp_rect);
|
||||
|
||||
// Comp guides (View ▸ Show Guides) and the region of interest.
|
||||
if app.ui.viewer.guides {
|
||||
if overlays && app.ui.viewer.guides {
|
||||
let [r, gg, b] = hex_rgb(&app.session.prefs.grids.guide_color).unwrap_or([0x3c, 0xc8, 0xf0]);
|
||||
let stroke = Stroke::new(1.0, Color32::from_rgb(r, gg, b));
|
||||
// Settings ▸ Grids & Guides ▸ Guide Style.
|
||||
@@ -625,7 +626,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if finish || app.ui.tool != Tool::Selection {
|
||||
ov::end_free_transform(&ctx);
|
||||
}
|
||||
if app.ui.viewer.show_layer_controls {
|
||||
if app.layer_controls_visible() {
|
||||
// Settings ▸ General ▸ Path Point and Handle Size; Appearance ▸ Use Label Color for
|
||||
// Layer Handles and Paths.
|
||||
let hs = app.session.prefs.general.path_point_size as f32 + 2.0;
|
||||
@@ -748,7 +749,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
// Track points of the current track (Tracker panel) on its layer, while that layer is selected.
|
||||
let mut track_hits = vec![];
|
||||
let track_cur = super::tracker::viewer_track(app);
|
||||
if app.ui.viewer.show_layer_controls
|
||||
if app.layer_controls_visible()
|
||||
&& let Some((tl, tu)) = track_cur
|
||||
&& selected.contains(&tl)
|
||||
&& let Some(layer) = comp.layer(tl)
|
||||
|
||||
@@ -533,6 +533,10 @@ pub struct UiState {
|
||||
/// The panel maximized to fill the dock area (`~`), if any.
|
||||
#[serde(default)]
|
||||
pub maximized: Option<PanelKind>,
|
||||
/// Locked Composition / Timeline tabs (panel ids): opening another composition does not
|
||||
/// bring a locked panel forward (the tab's lock icon, as After Effects' viewer lock).
|
||||
#[serde(default)]
|
||||
pub locked_tabs: BTreeSet<String>,
|
||||
pub focused: PanelKind,
|
||||
pub viewer: ViewerState,
|
||||
pub timeline: TimelineState,
|
||||
@@ -590,16 +594,13 @@ pub struct UiState {
|
||||
pub snapping: bool,
|
||||
/// Tool creates shape (true) or mask (false) when a layer is selected.
|
||||
pub tool_creates_shape: bool,
|
||||
/// Preview panel options.
|
||||
pub preview_loop: bool,
|
||||
pub preview_cache_first: bool,
|
||||
/// Preview panel "Include Audio" (Mute Audio off).
|
||||
#[serde(default = "yes")]
|
||||
pub preview_audio: bool,
|
||||
pub start_screen: bool,
|
||||
/// The Home screen shows its Learn tab (tutorials) instead of the recent projects.
|
||||
#[serde(default)]
|
||||
pub home_learn: bool,
|
||||
/// Align panel: Align Layers to Selection (off: to the composition).
|
||||
#[serde(default)]
|
||||
pub align_to_selection: bool,
|
||||
/// Composition ▸ Preview ▸ Cache Frames When Idle.
|
||||
pub cache_when_idle: bool,
|
||||
/// Tracker panel ▸ Motion Source chosen without a tracker yet (layer id).
|
||||
@@ -637,6 +638,7 @@ impl Default for UiState {
|
||||
floating: vec![],
|
||||
saved_floating: Default::default(),
|
||||
maximized: None,
|
||||
locked_tabs: BTreeSet::new(),
|
||||
focused: PanelKind::Composition,
|
||||
viewer: ViewerState::default(),
|
||||
timeline: TimelineState::default(),
|
||||
@@ -665,11 +667,9 @@ impl Default for UiState {
|
||||
stroke_width: 0.0,
|
||||
snapping: true,
|
||||
tool_creates_shape: true,
|
||||
preview_loop: true,
|
||||
preview_cache_first: false,
|
||||
preview_audio: true,
|
||||
start_screen: false,
|
||||
home_learn: false,
|
||||
align_to_selection: false,
|
||||
cache_when_idle: false,
|
||||
tracker_source: None,
|
||||
layer_panel: None,
|
||||
|
||||
@@ -154,8 +154,27 @@ pub fn dropdown(ui: &mut Ui, rect: Rect, text: &str, t: &Tokens, id: egui::Id) -
|
||||
let resp = ui.interact(rect, id, Sense::click());
|
||||
ui.painter().rect_filled(rect, 3.0, if resp.hovered() { t.hover } else { t.field_bg });
|
||||
ui.painter().rect_stroke(rect, 3.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
|
||||
ui.painter().text(pos2(rect.min.x + 7.0, rect.center().y), Align2::LEFT_CENTER, text, Tokens::ui(11.5), t.text);
|
||||
// Text that doesn't fit before the arrow is elided (narrow panels).
|
||||
let room = rect.width() - 7.0 - 18.0;
|
||||
let fits = |s: &str| ui.painter().layout_no_wrap(s.to_string(), Tokens::ui(11.5), t.text).size().x <= room;
|
||||
let shown = if fits(text) {
|
||||
text.to_string()
|
||||
} else {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let mut n = chars.len();
|
||||
loop {
|
||||
n = n.saturating_sub(1);
|
||||
let s: String = chars[..n].iter().collect::<String>().trim_end().to_string() + "…";
|
||||
if n == 0 || fits(&s) {
|
||||
break s;
|
||||
}
|
||||
}
|
||||
};
|
||||
ui.painter().text(pos2(rect.min.x + 7.0, rect.center().y), Align2::LEFT_CENTER, shown, Tokens::ui(11.5), t.text);
|
||||
icons::paint(ui.painter(), Rect::from_center_size(pos2(rect.max.x - 9.0, rect.center().y), vec2(8.0, 8.0)), Icon::ChevronDown, t.text_dim);
|
||||
if text.chars().count() > 0 && !fits(text) {
|
||||
return resp.on_hover_text(text.to_string());
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user