Skip to main content

alpha2_render/
catalog.rs

1use serde_json::{Value, json};
2
3use crate::builtins::{builtin_effect_groups, builtin_transition_groups};
4use crate::{
5    EffectDef, EffectKind, EffectResourceKind, ParamSpec, ParamType, ParamUnit, ParamValue,
6};
7
8/// The engine-owned effect catalog as JSON, without shader source.
9#[must_use]
10pub fn builtin_catalog() -> Value {
11    let entries = |groups: Vec<(&'static str, Vec<EffectDef>)>| {
12        groups
13            .into_iter()
14            .flat_map(|(group, definitions)| {
15                definitions
16                    .into_iter()
17                    .map(move |definition| catalog_entry(&definition, group))
18            })
19            .collect::<Vec<_>>()
20    };
21    json!({
22        "effects": entries(builtin_effect_groups()),
23        "transitions": entries(builtin_transition_groups()),
24    })
25}
26
27/// [`builtin_catalog`] with its `$id`, pretty-printed as `schema/effects.v1.json` holds it.
28#[must_use]
29pub fn builtin_catalog_document() -> String {
30    let mut catalog = builtin_catalog();
31    if let Some(object) = catalog.as_object_mut() {
32        object.insert(
33            "$id".to_owned(),
34            "https://alpha2.sh/schema/effects.v1.json".into(),
35        );
36    }
37    // A `Value` always serializes.
38    let mut text = serde_json::to_string_pretty(&catalog).unwrap_or_default();
39    text.push('\n');
40    text
41}
42
43/// Serializes [`builtin_catalog`] for process and WebAssembly boundaries.
44#[must_use]
45pub fn builtin_catalog_json() -> String {
46    builtin_catalog().to_string()
47}
48
49fn catalog_entry(definition: &EffectDef, group: &str) -> Value {
50    let label = label(&definition.id);
51    let mut entry = json!({
52        "id": definition.id,
53        "version": definition.version,
54        "kind": match definition.kind {
55            EffectKind::Effect => "effect",
56            EffectKind::Transition => "transition",
57            EffectKind::Generator => "generator",
58        },
59        "inputs": definition
60            .inputs
61            .iter()
62            .map(|input| json!({ "name": input.name }))
63            .collect::<Vec<_>>(),
64        "label": label,
65        "group": group,
66        "params": definition.params.iter().map(param).collect::<Vec<_>>(),
67        "resources": definition.resources.iter().map(|resource| json!({
68            "name": resource.name,
69            "kind": match resource.kind { EffectResourceKind::Lut3d => "lut3d" },
70        })).collect::<Vec<_>>(),
71    });
72    if definition.kind == EffectKind::Transition {
73        entry["coverage_commutes"] = json!(
74            crate::builtins::COVERAGE_COMMUTING_TRANSITIONS.contains(&definition.id.as_str())
75        );
76    }
77    entry
78}
79
80fn param(spec: &ParamSpec) -> Value {
81    let value = match &spec.default {
82        ParamValue::Float(value) => json!(value),
83        ParamValue::Vec2(value) => json!(value),
84        ParamValue::Vec4(value) | ParamValue::Color(value) => json!(value),
85        ParamValue::Enum(value) => json!(value),
86        ParamValue::Bool(value) => json!(value),
87    };
88    json!({
89        "name": spec.name,
90        "label": humanize(&spec.name),
91        "type": match spec.param_type {
92            ParamType::Float => "float",
93            ParamType::Vec2 => "vec2",
94            ParamType::Vec4 => "vec4",
95            ParamType::Color => "color",
96            ParamType::Enum => "enum",
97            ParamType::Bool => "bool",
98        },
99        "default": value,
100        "min": spec.min,
101        "max": spec.max,
102        "step": spec.step,
103        "unit": match spec.unit {
104            ParamUnit::Normalized => "normalized",
105            ParamUnit::Degrees => "degrees",
106            ParamUnit::Color => "color",
107            ParamUnit::Enum => "enum",
108            ParamUnit::Bool => "bool",
109        },
110        "enumValues": spec.enum_values,
111        // Enum and bool values have nothing between them, so their keyframes only hold.
112        "animatable": matches!(
113            spec.param_type,
114            ParamType::Float | ParamType::Vec2 | ParamType::Vec4 | ParamType::Color
115        ),
116    })
117}
118
119/// Labels `humanize` gets wrong (initialisms), by built-in short id.
120const LABELS: &[(&str, &str)] = &[
121    ("lut-3d", "3D LUT"),
122    ("black-and-white", "Black & White"),
123    ("hue-saturation", "Hue/Saturation"),
124    ("rgb-split", "RGB Split"),
125    ("crt", "CRT"),
126    ("vhs", "VHS"),
127    ("hsv-fade", "HSV Fade"),
128    ("tv-static", "TV Static"),
129    ("old-tv-lost-signal", "Old TV Lost Signal"),
130];
131
132fn label(id: &str) -> String {
133    let short = id.rsplit('.').next().unwrap_or(id);
134    LABELS
135        .iter()
136        .find(|(name, _)| *name == short)
137        .map_or_else(|| humanize(short), |(_, label)| (*label).to_owned())
138}
139
140fn humanize(value: &str) -> String {
141    value
142        .split(['-', '_'])
143        .filter(|part| !part.is_empty())
144        .map(|part| {
145            let mut chars = part.chars();
146            chars.next().map_or_else(String::new, |first| {
147                first.to_uppercase().collect::<String>() + chars.as_str()
148            })
149        })
150        .collect::<Vec<_>>()
151        .join(" ")
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn catalog_exposes_lut_resource_without_shader_source() {
160        let catalog = builtin_catalog();
161        let lut = catalog["effects"]
162            .as_array()
163            .unwrap()
164            .iter()
165            .find(|entry| entry["id"] == "alpha2.effect.lut-3d")
166            .unwrap();
167        assert_eq!(lut["resources"][0]["kind"], "lut3d");
168        assert_eq!(lut["label"], "3D LUT");
169        assert!(lut.get("wgslBody").is_none());
170
171        let crop = catalog["effects"]
172            .as_array()
173            .unwrap()
174            .iter()
175            .find(|entry| entry["id"] == "alpha2.effect.crop")
176            .unwrap();
177        assert_eq!(crop["params"][0]["min"], 0.0);
178        assert_eq!(crop["params"][0]["max"], 1.0);
179        assert!((crop["params"][0]["step"].as_f64().unwrap() - 0.005).abs() < 1e-8);
180    }
181
182    #[test]
183    fn every_built_in_lists_the_named_inputs_it_declares() {
184        let catalog = builtin_catalog();
185        let definitions = crate::builtin_effect_definitions()
186            .into_iter()
187            .chain(crate::builtin_transition_definitions())
188            .collect::<Vec<_>>();
189        let entries = catalog["effects"]
190            .as_array()
191            .unwrap()
192            .iter()
193            .chain(catalog["transitions"].as_array().unwrap())
194            .collect::<Vec<_>>();
195        assert_eq!(entries.len(), definitions.len());
196        for (entry, definition) in entries.into_iter().zip(&definitions) {
197            assert_eq!(entry["id"], definition.id);
198            let names = definition
199                .inputs
200                .iter()
201                .map(|input| json!({ "name": input.name }))
202                .collect::<Vec<_>>();
203            assert_eq!(entry["inputs"], json!(names), "{}", entry["id"]);
204        }
205    }
206
207    #[test]
208    fn every_built_in_is_alpha2_s_own_or_a_gl_transitions_port() {
209        // A source with other terms needs a notice and an exception here.
210        let own = crate::builtins::ALPHA2_EFFECT_LICENSE;
211        for definition in crate::builtin_effect_definitions()
212            .into_iter()
213            .chain(crate::builtins::internal_effect_definitions())
214        {
215            assert_eq!(
216                definition.license.as_deref(),
217                Some(own),
218                "{}",
219                definition.id
220            );
221        }
222        for definition in crate::builtin_transition_definitions() {
223            let license = definition.license.as_deref().unwrap_or_default();
224            assert!(
225                license == own
226                    || (license.starts_with("MIT; Author: ")
227                        && license.contains(crate::builtins::GL_TRANSITIONS_BASE)),
228                "{}: {license}",
229                definition.id
230            );
231        }
232    }
233
234    #[test]
235    fn every_label_exception_names_a_built_in_and_changes_its_label() {
236        let shorts = crate::builtin_effect_definitions()
237            .into_iter()
238            .chain(crate::builtin_transition_definitions())
239            .map(|definition| definition.id.rsplit('.').next().unwrap().to_owned())
240            .collect::<Vec<_>>();
241        for (short, label) in LABELS {
242            assert!(shorts.iter().any(|name| name == short), "{short}");
243            assert_ne!(humanize(short), *label, "{short} needs no exception");
244        }
245    }
246
247    #[test]
248    fn continuous_parameters_are_animatable_and_discrete_ones_hold() {
249        let catalog = builtin_catalog();
250        let mut seen = std::collections::BTreeSet::new();
251        for entry in catalog["effects"]
252            .as_array()
253            .unwrap()
254            .iter()
255            .chain(catalog["transitions"].as_array().unwrap())
256        {
257            for param in entry["params"].as_array().unwrap() {
258                let kind = param["type"].as_str().unwrap();
259                let animatable = param["animatable"].as_bool().unwrap();
260                assert_eq!(
261                    animatable,
262                    matches!(kind, "float" | "vec2" | "vec4" | "color"),
263                    "{}.{}",
264                    entry["id"],
265                    param["name"]
266                );
267                seen.insert(kind.to_owned());
268            }
269        }
270        assert!(seen.contains("float") && seen.contains("enum"), "{seen:?}");
271    }
272
273    #[test]
274    fn a_color_parameter_is_a_color_and_thresholds_are_a_vec4() {
275        let catalog = builtin_catalog();
276        for entry in catalog["effects"]
277            .as_array()
278            .unwrap()
279            .iter()
280            .chain(catalog["transitions"].as_array().unwrap())
281        {
282            for param in entry["params"].as_array().unwrap() {
283                if param["type"] == "color" {
284                    assert_eq!(param["unit"], "color", "{}.{}", entry["id"], param["name"]);
285                }
286            }
287        }
288        // color-phase's steps are per-channel thresholds, keyframed per component, not as a color.
289        let phase = catalog["transitions"]
290            .as_array()
291            .unwrap()
292            .iter()
293            .find(|entry| entry["id"] == "alpha2.transition.color-phase")
294            .unwrap();
295        for param in phase["params"].as_array().unwrap() {
296            assert_eq!(param["type"], "vec4", "{}", param["name"]);
297            assert_eq!(
298                (param["min"].as_f64(), param["max"].as_f64()),
299                (Some(0.0), Some(1.0))
300            );
301        }
302    }
303}