Merge pull request #150 from storytold/m2/colour-effects

feat(doc): colour effects, complete: every style, one exact colour transform (M2)
This commit is contained in:
Tanish Manku authored and GitHub committed 2026-11-11 14:23:29 -07:00
commit 46a45951cd
62 files changed
+1950 -305

No files matched your search

+1
View File
@@ -87,6 +87,7 @@ OR Apache-2.0) is noted in the table.
| Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. |
| Blend modes (separable modes, premultiplied) | `crates/render/src/lib.rs`, `crates/gpu/src/fine.wgsl` | W3C Compositing and Blending Level 1 | W3C Royalty-Free Patent Policy. |
| Adjust Color filter (brightness, contrast, saturation and hue as colour matrices) | `crates/render/src/filters.rs` | Paul Haeberli, *Matrix Operations for Image Processing* (Silicon Graphics, 1993) | Public description; standard matrix operations. |
| Colour effects (per-channel multiply and offset; brightness and tint as such transforms) | `crates/doc/src/color_effect.rs`, `crates/gpu/src/fine.wgsl`, `crates/render/src/svg.rs` | Adobe, *ActionScript 3.0 Reference: flash.geom.ColorTransform* (public documentation); W3C *Filter Effects Module Level 1*, `feColorMatrix` | Behaviour learned from the public descriptions; no code or assets used (ADR 0056). |
| Blur, drop shadow and glow by repeated box blurs | `crates/render/src/filters.rs` | Standard image processing (repeated box filters approach a Gaussian, central limit theorem) | Public; no specific implementation followed. |
| Bevel and Gradient Bevel by offset differences of the blurred opacity; Gradient Glow and Gradient Bevel through a colour ramp | `crates/render/src/filters.rs` | Standard image processing: embossing as the difference of an image offset along the light direction (a directional derivative; e.g. R. C. Gonzalez & R. E. Woods, *Digital Image Processing*); parameters and behaviour from Adobe's public Animate user guide and ActionScript 3.0 reference (`BevelFilter`, `GradientGlowFilter`, `GradientBevelFilter`) | Public descriptions only; no Adobe code or assets (ADR 0025). |
| Bevel and gradient filters in SVG export (`feComposite` arithmetic, `feComponentTransfer` tables) | `crates/render/src/svg.rs` | W3C Filter Effects Module Level 1 / SVG 1.1 filters | W3C Royalty-Free Patent Policy. |
+21
View File
@@ -2,6 +2,27 @@
## Unreleased
* **Colour effects, complete** (ADR 0056, M2).
* **Properties › Colour effect**: Animate's Style menu (None, Brightness, Tint, Advanced,
Alpha) with each style's controls: brightness −100..100 %, tint colour and amount,
Advanced's multiplier and offset for red, green, blue and alpha. Every row says "mixed"
when the selection differs, and a change sets only that value on all of them. Switching
style keeps the look where it can (Advanced starts as exactly the effect before).
* One exact colour transform behind every style: nested effects compose exactly (a
brightness around a tint shows both), and the CPU renderer, the GPU stage (bitmaps
included, pixel-identical), SVG (`feColorMatrix` on bitmaps), HTML canvas (bitmaps
recoloured, no longer reported) and Lottie (baked into the colours) draw the same.
* Classic tweens interpolate within a style (a brightness tween passes through 0) and across
styles in the Advanced space, as Animate does.
* Motion tweens key **Brightness**, **Tint** colour (red, green, blue) beside its amount, and
the eight **Advanced** values; the Motion Editor lists the styles in use and adds others
with **Add Colour Effect**. A tween has one colour effect style, as in Animate.
* XFL/FLA import brings every `Color` style across (Advanced no longer keeps only its
alpha); a new `colour` corpus package with goldens.
* `element.set_color_effect` for the CLI, MCP and plug-ins; `element.set_alpha` now keeps
the rest of the effect. Older files open unchanged, and None, Alpha and Tint effects are
still written exactly as before.
* **9-slice scaling for symbols** (ADR 0055, M2).
* **Enable guides for 9-slice scaling** on a symbol, in the Library's item properties or in
Properties. A scaled instance then keeps its corners unscaled, stretches its edges one way
+11 -7
View File
@@ -11,7 +11,7 @@
//! keeping its size (so a layer at depth 0 moves with the stage, a far background barely moves).
//! Everything here is pure: the camera at a frame is a function of the document.
use crate::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements};
use crate::{ColorEffect, ColorTransform, Element, ElementId, ElementKind, Layer, LayerKind, Rgba, Stage, Timeline, evaluate_layer_elements};
use anicraft_geom::{Affine, Decomposed, Vec2};
/// Smallest and largest camera zoom (5 % to 2,000 %).
@@ -55,13 +55,17 @@ impl Camera {
let center = Vec2::new(fin(d.tx, rest.center.x), fin(d.ty, rest.center.y));
let zoom = fin(d.sx.abs(), 1.0).clamp(MIN_ZOOM, MAX_ZOOM);
let rotation = fin(d.rotation, 0.0);
let c = el.color;
Camera { center, zoom, rotation, tint: c.tint.sanitized(), tint_amount: fin(c.tint_amount, 0.0).clamp(0.0, 1.0) }
// The camera's colour effect is a tint (ADR 0027); other styles leave the view as it is.
let (tint, amount) = match el.color {
ColorEffect::Tint { color, amount } => (color.sanitized(), fin(amount, 0.0).clamp(0.0, 1.0)),
_ => (Rgba::WHITE, 0.0),
};
Camera { center, zoom, rotation, tint, tint_amount: amount }
}
/// The camera element holding this camera (for commands).
pub fn to_element(&self, id: ElementId) -> Element {
Element { id, name: String::new(), transform: self.transform(), color: ColorEffect { alpha: 1.0, tint: self.tint, tint_amount: self.tint_amount }, kind: ElementKind::Camera }
Element { id, name: String::new(), transform: self.transform(), color: ColorEffect::Tint { color: self.tint, amount: self.tint_amount }, kind: ElementKind::Camera }
}
/// The camera on the stage: `T(centre) · R(rotation) · S(zoom)`.
@@ -70,8 +74,8 @@ impl Camera {
}
/// The colour effect the camera puts on everything it shows.
pub fn color(&self) -> ColorEffect {
ColorEffect { alpha: 1.0, tint: self.tint, tint_amount: self.tint_amount }
pub fn color(&self) -> ColorTransform {
ColorTransform::tint(self.tint, self.tint_amount)
}
/// Stage space → output space for a layer `depth` pixels behind the stage: the camera's
@@ -219,7 +223,7 @@ mod tests {
fn hostile_cameras_stay_finite() {
let mut el = Camera::rest(&stage()).to_element(ElementId(1));
el.transform = Affine { m: [f32::NAN, 0.0, 0.0, f32::INFINITY, f32::NAN, 1e30] };
el.color.tint_amount = f32::NAN;
el.color = ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN };
let c = Camera::of_element(&el, &stage());
assert!(c.view(&stage(), 0.0).is_finite());
assert!((MIN_ZOOM..=MAX_ZOOM).contains(&c.zoom));
+1 -2
View File
@@ -70,8 +70,7 @@ fn camera_rotation_and_tint_apply_to_the_whole_view() {
// Stage point (105, 50) is right of the centre; the camera turned clockwise, so it shows
// above the middle. In the square's space that point is (10, 50).
assert!(i.transform.apply(Vec2::new(10.0, 50.0)).distance(Vec2::new(100.0, 45.0)) < 1e-3);
assert_eq!(i.color.tint_amount, 0.5);
assert_eq!(i.color.tint, Rgba::hex(0xff0000));
assert_eq!(i.color, crate::ColorTransform::tint(Rgba::hex(0xff0000), 0.5));
}
#[test]
+526
View File
@@ -0,0 +1,526 @@
//! Colour effects (ADR 0056): what Animate's Properties calls an instance's colour effect
//! *style* (None, Brightness, Tint, Advanced, Alpha), and the one colour transform every style
//! is (a multiply and an offset per channel).
//!
//! An element stores its [`ColorEffect`] as authored, so Properties shows the style and values
//! the artist chose (a tint keeps its colour at 0 %). Everything that draws works on its
//! [`ColorTransform`]: nested instances, the camera and onion skin compose their transforms
//! exactly (`concat` is the composition of the two maps), and every renderer applies the same
//! arithmetic to straight colour: `c ↦ clamp(c·multiply + offset, 0, 1)`.
//!
//! Brightness `b` is a tint towards white (`b > 0`) or black (`b < 0`) by `|b|`; a tint of
//! colour `t` by amount `k` multiplies each colour channel by `1 − k` and adds `k·t`; alpha
//! multiplies the alpha channel; Advanced is the transform itself (Animate's per-channel
//! percent and −255..255 offset, here as fractions: offset 1 is 255).
use crate::Rgba;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// A colour transform on straight (not premultiplied) colour: channel `i` (red, green, blue,
/// alpha) becomes `clamp(c·mul[i] + add[i], 0, 1)`. Offsets are fractions of the full range.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ColorTransform {
pub mul: [f32; 4],
pub add: [f32; 4],
}
impl Default for ColorTransform {
fn default() -> Self {
ColorTransform::IDENTITY
}
}
/// Animate's Advanced ranges: multipliers −100..=100 %, offsets −255..=255.
pub const ADVANCED_MUL: std::ops::RangeInclusive<f32> = -1.0..=1.0;
pub const ADVANCED_ADD: std::ops::RangeInclusive<f32> = -1.0..=1.0;
fn fin(v: f32, or: f32) -> f32 {
if v.is_finite() { v } else { or }
}
impl ColorTransform {
pub const IDENTITY: ColorTransform = ColorTransform { mul: [1.0; 4], add: [0.0; 4] };
/// Multiplies alpha by `a`.
pub fn alpha(a: f32) -> ColorTransform {
ColorTransform { mul: [1.0, 1.0, 1.0, a], add: [0.0; 4] }
}
/// Mixes colour `t` in by `k` (alpha untouched).
pub fn tint(t: Rgba, k: f32) -> ColorTransform {
let j = 1.0 - k;
ColorTransform { mul: [j, j, j, 1.0], add: [k * t.r, k * t.g, k * t.b, 0.0] }
}
/// Brightness `b` in −1..=1: a tint towards white or black by `|b|`.
pub fn brightness(b: f32) -> ColorTransform {
if b >= 0.0 { ColorTransform::tint(Rgba::WHITE, b) } else { ColorTransform::tint(Rgba::BLACK, -b) }
}
pub fn is_identity(&self) -> bool {
*self == ColorTransform::IDENTITY
}
/// `self` applied after `inner`: the effect of `inner` nested inside `self`. Exact (no clamp
/// between the two), so composing then applying is applying one then the other on colours
/// that stay in range.
pub fn concat(&self, inner: &ColorTransform) -> ColorTransform {
let mut out = ColorTransform::IDENTITY;
for i in 0..4 {
out.mul[i] = self.mul[i] * inner.mul[i];
out.add[i] = self.mul[i] * inner.add[i] + self.add[i];
}
out
}
pub fn lerp(&self, o: &ColorTransform, t: f32) -> ColorTransform {
let mut out = ColorTransform::IDENTITY;
for i in 0..4 {
out.mul[i] = anicraft_geom::lerp(self.mul[i], o.mul[i], t);
out.add[i] = anicraft_geom::lerp(self.add[i], o.add[i], t);
}
out
}
/// Non-finite values drawn as a channel of 0 (as a NaN colour always was).
pub fn sanitized(&self) -> ColorTransform {
let mut out = *self;
for i in 0..4 {
if !(out.mul[i].is_finite() && out.add[i].is_finite()) {
out.mul[i] = 0.0;
out.add[i] = 0.0;
}
}
out
}
/// The transform applied to straight colour `c`, clamped to `0..=1` (NaN to 0).
pub fn apply(&self, c: Rgba) -> Rgba {
let f = self.sanitized();
let ch = |v: f32, i: usize| {
let x = fin(v, 0.0) * f.mul[i] + f.add[i];
if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }
};
Rgba::new(ch(c.r, 0), ch(c.g, 1), ch(c.b, 2), ch(c.a, 3))
}
/// The alpha multiplier when alpha is only multiplied (no alpha offset): what can fade a
/// whole group at once.
pub fn alpha_factor(&self) -> Option<f32> {
(self.add[3] == 0.0).then(|| fin(self.mul[3], 0.0).clamp(0.0, 1.0))
}
/// The same transform with alpha untouched.
pub fn without_alpha(&self) -> ColorTransform {
let mut out = *self;
out.mul[3] = 1.0;
out.add[3] = 0.0;
out
}
/// Whether colour channels change (anything beyond alpha).
pub fn changes_colour(&self) -> bool {
self.mul[..3].iter().any(|m| *m != 1.0) || self.add[..3].iter().any(|a| *a != 0.0)
}
/// The alpha multiplier as an opacity estimate `0..=1` (picking, outlines).
pub fn opacity(&self) -> f32 {
fin(self.mul[3] + self.add[3], 0.0).clamp(0.0, 1.0)
}
}
/// The colour effect styles of Properties' Style menu, in menu order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorStyle {
None,
Brightness,
Tint,
Advanced,
Alpha,
}
impl ColorStyle {
pub const ALL: [ColorStyle; 5] = [ColorStyle::None, ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha];
/// The name used in files and commands.
pub fn key(self) -> &'static str {
match self {
ColorStyle::None => "none",
ColorStyle::Brightness => "brightness",
ColorStyle::Tint => "tint",
ColorStyle::Advanced => "advanced",
ColorStyle::Alpha => "alpha",
}
}
pub fn label(self) -> &'static str {
match self {
ColorStyle::None => "None",
ColorStyle::Brightness => "Brightness",
ColorStyle::Tint => "Tint",
ColorStyle::Advanced => "Advanced",
ColorStyle::Alpha => "Alpha",
}
}
pub fn from_key(s: &str) -> Option<ColorStyle> {
let s = s.trim().to_ascii_lowercase();
ColorStyle::ALL.into_iter().find(|x| x.key() == s)
}
}
/// An element's colour effect, as authored: one style and its values. Draw it through
/// [`ColorEffect::transform`].
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum ColorEffect {
#[default]
None,
/// Brightness −1..=1 (−100..=100 %).
Brightness(f32),
/// Tint colour (opaque) and amount 0..=1.
Tint { color: Rgba, amount: f32 },
/// Per-channel multiply and offset (Animate's Advanced).
Advanced(ColorTransform),
/// Alpha multiplier 0..=1.
Alpha(f32),
}
impl ColorEffect {
pub fn style(&self) -> ColorStyle {
match self {
ColorEffect::None => ColorStyle::None,
ColorEffect::Brightness(_) => ColorStyle::Brightness,
ColorEffect::Tint { .. } => ColorStyle::Tint,
ColorEffect::Advanced(_) => ColorStyle::Advanced,
ColorEffect::Alpha(_) => ColorStyle::Alpha,
}
}
/// What it does to colour (its values clamped into the style's range first).
pub fn transform(&self) -> ColorTransform {
match self.sanitized() {
ColorEffect::None => ColorTransform::IDENTITY,
ColorEffect::Brightness(b) => ColorTransform::brightness(b),
ColorEffect::Tint { color, amount } => ColorTransform::tint(color, amount),
ColorEffect::Advanced(t) => t,
ColorEffect::Alpha(a) => ColorTransform::alpha(a),
}
}
/// The values clamped into each style's range, non-finite ones to the style's rest value.
pub fn sanitized(&self) -> ColorEffect {
match *self {
ColorEffect::None => ColorEffect::None,
ColorEffect::Brightness(b) => ColorEffect::Brightness(fin(b, 0.0).clamp(-1.0, 1.0)),
ColorEffect::Tint { color, amount } => ColorEffect::Tint { color: color.sanitized().with_alpha(1.0), amount: fin(amount, 0.0).clamp(0.0, 1.0) },
ColorEffect::Advanced(t) => {
let mut o = t;
for i in 0..4 {
o.mul[i] = fin(t.mul[i], 1.0).clamp(*ADVANCED_MUL.start(), *ADVANCED_MUL.end());
o.add[i] = fin(t.add[i], 0.0).clamp(*ADVANCED_ADD.start(), *ADVANCED_ADD.end());
}
ColorEffect::Advanced(o)
}
ColorEffect::Alpha(a) => ColorEffect::Alpha(fin(a, 1.0).clamp(0.0, 1.0)),
}
}
/// The alpha multiplier the effect has (1 for styles that leave alpha alone).
pub fn alpha(&self) -> f32 {
self.transform().mul[3]
}
/// The effect with its alpha multiplier set to `a`, the rest kept (what ActionScript's
/// `alpha` and `element.set_alpha` do): None and Alpha become Alpha(a); Advanced keeps
/// its other channels; Brightness and Tint become Advanced when `a` isn't 1.
pub fn with_alpha(&self, a: f32) -> ColorEffect {
match *self {
ColorEffect::None | ColorEffect::Alpha(_) => ColorEffect::Alpha(a),
ColorEffect::Advanced(mut t) => {
t.mul[3] = a;
ColorEffect::Advanced(t)
}
ColorEffect::Brightness(_) | ColorEffect::Tint { .. } if a == 1.0 => *self,
ColorEffect::Brightness(_) | ColorEffect::Tint { .. } => {
let mut t = self.transform();
t.mul[3] = a;
ColorEffect::Advanced(t)
}
}
}
/// The effect in `style`, as close to this one as that style can be: Advanced is exactly
/// this transform; Alpha keeps the alpha multiplier; a tint keeps its colour; Brightness and
/// Tint otherwise start where they change nothing (the look doesn't jump when the style
/// changes, except to None).
pub fn to_style(&self, style: ColorStyle) -> ColorEffect {
if self.style() == style {
return *self;
}
match style {
ColorStyle::None => ColorEffect::None,
ColorStyle::Advanced => ColorEffect::Advanced(self.transform()),
ColorStyle::Alpha => ColorEffect::Alpha(fin(self.alpha(), 1.0).clamp(0.0, 1.0)),
ColorStyle::Brightness => ColorEffect::Brightness(0.0),
ColorStyle::Tint => ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 },
}
}
/// `inner` nested inside `self` as one effect (Break Apart): the other when either is None,
/// alphas multiplied, else the composed transform as Advanced.
pub fn nested(&self, inner: &ColorEffect) -> ColorEffect {
match (self, inner) {
(ColorEffect::None, x) | (x, ColorEffect::None) => *x,
(ColorEffect::Alpha(a), ColorEffect::Alpha(b)) => ColorEffect::Alpha(a * b),
(o, i) => ColorEffect::Advanced(o.transform().concat(&i.transform())),
}
}
/// Alpha `a`, or None at full opacity.
pub fn opacity(a: f32) -> ColorEffect {
if a < 1.0 { ColorEffect::Alpha(a) } else { ColorEffect::None }
}
/// The classic tween between two effects: within one style its values travel (a tint's
/// colour and amount); None meets any style as that style's rest value; any other change of
/// style travels in the Advanced space (multiplies and offsets), as in Animate.
pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect {
use anicraft_geom::lerp;
let rest = |s: ColorStyle| ColorEffect::None.to_style(s);
let (a, b) = match (self, o) {
(ColorEffect::None, ColorEffect::None) => return ColorEffect::None,
(ColorEffect::None, x) if x.style() != ColorStyle::Advanced => (rest(x.style()), *x),
(x, ColorEffect::None) if x.style() != ColorStyle::Advanced => (*x, rest(x.style())),
(x, y) => (*x, *y),
};
// A tint meeting None keeps its colour all the way.
let (a, b) = match (a, b) {
(ColorEffect::Tint { amount, .. }, ColorEffect::Tint { color, amount: k }) if self.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }),
(ColorEffect::Tint { color, amount }, ColorEffect::Tint { amount: k, .. }) if o.style() == ColorStyle::None => (ColorEffect::Tint { color, amount }, ColorEffect::Tint { color, amount: k }),
p => p,
};
match (a, b) {
(ColorEffect::Brightness(x), ColorEffect::Brightness(y)) => ColorEffect::Brightness(lerp(x, y, t)),
(ColorEffect::Alpha(x), ColorEffect::Alpha(y)) => ColorEffect::Alpha(lerp(x, y, t)),
(ColorEffect::Tint { color: c1, amount: k1 }, ColorEffect::Tint { color: c2, amount: k2 }) => ColorEffect::Tint { color: c1.lerp(c2, t), amount: lerp(k1, k2, t) },
(x, y) => ColorEffect::Advanced(x.transform().lerp(&y.transform(), t)),
}
}
/// The effect several families make together (a motion tween keying more than one, or an
/// older file's alpha with a tint): the one family when only one is in use, else Advanced
/// with them composed (alpha outermost, then brightness, tint, advanced).
pub fn compose(alpha: Option<f32>, brightness: Option<f32>, tint: Option<(Rgba, f32)>, advanced: Option<ColorTransform>) -> ColorEffect {
let n = usize::from(alpha.is_some()) + usize::from(brightness.is_some()) + usize::from(tint.is_some()) + usize::from(advanced.is_some());
if n == 1 {
if let Some(a) = alpha {
return ColorEffect::Alpha(a);
}
if let Some(b) = brightness {
return ColorEffect::Brightness(b);
}
if let Some((color, amount)) = tint {
return ColorEffect::Tint { color, amount };
}
if let Some(t) = advanced {
return ColorEffect::Advanced(t);
}
}
if n == 0 {
return ColorEffect::None;
}
let mut t = advanced.unwrap_or(ColorTransform::IDENTITY);
if let Some((c, k)) = tint {
t = ColorTransform::tint(c, k).concat(&t);
}
if let Some(b) = brightness {
t = ColorTransform::brightness(b).concat(&t);
}
if let Some(a) = alpha {
t = ColorTransform::alpha(a).concat(&t);
}
ColorEffect::Advanced(t)
}
}
// ----- files ---------------------------------------------------------------------------------
//
// Every effect is written with the fields older AniCraft files have (`alpha`, `tint`,
// `tint_amount`: the look as near as they can say it), so None, Alpha and Tint effects are
// written exactly as before. `style` (and `brightness`, `multiply`, `offset`) are added only
// when those fields alone would read back as something else. A file without `style` reads as
// it always looked: a tint, an alpha, both (Advanced), or none.
fn one() -> f32 {
1.0
}
fn white() -> Rgba {
Rgba::WHITE
}
#[derive(Serialize, Deserialize)]
struct Wire {
#[serde(default = "one")]
alpha: f32,
#[serde(default = "white")]
tint: Rgba,
#[serde(default)]
tint_amount: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
style: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
brightness: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
multiply: Option<[f32; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
offset: Option<[f32; 4]>,
}
/// What the legacy fields alone say.
fn legacy(alpha: f32, tint: Rgba, amount: f32) -> ColorEffect {
// Older builds clamped these where they drew them.
let (alpha, amount) = (fin(alpha, 1.0).clamp(0.0, 1.0), fin(amount, 0.0).clamp(0.0, 1.0));
let a = (alpha != 1.0).then_some(alpha);
let t = (amount != 0.0).then_some((tint, amount));
ColorEffect::compose(a, None, t, None)
}
impl Serialize for ColorEffect {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut w = Wire { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0, style: None, brightness: None, multiply: None, offset: None };
match *self {
ColorEffect::None => {}
ColorEffect::Alpha(a) => w.alpha = a,
ColorEffect::Tint { color, amount } => (w.tint, w.tint_amount) = (color, amount),
ColorEffect::Brightness(b) => {
(w.tint, w.tint_amount) = (if b >= 0.0 { Rgba::WHITE } else { Rgba::BLACK }, b.abs());
w.brightness = Some(b);
}
ColorEffect::Advanced(t) => {
w.alpha = t.mul[3];
(w.multiply, w.offset) = (Some(t.mul), Some(t.add));
}
}
if legacy(w.alpha, w.tint, w.tint_amount) != *self {
w.style = Some(self.style().key().to_string());
}
w.serialize(s)
}
}
impl<'de> Deserialize<'de> for ColorEffect {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let w = Wire::deserialize(d)?;
let fx = match w.style.as_deref().and_then(ColorStyle::from_key) {
None => legacy(w.alpha, w.tint, w.tint_amount),
Some(ColorStyle::None) => ColorEffect::None,
Some(ColorStyle::Alpha) => ColorEffect::Alpha(w.alpha),
Some(ColorStyle::Tint) => ColorEffect::Tint { color: w.tint, amount: w.tint_amount },
Some(ColorStyle::Brightness) => ColorEffect::Brightness(w.brightness.unwrap_or(0.0)),
Some(ColorStyle::Advanced) => ColorEffect::Advanced(ColorTransform { mul: w.multiply.unwrap_or([1.0; 4]), add: w.offset.unwrap_or([0.0; 4]) }),
};
Ok(fx.sanitized())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn close(a: Rgba, b: Rgba) -> bool {
(a.r - b.r).abs() < 1e-5 && (a.g - b.g).abs() < 1e-5 && (a.b - b.b).abs() < 1e-5 && (a.a - b.a).abs() < 1e-5
}
#[test]
fn styles_are_the_transforms_animate_documents() {
let c = Rgba::new(0.4, 0.2, 0.8, 1.0);
// Brightness +60 %: towards white; −50 %: towards black.
assert!(close(ColorEffect::Brightness(0.6).transform().apply(c), Rgba::new(0.4 * 0.4 + 0.6, 0.2 * 0.4 + 0.6, 0.8 * 0.4 + 0.6, 1.0)));
assert!(close(ColorEffect::Brightness(-0.5).transform().apply(c), Rgba::new(0.2, 0.1, 0.4, 1.0)));
// Tint 25 % red.
let t = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.25 }.transform().apply(c);
assert!(close(t, Rgba::new(0.4 * 0.75 + 0.25, 0.15, 0.6, 1.0)));
// Advanced: red ×50 %, green +51 (0.2), alpha ×80 % −25.5 (−0.1); clamped.
let adv = ColorTransform { mul: [0.5, 1.0, 1.0, 0.8], add: [0.0, 0.2, 0.5, -0.1] };
assert!(close(adv.apply(c), Rgba::new(0.2, 0.4, 1.0, 0.7)));
assert!(close(ColorEffect::Alpha(0.3).transform().apply(c), c.with_alpha(0.3)));
}
#[test]
fn composition_is_exact() {
let outer = ColorTransform::tint(Rgba::new(0.0, 0.5, 1.0, 1.0), 0.4);
let inner = ColorTransform { mul: [0.5, -0.2, 0.9, 0.7], add: [0.1, 0.6, 0.0, 0.05] };
let c = Rgba::new(0.3, 0.6, 0.2, 0.9);
assert!(close(outer.concat(&inner).apply(c), outer.apply(inner.apply(c))));
assert_eq!(ColorTransform::IDENTITY.concat(&inner), inner);
assert_eq!(inner.concat(&ColorTransform::IDENTITY), inner);
}
#[test]
fn nan_draws_a_zero_channel() {
let t = ColorTransform { mul: [f32::NAN, 1.0, 1.0, 1.0], add: [0.0; 4] };
assert_eq!(t.apply(Rgba::WHITE), Rgba::new(0.0, 1.0, 1.0, 1.0));
assert_eq!(ColorEffect::Tint { color: Rgba::WHITE, amount: f32::NAN }.sanitized(), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 });
}
#[test]
fn tweens_within_a_style_and_across_styles() {
let red = Rgba::new(1.0, 0.0, 0.0, 1.0);
let blue = Rgba::new(0.0, 0.0, 1.0, 1.0);
assert_eq!(ColorEffect::Alpha(1.0).lerp(&ColorEffect::Alpha(0.0), 0.25), ColorEffect::Alpha(0.75));
assert_eq!(ColorEffect::None.lerp(&ColorEffect::Brightness(-1.0), 0.5), ColorEffect::Brightness(-0.5));
assert_eq!(ColorEffect::None.lerp(&ColorEffect::Tint { color: red, amount: 1.0 }, 0.5), ColorEffect::Tint { color: red, amount: 0.5 });
assert_eq!(ColorEffect::Tint { color: red, amount: 1.0 }.lerp(&ColorEffect::Tint { color: blue, amount: 1.0 }, 0.5), ColorEffect::Tint { color: Rgba::new(0.5, 0.0, 0.5, 1.0), amount: 1.0 });
// A style change travels in the advanced space: halfway between the two transforms.
let a = ColorEffect::Tint { color: red, amount: 1.0 };
let b = ColorEffect::Alpha(0.5);
let mid = a.lerp(&b, 0.5);
assert_eq!(mid.style(), ColorStyle::Advanced);
assert_eq!(mid.transform(), a.transform().lerp(&b.transform(), 0.5));
// The ends look like the keyframes.
assert_eq!(a.lerp(&b, 0.0).transform(), a.transform());
assert_eq!(a.lerp(&b, 1.0).transform(), b.transform());
}
#[test]
fn style_changes_keep_the_look_where_they_can() {
let fx = ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.4 };
assert_eq!(fx.to_style(ColorStyle::Advanced).transform(), fx.transform());
assert_eq!(ColorEffect::Alpha(0.3).to_style(ColorStyle::Advanced).alpha(), 0.3);
assert_eq!(ColorEffect::Advanced(ColorTransform::alpha(0.3)).to_style(ColorStyle::Alpha), ColorEffect::Alpha(0.3));
assert!(fx.to_style(ColorStyle::Brightness).transform().is_identity());
assert_eq!(fx.with_alpha(0.5).transform(), ColorTransform::alpha(0.5).concat(&fx.transform()));
assert_eq!(fx.with_alpha(1.0), fx);
assert_eq!(ColorEffect::None.with_alpha(0.2), ColorEffect::Alpha(0.2));
}
#[test]
fn older_files_read_as_they_looked_and_simple_effects_write_as_before() {
let read = |s: &str| serde_json::from_str::<ColorEffect>(s).unwrap();
let white = r#""tint":{"r":1.0,"g":1.0,"b":1.0,"a":1.0}"#;
assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#)), ColorEffect::None);
assert_eq!(read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#)), ColorEffect::Alpha(0.5));
assert_eq!(read(&format!(r#"{{"alpha":1.0,{white},"tint_amount":0.25}}"#)), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.25 });
let both = read(&format!(r#"{{"alpha":0.5,{white},"tint_amount":0.25}}"#));
assert_eq!(both.transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::WHITE, 0.25)));
// Byte for byte as before.
assert_eq!(serde_json::to_string(&ColorEffect::None).unwrap(), format!(r#"{{"alpha":1.0,{white},"tint_amount":0.0}}"#));
assert_eq!(serde_json::to_string(&ColorEffect::Alpha(0.5)).unwrap(), format!(r#"{{"alpha":0.5,{white},"tint_amount":0.0}}"#));
for fx in [
ColorEffect::None,
ColorEffect::Alpha(1.0),
ColorEffect::Alpha(0.25),
ColorEffect::Brightness(-0.5),
ColorEffect::Brightness(0.0),
ColorEffect::Tint { color: Rgba::new(1.0, 0.0, 0.0, 1.0), amount: 0.0 },
ColorEffect::Tint { color: Rgba::new(0.0, 0.5, 1.0, 1.0), amount: 0.75 },
ColorEffect::Advanced(ColorTransform { mul: [0.5, -1.0, 1.0, 0.75], add: [0.25, 0.0, -0.5, 0.125] }),
ColorEffect::Advanced(ColorTransform::IDENTITY),
] {
let json = serde_json::to_string(&fx).unwrap();
assert_eq!(read(&json), fx, "{json}");
}
// Brightness still reads, in older builds, as the tint it looks like.
let json = serde_json::to_string(&ColorEffect::Brightness(-0.5)).unwrap();
assert!(json.contains(r#""tint_amount":0.5"#) && json.contains(r#""style":"brightness""#), "{json}");
// Out-of-range values in a file are clamped; an unknown style reads as the legacy fields.
assert_eq!(read(r#"{"style":"brightness","brightness":7}"#), ColorEffect::Brightness(1.0));
assert_eq!(read(r#"{"style":"sepia","alpha":0.5}"#), ColorEffect::Alpha(0.5));
}
}
+14 -9
View File
@@ -3,7 +3,7 @@
use crate::camera::Camera;
use crate::nine_slice::Slicing;
use crate::player::PlayerState;
use crate::{ColorEffect, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
use anicraft_geom::walk::PathWalk;
use anicraft_geom::{Affine, FillRule, Path};
use std::borrow::Cow;
@@ -21,7 +21,8 @@ pub struct DisplayItem {
pub fill: Option<Paint>,
pub stroke: Option<Stroke>,
pub fill_rule: FillRule,
pub color: ColorEffect,
/// The colour transform of every instance around it, composed (ADR 0056).
pub color: ColorTransform,
/// The top-level layer and element this item came from (for picking).
pub layer: LayerId,
pub element: ElementId,
@@ -33,7 +34,7 @@ pub struct DisplayItem {
pub masks: Option<u32>,
/// Guide artwork: shown while editing, never in output.
pub guide: bool,
/// The innermost group this item fades with (see [`DisplayList::groups`]); `color.alpha`
/// The innermost group this item fades with (see [`DisplayList::groups`]); `color`
/// leaves out the groups' opacity.
pub group: Option<u32>,
/// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied).
@@ -74,7 +75,7 @@ impl DisplayList {
/// The opacity an item ends up with: its own times every group's it is in (what an item
/// looks like when nothing overlaps it; also what picking and outlines use).
pub fn effective_alpha(&self, item: &DisplayItem) -> f32 {
let mut a = item.color.alpha;
let mut a = item.color.opacity();
let mut g = item.group;
for _ in 0..self.groups.len() {
let Some(id) = g else { break };
@@ -294,7 +295,7 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft
struct Ctx {
/// Local → stage transform and colour effect of the enclosing instance.
xf: Affine,
color: ColorEffect,
color: ColorTransform,
depth: usize,
/// The top-level layer and element everything inside belongs to (for picking).
root: Option<(LayerId, ElementId)>,
@@ -317,7 +318,7 @@ struct Ctx {
impl Ctx {
fn top(xf: Affine) -> Ctx {
Ctx { xf, color: ColorEffect::default(), depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None, slice: None }
Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None, slice: None }
}
/// A main timeline seen through `camera`: its tint colours everything.
@@ -437,7 +438,8 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
};
let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id));
let xf = layer_xf.mul(&el.transform);
let color = cx.color.concat(&el.color);
let fx = el.color.transform();
let color = cx.color.concat(&fx);
match &el.kind {
ElementKind::Shape(s) => {
// Inside a 9-slice instance, the shape's outline is cut and mapped (bitmap
@@ -508,11 +510,14 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
// group at full opacity, and the group blends at the instance's alpha. (Mask
// artwork ignores opacity, so it never needs one.)
// A blend mode composites the instance on its own too, then blends it.
let fade = el.color.alpha.clamp(0.0, 1.0);
// An alpha offset (Advanced) changes each item's alpha on its own: it stays
// in the items' transform, and the group (for a blend or filters) is opaque.
let fade = fx.alpha_factor().unwrap_or(1.0);
let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || !filters.is_empty()) {
let gid = out.groups.len() as u32;
out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: filters.iter().map(crate::Filter::sanitized).collect(), clip });
(cx.color.concat(&ColorEffect { alpha: 1.0, ..el.color }), Some(gid))
let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx };
(cx.color.concat(&inner), Some(gid))
} else {
(color, cx.group)
};
+4 -4
View File
@@ -1,5 +1,5 @@
use super::*;
use crate::{Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind};
use crate::{ColorEffect, Easing, Keyframe, Symbol, SymbolId, SymbolKind, Tween, TweenKind};
fn shape_el(id: u64, x: f32) -> Element {
Element {
@@ -93,7 +93,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() {
id: ElementId(60),
name: String::new(),
transform: Affine::translate(100.0, 0.0),
color: ColorEffect { alpha: 0.5, ..Default::default() },
color: ColorEffect::Alpha(0.5),
kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() },
},
);
@@ -101,7 +101,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() {
assert_eq!(dl.items.len(), MAX_SYMBOL_DEPTH);
assert_eq!(dl.items[0].transform.translation().x, 100.0);
// The instance's opacity is its group's: it fades as one.
assert_eq!((dl.items[0].color.alpha, dl.effective_alpha(&dl.items[0])), (1.0, 0.5));
assert_eq!((dl.items[0].color.mul[3], dl.effective_alpha(&dl.items[0])), (1.0, 0.5));
assert_eq!(dl.groups.len(), 1);
assert!(dl.items.iter().all(|i| i.element == ElementId(60)));
}
@@ -352,7 +352,7 @@ fn a_motion_tween_drives_each_property_on_its_own_curve() {
let d = motion_doc();
let at = |f| {
let dl = evaluate(&d, f);
(dl.items[0].transform.translation().x, dl.items[0].color.alpha)
(dl.items[0].transform.translation().x, dl.items[0].color.mul[3])
};
assert_eq!(at(0), (0.0, 1.0));
// X eases in over 0..12 (a quarter of the way at half time); alpha runs linearly over 0..23.
+3 -39
View File
@@ -9,6 +9,7 @@ pub use anicraft_actions as actions;
pub mod armature;
mod bitmap;
mod color_effect;
pub mod camera;
mod filter;
mod easing;
@@ -27,9 +28,10 @@ pub mod sound;
pub use filter::{Filter, FilterSide, 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_encode, decode_png, image_to_png};
pub use easing::Easing;
pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform};
pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre};
pub use library::{FolderId, LibraryEntry, LibraryFolder, LibraryItem, LibraryTree, NameError};
pub use motion::{MotionTween, OnPath, Pin, PinError, Property, PropertyKey, Props, Track, motion_path};
pub use motion::{MotionTween, OnPath, PROPERTIES, Pin, PinError, Property, PropertyKey, Props, Track, motion_path};
pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync};
pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile};
pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle};
@@ -465,44 +467,6 @@ pub struct TextBlock {
pub box_height: f32,
}
/// Colour effect applied to an element and everything inside it.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ColorEffect {
/// Alpha multiplier `0..=1`.
pub alpha: f32,
/// Tint colour mixed in by `tint_amount`.
pub tint: Rgba,
pub tint_amount: f32,
}
impl Default for ColorEffect {
fn default() -> Self {
ColorEffect { alpha: 1.0, tint: Rgba::WHITE, tint_amount: 0.0 }
}
}
impl ColorEffect {
/// Effect of `inner` nested inside `self`.
pub fn concat(&self, inner: &ColorEffect) -> ColorEffect {
// Tints compose by keeping the stronger one; alpha multiplies.
let (tint, amount) = if inner.tint_amount >= self.tint_amount { (inner.tint, inner.tint_amount) } else { (self.tint, self.tint_amount) };
ColorEffect { alpha: self.alpha * inner.alpha, tint, tint_amount: amount }
}
pub fn lerp(&self, o: &ColorEffect, t: f32) -> ColorEffect {
ColorEffect {
alpha: anicraft_geom::lerp(self.alpha, o.alpha, t),
tint: self.tint.lerp(o.tint, t),
tint_amount: anicraft_geom::lerp(self.tint_amount, o.tint_amount, t),
}
}
pub fn apply(&self, c: Rgba) -> Rgba {
let k = self.tint_amount.clamp(0.0, 1.0);
let mut out = c.lerp(self.tint.with_alpha(c.a), k);
out.a = c.a * self.alpha.clamp(0.0, 1.0);
out
}
}
/// An instance on a keyframe.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Element {
+170 -20
View File
@@ -2,7 +2,7 @@
//!
//! A classic tween interpolates a whole keyframe into the next one. A motion tween instead
//! belongs to one keyframe span and one object in it (its *target*). Each property (x, y,
//! scale, rotation, skew, alpha, tint) may have a [`Track`] of property keyframes anywhere in
//! scale, rotation, skew, and the colour effect's alpha, brightness, tint and advanced values) may have a [`Track`] of property keyframes anywhere in
//! the span; between two keys the value follows the segment's [`Easing`], which may be a custom
//! cubic Bézier. A property without a track keeps the target's own value (its *base*: how it
//! looks on the span's first frame). Evaluation is pure: [`MotionTween::apply`] maps the base
@@ -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::{Element, ElementId, Easing};
use crate::{ColorEffect, ColorStyle, ColorTransform, Element, ElementId, Easing, Rgba};
use anicraft_geom::edit::ANCHOR;
use anicraft_geom::walk::CurveWalk;
use anicraft_geom::{Affine, Decomposed, Path, PathCmd, Vec2};
@@ -35,7 +35,7 @@ pub const MAX_KEYS: usize = 10_000;
pub const MAX_PATH_SEGMENTS: usize = 1_000;
/// A property a motion tween animates. Values are in the units the Motion Editor shows:
/// pixels, percent and degrees.
/// pixels, percent, degrees, and 0–255 for colour channels and offsets (as Animate shows them).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Property {
@@ -49,13 +49,64 @@ pub enum Property {
Rotation,
/// Degrees of horizontal skew, within ±89.
Skew,
/// Colour effect: opacity and tint amount, percent.
/// Colour effect (ADR 0056), by style. Alpha: opacity, percent.
Alpha,
/// Brightness, −100..=100 %.
Brightness,
/// Tint amount, percent, and the tint colour's channels, 0–255.
Tint,
TintRed,
TintGreen,
TintBlue,
/// Advanced: each channel's multiplier, −100..=100 %, and offset, −255..=255.
RedMultiplier,
GreenMultiplier,
BlueMultiplier,
AlphaMultiplier,
RedOffset,
GreenOffset,
BlueOffset,
AlphaOffset,
}
/// How many properties there are.
pub const PROPERTIES: usize = 20;
impl Property {
pub const ALL: [Property; 8] = [Property::X, Property::Y, Property::ScaleX, Property::ScaleY, Property::Rotation, Property::Skew, Property::Alpha, Property::Tint];
pub const ALL: [Property; PROPERTIES] = [
Property::X,
Property::Y,
Property::ScaleX,
Property::ScaleY,
Property::Rotation,
Property::Skew,
Property::Alpha,
Property::Brightness,
Property::Tint,
Property::TintRed,
Property::TintGreen,
Property::TintBlue,
Property::RedMultiplier,
Property::GreenMultiplier,
Property::BlueMultiplier,
Property::AlphaMultiplier,
Property::RedOffset,
Property::GreenOffset,
Property::BlueOffset,
Property::AlphaOffset,
];
/// The Advanced properties: multipliers then offsets, red first.
pub const ADVANCED: [Property; 8] = [
Property::RedMultiplier,
Property::GreenMultiplier,
Property::BlueMultiplier,
Property::AlphaMultiplier,
Property::RedOffset,
Property::GreenOffset,
Property::BlueOffset,
Property::AlphaOffset,
];
/// The name used in files and commands (`x`, `scale_x`, `alpha`…).
pub fn key(self) -> &'static str {
@@ -67,7 +118,19 @@ impl Property {
Property::Rotation => "rotation",
Property::Skew => "skew",
Property::Alpha => "alpha",
Property::Brightness => "brightness",
Property::Tint => "tint",
Property::TintRed => "tint_red",
Property::TintGreen => "tint_green",
Property::TintBlue => "tint_blue",
Property::RedMultiplier => "red_multiplier",
Property::GreenMultiplier => "green_multiplier",
Property::BlueMultiplier => "blue_multiplier",
Property::AlphaMultiplier => "alpha_multiplier",
Property::RedOffset => "red_offset",
Property::GreenOffset => "green_offset",
Property::BlueOffset => "blue_offset",
Property::AlphaOffset => "alpha_offset",
}
}
@@ -80,24 +143,49 @@ impl Property {
Property::Rotation => "Rotation",
Property::Skew => "Skew",
Property::Alpha => "Alpha",
Property::Brightness => "Brightness",
Property::Tint => "Tint",
Property::TintRed => "Tint red",
Property::TintGreen => "Tint green",
Property::TintBlue => "Tint blue",
Property::RedMultiplier => "Red multiplier",
Property::GreenMultiplier => "Green multiplier",
Property::BlueMultiplier => "Blue multiplier",
Property::AlphaMultiplier => "Alpha multiplier",
Property::RedOffset => "Red offset",
Property::GreenOffset => "Green offset",
Property::BlueOffset => "Blue offset",
Property::AlphaOffset => "Alpha offset",
}
}
pub fn unit(self) -> &'static str {
match self {
Property::X | Property::Y => "px",
Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Tint => "%",
Property::ScaleX | Property::ScaleY | Property::Alpha | Property::Brightness | Property::Tint => "%",
Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => "%",
Property::Rotation | Property::Skew => "°",
Property::TintRed | Property::TintGreen | Property::TintBlue | Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => "",
}
}
/// The Motion Editor's groups: Position, Transform, Colour effect.
pub fn group(self) -> &'static str {
match self.style() {
None if matches!(self, Property::X | Property::Y) => "Position",
None => "Transform",
Some(_) => "Colour effect",
}
}
/// The colour effect style a colour property belongs to (`None` for position and transform).
pub fn style(self) -> Option<ColorStyle> {
match self {
Property::X | Property::Y => "Position",
Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => "Transform",
Property::Alpha | Property::Tint => "Colour effect",
Property::X | Property::Y | Property::ScaleX | Property::ScaleY | Property::Rotation | Property::Skew => None,
Property::Alpha => Some(ColorStyle::Alpha),
Property::Brightness => Some(ColorStyle::Brightness),
Property::Tint | Property::TintRed | Property::TintGreen | Property::TintBlue => Some(ColorStyle::Tint),
Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier | Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => Some(ColorStyle::Advanced),
}
}
@@ -108,6 +196,7 @@ impl Property {
"scaley" => "scale_y",
"rotate" => "rotation",
"opacity" => "alpha",
"tint_amount" => "tint",
other => other,
};
Property::ALL.into_iter().find(|p| p.key() == s)
@@ -121,6 +210,9 @@ impl Property {
Property::Rotation => -100_000.0..=100_000.0,
Property::Skew => -89.0..=89.0,
Property::Alpha | Property::Tint => 0.0..=100.0,
Property::Brightness | Property::RedMultiplier | Property::GreenMultiplier | Property::BlueMultiplier | Property::AlphaMultiplier => -100.0..=100.0,
Property::TintRed | Property::TintGreen | Property::TintBlue => 0.0..=255.0,
Property::RedOffset | Property::GreenOffset | Property::BlueOffset | Property::AlphaOffset => -255.0..=255.0,
}
}
@@ -129,7 +221,7 @@ impl Property {
}
fn is_transform(self) -> bool {
!matches!(self, Property::Alpha | Property::Tint)
self.style().is_none()
}
fn clamp(self, v: f32) -> f32 {
@@ -140,13 +232,57 @@ impl Property {
/// Every property's value, indexed like [`Property::ALL`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Props(pub [f32; 8]);
pub struct Props(pub [f32; PROPERTIES]);
impl Props {
/// An element's own values.
/// An element's own values. Colour properties come from its colour effect's style; the
/// other styles' properties hold their rest values (alpha 100 %, brightness 0, tint 0 % of
/// white, Advanced 100 % and 0).
pub fn of(el: &Element) -> Props {
let d = el.transform.decompose();
Props([d.tx, d.ty, d.sx * 100.0, d.sy * 100.0, d.rotation.to_degrees(), d.skew.atan().to_degrees(), el.color.alpha * 100.0, el.color.tint_amount * 100.0])
let mut p = Props([0.0; PROPERTIES]);
for (q, v) in [(Property::X, d.tx), (Property::Y, d.ty), (Property::ScaleX, d.sx * 100.0), (Property::ScaleY, d.sy * 100.0), (Property::Rotation, d.rotation.to_degrees()), (Property::Skew, d.skew.atan().to_degrees())] {
p.set(q, v);
}
p.set_colour(&el.color);
p
}
/// Sets the colour properties from `fx`, as [`Props::of`] does.
fn set_colour(&mut self, fx: &ColorEffect) {
let (mut alpha, mut bright, mut tint, mut rgb, mut adv) = (1.0, 0.0, 0.0, Rgba::WHITE, ColorTransform::IDENTITY);
match *fx {
ColorEffect::None => {}
ColorEffect::Alpha(a) => alpha = a,
ColorEffect::Brightness(b) => bright = b,
ColorEffect::Tint { color, amount } => (tint, rgb) = (amount, color),
ColorEffect::Advanced(t) => adv = t,
}
self.set(Property::Alpha, alpha * 100.0);
self.set(Property::Brightness, bright * 100.0);
self.set(Property::Tint, tint * 100.0);
self.set(Property::TintRed, rgb.r * 255.0);
self.set(Property::TintGreen, rgb.g * 255.0);
self.set(Property::TintBlue, rgb.b * 255.0);
let values = adv.mul.iter().map(|m| m * 100.0).chain(adv.add.iter().map(|a| a * 255.0));
for (q, v) in Property::ADVANCED.into_iter().zip(values) {
self.set(q, v);
}
}
/// The colour effect of the styles in `styles` from these values (the other styles' values
/// are left out): one style alone is that style; several compose into Advanced (ADR 0056).
pub fn color_effect(&self, styles: &[ColorStyle]) -> ColorEffect {
let v = |p: Property| p.clamp(self.get(p));
let on = |s: ColorStyle| styles.contains(&s);
let alpha = on(ColorStyle::Alpha).then(|| v(Property::Alpha) / 100.0);
let bright = on(ColorStyle::Brightness).then(|| v(Property::Brightness) / 100.0);
let tint = on(ColorStyle::Tint).then(|| (Rgba::new(v(Property::TintRed) / 255.0, v(Property::TintGreen) / 255.0, v(Property::TintBlue) / 255.0, 1.0), v(Property::Tint) / 100.0));
let adv = on(ColorStyle::Advanced).then(|| {
let [rm, gm, bm, am, ro, go, bo, ao] = Property::ADVANCED.map(v);
ColorTransform { mul: [rm, gm, bm, am].map(|m| m / 100.0), add: [ro, go, bo, ao].map(|a| a / 255.0) }
});
ColorEffect::compose(alpha, bright, tint, adv).sanitized()
}
pub fn get(&self, p: Property) -> f32 {
self.0.get(p.index()).copied().unwrap_or(0.0)
@@ -891,15 +1027,29 @@ impl MotionTween {
el.transform = m;
}
}
if let Some(t) = self.track(Property::Alpha).and_then(|t| t.value_at(frame)) {
el.color.alpha = (t / 100.0).clamp(0.0, 1.0);
}
if let Some(t) = self.track(Property::Tint).and_then(|t| t.value_at(frame)) {
el.color.tint_amount = (t / 100.0).clamp(0.0, 1.0);
// Colour: the styles keyed here and the target's own, composed (ADR 0056).
if self.tracks.iter().any(|t| !t.property.is_transform()) {
el.color = props.color_effect(&self.colour_styles(&base.color));
}
el
}
/// The colour effect styles the target shows over the span. As in Animate, a motion tween
/// has one colour effect: the style its colour properties are keyed in, replacing the
/// target's own (which shows while none are keyed). Keys in several styles (older files
/// keyed alpha and tint together) compose into Advanced.
pub fn colour_styles(&self, own: &ColorEffect) -> Vec<ColorStyle> {
let mut out: Vec<ColorStyle> = Vec::new();
let keyed = self.tracks.iter().filter_map(|t| t.property.style());
let own = (own.style() != ColorStyle::None && !self.tracks.iter().any(|t| t.property.style().is_some())).then_some(own.style());
for s in keyed.chain(own) {
if !out.contains(&s) {
out.push(s);
}
}
out
}
/// Sets property `p`'s key at `frame`. A property's first key also gets a key on the span's
/// first frame holding `base` (its value until now), so the rest of the span is unchanged.
pub fn set_key(&mut self, p: Property, frame: u32, value: f32, base: f32) {
@@ -1083,7 +1233,7 @@ mod tests {
m.set_key(Property::Alpha, 10, 0.0, 100.0);
let at5 = m.apply(&base, 5.0);
assert_eq!(at5.transform, base.transform, "colour-only tween keeps the transform bit for bit");
assert!((at5.color.alpha - 0.5).abs() < 1e-6);
assert!((at5.color.alpha() - 0.5).abs() < 1e-6 && at5.color.style() == ColorStyle::Alpha);
}
#[test]
@@ -1167,7 +1317,7 @@ mod tests {
fn property_keys_round_trip() {
for p in Property::ALL {
assert_eq!(Property::from_key(p.key()), Some(p));
assert!(!p.label().is_empty() && !p.unit().is_empty() && !p.group().is_empty());
assert!(!p.label().is_empty() && (!p.unit().is_empty() || p.range() == (0.0..=255.0) || p.range() == (-255.0..=255.0)) && !p.group().is_empty());
}
assert_eq!(Property::from_key("Scale X"), Some(Property::ScaleX));
assert_eq!(Property::from_key("nope"), None);
+2 -2
View File
@@ -111,7 +111,7 @@ impl Overrides {
}
}
if let Some(a) = self.alpha {
e.color.alpha = a;
e.color = e.color.with_alpha(a);
}
e
}
@@ -435,7 +435,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi
};
let idx = out.len();
let node_xf = layer_xf.mul(&e.transform);
out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, local: el.transform, alpha: el.color.alpha, hittable: hit && shown, events: events.clone(), gain });
out.push(Node { path, parent: Some(parent), owner, name: e.name.clone(), symbol: Some(*symbol), kind, frame: local, frames: len, xf: node_xf, local: el.transform, alpha: el.color.alpha(), hittable: hit && shown, events: events.clone(), gain });
// Names inside a movie clip (or a button's states) are its own; a graphic's
// contents belong to the timeline the graphic is on.
let inner_owner = if kind == NodeKind::Graphic { owner } else { idx };
+1 -1
View File
@@ -528,7 +528,7 @@ fn scripts_read_instance_and_timeline_properties() {
let clip = symbol(100, SymbolKind::MovieClip, vec![layer(11, vec![kf(0, 3, vec![rect(12, 0.0, 0.0, 5.0, 5.0)], vec![], "walk")])]);
let mut hero = (*inst(3, 100, "hero", 30.0, 40.0, vec![])).clone();
hero.transform = Affine::translate(30.25, 40.0).mul(&Affine::scale(2.0, 0.5));
hero.color.alpha = 0.3;
hero.color = crate::ColorEffect::Alpha(0.3);
let src = "stop();\ntrace(hero.x, hero.y, hero.scaleX, hero.scaleY, hero.rotation, hero.alpha, hero.visible, hero.name);\ntrace(hero.currentFrame, hero.totalFrames, hero.currentLabel, currentFrame, totalFrames, currentLabel, this.name);\nhero.x = 0.1; hero.alpha = hero.alpha + 0.2; hero.visible = false;\ntrace(hero.x, hero.alpha, hero.visible);\nstage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void { trace(mouseX, mouseY, hero.mouseX, stage.mouseY); });";
let k = as3(kf(0, 2, vec![], vec![], "intro"), src);
let mut hk = Keyframe::new(0, 2);
+1 -1
View File
@@ -167,7 +167,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
let lim = 1_000_000.0;
c.center = Vec2::new(c.center.x.clamp(-lim, lim), c.center.y.clamp(-lim, lim));
el.transform = c.transform();
el.color = c.color();
el.color = c.to_element(el.id).color;
Ok(c)
})();
s.layer = layer;
+80 -4
View File
@@ -2,7 +2,7 @@
use crate::params::*;
use crate::{CommandSpec, EngineError, Result, Selection, Session};
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, ScaleGrid, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline};
use anicraft_doc::{ColorEffect, ColorStyle, Element, ElementId, ElementKind, Layer, LayerId, LibraryEntry, LibraryItem, LoopMode, Paint, ScaleGrid, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline};
use anicraft_geom::{Affine, Decomposed, Path, Vec2};
use serde_json::{Value, json};
use std::sync::Arc;
@@ -29,7 +29,8 @@ pub fn specs() -> Vec<CommandSpec> {
c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))),
c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))),
c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))),
c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))),
c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))),
c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera's effect is a tint", true, |s, p| s.each_layer(true, |s| set_color_effect(s, p))),
c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))),
c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))),
c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))),
@@ -410,11 +411,86 @@ fn set_alpha(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Param("param 'alpha' must be between 0 and 1".into()));
}
for e in s.selected_elements_mut()? {
e.color.alpha = a;
e.color = e.color.with_alpha(a);
}
Ok(json!({"alpha": a}))
}
/// Each colour effect value `element.set_color_effect` takes: its key, style, range and scale
/// (the model's value is the param's divided by it).
const EFFECT_VALUES: [(&str, ColorStyle, f32, f32, f32); 11] = [
("alpha", ColorStyle::Alpha, 0.0, 100.0, 100.0),
("brightness", ColorStyle::Brightness, -100.0, 100.0, 100.0),
("tint_amount", ColorStyle::Tint, 0.0, 100.0, 100.0),
("red_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0),
("green_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0),
("blue_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0),
("alpha_multiplier", ColorStyle::Advanced, -100.0, 100.0, 100.0),
("red_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0),
("green_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0),
("blue_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0),
("alpha_offset", ColorStyle::Advanced, -255.0, 255.0, 255.0),
];
fn set_color_effect(s: &mut Session, p: &Value) -> Result<Value> {
let style = match opt_str(p, "style")? {
Some(k) => Some(ColorStyle::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown style '{k}' (none, brightness, tint, advanced or alpha)")))?),
None => None,
};
let tint = opt_color(p, "tint")?;
let mut values: Vec<(usize, f32)> = Vec::new();
let mut families: Vec<ColorStyle> = tint.map(|_| ColorStyle::Tint).into_iter().collect();
for (i, (key, fam, lo, hi, scale)) in EFFECT_VALUES.iter().enumerate() {
if let Some(v) = opt_f32(p, key)? {
if !(*lo..=*hi).contains(&v) {
return Err(EngineError::Param(format!("param '{key}' must be between {lo} and {hi}")));
}
values.push((i, v / scale));
if !families.contains(fam) {
families.push(*fam);
}
}
}
let style = match (style, families.as_slice()) {
(Some(st), f) if f.iter().any(|x| *x != st) => return Err(EngineError::Param(format!("the {} style has none of these values: give only its own", st.key()))),
(Some(st), _) => Some(st),
(None, []) => return Err(EngineError::Param("give a style, or a value to set".into())),
(None, [one]) => Some(*one),
(None, _) => return Err(EngineError::Param("these values belong to different styles: give one style's values".into())),
};
let mut first = None;
for e in s.selected_elements_mut()? {
let target = style.unwrap_or(e.color.style());
if matches!(e.kind, ElementKind::Camera) && !matches!(target, ColorStyle::Tint | ColorStyle::None) {
return Err(EngineError::State("the camera's colour effect is a tint".into()));
}
let mut fx = e.color.to_style(target);
if let ColorEffect::Tint { color, .. } = &mut fx
&& let Some(t) = tint
{
*color = t.with_alpha(1.0);
}
for &(i, v) in &values {
match &mut fx {
ColorEffect::Alpha(a) if i == 0 => *a = v,
ColorEffect::Brightness(b) if i == 1 => *b = v,
ColorEffect::Tint { amount, .. } if i == 2 => *amount = v,
ColorEffect::Advanced(t) => {
if let Some(m) = i.checked_sub(3).and_then(|j| t.mul.get_mut(j)) {
*m = v;
} else if let Some(o) = i.checked_sub(7).and_then(|j| t.add.get_mut(j)) {
*o = v;
}
}
_ => {}
}
}
e.color = fx.sanitized();
first.get_or_insert(e.color);
}
Ok(first.map_or(Value::Null, |fx| crate::color_effect_json(&fx)))
}
/// Most filters on one instance.
const MAX_FILTERS: usize = 16;
@@ -814,7 +890,7 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
let mut c = (**child).clone();
c.id = ElementId(s.doc.alloc_id());
c.transform = e.transform.mul(&child.transform);
c.color = e.color.concat(&child.color);
c.color = e.color.nested(&child.color);
fresh_ids.push(c.id);
out.push(Arc::new(c));
}
+1 -1
View File
@@ -270,7 +270,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result<Value> {
list.into_iter()
.map(|e| {
let id = anicraft_doc::ElementId(s.doc.alloc_id());
Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect { alpha: e.alpha, ..Default::default() }, kind: e.kind })
Arc::new(anicraft_doc::Element { id, name: e.name, transform: place.mul(&e.transform), color: anicraft_doc::ColorEffect::opacity(e.alpha), kind: e.kind })
})
.collect()
};
+8 -7
View File
@@ -15,7 +15,7 @@
use crate::cmds_timeline::target;
use crate::params::*;
use crate::{CommandSpec, EngineError, Result, Session};
use anicraft_doc::{ColorEffect, Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props};
use anicraft_doc::{Element, ElementId, Keyframe, Layer, LayerId, LayerKind, MotionTween, Pin, PinError, Property, Props};
use anicraft_geom::{Affine, Vec2};
use serde_json::{Value, json};
use std::sync::Arc;
@@ -23,7 +23,7 @@ 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|tint, value (px, %, °), frame?, layer?}", true, set_key as crate::RunFn),
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), 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, property? (default: every property), frame? (inside the segment), layer?}", 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),
@@ -111,7 +111,7 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) {
let v = was.get(p) + d;
if e.offset == 0 && m.track(p).is_none() {
new_base.set(p, v);
if matches!(p, Property::Alpha | Property::Tint) {
if p.style().is_some() {
base_color = true;
} else {
base_xf = true;
@@ -120,8 +120,8 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) {
m.set_key(p, e.offset, v, base_props.get(p));
}
}
let tracks_xf = m.tracks.iter().any(|t| !matches!(t.property, Property::Alpha | Property::Tint));
let tracks_color = m.tracks.iter().any(|t| matches!(t.property, Property::Alpha | Property::Tint));
let tracks_xf = m.tracks.iter().any(|t| t.property.style().is_none());
let tracks_color = m.tracks.iter().any(|t| t.property.style().is_some());
let mut base = after;
// Exact where nothing is keyed on the first frame: the edited object is the new base.
base.transform = match (base_xf, e.offset == 0 && !tracks_xf) {
@@ -131,8 +131,9 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) {
};
base.color = match (base_color, e.offset == 0 && !tracks_color) {
(true, true) => base.color,
(true, false) => ColorEffect { alpha: (new_base.get(Property::Alpha) / 100.0).clamp(0.0, 1.0), tint: base.color.tint, tint_amount: (new_base.get(Property::Tint) / 100.0).clamp(0.0, 1.0) },
(false, _) => ColorEffect { tint: base.color.tint, ..e.base.color },
// The edit's style, from the new values (ADR 0056).
(true, false) => new_base.color_effect(&[base.color.style()]),
(false, _) => e.base.color,
};
if let Some(slot) = kf.elements.get_mut(idx) {
*slot = Arc::new(base);
+2 -1
View File
@@ -126,7 +126,8 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result<Value, String>
"selected": s.selection.contains(s.layer, e.id),
"transform": e.transform.m,
"bounds": if b.is_empty() { Value::Null } else { json!([b.min.x, b.min.y, b.max.x - b.min.x, b.max.y - b.min.y]) },
"alpha": e.color.alpha,
"alpha": e.color.alpha(),
"color_effect": crate::color_effect_json(&e.color),
});
match &e.kind {
ElementKind::Shape(sh) => {
+1 -1
View File
@@ -353,7 +353,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
// A motion tween split in two keeps moving the same way in both halves.
let motion = if copy {
k.motion.as_ref().map(|m| {
let base = m.target_index(&k.elements).and_then(|t| k.elements.get(t)).map_or(anicraft_doc::Props([0.0; 8]), |e| anicraft_doc::Props::of(e));
let base = m.target_index(&k.elements).and_then(|t| k.elements.get(t)).map_or(anicraft_doc::Props([0.0; anicraft_doc::PROPERTIES]), |e| anicraft_doc::Props::of(e));
m.split_at(&base, frame - k.start)
})
} else {
+259
View File
@@ -0,0 +1,259 @@
//! Colour effects through the command registry (ADR 0056): every style, switching styles,
//! values on a mixed selection, classic and motion tweens, undo, the file round trip and the
//! renders they give.
use super::*;
use anicraft_doc::{ColorEffect, ColorStyle, ColorTransform, 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}"),
}
}
/// A white 20 × 20 square at the origin, selected.
fn square() -> Session {
let mut s = Session::default();
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "fill": "#336699", "stroke": null}));
run(&mut s, "edit.select_all", json!({}));
s
}
fn effect(s: &Session) -> ColorEffect {
s.visible_elements().first().map(|e| e.color).unwrap_or_default()
}
/// The square's colour at the stage centre of its frame (CPU oracle, 1:1), 0–255.
fn pixel(s: &Session, frame: u32) -> [u8; 4] {
let pm = anicraft_render::render_frame(&s.doc, frame, 1.0).unwrap();
let px = pm.to_rgba8();
let i = ((10 * pm.width + 10) * 4) as usize;
[px[i], px[i + 1], px[i + 2], px[i + 3]]
}
fn near(a: [u8; 4], b: [u8; 4]) -> bool {
a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 1)
}
#[test]
fn every_style_is_set_and_reported() {
let mut s = square();
let v = run(&mut s, "element.set_color_effect", json!({"brightness": -50}));
assert_eq!(v, json!({"style": "brightness", "brightness": -50.0}));
assert_eq!(effect(&s), ColorEffect::Brightness(-0.5));
let v = run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 25}));
assert_eq!(v, json!({"style": "tint", "tint": "#ff0000", "tint_amount": 25.0}));
let v = run(&mut s, "element.set_color_effect", json!({"alpha": 40}));
assert_eq!(v, json!({"style": "alpha", "alpha": 40.0}));
run(&mut s, "element.set_color_effect", json!({"red_multiplier": -100, "red_offset": 255, "alpha_offset": -10.5}));
assert_eq!(effect(&s), ColorEffect::Advanced(ColorTransform { mul: [-1.0, 1.0, 1.0, 0.4], add: [1.0, 0.0, 0.0, -10.5 / 255.0] }), "Advanced starts from the alpha it had");
let v = run(&mut s, "element.set_color_effect", json!({"style": "none"}));
assert_eq!(v, json!({"style": "none"}));
assert_eq!(effect(&s), ColorEffect::None);
}
#[test]
fn a_new_style_keeps_the_look_it_can() {
let mut s = square();
run(&mut s, "element.set_color_effect", json!({"tint": "#00ff00", "tint_amount": 60}));
let before = pixel(&s, 0);
run(&mut s, "element.set_color_effect", json!({"style": "advanced"}));
assert_eq!(effect(&s).style(), ColorStyle::Advanced);
assert!(near(pixel(&s, 0), before), "Advanced is exactly the tint");
run(&mut s, "element.set_color_effect", json!({"style": "brightness"}));
assert_eq!(effect(&s), ColorEffect::Brightness(0.0));
run(&mut s, "element.set_color_effect", json!({"style": "tint"}));
assert_eq!(effect(&s), ColorEffect::Tint { color: Rgba::WHITE, amount: 0.0 });
}
#[test]
fn bad_params_change_nothing() {
let mut s = square();
let before = s.doc.clone();
for p in [
json!({}),
json!({"style": "sepia"}),
json!({"brightness": 101}),
json!({"tint_amount": -1}),
json!({"red_offset": 300}),
json!({"alpha": 50, "brightness": 10}),
json!({"style": "tint", "alpha": 50}),
json!({"tint": "red"}),
json!({"alpha": f64::NAN}),
] {
assert!(s.execute("element.set_color_effect", &p).is_err(), "{p}");
}
assert_eq!(s.doc, before);
run(&mut s, "edit.deselect", json!({}));
assert!(s.execute("element.set_color_effect", &json!({"style": "alpha"})).is_err(), "nothing selected");
}
#[test]
fn renders_follow_the_arithmetic() {
// #336699 = (51, 102, 153).
let mut s = square();
run(&mut s, "element.set_color_effect", json!({"brightness": 50}));
assert!(near(pixel(&s, 0), [153, 179, 204, 255]), "{:?}", pixel(&s, 0));
run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50}));
assert!(near(pixel(&s, 0), [153, 51, 77, 255]), "{:?}", pixel(&s, 0));
run(&mut s, "element.set_color_effect", json!({"style": "advanced", "red_multiplier": -100, "red_offset": 255, "green_multiplier": 50, "blue_offset": -100}));
// The tint carried over into Advanced (×50 %, +127.5 red), then these channels changed.
let fx = effect(&s).transform();
assert_eq!((fx.mul[0], fx.add[0], fx.mul[1], fx.add[2]), (-1.0, 1.0, 0.5, -100.0 / 255.0));
assert!(near(pixel(&s, 0), [204, 51, 0, 255]), "{:?}", pixel(&s, 0));
}
#[test]
fn a_change_on_a_mixed_selection_sets_only_that_value() {
let mut s = Session::default();
let a = run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap();
let b = run(&mut s, "draw.rect", json!({"x": 20, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap();
run(&mut s, "element.select", json!({"ids": [a]}));
run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50}));
run(&mut s, "element.select", json!({"ids": [b]}));
run(&mut s, "element.set_color_effect", json!({"tint": "#0000ff", "tint_amount": 10}));
run(&mut s, "element.select", json!({"ids": [a, b]}));
run(&mut s, "element.set_color_effect", json!({"tint_amount": 80}));
let fx: Vec<ColorEffect> = s.visible_elements().iter().map(|e| e.color).collect();
assert_eq!(fx, [ColorEffect::Tint { color: Rgba::hex(0xff0000), amount: 0.8 }, ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.8 }], "each keeps its colour");
// One undo step puts both back.
s.undo().unwrap();
assert_eq!(s.visible_elements()[1].color, ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.1 });
}
#[test]
fn set_alpha_keeps_the_rest_of_the_effect() {
let mut s = square();
run(&mut s, "element.set_color_effect", json!({"brightness": 20}));
run(&mut s, "element.set_alpha", json!({"alpha": 0.5}));
assert_eq!(effect(&s).transform(), ColorTransform::alpha(0.5).concat(&ColorTransform::brightness(0.2)));
run(&mut s, "element.set_color_effect", json!({"style": "none"}));
run(&mut s, "element.set_alpha", json!({"alpha": 0.5}));
assert_eq!(effect(&s), ColorEffect::Alpha(0.5));
}
#[test]
fn a_classic_tween_between_styles_travels_in_the_advanced_space() {
let mut s = square();
run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 100}));
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_color_effect", json!({"alpha": 50}));
run(&mut s, "timeline.goto", json!({"frame": 0}));
run(&mut s, "timeline.create_tween", json!({"easing": "Linear"}));
s.set_frame(5);
let mid = effect(&s);
assert_eq!(mid.style(), ColorStyle::Advanced);
let want = ColorTransform::tint(Rgba::hex(0xff0000), 1.0).lerp(&ColorTransform::alpha(0.5), 0.5);
let got = mid.transform();
assert!(got.mul.iter().zip(want.mul).chain(got.add.iter().zip(want.add)).all(|(a, b)| (a - b).abs() < 1e-5), "{got:?} vs {want:?}");
// Within one style the value itself travels: brightness −100 % to +100 % is 0 halfway.
let mut s = square();
run(&mut s, "element.set_color_effect", json!({"brightness": -100}));
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_color_effect", json!({"brightness": 100}));
run(&mut s, "timeline.goto", json!({"frame": 0}));
run(&mut s, "timeline.create_tween", json!({"easing": "Linear"}));
s.set_frame(5);
assert_eq!(effect(&s), ColorEffect::Brightness(0.0));
assert!(near(pixel(&s, 5), [51, 102, 153, 255]));
}
#[test]
fn motion_tweens_key_brightness_tint_and_advanced() {
let mut s = square();
run(&mut s, "timeline.create_motion_tween", json!({}));
run(&mut s, "motion.set_key", json!({"property": "brightness", "frame": 10, "value": 60}));
s.set_frame(5);
assert_eq!(effect(&s), ColorEffect::Brightness(0.3));
// A second style composes with the first into Advanced, exactly.
run(&mut s, "motion.set_key", json!({"property": "tint", "frame": 10, "value": 50}));
run(&mut s, "motion.set_key", json!({"property": "tint_red", "frame": 0, "value": 255}));
run(&mut s, "motion.set_key", json!({"property": "tint_green", "frame": 0, "value": 0}));
run(&mut s, "motion.set_key", json!({"property": "tint_blue", "frame": 0, "value": 0}));
s.set_frame(10);
let want = ColorTransform::brightness(0.6).concat(&ColorTransform::tint(Rgba::hex(0xff0000), 0.5));
assert_eq!(effect(&s).transform(), want);
// Advanced channels on their own curves.
let mut s = square();
run(&mut s, "timeline.create_motion_tween", json!({}));
run(&mut s, "motion.set_key", json!({"property": "red_offset", "frame": 10, "value": 255}));
run(&mut s, "motion.set_key", json!({"property": "alpha_multiplier", "frame": 10, "value": 0}));
s.set_frame(5);
let fx = effect(&s);
assert_eq!(fx.style(), ColorStyle::Advanced);
assert_eq!(fx.transform(), ColorTransform { mul: [1.0, 1.0, 1.0, 0.5], add: [0.5, 0.0, 0.0, 0.0] });
assert!(s.execute("motion.set_key", &json!({"property": "red_offset", "frame": 3, "value": 256})).is_err());
// Info lists the keys by their names.
let info = run(&mut s, "motion.info", json!({}));
assert!(info.to_string().contains("red_offset"), "{info}");
}
#[test]
fn a_motion_tween_has_one_colour_effect_style() {
let mut s = square();
run(&mut s, "element.set_color_effect", json!({"tint": "#00ff00", "tint_amount": 40}));
run(&mut s, "timeline.create_motion_tween", json!({}));
// Untracked, the target's own tint shows all along.
s.set_frame(5);
assert_eq!(effect(&s), ColorEffect::Tint { color: Rgba::hex(0x00ff00), amount: 0.4 });
// Keying alpha makes it an alpha tween, as in Animate.
run(&mut s, "motion.set_key", json!({"property": "alpha", "frame": 10, "value": 0}));
s.set_frame(5);
assert_eq!(effect(&s), ColorEffect::Alpha(0.5));
// Changing the alpha in Properties inside the span keys it there.
s.set_frame(4);
run(&mut s, "edit.select_all", json!({}));
run(&mut s, "element.set_color_effect", json!({"alpha": 90}));
s.set_frame(4);
assert!((effect(&s).alpha() - 0.9).abs() < 1e-4, "{:?}", effect(&s));
assert!(layer_motion_has(&s, Property::Alpha) && !layer_motion_has(&s, Property::Tint));
// Keying tint as well composes the two (older files keyed both); the tint colour is the
// target's own.
run(&mut s, "motion.set_key", json!({"property": "tint", "frame": 10, "value": 50}));
s.set_frame(10);
assert_eq!(effect(&s).transform(), ColorTransform::alpha(0.0).concat(&ColorTransform::tint(Rgba::hex(0x00ff00), 0.5)), "the tint keys start from the target's own colour");
}
fn layer_motion_has(s: &Session, p: Property) -> bool {
s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.as_ref()).is_some_and(|m| m.track(p).is_some())
}
#[test]
fn files_keep_every_style() {
let mut s = Session::default();
for (i, p) in [json!({"brightness": -30}), json!({"tint": "#123456", "tint_amount": 0}), json!({"style": "advanced", "blue_multiplier": -40, "green_offset": 12}), json!({"alpha": 100})].into_iter().enumerate() {
let id = run(&mut s, "draw.rect", json!({"x": i * 20, "y": 0, "w": 10, "h": 10, "object": true}))["element"].as_u64().unwrap();
run(&mut s, "element.select", json!({"ids": [id]}));
run(&mut s, "element.set_color_effect", p);
}
let text = crate::format::to_json(&s.doc).unwrap();
let back = crate::format::from_json(&text).unwrap();
assert_eq!(back, s.doc);
let styles: Vec<ColorStyle> = back.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| e.color.style()).collect();
assert_eq!(styles, [ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced, ColorStyle::Alpha]);
}
#[test]
fn plug_ins_may_set_colour_effects() {
assert!(crate::cmds_plugin::plugin_may_call("element.set_color_effect").is_ok());
}
#[test]
fn a_nine_slice_instance_takes_its_colour_effect() {
// ADR 0055 with ADR 0056: the slices are geometry; the colour effect applies to all of them.
let mut s = square();
run(&mut s, "modify.convert_to_symbol", json!({"name": "Panel"}));
run(&mut s, "symbol.set_scale_grid", json!({"on": true, "left": 5, "right": 15, "top": 5, "bottom": 15}));
run(&mut s, "element.set_transform", json!({"sx": 3.0, "sy": 3.0}));
run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50}));
let dl = anicraft_doc::evaluate(&s.doc, 0);
assert!(!dl.items.is_empty());
let want = ColorTransform::tint(Rgba::hex(0xff0000), 0.5);
assert!(dl.items.iter().all(|i| i.color == want), "every slice is tinted");
}
+1 -1
View File
@@ -221,7 +221,7 @@ fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32,
id: ElementId(doc.alloc_id()),
name: String::new(),
transform,
color: ColorEffect { alpha, ..ColorEffect::default() },
color: ColorEffect::opacity(alpha),
kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() },
}));
let mut layer = Layer::new(LayerId(doc.alloc_id()), "");
+26
View File
@@ -894,6 +894,30 @@ pub(crate) enum KeyEdit {
Pose,
}
/// A colour effect as commands report it (ADR 0056): its style and that style's values, in the
/// units `element.set_color_effect` takes (percent; Advanced offsets −255..255).
pub fn color_effect_json(fx: &anicraft_doc::ColorEffect) -> serde_json::Value {
use anicraft_doc::ColorEffect;
let r = |v: f32, k: f32| f64::from((v * k * 100.0).round() / 100.0);
let mut v = serde_json::json!({"style": fx.style().key()});
match *fx {
ColorEffect::None => {}
ColorEffect::Alpha(a) => v["alpha"] = r(a, 100.0).into(),
ColorEffect::Brightness(b) => v["brightness"] = r(b, 100.0).into(),
ColorEffect::Tint { color, amount } => {
v["tint"] = color.to_hex().into();
v["tint_amount"] = r(amount, 100.0).into();
}
ColorEffect::Advanced(t) => {
for (i, ch) in ["red", "green", "blue", "alpha"].iter().enumerate() {
v[format!("{ch}_multiplier")] = r(t.mul.get(i).copied().unwrap_or(1.0), 100.0).into();
v[format!("{ch}_offset")] = r(t.add.get(i).copied().unwrap_or(0.0), 255.0).into();
}
}
}
v
}
/// Short human label for an element (properties panel, library, CLI).
pub fn element_label(doc: &Document, e: &Element) -> String {
let kind = match &e.kind {
@@ -921,6 +945,8 @@ mod tests;
#[cfg(test)]
mod motion_tests;
#[cfg(test)]
mod color_tests;
#[cfg(test)]
mod motion_path_tests;
#[cfg(test)]
mod motion_pin_tests;
+1 -1
View File
@@ -95,7 +95,7 @@ fn transforms_and_colour_edits_key_their_own_properties() {
assert!(m.track(Property::ScaleY).is_none() && m.track(Property::X).is_none());
s.set_frame(4);
let e = s.visible_elements()[0].clone();
assert!((e.color.alpha - 0.625).abs() < 1e-5 && (e.transform.decompose().sx - 1.5).abs() < 1e-4);
assert!((e.color.alpha() - 0.625).abs() < 1e-5 && (e.transform.decompose().sx - 1.5).abs() < 1e-4);
// Non-tweenable edits change the object itself, whatever the frame.
run(&mut s, "edit.select_all", json!({}));
run(&mut s, "element.set_fill", json!({"color": "#ff0000"}));
+2 -2
View File
@@ -285,7 +285,7 @@ fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() {
let n = dl.items.len();
let (ghost, now) = (&dl.items[n - 2], &dl.items[n - 1]);
assert_eq!((left(ghost), left(now)), (100.0, 140.0));
assert!(ghost.color.alpha < 1.0 && ghost.color.tint_amount > 0.0 && now.color.alpha == 1.0);
assert!(ghost.color.mul[3] < 1.0 && ghost.color.changes_colour() && now.color.is_identity());
// The job does the same, keyed apart from the plain picture.
let view = anicraft_render::View { transform: Affine::IDENTITY, width: 64, height: 64, background: None };
let plain_job = crate::render_service::make_job(pic.state, &pic.doc, pic.frame, view, Some(&ghosts));
@@ -295,7 +295,7 @@ fn onion_skin_inside_a_symbol_composes_its_own_frames_where_it_stands() {
// Edit Multiple Frames shows both keyframes at full strength.
let multi = OnionSkin { edit_multiple: true, markers: crate::onion::Markers::Relative { before: 4, after: 0 }, ..OnionSkin::default() };
let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi);
assert!(dl.items.iter().rev().take(2).all(|i| i.color.alpha == 1.0 && i.color.tint_amount == 0.0));
assert!(dl.items.iter().rev().take(2).all(|i| i.color.is_identity()));
// With nothing to add, the job draws the picture as it is.
let off = make_off(&pic);
assert_eq!(off.display_list().items.len(), plain.items.len());
+3 -3
View File
@@ -19,7 +19,7 @@
//! program; nothing was copied.
use crate::{CommandSpec, MAX_FRAME, Result, Session};
use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline};
use anicraft_doc::{ColorTransform, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline};
use anicraft_geom::{Rect, Vec2};
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashSet};
@@ -168,12 +168,12 @@ impl OnionSkin {
}
/// The colour effect an onion frame gets, and the outline colour (when outlines are on).
pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorEffect, Option<Rgba>) {
pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorTransform, Option<Rgba>) {
let alpha = self.alpha(distance, reach);
let color = if past { self.past } else { self.future };
let (tint, tint_amount) = if self.tint { (color, TINT_AMOUNT) } else { (Rgba::WHITE, 0.0) };
let outline = self.outlines.then(|| color.with_alpha(alpha * color.a.clamp(0.0, 1.0)));
(ColorEffect { alpha, tint, tint_amount }, outline)
(ColorTransform::alpha(alpha).concat(&ColorTransform::tint(tint, tint_amount)), outline)
}
/// A hash of everything that changes the picture, for render-cache keys.
+10 -8
View File
@@ -106,11 +106,12 @@ fn onion_frames_fade_by_distance_in_their_colours() {
assert!((1..=5).all(|d| flat.alpha(d, 5) == NEAR_ALPHA));
let (past, line) = o.look(true, 1, 2);
assert_eq!((past.tint, past.tint_amount, past.alpha, line), (o.past, TINT_AMOUNT, NEAR_ALPHA, None));
let look = |c, a| anicraft_doc::ColorTransform::alpha(a).concat(&anicraft_doc::ColorTransform::tint(c, TINT_AMOUNT));
assert_eq!((past, line), (look(o.past, NEAR_ALPHA), None));
let (future, _) = o.look(false, 2, 2);
assert_eq!((future.tint, future.alpha), (o.future, FAR_ALPHA));
assert_eq!(future, look(o.future, FAR_ALPHA));
let (own, _) = OnionSkin { tint: false, ..o }.look(true, 1, 2);
assert_eq!(own.tint_amount, 0.0, "untinted frames keep their own colours");
assert!(!own.changes_colour(), "untinted frames keep their own colours");
let (_, line) = OnionSkin { outlines: true, ..o }.look(false, 2, 2);
assert_eq!(line, Some(o.future.with_alpha(FAR_ALPHA)));
}
@@ -182,10 +183,11 @@ fn composed_onion_frames_are_tinted_faded_and_under_the_playhead() {
let skin = OnionSkin::default();
let dl = compose(&s.doc, 0, 4, Some(&skin), |sc, f| evaluate_scene(&s.doc, sc, f));
// Frames 2, 6, 3, 5 under frame 4: the keyframes there hold the rectangle at 10, 50, 10, 50.
let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect();
let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.mul[3], 1.0 - i.color.mul[0])).collect();
assert_eq!(got, vec![(10.0, FAR_ALPHA, TINT_AMOUNT), (50.0, FAR_ALPHA, TINT_AMOUNT), (10.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, 1.0, 0.0)]);
assert_eq!(dl.items.first().map(|i| i.color.tint), Some(skin.past));
assert_eq!(dl.items.get(1).map(|i| i.color.tint), Some(skin.future));
let tint = |c| anicraft_doc::ColorTransform::tint(c, TINT_AMOUNT).add;
assert_eq!(dl.items.first().map(|i| i.color.add), Some(tint(skin.past)));
assert_eq!(dl.items.get(1).map(|i| i.color.add), Some(tint(skin.future)));
// Off, or None: the frame alone.
let off = OnionSkin { ghosts: false, ..skin };
assert_eq!(compose(&s.doc, 0, 4, Some(&off), |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1);
@@ -230,7 +232,7 @@ fn edit_multiple_frames_shows_keyframes_within_the_markers_at_full_strength() {
// doesn't; the one on 4 is the playhead's.
assert_eq!(multi_frames(tl, 4, 2, 6).iter().map(|e| e.frame).collect::<Vec<_>>(), vec![0]);
let dl = compose(&s.doc, 0, 4, Some(&near), |sc, f| evaluate_scene(&s.doc, sc, f));
assert_eq!(dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect::<Vec<_>>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]);
assert_eq!(dl.items.iter().map(|i| (left(i), i.color.mul[3], 1.0 - i.color.mul[0])).collect::<Vec<_>>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]);
let wide = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..near };
let dl = compose(&s.doc, 0, 4, Some(&wide), |sc, f| evaluate_scene(&s.doc, sc, f));
assert_eq!(dl.items.iter().map(left).collect::<Vec<_>>(), vec![10.0, 90.0, 50.0], "other keyframes in frame order, the playhead's on top");
@@ -420,7 +422,7 @@ fn extra_frames_sit_on_their_own_layer_over_an_opaque_background() {
let ball = plain.items.last().unwrap().layer;
let on_ball: Vec<&DisplayItem> = dl.items.iter().filter(|i| i.layer == ball).collect();
assert!(on_ball.len() > 1);
assert_eq!(on_ball.last().map(|i| (i.color.alpha, i.color.tint_amount)), Some((1.0, 0.0)), "the playhead's ball is on top");
assert_eq!(on_ball.last().map(|i| i.color.is_identity()), Some(true), "the playhead's ball is on top");
}
// Rendered: the ball on frame 1 (top left of its path) shows over the sky, in Edit Multiple
// Frames at full strength.
+1 -1
View File
@@ -206,7 +206,7 @@ fn properties_edits_apply_to_each_layer() {
run(&mut s, "element.set_transform", json!({"rotation": 45}));
for (l, id) in [(top, a), (bottom, b)] {
let e = element(&s, l, id).unwrap();
assert_eq!(e.color.alpha, 0.5);
assert_eq!(e.color, anicraft_doc::ColorEffect::Alpha(0.5));
assert_eq!(e.name, "both");
assert!((e.transform.decompose().rotation.to_degrees() - 45.0).abs() < 1e-3);
let ElementKind::Shape(sh) = &e.kind else { panic!() };
+20 -1
View File
@@ -29,6 +29,7 @@ fn corpus() -> PathBuf {
/// The frames rendered for each package (frames count across scenes, from 0).
const FRAMES: &[(&str, &[u32])] = &[
("bitmaps", &[0]),
("colour", &[0, 6, 12]),
("filters", &[0]),
("gradients", &[0]),
("guides", &[0, 6, 12]),
@@ -74,9 +75,27 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[
("symbols", 5, 130.0, 40.0, 0x457B9D),
// The button's Up frame.
("symbols", 0, 82.0, 130.0, 0x2A9D8F),
// Brightness +60% and -50% of #6D597A.
// Brightness +60% and -50% of #6D597A; Advanced: red ×20 %, green +120, at 80 % over white.
("symbols", 0, 230.0, 130.0, 0xC5BDCA),
("symbols", 0, 260.0, 130.0, 0x372D3D),
("symbols", 0, 290.0, 130.0, 0x44DA95),
// Colour effects on #2A9D8F (ADR 0056): None, Brightness +50 %, Tint 60 % #E9C46A, Advanced
// (red −100 % +255, green 50 %, blue −60), Alpha 25 % over white.
("colour", 0, 30.0, 40.0, 0x2A9D8F),
("colour", 0, 90.0, 40.0, 0x94CEC7),
("colour", 0, 150.0, 40.0, 0x9DB479),
("colour", 0, 210.0, 40.0, 0xD54F53),
("colour", 0, 270.0, 40.0, 0xCAE6E3),
// Brightness −40 % around a 50 % red tint: both, exactly (not the stronger one alone).
("colour", 0, 60.0, 110.0, 0x592F2B),
// Tint #264653 to Advanced: the ends, and halfway in the advanced space.
("colour", 0, 160.0, 105.0, 0x264653),
("colour", 6, 220.0, 105.0, 0x614771),
("colour", 12, 280.0, 105.0, 0x944C8D),
// Brightness −100 % to +60 %: halfway is brightness −20 % (not the transforms' midpoint).
("colour", 0, 160.0, 152.0, 0x000000),
("colour", 6, 220.0, 152.0, 0x227E72),
("colour", 12, 280.0, 152.0, 0xAAD8D2),
("tweens", 0, 20.0, 25.0, 0xF4A261),
("tweens", 12, 300.0, 25.0, 0xF4A261),
// Masked stripes: inside the spot, and outside it.
+3 -3
View File
@@ -13,7 +13,7 @@
//! (512 px tiles drawn in parallel, as the render service does, until finished); and how far
//! the GPU-binned picture is from the oracle's.
use anicraft_doc::{Bitmap, BitmapId, ColorEffect, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample};
use anicraft_doc::{Bitmap, BitmapId, ColorEffect, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample};
use anicraft_geom::{FillRule, Path};
use anicraft_gpu::{Binning, GpuRenderer, compare_premul8};
use anicraft_geom::Affine;
@@ -54,7 +54,7 @@ fn composited() -> Document {
0 | 1 => {
for k in &mut l.keyframes {
for e in &mut Arc::make_mut(k).elements {
Arc::make_mut(e).color.alpha = 0.6;
Arc::make_mut(e).color = ColorEffect::Alpha(0.6);
}
}
}
@@ -172,7 +172,7 @@ fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList {
let color = if is_past { past } else { future };
let mut part = evaluate(doc, f);
for item in &mut part.items {
item.color = item.color.concat(&ColorEffect { alpha, tint: color, tint_amount: 0.8 });
item.color = item.color.concat(&ColorTransform::alpha(alpha).concat(&ColorTransform::tint(color, 0.8)));
if mode == Onion::Outlines && item.masks.is_none() {
item.outline = Some(color.with_alpha(alpha));
}
+15 -25
View File
@@ -252,7 +252,16 @@ pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_
let mut images: Vec<Arc<Pixels>> = Vec::new();
let ramps_at = (PAINT_VEC4S * ops.len()) as u32;
// Where each layer shown by a fill goes, after the tables (the tables' size is known first).
let table_len: usize = ops.iter().filter(|f| matches!(f.shader, Shader::Linear { .. } | Shader::Radial { .. }) && f.layer.is_none()).count() * RAMP;
// Gradients' ramps, and each bitmap's colour transform (two entries).
let table_len: usize = ops
.iter()
.filter(|f| f.layer.is_none())
.map(|f| match &f.shader {
Shader::Linear { .. } | Shader::Radial { .. } => RAMP,
Shader::Bitmap { pixels, .. } if pixels.width > 0 && pixels.height > 0 => 2,
_ => 0,
})
.sum();
let mut layer_at: Vec<Option<u32>> = vec![None; scene.layers.len()];
let mut cursor = PAINT_VEC4S * ops.len() + table_len;
for f in &ops {
@@ -306,9 +315,12 @@ pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_
None => return Err(NeedsFull::Bitmaps),
};
let m = inv.m;
let (k, alpha, tint, keep) = colour_effect(fx);
// The colour transform (ADR 0056) rides in the ramp table: multiplies, then
// offsets, sanitized as the oracle applies them.
let fx = fx.sanitized();
ramps.extend_from_slice(&[fx.mul, fx.add]);
// Bit 0: repeat; bit 1: the nearest pixel instead of bilinear (no smoothing).
(BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], k, alpha], [tint[0], tint[1], tint[2], u(keep)]])
(BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], 0.0, 0.0], [0.0; 4]])
}
}
// `prepare_scene` never hands these over; draw nothing rather than guess.
@@ -441,28 +453,6 @@ fn cpu_lists(ops: &[&Fill], tables: &Tables, tiles_x: u32, tiles_y: u32) -> List
Lists { index, geo, entries_at: entries_at as u32, ops_at: ops_at as u32, entries: total, pieces, work }
}
/// A colour effect as the shader applies it to each bitmap tap, the same arithmetic as
/// [`anicraft_doc::ColorEffect::apply`] then `premultiply`'s sanitizing: `(tint amount, alpha,
/// tint, kept channels)`. Each straight channel `c` becomes `c + (tint − c)·k`, alpha `a·alpha`,
/// clamped to `0..=1`. A NaN the oracle would carry into a channel (and its sanitizing turn
/// into 0) is a channel left out of `kept` (bit per channel, red first) instead.
fn colour_effect(fx: &anicraft_doc::ColorEffect) -> (f32, f32, [f32; 3], u32) {
let k = fx.tint_amount.clamp(0.0, 1.0);
let alpha = fx.alpha.clamp(0.0, 1.0);
let t = [fx.tint.r, fx.tint.g, fx.tint.b];
let mut keep = 0u32;
let mut tint = [0.0f32; 3];
for (i, (&v, out)) in t.iter().zip(tint.iter_mut()).enumerate() {
if v.is_finite() && k.is_finite() {
keep |= 1 << i;
*out = v;
}
}
// A NaN opacity makes every channel 0 (premultiplied by a sanitized alpha of 0).
let alpha = if alpha.is_finite() { alpha } else { 0.0 };
(if k.is_finite() { k } else { 0.0 }, alpha, tint, keep)
}
/// Tile row `r`'s streams: per tile, its fills in drawing order with the clip and group
/// entries they need.
fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec<u32>)], piece_at: &[u32], t: &Tables) -> RowOut {
+13 -16
View File
@@ -167,19 +167,15 @@ fn wrap(i: i32, n: i32) -> i32 {
// One bitmap tap at integer (x, y) (wrapped when repeating, then clamped to the edges as
// `Pixels::at` does), through the colour effect, premultiplied.
fn tap(slot: u32, x: i32, y: i32, size: vec2<i32>, repeat: bool, fx: vec4<f32>, tint: vec4<f32>) -> vec4<f32> {
// The colour transform (ColorTransform::apply): each straight channel `c·mul + add`, clamped.
fn tap(slot: u32, x: i32, y: i32, size: vec2<i32>, repeat: bool, mul: vec4<f32>, add: vec4<f32>) -> vec4<f32> {
var q = vec2<i32>(x, y);
if repeat {
q = vec2<i32>(wrap(q.x, size.x), wrap(q.y, size.y));
}
q = clamp(q, vec2<i32>(0), size - vec2<i32>(1));
let c = texel(slot, q);
let keep = bitcast<u32>(tint.w);
let k = fx.z;
var rgb = clamp(c.rgb + (tint.rgb - c.rgb) * k, vec3<f32>(0.0), vec3<f32>(1.0));
rgb = select(vec3<f32>(0.0), rgb, vec3<bool>((keep & 1u) != 0u, (keep & 2u) != 0u, (keep & 4u) != 0u));
let a = clamp(c.a * fx.w, 0.0, 1.0);
return vec4<f32>(rgb * a, a);
let c = clamp(texel(slot, q) * mul + add, vec4<f32>(0.0), vec4<f32>(1.0));
return vec4<f32>(c.rgb * c.a, c.a);
}
// Rust's `rem_euclid` for f32.
@@ -190,11 +186,12 @@ fn rem_euclid(u: f32, n: f32) -> f32 {
// The oracle's sample of a bitmap at pixel centre `p` (paint.rs › sample): bilinear, or the
// pixel `p` falls in when the bitmap doesn't allow smoothing (flag bit 1).
fn bitmap(base: u32, p: vec2<f32>) -> vec4<f32> {
fn bitmap(base: u32, ramp: u32, p: vec2<f32>) -> vec4<f32> {
let h0 = paints[base];
let m = paints[base + 1u];
let n = paints[base + 2u];
let tint = paints[base + 3u];
let mul = paints[ramp];
let add = paints[ramp + 1u];
let slot = bitcast<u32>(h0.x);
let flags = bitcast<u32>(h0.y);
let repeat = (flags & 1u) != 0u;
@@ -214,7 +211,7 @@ fn bitmap(base: u32, p: vec2<f32>) -> vec4<f32> {
return vec4<f32>(0.0);
}
if nearest {
return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, n, tint);
return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, mul, add);
}
let fx_ = u - 0.5;
let fy_ = v - 0.5;
@@ -224,10 +221,10 @@ fn bitmap(base: u32, p: vec2<f32>) -> vec4<f32> {
let ty = fy_ - y0;
let xi = i32(x0);
let yi = i32(y0);
let a = tap(slot, xi, yi, size, repeat, n, tint);
let b = tap(slot, xi + 1, yi, size, repeat, n, tint);
let c = tap(slot, xi, yi + 1, size, repeat, n, tint);
let d = tap(slot, xi + 1, yi + 1, size, repeat, n, tint);
let a = tap(slot, xi, yi, size, repeat, mul, add);
let b = tap(slot, xi + 1, yi, size, repeat, mul, add);
let c = tap(slot, xi, yi + 1, size, repeat, mul, add);
let d = tap(slot, xi + 1, yi + 1, size, repeat, mul, add);
let top = a + (b - a) * tx;
let bottom = c + (d - c) * tx;
return top + (bottom - top) * ty;
@@ -254,7 +251,7 @@ fn shade(op: u32, kind: u32, ramp: u32, p: vec2<f32>, x: u32, y: u32) -> vec4<f3
return paints[base];
}
if kind == 3u {
return bitmap(base, p);
return bitmap(base, ramp, p);
}
if kind == 4u {
return layer(base, x, y);
+2 -2
View File
@@ -426,7 +426,7 @@ impl GpuRenderer {
/// symbol within the parity target. Catches drivers that build the pipelines but compute
/// garbage.
fn self_test(&self) -> Result<(), GpuError> {
use anicraft_doc::{ColorEffect, DisplayItem, ElementId, Filter, Group, LayerId, Paint, Pixels, Rgba};
use anicraft_doc::{ColorTransform, DisplayItem, ElementId, Filter, Group, LayerId, Paint, Pixels, Rgba};
use anicraft_geom::{Affine, FillRule, Path};
let item = |path: Path, fill: Paint| DisplayItem {
path: Arc::new(path),
@@ -434,7 +434,7 @@ impl GpuRenderer {
fill: Some(fill),
stroke: None,
fill_rule: FillRule::NonZero,
color: ColorEffect::default(),
color: ColorTransform::IDENTITY,
layer: LayerId(0),
element: ElementId(0),
outline: None,
+13 -9
View File
@@ -7,7 +7,7 @@
use super::*;
use crate::binning::{self as bn, Binned, PAINT_VEC4S, TILE, piece_cover, solid_of};
use anicraft_doc::{BlendMode, ColorEffect, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, Paint, Rgba, Stroke, sample};
use anicraft_doc::{BlendMode, ColorEffect, ColorTransform, DisplayItem, ElementId, ElementKind, GradientStop, Group, LayerId, LayerKind, Paint, Rgba, Stroke, sample};
use anicraft_geom::{Affine, FillRule, Path, Vec2};
use anicraft_render::{paint::Premul, render};
use std::sync::OnceLock;
@@ -22,7 +22,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem {
fill: Some(fill),
stroke: None,
fill_rule: FillRule::NonZero,
color: ColorEffect::default(),
color: ColorTransform::IDENTITY,
layer: LayerId(0),
element: ElementId(0),
outline: None,
@@ -125,7 +125,7 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> {
out.push(("styled strokes", list(vec![dashed, zig, dots]), view(160, 100, Some(Rgba::WHITE))));
// Larger than the surface on every side; colour effects (onion-skin style tint and alpha).
let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red));
huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 };
huge.color = ColorTransform::alpha(0.5).concat(&ColorTransform::tint(Rgba::hex(0x4cd07d), 0.7));
out.push(("off-surface", list(vec![huge]), view(100, 80, Some(Rgba::WHITE))));
out.push(("outlines", outlined(), view(150, 110, Some(Rgba::WHITE))));
out.extend(composited_scenes());
@@ -448,7 +448,7 @@ fn composited_sample() -> anicraft_doc::Document {
for k in &mut l.keyframes {
for e in &mut Arc::make_mut(k).elements {
let e = Arc::make_mut(e);
e.color.alpha = if i == 0 { 0.6 } else { 0.5 };
e.color = e.color.with_alpha(if i == 0 { 0.6 } else { 0.5 });
if let ElementKind::Symbol { blend, .. } = &mut e.kind
&& i == 0
{
@@ -778,7 +778,7 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() {
})
.collect();
let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1);
it.color.alpha = 0.5;
it.color = ColorTransform::alpha(0.5);
DisplayList { items: vec![it], clip_parents: Vec::new(), groups }
};
let deep = nested(MAX_FILTER_DEPTH + 1);
@@ -840,12 +840,16 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> {
("bitmap magnified, mirrored", list(vec![bitmap_item(Path::rect(0.0, 0.0, 64.0, 48.0), &c, false, Affine { m: [-1.7, 0.0, 0.0, 1.6, 66.0, -1.3] })]), view(64, 48, white)),
("one-pixel bitmap", list(vec![bitmap_item(Path::rect(5.5, 5.5, 20.0, 20.0), &b, true, Affine::scale(7.0, 7.0))]), view(32, 32, white)),
];
// Colour effects: tint and alpha per tap, and a NaN tint (sanitized to 0 as the oracle does).
// Colour effects: tint and alpha per tap, and a NaN multiplier (a channel of 0, as the oracle
// draws it).
let mut tinted = bitmap_item(Path::rect(0.0, 0.0, 60.0, 40.0), &c, true, Affine::scale(0.7, 0.9));
tinted.color = ColorEffect { alpha: 0.6, tint: Rgba::new(0.2, 0.9, 0.1, 1.0), tint_amount: 0.4 };
tinted.color = ColorTransform::alpha(0.6).concat(&ColorTransform::tint(Rgba::new(0.2, 0.9, 0.1, 1.0), 0.4));
let mut nan = bitmap_item(Path::rect(30.0, 10.0, 30.0, 30.0), &a, false, Affine::scale(2.0, 2.0));
nan.color = ColorEffect { alpha: 1.0, tint: Rgba::new(f32::NAN, 0.5, 0.5, 1.0), tint_amount: 0.3 };
out.push(("bitmap colour effects", list(vec![tinted, nan]), view(64, 48, Some(Rgba::new(0.1, 0.1, 0.3, 1.0)))));
nan.color = ColorTransform { mul: [f32::NAN, 0.7, 0.7, 1.0], add: [0.0, 0.15, 0.15, 0.0] };
// Advanced (ADR 0056): a negative multiplier, offsets and an alpha offset.
let mut advanced = bitmap_item(Path::rect(4.0, 20.0, 40.0, 26.0), &a, true, Affine::scale(1.3, 1.1));
advanced.color = ColorTransform { mul: [-1.0, 0.5, 0.2, 0.6], add: [1.0, 0.1, 0.4, 0.2] };
out.push(("bitmap colour effects", list(vec![tinted, nan, advanced]), view(64, 48, Some(Rgba::new(0.1, 0.1, 0.3, 1.0)))));
// A short (malformed) buffer: transparent past its end; an empty image draws nothing.
let short = Arc::new(anicraft_doc::Pixels { width: 4, height: 4, rgba: vec![200; 20] });
let empty = Arc::new(anicraft_doc::Pixels { width: 0, height: 3, rgba: Vec::new() });
+17 -22
View File
@@ -15,7 +15,7 @@
//!
//! What doesn't carry across is counted in the report: filters, 9-slice scaling (instances
//! scale as a whole), Subtract and Invert blending,
//! tints on bitmaps, plug-in frame scripts (they need the plug-in host) and kept scripts
//! plug-in frame scripts (they need the plug-in host) and kept scripts
//! outside the ActionScript subset. Scripts in the subset (ADR 0013 tiers 2 and 2.5) come
//! across as the same script IR the Rust player runs (as JSON), with each timeline's functions
//! and variable types, and `player.js` evaluates it the same way.
@@ -24,7 +24,7 @@ use crate::stroke::stroke_outline;
use anicraft_doc::actions::as3::Decls;
use anicraft_doc::actions::{Action, FrameRef, Seg, Target};
use anicraft_doc::player::TimelineRef;
use anicraft_doc::{BlendMode, ColorEffect, Document, Element, ElementKind, FrameScript, Layer, LayerKind, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start};
use anicraft_doc::{BlendMode, ColorTransform, Document, Element, ElementKind, FrameScript, Layer, LayerKind, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start};
use anicraft_geom::{Affine, FillRule, Path, PathCmd};
use serde_json::{Map, Value, json};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
@@ -93,7 +93,6 @@ pub struct HtmlExport {
/// Notes for the report.
const FILTERS: &str = "filters (not exported; drawn without them)";
const BLENDS: &str = "Subtract and Invert blending (drawn normally)";
const BITMAP_TINT: &str = "tints on bitmap fills (drawn untinted)";
const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)";
const BUTTON_SOUNDS: &str = "sounds on button frames (not played yet)";
const KEPT_SCRIPTS: &str = "kept frame scripts outside the ActionScript subset (not run; kept in the document only)";
@@ -144,15 +143,14 @@ fn matrix(m: &Affine) -> Option<Value> {
Some(json!([num(a, 1e5), num(b, 1e5), num(c, 1e5), num(d, 1e5), coord(e), coord(f)]))
}
/// `[alpha, tint r, g, b, tint amount]`; `None` for no effect.
fn effect(fx: &ColorEffect) -> Option<Value> {
if *fx == ColorEffect::default() {
/// A colour transform (ADR 0056): `[red, green, blue, alpha multipliers, red, green, blue,
/// alpha offsets]`; `None` for no effect.
fn effect(fx: &ColorTransform) -> Option<Value> {
let fx = fx.sanitized();
if fx.is_identity() {
return None;
}
let t = fx.tint.sanitized();
let a = if fx.alpha.is_finite() { fx.alpha } else { 1.0 };
let k = if fx.tint_amount.is_finite() { fx.tint_amount } else { 0.0 };
Some(json!([num(a, 1e4), num(t.r, 1e4), num(t.g, 1e4), num(t.b, 1e4), num(k, 1e4)]))
Some(Value::Array(fx.mul.iter().chain(fx.add.iter()).map(|v| num(*v, 1e4)).collect()))
}
/// SVG path data (what `Path2D` reads), three decimals; empty when a point isn't finite.
@@ -311,7 +309,7 @@ impl<'a> Bake<'a> {
i
}
fn paint(&mut self, p: &Paint, el: &Element) -> usize {
fn paint(&mut self, p: &Paint) -> usize {
let stops = |s: &[anicraft_doc::GradientStop]| -> Vec<Value> {
s.iter()
.map(|g| {
@@ -328,9 +326,6 @@ impl<'a> Bake<'a> {
Paint::Radial { center, radius, stops: s } => json!({"r": [coord(center.x), coord(center.y), coord(radius.max(0.0))], "st": stops(s)}),
Paint::Bitmap { bitmap, repeat, matrix: m } => match self.doc.bitmap(*bitmap) {
Some(b) => {
if el.color.tint_amount > 0.0 {
self.notes.entry(BITMAP_TINT).or_default().insert(el.id.0);
}
let n = self.images.len();
let i = *self.image_ix.entry(b.id.0).or_insert(n);
if i == n {
@@ -361,11 +356,11 @@ impl<'a> Bake<'a> {
/// A shape item: `p` path, `f` paint, `s` stroke `[r, g, b, a, width]`, `k` its style when
/// not round and solid (`c` cap, `j` join, `ml` miter limit, `d` dash lengths and `o` their
/// offset, in local units like the width), `eo` even-odd, `m` transform, `c` colour effect.
fn shape(&mut self, path: &Arc<Path>, m: &Affine, fx: &ColorEffect, fill: Option<(&Paint, &Element)>, stroke: Option<&anicraft_doc::Stroke>, rule: FillRule) -> Value {
fn shape(&mut self, path: &Arc<Path>, m: &Affine, fx: &ColorTransform, fill: Option<&Paint>, stroke: Option<&anicraft_doc::Stroke>, rule: FillRule) -> Value {
let mut o = Map::new();
o.insert("p".into(), json!(self.path(path)));
if let Some((p, el)) = fill {
o.insert("f".into(), json!(self.paint(p, el)));
if let Some(p) = fill {
o.insert("f".into(), json!(self.paint(p)));
}
if let Some(st) = stroke {
let mut s = color(st.color);
@@ -400,22 +395,22 @@ impl<'a> Bake<'a> {
// caps, joins and dashes included).
Some(st) => {
if let Some(p) = &s.fill {
out.push(self.shape(&s.path, &el.transform, &el.color, Some((p, el)), None, s.fill_rule));
out.push(self.shape(&s.path, &el.transform, &el.color.transform(), Some(p), None, s.fill_rule));
}
let outline = stroke_outline(&s.path, &el.transform, st, crate::TOLERANCE);
if !outline.is_empty() {
let fill = Paint::Solid(st.color);
out.push(self.shape(&Arc::new(outline), &Affine::IDENTITY, &el.color, Some((&fill, el)), None, FillRule::NonZero));
out.push(self.shape(&Arc::new(outline), &Affine::IDENTITY, &el.color.transform(), Some(&fill), None, FillRule::NonZero));
}
}
None => out.push(self.shape(&s.path, &el.transform, &el.color, s.fill.as_ref().map(|p| (p, el)), stroke, s.fill_rule)),
None => out.push(self.shape(&s.path, &el.transform, &el.color.transform(), s.fill.as_ref(), stroke, s.fill_rule)),
}
}
// The camera is the view, not artwork (ADR 0027): it is baked into the layers.
ElementKind::Camera => {}
ElementKind::Text(t) => {
let fill = Paint::Solid(t.color);
out.push(self.shape(&t.outline, &el.transform, &el.color, Some((&fill, el)), None, FillRule::NonZero));
out.push(self.shape(&t.outline, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero));
}
ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => {
let (Some(&y), Some(sym)) = (self.symbols.get(symbol), self.doc.symbol(*symbol)) else { return };
@@ -433,7 +428,7 @@ impl<'a> Bake<'a> {
if let Some(m) = matrix(&el.transform) {
o.insert("m".into(), m);
}
if let Some(c) = effect(&el.color) {
if let Some(c) = effect(&el.color.transform()) {
o.insert("c".into(), c);
}
match sym.kind {
+32 -3
View File
@@ -113,10 +113,14 @@
if (p.b !== undefined) {
const im = images[p.b];
if (!im || !im.complete || !im.naturalWidth) return "rgba(128,128,128,1)";
const key = f;
// A colour effect beyond alpha draws the bitmap's pixels through it (ADR 0056), as the
// renderer does: once per bitmap and effect while the effect stays the same.
const recolour = AniCraft.recolours(fx);
const key = recolour ? f + ":" + fx.join(",") : f;
let pat = patterns.get(key);
if (!pat) {
pat = g.createPattern(im, p.rep ? "repeat" : "no-repeat");
if (patterns.size > 256) patterns.clear();
pat = g.createPattern(recolour ? recoloured(im, fx) : im, p.rep ? "repeat" : "no-repeat");
if (pat && p.m && pat.setTransform) pat.setTransform(new DOMMatrix(p.m));
patterns.set(key, pat);
}
@@ -125,6 +129,31 @@
return null;
}
// `im`'s pixels through colour transform `fx`, on a canvas of its size.
function recoloured(im, fx) {
const c = document.createElement("canvas");
c.width = im.naturalWidth;
c.height = im.naturalHeight;
const g = c.getContext("2d");
g.drawImage(im, 0, 0);
let px;
try {
px = g.getImageData(0, 0, c.width, c.height);
} catch (e) {
return im;
}
const d = px.data;
for (let i = 0; i < d.length; i += 4) {
const o = AniCraft.applyEffect(fx, [d[i] / 255, d[i + 1] / 255, d[i + 2] / 255, d[i + 3] / 255]);
d[i] = Math.round(o[0] * 255);
d[i + 1] = Math.round(o[1] * 255);
d[i + 2] = Math.round(o[2] * 255);
d[i + 3] = Math.round(o[3] * 255);
}
g.putImageData(px, 0, 0);
return c;
}
function draw() {
const stack = [{ ctx: ctx, canvas: canvas }];
const masks = new Map();
@@ -153,7 +182,7 @@
const style = paintStyle(g, it.f, it.c);
if (style) {
const bitmap = movie.paints[it.f] && movie.paints[it.f].b !== undefined;
g.globalAlpha = bitmap ? Math.min(Math.max(it.c[0], 0), 1) : 1;
g.globalAlpha = bitmap && !AniCraft.recolours(it.c) ? Math.min(Math.max(it.c[3], 0), 1) : 1;
set(g, it.m);
g.fillStyle = style;
// A bitmap without Allow Smoothing keeps hard pixel edges (ADR 0050).
+26 -14
View File
@@ -26,7 +26,7 @@ var AniCraft = (function () {
const ROOT = 0, GRAPHIC = 1, CLIP = 2, BUTTON = 3;
const KINDS = { graphic: GRAPHIC, movieclip: CLIP, button: BUTTON };
const I = [1, 0, 0, 1, 0, 0];
const NO_EFFECT = [1, 1, 1, 1, 0];
const NO_EFFECT = [1, 1, 1, 1, 0, 0, 0, 0];
const EMPTY = { l: [] };
// ----- geometry ------------------------------------------------------------------------------
@@ -60,18 +60,29 @@ var AniCraft = (function () {
return mul(mul(mul([1, 0, 0, 1, q.tx, q.ty], [c, s, -s, c, 0, 0]), [1, 0, q.k, 1, 0, 0]), [q.sx, 0, 0, q.sy, 0, 0]);
}
// ----- colour effects: [alpha, tint r, g, b, tint amount] ---------------------------------------
// ----- colour effects (ADR 0056): [r, g, b, a multipliers, r, g, b, a offsets] --------------------
// ColorEffect::concat: tints keep the stronger one; alpha multiplies.
// ColorTransform::concat: `o` applied after `i`, exactly.
function concat(o, i) {
const t = i[4] >= o[4] ? i : o;
return [o[0] * i[0], t[1], t[2], t[3], t[4]];
const out = new Array(8);
for (let k = 0; k < 4; k++) {
out[k] = o[k] * i[k];
out[k + 4] = o[k] * i[k + 4] + o[k + 4];
}
return out;
}
// ColorEffect::apply on straight [r, g, b, a].
// ColorTransform::apply on straight [r, g, b, a], clamped.
function applyEffect(fx, c) {
const k = Math.min(Math.max(fx[4], 0), 1);
const a = Math.min(Math.max(fx[0], 0), 1);
return [c[0] + (fx[1] - c[0]) * k, c[1] + (fx[2] - c[1]) * k, c[2] + (fx[3] - c[2]) * k, c[3] * a];
const out = new Array(4);
for (let k = 0; k < 4; k++) {
const v = c[k] * fx[k] + fx[k + 4];
out[k] = Number.isFinite(v) ? Math.min(Math.max(v, 0), 1) : 0;
}
return out;
}
// Whether it does more than multiply alpha (a bitmap then needs its pixels recoloured).
function recolours(fx) {
return fx[0] !== 1 || fx[1] !== 1 || fx[2] !== 1 || fx[4] !== 0 || fx[5] !== 0 || fx[6] !== 0 || fx[7] !== 0;
}
// ----- dictionaries ------------------------------------------------------------------------------
@@ -194,7 +205,7 @@ var AniCraft = (function () {
}
if (ov.alpha !== undefined) {
fx = (fx || NO_EFFECT).slice();
fx[0] = ov.alpha;
fx[3] = ov.alpha;
}
return { m: m, c: fx || NO_EFFECT };
}
@@ -231,7 +242,7 @@ var AniCraft = (function () {
const local = kind === GRAPHIC ? e.g || 0 : kind === CLIP ? clipFrame(st, key, len) : buttonFrame(st, path, len);
const idx = out.length;
const nxf = mul(lxf, m);
out.push({ path: path, key: key, parent: parent, owner: owner, name: e.n || "", sym: e.y, kind: kind, frame: local, frames: len, xf: nxf, local: e.m || I, alpha: e.c ? e.c[0] : 1, hittable: hit && shown, events: e.ev || null, gain: gain });
out.push({ path: path, key: key, parent: parent, owner: owner, name: e.n || "", sym: e.y, kind: kind, frame: local, frames: len, xf: nxf, local: e.m || I, alpha: e.c ? e.c[3] : 1, hittable: hit && shown, events: e.ev || null, gain: gain });
// A graphic's contents belong to the timeline the graphic is on.
walk(M, st, sym.tl, local, idx, kind === GRAPHIC ? owner : idx, nxf, depth + 1, hit && shown, out);
}
@@ -325,13 +336,14 @@ var AniCraft = (function () {
// Outside the player (a button's hit area): movie clips where the timeline has them,
// buttons on Up.
else local = sym.kind === CLIP ? e.af || 0 : 0;
const fade = Math.min(Math.max(fx[0], 0), 1);
// Alpha alone fades the instance as one; an alpha offset stays on each item.
const fade = fx[7] === 0 ? Math.min(Math.max(fx[3], 0), 1) : 1;
const blend = e.bl || "normal";
let color = concat(cx.c, fx), group = cx.group;
if (masks === null && (fade < 1 - 1e-4 || blend !== "normal" || e.fx)) {
group = dl.groups.length;
dl.groups.push({ parent: cx.group, alpha: fade, blend: blend, clip: clip });
color = concat(cx.c, [1, fx[1], fx[2], fx[3], fx[4]]);
color = concat(cx.c, fx[7] === 0 ? [fx[0], fx[1], fx[2], 1, fx[4], fx[5], fx[6], 0] : fx);
}
if (v && group !== cx.group) v.groupBegin(group, dl.groups[group]);
const inner = { xf: xf, c: color, depth: cx.depth + 1, clip: clip, masks: masks, group: group };
@@ -1655,5 +1667,5 @@ var AniCraft = (function () {
return s.replace(/[A-Z]/g, (c) => c.toLowerCase());
}
return { Player: Player, evaluate: evaluate, applyEffect: applyEffect, mul: mul, meanScale: meanScale, finite: finite };
return { Player: Player, evaluate: evaluate, applyEffect: applyEffect, recolours: recolours, mul: mul, meanScale: meanScale, finite: finite };
})();
+7 -6
View File
@@ -1,7 +1,7 @@
use super::*;
use anicraft_doc::actions::{ButtonEvent, EventHandler, PluginScript, Property, Target};
use anicraft_doc::player::{Event, NoScripts, PlayerState, start, step};
use anicraft_doc::{ElementId, GradientStop, Keyframe, LayerId, LoopMode, Scene, Shape, Symbol, Tween, evaluate_player, sample};
use anicraft_doc::{ColorEffect, ColorTransform, ElementId, GradientStop, Keyframe, LayerId, LoopMode, Scene, Shape, Symbol, Tween, evaluate_player, sample};
use anicraft_geom::Vec2;
use boa_engine::{Context, Source};
@@ -65,7 +65,7 @@ fn fixture() -> Document {
let knob = symbol(200, SymbolKind::Button, vec![layer(201, vec![kf(0, 1, vec![rect(2001, -20.0, -20.0, 40.0, 40.0, 0x3d8bfd)], vec![], ""), kf(1, 1, vec![rect(2002, -20.0, -20.0, 40.0, 40.0, 0x6aa8ff)], vec![], ""), kf(2, 1, vec![rect(2003, -20.0, -20.0, 40.0, 40.0, 0x2a64c0)], vec![], ""), kf(3, 1, vec![rect(2004, -25.0, -25.0, 50.0, 50.0, 0)], vec![], "")])]);
// A looping three-frame graphic.
let mut red = (*rect(3001, 0.0, 0.0, 30.0, 30.0, 0xff0000)).clone();
red.color = ColorEffect { alpha: 0.8, tint: Rgba::hex(0xffffff), tint_amount: 0.2 };
red.color = ColorEffect::Brightness(0.2).with_alpha(0.8);
let blink = symbol(300, SymbolKind::Graphic, vec![layer(301, vec![kf(0, 1, vec![Arc::new(red)], vec![], ""), kf(1, 1, vec![rect(3002, 0.0, 0.0, 30.0, 30.0, 0x00ff00)], vec![], ""), kf(2, 1, vec![rect(3003, 0.0, 0.0, 30.0, 30.0, 0x0000ff)], vec![], "")])]);
// A panel clip holding its own door (panel.door), that plays on and talks to its parent.
let panel = symbol(400, SymbolKind::MovieClip, vec![
@@ -83,12 +83,13 @@ fn fixture() -> Document {
on(ButtonEvent::Release, vec![Action::GotoAndStop { target: Target::new("panel"), frame: FrameRef::Number(99), scene: None }]),
];
let mut faded = (*inst(5003, 300, "", Affine::translate(500.0, 40.0), vec![])).clone();
faded.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x00ffff), tint_amount: 0.6 };
// Advanced, with an alpha offset (it stays on each item: no group fade).
faded.color = ColorEffect::Advanced(ColorTransform { mul: [0.4, 0.4, 0.4, 0.5], add: [0.0, 0.6, 0.6, 0.1] });
let gradient = Arc::new(Element {
id: ElementId(5004),
name: String::new(),
transform: Affine::translate(20.0, 300.0),
color: ColorEffect { alpha: 1.0, tint: Rgba::hex(0xff00ff), tint_amount: 0.25 },
color: ColorEffect::Tint { color: Rgba::hex(0xff00ff), amount: 0.25 },
kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 100.0, 40.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(100.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xffffff) }, GradientStop { offset: 1.0, color: Rgba::hex(0x000000) }] }).with_stroke(Rgba::hex(0xffff00), 2.0)),
});
let mut mask = Layer::new(LayerId(6), "mask");
@@ -278,7 +279,7 @@ fn same_display_list(js: &mut Js, m: &Movie, doc: &Document, st: &PlayerState, w
}
assert_eq!(a["s"].is_array(), b.stroke.is_some(), "{when}: item {k} stroke");
let c = &a["c"];
for (i, y) in [b.color.alpha, b.color.tint.r, b.color.tint.g, b.color.tint.b, b.color.tint_amount].into_iter().enumerate() {
for (i, y) in b.color.mul.into_iter().chain(b.color.add).enumerate() {
assert!(close(c[i].as_f64().unwrap(), y, 1e-3), "{when}: item {k} colour effect {c} vs {:?}", b.color);
}
let idx = |v: &Value| v.as_u64().map(|x| x as u32);
@@ -633,7 +634,7 @@ fn sounds_carry_their_envelopes_and_volumes_and_start_in_graphics_and_clips_as_i
#[test]
fn hostile_documents_export_without_panicking() {
let mut doc = Document::default();
let bad = Element { id: ElementId(5), name: "x".into(), transform: Affine { m: [f32::NAN, 0.0, 0.0, 1.0, f32::INFINITY, 0.0] }, color: ColorEffect { alpha: f32::NAN, tint: Rgba::new(f32::NAN, 2.0, -1.0, 1.0), tint_amount: f32::INFINITY }, kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, f32::NAN, 1.0), Paint::Radial { center: Vec2::ZERO, radius: -5.0, stops: vec![GradientStop { offset: f32::NAN, color: Rgba::BLACK }] })) };
let bad = Element { id: ElementId(5), name: "x".into(), transform: Affine { m: [f32::NAN, 0.0, 0.0, 1.0, f32::INFINITY, 0.0] }, color: ColorEffect::Advanced(ColorTransform { mul: [f32::NAN, 2.0, -1.0, f32::INFINITY], add: [f32::NAN, 0.0, 0.0, 0.0] }), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, f32::NAN, 1.0), Paint::Radial { center: Vec2::ZERO, radius: -5.0, stops: vec![GradientStop { offset: f32::NAN, color: Rgba::BLACK }] })) };
let fine = Element { id: ElementId(6), transform: Affine::IDENTITY, ..bad.clone() };
let missing = inst(7, 12345, "ghost", Affine::IDENTITY, vec![]);
Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = vec![Arc::new(bad), Arc::new(fine), missing];
+45 -5
View File
@@ -13,7 +13,7 @@ pub mod html;
pub mod lottie;
pub mod svg;
use anicraft_doc::{BlendMode, ColorEffect, DisplayItem, DisplayList, Document, Paint, Rgba, evaluate};
use anicraft_doc::{BlendMode, ColorTransform, DisplayItem, DisplayList, Document, Paint, Rgba, evaluate};
use anicraft_geom::{Affine, FillRule, Rect, Vec2};
use paint::{Premul, Shader, premultiply};
use raster::{Coverage, IRect};
@@ -836,7 +836,7 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
// Caps, joins, dashes (ADR 0046) and width profiles (ADR 0018); thin strokes and
// sub-pixel dash patterns fade instead of dropping out.
let (polys, alpha) = stroke::stroke_geometry(&lines, st, &m, true)?;
let fx = ColorEffect { alpha: item.color.alpha * alpha, ..item.color };
let fx = ColorTransform::alpha(alpha).concat(&item.color);
Some((polys, Shader::new(&Paint::Solid(st.color), &m, &fx, None)))
});
if let Some(fill) = &item.fill {
@@ -920,7 +920,7 @@ mod tests {
fill: Some(fill),
stroke: None,
fill_rule: FillRule::NonZero,
color: ColorEffect::default(),
color: ColorTransform::IDENTITY,
layer: LayerId(0),
element: ElementId(0),
outline: None,
@@ -966,6 +966,46 @@ mod tests {
assert!((alpha_sum(&pm2) - (800.0 + area / 2.0)).abs() < 8.0, "{}", alpha_sum(&pm2));
}
#[test]
fn colour_transforms_apply_to_solids_gradients_and_bitmaps_alike() {
// ADR 0056: each straight channel c·mul + add, clamped, on every kind of paint.
let fx = ColorTransform { mul: [-1.0, 0.5, 1.0, 0.8], add: [1.0, 0.25, -0.5, 0.0] };
let want = |c: Rgba| {
let o = fx.apply(c);
[o.r * o.a, o.g * o.a, o.b * o.a, o.a]
};
let near = |p: [f32; 4], q: [f32; 4]| p.iter().zip(q).all(|(a, b)| (a - b).abs() < 2e-3);
let c = Rgba::new(0.2, 0.6, 0.9, 1.0);
// Solid.
let mut solid = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(c));
solid.color = fx;
let (pm, _) = render(&list(vec![solid]), &view(4, 4)).unwrap();
assert!(near(pm.pixel(2, 2).unwrap(), want(c)), "{:?} vs {:?}", pm.pixel(2, 2), want(c));
// A two-stop gradient of one colour is that colour, through the transform.
let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: c }, anicraft_doc::GradientStop { offset: 1.0, color: c }];
let mut grad = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(4.0, 0.0), stops });
grad.color = fx;
let (pm, _) = render(&list(vec![grad]), &view(4, 4)).unwrap();
assert!(near(pm.pixel(1, 2).unwrap(), want(c)));
// A bitmap of one colour, sampled anywhere.
let px = Arc::new(anicraft_doc::Pixels { width: 2, height: 2, rgba: [51u8, 153, 230, 255].repeat(4) });
let b = Rgba::new(51.0 / 255.0, 153.0 / 255.0, 230.0 / 255.0, 1.0);
let mut bmp = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY });
bmp.image = Some(px);
bmp.color = fx;
let (pm, _) = render(&list(vec![bmp]), &view(4, 4)).unwrap();
assert!(near(pm.pixel(1, 1).unwrap(), want(b)), "{:?} vs {:?}", pm.pixel(1, 1), want(b));
// Nested transforms compose exactly: drawing through the composition is drawing through
// one then the other.
let inner = ColorTransform::tint(Rgba::new(1.0, 0.0, 0.0, 1.0), 0.5);
let outer = ColorTransform::brightness(-0.4);
let mut nested = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(c));
nested.color = outer.concat(&inner);
let (pm, _) = render(&list(vec![nested]), &view(4, 4)).unwrap();
let o = outer.apply(inner.apply(c));
assert!(near(pm.pixel(2, 2).unwrap(), [o.r, o.g, o.b, 1.0]));
}
#[test]
fn groups_fade_as_one() {
// A red square under a blue one, overlapping, in a group at 50% over white.
@@ -983,8 +1023,8 @@ mod tests {
// Fading each square on its own would let the red show through the blue.
let (mut r2, mut b2) = (red, blue);
(r2.group, b2.group) = (None, None);
r2.color.alpha = 0.5;
b2.color.alpha = 0.5;
r2.color = ColorTransform::alpha(0.5);
b2.color = ColorTransform::alpha(0.5);
let (each, _) = render(&list(vec![r2, b2]), &white).unwrap();
assert!(each.pixel(6, 1).unwrap()[0] > 0.2, "per-shape fading mixes in red");
// Nested groups multiply; a group with a bad parent link is a top-level group.
+22 -1
View File
@@ -4,7 +4,8 @@
//! Frame-accurate rather than re-keyed: each frame is evaluated, and every piece of artwork
//! that persists from frame to frame (same layer, element and path structure) becomes one
//! shape layer, its outline baked into stage space. Whatever changes (outline, colours,
//! gradient points, stroke width, opacity, masks) is written as hold keyframes at the frames
//! gradient points, stroke width, opacity, masks; colour effects of every style are baked into
//! the colours, ADR 0056) is written as hold keyframes at the frames
//! where it changes, so any Lottie player shows exactly AniCraft's frames. Strokes keep their
//! caps, joins, miter limit and dashes (dash lengths scaled like the width, dots as zero-length
//! round dashes; ADR 0046); variable-width strokes are filled outlines (the polygons the
@@ -674,6 +675,26 @@ mod tests {
assert!(part["layers"].as_array().unwrap().iter().all(|l| l["ty"] == 4), "transparent: no stage layer");
}
#[test]
fn every_colour_effect_style_is_baked_into_the_colours() {
// ADR 0056: Lottie has no colour transform, so the effect is in each fill colour (and
// tweening effects become colour keyframes); nothing is reported lost.
use anicraft_doc::{ColorEffect, ColorTransform, Document, Element, ElementId, ElementKind, Shape};
let mut doc = Document::default();
let fx = ColorEffect::Advanced(ColorTransform { mul: [-1.0, 0.5, 1.0, 1.0], add: [1.0, 0.0, 0.0, 0.0] });
let shape = Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::new(0.2, 0.4, 0.6, 1.0)));
let el = Element { id: ElementId(77), name: String::new(), transform: Affine::IDENTITY, color: fx, kind: ElementKind::Shape(shape) };
let layer = std::sync::Arc::make_mut(&mut doc.timeline_mut(0).layers[0]);
layer.keyframe_mut(0).unwrap().elements.push(std::sync::Arc::new(el));
let e = to_lottie(&doc, "fx", 0, 0, false);
let v = parse(&e);
let it = v["layers"][0]["shapes"][0]["it"].as_array().unwrap();
let fill = it.iter().find(|i| i["ty"] == "fl").expect("a fill");
let c: Vec<f64> = fill["c"]["k"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
assert!((c[0] - 0.8).abs() < 1e-3 && (c[1] - 0.2).abs() < 1e-3 && (c[2] - 0.6).abs() < 1e-3, "{c:?}");
assert!(e.report.is_empty(), "nothing lost: {:?}", e.report);
}
#[test]
fn variable_width_strokes_export_as_filled_outlines() {
use anicraft_doc::{Document, Element, ElementId, ElementKind, ProfilePreset, Shape, Stroke};
+17 -17
View File
@@ -1,6 +1,6 @@
//! Paint shaders: solid colours and gradients evaluated per pixel through a 256-entry LUT.
use anicraft_doc::{ColorEffect, GradientStop, Paint, Pixels, Rgba};
use anicraft_doc::{ColorTransform, GradientStop, Paint, Pixels, Rgba};
use std::sync::Arc;
use anicraft_geom::{Affine, Vec2};
@@ -20,7 +20,7 @@ pub enum Shader {
Radial { inv: Affine, center: Vec2, inv_radius: f32, lut: Box<[Premul; LUT]> },
/// Samples of a bitmap: `inv` maps pixels back to the bitmap's own pixel grid. Bilinear
/// when `smooth` (Allow Smoothing, ADR 0050), else the nearest pixel.
Bitmap { inv: Affine, pixels: Arc<Pixels>, repeat: bool, fx: ColorEffect, smooth: bool },
Bitmap { inv: Affine, pixels: Arc<Pixels>, repeat: bool, fx: ColorTransform, smooth: bool },
/// Premultiplied pixels already in surface space (a filtered group): `w` wide, its top-left
/// at `(x0, y0)`; transparent outside.
Image { data: Arc<Vec<Premul>>, x0: i32, y0: i32, w: usize },
@@ -42,7 +42,7 @@ fn sample_stops(stops: &[GradientStop], t: f32) -> Rgba {
stops.last().map_or(first.color, |s| s.color)
}
fn build_lut(stops: &[GradientStop], fx: &ColorEffect) -> Box<[Premul; LUT]> {
fn build_lut(stops: &[GradientStop], fx: &ColorTransform) -> Box<[Premul; LUT]> {
let mut sorted: Vec<GradientStop> = stops.iter().copied().filter(|s| s.offset.is_finite()).collect();
sorted.sort_by(|a, b| a.offset.total_cmp(&b.offset));
let mut lut = Box::new([[0.0; 4]; LUT]);
@@ -56,7 +56,7 @@ fn build_lut(stops: &[GradientStop], fx: &ColorEffect) -> Box<[Premul; LUT]> {
impl Shader {
/// `to_pixel` maps the paint's local space to pixels.
/// `image` holds a [`Paint::Bitmap`]'s pixels (an image that can't be read shows grey).
pub fn new(paint: &Paint, to_pixel: &Affine, fx: &ColorEffect, image: Option<&Arc<Pixels>>) -> Shader {
pub fn new(paint: &Paint, to_pixel: &Affine, fx: &ColorTransform, image: Option<&Arc<Pixels>>) -> Shader {
let inv = to_pixel.inverse();
match (paint, inv) {
(Paint::Solid(c), _) => Shader::Solid(premultiply(fx.apply(*c))),
@@ -128,7 +128,7 @@ impl Shader {
/// A sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), bilinear when
/// `smooth`, else the pixel `q` is in, with the colour effect applied and premultiplied.
/// Outside a non-repeating bitmap: transparent.
fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorEffect) -> Premul {
fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorTransform) -> Premul {
let (w, h) = (px.width as f32, px.height as f32);
if !(q.x.is_finite() && q.y.is_finite()) || w < 1.0 || h < 1.0 {
return [0.0; 4];
@@ -173,12 +173,12 @@ mod tests {
end: Vec2::new(100.0, 0.0),
stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }],
};
let s = Shader::new(&paint, &Affine::IDENTITY, &ColorEffect::default(), None);
let s = Shader::new(&paint, &Affine::IDENTITY, &ColorTransform::default(), None);
assert!(s.at(0, 0)[0] < 0.02);
assert!(s.at(99, 0)[0] > 0.98);
assert!((s.at(49, 0)[0] - 0.5).abs() < 0.02);
// gradient follows the transform
let s2 = Shader::new(&paint, &Affine::scale(2.0, 1.0), &ColorEffect::default(), None);
let s2 = Shader::new(&paint, &Affine::scale(2.0, 1.0), &ColorTransform::default(), None);
assert!((s2.at(99, 0)[0] - 0.5).abs() < 0.02);
}
@@ -188,8 +188,8 @@ mod tests {
// without smoothing, each half is one flat colour up to the edge between them.
let px = Arc::new(Pixels { width: 2, height: 1, rgba: vec![0, 0, 0, 255, 255, 255, 255, 255] });
let paint = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY };
let smooth = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px));
let hard = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px)).smoothed(false);
let smooth = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorTransform::default(), Some(&px));
let hard = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorTransform::default(), Some(&px)).smoothed(false);
assert!(smooth.at(9, 5)[0] > 0.3 && smooth.at(9, 5)[0] < 0.7, "{:?}", smooth.at(9, 5));
assert_eq!(hard.at(9, 5), [0.0, 0.0, 0.0, 1.0]);
assert_eq!(hard.at(10, 5), [1.0, 1.0, 1.0, 1.0]);
@@ -197,39 +197,39 @@ mod tests {
assert_eq!(hard.at(19, 9), [1.0, 1.0, 1.0, 1.0]);
assert_eq!(hard.at(20, 5), [0.0; 4], "outside stays transparent");
// Solid shaders ignore it.
assert!(Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorEffect::default(), None).smoothed(false).is_solid().is_some());
assert!(Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorTransform::default(), None).smoothed(false).is_solid().is_some());
}
#[test]
fn bitmaps_sample_bilinear_once_or_tiled() {
// 2×1: black, white.
let px = Arc::new(Pixels { width: 2, height: 1, rgba: vec![0, 0, 0, 255, 255, 255, 255, 255] });
let once = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px));
let once = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorTransform::default(), Some(&px));
let r = |s: &Shader, x| s.at(x, 3)[0];
assert!(r(&once, 0) < 0.01, "the black pixel");
assert!(r(&once, 19) > 0.99, "the white pixel");
assert!((r(&once, 9) - 0.45).abs() < 0.06, "blended across the seam: {}", r(&once, 9));
assert_eq!(once.at(25, 3), [0.0; 4], "nothing past the edge");
let tiled = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px));
let tiled = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorTransform::default(), Some(&px));
assert!(r(&tiled, 25) < 0.2 && r(&tiled, 35) > 0.8, "tiles repeat");
assert!(r(&tiled, 21) > 0.2, "and blend across the wrap-around seam");
// Opacity applies, premultiplied; a missing image is grey, not a crash.
let half = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorEffect { alpha: 0.5, ..Default::default() }, Some(&px));
let half = Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }, &Affine::scale(10.0, 10.0), &ColorTransform::alpha(0.5), Some(&px));
assert!((half.at(19, 3)[3] - 0.5).abs() < 1e-3 && (half.at(19, 3)[0] - 0.5).abs() < 1e-2);
assert!(Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(9), repeat: false, matrix: Affine::IDENTITY }, &Affine::IDENTITY, &ColorEffect::default(), None).is_solid().is_some());
assert!(Shader::new(&Paint::Bitmap { bitmap: anicraft_doc::BitmapId(9), repeat: false, matrix: Affine::IDENTITY }, &Affine::IDENTITY, &ColorTransform::default(), None).is_solid().is_some());
// The fill's image matrix places the image inside the shape: here 10× larger, from x = 40.
let placed = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine { m: [10.0, 0.0, 0.0, 10.0, 40.0, 0.0] } };
let placed = Shader::new(&placed, &Affine::IDENTITY, &ColorEffect::default(), Some(&px));
let placed = Shader::new(&placed, &Affine::IDENTITY, &ColorTransform::default(), Some(&px));
assert_eq!(placed.at(30, 3), [0.0; 4], "before the image");
assert!(r(&placed, 42) < 0.01 && r(&placed, 57) > 0.99, "black then white, 10 px each");
// A collapsed image matrix shows nothing rather than dividing by zero.
let flat = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine { m: [0.0; 6] } };
assert_eq!(Shader::new(&flat, &Affine::IDENTITY, &ColorEffect::default(), Some(&px)).at(3, 3), [0.0; 4]);
assert_eq!(Shader::new(&flat, &Affine::IDENTITY, &ColorTransform::default(), Some(&px)).at(3, 3), [0.0; 4]);
}
#[test]
fn alpha_effect_premultiplies() {
let s = Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorEffect { alpha: 0.5, ..Default::default() }, None);
let s = Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorTransform::alpha(0.5), None);
assert_eq!(s.at(0, 0), [0.5, 0.5, 0.5, 0.5]);
}
}
+49 -9
View File
@@ -6,7 +6,8 @@
//! way (`stroke-dasharray`, `stroke-dashoffset`; dots are zero-length round-capped dashes),
//! as the renderer measures them (ADR 0046);
//! * gradients keep their local geometry under a `gradientTransform`, padded at the ends;
//! * colour effects (alpha, tint) are baked into every colour and stop;
//! * colour effects (every style, ADR 0056) are baked into every colour and stop, and drawn
//! on bitmaps through an `feColorMatrix` (alpha alone as `fill-opacity`);
//! * masks become `clipPath`s (fill areas only, nested through `clip-path` on the clip), and an
//! empty mask clips everything, as on the stage;
//! * outline-mode layers are hairlines in the layer colour;
@@ -15,7 +16,7 @@
//! The output is deterministic and contains only generated ids and numbers, so it needs no
//! escaping.
use anicraft_doc::{ColorEffect, DisplayItem, DisplayList, Paint, Rgba, Stage};
use anicraft_doc::{ColorTransform, DisplayItem, DisplayList, Paint, Rgba, Stage};
use anicraft_geom::{Affine, FillRule};
use std::fmt::Write;
@@ -340,7 +341,7 @@ fn effect_svg(f: &anicraft_doc::Filter, i: usize, prims: &mut String) {
/// The fill attribute for `paint`, defining a gradient in `defs` when needed. `None` when the
/// paint draws nothing.
fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n: &mut usize, image: Option<(&std::sync::Arc<anicraft_doc::Pixels>, bool)>, images: &mut Vec<(usize, bool, String)>) -> Option<String> {
fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorTransform, defs: &mut String, n: &mut usize, image: Option<(&std::sync::Arc<anicraft_doc::Pixels>, bool)>, images: &mut Vec<(usize, bool, String)>) -> Option<String> {
let stops = match paint {
Paint::Solid(c) => {
let c = fx.apply(*c).sanitized();
@@ -350,7 +351,6 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n
Paint::Bitmap { matrix, .. } => {
// A pattern of the bitmap at its own pixel size, placed by the shape's transform
// and the fill's image matrix.
// (Opacity comes across; tint has no SVG equivalent and is left out.)
// Without Allow Smoothing (ADR 0050) the image keeps hard pixel edges.
let (px, smooth) = image?;
let key = std::sync::Arc::as_ptr(px) as usize;
@@ -367,10 +367,35 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n
};
let id = format!("p{n}");
*n += 1;
// A colour effect beyond alpha is a colour matrix on the image's pixels (ADR 0056):
// the same multiply and offset per straight channel, clamped, as the renderer's.
let fxs = fx.sanitized();
let recolour = fxs.changes_colour() || fxs.add[3] != 0.0;
let filter = if recolour {
let fid = format!("cm{n}");
*n += 1;
let [mr, mg, mb, ma] = fxs.mul;
let [ar, ag, ab, aa] = fxs.add;
let _ = write!(
defs,
"<filter id=\"{fid}\" color-interpolation-filters=\"sRGB\"><feColorMatrix type=\"matrix\" values=\"{} 0 0 0 {} 0 {} 0 0 {} 0 0 {} 0 {} 0 0 0 {} {}\"/></filter>",
num(mr),
num(ar),
num(mg),
num(ag),
num(mb),
num(ab),
num(ma),
num(aa)
);
format!(" filter=\"url(#{fid})\"")
} else {
String::new()
};
let m = xf.mul(matrix).m;
let _ = write!(
defs,
"<pattern id=\"{id}\" patternUnits=\"userSpaceOnUse\" patternTransform=\"matrix({} {} {} {} {} {})\" width=\"{}\" height=\"{}\"><use href=\"#{img_id}\"/></pattern>",
"<pattern id=\"{id}\" patternUnits=\"userSpaceOnUse\" patternTransform=\"matrix({} {} {} {} {} {})\" width=\"{}\" height=\"{}\"><use href=\"#{img_id}\"{filter}/></pattern>",
num(m[0]),
num(m[1]),
num(m[2]),
@@ -380,7 +405,7 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n
px.width,
px.height
);
let a = fx.alpha.clamp(0.0, 1.0);
let a = if recolour { 1.0 } else { fxs.mul[3].clamp(0.0, 1.0) };
return Some(if a < 1.0 { format!(" fill=\"url(#{id})\" fill-opacity=\"{}\"", num(a)) } else { format!(" fill=\"url(#{id})\"") });
}
};
@@ -428,7 +453,7 @@ mod tests {
fill,
stroke: None,
fill_rule: FillRule::NonZero,
color: ColorEffect::default(),
color: ColorTransform::default(),
layer: LayerId(0),
element: ElementId(0),
outline: None,
@@ -445,12 +470,27 @@ mod tests {
Stage { width: 100, height: 50, fps: 24.0, background: Rgba::WHITE }
}
#[test]
fn bitmaps_take_colour_effects_as_a_colour_matrix() {
// ADR 0056: alpha alone is fill-opacity; anything more is an feColorMatrix on the image.
let px = Arc::new(anicraft_doc::Pixels { width: 1, height: 1, rgba: vec![10, 20, 30, 255] });
let mut b = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY }));
b.image = Some(px);
b.color = ColorTransform::alpha(0.5);
let svg = to_svg(&DisplayList { items: vec![b.clone()], ..Default::default() }, &stage());
assert!(svg.contains("fill-opacity=\"0.5\"") && !svg.contains("feColorMatrix"), "{svg}");
b.color = ColorTransform { mul: [-1.0, 0.5, 1.0, 0.8], add: [1.0, 0.25, 0.0, 0.1] };
let svg = to_svg(&DisplayList { items: vec![b], ..Default::default() }, &stage());
assert!(svg.contains("<feColorMatrix type=\"matrix\" values=\"-1 0 0 0 1 0 0.5 0 0 0.25 0 0 1 0 0 0 0 0 0.8 0.1\"/>"), "{svg}");
assert!(svg.contains("filter=\"url(#cm") && !svg.contains("fill-opacity"), "{svg}");
}
#[test]
fn shapes_strokes_and_effects_come_out_in_stage_space() {
let mut a = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::Solid(Rgba::hex(0xff0000))));
a.transform = Affine::translate(5.0, 7.0).mul(&Affine::scale(2.0, 2.0));
a.stroke = Some(Stroke::new(Rgba::BLACK, 3.0));
a.color = ColorEffect { alpha: 0.5, ..Default::default() };
a.color = ColorTransform::alpha(0.5);
a.fill_rule = FillRule::EvenOdd;
let svg = to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
assert!(svg.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"50\" viewBox=\"0 0 100 50\">"));
@@ -548,7 +588,7 @@ mod group_tests {
fill: Some(Paint::Solid(Rgba::BLACK)),
stroke: None,
fill_rule: FillRule::NonZero,
color: ColorEffect::default(),
color: ColorTransform::default(),
layer: LayerId(0),
element: ElementId(0),
outline: None,
+27 -18
View File
@@ -5,7 +5,7 @@
//! and keyframes with durations, labels and classic tweens with their ease; shapes (solid,
//! linear and radial fills, solid, dashed and dotted strokes with their caps, joints and
//! miter limit), groups (flattened), rectangle and oval
//! primitives; symbol instances with their matrix, alpha and tint, loop mode and first frame;
//! primitives; symbol instances with their matrix, colour effect (every style, ADR 0056), loop mode and first frame;
//! library symbols (graphic, movie clip, button) with their own timelines, nested to any
//! depth; bitmaps (library items, instances and bitmap fills) whose image is stored as PNG or
//! JPEG in the package; text fields, laid out with this computer's fonts (`text`, ADR 0014);
@@ -15,13 +15,13 @@
//! Everything else (sound, motion tweens with property curves, unknown filters,
//! bitmaps kept only in Animate's own storage) is counted in the report instead of guessed at,
//! and so is whatever is drawn the nearest way AniCraft can (ragged, stipple and hatched
//! strokes, reflecting gradients, advanced colour effects, …). The self-authored corpus in `tests/corpus/` covers
//! strokes, reflecting gradients, …). The self-authored corpus in `tests/corpus/` covers
//! every feature listed here, with golden renders (ADR 0035).
use crate::edges::{self, Edge};
use crate::xml::{self, Element as X};
use anicraft_doc::{
Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId,
Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, ColorTransform, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId,
Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, Language, Linkage, ScaleGrid, SourceScript,
};
use anicraft_geom::{Affine, FillRule, Path, Vec2};
@@ -408,25 +408,34 @@ impl<'a> Builder<'a> {
}
}
/// An instance's `Color`: alpha, tint, or brightness (a tint towards white or black by that
/// amount, which is the same colour change). Other channel multipliers and offsets
/// (Animate's Advanced style) keep only their alpha, and are reported.
/// An instance's `Color` (ADR 0056): Animate's style comes from which attributes it has: a
/// tint (`tintMultiplier`, `tintColor`), a brightness (`brightness`, −1..1), Advanced (any
/// channel's multiplier other than 1 or an offset, −255..255), or alpha alone. Values are
/// clamped into Animate's ranges.
fn color_effect(&mut self, c: &X) -> ColorEffect {
let mut fx = ColorEffect { alpha: c.f32("alphaMultiplier").unwrap_or(1.0).clamp(0.0, 1.0), ..ColorEffect::default() };
if let Some(t) = c.f32("tintMultiplier") {
fx.tint = color(c, "tintColor", "__none");
fx.tint_amount = t.clamp(0.0, 1.0);
let mul = |k: &str| c.f32(k).filter(|v| v.is_finite()).unwrap_or(1.0);
let off = |k: &str| c.f32(k).filter(|v| v.is_finite()).unwrap_or(0.0) / 255.0;
let alpha = mul("alphaMultiplier");
let fx = if let Some(t) = c.f32("tintMultiplier") {
let tint = ColorEffect::Tint { color: color(c, "tintColor", "__none").with_alpha(1.0), amount: t };
if alpha != 1.0 { tint.with_alpha(alpha) } else { tint }
} else if let Some(b) = c.f32("brightness").filter(|b| *b != 0.0) {
fx.tint = if b > 0.0 { Rgba::WHITE } else { Rgba::BLACK };
fx.tint_amount = b.abs().min(1.0);
let bright = ColorEffect::Brightness(b);
if alpha != 1.0 { bright.with_alpha(alpha) } else { bright }
} else {
let multiplied = ["redMultiplier", "greenMultiplier", "blueMultiplier"].iter().any(|k| c.f32(k).is_some_and(|v| v != 1.0));
let offset = ["redOffset", "greenOffset", "blueOffset", "alphaOffset"].iter().any(|k| c.f32(k).is_some_and(|v| v != 0.0));
if multiplied || offset {
self.report.skip("advanced colour effects (only alpha kept)");
let t = ColorTransform {
mul: [mul("redMultiplier"), mul("greenMultiplier"), mul("blueMultiplier"), alpha],
add: [off("redOffset"), off("greenOffset"), off("blueOffset"), off("alphaOffset")],
};
if t.changes_colour() || t.add[3] != 0.0 {
ColorEffect::Advanced(t)
} else if alpha != 1.0 {
ColorEffect::Alpha(alpha)
} else {
ColorEffect::None
}
}
fx
};
fx.sanitized()
}
fn instance(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
+1 -1
View File
@@ -169,7 +169,7 @@ fn symbols_instances_and_the_tween_between_them() {
assert_eq!((stops[1].offset, stops[1].color.a), (0.5, 0.0));
assert_eq!((*symbol, *loop_mode, *first_frame), (sym.id, LoopMode::PlayOnce, 2));
assert_eq!(inst.transform.m, [2.0, 0.0, 0.0, 2.0, 100.0, 50.0]);
assert_eq!(inst.color.alpha, 0.5);
assert_eq!(inst.color, anicraft_doc::ColorEffect::Alpha(0.5));
// Half-way through the tween (eased), the ball is between its two positions.
let dl = evaluate(&doc, 5);
let ball = dl.items.iter().find(|i| matches!(i.fill, Some(Paint::Solid(c)) if c == Rgba::hex(0xff0000))).expect("the ball renders");
+28 -8
View File
@@ -55,6 +55,7 @@ fn import(case: &str) -> (Document, Report) {
/// package uses on purpose.
const REPORTS: &[(&str, &[(&str, usize)])] = &[
("bitmaps", &[("instances of missing bitmaps", 1), ("missing bitmap files", 1)]),
("colour", &[]),
("filters", &[("unknown filters", 1)]),
(
"gradients",
@@ -76,7 +77,7 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[
("shapes", &[]),
(
"symbols",
&[("advanced colour effects (only alpha kept)", 1), ("instances of missing symbols", 1), ("missing library files", 1), ("reverse loop modes (played forward)", 1)],
&[("instances of missing symbols", 1), ("missing library files", 1), ("reverse loop modes (played forward)", 1)],
),
("text", &[("dynamic and input text fields (imported as static text)", 2), ("text fields (no fonts on this computer)", 4)]),
("tweens", &[("motion tweens (kept as keyframes)", 1), ("tween spins (turned the shortest way)", 1)]),
@@ -175,16 +176,35 @@ fn symbols_keep_their_kinds_loop_modes_and_colour_effects() {
let loops = &doc.timeline(0).layers[2].keyframes[0].elements;
let modes: Vec<(LoopMode, u32)> = loops.iter().filter_map(|e| if let ElementKind::Symbol { loop_mode, first_frame, .. } = &e.kind { Some((*loop_mode, *first_frame)) } else { None }).collect();
assert_eq!(modes, [(LoopMode::Loop, 0), (LoopMode::PlayOnce, 1), (LoopMode::SingleFrame, 2), (LoopMode::PlayOnce, 3), (LoopMode::Loop, 0)]);
let fx: Vec<_> = doc.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| (e.color.alpha, e.color.tint, e.color.tint_amount)).collect();
use anicraft_doc::Rgba;
assert_eq!(fx[0].0, 0.4);
assert_eq!((fx[1].1, fx[1].2), (Rgba::hex(0x0000ff), 0.7));
assert_eq!((fx[2].1, fx[2].2), (Rgba::WHITE, 0.6), "brightness up is a tint towards white");
assert_eq!((fx[3].1, fx[3].2), (Rgba::BLACK, 0.5), "brightness down is a tint towards black");
assert_eq!((fx[4].0, fx[4].2), (0.8, 0.0), "advanced: alpha kept");
let fx: Vec<ColorEffect> = doc.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| e.color).collect();
use anicraft_doc::{ColorEffect, ColorTransform, Rgba};
assert_eq!(fx[0], ColorEffect::Alpha(0.4));
assert_eq!(fx[1], ColorEffect::Tint { color: Rgba::hex(0x0000ff), amount: 0.7 });
assert_eq!(fx[2], ColorEffect::Brightness(0.6));
assert_eq!(fx[3], ColorEffect::Brightness(-0.5));
assert_eq!(fx[4], ColorEffect::Advanced(ColorTransform { mul: [0.2, 1.0, 1.0, 0.8], add: [0.0, 120.0 / 255.0, 0.0, 0.0] }), "advanced: every channel");
assert_eq!(doc.timeline(0).layers[1].keyframes[0].elements[0].name, "spinner", "a movie clip keeps its instance name");
}
#[test]
fn colour_effects_come_across_in_every_style() {
use anicraft_doc::{ColorEffect, ColorTransform, Rgba};
let (doc, _) = import("colour");
let fx: Vec<ColorEffect> = doc.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| e.color).collect();
assert_eq!(fx[0], ColorEffect::None);
assert_eq!(fx[1], ColorEffect::Brightness(0.5));
assert_eq!(fx[2], ColorEffect::Tint { color: Rgba::hex(0xE9C46A), amount: 0.6 });
assert_eq!(fx[3], ColorEffect::Advanced(ColorTransform { mul: [-1.0, 0.5, 1.0, 1.0], add: [1.0, 0.0, -60.0 / 255.0, 0.0] }));
assert_eq!(fx[4], ColorEffect::Alpha(0.25));
assert_eq!(fx[5], ColorEffect::Brightness(-0.4));
let pair = doc.library.iter().find(|s| s.name == "Pair").expect("Pair");
assert_eq!(pair.timeline.layers[0].keyframes[0].elements[0].color, ColorEffect::Tint { color: Rgba::hex(0xFF0000), amount: 0.5 });
let ends = |l: usize| (doc.timeline(0).layers[l].keyframes[0].elements[0].color.style(), doc.timeline(0).layers[l].keyframes[1].elements[0].color.style());
use anicraft_doc::ColorStyle;
assert_eq!(ends(1), (ColorStyle::Tint, ColorStyle::Advanced));
assert_eq!(ends(2), (ColorStyle::Brightness, ColorStyle::Brightness));
}
#[test]
fn tweens_keep_their_kinds_eases_and_hints() {
let (doc, _) = import("tweens");
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- AniCraft XFL corpus: colour effects (ADR 0056). Every style of Properties' Style menu on a
chip (None, Brightness, Tint, Advanced with a negative multiplier and offsets, Alpha), a
brightness inside a tint (nested effects compose exactly), a classic tween from a tint to
Advanced (a style change: it travels in the advanced space) and one from brightness -100 %
to +60 % (within one style: brightness itself travels). Self-authored. -->
<DOMDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" width="320" height="180" frameRate="24" backgroundColor="#FFFFFF">
<symbols>
<Include href="Chip.xml" loadImmediate="false"/>
<Include href="Pair.xml" loadImmediate="false"/>
</symbols>
<timelines>
<DOMTimeline name="Scene 1">
<layers>
<DOMLayer name="Styles" color="#4F80FF">
<frames>
<DOMFrame index="0" duration="13" keyMode="9728">
<elements>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="30" ty="40"/></matrix></DOMSymbolInstance>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="90" ty="40"/></matrix><color><Color brightness="0.5"/></color></DOMSymbolInstance>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="150" ty="40"/></matrix><color><Color tintMultiplier="0.6" tintColor="#E9C46A"/></color></DOMSymbolInstance>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="210" ty="40"/></matrix><color><Color redMultiplier="-1" redOffset="255" greenMultiplier="0.5" blueOffset="-60"/></color></DOMSymbolInstance>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="270" ty="40"/></matrix><color><Color alphaMultiplier="0.25"/></color></DOMSymbolInstance>
<DOMSymbolInstance libraryItemName="Pair" symbolType="graphic" loop="loop"><matrix><Matrix tx="60" ty="110"/></matrix><color><Color brightness="-0.4"/></color></DOMSymbolInstance>
</elements>
</DOMFrame>
</frames>
</DOMLayer>
<DOMLayer name="Style change" color="#FF4F4F">
<frames>
<DOMFrame index="0" duration="12" tweenType="motion" motionTweenSnap="true" keyMode="22017">
<elements>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="160" ty="105"/></matrix><color><Color tintMultiplier="1" tintColor="#264653"/></color></DOMSymbolInstance>
</elements>
</DOMFrame>
<DOMFrame index="12" keyMode="9728">
<elements>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="280" ty="105"/></matrix><color><Color redMultiplier="0.5" redOffset="100" greenMultiplier="0.2" blueMultiplier="-1" blueOffset="255" alphaMultiplier="0.8"/></color></DOMSymbolInstance>
</elements>
</DOMFrame>
</frames>
</DOMLayer>
<DOMLayer name="Brightness" color="#4FFF4F">
<frames>
<DOMFrame index="0" duration="12" tweenType="motion" motionTweenSnap="true" keyMode="22017">
<elements>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="160" ty="152"/></matrix><color><Color brightness="-1"/></color></DOMSymbolInstance>
</elements>
</DOMFrame>
<DOMFrame index="12" keyMode="9728">
<elements>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop"><matrix><Matrix tx="280" ty="152"/></matrix><color><Color brightness="0.6"/></color></DOMSymbolInstance>
</elements>
</DOMFrame>
</frames>
</DOMLayer>
</layers>
</DOMTimeline>
</timelines>
</DOMDocument>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Self-authored corpus symbol. -->
<DOMSymbolItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" name="Chip" itemID="00000000-0000-0000-0000-000000000501" symbolType="graphic">
<timeline>
<DOMTimeline name="Chip">
<layers>
<DOMLayer name="Layer 1" color="#4F80FF">
<frames>
<DOMFrame index="0" keyMode="9728">
<elements>
<DOMRectangleObject x="-20" y="-20" objectWidth="40" objectHeight="40"><fill><SolidColor color="#2A9D8F"/></fill></DOMRectangleObject>
</elements>
</DOMFrame>
</frames>
</DOMLayer>
</layers>
</DOMTimeline>
</timeline>
</DOMSymbolItem>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Self-authored corpus symbol: a chip tinted inside, for nested colour effects. -->
<DOMSymbolItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" name="Pair" itemID="00000000-0000-0000-0000-000000000502" symbolType="graphic">
<timeline>
<DOMTimeline name="Pair">
<layers>
<DOMLayer name="Layer 1" color="#4F80FF">
<frames>
<DOMFrame index="0" keyMode="9728">
<elements>
<DOMSymbolInstance libraryItemName="Chip" symbolType="graphic" loop="loop">
<color><Color tintMultiplier="0.5" tintColor="#FF0000"/></color>
</DOMSymbolInstance>
</elements>
</DOMFrame>
</frames>
</DOMLayer>
</layers>
</DOMTimeline>
</timeline>
</DOMSymbolItem>
@@ -0,0 +1 @@
PROXY-CS5
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

+3 -2
View File
@@ -77,8 +77,9 @@ Headless: `timeline.create_motion_tween`, `timeline.remove_tween`, `motion.set_k
* Resizing a span does not rescale its property keys yet: keys past a shortened end are kept
but not reached, and a lengthened span holds its last values.
* Motion paths drawn and edited on the stage, with orient to path, came in ADR 0030.
* Tint colour (red, green, blue), brightness and the eight Advanced properties came in ADR
0056, with one colour effect style per tween as in Animate (keys in several styles compose).
* Not yet (later PRs): dragging keys in time in the Motion Editor, ease presets with
strengths and saved custom eases, separate tint colour and brightness/advanced colour
properties, 3D rotation and position, Split Motion and joining tweens as commands, Lottie
strengths and saved custom eases, 3D rotation and position, Split Motion and joining tweens as commands, Lottie
export of property curves as eased keyframes (it exports frame-accurate hold keys today),
and importing motion tweens from XFL (`motionObjectXML`; still reported, kept as keyframes).
+115
View File
@@ -0,0 +1,115 @@
# ADR 0056: Colour effects: one colour transform for every style
* Status: accepted (2026-11-11)
* Relates to: ADR 0016 (motion tweens), ADR 0019 and 0032 (GPU stage), ADR 0027 (camera tint),
ADR 0035 (XFL corpus), ADR 0053 (mixed Properties rows), roadmap M2
## Context
An instance's colour effect was `{alpha, tint, tint_amount}`. Brightness came in as a tint towards
white or black (ADR 0035), Animate's Advanced style kept only its alpha (reported), there was no
command or Properties control for anything but alpha, nested tints composed by keeping the stronger
one, and the motion tween slice (ADR 0016) had alpha and tint amount tracks only, the tint colour
left out.
Animate's Properties offers five styles: None, Brightness, Tint, Advanced (a multiplier in percent
and an offset in −255..255 for each of red, green, blue and alpha) and Alpha. Its public
documentation (ActionScript 3 `ColorTransform`, the XFL `Color` element's attributes) describes all
of them as one operation on each straight colour channel: `c ↦ c·multiplier + offset`, clamped.
## Decision
1. **Two types, authored and drawn** (`crates/doc/src/color_effect.rs`).
* `ColorEffect` is what an element stores: an enum of the five styles with that style's values
(`Brightness(b)`, `Tint { color, amount }`, `Advanced(ColorTransform)`, `Alpha(a)`, `None`).
Properties shows the style the artist chose, and a tint keeps its colour at 0 %.
* `ColorTransform { mul: [f32; 4], add: [f32; 4] }` is what everything draws with. Each style is
a transform: brightness `b` is a tint towards white (`b > 0`) or black by `|b|`; a tint of `t`
by `k` multiplies colour channels by `1 − k` and adds `k·t`; alpha multiplies alpha.
* `DisplayItem::color` is a `ColorTransform`. Nested instances, the camera's tint and onion skin
compose by `concat`, the exact composition of the two maps (no clamp between). The old "the
stronger tint wins" rule is gone: a brightness around a tint now shows both, as in Animate.
2. **One arithmetic in every renderer.** The CPU oracle applies `clamp(c·mul + add)` to straight
colour before premultiplying (solids, gradient ramps and each bitmap sample). The GPU stage
carries a bitmap's transform as two entries of its ramp table (no new buffer, the record layout
unchanged) and applies the same expression in `fine.wgsl`; solids and gradients arrive already
transformed. Parity on the bitmap colour cases, Advanced with a negative multiplier and an
alpha offset included, is exact (0 of 3072 pixels differ). NaN multipliers or offsets draw a
channel of 0, as a NaN colour always did.
3. **Groups.** An instance whose transform only multiplies alpha still fades as one group at that
alpha. An alpha *offset* changes each item's alpha on its own, so it
stays in the items' transform and the group (for a blend or filters) is opaque.
4. **Files.** `ColorEffect` writes the fields older files have (`alpha`, `tint`, `tint_amount`,
the look as near as they can say it), so None, Alpha and Tint are written byte for byte as
before, and older builds open Brightness as the tint it looks like and Advanced as its alpha.
`style` (with `brightness`, or `multiply` and `offset` as fractions, offset 1 = 255) is added
only when those fields alone would read back as something else. A file without `style` reads as
it always looked: a tint, an alpha, both together (Advanced: alpha after tint), or none. Values
are clamped into Animate's ranges on read.
5. **Commands.** `element.set_color_effect {style?, alpha?, brightness?, tint?, tint_amount?,
red_multiplier? … alpha_offset?}` on every selected element (per layer, one undo step). The
style defaults to the one the given values belong to, else each element's own, so a change on
a mixed selection sets only that value (ADR 0053). A new style starts from the look it can keep:
Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at
0 % (switching never jumps, except to None). `element.set_alpha` (plug-ins, ActionScript's
`alpha`, tier 2 unchanged) sets the alpha multiplier and keeps the rest: None becomes Alpha;
Brightness and Tint become Advanced below 1. Element listings report `color_effect`.
6. **Classic tweens.** Within one style its values travel (a tint's colour and amount, the
brightness itself: −100 % to +100 % is 0 halfway); None meets any style as that style's rest
value; any other change of style travels in the Advanced space (multipliers and offsets
interpolated), as Animate does.
7. **Motion tweens.** New properties: `brightness`, `tint_red`/`tint_green`/`tint_blue` (0–255,
beside the existing `tint` amount), and the eight Advanced ones (`red_multiplier` …
`alpha_offset`). As in Animate a motion tween has one colour effect: the style its colour
properties are keyed in replaces the target's own (which shows while none are keyed). Keys in
several styles (older files keyed alpha and tint together, and the Motion Editor allows it)
compose into Advanced, alpha outermost, then brightness, tint, Advanced. A style's properties
start from the target's own values (a tinted target's tint keys start from its colour). The
Motion Editor lists the styles in use (Alpha when none) and adds others with **Add Colour
Effect**.
8. **Exports and import.**
* SVG: colours and stops carry the effect (as before, now every style); a bitmap fill with more
than alpha draws its image through an `feColorMatrix` (`sRGB`, the same matrix).
* HTML canvas: the exported effect is the 8-number transform; the player composes it exactly
(`player.js` mirrors `concat`) and a bitmap with more than alpha is drawn from a recoloured
copy of its pixels (cached per bitmap and effect), so the old "tints on bitmaps" report entry
is gone. JS parity with `evaluate_player` is tested under boa, Brightness, Tint and Advanced
with an alpha offset included.
* Lottie has no colour transform: every style is baked into the colours (tweens become colour
keyframes), which maps fully; bitmap fills stay unexported as before.
* XFL: a `Color` with `tintMultiplier`/`tintColor` is Tint, with `brightness` Brightness, with
any other multiplier or an offset (−255..255) Advanced, with `alphaMultiplier` alone Alpha. The
"advanced colour effects (only alpha kept)" report entry is gone. A new `colour` corpus package
(every style, a brightness around a tint, a tint-to-Advanced and a brightness tween) has goldens
and hand-worked probes; the `symbols` and `tweens` goldens were regenerated (the Advanced
instance now draws its channels; None-to-Tint now keeps the tint's colour all the way).
9. **Properties.** A **Colour effect** row with the Style menu (None, Brightness, Tint, Advanced,
Alpha), then the style's controls: an Alpha slider; a Brightness slider (−100..100 %); Tint's
colour swatch and amount; Advanced's four channel rows, multiplier (%) and signed offset. Every
row is mixed-aware (each value compared as the first element's style sees them). The camera
keeps its own tint row.
## Consequences
* One representation reaches every output; adding a sixth style (none planned) is a new
`ColorEffect` arm and a transform.
* Composition of nested effects changes for nested *tints*: older documents with a tint inside a
tint now show both, exactly, instead of the stronger one. This is Animate's behaviour.
* An older motion tween with both alpha and tint tracks looks as it did; a tint track on an
element whose tint colour was stored at 0 % (possible only through XFL import) now starts from
white.
* `Props` holds 20 values; `Property::ALL` grew from 8 to 20.
## Not in this slice
* Colour effects on the camera beyond its tint (ADR 0027).
* A per-channel colour picker for the Motion Editor's tint colour (three 0–255 tracks for now).
* Lottie bitmaps (not exported at all yet).
+2 -2
View File
@@ -16,7 +16,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. |
| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. |
| Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. |
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Brightness colour effects (as a tint towards white or black), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, advanced colour effects, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buLine truncated
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and Line truncated
| Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported. Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. |
| Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. |
| Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. |
@@ -33,7 +33,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|---|---|---|
| **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. |
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. |
| **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); ~~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); ~~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`). |
| **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); ~~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: camera colour effects beyond tint, 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); 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); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. |
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields 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; button sounds and XFL sounds later); ~~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 later) and ~~blend modes~~ ✅ on Movie Clips. |
+12
View File
@@ -369,6 +369,18 @@ mod tests {
let filters: Vec<_> = anicraft_engine::doc::Filter::KINDS.iter().map(|(k, _)| serde_json::json!({"type": k})).collect();
assert!(a.run("element.set_filters", serde_json::json!({"filters": filters})).is_some());
}));
// Each colour effect style's controls (ADR 0056), and the Motion Editor's colour rows.
for style in ["brightness", "tint", "advanced", "alpha"] {
found.extend(check(&format!("colour effect {style}"), |a, _| {
a.run("layer.select", serde_json::json!({"index": 0}));
a.run("edit.select_all", serde_json::json!({}));
assert!(a.run("element.set_color_effect", serde_json::json!({"style": style})).is_some());
}));
}
found.extend(check("motion editor colour rows", |a, _| {
a.open_panel(Some("motionedit"));
a.me_styles = vec![anicraft_engine::doc::ColorStyle::Tint, anicraft_engine::doc::ColorStyle::Advanced, anicraft_engine::doc::ColorStyle::Brightness];
}));
found.extend(check("high contrast at 200%", |a, ctx| {
let mut p = a.prefs.clone();
p.theme = crate::theme::Palette::HighContrast;
+17
View File
@@ -369,6 +369,8 @@ pub struct App {
pub me_key: Option<u32>,
pub me_drag: Option<motion_editor::MeDrag>,
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 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).
@@ -532,6 +534,7 @@ impl App {
me_key: None,
me_drag: None,
me_vscroll: 0.0,
me_styles: Vec::new(),
timeline_focus: false,
confirm: None,
skip_confirm: HashSet::new(),
@@ -824,6 +827,20 @@ impl App {
self.run("element.select", json!({"ids": [a, b]}));
}
}
Some("colour") => {
// A row of instances in each colour effect style (ADR 0056), the Advanced one
// selected: Properties shows the Style menu and its channel rows.
if let Some(ball) = self.s.doc.library.first().map(|s| s.id.0) {
self.run("edit.deselect", json!({}));
let id = |v: Option<Value>| v.and_then(|v| v["element"].as_u64()).unwrap_or(0);
let styles = [json!({"brightness": 45}), json!({"tint": "#2a9d8f", "tint_amount": 70}), json!({"alpha": 40}), json!({"style": "advanced", "red_multiplier": -100, "red_offset": 255, "green_multiplier": 60, "blue_offset": -40})];
for (i, fx) in styles.into_iter().enumerate() {
let e = id(self.run("library.place", json!({"symbol": ball, "x": 640 + 130 * i, "y": 470})));
self.run("element.select", json!({"ids": [e]}));
self.run("element.set_color_effect", fx);
}
}
}
Some("bitmap") => {
// Two placed bitmaps of different images, selected: the Bitmap row with Swap…
// says "mixed" (ADR 0053).
+16
View File
@@ -120,6 +120,7 @@ fn all_keys() -> BTreeSet<Key> {
}
add(&doc::Easing::Linear.label());
doc::Property::ALL.iter().for_each(|p| add(p.label()));
doc::ColorStyle::ALL.iter().for_each(|s| add(s.label()));
doc::ProfilePreset::ALL.iter().for_each(|p| add(p.label()));
doc::Cap::ALL.iter().for_each(|c| add(c.label()));
doc::Join::ALL.iter().for_each(|j| add(j.label()));
@@ -578,6 +579,14 @@ fn every_control_can_be_used_in_the_pseudo_locale() {
a.run("symbol.set_kind", serde_json::json!({"symbol": symbol, "kind": "movie_clip"}));
a.run("element.set_filters", serde_json::json!({"filters": [{"type": "drop_shadow"}, {"type": "gradient_glow"}]}));
}));
// Every colour effect style's controls in Properties (ADR 0056).
for style in ["brightness", "tint", "advanced", "alpha"] {
found.extend(click_everything(&format!("colour effect {style}"), |a, _| {
a.run("layer.select", serde_json::json!({"index": 0}));
a.run("edit.select_all", serde_json::json!({}));
a.run("element.set_color_effect", serde_json::json!({"style": style}));
}));
}
for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol"] {
found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel))));
}
@@ -754,6 +763,13 @@ fn screen_reader_names_are_translated_too() {
}
crate::actions_panel::open(a, crate::actions_panel::Tab::Instance);
}));
for style in ["brightness", "tint", "advanced", "alpha"] {
found.extend(untranslated_names(&format!("colour effect {style}"), |a, _| {
a.run("layer.select", serde_json::json!({"index": 0}));
a.run("edit.select_all", serde_json::json!({}));
a.run("element.set_color_effect", serde_json::json!({"style": style}));
}));
}
found.extend(untranslated_names("close guard", |a, _| {
a.run("layer.new", serde_json::json!({}));
a.close_dialog = true;
+1 -1
View File
@@ -180,7 +180,7 @@ fn main() -> eframe::Result {
}
"--help" | "-h" => {
println!( // i18n-exempt: the --help console text
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu]\n\
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu|colour]\n\
--renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\
--open shows a panel at start (handy with --screenshot for visual checks)\n\
ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\
+76 -7
View File
@@ -5,7 +5,7 @@
//! it edits (Blending only movie clips and buttons, Looping only graphics, Fill only shapes), so
//! a shape beside a movie clip never makes Blending mixed. Pure, so every row is tested here.
use anicraft_engine::doc::{Document, Element, ElementKind, Paint, Shape, SymbolKind};
use anicraft_engine::doc::{ColorEffect, Document, Element, ElementKind, Paint, Shape, SymbolKind};
use std::sync::Arc;
/// The rows whose values differ across the selection.
@@ -13,8 +13,8 @@ use std::sync::Arc;
pub struct Mixed {
pub scale: bool,
pub rotation: bool,
/// The colour effect (the Alpha row).
pub alpha: bool,
/// The colour effect's rows (ADR 0056).
pub color: ColorMixed,
/// The instances show different symbols (the Symbol row, Swap…).
pub symbol: bool,
/// Their symbols are of different types.
@@ -33,6 +33,46 @@ pub struct Mixed {
pub style: bool,
}
/// Which colour effect rows differ. Each value compares the elements as the first one's style
/// sees them (an element in another style counts as that style's value it would start from),
/// which is what a change sets on all of them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ColorMixed {
pub style: bool,
pub alpha: bool,
pub brightness: bool,
pub tint: bool,
pub tint_amount: bool,
/// Red, green, blue, alpha multipliers, then their offsets.
pub advanced: [bool; 8],
}
fn color_mixed(all: &[Arc<Element>]) -> ColorMixed {
let Some(first) = all.first() else { return ColorMixed::default() };
let style = first.color.style();
let seen: Vec<ColorEffect> = all.iter().map(|e| e.color.to_style(style)).collect();
let mut m = ColorMixed { style: differ(all.iter().map(|e| e.color.style())), ..ColorMixed::default() };
match style {
anicraft_engine::doc::ColorStyle::None => {}
anicraft_engine::doc::ColorStyle::Alpha => m.alpha = differ_f32(seen.iter().map(ColorEffect::alpha)),
anicraft_engine::doc::ColorStyle::Brightness => {
m.brightness = differ_f32(seen.iter().map(|f| if let ColorEffect::Brightness(b) = f { *b } else { 0.0 }));
}
anicraft_engine::doc::ColorStyle::Tint => {
let tints: Vec<_> = seen.iter().filter_map(|f| if let ColorEffect::Tint { color, amount } = f { Some((*color, *amount)) } else { None }).collect();
m.tint = differ(tints.iter().map(|t| t.0.to_hex()));
m.tint_amount = differ_f32(tints.iter().map(|t| t.1));
}
anicraft_engine::doc::ColorStyle::Advanced => {
let ts: Vec<_> = seen.iter().map(ColorEffect::transform).collect();
for (i, slot) in m.advanced.iter_mut().enumerate() {
*slot = differ_f32(ts.iter().map(|t| if i < 4 { t.mul.get(i).copied().unwrap_or(1.0) } else { t.add.get(i - 4).copied().unwrap_or(0.0) }));
}
}
}
m
}
/// Whether `values` holds two that differ.
fn differ<T: PartialEq>(mut values: impl Iterator<Item = T>) -> bool {
match values.next() {
@@ -76,7 +116,7 @@ pub fn of(doc: &Document, all: &[Arc<Element>]) -> Mixed {
Mixed {
scale: differ_f32(decomposed.iter().map(|d| d.sx)) || differ_f32(decomposed.iter().map(|d| d.sy)),
rotation: differ_f32(decomposed.iter().map(|d| d.rotation)),
alpha: differ_f32(all.iter().map(|e| e.color.alpha)),
color: color_mixed(all),
symbol: differ(instances().filter_map(|e| match &e.kind {
ElementKind::Symbol { symbol, .. } => Some(*symbol),
_ => None,
@@ -174,17 +214,46 @@ mod tests {
select(&mut s, &[b]);
run(&mut s, "element.set_transform", json!({"sx": 2.0}));
select(&mut s, &[a, b, g]);
assert!(mixed(&s).scale && !mixed(&s).rotation && !mixed(&s).alpha);
assert!(mixed(&s).scale && !mixed(&s).rotation && mixed(&s).color == ColorMixed::default());
select(&mut s, &[g]);
run(&mut s, "element.set_transform", json!({"rotation": 30}));
run(&mut s, "element.set_alpha", json!({"alpha": 0.5}));
select(&mut s, &[a, g]);
let m = mixed(&s);
assert!(m.rotation && m.alpha && !m.scale);
assert!(m.rotation && m.color.style && !m.scale);
// Editing a mixed row sets all: then it isn't mixed any more.
run(&mut s, "element.set_alpha", json!({"alpha": 0.25}));
run(&mut s, "element.set_transform", json!({"rotation": 0}));
assert!(!mixed(&s).alpha && !mixed(&s).rotation);
assert!(mixed(&s).color == ColorMixed::default() && !mixed(&s).rotation);
}
#[test]
fn colour_effect_rows_compare_in_the_first_ones_style() {
let (mut s, [a, b, g], _) = session();
select(&mut s, &[a]);
run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 50}));
select(&mut s, &[b]);
run(&mut s, "element.set_color_effect", json!({"tint": "#ff0000", "tint_amount": 20}));
select(&mut s, &[a, b]);
let m = mixed(&s).color;
assert!(!m.style && !m.tint && m.tint_amount);
// An element in another style differs in style, and counts as a tint of 0 % of white.
select(&mut s, &[a, g]);
let m = mixed(&s).color;
assert!(m.style && m.tint && m.tint_amount);
// Setting the amount on all makes them alike tints of their own colours.
run(&mut s, "element.set_color_effect", json!({"tint_amount": 30}));
let m = mixed(&s).color;
assert!(!m.style && !m.tint_amount && m.tint);
// Advanced: only the channel that differs.
select(&mut s, &[a, b]);
run(&mut s, "element.set_color_effect", json!({"tint_amount": 30}));
run(&mut s, "element.set_color_effect", json!({"style": "advanced"}));
assert_eq!(mixed(&s).color, ColorMixed::default(), "the same tint, as Advanced");
select(&mut s, &[b]);
run(&mut s, "element.set_color_effect", json!({"green_offset": 40}));
select(&mut s, &[a, b]);
assert_eq!(mixed(&s).color.advanced, [false, false, false, false, false, true, false, false]);
}
#[test]
+41 -10
View File
@@ -14,7 +14,7 @@
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::{Easing, MotionTween, Pin, Property, Props, Track};
use anicraft_engine::doc::{ColorStyle, Easing, MotionTween, Pin, Property, Props, Track};
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, WidgetType, pos2, vec2};
use serde_json::json;
@@ -40,12 +40,24 @@ pub enum MeDrag {
Scrub,
}
/// The motion tween at the playhead on the active layer: its first frame, length and data.
fn current(app: &App) -> Option<(u32, u32, MotionTween, Props)> {
/// The motion tween at the playhead on the active layer: its first frame, length and data, and
/// the colour effect styles it shows (ADR 0056).
fn current(app: &App) -> Option<(u32, u32, MotionTween, Props, Vec<ColorStyle>)> {
let k = app.s.active_layer()?.keyframe_at(app.s.frame)?;
let m = k.motion.clone()?;
let base = m.target_index(&k.elements).and_then(|i| k.elements.get(i)).map(|e| Props::of(e))?;
Some((k.start, k.duration, m, base))
let target = m.target_index(&k.elements).and_then(|i| k.elements.get(i))?;
let styles = m.colour_styles(&target.color);
Some((k.start, k.duration, m, Props::of(target), styles))
}
/// 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> {
let mut shown: Vec<ColorStyle> = used.iter().chain(added).copied().collect();
if shown.is_empty() {
shown.push(ColorStyle::Alpha);
}
Property::ALL.into_iter().filter(|p| p.style().is_none_or(|s| shown.contains(&s))).collect()
}
/// A readable step for grid lines across `span` (1, 2 or 5 × 10ⁿ).
@@ -106,7 +118,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
painter.rect_filled(body, 0.0, T.panel);
painter.line_segment([body.left_top(), body.right_top()], Stroke::new(1.0, T.border));
let Some((start, frames, m, base)) = current(app) else {
let Some((start, frames, m, base, used)) = current(app) else {
empty_state(app, ui, body);
return;
};
@@ -127,7 +139,11 @@ 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 n = Property::ALL.len();
let rows = listed(&used, &app.me_styles);
if !rows.contains(&app.me_prop) {
app.me_prop = Property::X;
}
let n = rows.len();
if ui.rect_contains_pointer(list) {
let d = ui.input(|i| i.smooth_scroll_delta.y);
app.me_vscroll = (app.me_vscroll - d / ROW_H).clamp(0.0, n.saturating_sub(fit) as f32);
@@ -135,7 +151,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
app.me_vscroll = app.me_vscroll.min(n.saturating_sub(fit) as f32);
let first = app.me_vscroll.floor() as usize;
let mut last_group = "";
for (r, p) in Property::ALL.into_iter().enumerate().skip(first).take(fit) {
for (r, p) in rows.iter().copied().enumerate().skip(first).take(fit) {
let y = rows_top + (r - first) as f32 * ROW_H;
let row = Rect::from_min_size(pos2(list.left(), y), vec2(LIST_W, ROW_H));
let selected = app.me_prop == p;
@@ -404,7 +420,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
None => gr.on_hover_text_at_pointer(tr!("Drag a key up or down to change it, or a handle to shape the ease. Double-click to add a key.")),
};
footer(app, ui, body, track, sel_key, start);
footer(app, ui, body, track, sel_key, start, &rows);
}
/// Whether `q` is a pin between the ends (which can be let go).
@@ -425,7 +441,7 @@ fn diamond(p: &egui::Painter, c: Pos2, r: f32, fill: Color32, stroke: Stroke) {
}
/// The ease of the selected segment, and the tween's own actions.
fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, sel_key: Option<u32>, start: u32) {
fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, sel_key: Option<u32>, start: u32, rows: &[Property]) {
let bar = Rect::from_min_max(pos2(body.left(), body.bottom() - FOOTER_H), body.right_bottom());
ui.painter().rect_filled(bar, SQUARE, T.panel_alt);
ui.painter().line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, T.border));
@@ -454,6 +470,21 @@ fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, s
}
}
ui.separator();
// Animate's "+" for colour effects: list another style's properties (keying one adds it).
let missing: Vec<ColorStyle> = [ColorStyle::Alpha, ColorStyle::Brightness, ColorStyle::Tint, ColorStyle::Advanced].into_iter().filter(|s| !rows.iter().any(|p| p.style() == Some(*s))).collect();
if !missing.is_empty() {
ui.menu_button(tr!("Add Colour Effect"), |ui| {
for st in missing {
if ui.button(crate::i18n::t(st.label())).clicked() {
app.me_styles.push(st);
app.me_prop = Property::ALL.into_iter().find(|p| p.style() == Some(st)).unwrap_or(Property::Alpha);
ui.close();
}
}
})
.response
.on_hover_text(tr!("List a colour effect style's properties here; keying one adds it to the tween"));
}
if ui.button(tr!("Remove Tween")).on_hover_text(tr!("The object stays as it is on the span's first frame ({undo} to undo)", undo = app.undo_key())).clicked() {
app.run("timeline.remove_tween", json!({}));
}
+79 -8
View File
@@ -3,7 +3,7 @@
use crate::app::{App, Tool};
use crate::icons::{self, Icon};
use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, section, text, to_color32, with_type};
use anicraft_engine::doc::{ElementKind, LibraryItem, Paint, Rgba, SymbolKind, evaluate_layer_elements};
use anicraft_engine::doc::{ColorEffect, ColorStyle, ElementKind, LibraryItem, Paint, Rgba, SymbolKind, evaluate_layer_elements};
use crate::a11y::{self, Named};
use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
use serde_json::{Value, json};
@@ -522,6 +522,81 @@ fn mixed(ui: &mut egui::Ui, differs: bool) {
}
}
/// The colour effect (ADR 0056): Animate's Style menu, then the chosen style's controls. Each
/// change sets that value on every selected element (ADR 0053), as one undo step per drag.
fn colour_effect_rows(app: &mut App, ui: &mut egui::Ui, fx: &ColorEffect, m: crate::mixed::ColorMixed) {
let current = fx.style();
row_prose(ui, tr!("Colour effect"), |ui| {
egui::ComboBox::from_id_salt("prop_color_style").selected_text(crate::i18n::t(current.label())).show_ui(ui, |ui| {
for st in ColorStyle::ALL {
if ui.selectable_label(st == current, crate::i18n::t(st.label())).clicked() && (st != current || m.style) {
app.run("element.set_color_effect", json!({"style": st.key()}));
}
}
})
.response
.set_name(tr!("Colour effect style"));
mixed(ui, m.style);
});
let pct = a11y::SliderLook { suffix: " %", max_decimals: Some(0), ..Default::default() };
let set = |app: &mut App, p: Value| live(app, tr_noop!("Colour Effect"), "element.set_color_effect", p);
match *fx {
ColorEffect::None => {}
ColorEffect::Alpha(a) => {
let mut v = a * 100.0;
row(ui, tr!("Alpha"), |ui| {
if a11y::slider(ui, &mut v, 0.0..=100.0, tr!("Alpha"), pct).changed() {
set(app, json!({"alpha": v}));
}
mixed(ui, m.alpha);
});
}
ColorEffect::Brightness(b) => {
let mut v = b * 100.0;
row(ui, tr!("Brightness"), |ui| {
if a11y::slider(ui, &mut v, -100.0..=100.0, tr!("Brightness"), pct).changed() {
set(app, json!({"brightness": v}));
}
mixed(ui, m.brightness);
});
}
ColorEffect::Tint { color, amount } => {
let mut c = rgb(color);
row(ui, tr!("Tint"), |ui| {
if ui.color_edit_button_srgb(&mut c).named(tr!("Tint colour")).changed() {
set(app, json!({"tint": hex(c)}));
}
ui.label(text(Type::Data, hex(c)));
mixed(ui, m.tint);
});
let mut v = amount * 100.0;
row(ui, tr!("Tint amount"), |ui| {
if a11y::slider(ui, &mut v, 0.0..=100.0, tr!("Tint amount"), pct).changed() {
set(app, json!({"tint_amount": v}));
}
mixed(ui, m.tint_amount);
});
}
ColorEffect::Advanced(t) => {
// Each channel: its multiplier in percent, then the offset added (−255..255).
let channels = [(tr!("Red"), tr!("Red multiplier"), tr!("Red offset"), "red"), (tr!("Green"), tr!("Green multiplier"), tr!("Green offset"), "green"), (tr!("Blue"), tr!("Blue multiplier"), tr!("Blue offset"), "blue"), (tr!("Alpha"), tr!("Alpha multiplier"), tr!("Alpha offset"), "alpha")];
for (i, (label, mul_name, off_name, key)) in channels.into_iter().enumerate() {
let mut mv = t.mul.get(i).copied().unwrap_or(1.0) * 100.0;
let mut ov = t.add.get(i).copied().unwrap_or(0.0) * 255.0;
row(ui, label, |ui| {
if ui.add(egui::DragValue::new(&mut mv).suffix(" %").speed(0.5).range(-100.0..=100.0).max_decimals(0)).named(mul_name).changed() {
set(app, json!({format!("{key}_multiplier"): mv}));
}
if ui.add(egui::DragValue::new(&mut ov).custom_formatter(|v, _| format!("{v:+.0}")).speed(1.0).range(-255.0..=255.0).max_decimals(0)).named(off_name).changed() {
set(app, json!({format!("{key}_offset"): ov}));
}
mixed(ui, m.advanced.get(i).copied().unwrap_or(false) || m.advanced.get(i + 4).copied().unwrap_or(false));
});
}
}
}
}
/// The selection's properties: `e` is the first selected element, `all` the whole selection.
fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Element, all: &[std::sync::Arc<anicraft_engine::doc::Element>]) {
let many = all.len() > 1;
@@ -571,13 +646,9 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
}
mixed(ui, m.rotation);
});
let mut alpha = e.color.alpha * 100.0;
row(ui, tr!("Alpha"), |ui| {
if a11y::slider(ui, &mut alpha, 0.0..=100.0, tr!("Alpha"), a11y::SliderLook { suffix: " %", max_decimals: Some(0), ..Default::default() }).changed() {
live(app, tr_noop!("Alpha"), "element.set_alpha", json!({"alpha": alpha / 100.0}));
}
mixed(ui, m.alpha);
});
if !matches!(e.kind, ElementKind::Camera) {
colour_effect_rows(app, ui, &e.color, m.color);
}
// Blending and filters, on movie clips and buttons as in Animate.
if let ElementKind::Symbol { symbol, filters, .. } = &e.kind
&& app.s.doc.symbol(*symbol).is_some_and(|x| x.kind != SymbolKind::Graphic)