Skip to main content

alpha2_render/builtins/
mod.rs

1//! Built-in effects and transitions as data, one module per catalog group.
2
3use alpha2_gpu::CapabilityTier;
4use alpha2_shaders::{
5    CHROMA_KEY_BODY, EFFECT_HELPERS, EXPANDED_EFFECT, FOCUS_COMBINE, GAUSSIAN_BLUR,
6    GL_TRANSITION_ENTRY, GLOW_COMBINE, GLOW_THRESHOLD, LUT_3D_BODY, SHADOW_COMBINE, SHADOW_OFFSET,
7    TRANSITION_HELPERS, UNSHARP_COMBINE,
8};
9
10use crate::{
11    EffectDef, EffectId, EffectKind, EffectResourceKind, InputSpec, ParamSpec, ParamType,
12    ParamUnit, ParamValue, Renderer, ResourceSpec, ShaderDiagnostics,
13};
14
15mod effects;
16mod transitions;
17
18pub(crate) use effects::blur::{
19    directional_blur_definition, tilt_shift_definition, unsharp_mask_definition,
20};
21pub(crate) use effects::stylize::drop_shadow_definition;
22
23/// Stable identifier of the built-in chroma-key effect.
24pub const CHROMA_KEY_ID: &str = "alpha2.effect.chroma-key";
25
26/// Stable identifier of the atomic Gaussian-blur effect.
27pub const GAUSSIAN_BLUR_ID: &str = "alpha2.effect.gaussian-blur";
28
29/// Internal stable identifier of one separable Gaussian-blur pass.
30pub(crate) const GAUSSIAN_BLUR_PASS_ID: &str = "alpha2.internal.gaussian-blur-pass";
31
32/// Stable identifier of the built-in glow effect.
33pub const GLOW_ID: &str = "alpha2.effect.glow";
34
35/// Internal stable identifier of glow's threshold pass.
36pub(crate) const GLOW_THRESHOLD_ID: &str = "alpha2.internal.glow-threshold";
37
38/// Internal stable identifier of glow's two-input combining pass.
39pub(crate) const GLOW_COMBINE_ID: &str = "alpha2.internal.glow-combine";
40
41/// Stable identifier of the built-in directional (one-axis Gaussian) blur.
42pub(crate) const DIRECTIONAL_BLUR_ID: &str = "alpha2.effect.directional-blur";
43
44/// Stable identifier of the built-in unsharp mask.
45pub(crate) const UNSHARP_MASK_ID: &str = "alpha2.effect.unsharp-mask";
46
47/// Internal stable identifier of unsharp mask's two-input combining pass.
48pub(crate) const UNSHARP_COMBINE_ID: &str = "alpha2.internal.unsharp-combine";
49
50/// Stable identifier of the built-in tilt-shift.
51pub(crate) const TILT_SHIFT_ID: &str = "alpha2.effect.tilt-shift";
52
53/// Internal identifier of tilt-shift's pass mixing the source and its two blurs.
54pub(crate) const FOCUS_COMBINE_ID: &str = "alpha2.internal.focus-combine";
55
56/// Stable identifier of the built-in drop shadow.
57pub(crate) const DROP_SHADOW_ID: &str = "alpha2.effect.drop-shadow";
58
59/// Internal stable identifier of drop shadow's offset pass.
60pub(crate) const SHADOW_OFFSET_ID: &str = "alpha2.internal.shadow-offset";
61
62/// Internal stable identifier of drop shadow's two-input combining pass.
63pub(crate) const SHADOW_COMBINE_ID: &str = "alpha2.internal.shadow-combine";
64
65/// `EffectDef::license` of the effects Alpha2 itself wrote.
66pub(crate) const ALPHA2_EFFECT_LICENSE: &str = "MIT; Copyright Alpha2 contributors";
67
68/// Stable identifier of the resource-backed 3D LUT effect.
69pub const LUT_3D_ID: &str = "alpha2.effect.lut-3d";
70
71/// The gl-transitions commit the ports come from.
72pub(crate) const GL_TRANSITIONS_BASE: &str = "https://github.com/gl-transitions/gl-transitions/blob/902218a1b63773ac0d0d9f491951da3392365bfe/transitions/";
73
74/// Returns fresh definitions for every public built-in clip effect.
75#[must_use]
76pub fn builtin_effect_definitions() -> Vec<EffectDef> {
77    builtin_effect_groups()
78        .into_iter()
79        .flat_map(|(_, definitions)| definitions)
80        .collect()
81}
82
83/// The public built-in effects by catalog group, in catalog order.
84pub(crate) fn builtin_effect_groups() -> Vec<(&'static str, Vec<EffectDef>)> {
85    vec![
86        ("Color", effects::color::definitions()),
87        ("Keying", effects::keying::definitions()),
88        ("Blur & Sharpen", effects::blur::definitions()),
89        ("Stylize", effects::stylize::definitions()),
90        ("Distort", effects::distort::definitions()),
91    ]
92}
93
94/// Transitions that mix the two pictures at each pixel's own place and add nothing, for every
95/// parameter value, so a matte or mask may apply to each side. A render test checks the list.
96pub const COVERAGE_COMMUTING_TRANSITIONS: [&str; 38] = [
97    "alpha2.transition.fade",
98    "alpha2.transition.circle-open",
99    "alpha2.transition.angular",
100    "alpha2.transition.directional-wipe",
101    "alpha2.transition.radial",
102    "alpha2.transition.hsv-fade",
103    "alpha2.transition.wipe-up",
104    "alpha2.transition.wipe-down",
105    "alpha2.transition.wipe-left",
106    "alpha2.transition.wipe-right",
107    "alpha2.transition.window-blinds",
108    "alpha2.transition.window-slice",
109    "alpha2.transition.wind",
110    "alpha2.transition.pinwheel",
111    "alpha2.transition.heart",
112    "alpha2.transition.horizontal-open",
113    "alpha2.transition.horizontal-close",
114    "alpha2.transition.vertical-open",
115    "alpha2.transition.vertical-close",
116    "alpha2.transition.squares-wire",
117    "alpha2.transition.gradient-wipe",
118    "alpha2.transition.color-phase",
119    "alpha2.transition.fade-grayscale",
120    "alpha2.transition.polka-dots-curtain",
121    "alpha2.transition.block-dissolve",
122    "alpha2.transition.random-squares",
123    "alpha2.transition.perlin",
124    "alpha2.transition.overexposure",
125    "alpha2.transition.burn",
126    "alpha2.transition.crosshatch",
127    "alpha2.transition.random-noise",
128    "alpha2.transition.box",
129    "alpha2.transition.chessboard",
130    "alpha2.transition.bow-tie",
131    "alpha2.transition.bow-tie-horizontal",
132    "alpha2.transition.bow-tie-vertical",
133    "alpha2.transition.polar-function",
134    "alpha2.transition.shape-wipe",
135];
136
137/// Returns fresh, data-only definitions for all built-in transitions.
138#[must_use]
139pub fn builtin_transition_definitions() -> Vec<EffectDef> {
140    builtin_transition_groups()
141        .into_iter()
142        .flat_map(|(_, definitions)| definitions)
143        .collect()
144}
145
146/// The built-in transitions by catalog group, in catalog order.
147pub(crate) fn builtin_transition_groups() -> Vec<(&'static str, Vec<EffectDef>)> {
148    vec![
149        ("Classic", transitions::classic::definitions()),
150        ("Wipes", transitions::wipes::definitions()),
151        ("Stylized", transitions::stylized::definitions()),
152        ("Shapes", transitions::shapes::definitions()),
153        ("3D", transitions::three_d::definitions()),
154        ("Zoom & Blur", transitions::zoom_blur::definitions()),
155        ("Glitch", transitions::glitch::definitions()),
156    ]
157}
158
159/// Returns the data-only definition of the built-in chroma-key effect.
160///
161/// `key_color` is compared against straight sRGB-encoded color, as a color picker shows the
162/// screen. With `distance_mode` `rgb`, pixels within `threshold` are removed, a `softness` band
163/// is partly transparent and `spill_suppression` desaturates it; `chroma` compares only chroma,
164/// so the key survives shadows.
165#[must_use]
166pub fn chroma_key_definition() -> EffectDef {
167    EffectDef {
168        id: CHROMA_KEY_ID.into(),
169        version: 1,
170        kind: EffectKind::Effect,
171        inputs: Vec::new(),
172        params: vec![
173            color("key_color", [0.0, 1.0, 0.0, 1.0]),
174            float("threshold", 0.35, 0.0, 3.0_f32.sqrt()),
175            float("softness", 0.1, f32::EPSILON, 1.0),
176            float("spill_suppression", 0.2, 0.0, 1.0),
177            choice("distance_mode", 0, &["rgb", "chroma"]),
178        ],
179        resources: Vec::new(),
180        wgsl_body: effect_body(CHROMA_KEY_BODY),
181        tier_min: CapabilityTier::TierB,
182        license: Some(ALPHA2_EFFECT_LICENSE.into()),
183    }
184}
185
186/// Returns the data-only definition of the built-in Gaussian blur.
187///
188/// Standard deviation is half the `radius`, a fraction of the shorter side. The graph draws it
189/// as separable passes ([`crate::RenderGraph::add_effect`]); its own body is never drawn.
190#[must_use]
191pub fn gaussian_blur_definition() -> EffectDef {
192    EffectDef {
193        id: GAUSSIAN_BLUR_ID.into(),
194        version: 1,
195        kind: EffectKind::Effect,
196        inputs: Vec::new(),
197        params: vec![float_step("radius", 0.012, 0.0, 1.0, 0.001)],
198        resources: Vec::new(),
199        wgsl_body: effect_body(EXPANDED_EFFECT),
200        tier_min: CapabilityTier::TierB,
201        license: Some(ALPHA2_EFFECT_LICENSE.into()),
202    }
203}
204
205pub(crate) fn gaussian_blur_pass_definition() -> EffectDef {
206    EffectDef {
207        id: GAUSSIAN_BLUR_PASS_ID.into(),
208        version: 1,
209        kind: EffectKind::Effect,
210        inputs: Vec::new(),
211        params: vec![
212            vec2("step", [0.0, 0.0]),
213            float_step(
214                "sigma",
215                1.0,
216                0.0,
217                crate::gaussian_blur::MAX_PASS_SIGMA_TAPS,
218                0.001,
219            ),
220        ],
221        resources: Vec::new(),
222        wgsl_body: effect_body(GAUSSIAN_BLUR),
223        tier_min: CapabilityTier::TierB,
224        license: Some(ALPHA2_EFFECT_LICENSE.into()),
225    }
226}
227
228/// Returns the data-only definition of the built-in glow.
229///
230/// Straight color above `threshold` is blurred with `radius` and added back scaled by
231/// `intensity`. Drawn as internal passes; its own body is never drawn.
232#[must_use]
233pub fn glow_definition() -> EffectDef {
234    EffectDef {
235        id: GLOW_ID.into(),
236        version: 1,
237        kind: EffectKind::Effect,
238        inputs: Vec::new(),
239        params: vec![
240            float("threshold", 0.6, 0.0, 1.0),
241            float("intensity", 0.8, 0.0, 3.0),
242            float("radius", 0.012, 0.0, 0.06),
243        ],
244        resources: Vec::new(),
245        wgsl_body: effect_body(EXPANDED_EFFECT),
246        tier_min: CapabilityTier::TierB,
247        license: Some(ALPHA2_EFFECT_LICENSE.into()),
248    }
249}
250
251fn glow_threshold_definition() -> EffectDef {
252    EffectDef {
253        id: GLOW_THRESHOLD_ID.into(),
254        ..simple_effect(
255            "glow-threshold",
256            GLOW_THRESHOLD,
257            vec![float("threshold", 0.6, 0.0, 1.0)],
258        )
259    }
260}
261
262// Two inputs make it a transition to the registry; drawn at progress 0.5, which it ignores.
263fn glow_combine_definition() -> EffectDef {
264    EffectDef {
265        id: GLOW_COMBINE_ID.into(),
266        version: 1,
267        kind: EffectKind::Transition,
268        inputs: Vec::new(),
269        params: vec![float("intensity", 0.8, 0.0, 3.0)],
270        resources: Vec::new(),
271        wgsl_body: effect_body(GLOW_COMBINE),
272        tier_min: CapabilityTier::TierB,
273        license: Some(ALPHA2_EFFECT_LICENSE.into()),
274    }
275}
276
277fn unsharp_combine_definition() -> EffectDef {
278    EffectDef {
279        id: UNSHARP_COMBINE_ID.into(),
280        version: 1,
281        kind: EffectKind::Transition,
282        inputs: Vec::new(),
283        params: vec![
284            float("amount", 1.0, 0.0, 5.0),
285            float("threshold", 0.0, 0.0, 1.0),
286        ],
287        resources: Vec::new(),
288        wgsl_body: effect_body(UNSHARP_COMBINE),
289        tier_min: CapabilityTier::TierB,
290        license: Some(ALPHA2_EFFECT_LICENSE.into()),
291    }
292}
293
294fn focus_combine_definition() -> EffectDef {
295    EffectDef {
296        id: FOCUS_COMBINE_ID.into(),
297        version: 1,
298        kind: EffectKind::Effect,
299        inputs: vec![
300            InputSpec {
301                name: "soft".into(),
302            },
303            InputSpec {
304                name: "blurred".into(),
305            },
306        ],
307        params: vec![
308            float("position", 0.5, 0.0, 1.0),
309            degrees("angle", 0.0, -90.0, 90.0),
310            float("focus", 0.15, 0.0, 1.0),
311            float_step("falloff", 0.25, 0.001, 1.0, 0.005),
312        ],
313        resources: Vec::new(),
314        wgsl_body: effect_body(FOCUS_COMBINE),
315        tier_min: CapabilityTier::TierB,
316        license: Some(ALPHA2_EFFECT_LICENSE.into()),
317    }
318}
319
320fn shadow_offset_definition() -> EffectDef {
321    EffectDef {
322        id: SHADOW_OFFSET_ID.into(),
323        ..simple_effect(
324            "shadow-offset",
325            SHADOW_OFFSET,
326            vec![
327                vec2("offset", [0.0, 0.0]),
328                color("color", [0.0, 0.0, 0.0, 1.0]),
329                float("opacity", 0.6, 0.0, 1.0),
330            ],
331        )
332    }
333}
334
335fn shadow_combine_definition() -> EffectDef {
336    EffectDef {
337        id: SHADOW_COMBINE_ID.into(),
338        version: 1,
339        kind: EffectKind::Transition,
340        inputs: Vec::new(),
341        params: vec![boolean("shadow_only", false)],
342        resources: Vec::new(),
343        wgsl_body: effect_body(SHADOW_COMBINE),
344        tier_min: CapabilityTier::TierB,
345        license: Some(ALPHA2_EFFECT_LICENSE.into()),
346    }
347}
348
349/// Returns the data-only definition of the resource-backed 3D LUT effect.
350#[must_use]
351pub fn lut_3d_definition() -> EffectDef {
352    EffectDef {
353        id: LUT_3D_ID.into(),
354        version: 1,
355        kind: EffectKind::Effect,
356        inputs: Vec::new(),
357        params: vec![float("strength", 1.0, 0.0, 1.0)],
358        resources: vec![ResourceSpec {
359            name: "lut".into(),
360            kind: EffectResourceKind::Lut3d,
361        }],
362        wgsl_body: effect_body(LUT_3D_BODY),
363        tier_min: CapabilityTier::TierB,
364        license: Some(ALPHA2_EFFECT_LICENSE.into()),
365    }
366}
367
368/// The passes the engine inserts itself, hidden from the effect catalog.
369pub(crate) fn internal_effect_definitions() -> Vec<EffectDef> {
370    let mut definitions = vec![
371        gaussian_blur_pass_definition(),
372        glow_threshold_definition(),
373        glow_combine_definition(),
374        shadow_offset_definition(),
375        shadow_combine_definition(),
376        unsharp_combine_definition(),
377        focus_combine_definition(),
378        crate::masking::track_matte_definition(),
379        crate::generator::generator_definition(),
380    ];
381    definitions.extend(crate::masking::mask_combine_definitions());
382    definitions.extend(crate::masking::key_mix_definitions());
383    definitions
384}
385
386impl Renderer {
387    fn register_builtin_definition(
388        &mut self,
389        definition: EffectDef,
390    ) -> Result<EffectId, ShaderDiagnostics> {
391        let id = self.register_lazily(definition)?;
392        self.effects_mut().mark_builtin(id.clone());
393        Ok(id)
394    }
395
396    /// Registers the full built-in catalog; pipelines are made on first draw or [`Self::warmup`].
397    /// Built-ins cannot be removed through the host-effect methods.
398    ///
399    /// # Errors
400    /// Returns diagnostics from the first definition that fails.
401    pub fn register_builtins(&mut self) -> Result<Vec<EffectId>, ShaderDiagnostics> {
402        for definition in internal_effect_definitions() {
403            let internal = self.register_builtin_definition(definition)?;
404            self.effects_mut().mark_internal(internal);
405        }
406        let mut definitions = builtin_effect_definitions();
407        definitions.extend(builtin_transition_definitions());
408        let mut ids = Vec::with_capacity(definitions.len());
409        for definition in definitions {
410            ids.push(self.register_builtin_definition(definition)?);
411        }
412        Ok(ids)
413    }
414
415    /// Registers the built-in chroma-key effect.
416    ///
417    /// # Errors
418    /// Returns schema diagnostics when registration fails.
419    pub fn register_builtin_chroma_key(&mut self) -> Result<EffectId, ShaderDiagnostics> {
420        self.register_builtin_definition(chroma_key_definition())
421    }
422
423    /// Registers the public Gaussian blur and its internal pass.
424    ///
425    /// # Errors
426    /// Returns schema diagnostics when registration fails.
427    pub fn register_builtin_gaussian_blur(&mut self) -> Result<EffectId, ShaderDiagnostics> {
428        let internal = self.register_builtin_definition(gaussian_blur_pass_definition())?;
429        self.effects_mut().mark_internal(internal);
430        self.register_builtin_definition(gaussian_blur_definition())
431    }
432
433    /// Registers the built-in 3D LUT effect.
434    ///
435    /// # Errors
436    /// Returns schema diagnostics when registration fails.
437    pub fn register_builtin_lut_3d(&mut self) -> Result<EffectId, ShaderDiagnostics> {
438        self.register_builtin_definition(lut_3d_definition())
439    }
440
441    /// Registers all built-in transition definitions.
442    ///
443    /// # Errors
444    /// Diagnostics from the first failure; earlier definitions stay registered.
445    pub fn register_builtin_transitions(&mut self) -> Result<Vec<EffectId>, ShaderDiagnostics> {
446        let definitions = builtin_transition_definitions();
447        let mut ids = Vec::with_capacity(definitions.len());
448        for definition in definitions {
449            ids.push(self.register_builtin_definition(definition)?);
450        }
451        Ok(ids)
452    }
453}
454
455pub(crate) fn effect_body(body: &str) -> String {
456    format!("{EFFECT_HELPERS}\n{body}")
457}
458
459/// A public effect Alpha2 wrote, `alpha2.effect.<name>`.
460pub(crate) fn simple_effect(name: &str, body: &str, params: Vec<ParamSpec>) -> EffectDef {
461    EffectDef {
462        id: format!("alpha2.effect.{name}"),
463        version: 1,
464        kind: EffectKind::Effect,
465        inputs: Vec::new(),
466        params,
467        resources: Vec::new(),
468        wgsl_body: effect_body(body),
469        tier_min: CapabilityTier::TierB,
470        license: Some(ALPHA2_EFFECT_LICENSE.into()),
471    }
472}
473
474/// A port of gl-transitions file `source` by `author`, `alpha2.transition.<name>`.
475pub(crate) fn transition(
476    name: &str,
477    body: &str,
478    source: &str,
479    author: &str,
480    params: Vec<ParamSpec>,
481) -> EffectDef {
482    EffectDef {
483        id: format!("alpha2.transition.{name}"),
484        version: 1,
485        kind: EffectKind::Transition,
486        inputs: Vec::new(),
487        params,
488        resources: Vec::new(),
489        wgsl_body: format!("{TRANSITION_HELPERS}\n{GL_TRANSITION_ENTRY}\n{body}"),
490        tier_min: CapabilityTier::TierB,
491        license: Some(format!(
492            "MIT; Author: {author}; Source: {GL_TRANSITIONS_BASE}{source}"
493        )),
494    }
495}
496
497/// A transition Alpha2 wrote, `alpha2.transition.<name>`; its body defines `transition` over
498/// top-left uv.
499pub(crate) fn original_transition(name: &str, body: &str, params: Vec<ParamSpec>) -> EffectDef {
500    EffectDef {
501        id: format!("alpha2.transition.{name}"),
502        version: 1,
503        kind: EffectKind::Transition,
504        inputs: Vec::new(),
505        params,
506        resources: Vec::new(),
507        wgsl_body: format!("{TRANSITION_HELPERS}\n{body}"),
508        tier_min: CapabilityTier::TierB,
509        license: Some(ALPHA2_EFFECT_LICENSE.into()),
510    }
511}
512
513pub(crate) fn float(name: &str, default: f32, min: f32, max: f32) -> ParamSpec {
514    let span = max - min;
515    let step = if span > 50.0 {
516        1.0
517    } else if span <= 0.1 {
518        0.001
519    } else {
520        0.01
521    };
522    float_step(name, default, min, max, step)
523}
524
525pub(crate) fn float_step(name: &str, default: f32, min: f32, max: f32, step: f32) -> ParamSpec {
526    ParamSpec {
527        name: name.into(),
528        param_type: ParamType::Float,
529        default: ParamValue::Float(default),
530        min: Some(min),
531        max: Some(max),
532        step: Some(step),
533        unit: ParamUnit::Normalized,
534        enum_values: Vec::new(),
535    }
536}
537
538pub(crate) fn degrees(name: &str, default: f32, min: f32, max: f32) -> ParamSpec {
539    ParamSpec {
540        unit: ParamUnit::Degrees,
541        step: Some(1.0),
542        ..float(name, default, min, max)
543    }
544}
545
546pub(crate) fn vec2(name: &str, default: [f32; 2]) -> ParamSpec {
547    ParamSpec {
548        name: name.into(),
549        param_type: ParamType::Vec2,
550        default: ParamValue::Vec2(default),
551        min: None,
552        max: None,
553        step: None,
554        unit: ParamUnit::Normalized,
555        enum_values: Vec::new(),
556    }
557}
558
559pub(crate) fn vec2_range(
560    name: &str,
561    default: [f32; 2],
562    min: f32,
563    max: f32,
564    step: f32,
565) -> ParamSpec {
566    ParamSpec {
567        min: Some(min),
568        max: Some(max),
569        step: Some(step),
570        ..vec2(name, default)
571    }
572}
573
574pub(crate) fn color(name: &str, default: [f32; 4]) -> ParamSpec {
575    ParamSpec {
576        name: name.into(),
577        param_type: ParamType::Color,
578        default: ParamValue::Color(default),
579        min: None,
580        max: None,
581        step: None,
582        unit: ParamUnit::Color,
583        enum_values: Vec::new(),
584    }
585}
586
587/// Four independent progress thresholds, one per channel, in `0..=1`.
588pub(crate) fn thresholds(name: &str, default: [f32; 4]) -> ParamSpec {
589    ParamSpec {
590        name: name.into(),
591        param_type: ParamType::Vec4,
592        default: ParamValue::Vec4(default),
593        min: Some(0.0),
594        max: Some(1.0),
595        step: Some(0.01),
596        unit: ParamUnit::Normalized,
597        enum_values: Vec::new(),
598    }
599}
600
601pub(crate) fn choice(name: &str, default: u32, values: &[&str]) -> ParamSpec {
602    ParamSpec {
603        name: name.into(),
604        param_type: ParamType::Enum,
605        default: ParamValue::Enum(default),
606        min: None,
607        max: None,
608        step: None,
609        unit: ParamUnit::Enum,
610        enum_values: values.iter().map(|value| (*value).into()).collect(),
611    }
612}
613
614pub(crate) fn boolean(name: &str, default: bool) -> ParamSpec {
615    ParamSpec {
616        name: name.into(),
617        param_type: ParamType::Bool,
618        default: ParamValue::Bool(default),
619        min: None,
620        max: None,
621        step: None,
622        unit: ParamUnit::Bool,
623        enum_values: Vec::new(),
624    }
625}