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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-03 09:54:37 -04:00
co-authored by Claude Opus 5.5
146 changed files with 19761 additions and 676 deletions
+23 -5
View File
@@ -12,7 +12,8 @@
//! - layer parameters have a layer popup and a Source / Masks / Effects & Masks popup; mask
//! ("Path") parameters list the layer's masks;
//! - Curves has its graph editor, Levels its histogram with input/output triangles, Auto
//! Levels a histogram.
//! Levels a histogram; Lumetri's curves, Colorama's output cycle, Glow's colour map and
//! Reshape's correspondence points have visual editors ([`super::fx_editors`]).
use effectcraft_engine::geom::Mat3;
use effectcraft_engine::keyframe::Value;
@@ -40,7 +41,7 @@ fn selected_layer(app: &EffectcraftApp) -> Option<Layer> {
/// An undo-merge key for one gesture on `id`: a new key each time a drag starts, so separate
/// drags are separate undo steps while one drag is one step.
fn gesture_key(ui: &egui::Ui, id: egui::Id, started: bool) -> String {
pub(super) fn gesture_key(ui: &egui::Ui, id: egui::Id, started: bool) -> String {
let kid = id.with("gesture");
let n: u64 = if started {
let n = ui.data(|d| d.get_temp::<u64>(kid)).unwrap_or(0) + 1;
@@ -536,6 +537,15 @@ fn group_rows(
}
if open {
let sub = fx.sub(&sg.match_id);
// A visual editor for the group's hidden parameters (Lumetri curves, …).
let eh = super::fx_editors::inline_height(fx.effect, &sub.path, rect.width());
if eh > 0.0 {
let er = Rect::from_min_size(pos2(rect.min.x, *y), vec2(rect.width(), eh));
*y += eh;
if er.max.y >= rect.min.y && er.min.y <= rect.max.y {
super::fx_editors::inline_editor(app, ui, p, layer, fx.root, sg, fx.effect, &sub.path, ectx, er, actions);
}
}
group_rows(app, ui, p, layer, sg, ectx, rect, y, depth + 1, &sub, actions);
}
}
@@ -603,8 +613,9 @@ fn roto_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, l
// Curves / Levels editors
/// Height of the custom editor shown under an effect's header (0 when none).
fn editor_height(effect: &str, width: f32) -> f32 {
fn editor_height(effect: &str, g: &PropGroup, width: f32) -> f32 {
match effect {
super::fx_editors::GLOW | super::fx_editors::RESHAPE => super::fx_editors::header_height(effect, g, width),
"ec.color.curves" => 34.0 + curves_size(width) + 26.0,
effectcraft_engine::effects::warp_stab::ID => 50.0,
effectcraft_engine::effects::camera_tracker::ID => super::camera_tracker_ui::EDITOR_HEIGHT,
@@ -995,7 +1006,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
item(ui, "Move Down", fi + 1 < fx.len(), "effect.reorder", json!({"layer": lid, "effect": g.uid, "index": fi + 2}));
});
if open {
let eh = editor_height(effect, body.width());
let eh = editor_height(effect, g, body.width());
if eh > 0.0 {
let er = Rect::from_min_size(pos2(body.min.x, y), vec2(body.width(), eh));
y += eh;
@@ -1006,6 +1017,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
effectcraft_engine::effects::camera_tracker::ID => super::camera_tracker_ui::editor(app, ui, &bp, &layer, g, er, &mut actions),
effectcraft_engine::effects::roto::ID => roto_editor(app, ui, &bp, &layer, g, er, &mut actions),
"ec.color.levels" | "ec.color.levelsic" => levels_editor(app, ui, &bp, &layer, g, effect, &ectx, er, &mut actions),
super::fx_editors::GLOW | super::fx_editors::RESHAPE => {
super::fx_editors::header_editor(app, ui, &bp, &layer, g, effect, &ectx, er, &mut actions)
}
_ => histogram_only(app, ui, &bp, g, er),
}
}
@@ -1130,10 +1144,14 @@ pub fn viewer_hook(
} else if app.ui.viewer.show_layer_controls {
// ⊕ controls for the point parameters of the selected effects.
let sel = app.session.state.selected_props.clone();
for layer in ectx.comp.layers.iter().filter(|l| app.session.state.selected_layers.contains(&l.id) && l.is_active_at(ectx.time)) {
let selected = app.session.state.selected_layers.clone();
for layer in ectx.comp.layers.iter().filter(|l| selected.contains(&l.id) && l.is_active_at(ectx.time)) {
let Some(fx) = layer.effects() else { continue };
let m = l2c(ectx, layer);
for g in fx.groups().filter(|g| g.enabled && sel.iter().any(|(l, u)| *l == layer.id && *u == g.uid)) {
if matches!(&g.kind, GroupKind::Effect { effect } if effect == super::fx_editors::RESHAPE) {
super::fx_editors::reshape_overlay(app, ui, painter, map, ectx, layer, g, &m, &mut actions);
}
let pts: Vec<&Property> = g.props().filter(|p| matches!(p.ui, ParamUi::Point)).collect();
let screen: Vec<egui::Pos2> = pts
.iter()
+68 -5
View File
@@ -4,7 +4,8 @@
//! be exposed) and the template name.
//! - The controls: drag a property name from the timeline onto the list (or Animation ▸ Add
//! Property to Essential Graphics); each shows as a text / colour / slider / checkbox / point /
//! angle / dropdown control editing the source property; rename by double-clicking the name;
//! angle / dropdown control editing the source property (Add Selected As: Source Text as a font
//! control, Scale as one uniform slider); rename by double-clicking the name;
//! reorder with ▲▼, remove with ✕; groups and comments from Add Formatting; Media
//! Replacement for the selected footage layer.
//! - **Mirrors and links**: adding a property that is already in the panel adds a *mirror*
@@ -138,6 +139,19 @@ fn body(app: &mut EffectcraftApp, ui: &mut egui::Ui) -> (Actions, Actions) {
}
});
app.auto.add("essential.addFormatting", r.response.rect, "Add Formatting");
// The selected property as a Font control (Source Text) or a uniform Scale slider.
let has_sel = !app.session.state.selected_props.is_empty();
let r = ui.add_enabled_ui(has_sel, |ui| {
ui.menu_button("Add Selected As", |ui| {
for (label, as_type) in [("Font Control", "font"), ("Uniform Scale", "scale")] {
if ui.button(label).clicked() {
actions.push(("essential.addProperty".into(), json!({"as": as_type})));
ui.close();
}
}
})
});
app.auto.add("essential.addAs", r.response.rect, "Add Selected As");
let footage_layer = app.session.active_comp().and_then(|c| {
app.session.state.selected_layers.iter().filter_map(|l| c.layer(*l)).find(|l| matches!(l.source, LayerSource::Footage { .. })).map(|l| l.id.0)
});
@@ -205,7 +219,14 @@ fn controls(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, list: &[Eg
match src {
Some((layer, lt, p)) => {
let v = p.value_at(lt);
if let Some(nv) = value_widget(app, ui, &format!("essential.control.{}.value", c.id), &p, &v) {
if let Some(nv) = value_widget(
app,
ui,
&format!("essential.control.{}.value", c.id),
essential::effective_type(eg.resolve(c.id).unwrap_or(c), &p),
&p,
&v,
) {
actions.push((
"prop.set".into(),
json!({"comp": cid.0, "layer": layer, "prop": p.uid, "value": nv, "merge": format!("eg-{}", c.id)}),
@@ -296,8 +317,8 @@ fn name_label(app: &mut EffectcraftApp, ui: &mut egui::Ui, cid: ItemId, c: &EgCo
}
/// The editor for a control's value; returns the new value (JSON for `prop.set`).
fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, p: &Property, v: &KV) -> Option<Value> {
let ty = essential::control_type(p)?;
fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Option<ControlType>, p: &Property, v: &KV) -> Option<Value> {
let ty = ty?;
let mut out = None;
let rect;
match ty {
@@ -370,6 +391,48 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, p: &Pro
}
rect = r.rect;
}
ControlType::Font => {
// Family (from the installed fonts), style and size; the text stays as it is.
let KV::Text(doc) = v else { return None };
let fams = effectcraft_engine::text::fonts::families();
let mut d = (**doc).clone();
let mut changed = false;
let r1 = egui::ComboBox::from_id_salt(("eg-font", auto)).selected_text(&d.font).width(110.0).show_ui(ui, |ui| {
for (f, _) in &fams {
if ui.selectable_label(*f == d.font, f).clicked() {
d.font = f.clone();
changed = true;
}
}
});
let styles: Vec<String> = fams.iter().find(|(f, _)| *f == d.font).map(|(_, st)| st.clone()).unwrap_or_default();
let r2 = egui::ComboBox::from_id_salt(("eg-style", auto)).selected_text(&d.style).width(70.0).show_ui(ui, |ui| {
for st in &styles {
if ui.selectable_label(*st == d.style, st).clicked() {
d.style = st.clone();
changed = true;
}
}
});
let r3 = ui.add(egui::DragValue::new(&mut d.size).speed(0.5).range(1.0..=2000.0).suffix(" px").max_decimals(1));
app.auto.add(&format!("{auto}.font"), r1.response.rect, "Font");
app.auto.add(&format!("{auto}.style"), r2.response.rect, "Style");
app.auto.add(&format!("{auto}.size"), r3.rect, "Size");
if changed || r3.changed() {
out = serde_json::to_value(&d).ok();
}
rect = r1.response.rect.union(r3.rect);
}
ControlType::Scale => {
// One percentage for every axis.
let comps = v.components();
let mut x = comps.first().copied().unwrap_or(100.0);
let r = ui.add(egui::DragValue::new(&mut x).speed(0.5).suffix("%").max_decimals(1));
if r.changed() {
out = Some(json!(vec![x; comps.len().max(1)]));
}
rect = r.rect;
}
ControlType::Slider | ControlType::Media => {
let mut x = v.as_f64();
let r = match p.ui {
@@ -440,7 +503,7 @@ fn instance(app: &mut EffectcraftApp, ui: &mut egui::Ui, actions: &mut Actions)
}
_ => {
let v = p.value_at(lt);
if let Some(nv) = value_widget(app, ui, &auto, &p, &v) {
if let Some(nv) = value_widget(app, ui, &auto, essential::effective_type(eg.resolve(c.id).unwrap_or(c), &p), &p, &v) {
actions.push((
"essential.set".into(),
json!({"layer": layer.id.0, "control": c.id, "value": nv, "merge": format!("egi-{}-{}", layer.id.0, c.id)}),
+18
View File
@@ -118,6 +118,16 @@ fn is_layered(p: &Value) -> bool {
}
}
/// The import includes a PDF or Illustrator file (which may have several pages).
fn is_pdf(p: &Value) -> bool {
let pdf = |v: &Value| v.as_str().is_some_and(|s| matches!(s.rsplit('.').next().map(str::to_ascii_lowercase).as_deref(), Some("pdf" | "ai")));
match p.get("paths").or(p.get("path")) {
Some(Value::Array(a)) => a.iter().any(pdf),
Some(v) => pdf(v),
None => false,
}
}
pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
let s = &app.session;
let comp = s.active_comp();
@@ -136,6 +146,14 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
1,
)],
),
// PDF / Illustrator files: Import Kind and the page.
"file.import" if !has(p, &["importAs", "page"]) && is_pdf(p) => (
"Import PDF / Illustrator File".into(),
vec![
Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], 0),
Field::num("page", "Page", 1.0),
],
),
// Puppet tool ▸ Record Options.
"puppet.recordOptions" if !has(p, &["speed", "smoothing", "useDraftDeformation", "showMesh"]) => {
let o = &s.state.puppet;
+932
View File
@@ -0,0 +1,932 @@
//! Visual editors for effect parameters stored as hidden or text parameters (Effect Controls):
//!
//! - Lumetri Color ▸ Curves ▸ RGB Curves: master / red / green / blue curve graphs (channel
//! swatches like After Effects'), and ▸ Hue Saturation Curves: Hue vs Sat, Hue vs Hue, Hue vs
//! Luma, Luma vs Sat and Sat vs Sat graphs over their colour gradients (y = ½ is neutral);
//! - Colorama ▸ Output Cycle: the palette wheel, with draggable colour stops (click the ring to
//! add one, Alt-click or drag one off to remove it, select one to pick its colour); editing a
//! preset palette turns it into Custom;
//! - Glow: the colour map (A & B Colors: a preview strip of the gradient over glow brightness;
//! Arbitrary Map: red / green / blue curve graphs and the resulting strip);
//! - Reshape: correspondence point list buttons here, and on the Composition viewer the source
//! and destination mask outlines with draggable correspondence handles ([`reshape_overlay`]).
//!
//! Every edit is a `prop.set` engine command (undoable; one drag = one undo step) and every
//! handle registers an automation id.
use effectcraft_engine::effects::{ColoramaPalette, OffsetCurve};
use effectcraft_engine::geom::Mat3;
use effectcraft_engine::keyframe::Value;
use effectcraft_engine::project::{Layer, PropGroup};
use effectcraft_engine::render::EvalCtx;
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde_json::json;
use super::effect_controls::gesture_key;
use super::fx_widgets as fw;
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
type Actions = Vec<(String, serde_json::Value)>;
pub const LUMETRI: &str = "ec.color.lumetri";
pub const COLORAMA: &str = "ec.color.colorama";
pub const GLOW: &str = "ec.stylize.glow";
pub const RESHAPE: &str = "ec.distort.reshape";
fn str_value(layer: &Layer, ectx: &EvalCtx, g: &PropGroup, id: &str) -> String {
match g.get(id).map(|p| ectx.value(layer, p)) {
Some(Value::Str(s)) => s,
_ => String::new(),
}
}
fn set_str(actions: &mut Actions, layer: &Layer, g: &PropGroup, id: &str, v: String, merge: Option<String>) {
let Some(p) = g.get(id) else { return };
let mut a = json!({"layer": layer.id.0, "prop": p.uid, "value": v});
if let Some(m) = merge {
a["merge"] = json!(m);
}
actions.push(("prop.set".into(), a));
}
/// Register automation ids for a curve's control points (`<prefix>.point.<i>`).
fn register_points(app: &mut EffectcraftApp, prefix: &str, gr: Rect, pts: &[[f32; 2]]) {
for (i, q) in pts.iter().enumerate() {
let s = pos2(gr.min.x + q[0] * gr.width(), gr.max.y - q[1] * gr.height());
app.auto.add(&format!("{prefix}.point.{i}"), Rect::from_center_size(s, vec2(9.0, 9.0)), &format!("Point {}", i + 1));
}
}
/// Small coloured tabs (`names[i]`, swatch `cols[i]`); returns the clicked one.
fn tabs(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
x0: f32,
cy: f32,
cur: usize,
names: &[&str],
cols: &[Color32],
id: &str,
) -> Option<usize> {
let t = app.tokens;
let mut x = x0;
let mut out = None;
for (i, name) in names.iter().enumerate() {
let w = if cols.is_empty() { 16.0 + name.chars().count() as f32 * 6.2 } else { 20.0 };
let r = Rect::from_min_size(pos2(x, cy - 9.0), vec2(w, 18.0));
let resp = ui.interact(r, egui::Id::new((id, i)), Sense::click());
let sel = i == cur;
if sel {
p.rect_filled(r, 3.0, t.row_selected);
} else if resp.hovered() {
p.rect_filled(r, 3.0, t.hover);
}
match cols.get(i) {
Some(c) => {
p.circle_filled(r.center(), 5.5, *c);
if sel {
p.circle_stroke(r.center(), 7.0, Stroke::new(1.0, t.text));
}
}
None => {
p.text(r.center(), Align2::CENTER_CENTER, *name, Tokens::ui(11.0), if sel { t.text } else { t.text_dim });
}
}
app.auto.add(&format!("{id}.{i}"), r, name);
if resp.clicked() {
out = Some(i);
}
resp.on_hover_text(*name);
x += w + 4.0;
}
out
}
fn reset_link(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, r: Rect, id: &str) -> bool {
let t = app.tokens;
let resp = ui.interact(r, egui::Id::new(id), Sense::click());
p.text(r.center(), Align2::CENTER_CENTER, "Reset", Tokens::ui(11.5), if resp.hovered() { t.hot_text } else { t.text_dim });
app.auto.add(id, r, "Reset");
resp.clicked()
}
fn graph_size(width: f32) -> f32 {
(width - 72.0).clamp(120.0, 256.0)
}
// ---------------------------------------------------------------------------------------------
// Inline editors (inside a parameter group)
/// Height of the editor shown at the top of group `path` (spec-id path with a trailing `/`)
/// of `effect` (0 when none).
pub fn inline_height(effect: &str, path: &str, width: f32) -> f32 {
match (effect, path) {
(LUMETRI, "curves/rgbCurves/") => 30.0 + graph_size(width) + 22.0,
(LUMETRI, "curves/hueSaturationCurves/") => 30.0 + graph_size(width) * 0.6 + 34.0,
(COLORAMA, "outputCycle/") => 30.0 + wheel_size(width) + 34.0,
_ => 0.0,
}
}
/// Draw the editor of group `g` (at `path`) in `r`. `root`: the effect's group.
#[allow(clippy::too_many_arguments)]
pub fn inline_editor(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
root: &PropGroup,
g: &PropGroup,
effect: &str,
path: &str,
ectx: &EvalCtx,
r: Rect,
actions: &mut Actions,
) {
match (effect, path) {
(LUMETRI, "curves/rgbCurves/") => rgb_curves(app, ui, p, layer, root, g, ectx, r, actions),
(LUMETRI, "curves/hueSaturationCurves/") => huesat_curves(app, ui, p, layer, root, g, ectx, r, actions),
(COLORAMA, "outputCycle/") => colorama_wheel(app, ui, p, layer, root, g, ectx, r, actions),
_ => {}
}
}
const RGB_CURVES: [(&str, &str); 4] = [("master", "Master"), ("red", "Red"), ("green", "Green"), ("blue", "Blue")];
#[allow(clippy::too_many_arguments)]
fn rgb_curves(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
root: &PropGroup,
g: &PropGroup,
ectx: &EvalCtx,
r: Rect,
actions: &mut Actions,
) {
let t = app.tokens;
let euid = root.uid;
let prefix = format!("effectControls.effect.{euid}.lumetri.rgbCurves");
let ch = app.ui.fx_curve_channel.get(&g.uid).copied().unwrap_or(0).min(3);
let x0 = r.min.x + 38.0;
let cy = r.min.y + 15.0;
let cols = [Color32::from_gray(0xe8), Color32::from_rgb(0xf0, 0x50, 0x50), Color32::from_rgb(0x50, 0xd0, 0x60), Color32::from_rgb(0x50, 0x80, 0xff)];
let names: Vec<&str> = RGB_CURVES.iter().map(|c| c.1).collect();
if let Some(n) = tabs(app, ui, p, x0, cy, ch, &names, &cols, &format!("{prefix}.channel")) {
app.ui.fx_curve_channel.insert(g.uid, n);
}
let id = RGB_CURVES[ch].0;
let cur = fw::CurvePoints::parse(&str_value(layer, ectx, g, id));
let size = graph_size(r.width());
if reset_link(app, ui, p, Rect::from_min_size(pos2(x0 + size - 44.0, cy - 9.0), vec2(44.0, 18.0)), &format!("{prefix}.reset")) {
set_str(actions, layer, g, id, fw::CurvePoints::identity().format(), None);
}
let gr = Rect::from_min_size(pos2(x0, r.min.y + 30.0), vec2(size, size));
let gid = egui::Id::new(("lumetri-rgb", euid, ch));
let (resp, edit) = fw::curves_graph(ui, gr, &cur, ch, false, gid, &t);
app.auto.add(&format!("{prefix}.graph"), gr, "RGB Curves");
register_points(app, &prefix, gr, &cur.0);
let key = gesture_key(ui, gid, resp.drag_started() || resp.clicked());
if let Some(np) = edit.changed {
set_str(actions, layer, g, id, np.format(), Some(key));
}
p.text(pos2(gr.min.x, gr.max.y + 11.0), Align2::LEFT_CENTER, "Click adds a point; drag one off to remove", Tokens::ui(10.5), t.text_faint);
}
/// A hue / saturation curve's points (`x,y` in 0..1, y = ½ neutral), any count (empty = flat).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct OffsetPoints(pub Vec<[f32; 2]>);
impl OffsetPoints {
pub fn parse(s: &str) -> OffsetPoints {
let mut v: Vec<[f32; 2]> = s
.split(|c: char| c.is_whitespace() || c == ';')
.filter_map(|tk| {
let (x, y) = tk.split_once(',')?;
let (x, y) = (x.trim().parse::<f32>().ok()?, y.trim().parse::<f32>().ok()?);
(x.is_finite() && y.is_finite()).then_some([x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)])
})
.collect();
v.sort_by(|a, b| a[0].total_cmp(&b[0]));
OffsetPoints(v)
}
pub fn format(&self) -> String {
let f = |v: f32| {
let s = format!("{v:.4}");
let s = s.trim_end_matches('0').trim_end_matches('.').to_string();
if s.is_empty() || s == "-0" { "0".into() } else { s }
};
self.0.iter().map(|q| format!("{},{}", f(q[0]), f(q[1]))).collect::<Vec<_>>().join(" ")
}
pub fn insert(&mut self, x: f32, y: f32) -> usize {
let i = self.0.partition_point(|q| q[0] < x);
self.0.insert(i, [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)]);
i
}
/// Move point `i`, keeping the order.
pub fn move_point(&mut self, i: usize, x: f32, y: f32) {
let n = self.0.len();
if i >= n {
return;
}
let lo = if i == 0 { 0.0 } else { self.0[i - 1][0] + 0.002 };
let hi = if i + 1 == n { 1.0 } else { self.0[i + 1][0] - 0.002 };
self.0[i] = [x.clamp(lo, hi.max(lo)), y.clamp(0.0, 1.0)];
}
pub fn hit(&self, x: f32, y: f32, r: [f32; 2]) -> Option<usize> {
self.0
.iter()
.enumerate()
.map(|(i, q)| (i, ((q[0] - x) / r[0]).hypot((q[1] - y) / r[1])))
.filter(|(_, d)| *d <= 1.0)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i)
}
}
/// Lumetri's hue / saturation curves: parameter id, tab name, x axis (0 hue, 1 luma, 2 sat),
/// whether x wraps around.
const HUESAT: [(&str, &str, u8, bool); 5] = [
("hueVsSat", "Hue vs Sat", 0, true),
("hueVsHue", "Hue vs Hue", 0, true),
("hueVsLuma", "Hue vs Luma", 0, true),
("lumaVsSat", "Luma vs Sat", 1, false),
("satVsSat", "Sat vs Sat", 2, false),
];
fn hue_color(h: f32) -> Color32 {
let c = egui::ecolor::Hsva::new(h.rem_euclid(1.0), 0.85, 0.9, 1.0);
Color32::from(c)
}
#[allow(clippy::too_many_arguments)]
fn huesat_curves(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
root: &PropGroup,
g: &PropGroup,
ectx: &EvalCtx,
r: Rect,
actions: &mut Actions,
) {
let t = app.tokens;
let euid = root.uid;
let prefix = format!("effectControls.effect.{euid}.lumetri.hueSatCurves");
let k = app.ui.fx_curve_channel.get(&g.uid).copied().unwrap_or(0).min(4);
let x0 = r.min.x + 38.0;
let cy = r.min.y + 15.0;
let names: Vec<&str> = HUESAT.iter().map(|c| c.1).collect();
if let Some(n) = tabs(app, ui, p, x0, cy, k, &names, &[], &format!("{prefix}.curve")) {
app.ui.fx_curve_channel.insert(g.uid, n);
}
let (id, name, axis, periodic) = HUESAT[k];
let cur = OffsetPoints::parse(&str_value(layer, ectx, g, id));
let size = graph_size(r.width());
let gr = Rect::from_min_size(pos2(x0, r.min.y + 30.0), vec2(size, size * 0.6));
// Background: the x axis' colours (hue spectrum, grey ramp) as a band, the neutral line.
p.rect_filled(gr, 0.0, Color32::from_rgb(0x1c, 0x1c, 0x1c));
let n = 48;
for i in 0..n {
let f = (i as f32 + 0.5) / n as f32;
let c = match axis {
0 => hue_color(f),
1 => Color32::from_gray((f * 255.0) as u8),
_ => Color32::from(egui::ecolor::Hsva::new(0.0, f, 0.85, 1.0)),
};
let x = gr.min.x + gr.width() * i as f32 / n as f32;
let band = Rect::from_min_max(pos2(x, gr.max.y - 8.0), pos2(x + gr.width() / n as f32 + 0.5, gr.max.y));
p.rect_filled(band, 0.0, c);
p.rect_filled(Rect::from_min_max(pos2(band.min.x, gr.min.y), pos2(band.max.x, gr.max.y - 8.0)), 0.0, c.gamma_multiply(0.12));
}
let to_s = |x: f32, y: f32| pos2(gr.min.x + x * gr.width(), gr.max.y - y * gr.height());
p.line_segment([to_s(0.0, 0.5), to_s(1.0, 0.5)], Stroke::new(1.0, Color32::from_white_alpha(60)));
p.rect_stroke(gr, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
let curve = OffsetCurve::parse(&cur.format(), periodic);
let line: Vec<Pos2> = (0..=96)
.map(|i| {
let x = i as f32 / 96.0;
to_s(x, 0.5 + curve.as_ref().map(|c| c.at(x)).unwrap_or(0.0))
})
.collect();
p.add(egui::Shape::line(line, Stroke::new(1.5, Color32::from_gray(0xe8))));
let gid = egui::Id::new(("lumetri-hs", euid, k));
let resp = ui.interact(gr.expand(6.0), gid, Sense::click_and_drag());
app.auto.add(&format!("{prefix}.graph"), gr, name);
let drag_id = gid.with("drag");
let dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id));
for (i, q) in cur.0.iter().enumerate() {
let s = to_s(q[0], q[1]);
let hr = Rect::from_center_size(s, vec2(7.0, 7.0));
p.circle_filled(s, 3.5, if dragging == Some(i) { Color32::WHITE } else { Color32::from_rgb(0x1c, 0x1c, 0x1c) });
p.circle_stroke(s, 3.5, Stroke::new(1.2, Color32::WHITE));
app.auto.add(&format!("{prefix}.point.{i}"), hr, &format!("Point {}", i + 1));
}
let to_g = |s: Pos2| [((s.x - gr.min.x) / gr.width()).clamp(0.0, 1.0), ((gr.max.y - s.y) / gr.height()).clamp(0.0, 1.0)];
let hit_r = [7.0 / gr.width(), 7.0 / gr.height()];
let mut changed: Option<OffsetPoints> = None;
let alt = ui.input(|i| i.modifiers.alt);
// One undo step per click or drag.
let key = gesture_key(ui, gid, resp.drag_started() || resp.clicked());
if resp.drag_started()
&& let Some(pt) = ui.input(|i| i.pointer.press_origin())
{
let q = to_g(pt);
let i = match cur.hit(q[0], q[1], hit_r) {
Some(i) => i,
None => {
let mut np = cur.clone();
let i = np.insert(q[0], q[1]);
changed = Some(np);
i
}
};
ui.data_mut(|d| d.insert_temp(drag_id, i));
} else if resp.dragged()
&& let (Some(i), Some(pt)) = (dragging, resp.interact_pointer_pos())
{
let q = to_g(pt);
let mut np = cur.clone();
np.move_point(i, q[0], q[1]);
if np != cur {
changed = Some(np);
}
}
if resp.drag_stopped() {
if let (Some(i), Some(pt)) = (dragging, resp.interact_pointer_pos())
&& !gr.expand(14.0).contains(pt)
&& i < cur.0.len()
{
let mut np = cur.clone();
np.0.remove(i);
changed = Some(np);
}
ui.data_mut(|d| d.remove::<usize>(drag_id));
}
if resp.clicked()
&& let Some(pt) = resp.interact_pointer_pos()
{
let q = to_g(pt);
let mut np = cur.clone();
match cur.hit(q[0], q[1], hit_r) {
Some(i) if alt => {
np.0.remove(i);
}
Some(_) => {}
None => {
np.insert(q[0], q[1]);
}
}
if np != cur {
changed = Some(np);
}
}
if let Some(np) = changed {
set_str(actions, layer, g, id, np.format(), Some(key));
}
if reset_link(app, ui, p, Rect::from_min_size(pos2(gr.max.x - 44.0, gr.max.y + 4.0), vec2(44.0, 18.0)), &format!("{prefix}.reset")) {
set_str(actions, layer, g, id, String::new(), None);
}
p.text(pos2(gr.min.x, gr.max.y + 13.0), Align2::LEFT_CENTER, "Click adds a point (½ height = no change)", Tokens::ui(10.5), t.text_faint);
}
// ---------------------------------------------------------------------------------------------
// Colorama output cycle
fn wheel_size(width: f32) -> f32 {
(width - 90.0).clamp(110.0, 200.0)
}
/// Colorama's palette as stops: (position, straight RGBA).
pub fn format_palette(stops: &[(f32, [f32; 4])]) -> String {
let f = |v: f32| {
let s = format!("{v:.4}");
let s = s.trim_end_matches('0').trim_end_matches('.').to_string();
if s.is_empty() || s == "-0" { "0".into() } else { s }
};
stops
.iter()
.map(|(pos, c)| {
let rgb = format!("{},{},{}", f(c[0]), f(c[1]), f(c[2]));
if (c[3] - 1.0).abs() > 1e-4 { format!("{}:{rgb},{}", f(*pos), f(c[3])) } else { format!("{}:{rgb}", f(*pos)) }
})
.collect::<Vec<_>>()
.join(" ")
}
fn rgba8(c: [f32; 4]) -> Color32 {
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
Color32::from_rgb(b(c[0]), b(c[1]), b(c[2]))
}
/// Phase (0..1, clockwise from the top) of a point around `c`.
fn phase_at(c: Pos2, q: Pos2) -> f32 {
let a = (q.x - c.x).atan2(-(q.y - c.y));
(a / std::f32::consts::TAU).rem_euclid(1.0)
}
fn wheel_point(c: Pos2, radius: f32, phase: f32) -> Pos2 {
let a = phase * std::f32::consts::TAU;
pos2(c.x + radius * a.sin(), c.y - radius * a.cos())
}
#[allow(clippy::too_many_arguments)]
fn colorama_wheel(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
root: &PropGroup,
g: &PropGroup,
ectx: &EvalCtx,
r: Rect,
actions: &mut Actions,
) {
let t = app.tokens;
let euid = root.uid;
let prefix = format!("effectControls.effect.{euid}.colorama");
let preset = g.get("usePresetPalette").map(|pr| ectx.value(layer, pr).as_enum()).unwrap_or(0);
let custom = preset as usize == effectcraft_engine::effects::COLORAMA_PRESETS.len() - 1;
let interp = g.get("interpolatePalette").is_none_or(|pr| ectx.value(layer, pr).as_bool());
let pal = if custom { ColoramaPalette::parse(&str_value(layer, ectx, g, "palette")) } else { None }.unwrap_or_else(|| ColoramaPalette::preset(preset));
let x0 = r.min.x + 38.0;
let label = if custom { "Custom palette" } else { effectcraft_engine::effects::COLORAMA_PRESETS.get(preset as usize).copied().unwrap_or("Preset") };
p.text(pos2(x0, r.min.y + 15.0), Align2::LEFT_CENTER, format!("Output Cycle: {label}"), Tokens::ui(11.5), t.text_dim);
let size = wheel_size(r.width());
let c = pos2(x0 + size / 2.0, r.min.y + 30.0 + size / 2.0);
let (outer, inner) = (size / 2.0 - 8.0, size / 2.0 - 26.0);
// The ring: palette colours around the wheel.
let n = 96;
for i in 0..n {
let (a0, a1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
let col = rgba8(pal.eval((a0 + a1) * 0.5, interp));
let quad = vec![wheel_point(c, inner, a0), wheel_point(c, outer, a0), wheel_point(c, outer, a1 + 0.002), wheel_point(c, inner, a1 + 0.002)];
p.add(egui::Shape::convex_polygon(quad, col, Stroke::NONE));
}
p.circle_stroke(c, outer, Stroke::new(1.0, Color32::from_black_alpha(160)));
p.circle_stroke(c, inner, Stroke::new(1.0, Color32::from_black_alpha(160)));
let wid = egui::Id::new(("colorama-wheel", euid));
let ring = Rect::from_center_size(c, vec2(outer * 2.0 + 40.0, outer * 2.0 + 40.0));
let resp = ui.interact(ring, wid, Sense::click_and_drag());
app.auto.add(&format!("{prefix}.wheel"), ring, "Output Cycle");
let sel_id = wid.with("sel");
let drag_id = wid.with("drag");
let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0);
if sel >= pal.stops.len() {
sel = 0;
}
let dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id));
// Stops: triangles on the outside of the ring.
let mut stop_rects = vec![];
for (i, (ph, col)) in pal.stops.iter().enumerate() {
let tip = wheel_point(c, outer + 2.0, *ph);
let a = wheel_point(c, outer + 12.0, *ph - 0.018);
let b = wheel_point(c, outer + 12.0, *ph + 0.018);
let fill = rgba8(*col);
p.add(egui::Shape::convex_polygon(
vec![tip, a, b],
fill,
Stroke::new(if i == sel || dragging == Some(i) { 1.6 } else { 1.0 }, if i == sel { Color32::WHITE } else { Color32::from_gray(0x80) }),
));
let hr = Rect::from_center_size(wheel_point(c, outer + 8.0, *ph), vec2(14.0, 14.0));
app.auto.add(&format!("{prefix}.stop.{i}"), hr, &format!("Stop {}", i + 1));
stop_rects.push(hr);
}
let hit = |q: Pos2| -> Option<usize> {
stop_rects
.iter()
.enumerate()
.filter(|(_, hr)| hr.expand(3.0).contains(q))
.min_by(|a, b| a.1.center().distance(q).total_cmp(&b.1.center().distance(q)))
.map(|(i, _)| i)
};
let mut new_stops: Option<Vec<(f32, [f32; 4])>> = None;
let alt = ui.input(|i| i.modifiers.alt);
// One undo step per click or drag (a colour pick is its own step).
let key = gesture_key(ui, wid, resp.drag_started() || resp.clicked() || !resp.dragged());
if resp.drag_started()
&& let Some(q) = ui.input(|i| i.pointer.press_origin())
&& let Some(i) = hit(q)
{
ui.data_mut(|d| {
d.insert_temp(drag_id, i);
d.insert_temp(sel_id, i);
});
} else if resp.dragged()
&& let (Some(i), Some(q)) = (dragging, resp.interact_pointer_pos())
&& i < pal.stops.len()
{
let mut st = pal.stops.clone();
st[i].0 = phase_at(c, q);
new_stops = Some(st);
}
if resp.drag_stopped() {
if let (Some(i), Some(q)) = (dragging, resp.interact_pointer_pos())
&& q.distance(c) > outer + 40.0
&& pal.stops.len() > 1
&& i < pal.stops.len()
{
let mut st = pal.stops.clone();
st.remove(i);
new_stops = Some(st);
}
ui.data_mut(|d| d.remove::<usize>(drag_id));
}
if resp.clicked()
&& let Some(q) = resp.interact_pointer_pos()
{
match hit(q) {
Some(i) if alt && pal.stops.len() > 1 => {
let mut st = pal.stops.clone();
st.remove(i);
new_stops = Some(st);
}
Some(i) => {
ui.data_mut(|d| d.insert_temp(sel_id, i));
}
// A click on the ring adds a stop with the colour there (and selects it).
None if (inner - 4.0..=outer + 4.0).contains(&q.distance(c)) => {
let ph = phase_at(c, q);
let mut st = pal.stops.clone();
st.push((ph, pal.eval(ph, interp)));
st.sort_by(|a, b| a.0.total_cmp(&b.0));
let k = st.iter().position(|s| s.0 == ph).unwrap_or(0);
ui.data_mut(|d| d.insert_temp(sel_id, k));
new_stops = Some(st);
}
None => {}
}
}
// The selected stop's colour.
let sr = Rect::from_min_size(pos2(x0, c.y + size / 2.0 + 8.0), vec2(30.0, 16.0));
if let Some((ph, col)) = pal.stops.get(sel).copied() {
let pop = wid.with("color");
if widgets::swatch(ui, sr, col, wid.with("swatch"), &t).clicked() {
widgets::open_popup(ui, pop);
}
app.auto.add(&format!("{prefix}.color"), sr, "Stop color");
p.text(pos2(sr.max.x + 8.0, sr.center().y), Align2::LEFT_CENTER, format!("Stop {} at {:.0}°", sel + 1, ph * 360.0), Tokens::ui(11.0), t.text_dim);
let mut rgb = [col[0], col[1], col[2]];
if crate::header::color_popup(ui, pop, sr.left_bottom(), &mut rgb) {
let mut st = pal.stops.clone();
st[sel].1 = [rgb[0], rgb[1], rgb[2], col[3]];
new_stops = Some(st);
}
}
p.text(
pos2(sr.min.x, sr.max.y + 9.0),
Align2::LEFT_CENTER,
"Click the ring to add a colour; Alt-click a stop (or drag it off) to remove it",
Tokens::ui(10.5),
t.text_faint,
);
if let Some(mut st) = new_stops {
st.sort_by(|a, b| a.0.total_cmp(&b.0));
// Editing a preset makes it the custom palette (both in one undo step).
if !custom && let Some(pr) = g.get("usePresetPalette") {
actions.push((
"prop.set".into(),
json!({"layer": layer.id.0, "prop": pr.uid, "value": effectcraft_engine::effects::COLORAMA_PRESETS.len() - 1, "merge": key}),
));
}
set_str(actions, layer, g, "palette", format_palette(&st), Some(key));
}
}
// ---------------------------------------------------------------------------------------------
// Header editors (under the effect's title)
/// Height of the editor under `effect`'s header (`g`: the instance), 0 when none.
pub fn header_height(effect: &str, g: &PropGroup, width: f32) -> f32 {
match effect {
GLOW => match g.get("colors").map(|p| p.value.as_enum()) {
Some(2) => 30.0 + graph_size(width) + 40.0,
Some(1) => 34.0,
_ => 0.0,
},
RESHAPE => 50.0,
_ => 0.0,
}
}
#[allow(clippy::too_many_arguments)]
pub fn header_editor(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
g: &PropGroup,
effect: &str,
ectx: &EvalCtx,
r: Rect,
actions: &mut Actions,
) {
match effect {
GLOW => glow_map(app, ui, p, layer, g, ectx, r, actions),
RESHAPE => reshape_buttons(app, ui, p, layer, g, ectx, r, actions),
_ => {}
}
}
/// Glow's Arbitrary Map: "red | green | blue" Curves point lists.
pub fn split_map(s: &str) -> [fw::CurvePoints; 3] {
let mut parts = s.split('|');
std::array::from_fn(|_| parts.next().map(fw::CurvePoints::parse).unwrap_or_else(fw::CurvePoints::identity))
}
pub fn join_map(m: &[fw::CurvePoints; 3]) -> String {
m.iter().map(|c| c.format()).collect::<Vec<_>>().join(" | ")
}
#[allow(clippy::too_many_arguments)]
fn glow_map(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, layer: &Layer, g: &PropGroup, ectx: &EvalCtx, r: Rect, actions: &mut Actions) {
let t = app.tokens;
let euid = g.uid;
let prefix = format!("effectControls.effect.{euid}.glow");
let mode = g.get("colors").map(|pr| ectx.value(layer, pr).as_enum()).unwrap_or(0);
let x0 = r.min.x + 38.0;
let num = |id: &str| g.get(id).map(|pr| ectx.value(layer, pr).as_f64()).unwrap_or(0.0);
let looping = g.get("colorLooping").map(|pr| ectx.value(layer, pr).as_enum()).unwrap_or(2);
let (loops, phase, mid) = (num("colorLoops") as f32, (num("colorPhase") / 360.0) as f32, (num("abMidpoint") / 100.0) as f32);
let map = split_map(&str_value(layer, ectx, g, "arbitraryMap"));
let color_at = |l: f32| -> Color32 {
let tt = effectcraft_engine::effects::glow_ab_t(l, looping, loops, phase, mid);
if mode == 2 {
Color32::from_rgb(
(map[0].eval(tt).clamp(0.0, 1.0) * 255.0) as u8,
(map[1].eval(tt).clamp(0.0, 1.0) * 255.0) as u8,
(map[2].eval(tt).clamp(0.0, 1.0) * 255.0) as u8,
)
} else {
let col = |id: &str| match g.get(id).map(|pr| ectx.value(layer, pr)) {
Some(Value::Color(c)) => c,
_ => [0.0; 4],
};
let (a, b) = (col("colorA"), col("colorB"));
let m = |i: usize| ((a[i] + (b[i] - a[i]) * tt as f64).clamp(0.0, 1.0) * 255.0) as u8;
Color32::from_rgb(m(0), m(1), m(2))
}
};
let size = graph_size(r.width());
let strip_y = if mode == 2 { r.min.y + 30.0 + size + 12.0 } else { r.min.y + 8.0 };
let strip = Rect::from_min_size(pos2(x0, strip_y), vec2(size, 12.0));
let n = 64;
for i in 0..n {
let f = (i as f32 + 0.5) / n as f32;
let x = strip.min.x + strip.width() * i as f32 / n as f32;
p.rect_filled(Rect::from_min_max(pos2(x, strip.min.y), pos2(x + strip.width() / n as f32 + 0.5, strip.max.y)), 0.0, color_at(f));
}
p.rect_stroke(strip, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
app.auto.add(&format!("{prefix}.colorMap"), strip, "Glow colour map");
p.text(pos2(strip.max.x + 8.0, strip.center().y), Align2::LEFT_CENTER, "Colour map", Tokens::ui(10.5), t.text_faint);
if mode != 2 {
return;
}
let ch = app.ui.fx_curve_channel.get(&euid).copied().unwrap_or(0).min(2);
let cols = [Color32::from_rgb(0xf0, 0x50, 0x50), Color32::from_rgb(0x50, 0xd0, 0x60), Color32::from_rgb(0x50, 0x80, 0xff)];
if let Some(n) = tabs(app, ui, p, x0, r.min.y + 15.0, ch, &["Red", "Green", "Blue"], &cols, &format!("{prefix}.channel")) {
app.ui.fx_curve_channel.insert(euid, n);
}
if reset_link(app, ui, p, Rect::from_min_size(pos2(x0 + size - 44.0, r.min.y + 6.0), vec2(44.0, 18.0)), &format!("{prefix}.reset")) {
let mut m = map.clone();
m[ch] = fw::CurvePoints::identity();
set_str(actions, layer, g, "arbitraryMap", join_map(&m), None);
}
let gr = Rect::from_min_size(pos2(x0, r.min.y + 30.0), vec2(size, size));
let gid = egui::Id::new(("glow-map", euid, ch));
let (resp, edit) = fw::curves_graph(ui, gr, &map[ch], ch + 1, false, gid, &t);
app.auto.add(&format!("{prefix}.graph"), gr, "Arbitrary Map");
register_points(app, &prefix, gr, &map[ch].0);
let key = gesture_key(ui, gid, resp.drag_started() || resp.clicked());
if let Some(np) = edit.changed {
let mut m = map.clone();
m[ch] = np;
set_str(actions, layer, g, "arbitraryMap", join_map(&m), Some(key));
}
}
// ---------------------------------------------------------------------------------------------
// Reshape
/// Reshape's correspondence pairs (source, destination outline fractions), in stored order.
pub fn parse_pairs(s: &str) -> Vec<(f64, f64)> {
s.split_whitespace()
.filter_map(|tk| {
let (a, b) = tk.split_once(',')?;
Some((a.trim().parse::<f64>().ok()?.rem_euclid(1.0), b.trim().parse::<f64>().ok()?.rem_euclid(1.0)))
})
.collect()
}
pub fn format_pairs(v: &[(f64, f64)]) -> String {
let f = |x: f64| {
let s = format!("{x:.4}");
let s = s.trim_end_matches('0').trim_end_matches('.').to_string();
if s.is_empty() { "0".into() } else { s }
};
v.iter().map(|(a, b)| format!("{},{}", f(*a), f(*b))).collect::<Vec<_>>().join(" ")
}
/// A new pair in the widest gap between the destination fractions (the source fraction
/// interpolated between its neighbours'), or (0, 0) for the first.
pub fn add_pair(v: &[(f64, f64)]) -> (f64, f64) {
if v.is_empty() {
return (0.0, 0.0);
}
let mut s: Vec<(f64, f64)> = v.to_vec();
s.sort_by(|a, b| a.1.total_cmp(&b.1));
let n = s.len();
let (mut best, mut gap) = (0, -1.0);
for i in 0..n {
let g = (s[(i + 1) % n].1 - s[i].1).rem_euclid(1.0);
let g = if n == 1 { 1.0 } else { g };
if g > gap {
gap = g;
best = i;
}
}
let (a, b) = (s[best], s[(best + 1) % n]);
let ds = if n == 1 { 1.0 } else { (b.0 - a.0).rem_euclid(1.0) };
((a.0 + ds * 0.5).rem_euclid(1.0), (a.1 + gap * 0.5).rem_euclid(1.0))
}
#[allow(clippy::too_many_arguments)]
fn reshape_buttons(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
p: &egui::Painter,
layer: &Layer,
g: &PropGroup,
ectx: &EvalCtx,
r: Rect,
actions: &mut Actions,
) {
let t = app.tokens;
let euid = g.uid;
let pairs = parse_pairs(&str_value(layer, ectx, g, "correspondencePoints"));
let b1 = Rect::from_min_size(pos2(r.min.x + 24.0, r.min.y + 4.0), vec2(84.0, 22.0));
let b2 = Rect::from_min_size(pos2(b1.max.x + 8.0, b1.min.y), vec2(96.0, 22.0));
let b3 = Rect::from_min_size(pos2(b2.max.x + 8.0, b1.min.y), vec2(56.0, 22.0));
if widgets::text_button(ui, b1, "Add Point", false, &t, egui::Id::new(("reshape-add", euid))).clicked() {
let mut v = pairs.clone();
v.push(add_pair(&pairs));
set_str(actions, layer, g, "correspondencePoints", format_pairs(&v), None);
}
app.auto.add(&format!("effectControls.effect.{euid}.reshape.add"), b1, "Add Point");
if widgets::text_button(ui, b2, "Remove Point", false, &t, egui::Id::new(("reshape-remove", euid))).clicked() && !pairs.is_empty() {
let mut v = pairs.clone();
v.pop();
set_str(actions, layer, g, "correspondencePoints", format_pairs(&v), None);
}
app.auto.add(&format!("effectControls.effect.{euid}.reshape.remove"), b2, "Remove Point");
if widgets::text_button(ui, b3, "Clear", false, &t, egui::Id::new(("reshape-clear", euid))).clicked() && !pairs.is_empty() {
set_str(actions, layer, g, "correspondencePoints", String::new(), None);
}
app.auto.add(&format!("effectControls.effect.{euid}.reshape.clear"), b3, "Clear");
let status = if pairs.is_empty() {
"Correspondence: automatic (select the effect to edit points on the viewer)".to_string()
} else {
format!("{} correspondence point(s): drag them along the mask outlines in the viewer", pairs.len())
};
p.text(pos2(r.min.x + 24.0, r.min.y + 38.0), Align2::LEFT_CENTER, status, Tokens::ui(11.5), t.text_dim);
}
/// Arc-length fraction (0..1) of the point of a polyline nearest to `q`.
pub fn nearest_fraction(pts: &[[f64; 2]], closed: bool, q: [f64; 2]) -> f64 {
let n = pts.len();
if n < 2 {
return 0.0;
}
let total = effectcraft_engine::effects::util::poly_length(pts, closed).max(1e-9);
let segs = if closed { n } else { n - 1 };
let (mut best, mut best_s, mut acc) = (f64::INFINITY, 0.0, 0.0);
for i in 0..segs {
let (a, b) = (pts[i], pts[(i + 1) % n]);
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let l2 = dx * dx + dy * dy;
let l = l2.sqrt();
let tt = if l2 > 0.0 { (((q[0] - a[0]) * dx + (q[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
let d = (a[0] + dx * tt - q[0]).hypot(a[1] + dy * tt - q[1]);
if d < best {
best = d;
best_s = acc + l * tt;
}
acc += l;
}
(best_s / total).rem_euclid(1.0)
}
/// The Composition viewer's Reshape controls while the effect is selected: the source (yellow)
/// and destination (cyan) mask outlines and each correspondence pair as a line between its two
/// handles; dragging a handle slides it along its outline (one undo step per drag).
#[allow(clippy::too_many_arguments)]
pub fn reshape_overlay(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
painter: &egui::Painter,
map: &super::viewer::ViewerMap,
ectx: &EvalCtx,
layer: &Layer,
g: &PropGroup,
m: &Mat3,
actions: &mut Actions,
) {
let shapes = effectcraft_engine::render::masks::shapes(ectx, layer);
let mask = |id: &str| -> Option<(Vec<[f64; 2]>, bool)> {
let i = g.get(id).map(|pr| ectx.value(layer, pr).as_enum()).unwrap_or(0) as usize;
let s = shapes.get(i.checked_sub(1)?)?;
(s.points.len() >= 2).then(|| (s.points.clone(), s.closed))
};
let (Some(src), Some(dst)) = (mask("sourceMask"), mask("destinationMask")) else { return };
let to_screen = |q: [f64; 2]| map.to_screen(fw::layer_to_comp(m, q));
let outline = |pts: &[[f64; 2]], closed: bool, col: Color32| {
let mut v: Vec<Pos2> = pts.iter().map(|q| to_screen(*q)).collect();
if closed && let Some(f) = v.first().copied() {
v.push(f);
}
painter.add(egui::Shape::dashed_line(&v, Stroke::new(1.0, col), 5.0, 3.0));
};
let (ys, cs) = (Color32::from_rgb(0xff, 0xd8, 0x40), Color32::from_rgb(0x40, 0xd8, 0xff));
outline(&src.0, src.1, ys);
outline(&dst.0, dst.1, cs);
let at = |pts: &[[f64; 2]], closed: bool, f: f64| {
let len = effectcraft_engine::effects::util::poly_length(pts, closed);
effectcraft_engine::effects::util::poly_point_at(pts, closed, f * len).0
};
let raw = match g.get("correspondencePoints").map(|pr| ectx.value(layer, pr)) {
Some(Value::Str(s)) => s,
_ => String::new(),
};
let pairs = parse_pairs(&raw);
let ctx = ui.ctx().clone();
for (i, (fs, fd)) in pairs.iter().enumerate() {
let (ps, pd) = (to_screen(at(&src.0, src.1, *fs)), to_screen(at(&dst.0, dst.1, *fd)));
painter.line_segment([ps, pd], Stroke::new(1.0, Color32::from_white_alpha(150)));
for (end, s, col) in [(0usize, ps, ys), (1, pd, cs)] {
let hr = Rect::from_center_size(s, vec2(12.0, 12.0));
let id = egui::Id::new(("reshape-pt", g.uid, i, end));
let resp = ui.interact(hr, id, Sense::drag());
let hot = resp.hovered() || resp.dragged();
painter.rect_filled(Rect::from_center_size(s, vec2(7.0, 7.0)), 0.0, if hot { Color32::WHITE } else { col });
painter.rect_stroke(Rect::from_center_size(s, vec2(7.0, 7.0)), 0.0, Stroke::new(1.0, Color32::BLACK), StrokeKind::Outside);
let which = if end == 0 { "source" } else { "dest" };
app.auto.add(&format!("viewer.reshape.{}.{which}.{i}", g.uid), hr, &format!("Correspondence point {} ({which})", i + 1));
if hot {
ctx.set_cursor_icon(egui::CursorIcon::Move);
}
if resp.dragged()
&& let Some(pos) = resp.interact_pointer_pos()
&& let Some(lp) = fw::comp_to_layer(m, map.to_comp(pos))
{
let mut v = pairs.clone();
if end == 0 {
v[i].0 = nearest_fraction(&src.0, src.1, lp);
} else {
v[i].1 = nearest_fraction(&dst.0, dst.1, lp);
}
let key = gesture_key(ui, id, resp.drag_started());
if let Some(pr) = g.get("correspondencePoints") {
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": pr.uid, "value": format_pairs(&v), "merge": key})));
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn offset_points_and_palettes_round_trip() {
let p = OffsetPoints::parse("0.5,0.75 0.1,0.5");
assert_eq!(p.0, vec![[0.1, 0.5], [0.5, 0.75]]);
assert_eq!(OffsetPoints::parse(&p.format()), p);
assert!(OffsetPoints::parse("").0.is_empty());
let stops = vec![(0.0, [1.0, 0.0, 0.0, 1.0]), (0.5, [0.0, 0.25, 1.0, 0.5])];
let s = format_palette(&stops);
assert_eq!(s, "0:1,0,0 0.5:0,0.25,1,0.5");
assert_eq!(ColoramaPalette::parse(&s).unwrap().stops, stops);
let m = split_map("0,0 1,0.5 | | 0,1 1,0");
assert_eq!(m[1], fw::CurvePoints::identity());
assert_eq!(split_map(&join_map(&m)), m);
}
#[test]
fn reshape_pairs_and_outline_fractions() {
assert_eq!(parse_pairs("0.25,0 1.5,0.5"), vec![(0.25, 0.0), (0.5, 0.5)]);
assert_eq!(format_pairs(&[(0.25, 0.0), (0.5, 0.125)]), "0.25,0 0.5,0.125");
assert_eq!(add_pair(&[]), (0.0, 0.0));
assert_eq!(add_pair(&[(0.1, 0.0)]), (0.6, 0.5));
let (s, d) = add_pair(&[(0.0, 0.0), (0.2, 0.25)]);
assert!((d - 0.625).abs() < 1e-9 && (s - 0.6).abs() < 1e-9, "{s} {d}");
// A 10×10 square (closed): the point nearest (10, 5) is 3/8 of the way round.
let sq = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]];
assert!((nearest_fraction(&sq, true, [12.0, 5.0]) - 0.375).abs() < 1e-9);
assert!(nearest_fraction(&sq, true, [-1.0, -1.0]).abs() < 1e-9);
}
}
+20 -6
View File
@@ -65,13 +65,13 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let ctx = ui.ctx().clone();
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.panel_bg);
if !mb::available() {
p.text(rect.center(), Align2::CENTER_CENTER, "The Media Browser needs the desktop app (use File ▸ Import here)", Tokens::ui(12.0), t.text_faint);
let Some(b) = app.session.media_browser() else {
p.text(rect.center(), Align2::CENTER_CENTER, "The Media Browser is not available here (use File ▸ Import)", Tokens::ui(12.0), t.text_faint);
app.auto.add("mediaBrowser.unavailable", rect, "Media Browser unavailable");
return;
}
};
let st = app.session.state.media_browser.clone();
let dir = st.folder.clone().unwrap_or_else(mb::home);
let dir = st.folder.clone().unwrap_or_else(|| b.home());
// Listing cached per folder for a second.
let lid = egui::Id::new(("mb-list", dir.clone(), st.importable_only));
let now = ctx.input(|i| i.time);
@@ -79,7 +79,7 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let entries = match listing {
Some((at, l)) if now - at < 1.0 => l,
_ => {
let l = mb::list(&dir, st.importable_only);
let l = b.list(&dir, st.importable_only);
ctx.data_mut(|d| d.insert_temp(lid, (now, l.clone())));
l
}
@@ -104,6 +104,20 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if only != st.importable_only {
kit::exec(app, "mediaBrowser.go", json!({"path": dir, "importableOnly": only}));
}
// The browser's own actions (web: Open Folder…, Add Files…), right-aligned.
let mut ax = rect.max.x - 8.0;
for (id, label) in b.actions().iter().rev() {
let w = 14.0 + label.chars().count() as f32 * 6.4;
ax -= w;
if ax < x + 96.0 {
break;
}
if kit::button(app, ui, Rect::from_min_size(pos2(ax, y), vec2(w, 20.0)), &format!("mediaBrowser.action.{id}"), label, false) {
kit::exec(app, "mediaBrowser.action", json!({"action": id}));
ctx.data_mut(|d| d.remove::<(f64, Result<Vec<mb::Entry>, String>)>(lid));
}
ax -= 6.0;
}
// The path on its own row.
let _ = x;
let py = y + 24.0;
@@ -114,7 +128,7 @@ pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
p.line_segment([side.right_top(), side.right_bottom()], Stroke::new(1.0, t.separator));
p.text(pos2(side.min.x + 10.0, side.min.y + 10.0), Align2::LEFT_CENTER, "Favorites", Tokens::semibold(11.5), t.text_dim);
let mut fy = side.min.y + 22.0;
let mut places: Vec<(String, String)> = vec![("Home".into(), mb::home())];
let mut places: Vec<(String, String)> = b.places();
places.extend(
st.favorites.iter().map(|f| (std::path::Path::new(f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone()), f.clone())),
);
+22 -1
View File
@@ -21,7 +21,16 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let ctx = ui.ctx().clone();
let p = ui.painter().with_clip_rect(rect);
let y = rect.min.y + 12.0;
// The panel scrolls when it is shorter than its controls (the default workspace shows just
// the transport row, as in After Effects).
let scroll_id = egui::Id::new("preview-scroll");
let mut scroll: f32 = ctx.data(|d| d.get_temp(scroll_id).unwrap_or(0.0));
if ui.rect_contains_pointer(rect) {
scroll = (scroll - ui.input(|i| i.smooth_scroll_delta.y)).max(0.0);
}
let panel_clip = ui.clip_rect();
ui.set_clip_rect(rect.intersect(panel_clip));
let y = rect.min.y + 12.0 - scroll;
let bw = 30.0;
let total = bw * 5.0 + 16.0;
let mut x = rect.center().x - total / 2.0;
@@ -223,6 +232,18 @@ pub fn preview(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let status = if app.playback.playing && app.playback.caching { " — caching before playback" } else { "" };
p.text(pos2(bar.min.x, bar.max.y + 12.0), Align2::LEFT_CENTER, format!("{cached} / {total} frames cached{status}"), Tokens::ui(11.0), t.text_faint);
}
ui.set_clip_rect(panel_clip);
let content = yy + 30.0 - (rect.min.y - scroll);
let max = (content - rect.height()).max(0.0);
scroll = scroll.min(max);
ctx.data_mut(|d| d.insert_temp(scroll_id, scroll));
if max > 0.0 {
// A thin scroll indicator on the right edge.
let h = (rect.height() * rect.height() / content).max(12.0);
let top = rect.min.y + (rect.height() - h) * (scroll / max);
p.rect_filled(Rect::from_min_size(pos2(rect.max.x - 5.0, top), vec2(3.0, h)), 1.5, t.text_faint.gamma_multiply(0.6));
app.auto.add("preview.scroll", Rect::from_min_size(pos2(rect.max.x - 6.0, rect.min.y), vec2(6.0, rect.height())), "Preview scroll");
}
}
fn fmt_rate(r: f64) -> String {
+4
View File
@@ -14,6 +14,7 @@ pub mod expr_editor;
pub mod flowchart;
pub mod footage_panel;
pub mod forms;
pub mod fx_editors;
pub mod fx_widgets;
pub mod graph;
pub mod graph_tools;
@@ -28,6 +29,7 @@ pub mod media_panels;
pub mod misc;
pub mod paint_panels;
pub mod panel_kit;
pub mod path_vr_panels;
pub mod precomp;
pub mod project;
pub mod properties;
@@ -117,6 +119,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
PanelKind::Metadata => media_panels::metadata(app, ui, rect),
PanelKind::Progress => media_panels::progress(app, ui, rect),
PanelKind::ContentAwareFill => content_fill_panel::show(app, ui, rect),
PanelKind::CreateNullsFromPaths => path_vr_panels::create_nulls(app, ui, rect),
PanelKind::VrCompEditor => path_vr_panels::vr_editor(app, ui, rect),
}
}
+123
View File
@@ -0,0 +1,123 @@
//! Two built-in panels After Effects ships as scripts, written from scratch as panels:
//!
//! - **Create Nulls From Paths** (Window ▸ Create Nulls From Paths): with a mask or shape path (or
//! a layer that has one) selected, Points Follow Nulls / Nulls Follow Points / Trace Path
//! (`paths.*` commands; Trace Path can loop).
//! - **VR Comp Editor** (Window ▸ VR Comp Editor): the project's VR environments (Composition ▸ VR
//! ▸ Create VR Environment); pick one and edit its 360 view's camera orientation (pan, tilt,
//! roll) with `comp.vr.setView`; open its output.
//!
//! Automation ids: `createNulls.pointsFollowNulls`, `createNulls.nullsFollowPoints`,
//! `createNulls.tracePath`, `createNulls.loop`, `vrEditor.env.<output id>`, `vrEditor.pan`,
//! `vrEditor.tilt`, `vrEditor.roll`, `vrEditor.reset`, `vrEditor.open`.
use egui::{Rect, RichText};
use serde_json::{Value, json};
use crate::EffectcraftApp;
fn run(app: &mut EffectcraftApp, ctx: &egui::Context, actions: Vec<(&str, Value)>) {
for (id, p) in actions {
match crate::menus::invoke(app, ctx, id, p) {
Ok(_) => {}
Err(e) => app.ui.status = e,
}
}
}
fn area(ui: &mut egui::Ui, rect: Rect) -> egui::Ui {
ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink(10.0)).layout(egui::Layout::top_down(egui::Align::Min)))
}
/// Window ▸ Create Nulls From Paths.
pub fn create_nulls(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let ctx = ui.ctx().clone();
let mut ui = area(ui, rect);
let loop_id = egui::Id::new("createNulls.loop");
let mut looping: bool = ui.data(|d| d.get_temp(loop_id)).unwrap_or(false);
let ready = app.session.is_enabled("paths.nullsFollowPoints") && !app.session.state.selected_layers.is_empty();
ui.label(RichText::new("Select a layer with a mask or shape path (or the path property).").color(t.text_dim).small());
ui.add_space(6.0);
let mut acts = vec![];
for (id, label, tip) in [
("paths.pointsFollowNulls", "Points Follow Nulls", "A null on each vertex; move the nulls to reshape the path"),
("paths.nullsFollowPoints", "Nulls Follow Points", "A null on each vertex that follows the (animated) path"),
("paths.tracePath", "Trace Path", "A null moving along the path, driven by its Progress slider"),
] {
let r = ui.add_enabled(ready, egui::Button::new(label).min_size(egui::vec2(170.0, 24.0))).on_hover_text(tip);
let auto = format!("createNulls.{}", id.trim_start_matches("paths."));
app.auto.add(&auto, r.rect, label);
if r.clicked() {
acts.push((id, if id == "paths.tracePath" { json!({"loop": looping}) } else { json!({}) }));
}
}
let r = ui.checkbox(&mut looping, "Loop (Trace Path)");
app.auto.add("createNulls.loop", r.rect, "Loop");
ui.data_mut(|d| d.insert_temp(loop_id, looping));
run(app, &ctx, acts);
}
/// Window ▸ VR Comp Editor.
pub fn vr_editor(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let ctx = ui.ctx().clone();
let mut ui = area(ui, rect);
let envs = app.session.execute("comp.vr.environments", json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default();
if envs.is_empty() {
ui.label(RichText::new("No VR environments yet. Create one with Composition ▸ VR ▸ Create VR Environment…").color(t.text_faint));
return;
}
let sel_id = egui::Id::new("vrEditor.selected");
let active = app.session.state.active_comp.map(|c| c.0);
let mut sel: u64 = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0);
// Default: the active comp's environment, else the first.
let owns = |e: &Value, c: u64| e["output"] == c || e["cubeMap"] == c || e["faces"].as_array().is_some_and(|f| f.iter().any(|x| x["comp"] == c));
if !envs.iter().any(|e| e["output"] == sel) {
sel = active.and_then(|c| envs.iter().find(|e| owns(e, c))).or(envs.first()).and_then(|e| e["output"].as_u64()).unwrap_or(0);
}
let mut acts = vec![];
ui.label(RichText::new("VR Environments").strong());
for e in &envs {
let out = e["output"].as_u64().unwrap_or(0);
let r = ui.selectable_label(out == sel, e["name"].as_str().unwrap_or(""));
app.auto.add(&format!("vrEditor.env.{out}"), r.rect, e["name"].as_str().unwrap_or(""));
if r.clicked() {
sel = out;
}
}
ui.data_mut(|d| d.insert_temp(sel_id, sel));
let Some(env) = envs.iter().find(|e| e["output"] == sel) else { return };
ui.separator();
ui.label(RichText::new("360 View Orientation").strong());
let view: Vec<f64> = env["view"].as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
let signed = |a: f64| if a > 180.0 { a - 360.0 } else { a };
let (mut tilt, mut pan, mut roll) =
(signed(view.first().copied().unwrap_or(0.0)), signed(view.get(1).copied().unwrap_or(0.0)), signed(view.get(2).copied().unwrap_or(0.0)));
let mut changed = false;
for (label, auto, v) in [("Pan", "vrEditor.pan", &mut pan), ("Tilt", "vrEditor.tilt", &mut tilt), ("Roll", "vrEditor.roll", &mut roll)] {
ui.horizontal(|ui| {
ui.label(label);
let r = ui.add(egui::Slider::new(v, -180.0..=180.0).suffix("°").max_decimals(1));
app.auto.add(auto, r.rect, label);
changed |= r.changed();
});
}
if changed {
acts.push(("comp.vr.setView", json!({"comp": sel, "pan": pan, "tilt": tilt, "roll": roll})));
}
ui.horizontal(|ui| {
let r = ui.button("Reset");
app.auto.add("vrEditor.reset", r.rect, "Reset");
if r.clicked() {
acts.push(("comp.vr.setView", json!({"comp": sel, "orientation": [0.0, 0.0, 0.0]})));
}
let r = ui.button("Open Output");
app.auto.add("vrEditor.open", r.rect, "Open Output");
if r.clicked() {
acts.push(("comp.open", json!({"comp": sel})));
}
});
ui.label(RichText::new("All six face cameras turn together; the scene is not changed.").color(t.text_faint).small());
run(app, &ctx, acts);
}
+79 -3
View File
@@ -3,9 +3,10 @@
//! computed; what the user does goes back through the `scriptui.click` / `scriptui.set` /
//! `scriptui.close` commands, which run the script's handlers. Every control registers an
//! automation id `scriptui.<window>.<control>` (and `scriptui.<window>.<name>` when the script
//! named it).
//! named it). Controls with an `onDraw` handler are painted from their draw list; edit texts and
//! sliders send live `changing` updates (onChanging) while typing / dragging.
use effectcraft_engine::scriptui::{ScriptWindow, Widget, WidgetKind, WindowKind, layout};
use effectcraft_engine::scriptui::{DrawOp, PathSeg, ScriptWindow, Widget, WidgetKind, WindowKind, layout};
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, UiBuilder, pos2, vec2};
use serde_json::{Value, json};
@@ -16,6 +17,8 @@ use crate::theme::Tokens;
enum Act {
Click(u32, u32),
Set(u32, u32, Value),
/// A live update (each keystroke / slider step): fires onChanging.
Changing(u32, u32, Value),
Close(u32),
}
@@ -78,6 +81,27 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
register(app, win, w, rect);
let id = egui::Id::new(("sui", win, w.id));
let tip = |r: egui::Response| if w.help_tip.is_empty() { r } else { r.on_hover_text(&w.help_tip) };
// onDraw: the script paints the control. Without drawOSControl() its paint replaces the
// default look (buttons and toggles still respond to clicks); with it, it goes on top.
let custom = w.handlers.iter().any(|h| h == "onDraw");
let os = w.draw.iter().any(|d| matches!(d, DrawOp::Os));
if custom && !os {
if w.kind.is_container() {
paint_draw(ui, rect, &w.draw, &t);
draw_children(app, ui, origin, win, w, acts);
return;
}
let clickable = matches!(w.kind, WidgetKind::Button | WidgetKind::IconButton | WidgetKind::Checkbox | WidgetKind::RadioButton);
let r = ui.interact(rect, id, if clickable && w.enabled { Sense::click() } else { Sense::hover() });
paint_draw(ui, rect, &w.draw, &t);
if tip(r).clicked() && clickable {
acts.push(Act::Click(win, w.id));
}
return;
}
if custom && w.kind.is_container() {
paint_draw(ui, rect, &w.draw, &t);
}
match w.kind {
WidgetKind::Group | WidgetKind::Tab | WidgetKind::Window | WidgetKind::TabbedPanel => draw_children(app, ui, origin, win, w, acts),
WidgetKind::Panel => {
@@ -112,8 +136,16 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
let te = te.id(id).interactive(!w.read_only).font(Tokens::ui(12.0));
let r = ui.add_enabled_ui(w.enabled, |ui| ui.put(rect, te)).inner;
let r = tip(r);
if r.lost_focus() && buf != w.text {
// Live updates already sent the text: the commit still runs onChange.
let dirty_id = id.with("dirty");
let dirty = ui.data(|d| d.get_temp::<bool>(dirty_id)).unwrap_or(false);
if r.lost_focus() && (buf != w.text || dirty) {
acts.push(Act::Set(win, w.id, json!(buf)));
ui.data_mut(|d| d.remove::<bool>(dirty_id));
} else if r.changed() && w.handlers.iter().any(|h| h == "onChanging") {
// Each keystroke reaches the script's onChanging (onChange runs on commit).
acts.push(Act::Changing(win, w.id, json!(buf)));
ui.data_mut(|d| d.insert_temp(dirty_id, true));
}
ui.data_mut(|d| d.insert_temp(id, buf));
}
@@ -145,6 +177,10 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
.inner;
let r = tip(r);
if r.dragged() {
// Live: each step of the drag reaches the script (onChanging).
if r.changed() {
acts.push(Act::Changing(win, w.id, json!(v)));
}
ui.data_mut(|d| d.insert_temp(id, v));
} else {
ui.data_mut(|d| d.remove::<f64>(id));
@@ -203,6 +239,45 @@ fn draw_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, origin: egui::Pos2,
ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
}
}
if custom && !w.kind.is_container() {
paint_draw(ui, rect, &w.draw, &t);
}
}
/// Paint an onDraw draw list in `rect` (control coordinates → screen).
fn paint_draw(ui: &egui::Ui, rect: Rect, ops: &[DrawOp], t: &Tokens) {
let p = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect()));
let col = |c: &Option<[f32; 4]>, theme: Color32| match c {
Some(c) => egui::Rgba::from_rgba_unmultiplied(c[0], c[1], c[2], c[3]).into(),
None => theme,
};
let at = |x: f64, y: f64| rect.min + vec2(x as f32, y as f32);
for op in ops {
match op {
DrawOp::Fill { color, path } => {
let c = col(color, t.field_bg);
for (pts, _) in PathSeg::polylines(path, 48) {
let pts: Vec<egui::Pos2> = pts.iter().map(|q| at(q[0], q[1])).collect();
p.add(egui::Shape::convex_polygon(pts, c, Stroke::NONE));
}
}
DrawOp::Stroke { color, width, path } => {
let s = Stroke::new(*width as f32, col(color, t.text));
for (pts, closed) in PathSeg::polylines(path, 48) {
let pts: Vec<egui::Pos2> = pts.iter().map(|q| at(q[0], q[1])).collect();
p.add(if closed { egui::Shape::closed_line(pts, s) } else { egui::Shape::line(pts, s) });
}
}
DrawOp::Text { text, color, x, y, size, .. } => {
p.text(at(*x, *y), Align2::LEFT_TOP, text, Tokens::ui(*size as f32), col(color, t.text));
}
DrawOp::Image { x, y, w, h } => {
let r = Rect::from_min_size(at(*x, *y), vec2(*w as f32, *h as f32));
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
}
DrawOp::Os => {}
}
}
}
/// Checkboxes and radio buttons sit at the left of their (possibly filled) bounds.
@@ -216,6 +291,7 @@ fn perform(app: &mut EffectcraftApp, ctx: &egui::Context, acts: Vec<Act>) {
let (cmd, p) = match a {
Act::Click(w, id) => ("scriptui.click", json!({"window": w, "widget": id})),
Act::Set(w, id, v) => ("scriptui.set", json!({"window": w, "widget": id, "value": v})),
Act::Changing(w, id, v) => ("scriptui.set", json!({"window": w, "widget": id, "value": v, "changing": true})),
Act::Close(w) => ("scriptui.close", json!({"window": w})),
};
match crate::menus::invoke(app, ctx, cmd, p) {
+23
View File
@@ -256,6 +256,29 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
p.text(pos2(cr.max.x + 6.0, y + 7.0), Align2::LEFT_CENTER, label, Tokens::ui(11.0), t.text_dim);
}
}
// Variable Font Axes: one value per axis of a variable font (`character.axis.<tag>`).
let face = effectcraft_engine::text::resolve(&doc.font, &doc.style).face;
let axes = effectcraft_engine::text::variable::font_axes(face);
if !axes.is_empty() {
y += 26.0;
p.text(pos2(x0, y + 7.0), Align2::LEFT_CENTER, "Variable Font Axes", Tokens::semibold(11.0), t.text_dim);
for (i, a) in axes.iter().enumerate() {
let (col, row) = (i % 2, i / 2);
let fx = x0 + col as f32 * (w / 2.0);
let fy = y + 20.0 + row as f32 * 24.0;
let tag = a.tag.trim_end().to_string();
let v = doc.variations.iter().find(|(t2, _)| t2.trim_end() == tag).map(|(_, v)| *v).unwrap_or(a.default);
p.text(pos2(fx, fy + 9.0), Align2::LEFT_CENTER, &tag, Tokens::semibold(10.5), t.text_dim);
let (r, nv, _) =
widgets::hot_number_at(ui, pos2(fx + 34.0, fy), egui::Id::new(("char-axis", &tag)), v as f64, 1.0, (a.min as f64, a.max as f64), 0, "", &t);
app.auto.add(&format!("character.axis.{tag}"), r, &a.name);
if let Some(nv) = nv
&& enabled
{
actions.push(json!({"variations": {tag.clone(): nv}, "merge": format!("char-axis-{tag}")}));
}
}
}
match &target {
None => {
p.text(pos2(rect.center().x, rect.max.y - 20.0), Align2::CENTER_CENTER, "Select a text layer", Tokens::ui(11.0), t.text_faint);