Skip to main content

three_rs/nodes/
code.rs

1//! `wgslFn()` — `CodeNode` / `FunctionNode` / `FunctionCallNode` and the WGSL
2//! declaration parser behind them (`WGSLNodeFunction.js`).
3//!
4//! A `wgslFn` is a string of hand-written WGSL that the node system does not
5//! understand: it only parses far enough to learn the function's name, its
6//! parameter names and types and its return type, and then emits the source
7//! *verbatim* into `// codes` and calls it. Everything after the declaration —
8//! the body, its indentation, the whitespace a JS template literal leaves
9//! after the closing brace — is copied through untouched, which is why the
10//! generated shader keeps the example file's six-tab indentation.
11
12use std::rc::Rc;
13
14use super::node::{NodeRef, Type};
15
16/// What one declared parameter of a `wgslFn` binds to.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum ParamKind {
19    /// An ordinary value: the argument is generated and padded to this type.
20    Value(Type),
21    /// `texture_2d<f32>` and friends: the argument must be a texture node, and
22    /// what is passed is the binding itself, not a sample of it.
23    Texture,
24    /// `sampler`: the argument is again a texture node, and what is passed is
25    /// that binding's companion sampler.
26    Sampler,
27}
28
29/// A parsed `wgslFn` — `CodeNode` plus the `WGSLNodeFunction` it holds.
30#[derive(Debug)]
31pub struct CodeDef {
32    /// The name in the declaration, which is also the name it is called by.
33    pub name: String,
34    /// `WGSLNodeFunction.getCode()`: the rebuilt declaration line followed by
35    /// the source's own block, verbatim.
36    pub code: String,
37    /// The declared parameters, in declaration order.
38    pub(crate) params: Vec<(String, ParamKind)>,
39    /// The return type. `void` is not modelled: nothing in the rung uses it.
40    pub(crate) ret: Type,
41    /// `CodeNode.includes` — the nodes three builds *before* this one, so
42    /// whatever they declare is in scope for the hand-written body. Two kinds
43    /// reach it: another `wgslFn` this one calls, which lands in `// codes`
44    /// ahead of its caller, and a `varyingProperty()` the body assigns to,
45    /// which is how `webgpu_tsl_interoperability`'s `varyings.vUv = uv;` gets
46    /// `vUv` into `VaryingsStruct` without any node ever reading it in the
47    /// vertex stage. See `docs/nodes.md` §20.
48    pub includes: Vec<NodeRef>,
49}
50
51/// `wgslFn( source, includes )`.
52///
53/// # Panics
54///
55/// If the source does not start with a WGSL function declaration, or declares
56/// a type the port does not model. Three throws on the first and silently
57/// produces `undefined` on the second; a panic at setup time is the port's
58/// equivalent of a thrown `Error`, and both happen long before any pixels.
59pub fn wgsl_fn(source: &str, includes: Vec<NodeRef>) -> Rc<CodeDef> {
60    let parsed = parse(source);
61    let output = if parsed.output_type == "void" {
62        String::new()
63    } else {
64        format!("-> {}", parsed.output_type)
65    };
66    // `getCode()`: `fn <name> ( <inputsCode.trim()> ) <outputType>` + blockCode.
67    // The space before the parenthesis and the one after `)` are three's, and
68    // the block keeps the source's own leading space and indentation.
69    let code = format!(
70        "fn {} ( {} ) {}{}",
71        parsed.name,
72        parsed.inputs_code.trim(),
73        output,
74        parsed.block_code
75    );
76    Rc::new(CodeDef {
77        name: parsed.name,
78        code,
79        params: parsed.params,
80        ret: param_type(&parsed.output_type)
81            .unwrap_or_else(|| panic!("three-rs: wgslFn returns an unmodelled type")),
82        includes,
83    })
84}
85
86struct Parsed {
87    name: String,
88    inputs_code: String,
89    block_code: String,
90    output_type: String,
91    params: Vec<(String, ParamKind)>,
92}
93
94fn is_ident(c: char) -> bool {
95    c.is_ascii_alphanumeric() || c == '_'
96}
97
98/// The Rust of `declarationRegexp`. Three's regex is
99/// `^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)`
100/// applied to the source after its leading comments and whitespace have been
101/// stripped; the non-greedy groups mean "up to the first `)`" and "up to the
102/// first `>`", which is what the hand-written scanner below does.
103fn parse(source: &str) -> Parsed {
104    let source = strip_leading(source);
105    let bytes: Vec<char> = source.chars().collect();
106    let mut i = 0;
107    let at = |i: usize| bytes.get(i).copied().unwrap_or('\0');
108
109    // `[fn]*` is a character class, not the word `fn`.
110    while matches!(at(i), 'f' | 'n') {
111        i += 1;
112    }
113    while at(i).is_whitespace() {
114        i += 1;
115    }
116    let name_start = i;
117    while is_ident(at(i)) {
118        i += 1;
119    }
120    let name: String = bytes[name_start..i].iter().collect();
121    while at(i).is_whitespace() {
122        i += 1;
123    }
124    assert_eq!(at(i), '(', "three-rs: wgslFn source is not a WGSL function");
125    i += 1;
126    let inputs_start = i;
127    while at(i) != ')' {
128        assert!(i < bytes.len(), "three-rs: wgslFn declaration has no `)`");
129        i += 1;
130    }
131    let inputs_code: String = bytes[inputs_start..i].iter().collect();
132    i += 1;
133    while at(i).is_whitespace() {
134        i += 1;
135    }
136    while matches!(at(i), '-' | '>') {
137        i += 1;
138    }
139    while at(i).is_whitespace() {
140        i += 1;
141    }
142    let out_start = i;
143    while is_ident(at(i)) {
144        i += 1;
145    }
146    if at(i) == '<' {
147        while at(i) != '>' {
148            assert!(i < bytes.len(), "three-rs: wgslFn return type has no `>`");
149            i += 1;
150        }
151        i += 1;
152    }
153    let output_type: String = bytes[out_start..i].iter().collect();
154    let block_code: String = bytes[i..].iter().collect();
155
156    Parsed {
157        params: parse_params(&inputs_code),
158        name,
159        inputs_code,
160        block_code,
161        output_type,
162    }
163}
164
165/// `source.replace( /^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/, '' )`.
166fn strip_leading(source: &str) -> &str {
167    let mut rest = source.trim_start();
168    loop {
169        if let Some(after) = rest.strip_prefix("//") {
170            rest = after
171                .find(['\r', '\n'])
172                .map_or("", |at| &after[at..])
173                .trim_start();
174        } else if let Some(after) = rest.strip_prefix("/*") {
175            rest = after
176                .find("*/")
177                .map_or("", |at| &after[at + 2..])
178                .trim_start();
179        } else {
180            return rest;
181        }
182    }
183}
184
185/// `propertiesRegexp` — every `name : type` pair in the declaration's inputs.
186fn parse_params(inputs_code: &str) -> Vec<(String, ParamKind)> {
187    let chars: Vec<char> = inputs_code.chars().collect();
188    let at = |i: usize| chars.get(i).copied().unwrap_or('\0');
189    let mut params = Vec::new();
190    let mut i = 0;
191    while i < chars.len() {
192        if !is_ident(at(i)) {
193            i += 1;
194            continue;
195        }
196        let start = i;
197        while is_ident(at(i)) {
198            i += 1;
199        }
200        let name: String = chars[start..i].iter().collect();
201        let mut j = i;
202        while at(j).is_whitespace() {
203            j += 1;
204        }
205        if at(j) != ':' {
206            // Not a `name : type` pair; the regex would skip past it too.
207            continue;
208        }
209        j += 1;
210        while at(j).is_whitespace() {
211            j += 1;
212        }
213        let type_start = j;
214        while is_ident(at(j)) {
215            j += 1;
216        }
217        if at(j) == '<' {
218            while j < chars.len() && at(j) != '>' {
219                j += 1;
220            }
221            j += 1;
222        }
223        let ty: String = chars[type_start..j].iter().collect();
224        params.push((name, param_kind(&ty)));
225        i = j;
226    }
227    params
228}
229
230fn param_kind(ty: &str) -> ParamKind {
231    if ty == "sampler" {
232        ParamKind::Sampler
233    } else if ty.starts_with("texture") {
234        ParamKind::Texture
235    } else {
236        ParamKind::Value(
237            param_type(ty).unwrap_or_else(|| panic!("three-rs: wgslFn parameter type `{ty}`")),
238        )
239    }
240}
241
242/// `wgslTypeLib`, as far as the port's [`Type`] reaches.
243fn param_type(ty: &str) -> Option<Type> {
244    Some(match ty {
245        "f32" => Type::F32,
246        "i32" => Type::I32,
247        "u32" => Type::U32,
248        "bool" => Type::Bool,
249        "vec2<f32>" | "vec2f" => Type::Vec2,
250        "vec3<f32>" | "vec3f" => Type::Vec3,
251        "vec4<f32>" | "vec4f" => Type::Vec4,
252        "vec2<u32>" | "vec2u" => Type::UVec2,
253        "vec2<i32>" | "vec2i" => Type::IVec2,
254        "vec3<u32>" | "vec3u" => Type::UVec3,
255        "vec3<bool>" | "vec3b" => Type::BVec3,
256        "mat2x2<f32>" | "mat2x2f" => Type::Mat2,
257        "mat3x3<f32>" | "mat3x3f" => Type::Mat3,
258        "mat4x4<f32>" | "mat4x4f" => Type::Mat4,
259        _ => return None,
260    })
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    const DESATURATE: &str = "
268\t\t\t\t\tfn desaturate( color:vec3<f32> ) -> vec3<f32> {
269
270\t\t\t\t\t\treturn vec3<f32>( dot( lum, color ) );
271
272\t\t\t\t\t}
273\t\t\t\t";
274
275    /// `getCode()` rebuilds only the declaration line; everything from the `{`
276    /// on is the source's own text, tabs and trailing whitespace included.
277    /// Three's dump of this example keeps the page's six-tab indentation, so a
278    /// port that reformatted the body would diverge on every line of it.
279    #[test]
280    fn the_body_is_copied_through_verbatim() {
281        let def = wgsl_fn(DESATURATE, vec![]);
282        assert_eq!(def.name, "desaturate");
283        assert_eq!(def.ret, Type::Vec3);
284        assert_eq!(
285            def.params,
286            vec![("color".to_string(), ParamKind::Value(Type::Vec3))]
287        );
288        assert_eq!(
289            def.code,
290            "fn desaturate ( color:vec3<f32> ) -> vec3<f32> {\n\n\t\t\t\t\t\treturn vec3<f32>( dot( lum, color ) );\n\n\t\t\t\t\t}\n\t\t\t\t"
291        );
292    }
293
294    /// A `texture_2d<f32>` parameter and a `sampler` parameter are bindings,
295    /// not values; `wgslTypeLib` keys the first off the prefix.
296    #[test]
297    fn texture_and_sampler_parameters_are_bindings() {
298        let def = wgsl_fn(
299            "fn f( tex: texture_2d<f32>, tex_sampler: sampler, uv:vec2<f32> ) -> vec4<f32> { }",
300            vec![],
301        );
302        let kinds: Vec<ParamKind> = def.params.iter().map(|(_, k)| *k).collect();
303        assert_eq!(
304            kinds,
305            vec![
306                ParamKind::Texture,
307                ParamKind::Sampler,
308                ParamKind::Value(Type::Vec2)
309            ]
310        );
311    }
312
313    /// The leading-comment strip and `[fn]*` being a character class rather
314    /// than the word `fn`.
315    #[test]
316    fn leading_comments_are_stripped() {
317        let def = wgsl_fn(
318            "// a note\n/* and another */\nfn f( x:f32 ) -> f32 { return x; }",
319            vec![],
320        );
321        assert_eq!(def.name, "f");
322        assert_eq!(def.code, "fn f ( x:f32 ) -> f32 { return x; }");
323    }
324}