Skip to main content

alpha2_shaders/
lib.rs

1//! Reusable shader assets for the alpha2 render pipeline.
2//!
3//! Shader source lives under `shaders/`, never inline in Rust, and is split by
4//! how it reaches the GPU:
5//!
6//! - `shaders/build/*.wesl` are complete modules with their own entry points.
7//!   `build.rs` resolves their imports and flattens each one into WGSL at build
8//!   time, so they are embedded here already compiled.
9//! - `shaders/runtime/**/*.wgsl` are effect *bodies*, not modules. They are not
10//!   valid on their own: `alpha2-render` generates a per-effect preamble from
11//!   the effect's parameter schema and concatenates the body onto it, which is
12//!   why these cannot be resolved ahead of time.
13
14mod effects;
15mod transitions;
16
17pub use effects::*;
18pub use transitions::*;
19
20/// Embeds a WESL module compiled by `build.rs` into `OUT_DIR`.
21macro_rules! built_module {
22    ($entry:literal) => {
23        include_str!(concat!(env!("OUT_DIR"), "/", $entry, ".wgsl"))
24    };
25}
26
27/// Full-screen triangle drawing a rendered frame onto a browser canvas.
28pub const CANVAS_PRESENT_WGSL: &str = built_module!("canvas-present");
29/// Full-screen triangle copying a premultiplied-alpha texel.
30pub const FULLSCREEN_TEXTURE_QUAD_WGSL: &str = built_module!("fullscreen-quad");
31/// Transform and blend one premultiplied RGBA layer over a backdrop.
32pub const COMPOSITE_WGSL: &str = built_module!("composite");
33/// GPU quantization from float intermediates into an RGBA8 readback texture.
34pub const READBACK_PACK_WGSL: &str = built_module!("readback-pack");
35/// GPU contain/rotation/premultiplication for browser-imported RGBA frames.
36pub const RGBA_PRESENT_WGSL: &str = built_module!("rgba-present");
37/// GPU conversion from premultiplied RGB intermediates into planar YUV420.
38pub const RGB_TO_YUV420_WGSL: &str = built_module!("rgb-to-yuv420");
39/// Sample-for-sample copy of decoded 8-bit 4:2:0 planes into NV12 targets.
40pub const YUV_REPACK_WGSL: &str = built_module!("yuv-repack");
41/// Limited/full-range BT.601/709/2020-NCL YUV plane conversion into linear RGB.
42pub const YUV_TO_LINEAR_WGSL: &str = built_module!("yuv-to-linear");
43/// [`YUV_TO_LINEAR_WGSL`] for 16-bit containers uploaded as unsigned
44/// integers, which it filters and normalizes itself.
45pub const YUV16_TO_LINEAR_WGSL: &str = built_module!("yuv16-to-linear");
46
47#[cfg(test)]
48mod tests {
49    use std::path::{Path, PathBuf};
50
51    fn shader_files(directory: &Path, files: &mut Vec<PathBuf>) {
52        for entry in std::fs::read_dir(directory).expect("shader directory") {
53            let path = entry.expect("shader entry").path();
54            if path.is_dir() {
55                shader_files(&path, files);
56            } else if path
57                .extension()
58                .is_some_and(|extension| extension == "wgsl" || extension == "wesl")
59            {
60                files.push(path);
61            }
62        }
63    }
64
65    /// `text` without `//` comments and with the whitespace gone, which is
66    /// all a search for a call needs. The shaders write no `/* */` comments.
67    fn code(text: &str) -> String {
68        text.lines()
69            .map(|line| line.split("//").next().unwrap_or_default())
70            .flat_map(str::chars)
71            .filter(|character| !character.is_whitespace())
72            .collect()
73    }
74
75    #[test]
76    fn no_built_in_shader_hashes_through_sin() {
77        // `fract(sin(x) * 43758.5453)` is not a hash on every GPU: large-argument `sin` has no
78        // required precision, so each driver's error gives a different value.
79        let mut files = Vec::new();
80        shader_files(
81            &Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders"),
82            &mut files,
83        );
84        assert!(files.len() > 10, "found only {files:?}");
85        for file in files {
86            let text = std::fs::read_to_string(&file).expect("shader text");
87            assert!(!text.contains("/*"), "{}: block comment", file.display());
88            let code = code(&text);
89            assert!(
90                !code.contains("fract(sin("),
91                "{} hashes through fract(sin(...)); use an integer hash (PCG) instead",
92                file.display()
93            );
94        }
95    }
96
97    /// The first two arguments, without whitespace, of every call to the
98    /// built-in `smoothstep` in `text`, not counting the helpers whose names
99    /// end in it.
100    fn smoothstep_edges(text: &str) -> Vec<(String, String)> {
101        let text = text
102            .lines()
103            .map(|line| line.split("//").next().unwrap_or_default())
104            .collect::<Vec<_>>()
105            .join("\n");
106        let mut found = Vec::new();
107        let mut search = 0;
108        while let Some(offset) = text[search..].find("smoothstep") {
109            let start = search + offset;
110            search = start + "smoothstep".len();
111            let before = text[..start].chars().next_back();
112            let rest = text[search..].trim_start();
113            if before.is_some_and(|character| character.is_ascii_alphanumeric() || character == '_')
114                || !rest.starts_with('(')
115            {
116                continue;
117            }
118            let (mut depth, mut arguments, mut argument) = (0_usize, Vec::new(), String::new());
119            for character in rest[1..].chars() {
120                match character {
121                    '(' | '[' => depth += 1,
122                    ')' | ']' if depth == 0 => break,
123                    ')' | ']' => depth -= 1,
124                    ',' if depth == 0 => {
125                        arguments.push(std::mem::take(&mut argument));
126                        continue;
127                    }
128                    _ if character.is_whitespace() => continue,
129                    _ => {}
130                }
131                argument.push(character);
132            }
133            // A trailing comma leaves nothing after it.
134            if !argument.is_empty() {
135                arguments.push(argument);
136            }
137            let [edge0, edge1, _] = <[String; 3]>::try_from(arguments).expect("three arguments");
138            found.push((edge0, edge1));
139        }
140        found
141    }
142
143    #[test]
144    fn built_in_shaders_call_smoothstep_only_with_ascending_edges() {
145        // naga emits MSL/GLSL `smoothstep` and SPIR-V `SmoothStep`, which leave `edge0 >= edge1`
146        // undefined; descending ramps go through `builtin_smoothstep`. Each raw call below is
147        // ascending by its constants or its parameter's schema range.
148        let ascending = [
149            ("cross-warp.wgsl", "0.0", "1.0", "constants"),
150            ("ripple.wgsl", "0.2", "1.0", "constants"),
151            ("window-blinds.wgsl", "0.8", "1.0", "constants"),
152            (
153                "simple-zoom.wgsl",
154                "0.0",
155                "quickness",
156                "quickness is clamped to 0.2..1",
157            ),
158            (
159                "simple-zoom.wgsl",
160                "quickness-0.2",
161                "1.0",
162                "quickness is clamped to 0.2..1",
163            ),
164            (
165                "directional-warp.wgsl",
166                "-params.smoothness",
167                "0.0",
168                "smoothness >= 0.0001",
169            ),
170            (
171                "crop.wgsl",
172                "line-feather",
173                "line+feather",
174                "feather >= 0.0001, line in 0..1",
175            ),
176            (
177                "vignette.wgsl",
178                "params.radius-params.softness",
179                "params.radius+params.softness",
180                "softness >= 0.01, radius <= 1.5",
181            ),
182            // threshold <= sqrt(3) < 2, where f32 values are f32::EPSILON apart, and
183            // softness >= f32::EPSILON: the sum is at least the next value up.
184            (
185                "chroma-key.wgsl",
186                "params.threshold",
187                "params.threshold+params.softness",
188                "softness >= f32::EPSILON, threshold <= sqrt(3)",
189            ),
190        ];
191        let mut files = Vec::new();
192        shader_files(
193            &Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders"),
194            &mut files,
195        );
196        let mut used = vec![false; ascending.len()];
197        for file in files {
198            let name = file
199                .file_name()
200                .and_then(|name| name.to_str())
201                .expect("name");
202            let text = std::fs::read_to_string(&file).expect("shader text");
203            for (edge0, edge1) in smoothstep_edges(&text) {
204                let listed = ascending.iter().position(|&(listed, low, high, _)| {
205                    (listed, low, high) == (name, edge0.as_str(), edge1.as_str())
206                });
207                let Some(index) = listed else {
208                    panic!(
209                        "{}: smoothstep({edge0}, {edge1}, ...) is not known to be ascending; \
210                         call builtin_smoothstep instead",
211                        file.display()
212                    );
213                };
214                used[index] = true;
215            }
216        }
217        for (index, entry) in ascending.iter().enumerate() {
218            assert!(used[index], "no longer called: {entry:?}");
219        }
220    }
221}