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
383}
384
385impl Renderer {
386    fn register_builtin_definition(
387        &mut self,
388        definition: EffectDef,
389    ) -> Result<EffectId, ShaderDiagnostics> {
390        let id = self.register_lazily(definition)?;
391        self.effects_mut().mark_builtin(id.clone());
392        Ok(id)
393    }
394
395    /// Registers the full built-in catalog; pipelines are made on first draw or [`Self::warmup`].
396    /// Built-ins cannot be removed through the host-effect methods.
397    ///
398    /// # Errors
399    /// Returns diagnostics from the first definition that fails.
400    pub fn register_builtins(&mut self) -> Result<Vec<EffectId>, ShaderDiagnostics> {
401        for definition in internal_effect_definitions() {
402            let internal = self.register_builtin_definition(definition)?;
403            self.effects_mut().mark_internal(internal);
404        }
405        let mut definitions = builtin_effect_definitions();
406        definitions.extend(builtin_transition_definitions());
407        let mut ids = Vec::with_capacity(definitions.len());
408        for definition in definitions {
409            ids.push(self.register_builtin_definition(definition)?);
410        }
411        Ok(ids)
412    }
413
414    /// Registers the built-in chroma-key effect.
415    ///
416    /// # Errors
417    /// Returns schema diagnostics when registration fails.
418    pub fn register_builtin_chroma_key(&mut self) -> Result<EffectId, ShaderDiagnostics> {
419        self.register_builtin_definition(chroma_key_definition())
420    }
421
422    /// Registers the public Gaussian blur and its internal pass.
423    ///
424    /// # Errors
425    /// Returns schema diagnostics when registration fails.
426    pub fn register_builtin_gaussian_blur(&mut self) -> Result<EffectId, ShaderDiagnostics> {
427        let internal = self.register_builtin_definition(gaussian_blur_pass_definition())?;
428        self.effects_mut().mark_internal(internal);
429        self.register_builtin_definition(gaussian_blur_definition())
430    }
431
432    /// Registers the built-in 3D LUT effect.
433    ///
434    /// # Errors
435    /// Returns schema diagnostics when registration fails.
436    pub fn register_builtin_lut_3d(&mut self) -> Result<EffectId, ShaderDiagnostics> {
437        self.register_builtin_definition(lut_3d_definition())
438    }
439
440    /// Registers all built-in transition definitions.
441    ///
442    /// # Errors
443    /// Diagnostics from the first failure; earlier definitions stay registered.
444    pub fn register_builtin_transitions(&mut self) -> Result<Vec<EffectId>, ShaderDiagnostics> {
445        let definitions = builtin_transition_definitions();
446        let mut ids = Vec::with_capacity(definitions.len());
447        for definition in definitions {
448            ids.push(self.register_builtin_definition(definition)?);
449        }
450        Ok(ids)
451    }
452}
453
454pub(crate) fn effect_body(body: &str) -> String {
455    format!("{EFFECT_HELPERS}\n{body}")
456}
457
458/// A public effect Alpha2 wrote, `alpha2.effect.<name>`.
459pub(crate) fn simple_effect(name: &str, body: &str, params: Vec<ParamSpec>) -> EffectDef {
460    EffectDef {
461        id: format!("alpha2.effect.{name}"),
462        version: 1,
463        kind: EffectKind::Effect,
464        inputs: Vec::new(),
465        params,
466        resources: Vec::new(),
467        wgsl_body: effect_body(body),
468        tier_min: CapabilityTier::TierB,
469        license: Some(ALPHA2_EFFECT_LICENSE.into()),
470    }
471}
472
473/// A port of gl-transitions file `source` by `author`, `alpha2.transition.<name>`.
474pub(crate) fn transition(
475    name: &str,
476    body: &str,
477    source: &str,
478    author: &str,
479    params: Vec<ParamSpec>,
480) -> EffectDef {
481    EffectDef {
482        id: format!("alpha2.transition.{name}"),
483        version: 1,
484        kind: EffectKind::Transition,
485        inputs: Vec::new(),
486        params,
487        resources: Vec::new(),
488        wgsl_body: format!("{TRANSITION_HELPERS}\n{GL_TRANSITION_ENTRY}\n{body}"),
489        tier_min: CapabilityTier::TierB,
490        license: Some(format!(
491            "MIT; Author: {author}; Source: {GL_TRANSITIONS_BASE}{source}"
492        )),
493    }
494}
495
496/// A transition Alpha2 wrote, `alpha2.transition.<name>`; its body defines `transition` over
497/// top-left uv.
498pub(crate) fn original_transition(name: &str, body: &str, params: Vec<ParamSpec>) -> EffectDef {
499    EffectDef {
500        id: format!("alpha2.transition.{name}"),
501        version: 1,
502        kind: EffectKind::Transition,
503        inputs: Vec::new(),
504        params,
505        resources: Vec::new(),
506        wgsl_body: format!("{TRANSITION_HELPERS}\n{body}"),
507        tier_min: CapabilityTier::TierB,
508        license: Some(ALPHA2_EFFECT_LICENSE.into()),
509    }
510}
511
512pub(crate) fn float(name: &str, default: f32, min: f32, max: f32) -> ParamSpec {
513    let span = max - min;
514    let step = if span > 50.0 {
515        1.0
516    } else if span <= 0.1 {
517        0.001
518    } else {
519        0.01
520    };
521    float_step(name, default, min, max, step)
522}
523
524pub(crate) fn float_step(name: &str, default: f32, min: f32, max: f32, step: f32) -> ParamSpec {
525    ParamSpec {
526        name: name.into(),
527        param_type: ParamType::Float,
528        default: ParamValue::Float(default),
529        min: Some(min),
530        max: Some(max),
531        step: Some(step),
532        unit: ParamUnit::Normalized,
533        enum_values: Vec::new(),
534    }
535}
536
537pub(crate) fn degrees(name: &str, default: f32, min: f32, max: f32) -> ParamSpec {
538    ParamSpec {
539        unit: ParamUnit::Degrees,
540        step: Some(1.0),
541        ..float(name, default, min, max)
542    }
543}
544
545pub(crate) fn vec2(name: &str, default: [f32; 2]) -> ParamSpec {
546    ParamSpec {
547        name: name.into(),
548        param_type: ParamType::Vec2,
549        default: ParamValue::Vec2(default),
550        min: None,
551        max: None,
552        step: None,
553        unit: ParamUnit::Normalized,
554        enum_values: Vec::new(),
555    }
556}
557
558pub(crate) fn vec2_range(
559    name: &str,
560    default: [f32; 2],
561    min: f32,
562    max: f32,
563    step: f32,
564) -> ParamSpec {
565    ParamSpec {
566        min: Some(min),
567        max: Some(max),
568        step: Some(step),
569        ..vec2(name, default)
570    }
571}
572
573pub(crate) fn color(name: &str, default: [f32; 4]) -> ParamSpec {
574    ParamSpec {
575        name: name.into(),
576        param_type: ParamType::Color,
577        default: ParamValue::Color(default),
578        min: None,
579        max: None,
580        step: None,
581        unit: ParamUnit::Color,
582        enum_values: Vec::new(),
583    }
584}
585
586/// Four independent progress thresholds, one per channel, in `0..=1`.
587pub(crate) fn thresholds(name: &str, default: [f32; 4]) -> ParamSpec {
588    ParamSpec {
589        name: name.into(),
590        param_type: ParamType::Vec4,
591        default: ParamValue::Vec4(default),
592        min: Some(0.0),
593        max: Some(1.0),
594        step: Some(0.01),
595        unit: ParamUnit::Normalized,
596        enum_values: Vec::new(),
597    }
598}
599
600pub(crate) fn choice(name: &str, default: u32, values: &[&str]) -> ParamSpec {
601    ParamSpec {
602        name: name.into(),
603        param_type: ParamType::Enum,
604        default: ParamValue::Enum(default),
605        min: None,
606        max: None,
607        step: None,
608        unit: ParamUnit::Enum,
609        enum_values: values.iter().map(|value| (*value).into()).collect(),
610    }
611}
612
613pub(crate) fn boolean(name: &str, default: bool) -> ParamSpec {
614    ParamSpec {
615        name: name.into(),
616        param_type: ParamType::Bool,
617        default: ParamValue::Bool(default),
618        min: None,
619        max: None,
620        step: None,
621        unit: ParamUnit::Bool,
622        enum_values: Vec::new(),
623    }
624}