Skip to main content

alpha2_model/
effect_spec.rs

1//! The built-in effects, transitions and generators every engine registers, as data.
2
3use std::collections::{BTreeMap, HashMap};
4use std::sync::OnceLock;
5
6use serde::Deserialize;
7
8use crate::{Animated, ClipEffect, EffectValue, NodeId};
9
10/// Id prefix of built-in effects, transitions and generators. A document id under it must name a
11/// built-in, so host effects use ids outside it.
12pub const BUILTIN_EFFECT_PREFIX: &str = "alpha2.";
13
14/// The catalog the renderer's built-ins serialize to, written by `emit-effect-catalog`.
15const CATALOG_JSON: &str = include_str!("builtin-effects.json");
16
17/// What an effect definition draws.
18#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
19#[serde(rename_all = "snake_case")]
20pub enum EffectKind {
21    /// An image effect with one source and any declared named inputs.
22    Effect,
23    /// A two-input transition at an explicit progress.
24    Transition,
25    /// A picture drawn from no input.
26    Generator,
27}
28
29/// The type of a parameter's values: the [`EffectValue`] variant it takes.
30#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
31#[serde(rename_all = "snake_case")]
32pub enum EffectParamType {
33    /// [`EffectValue::Float`].
34    Float,
35    /// [`EffectValue::Vec2`].
36    Vec2,
37    /// [`EffectValue::Vec4`].
38    Vec4,
39    /// [`EffectValue::Color`].
40    Color,
41    /// [`EffectValue::Enum`].
42    Enum,
43    /// [`EffectValue::Bool`].
44    Bool,
45}
46
47/// How a parameter's value reads in an editor.
48#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
49#[serde(rename_all = "snake_case")]
50pub enum EffectParamUnit {
51    /// A plain or normalized number: a fraction, count, rate, seed or size.
52    Normalized,
53    /// An angle in degrees.
54    Degrees,
55    /// A color.
56    Color,
57    /// One of the named choices.
58    Enum,
59    /// A toggle.
60    Bool,
61}
62
63/// One declared parameter of a built-in definition.
64#[derive(Clone, Debug, PartialEq)]
65#[non_exhaustive]
66pub struct EffectParamSpec {
67    /// The name a [`ClipEffect`] sets it by.
68    pub name: String,
69    /// A human-readable label.
70    pub label: String,
71    /// The type of its values.
72    pub param_type: EffectParamType,
73    /// The value used when a document leaves it out.
74    pub default: EffectValue,
75    /// Inclusive minimum of each scalar component.
76    pub min: Option<f32>,
77    /// Inclusive maximum of each scalar component.
78    pub max: Option<f32>,
79    /// A suggested editing increment.
80    pub step: Option<f32>,
81    /// How its value reads.
82    pub unit: EffectParamUnit,
83    /// The choices of an [`EffectParamType::Enum`]; an enum value is an index into them.
84    pub enum_values: Vec<String>,
85}
86
87impl EffectParamSpec {
88    /// Whether `value` has this parameter's type and lies in its range, as the renderer
89    /// requires of an authored value.
90    #[must_use]
91    pub fn accepts(&self, value: &EffectValue) -> bool {
92        let scalar = |value: f32| {
93            value.is_finite()
94                && self.min.is_none_or(|minimum| value >= minimum)
95                && self.max.is_none_or(|maximum| value <= maximum)
96        };
97        match (self.param_type, value) {
98            (EffectParamType::Float, EffectValue::Float(value)) => scalar(*value),
99            (EffectParamType::Vec2, EffectValue::Vec2(values)) => {
100                values.iter().all(|value| scalar(*value))
101            }
102            (EffectParamType::Vec4, EffectValue::Vec4(values)) => {
103                values.iter().all(|value| scalar(*value))
104            }
105            (EffectParamType::Color, EffectValue::Color(values)) => values
106                .iter()
107                .all(|value| value.is_finite() && (0.0..=1.0).contains(value)),
108            (EffectParamType::Enum, EffectValue::Enum(index)) => {
109                usize::try_from(*index).is_ok_and(|index| index < self.enum_values.len())
110            }
111            (EffectParamType::Bool, EffectValue::Bool(_)) => true,
112            _ => false,
113        }
114    }
115
116    /// The range of each scalar component, as [`Self::accepts`] checks it.
117    #[must_use]
118    pub const fn domain(&self) -> crate::Domain {
119        crate::Domain::new(
120            match self.min {
121                Some(min) => min,
122                None => f32::NEG_INFINITY,
123            },
124            match self.max {
125                Some(max) => max,
126                None => f32::INFINITY,
127            },
128        )
129    }
130
131    /// Whether the parameter can follow a data set, which only Float and Vec2 ones can.
132    #[must_use]
133    pub const fn takes_data(&self) -> bool {
134        matches!(
135            self.param_type,
136            EffectParamType::Float | EffectParamType::Vec2
137        )
138    }
139
140    /// Whether every authored value of `animation` is accepted, or for a data binding whether the
141    /// type takes data. Only keyframe values count, since interpolated overshoot is clamped. A
142    /// `split` value is accepted by a `vec2` parameter with two channels and a `vec4` with four.
143    #[must_use]
144    pub fn accepts_animation(&self, animation: &Animated<EffectValue>) -> bool {
145        match animation {
146            Animated::Constant { value } => self.accepts(value),
147            Animated::Keyframes { keyframes, .. } => keyframes
148                .iter()
149                .all(|keyframe| self.accepts(&keyframe.value)),
150            Animated::Split { channels } => {
151                let components = match self.param_type {
152                    EffectParamType::Vec2 => 2,
153                    EffectParamType::Vec4 => 4,
154                    _ => return false,
155                };
156                let domain = self.domain();
157                channels.len() == components
158                    && channels.iter().all(|channel| match channel {
159                        Animated::Constant { value } => domain.contains(*value),
160                        Animated::Keyframes { keyframes, .. } => keyframes
161                            .iter()
162                            .all(|keyframe| domain.contains(keyframe.value)),
163                        Animated::Data(_) => true,
164                        Animated::Split { .. } => false,
165                    })
166            }
167            Animated::Data(_) => self.takes_data(),
168        }
169    }
170}
171
172/// A built-in effect, transition or generator definition, without its shader.
173#[derive(Clone, Debug, PartialEq)]
174#[non_exhaustive]
175pub struct EffectSpec {
176    /// The id documents name it by.
177    pub id: String,
178    /// The version documents must name.
179    pub version: u32,
180    /// What it draws.
181    pub kind: EffectKind,
182    /// A human-readable label.
183    pub label: String,
184    /// The catalog group it is listed under.
185    pub group: String,
186    /// The named images it samples besides its input.
187    pub inputs: Vec<String>,
188    /// Its parameters, in declaration order.
189    pub params: Vec<EffectParamSpec>,
190    /// The external resources it reads, by slot name.
191    pub resources: Vec<String>,
192    /// Whether this transition of two pictures under one coverage (a matte or mask) equals that
193    /// coverage over their transition, for every parameter value.
194    pub coverage_commutes: bool,
195}
196
197impl EffectSpec {
198    /// The parameter named `name`.
199    #[must_use]
200    pub fn param(&self, name: &str) -> Option<&EffectParamSpec> {
201        self.params.iter().find(|param| param.name == name)
202    }
203}
204
205/// Every built-in definition: effects, then transitions, then generators, in catalog order.
206#[must_use]
207pub fn builtin_effects() -> &'static [EffectSpec] {
208    &catalog().0
209}
210
211/// The built-in definition with `id`.
212#[must_use]
213pub fn builtin_effect(id: &str) -> Option<&'static EffectSpec> {
214    let (specs, index) = catalog();
215    index.get(id).map(|position| &specs[*position])
216}
217
218/// The catalog JSON the built-ins were read from, as `schema/effects.v1.json` publishes it.
219#[must_use]
220pub const fn builtin_effects_json() -> &'static str {
221    CATALOG_JSON
222}
223
224fn catalog() -> &'static (Vec<EffectSpec>, HashMap<String, usize>) {
225    static CATALOG: OnceLock<(Vec<EffectSpec>, HashMap<String, usize>)> = OnceLock::new();
226    CATALOG.get_or_init(|| {
227        let wire: CatalogWire =
228            serde_json::from_str(CATALOG_JSON).expect("the built-in effect catalog parses");
229        let specs = wire
230            .effects
231            .into_iter()
232            .chain(wire.transitions)
233            .chain(wire.generators)
234            .map(EffectSpec::from)
235            .collect::<Vec<_>>();
236        let index = specs
237            .iter()
238            .enumerate()
239            .map(|(position, spec)| (spec.id.clone(), position))
240            .collect();
241        (specs, index)
242    })
243}
244
245/// Why a [`ClipEffect`] naming a built-in does not match it.
246#[derive(Clone, Debug, Eq, PartialEq)]
247#[non_exhaustive]
248pub enum EffectProblem {
249    /// The id is under [`BUILTIN_EFFECT_PREFIX`] but names no built-in.
250    UnknownBuiltin,
251    /// The version is not the built-in's.
252    Version {
253        /// The built-in's version.
254        expected: u32,
255    },
256    /// A definition of one kind where another belongs: an effect, a transition or a generator.
257    Kind,
258    /// A parameter the definition does not declare.
259    UnknownParam(String),
260    /// A parameter value of the wrong type or outside the declared range.
261    InvalidParam(String),
262    /// Named inputs other than exactly the declared ones.
263    Inputs,
264    /// Resources other than exactly the declared ones.
265    Resources,
266}
267
268/// Checks `effect` against its built-in definition, used as `kind`, as project validation does
269/// for a timeline transition, a generator or a node without named inputs. Ids outside
270/// [`BUILTIN_EFFECT_PREFIX`] belong to the host and pass.
271///
272/// # Errors
273/// What is wrong with the effect.
274pub fn check_builtin_effect(effect: &ClipEffect, kind: EffectKind) -> Result<(), EffectProblem> {
275    check_builtin(effect, kind, None)
276}
277
278/// Checks `effect` against its built-in definition, used as `kind`; `inputs` are an effect
279/// node's named inputs. Ids outside [`BUILTIN_EFFECT_PREFIX`] belong to the host and pass.
280pub(crate) fn check_builtin(
281    effect: &ClipEffect,
282    kind: EffectKind,
283    inputs: Option<&BTreeMap<String, Option<NodeId>>>,
284) -> Result<(), EffectProblem> {
285    if !effect.id.starts_with(BUILTIN_EFFECT_PREFIX) {
286        return Ok(());
287    }
288    let spec = builtin_effect(&effect.id).ok_or(EffectProblem::UnknownBuiltin)?;
289    if effect.version != spec.version {
290        return Err(EffectProblem::Version {
291            expected: spec.version,
292        });
293    }
294    if spec.kind != kind {
295        return Err(EffectProblem::Kind);
296    }
297    for (name, value) in &effect.params {
298        let param = spec
299            .param(name)
300            .ok_or_else(|| EffectProblem::UnknownParam(name.clone()))?;
301        if !param.accepts_animation(value) {
302            return Err(EffectProblem::InvalidParam(name.clone()));
303        }
304    }
305    let declared = |names: &[String], used: &mut dyn Iterator<Item = &String>| {
306        let used = used.collect::<Vec<_>>();
307        used.len() == names.len() && used.iter().all(|name| names.contains(name))
308    };
309    if !declared(
310        &spec.inputs,
311        &mut inputs.into_iter().flat_map(BTreeMap::keys),
312    ) {
313        return Err(EffectProblem::Inputs);
314    }
315    if !declared(&spec.resources, &mut effect.resources.keys()) {
316        return Err(EffectProblem::Resources);
317    }
318    Ok(())
319}
320
321#[derive(Deserialize)]
322struct CatalogWire {
323    effects: Vec<SpecWire>,
324    transitions: Vec<SpecWire>,
325    generators: Vec<SpecWire>,
326}
327
328#[derive(Deserialize)]
329struct SpecWire {
330    id: String,
331    version: u32,
332    kind: EffectKind,
333    label: String,
334    group: String,
335    inputs: Vec<NamedWire>,
336    params: Vec<ParamWire>,
337    resources: Vec<NamedWire>,
338    #[serde(default)]
339    coverage_commutes: bool,
340}
341
342#[derive(Deserialize)]
343struct NamedWire {
344    name: String,
345}
346
347#[derive(Deserialize)]
348#[serde(rename_all = "camelCase")]
349struct ParamWire {
350    name: String,
351    label: String,
352    #[serde(rename = "type")]
353    param_type: EffectParamType,
354    default: serde_json::Value,
355    min: Option<f32>,
356    max: Option<f32>,
357    step: Option<f32>,
358    unit: EffectParamUnit,
359    enum_values: Vec<String>,
360}
361
362impl From<SpecWire> for EffectSpec {
363    fn from(wire: SpecWire) -> Self {
364        Self {
365            id: wire.id,
366            version: wire.version,
367            kind: wire.kind,
368            label: wire.label,
369            group: wire.group,
370            inputs: wire.inputs.into_iter().map(|input| input.name).collect(),
371            params: wire.params.into_iter().map(EffectParamSpec::from).collect(),
372            resources: wire
373                .resources
374                .into_iter()
375                .map(|resource| resource.name)
376                .collect(),
377            coverage_commutes: wire.coverage_commutes,
378        }
379    }
380}
381
382impl From<ParamWire> for EffectParamSpec {
383    fn from(wire: ParamWire) -> Self {
384        let default = default_value(wire.param_type, &wire.default)
385            .unwrap_or_else(|| panic!("parameter {} has a default of its type", wire.name));
386        Self {
387            name: wire.name,
388            label: wire.label,
389            param_type: wire.param_type,
390            default,
391            min: wire.min,
392            max: wire.max,
393            step: wire.step,
394            unit: wire.unit,
395            enum_values: wire.enum_values,
396        }
397    }
398}
399
400#[allow(clippy::cast_possible_truncation)]
401fn default_value(param_type: EffectParamType, value: &serde_json::Value) -> Option<EffectValue> {
402    // The catalog widens each `f32` to `f64`; narrowing restores it exactly.
403    let numbers = |count: usize| {
404        let values = value.as_array()?;
405        (values.len() == count)
406            .then(|| {
407                values
408                    .iter()
409                    .map(|value| value.as_f64().map(|value| value as f32))
410            })?
411            .collect::<Option<Vec<f32>>>()
412    };
413    Some(match param_type {
414        EffectParamType::Float => EffectValue::Float(value.as_f64()? as f32),
415        EffectParamType::Vec2 => EffectValue::Vec2(numbers(2)?.try_into().ok()?),
416        EffectParamType::Vec4 => EffectValue::Vec4(numbers(4)?.try_into().ok()?),
417        EffectParamType::Color => EffectValue::Color(numbers(4)?.try_into().ok()?),
418        EffectParamType::Enum => EffectValue::Enum(u32::try_from(value.as_u64()?).ok()?),
419        EffectParamType::Bool => EffectValue::Bool(value.as_bool()?),
420    })
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    #[test]
428    fn every_builtin_parses_with_defaults_it_accepts() {
429        let specs = builtin_effects();
430        assert!(specs.iter().any(|spec| spec.kind == EffectKind::Effect));
431        assert!(specs.iter().any(|spec| spec.kind == EffectKind::Transition));
432        for spec in specs {
433            assert!(spec.id.starts_with(BUILTIN_EFFECT_PREFIX), "{}", spec.id);
434            assert_eq!(builtin_effect(&spec.id), Some(spec));
435            for param in &spec.params {
436                assert!(param.accepts(&param.default), "{} {}", spec.id, param.name);
437            }
438        }
439    }
440}