use std::rc::Rc;
use super::node::{NodeRef, Type};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ParamKind {
Value(Type),
Texture,
Sampler,
}
#[derive(Debug)]
pub struct CodeDef {
pub name: String,
pub code: String,
pub(crate) params: Vec<(String, ParamKind)>,
pub(crate) ret: Type,
pub includes: Vec<NodeRef>,
}
pub fn wgsl_fn(source: &str, includes: Vec<NodeRef>) -> Rc<CodeDef> {
let parsed = parse(source);
let output = if parsed.output_type == "void" {
String::new()
} else {
format!("-> {}", parsed.output_type)
};
let code = format!(
"fn {} ( {} ) {}{}",
parsed.name,
parsed.inputs_code.trim(),
output,
parsed.block_code
);
Rc::new(CodeDef {
name: parsed.name,
code,
params: parsed.params,
ret: param_type(&parsed.output_type)
.unwrap_or_else(|| panic!("three-rs: wgslFn returns an unmodelled type")),
includes,
})
}
struct Parsed {
name: String,
inputs_code: String,
block_code: String,
output_type: String,
params: Vec<(String, ParamKind)>,
}
fn is_ident(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '_'
}
fn parse(source: &str) -> Parsed {
let source = strip_leading(source);
let bytes: Vec<char> = source.chars().collect();
let mut i = 0;
let at = |i: usize| bytes.get(i).copied().unwrap_or('\0');
while matches!(at(i), 'f' | 'n') {
i += 1;
}
while at(i).is_whitespace() {
i += 1;
}
let name_start = i;
while is_ident(at(i)) {
i += 1;
}
let name: String = bytes[name_start..i].iter().collect();
while at(i).is_whitespace() {
i += 1;
}
assert_eq!(at(i), '(', "three-rs: wgslFn source is not a WGSL function");
i += 1;
let inputs_start = i;
while at(i) != ')' {
assert!(i < bytes.len(), "three-rs: wgslFn declaration has no `)`");
i += 1;
}
let inputs_code: String = bytes[inputs_start..i].iter().collect();
i += 1;
while at(i).is_whitespace() {
i += 1;
}
while matches!(at(i), '-' | '>') {
i += 1;
}
while at(i).is_whitespace() {
i += 1;
}
let out_start = i;
while is_ident(at(i)) {
i += 1;
}
if at(i) == '<' {
while at(i) != '>' {
assert!(i < bytes.len(), "three-rs: wgslFn return type has no `>`");
i += 1;
}
i += 1;
}
let output_type: String = bytes[out_start..i].iter().collect();
let block_code: String = bytes[i..].iter().collect();
Parsed {
params: parse_params(&inputs_code),
name,
inputs_code,
block_code,
output_type,
}
}
fn strip_leading(source: &str) -> &str {
let mut rest = source.trim_start();
loop {
if let Some(after) = rest.strip_prefix("//") {
rest = after
.find(['\r', '\n'])
.map_or("", |at| &after[at..])
.trim_start();
} else if let Some(after) = rest.strip_prefix("/*") {
rest = after
.find("*/")
.map_or("", |at| &after[at + 2..])
.trim_start();
} else {
return rest;
}
}
}
fn parse_params(inputs_code: &str) -> Vec<(String, ParamKind)> {
let chars: Vec<char> = inputs_code.chars().collect();
let at = |i: usize| chars.get(i).copied().unwrap_or('\0');
let mut params = Vec::new();
let mut i = 0;
while i < chars.len() {
if !is_ident(at(i)) {
i += 1;
continue;
}
let start = i;
while is_ident(at(i)) {
i += 1;
}
let name: String = chars[start..i].iter().collect();
let mut j = i;
while at(j).is_whitespace() {
j += 1;
}
if at(j) != ':' {
continue;
}
j += 1;
while at(j).is_whitespace() {
j += 1;
}
let type_start = j;
while is_ident(at(j)) {
j += 1;
}
if at(j) == '<' {
while j < chars.len() && at(j) != '>' {
j += 1;
}
j += 1;
}
let ty: String = chars[type_start..j].iter().collect();
params.push((name, param_kind(&ty)));
i = j;
}
params
}
fn param_kind(ty: &str) -> ParamKind {
if ty == "sampler" {
ParamKind::Sampler
} else if ty.starts_with("texture") {
ParamKind::Texture
} else {
ParamKind::Value(
param_type(ty).unwrap_or_else(|| panic!("three-rs: wgslFn parameter type `{ty}`")),
)
}
}
fn param_type(ty: &str) -> Option<Type> {
Some(match ty {
"f32" => Type::F32,
"i32" => Type::I32,
"u32" => Type::U32,
"bool" => Type::Bool,
"vec2<f32>" | "vec2f" => Type::Vec2,
"vec3<f32>" | "vec3f" => Type::Vec3,
"vec4<f32>" | "vec4f" => Type::Vec4,
"vec2<u32>" | "vec2u" => Type::UVec2,
"vec2<i32>" | "vec2i" => Type::IVec2,
"vec3<u32>" | "vec3u" => Type::UVec3,
"vec3<bool>" | "vec3b" => Type::BVec3,
"mat2x2<f32>" | "mat2x2f" => Type::Mat2,
"mat3x3<f32>" | "mat3x3f" => Type::Mat3,
"mat4x4<f32>" | "mat4x4f" => Type::Mat4,
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
const DESATURATE: &str = "
\t\t\t\t\tfn desaturate( color:vec3<f32> ) -> vec3<f32> {
\t\t\t\t\t\treturn vec3<f32>( dot( lum, color ) );
\t\t\t\t\t}
\t\t\t\t";
#[test]
fn the_body_is_copied_through_verbatim() {
let def = wgsl_fn(DESATURATE, vec![]);
assert_eq!(def.name, "desaturate");
assert_eq!(def.ret, Type::Vec3);
assert_eq!(
def.params,
vec![("color".to_string(), ParamKind::Value(Type::Vec3))]
);
assert_eq!(
def.code,
"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"
);
}
#[test]
fn texture_and_sampler_parameters_are_bindings() {
let def = wgsl_fn(
"fn f( tex: texture_2d<f32>, tex_sampler: sampler, uv:vec2<f32> ) -> vec4<f32> { }",
vec![],
);
let kinds: Vec<ParamKind> = def.params.iter().map(|(_, k)| *k).collect();
assert_eq!(
kinds,
vec![
ParamKind::Texture,
ParamKind::Sampler,
ParamKind::Value(Type::Vec2)
]
);
}
#[test]
fn leading_comments_are_stripped() {
let def = wgsl_fn(
"// a note\n/* and another */\nfn f( x:f32 ) -> f32 { return x; }",
vec![],
);
assert_eq!(def.name, "f");
assert_eq!(def.code, "fn f ( x:f32 ) -> f32 { return x; }");
}
}