Merge main into M13.4 (codec completion)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-03 09:24:05 -04:00
co-authored by Claude Opus 5.5
181 changed files with 28985 additions and 1712 deletions
+83 -13
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;
@@ -441,6 +442,37 @@ fn dial_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, layer: &Layer, prop: &P
}
}
/// The effect instance a row belongs to, for conditional visibility
/// ([`effectcraft_engine::effects::catalog::param_shown`]): effect id, the instance's root
/// group and the spec-id path of the group being drawn (`""` or `cameraPosition/`).
struct FxScope<'a> {
effect: &'a str,
root: &'a PropGroup,
path: String,
}
impl<'a> FxScope<'a> {
fn sub(&self, m: &str) -> FxScope<'a> {
FxScope { effect: self.effect, root: self.root, path: format!("{}{m}/", self.path) }
}
/// Whether child `m` of the current group is shown.
fn shown(&self, layer: &Layer, ectx: &EvalCtx, m: &str) -> bool {
let root = self.root;
let value = |id: &str| -> Option<Value> {
let mut g = root;
let mut parts = id.split('/').peekable();
while let Some(part) = parts.next() {
if parts.peek().is_none() {
return g.get(part).map(|p| ectx.value(layer, p));
}
g = g.sub(part)?;
}
None
};
effectcraft_engine::effects::catalog::param_shown(self.effect, &format!("{}{m}", self.path), &value)
}
}
#[allow(clippy::too_many_arguments)]
fn group_rows(
app: &mut EffectcraftApp,
@@ -452,6 +484,7 @@ fn group_rows(
rect: Rect,
y: &mut f32,
depth: usize,
fx: &FxScope,
actions: &mut Actions,
) {
let t = app.tokens;
@@ -459,7 +492,7 @@ fn group_rows(
let r = Rect::from_min_size(pos2(rect.min.x, *y), vec2(rect.width(), ROW));
match c {
Node::Prop(pr) => {
if matches!(pr.ui, ParamUi::Hidden) || pr.three_d_only && !layer.is_3d() {
if matches!(pr.ui, ParamUi::Hidden) || pr.three_d_only && !layer.is_3d() || !fx.shown(layer, ectx, &pr.match_id) {
continue;
}
*y += ROW;
@@ -486,7 +519,7 @@ fn group_rows(
}
Node::Group(sg) => {
// Paint strokes live in the Timeline only (AE's Paint shows Paint on Transparent).
if effectcraft_engine::effects::paint::is_paint(g) {
if effectcraft_engine::effects::paint::is_paint(g) || !fx.shown(layer, ectx, &sg.match_id) {
continue;
}
*y += ROW;
@@ -503,7 +536,17 @@ fn group_rows(
p.text(pos2(tw.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, &sg.name, Tokens::ui(12.0), t.text);
}
if open {
group_rows(app, ui, p, layer, sg, ectx, rect, y, depth + 1, actions);
let sub = fx.sub(&sg.match_id);
// A visual editor for the group's hidden parameters (Lumetri curves, …).
let eh = super::fx_editors::inline_height(fx.effect, &sub.path, rect.width());
if eh > 0.0 {
let er = Rect::from_min_size(pos2(rect.min.x, *y), vec2(rect.width(), eh));
*y += eh;
if er.max.y >= rect.min.y && er.min.y <= rect.max.y {
super::fx_editors::inline_editor(app, ui, p, layer, fx.root, sg, fx.effect, &sub.path, ectx, er, actions);
}
}
group_rows(app, ui, p, layer, sg, ectx, rect, y, depth + 1, &sub, actions);
}
}
}
@@ -570,8 +613,9 @@ fn roto_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, l
// Curves / Levels editors
/// Height of the custom editor shown under an effect's header (0 when none).
fn editor_height(effect: &str, width: f32) -> f32 {
fn editor_height(effect: &str, g: &PropGroup, width: f32) -> f32 {
match effect {
super::fx_editors::GLOW | super::fx_editors::RESHAPE => super::fx_editors::header_height(effect, g, width),
"ec.color.curves" => 34.0 + curves_size(width) + 26.0,
effectcraft_engine::effects::warp_stab::ID => 50.0,
effectcraft_engine::effects::camera_tracker::ID => super::camera_tracker_ui::EDITOR_HEIGHT,
@@ -642,12 +686,24 @@ fn channel_popup(
fn curves_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, layer: &Layer, g: &PropGroup, ectx: &EvalCtx, r: Rect, actions: &mut Actions) {
let t = app.tokens;
let euid = g.uid;
let ch = app.ui.fx_curve_channel.get(&euid).copied().unwrap_or(0).min(4);
// The channel lives in the effect's hidden Channel parameter (UI state for instances
// saved before it existed).
let chan_prop = g.get("channel");
let ch = match chan_prop {
Some(pr) => ectx.value(layer, pr).as_enum() as usize,
None => app.ui.fx_curve_channel.get(&euid).copied().unwrap_or(0),
}
.min(4);
let x0 = r.min.x + 30.0;
let cy = r.min.y + 17.0;
let names: Vec<&str> = fw::CURVE_CHANNELS.iter().map(|c| c.1).collect();
if let Some(n) = channel_popup(app, ui, p, x0, cy, ch, &names, egui::Id::new(("ec-cch", euid)), &format!("effectControls.effect.{euid}.curves.channel")) {
app.ui.fx_curve_channel.insert(euid, n);
match chan_prop {
Some(pr) => actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": pr.uid, "value": n}))),
None => {
app.ui.fx_curve_channel.insert(euid, n);
}
}
}
let pencil = app.ui.fx_curve_pencil.contains(&euid);
let mr = Rect::from_min_size(pos2(x0 + 146.0, cy - 9.0), vec2(56.0, 18.0));
@@ -696,7 +752,7 @@ fn curves_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter,
/// Levels parameter ids for a channel: input black, input white, gamma, output black, output white.
fn levels_ids(effect: &str, ch: usize) -> [String; 5] {
if effect == "ec.color.levels" {
return ["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].map(String::from);
return effectcraft_engine::effects::levels_channel_ids(ch);
}
// Levels (Individual Controls) nests each channel's controls in its twirl-down group.
let pre = fw::LEVELS_CHANNELS[ch.min(4)].0;
@@ -721,7 +777,13 @@ fn levels_editor(
let euid = g.uid;
let x0 = r.min.x + 30.0;
let cy = r.min.y + 17.0;
let ch = if effect == "ec.color.levelsic" { app.ui.fx_levels_channel.get(&euid).copied().unwrap_or(0).min(4) } else { 0 };
// Levels keeps its channel in the Channel parameter; Levels (Individual Controls) shows
// every channel and the popup only picks the histogram.
let ch = if effect == "ec.color.levelsic" {
app.ui.fx_levels_channel.get(&euid).copied().unwrap_or(0).min(4)
} else {
g.get("channel").map(|pr| ectx.value(layer, pr).as_enum() as usize).unwrap_or(0).min(4)
};
if effect == "ec.color.levelsic" {
let names: Vec<&str> = fw::LEVELS_CHANNELS.iter().map(|c| c.1).collect();
if let Some(n) = channel_popup(app, ui, p, x0, cy, ch, &names, egui::Id::new(("ec-lch", euid)), &format!("effectControls.effect.{euid}.levels.channel"))
@@ -944,7 +1006,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
item(ui, "Move Down", fi + 1 < fx.len(), "effect.reorder", json!({"layer": lid, "effect": g.uid, "index": fi + 2}));
});
if open {
let eh = editor_height(effect, body.width());
let eh = editor_height(effect, g, body.width());
if eh > 0.0 {
let er = Rect::from_min_size(pos2(body.min.x, y), vec2(body.width(), eh));
y += eh;
@@ -955,11 +1017,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
effectcraft_engine::effects::camera_tracker::ID => super::camera_tracker_ui::editor(app, ui, &bp, &layer, g, er, &mut actions),
effectcraft_engine::effects::roto::ID => roto_editor(app, ui, &bp, &layer, g, er, &mut actions),
"ec.color.levels" | "ec.color.levelsic" => levels_editor(app, ui, &bp, &layer, g, effect, &ectx, er, &mut actions),
super::fx_editors::GLOW | super::fx_editors::RESHAPE => {
super::fx_editors::header_editor(app, ui, &bp, &layer, g, effect, &ectx, er, &mut actions)
}
_ => histogram_only(app, ui, &bp, g, er),
}
}
}
group_rows(app, ui, &bp, &layer, g, &ectx, body, &mut y, 0, &mut actions);
let scope = FxScope { effect: effect.as_str(), root: g, path: String::new() };
group_rows(app, ui, &bp, &layer, g, &ectx, body, &mut y, 0, &scope, &mut actions);
}
y += 4.0;
}
@@ -1078,10 +1144,14 @@ pub fn viewer_hook(
} else if app.ui.viewer.show_layer_controls {
// ⊕ controls for the point parameters of the selected effects.
let sel = app.session.state.selected_props.clone();
for layer in ectx.comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id) && l.is_active_at(ectx.time)) {
let selected = app.session.state.selected_layers.clone();
for layer in ectx.comp.layers.iter().filter(|l| selected.contains(&l.id) && l.is_active_at(ectx.time)) {
let Some(fx) = layer.effects() else { continue };
let m = l2c(ectx, layer);
for g in fx.groups().filter(|g| g.enabled && sel.iter().any(|(l, u)| *l == layer.id && *u == g.uid)) {
if matches!(&g.kind, GroupKind::Effect { effect } if effect == super::fx_editors::RESHAPE) {
super::fx_editors::reshape_overlay(app, ui, painter, map, ectx, layer, g, &m, &mut actions);
}
let pts: Vec<&Property> = g.props().filter(|p| matches!(p.ui, ParamUi::Point)).collect();
let screen: Vec<egui::Pos2> = pts
.iter()
+61 -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.
//! - **Export Template…** writes an open `.ectemplate`.
@@ -134,6 +135,19 @@ fn body(app: &mut EffectcraftApp, ui: &mut egui::Ui) -> (Actions, Actions) {
}
});
app.auto.add("essential.addFormatting", r.response.rect, "Add Formatting");
// The selected property as a Font control (Source Text) or a uniform Scale slider.
let has_sel = !app.session.state.selected_props.is_empty();
let r = ui.add_enabled_ui(has_sel, |ui| {
ui.menu_button("Add Selected As", |ui| {
for (label, as_type) in [("Font Control", "font"), ("Uniform Scale", "scale")] {
if ui.button(label).clicked() {
actions.push(("essential.addProperty".into(), json!({"as": as_type})));
ui.close();
}
}
})
});
app.auto.add("essential.addAs", r.response.rect, "Add Selected As");
let footage_layer = app.session.active_comp().and_then(|c| {
app.session.state.selected_layers.iter().filter_map(|l| c.layer(*l)).find(|l| matches!(l.source, LayerSource::Footage { .. })).map(|l| l.id.0)
});
@@ -184,7 +198,7 @@ fn controls(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, list: &[Eg
match src {
Some((layer, lt, p)) => {
let v = p.value_at(lt);
if let Some(nv) = value_widget(app, ui, &format!("essential.control.{}.value", c.id), &p, &v) {
if let Some(nv) = value_widget(app, ui, &format!("essential.control.{}.value", c.id), essential::effective_type(c, &p), &p, &v) {
actions.push((
"prop.set".into(),
json!({"comp": cid.0, "layer": layer, "prop": p.uid, "value": nv, "merge": format!("eg-{}", c.id)}),
@@ -245,8 +259,8 @@ fn name_label(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, c: &EgCo
}
/// The editor for a control's value; returns the new value (JSON for `prop.set`).
fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, p: &Property, v: &KV) -> Option<Value> {
let ty = essential::control_type(p)?;
fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Option<ControlType>, p: &Property, v: &KV) -> Option<Value> {
let ty = ty?;
let mut out = None;
let rect;
match ty {
@@ -319,6 +333,48 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, p: &Pro
}
rect = r.rect;
}
ControlType::Font => {
// Family (from the installed fonts), style and size; the text stays as it is.
let KV::Text(doc) = v else { return None };
let fams = effectcraft_engine::text::fonts::families();
let mut d = (**doc).clone();
let mut changed = false;
let r1 = egui::ComboBox::from_id_salt(("eg-font", auto)).selected_text(&d.font).width(110.0).show_ui(ui, |ui| {
for (f, _) in &fams {
if ui.selectable_label(*f == d.font, f).clicked() {
d.font = f.clone();
changed = true;
}
}
});
let styles: Vec<String> = fams.iter().find(|(f, _)| *f == d.font).map(|(_, st)| st.clone()).unwrap_or_default();
let r2 = egui::ComboBox::from_id_salt(("eg-style", auto)).selected_text(&d.style).width(70.0).show_ui(ui, |ui| {
for st in &styles {
if ui.selectable_label(*st == d.style, st).clicked() {
d.style = st.clone();
changed = true;
}
}
});
let r3 = ui.add(egui::DragValue::new(&mut d.size).speed(0.5).range(1.0..=2000.0).suffix(" px").max_decimals(1));
app.auto.add(&format!("{auto}.font"), r1.response.rect, "Font");
app.auto.add(&format!("{auto}.style"), r2.response.rect, "Style");
app.auto.add(&format!("{auto}.size"), r3.rect, "Size");
if changed || r3.changed() {
out = serde_json::to_value(&d).ok();
}
rect = r1.response.rect.union(r3.rect);
}
ControlType::Scale => {
// One percentage for every axis.
let comps = v.components();
let mut x = comps.first().copied().unwrap_or(100.0);
let r = ui.add(egui::DragValue::new(&mut x).speed(0.5).suffix("%").max_decimals(1));
if r.changed() {
out = Some(json!(vec![x; comps.len().max(1)]));
}
rect = r.rect;
}
ControlType::Slider | ControlType::Media => {
let mut x = v.as_f64();
let r = match p.ui {
@@ -389,7 +445,7 @@ fn instance(app: &mut EffectcraftApp, ui: &mut egui::Ui, actions: &mut Actions)
}
_ => {
let v = p.value_at(lt);
if let Some(nv) = value_widget(app, ui, &auto, &p, &v) {
if let Some(nv) = value_widget(app, ui, &auto, essential::effective_type(c, &p), &p, &v) {
actions.push((
"essential.set".into(),
json!({"layer": layer.id.0, "control": c.id, "value": nv, "merge": format!("egi-{}-{}", layer.id.0, c.id)}),
+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())),
);
+248 -33
View File
@@ -13,12 +13,24 @@ pub fn placeholder(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, p: P
ui.painter().text(rect.center(), Align2::CENTER_CENTER, format!("{} — coming soon", p.title()), Tokens::ui(12.0), t.text_faint);
}
/// Preview panel: transport controls and RAM preview options.
/// Preview panel: transport controls, the shortcut whose options are shown, and that
/// shortcut's options (each Preview shortcut keeps its own; see `effectcraft_engine::preview`).
/// Every change runs `playback.settings.set`.
pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
use effectcraft_engine::preview::{PlayFrom, PreviewRange, PreviewResolution, PreviewShortcut};
let t = app.tokens;
let ctx = ui.ctx().clone();
let p = ui.painter().with_clip_rect(rect);
let y = rect.min.y + 12.0;
// The panel scrolls when it is shorter than its controls (the default workspace shows just
// the transport row, as in After Effects).
let scroll_id = egui::Id::new("preview-scroll");
let mut scroll: f32 = ctx.data(|d| d.get_temp(scroll_id).unwrap_or(0.0));
if ui.rect_contains_pointer(rect) {
scroll = (scroll - ui.input(|i| i.smooth_scroll_delta.y)).max(0.0);
}
let panel_clip = ui.clip_rect();
ui.set_clip_rect(rect.intersect(panel_clip));
let y = rect.min.y + 12.0 - scroll;
let bw = 30.0;
let total = bw * 5.0 + 16.0;
let mut x = rect.center().x - total / 2.0;
@@ -29,55 +41,258 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
(Icon::StepFwd, "time.nextFrame", "Next Frame"),
(Icon::Last, "time.end", "Last Frame"),
];
let current = app.session.prefs.preview.current;
for (icon, cmd, tip) in buttons {
let r = Rect::from_min_size(pos2(x, y), vec2(bw, 28.0));
let icon = if cmd == "playback.toggle" && app.playback.playing { Icon::Pause } else { icon };
if widgets::icon_button(ui, r, icon, cmd == "playback.toggle" && app.playback.playing, &t, egui::Id::new(("pv", cmd))).on_hover_text(tip).clicked() {
let _ = crate::menus::invoke(app, &ctx, cmd, json!({}));
// The play button plays with the options of the shortcut shown below.
let params = if cmd == "playback.toggle" { json!({"shortcut": current.id()}) } else { json!({}) };
let _ = crate::menus::invoke(app, &ctx, cmd, params);
}
app.auto.add(&format!("preview.{}", tip.replace([' ', '/'], "")), r, tip);
x += bw + 4.0;
}
let mut yy = y + 44.0;
let row = |p: &egui::Painter, yy: f32, k: &str, v: &str| {
p.text(pos2(rect.min.x + 12.0, yy), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim);
p.text(pos2(rect.min.x + 130.0, yy), Align2::LEFT_CENTER, v, Tokens::ui(12.0), t.text);
let o = app.session.prefs.preview.get(current).clone();
let mut changes: Vec<serde_json::Value> = vec![];
let x0 = rect.min.x + 12.0;
let xv = rect.min.x + 92.0;
let wv = (rect.max.x - xv - 12.0).clamp(80.0, 240.0);
let label = |yy: f32, k: &str| {
p.text(pos2(x0, yy), Align2::LEFT_CENTER, k, Tokens::ui(12.0), t.text_dim);
};
row(&p, yy, "Shortcut", "Spacebar");
yy += 22.0;
let lr = Rect::from_min_size(pos2(rect.min.x + 10.0, yy - 8.0), vec2(16.0, 16.0));
if widgets::checkbox(ui, lr, app.ui.preview_loop, &t, egui::Id::new("pv-loop")).clicked() {
app.ui.preview_loop = !app.ui.preview_loop;
let mut yy = y + 46.0;
// Shortcut.
label(yy, "Shortcut");
let names: Vec<String> = PreviewShortcut::ALL.iter().map(|s| s.label().to_string()).collect();
if let Some(i) = dropdown_row(
app,
ui,
Rect::from_min_size(pos2(xv, yy - 10.0), vec2(wv, 20.0)),
"shortcut",
current.label(),
&names,
PreviewShortcut::ALL.iter().position(|s| *s == current),
) {
let s = PreviewShortcut::ALL[i];
changes.push(json!({"shortcut": s.id(), "current": s.id()}));
}
app.auto.add("preview.loop", lr, "Loop");
p.text(pos2(lr.max.x + 6.0, yy), Align2::LEFT_CENTER, "Loop", Tokens::ui(12.0), t.text);
let ar = Rect::from_min_size(pos2(rect.min.x + 90.0, yy - 8.0), vec2(16.0, 16.0));
if widgets::checkbox(ui, ar, app.ui.preview_audio, &t, egui::Id::new("pv-audio")).clicked() {
let _ = crate::menus::invoke(app, &ctx, "playback.audio", json!({}));
}
app.auto.add("preview.audio", ar, "Include Audio");
p.text(pos2(ar.max.x + 6.0, yy), Align2::LEFT_CENTER, "Include Audio", Tokens::ui(12.0), t.text);
yy += 24.0;
row(&p, yy, "Range", "Work Area Extended By Current Time");
yy += 22.0;
row(&p, yy, "Play From", "Current Time");
yy += 22.0;
let comp = app.session.active_comp().cloned();
row(&p, yy, "Frame Rate", &comp.as_ref().map(|c| format!("({:.2})", c.frame_rate.as_f64())).unwrap_or_default());
yy += 22.0;
row(&p, yy, "Resolution", app.ui.viewer.res.label());
yy += 26.0;
if let Some(c) = comp {
// Include Video / Audio / Overlays / Layer Controls, Loop, Cache Before Playback.
let checks: [(&str, &str, bool); 6] = [
("includeVideo", "Video", o.include_video),
("includeAudio", "Audio", o.include_audio),
("includeOverlays", "Overlays", o.include_overlays),
("includeLayerControls", "Layer Controls", o.include_layer_controls),
("loop", "Loop", o.loop_),
("cacheBeforePlayback", "Cache Before Playback", o.cache_before_playback),
];
for (i, (key, text, on)) in checks.into_iter().enumerate() {
let col = if i < 4 { i % 2 } else { 0 };
let row = if i < 4 { i / 2 } else { i - 2 };
let cx = x0 + col as f32 * 110.0 - 2.0;
let cy = yy + row as f32 * 22.0;
if check_row(app, ui, &p, pos2(cx, cy), key, text, on) {
changes.push(json!({"shortcut": current.id(), key: !on}));
}
}
yy += 4.0 * 22.0 + 6.0;
// Range (and the pre/post-roll of Play Around Current Time).
label(yy, "Range");
let ranges: Vec<String> = PreviewRange::ALL.iter().map(|r| r.label().to_string()).collect();
let range_ids = ["workArea", "workAreaExtended", "entireDuration", "aroundCurrentTime"];
if let Some(i) = dropdown_row(
app,
ui,
Rect::from_min_size(pos2(xv, yy - 10.0), vec2(wv, 20.0)),
"range",
o.range.label(),
&ranges,
PreviewRange::ALL.iter().position(|r| *r == o.range),
) {
changes.push(json!({"shortcut": current.id(), "range": range_ids[i]}));
}
yy += 24.0;
if o.range == PreviewRange::AroundCurrentTime {
for (k, (key, text, v)) in [("preRoll", "Pre-roll", o.pre_roll), ("postRoll", "Post-roll", o.post_roll)].into_iter().enumerate() {
let lx = xv + k as f32 * 100.0;
p.text(pos2(lx, yy), Align2::LEFT_CENTER, text, Tokens::ui(11.5), t.text_dim);
let (r, nv, _) = widgets::hot_number_at(ui, pos2(lx + 52.0, yy - 9.0), egui::Id::new(("pv-roll", key)), v, 0.05, (0.0, 600.0), 1, "s", &t);
app.auto.add(&format!("preview.{key}"), r, text);
if let Some(nv) = nv {
changes.push(json!({"shortcut": current.id(), key: nv}));
}
}
yy += 22.0;
}
// Play From.
label(yy, "Play From");
let froms: Vec<String> = PlayFrom::ALL.iter().map(|f| f.label().to_string()).collect();
if let Some(i) = dropdown_row(
app,
ui,
Rect::from_min_size(pos2(xv, yy - 10.0), vec2(wv, 20.0)),
"playFrom",
o.play_from.label(),
&froms,
PlayFrom::ALL.iter().position(|f| *f == o.play_from),
) {
changes.push(json!({"shortcut": current.id(), "playFrom": (["rangeStart", "currentTime"][i])}));
}
yy += 26.0;
// Frame Rate, Skip, Resolution.
let comp_fps = app.session.active_comp().map(|c| c.frame_rate.as_f64());
label(yy, "Frame Rate");
const RATES: [f64; 12] = [8.0, 10.0, 12.0, 12.5, 15.0, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 60.0];
let auto = format!("({:.2}) Auto", comp_fps.unwrap_or(0.0));
let mut rates = vec![auto.clone()];
rates.extend(RATES.iter().map(|r| fmt_rate(*r)));
let rate_text = o.frame_rate.map(fmt_rate).unwrap_or(auto);
let rate_cur = match o.frame_rate {
None => Some(0),
Some(r) => RATES.iter().position(|x| (x - r).abs() < 1e-3).map(|i| i + 1),
};
if let Some(i) = dropdown_row(app, ui, Rect::from_min_size(pos2(xv, yy - 10.0), vec2(96.0, 20.0)), "frameRate", &rate_text, &rates, rate_cur) {
let v = if i == 0 { json!("auto") } else { json!(RATES[i - 1]) };
changes.push(json!({"shortcut": current.id(), "frameRate": v}));
}
let sx = xv + 106.0;
p.text(pos2(sx, yy), Align2::LEFT_CENTER, "Skip", Tokens::ui(12.0), t.text_dim);
let (r, nv, _) = widgets::hot_number_at(ui, pos2(sx + 30.0, yy - 9.0), egui::Id::new("pv-skip"), o.skip as f64, 0.1, (0.0, 99.0), 0, "", &t);
app.auto.add("preview.skip", r, "Skip");
if let Some(nv) = nv {
changes.push(json!({"shortcut": current.id(), "skip": nv.round() as u32}));
}
yy += 24.0;
label(yy, "Resolution");
let ress: Vec<String> = PreviewResolution::ALL.iter().map(|r| r.label().to_string()).collect();
let res_ids = ["auto", "full", "half", "third", "quarter", "custom"];
if let Some(i) = dropdown_row(
app,
ui,
Rect::from_min_size(pos2(xv, yy - 10.0), vec2(96.0, 20.0)),
"resolution",
o.resolution.label(),
&ress,
PreviewResolution::ALL.iter().position(|r| *r == o.resolution),
) {
changes.push(json!({"shortcut": current.id(), "resolution": res_ids[i]}));
}
if o.resolution == PreviewResolution::Custom {
let (r, nv, _) =
widgets::hot_number_at(ui, pos2(xv + 106.0, yy - 9.0), egui::Id::new("pv-custom-res"), o.custom_resolution as f64, 0.1, (1.0, 40.0), 0, "", &t);
app.auto.add("preview.customResolution", r, "Custom Resolution");
if let Some(nv) = nv {
changes.push(json!({"shortcut": current.id(), "customResolution": nv.round() as u32}));
}
}
yy += 24.0;
if check_row(app, ui, &p, pos2(x0 - 2.0, yy), "fullScreen", "Full Screen", o.full_screen) {
changes.push(json!({"shortcut": current.id(), "fullScreen": !o.full_screen}));
}
yy += 24.0;
// What stopping does.
p.text(pos2(x0, yy), Align2::LEFT_CENTER, format!("On ({}) stop:", current.label()), Tokens::ui(11.5), t.text_dim);
yy += 20.0;
if check_row(app, ui, &p, pos2(x0 - 2.0, yy), "playCachedFrames", "If caching, play cached frames", o.play_cached_frames) {
changes.push(json!({"shortcut": current.id(), "playCachedFrames": !o.play_cached_frames}));
}
yy += 22.0;
if check_row(app, ui, &p, pos2(x0 - 2.0, yy), "moveTimeToPreviewTime", "Move time to preview time", o.move_time_to_preview_time) {
changes.push(json!({"shortcut": current.id(), "moveTimeToPreviewTime": !o.move_time_to_preview_time}));
}
yy += 24.0;
for c in changes {
if let Err(e) = app.session.execute("playback.settings.set", c) {
app.ui.status = e.to_string();
}
}
// Cache bar over the preview range.
if let Some(c) = app.session.active_comp().cloned() {
let cid = app.session.active_comp_id().map(|i| i.0).unwrap_or(0);
let scale = app.viewer_shown.as_ref().map(|(_, k)| k.scale).unwrap_or(1000);
let cached = app.frames.cached_frames(app.session.revision, cid, scale).len();
let total = c.frame_rate.frame_at(c.work_area.1) - c.frame_rate.frame_at(c.work_area.0);
let pl = match app.playback.plan.filter(|_| app.playback.playing) {
Some(pl) => pl,
None => effectcraft_engine::preview::plan(&o, &c, app.session.time()),
};
let cached_set = app.frames.cached_frames(app.session.revision, cid, scale);
let total = pl.frames().count();
let cached = pl.frames().filter(|f| cached_set.binary_search(f).is_ok()).count();
let bar = Rect::from_min_size(pos2(rect.min.x + 12.0, yy), vec2(rect.width() - 24.0, 6.0));
p.rect_filled(bar, 3.0, t.field_bg);
let f = (cached as f32 / total.max(1) as f32).min(1.0);
p.rect_filled(Rect::from_min_size(bar.min, vec2(bar.width() * f, bar.height())), 3.0, t.cache_green);
p.text(pos2(bar.min.x, bar.max.y + 12.0), Align2::LEFT_CENTER, format!("{cached} / {total} frames cached"), Tokens::ui(11.0), t.text_faint);
let status = if app.playback.playing && app.playback.caching { " — caching before playback" } else { "" };
p.text(pos2(bar.min.x, bar.max.y + 12.0), Align2::LEFT_CENTER, format!("{cached} / {total} frames cached{status}"), Tokens::ui(11.0), t.text_faint);
}
ui.set_clip_rect(panel_clip);
let content = yy + 30.0 - (rect.min.y - scroll);
let max = (content - rect.height()).max(0.0);
scroll = scroll.min(max);
ctx.data_mut(|d| d.insert_temp(scroll_id, scroll));
if max > 0.0 {
// A thin scroll indicator on the right edge.
let h = (rect.height() * rect.height() / content).max(12.0);
let top = rect.min.y + (rect.height() - h) * (scroll / max);
p.rect_filled(Rect::from_min_size(pos2(rect.max.x - 5.0, top), vec2(3.0, h)), 1.5, t.text_faint.gamma_multiply(0.6));
app.auto.add("preview.scroll", Rect::from_min_size(pos2(rect.max.x - 6.0, rect.min.y), vec2(6.0, rect.height())), "Preview scroll");
}
}
fn fmt_rate(r: f64) -> String {
if (r - r.round()).abs() < 1e-6 { format!("{r:.0}") } else { format!("{r}") }
}
/// A checkbox with its label; returns true when clicked.
fn check_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, at: egui::Pos2, key: &str, text: &str, on: bool) -> bool {
let t = app.tokens;
let r = Rect::from_min_size(pos2(at.x, at.y - 8.0), vec2(16.0, 16.0));
let clicked = widgets::checkbox(ui, r, on, &t, egui::Id::new(("pv-check", key))).clicked();
p.text(pos2(r.max.x + 5.0, at.y), Align2::LEFT_CENTER, text, Tokens::ui(12.0), t.text);
app.auto.add(&format!("preview.{key}"), r, text);
clicked
}
/// A dropdown with its popup list (automation ids `preview.<key>` and `preview.<key>.<i>`);
/// returns the chosen index.
fn dropdown_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, r: Rect, key: &str, text: &str, items: &[String], current: Option<usize>) -> Option<usize> {
let t = app.tokens;
let pid = egui::Id::new(("pv-pop", key));
if widgets::dropdown(ui, r, text, &t, pid.with("btn")).clicked() {
let open: bool = ui.data(|d| d.get_temp(pid.with("open")).unwrap_or(false));
ui.data_mut(|d| d.insert_temp(pid.with("open"), !open));
}
app.auto.add(&format!("preview.{key}"), r, text);
let open: bool = ui.data(|d| d.get_temp(pid.with("open")).unwrap_or(false));
if !open {
return None;
}
let mut chosen = None;
let area = egui::Area::new(pid.with("area")).order(egui::Order::Foreground).fixed_pos(r.left_bottom() + vec2(0.0, 2.0)).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_min_width(r.width().max(140.0));
for (i, label) in items.iter().enumerate() {
let resp = ui.selectable_label(current == Some(i), label.as_str());
app.auto.add(&format!("preview.{key}.{i}"), resp.rect, label);
if resp.clicked() {
chosen = Some(i);
}
}
});
});
let outside =
ui.input(|i| i.pointer.any_pressed()) && !area.response.contains_pointer() && !r.contains(ui.input(|i| i.pointer.interact_pos()).unwrap_or_default());
if chosen.is_some() || outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
ui.data_mut(|d| d.insert_temp(pid.with("open"), false));
}
chosen
}
/// Audio panel: L/R VU meters (dBFS, 0 to -48) with peak hold and clip indicators, fed by the
+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) {
+136 -73
View File
@@ -7,7 +7,6 @@ use effectcraft_engine::render::EvalCtx;
use egui::{Align2, Rect, Sense, pos2, vec2};
use serde_json::json;
use crate::icons::{self, Icon};
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
@@ -257,6 +256,29 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
p.text(pos2(cr.max.x + 6.0, y + 7.0), Align2::LEFT_CENTER, label, Tokens::ui(11.0), t.text_dim);
}
}
// Variable Font Axes: one value per axis of a variable font (`character.axis.<tag>`).
let face = effectcraft_engine::text::resolve(&doc.font, &doc.style).face;
let axes = effectcraft_engine::text::variable::font_axes(face);
if !axes.is_empty() {
y += 26.0;
p.text(pos2(x0, y + 7.0), Align2::LEFT_CENTER, "Variable Font Axes", Tokens::semibold(11.0), t.text_dim);
for (i, a) in axes.iter().enumerate() {
let (col, row) = (i % 2, i / 2);
let fx = x0 + col as f32 * (w / 2.0);
let fy = y + 20.0 + row as f32 * 24.0;
let tag = a.tag.trim_end().to_string();
let v = doc.variations.iter().find(|(t2, _)| t2.trim_end() == tag).map(|(_, v)| *v).unwrap_or(a.default);
p.text(pos2(fx, fy + 9.0), Align2::LEFT_CENTER, &tag, Tokens::semibold(10.5), t.text_dim);
let (r, nv, _) =
widgets::hot_number_at(ui, pos2(fx + 34.0, fy), egui::Id::new(("char-axis", &tag)), v as f64, 1.0, (a.min as f64, a.max as f64), 0, "", &t);
app.auto.add(&format!("character.axis.{tag}"), r, &a.name);
if let Some(nv) = nv
&& enabled
{
actions.push(json!({"variations": {tag.clone(): nv}, "merge": format!("char-axis-{tag}")}));
}
}
}
match &target {
None => {
p.text(pos2(rect.center().x, rect.max.y - 20.0), Align2::CENTER_CENTER, "Select a text layer", Tokens::ui(11.0), t.text_faint);
@@ -568,90 +590,131 @@ fn font_popup(app: &EffectcraftApp, ui: &mut egui::Ui, id: egui::Id, pos: egui::
chosen
}
/// Align panel: align selected layers to the composition (or to the selection).
/// Align panel: Align Layers to Selection / Composition, the six align buttons and the six
/// Distribute Layers buttons. Buttons run `layer.align {edge, to}` and `layer.distribute
/// {mode}` on the selected layers.
pub fn align(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
let x0 = rect.min.x + 10.0;
let y = rect.min.y + 10.0;
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Align Layers to: Composition", Tokens::ui(11.5), t.text_dim);
let mut y = rect.min.y + 10.0;
p.text(pos2(x0, y + 10.0), Align2::LEFT_CENTER, "Align Layers to:", Tokens::ui(11.5), t.text_dim);
let dr = Rect::from_min_size(pos2(x0 + 100.0, y), vec2(110.0, 20.0));
let to_sel = app.ui.align_to_selection;
let pid = egui::Id::new("align-to-pop");
if widgets::dropdown(ui, dr, if to_sel { "Selection" } else { "Composition" }, &t, pid.with("btn")).clicked() {
widgets::open_popup(ui, pid);
}
app.auto.add("align.to", dr, if to_sel { "Selection" } else { "Composition" });
if let Some(i) =
widgets::popup_menu(ui, pid, dr.left_bottom() + vec2(0.0, 2.0), &["Selection".to_string(), "Composition".to_string()], Some(if to_sel { 0 } else { 1 }))
{
app.ui.align_to_selection = i == 0;
}
y += 28.0;
let ops = ["left", "hcenter", "right", "top", "vcenter", "bottom"];
for (i, op) in ops.iter().enumerate() {
let r = Rect::from_min_size(pos2(x0 + i as f32 * 34.0 + if i >= 3 { 12.0 } else { 0.0 }, y + 24.0), vec2(30.0, 28.0));
let resp = ui.interact(r, egui::Id::new(("align", *op)), Sense::click());
p.rect_filled(r, 3.0, if resp.hovered() { t.hover } else { t.field_bg });
// Glyph: a bar (alignment edge) and two boxes.
let c = r.center();
let st = egui::Stroke::new(1.3, t.text);
match *op {
"left" | "hcenter" | "right" => {
let ex = match *op {
"left" => r.min.x + 7.0,
"right" => r.max.x - 7.0,
_ => c.x,
};
p.line_segment([pos2(ex, r.min.y + 5.0), pos2(ex, r.max.y - 5.0)], st);
let off = |w: f32| match *op {
"left" => ex,
"right" => ex - w,
_ => ex - w / 2.0,
};
p.rect_filled(Rect::from_min_size(pos2(off(14.0), c.y - 7.0), vec2(14.0, 5.0)), 1.0, t.text_dim);
p.rect_filled(Rect::from_min_size(pos2(off(9.0), c.y + 2.0), vec2(9.0, 5.0)), 1.0, t.text_dim);
}
_ => {
let ey = match *op {
"top" => r.min.y + 6.0,
"bottom" => r.max.y - 6.0,
_ => c.y,
};
p.line_segment([pos2(r.min.x + 5.0, ey), pos2(r.max.x - 5.0, ey)], st);
let off = |h: f32| match *op {
"top" => ey,
"bottom" => ey - h,
_ => ey - h / 2.0,
};
p.rect_filled(Rect::from_min_size(pos2(c.x - 8.0, off(14.0)), vec2(5.0, 14.0)), 1.0, t.text_dim);
p.rect_filled(Rect::from_min_size(pos2(c.x + 3.0, off(9.0)), vec2(5.0, 9.0)), 1.0, t.text_dim);
let mut run: Option<(&str, &str)> = None;
for (row, kind) in ["align", "distribute"].into_iter().enumerate() {
if row == 1 {
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Distribute Layers:", Tokens::ui(11.5), t.text_dim);
y += 20.0;
}
for (i, op) in ops.iter().enumerate() {
let r = Rect::from_min_size(pos2(x0 + i as f32 * 34.0 + if i >= 3 { 12.0 } else { 0.0 }, y), vec2(30.0, 28.0));
let resp = ui.interact(r, egui::Id::new((kind, *op)), Sense::click());
p.rect_filled(r, 3.0, if resp.hovered() { t.hover } else { t.field_bg });
align_glyph(&p, r, op, row == 1, &t);
let tip = align_tip(kind, op);
app.auto.add(&format!("{kind}.{op}"), r, &tip);
if resp.on_hover_text(tip).clicked() {
run = Some((kind, op));
}
}
app.auto.add(&format!("align.{op}"), r, op);
if resp.clicked() {
align_layers(app, op);
y += 34.0;
}
if let Some((kind, op)) = run {
let r = if kind == "align" {
let to = if app.ui.align_to_selection { "selection" } else { "composition" };
app.session.execute("layer.align", json!({"edge": op, "to": to}))
} else {
app.session.execute("layer.distribute", json!({"mode": op}))
};
if let Err(e) = r {
app.ui.status = e.to_string();
}
}
let _ = icons::paint;
let _ = Icon::Grid;
}
/// Move selected layers so their content bounds align to the comp.
pub fn align_layers(app: &mut EffectcraftApp, op: &str) {
let Some(cid) = app.session.active_comp_id() else { return };
let Some(comp) = app.session.project.comp(cid).cloned() else { return };
let time = app.session.time();
let mut moves = vec![];
{
let ectx = EvalCtx { project: &app.session.project, comp_id: cid, comp: &comp, time, expr: app.session.expr.as_deref(), footage: None };
for l in comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id)) {
let Some(b) = effectcraft_engine::render::content_bounds(&ectx, l) else { continue };
let (m, _) = ectx.layer_to_comp(l);
let pts = [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]].map(|p| m.apply(effectcraft_engine::geom::vec2(p[0], p[1])));
let (x0, x1) = (pts.iter().map(|p| p.x).fold(f64::INFINITY, f64::min), pts.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max));
let (y0, y1) = (pts.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), pts.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max));
let (cw, ch) = (comp.width as f64, comp.height as f64);
let (dx, dy) = match op {
"left" => (-x0, 0.0),
"right" => (cw - x1, 0.0),
"hcenter" => (cw / 2.0 - (x0 + x1) / 2.0, 0.0),
"top" => (0.0, -y0),
"bottom" => (0.0, ch - y1),
_ => (0.0, ch / 2.0 - (y0 + y1) / 2.0),
};
let pos = l.transform().map(|tr| ectx.v3(l, tr, "position", [0.0; 3])).unwrap_or([0.0; 3]);
moves.push((l.id.0, [pos[0] + dx, pos[1] + dy, pos[2]]));
fn align_tip(kind: &str, op: &str) -> String {
let what = match op {
"left" => "Left",
"hcenter" => "Horizontal Center",
"right" => "Right",
"top" => "Top",
"vcenter" => "Vertical Center",
_ => "Bottom",
};
if kind == "align" { format!("Align {what}") } else { format!("Distribute {what}") }
}
/// Button glyph: the alignment edge as a line and two boxes (distribute: three boxes spread,
/// the line through each).
fn align_glyph(p: &egui::Painter, r: Rect, op: &str, distribute: bool, t: &Tokens) {
let c = r.center();
let st = egui::Stroke::new(1.3, t.text);
let horizontal = matches!(op, "left" | "hcenter" | "right");
if distribute {
for k in 0..3 {
let f = (k as f32 - 1.0) * 7.0;
if horizontal {
let bx = c.x + f;
let ex = match op {
"left" => bx - 2.5,
"right" => bx + 2.5,
_ => bx,
};
p.rect_filled(Rect::from_center_size(pos2(bx, c.y), vec2(5.0, 10.0 + k as f32 * 2.0)), 1.0, t.text_dim);
p.line_segment([pos2(ex, r.min.y + 5.0), pos2(ex, r.max.y - 5.0)], st);
} else {
let by = c.y + f;
let ey = match op {
"top" => by - 2.5,
"bottom" => by + 2.5,
_ => by,
};
p.rect_filled(Rect::from_center_size(pos2(c.x, by), vec2(10.0 + k as f32 * 2.0, 5.0)), 1.0, t.text_dim);
p.line_segment([pos2(r.min.x + 5.0, ey), pos2(r.max.x - 5.0, ey)], st);
}
}
return;
}
for (id, v) in moves {
let _ = app.session.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": v}));
if horizontal {
let ex = match op {
"left" => r.min.x + 7.0,
"right" => r.max.x - 7.0,
_ => c.x,
};
p.line_segment([pos2(ex, r.min.y + 5.0), pos2(ex, r.max.y - 5.0)], st);
let off = |w: f32| match op {
"left" => ex,
"right" => ex - w,
_ => ex - w / 2.0,
};
p.rect_filled(Rect::from_min_size(pos2(off(14.0), c.y - 7.0), vec2(14.0, 5.0)), 1.0, t.text_dim);
p.rect_filled(Rect::from_min_size(pos2(off(9.0), c.y + 2.0), vec2(9.0, 5.0)), 1.0, t.text_dim);
} else {
let ey = match op {
"top" => r.min.y + 6.0,
"bottom" => r.max.y - 6.0,
_ => c.y,
};
p.line_segment([pos2(r.min.x + 5.0, ey), pos2(r.max.x - 5.0, ey)], st);
let off = |h: f32| match op {
"top" => ey,
"bottom" => ey - h,
_ => ey - h / 2.0,
};
p.rect_filled(Rect::from_min_size(pos2(c.x - 8.0, off(14.0)), vec2(5.0, 14.0)), 1.0, t.text_dim);
p.rect_filled(Rect::from_min_size(pos2(c.x + 3.0, off(9.0)), vec2(5.0, 9.0)), 1.0, t.text_dim);
}
}
+6 -5
View File
@@ -519,7 +519,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.auto.add("viewer.area", area, "Composition viewer");
// Guides.
if app.ui.viewer.safe_margins {
let overlays = app.overlays_visible();
if overlays && app.ui.viewer.safe_margins {
let g = &app.session.prefs.grids;
let (act, title) = (1.0 - g.action_safe as f32 / 100.0, 1.0 - g.title_safe as f32 / 100.0);
for (k, a) in [(act, 120u8), (title, 160)] {
@@ -530,7 +531,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
painter.line_segment([c - vec2(10.0, 0.0), c + vec2(10.0, 0.0)], Stroke::new(1.0, Color32::from_white_alpha(140)));
painter.line_segment([c - vec2(0.0, 10.0), c + vec2(0.0, 10.0)], Stroke::new(1.0, Color32::from_white_alpha(140)));
}
if app.ui.viewer.grid {
if overlays && app.ui.viewer.grid {
// Settings ▸ Grids & Guides: gridline spacing, subdivisions and colour.
let g = &app.session.prefs.grids;
let [r, gg, b] = hex_rgb(&g.grid_color).unwrap_or([120, 160, 255]);
@@ -567,7 +568,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
vt::proportional_grid(app, &painter, comp_rect);
// Comp guides (View ▸ Show Guides) and the region of interest.
if app.ui.viewer.guides {
if overlays && app.ui.viewer.guides {
let [r, gg, b] = hex_rgb(&app.session.prefs.grids.guide_color).unwrap_or([0x3c, 0xc8, 0xf0]);
let stroke = Stroke::new(1.0, Color32::from_rgb(r, gg, b));
// Settings ▸ Grids & Guides ▸ Guide Style.
@@ -625,7 +626,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if finish || app.ui.tool != Tool::Selection {
ov::end_free_transform(&ctx);
}
if app.ui.viewer.show_layer_controls {
if app.layer_controls_visible() {
// Settings ▸ General ▸ Path Point and Handle Size; Appearance ▸ Use Label Color for
// Layer Handles and Paths.
let hs = app.session.prefs.general.path_point_size as f32 + 2.0;
@@ -748,7 +749,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
// Track points of the current track (Tracker panel) on its layer, while that layer is selected.
let mut track_hits = vec![];
let track_cur = super::tracker::viewer_track(app);
if app.ui.viewer.show_layer_controls
if app.layer_controls_visible()
&& let Some((tl, tu)) = track_cur
&& selected.contains(&tl)
&& let Some(layer) = comp.layer(tl)