Merge origin/main into the outside pull request batch (M8)

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
Tanish Manku committed 2026-11-17 16:02:56 -07:00
commit 68898eb549
35 files changed
+2225 -250

No files matched your search

+20
View File
@@ -37,6 +37,26 @@
scene's artwork on the stage (fixes #305).
* **Camera** (Kushagra Kumar): with the camera layer hidden, Preview Through Camera no longer
blocks drawing on the stage (fixes #126).
* **Filters: animated colours and switches, built-in presets, and filters on text** (ADR 0099,
M5).
* **Filter colours animate** in a motion tween: a glow's or shadow's colour, a bevel's shadow
and highlight, and each stop of a gradient filter's ramp. The Motion Editor has a row per
colour with a swatch (pick a colour to key it at the playhead); click the row for its Red,
Green, Blue and Alpha curves. Colours change the way a Tint does.
* **Quality, Inner, Knockout and Hide object animate as steps**: a key holds until the next
one, so a switch turns on exactly at its frame.
* Editing a filter's colour or a switch in Properties inside a tween keys it, like its numbers.
* **Classic tweens between different filter lists** now fade: a filter only one keyframe has
fades in or out, and the ones both have change from one to the other (before, the first
keyframe's filters held).
* **Built-in filter presets**: Soft Shadow, Hard Shadow, Neon Glow, Outline, Emboss, Engrave,
Soft Focus and Greyscale. They can't be deleted; untick one under **Built-in Presets** to
take it off the menu (`filter.preset_hide`).
* **Filters on text**: static, dynamic and input text take filters in Properties as movie
clips do, on the stage, in Test Movie and in every export, and they tween. Animate files'
filters on text fields now come in instead of being reported.
* Headless: `motion.set_key {property: "filter.0.color", color: "#ff3ea5"}` keys a whole
colour; channels and switches are `filter.0.color_red`, `filter.0.knockout` and so on.
* **Mixed armatures: symbols and shapes in one armature** (ADR 0098, M7).
* A body drawn as a shape that bends can carry a head, hands or props that are symbol
+21 -5
View File
@@ -372,8 +372,9 @@ fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(an
};
ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge, warp })
}
// An instance tweens its filters when both keyframes have the same kinds in the same
// order (Animate's rule); otherwise they hold.
// An instance tweens its filters: pairwise when both keyframes have the same kinds in
// the same order, else as Animate pairs them, a filter without a partner fading in or
// out (ADR 0099).
(ElementKind::Symbol { symbol: s1, filters: fa, .. }, ElementKind::Symbol { symbol: s2, filters: fb, .. }) if s1 == s2 => {
let mut k = a.kind.clone();
if let (ElementKind::Symbol { filters, .. }, Some(lerped)) = (&mut k, crate::filter::lerp_filters(fa, fb, pr.filters)) {
@@ -381,8 +382,12 @@ fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(an
}
k
}
// Text tweens its placement and colour effect; the words stay the first keyframe's.
(ElementKind::Text(_), ElementKind::Text(_)) => a.kind.clone(),
// Text tweens its placement, colour effect and filters (ADR 0099); the words stay the
// first keyframe's.
(ElementKind::Text(ta), ElementKind::Text(tb)) => match crate::filter::lerp_filters(&ta.filters, &tb.filters, pr.filters) {
Some(filters) => ElementKind::Text(Arc::new(crate::TextBlock { filters, ..(**ta).clone() })),
None => a.kind.clone(),
},
(ElementKind::Camera, ElementKind::Camera) => ElementKind::Camera,
// A group tweens its placement and colour effect, and its members pair by order, layer by
// layer, tweening as they would on their own (ADR 0073); a member without a partner holds.
@@ -646,6 +651,17 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out:
});
}
ElementKind::Text(t) => {
// Text with filters draws on its own, as a movie clip does (ADR 0099): its items
// composite in a group the filters run on, and the group fades at the text's alpha.
// (Mask artwork takes neither.)
let (color, group) = if masks.is_none() && crate::filter::any_active(&t.filters) {
let gid = out.groups.len() as u32;
out.groups.push(Group { parent: cx.group, alpha: fx.alpha_factor().unwrap_or(1.0), blend: crate::BlendMode::Normal, filters: crate::filter::active(&t.filters).into(), clip });
let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx };
(cx.color.concat(&inner), Some(gid))
} else {
(color, cx.group)
};
let item = |path: Arc<Path>, transform: Affine, fill: Option<Paint>, stroke: Option<Stroke>, clip: Option<u32>, masks: Option<u32>| DisplayItem {
path,
transform,
@@ -659,7 +675,7 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out:
clip,
masks,
guide,
group: cx.group,
group,
image: None,
smooth: true,
warp: None,
+126 -3
View File
@@ -576,12 +576,135 @@ fn instance_filters_tween_when_they_pair_up() {
_ => Vec::new(),
};
assert_eq!(filters(5)[0], blur(40.0 * 0.25).into(), "eased by the filters group's ease");
// Lists that don't pair up hold the first keyframe's.
let e = |f: Filter| crate::FilterEntry::from(f);
assert_eq!(crate::filter::lerp_filters(&[e(blur(1.0))], &[e(Filter::new("glow").unwrap())], 0.5), None);
assert_eq!(crate::filter::lerp_filters(&[e(blur(1.0))], &[e(blur(1.0)), e(blur(2.0))], 0.5), None);
// A switched-off filter still pairs up (and stays off, as the first keyframe has it).
let off = crate::FilterEntry { filter: blur(0.0), enabled: false };
let got = crate::filter::lerp_filters(std::slice::from_ref(&off), &[e(blur(10.0))], 0.5).unwrap();
assert_eq!(got, vec![crate::FilterEntry { filter: blur(5.0), enabled: false }]);
assert_eq!(crate::filter::lerp_filters(&[e(blur(1.0))], &[e(blur(1.0))], 0.5), None, "equal lists hold as they are");
}
/// ADR 0099: lists that differ pair as Animate pairs them. Filters of the same kind in the same
/// order travel to each other; one without a partner travels to, or from, itself doing nothing,
/// so it fades out or in. The first keyframe itself shows exactly its own list.
#[test]
fn mismatched_filter_lists_pair_and_the_rest_fade() {
use crate::Filter;
use crate::filter::{lerp_filters, pairing};
let e = |f: Filter| crate::FilterEntry::from(f);
let blur = |b: f32| Filter::Blur { blur_x: b, blur_y: b, quality: 1 };
let glow = |s: f32, knockout: bool| Filter::Glow { blur_x: 8.0, blur_y: 8.0, strength: s, quality: 2, color: Rgba::hex(0x00ff00), inner: false, knockout };
// A glow only the second keyframe has fades in from nothing, with its own colour and
// switches; the blur both have travels as before.
let (a, b) = (vec![e(blur(2.0))], vec![e(blur(6.0)), e(glow(2.0, true))]);
assert_eq!(pairing(&a, &b), Some(vec![(Some(0), Some(0)), (None, Some(1))]));
let mid = lerp_filters(&a, &b, 0.5).unwrap();
assert_eq!(mid[0], e(blur(4.0)));
assert_eq!(mid[1], e(Filter::Glow { blur_x: 4.0, blur_y: 4.0, strength: 1.0, quality: 2, color: Rgba::hex(0x00ff00), inner: false, knockout: true }));
assert_eq!(lerp_filters(&a, &b, 0.0), None, "on the first keyframe its own list shows, exactly");
assert_eq!(lerp_filters(&a, &b, 1.0).unwrap(), b);
// One only the first keyframe has fades out.
let out = lerp_filters(&b, &a, 0.75).unwrap();
assert_eq!(out.len(), 2);
assert!(matches!(out[1].filter, Filter::Glow { strength, blur_x, .. } if (strength - 0.5).abs() < 1e-6 && (blur_x - 2.0).abs() < 1e-6), "{out:?}");
// Another kind in the same place: the old one fades out as the new one fades in.
let swap = lerp_filters(&[e(blur(8.0))], &[e(glow(1.0, false))], 0.25).unwrap();
assert_eq!(swap.len(), 2);
assert_eq!(swap[0], e(blur(6.0)));
assert!(matches!(swap[1].filter, Filter::Glow { strength, .. } if (strength - 0.25).abs() < 1e-6));
// Reordered lists keep the longest run of kinds they share paired; the rest fade.
let (x, y) = (vec![e(blur(1.0)), e(glow(1.0, false)), e(Filter::new("bevel").unwrap())], vec![e(glow(3.0, false)), e(Filter::new("bevel").unwrap()), e(blur(9.0))]);
assert_eq!(pairing(&x, &y), Some(vec![(Some(0), None), (Some(1), Some(0)), (Some(2), Some(1)), (None, Some(2))]));
// A filter doing nothing keeps its look for when it fades in: colours, angle, switches.
let Filter::DropShadow { blur_x, strength, distance, angle, color, hide_object, .. } = (Filter::DropShadow { blur_x: 9.0, blur_y: 9.0, strength: 2.0, quality: 3, angle: 120.0, distance: 7.0, color: Rgba::hex(0x112233), inner: false, knockout: false, hide_object: true }).neutral() else { panic!() };
assert_eq!((blur_x, strength, distance, angle, color, hide_object), (0.0, 0.0, 0.0, 120.0, Rgba::hex(0x112233), true));
assert_eq!(Filter::AdjustColor { brightness: 40.0, contrast: -20.0, saturation: 10.0, hue: 90.0 }.neutral(), Filter::new("adjust_color").unwrap());
// Hostile lengths are refused, not walked.
let long: Vec<crate::FilterEntry> = (0..200).map(|_| e(blur(1.0))).collect();
assert_eq!(pairing(&long, &a), None);
assert_eq!(lerp_filters(&long, &a, 0.5), None);
assert_eq!(pairing(&[], &[]), Some(Vec::new()));
}
fn text_el(id: u64, filters: Vec<crate::FilterEntry>, field: Option<crate::TextField>) -> Element {
let block = crate::TextBlock {
text: "Hi".into(),
font: "Test".into(),
size: 20.0,
bold: false,
italic: false,
color: Rgba::BLACK,
align: Default::default(),
letter_spacing: 0.0,
line_spacing: 0.0,
width: None,
outline: Arc::new(Path::rect(2.0, 2.0, 30.0, 16.0)),
box_width: 40.0,
box_height: 24.0,
field,
on_path: None,
filters,
..crate::TextBlock::default()
};
Element { id: ElementId(id), name: String::new(), transform: Affine::translate(50.0, 40.0), color: ColorEffect::Alpha(0.5), kind: ElementKind::Text(Arc::new(block)) }
}
/// ADR 0099: text with filters draws in a group of its own that the filters run on, as a movie
/// clip does: static text and fields alike, their box and border included. Switched-off
/// filters draw nothing, and files from before open without any.
#[test]
fn text_with_filters_draws_in_a_filtered_group() {
use crate::{Filter, FilterEntry, TextField, TextKind};
let shadow = FilterEntry::from(Filter::new("drop_shadow").unwrap());
let off = FilterEntry { filter: Filter::new("blur").unwrap(), enabled: false };
let field = TextField { border: true, background: true, ..TextField::new(TextKind::Dynamic) };
for field in [None, Some(field)] {
let mut d = Document::default();
push(layer0(&mut d), 0, text_el(1, vec![off.clone(), shadow.clone()], field.clone()));
let dl = evaluate(&d, 0);
assert_eq!(dl.groups.len(), 1, "one group for the text");
let g = &dl.groups[0];
assert_eq!(&*g.filters, std::slice::from_ref(&shadow.filter), "only the filter that is on");
assert_eq!(g.alpha, 0.5, "the text's alpha fades the group, after the filters");
assert!(!dl.items.is_empty() && dl.items.iter().all(|i| i.group == Some(0)), "every item of the text is in it");
assert!(dl.items.iter().all(|i| i.color.mul[3] == 1.0), "and none fades on its own");
// Without filters that draw, the text is as it was before: no group.
let mut plain = Document::default();
push(layer0(&mut plain), 0, text_el(1, vec![off.clone()], field));
let dl = evaluate(&plain, 0);
assert!(dl.groups.is_empty() && dl.items.iter().all(|i| i.group.is_none()));
}
// The file: filters ride with the block, left out when there are none, and old files open.
let with = text_el(1, vec![shadow.clone(), off], None);
let json = serde_json::to_value(&with).unwrap();
assert_eq!(json["kind"]["Text"]["filters"][0]["type"], "drop_shadow");
assert_eq!(json["kind"]["Text"]["filters"][1]["enabled"], false);
assert_eq!(serde_json::from_value::<Element>(json).unwrap(), with);
let mut old = serde_json::to_value(text_el(1, Vec::new(), None)).unwrap();
assert!(old["kind"]["Text"].get("filters").is_none(), "no key without filters: files stay as they were");
old["kind"]["Text"]["text"] = serde_json::json!("Old");
assert!(serde_json::from_value::<Element>(old).unwrap().kind.filters().is_some_and(<[FilterEntry]>::is_empty));
// One list for what takes filters; nothing else has one.
assert!(shape_el(9, 0.0).kind.filters().is_none() && ElementKind::Camera.filters().is_none());
}
/// ADR 0099: a classic tween between two keyframes of a text tweens its filters as it does a
/// movie clip's.
#[test]
fn text_filters_tween_between_keyframes() {
use crate::{Filter, FilterEntry};
let glow = |blur: f32, color: u32| FilterEntry::from(Filter::Glow { blur_x: blur, blur_y: blur, strength: 1.0, quality: 1, color: Rgba::hex(color), inner: false, knockout: false });
let mut d = Document::default();
let mut k0 = Keyframe::new(0, 10);
k0.elements.push(Arc::new(text_el(1, vec![glow(0.0, 0xff0000)], None)));
k0.tween = Some(Tween::new(Easing::Linear, TweenKind::Classic));
let mut k1 = Keyframe::new(10, 1);
k1.elements.push(Arc::new(text_el(1, vec![glow(20.0, 0x0000ff)], None)));
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
let at5 = crate::evaluate_layer_elements(&d.timeline(0).layers[0], 5).unwrap().1;
let Some([FilterEntry { filter: Filter::Glow { blur_x, color, .. }, .. }]) = at5[0].kind.filters() else { panic!("{:?}", at5[0].kind) };
assert_eq!(*blur_x, 10.0);
assert_eq!(*color, Rgba::new(0.5, 0.0, 0.5, 1.0), "colours travel channel by channel, as a tint does");
// And the renderers get the tweened filter.
assert_eq!(&*evaluate(&d, 5).groups[0].filters, &[Filter::Glow { blur_x: 10.0, blur_y: 10.0, strength: 1.0, quality: 1, color: Rgba::new(0.5, 0.0, 0.5, 1.0), inner: false, knockout: false }]);
}
+367 -64
View File
@@ -4,6 +4,7 @@
use crate::{GradientStop, Rgba};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
/// Blur passes: Low, Medium, High (each pass is a box blur; three approach a Gaussian).
pub const MAX_QUALITY: u8 = 3;
@@ -401,40 +402,160 @@ impl Filter {
}
}
/// A number of a filter a motion tween can animate (ADR 0092), in the units the Motion Editor
/// and the Filters panel show: pixels, percent (strength) and degrees.
/// A colour of a filter a motion tween can animate (ADR 0099), channel by channel.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum FilterColor {
/// The colour of a Drop Shadow or a Glow.
Color,
/// The shadow and the highlight of a Bevel.
Shadow,
Highlight,
/// A ramp stop of a gradient filter, by its place in the ramp (0 is the first).
Stop(u8),
}
impl FilterColor {
/// The name in files and commands, as the field of the filter (`color`, `shadow_color`,
/// `highlight_color`), or `stop_<n>`.
pub fn key(self) -> Cow<'static, str> {
Cow::Borrowed(match self {
FilterColor::Color => "color",
FilterColor::Shadow => "shadow_color",
FilterColor::Highlight => "highlight_color",
FilterColor::Stop(n) => return Cow::Owned(format!("stop_{n}")),
})
}
pub fn from_key(s: &str) -> Option<FilterColor> {
match s {
"color" | "colour" => Some(FilterColor::Color),
"shadow_color" | "shadow_colour" | "shadow" => Some(FilterColor::Shadow),
"highlight_color" | "highlight_colour" | "highlight" => Some(FilterColor::Highlight),
_ => s.strip_prefix("stop_")?.parse::<u8>().ok().filter(|n| usize::from(*n) < MAX_RAMP_STOPS).map(FilterColor::Stop),
}
}
/// The label (for a stop it is "Stop": the interface adds its number).
pub fn label(self) -> &'static str {
match self {
FilterColor::Color => "Colour",
FilterColor::Shadow => "Shadow",
FilterColor::Highlight => "Highlight",
FilterColor::Stop(_) => "Stop",
}
}
fn index(self) -> usize {
match self {
FilterColor::Color => 0,
FilterColor::Shadow => 1,
FilterColor::Highlight => 2,
FilterColor::Stop(n) => 3 + usize::from(n).min(MAX_RAMP_STOPS - 1),
}
}
}
/// How many [`FilterColor`]s there are.
const FILTER_COLORS: usize = 3 + MAX_RAMP_STOPS;
/// A channel of a [`FilterColor`]: red, green and blue in 0–255 and alpha in percent, as the
/// tint and alpha of a colour effect are (so both travel the same way: each channel of the
/// straight sRGB colour on its own).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Channel {
Red,
Green,
Blue,
Alpha,
}
impl Channel {
pub const ALL: [Channel; 4] = [Channel::Red, Channel::Green, Channel::Blue, Channel::Alpha];
pub fn key(self) -> &'static str {
match self {
Channel::Red => "red",
Channel::Green => "green",
Channel::Blue => "blue",
Channel::Alpha => "alpha",
}
}
pub fn label(self) -> &'static str {
match self {
Channel::Red => "Red",
Channel::Green => "Green",
Channel::Blue => "Blue",
Channel::Alpha => "Alpha",
}
}
/// The factor from the 0–1 a colour holds to the units of the Motion Editor.
pub fn scale(self) -> f32 {
if self == Channel::Alpha { 100.0 } else { 255.0 }
}
fn index(self) -> usize {
Channel::ALL.iter().position(|c| *c == self).unwrap_or(0)
}
}
/// A value of a filter a motion tween can animate (ADR 0092, 0099), in the units the Motion
/// Editor and the Filters panel show: pixels, percent (strength, alpha), degrees, and 0–255 for
/// the red, green and blue of a colour. Quality and the switches are *stepped*: a key holds
/// until the next one, with nothing in between (as Animate, which never interpolates them).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum FilterParam {
BlurX,
BlurY,
/// Percent (100 = the filter's full strength).
/// Percent (100 = the full strength of the filter).
Strength,
/// Degrees, clockwise from the right; not wrapped in keys, so 0 → 720 turns twice.
Angle,
Distance,
/// Adjust Color's four.
/// The four of Adjust Color.
Brightness,
Contrast,
Saturation,
Hue,
/// A channel of one of the colours of the filter (ADR 0099).
Color(FilterColor, Channel),
/// Stepped (ADR 0099): 1 Low, 2 Medium, 3 High.
Quality,
/// Stepped switches: 0 off, 1 on.
Inner,
Knockout,
HideObject,
}
impl FilterParam {
pub const ALL: [FilterParam; 9] = [
FilterParam::BlurX,
FilterParam::BlurY,
FilterParam::Strength,
FilterParam::Angle,
FilterParam::Distance,
FilterParam::Brightness,
FilterParam::Contrast,
FilterParam::Saturation,
FilterParam::Hue,
];
/// The numbers: every [`FilterParam`] that is neither a channel of a colour nor stepped.
const NUMBERS: [FilterParam; 9] = [
FilterParam::BlurX,
FilterParam::BlurY,
FilterParam::Strength,
FilterParam::Angle,
FilterParam::Distance,
FilterParam::Brightness,
FilterParam::Contrast,
FilterParam::Saturation,
FilterParam::Hue,
];
/// The name in files and commands (`blur_x`, `strength`…), as the filter's own field.
pub fn key(self) -> &'static str {
match self {
/// The stepped ones.
const STEPPED: [FilterParam; 4] = [FilterParam::Quality, FilterParam::Inner, FilterParam::Knockout, FilterParam::HideObject];
impl FilterParam {
/// Every value there is, in track order: the numbers, the channels of the colours (colour,
/// shadow, highlight, then the stops of the ramp), quality and the switches.
pub fn all() -> Vec<FilterParam> {
let colors = [FilterColor::Color, FilterColor::Shadow, FilterColor::Highlight].into_iter().chain((0..MAX_RAMP_STOPS as u8).map(FilterColor::Stop));
NUMBERS.into_iter().chain(colors.flat_map(|c| Channel::ALL.map(|ch| FilterParam::Color(c, ch)))).chain(STEPPED).collect()
}
/// The name in files and commands (`blur_x`, `strength`, `color_red`, `stop_2_alpha`,
/// `knockout`…), after the fields of the filter.
pub fn key(self) -> Cow<'static, str> {
Cow::Borrowed(match self {
FilterParam::BlurX => "blur_x",
FilterParam::BlurY => "blur_y",
FilterParam::Strength => "strength",
@@ -444,7 +565,12 @@ impl FilterParam {
FilterParam::Contrast => "contrast",
FilterParam::Saturation => "saturation",
FilterParam::Hue => "hue",
}
FilterParam::Color(c, ch) => return Cow::Owned(format!("{}_{}", c.key(), ch.key())),
FilterParam::Quality => "quality",
FilterParam::Inner => "inner",
FilterParam::Knockout => "knockout",
FilterParam::HideObject => "hide_object",
})
}
pub fn from_key(s: &str) -> Option<FilterParam> {
@@ -452,11 +578,19 @@ impl FilterParam {
let s = match s.as_str() {
"blurx" => "blur_x",
"blury" => "blur_y",
"hideobject" => "hide_object",
other => other,
};
FilterParam::ALL.into_iter().find(|p| p.key() == s)
if let Some(p) = NUMBERS.into_iter().chain(STEPPED).find(|p| p.key() == s) {
return Some(p);
}
// `<colour>_<channel>`: the channel is the last word.
let (color, channel) = s.rsplit_once('_')?;
let channel = Channel::ALL.into_iter().find(|c| c.key() == channel)?;
Some(FilterParam::Color(FilterColor::from_key(color)?, channel))
}
/// The label (a channel of a colour is named by the channel: the interface names the colour).
pub fn label(self) -> &'static str {
match self {
FilterParam::BlurX => "Blur X",
@@ -468,15 +602,21 @@ impl FilterParam {
FilterParam::Contrast => "Contrast",
FilterParam::Saturation => "Saturation",
FilterParam::Hue => "Hue",
FilterParam::Color(_, ch) => ch.label(),
FilterParam::Quality => "Quality",
FilterParam::Inner => "Inner",
FilterParam::Knockout => "Knockout",
FilterParam::HideObject => "Hide object",
}
}
pub fn unit(self) -> &'static str {
match self {
FilterParam::BlurX | FilterParam::BlurY | FilterParam::Distance => "px",
FilterParam::Strength => "%",
FilterParam::Strength | FilterParam::Color(_, Channel::Alpha) => "%",
FilterParam::Angle | FilterParam::Hue => "°",
FilterParam::Brightness | FilterParam::Contrast | FilterParam::Saturation => "",
FilterParam::Brightness | FilterParam::Contrast | FilterParam::Saturation | FilterParam::Color(..) => "",
FilterParam::Quality | FilterParam::Inner | FilterParam::Knockout | FilterParam::HideObject => "",
}
}
@@ -489,62 +629,140 @@ impl FilterParam {
FilterParam::Distance => -1000.0..=1000.0,
FilterParam::Brightness | FilterParam::Contrast | FilterParam::Saturation => -100.0..=100.0,
FilterParam::Hue => -180.0..=180.0,
FilterParam::Color(_, ch) => 0.0..=ch.scale(),
FilterParam::Quality => 1.0..=f32::from(MAX_QUALITY),
FilterParam::Inner | FilterParam::Knockout | FilterParam::HideObject => 0.0..=1.0,
}
}
/// Whether a key holds until the next one instead of travelling to it: quality and the
/// switches (whole numbers; the value of a key is rounded).
pub fn is_stepped(self) -> bool {
STEPPED.contains(&self)
}
/// The colour this is a channel of.
pub fn color(self) -> Option<(FilterColor, Channel)> {
match self {
FilterParam::Color(c, ch) => Some((c, ch)),
_ => None,
}
}
fn index(self) -> usize {
FilterParam::ALL.iter().position(|p| *p == self).unwrap_or(0)
match self {
FilterParam::Color(c, ch) => NUMBERS.len() + c.index() * Channel::ALL.len() + ch.index(),
p => match STEPPED.iter().position(|q| *q == p) {
Some(i) => NUMBERS.len() + FILTER_COLORS * Channel::ALL.len() + i,
None => NUMBERS.iter().position(|q| *q == p).unwrap_or(0),
},
}
}
}
/// How many [`FilterParam`]s there are.
pub const FILTER_PARAMS: usize = 9;
pub const FILTER_PARAMS: usize = NUMBERS.len() + FILTER_COLORS * Channel::ALL.len() + STEPPED.len();
impl Filter {
/// The numbers of this filter a motion tween can animate, in the Filters panel's order.
pub fn params(&self) -> &'static [FilterParam] {
/// The values of this filter a motion tween can animate, in the order of the Filters panel:
/// its numbers, its colours channel by channel (the ramp of a gradient filter stop by stop),
/// then quality and its switches.
pub fn params(&self) -> Vec<FilterParam> {
use FilterParam::*;
let color = |c: FilterColor| Channel::ALL.map(|ch| Color(c, ch));
let mut v: Vec<FilterParam> = match self {
Filter::Blur { .. } => vec![BlurX, BlurY],
Filter::Glow { .. } => vec![BlurX, BlurY, Strength],
Filter::DropShadow { .. } | Filter::Bevel { .. } | Filter::GradientGlow { .. } | Filter::GradientBevel { .. } => vec![BlurX, BlurY, Strength, Angle, Distance],
Filter::AdjustColor { .. } => return vec![Brightness, Contrast, Saturation, Hue],
};
match self {
Filter::Blur { .. } => &[BlurX, BlurY],
Filter::Glow { .. } => &[BlurX, BlurY, Strength],
Filter::DropShadow { .. } | Filter::Bevel { .. } | Filter::GradientGlow { .. } | Filter::GradientBevel { .. } => &[BlurX, BlurY, Strength, Angle, Distance],
Filter::AdjustColor { .. } => &[Brightness, Contrast, Saturation, Hue],
Filter::DropShadow { .. } | Filter::Glow { .. } => v.extend(color(FilterColor::Color)),
Filter::Bevel { .. } => v.extend(color(FilterColor::Shadow).into_iter().chain(color(FilterColor::Highlight))),
Filter::GradientGlow { stops, .. } | Filter::GradientBevel { stops, .. } => v.extend((0..stops.len().min(MAX_RAMP_STOPS) as u8).flat_map(|n| color(FilterColor::Stop(n)))),
_ => {}
}
v.push(Quality);
match self {
Filter::DropShadow { .. } => v.extend([Inner, Knockout, HideObject]),
Filter::Glow { .. } => v.extend([Inner, Knockout]),
Filter::Bevel { .. } | Filter::GradientGlow { .. } | Filter::GradientBevel { .. } => v.push(Knockout),
_ => {}
}
v
}
/// The colours of this filter a motion tween can animate, in the order of [`Filter::params`].
pub fn colors(&self) -> Vec<FilterColor> {
self.params().into_iter().filter_map(|p| p.color()).filter(|(_, ch)| *ch == Channel::Red).map(|(c, _)| c).collect()
}
/// The colour `c` of this filter as it is; `None` when it has no such colour.
pub fn color(&self, c: FilterColor) -> Option<Rgba> {
match (self, c) {
(Filter::DropShadow { color, .. } | Filter::Glow { color, .. }, FilterColor::Color) => Some(*color),
(Filter::Bevel { shadow_color, .. }, FilterColor::Shadow) => Some(*shadow_color),
(Filter::Bevel { highlight_color, .. }, FilterColor::Highlight) => Some(*highlight_color),
(Filter::GradientGlow { stops, .. } | Filter::GradientBevel { stops, .. }, FilterColor::Stop(n)) => stops.get(usize::from(n)).map(|s| s.color),
_ => None,
}
}
/// The filter's value of `p` in the Motion Editor's units; `None` when it has no such number.
/// The value of `p` in the units of the Motion Editor; `None` when the filter has no such
/// value.
pub fn param(&self, p: FilterParam) -> Option<f32> {
if !self.params().contains(&p) {
return None;
let flag = |b: &bool| Some(if *b { 1.0 } else { 0.0 });
match (self, p) {
(Filter::Blur { quality, .. } | Filter::DropShadow { quality, .. } | Filter::Glow { quality, .. } | Filter::Bevel { quality, .. } | Filter::GradientGlow { quality, .. } | Filter::GradientBevel { quality, .. }, FilterParam::Quality) => Some(f32::from(*quality)),
(Filter::DropShadow { inner, .. } | Filter::Glow { inner, .. }, FilterParam::Inner) => flag(inner),
(Filter::DropShadow { knockout, .. } | Filter::Glow { knockout, .. } | Filter::Bevel { knockout, .. } | Filter::GradientGlow { knockout, .. } | Filter::GradientBevel { knockout, .. }, FilterParam::Knockout) => flag(knockout),
(Filter::DropShadow { hide_object, .. }, FilterParam::HideObject) => flag(hide_object),
(_, FilterParam::Color(c, ch)) => {
let rgba = self.color(c)?;
Some(ch.scale() * [rgba.r, rgba.g, rgba.b, rgba.a].get(ch.index()).copied()?)
}
_ => {
let mut c = self.clone();
c.field_mut(p).map(|(x, scale)| *x * scale)
}
}
let mut out = None;
self.visit(p, |v, scale| out = Some(*v * scale));
out
}
/// Sets `p` to `v` (Motion Editor units, brought into the filter's range when drawn); false
/// when the filter has no such number.
/// Sets `p` to `v` (Motion Editor units, brought into the range of the filter when drawn; a
/// stepped value is rounded); false when the filter has no such value.
pub fn set_param(&mut self, p: FilterParam, v: f32) -> bool {
if !self.params().contains(&p) || !v.is_finite() {
if !v.is_finite() {
return false;
}
let mut done = false;
self.visit_mut(p, |x, scale| {
*x = v / scale;
done = true;
});
done
match (&mut *self, p) {
(Filter::Blur { quality, .. } | Filter::DropShadow { quality, .. } | Filter::Glow { quality, .. } | Filter::Bevel { quality, .. } | Filter::GradientGlow { quality, .. } | Filter::GradientBevel { quality, .. }, FilterParam::Quality) => *quality = v.round().clamp(1.0, f32::from(MAX_QUALITY)) as u8,
(Filter::DropShadow { inner, .. } | Filter::Glow { inner, .. }, FilterParam::Inner) => *inner = v >= 0.5,
(Filter::DropShadow { knockout, .. } | Filter::Glow { knockout, .. } | Filter::Bevel { knockout, .. } | Filter::GradientGlow { knockout, .. } | Filter::GradientBevel { knockout, .. }, FilterParam::Knockout) => *knockout = v >= 0.5,
(Filter::DropShadow { hide_object, .. }, FilterParam::HideObject) => *hide_object = v >= 0.5,
(f, p) => match f.field_mut(p) {
Some((x, scale)) => *x = v / scale,
None => return false,
},
}
true
}
/// The field holding `p` and the factor to the Motion Editor's units (strength in percent).
fn visit(&self, p: FilterParam, f: impl FnOnce(&f32, f32)) {
let mut c = self.clone();
c.visit_mut(p, |x, s| f(x, s));
}
fn visit_mut(&mut self, p: FilterParam, f: impl FnOnce(&mut f32, f32)) {
/// The field holding the number or colour channel `p`, and the factor to the units of the
/// Motion Editor (strength and alpha in percent, red, green and blue in 0–255).
fn field_mut(&mut self, p: FilterParam) -> Option<(&mut f32, f32)> {
use FilterParam as P;
let field: Option<(&mut f32, f32)> = match (self, p) {
fn channel(c: &mut Rgba, ch: Channel) -> Option<(&mut f32, f32)> {
Some((
match ch {
Channel::Red => &mut c.r,
Channel::Green => &mut c.g,
Channel::Blue => &mut c.b,
Channel::Alpha => &mut c.a,
},
ch.scale(),
))
}
match (self, p) {
(Filter::Blur { blur_x, .. }, P::BlurX) => Some((blur_x, 1.0)),
(Filter::Blur { blur_y, .. }, P::BlurY) => Some((blur_y, 1.0)),
(Filter::DropShadow { blur_x, .. } | Filter::Glow { blur_x, .. } | Filter::Bevel { blur_x, .. } | Filter::GradientGlow { blur_x, .. } | Filter::GradientBevel { blur_x, .. }, P::BlurX) => Some((blur_x, 1.0)),
@@ -556,12 +774,24 @@ impl Filter {
(Filter::AdjustColor { contrast, .. }, P::Contrast) => Some((contrast, 1.0)),
(Filter::AdjustColor { saturation, .. }, P::Saturation) => Some((saturation, 1.0)),
(Filter::AdjustColor { hue, .. }, P::Hue) => Some((hue, 1.0)),
(Filter::DropShadow { color, .. } | Filter::Glow { color, .. }, P::Color(FilterColor::Color, ch)) => channel(color, ch),
(Filter::Bevel { shadow_color, .. }, P::Color(FilterColor::Shadow, ch)) => channel(shadow_color, ch),
(Filter::Bevel { highlight_color, .. }, P::Color(FilterColor::Highlight, ch)) => channel(highlight_color, ch),
(Filter::GradientGlow { stops, .. } | Filter::GradientBevel { stops, .. }, P::Color(FilterColor::Stop(n), ch)) => stops.get_mut(usize::from(n)).and_then(|s| channel(&mut s.color, ch)),
_ => None,
};
if let Some((x, s)) = field {
f(x, s);
}
}
/// The same filter doing nothing (ADR 0099): no blur, strength or distance, an Adjust Color
/// at rest; its colours, angle, quality and switches kept. What a classic tween pairs with a
/// filter the other keyframe has no partner for, so that filter fades in or out.
pub fn neutral(&self) -> Filter {
let mut f = self.clone();
for p in [FilterParam::BlurX, FilterParam::BlurY, FilterParam::Strength, FilterParam::Distance, FilterParam::Brightness, FilterParam::Contrast, FilterParam::Saturation, FilterParam::Hue] {
f.set_param(p, 0.0);
}
f
}
}
/// A filter's number addressed in an instance's list (ADR 0092): the filter's place (0 is the
@@ -631,16 +861,89 @@ pub fn pairs_up(a: &[FilterEntry], b: &[FilterEntry]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| std::mem::discriminant(&x.filter) == std::mem::discriminant(&y.filter))
}
/// The classic tween between two filter lists (ADR 0081, 0091): when both have the same kinds
/// in the same order, each filter's numbers and colours travel (switches such as Inner and
/// Knockout, the quality, and whether the filter is on stay the first keyframe's; ramps travel
/// stop by stop when they have as many stops). `None` when the lists are equal or don't pair
/// up: the first list holds.
/// The classic tween between two filter lists (ADR 0081, 0091, 0099). Every filter's numbers
/// and colours travel to its partner's; quality, the switches (Inner, Knockout, Hide object,
/// the Type) and whether the filter is on stay the first keyframe's, and ramps travel stop by
/// stop when they have as many stops.
///
/// Lists with the same kinds in the same order pair one to one. Other lists pair as Animate
/// pairs them ([`pairing`]): a filter with no partner in the other keyframe travels to, or
/// from, the same filter doing nothing ([`Filter::neutral`]), so it fades out or in instead of
/// popping. `None` when the first list holds as it is: the lists are equal, or they don't pair
/// one to one and `t` is 0 (the first keyframe itself shows exactly its own filters).
pub fn lerp_filters(a: &[FilterEntry], b: &[FilterEntry], t: f32) -> Option<Vec<FilterEntry>> {
if a == b || !pairs_up(a, b) {
if a == b {
return None;
}
a.iter().zip(b).map(|(x, y)| Some(FilterEntry { filter: x.filter.lerp(&y.filter, t)?, enabled: x.enabled })).collect()
if pairs_up(a, b) {
return a.iter().zip(b).map(|(x, y)| Some(FilterEntry { filter: x.filter.lerp(&y.filter, t)?, enabled: x.enabled })).collect();
}
if t.is_nan() || t <= 0.0 {
return None;
}
pairing(a, b)?
.into_iter()
.map(|pair| match pair {
(Some(i), Some(j)) => {
let (x, y) = (a.get(i)?, b.get(j)?);
Some(FilterEntry { filter: x.filter.lerp(&y.filter, t)?, enabled: x.enabled })
}
(Some(i), None) => {
let x = a.get(i)?;
Some(FilterEntry { filter: x.filter.lerp(&x.filter.neutral(), t)?, enabled: x.enabled })
}
(None, Some(j)) => {
let y = b.get(j)?;
Some(FilterEntry { filter: y.filter.neutral().lerp(&y.filter, t)?, enabled: y.enabled })
}
(None, None) => None,
})
.collect()
}
/// Longest lists [`pairing`] looks at (an instance holds at most 16 filters; a file may say more).
const MAX_PAIRED: usize = 64;
/// How the filters of two keyframes pair up for a tween when the lists differ (ADR 0099), in
/// the order the tween applies them: `(Some(i), Some(j))` pairs `a[i]` with `b[j]` (the same
/// kind), `(Some(i), None)` is a filter only the first keyframe has, `(None, Some(j))` one only
/// the second has. The pairs are the longest run of same kinds both lists hold in the same
/// order, so filters added, removed or replaced leave the others paired; among equally long
/// runs the earliest filters pair. `None` for lists too long to pair.
pub fn pairing(a: &[FilterEntry], b: &[FilterEntry]) -> Option<Vec<(Option<usize>, Option<usize>)>> {
let (n, m) = (a.len(), b.len());
if n > MAX_PAIRED || m > MAX_PAIRED {
return None;
}
let same = |i: usize, j: usize| matches!((a.get(i), b.get(j)), (Some(x), Some(y)) if std::mem::discriminant(&x.filter) == std::mem::discriminant(&y.filter));
// lcs[i][j]: the longest common run of kinds of a[i..] and b[j..].
let w = m + 1;
let mut lcs = vec![0u16; (n + 1) * w];
let at = |lcs: &[u16], i: usize, j: usize| lcs.get(i * w + j).copied().unwrap_or(0);
for i in (0..n).rev() {
for j in (0..m).rev() {
let v = if same(i, j) { at(&lcs, i + 1, j + 1) + 1 } else { at(&lcs, i + 1, j).max(at(&lcs, i, j + 1)) };
if let Some(slot) = lcs.get_mut(i * w + j) {
*slot = v;
}
}
}
let mut out = Vec::with_capacity(n + m);
let (mut i, mut j) = (0, 0);
while i < n || j < m {
if i < n && j < m && same(i, j) {
out.push((Some(i), Some(j)));
i += 1;
j += 1;
} else if i < n && (j >= m || at(&lcs, i + 1, j) >= at(&lcs, i, j + 1)) {
out.push((Some(i), None));
i += 1;
} else {
out.push((None, Some(j)));
j += 1;
}
}
Some(out)
}
fn ramp_lerp(a: &[GradientStop], b: &[GradientStop], t: f32) -> Vec<GradientStop> {
+25 -1
View File
@@ -35,7 +35,7 @@ pub mod templates;
pub mod sound;
pub mod swatch;
pub use filter::{FILTER_PARAMS, Filter, FilterEntry, FilterParam, FilterProp, FilterSide, MAX_FILTER_SLOTS, active as active_filters, any_active as any_active_filter, pairs_up as filters_pair_up, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at};
pub use filter::{Channel, FILTER_PARAMS, Filter, FilterColor, FilterEntry, FilterParam, FilterProp, FilterSide, MAX_FILTER_SLOTS, pairing as filter_pairing, active as active_filters, any_active as any_active_filter, pairs_up as filters_pair_up, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at};
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png};
pub use easing::{CustomEase, EaseDir, EaseFamily, EasePoint, Easing, Handle, MAX_EASE_NAME, MAX_EASE_POINTS, MAX_EASE_SAMPLES, MAX_EASE_Y, MAX_SAVED_EASES, SampledEase, SavedEase, ease_name};
pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform};
@@ -591,6 +591,25 @@ pub enum ElementKind {
}
impl ElementKind {
/// The filter list of what takes filters: a symbol instance (movie clips and buttons draw
/// them) or a block of text (ADR 0099). `None` for everything else.
pub fn filters(&self) -> Option<&[FilterEntry]> {
match self {
ElementKind::Symbol { filters, .. } => Some(filters),
ElementKind::Text(t) => Some(&t.filters),
_ => None,
}
}
/// The same list, to change (a text block shared with another element is copied first).
pub fn filters_mut(&mut self) -> Option<&mut Vec<FilterEntry>> {
match self {
ElementKind::Symbol { filters, .. } => Some(filters),
ElementKind::Text(t) => Some(&mut Arc::make_mut(t).filters),
_ => None,
}
}
/// A group of `elements` (ADR 0073), on one layer with id `layer`.
pub fn group(layer: LayerId, elements: Vec<Arc<Element>>) -> ElementKind {
let mut l = Layer::new(layer, "Layer 1");
@@ -779,6 +798,10 @@ pub struct TextBlock {
/// `outline` holds the glyphs set along it. Static text only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_path: Option<TextPath>,
/// Filters, applied in order to the text as it is drawn (its box and border included), as
/// on a movie clip (ADR 0099); each may be switched off.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub filters: Vec<FilterEntry>,
/// The first run's baseline shift, underline and link (ADR 0085).
#[serde(default, skip_serializing_if = "rich_text_is_normal")]
pub shift: BaselineShift,
@@ -829,6 +852,7 @@ impl Default for TextBlock {
box_height: 0.0,
field: None,
on_path: None,
filters: Vec::new(),
shift: BaselineShift::Normal,
underline: false,
url: String::new(),
+197 -15
View File
@@ -21,7 +21,7 @@
//! time the whole path when only the ends are pinned. Anchors that aren't pinned shape the path
//! only.
use crate::{ColorEffect, ColorStyle, ColorTransform, Element, ElementId, ElementKind, Easing, FilterParam, FilterProp, MAX_FILTER_SLOTS, Rgba};
use crate::{ColorEffect, ColorStyle, ColorTransform, Element, ElementId, Easing, FilterParam, FilterProp, MAX_FILTER_SLOTS, Rgba};
use std::borrow::Cow;
use anicraft_geom::edit::ANCHOR;
use anicraft_geom::walk::CurveWalk;
@@ -72,7 +72,9 @@ pub enum Property {
GreenOffset,
BlueOffset,
AlphaOffset,
/// A number of a filter on the target (ADR 0092), by the filter's place in its list.
/// A value of a filter on the target (ADR 0092), by the filter's place in its list: a
/// number, a channel of one of its colours, or quality and the switches, which are stepped
/// (ADR 0099).
Filter(FilterProp),
}
@@ -273,6 +275,12 @@ impl Property {
}
}
/// Whether a key of this property holds until the next key instead of travelling to it
/// (ADR 0099): a filter's quality and switches. Their values are whole numbers.
pub fn is_stepped(self) -> bool {
self.filter().is_some_and(|f| f.param.is_stepped())
}
/// Position and transform (the properties the element's matrix holds).
pub fn is_transform(self) -> bool {
self.style().is_none() && !self.is_filter()
@@ -280,7 +288,8 @@ impl Property {
fn clamp(self, v: f32) -> f32 {
let r = self.range();
if v.is_finite() { v.clamp(*r.start(), *r.end()) } else { 0.0 }
let v = if v.is_finite() { v.clamp(*r.start(), *r.end()) } else { 0.0f32.clamp(*r.start(), *r.end()) };
if self.is_stepped() { v.round() } else { v }
}
}
@@ -375,20 +384,18 @@ pub fn own_value(el: &Element, p: Property) -> Option<f32> {
}
fn filter_entry(el: &Element, slot: u8) -> Option<&crate::FilterEntry> {
match &el.kind {
ElementKind::Symbol { filters, .. } => filters.get(usize::from(slot)),
_ => None,
}
el.kind.filters()?.get(usize::from(slot))
}
/// Every filter number the object has, in its list's order (the Motion Editor's filter rows).
/// Every filter value the object has that a tween can animate, in its list's order (the Motion
/// Editor's filter rows): each filter's numbers, colour channels, quality and switches.
pub fn filter_properties(el: &Element) -> Vec<Property> {
let ElementKind::Symbol { filters, .. } = &el.kind else { return Vec::new() };
let Some(filters) = el.kind.filters() else { return Vec::new() };
filters
.iter()
.take(usize::from(MAX_FILTER_SLOTS))
.enumerate()
.flat_map(|(slot, e)| e.filter.params().iter().map(move |&param| Property::Filter(FilterProp { slot: slot as u8, param })))
.flat_map(|(slot, e)| e.filter.params().into_iter().map(move |param| Property::Filter(FilterProp { slot: slot as u8, param })))
.collect()
}
@@ -430,6 +437,11 @@ impl Track {
// The segment [a, b) holding `frame`: binary search on the key frames.
let i = self.keys.partition_point(|k| k.frame as f32 <= frame);
let (a, b) = (self.keys.get(i.checked_sub(1)?)?, self.keys.get(i)?);
// A stepped property holds its key until the next one (ADR 0099): no ease, nothing in
// between, and exactly the next key's value from its frame on.
if self.property.is_stepped() {
return Some(a.value);
}
let span = (b.frame - a.frame).max(1) as f32;
let t = a.ease.apply((frame - a.frame as f32) / span);
Some(a.value + (b.value - a.value) * t)
@@ -1125,7 +1137,9 @@ impl MotionTween {
}
// The filters' numbers (ADR 0092): a track whose filter isn't there, or has no such
// number, does nothing (its filter was replaced by another kind).
if let ElementKind::Symbol { filters, .. } = &mut el.kind {
if self.tracks.iter().any(|t| t.property.is_filter())
&& let Some(filters) = el.kind.filters_mut()
{
for t in self.tracks.iter().filter(|t| t.property.is_filter()) {
if let (Some(f), Some(v)) = (t.property.filter(), t.value_at(frame))
&& let Some(e) = filters.get_mut(usize::from(f.slot))
@@ -1954,10 +1968,176 @@ mod tests {
}
fn blur_x(e: &Element, slot: usize) -> Option<f32> {
match &e.kind {
ElementKind::Symbol { filters, .. } => filters.get(slot).and_then(|f| f.filter.param(FilterParam::BlurX)),
_ => None,
e.kind.filters()?.get(slot).and_then(|f| f.filter.param(FilterParam::BlurX))
}
/// ADR 0099: a filter's colour tweens channel by channel, in the units and the space of the
/// colour effect's tint (straight sRGB, 0–255; alpha in percent), each on its own curve.
#[test]
fn a_filter_colour_tweens_channel_by_channel() {
use crate::{Channel, FilterColor};
let glow = crate::Filter::Glow { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, color: Rgba::new(1.0, 0.0, 0.0, 1.0), inner: false, knockout: false };
let base = clip(0.0, vec![glow]);
let ch = |c: Channel| fp(0, FilterParam::Color(FilterColor::Color, c));
let colour = |e: &Element| e.kind.filters().and_then(|f| f.first()).and_then(|f| f.filter.color(FilterColor::Color)).unwrap();
// The object's own colour, in the Motion Editor's units.
assert_eq!([Channel::Red, Channel::Green, Channel::Blue, Channel::Alpha].map(|c| own_value(&base, ch(c))), [Some(255.0), Some(0.0), Some(0.0), Some(100.0)]);
// Red to blue, half transparent, over ten frames.
let mut m = MotionTween::new(ElementId(1));
for (c, to, own) in [(Channel::Red, 0.0, 255.0), (Channel::Blue, 255.0, 0.0), (Channel::Alpha, 50.0, 100.0)] {
m.set_key(ch(c), 10, to, own);
}
assert_eq!(colour(&m.apply(&base, 0.0)), Rgba::new(1.0, 0.0, 0.0, 1.0));
// The midpoint: each channel half way, exactly what a tint's tween gives.
let mid = colour(&m.apply(&base, 5.0));
assert_eq!(mid, Rgba::new(0.5, 0.0, 0.5, 0.75));
assert_eq!(mid, Rgba::new(1.0, 0.0, 0.0, 1.0).lerp(Rgba::new(0.0, 0.0, 1.0, 0.5), 0.5), "the same as the colour's own lerp");
assert_eq!(colour(&m.apply(&base, 10.0)), Rgba::new(0.0, 0.0, 1.0, 0.5));
// Green has no track: the object's own, bit for bit. Each channel eases on its own.
if let Some(k) = m.track_mut(ch(Channel::Blue)).and_then(|t| t.keys.first_mut()) {
k.ease = Easing::QuadIn;
}
let eased = colour(&m.apply(&base, 5.0));
assert_eq!((eased.r, eased.g, eased.b), (0.5, 0.0, 0.25));
// A bevel's two colours and a ramp's stops are addressed the same way; a stop the ramp
// doesn't have does nothing.
let bevel = crate::Filter::new("bevel").unwrap();
assert_eq!(bevel.colors(), [FilterColor::Shadow, FilterColor::Highlight]);
let ramp = crate::Filter::new("gradient_bevel").unwrap();
assert_eq!(ramp.colors(), [FilterColor::Stop(0), FilterColor::Stop(1), FilterColor::Stop(2)]);
let base = clip(0.0, vec![bevel, ramp.clone()]);
let mut m = MotionTween::new(ElementId(1));
m.set_key(fp(0, FilterParam::Color(FilterColor::Highlight, Channel::Blue)), 4, 0.0, 255.0);
m.set_key(fp(1, FilterParam::Color(FilterColor::Stop(2), Channel::Red)), 4, 255.0, 0.0);
m.set_key(fp(1, FilterParam::Color(FilterColor::Stop(9), Channel::Red)), 4, 255.0, 0.0);
let at = m.apply(&base, 2.0);
let f = at.kind.filters().unwrap();
assert_eq!(f[0].filter.color(FilterColor::Highlight), Some(Rgba::new(1.0, 1.0, 0.5, 1.0)));
assert_eq!(f[0].filter.color(FilterColor::Shadow), Some(Rgba::BLACK), "the shadow keeps its own");
assert_eq!(f[1].filter.color(FilterColor::Stop(2)), Some(Rgba::new(0.5, 0.0, 0.0, 1.0)));
assert_eq!(f[1].filter.color(FilterColor::Stop(9)), None);
assert_eq!(own_value(&base, fp(1, FilterParam::Color(FilterColor::Stop(9), Channel::Red))), None);
assert_eq!(own_value(&base, fp(0, FilterParam::Color(FilterColor::Color, Channel::Red))), None, "a bevel has no single colour");
}
/// ADR 0099: quality and the switches are stepped: a key holds until the next key's frame,
/// where the value is exactly that key's; nothing in between, whatever the ease.
#[test]
fn switches_and_quality_hold_their_keys() {
let shadow = crate::Filter::new("drop_shadow").unwrap();
let base = clip(0.0, vec![shadow]);
let (knock, quality, hide) = (fp(0, FilterParam::Knockout), fp(0, FilterParam::Quality), fp(0, FilterParam::HideObject));
assert!(knock.is_stepped() && quality.is_stepped() && !fp(0, FilterParam::BlurX).is_stepped() && !Property::X.is_stepped());
let mut m = MotionTween::new(ElementId(1));
m.set_key(knock, 6, 1.0, 0.0);
m.set_key(quality, 4, 3.0, 1.0);
m.set_key(quality, 8, 2.2, 1.0);
// An ease on a stepped track changes nothing.
for t in &mut m.tracks {
for k in &mut t.keys {
k.ease = Easing::QuadIn;
}
}
let at = |f: f32| {
let e = m.apply(&base, f);
let f = e.kind.filters().unwrap()[0].filter.clone();
(f.param(FilterParam::Knockout).unwrap(), f.param(FilterParam::Quality).unwrap())
};
assert_eq!(at(0.0), (0.0, 1.0));
assert_eq!(at(3.0), (0.0, 1.0), "held: no travel toward the next key");
assert_eq!(at(3.99), (0.0, 1.0));
assert_eq!(at(4.0), (0.0, 3.0), "exact at the key's frame");
assert_eq!(at(5.9), (0.0, 3.0));
assert_eq!(at(6.0), (1.0, 3.0));
assert_eq!(at(8.0), (1.0, 2.0), "a key's value is a whole number");
assert_eq!(at(20.0), (1.0, 2.0));
assert_eq!(m.track(quality).unwrap().keys.iter().map(|k| k.value).collect::<Vec<_>>(), [1.0, 3.0, 2.0]);
// The filter itself holds the switch and the quality, not numbers.
let e = m.apply(&base, 7.0);
assert!(matches!(e.kind.filters().unwrap()[0].filter, crate::Filter::DropShadow { knockout: true, quality: 3, hide_object: false, .. }));
// Splitting the span keeps every frame: the second half starts with what held there.
let tail = m.split_at(&Props::of(&base), 5);
assert_eq!(tail.track(quality).unwrap().keys.iter().map(|k| (k.frame, k.value)).collect::<Vec<_>>(), [(0, 3.0), (3, 2.0)]);
assert_eq!(tail.track(knock).unwrap().keys.iter().map(|k| (k.frame, k.value)).collect::<Vec<_>>(), [(0, 0.0), (1, 1.0)]);
// A kind without the switch takes no key value from it (a blur has no Knockout).
assert_eq!(own_value(&clip(0.0, vec![crate::Filter::new("blur").unwrap()]), fp(0, FilterParam::Knockout)), None);
assert_eq!(own_value(&base, hide), Some(0.0));
// Files and repairs keep stepped values whole and in range.
let mut wild = m.clone();
if let Some(t) = wild.track_mut(quality) {
t.keys[1].value = 9.7;
}
assert!(!wild.is_sane());
wild.sanitize();
assert_eq!(wild.track(quality).unwrap().keys[1].value, 3.0);
}
/// ADR 0099: every value's name in files and commands reads back as itself, and the names
/// are the filter's own fields.
#[test]
fn filter_value_names_round_trip() {
use crate::{Channel, FilterColor};
let all = FilterParam::all();
assert_eq!(all.len(), crate::FILTER_PARAMS);
for (i, p) in all.iter().enumerate() {
assert_eq!(FilterParam::from_key(&p.key()), Some(*p), "{}", p.key());
assert_eq!(fp(0, *p).index(), PROPERTIES + i, "{}: tracks keep this order", p.key());
let r = p.range();
assert!(r.start() < r.end());
}
assert_eq!(fp(3, FilterParam::Color(FilterColor::Color, Channel::Red)).key(), "filter.3.color_red");
assert_eq!(fp(0, FilterParam::Color(FilterColor::Shadow, Channel::Alpha)).key(), "filter.0.shadow_color_alpha");
assert_eq!(fp(0, FilterParam::Color(FilterColor::Stop(14), Channel::Green)).key(), "filter.0.stop_14_green");
assert_eq!(Property::from_key("filter.2.Highlight-Color Blue"), Some(fp(2, FilterParam::Color(FilterColor::Highlight, Channel::Blue))));
assert_eq!(Property::from_key("filter.0.hide_object"), Some(fp(0, FilterParam::HideObject)));
for bad in ["filter.0.stop_15_red", "filter.0.stop_x_red", "filter.0.color", "filter.0.color_", "filter.0.colour_purple", "filter.0.stop_-1_red"] {
assert_eq!(Property::from_key(bad), None, "{bad}");
}
// In files they sit with the other filter tracks, apart from the twenty.
let mut m = MotionTween::new(ElementId(1));
m.set_key(fp(0, FilterParam::Color(FilterColor::Color, Channel::Red)), 4, 12.0, 255.0);
m.set_key(fp(0, FilterParam::Inner), 4, 1.0, 0.0);
let v = serde_json::to_value(&m).unwrap();
assert_eq!(v["filter_tracks"][0]["property"], "filter.0.color_red");
assert_eq!(v["filter_tracks"][1]["property"], "filter.0.inner");
assert!(v.get("tracks").is_none());
assert_eq!(serde_json::from_value::<MotionTween>(v).unwrap(), m);
}
/// ADR 0099: text takes filter tracks as a movie clip does.
#[test]
fn text_filters_tween_on_their_own_curves() {
let block = crate::TextBlock {
text: "Hi".into(),
font: "Test".into(),
size: 20.0,
bold: false,
italic: false,
color: Rgba::BLACK,
align: Default::default(),
letter_spacing: 0.0,
line_spacing: 0.0,
width: None,
outline: Arc::new(Path::rect(0.0, 0.0, 30.0, 16.0)),
box_width: 30.0,
box_height: 16.0,
field: None,
on_path: None,
filters: vec![crate::Filter::new("drop_shadow").unwrap().into()],
..crate::TextBlock::default()
};
let text = Arc::new(block);
let base = Element { kind: ElementKind::Text(text.clone()), ..el(1, 0.0, 0.0) };
assert_eq!(filter_properties(&base).len(), 5 + 4 + 4);
let mut m = MotionTween::new(ElementId(1));
m.set_key(fp(0, FilterParam::Distance), 10, 24.0, 4.0);
assert_eq!(own_value(&m.apply(&base, 5.0), fp(0, FilterParam::Distance)), Some(14.0));
assert_eq!(text.filters[0].filter.param(FilterParam::Distance), Some(4.0), "the block the keyframe holds is untouched");
// Without filter tracks the block is shared, not copied.
let mut plain = MotionTween::new(ElementId(1));
plain.set_key(Property::X, 10, 50.0, 0.0);
let ElementKind::Text(t) = &plain.apply(&base, 5.0).kind else { panic!() };
assert!(Arc::ptr_eq(t, &text));
}
fn fp(slot: u8, param: FilterParam) -> Property {
@@ -1999,7 +2179,9 @@ mod tests {
assert_eq!(own_value(&base, fp(1, FilterParam::BlurX)), Some(5.0));
assert_eq!(own_value(&base, fp(1, FilterParam::Angle)), None, "a blur has no angle");
assert_eq!(own_value(&base, fp(5, FilterParam::BlurX)), None);
assert_eq!(filter_properties(&base).len(), 5 + 2);
// Every value a tween can animate: the shadow's five numbers, its colour's four
// channels, quality and three switches; the blur's two numbers and quality (ADR 0099).
assert_eq!(filter_properties(&base).len(), (5 + 4 + 4) + (2 + 1));
}
/// In files a filter's track sits under `filter_tracks`, addressed `filter.<slot>.<param>`,
+67 -40
View File
@@ -1,13 +1,14 @@
//! The filter list of movie clip and button instances (ADR 0025, 0091): replacing it
//! (`element.set_filters`), reordering, switching filters on and off, removing them, copying
//! and pasting them between instances, and the user's filter presets.
//! The filter list of movie clip and button instances and of text (ADR 0025, 0091, 0099):
//! replacing it (`element.set_filters`), reordering, switching filters on and off, removing
//! them, copying and pasting them between objects, and filter presets: the user's own and the
//! built-in ones.
//!
//! Every edit acts on each selected movie clip and button instance (graphics take no filters,
//! as in Animate) and is one undo step. A filter at an index acts where an instance has one;
//! the command fails only when it acts nowhere. Copied filters and presets live in the session,
//! Every edit acts on each selected movie clip, button and text (graphics take no filters, as
//! in Animate) and is one undo step. A filter at an index acts where an object has one; the
//! command fails only when it acts nowhere. Copied filters and presets live in the session,
//! outside the document and its undo history.
use crate::filter_library::{FilterLibrary, MAX_FILE_BYTES, MAX_FILTERS, MAX_PRESETS};
use crate::filter_library::{FilterLibrary, MAX_FILE_BYTES, MAX_FILTERS, MAX_PRESETS, builtins};
use crate::params::*;
use crate::{CommandSpec, EngineError, Result, Session};
use anicraft_doc::{ElementKind, FilterEntry, SymbolId, SymbolKind};
@@ -16,17 +17,18 @@ use serde_json::{Value, json};
pub fn specs() -> Vec<CommandSpec> {
let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run };
vec![
c("filter.move", "Move Filter", "{from, to} moves the filter at index `from` (0 is the first, applied first) to index `to` in the selected movie clip and button instances' lists; the order changes how they draw", true, (|s, p| s.each_layer(false, |s| move_filter(s, p))) as crate::RunFn),
c("filter.move", "Move Filter", "{from, to} moves the filter at index `from` (0 is the first, applied first) to index `to` in the lists of the selected movie clips, buttons and text; the order changes how they draw", true, (|s, p| s.each_layer(false, |s| move_filter(s, p))) as crate::RunFn),
c("filter.enable", "Enable Filter", "{enabled: bool, index? (default: every filter)} switches a filter on or off; a filter switched off keeps its settings and draws nothing", true, |s, p| s.each_layer(false, |s| enable(s, p))),
c("filter.remove", "Remove Filter", "{index? (default: every filter)} removes a filter from the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| remove(s, p))),
c("filter.copy", "Copy Filters", "{index? (default: every filter)} copies the selected instance's filters (one, or all), for Paste Filters", false, copy),
c("filter.paste", "Paste Filters", "{replace? (default false: added after the instances' own)} pastes the copied filters onto the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| paste(s, p))),
c("filter.preset_list", "Filter Presets", "{} your filter presets, each a name and its filters", false, preset_list),
c("filter.preset_save", "Save Filter Preset", "{name, filters? (a list as element.set_filters takes; default: the selected instance's)} saves a filter preset of your own (kept in your preferences; a name you have already is replaced, after asking)", false, preset_save),
c("filter.preset_apply", "Apply Filter Preset", "{name} gives the selected movie clip and button instances the preset's filters, replacing theirs (as Animate does)", true, |s, p| s.each_layer(false, |s| preset_apply(s, p))),
c("filter.preset_rename", "Rename Filter Preset", "{name, to}", false, preset_rename),
c("filter.preset_delete", "Delete Filter Preset", "{name} deletes a filter preset (asks first: it can't be undone; artwork that used it keeps its filters)", false, preset_delete),
c("filter.preset_export", "Export Filter Presets", "{path, names? (default: all)} writes your filter presets to a small JSON file", false, preset_export),
c("filter.remove", "Remove Filter", "{index? (default: every filter)} removes a filter from the selected movie clips, buttons and text", true, |s, p| s.each_layer(false, |s| remove(s, p))),
c("filter.copy", "Copy Filters", "{index? (default: every filter)} copies the filters of the selected movie clip, button or text (one, or all), for Paste Filters", false, copy),
c("filter.paste", "Paste Filters", "{replace? (default false: added after their own)} pastes the copied filters onto the selected movie clips, buttons and text", true, |s, p| s.each_layer(false, |s| paste(s, p))),
c("filter.preset_list", "Filter Presets", "{} → {presets: your filter presets, each a name and its filters; builtin: the built-in ones (ADR 0099), each with its name, filters and whether you have hidden it}", false, preset_list),
c("filter.preset_save", "Save Filter Preset", "{name, filters? (a list as element.set_filters takes; default: the selected object's)} saves a filter preset of your own (kept in your preferences; a name you have already is replaced, after asking; a built-in preset's name is refused)", false, preset_save),
c("filter.preset_apply", "Apply Filter Preset", "{name: one of yours, or a built-in one (Soft Shadow, Hard Shadow, Neon Glow, Outline, Emboss, Engrave, Soft Focus, Greyscale)} gives the selected movie clips, buttons and text the preset's filters, replacing theirs (as Animate does)", true, |s, p| s.each_layer(false, |s| preset_apply(s, p))),
c("filter.preset_rename", "Rename Filter Preset", "{name, to} (your own presets; the built-in ones keep their names)", false, preset_rename),
c("filter.preset_delete", "Delete Filter Preset", "{name} deletes a filter preset of yours (asks first: it can't be undone; artwork that used it keeps its filters). Built-in presets can't be deleted, only hidden (filter.preset_hide)", false, preset_delete),
c("filter.preset_hide", "Hide Built-in Filter Preset", "{name, hidden? (default true; false shows it again)} hides a built-in filter preset from the presets menu, or shows it again (kept in your preferences; a hidden preset still applies by name)", false, preset_hide),
c("filter.preset_export", "Export Filter Presets", "{path, names? (default: all of yours; built-in ones may be named)} writes filter presets to a small JSON file", false, preset_export),
c("filter.preset_import", "Import Filter Presets", "{path} adds the presets in a filter preset file to yours (a name you have already gets a number)", false, preset_import),
]
}
@@ -62,29 +64,39 @@ pub(crate) fn parse_list(list: Option<&Value>) -> Result<Vec<FilterEntry>> {
Ok(filters.iter().map(FilterEntry::sanitized).collect())
}
/// Runs `edit` on the filter list of each selected movie clip and button instance; `edit`
/// says whether it changed that list. Fails when no instance takes filters, or none changed
/// (`nothing` says why).
/// What to select for a filter command.
const SELECT: &str = "select a movie clip or button instance, or text";
/// Runs `edit` on the filter list of each selected movie clip, button and text (ADR 0099);
/// `edit` says whether it changed that list. Fails when nothing selected takes filters, or
/// none changed (`nothing` says why).
fn edit_lists(s: &mut Session, nothing: &str, mut edit: impl FnMut(&mut Vec<FilterEntry>) -> bool) -> Result<usize> {
let kinds: std::collections::HashMap<SymbolId, SymbolKind> = s.doc.library.iter().map(|x| (x.id, x.kind)).collect();
let (mut set, mut clips, mut graphics) = (0, 0, 0);
for e in s.selected_props_mut()? {
if let ElementKind::Symbol { symbol, filters, .. } = &mut e.kind {
if kinds.get(symbol) == Some(&SymbolKind::Graphic) {
graphics += 1;
continue;
}
clips += 1;
if edit(filters) {
set += 1;
if matches!(&e.kind, ElementKind::Symbol { symbol, .. } if kinds.get(symbol) == Some(&SymbolKind::Graphic)) {
graphics += 1;
continue;
}
// Only what takes filters is touched (a text block shared with another keyframe is
// copied when its list is asked for).
if e.kind.filters().is_none() {
continue;
}
let mut list = e.kind.filters().map(<[FilterEntry]>::to_vec).unwrap_or_default();
clips += 1;
if edit(&mut list) {
set += 1;
if let Some(slot) = e.kind.filters_mut() {
*slot = list;
}
}
}
if clips == 0 {
return Err(EngineError::State(if graphics > 0 {
"filters apply to movie clip and button instances; set the symbol's Type to Movie Clip first".into()
"filters apply to movie clip and button instances and to text; set the symbol's Type to Movie Clip first".into()
} else {
"select a movie clip or button instance".into()
SELECT.into()
}));
}
if set == 0 {
@@ -93,7 +105,7 @@ fn edit_lists(s: &mut Session, nothing: &str, mut edit: impl FnMut(&mut Vec<Filt
Ok(set)
}
/// Filters for the selected movie clip and button instances (Animate offers them on those only).
/// Filters for the selected movie clip and button instances and text (as Animate offers them).
pub(crate) fn set_filters(s: &mut Session, p: &Value) -> Result<Value> {
let filters = parse_list(p.get("filters"))?;
let set = edit_lists(s, "", |f| {
@@ -164,23 +176,23 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"removed": set}))
}
/// The filters of the first selected movie clip or button instance, as it shows now.
/// The filters of the first selected movie clip, button or text, as it shows now.
fn selected_list(s: &Session) -> Result<Vec<FilterEntry>> {
let kinds: std::collections::HashMap<SymbolId, SymbolKind> = s.doc.library.iter().map(|x| (x.id, x.kind)).collect();
s.selected_elements()
.into_iter()
.find_map(|(_, e)| match &e.kind {
ElementKind::Symbol { symbol, filters, .. } if kinds.get(symbol).is_some_and(|k| *k != SymbolKind::Graphic) => Some(filters.clone()),
_ => None,
ElementKind::Symbol { symbol, .. } if kinds.get(symbol).is_none_or(|k| *k == SymbolKind::Graphic) => None,
kind => kind.filters().map(<[FilterEntry]>::to_vec),
})
.ok_or_else(|| EngineError::State("select a movie clip or button instance".into()))
.ok_or_else(|| EngineError::State(SELECT.into()))
}
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
let list = selected_list(s)?;
let chosen = match index(p, "index")? {
Some(i) => vec![list.get(i).cloned().ok_or_else(|| EngineError::Param(no_filter(i)))?],
None if list.is_empty() => return Err(EngineError::State("the instance has no filters to copy".into())),
None if list.is_empty() => return Err(EngineError::State("the selection has no filters to copy".into())),
None => list,
};
let n = chosen.len();
@@ -204,7 +216,7 @@ fn put(s: &mut Session, add: &[FilterEntry], replace: bool) -> Result<usize> {
true
});
match set {
Err(_) if full => Err(EngineError::State(format!("an instance has at most {MAX_FILTERS} filters; remove some first"))),
Err(_) if full => Err(EngineError::State(format!("an object has at most {MAX_FILTERS} filters; remove some first"))),
other => other,
}
}
@@ -221,7 +233,22 @@ fn preset_json(p: &crate::filter_library::FilterPreset) -> Value {
}
fn preset_list(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({"presets": s.filter_presets.presets().iter().map(preset_json).collect::<Vec<_>>()}))
let builtin: Vec<Value> = builtins()
.iter()
.map(|p| {
let mut v = preset_json(p);
v["hidden"] = json!(s.filter_presets.is_hidden(&p.name));
v
})
.collect();
Ok(json!({"presets": s.filter_presets.presets().iter().map(preset_json).collect::<Vec<_>>(), "builtin": builtin}))
}
/// Hides a built-in preset from the presets menu, or shows it again (ADR 0099).
fn preset_hide(s: &mut Session, p: &Value) -> Result<Value> {
let hidden = opt_bool(p, "hidden")?.unwrap_or(true);
let name = s.filter_presets.set_hidden(str_req(p, "name")?, hidden)?;
Ok(json!({"name": name, "hidden": hidden, "hidden_presets": s.filter_presets.hidden()}))
}
fn preset_save(s: &mut Session, p: &Value) -> Result<Value> {
@@ -236,7 +263,7 @@ fn preset_save(s: &mut Session, p: &Value) -> Result<Value> {
fn preset_apply(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_req(p, "name")?;
let preset = s.filter_presets.find(name).cloned().ok_or_else(|| EngineError::Param(format!("you have no filter preset named '{}'", name.chars().take(64).collect::<String>())))?;
let preset = s.filter_presets.resolve(name).ok_or_else(|| EngineError::Param(format!("there is no filter preset named '{}'", name.chars().take(64).collect::<String>())))?;
let set = put(s, &preset.filters, true)?;
Ok(json!({"name": preset.name, "filters": preset.filters.len(), "set": set}))
}
@@ -261,7 +288,7 @@ fn preset_export(s: &mut Session, p: &Value) -> Result<Value> {
.take(MAX_PRESETS * 2)
.map(|n| {
let n = n.as_str().ok_or_else(bad)?;
s.filter_presets.find(n).cloned().ok_or_else(|| EngineError::Param(format!("you have no filter preset named '{}'", n.chars().take(64).collect::<String>())))
s.filter_presets.resolve(n).ok_or_else(|| EngineError::Param(format!("there is no filter preset named '{}'", n.chars().take(64).collect::<String>())))
})
.collect::<Result<_>>()?,
Some(_) => return Err(bad()),
+79 -28
View File
@@ -9,7 +9,10 @@
//!
//! Filters (ADR 0092): a filter's numbers tween as properties too, addressed by the filter's place
//! (`filter.0.blur_x`). An edit of a filter's number at the playhead keys it there; an edit that
//! reorders, removes or adds filters takes the tracks along with their filters.
//! reorders, removes or adds filters takes the tracks along with their filters. So do its
//! colours, channel by channel (`filter.0.color_red`; `filter.0.color` names all four at once),
//! and its quality and switches, whose keys hold instead of travelling (ADR 0099). Text takes
//! filters and their tracks as movie clips do.
//!
//! On a motion path, moving the object at a frame pins the path there (ADR 0049): the anchor
//! pinned to that frame moves (an end, at the first or last position key), or a new anchor is
@@ -19,7 +22,7 @@
use crate::cmds_timeline::target;
use crate::params::*;
use crate::{CommandSpec, EngineError, Result, Session};
use anicraft_doc::{Element, ElementId, ElementKind, FilterEntry, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props, filter_properties, own_value};
use anicraft_doc::{Channel, Element, ElementId, FilterColor, FilterEntry, FilterParam, FilterProp, Keyframe, Layer, LayerId, LayerKind, MAX_FILTER_SLOTS, MotionTween, Pin, PinError, Property, Props, Rgba, filter_properties, own_value};
use anicraft_geom::{Affine, Vec2};
use serde_json::{Value, json};
use std::sync::Arc;
@@ -27,9 +30,9 @@ use std::sync::Arc;
pub fn specs() -> Vec<CommandSpec> {
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
vec![
c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255)|filter.<slot>.<blur_x|blur_y|strength (%)|angle|distance|brightness|contrast|saturation|hue> (a number of the object's filter at that place, 0 the first; ADR 0092), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)", true, set_key as crate::RunFn),
c("motion.remove_key", "Remove Property Keyframe", "", None, "{property? (default: every property), frame?, layer?}", true, remove_key),
c("motion.set_ease", "Property Ease", "", None, "{easing (as timeline.set_easing takes it, saved eases too), property? (default: every property), frame? (inside the segment), layer?}", true, set_ease),
c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255)|filter.<slot>.<blur_x|blur_y|strength (%)|angle|distance|brightness|contrast|saturation|hue> (a number of the object's filter at that place, 0 the first; ADR 0092)|filter.<slot>.<color|shadow_color|highlight_color|stop_<n>>_<red|green|blue (0..255)|alpha (%)> (a channel of one of the filter's colours, stop_0 the ramp's first stop)|filter.<slot>.<quality (1..3)|inner|knockout|hide_object (0 or 1)> (stepped: a key holds until the next one; ADR 0099), value (px, %, °), frame?, layer?} or {property: filter.<slot>.<color|shadow_color|highlight_color|stop_<n>>, color: \"#rrggbb\" or \"#rrggbbaa\"} to key a filter colour's four channels at once (colour properties of several styles compose into Advanced, ADR 0056)", true, set_key as crate::RunFn),
c("motion.remove_key", "Remove Property Keyframe", "", None, "{property? (default: every property; a filter colour such as filter.0.color names its four channels), frame?, layer?}", true, remove_key),
c("motion.set_ease", "Property Ease", "", None, "{easing (as timeline.set_easing takes it, saved eases too), property? (default: every property; a filter colour such as filter.0.color names its four channels), frame? (inside the segment), layer?} (stepped properties hold their keys and take no ease)", true, set_ease),
c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is", false, info),
c("motion.set_path", "Edit Motion Path", "", None, "{d: SVG path data in stage space (its first subpath; ends are the start and end positions), layer?, frame?}", true, set_path),
c("motion.clear_path", "Remove Motion Path", "", None, "{layer?, frame?}: back to the straight path the X/Y curves trace", true, clear_path),
@@ -128,7 +131,7 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) {
let tracks_color = m.tracks.iter().any(|t| t.property.style().is_some());
let filters = key_filters(m, &e, &after);
let mut base = after;
if let (Some(f), ElementKind::Symbol { filters: slot, .. }) = (filters, &mut base.kind) {
if let (Some(f), Some(slot)) = (filters, base.kind.filters_mut()) {
*slot = f;
}
// Exact where nothing is keyed on the first frame: the edited object is the new base.
@@ -157,10 +160,7 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) {
/// those of filters that went go too. The base's new list, or `None` when there are no filters
/// to look after.
fn key_filters(m: &mut MotionTween, e: &MotionEdit, after: &Element) -> Option<Vec<FilterEntry>> {
let list = |el: &Element| match &el.kind {
ElementKind::Symbol { filters, .. } => Some(filters.clone()),
_ => None,
};
let list = |el: &Element| el.kind.filters().map(<[FilterEntry]>::to_vec);
let (before, base, mut now) = (list(&e.before)?, list(&e.base)?, list(after)?);
if !anicraft_doc::filters_pair_up(&before, &now) {
// Where each filter went: the first one left that holds the same.
@@ -189,7 +189,7 @@ fn key_filters(m: &mut MotionTween, e: &MotionEdit, after: &Element) -> Option<V
return Some(now);
}
for (slot, (was, is)) in before.iter().zip(&now).enumerate().take(usize::from(anicraft_doc::MAX_FILTER_SLOTS)) {
for &param in is.filter.params() {
for param in is.filter.params() {
let p = Property::Filter(anicraft_doc::FilterProp { slot: slot as u8, param });
let (Some(v0), Some(v1)) = (was.filter.param(param), is.filter.param(param)) else { continue };
if (v1 - v0).abs() > 1e-4 && !(e.offset == 0 && m.track(p).is_none()) {
@@ -707,14 +707,50 @@ fn property(p: &Value) -> Result<Option<Property>> {
None => Ok(None),
Some(k) => Property::from_key(k).map(Some).ok_or_else(|| {
let all: Vec<String> = Property::ALL.iter().map(|p| p.key().into_owned()).collect();
EngineError::Param(format!("unknown property '{k}' ({}, or filter.<slot>.<blur_x|blur_y|strength|angle|distance|brightness|contrast|saturation|hue>, slot 0 to 15)", all.join(", ")))
EngineError::Param(format!("unknown property '{k}' ({}, or filter.<slot>.<blur_x|blur_y|strength|angle|distance|brightness|contrast|saturation|hue|quality|inner|knockout|hide_object>, or a colour channel filter.<slot>.<color|shadow_color|highlight_color|stop_<n>>_<red|green|blue|alpha>, slot 0 to 15)", all.join(", ")))
}),
}
}
/// The four channels of the filter colour `k` names whole (`filter.<slot>.<color|shadow_color|
/// highlight_color|stop_<n>>`, ADR 0099): red, green, blue, alpha.
fn colour_channels(k: &str) -> Option<[Property; 4]> {
let (slot, name) = k.trim().strip_prefix("filter.")?.split_once('.')?;
let slot = slot.trim().parse::<u8>().ok().filter(|n| *n < MAX_FILTER_SLOTS)?;
let c = FilterColor::from_key(&name.trim().to_ascii_lowercase())?;
Some(Channel::ALL.map(|ch| Property::Filter(FilterProp { slot, param: FilterParam::Color(c, ch) })))
}
/// A colour with its alpha, as `#rrggbbaa` (what `color` params read back).
fn hex8(c: Rgba) -> String {
let c = c.sanitized();
format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8)
}
/// The properties `property` names: one, or the four channels of a filter's colour.
fn properties(p: &Value) -> Result<Option<Vec<Property>>> {
match opt_str(p, "property")?.and_then(colour_channels) {
Some(four) => Ok(Some(four.to_vec())),
None => Ok(property(p)?.map(|x| vec![x])),
}
}
fn set_key(s: &mut Session, p: &Value) -> Result<Value> {
// A filter's colour, whole: its four channels keyed together.
if let Some(four) = opt_str(p, "property")?.and_then(colour_channels) {
let c = opt_color(p, "color")?.ok_or_else(|| EngineError::Param("a filter colour takes 'color' (\"#rrggbb\" or \"#rrggbbaa\"); name a channel (…_red, …_alpha) to give a 'value'".into()))?.sanitized();
let mut frame = Value::Null;
for (prop, v) in four.into_iter().zip([c.r * 255.0, c.g * 255.0, c.b * 255.0, c.a * 100.0]) {
frame = key_value(s, p, prop, v)?["frame"].take();
}
return Ok(json!({"property": opt_str(p, "property")?, "frame": frame, "color": hex8(c)}));
}
let prop = property(p)?.ok_or_else(|| EngineError::Param("param 'property' is required".into()))?;
let value = f32_req(p, "value")?;
key_value(s, p, prop, f32_req(p, "value")?)
}
/// Keys `prop` at the frame `p` names, holding `value`.
fn key_value(s: &mut Session, p: &Value, prop: Property, value: f32) -> Result<Value> {
let r = prop.range();
if !r.contains(&value) {
return Err(EngineError::Param(format!("{} must be between {} and {} {}", prop.label(), r.start(), r.end(), prop.unit())));
@@ -724,12 +760,12 @@ fn set_key(s: &mut Session, p: &Value) -> Result<Value> {
let target = target.ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?;
let base = Props::of(&target);
let own = own_value(&target, prop).ok_or_else(|| match prop.filter() {
Some(f) => EngineError::State(match &target.kind {
ElementKind::Symbol { filters, .. } => match filters.get(usize::from(f.slot)) {
Some(e) => format!("filter {} of the tween's object is a {}, which has no {}", f.slot, e.filter.label(), f.param.label()),
Some(f) => EngineError::State(match target.kind.filters() {
Some(filters) => match filters.get(usize::from(f.slot)) {
Some(e) => format!("filter {} of the tween's object is a {}, which has no {}", f.slot, e.filter.label(), f.param.key()),
None => format!("the tween's object has no filter {} (it has {}; 0 is the first)", f.slot, filters.len()),
},
_ => "filters apply to movie clip and button instances: the tween's object has none".into(),
None => "filters apply to movie clip and button instances and to text: the tween's object has none".into(),
}),
None => EngineError::State("the motion tween's object has no such property".into()),
})?;
@@ -747,18 +783,20 @@ fn set_key(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({"property": prop.key(), "frame": start + offset, "value": value, "anchor": pin.anchor}));
}
m.set_key(prop, offset, value, own);
// A stepped value is kept whole.
let value = m.track(prop).and_then(|t| t.key_at(offset).and_then(|i| t.keys.get(i))).map_or(value, |k| k.value);
Ok(json!({"property": prop.key(), "frame": start + offset, "value": value}))
}
fn remove_key(s: &mut Session, p: &Value) -> Result<Value> {
let only = property(p)?;
let only = properties(p)?;
let (kf, offset) = motion_span(s, p)?;
let start = kf.start;
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
// Removing a pinned frame's X or Y key lets the pin go, with both keys (ADR 0049).
let pin = m.live_pins().into_iter().find(|q| q.frame == offset).filter(|_| only.is_none_or(|o| matches!(o, Property::X | Property::Y)));
let pin = m.live_pins().into_iter().find(|q| q.frame == offset).filter(|_| only.as_ref().is_none_or(|o| o.iter().any(|o| matches!(o, Property::X | Property::Y))));
let keyed: Vec<Property> = m.tracks.iter().map(|t| t.property).collect();
let mut removed: Vec<std::borrow::Cow<'static, str>> = keyed.into_iter().filter(|x| only.is_none_or(|o| o == *x)).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect();
let mut removed: Vec<std::borrow::Cow<'static, str>> = keyed.into_iter().filter(|x| only.as_ref().is_none_or(|o| o.contains(x))).filter(|x| m.remove_key(*x, offset)).map(Property::key).collect();
if pin.is_some() {
for k in [Property::X.key(), Property::Y.key()] {
if !removed.contains(&k) {
@@ -774,20 +812,26 @@ fn remove_key(s: &mut Session, p: &Value) -> Result<Value> {
fn set_ease(s: &mut Session, p: &Value) -> Result<Value> {
let easing = opt_easing_in(s, p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?;
let only = property(p)?;
let only = properties(p)?;
let label = easing.label();
let (kf, offset) = motion_span(s, p)?;
let start = kf.start;
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
if let Some([one]) = only.as_deref()
&& one.is_stepped()
{
return Err(EngineError::State(format!("{} is stepped: a key holds until the next one, so it takes no ease", one.key())));
}
let mut set = Vec::new();
for t in m.tracks.iter_mut().filter(|t| only.is_none_or(|o| o == t.property)) {
// Stepped tracks hold their keys: an ease would do nothing, so they keep none (ADR 0099).
for t in m.tracks.iter_mut().filter(|t| !t.property.is_stepped() && only.as_ref().is_none_or(|o| o.contains(&t.property))) {
if let Some(k) = t.segment_at(offset).and_then(|i| t.keys.get_mut(i)) {
k.ease = easing.clone();
set.push(t.property.key());
}
}
if set.is_empty() {
return Err(EngineError::State(format!("frame {} is not between two property keyframes{}", start + offset + 1, only.map_or_else(String::new, |o| format!(" of {}", o.label())))));
return Err(EngineError::State(format!("frame {} is not between two property keyframes{}", start + offset + 1, only.as_deref().and_then(<[Property]>::first).map_or_else(String::new, |o| format!(" of {}", o.label())))));
}
Ok(json!({"easing": label, "properties": set}))
}
@@ -801,10 +845,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let target = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i));
let base = target.map(|e| Props::of(e));
let now = base.map(|b| m.props_at(&b, (frame - kf.start) as f32));
let filter_of = |slot: u8| match target.map(|e| &e.kind) {
Some(ElementKind::Symbol { filters, .. }) => filters.get(usize::from(slot)).map(|e| e.filter.label()),
_ => None,
};
let filter_of = |slot: u8| target.and_then(|e| e.kind.filters()).and_then(|f| f.get(usize::from(slot))).map(|e| e.filter.label());
let tracks: Vec<Value> = m
.tracks
.iter()
@@ -815,11 +856,14 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(f) = t.property.filter() {
v["filter"] = json!({"slot": f.slot, "kind": filter_of(f.slot)});
}
if t.property.is_stepped() {
v["stepped"] = json!(true);
}
v
})
.collect();
let mut values: serde_json::Map<String, Value> = Property::ALL.iter().filter_map(|p| now.map(|n| (p.key().into_owned(), json!(n.get(*p))))).collect();
// And the filters' numbers at the frame.
// And the filters' values at the frame, with each colour whole (ADR 0099).
if let Some(e) = target {
let at = m.apply(e, (frame - kf.start) as f32);
for p in filter_properties(e) {
@@ -827,6 +871,13 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
values.insert(p.key().into_owned(), json!(v));
}
}
for (slot, entry) in at.kind.filters().into_iter().flatten().enumerate() {
for c in entry.filter.colors() {
if let Some(rgba) = entry.filter.color(c) {
values.insert(format!("filter.{slot}.{}", c.key()), json!(hex8(rgba)));
}
}
}
}
// Where the object is (on a motion path the X/Y values are its timing, not its place).
let position = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| m.apply(e, (frame - kf.start) as f32).transform.translation()).map(|q| json!([q.x, q.y]));
+1 -1
View File
@@ -50,7 +50,7 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> {
// Filter lists are the document's (ADR 0091); copied filters are the artist's
// clipboard, and the presets their preferences (listing and applying one is fine).
"filter" if matches!(id, "filter.copy" | "filter.paste") => Err("plug-ins don't use your clipboard"),
"filter" if matches!(id, "filter.preset_save" | "filter.preset_rename" | "filter.preset_delete" | "filter.preset_export" | "filter.preset_import") => Err("plug-ins can't change your filter presets or read and write preset files"),
"filter" if matches!(id, "filter.preset_save" | "filter.preset_rename" | "filter.preset_delete" | "filter.preset_hide" | "filter.preset_export" | "filter.preset_import") => Err("plug-ins can't change your filter presets or read and write preset files"),
"filter" => Ok(()),
// The document's swatches are document data; swatch files are files.
"swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"),
+110 -7
View File
@@ -1,5 +1,10 @@
//! Filter presets (ADR 0091): named filter lists of the user's own, as Animate's Filters panel
//! keeps them (Save as Preset, apply, rename, delete).
//! keeps them (Save as Preset, apply, rename, delete), and the built-in ones (ADR 0099).
//!
//! The built-in presets are AniCraft's own, written here from the filters' parameters (no
//! other product's presets or values). They are always there: they can't be renamed, replaced
//! or deleted, only hidden from the menu, and a hidden one still applies by name, so a script
//! or a plug-in that names one works on every computer.
//!
//! Like the user's brushes (ADR 0068) the presets belong to the session, not the document: they
//! survive New and Open, the desktop app keeps them in its preferences and puts them back at
@@ -8,7 +13,7 @@
//! instances: a preset edited or deleted later never changes artwork behind the artist's back.
use crate::{EngineError, Result};
use anicraft_doc::FilterEntry;
use anicraft_doc::{Filter, FilterEntry, FilterSide, Rgba};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -53,11 +58,52 @@ fn same_name(a: &str, b: &str) -> bool {
a.trim().to_lowercase() == b.trim().to_lowercase()
}
/// The user's filter presets, in the order they were saved; names are unique, case aside.
/// The built-in presets' names (English; the interface translates them where it draws them),
/// in the order the menu shows them.
pub const BUILTIN_NAMES: [&str; 8] = ["Soft Shadow", "Hard Shadow", "Neon Glow", "Outline", "Emboss", "Engrave", "Soft Focus", "Greyscale"];
/// The built-in presets (ADR 0099), in menu order. The values are AniCraft's own.
pub fn builtins() -> Vec<FilterPreset> {
let shadow = |blur: f32, strength: f32, quality: u8, angle: f32, distance: f32| Filter::DropShadow { blur_x: blur, blur_y: blur, strength, quality, angle, distance, color: Rgba::BLACK, inner: false, knockout: false, hide_object: false };
let glow = |blur: f32, strength: f32, color: u32| Filter::Glow { blur_x: blur, blur_y: blur, strength, quality: 3, color: Rgba::hex(color), inner: false, knockout: false };
// A bevel lit from `angle`'s far side (45: light from the top left, so the edge looks raised;
// 225: from the bottom right, so it looks cut in).
let bevel = |angle: f32| Filter::Bevel { blur_x: 3.0, blur_y: 3.0, strength: 1.2, quality: 3, angle, distance: 2.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side: FilterSide::Inner, knockout: false };
let lists: [Vec<Filter>; 8] = [
vec![shadow(12.0, 0.45, 3, 60.0, 6.0)],
vec![shadow(0.0, 0.5, 1, 45.0, 5.0)],
// A tight bright core inside a wide halo.
vec![glow(4.0, 2.2, 0x9ff6ff), glow(22.0, 1.3, 0x1fb6ff)],
// A small glow at full strength reads as a line round the artwork.
vec![glow(3.0, 10.0, 0x000000)],
vec![bevel(45.0)],
vec![bevel(225.0)],
vec![Filter::Blur { blur_x: 6.0, blur_y: 6.0, quality: 3 }],
vec![Filter::AdjustColor { brightness: 0.0, contrast: 0.0, saturation: -100.0, hue: 0.0 }],
];
BUILTIN_NAMES.iter().zip(lists).map(|(name, filters)| FilterPreset { name: (*name).to_string(), filters: filters.iter().map(|f| FilterEntry::from(f.sanitized())).collect() }).collect()
}
/// The built-in preset called `name` (case aside), as it is written.
pub fn builtin_name(name: &str) -> Option<&'static str> {
BUILTIN_NAMES.into_iter().find(|n| same_name(n, name))
}
/// Whether `name` is a built-in preset's.
pub fn is_builtin_name(name: &str) -> bool {
builtin_name(name).is_some()
}
/// The user's filter presets, in the order they were saved; names are unique, case aside, and
/// never a built-in preset's. With them, which built-in presets the user has hidden from the
/// menu (kept apart in the preferences, so the list of presets stays what older builds read).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct FilterLibrary {
presets: Vec<FilterPreset>,
/// Built-in presets hidden from the menu, by name as [`BUILTIN_NAMES`] writes it.
#[serde(skip)]
hidden: Vec<String>,
}
#[derive(Serialize, Deserialize)]
@@ -90,7 +136,52 @@ impl FilterLibrary {
/// The same library with every entry sanitized (after deserializing preferences).
pub fn sanitized(self) -> FilterLibrary {
FilterLibrary::from_values(self.presets.into_iter().filter_map(|p| serde_json::to_value(p).ok()))
let mut lib = FilterLibrary::from_values(self.presets.into_iter().filter_map(|p| serde_json::to_value(p).ok()));
lib.restore_hidden(&self.hidden);
lib
}
/// The built-in presets hidden from the menu.
pub fn hidden(&self) -> &[String] {
&self.hidden
}
pub fn is_hidden(&self, name: &str) -> bool {
self.hidden.iter().any(|h| same_name(h, name))
}
/// The built-in presets the menu shows: all but the hidden ones.
pub fn shown_builtins(&self) -> Vec<FilterPreset> {
builtins().into_iter().filter(|p| !self.is_hidden(&p.name)).collect()
}
/// Sets which built-in presets are hidden, from the preferences: names that aren't a
/// built-in preset's are dropped.
pub fn restore_hidden(&mut self, names: &[String]) {
self.hidden = BUILTIN_NAMES.into_iter().filter(|b| names.iter().take(MAX_PRESETS).any(|n| same_name(n, b))).map(str::to_string).collect();
}
/// Hides the built-in preset `name` from the menu, or shows it again. Its name as written.
pub fn set_hidden(&mut self, name: &str, hidden: bool) -> Result<String> {
let Some(builtin) = builtin_name(name) else {
return Err(match self.find(name) {
Some(p) => EngineError::Param(format!("'{}' is a preset of yours; only built-in presets are hidden (delete it instead)", p.name)),
None => Self::missing(name),
});
};
self.hidden.retain(|h| !same_name(h, builtin));
if hidden {
self.hidden.push(builtin.to_string());
// In menu order, so the preferences don't change with the order of hiding.
let kept = std::mem::take(&mut self.hidden);
self.restore_hidden(&kept);
}
Ok(builtin.to_string())
}
/// The preset called `name`: one of the user's, or a built-in one (hidden or not).
pub fn resolve(&self, name: &str) -> Option<FilterPreset> {
self.find(name).cloned().or_else(|| builtins().into_iter().find(|p| same_name(&p.name, name)))
}
pub fn position(&self, name: &str) -> Option<usize> {
@@ -109,6 +200,9 @@ impl FilterLibrary {
/// and whether it replaced one.
pub fn save(&mut self, name: &str, filters: &[FilterEntry]) -> Result<(String, bool)> {
let p = FilterPreset { name: name.to_string(), filters: filters.to_vec() }.sanitized().ok_or_else(|| EngineError::Param("a filter preset needs a name".into()))?;
if let Some(b) = builtin_name(&p.name) {
return Err(EngineError::Param(format!("'{b}' is a built-in filter preset; save yours under another name")));
}
if p.filters.is_empty() {
return Err(EngineError::State("there are no filters to save; add one first".into()));
}
@@ -136,7 +230,7 @@ impl FilterLibrary {
let base = p.name.clone();
let mut name = base.clone();
let mut k = 2;
while self.position(&name).is_some() {
while self.position(&name).is_some() || is_builtin_name(&name) {
if k > MAX_PRESETS + 10 {
return Err(EngineError::State("too many filter presets of that name".into()));
}
@@ -149,8 +243,14 @@ impl FilterLibrary {
}
pub fn rename(&mut self, name: &str, to: &str) -> Result<String> {
let i = self.position(name).ok_or_else(|| Self::missing(name))?;
let i = self.position(name).ok_or_else(|| match builtin_name(name) {
Some(b) => EngineError::Param(format!("'{b}' is a built-in filter preset; it keeps its name")),
None => Self::missing(name),
})?;
let to = clean_name(to).ok_or_else(|| EngineError::Param("a filter preset needs a name".into()))?;
if let Some(b) = builtin_name(&to) {
return Err(EngineError::Param(format!("'{b}' is a built-in filter preset's name")));
}
if self.position(&to).is_some_and(|j| j != i) {
return Err(EngineError::Param(format!("you already have a filter preset named '{to}'")));
}
@@ -161,7 +261,10 @@ impl FilterLibrary {
}
pub fn delete(&mut self, name: &str) -> Result<FilterPreset> {
let i = self.position(name).ok_or_else(|| Self::missing(name))?;
let i = self.position(name).ok_or_else(|| match builtin_name(name) {
Some(b) => EngineError::Param(format!("'{b}' is a built-in filter preset: it can't be deleted, only hidden (filter.preset_hide)")),
None => Self::missing(name),
})?;
Ok(self.presets.remove(i))
}
+2
View File
@@ -1219,6 +1219,8 @@ mod tests_filter;
#[cfg(test)]
mod tests_filter_tracks;
#[cfg(test)]
mod tests_filter_colour;
#[cfg(test)]
mod desktop_tests;
#[cfg(test)]
mod merge_tests;
+7 -2
View File
@@ -239,9 +239,14 @@ fn classic_tweens_carry_blur_and_glow_to_their_midpoint() {
let dl = anicraft_doc::evaluate(&s.doc, 5);
let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group");
assert_eq!(g.filters.len(), 1, "only the blur draws");
// Reordered on one keyframe, the lists no longer pair up: the first keyframe's holds.
// Reordered on one keyframe, the lists no longer pair one to one (ADR 0099): the blur both
// keyframes have still travels, the first keyframe's glow (off) fades out where it stood
// and the second keyframe's fades in after the blur. The first keyframe shows its own.
run(&mut s, "filter.move", json!({"from": 1, "to": 0}));
let dl = anicraft_doc::evaluate(&s.doc, 5);
let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group");
assert!(matches!(g.filters[0], Filter::Blur { blur_x, .. } if blur_x == 0.0), "{:?}", g.filters);
assert!(matches!(g.filters[..], [Filter::Blur { blur_x, .. }, Filter::Glow { strength, .. }] if blur_x == 10.0 && strength == 1.0), "{:?}", g.filters);
let dl = anicraft_doc::evaluate(&s.doc, 0);
let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group");
assert!(matches!(g.filters[..], [Filter::Blur { blur_x, .. }] if blur_x == 0.0), "{:?}", g.filters);
}
+372
View File
@@ -0,0 +1,372 @@
//! The last slice of filters (ADR 0099), through the command registry: colour tracks, stepped
//! quality and switches, classic tweens of lists that differ, the built-in presets, and filters
//! on text.
use super::*;
use anicraft_doc::{Channel, ElementKind, Filter, FilterColor, FilterEntry, FilterParam, FilterProp, Property, Rgba};
use serde_json::json;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
fn refused(s: &mut Session, id: &str, p: Value) -> String {
match s.execute(id, &p) {
Ok(v) => panic!("{id} {p} should be refused, gave {v}"),
Err(EngineError::NeedsConfirmation(c)) => panic!("{id} {p} should be refused, not asked about: {c}"),
Err(e) => e.to_string(),
}
}
/// A red 100 × 100 movie clip at (100, 100), selected.
fn clip() -> Session {
let mut s = Session::default();
run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"}));
run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"}));
s
}
/// The clip with `filters`, in a one-second motion tween.
fn tweened(filters: Value) -> Session {
let mut s = clip();
run(&mut s, "element.set_filters", json!({ "filters": filters }));
run(&mut s, "timeline.create_motion_tween", json!({}));
s
}
/// The first element's filters as its keyframe holds them.
fn list(s: &Session) -> Vec<FilterEntry> {
s.doc.timeline(s.scene).layers[0].keyframes[0].elements[0].kind.filters().map(<[FilterEntry]>::to_vec).unwrap_or_default()
}
/// The filters the renderers get at `frame`.
fn drawn(s: &Session, frame: u32) -> Vec<Filter> {
anicraft_doc::evaluate(&s.doc, frame).groups.iter().find(|g| !g.filters.is_empty()).map(|g| g.filters.to_vec()).unwrap_or_default()
}
fn px(s: &Session, frame: u32, x: u32, y: u32) -> [f32; 4] {
anicraft_render::render_frame(&s.doc, frame, 1.0).unwrap().pixel(x, y).unwrap()
}
fn track_keys(s: &mut Session, key: &str) -> Vec<(u64, f64)> {
let v = run(s, "motion.info", json!({}));
let t = v["tracks"].as_array().and_then(|ts| ts.iter().find(|t| t["property"] == key).cloned());
t.map(|t| t["keys"].as_array().map(|ks| ks.iter().map(|k| (k["frame"].as_u64().unwrap_or(0), k["value"].as_f64().unwrap_or(0.0))).collect()).unwrap_or_default()).unwrap_or_default()
}
fn channel(slot: u8, c: FilterColor, ch: Channel) -> Property {
Property::Filter(FilterProp { slot, param: FilterParam::Color(c, ch) })
}
/// A glow's colour keyed whole travels channel by channel: at the midpoint every channel is
/// half way, in the display list and in the pixels.
#[test]
fn a_glow_colour_tweens_to_its_midpoint() {
let mut s = tweened(json!([{"type": "glow", "color": "#00ff00", "blur_x": 20, "blur_y": 20, "strength": 4, "quality": 2}]));
let v = run(&mut s, "motion.set_key", json!({"property": "filter.0.color", "frame": 12, "color": "#0000ff"}));
assert_eq!((v["frame"].as_u64(), v["color"].as_str()), (Some(12), Some("#0000ffff")));
// Four tracks, one per channel, each pinned to the object's own colour at the start.
assert_eq!(track_keys(&mut s, "filter.0.color_green"), vec![(0, 255.0), (12, 0.0)]);
assert_eq!(track_keys(&mut s, "filter.0.color_blue"), vec![(0, 0.0), (12, 255.0)]);
assert_eq!(track_keys(&mut s, "filter.0.color_red"), vec![(0, 0.0), (12, 0.0)]);
assert_eq!(track_keys(&mut s, "filter.0.color_alpha"), vec![(0, 100.0), (12, 100.0)]);
// The midpoint, exactly: what the renderers and every export draw.
let Some(Filter::Glow { color, .. }) = drawn(&s, 6).first().cloned() else { panic!("a glow") };
assert_eq!(color, Rgba::new(0.0, 0.5, 0.5, 1.0));
assert_eq!(color, Rgba::hex(0x00ff00).lerp(Rgba::hex(0x0000ff), 0.5), "as a colour effect's tint travels");
let info = run(&mut s, "motion.info", json!({"frame": 6}));
assert_eq!(info["values"]["filter.0.color"], "#008080ff");
assert_eq!(info["values"]["filter.0.color_green"], 127.5);
// The pixels just left of the box: green at the start, blue at the end, both equally mid-way.
let (a, mid, b) = (px(&s, 0, 95, 150), px(&s, 6, 95, 150), px(&s, 12, 95, 150));
assert!(a[1] > 0.99 && a[2] < 0.9 && a[0] < 0.9, "green glow over white: {a:?}");
assert!(b[2] > 0.99 && b[1] < 0.9, "blue glow over white: {b:?}");
assert!((mid[1] - mid[2]).abs() < 1e-5 && mid[0] < mid[1], "half green, half blue: {mid:?}");
// A still clip with that colour draws the same picture.
let mut still = clip();
let mut f = list(&s);
f[0].filter.set_param(FilterParam::Color(FilterColor::Color, Channel::Green), 127.5);
f[0].filter.set_param(FilterParam::Color(FilterColor::Color, Channel::Blue), 127.5);
run(&mut still, "element.set_filters", json!({ "filters": f }));
assert_eq!(anicraft_render::render_frame(&s.doc, 6, 1.0).unwrap().data, anicraft_render::render_frame(&still.doc, 0, 1.0).unwrap().data);
// One channel on its own, with an ease of its own.
run(&mut s, "motion.set_key", json!({"property": "filter.0.color_alpha", "frame": 12, "value": 50}));
run(&mut s, "motion.set_ease", json!({"property": "filter.0.color_alpha", "frame": 3, "easing": "QuadIn"}));
let Some(Filter::Glow { color, .. }) = drawn(&s, 6).first().cloned() else { panic!("a glow") };
assert_eq!(color.a, 0.875, "100 % to 50 %, a quarter of the way");
// The whole colour takes an ease on its four channels, and its key goes as one.
let v = run(&mut s, "motion.set_ease", json!({"property": "filter.0.color", "frame": 3, "easing": "CubicOut"}));
assert_eq!(v["properties"].as_array().map(Vec::len), Some(4));
let v = run(&mut s, "motion.remove_key", json!({"property": "filter.0.color", "frame": 12}));
assert_eq!(v["removed"].as_array().map(Vec::len), Some(4));
// What can't be keyed says why.
for (p, want) in [
(json!({"property": "filter.0.color", "value": 3}), "takes 'color'"),
(json!({"property": "filter.0.color", "color": "nope"}), "colour"),
(json!({"property": "filter.0.color_red", "value": 256}), "between"),
(json!({"property": "filter.0.shadow_color_red", "value": 1}), "has no shadow_color_red"),
(json!({"property": "filter.0.stop_0_red", "value": 1}), "has no stop_0_red"),
(json!({"property": "filter.0.stop_99_red", "value": 1}), "unknown property"),
(json!({"property": "filter.3.color", "color": "#ffffff"}), "no filter 3"),
] {
let e = refused(&mut s, "motion.set_key", p.clone());
assert!(e.contains(want), "{p}: {e}");
}
}
/// Quality and the switches hold their keys: the frame before a key draws the old value, the
/// key's frame exactly the new one.
#[test]
fn a_switch_steps_exactly_at_its_key() {
let mut s = tweened(json!([{"type": "glow", "color": "#0000ff", "blur_x": 10, "blur_y": 10, "strength": 2}]));
let v = run(&mut s, "motion.set_key", json!({"property": "filter.0.knockout", "frame": 6, "value": 1}));
assert_eq!(v["value"], 1.0);
run(&mut s, "motion.set_key", json!({"property": "filter.0.quality", "frame": 4, "value": 2.6}));
assert_eq!(track_keys(&mut s, "filter.0.quality"), vec![(0, 1.0), (4, 3.0)], "a stepped key is a whole number");
let at = |s: &Session, f: u32| match drawn(s, f).first() {
Some(Filter::Glow { knockout, quality, .. }) => (*knockout, *quality),
other => panic!("{other:?}"),
};
assert_eq!([0, 3, 4, 5, 6, 20].map(|f| at(&s, f)), [(false, 1), (false, 1), (false, 3), (false, 3), (true, 3), (true, 3)]);
// The pixels: the box is there on frame 5 and knocked out on frame 6 (the glow stays).
let (before, on) = (px(&s, 5, 150, 150), px(&s, 6, 150, 150));
assert!(before[0] > 0.99 && before[1] < 0.01, "the red box: {before:?}");
assert!(on[1] > 0.99 && on[2] > 0.99 && on[0] > 0.99, "knocked out to the white stage: {on:?}");
assert!(px(&s, 6, 96, 150)[0] < 0.9, "the glow still draws round it");
// motion.info marks them, and they take no ease.
let info = run(&mut s, "motion.info", json!({"frame": 5}));
let t = info["tracks"].as_array().unwrap().iter().find(|t| t["property"] == "filter.0.knockout").unwrap().clone();
assert_eq!((t["stepped"].as_bool(), t["label"].as_str()), (Some(true), Some("Knockout")));
assert_eq!((info["values"]["filter.0.knockout"].as_f64(), info["values"]["filter.0.quality"].as_f64()), (Some(0.0), Some(3.0)));
assert!(refused(&mut s, "motion.set_ease", json!({"property": "filter.0.knockout", "frame": 2, "easing": "QuadIn"})).contains("stepped"));
// An ease for every property skips them.
run(&mut s, "motion.set_key", json!({"property": "filter.0.blur_x", "frame": 6, "value": 30}));
let v = run(&mut s, "motion.set_ease", json!({"frame": 2, "easing": "QuadIn"}));
assert_eq!(v["properties"], json!(["filter.0.blur_x"]));
assert_eq!(at(&s, 5), (false, 3), "still held");
// Moving a key in time moves the step with it.
run(&mut s, "motion.move_keys", json!({"keys": [{"property": "filter.0.knockout", "frame": 6}], "by": 3}));
assert_eq!([8, 9].map(|f| at(&s, f).0), [false, true]);
// Out of range, or a switch the filter doesn't have.
assert!(refused(&mut s, "motion.set_key", json!({"property": "filter.0.quality", "value": 4})).contains("between"));
assert!(refused(&mut s, "motion.set_key", json!({"property": "filter.0.hide_object", "value": 1})).contains("has no hide_object"));
// Hide object, on a drop shadow: the shadow alone from the key on.
let mut s = tweened(json!([{"type": "drop_shadow", "distance": 30, "angle": 0, "blur_x": 0, "blur_y": 0, "color": "#000000"}]));
run(&mut s, "motion.set_key", json!({"property": "filter.0.hide_object", "frame": 8, "value": 1}));
assert!(px(&s, 7, 110, 150)[0] > 0.99 && px(&s, 7, 110, 150)[1] < 0.01, "the box on frame 7");
assert!(px(&s, 8, 110, 150)[0] > 0.99 && px(&s, 8, 110, 150)[1] > 0.99, "hidden on frame 8");
assert!(px(&s, 8, 215, 150)[0] < 0.01, "its shadow stays");
}
/// Editing a filter's colour or a switch in Properties inside the tween keys what changed at
/// the playhead, one undo step, like its numbers.
#[test]
fn editing_a_colour_or_a_switch_inside_the_tween_keys_it() {
let mut s = tweened(json!([{"type": "bevel", "highlight_color": "#ffffff", "shadow_color": "#000000"}]));
let steps = s.history_len();
s.set_frame(10);
run(&mut s, "element.set_filters", json!({"filters": [{"type": "bevel", "highlight_color": "#ffff00", "shadow_color": "#000000", "knockout": true, "quality": 3}]}));
assert_eq!(s.history_len(), steps + 1, "one undo step");
assert_eq!(track_keys(&mut s, "filter.0.highlight_color_blue"), vec![(0, 255.0), (10, 0.0)]);
assert!(track_keys(&mut s, "filter.0.highlight_color_red").is_empty(), "only the channel that changed");
assert!(track_keys(&mut s, "filter.0.shadow_color_red").is_empty());
assert_eq!(track_keys(&mut s, "filter.0.knockout"), vec![(0, 0.0), (10, 1.0)]);
assert_eq!(track_keys(&mut s, "filter.0.quality"), vec![(0, 1.0), (10, 3.0)]);
// The object keeps its own underneath; the tracks give the rest.
assert!(matches!(list(&s)[0].filter, Filter::Bevel { knockout: false, quality: 1, highlight_color, .. } if highlight_color == Rgba::WHITE));
assert!(matches!(drawn(&s, 5).first(), Some(Filter::Bevel { knockout: false, quality: 1, highlight_color, .. }) if *highlight_color == Rgba::new(1.0, 1.0, 0.5, 1.0)));
assert!(matches!(drawn(&s, 10).first(), Some(Filter::Bevel { knockout: true, quality: 3, .. })));
run(&mut s, "edit.undo", json!({}));
assert!(track_keys(&mut s, "filter.0.knockout").is_empty() && track_keys(&mut s, "filter.0.highlight_color_blue").is_empty());
// A ramp's stops are keyed by their place.
let mut s = tweened(json!([{"type": "gradient_glow", "stops": [{"offset": 0, "color": "#ffffff00"}, {"offset": 1, "color": "#ff0000"}]}]));
s.set_frame(10);
run(&mut s, "element.set_filters", json!({"filters": [{"type": "gradient_glow", "stops": [{"offset": 0, "color": "#ffffff00"}, {"offset": 1, "color": "#0000ff"}]}]}));
assert_eq!(track_keys(&mut s, "filter.0.stop_1_red"), vec![(0, 255.0), (10, 0.0)]);
assert_eq!(track_keys(&mut s, "filter.0.stop_1_blue"), vec![(0, 0.0), (10, 255.0)]);
let Some(Filter::GradientGlow { stops, .. }) = drawn(&s, 5).first().cloned() else { panic!() };
assert_eq!(stops[1].color, Rgba::new(0.5, 0.0, 0.5, 1.0));
// F6 keys everything a filter has, and the file keeps the tracks.
run(&mut s, "timeline.insert_keyframe", json!({}));
assert_eq!(track_keys(&mut s, "filter.0.knockout"), vec![(0, 0.0), (10, 0.0)]);
assert_eq!(track_keys(&mut s, "filter.0.stop_0_alpha"), vec![(0, 0.0), (10, 0.0)]);
let json = serde_json::to_string(&s.doc).unwrap();
assert!(json.contains("filter.0.stop_1_red") && json.contains("filter.0.knockout"));
let back: anicraft_doc::Document = serde_json::from_str(&json).unwrap();
assert!(back == s.doc);
assert!(back.timeline(0).layers[0].keyframes[0].motion.as_ref().is_some_and(|m| m.track(channel(0, FilterColor::Stop(1), Channel::Red)).is_some()));
}
/// A classic tween between keyframes whose filter lists differ: what they share travels, a
/// filter only one keyframe has fades in or out, and the first keyframe shows its own list.
#[test]
fn classic_tweens_fade_filters_only_one_keyframe_has() {
let mut s = clip();
run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 0, "blur_y": 0}]}));
run(&mut s, "timeline.goto", json!({"frame": 10}));
run(&mut s, "timeline.insert_keyframe", json!({}));
run(&mut s, "edit.select_all", json!({}));
run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 20, "blur_y": 20}, {"type": "glow", "strength": 2, "blur_x": 8, "blur_y": 8, "color": "#0000ff"}]}));
run(&mut s, "timeline.goto", json!({"frame": 0}));
run(&mut s, "timeline.create_tween", json!({"easing": "Linear"}));
assert_eq!(drawn(&s, 0), vec![Filter::Blur { blur_x: 0.0, blur_y: 0.0, quality: 1 }], "the first keyframe's own list");
let mid = drawn(&s, 5);
assert_eq!(mid.len(), 2);
assert_eq!(mid[0], Filter::Blur { blur_x: 10.0, blur_y: 10.0, quality: 1 });
assert!(matches!(mid[1], Filter::Glow { strength, blur_x, color, .. } if strength == 1.0 && blur_x == 4.0 && color == Rgba::hex(0x0000ff)), "{:?}", mid[1]);
assert_eq!(drawn(&s, 10).len(), 2);
// It renders like a still clip with those filters.
let mut still = clip();
run(&mut still, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 10, "blur_y": 10}, {"type": "glow", "strength": 1, "blur_x": 4, "blur_y": 4, "color": "#0000ff"}]}));
assert_eq!(anicraft_render::render_frame(&s.doc, 5, 1.0).unwrap().data, anicraft_render::render_frame(&still.doc, 0, 1.0).unwrap().data);
}
/// The built-in presets are always there: they apply by name, can't be renamed, replaced or
/// deleted, and hiding one only takes it off the menu.
#[test]
fn built_in_presets_are_there_read_only_and_can_be_hidden() {
let mut s = clip();
let names = crate::filter_library::BUILTIN_NAMES;
let listed = run(&mut s, "filter.preset_list", json!({}));
assert_eq!(listed["presets"], json!([]), "none of your own yet");
let builtin = listed["builtin"].as_array().unwrap();
assert_eq!(builtin.iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(), names);
for b in builtin {
assert_eq!(b["hidden"], false);
assert!(b["filters"].as_array().is_some_and(|f| !f.is_empty()), "{b}");
}
for name in ["Soft Shadow", "Neon Glow", "Emboss"] {
assert!(names.contains(&name), "{name}");
}
// Each is in range as written, and applies.
for p in crate::filter_library::builtins() {
assert!(!p.filters.is_empty() && p.filters.iter().all(|f| f.enabled && f.sanitized() == *f), "{}", p.name);
let v = run(&mut s, "filter.preset_apply", json!({"name": p.name.to_uppercase()}));
assert_eq!(v["name"], p.name);
assert_eq!(list(&s), p.filters);
}
run(&mut s, "filter.preset_apply", json!({"name": "neon glow"}));
assert!(matches!(list(&s).as_slice(), [FilterEntry { filter: Filter::Glow { .. }, .. }, FilterEntry { filter: Filter::Glow { .. }, .. }]));
assert!(px(&s, 0, 92, 150)[0] < 0.95, "the glow draws round the box");
// Read-only: refused outright (never asked about), with the reason.
assert!(refused(&mut s, "filter.preset_delete", json!({"name": "Emboss"})).contains("can't be deleted, only hidden"));
assert!(refused(&mut s, "filter.preset_delete", json!({"name": "emboss", "confirm": true})).contains("built-in"));
assert!(refused(&mut s, "filter.preset_rename", json!({"name": "Emboss", "to": "Mine"})).contains("keeps its name"));
assert!(refused(&mut s, "filter.preset_save", json!({"name": "soft shadow"})).contains("built-in"));
assert!(refused(&mut s, "filter.preset_save", json!({"name": "Soft Shadow", "confirm": true})).contains("built-in"));
run(&mut s, "filter.preset_save", json!({"name": "Mine"}));
assert!(refused(&mut s, "filter.preset_rename", json!({"name": "Mine", "to": "Outline"})).contains("built-in"));
assert_eq!(crate::filter_library::builtins().len(), names.len());
// Hidden: off the menu, still there by name; shown again.
let v = run(&mut s, "filter.preset_hide", json!({"name": "greyscale"}));
assert_eq!((v["name"].as_str(), v["hidden"].as_bool()), (Some("Greyscale"), Some(true)));
run(&mut s, "filter.preset_hide", json!({"name": "Emboss"}));
assert_eq!(s.filter_presets.hidden(), ["Emboss", "Greyscale"], "kept in menu order");
let listed = run(&mut s, "filter.preset_list", json!({}));
assert_eq!(listed["builtin"].as_array().unwrap().iter().filter(|b| b["hidden"] == true).count(), 2);
assert_eq!(s.filter_presets.shown_builtins().len(), names.len() - 2);
run(&mut s, "filter.preset_apply", json!({"name": "Greyscale"}));
assert!(matches!(list(&s).as_slice(), [FilterEntry { filter: Filter::AdjustColor { .. }, .. }]));
run(&mut s, "filter.preset_hide", json!({"name": "Greyscale", "hidden": false}));
assert_eq!(s.filter_presets.hidden(), ["Emboss"]);
assert!(refused(&mut s, "filter.preset_hide", json!({"name": "Mine"})).contains("preset of yours"));
assert!(refused(&mut s, "filter.preset_hide", json!({"name": "nope"})).contains("no filter preset"));
// What is hidden survives a new document and the preferences' round trip, junk dropped.
run(&mut s, "file.new", json!({"confirm": true}));
assert_eq!(s.filter_presets.hidden(), ["Emboss"]);
let mut lib = crate::filter_library::FilterLibrary::default();
lib.restore_hidden(&["emboss".into(), "Mine".into(), "Outline".into(), "Outline".into()]);
assert_eq!(lib.hidden(), ["Outline", "Emboss"]);
assert_eq!(lib.clone().sanitized(), lib);
assert_eq!(serde_json::to_value(&lib).unwrap(), json!([]), "the presets list in the preferences stays a list");
// A file's preset with a built-in's name comes in numbered; built-ins export by name.
let dir = std::env::temp_dir().join(format!("anicraft-builtin-presets-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("p.json").display().to_string();
let v = run(&mut s, "filter.preset_export", json!({"path": path, "names": ["Emboss", "Mine"]}));
assert_eq!(v["presets"], 2);
let v = run(&mut s, "filter.preset_import", json!({"path": path}));
assert_eq!(v["imported"], json!(["Emboss 2", "Mine 2"]));
let _ = std::fs::remove_dir_all(&dir);
// Plug-ins may list and apply presets, not hide them (the menu is the artist's).
assert!(crate::cmds_plugin::plugin_may_call("filter.preset_apply").is_ok());
assert!(crate::cmds_plugin::plugin_may_call("filter.preset_hide").is_err());
}
/// Text takes filters as a movie clip does: a drop shadow under the glyphs, in the pixels; the
/// list survives edits of the words and of the text type; graphics are still refused.
#[test]
fn text_takes_filters_and_keeps_them() {
if anicraft_text::Fonts::get().families().is_empty() {
eprintln!("no fonts on this computer: text test skipped");
return;
}
let mut s = Session::default();
run(&mut s, "text.create", json!({"text": "HI", "x": 100, "y": 60, "size": 96, "bold": true, "color": "#000000"}));
let plain = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
// A red shadow straight down, 30 px, sharp.
let v = run(&mut s, "element.set_filters", json!({"filters": [{"type": "drop_shadow", "angle": 90, "distance": 30, "blur_x": 0, "blur_y": 0, "strength": 1, "color": "#ff0000"}]}));
assert_eq!((v["filters"].as_u64(), v["set"].as_u64()), (Some(1), Some(1)));
assert_eq!(list(&s).len(), 1);
let shadowed = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
let ink = |p: [f32; 4]| p[0] < 0.1 && p[1] < 0.1 && p[2] < 0.1;
let white = |p: [f32; 4]| p[0] > 0.99 && p[1] > 0.99 && p[2] > 0.99;
let red = |p: [f32; 4]| p[0] > 0.9 && p[1] < 0.1 && p[2] < 0.1;
// Glyph pixels whose spot 30 px below was empty stage: there the shadow shows, red.
let (mut inked, mut shadows) = (0, 0);
for y in 0..plain.height.saturating_sub(30) {
for x in 0..plain.width {
let (Some(here), Some(below)) = (plain.pixel(x, y), plain.pixel(x, y + 30)) else { continue };
if ink(here) {
inked += 1;
assert!(ink(shadowed.pixel(x, y).unwrap()), "the text draws over its shadow at {x},{y}");
if white(below) {
shadows += 1;
assert!(red(shadowed.pixel(x, y + 30).unwrap()), "the shadow of {x},{y}: {:?}", shadowed.pixel(x, y + 30));
}
}
}
}
assert!(inked > 500 && shadows > 100, "{inked} glyph pixels, {shadows} of them with their shadow on the stage");
// Switched off, the picture is the plain text's again.
run(&mut s, "filter.enable", json!({"enabled": false}));
assert_eq!(anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().data, plain.data);
run(&mut s, "filter.enable", json!({"enabled": true}));
// The words, the style and the text type change; the filters stay.
run(&mut s, "text.edit", json!({"text": "HEY", "size": 80}));
assert_eq!(list(&s).len(), 1, "after editing the text");
run(&mut s, "text.field", json!({"type": "dynamic", "border": true}));
assert_eq!(list(&s).len(), 1, "as a dynamic field");
assert!(matches!(&s.doc.timeline(s.scene).layers[0].keyframes[0].elements[0].kind, ElementKind::Text(t) if t.field.is_some()));
let dl = anicraft_doc::evaluate(&s.doc, 0);
assert_eq!(dl.groups.len(), 1);
assert!(dl.items.len() >= 3 && dl.items.iter().all(|i| i.group == Some(0)), "the field's box, text and border are filtered as one");
run(&mut s, "text.field", json!({"type": "static"}));
assert_eq!(list(&s).len(), 1, "back to static text");
// The rest of the filter commands, presets and the clipboard work on text.
run(&mut s, "filter.preset_apply", json!({"name": "Neon Glow"}));
run(&mut s, "filter.copy", json!({}));
run(&mut s, "filter.paste", json!({}));
run(&mut s, "filter.move", json!({"from": 0, "to": 3}));
run(&mut s, "filter.remove", json!({"index": 0}));
assert_eq!(list(&s).len(), 3);
// It round-trips through the file, and undo takes the filters back.
let back: anicraft_doc::Document = serde_json::from_str(&serde_json::to_string(&s.doc).unwrap()).unwrap();
assert!(back == s.doc);
// In a motion tween, a text's filter tweens like a clip's.
run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 0, "blur_y": 0}]}));
run(&mut s, "timeline.create_motion_tween", json!({}));
run(&mut s, "motion.set_key", json!({"property": "filter.0.blur_x", "frame": 10, "value": 20}));
assert!(matches!(drawn(&s, 5).first(), Some(Filter::Blur { blur_x, .. }) if *blur_x == 10.0));
// Shapes and graphics take none, and say so.
let mut s = Session::default();
run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 50, "h": 50, "fill": "#ff0000"}));
assert!(refused(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]})).contains("select a movie clip or button instance, or text"));
run(&mut s, "modify.convert_to_symbol", json!({"name": "G"}));
run(&mut s, "symbol.set_kind", json!({"kind": "graphic"}));
assert!(refused(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]})).contains("and to text"));
}
+1 -1
View File
@@ -73,7 +73,7 @@ fn a_blur_tweens_by_commands_with_eases_and_retiming() {
let v = run(&mut s, "motion.remove_key", json!({"property": "filter.0.blur_y", "frame": 12}));
assert_eq!(v["removed"], json!(["filter.0.blur_y"]));
// What can't be keyed says why.
for (p, want) in [(json!({"property": "filter.1.blur_x", "value": 3}), "no filter 1"), (json!({"property": "filter.0.angle", "value": 3}), "has no Angle"), (json!({"property": "filter.0.blur_x", "value": 900}), "between"), (json!({"property": "filter.0.sparkle", "value": 1}), "unknown property")] {
for (p, want) in [(json!({"property": "filter.1.blur_x", "value": 3}), "no filter 1"), (json!({"property": "filter.0.angle", "value": 3}), "has no angle"), (json!({"property": "filter.0.blur_x", "value": 900}), "between"), (json!({"property": "filter.0.sparkle", "value": 1}), "unknown property")] {
let e = s.execute("motion.set_key", &p).expect_err("refused").to_string();
assert!(e.contains(want), "{p}: {e}");
}
+49
View File
@@ -1172,6 +1172,55 @@ fn gpu_matches_the_oracle_on_the_filtered_sample() {
}
/// ADR 0099: text with filters reaches the renderers as a filtered group like a movie clip's
/// (no pass changed), so the GPU stage draws it as the oracle does: static text with a bevel,
/// and a half-transparent dynamic field (box, clipped text and border) with a shadow and a
/// glow.
#[test]
fn gpu_matches_the_oracle_on_filtered_text() {
use anicraft_doc::{Filter as F, FilterSide, TextBlock, TextField, TextKind};
let Some(g) = gpu() else { return };
let mut glyphs = Path::ellipse(30.0, 22.0, 18.0, 14.0);
glyphs.cmds.extend(Path::rect(56.0, 8.0, 14.0, 30.0).cmds);
glyphs.cmds.extend(Path::rect(78.0, 8.0, 60.0, 9.0).cmds);
let block = |field: Option<TextField>, filters: Vec<F>| TextBlock {
text: "Hi".into(),
font: "Test".into(),
size: 30.0,
bold: false,
italic: false,
color: Rgba::new(0.1, 0.2, 0.5, 1.0),
align: Default::default(),
letter_spacing: 0.0,
line_spacing: 0.0,
width: None,
outline: Arc::new(glyphs.clone()),
box_width: 120.0,
box_height: 44.0,
field,
on_path: None,
filters: filters.into_iter().map(anicraft_doc::FilterEntry::from).collect(),
..TextBlock::default()
};
let mut field = TextField::new(TextKind::Dynamic);
(field.border, field.background, field.background_color) = (true, true, Rgba::new(1.0, 0.95, 0.8, 1.0));
let shadow = F::DropShadow { blur_x: 6.0, blur_y: 6.0, strength: 0.8, quality: 2, angle: 45.0, distance: 8.0, color: Rgba::BLACK, inner: false, knockout: false, hide_object: false };
let glow = F::Glow { blur_x: 10.0, blur_y: 10.0, strength: 1.5, quality: 2, color: Rgba::new(1.0, 0.3, 0.1, 1.0), inner: false, knockout: false };
let bevel = F::Bevel { blur_x: 4.0, blur_y: 4.0, strength: 1.2, quality: 2, angle: 45.0, distance: 3.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side: FilterSide::Inner, knockout: false };
let mut doc = anicraft_doc::Document { stage: anicraft_doc::Stage { width: 220, height: 160, fps: 24.0, background: Rgba::new(0.9, 0.95, 1.0, 1.0) }, ..Default::default() };
let text = |id: u64, at: (f32, f32), color: ColorEffect, block: TextBlock| Arc::new(anicraft_doc::Element { id: ElementId(id), name: String::new(), transform: Affine::translate(at.0, at.1).mul(&Affine::rotate(0.08)), color, kind: ElementKind::Text(Arc::new(block)) });
let els = vec![text(1, (20.0, 12.0), ColorEffect::default(), block(None, vec![bevel])), text(2, (40.0, 84.0), ColorEffect::Alpha(0.5), block(Some(field), vec![shadow, glow]))];
if let Some(k) = Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0) {
k.elements = els;
}
let dl = anicraft_doc::evaluate(&doc, 0);
assert_eq!(dl.groups.iter().map(|g| g.filters.len()).collect::<Vec<_>>(), [1, 2], "each text is a filtered group");
for s in [1.0f32, 0.5, 1.7] {
let d = assert_parity(g, "filtered text", &dl, &View::stage(&doc, s));
eprintln!("filtered text at {s}: mean {:.5} / max {} / {} of {} px differ", d.mean, d.max, d.differing, d.pixels);
}
}
// ----- binning on the GPU (ADR 0048) ----------------------------------------------------------
/// Scenes the GPU bins (no fill in a mask or a group): the analytic ones, the sample, stress
+33 -6
View File
@@ -102,6 +102,9 @@ pub struct HtmlExport {
const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)";
const KEPT_SCRIPTS: &str = "kept frame scripts outside the ActionScript subset (not run; kept in the document only)";
const NINE_SLICE: &str = "9-slice scaling (scaled as a whole)";
/// An input field is a real form element over the canvas (ADR 0066): what is typed is the
/// browser's to draw, so the filters reach the field's box, border and authored text only.
const INPUT_FILTERS: &str = "filters on input text (typed text is drawn by the browser, without them)";
const OUTSIDE_CALLS: &str = "script calls that reach outside the movie (ignored)";
const WARPED_BITMAPS: &str = "warped bitmaps (the image shows unbent inside its bent outline; warped shapes come across)";
const FIELD_FONTS: &str = "text fields (their authored text keeps its outlines; text a script or the viewer changes is drawn with the browser's fonts)";
@@ -159,6 +162,16 @@ fn exact_color(c: Rgba) -> Value {
/// `[r, g, b, a]`, ramps as `[offset, r, g, b, a]` stops, Adjust Color as its 4 × 5 matrix.
/// The angle comes as the renderer's own `[cos, sin]` (`u`), so the page multiplies the same
/// numbers and its whole-pixel offsets round as the renderer's do, at halves too.
/// An item's filters, on a symbol instance or on text (ADR 0099): `fx` the list, `fm` how far
/// they reach together (stage pixels); filters switched off are left out (ADR 0091).
fn filters_json(filters: &[anicraft_doc::FilterEntry], item: &mut Map<String, Value>) {
let on = anicraft_doc::active_filters(filters);
if !on.is_empty() {
item.insert("fx".into(), Value::Array(on.iter().map(filter_json).collect()));
item.insert("fm".into(), exact(on.iter().map(anicraft_doc::Filter::margin).sum::<f32>()));
}
}
fn filter_json(f: &anicraft_doc::Filter) -> Value {
use anicraft_doc::{Filter, FilterSide, GradientStop};
let unit = |angle: f32| {
@@ -591,6 +604,10 @@ impl<'a> Bake<'a> {
if let Some(c) = effect(&el.color.transform()) {
item.insert("c".into(), c);
}
filters_json(&t.filters, &mut item);
if f.kind == anicraft_doc::TextKind::Input && anicraft_doc::any_active_filter(&t.filters) {
self.notes.entry(INPUT_FILTERS).or_default().insert(el.id.0);
}
Value::Object(item)
}
@@ -636,7 +653,21 @@ impl<'a> Bake<'a> {
let item = self.field(el, t, f);
out.push(item);
}
// One shape per colour piece (ADR 0085).
// One shape per colour piece (ADR 0085); with filters, one item of pieces, so
// they draw in one filtered group as `evaluate` draws them (ADR 0099).
None if anicraft_doc::any_active_filter(&t.filters) => {
let pieces = t.fill_paths();
let fill = Paint::Solid(pieces.first().map_or(t.color, |p| p.0));
let mut item = self.shape(&t.outline, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero);
if let Some(o) = item.as_object_mut() {
if pieces.len() > 1 {
let pp: Vec<Value> = pieces.iter().map(|(c, _, p)| json!([self.path(p), self.paint(&Paint::Solid(*c))])).collect();
o.insert("pp".into(), Value::Array(pp));
}
filters_json(&t.filters, o);
}
out.push(item);
}
None => {
for (color, _, path) in t.fill_paths() {
let fill = Paint::Solid(color);
@@ -685,11 +716,7 @@ impl<'a> Bake<'a> {
// Filters run in the page as the renderer runs them (ADR 0072): `fx` the list,
// `fm` how far they reach together (stage pixels).
// Filters switched off are left out, as the renderer leaves them (ADR 0091).
let on = anicraft_doc::active_filters(filters);
if !on.is_empty() {
o.insert("fx".into(), Value::Array(on.iter().map(filter_json).collect()));
o.insert("fm".into(), exact(on.iter().map(anicraft_doc::Filter::margin).sum::<f32>()));
}
filters_json(filters, &mut o);
if !events.is_empty() {
o.insert("ev".into(), Value::Array(events.iter().map(|h| json!([h.event.key(), actions(&h.actions)])).collect()));
}
+24 -5
View File
@@ -363,11 +363,30 @@ var AniCraft = (function () {
}
}
const xf = mul(cx.xf, m);
if (e.tf) return evalField(e.tf, e.n || "", xf, concat(cx.c, fx), cx.group, clip, masks, dl, child, v);
if (e.y === undefined) {
const it = { p: e.p, m: xf, f: e.f === undefined ? -1 : e.f, s: e.s || null, k: e.k || null, eo: !!e.eo, c: concat(cx.c, fx), clip: clip, masks: masks, group: cx.group };
dl.items.push(it);
if (v) v.item(it);
if (e.tf || e.y === undefined) {
// Text with filters draws in a group of its own, as a movie clip does (eval.rs, ADR
// 0099): the group fades at the text's alpha and its items keep the rest of the effect.
// (Mask artwork takes neither.)
const filters = masks === null && Array.isArray(e.fx) && e.fx.length ? e.fx : null;
let color = concat(cx.c, fx), group = cx.group;
if (filters) {
group = dl.groups.length;
dl.groups.push({ parent: cx.group, alpha: fx[7] === 0 ? Math.min(Math.max(fx[3], 0), 1) : 1, blend: "normal", clip: clip, filters: filters, margin: e.fm || 0 });
color = concat(cx.c, fx[7] === 0 ? [fx[0], fx[1], fx[2], 1, fx[4], fx[5], fx[6], 0] : fx);
if (v) v.groupBegin(group, dl.groups[group]);
}
if (e.tf) evalField(e.tf, e.n || "", xf, color, group, clip, masks, dl, child, v);
else {
// Text in several colours with filters comes as one item of pieces (`pp`), so the
// pieces share one filter group (ADR 0085, ADR 0099).
const pieces = Array.isArray(e.pp) ? e.pp : [[e.p, e.f === undefined ? -1 : e.f]];
for (const pc of pieces) {
const it = { p: pc[0], m: xf, f: pc[1], s: e.s || null, k: e.k || null, eo: !!e.eo, c: color, clip: clip, masks: masks, group: group };
dl.items.push(it);
if (v) v.item(it);
}
}
if (filters && v) v.groupEnd(group, dl.groups[group]);
return;
}
const sym = M.symbols[e.y];
+69
View File
@@ -1471,3 +1471,72 @@ fn shared_html_escape_preserves_all_unicode_scalars() {
assert_eq!(super::escape_html(text), previous_html_escape(text));
}
}
/// ADR 0099: filters on text reach the page as an instance's do (`fx`, `fm`), switched-off ones
/// left out; the page's player draws the text in a filtered group exactly as `evaluate` does,
/// static text and fields alike; and what an input field can't show is reported.
#[test]
fn filters_on_text_reach_the_page_and_group_as_in_the_renderer() {
use anicraft_doc::{Filter, FilterEntry, TextField, TextKind};
let with = |e: Arc<Element>, filters: Vec<FilterEntry>, color: ColorEffect| {
let mut e = (*e).clone();
if let Some(list) = e.kind.filters_mut() {
*list = filters;
}
e.color = color;
Arc::new(e)
};
let shadow = FilterEntry::from(Filter::new("drop_shadow").unwrap());
let glow = FilterEntry::from(Filter::Glow { blur_x: 6.0, blur_y: 6.0, strength: 2.0, quality: 2, color: Rgba::hex(0x00aaff), inner: false, knockout: false });
let off = FilterEntry { filter: Filter::new("blur").unwrap(), enabled: false };
let mut note = TextField::new(TextKind::Dynamic);
(note.background, note.border) = (true, true);
let mut doc = Document { stage: anicraft_doc::Stage { width: 200, height: 120, fps: 24.0, background: Rgba::hex(0xffffff) }, ..Document::default() };
let els = vec![
// Static text with a glow, half transparent: the group fades, after the filters.
with(field_el(60, "", Vec2::new(5.0, 5.0), (40.0, 16.0), "Hi", None), vec![glow.clone()], ColorEffect::Alpha(0.5)),
// A dynamic field with a shadow (and a filter switched off): box, text and border as one.
with(field_el(61, "note_txt", Vec2::new(5.0, 30.0), (150.0, 40.0), "Hello", Some(note)), vec![off.clone(), shadow.clone()], ColorEffect::default()),
// An input field with a glow: the page's form element draws what is typed.
with(field_el(62, "name_txt", Vec2::new(5.0, 80.0), (90.0, 18.0), "", Some(TextField::new(TextKind::Input))), vec![glow.clone()], ColorEffect::default()),
// Text whose only filter is off, and plain text: as before, no group.
with(field_el(63, "", Vec2::new(120.0, 5.0), (40.0, 16.0), "No", None), vec![off], ColorEffect::default()),
field_el(64, "", Vec2::new(160.0, 5.0), (30.0, 16.0), "Ok", None),
];
Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = els;
let m = movie(&doc, &HtmlOptions::default());
let items = m.json["contents"][0]["l"][0]["e"].as_array().unwrap().clone();
assert_eq!(items.iter().map(|e| e.get("fx").is_some()).collect::<Vec<_>>(), [true, true, true, false, false]);
assert_eq!(items[0]["fx"].as_array().map(Vec::len), Some(1));
assert_eq!(items[0]["fx"][0]["k"], "shadow", "a glow is the page's shadow kind");
assert_eq!(items[0]["fm"].as_f64(), Some(f64::from(glow.filter.margin())));
assert_eq!(items[1]["fx"].as_array().map(Vec::len), Some(1), "the filter that is off is left out: {}", items[1]["fx"]);
assert_eq!(items[1]["fm"].as_f64(), Some(f64::from(shadow.filter.margin())));
assert!(items[1].get("tf").is_some() && items[0].get("tf").is_none());
assert_eq!(m.report.get(INPUT_FILTERS), Some(&1), "{:?}", m.report);
// The page's display list is the renderer's: three filtered groups, their items in them.
let r = start(&doc, &mut NoScripts);
let mut js = Js::new(&m);
js.eval("P.start().output");
same_display_list(&mut js, &m, &doc, &r.state, "start");
let dl = evaluate_player(&doc, &r.state);
assert_eq!(dl.groups.iter().map(|g| (g.filters.len(), g.alpha)).collect::<Vec<_>>(), [(1, 0.5), (1, 1.0), (1, 1.0)]);
// The page hears each group open and close around its text (canvas.js draws so).
let seen = js.eval("(function () { var out = []; P.evaluate({ item: function () { out.push('i'); }, field: function (f) { out.push('f' + f.group); }, clipBegin: function () {}, clipEnd: function () {}, maskBegin: function () {}, maskEnd: function () {}, groupBegin: function (g, grp) { out.push('<' + g + ':' + grp.filters.length + ':' + grp.margin); }, groupEnd: function (g) { out.push('>' + g); } }); return out.join(' '); })()");
let want = format!("<0:1:{} i >0 <1:1:{} f1 >1 <2:1:{} f2 >2 i i", glow.filter.margin(), shadow.filter.margin(), glow.filter.margin());
assert_eq!(seen, json!(want));
// Mask artwork takes no filters: the text masks as it is.
let mut masked = doc.clone();
let tl = masked.timeline_mut(0);
let mut below = Layer::new(LayerId(7), "below");
below.keyframe_mut(0).unwrap().elements = vec![rect(70, 0.0, 0.0, 200.0, 120.0, 0x223344)];
below.parent = Some(tl.layers[0].id);
Arc::make_mut(&mut tl.layers[0]).kind = LayerKind::Mask;
tl.layers.push(Arc::new(below));
let m = movie(&masked, &HtmlOptions::default());
let r = start(&masked, &mut NoScripts);
let mut js = Js::new(&m);
js.eval("P.start().output");
same_display_list(&mut js, &m, &masked, &r.state, "masking");
assert!(evaluate_player(&masked, &r.state).groups.is_empty());
}
+5 -1
View File
@@ -586,7 +586,10 @@ impl<'a> Builder<'a> {
}
/// A text field: one text element per block (`text::field`), placed by the field's matrix.
/// Its filters (the same `<filters>` records an instance holds) come in on each block, in
/// order, switched off where Animate had them off (ADR 0099).
fn text_field(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
let filters = self.filters(el);
let fonts: &'a Fonts = match self.fonts {
Some(f) => f,
None => Fonts::get(),
@@ -595,7 +598,8 @@ impl<'a> Builder<'a> {
let m = parent.mul(&matrix(el));
let name: String = el.attr("name").unwrap_or("").chars().take(256).collect();
for (i, p) in crate::text::field(el, fonts, &mut self.faces, &mut self.report).into_iter().enumerate() {
let mut e = Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform: m.mul(&Affine::translate(p.offset.x, p.offset.y)), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(p.block)) };
let block = anicraft_doc::TextBlock { filters: filters.clone(), ..p.block };
let mut e = Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform: m.mul(&Affine::translate(p.offset.x, p.offset.y)), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) };
// A dynamic or input field's instance name goes on it (its first block for static
// text, which keeps the name for a later conversion).
if i == 0 {
+1 -3
View File
@@ -198,9 +198,7 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap<String, FaceMatch>, repo
if native.orientation().is_some_and(|o| o != "horizontal") {
report.skip("vertical text (drawn horizontal)");
}
if native.has_filters() {
report.skip("filters on text");
}
// Filters on text come across: the importer sets them on each block (ADR 0099).
let mut flags = Flags::default();
let styled = read_runs(el, &native, fonts, faces, report, &mut flags);
if flags.justified {
+33
View File
@@ -461,6 +461,39 @@ self-authored, line two", 28.0, true), ("", "A fixed-width field wraps its words
assert_eq!(fields, [("score_txt".into(), Dynamic, 200.0, 28.0), ("name_txt".into(), Input, 200.0, 24.0), ("notes_txt".into(), Input, 140.0, 64.0), ("pw_txt".into(), Input, 120.0, 24.0)]);
}
/// ADR 0099: a text field's `<filters>` (the records an instance holds) come in on the text, in
/// order, switched-off ones switched off; nothing about them is reported as skipped.
#[test]
fn filters_on_text_fields_come_in_on_the_text() {
let mut package = files("textfields");
let xml = String::from_utf8(package["DOMDocument.xml"].clone()).unwrap();
let field = "<DOMDynamicText name=\"score_txt\" fontRenderingMode=\"standard\" width=\"200\" height=\"28\" border=\"true\" isSelectable=\"false\">";
assert!(xml.contains(field), "the fixture's dynamic field");
let filters = "<filters><DropShadowFilter blurX=\"4\" blurY=\"4\" distance=\"6\" angle=\"45\" color=\"#112233\" strength=\"0.6\"/><GlowFilter blurX=\"10\" blurY=\"10\" color=\"#E63946\" enabled=\"false\"/><SparkleFilter/></filters>";
package.insert("DOMDocument.xml".into(), xml.replace(field, &format!("{field}{filters}")).into_bytes());
// Without fonts no text comes in; the import still reads the package, and says only that.
let (_, report) = import_files(&package, &Fonts::from_faces(Vec::new())).unwrap();
assert!(!report.skipped.contains_key("filters on text"), "{:?}", report.skipped);
assert_eq!(report.skipped.get("unknown filters"), Some(&1), "a filter AniCraft doesn't know is reported: {:?}", report.skipped);
let fonts = Fonts::get();
if fonts.resolve("").is_none() {
return; // A computer without fonts: nothing to hold the filters.
}
let (doc, report) = import_files(&package, fonts).unwrap();
assert!(!report.skipped.contains_key("filters on text"), "{:?}", report.skipped);
let texts: Vec<(String, Vec<anicraft_doc::FilterEntry>)> = doc.timeline(0).layers[1].keyframes[0].elements.iter().filter_map(|e| if let ElementKind::Text(t) = &e.kind { Some((e.name.clone(), t.filters.clone())) } else { None }).collect();
let (name, list) = &texts[0];
assert_eq!(name, "score_txt");
assert_eq!(list.len(), 2, "{list:?}");
assert!(matches!(list[0], anicraft_doc::FilterEntry { filter: anicraft_doc::Filter::DropShadow { blur_x, distance, strength, color, .. }, enabled: true } if blur_x == 4.0 && distance == 6.0 && (strength - 0.6).abs() < 1e-6 && color == anicraft_doc::Rgba::hex(0x112233)), "{:?}", list[0]);
assert!(matches!(list[1], anicraft_doc::FilterEntry { filter: anicraft_doc::Filter::Glow { .. }, .. }), "{:?}", list[1]);
assert!(texts.iter().skip(1).all(|(_, f)| f.is_empty()), "the other fields have none");
// And the text draws through them: one filtered group, the field's items in it.
let dl = anicraft_doc::evaluate(&doc, 0);
let g = dl.groups.iter().position(|g| !g.filters.is_empty()).expect("a filtered group") as u32;
assert!(dl.items.iter().filter(|i| i.group == Some(g)).count() >= 2);
}
/// A small deterministic generator (xorshift), so a failing variant can be found again.
struct Rng(u64);
impl Rng {
@@ -58,7 +58,8 @@ same order) and by observation. No Adobe code or asset was used.
order, switched-off filters included, so switching one off never breaks a tween; numbers
and colours travel, and on/off (like Inner, Knockout and Quality) holds from the first
keyframe. Reordering one keyframe's list makes the lists no longer pair up, and the first
keyframe's filters hold, as in Animate.
keyframe's filters hold, as in Animate. (Superseded for lists that differ by ADR 0099 §3:
what matches is paired and the rest fade in or out.)
7. **XFL.** `enabled="false"` filters now import switched off, in their place, instead of being
dropped; the corpus already holds one and its golden render is unchanged.
8. **Clipboard and plug-ins.** Copied filters live in `Session.filter_clipboard`, outside undo,
@@ -0,0 +1,170 @@
# ADR 0099: Filter colour and stepped tracks, built-in presets, and filters on text
* Status: accepted (2026-11-16)
* Relates to: roadmap M5 (filters, last slice), ADR 0025 (bevel and gradient filters), ADR 0032
(GPU filters), ADR 0056 (colour effect properties in motion tweens), ADR 0066 (dynamic and
input text), ADR 0068 (brush presets: built-in ones and the user's), ADR 0072 (filters in the
HTML page), ADR 0081 (classic tweens ease filters as a group), ADR 0091 (filter lists,
presets and tweens), ADR 0092 (Motion Editor filter tracks), ADR 0004 (destructive actions),
ADR 0009 and 0014 (XFL import)
## Context
ADR 0091 and 0092 left four things for later: filter **colours** as motion-tween tracks,
**quality and switches** as tracks, **built-in presets**, and **filters on text**. ADR 0091 also
made a classic tween hold the first keyframe's filters whenever the two lists differed, and
called that Animate's behaviour. It is not quite: Adobe's public help for animated filters says
that when the two keyframes' filters don't match, Animate pairs what matches and gives the
other keyframe a filter "that has no parameters" with the colour of the existing one, so the
unmatched filter fades in or out; and that Knockout, Inner and the Type are taken from the first
keyframe when they differ. Animate also offers filters on text as on movie clips and buttons.
Behaviour was learnt from Adobe's public help pages and by observation. No Adobe code, preset
or asset was used; the built-in presets' values are AniCraft's own.
## Decision
### 1. A filter's colour is four tracks, in the tint's units and space
`FilterParam` gains `Color(FilterColor, Channel)`:
* `FilterColor` is the filter's own field: `Color` (Drop Shadow, Glow), `Shadow` and
`Highlight` (Bevel), and `Stop(n)` for a gradient filter's ramp stop by its place (0 to 14).
* `Channel` is red, green, blue (0–255) or alpha (percent): exactly the units of the colour
effect's `tint_red`/`tint_green`/`tint_blue` and `alpha` (ADR 0056).
Each channel is a `Property` like any other (`filter.0.color_red`, `filter.1.shadow_color_alpha`,
`filter.0.stop_2_blue`), so it keys, eases, retimes, splits and joins with no new machinery,
and the files need nothing new (`filter_tracks`, ADR 0092). The colour therefore travels as a
tint travels: each channel of the straight sRGB colour on its own curve. With linear eases the
midpoint is `Rgba::lerp`'s, which is also what classic tweens give a filter colour; a test pins
the two together. One colour space for every colour that tweens was preferred over a better
one for filters only: an artist who matches a glow to a tint must see them stay matched.
A whole colour is addressed without a channel where that is the natural unit:
`motion.set_key {property: "filter.0.color", color: "#rrggbbaa"}` keys the four channels in one
undo step, `motion.remove_key` and `motion.set_ease` take the same name, and `motion.info`
reports `filter.0.color` as `#rrggbbaa` beside the channels.
Ramp stops are addressed by place. A stop the ramp doesn't have does nothing (as a track whose
filter went, ADR 0092). Stop *positions* are not tracks.
### 2. Quality and the switches are stepped tracks
`FilterParam::Quality` (1 to 3), `Inner`, `Knockout` and `HideObject` (0 or 1) are *stepped*
(`Property::is_stepped`): `Track::value_at` returns the key before the frame, never a value in
between, and exactly the next key's value from its frame on. Keys are whole numbers (rounded
when set and when a file is repaired). An ease on such a segment would do nothing, so
`motion.set_ease` refuses one named alone and skips them when easing every property. This is
Animate's rule (switches never interpolate) made explicit as hold keys, so an artist can turn
Knockout on at frame 20 instead of being limited to the first keyframe's setting.
The Type of a bevel or gradient filter (inner, outer, full) and a filter's on/off are not
tracks: they stay the object's own.
`Filter::params` now lists everything a tween can animate (numbers, colour channels, quality,
switches), so auto-key (ADR 0092 §5) and F6 cover colours and switches without change: editing
a glow's colour or ticking Knockout in Properties inside a tween keys just what changed.
### 3. Classic tweens pair lists that differ, and the rest fade
`lerp_filters` replaces ADR 0091 §6's "the first keyframe's filters hold":
* **Same kinds in the same order**: pairwise, as before. Numbers and colours travel; quality,
switches, the Type and on/off stay the first keyframe's.
* **Otherwise** (`filter::pairing`): the longest run of kinds both lists hold in the same order
is paired (a longest common subsequence over at most 64 entries a side; among equal runs the
earliest filters pair). A filter with no partner travels to, or from, `Filter::neutral()`:
itself with no blur, strength or distance (an Adjust Color at rest), keeping its colours,
angle, quality and switches. So an added filter fades in, a removed one fades out, and a
filter replaced by another kind cross-fades with it. The tween applies them in the merged
order.
* **On the first keyframe itself** (`t` = 0) the result is exactly its own list, so what the
artist authored is what shows, even when a fading-in filter has Hide Object or Knockout.
Deliberately not copied: Animate "first processes the clip with the most filters"; we pair by
order, which is deterministic and keeps filters the artist didn't touch paired.
### 4. Built-in presets: always there, hidden, never deleted
Eight presets written in `filter_library::builtins()` from the filters' own parameters: Soft
Shadow, Hard Shadow, Neon Glow, Outline, Emboss, Engrave, Soft Focus, Greyscale.
* They follow the brushes' rule (ADR 0068): a built-in's name can't be saved over, renamed to,
renamed from or deleted; the engine refuses with the reason (never a confirmation, since
nothing irreversible can happen). A preset in a file or in older preferences with a
built-in's name is numbered ("Emboss 2").
* **Hidden, not removed**: `filter.preset_hide {name, hidden?}` takes one off the presets menu
and puts it back. A hidden preset still applies by name, so scripts, the CLI, MCP and
plug-ins that name one work on every computer. Hiding is reversible, so it asks nothing.
* What is hidden lives in the session's library (`FilterLibrary::hidden`) and in the
preferences under a key of its own, `filter_presets_hidden`. The `filter_presets` list stays
the plain list older builds read.
* `filter.preset_list` returns `builtin` (name, filters, hidden) beside `presets` (the user's),
so existing callers see what they saw. Plug-ins may list and apply; they may not hide
(`plugin_may_call`): the menu is the artist's.
* Names are English in commands and files; the interface translates them where it draws them.
### 5. Filters on text
`TextBlock` gains `filters: Vec<FilterEntry>` (left out of files when empty, so older files and
older builds are unaffected), on every text: static, dynamic and input, as Animate offers.
* `ElementKind::filters()`/`filters_mut()` give the one list of whatever takes filters; the
motion tween, the filter commands, the Motion Editor and Properties go through them, so text
gets the list, the order, on/off, copy and paste, presets, classic tweens and motion-tween
tracks with no second implementation.
* `evaluate` draws text with active filters in a group of its own with the filters on it, as
for a movie clip: a field's background, clipped text, selection, caret and border are
filtered as one, and the text's alpha fades the group after the filters. Mask artwork takes
none. So the CPU oracle, the GPU stage and every display-list export draw them **with no
renderer change**; a GPU parity test covers filtered text all the same.
* The text commands that lay a block out again (`text.edit`, `text.field`, `text.path`, Find
and Replace) carry the list over.
* The HTML page places elements itself: text items carry `fx`/`fm` like instances and the
page's player opens the same group. An input field's typed text is a real form element (ADR
0066), drawn by the browser, so only its box, border and authored text are filtered; the
export report says so.
* XFL: a text field's `<filters>` are the records an instance holds, so they import with the
same reader, switched-off ones switched off, instead of being reported as skipped.
### 6. Interface
* **Motion Editor**: after a filter's numbers, one row per colour (Colour, Shadow, Highlight,
Stop 1…) with a swatch showing the colour at the playhead (picking a colour keys it there)
and a diamond for its four keys. Clicking the row lists its Red, Green, Blue and Alpha rows,
ordinary curves; while one is shown, a strip along the foot of the graph shows the whole
colour over the span. Quality reads Low, Medium, High; switches are tick boxes; their curves
are steps, without ease handles, and the footer says they hold.
* **Properties**: the Filters section appears for text. The presets menu lists the built-in
presets, then the user's, and **Built-in Presets** ticks which ones the menu shows.
* All of it is named for screen readers ("Glow: Colour · Red") and translatable.
## Tests
* Doc: a colour's midpoint equal to `Rgba::lerp`'s and each channel on its own ease; stepped
values held, exact at the key, whole after repair, kept by a split; every value's name
reading back; pairing (added, removed, replaced, reordered, hostile lengths) and `neutral`;
text drawn in a filtered group, its file round trip and old files; text tweening its filters.
* Engine, through the commands: a glow's colour to its midpoint in the display list and the
pixels, equal to a still clip; a switch stepping exactly at its key in the pixels; auto-key
of a colour, a switch and a ramp stop with one undo step; F6 and the document round trip;
lists that differ fading in; the built-in presets present, applying, read-only and hidden;
a text's drop shadow in the pixels, kept through edits; `panic_hunt_every_command` green.
* Render: the page's display list equal to `evaluate`'s for filtered text, groups opening and
closing round it, the input-field note. XFL: a field's filters imported.
* GPU: filtered text against the oracle (max 1/255, mean 0.003–0.005 at three scales).
* Shell: the Motion Editor's rows and names; hidden presets through the preferences; the
Filters row comparing text. Screenshots: `--open motioncolour`, `--open textshadow`.
## Consequences
* ADR 0091 §6 is superseded for lists that differ, and ADR 0092's "colours, quality and
switches stay the object's own" no longer holds. A document whose classic tween crossed two
different filter lists now fades between them instead of holding; nothing else changes in
existing files.
* F6 inside a motion tween keys a filter's colours and switches too: up to 86 tracks for a
filter with a full ramp. Bounded (16 slots), and only where the artist asked to pin a pose.
* Not yet: the Type and on/off as tracks; ramp stop positions as tracks; filter tracks from
Animate's XFL motion tweens; a text field's typed text filtered in the HTML page; filters on
text in the SVG importer; editing the built-in presets' values (save a copy under a name).
+16 -5
View File
@@ -441,7 +441,8 @@ animate the colour effect too (see [Tweens](tweens.md)).
Movie clip and button instances can also have **Filters** and **Blending**, as in Animate.
Convert your artwork to a movie clip symbol first (see
[Symbols and the Library](symbols-and-library.md)).
[Symbols and the Library](symbols-and-library.md)). Text takes filters as it is, with no
symbol needed (see [Text](text.md#filters-on-text)).
**Filters**: choose **Add filter** under Filters in Properties, and stack as many as you like:
**Drop Shadow**, **Blur**, **Glow**, **Bevel**, **Gradient Glow**, **Gradient Bevel** and
@@ -471,10 +472,20 @@ the filters it got). **Export Presets…** writes them to a small JSON file and
Presets…** adds a file's presets to yours, to move them to another computer. Presets are kept
in your preferences.
**Tweening filters**: a classic tween changes filter values smoothly when both keyframes have
the same filters in the same order (switched-off ones count), as in Animate: a Blur from 0 to
20 is 10 halfway. On/off, Inner, Knockout and Quality stay as the first keyframe has them.
If the lists differ, the first keyframe's filters hold until the next keyframe.
The menu starts with AniCraft's **built-in presets**: **Soft Shadow**, **Hard Shadow**, **Neon
Glow**, **Outline**, **Emboss**, **Engrave**, **Soft Focus** and **Greyscale**. They are a
starting point: apply one, then change its values in the list. Built-in presets can't be
renamed or deleted. If you don't use one, open **Built-in Presets** in the same menu and
untick it to take it off the menu; tick it to bring it back. To keep your own version of one,
change it and **Save as Preset…** under a new name.
**Tweening filters**: a classic tween changes filter values and colours smoothly between two
keyframes, as in Animate: a Blur from 0 to 20 is 10 halfway. On/off, Inner, Knockout, the Type
and Quality stay as the first keyframe has them. The filters don't have to match: one that
only the second keyframe has fades in, one that only the first has fades out, and the filters
both have (the same kinds in the same order, switched-off ones included) change from one to
the other. To change a filter's colour, quality or switches part way, use a motion tween (see
[Tweens](tweens.md#animating-filters)).
**Blending** sets how the instance mixes with what's below it: Normal, Layer, Darken,
Multiply, Lighten, Screen, Overlay, Hard Light, Add, Subtract, Difference, Invert, Alpha and
+1 -1
View File
@@ -111,7 +111,7 @@ These come across, but look a little different from Animate, and the report coun
(played without an effect).
* **Video playback.** Videos other than Screen Video (Sorenson H.263, On2 VP6, H.264, linked
MPEG-4 files) are named in the report, not shown; their instances are left out.
* Frame comments, filters on text, and linkage classes on bitmaps and sounds.
* Frame comments, and linkage classes on bitmaps and sounds.
* Camera layers and bone armatures don't come across as a camera or an armature.
* Anything AniCraft doesn't recognise at all is counted as "other elements".
+16 -14
View File
@@ -1,6 +1,6 @@
# Command reference
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 363 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 364 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
This page is generated from the command registry, so it always matches the version of AniCraft it came with.
@@ -398,11 +398,11 @@ These commands have no menu item: the panels, the stage and the timeline use the
- **Warp Mesh** `warp.info`
Parameters: `{element?, frame?} → the artwork's warp at the frame: resolution, the mesh's columns, rows, vertices and triangles, whether it is bent, and its pins (id, where they show in stage px, and where they were placed on the artwork as drawn, in its own space)`
- **Property Keyframe** `motion.set_key` · changes the document
Parameters: `{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255)|filter.<slot>.<blur_x|blur_y|strength (%)|angle|distance|brightness|contrast|saturation|hue> (a number of the object's filter at that place, 0 the first; ADR 0092), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)`
Parameters: `{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255)|filter.<slot>.<blur_x|blur_y|strength (%)|angle|distance|brightness|contrast|saturation|hue> (a number of the object's filter at that place, 0 the first; ADR 0092)|filter.<slot>.<color|shadow_color|highlight_color|stop_<n>>_<red|green|blue (0..255)|alpha (%)> (a channel of one of the filter's colours, stop_0 the ramp's first stop)|filter.<slot>.<quality (1..3)|inner|knockout|hide_object (0 or 1)> (stepped: a key holds until the next one; ADR 0099), value (px, %, °), frame?, layer?} or {property: filter.<slot>.<color|shadow_color|highlight_color|stop_<n>>, color: "#rrggbb" or "#rrggbbaa"} to key a filter colour's four channels at once (colour properties of several styles compose into Advanced, ADR 0056)`
- **Remove Property Keyframe** `motion.remove_key` · changes the document
Parameters: `{property? (default: every property), frame?, layer?}`
Parameters: `{property? (default: every property; a filter colour such as filter.0.color names its four channels), frame?, layer?}`
- **Property Ease** `motion.set_ease` · changes the document
Parameters: `{easing (as timeline.set_easing takes it, saved eases too), property? (default: every property), frame? (inside the segment), layer?}`
Parameters: `{easing (as timeline.set_easing takes it, saved eases too), property? (default: every property; a filter colour such as filter.0.color names its four channels), frame? (inside the segment), layer?} (stepped properties hold their keys and take no ease)`
- **Motion Tween** `motion.info`
Parameters: `{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is`
- **Edit Motion Path** `motion.set_path` · changes the document
@@ -616,27 +616,29 @@ These commands have no menu item: the panels, the stage and the timeline use the
- **Import Brushes** `brush.preset_import`
Parameters: `{path} adds the brushes in a brush set file to yours (a name you have already gets a number)`
- **Move Filter** `filter.move` · changes the document
Parameters: ``{from, to} moves the filter at index `from` (0 is the first, applied first) to index `to` in the selected movie clip and button instances' lists; the order changes how they draw``
Parameters: ``{from, to} moves the filter at index `from` (0 is the first, applied first) to index `to` in the lists of the selected movie clips, buttons and text; the order changes how they draw``
- **Enable Filter** `filter.enable` · changes the document
Parameters: `{enabled: bool, index? (default: every filter)} switches a filter on or off; a filter switched off keeps its settings and draws nothing`
- **Remove Filter** `filter.remove` · changes the document
Parameters: `{index? (default: every filter)} removes a filter from the selected movie clip and button instances`
Parameters: `{index? (default: every filter)} removes a filter from the selected movie clips, buttons and text`
- **Copy Filters** `filter.copy`
Parameters: `{index? (default: every filter)} copies the selected instance's filters (one, or all), for Paste Filters`
Parameters: `{index? (default: every filter)} copies the filters of the selected movie clip, button or text (one, or all), for Paste Filters`
- **Paste Filters** `filter.paste` · changes the document
Parameters: `{replace? (default false: added after the instances' own)} pastes the copied filters onto the selected movie clip and button instances`
Parameters: `{replace? (default false: added after their own)} pastes the copied filters onto the selected movie clips, buttons and text`
- **Filter Presets** `filter.preset_list`
Parameters: `{} your filter presets, each a name and its filters`
Parameters: `{} → {presets: your filter presets, each a name and its filters; builtin: the built-in ones (ADR 0099), each with its name, filters and whether you have hidden it}`
- **Save Filter Preset** `filter.preset_save`
Parameters: `{name, filters? (a list as element.set_filters takes; default: the selected instance's)} saves a filter preset of your own (kept in your preferences; a name you have already is replaced, after asking)`
Parameters: `{name, filters? (a list as element.set_filters takes; default: the selected object's)} saves a filter preset of your own (kept in your preferences; a name you have already is replaced, after asking; a built-in preset's name is refused)`
- **Apply Filter Preset** `filter.preset_apply` · changes the document
Parameters: `{name} gives the selected movie clip and button instances the preset's filters, replacing theirs (as Animate does)`
Parameters: `{name: one of yours, or a built-in one (Soft Shadow, Hard Shadow, Neon Glow, Outline, Emboss, Engrave, Soft Focus, Greyscale)} gives the selected movie clips, buttons and text the preset's filters, replacing theirs (as Animate does)`
- **Rename Filter Preset** `filter.preset_rename`
Parameters: `{name, to}`
Parameters: `{name, to} (your own presets; the built-in ones keep their names)`
- **Delete Filter Preset** `filter.preset_delete`
Parameters: `{name} deletes a filter preset (asks first: it can't be undone; artwork that used it keeps its filters)`
Parameters: `{name} deletes a filter preset of yours (asks first: it can't be undone; artwork that used it keeps its filters). Built-in presets can't be deleted, only hidden (filter.preset_hide)`
- **Hide Built-in Filter Preset** `filter.preset_hide`
Parameters: `{name, hidden? (default true; false shows it again)} hides a built-in filter preset from the presets menu, or shows it again (kept in your preferences; a hidden preset still applies by name)`
- **Export Filter Presets** `filter.preset_export`
Parameters: `{path, names? (default: all)} writes your filter presets to a small JSON file`
Parameters: `{path, names? (default: all of yours; built-in ones may be named)} writes filter presets to a small JSON file`
- **Import Filter Presets** `filter.preset_import`
Parameters: `{path} adds the presets in a filter preset file to yours (a name you have already gets a number)`
- **Eraser** `draw.erase` · changes the document
+20 -3
View File
@@ -155,6 +155,21 @@ wraps round; on an open one, letters that would run past the ends don't show. Th
shows the path it follows. Text on a path is always static text, and it is drawn from its own
outlines like all text, so it looks the same on every computer.
## Filters on text
Text takes the same filters as movie clips and buttons: **Drop Shadow**, **Blur**, **Glow**,
**Bevel**, **Gradient Glow**, **Gradient Bevel** and **Adjust Color**. Select the text and
choose **Add filter** under **Filters** in Properties; you don't need to make a symbol first.
Everything in [Filters and blend modes](drawing.md#filters-and-blend-modes) works here too: the
order, the eye that switches a filter off, copying and pasting filters, and presets, the
built-in ones included.
Filters work on static, dynamic and input text. On a field, the box, the border and the text
are filtered together, so a drop shadow falls from the whole field. Changing the words, the
font or the text type keeps the filters. They tween between keyframes and in the Motion Editor
like a movie clip's (see [Tweens](tweens.md#animating-filters)). **Modify › Break Apart** turns
the text into a shape, which has no filters.
## Turning text into shapes
To reshape the letters themselves, select the text and choose **Modify › Break Apart**
@@ -173,7 +188,9 @@ In the **HTML canvas** export, the movie plays in a web browser:
* static text, and the authored text of fields, is drawn exactly as in AniCraft;
* input fields become real text boxes over the movie, so the browser's input methods, on-screen
keyboards on phones and tablets, and the clipboard all work;
keyboards on phones and tablets, and the clipboard all work. Filters on an input field show
on its box and border there; what the viewer types is drawn by the browser, without them
(the export report says so);
* text that a script or the viewer changes is drawn with the fonts in the viewer's browser. If
the viewer doesn't have your font, it uses a similar one, and the export report tells you this
can happen.
@@ -189,8 +206,8 @@ See [Exporting and Publish](exporting-and-publish.md) for every format.
When you open an Animate document, its text comes across as text you can edit, with its font,
size, colour, bold and italic, superscript and subscript, links, alignment, indents, margins,
spacing, position and wrapping. Each Animate text block stays one block, with every run's style
kept. Dynamic and input fields come across as fields, with their names, boxes, borders and line
types. Fonts that aren't on
kept, and its filters. Dynamic and input fields come across as fields, with their names, boxes,
borders and line types. Fonts that aren't on
your computer use the default font, and the status bar names them. See
[Opening Animate files](opening-animate-files.md).
+19 -3
View File
@@ -191,9 +191,25 @@ Motion Editor, below the colour effect, with its numbers under its name: **Blur
any other property, so a blur can sharpen with an ease-out and then pulse.
You can also change a filter in **Properties › Filters** with the playhead inside the tween: the
number you changed gets a key there, as moving the object does. Reordering or removing filters
takes their keys along with them. A filter's colours, quality and switches aren't animated yet;
they stay as the object has them.
value you changed gets a key there, as moving the object does. Reordering or removing filters
takes their keys along with them.
**Colours.** Under a filter's numbers there is a row for each of its colours: **Colour** for a
Drop Shadow or a Glow, **Shadow** and **Highlight** for a Bevel, and **Stop 1**, **Stop 2**… for
the ramp of a Gradient Glow or Gradient Bevel. The swatch shows the colour at the playhead;
click it and pick a colour to key it there. The diamond adds or removes the colour's key. To
shape how the colour changes, click the row: it opens to **Red**, **Green**, **Blue** and
**Alpha**, each with a curve and eases of its own, and a strip along the bottom of the graph
shows the whole colour across the tween. Colours change the same way a Tint does, so a glow
and a tint you keyed alike stay alike.
**Quality and the switches.** **Quality**, **Inner**, **Knockout** and **Hide object** come
last. They can't be half on, so a key holds until the next key: tick **Knockout** at frame 20
and the artwork is knocked out from frame 20 on, not gradually. Their curves are steps and
they take no ease. A filter's Type (inner, outer, full) and its eye (on or off) aren't
animated; they stay as the object has them.
Text takes filters too (see [Text](text.md#filters-on-text)), and they animate the same way.
### Moving keys in time
+1 -1
View File
@@ -42,7 +42,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; the ease presets, saved and custom eases of ADR 0081 per segment); ~~Motion Editor and timeline retiming, Split/Join Motion~~ ✅ (ADR 0083); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); ~~surviving GPU failures mid-session~~ ✅ (ADR 0092: the stage drops to the CPU at once and retries the GPU after 3, 15, 60 and 300 s or on a resize; the window's device gets an error handler and a loss callback instead of wgpu's panic, a failing surface is reconfigured then recreated, and a lost window device autosaves, reopens the window a safer way and makes the next 3 starts try it late; not yet: recreating the window's device in place, which eframe doesn't offer); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. |
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). |
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text); ~~per-character and paragraph styles~~ ✅ first slice (ADR 0085: styled runs (font, size, bold, italic, colour, letter spacing, superscript/subscript by the font's OS/2 metrics, underline, link) set on the selected characters while typing, mixed values in Properties, paragraph alignment, indent, margins and line spacing, runs shaped one by one and wrapped across, one fill per colour in every export, SVG links, XFL `DOMTextRun`s kept in one block, `text.style`/`text.paragraph`/`text.styles`; not yet: justified text, runs on a path's underlines, `htmlText` in fields, links that click in Test Movie and the HTML page, SVG `<text>`/`<tspan>` output, the editor showing the real faces and alignment); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~audio output polish (latency-aware clock, event tails, monitor volume and mute, scrubbing preference, device recovery, Web Audio)~~ ✅ (ADR 0095); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals; not yet: filter colours, quality and switches as tracks, Animate's filter tracks from XFL; filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. |
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text); ~~per-character and paragraph styles~~ ✅ first slice (ADR 0085: styled runs (font, size, bold, italic, colour, letter spacing, superscript/subscript by the font's OS/2 metrics, underline, link) set on the selected characters while typing, mixed values in Properties, paragraph alignment, indent, margins and line spacing, runs shaped one by one and wrapped across, one fill per colour in every export, SVG links, XFL `DOMTextRun`s kept in one block, `text.style`/`text.paragraph`/`text.styles`; not yet: justified text, runs on a path's underlines, `htmlText` in fields, links that click in Test Movie and the HTML page, SVG `<text>`/`<tspan>` output, the editor showing the real faces and alignment); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~audio output polish (latency-aware clock, event tails, monitor volume and mute, scrubbing preference, device recovery, Web Audio)~~ ✅ (ADR 0095); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals), ~~filter colours, quality and switches as tracks, built-in presets and filters on text~~ ✅ (ADR 0099: a filter's colours and ramp stops channel by channel in the tint's units, with a swatch row in the Motion Editor; quality, Inner, Knockout and Hide Object as stepped tracks; classic tweens of lists that differ pair what matches and fade the rest; eight built-in presets that can be hidden, not deleted; filters on static, dynamic and input text, in every export and from XFL; not yet: the Type and on/off as tracks, ramp stop positions as tracks, Animate's filter tracks from XFL motion tweens, typed text of an input field filtered in the HTML page) and ~~blend modes~~ ✅ on Movie Clips. |
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); ~~command macros~~ ✅ first slice (ADR 0097: every undo step records its commands; History › Save As Command with steps rewritten to act on the selection or refused with the step named; saved commands at the end of the Commands menu with shortcuts; Manage Saved Commands; Run Command…; one transactional undo step; small JSON files in the settings folder; `macro.*` headless, CLI and MCP; macros call only what plug-ins may. Not yet: Replay Steps without saving, editing a macro's steps, macros that ask for values, the browser build and the command palette). **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: reshaping at a posed frame); ~~mixed armatures: symbol instances and shapes in one armature~~ ✅ (ADR 0098: bones inside a shape and bones that move instances or whole shapes in one armature, several skinned shapes, chains across the kinds with the Bone tool, one pose for IK, tweens, springs and translation, file format version 4 only for documents that use it; not yet: joining two armatures, joining a whole shape from a shape's bone by dragging, XFL import of armatures); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles) and brush library; ~~tilt, textured brushes, erasing inside symbols, gradients and width profiles in the merge~~ ✅ second slice (ADR 0093: tilt turns and widens the tip per sample, paper-grain texture and scatter as vector paint, Charcoal and Spatter, the Eraser's hint for symbols and objects, width profiles carried into each merged piece; not yet: reading tilt on desktop systems (winit 0.30 reports it only on iOS), bitmap, art and pattern brushes, eraser pressure and presets, the live preview through texture and tilt); ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). |
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); ~~AppImage desktop integration, portable mode, store readiness checks~~ ✅ (ADR 0094); next: store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline), ~~search and context help~~ ✅ (ADR 0096: a prebuilt index and an offline search page with the same ranking as `anicraft-cli guide search`; F1, Help › Help for This and each panel menu open the guide at the section for the dialog, panel or tool, through a map checked against the guide's headings; F1 moves from the shortcut editor, which keeps Ctrl+Alt+Shift+K); next: translated guides, a print edition (PDF through the browser; a native PDF proposed in ADR 0096), help for single fields; ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout), second slice ✅ (ADR 0087: the tools move like any panel, as a slim bar on any side or a tab laid out in columns; floating windows hold several tabs and drag back into a dock by their grip or title bar with the drop targets shown; docks collapse to strips of panel icons with flyouts over the stage (Esc or a click outside closes them); Manage Workspaces renames and deletes your own (built-in ones reset only); every panel fits the narrowest dock (200 pt), form rows wrapping under their label, checked by test in English and the pseudo-locale; not yet: dragging between two windows of their own on mixed-DPI screens verified by hand, panels side by side inside a floating window, columns of groLine truncated
+55
View File
@@ -509,6 +509,9 @@ pub struct App {
pub me_vscroll: f32,
/// Colour effect styles the Motion Editor lists besides those the tween uses (ADR 0056).
pub me_styles: Vec<anicraft_engine::doc::ColorStyle>,
/// The filter colours whose channels the Motion Editor lists (ADR 0099): filter slot and
/// colour. View state; it starts afresh on another span.
pub me_open: Vec<(u8, anicraft_engine::doc::FilterColor)>,
/// The frame grid was clicked more recently than the stage: Ctrl+X/C/V act on frames.
pub timeline_focus: bool,
/// A destructive command waiting for the user's decision (ADR 0004).
@@ -686,6 +689,7 @@ impl App {
session.recent = prefs.recent.clone();
session.brushes = prefs.brushes.clone();
session.filter_presets = prefs.filter_presets.clone();
session.filter_presets.restore_hidden(&prefs.filter_presets_hidden);
// Whether rulers, grid and guides show and snap carries over between sessions (ADR 0076).
session.aids = prefs.aids;
// The editor draws as Animate does: merge drawing, until Object Drawing (J) is switched on.
@@ -782,6 +786,7 @@ impl App {
me_drag: None,
me_vscroll: 0.0,
me_styles: Vec::new(),
me_open: Vec::new(),
timeline_focus: false,
confirm: None,
skip_confirm: HashSet::new(),
@@ -2740,6 +2745,56 @@ impl App {
let _ = self.s.execute("edit.deselect", &json!({}));
}
}
Some("motioncolour") => {
// A glow's colour tweening in the Motion Editor (ADR 0099): the Star becomes a
// movie clip with a glow that goes from gold to magenta and is knocked out for
// the last third; the editor lists the colour's channels and shows the red one.
self.run("layer.select", json!({"index": 1}));
self.run("timeline.goto", json!({"frame": 0}));
self.run("edit.select_all", json!({}));
self.run("symbol.set_kind", json!({"kind": "movie_clip"}));
self.run("element.set_filters", json!({"filters": [{"type": "glow", "color": "#ffd54a", "blur_x": 18, "blur_y": 18, "strength": 2, "quality": 2}]}));
if self.run("timeline.create_motion_tween", json!({"frame": 0})).is_some() {
let frames = self.s.active_layer().and_then(|l| l.keyframes.first()).map_or(24, |k| k.duration);
let (mid, end) = (frames / 2, frames.saturating_sub(1));
self.run("motion.set_key", json!({"property": "filter.0.color", "frame": mid, "color": "#ff3ea5"}));
self.run("motion.set_key", json!({"property": "filter.0.color", "frame": end, "color": "#5b8cff"}));
self.run("motion.set_ease", json!({"property": "filter.0.color", "frame": 1, "easing": "CubicOut"}));
self.run("motion.set_key", json!({"property": "filter.0.knockout", "frame": end.saturating_sub(frames / 3), "value": 1}));
self.s.mark_saved();
self.show_panel(crate::dock::Panel::MotionEditor);
// The colour's channels listed (the editor starts a span with them closed).
let start = self.s.active_layer().and_then(|l| l.keyframes.first()).map_or(0, |k| k.start);
self.me_sel_at = (self.s.layer.0, start);
self.me_open = vec![(0, anicraft_engine::doc::FilterColor::Color)];
self.me_prop = anicraft_engine::doc::Property::from_key("filter.0.color_red").unwrap_or(anicraft_engine::doc::Property::X);
self.me_key = Some(0);
// The filter rows in view.
self.me_vscroll = 7.0;
self.run("timeline.goto", json!({"frame": mid / 2}));
let _ = self.s.execute("edit.deselect", &json!({}));
}
}
Some("textshadow") => {
// A dynamic text field with a drop shadow and a glow switched off, selected:
// Properties › Filters lists them on text as on a movie clip (ADR 0099), and the
// stage draws the field (box, border and text) through them.
if self.run("text.create", json!({"text": "Score 0042", "type": "dynamic", "x": 760, "y": 520, "size": 64, "bold": true, "color": "#1b2a4a"})).is_some() {
self.run("text.field", json!({"border": true, "background": true, "background_color": "#fff6d8"}));
self.run("instance.set_name", json!({"name": "score_txt"}));
self.run(
"element.set_filters",
json!({"filters": [
{"type": "drop_shadow", "blur_x": 12, "blur_y": 12, "distance": 14, "strength": 0.6, "quality": 2, "color": "#1b2a4a"},
{"type": "glow", "blur_x": 8, "blur_y": 8, "color": "#ff3ea5", "enabled": false},
]}),
);
for p in [crate::dock::Panel::Align, crate::dock::Panel::Library, crate::dock::Panel::MovieExplorer, crate::dock::Panel::History] {
self.dock.close(p);
}
self.s.mark_saved();
}
}
Some("motionstretch") => {
// A motion span stretched by its end (ADR 0083): `motionspan`'s tween made half
// as long again, its keys in proportion, and its end being dragged further.
+3 -1
View File
@@ -122,7 +122,9 @@ fn all_keys() -> BTreeSet<Key> {
}
add(&doc::Easing::Linear.label());
doc::Property::ALL.iter().for_each(|p| add(p.label()));
doc::FilterParam::ALL.iter().for_each(|p| add(p.label()));
doc::FilterParam::all().iter().for_each(|p| add(p.label()));
[doc::FilterColor::Color, doc::FilterColor::Shadow, doc::FilterColor::Highlight, doc::FilterColor::Stop(0)].iter().for_each(|c| add(c.label()));
anicraft_engine::filter_library::BUILTIN_NAMES.iter().for_each(|n| add(n));
add("Filters");
add("Filter");
doc::ColorStyle::ALL.iter().for_each(|s| add(s.label()));
+24 -4
View File
@@ -122,10 +122,8 @@ pub fn of(doc: &Document, all: &[Arc<Element>]) -> Mixed {
_ => None,
})),
kind: differ(instances().map(|e| kind_of(e))),
filters: differ(clips().filter_map(|e| match &e.kind {
ElementKind::Symbol { filters, .. } => Some(filters),
_ => None,
})),
// Filters: movie clips, buttons and text (ADR 0099).
filters: differ(all.iter().filter(|e| matches!(e.kind, ElementKind::Text(_)) || kind_of(e).is_some_and(|k| k != SymbolKind::Graphic)).filter_map(|e| e.kind.filters())),
blend: differ(clips().filter_map(|e| match &e.kind {
ElementKind::Symbol { blend, .. } => Some(*blend),
_ => None,
@@ -277,6 +275,28 @@ mod tests {
assert!(!m.blend && !m.filters);
}
/// ADR 0099: text takes filters, so its Filters row compares with movie clips' and other
/// text's.
#[test]
fn the_filters_row_compares_text_too() {
if anicraft_engine::text::Fonts::get().families().is_empty() {
return; // No fonts on this computer: no text to make.
}
let (mut s, [a, _, _], _) = session();
let t1 = id(&run(&mut s, "text.create", json!({"text": "One", "x": 20, "y": 20})));
let t2 = id(&run(&mut s, "text.create", json!({"text": "Two", "x": 20, "y": 80})));
select(&mut s, &[t1, t2]);
assert!(!mixed(&s).filters);
select(&mut s, &[t1]);
run(&mut s, "element.set_filters", json!({"filters": [{"type": "drop_shadow"}]}));
select(&mut s, &[t1, t2]);
assert!(mixed(&s).filters, "one text has a shadow, the other none");
// A movie clip beside them is compared with them; setting the list makes all alike.
select(&mut s, &[t1, t2, a]);
run(&mut s, "element.set_filters", json!({"filters": [{"type": "glow"}]}));
assert!(!mixed(&s).filters);
}
#[test]
fn looping_and_first_frame_rows_compare_graphics_only() {
let (mut s, [a, _, g], _) = session();
+231 -33
View File
@@ -16,12 +16,16 @@
//! the stage, and removing one unpins it.
//!
//! Below the colour effect, each filter of the object (ADR 0092) lists its numbers under the
//! filter's name (Blur X, Blur Y, Strength…), curves and keys like the other properties.
//! filter's name (Blur X, Blur Y, Strength…), curves and keys like the other properties. Its
//! colours follow (ADR 0099): one row a colour, with a swatch that keys the whole colour at the
//! playhead and a diamond for all four channels; click the row to list its red, green, blue and
//! alpha, each a curve of its own. Last come quality and the switches, which hold their keys:
//! their curves are steps and they take no ease.
use crate::a11y::{self, Named};
use crate::app::App;
use crate::theme::{SQUARE, T, TARGET, Type, color, font, text, with_type};
use anicraft_engine::doc::{ColorStyle, Easing, Element, ElementKind, MotionTween, Pin, Property, Props, Track, filter_properties, own_value};
use anicraft_engine::doc::{Channel, ColorStyle, Easing, Element, FilterColor, FilterParam, FilterProp, MotionTween, Pin, Property, Props, Rgba, Track, filter_properties, own_value};
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, WidgetType, pos2, vec2};
use serde_json::json;
@@ -73,28 +77,90 @@ fn current(app: &App) -> Option<(u32, u32, MotionTween, Props, Vec<ColorStyle>,
Some((k.start, k.duration, m, Props::of(target), styles, (**target).clone()))
}
/// A row of the property list: a property, or the name of a filter above its numbers.
/// A row of the property list: a property, the name of a filter above its values, or one of a
/// filter's colours above its channels.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Row {
Prop(Property),
/// A filter's place, name and whether it is on.
Filter(u8, &'static str, bool),
/// A filter's colour (ADR 0099), by the filter's place: a swatch for the whole colour;
/// its four channels are listed under it when it is open.
Colour(u8, FilterColor),
}
/// The rows: [`listed`]'s properties, then each filter of the object with its numbers.
fn rows_for(used: &[ColorStyle], added: &[ColorStyle], target: &Element) -> Vec<Row> {
/// The four channels of the colour `c` of the filter at `slot`: red, green, blue, alpha.
fn channels(slot: u8, c: FilterColor) -> [Property; 4] {
Channel::ALL.map(|ch| Property::Filter(FilterProp { slot, param: FilterParam::Color(c, ch) }))
}
/// The rows: [`listed`]'s properties, then each filter of the object: its numbers, its
/// colours (with their channels where `open` lists them), then quality and its switches.
fn rows_for(used: &[ColorStyle], added: &[ColorStyle], target: &Element, open: &[(u8, FilterColor)]) -> Vec<Row> {
let mut out: Vec<Row> = listed(used, added).into_iter().map(Row::Prop).collect();
let ElementKind::Symbol { filters, .. } = &target.kind else { return out };
let Some(filters) = target.kind.filters() else { return out };
let mut props = filter_properties(target).into_iter().peekable();
for (slot, e) in filters.iter().enumerate() {
out.push(Row::Filter(slot as u8, e.filter.label(), e.enabled));
while let Some(p) = props.next_if(|p| p.filter().is_some_and(|f| usize::from(f.slot) == slot)) {
out.push(Row::Prop(p));
match p.filter().and_then(|f| f.param.color()) {
// A colour's row comes with its first channel; the channels only when open.
Some((c, ch)) => {
if ch == Channel::Red {
out.push(Row::Colour(slot as u8, c));
}
if open.contains(&(slot as u8, c)) {
out.push(Row::Prop(p));
}
}
None => out.push(Row::Prop(p)),
}
}
}
out
}
/// The name of a filter's colour: "Colour", "Shadow", "Highlight", "Stop 2".
fn colour_name(c: FilterColor) -> String {
match c {
FilterColor::Stop(n) => tr!("Stop {n}", n = u32::from(n) + 1),
c => crate::i18n::t(c.label()).to_string(),
}
}
/// A property's name on its own row: its label, and for a colour's channel just the channel.
/// With `full`, as screen readers and the graph say it: "Glow: Colour · Red", "Blur: Blur X".
fn prop_name(target: &Element, p: Property, full: bool) -> String {
let label = crate::i18n::t(p.label());
let Some(f) = p.filter().filter(|_| full) else { return label.to_string() };
let filter = crate::i18n::t(filter_name(target, f.slot));
match f.param.color() {
Some((c, _)) => tr!("{filter}: {colour} · {channel}", filter = filter, colour = colour_name(c), channel = label),
None => tr!("{filter}: {property}", filter = filter, property = label),
}
}
/// A stepped value in words: a switch is On or Off, quality Low, Medium or High.
fn stepped_text(p: Property, v: f32) -> Option<String> {
let f = p.filter().filter(|f| f.param.is_stepped())?;
let word: &str = match f.param {
FilterParam::Quality => [tr!("Low"), tr!("Medium"), tr!("High")].get((v.round() as usize).clamp(1, 3) - 1).copied().unwrap_or_default(),
_ if v >= 0.5 => tr!("On"),
_ => tr!("Off"),
};
Some(word.to_string())
}
/// The colour `c` of the object's filter at `slot`, as the object `at` (it at a frame) has it.
fn colour_of(at: &Element, slot: u8, c: FilterColor) -> Option<Rgba> {
at.kind.filters()?.get(usize::from(slot))?.filter.color(c).map(Rgba::sanitized)
}
/// A colour as commands take it, alpha included.
fn hex8(c: Rgba) -> String {
format!("{}{:02x}", c.to_hex(), (c.sanitized().a * 255.0).round() as u8)
}
/// The properties the list shows: position and transform, and the colour effect styles the
/// tween uses or the artist added (Alpha when there are none).
fn listed(used: &[ColorStyle], added: &[ColorStyle]) -> Vec<Property> {
@@ -113,6 +179,9 @@ fn nice_step(span: f32) -> f32 {
}
fn fmt(p: Property, v: f32) -> String {
if let Some(s) = stepped_text(p, v) {
return s;
}
match p {
Property::X | Property::Y => format!("{v:.1} {}", p.unit()),
_ => format!("{v:.1}{}", p.unit()),
@@ -146,6 +215,8 @@ fn value_range(track: Option<&Track>, base: f32, frames: u32, p: Property) -> (f
}
let min_span = match p {
Property::X | Property::Y => 20.0,
// A switch's two values, or quality's three, fill the view.
p if p.is_stepped() => 1.0,
_ => 10.0,
};
if hi - lo < min_span {
@@ -174,6 +245,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let here = (app.s.layer.0, start);
if app.me_sel_at != here {
app.me_sel.clear();
app.me_open.clear();
app.me_sel_at = here;
}
app.me_sel.retain(|(p, f)| m.track(*p).is_some_and(|t| t.key_at(*f).is_some()));
@@ -199,7 +271,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let rows_top = list.top() + RULER_H;
// Rows that don't fit scroll with the wheel over the list.
let fit = (((list.bottom() - rows_top) / ROW_H).floor() as usize).max(1);
let list_rows = rows_for(&used, &app.me_styles, &target);
let list_rows = rows_for(&used, &app.me_styles, &target, &app.me_open);
let rows: Vec<Property> = list_rows.iter().filter_map(|r| if let Row::Prop(p) = r { Some(*p) } else { None }).collect();
if !rows.contains(&app.me_prop) {
app.me_prop = Property::X;
@@ -228,11 +300,17 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
last_group = "Filters"; // i18n-exempt: a group key (Property::group), not shown
continue;
}
Row::Colour(slot, c) => {
colour_row(app, ui, &painter, row, r, &m, &target, &at, offset, slot, c);
continue;
}
};
let selected = app.me_prop == p;
painter.rect_filled(row, 0.0, if selected { T.accent_dim } else if r % 2 == 0 { T.panel } else { T.panel_alt });
let track = m.track(p);
let label = crate::i18n::t(p.label());
let label = prop_name(&target, p, false);
// A colour's channels sit under its row, set in.
let indent = if p.filter().is_some_and(|f| f.param.color().is_some()) { 16.0 } else { 0.0 };
// Groups (Position, Transform, Colour effect) are set apart by a rule.
if p.group() != last_group {
if !last_group.is_empty() {
@@ -240,16 +318,13 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
}
last_group = p.group();
}
painter.text(pos2(row.left() + 12.0, row.center().y), Align2::LEFT_CENTER, label, font(Type::Body), if track.is_some() { T.text } else { T.text_dim });
painter.text(pos2(row.left() + 12.0 + indent, row.center().y), Align2::LEFT_CENTER, label, font(Type::Body), if track.is_some() { T.text } else { T.text_dim });
if track.is_some() {
painter.text(pos2(row.left() + 84.0, row.center().y), Align2::LEFT_CENTER, tr!("keyed"), font(Type::Caption), T.tween_motion);
}
let rr = ui.interact(row, ui.id().with(("me_row", p.key())), Sense::click());
let label = match p.filter() {
// Named with its filter for screen readers and tips ("Blur: Blur X").
Some(f) => tr!("{filter}: {property}", filter = crate::i18n::t(filter_name(&target, f.slot)), property = label),
None => label.to_string(),
};
// Named with its filter for screen readers and tips ("Blur: Blur X").
let label = prop_name(&target, p, true);
let label = label.as_str();
a11y::control(ui, &rr, WidgetType::SelectableLabel, &if track.is_some() { tr!("{property} · keyed", property = label) } else { label.to_string() }, Some(selected));
if rr.clicked() {
@@ -264,13 +339,36 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let suffix = if p.unit() == "px" { " px" } else { p.unit() };
// In a child placed on the row, so the field never grows the dock.
let mut cell = ui.new_child(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center)));
let r = with_type(&mut cell, Type::Data, |ui| ui.add_sized(vec2(field.width(), field.height()), egui::DragValue::new(&mut v).speed(speed).range(range).max_decimals(1).suffix(suffix)).named(label));
if r.changed() {
let r = match p.filter().map(|f| f.param).filter(|q| q.is_stepped()) {
// A switch: a tick box. Changing it keys it at the playhead, like any value.
Some(FilterParam::Inner | FilterParam::Knockout | FilterParam::HideObject) => {
let mut on = v >= 0.5;
let r = crate::theme::checkbox(&mut cell, &mut on, "").named(label);
v = if on { 1.0 } else { 0.0 };
r
}
// Quality: Low, Medium, High (drag, or type the word or 1 to 3).
Some(_) => with_type(&mut cell, Type::Body, |ui| {
let words: [&'static str; 3] = [tr!("Low"), tr!("Medium"), tr!("High")];
let dv = egui::DragValue::new(&mut v)
.speed(0.03)
.range(range)
.custom_formatter(move |n, _| words.get((n.round() as usize).clamp(1, 3) - 1).copied().unwrap_or_default().to_string())
.custom_parser(move |s| words.iter().position(|w| w.eq_ignore_ascii_case(s.trim())).map(|i| (i + 1) as f64).or_else(|| s.trim().parse::<f64>().ok()));
ui.add_sized(vec2(field.width(), field.height()), dv).named(label)
}),
None => with_type(&mut cell, Type::Data, |ui| ui.add_sized(vec2(field.width(), field.height()), egui::DragValue::new(&mut v).speed(speed).range(range).max_decimals(1).suffix(suffix)).named(label)),
};
if p.is_stepped() {
v = v.round();
}
if r.changed() && (!p.is_stepped() || (v - now_of(p)).abs() > 0.5) {
app.me_prop = p;
app.s.begin_gesture(tr_noop!("Property keyframe"));
app.run("motion.set_key", json!({"property": p.key(), "frame": app.s.frame, "value": v}));
}
if r.drag_stopped() {
// A switch is one click: its undo step ends with it.
if r.drag_stopped() || (r.changed() && p.is_stepped() && !r.dragged()) {
app.s.end_gesture();
}
// Key toggle: a filled diamond where this property has a key at the playhead.
@@ -302,10 +400,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
// ---- graph -----------------------------------------------------------------------------
let p = app.me_prop;
let track = m.track(p);
let label = match p.filter() {
Some(f) => tr!("{filter}: {property}", filter = crate::i18n::t(filter_name(&target, f.slot)), property = crate::i18n::t(p.label())),
None => crate::i18n::t(p.label()).to_string(),
};
let label = prop_name(&target, p, true);
let (lo, hi) = match app.me_drag {
Some(MeDrag::Key { lo, hi, lane: false, .. } | MeDrag::Handle { lo, hi, .. }) => (lo, hi),
_ => value_range(track, own(p), frames, p),
@@ -366,12 +461,28 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
if track.is_none() {
gp.text(graph.center(), Align2::CENTER_CENTER, tr!("{property} has no keyframes: it stays {value}. Click ◇ or drag its value to key it here.", property = label, value = fmt(p, own(p))), font(Type::Caption), color(Type::Caption));
}
// A colour's channel: the whole colour over the span, along the bottom of the graph, so
// the four curves read as the colour they make (ADR 0099).
if let Some((f, (c, _))) = p.filter().and_then(|f| Some((f, f.param.color()?))) {
let strip = Rect::from_min_max(pos2(inner.left(), graph.bottom() - 10.0), pos2(inner.right(), graph.bottom() - 3.0));
let step = (strip.width() / 160.0).max(3.0);
let mut x = strip.left();
while x < strip.right() {
let x1 = (x + step).min(strip.right());
if let Some(rgba) = colour_of(&m.apply(&target, f_of((x + x1) * 0.5)), f.slot, c) {
gp.rect_filled(Rect::from_min_max(pos2(x, strip.top()), pos2(x1, strip.bottom())), 0.0, crate::theme::to_color32(rgba));
}
x = x1;
}
gp.rect_stroke(strip, 0.0, Stroke::new(1.0, T.border), egui::StrokeKind::Outside);
}
// Keys and the selected segment's handles.
let keys: Vec<(u32, f32, Easing)> = track.map(|t| t.keys.iter().filter(|k| k.frame < frames).map(|k| (k.frame, k.value, k.ease.clone())).collect()).unwrap_or_default();
// The selected key: the one picked, else the one starting the segment at the playhead.
let sel_key = app.me_key.filter(|f| keys.iter().any(|k| k.0 == *f)).or_else(|| keys.iter().rev().find(|k| k.0 <= offset).map(|k| k.0));
let handles: Option<[Pos2; 4]> = sel_key.and_then(|f| {
// A stepped property holds its keys: no ease, so no handles (ADR 0099).
let handles: Option<[Pos2; 4]> = sel_key.filter(|_| !p.is_stepped()).and_then(|f| {
let i = keys.iter().position(|k| k.0 == f)?;
let (a, b) = (keys.get(i)?, track?.keys.get(i + 1)?);
// Eases one curve can't draw (Bounce, Elastic, custom curves) are shaped in the
@@ -614,12 +725,76 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
/// The name of the object's filter at `slot` (Animate's, for the list and screen readers).
fn filter_name(target: &Element, slot: u8) -> &'static str {
match &target.kind {
ElementKind::Symbol { filters, .. } => filters.get(usize::from(slot)).map_or("Filter", |e| e.filter.label()), // i18n-exempt: translated where drawn (i18n::t)
_ => "Filter", // i18n-exempt: translated where drawn (i18n::t)
match target.kind.filters() {
Some(filters) => filters.get(usize::from(slot)).map_or("Filter", |e| e.filter.label()), // i18n-exempt: translated where drawn (i18n::t)
None => "Filter", // i18n-exempt: translated where drawn (i18n::t)
}
}
/// A filter colour's row (ADR 0099): its name with a mark that opens its channels, a swatch
/// showing the colour at the playhead (picking one keys all four channels there, one undo step
/// a pick) and a diamond that adds or removes the four keys.
#[allow(clippy::too_many_arguments)]
fn colour_row(app: &mut App, ui: &mut egui::Ui, painter: &egui::Painter, row: Rect, r: usize, m: &MotionTween, target: &Element, at: &Element, offset: u32, slot: u8, c: FilterColor) {
let four = channels(slot, c);
let open = app.me_open.contains(&(slot, c));
let any_track = four.iter().any(|p| m.track(*p).is_some());
painter.rect_filled(row, 0.0, if r.is_multiple_of(2) { T.panel } else { T.panel_alt });
// The mark: pointing right when closed, down when its channels show.
let tip = pos2(row.left() + 16.0, row.center().y);
let tri = if open { vec![tip + vec2(-4.0, -2.5), tip + vec2(4.0, -2.5), tip + vec2(0.0, 3.5)] } else { vec![tip + vec2(-2.5, -4.0), tip + vec2(3.5, 0.0), tip + vec2(-2.5, 4.0)] };
painter.add(egui::Shape::convex_polygon(tri, T.text_dim, Stroke::NONE));
let name = colour_name(c);
painter.text(pos2(row.left() + 26.0, row.center().y), Align2::LEFT_CENTER, &name, font(Type::Body), if any_track { T.text } else { T.text_dim });
if any_track {
painter.text(pos2(row.left() + 84.0, row.center().y), Align2::LEFT_CENTER, tr!("keyed"), font(Type::Caption), T.tween_motion);
}
let key = format!("filter.{slot}.{}", c.key());
let full = tr!("{filter}: {colour}", filter = crate::i18n::t(filter_name(target, slot)), colour = name);
let rr = ui.interact(row, ui.id().with(("me_colour", slot, c)), Sense::click());
a11y::control(ui, &rr, WidgetType::CollapsingHeader, &if any_track { tr!("{property} · keyed", property = full.as_str()) } else { full.clone() }, Some(open));
if rr.clicked() {
if open {
app.me_open.retain(|o| *o != (slot, c));
} else {
app.me_open.push((slot, c));
// Its first channel's curve shows, with the colour along the graph's foot.
if let Some(red) = four.first() {
app.me_prop = *red;
app.me_key = None;
}
}
}
// The colour at the playhead: pick one to key it there.
let field = Rect::from_min_size(pos2(row.right() - 128.0, row.top() + 3.0), vec2(88.0, ROW_H - 6.0));
let now = colour_of(at, slot, c).unwrap_or(Rgba::BLACK);
let mut picked = now;
let mut cell = ui.new_child(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center)));
if crate::panels::alpha_swatch(&mut cell, &mut picked, &full) {
app.s.begin_gesture(tr_noop!("Filter colour keyframe"));
app.run("motion.set_key", json!({"property": key, "frame": app.s.frame, "color": hex8(picked)}));
app.s.end_gesture();
}
// The diamond: filled where all four channels have a key at the playhead.
let keyed = four.iter().all(|p| m.track(*p).is_some_and(|t| t.key_at(offset).is_some()));
let toggle = Rect::from_center_size(pos2(row.right() - 20.0, row.center().y), vec2(24.0, 24.0));
let tr = ui.interact(toggle, ui.id().with(("me_colour_key", slot, c)), Sense::click());
if tr.hovered() {
painter.rect_filled(toggle, T.rc(), T.hover);
}
diamond(painter, toggle.center(), 5.0, if keyed { T.text } else { Color32::TRANSPARENT }, Stroke::new(1.5, if keyed { T.text } else { T.text_faint }));
let tip = if keyed { tr!("Remove the {property} keyframe at frame {frame}", property = full.as_str(), frame = app.s.frame + 1) } else { tr!("Add a {property} keyframe at frame {frame}", property = full.as_str(), frame = app.s.frame + 1) };
a11y::control(ui, &tr, WidgetType::Checkbox, &tr!("{property} keyframe at frame {frame}", property = full.as_str(), frame = app.s.frame + 1), Some(keyed));
if tr.on_hover_text(tip).clicked() {
if keyed {
app.run("motion.remove_key", json!({"property": key, "frame": app.s.frame}));
} else {
app.run("motion.set_key", json!({"property": key, "frame": app.s.frame, "color": hex8(now)}));
}
}
painter.line_segment([row.left_bottom(), row.right_bottom()], Stroke::new(1.0, T.separator));
}
/// Picks `keys` (every property's keys on one frame): instead of the pick, or added to it.
fn pick_frame(app: &mut App, keys: Vec<(Property, u32)>, add: bool) {
if !add {
@@ -721,6 +896,10 @@ fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, s
let seg = sel_key.zip(track).and_then(|(f, t)| t.key_at(f).filter(|i| *i + 1 < t.keys.len()).and_then(|i| t.keys.get(i)).map(|k| (f, k.ease.clone())));
ui.label(text(Type::Label, tr!("{property} ease", property = label)));
match seg {
// Quality and the switches hold their keys (ADR 0099).
_ if p.is_stepped() => {
ui.label(text(Type::Caption, tr!("Holds each key until the next one (no ease)")));
}
Some((f, ease)) => {
// The presets and the saved eases (ADR 0081); Edit Ease… shapes the segment's curve.
match crate::ease_editor::picker(app, ui, "me_ease", &ease, 160.0, tr!("Ease")) {
@@ -792,16 +971,35 @@ mod tests {
/// colour effect.
#[test]
fn filters_list_their_numbers_under_their_names() {
use anicraft_engine::doc::{ColorEffect, ElementId, Filter, FilterEntry, SymbolId};
use anicraft_engine::doc::{ColorEffect, ElementId, ElementKind, Filter, FilterEntry, SymbolId};
use anicraft_engine::geom::Affine;
let filters = vec![FilterEntry::from(Filter::new("blur").unwrap()), FilterEntry { filter: Filter::new("adjust_color").unwrap(), enabled: false }];
let clip = Element { id: ElementId(1), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters, events: Vec::new() } };
let rows = rows_for(&[], &[], &clip);
let names: Vec<String> = rows.iter().skip_while(|r| matches!(r, Row::Prop(p) if !p.is_filter())).map(|r| match r {
Row::Filter(slot, name, on) => format!("[{slot} {name} {on}]"),
Row::Prop(p) => p.key().into_owned(),
}).collect();
assert_eq!(names, ["[0 Blur true]", "filter.0.blur_x", "filter.0.blur_y", "[1 Adjust Color false]", "filter.1.brightness", "filter.1.contrast", "filter.1.saturation", "filter.1.hue"]);
let names = |rows: Vec<Row>| -> Vec<String> {
rows.iter()
.skip_while(|r| matches!(r, Row::Prop(p) if !p.is_filter()))
.map(|r| match r {
Row::Filter(slot, name, on) => format!("[{slot} {name} {on}]"),
Row::Colour(slot, c) => format!("({slot} {})", c.key()),
Row::Prop(p) => p.key().into_owned(),
})
.collect()
};
assert_eq!(names(rows_for(&[], &[], &clip, &[])), ["[0 Blur true]", "filter.0.blur_x", "filter.0.blur_y", "filter.0.quality", "[1 Adjust Color false]", "filter.1.brightness", "filter.1.contrast", "filter.1.saturation", "filter.1.hue"]);
// ADR 0099: a colour is one row; its channels are listed when it is open; quality and
// the switches come last.
let glow = Element { kind: ElementKind::Symbol { symbol: SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: vec![Filter::new("glow").unwrap().into()], events: Vec::new() }, ..clip.clone() };
assert_eq!(names(rows_for(&[], &[], &glow, &[])), ["[0 Glow true]", "filter.0.blur_x", "filter.0.blur_y", "filter.0.strength", "(0 color)", "filter.0.quality", "filter.0.inner", "filter.0.knockout"]);
let open = names(rows_for(&[], &[], &glow, &[(0, FilterColor::Color)]));
assert_eq!(open[4..9], ["(0 color)", "filter.0.color_red", "filter.0.color_green", "filter.0.color_blue", "filter.0.color_alpha"]);
assert_eq!(prop_name(&glow, Property::from_key("filter.0.color_red").unwrap(), true), "Glow: Colour · Red");
assert_eq!(prop_name(&glow, Property::from_key("filter.0.color_red").unwrap(), false), "Red");
assert_eq!(colour_name(FilterColor::Stop(1)), "Stop 2");
assert_eq!(stepped_text(Property::from_key("filter.0.knockout").unwrap(), 1.0).as_deref(), Some("On"));
assert_eq!(stepped_text(Property::from_key("filter.0.quality").unwrap(), 2.0).as_deref(), Some("Medium"));
assert_eq!(stepped_text(Property::X, 2.0), None);
// A colour goes to commands with its alpha.
assert_eq!(hex8(Rgba::hex(0xff8000).with_alpha(0.5)), "#ff800080");
assert_eq!(filter_name(&clip, 1), "Adjust Color");
assert_eq!(filter_name(&clip, 7), "Filter");
}
+38 -2
View File
@@ -1076,12 +1076,15 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
if !matches!(e.kind, ElementKind::Camera) {
colour_effect_rows(app, ui, &e.color, m.color, EffectOf::Selection);
}
// Blending and filters, on movie clips and buttons.
// Blending and filters, on movie clips and buttons; filters on text too (ADR 0099).
if let ElementKind::Symbol { symbol, filters, .. } = &e.kind
&& app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic)
{
filter_rows(app, ui, filters, m.filters);
}
if let ElementKind::Text(t) = &e.kind {
filter_rows(app, ui, &t.filters, m.filters);
}
if let ElementKind::Symbol { symbol, blend, .. } = &e.kind
&& app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic)
{
@@ -1488,6 +1491,7 @@ pub fn sync_filter_presets(app: &mut App) {
return;
}
app.prefs.filter_presets = app.s.filter_presets.clone();
app.prefs.filter_presets_hidden = app.s.filter_presets.hidden().to_vec();
if app.shot.is_none()
&& let Err(e) = app.prefs.save()
{
@@ -1504,6 +1508,8 @@ enum FilterAct {
Paste,
Apply(String),
Delete(String),
/// Hide a built-in preset from the menu, or show it again.
Hide(String, bool),
}
/// A filter's grip: drag it up or down the list to reorder, or, focused, Alt+Up and Alt+Down
@@ -1544,7 +1550,10 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc
let n = list.len();
let mut changed: Option<&'static str> = None;
let mut act: Option<FilterAct> = None;
let presets: Vec<(String, String)> = app.s.filter_presets.presets().iter().map(|p| (p.name.clone(), p.filters.iter().map(|f| crate::i18n::t(f.filter.label())).collect::<Vec<_>>().join(", "))).collect();
let what = |p: &anicraft_engine::filter_library::FilterPreset| p.filters.iter().map(|f| crate::i18n::t(f.filter.label())).collect::<Vec<_>>().join(", ");
let presets: Vec<(String, String)> = app.s.filter_presets.presets().iter().map(|p| (p.name.clone(), what(p))).collect();
// The built-in presets (ADR 0099): name, what is in it, and whether the menu lists it.
let builtin: Vec<(&'static str, String, bool)> = anicraft_engine::filter_library::BUILTIN_NAMES.into_iter().zip(anicraft_engine::filter_library::builtins().iter()).map(|(name, p)| (name, what(p), !app.s.filter_presets.is_hidden(name))).collect();
let copied = app.s.filter_clipboard.as_ref().map_or(0, Vec::len);
let mut naming = app.filter_naming.name.clone();
row_prose(ui, tr!("Filters"), |ui| {
@@ -1562,6 +1571,20 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc
.set_name(tr!("Add filter"));
let pr = crate::timeline::icon_button(ui, tr!("Filter presets: apply, save, rename, delete, import, export"), None, Icon::Folder);
egui::Popup::menu(&pr).id(egui::Id::new("anicraft.filters.presets")).show(|ui| {
// The built-in presets the menu lists, then your own.
let shown: Vec<&(&'static str, String, bool)> = builtin.iter().filter(|b| b.2).collect();
if !shown.is_empty() {
ui.label(text(Type::Caption, tr!("Built-in")));
}
for (name, what, _) in shown.iter().copied() {
if ui.button(crate::i18n::t(name)).on_hover_text(tr!("Apply: {filters} (replaces the filters)", filters = what.as_str())).clicked() {
act = Some(FilterAct::Apply((*name).to_string()));
}
}
if !shown.is_empty() {
ui.separator();
ui.label(text(Type::Caption, tr!("Yours")));
}
if presets.is_empty() {
ui.label(text(Type::Caption, tr!("No presets yet. Set up filters, then Save as Preset.")));
}
@@ -1571,6 +1594,16 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc
}
}
ui.separator();
// Built-in presets can't be deleted: untick one to take it off this menu.
ui.menu_button(tr!("Built-in Presets"), |ui| {
ui.label(text(Type::Caption, tr!("Untick one to hide it from this menu")));
for (name, _, listed) in &builtin {
let mut on = *listed;
if crate::theme::checkbox(ui, &mut on, crate::i18n::t(name)).named(&tr!("Show the built-in preset {name}", name = crate::i18n::t(name))).changed() {
act = Some(FilterAct::Hide((*name).to_string(), !on));
}
}
});
if ui.add_enabled(n > 0, egui::Button::new(tr!("Save as Preset…"))).on_hover_text(tr!("Keep these filters under a name, for any document")).clicked() {
naming = Some((String::new(), None));
}
@@ -1845,6 +1878,9 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc
app.run("filter.preset_apply", json!({"name": name}));
}
FilterAct::Delete(name) => app.request("filter.preset_delete", json!({"name": name})),
FilterAct::Hide(name, hidden) => {
app.run("filter.preset_hide", json!({"name": name, "hidden": hidden}));
}
}
return;
}
+20
View File
@@ -154,6 +154,8 @@ pub struct Prefs {
/// Filter presets of your own (ADR 0091), for movie clips and buttons in any document.
#[serde(deserialize_with = "lenient_filter_presets")]
pub filter_presets: anicraft_engine::filter_library::FilterLibrary,
/// The built-in filter presets you have hidden from the presets menu (ADR 0099), by name.
pub filter_presets_hidden: Vec<String>,
/// Test Movie plays in a window of its own (ADR 0062); off, or where a system can't open
/// one, it floats inside the editor.
pub test_movie_window: bool,
@@ -240,6 +242,7 @@ impl Default for Prefs {
start_screen: true,
brushes: Default::default(),
filter_presets: Default::default(),
filter_presets_hidden: Vec::new(),
test_movie_window: true,
test_movie_pos: None,
workspaces: crate::dock::Workspaces::default(),
@@ -355,6 +358,9 @@ impl Prefs {
self.recent = std::mem::take(&mut self.recent).sanitized();
self.brushes = std::mem::take(&mut self.brushes).sanitized();
self.filter_presets = std::mem::take(&mut self.filter_presets).sanitized();
// The library carries which built-in presets are hidden; names that aren't one go.
self.filter_presets.restore_hidden(&self.filter_presets_hidden);
self.filter_presets_hidden = self.filter_presets.hidden().to_vec();
self.test_movie_pos = self.test_movie_pos.filter(|[x, y]| x.is_finite() && y.is_finite() && x.abs() < 1e5 && y.abs() < 1e5);
self
}
@@ -542,6 +548,20 @@ mod tests {
assert!(!p.start_screen);
let back = Prefs::from_json(&serde_json::to_string(&p).unwrap());
assert_eq!(back.brushes, p.brushes);
// The built-in filter presets you have hidden (ADR 0099): none in older files; names
// that aren't a built-in preset's are dropped; they survive a save and load beside
// your own presets, whose list stays a plain list (what older builds read).
let p = Prefs::from_json(r#"{"ui_scale": 1.25}"#);
assert!(p.filter_presets_hidden.is_empty() && p.filter_presets.hidden().is_empty());
let p = Prefs::from_json(r#"{"filter_presets": [{"name": "Mine", "filters": [{"type": "blur"}]}, {"name": "Emboss", "filters": [{"type": "glow"}]}], "filter_presets_hidden": ["emboss", "Mine", "nope", "Soft Shadow"]}"#);
assert_eq!(p.filter_presets_hidden, ["Soft Shadow", "Emboss"]);
assert_eq!(p.filter_presets.hidden(), ["Soft Shadow", "Emboss"]);
let names: Vec<_> = p.filter_presets.presets().iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, ["Mine", "Emboss 2"], "a preset of yours named like a built-in one is numbered");
let json = serde_json::to_value(&p).unwrap();
assert!(json["filter_presets"].is_array() && json["filter_presets_hidden"] == serde_json::json!(["Soft Shadow", "Emboss"]));
let back = Prefs::from_json(&json.to_string());
assert_eq!((back.filter_presets, back.filter_presets_hidden), (p.filter_presets, p.filter_presets_hidden));
// Older files open Test Movie in its own window, with no remembered place (ADR 0062);
// a place someone broke by hand is forgotten, not used.
let p = Prefs::from_json(r#"{"ui_scale": 1.25}"#);