Merge branch 'main' into worktree-agent-a4b0610bd14276508

This commit is contained in:
Brandon Thomas
2026-10-03 10:53:00 -04:00
360 changed files with 28430 additions and 578 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)
+59 -2
View File
@@ -722,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.
@@ -807,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();
@@ -833,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());
@@ -851,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 {
@@ -487,3 +639,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)
}
}
+35 -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))),
+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()
+61 -3
View File
@@ -8,6 +8,10 @@
//! 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*
//! (same value, its own name and place); a control's ⋯ menu adds a mirror, links the selected
//! timeline property (the control then drives both) or unlinks one. Mirrors and linked
//! controls are badged (`essential.control.<id>.badge`, `.menu`).
//! - **Export Template…** writes an open `.ectemplate`.
//! - With a precomp layer that has Essential Properties selected, its instance values: edit them
//! (overrides), Revert or Push to Comp.
@@ -192,13 +196,37 @@ fn controls(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, list: &[Eg
let shown = EgControl { name: text.clone(), ..c.clone() };
name_label(app, ui, cid, &shown, RichText::new(text).italics().color(t.text_dim), actions);
}
EgKind::Property { .. } => {
EgKind::Property { .. } | EgKind::Mirror { .. } => {
name_label(app, ui, cid, c, RichText::new(&c.name), actions);
// Mirrors and linked properties are marked (hover: what they share).
let eg = app.session.project.comp(cid).and_then(|x| x.essential.clone()).unwrap_or_default();
let badge = match &c.kind {
EgKind::Mirror { of } => Some(("mirror".to_string(), format!("Mirror of {}", eg.find(*of).map(|m| m.name.as_str()).unwrap_or("?")))),
EgKind::Property { links, .. } if !links.is_empty() => {
let names: Vec<String> = essential::linked_props(&app.session.project, cid, c)
.into_iter()
.map(|(l, p)| format!("{} › {}", l.name, l.props.name_path_of(p.uid).unwrap_or_else(|| p.name.clone())))
.collect();
Some((format!("+{} linked", links.len()), format!("Also drives:\n{}", names.join("\n"))))
}
_ => None,
};
if let Some((text, tip)) = badge {
let r = ui.label(RichText::new(text).color(t.accent).size(10.0)).on_hover_text(&tip);
app.auto.add(&format!("essential.control.{}.badge", c.id), r.rect, &tip);
}
let src = essential::source_prop(&app.session.project, cid, c).map(|(l, p)| (l.id.0, l.layer_time(app.session.time()), p.clone()));
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), essential::effective_type(c, &p), &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)}),
@@ -209,6 +237,7 @@ fn controls(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, list: &[Eg
ui.label(RichText::new("(missing)").color(t.danger));
}
}
link_menu(app, ui, cid, c, group, actions);
}
EgKind::Media { .. } => {
name_label(app, ui, cid, c, RichText::new(&c.name), actions);
@@ -230,6 +259,35 @@ fn controls(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, list: &[Eg
}
}
/// A property control's "⋯" menu: Add Mirror, Link Selected Property, Unlink.
fn link_menu(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, c: &EgControl, group: Option<u64>, actions: &mut Actions) {
let links: Vec<(u64, u64, String)> = match &c.kind {
EgKind::Property { .. } => essential::linked_props(&app.session.project, cid, c)
.into_iter()
.map(|(l, p)| (l.id.0, p.uid, format!("{} › {}", l.name, l.props.name_path_of(p.uid).unwrap_or_else(|| p.name.clone()))))
.collect(),
_ => vec![],
};
let has_sel = !app.session.state.selected_props.is_empty();
let r = ui.menu_button(RichText::new("⋯").size(10.0), |ui| {
if ui.button("Add Mirror").clicked() {
actions.push(("essential.addMirror".into(), json!({"comp": cid.0, "control": c.id, "group": group})));
ui.close();
}
if ui.add_enabled(has_sel, egui::Button::new("Link Selected Property")).clicked() {
actions.push(("essential.linkProperty".into(), json!({"comp": cid.0, "control": c.id})));
ui.close();
}
for (layer, prop, name) in &links {
if ui.button(format!("Unlink {name}")).clicked() {
actions.push(("essential.unlinkProperty".into(), json!({"comp": cid.0, "control": c.id, "layer": layer, "prop": prop})));
ui.close();
}
}
});
app.auto.add(&format!("essential.control.{}.menu", c.id), r.response.rect, "Mirror and link");
}
/// A control's name; double-click to rename (comments: edit the text).
fn name_label(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, c: &EgControl, text: RichText, actions: &mut Actions) {
let edit_id = egui::Id::new(("eg-rename", c.id));
@@ -445,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, essential::effective_type(c, &p), &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)}),
+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 {
+1
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;
+77 -7
View File
@@ -12,8 +12,8 @@
//! key frame interval, Make Template) open a form that runs the same command.
use effectcraft_engine::project::render_queue::{
AlphaMode, AudioFormat, AudioOutput, Channels, ColorDepth, CurrentOrOff, EffectsMode, FieldRender, OutputFormat, PostRenderAction, ProResProfile, Pulldown,
RESIZE_PRESETS, RenderLog, RenderQuality, RenderQueueItem, RenderStatus, ResizeQuality, SwitchOverride, TimeSpan,
AlphaMode, AudioFormat, AudioOutput, Channels, ColorDepth, CurrentOrOff, EffectsMode, FieldRender, OpusApplication, OutputFormat, PostRenderAction,
ProResProfile, Pulldown, RESIZE_PRESETS, RenderLog, RenderQuality, RenderQueueItem, RenderStatus, ResizeQuality, SwitchOverride, TimeSpan, WebmVideoCodec,
};
use effectcraft_engine::project::render_templates::RenderTemplates;
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
@@ -144,7 +144,7 @@ fn output_menu(it: &RenderQueueItem, available: &[OutputFormat], templates: &Ren
}
v.push(("-".into(), Value::Null));
v.push((mark(o.channels == Channels::Rgb, "Channels: RGB"), json!({"channels": "rgb"})));
if o.format.supports_alpha() {
if o.supports_alpha() {
v.push((mark(o.channels == Channels::Rgba, "Channels: RGB + Alpha"), json!({"channels": "rgba"})));
}
if !o.format.is_audio_only() {
@@ -167,15 +167,35 @@ fn output_menu(it: &RenderQueueItem, available: &[OutputFormat], templates: &Ren
v.push((mark(o.bitrate_kbps == kbps, &format!("Bitrate: {} Mbps", kbps / 1000)), json!({"bitrate": kbps})));
}
}
OutputFormat::JpegSequence | OutputFormat::WebM => {
OutputFormat::Hevc | OutputFormat::Av1 => codec_menu(o, &mut v),
OutputFormat::WebM => {
v.push(("-".into(), Value::Null));
for q in [60u8, 80, 90, 100] {
v.push((mark(o.quality == q && !o.webm_bitrate, &format!("Quality: {q}")), json!({"quality": q, "webmBitrate": false})));
for c in [WebmVideoCodec::Vp9, WebmVideoCodec::Av1] {
v.push((mark(o.webm_codec == c, &format!("Video Codec: {}", c.label())), json!({"webmCodec": c.label().to_ascii_lowercase()})));
}
if o.format == OutputFormat::WebM {
if o.webm_codec == WebmVideoCodec::Av1 {
codec_menu(o, &mut v);
} else {
v.push(("-".into(), Value::Null));
for q in [60u8, 80, 90, 100] {
v.push((mark(o.quality == q && !o.webm_bitrate, &format!("Quality: {q}")), json!({"quality": q, "webmBitrate": false})));
}
v.push((mark(o.webm_bitrate, &format!("Target Bitrate ({} kbps)…", o.bitrate_kbps)), json!({"form": "bitrate"})));
v.push((mark(o.keyframe_interval > 0, "Key Frame Interval…"), json!({"form": "keyframes"})));
}
v.push(("-".into(), Value::Null));
for kbps in [24u32, 32, 64, 96, 128, 192, 256] {
v.push((mark(o.opus_bitrate_kbps == kbps, &format!("Opus Bitrate: {kbps} kbps")), json!({"audioBitrate": kbps})));
}
for (a, k) in [(OpusApplication::Audio, "audio"), (OpusApplication::Voip, "voice")] {
v.push((mark(o.opus_application == a, &format!("Opus Tuning: {}", a.label())), json!({"opusApplication": k})));
}
}
OutputFormat::JpegSequence => {
v.push(("-".into(), Value::Null));
for q in [60u8, 80, 90, 100] {
v.push((mark(o.quality == q, &format!("Quality: {q}")), json!({"quality": q})));
}
}
OutputFormat::Gif => {
v.push(("-".into(), Value::Null));
@@ -236,6 +256,49 @@ fn output_menu(it: &RenderQueueItem, available: &[OutputFormat], templates: &Ren
v
}
/// HEVC / AV1 options: profile, level, rate control (bitrate or constant quality), key frames.
fn codec_menu(o: &effectcraft_engine::project::render_queue::OutputModule, v: &mut Vec<(String, Value)>) {
use effectcraft_engine::project::render_queue::{CodecProfile, RateControlMode, VideoCodecOptions};
let c = &o.codec;
v.push(("-".into(), Value::Null));
for p in CodecProfile::ALL {
v.push((mark(c.profile == p, &format!("Profile: {}", p.label())), json!({"profile": format!("{p:?}").to_ascii_lowercase()})));
}
v.push(("-".into(), Value::Null));
v.push((mark(c.level.is_none(), "Level: Auto"), json!({"level": "auto"})));
// The common HEVC / AV1 levels (every level is reachable over the control channel).
for l in [30u8, 31, 40, 41, 50, 51, 52] {
debug_assert!(VideoCodecOptions::HEVC_LEVELS.contains(&l) && VideoCodecOptions::AV1_LEVELS.contains(&l));
let name = format!("{}.{}", l / 10, l % 10);
v.push((mark(c.level == Some(l), &format!("Level: {name}")), json!({"level": name})));
}
v.push(("-".into(), Value::Null));
for r in [RateControlMode::Bitrate, RateControlMode::Quality] {
v.push((mark(c.rate_control == r, &format!("Rate Control: {}", r.label())), json!({"rateControl": format!("{r:?}").to_ascii_lowercase()})));
}
if c.rate_control == RateControlMode::Bitrate {
for kbps in [1_000u32, 2_000, 5_000, 10_000, 20_000, 40_000] {
let l = if kbps < 2_000 { format!("Bitrate: {kbps} kbps") } else { format!("Bitrate: {} Mbps", kbps / 1000) };
v.push((mark(o.bitrate_kbps == kbps, &l), json!({"bitrate": kbps})));
}
v.push((mark(false, "Bitrate: Custom…"), json!({"form": "codecBitrate"})));
} else {
for q in [40u8, 60, 70, 80, 90, 100] {
v.push((mark(c.quality == q, &format!("Quality: {q}")), json!({"quality": q})));
}
}
v.push(("-".into(), Value::Null));
for k in [0u32, 1, 30, 60, 120, 250] {
let l = match k {
0 => "Key Frames: Auto (2 s)".to_string(),
1 => "Key Frames: Every Frame (all intra)".to_string(),
k => format!("Key Frames: Every {k} Frames"),
};
v.push((mark(o.keyframe_interval == k, &l), json!({"keyframeInterval": k})));
}
v.push((mark(false, "Key Frame Interval…"), json!({"form": "keyframes"})));
}
/// Open the form behind a `{"form": …}` menu entry.
fn open_menu_form(app: &mut EffectcraftApp, it: &RenderQueueItem, form: &str) {
use crate::panels::forms::{Field, form as open};
@@ -297,6 +360,13 @@ fn open_menu_form(app: &mut EffectcraftApp, it: &RenderQueueItem, form: &str) {
json!({"item": id, "webmBitrate": true}),
vec![Field::num("bitrate", "Bitrate (kbps)", o.bitrate_kbps as f64)],
),
"codecBitrate" => open(
app,
"Target Bitrate",
"renderQueue.setOutputModule",
json!({"item": id, "rateControl": "bitrate"}),
vec![Field::num("bitrate", "Bitrate (kbps)", o.bitrate_kbps as f64)],
),
"keyframes" => open(
app,
"Key Frame Interval",
+67 -13
View File
@@ -6,7 +6,8 @@
//! 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::{DrawOp, PathSeg, ScriptWindow, Widget, WidgetKind, WindowKind, layout};
use effectcraft_engine::Services;
use effectcraft_engine::scriptui::{DrawOp, ImageRef, PathSeg, ScriptWindow, Widget, WidgetKind, WindowKind, layout};
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, UiBuilder, pos2, vec2};
use serde_json::{Value, json};
@@ -77,6 +78,7 @@ fn draw_children(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2
fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2, win: u32, w: &Widget, acts: &mut Vec<Act>) {
let t = app.tokens;
let services = app.session.services.clone();
let rect = rect_of(origin, w.bounds);
register(app, win, w, rect);
let id = egui::Id::new(("sui", win, w.id));
@@ -87,20 +89,20 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
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);
paint_draw(ui, rect, &w.draw, &t, &*services);
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);
paint_draw(ui, rect, &w.draw, &t, &*services);
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);
paint_draw(ui, rect, &w.draw, &t, &*services);
}
match w.kind {
WidgetKind::Group | WidgetKind::Tab | WidgetKind::Window | WidgetKind::TabbedPanel => draw_children(app, ui, origin, win, w, acts),
@@ -117,6 +119,9 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
}
WidgetKind::Button | WidgetKind::IconButton => {
let r = ui.add_enabled_ui(w.enabled, |ui| ui.put(rect, egui::Button::new(&w.text))).inner;
if let Some(img) = &w.image {
paint_image(ui, rect.shrink(3.0), img, &*services);
}
if tip(r).clicked() {
acts.push(Act::Click(win, w.id));
}
@@ -236,16 +241,18 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
}
}
WidgetKind::Image | WidgetKind::Unknown => {
ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
if !w.image.as_ref().is_some_and(|img| paint_image(ui, rect, img, &*services)) {
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_draw(ui, rect, &w.draw, &t, &*services);
}
}
/// Paint an onDraw draw list in `rect` (control coordinates → screen).
fn paint_draw(ui: &egui::Ui, rect: Rect, ops: &[DrawOp], t: &Tokens) {
fn paint_draw(ui: &egui::Ui, rect: Rect, ops: &[DrawOp], t: &Tokens, services: &dyn Services) {
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(),
@@ -255,10 +262,19 @@ fn paint_draw(ui: &egui::Ui, rect: Rect, ops: &[DrawOp], t: &Tokens) {
for op in ops {
match op {
DrawOp::Fill { color, path } => {
// Any path shape (concave, self-intersecting, with holes): non-zero winding
// triangles, not egui's convex-only polygon fill.
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));
let mut mesh = egui::Mesh::default();
for tri in PathSeg::fill_triangles(path, 48, false) {
let base = mesh.vertices.len() as u32;
for q in tri {
mesh.colored_vertex(at(q[0], q[1]), c);
}
mesh.add_triangle(base, base + 1, base + 2);
}
if !mesh.is_empty() {
p.add(egui::Shape::mesh(mesh));
}
}
DrawOp::Stroke { color, width, path } => {
@@ -271,15 +287,53 @@ fn paint_draw(ui: &egui::Ui, rect: Rect, ops: &[DrawOp], t: &Tokens) {
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::Image { image, x, y, w, h } => {
let tex = image.as_ref().and_then(|i| image_texture(ui.ctx(), i, services));
let size = match &tex {
Some(tx) if *w <= 0.0 || *h <= 0.0 => tx.size_vec2(),
_ => vec2(*w as f32, *h as f32),
};
let r = Rect::from_min_size(at(*x, *y), size);
match tex {
Some(tx) => {
p.image(tx.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
None => {
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
}
}
}
DrawOp::Os => {}
}
}
}
/// A ScriptUIImage as a texture (decoded once and kept; `None` when it can't be read or
/// decoded).
fn image_texture(ctx: &egui::Context, img: &ImageRef, services: &dyn Services) -> Option<egui::TextureHandle> {
let id = egui::Id::new(("scriptui-image", img));
if let Some(cached) = ctx.data(|d| d.get_temp::<Option<egui::TextureHandle>>(id)) {
return cached;
}
let tex = img.bytes(services).and_then(|b| image::load_from_memory(&b).ok()).map(|d| {
let rgba = d.to_rgba8();
let ci = egui::ColorImage::from_rgba_unmultiplied([rgba.width() as usize, rgba.height() as usize], rgba.as_raw());
ctx.load_texture(format!("scriptui-image-{}", img.name), ci, egui::TextureOptions::LINEAR)
});
ctx.data_mut(|d| d.insert_temp(id, tex.clone()));
tex
}
/// An image control's or icon button's image, fitted (aspect kept) and centred in `r`.
fn paint_image(ui: &egui::Ui, r: Rect, img: &ImageRef, services: &dyn Services) -> bool {
let Some(tex) = image_texture(ui.ctx(), img, services) else { return false };
let s = tex.size_vec2();
let k = (r.width() / s.x.max(1.0)).min(r.height() / s.y.max(1.0)).min(1.0);
let dst = Rect::from_center_size(r.center(), s * k);
ui.painter().with_clip_rect(r.intersect(ui.clip_rect())).image(tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
true
}
/// Checkboxes and radio buttons sit at the left of their (possibly filled) bounds.
fn snug(r: Rect, text: &str) -> Rect {
let w = (text.chars().count() as f32 * 7.0 + 26.0).min(r.width());
+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
}