Merge main into M13.11 (bokeh kernel_spans/blur_levels, Essential Graphics as_type controls with mirrors and links)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-03 09:54:37 -04:00
co-authored by Claude Opus 5.5
146 changed files with 19761 additions and 676 deletions
+84 -3
View File
@@ -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, &params) {
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)
+82 -4
View File
@@ -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);
+32 -8
View File
@@ -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
View File
@@ -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)
}
}
+52 -3
View File
@@ -143,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,
@@ -210,6 +212,7 @@ impl EffectcraftApp {
deferred: vec![],
synthetic: vec![],
input_waiters: vec![],
job_waiters: vec![],
queued_screenshots: vec![],
pending_screenshots: vec![],
next_token: 1,
@@ -847,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)
}
@@ -881,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.
@@ -897,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) {
@@ -961,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))),
@@ -1094,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
+9
View File
@@ -818,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
@@ -848,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")),
+23 -5
View File
@@ -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;
@@ -536,6 +537,15 @@ fn group_rows(
}
if open {
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);
}
}
@@ -603,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,
@@ -995,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;
@@ -1006,6 +1017,9 @@ 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),
}
}
@@ -1130,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()
+68 -5
View File
@@ -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.
//! - **Mirrors and links**: adding a property that is already in the panel adds a *mirror*
@@ -138,6 +139,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)
});
@@ -205,7 +219,14 @@ 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(eg.resolve(c.id).unwrap_or(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)}),
@@ -296,8 +317,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 {
@@ -370,6 +391,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 {
@@ -440,7 +503,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(eg.resolve(c.id).unwrap_or(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)}),
+18
View File
@@ -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;
+932
View File
@@ -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);
}
}
+20 -6
View File
@@ -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())),
);
+22 -1
View File
@@ -21,7 +21,16 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
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;
@@ -223,6 +232,18 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
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 {
+4
View File
@@ -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),
}
}
+123
View File
@@ -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);
}
+79 -3
View File
@@ -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) {
+23
View File
@@ -256,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);
+5
View File
@@ -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,
@@ -634,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(),
+20 -1
View File
@@ -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
}