Skip to main content

alpha2_model/
effect.rs

1use std::collections::BTreeMap;
2
3use crate::{Animated, EffectResourceId, Interpolation};
4
5use serde::{Deserialize, Serialize};
6
7/// Blend mode, from W3C Compositing and Blending Level 1 (CSS `mix-blend-mode`) with the
8/// specification's formulas, plus `plus-lighter` from Level 2.
9#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
10#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
11#[serde(rename_all = "snake_case")]
12pub enum ClipBlendMode {
13    /// Preserve source color and apply source-over coverage.
14    #[default]
15    Normal,
16    /// Multiply source and backdrop components.
17    Multiply,
18    /// Inverse-multiply source and backdrop components.
19    Screen,
20    /// Multiply dark backdrop regions and screen light regions.
21    Overlay,
22    /// The darker of source and backdrop, per channel.
23    Darken,
24    /// The lighter of source and backdrop, per channel.
25    Lighten,
26    /// Brighten the backdrop to reflect the source.
27    ColorDodge,
28    /// Darken the backdrop to reflect the source.
29    ColorBurn,
30    /// Multiply or screen, depending on the source.
31    HardLight,
32    /// Darken or lighten, depending on the source: a diffused hard light.
33    SoftLight,
34    /// The absolute difference of source and backdrop.
35    Difference,
36    /// Like difference, with lower contrast.
37    Exclusion,
38    /// The source's hue with the backdrop's saturation and luminosity.
39    Hue,
40    /// The source's saturation with the backdrop's hue and luminosity.
41    Saturation,
42    /// The source's hue and saturation with the backdrop's luminosity.
43    Color,
44    /// The source's luminosity with the backdrop's hue and saturation.
45    Luminosity,
46    /// Source and backdrop added, premultiplied color and alpha each clamped to 1 (Add or Linear
47    /// Dodge in design tools). It replaces source-over rather than blending inside it.
48    PlusLighter,
49}
50
51/// Serializable value supplied to one runtime effect parameter.
52#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
53#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
54#[serde(deny_unknown_fields)]
55#[serde(tag = "type", content = "value", rename_all = "snake_case")]
56pub enum EffectValue {
57    /// One finite scalar.
58    Float(
59        /// The scalar.
60        f32,
61    ),
62    /// Two finite components, normally in normalized coordinates.
63    Vec2(
64        /// The components, `[x, y]`.
65        [f32; 2],
66    ),
67    /// Four finite components that are not a color, such as per-channel thresholds; they
68    /// keyframe component by component.
69    Vec4(
70        /// The four components.
71        [f32; 4],
72    ),
73    /// Straight (not premultiplied), sRGB-encoded RGBA in `0..=1`, as a color picker shows it.
74    Color(
75        /// Red, green, blue and alpha.
76        [f32; 4],
77    ),
78    /// Index into an effect definition's enum choices.
79    Enum(
80        /// The choice's index, from 0.
81        u32,
82    ),
83    /// Boolean toggle.
84    Bool(
85        /// Whether the toggle is on.
86        bool,
87    ),
88}
89
90impl EffectValue {
91    /// Whether keyframes of this type interpolate. `Enum` and `Bool` keyframes only hold.
92    #[must_use]
93    pub const fn interpolates(&self) -> bool {
94        matches!(
95            self,
96            Self::Float(_) | Self::Vec2(_) | Self::Vec4(_) | Self::Color(_)
97        )
98    }
99
100    /// Whether `other` is the same type of value.
101    #[must_use]
102    pub fn same_type(&self, other: &Self) -> bool {
103        core::mem::discriminant(self) == core::mem::discriminant(other)
104    }
105
106    pub(crate) fn is_valid(&self) -> bool {
107        match self {
108            Self::Float(value) => value.is_finite(),
109            Self::Vec2(values) => values.iter().all(|value| value.is_finite()),
110            Self::Vec4(values) => values.iter().all(|value| value.is_finite()),
111            Self::Color(values) => values
112                .iter()
113                .all(|value| value.is_finite() && (0.0..=1.0).contains(value)),
114            Self::Enum(_) | Self::Bool(_) => true,
115        }
116    }
117}
118
119/// One versioned effect invocation: a composition's effect or transition node, a timeline
120/// transition, or an effect generator.
121#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
122#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
123#[serde(deny_unknown_fields)]
124pub struct ClipEffect {
125    /// Stable effect definition identifier. Ids under `alpha2.` name built-ins
126    /// (`schema/effects.v1.json`): validation checks such an invocation's version, kind,
127    /// parameters, inputs and resources against its definition.
128    pub id: String,
129    /// Exact effect definition version required by the project.
130    pub version: u32,
131    /// Named parameter values, constant or keyframed. Omitted entries use definition defaults.
132    ///
133    /// Keyframe times are composition times in a composition node, timeline times in a
134    /// timeline transition and picture times in a generator, whose parameters take no data. A
135    /// parameter's keyframes share one value type, and `enum` and `bool` keyframes only hold.
136    /// Interpolated overshoot is clamped to the parameter's range; an authored value outside it
137    /// is an error.
138    #[serde(default)]
139    pub params: BTreeMap<String, Animated<EffectValue>>,
140    /// Named external resources matched against the effect definition.
141    #[serde(default)]
142    pub resources: BTreeMap<String, EffectResourceId>,
143}
144
145impl ClipEffect {
146    pub(crate) fn is_valid(&self) -> bool {
147        !self.id.is_empty()
148            && self.version > 0
149            && self
150                .params
151                .iter()
152                .all(|(name, value)| valid_binding_name(name) && valid_param(value))
153            && self
154                .resources
155                .iter()
156                .all(|(name, id)| valid_binding_name(name) && !id.as_str().is_empty())
157    }
158}
159
160/// Whether `name` can name a parameter, resource or named input: an ASCII letter or `_`,
161/// then letters, digits or `_`.
162pub(crate) fn valid_binding_name(name: &str) -> bool {
163    let mut bytes = name.bytes();
164    bytes
165        .next()
166        .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
167        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
168}
169
170pub(crate) fn valid_param(animation: &Animated<EffectValue>) -> bool {
171    match animation {
172        Animated::Data(_) => true,
173        Animated::Split { channels } => {
174            matches!(channels.len(), 2 | 4)
175                && crate::animation::valid_channels(channels, 2..=4, |_| true)
176        }
177        Animated::Constant { value } => value.is_valid(),
178        Animated::Keyframes {
179            keyframes,
180            before,
181            after,
182        } => {
183            let Some(first) = keyframes.first() else {
184                return false;
185            };
186            crate::animation::valid_keyframes(keyframes, *before, *after)
187                && keyframes.iter().all(|keyframe| {
188                    keyframe.value.is_valid()
189                        && keyframe.value.same_type(&first.value)
190                        && (first.value.interpolates()
191                            || keyframe.interpolation == Interpolation::Hold)
192                })
193        }
194    }
195}