From f7716eb9e13c156a06b87abbcf3cea3f5200256b Mon Sep 17 00:00:00 2001 From: clover caruso Date: Wed, 2 Dec 2026 03:51:12 -0800 Subject: [PATCH] feat(engine): implement Fusion Lua and GPU-accelerated DCTL Fuse runtime --- Cargo.lock | 294 +------- crates/engine/Cargo.toml | 1 + crates/engine/src/eval/mod.rs | 23 +- crates/engine/src/fuse_runtime/dctl.rs | 681 ++++++++++++++++++ crates/engine/src/fuse_runtime/dctl_expr.rs | 446 ++++++++++++ crates/engine/src/fuse_runtime/dctl_parse.rs | 695 +++++++++++++++++++ crates/engine/src/fuse_runtime/lua_bridge.rs | 287 ++++++++ crates/engine/src/fuse_runtime/lua_dvip.rs | 459 ++++++++++++ crates/engine/src/fuse_runtime/lua_host.rs | 669 ++++++++++++++++++ crates/engine/src/fuse_runtime/lua_types.rs | 636 +++++++++++++++++ crates/engine/src/fuse_runtime/mod.rs | 525 ++++++++++++++ crates/engine/src/fuse_runtime/tests.rs | 634 +++++++++++++++++ crates/engine/src/lib.rs | 1 + 13 files changed, 5069 insertions(+), 282 deletions(-) create mode 100644 crates/engine/src/fuse_runtime/dctl.rs create mode 100644 crates/engine/src/fuse_runtime/dctl_expr.rs create mode 100644 crates/engine/src/fuse_runtime/dctl_parse.rs create mode 100644 crates/engine/src/fuse_runtime/lua_bridge.rs create mode 100644 crates/engine/src/fuse_runtime/lua_dvip.rs create mode 100644 crates/engine/src/fuse_runtime/lua_host.rs create mode 100644 crates/engine/src/fuse_runtime/lua_types.rs create mode 100644 crates/engine/src/fuse_runtime/mod.rs create mode 100644 crates/engine/src/fuse_runtime/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 4bb36ae7427481d877e4457c8d52b9aa29f929fd..5acaa4a6ef338f459f9ae74f7b0f978521b08d48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -868,14 +868,6 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -[[package]] -name = "diff" -version = "0.1.0" -dependencies = [ - "highlight", - "tree-sitter", -] - [[package]] name = "digest" version = "0.11.3" @@ -975,6 +967,7 @@ dependencies = [ "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", + "regex", "text", "unicode-segmentation", "windows-sys 0.61.2", @@ -1016,6 +1009,7 @@ dependencies = [ "exr", "fontdb 0.23.0", "image", + "mlua", "model", "png", "pollster", @@ -1488,35 +1482,6 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -[[package]] -name = "highlight" -version = "0.1.0" -dependencies = [ - "streaming-iterator", - "tree-sitter", - "tree-sitter-bash", - "tree-sitter-c", - "tree-sitter-cpp", - "tree-sitter-css", - "tree-sitter-diff", - "tree-sitter-go", - "tree-sitter-html", - "tree-sitter-java", - "tree-sitter-javascript", - "tree-sitter-json", - "tree-sitter-lua", - "tree-sitter-md", - "tree-sitter-python", - "tree-sitter-ruby", - "tree-sitter-rust", - "tree-sitter-sequel", - "tree-sitter-swift", - "tree-sitter-toml-ng", - "tree-sitter-typescript", - "tree-sitter-yaml", - "tree-sitter-zig", -] - [[package]] name = "hybrid-array" version = "0.4.15" @@ -3075,8 +3040,6 @@ version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ - "foldhash 0.2.0", - "indexmap", "itoa", "memchr", "serde", @@ -3296,12 +3259,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "streaming-iterator" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" - [[package]] name = "strict-num" version = "0.1.1" @@ -3489,6 +3446,10 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "syntax-tokens" +version = "0.1.0" + [[package]] name = "target-features" version = "0.1.6" @@ -3544,12 +3505,12 @@ dependencies = [ name = "theme" version = "0.1.0" dependencies = [ - "diff", "draw", "flate2", - "highlight", "memmap2", + "syntax-tokens", "text", + "zstd", ] [[package]] @@ -3752,235 +3713,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "tree-sitter" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2bed8f39a73439f3b0b7ed8f452be5d2911b5e9da69d352ef113bb7448fb8" -dependencies = [ - "cc", - "regex", - "serde_json", - "streaming-iterator", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-bash" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5ec769279cc91b561d3df0d8a5deb26b0ad40d183127f409494d6d8fc53062" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-c" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9b2eb57a55fed6b00812912e730b7a275cf4fe98bfd6a5d76263d4438371728" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-cpp" -version = "0.23.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df2196ea9d47b4ab4a31b9297eaa5a5d19a0b121dceb9f118f6790ad0ab94743" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-css" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5cbc5e18f29a2c6d6435891f42569525cf95435a3e01c2f1947abcde178686f" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-diff" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfe1e5ca280a65dfe5ba4205c1bcc84edf486464fed315db53dee6da9a335889" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-go" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8560a4d2f835cc0d4d2c2e03cbd0dde2f6114b43bc491164238d333e28b16ea" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-html" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-java" -version = "0.23.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-javascript" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-json" -version = "0.24.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-language" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" - -[[package]] -name = "tree-sitter-lua" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8daaf5f4235188a58603c39760d5fa5d4b920d36a299c934adddae757f32a10c" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-md" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed661bfe3c264961425f77cd89ad2998bf5d629e71ce8bab1e5d7e940d6246e" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-python" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-ruby" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be0484ea4ef6bb9c575b4fdabde7e31340a8d2dbc7d52b321ac83da703249f95" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-rust" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-sequel" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711e236e1ae0708f911d8413c3b5656f522416cba683ea91589aebc49eda1b5a" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-swift" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2688c06564afa397313e0db17d140a73e2c6a47f3884794614246167c9dd5dfd" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-toml-ng" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-typescript" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-yaml" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97" -dependencies = [ - "cc", - "tree-sitter-language", -] - -[[package]] -name = "tree-sitter-zig" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab11fc124851b0db4dd5e55983bbd9631192e93238389dcd44521715e5d53e28" -dependencies = [ - "cc", - "tree-sitter-language", -] - [[package]] name = "tree_magic_mini" version = "3.2.2" @@ -4046,6 +3778,7 @@ dependencies = [ "text", "theme", "time", + "ui-data-derive", "wgpu", "windows-sys 0.61.2", "winit", @@ -4053,6 +3786,15 @@ dependencies = [ "zbus", ] +[[package]] +name = "ui-data-derive" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "unicode-bidi" version = "0.3.18" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 47e1c5f5877444b3e191c89561a6e46bb77af629..b4b87bf377f8b3222ac973d87c509e77aa16fc1b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -22,6 +22,7 @@ zeno.workspace = true [target.'cfg(not(target_arch = "wasm32"))'.dependencies] cpal = "0.15" +mlua.workspace = true symphonia = { version = "0.5", default-features = false, features = ["wav", "mp3", "flac", "ogg", "aac", "isomp4", "pcm"] } [target.'cfg(target_arch = "wasm32")'.dependencies] diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index bbf10ee7926be40394d903f2af5806582986d1ae..e9d4481d571686ef2fd81ebc8e518d7b9a4d3cae 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -69,8 +69,8 @@ impl Default for DisplaySettings { } pub struct Engine { - device: wgpu::Device, - queue: wgpu::Queue, + pub(crate) device: wgpu::Device, + pub(crate) queue: wgpu::Queue, pipelines: RefCell, pipelines_int16: OnceCell>, pipelines_f16: OnceCell>, @@ -83,15 +83,16 @@ pub struct Engine { fx_fuses_pipelines: OnceCell>, archive_fx2_pipelines: OnceCell>, motion_blur: crate::motion_blur::MotionBlurPipelines, - supports_f32_filter: bool, + pub(crate) supports_f32_filter: bool, scene3d: crate::scene3d::Scene3DRenderer, optflow: std::sync::OnceLock, tracker: std::sync::OnceLock, particles: crate::particles::ParticleCache, custom_shaders: crate::custom_shader::CustomShaderCache, + pub fuse_registry: crate::fuse_runtime::FuseRegistry, sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, ram_upload_tex: RefCell>, - dummy: CachedTexture, + pub(crate) dummy: CachedTexture, vram_budget_bytes: u64, last_bg_vram_drops: Cell, pub cache: NodeCache, @@ -201,6 +202,7 @@ impl Engine { tracker: std::sync::OnceLock::new(), particles: crate::particles::ParticleCache::default(), custom_shaders: crate::custom_shader::CustomShaderCache::new(), + fuse_registry: crate::fuse_runtime::FuseRegistry::new(), sprite_cache: HashMap::new(), ram_upload_tex: RefCell::new(None), dummy, @@ -264,7 +266,7 @@ impl Engine { } } - fn node_depth(&self, comp: &Comp, node: &Node, time: f64, upstream: Option) -> BitDepth { + pub(crate) fn node_depth(&self, comp: &Comp, node: &Node, time: f64, upstream: Option) -> BitDepth { if !self.hiq { return BitDepth::Int8; } @@ -618,7 +620,7 @@ impl Engine { [(w / s).max(1), (h / s).max(1)] } - fn eval_node( + pub(crate) fn eval_node( &mut self, comp: &Comp, id: NodeId, @@ -1054,6 +1056,15 @@ impl Engine { } "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), other => { + // Dynamically evaluate any registered Fusion Lua / GPU-DCTL `.fuse` tool before + // falling back to passthrough + unsupported_nodes. + if other.starts_with("Fuse.") + && let Some(tex) = self.eval_fuse_runtime( + comp, node, time, frame_i, comp_dims, enc, visiting, stats, + ) + { + return tex; + } // Graceful passthrough for preserved/unknown image nodes (e.g. SurfaceTracker, MagicMask, // Fuse.Cryptomatte, Dimension.OpticalFlow) via standard primary image ports so downstream // graphs stay live without mistaking auxiliary sprite/material ports (like pEmitter's diff --git a/crates/engine/src/fuse_runtime/dctl.rs b/crates/engine/src/fuse_runtime/dctl.rs new file mode 100644 index 0000000000000000000000000000000000000000..76cd34432fa0537f56a6ff58b96d49a74e190e44 --- /dev/null +++ b/crates/engine/src/fuse_runtime/dctl.rs @@ -0,0 +1,681 @@ +//! Pure-Rust DCTL (DaVinci Color Transform Language / Fusion GPU Fuse) to WGSL +//! compute shader transpiler and std430 parameter block layout parser. +//! +//! Compiles on all targets including `wasm32-unknown-unknown`. + +use std::collections::HashMap; + +/// Scalar / vector field type supported inside a DCTL parameter block. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ParamType { + F32, + I32, + U32, + Vec2F, + Vec3F, + Vec4F, + Vec2I, + Vec3I, + Vec4I, +} + +impl ParamType { + pub fn from_c_type(s: &str) -> Option { + match s.trim() { + "float" | "double" | "half" => Some(Self::F32), + "int" | "bool" | "short" | "char" => Some(Self::I32), + "uint" | "unsigned int" | "unsigned" => Some(Self::U32), + "float2" => Some(Self::Vec2F), + "float3" => Some(Self::Vec3F), + "float4" => Some(Self::Vec4F), + "int2" => Some(Self::Vec2I), + "int3" => Some(Self::Vec3I), + "int4" => Some(Self::Vec4I), + _ => None, + } + } + + pub fn wgsl_name(self) -> &'static str { + match self { + Self::F32 => "f32", + Self::I32 => "i32", + Self::U32 => "u32", + Self::Vec2F => "vec2", + Self::Vec3F => "vec3", + Self::Vec4F => "vec4", + Self::Vec2I => "vec2", + Self::Vec3I => "vec3", + Self::Vec4I => "vec4", + } + } + + pub fn align(self) -> usize { + match self { + Self::F32 | Self::I32 | Self::U32 => 4, + Self::Vec2F | Self::Vec2I => 8, + Self::Vec3F | Self::Vec3I | Self::Vec4F | Self::Vec4I => 16, + } + } + + pub fn size(self) -> usize { + match self { + Self::F32 | Self::I32 | Self::U32 => 4, + Self::Vec2F | Self::Vec2I => 8, + Self::Vec3F | Self::Vec3I => 12, + Self::Vec4F | Self::Vec4I => 16, + } + } + + pub fn elem_stride(self) -> usize { + round_up(self.size(), self.align()) + } + + pub fn components(self) -> usize { + match self { + Self::F32 | Self::I32 | Self::U32 => 1, + Self::Vec2F | Self::Vec2I => 2, + Self::Vec3F | Self::Vec3I => 3, + Self::Vec4F | Self::Vec4I => 4, + } + } + + pub fn is_int(self) -> bool { + matches!(self, Self::I32 | Self::U32 | Self::Vec2I | Self::Vec3I | Self::Vec4I) + } +} + +/// One field in a std430-laid-out DCTL parameter struct. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ParamField { + pub name: String, + pub ty: ParamType, + /// `None` for scalar/vector fields, `Some(n)` for fixed C arrays (`float color[3]`). + pub array_len: Option, + pub offset: usize, + pub size: usize, + pub align: usize, +} + +/// Full std430 layout of a DCTL parameter block. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ParamLayout { + pub fields: Vec, + pub total_size: usize, +} + +impl ParamLayout { + pub fn field(&self, name: &str) -> Option<&ParamField> { + self.fields.iter().find(|f| f.name == name) + } + + pub fn buffer_size(&self) -> usize { + self.total_size.max(16) + } + + /// Emits a WGSL `struct` definition matching this std430 storage layout. + pub fn to_wgsl_struct(&self, struct_name: &str) -> String { + let mut out = format!("struct {struct_name} {{\n"); + if self.fields.is_empty() { + out.push_str(" _dctl_pad0: u32,\n _dctl_pad1: u32,\n _dctl_pad2: u32,\n _dctl_pad3: u32,\n"); + } else { + for f in &self.fields { + if let Some(n) = f.array_len { + out.push_str(&format!(" {}: array<{}, {n}>,\n", f.name, f.ty.wgsl_name())); + } else { + out.push_str(&format!(" {}: {},\n", f.name, f.ty.wgsl_name())); + } + } + } + out.push_str("}\n"); + out + } + + /// Writes a single scalar/vector element at `field_name` (and optional `index`) into `buf`. + pub fn write_scalar(&self, buf: &mut [u8], field_name: &str, index: Option, value: f64) { + let Some(f) = self.field(field_name) else { + return; + }; + let off = match (f.array_len, index) { + (Some(len), Some(idx)) if idx < len => f.offset + idx * f.ty.elem_stride(), + (None, None) => f.offset, + (None, Some(idx)) if idx < f.ty.components() => f.offset + idx * 4, + _ => return, + }; + if off + 4 > buf.len() { + return; + } + let bytes = match f.ty { + ParamType::I32 | ParamType::Vec2I | ParamType::Vec3I | ParamType::Vec4I => { + (value.round() as i32).to_le_bytes() + } + ParamType::U32 => (value.round().max(0.0) as u32).to_le_bytes(), + _ => (value as f32).to_le_bytes(), + }; + buf[off..off + 4].copy_from_slice(&bytes); + } + + /// Reads a single scalar/vector element from `buf`. + pub fn read_scalar(&self, buf: &[u8], field_name: &str, index: Option) -> Option { + let f = self.field(field_name)?; + let off = match (f.array_len, index) { + (Some(len), Some(idx)) if idx < len => f.offset + idx * f.ty.elem_stride(), + (None, None) => f.offset, + (None, Some(idx)) if idx < f.ty.components() => f.offset + idx * 4, + _ => return None, + }; + let bytes: [u8; 4] = buf.get(off..off + 4)?.try_into().ok()?; + let val = match f.ty { + ParamType::I32 | ParamType::Vec2I | ParamType::Vec3I | ParamType::Vec4I => { + i32::from_le_bytes(bytes) as f64 + } + ParamType::U32 => u32::from_le_bytes(bytes) as f64, + _ => f32::from_le_bytes(bytes) as f64, + }; + Some(val) + } +} + +/// Output of `transpile_dctl_to_wgsl`. +#[derive(Clone, Debug)] +pub struct TranspiledKernel { + pub wgsl: String, + pub entry_point: String, + pub params_struct_name: String, + pub param_layout: ParamLayout, + pub input_textures: Vec, + pub output_textures: Vec, +} + +fn round_up(val: usize, align: usize) -> usize { + if align <= 1 { + val + } else { + (val + align - 1) & !(align - 1) + } +} + +pub fn wgsl_storage_format(format: wgpu::TextureFormat) -> &'static str { + match format { + wgpu::TextureFormat::Rgba16Float => "rgba16float", + wgpu::TextureFormat::Rgba32Float => "rgba32float", + _ => "rgba8unorm", + } +} + +/// Parses a DCTL parameter block definition (either bare C fields or `typedef struct { ... } Name;`) +/// into a std430 `ParamLayout`. +pub fn parse_param_block(def: &str) -> Result { + let cleaned = strip_comments(def); + let body = extract_struct_body(&cleaned); + let mut layout = ParamLayout::default(); + let mut offset = 0usize; + let mut max_align = 4usize; + + for raw_stmt in body.split(';') { + let stmt = raw_stmt.trim(); + if stmt.is_empty() || stmt.starts_with('#') { + continue; + } + let tokens: Vec<&str> = stmt.split_whitespace().collect(); + if tokens.len() < 2 { + continue; + } + let (ty_str, rest_start) = if tokens[0] == "unsigned" && tokens.len() >= 3 && tokens[1] == "int" { + ("unsigned int", 2) + } else if matches!(tokens[0], "const" | "volatile") && tokens.len() >= 3 { + (tokens[1], 2) + } else { + (tokens[0], 1) + }; + let Some(ty) = ParamType::from_c_type(ty_str) else { + return Err(format!("unsupported DCTL param field type `{ty_str}` in `{stmt}`")); + }; + let rest = tokens[rest_start..].join(" "); + for decl in rest.split(',') { + let decl = decl.trim(); + if decl.is_empty() { + continue; + } + let (name, array_len) = if let Some(b) = decl.find('[') { + let end = decl.find(']').ok_or_else(|| format!("unclosed `[` in `{decl}`"))?; + let len_str = decl[b + 1..end].trim(); + let len: usize = len_str + .parse() + .map_err(|_| format!("invalid array size `{len_str}` in `{decl}`"))?; + (decl[..b].trim(), Some(len.max(1))) + } else { + (decl, None) + }; + let align = ty.align(); + max_align = max_align.max(align); + offset = round_up(offset, align); + let size = match array_len { + Some(n) => ty.elem_stride() * n, + None => ty.size(), + }; + layout.fields.push(ParamField { + name: name.to_owned(), + ty, + array_len, + offset, + size, + align, + }); + offset += size; + } + } + layout.total_size = round_up(offset, max_align).max(16); + Ok(layout) +} + +fn extract_struct_body(src: &str) -> &str { + if let (Some(open), Some(close)) = (src.find('{'), src.rfind('}')) + && open < close + { + &src[open + 1..close] + } else { + src + } +} + +fn strip_comments(src: &str) -> String { + let bytes = src.as_bytes(); + let mut out = String::with_capacity(src.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') { + i += 2; + while i < bytes.len() && bytes[i] != b'\n' { + i += 1; + } + } else if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') { + i += 2; + while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') { + i += 1; + } + i = (i + 2).min(bytes.len()); + out.push(' '); + } else { + let ch = src[i..].chars().next().unwrap(); + out.push(ch); + i += ch.len_utf8(); + } + } + out +} + +// --------------------------------------------------------------------------- +// Lexer +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum Tok { + Ident(String), + Float(String), + Int(String), + Punct(String), +} + +pub(super) fn lex_dctl(src: &str) -> Vec { + let stripped = strip_comments(src); + let mut defines: HashMap> = HashMap::new(); + let mut body = String::with_capacity(stripped.len()); + + for line in stripped.lines() { + let trimmed = line.trim_start(); + if let Some(rest) = trimmed.strip_prefix("#define") + && rest.starts_with(char::is_whitespace) + { + let rest = rest.trim_start(); + let mut parts = rest.splitn(2, char::is_whitespace); + if let (Some(name), Some(val)) = (parts.next(), parts.next()) + && !name.contains('(') + && !val.trim().is_empty() + { + defines.insert(name.to_owned(), lex_raw(val)); + } + } else if trimmed.starts_with('#') { + // Skip #include, #ifdef, #endif, #pragma, etc. + } else { + body.push_str(line); + body.push('\n'); + } + } + + let raw = lex_raw(&body); + if defines.is_empty() { + return raw; + } + let mut expanded = Vec::with_capacity(raw.len()); + for tok in raw { + if let Tok::Ident(ref name) = tok + && let Some(rep) = defines.get(name) + { + expanded.extend(rep.iter().cloned()); + continue; + } + expanded.push(tok); + } + expanded +} + +fn lex_raw(src: &str) -> Vec { + let b = src.as_bytes(); + let mut toks = Vec::new(); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if c.is_ascii_whitespace() { + i += 1; + continue; + } + if c.is_ascii_alphabetic() || c == b'_' { + let start = i; + i += 1; + while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { + i += 1; + } + toks.push(Tok::Ident(src[start..i].to_owned())); + continue; + } + if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) { + let start = i; + let mut is_float = c == b'.'; + if c == b'0' && matches!(b.get(i + 1), Some(b'x' | b'X')) { + i += 2; + while i < b.len() && b[i].is_ascii_hexdigit() { + i += 1; + } + while i < b.len() && matches!(b[i], b'u' | b'U' | b'l' | b'L') { + i += 1; + } + let s = src[start..i].trim_end_matches(['u', 'U', 'l', 'L']); + toks.push(Tok::Int(s.to_owned())); + continue; + } + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if i < b.len() && b[i] == b'.' { + is_float = true; + i += 1; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } + if i < b.len() && matches!(b[i], b'e' | b'E') { + is_float = true; + i += 1; + if i < b.len() && matches!(b[i], b'+' | b'-') { + i += 1; + } + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } + let num_end = i; + let mut has_f = false; + while i < b.len() && matches!(b[i], b'f' | b'F' | b'h' | b'H' | b'u' | b'U' | b'l' | b'L') { + if matches!(b[i], b'f' | b'F' | b'h' | b'H') { + has_f = true; + } + i += 1; + } + let raw = &src[start..num_end]; + if is_float || has_f { + let mut norm = raw.to_owned(); + if norm.starts_with('.') { + norm.insert(0, '0'); + } + if norm.ends_with('.') { + norm.push('0'); + } + if !norm.contains('.') && !norm.contains('e') && !norm.contains('E') { + norm.push_str(".0"); + } + norm.push('f'); + toks.push(Tok::Float(norm)); + } else { + toks.push(Tok::Int(raw.to_owned())); + } + continue; + } + // Two-character operators + if i + 1 < b.len() { + let two = &src[i..i + 2]; + if matches!( + two, + "->" | "==" + | "!=" + | "<=" + | ">=" + | "&&" + | "||" + | "++" + | "--" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "<<" + | ">>" + | "&=" + | "|=" + | "^=" + ) { + toks.push(Tok::Punct(two.to_owned())); + i += 2; + continue; + } + } + toks.push(Tok::Punct((c as char).to_string())); + i += 1; + } + toks +} + +// --------------------------------------------------------------------------- +// Type Mapping +// --------------------------------------------------------------------------- + +pub(super) fn c_type_to_wgsl(name: &str) -> Option<&'static str> { + match name { + "float" | "double" | "half" => Some("f32"), + "int" | "short" | "char" => Some("i32"), + "uint" | "unsigned" => Some("u32"), + "bool" => Some("bool"), + "void" => Some("void"), + "float2" => Some("vec2"), + "float3" => Some("vec3"), + "float4" => Some("vec4"), + "int2" => Some("vec2"), + "int3" => Some("vec3"), + "int4" => Some("vec4"), + "uint2" => Some("vec2"), + "uint3" => Some("vec3"), + "uint4" => Some("vec4"), + "float2x2" => Some("mat2x2"), + "float3x3" => Some("mat3x3"), + "float4x4" => Some("mat4x4"), + _ => None, + } +} + +pub(super) fn is_c_qualifier(s: &str) -> bool { + matches!( + s, + "const" + | "volatile" + | "inline" + | "static" + | "__CONSTANT__" + | "__CONSTANTREF__" + | "__GLOBAL__" + | "__LOCAL__" + | "__PRIVATE__" + ) +} + + +use super::dctl_parse::Transpiler; + +/// Transpiles a DCTL source string into a complete WebGPU-safe WGSL compute shader +/// (`@compute @workgroup_size(8, 8)`). +pub fn transpile_dctl_to_wgsl( + source: &str, + kernel_name: &str, + params_name: Option<&str>, + params_def: Option<&str>, + storage_format: wgpu::TextureFormat, +) -> Result { + let toks = lex_dctl(source); + let mut tr = Transpiler::new(toks); + if let Some(pname) = params_name + && !pname.is_empty() + { + tr.known_structs.insert(pname.to_owned()); + } + tr.parse_program()?; + + let kernel = tr + .kernels + .iter() + .find(|k| k.name == kernel_name) + .or_else(|| tr.kernels.first()) + .ok_or_else(|| format!("no `__KERNEL__` function `{kernel_name}` found in DCTL source"))?; + + let resolved_params_name = params_name + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .or_else(|| kernel.params_type.clone()) + .unwrap_or_else(|| "DctlParams".to_owned()); + + let param_layout = if let Some(def) = params_def.filter(|s| !s.trim().is_empty()) { + parse_param_block(def)? + } else if let Some(inline) = tr.inline_param_structs.get(&resolved_params_name) { + inline.clone() + } else { + ParamLayout { + fields: Vec::new(), + total_size: 16, + } + }; + + let fmt = wgsl_storage_format(storage_format); + let mut wgsl = String::with_capacity(source.len() * 2 + 1024); + + // 1. Meta uniform struct & parameter struct(s) + wgsl.push_str( + "struct _DctlMeta {\n\ + \x20 width: u32,\n\ + \x20 height: u32,\n\ + \x20 normalized: u32,\n\ + \x20 linear_filter: u32,\n\ + }\n\n", + ); + + let mut emitted_params_struct = false; + for (sname, sdef) in &tr.struct_defs { + if *sname == resolved_params_name { + wgsl.push_str(¶m_layout.to_wgsl_struct(&resolved_params_name)); + wgsl.push('\n'); + emitted_params_struct = true; + } else { + wgsl.push_str(sdef); + wgsl.push('\n'); + } + } + if !emitted_params_struct { + wgsl.push_str(¶m_layout.to_wgsl_struct(&resolved_params_name)); + wgsl.push('\n'); + } + + // 2. Bindings: 0 = params storage, 1 = sampler, 2 = meta uniform, 3.. = inputs, 3+N.. = outputs + wgsl.push_str(&format!( + "@group(0) @binding(0) var {}: {};\n", + kernel.params_var, resolved_params_name + )); + wgsl.push_str("@group(0) @binding(1) var _dctl_sampler: sampler;\n"); + wgsl.push_str("@group(0) @binding(2) var _dctl_meta: _DctlMeta;\n"); + + let mut binding = 3u32; + for tex in &kernel.input_textures { + wgsl.push_str(&format!("@group(0) @binding({binding}) var {tex}: texture_2d;\n")); + binding += 1; + } + for dst in &kernel.output_textures { + wgsl.push_str(&format!( + "@group(0) @binding({binding}) var {dst}: texture_storage_2d<{fmt}, write>;\n" + )); + binding += 1; + } + wgsl.push('\n'); + + // 3. Built-in DCTL helper functions + wgsl.push_str( + "fn _dctl_pow(base: f32, exp_v: f32) -> f32 {\n\ + \x20 if (base <= 0.0) { return select(0.0, 1.0, exp_v == 0.0); }\n\ + \x20 return pow(base, exp_v);\n\ + }\n\ + fn _dctl_fmod(x: f32, y: f32) -> f32 {\n\ + \x20 if (y == 0.0) { return 0.0; }\n\ + \x20 return x - y * trunc(x / y);\n\ + }\n\ + fn _dctl_copysign(x: f32, y: f32) -> f32 {\n\ + \x20 return select(-abs(x), abs(x), y >= 0.0);\n\ + }\n\ + fn _dctl_tex2d(t: texture_2d, fx: f32, fy: f32) -> vec4 {\n\ + \x20 let dims = textureDimensions(t);\n\ + \x20 if (_dctl_meta.normalized != 0u) {\n\ + \x20 return textureSampleLevel(t, _dctl_sampler, vec2(fx, 1.0 - fy), 0.0);\n\ + \x20 }\n\ + \x20 if (_dctl_meta.linear_filter != 0u) {\n\ + \x20 let uv = vec2((fx + 0.5) / f32(dims.x), 1.0 - (fy + 0.5) / f32(dims.y));\n\ + \x20 return textureSampleLevel(t, _dctl_sampler, uv, 0.0);\n\ + \x20 }\n\ + \x20 let ix = clamp(i32(round(fx)), 0, i32(dims.x) - 1);\n\ + \x20 let iy = clamp(i32(dims.y) - 1 - i32(round(fy)), 0, i32(dims.y) - 1);\n\ + \x20 return textureLoad(t, vec2(ix, iy), 0);\n\ + }\n\ + fn _dctl_tex2d_n(t: texture_2d, fx: f32, fy: f32, comp_order: i32) -> vec4 {\n\ + \x20 let c = _dctl_tex2d(t, fx, fy);\n\ + \x20 if (comp_order == 1) { return vec4(c.w, c.w, c.w, c.w); }\n\ + \x20 return c;\n\ + }\n\n", + ); + + // 4. Global constants and `__DEVICE__` helper functions + for g in &tr.globals_wgsl { + wgsl.push_str(g); + } + for h in &tr.helpers_wgsl { + wgsl.push_str(h); + wgsl.push('\n'); + } + + // 5. Compute entry point + let entry_point = "dctl_main".to_owned(); + let dims_expr = if let Some(dst0) = kernel.output_textures.first() { + format!("textureDimensions({dst0})") + } else { + "vec2(_dctl_meta.width, _dctl_meta.height)".to_owned() + }; + wgsl.push_str(&format!( + "@compute @workgroup_size(8, 8)\n\ + fn {entry_point}(@builtin(global_invocation_id) _dctl_gid: vec3) {{\n\ + \x20 let _dctl_dims = {dims_expr};\n\ + \x20 if (_dctl_gid.x >= _dctl_dims.x || _dctl_gid.y >= _dctl_dims.y) {{ return; }}\n" + )); + wgsl.push_str(&kernel.body_wgsl); + wgsl.push_str("}\n"); + + Ok(TranspiledKernel { + wgsl, + entry_point, + params_struct_name: resolved_params_name, + param_layout, + input_textures: kernel.input_textures.clone(), + output_textures: kernel.output_textures.clone(), + }) +} diff --git a/crates/engine/src/fuse_runtime/dctl_expr.rs b/crates/engine/src/fuse_runtime/dctl_expr.rs new file mode 100644 index 0000000000000000000000000000000000000000..2c29152265b48d59a8874bf4cf079a48967a3e0b --- /dev/null +++ b/crates/engine/src/fuse_runtime/dctl_expr.rs @@ -0,0 +1,446 @@ +//! DCTL expression parser and intrinsic-to-WGSL rewriter. + +use super::dctl::Tok; +use super::dctl_parse::Transpiler; + +impl Transpiler { + // ----------------------------------------------------------------------- + // Expressions + // ----------------------------------------------------------------------- + + fn looks_boolean(&self, expr: &str) -> bool { + let t = expr.trim(); + if t == "true" || t == "false" || self.bool_vars.contains(t) { + return true; + } + if t.starts_with('!') { + return true; + } + // Check top-level (paren-depth 0) comparison or logical operator + let b = t.as_bytes(); + let mut depth = 0i32; + let mut i = 0; + while i < b.len() { + match b[i] { + b'(' | b'[' => depth += 1, + b')' | b']' => depth -= 1, + _ if depth == 0 => { + if i + 1 < b.len() { + let two = &t[i..i + 2]; + if matches!(two, "==" | "!=" | "<=" | ">=" | "&&" | "||") { + return true; + } + } + if matches!(b[i], b'<' | b'>') { + // Avoid matching `` inside `vec3` + let prev_alpha = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); + if !prev_alpha || b[i] == b'>' { + if b[i] == b'<' && !prev_alpha { + return true; + } + if b[i] == b'>' && !t[..i].ends_with("f32") && !t[..i].ends_with("i32") && !t[..i].ends_with("u32") { + return true; + } + } + } + } + _ => {} + } + i += 1; + } + // Unwrap outer parentheses and check recursively + if t.starts_with('(') && t.ends_with(')') { + let mut d = 0i32; + let mut wraps_all = true; + for (idx, &ch) in b.iter().enumerate() { + if ch == b'(' { + d += 1; + } else if ch == b')' { + d -= 1; + if d == 0 && idx + 1 < b.len() { + wraps_all = false; + break; + } + } + } + if wraps_all { + return self.looks_boolean(&t[1..t.len() - 1]); + } + } + false + } + + pub(super) fn parse_bool_expr(&mut self) -> Result { + let e = self.parse_expr()?; + if self.looks_boolean(&e) { + Ok(e) + } else { + Ok(format!("(({e}) != 0)")) + } + } + + pub(super) fn parse_expr(&mut self) -> Result { + self.parse_assign() + } + + fn parse_assign(&mut self) -> Result { + let lhs = self.parse_ternary()?; + for op in ["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^="] { + if self.eat_punct(op) { + let rhs = self.parse_assign()?; + return Ok(format!("{lhs} {op} {rhs}")); + } + } + Ok(lhs) + } + + fn parse_ternary(&mut self) -> Result { + let cond = self.parse_logical_or()?; + if self.eat_punct("?") { + let then_e = self.parse_expr()?; + self.expect_punct(":")?; + let else_e = self.parse_ternary()?; + let bcond = if self.looks_boolean(&cond) { + cond + } else { + format!("(({cond}) != 0)") + }; + Ok(format!("select({else_e}, {then_e}, {bcond})")) + } else { + Ok(cond) + } + } + + fn parse_logical_or(&mut self) -> Result { + let mut lhs = self.parse_logical_and()?; + while self.eat_punct("||") { + let rhs = self.parse_logical_and()?; + lhs = format!("({lhs} || {rhs})"); + } + Ok(lhs) + } + + fn parse_logical_and(&mut self) -> Result { + let mut lhs = self.parse_bit_or()?; + while self.eat_punct("&&") { + let rhs = self.parse_bit_or()?; + lhs = format!("({lhs} && {rhs})"); + } + Ok(lhs) + } + + fn parse_bit_or(&mut self) -> Result { + let mut lhs = self.parse_bit_xor()?; + while self.eat_punct("|") { + let rhs = self.parse_bit_xor()?; + lhs = format!("({lhs} | {rhs})"); + } + Ok(lhs) + } + + fn parse_bit_xor(&mut self) -> Result { + let mut lhs = self.parse_bit_and()?; + while self.eat_punct("^") { + let rhs = self.parse_bit_and()?; + lhs = format!("({lhs} ^ {rhs})"); + } + Ok(lhs) + } + + fn parse_bit_and(&mut self) -> Result { + let mut lhs = self.parse_eq()?; + while self.eat_punct("&") { + let rhs = self.parse_eq()?; + lhs = format!("({lhs} & {rhs})"); + } + Ok(lhs) + } + + fn parse_eq(&mut self) -> Result { + let mut lhs = self.parse_rel()?; + loop { + if self.eat_punct("==") { + let rhs = self.parse_rel()?; + lhs = format!("({lhs} == {rhs})"); + } else if self.eat_punct("!=") { + let rhs = self.parse_rel()?; + lhs = format!("({lhs} != {rhs})"); + } else { + break; + } + } + Ok(lhs) + } + + fn parse_rel(&mut self) -> Result { + let mut lhs = self.parse_shift()?; + loop { + let op = if self.eat_punct("<=") { + "<=" + } else if self.eat_punct(">=") { + ">=" + } else if self.eat_punct("<") { + "<" + } else if self.eat_punct(">") { + ">" + } else { + break; + }; + let rhs = self.parse_shift()?; + lhs = format!("({lhs} {op} {rhs})"); + } + Ok(lhs) + } + + fn parse_shift(&mut self) -> Result { + let mut lhs = self.parse_add()?; + loop { + let op = if self.eat_punct("<<") { + "<<" + } else if self.eat_punct(">>") { + ">>" + } else { + break; + }; + let rhs = self.parse_add()?; + lhs = format!("({lhs} {op} {rhs})"); + } + Ok(lhs) + } + + fn parse_add(&mut self) -> Result { + let mut lhs = self.parse_mul()?; + loop { + let op = if self.eat_punct("+") { + "+" + } else if self.eat_punct("-") { + "-" + } else { + break; + }; + let rhs = self.parse_mul()?; + lhs = format!("({lhs} {op} {rhs})"); + } + Ok(lhs) + } + + fn parse_mul(&mut self) -> Result { + let mut lhs = self.parse_unary()?; + loop { + let op = if self.eat_punct("*") { + "*" + } else if self.eat_punct("/") { + "/" + } else if self.eat_punct("%") { + "%" + } else { + break; + }; + let rhs = self.parse_unary()?; + lhs = format!("({lhs} {op} {rhs})"); + } + Ok(lhs) + } + + fn try_parse_c_cast(&mut self) -> Option { + if !self.is_punct("(") { + return None; + } + let (ty, consumed) = self.peek_type_at(self.pos + 1)?; + if matches!(self.toks.get(self.pos + 1 + consumed), Some(Tok::Punct(p)) if p == ")") { + self.pos += 2 + consumed; + return Some(ty); + } + None + } + + pub(super) fn parse_unary(&mut self) -> Result { + if let Some(cast_ty) = self.try_parse_c_cast() { + let inner = self.parse_unary()?; + return Ok(format!("{cast_ty}({inner})")); + } + if self.eat_punct("-") { + let inner = self.parse_unary()?; + return Ok(format!("(-{inner})")); + } + if self.eat_punct("+") { + return self.parse_unary(); + } + if self.eat_punct("!") { + let inner = self.parse_unary()?; + if self.looks_boolean(&inner) { + return Ok(format!("(!({inner}))")); + } + return Ok(format!("(({inner}) == 0)")); + } + if self.eat_punct("~") { + let inner = self.parse_unary()?; + return Ok(format!("(~{inner})")); + } + if self.eat_punct("*") { + let inner = self.parse_unary()?; + return Ok(format!("(*{inner})")); + } + if self.eat_punct("&") { + let inner = self.parse_unary()?; + return Ok(format!("(&{inner})")); + } + self.parse_postfix() + } + + fn parse_postfix(&mut self) -> Result { + let mut expr = self.parse_primary()?; + loop { + if self.eat_punct("(") { + let mut args = Vec::new(); + while !self.is_punct(")") && self.pos < self.toks.len() { + args.push(self.parse_expr()?); + if !self.eat_punct(",") { + break; + } + } + self.expect_punct(")")?; + expr = rewrite_dctl_call(&expr, &args); + } else if self.eat_punct("[") { + let idx = self.parse_expr()?; + self.expect_punct("]")?; + expr = format!("{expr}[{idx}]"); + } else if self.eat_punct(".") || self.eat_punct("->") { + let field = self.expect_ident()?; + expr = format!("{expr}.{field}"); + } else { + break; + } + } + Ok(expr) + } + + fn parse_primary(&mut self) -> Result { + match self.bump() { + Some(Tok::Float(s)) => Ok(s), + Some(Tok::Int(s)) => Ok(s), + Some(Tok::Ident(id)) => Ok(match id.as_str() { + "M_PI" | "CUDART_PI_F" => "3.141592653589793f".to_owned(), + "M_PI_2" => "1.5707963267948966f".to_owned(), + "M_PI_4" => "0.7853981633974483f".to_owned(), + "M_2PI" | "M_TWOPI" => "6.283185307179586f".to_owned(), + "M_1_PI" => "0.3183098861837907f".to_owned(), + "M_E" => "2.718281828459045f".to_owned(), + "M_SQRT2" => "1.4142135623730951f".to_owned(), + _ => id, + }), + Some(Tok::Punct(p)) if p == "(" => { + let inner = self.parse_expr()?; + self.expect_punct(")")?; + Ok(format!("({inner})")) + } + other => Err(format!("unexpected token in expression: {other:?}")), + } + } +} + +fn rewrite_dctl_call(name: &str, args: &[String]) -> String { + let a = |i: usize| args.get(i).map(String::as_str).unwrap_or("0.0"); + match name { + // Vector constructors + "to_float2" | "make_float2" => match args.len() { + 1 => format!("vec2(f32({}))", a(0)), + _ => format!("vec2(f32({}), f32({}))", a(0), a(1)), + }, + "to_float3" | "make_float3" => match args.len() { + 1 => format!("vec3(f32({}))", a(0)), + 2 => format!("vec3({}, f32({}))", a(0), a(1)), + _ => format!("vec3(f32({}), f32({}), f32({}))", a(0), a(1), a(2)), + }, + "to_float4" | "make_float4" => match args.len() { + 1 => format!("vec4(f32({}))", a(0)), + 2 => format!("vec4({}, f32({}))", a(0), a(1)), + 3 => format!("vec4({}, f32({}), f32({}))", a(0), a(1), a(2)), + _ => format!( + "vec4(f32({}), f32({}), f32({}), f32({}))", + a(0), + a(1), + a(2), + a(3) + ), + }, + "to_float2_s" => format!("vec2(f32({}))", a(0)), + "to_float3_s" => format!("vec3(f32({}))", a(0)), + "to_float4_s" => format!("vec4(f32({}))", a(0)), + "to_float2_v" => format!("vec2({0}[0], {0}[1])", a(0)), + "to_float3_v" => format!("vec3({0}[0], {0}[1], {0}[2])", a(0)), + "to_float4_v" => format!("vec4({0}[0], {0}[1], {0}[2], {0}[3])", a(0)), + "to_float3_aw" => format!("vec3({}, f32({}))", a(0), a(1)), + "to_float4_aw" => format!("vec4({}, f32({}))", a(0), a(1)), + "to_int2" | "make_int2" => format!("vec2(i32({}), i32({}))", a(0), a(1)), + "to_int3" | "make_int3" => format!("vec3(i32({}), i32({}), i32({}))", a(0), a(1), a(2)), + "to_int4" | "make_int4" => format!( + "vec4(i32({}), i32({}), i32({}), i32({}))", + a(0), + a(1), + a(2), + a(3) + ), + + // Swizzles + "swi2" if args.len() == 3 => format!("(({}).{}{})", a(0), a(1), a(2)), + "swi3" if args.len() == 4 => format!("(({}).{}{}{})", a(0), a(1), a(2), a(3)), + "swi4" if args.len() == 5 => format!("(({}).{}{}{}{})", a(0), a(1), a(2), a(3), a(4)), + + // Texture reads & writes + "_tex2DVecN" if args.len() >= 4 => { + format!("_dctl_tex2d_n({}, f32({}), f32({}), i32({}))", a(0), a(1), a(2), a(3)) + } + "_tex2DVec4" if args.len() >= 3 => { + format!("_dctl_tex2d({}, f32({}), f32({}))", a(0), a(1), a(2)) + } + "_tex2DVec4Write" if args.len() >= 4 => format!( + "textureStore({0}, vec2(i32({1}), i32(textureDimensions({0}).y) - 1 - i32({2})), {3})", + a(0), + a(1), + a(2), + a(3) + ), + + // Math intrinsics + "_sinf" => format!("sin({})", a(0)), + "_cosf" => format!("cos({})", a(0)), + "_tanf" => format!("tan({})", a(0)), + "_asinf" => format!("asin({})", a(0)), + "_acosf" => format!("acos({})", a(0)), + "_atanf" => format!("atan({})", a(0)), + "_atan2f" => format!("atan2({}, {})", a(0), a(1)), + "_sinhf" => format!("sinh({})", a(0)), + "_coshf" => format!("cosh({})", a(0)), + "_tanhf" => format!("tanh({})", a(0)), + "_sqrtf" => format!("sqrt(max({}, 0.0))", a(0)), + "_rsqrtf" => format!("inverseSqrt(max({}, 1e-12))", a(0)), + "_powf" => format!("_dctl_pow({}, {})", a(0), a(1)), + "_fabs" | "_fabsf" => format!("abs({})", a(0)), + "_fmod" | "_fmodf" => format!("_dctl_fmod({}, {})", a(0), a(1)), + "_floorf" | "_floor" => format!("floor({})", a(0)), + "_ceilf" | "_ceil" => format!("ceil({})", a(0)), + "_round" | "_roundf" => format!("round({})", a(0)), + "_truncf" => format!("trunc({})", a(0)), + "_fractf" | "_fract" => format!("fract({})", a(0)), + "_fminf" => format!("min({}, {})", a(0), a(1)), + "_fmaxf" => format!("max({}, {})", a(0), a(1)), + "_clampf" => format!("clamp({}, {}, {})", a(0), a(1), a(2)), + "_mix" => format!("mix({}, {}, {})", a(0), a(1), a(2)), + "_saturatef" => format!("clamp({}, 0.0, 1.0)", a(0)), + "_expf" => format!("exp({})", a(0)), + "_exp2f" => format!("exp2({})", a(0)), + "_logf" => format!("log(max({}, 1e-12))", a(0)), + "_log2f" => format!("log2(max({}, 1e-12))", a(0)), + "_log10f" => format!("(log(max({}, 1e-12)) * 0.4342944819032518)", a(0)), + "_copysignf" => format!("_dctl_copysign({}, {})", a(0), a(1)), + "_hypotf" => format!("length(vec2({}, {}))", a(0), a(1)), + "_fdivide" => format!("(({}) / ({}))", a(0), a(1)), + "_fmaf" => format!("fma({}, {}, {})", a(0), a(1), a(2)), + "_smoothstep" => format!("smoothstep({}, {}, {})", a(0), a(1), a(2)), + "_step" => format!("step({}, {})", a(0), a(1)), + "_sign" => format!("sign({})", a(0)), + _ => format!("{name}({})", args.join(", ")), + } +} + diff --git a/crates/engine/src/fuse_runtime/dctl_parse.rs b/crates/engine/src/fuse_runtime/dctl_parse.rs new file mode 100644 index 0000000000000000000000000000000000000000..bea1f6b95924681edb53397f261869967d9188c7 --- /dev/null +++ b/crates/engine/src/fuse_runtime/dctl_parse.rs @@ -0,0 +1,695 @@ +//! DCTL top-level declaration and statement parser/emitter. + +use std::collections::{HashMap, HashSet}; + +use super::dctl::{ParamLayout, Tok, c_type_to_wgsl, is_c_qualifier, parse_param_block}; + +// --------------------------------------------------------------------------- +// Parser & WGSL Emitter +// --------------------------------------------------------------------------- + +pub(super) struct KernelInfo { + pub(super) name: String, + pub(super) params_type: Option, + pub(super) params_var: String, + pub(super) input_textures: Vec, + pub(super) output_textures: Vec, + pub(super) body_wgsl: String, +} + +pub(super) struct Transpiler { + pub(super) toks: Vec, + pub(super) pos: usize, + pub(super) known_structs: HashSet, + pub(super) struct_defs: Vec<(String, String)>, + pub(super) inline_param_structs: HashMap, + pub(super) globals_wgsl: Vec, + pub(super) helpers_wgsl: Vec, + pub(super) kernels: Vec, + pub(super) bool_vars: HashSet, + /// Variables in current function that hold a pointer (`*p`). + ptr_vars: HashSet, + /// Variables that are `__CONSTANTREF__` struct refs (accessed via `.` after `->`). + struct_ref_vars: HashSet, +} + +impl Transpiler { + pub(super) fn new(toks: Vec) -> Self { + Self { + toks, + pos: 0, + known_structs: HashSet::new(), + struct_defs: Vec::new(), + inline_param_structs: HashMap::new(), + globals_wgsl: Vec::new(), + helpers_wgsl: Vec::new(), + kernels: Vec::new(), + bool_vars: HashSet::new(), + ptr_vars: HashSet::new(), + struct_ref_vars: HashSet::new(), + } + } + + pub(super) fn peek(&self) -> Option<&Tok> { + self.toks.get(self.pos) + } + + fn peek_n(&self, n: usize) -> Option<&Tok> { + self.toks.get(self.pos + n) + } + + pub(super) fn bump(&mut self) -> Option { + let t = self.toks.get(self.pos)?.clone(); + self.pos += 1; + Some(t) + } + + pub(super) fn is_punct(&self, p: &str) -> bool { + matches!(self.peek(), Some(Tok::Punct(s)) if s == p) + } + + fn is_ident(&self, id: &str) -> bool { + matches!(self.peek(), Some(Tok::Ident(s)) if s == id) + } + + pub(super) fn eat_punct(&mut self, p: &str) -> bool { + if self.is_punct(p) { + self.pos += 1; + true + } else { + false + } + } + + pub(super) fn expect_punct(&mut self, p: &str) -> Result<(), String> { + if self.eat_punct(p) { + Ok(()) + } else { + Err(format!("expected `{p}` near {:?}", self.peek())) + } + } + + pub(super) fn expect_ident(&mut self) -> Result { + match self.bump() { + Some(Tok::Ident(s)) => Ok(s), + other => Err(format!("expected identifier, got {other:?}")), + } + } + + fn skip_qualifiers(&mut self) -> bool { + let mut saw_const = false; + while let Some(Tok::Ident(s)) = self.peek() { + if is_c_qualifier(s) { + if s == "const" || s == "__CONSTANT__" { + saw_const = true; + } + self.pos += 1; + } else { + break; + } + } + saw_const + } + + pub(super) fn peek_type_at(&self, idx: usize) -> Option<(String, usize)> { + let Tok::Ident(first) = self.toks.get(idx)? else { + return None; + }; + if first == "unsigned" { + if let Some(Tok::Ident(second)) = self.toks.get(idx + 1) + && second == "int" + { + return Some(("u32".to_owned(), 2)); + } + return Some(("u32".to_owned(), 1)); + } + if first == "struct" { + if let Some(Tok::Ident(sname)) = self.toks.get(idx + 1) { + return Some((sname.clone(), 2)); + } + return None; + } + if let Some(wgsl) = c_type_to_wgsl(first) { + return Some((wgsl.to_owned(), 1)); + } + if self.known_structs.contains(first) { + return Some((first.clone(), 1)); + } + None + } + + fn parse_type(&mut self) -> Result { + let Some((ty, consumed)) = self.peek_type_at(self.pos) else { + return Err(format!("expected type near {:?}", self.peek())); + }; + self.pos += consumed; + Ok(ty) + } + + pub(super) fn parse_program(&mut self) -> Result<(), String> { + while self.pos < self.toks.len() { + if self.eat_punct(";") { + continue; + } + if self.is_ident("typedef") { + self.parse_typedef_struct()?; + } else if self.is_ident("struct") { + self.parse_struct_def()?; + } else if self.is_ident("__KERNEL__") { + self.pos += 1; + self.parse_kernel()?; + } else if self.is_ident("__DEVICE__") { + self.pos += 1; + self.parse_device_fn()?; + } else { + // Could be a global const or unmarked helper function. + let save = self.pos; + let _ = self.skip_qualifiers(); + if self.peek_type_at(self.pos).is_some() { + let _ty = self.parse_type()?; + if matches!(self.peek(), Some(Tok::Ident(_))) + && matches!(self.peek_n(1), Some(Tok::Punct(p)) if p == "(") + { + self.pos = save; + self.parse_device_fn()?; + continue; + } + self.pos = save; + self.parse_global_const()?; + } else { + // Skip unknown top-level token safely. + self.pos += 1; + } + } + } + Ok(()) + } + + fn parse_typedef_struct(&mut self) -> Result<(), String> { + self.pos += 1; // typedef + if !self.is_ident("struct") { + while self.pos < self.toks.len() && !self.eat_punct(";") { + self.pos += 1; + } + return Ok(()); + } + self.pos += 1; // struct + // Optional tag name before `{` + if matches!(self.peek(), Some(Tok::Ident(_))) { + self.pos += 1; + } + let body_text = self.collect_brace_raw_text()?; + let name = self.expect_ident()?; + let _ = self.eat_punct(";"); + let layout = parse_param_block(&body_text)?; + let wgsl = layout.to_wgsl_struct(&name); + self.known_structs.insert(name.clone()); + self.inline_param_structs.insert(name.clone(), layout); + self.struct_defs.push((name, wgsl)); + Ok(()) + } + + fn parse_struct_def(&mut self) -> Result<(), String> { + self.pos += 1; // struct + let name = self.expect_ident()?; + let body_text = self.collect_brace_raw_text()?; + let _ = self.eat_punct(";"); + let layout = parse_param_block(&body_text)?; + let wgsl = layout.to_wgsl_struct(&name); + self.known_structs.insert(name.clone()); + self.inline_param_structs.insert(name.clone(), layout); + self.struct_defs.push((name, wgsl)); + Ok(()) + } + + fn collect_brace_raw_text(&mut self) -> Result { + self.expect_punct("{")?; + let mut depth = 1usize; + let mut s = String::new(); + while self.pos < self.toks.len() && depth > 0 { + match self.bump().unwrap() { + Tok::Punct(p) if p == "{" => { + depth += 1; + s.push_str("{ "); + } + Tok::Punct(p) if p == "}" => { + depth -= 1; + if depth > 0 { + s.push_str("} "); + } + } + Tok::Ident(id) => { + s.push_str(&id); + s.push(' '); + } + Tok::Int(n) | Tok::Float(n) => { + s.push_str(&n); + s.push(' '); + } + Tok::Punct(p) => { + s.push_str(&p); + if p == ";" { + s.push('\n'); + } + } + } + } + Ok(s) + } + + fn parse_global_const(&mut self) -> Result<(), String> { + let _ = self.skip_qualifiers(); + let ty = self.parse_type()?; + let name = self.expect_ident()?; + let arr_len = if self.eat_punct("[") { + let n = if let Some(Tok::Int(s)) = self.peek() { + let s = s.clone(); + self.pos += 1; + Some(s) + } else { + None + }; + self.expect_punct("]")?; + n + } else { + None + }; + self.expect_punct("=")?; + if let Some(len) = arr_len { + let items = self.parse_brace_init_list()?; + self.expect_punct(";")?; + self.globals_wgsl.push(format!( + "const {name}: array<{ty}, {len}> = array<{ty}, {len}>({});\n", + items.join(", ") + )); + } else { + let expr = self.parse_expr()?; + self.expect_punct(";")?; + self.globals_wgsl + .push(format!("const {name}: {ty} = {expr};\n")); + } + Ok(()) + } + + fn parse_device_fn(&mut self) -> Result<(), String> { + let _ = self.skip_qualifiers(); + let ret_ty = self.parse_type()?; + let name = self.expect_ident()?; + self.expect_punct("(")?; + + let mut wgsl_params = Vec::new(); + let mut prelude = Vec::new(); + self.bool_vars.clear(); + self.ptr_vars.clear(); + self.struct_ref_vars.clear(); + + while !self.is_punct(")") && self.pos < self.toks.len() { + let mut is_const_ref = false; + while let Some(Tok::Ident(s)) = self.peek() { + if s == "__CONSTANTREF__" { + is_const_ref = true; + self.pos += 1; + } else if is_c_qualifier(s) { + self.pos += 1; + } else { + break; + } + } + if self.is_ident("void") && matches!(self.peek_n(1), Some(Tok::Punct(p)) if p == ")") { + self.pos += 1; + break; + } + let pty = self.parse_type()?; + let is_ptr = self.eat_punct("*"); + let pname = self.expect_ident()?; + if pty == "bool" { + self.bool_vars.insert(pname.clone()); + } + if is_const_ref && is_ptr { + wgsl_params.push(format!("_p_{pname}: {pty}")); + prelude.push(format!(" let {pname} = _p_{pname};\n")); + self.struct_ref_vars.insert(pname); + } else if is_ptr { + wgsl_params.push(format!("{pname}: ptr")); + self.ptr_vars.insert(pname); + } else { + wgsl_params.push(format!("_p_{pname}: {pty}")); + prelude.push(format!(" var {pname}: {pty} = _p_{pname};\n")); + } + if !self.eat_punct(",") { + break; + } + } + self.expect_punct(")")?; + if self.eat_punct(";") { + // Forward prototype — WGSL does not need forward declarations. + return Ok(()); + } + let body = self.parse_block_inner()?; + let ret_clause = if ret_ty == "void" { + String::new() + } else { + format!(" -> {ret_ty}") + }; + let mut fn_wgsl = format!("fn {name}({}){ret_clause} {{\n", wgsl_params.join(", ")); + for line in prelude { + fn_wgsl.push_str(&line); + } + fn_wgsl.push_str(&body); + fn_wgsl.push_str("}\n"); + self.helpers_wgsl.push(fn_wgsl); + Ok(()) + } + + fn parse_kernel(&mut self) -> Result<(), String> { + let _ = self.skip_qualifiers(); + let _ret = self.parse_type()?; // void + let name = self.expect_ident()?; + self.expect_punct("(")?; + + let mut params_type = None; + let mut params_var = "params".to_owned(); + let mut input_textures = Vec::new(); + let mut output_textures = Vec::new(); + self.bool_vars.clear(); + self.ptr_vars.clear(); + self.struct_ref_vars.clear(); + + while !self.is_punct(")") && self.pos < self.toks.len() { + if self.is_ident("__CONSTANTREF__") { + self.pos += 1; + let _ = self.skip_qualifiers(); + let ty = self.expect_ident()?; + let _ = self.eat_punct("*"); + let var = self.expect_ident()?; + self.known_structs.insert(ty.clone()); + self.struct_ref_vars.insert(var.clone()); + params_type = Some(ty); + params_var = var; + } else if self.is_ident("__TEXTURE2D__") { + self.pos += 1; + let var = self.expect_ident()?; + input_textures.push(var); + } else if self.is_ident("__TEXTURE2D_WRITE__") { + self.pos += 1; + let var = self.expect_ident()?; + output_textures.push(var); + } else { + // Skip optional extra kernel arguments cleanly + let _ = self.skip_qualifiers(); + let _ = self.bump(); + let _ = self.eat_punct("*"); + if matches!(self.peek(), Some(Tok::Ident(_))) { + self.pos += 1; + } + } + if !self.eat_punct(",") { + break; + } + } + self.expect_punct(")")?; + let body_wgsl = self.parse_block_inner()?; + self.kernels.push(KernelInfo { + name, + params_type, + params_var, + input_textures, + output_textures, + body_wgsl, + }); + Ok(()) + } + + fn parse_block_inner(&mut self) -> Result { + self.expect_punct("{")?; + let mut out = String::new(); + while !self.is_punct("}") && self.pos < self.toks.len() { + self.parse_stmt(&mut out, 1)?; + } + self.expect_punct("}")?; + Ok(out) + } + + fn parse_stmt_or_block(&mut self, out: &mut String, indent: usize) -> Result<(), String> { + if self.is_punct("{") { + self.pos += 1; + while !self.is_punct("}") && self.pos < self.toks.len() { + self.parse_stmt(out, indent)?; + } + self.expect_punct("}")?; + } else { + self.parse_stmt(out, indent)?; + } + Ok(()) + } + + fn parse_stmt(&mut self, out: &mut String, indent: usize) -> Result<(), String> { + let pad = " ".repeat(indent); + if self.eat_punct(";") { + return Ok(()); + } + if self.is_punct("{") { + out.push_str(&format!("{pad}{{\n")); + self.parse_stmt_or_block(out, indent + 1)?; + out.push_str(&format!("{pad}}}\n")); + return Ok(()); + } + if self.is_ident("DEFINE_KERNEL_ITERATORS_XY") { + self.pos += 1; + self.expect_punct("(")?; + let x_var = self.expect_ident()?; + self.expect_punct(",")?; + let y_var = self.expect_ident()?; + self.expect_punct(")")?; + let _ = self.eat_punct(";"); + out.push_str(&format!( + "{pad}var {x_var}: i32 = i32(_dctl_gid.x);\n\ + {pad}var {y_var}: i32 = i32(_dctl_dims.y - 1u - _dctl_gid.y);\n" + )); + return Ok(()); + } + if self.is_ident("if") { + self.pos += 1; + self.expect_punct("(")?; + let cond = self.parse_bool_expr()?; + self.expect_punct(")")?; + out.push_str(&format!("{pad}if ({cond}) {{\n")); + self.parse_stmt_or_block(out, indent + 1)?; + out.push_str(&format!("{pad}}}")); + if self.is_ident("else") { + self.pos += 1; + if self.is_ident("if") { + out.push_str(" else "); + let mut nested = String::new(); + self.parse_stmt(&mut nested, indent)?; + out.push_str(nested.trim_start()); + } else { + out.push_str(" else {\n"); + self.parse_stmt_or_block(out, indent + 1)?; + out.push_str(&format!("{pad}}}\n")); + } + } else { + out.push('\n'); + } + return Ok(()); + } + if self.is_ident("for") { + self.pos += 1; + self.expect_punct("(")?; + let init = if self.is_punct(";") { + self.pos += 1; + String::new() + } else if self.is_var_decl_ahead() { + self.parse_single_var_decl_inline()? + } else { + let e = self.parse_expr_stmt_inline()?; + self.expect_punct(";")?; + e + }; + let cond = if self.is_punct(";") { + self.pos += 1; + String::new() + } else { + let c = self.parse_bool_expr()?; + self.expect_punct(";")?; + c + }; + let step = if self.is_punct(")") { + String::new() + } else { + self.parse_expr_stmt_inline()? + }; + self.expect_punct(")")?; + out.push_str(&format!("{pad}for ({init}; {cond}; {step}) {{\n")); + self.parse_stmt_or_block(out, indent + 1)?; + out.push_str(&format!("{pad}}}\n")); + return Ok(()); + } + if self.is_ident("while") { + self.pos += 1; + self.expect_punct("(")?; + let cond = self.parse_bool_expr()?; + self.expect_punct(")")?; + out.push_str(&format!("{pad}while ({cond}) {{\n")); + self.parse_stmt_or_block(out, indent + 1)?; + out.push_str(&format!("{pad}}}\n")); + return Ok(()); + } + if self.is_ident("do") { + self.pos += 1; + out.push_str(&format!("{pad}loop {{\n")); + self.parse_stmt_or_block(out, indent + 1)?; + if !self.is_ident("while") { + return Err("expected `while` after `do` block".to_owned()); + } + self.pos += 1; + self.expect_punct("(")?; + let cond = self.parse_bool_expr()?; + self.expect_punct(")")?; + let _ = self.eat_punct(";"); + out.push_str(&format!("{pad} if (!({cond})) {{ break; }}\n{pad}}}\n")); + return Ok(()); + } + if self.is_ident("return") { + self.pos += 1; + if self.eat_punct(";") { + out.push_str(&format!("{pad}return;\n")); + } else { + let e = self.parse_expr()?; + self.expect_punct(";")?; + out.push_str(&format!("{pad}return {e};\n")); + } + return Ok(()); + } + if self.is_ident("break") { + self.pos += 1; + self.expect_punct(";")?; + out.push_str(&format!("{pad}break;\n")); + return Ok(()); + } + if self.is_ident("continue") { + self.pos += 1; + self.expect_punct(";")?; + out.push_str(&format!("{pad}continue;\n")); + return Ok(()); + } + if self.is_var_decl_ahead() { + self.parse_var_decl_stmt(out, &pad)?; + return Ok(()); + } + let expr_stmt = self.parse_expr_stmt_inline()?; + self.expect_punct(";")?; + out.push_str(&format!("{pad}{expr_stmt};\n")); + Ok(()) + } + + fn is_var_decl_ahead(&self) -> bool { + let mut idx = self.pos; + while let Some(Tok::Ident(s)) = self.toks.get(idx) { + if is_c_qualifier(s) { + idx += 1; + } else { + break; + } + } + let Some((_, consumed)) = self.peek_type_at(idx) else { + return false; + }; + let next_idx = idx + consumed; + matches!(self.toks.get(next_idx), Some(Tok::Ident(_))) + } + + fn parse_var_decl_stmt(&mut self, out: &mut String, pad: &str) -> Result<(), String> { + let is_const = self.skip_qualifiers(); + let ty = self.parse_type()?; + let kw = if is_const { "let" } else { "var" }; + loop { + let name = self.expect_ident()?; + if ty == "bool" { + self.bool_vars.insert(name.clone()); + } + let arr_len = if self.eat_punct("[") { + let n = if let Some(Tok::Int(s)) = self.peek() { + let s = s.clone(); + self.pos += 1; + Some(s) + } else { + None + }; + self.expect_punct("]")?; + n + } else { + None + }; + if self.eat_punct("=") { + if let Some(len) = arr_len { + let items = self.parse_brace_init_list()?; + out.push_str(&format!( + "{pad}{kw} {name}: array<{ty}, {len}> = array<{ty}, {len}>({});\n", + items.join(", ") + )); + } else { + let init = self.parse_expr()?; + out.push_str(&format!("{pad}{kw} {name}: {ty} = {init};\n")); + } + } else if let Some(len) = arr_len { + out.push_str(&format!("{pad}var {name}: array<{ty}, {len}>;\n")); + } else { + out.push_str(&format!("{pad}var {name}: {ty};\n")); + } + if !self.eat_punct(",") { + break; + } + } + self.expect_punct(";")?; + Ok(()) + } + + fn parse_single_var_decl_inline(&mut self) -> Result { + let _ = self.skip_qualifiers(); + let ty = self.parse_type()?; + let name = self.expect_ident()?; + let res = if self.eat_punct("=") { + let init = self.parse_expr()?; + format!("var {name}: {ty} = {init}") + } else { + format!("var {name}: {ty}") + }; + self.expect_punct(";")?; + Ok(res) + } + + fn parse_expr_stmt_inline(&mut self) -> Result { + // Handle prefix `++x` / `--x` as statement -> `x += 1` / `x -= 1` + if self.eat_punct("++") { + let lhs = self.parse_unary()?; + return Ok(format!("{lhs} += 1")); + } + if self.eat_punct("--") { + let lhs = self.parse_unary()?; + return Ok(format!("{lhs} -= 1")); + } + let lhs = self.parse_expr()?; + if self.eat_punct("++") { + return Ok(format!("{lhs} += 1")); + } + if self.eat_punct("--") { + return Ok(format!("{lhs} -= 1")); + } + Ok(lhs) + } + + fn parse_brace_init_list(&mut self) -> Result, String> { + self.expect_punct("{")?; + let mut items = Vec::new(); + while !self.is_punct("}") && self.pos < self.toks.len() { + items.push(self.parse_expr()?); + if !self.eat_punct(",") { + break; + } + } + self.expect_punct("}")?; + Ok(items) + } + +} diff --git a/crates/engine/src/fuse_runtime/lua_bridge.rs b/crates/engine/src/fuse_runtime/lua_bridge.rs new file mode 100644 index 0000000000000000000000000000000000000000..dca851252d8b2d026da4f3b70b8df68905fb9638 --- /dev/null +++ b/crates/engine/src/fuse_runtime/lua_bridge.rs @@ -0,0 +1,287 @@ +//! GPU + Comp host bridge shared with the sandboxed Fusion Lua runtime. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; + +use model::{BitDepth, Gradient}; + +use crate::cache::CachedTexture; +use crate::eval::create_texture_dod_fmt; + +use super::lua_types::ImageInner; +use super::{DctlPipelineCache, FuseMeta}; + +/// Pre-evaluated Fusion parameter value passed from `Comp` / `Node` into the Lua host. +#[derive(Clone, Debug)] +pub enum EvalParam { + Number(f64), + Point([f64; 2]), + Text(String), + Gradient(Gradient), +} + +/// GPU + Comp bridge stored in `Lua` app data during a single Fuse execution. +pub struct HostBridge { + pub device: wgpu::Device, + pub queue: wgpu::Queue, + pub encoder: Option, + pub dummy_tex: CachedTexture, + pub pipeline_cache: Arc>, + pub supports_f32_filter: bool, + pub hiq: bool, + pub default_depth: BitDepth, + pub comp_dims: [u32; 2], + pub time: f64, + pub global_range: [i64; 2], + pub render_range: [i64; 2], + pub upstream_images: HashMap, + pub main_input: Option, + pub params: HashMap, + pub fuse_meta: FuseMeta, + pub output_image: Option>>, + pub tool_data: HashMap, + pub content_hash_seed: u64, +} + +impl HostBridge { + pub(super) fn format_for_depth(&self, depth: BitDepth) -> wgpu::TextureFormat { + let eff = if self.hiq { depth } else { BitDepth::Int8 }; + match eff { + BitDepth::Int8 => wgpu::TextureFormat::Rgba8Unorm, + BitDepth::Int16 | BitDepth::Float16 => wgpu::TextureFormat::Rgba16Float, + BitDepth::Float32 => { + if self.supports_f32_filter { + wgpu::TextureFormat::Rgba32Float + } else { + wgpu::TextureFormat::Rgba16Float + } + } + } + } + + pub(super) fn alloc_gpu_tex(&self, size: [u32; 2], depth: BitDepth, hash: u64) -> CachedTexture { + let eff = if self.hiq { depth } else { BitDepth::Int8 }; + let fmt = self.format_for_depth(eff); + create_texture_dod_fmt(&self.device, size, [0, 0], size, eff, fmt, hash) + } + + /// Flushes any pending GPU commands so subsequent CPU readbacks observe upstream writes. + fn flush_encoder(&mut self) { + if let Some(enc) = self.encoder.take() { + let sub = self.queue.submit(Some(enc.finish())); + let _ = self.device.poll(wgpu::PollType::Wait { + submission_index: Some(sub), + timeout: Some(std::time::Duration::from_secs(10)), + }); + self.encoder = Some(self.device.create_command_encoder( + &wgpu::CommandEncoderDescriptor { + label: Some("fuse-runtime-post-flush"), + }, + )); + } + } + + /// Reads back a `CachedTexture` (Fission Y-down) into Fusion Y-up linear `Vec<[f32; 4]>`. + pub(super) fn readback_gpu_to_fusion_y_up(&mut self, tex: &CachedTexture) -> Result, String> { + self.flush_encoder(); + let [w, h] = tex.size; + let bpp: u32 = match tex.format { + wgpu::TextureFormat::Rgba32Float => 16, + wgpu::TextureFormat::Rgba16Float => 8, + wgpu::TextureFormat::Rgba8Unorm => 4, + other => return Err(format!("unsupported format for Fuse CPU readback: {other:?}")), + }; + let unpadded_bpr = w * bpp; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let buf_size = u64::from(padded_bpr) * u64::from(h); + let staging = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("fuse-cpu-readback"), + size: buf_size.max(4), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("fuse-readback-copy"), + }); + enc.copy_texture_to_buffer( + tex.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &staging, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h), + }, + }, + wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + ); + let sub = self.queue.submit(Some(enc.finish())); + let slice = staging.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + let _ = self.device.poll(wgpu::PollType::Wait { + submission_index: Some(sub), + timeout: Some(std::time::Duration::from_secs(10)), + }); + rx.recv() + .map_err(|e| e.to_string())? + .map_err(|e| format!("{e:?}"))?; + + let mapped = slice.get_mapped_range().map_err(|e| format!("{e:?}"))?; + let mut pixels = vec![[0.0f32; 4]; (w as usize) * (h as usize)]; + for ty in 0..h as usize { + let fy = (h as usize) - 1 - ty; // flip Y-down -> Fusion Y-up + let row = &mapped[ty * padded_bpr as usize..ty * padded_bpr as usize + unpadded_bpr as usize]; + let dst_row = &mut pixels[fy * w as usize..(fy + 1) * w as usize]; + match tex.format { + wgpu::TextureFormat::Rgba8Unorm => { + for (x, c) in row.chunks_exact(4).enumerate() { + dst_row[x] = [ + f32::from(c[0]) / 255.0, + f32::from(c[1]) / 255.0, + f32::from(c[2]) / 255.0, + f32::from(c[3]) / 255.0, + ]; + } + } + wgpu::TextureFormat::Rgba16Float => { + for (x, c) in row.chunks_exact(8).enumerate() { + dst_row[x] = [ + ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[0], c[1]])).to_f32(), + ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[2], c[3]])).to_f32(), + ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[4], c[5]])).to_f32(), + ::exr::prelude::f16::from_bits(u16::from_le_bytes([c[6], c[7]])).to_f32(), + ]; + } + } + wgpu::TextureFormat::Rgba32Float => { + for (x, c) in row.chunks_exact(16).enumerate() { + dst_row[x] = [ + f32::from_le_bytes([c[0], c[1], c[2], c[3]]), + f32::from_le_bytes([c[4], c[5], c[6], c[7]]), + f32::from_le_bytes([c[8], c[9], c[10], c[11]]), + f32::from_le_bytes([c[12], c[13], c[14], c[15]]), + ]; + } + } + _ => {} + } + } + drop(mapped); + staging.unmap(); + Ok(pixels) + } + + /// Uploads a Fusion Y-up `Vec<[f32; 4]>` buffer into a Fission Y-down GPU `CachedTexture`. + pub(super) fn upload_fusion_y_up_to_gpu( + &self, + width: u32, + height: u32, + depth: BitDepth, + pixels: &[[f32; 4]], + hash: u64, + ) -> CachedTexture { + let tex = self.alloc_gpu_tex([width, height], depth, hash); + let w = width as usize; + let h = height as usize; + match tex.format { + wgpu::TextureFormat::Rgba8Unorm => { + let mut raw = vec![0u8; w * h * 4]; + for ty in 0..h { + let fy = h - 1 - ty; + for x in 0..w { + let p = pixels[fy * w + x]; + let o = (ty * w + x) * 4; + raw[o] = (p[0].clamp(0.0, 1.0) * 255.0).round() as u8; + raw[o + 1] = (p[1].clamp(0.0, 1.0) * 255.0).round() as u8; + raw[o + 2] = (p[2].clamp(0.0, 1.0) * 255.0).round() as u8; + raw[o + 3] = (p[3].clamp(0.0, 1.0) * 255.0).round() as u8; + } + } + self.queue.write_texture( + tex.texture.as_image_copy(), + &raw, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(width * 4), + rows_per_image: Some(height), + }, + wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + ); + } + wgpu::TextureFormat::Rgba16Float => { + let mut raw = vec![0u8; w * h * 8]; + for ty in 0..h { + let fy = h - 1 - ty; + for x in 0..w { + let p = pixels[fy * w + x]; + let o = (ty * w + x) * 8; + for (c, &val) in p.iter().enumerate() { + let bits = ::exr::prelude::f16::from_f32(val).to_bits().to_le_bytes(); + raw[o + c * 2] = bits[0]; + raw[o + c * 2 + 1] = bits[1]; + } + } + } + self.queue.write_texture( + tex.texture.as_image_copy(), + &raw, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(width * 8), + rows_per_image: Some(height), + }, + wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + ); + } + wgpu::TextureFormat::Rgba32Float => { + let mut raw = vec![0u8; w * h * 16]; + for ty in 0..h { + let fy = h - 1 - ty; + for x in 0..w { + let p = pixels[fy * w + x]; + let o = (ty * w + x) * 16; + for (c, &val) in p.iter().enumerate() { + raw[o + c * 4..o + c * 4 + 4].copy_from_slice(&val.to_le_bytes()); + } + } + } + self.queue.write_texture( + tex.texture.as_image_copy(), + &raw, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(width * 16), + rows_per_image: Some(height), + }, + wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + ); + } + _ => {} + } + tex + } +} + + diff --git a/crates/engine/src/fuse_runtime/lua_dvip.rs b/crates/engine/src/fuse_runtime/lua_dvip.rs new file mode 100644 index 0000000000000000000000000000000000000000..b58f42391f8e21112bd920e40cdd6ba043913720 --- /dev/null +++ b/crates/engine/src/fuse_runtime/lua_dvip.rs @@ -0,0 +1,459 @@ +//! Fusion `DVIPComputeNode` and `ParamBlock` GPU DCTL compilation and dispatch. + +use std::cell::RefCell; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::rc::Rc; +use std::sync::Arc; + +use mlua::{MetaMethod, Result as LuaResult, UserData, UserDataMethods, Value}; + +use crate::cache::CachedTexture; + +use super::CompiledDctlPipeline; +use super::dctl::{ParamLayout, parse_param_block, transpile_dctl_to_wgsl}; +use super::lua_host::{HostBridge, val_to_f64}; +use super::lua_types::{ImageBacking, ImageInner, LuaImage}; + +// --------------------------------------------------------------------------- +// DVIPComputeNode + ParamBlock (GPU DCTL execution) +// --------------------------------------------------------------------------- + +struct ParamBlockInner { + layout: ParamLayout, + bytes: Vec, +} + +#[derive(Clone)] +struct LuaParamBlock(Rc>); + +#[derive(Clone)] +struct LuaParamArrayView { + inner: Rc>, + field_name: String, +} + +impl UserData for LuaParamArrayView { + fn add_methods>(methods: &mut M) { + methods.add_meta_method(MetaMethod::Index, |_, this, key: Value| { + let idx = key_to_elem_index(&key)?; + let inner = this.inner.borrow(); + Ok(inner.layout.read_scalar(&inner.bytes, &this.field_name, Some(idx)).unwrap_or(0.0)) + }); + methods.add_meta_method(MetaMethod::NewIndex, |_, this, (key, val): (Value, Value)| { + let idx = key_to_elem_index(&key)?; + let num = val_to_f64(&val); + let mut inner = this.inner.borrow_mut(); + let layout = inner.layout.clone(); + layout.write_scalar(&mut inner.bytes, &this.field_name, Some(idx), num); + Ok(()) + }); + } +} + +impl UserData for LuaParamBlock { + fn add_methods>(methods: &mut M) { + methods.add_meta_method(MetaMethod::Index, |lua, this, key: String| { + let inner = this.0.borrow(); + if let Some(f) = inner.layout.field(&key) { + if f.array_len.is_some() || f.ty.components() > 1 { + let view = LuaParamArrayView { + inner: this.0.clone(), + field_name: key, + }; + return Ok(Value::UserData(lua.create_userdata(view)?)); + } + let v = inner.layout.read_scalar(&inner.bytes, &key, None).unwrap_or(0.0); + return Ok(Value::Number(v)); + } + Ok(Value::Nil) + }); + methods.add_meta_method(MetaMethod::NewIndex, |_, this, (key, val): (String, Value)| { + let mut inner = this.0.borrow_mut(); + let layout = inner.layout.clone(); + if let Some(f) = layout.field(&key) { + match val { + Value::Table(tbl) => { + let count = f.array_len.unwrap_or_else(|| f.ty.components()); + let zero_based = tbl.get::(0).ok().is_some_and(|v| !matches!(v, Value::Nil)); + for i in 0..count { + let k = if zero_based { i as i64 } else { (i + 1) as i64 }; + if let Ok(v) = tbl.get::(k) { + layout.write_scalar(&mut inner.bytes, &key, Some(i), v); + } + } + } + other => { + layout.write_scalar(&mut inner.bytes, &key, None, val_to_f64(&other)); + } + } + } + Ok(()) + }); + } +} + +fn key_to_elem_index(key: &Value) -> LuaResult { + match key { + Value::Integer(i) if *i >= 0 => Ok(*i as usize), + Value::Number(n) if *n >= 0.0 => Ok(*n as usize), + Value::String(s) => match s.to_str()?.as_ref() { + "x" | "X" | "r" | "R" => Ok(0), + "y" | "Y" | "g" | "G" => Ok(1), + "z" | "Z" | "b" | "B" => Ok(2), + "w" | "W" | "a" | "A" => Ok(3), + other => Err(mlua::Error::RuntimeError(format!("unknown vector component `{other}`"))), + }, + _ => Err(mlua::Error::RuntimeError("invalid param array index".into())), + } +} + +pub(super) struct DvipNodeInner { + pub(super) kernel_name: String, + pub(super) source: String, + pub(super) params_name: String, + pub(super) params_def: String, + pub(super) param_bytes: Vec, + pub(super) inputs: Vec<(String, Rc>)>, + pub(super) outputs: Vec<(String, Rc>)>, + pub(super) normalized_coords: bool, + pub(super) linear_filter: bool, + pub(super) address_mode: u32, + pub(super) error_log: String, +} + +#[derive(Clone)] +pub(super) struct LuaDvipNode(pub(super) Rc>); + +impl UserData for LuaDvipNode { + fn add_methods>(methods: &mut M) { + methods.add_method("GetParamBlock", |_, this, def_override: Option| { + let def = def_override.unwrap_or_else(|| this.0.borrow().params_def.clone()); + let layout = parse_param_block(&def).map_err(mlua::Error::RuntimeError)?; + let bytes = vec![0u8; layout.buffer_size()]; + Ok(LuaParamBlock(Rc::new(RefCell::new(ParamBlockInner { layout, bytes })))) + }); + methods.add_method("SetParamBlock", |_, this, params: mlua::UserDataRef| { + let bytes = params.0.borrow().bytes.clone(); + this.0.borrow_mut().param_bytes = bytes; + Ok(()) + }); + methods.add_method( + "AddSampler", + |_, this, (_name, filter, addr, norm): (String, Option, Option, Option)| { + let mut n = this.0.borrow_mut(); + if let Some(f) = filter { + n.linear_filter = f != 0; + } + if let Some(a) = addr { + n.address_mode = a.max(0) as u32; + } + if let Some(nc) = norm { + n.normalized_coords = nc != 0; + } + Ok(()) + }, + ); + methods.add_method("AddInput", |_, this, (name, img): (String, mlua::UserDataRef)| { + let mut n = this.0.borrow_mut(); + if let Some(slot) = n.inputs.iter_mut().find(|(k, _)| k == &name) { + slot.1 = img.0.clone(); + } else { + n.inputs.push((name, img.0.clone())); + } + Ok(()) + }); + methods.add_method("AddOutput", |_, this, (name, img): (String, mlua::UserDataRef)| { + let mut n = this.0.borrow_mut(); + if let Some(slot) = n.outputs.iter_mut().find(|(k, _)| k == &name) { + slot.1 = img.0.clone(); + } else { + n.outputs.push((name, img.0.clone())); + } + Ok(()) + }); + methods.add_method("GetErrorLog", |_, this, ()| Ok(this.0.borrow().error_log.clone())); + methods.add_method("RunSession", |lua, this, _req: Value| { + let mut bridge = lua + .app_data_mut::() + .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; + let res = run_dvip_session(&mut this.0.borrow_mut(), &mut bridge); + match res { + Ok(()) => Ok(true), + Err(msg) => { + this.0.borrow_mut().error_log = msg; + Ok(false) + } + } + }); + } +} + +fn run_dvip_session(node: &mut DvipNodeInner, bridge: &mut HostBridge) -> Result<(), String> { + if node.outputs.is_empty() { + return Err("DVIPComputeNode has no registered outputs".to_owned()); + } + let (dst_size, dst_depth) = { + let out0 = node.outputs[0].1.borrow(); + ([out0.width.max(1), out0.height.max(1)], out0.depth) + }; + let dst_format = bridge.format_for_depth(dst_depth); + + // 1. Lookup or compile cached WGSL compute pipeline + let mut hasher = DefaultHasher::new(); + node.source.hash(&mut hasher); + node.kernel_name.hash(&mut hasher); + node.params_name.hash(&mut hasher); + node.params_def.hash(&mut hasher); + let cache_key = (hasher.finish(), dst_format); + + let compiled: Arc = { + let mut cache = bridge + .pipeline_cache + .lock() + .map_err(|_| "DCTL pipeline cache poisoned".to_owned())?; + if let Some(hit) = cache.get(&cache_key) { + hit + } else { + let transpiled = transpile_dctl_to_wgsl( + &node.source, + &node.kernel_name, + Some(&node.params_name), + Some(&node.params_def), + dst_format, + )?; + let compiled = compile_dctl_pipeline(&bridge.device, &transpiled, dst_format)?; + let arc = Arc::new(compiled); + cache.insert(cache_key, arc.clone()); + arc + } + }; + + // 2. Ensure GPU textures for all kernel inputs (zero CPU roundtrip!) + let mut input_texs: Vec = Vec::with_capacity(compiled.input_textures.len()); + for (idx, tex_name) in compiled.input_textures.iter().enumerate() { + let found = node + .inputs + .iter() + .find(|(k, _)| k == tex_name) + .or_else(|| node.inputs.get(idx)); + if let Some((_, img_rc)) = found { + let tex = img_rc.borrow_mut().ensure_gpu(bridge, bridge.content_hash_seed ^ (idx as u64 + 1)); + input_texs.push(tex); + } else { + input_texs.push(bridge.dummy_tex.clone()); + } + } + + // 3. Allocate GPU output textures and attach them back onto the Lua output Image handles + let mut output_texs: Vec = Vec::with_capacity(compiled.output_textures.len()); + for (idx, dst_name) in compiled.output_textures.iter().enumerate() { + let found = node + .outputs + .iter() + .find(|(k, _)| k == dst_name) + .or_else(|| node.outputs.get(idx)); + let out_tex = if let Some((_, img_rc)) = found { + let mut inner = img_rc.borrow_mut(); + let sz = [inner.width.max(1), inner.height.max(1)]; + let tex = bridge.alloc_gpu_tex(sz, inner.depth, bridge.content_hash_seed ^ (0xF000 + idx as u64)); + inner.backing = ImageBacking::Gpu(tex.clone()); + tex + } else { + bridge.alloc_gpu_tex(dst_size, dst_depth, bridge.content_hash_seed ^ (0xF000 + idx as u64)) + }; + output_texs.push(out_tex); + } + + // 4. Upload params storage buffer & meta uniform buffer + let required_param_bytes = compiled.param_layout.buffer_size(); + let mut param_data = node.param_bytes.clone(); + param_data.resize(required_param_bytes, 0); + let param_buf = bridge.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("dctl-params-buf"), + size: required_param_bytes as u64, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + bridge.queue.write_buffer(¶m_buf, 0, ¶m_data); + + let meta: [u32; 4] = [ + dst_size[0], + dst_size[1], + u32::from(node.normalized_coords), + u32::from(node.linear_filter), + ]; + let meta_buf = bridge.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("dctl-meta-buf"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + bridge.queue.write_buffer(&meta_buf, 0, bytemuck::cast_slice(&meta)); + + let addr_mode = match node.address_mode { + 2 => wgpu::AddressMode::Repeat, + 3 => wgpu::AddressMode::MirrorRepeat, + _ => wgpu::AddressMode::ClampToEdge, + }; + let filter = if node.linear_filter { + wgpu::FilterMode::Linear + } else { + wgpu::FilterMode::Nearest + }; + let sampler = bridge.device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("dctl-sampler"), + address_mode_u: addr_mode, + address_mode_v: addr_mode, + mag_filter: filter, + min_filter: filter, + ..Default::default() + }); + + // 5. Build bind group & dispatch compute pass onto the shared CommandEncoder! + let mut entries: Vec> = Vec::with_capacity(3 + input_texs.len() + output_texs.len()); + entries.push(wgpu::BindGroupEntry { + binding: 0, + resource: param_buf.as_entire_binding(), + }); + entries.push(wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&sampler), + }); + entries.push(wgpu::BindGroupEntry { + binding: 2, + resource: meta_buf.as_entire_binding(), + }); + let mut binding = 3u32; + for t in &input_texs { + entries.push(wgpu::BindGroupEntry { + binding, + resource: wgpu::BindingResource::TextureView(&t.view), + }); + binding += 1; + } + for t in &output_texs { + entries.push(wgpu::BindGroupEntry { + binding, + resource: wgpu::BindingResource::TextureView(&t.view), + }); + binding += 1; + } + let bg = bridge.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("dctl-bg"), + layout: &compiled.bgl, + entries: &entries, + }); + + let enc = bridge + .encoder + .as_mut() + .ok_or_else(|| "missing active CommandEncoder".to_owned())?; + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("dctl-compute-pass"), + timestamp_writes: None, + }); + pass.set_pipeline(&compiled.pipeline); + pass.set_bind_group(0, &bg, &[]); + pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1); + Ok(()) +} + +/// Compiles a transpiled DCTL WGSL shader into a validated `wgpu::ComputePipeline` inside +/// `push_error_scope` so malformed Fuses never panic. +pub fn compile_dctl_pipeline( + device: &wgpu::Device, + transpiled: &super::dctl::TranspiledKernel, + dst_format: wgpu::TextureFormat, +) -> Result { + let mut layout_entries = vec![ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ]; + let mut binding = 3u32; + for _ in &transpiled.input_textures { + layout_entries.push(wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }); + binding += 1; + } + for _ in &transpiled.output_textures { + layout_entries.push(wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: dst_format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }); + binding += 1; + } + + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("dctl-bgl"), + entries: &layout_entries, + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("dctl-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("dctl-shader"), + source: wgpu::ShaderSource::Wgsl(transpiled.wgsl.as_str().into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("dctl-compute-pipeline"), + layout: Some(&pl), + module: &module, + entry_point: Some(&transpiled.entry_point), + compilation_options: Default::default(), + cache: None, + }); + if let Some(err) = pollster::block_on(scope.pop()) { + return Err(format!("WGSL validation failed: {err}")); + } + + Ok(CompiledDctlPipeline { + pipeline, + bgl, + param_layout: transpiled.param_layout.clone(), + input_textures: transpiled.input_textures.clone(), + output_textures: transpiled.output_textures.clone(), + }) +} + diff --git a/crates/engine/src/fuse_runtime/lua_host.rs b/crates/engine/src/fuse_runtime/lua_host.rs new file mode 100644 index 0000000000000000000000000000000000000000..5b43a3d5e29790668a66b5a5a8c164ddaa91846c --- /dev/null +++ b/crates/engine/src/fuse_runtime/lua_host.rs @@ -0,0 +1,669 @@ +//! Sandboxed `mlua` Lua 5.4 host implementing Fusion's Fuse API and GPU-accelerated +//! `DVIPComputeNode` execution. + +use std::cell::RefCell; +use std::rc::Rc; + +use mlua::{ + Function, HookTriggers, Lua, LuaOptions, MultiValue, Result as LuaResult, StdLib, Table, + UserData, UserDataFields, UserDataMethods, Value, +}; +use model::Gradient; + +use crate::cache::CachedTexture; + +use super::dctl::parse_param_block; +pub use super::lua_bridge::{EvalParam, HostBridge}; +pub use super::lua_dvip::compile_dctl_pipeline; +use super::lua_dvip::{DvipNodeInner, LuaDvipNode}; +use super::lua_types::{ + ImageBacking, ImageInner, LuaGradient, LuaImage, LuaImgRectI, LuaMatrix4, LuaPixel, LuaPoint, + LuaVector4, fusion_imdp_to_depth, +}; + +const MAX_LUA_HOOK_STEPS: usize = 25_000; // 25_000 * 10_000 = 250M instructions + +// --------------------------------------------------------------------------- +// Input / Output / Request / Tool handles +// --------------------------------------------------------------------------- + +#[derive(Clone)] +struct LuaInput { + id: String, + data_type: String, + default_num: f64, + default_pt: [f64; 2], + default_str: String, + link_main: Option, +} + +impl LuaInput { + fn eval_value(&self, lua: &Lua) -> LuaResult { + let bridge = lua + .app_data_ref::() + .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; + match self.data_type.as_str() { + "Image" => { + let tex_opt = bridge + .upstream_images + .get(&self.id) + .cloned() + .or_else(|| { + if self.link_main == Some(1) { + bridge.main_input.clone() + } else { + None + } + }); + match tex_opt { + Some(tex) => { + let img = LuaImage(Rc::new(RefCell::new(ImageInner { + width: tex.size[0], + height: tex.size[1], + depth: tex.depth, + x_scale: 1.0, + y_scale: 1.0, + is_mask: false, + backing: ImageBacking::Gpu(tex), + }))); + Ok(Value::UserData(lua.create_userdata(img)?)) + } + None => Ok(Value::Nil), + } + } + "Point" => { + let pt = match bridge.params.get(&self.id) { + Some(EvalParam::Point(p)) => *p, + _ => self.default_pt, + }; + Ok(Value::UserData(lua.create_userdata(LuaPoint { x: pt[0], y: pt[1] })?)) + } + "Text" | "FuID" => { + let s = match bridge.params.get(&self.id) { + Some(EvalParam::Text(s)) => s.clone(), + _ => self.default_str.clone(), + }; + let tbl = lua.create_table()?; + tbl.set("Value", s)?; + Ok(Value::Table(tbl)) + } + "Gradient" => { + let g = match bridge.params.get(&self.id) { + Some(EvalParam::Gradient(g)) => g.clone(), + _ => Gradient::default(), + }; + Ok(Value::UserData(lua.create_userdata(LuaGradient(g))?)) + } + _ => { + let num = match bridge.params.get(&self.id) { + Some(EvalParam::Number(n)) => *n, + _ => self.default_num, + }; + let tbl = lua.create_table()?; + tbl.set("Value", num)?; + Ok(Value::Table(tbl)) + } + } + } +} + +impl UserData for LuaInput { + fn add_methods>(methods: &mut M) { + methods.add_method("GetValue", |lua, this, _req: Value| this.eval_value(lua)); + methods.add_method("GetSource", |lua, this, (_t, _flags): (Option, Option)| { + this.eval_value(lua) + }); + methods.add_method("SetAttrs", |_, _, _attrs: Value| Ok(())); + } +} + +#[derive(Clone)] +struct LuaOutput; + +impl UserData for LuaOutput { + fn add_methods>(methods: &mut M) { + methods.add_method("Set", |lua, _, (_req, val): (Value, Value)| { + if let Value::UserData(ud) = val + && let Ok(img) = ud.borrow::() + { + if let Some(mut bridge) = lua.app_data_mut::() { + bridge.output_image = Some(img.0.clone()); + } + } + Ok(()) + }); + } +} + +#[derive(Clone, Copy)] +struct LuaRequest { + time: f64, + precalc: bool, + width: i32, + height: i32, +} + +impl UserData for LuaRequest { + fn add_fields>(fields: &mut F) { + fields.add_field_method_get("Time", |_, this| Ok(this.time)); + } + + fn add_methods>(methods: &mut M) { + methods.add_method("IsPreCalc", |_, this, ()| Ok(this.precalc)); + methods.add_method("IsQuick", |_, _, ()| Ok(false)); + methods.add_method("IsNoMotionBlur", |_, _, ()| Ok(false)); + methods.add_method("IsStampOnly", |_, _, ()| Ok(false)); + methods.add_method("IsFailed", |_, _, ()| Ok(false)); + methods.add_method("GetPri", |_, _, ()| Ok(0i32)); + methods.add_method("GetRoI", |_, _, ()| Ok(Value::Nil)); + methods.add_method("GetDoD", |_, this, ()| { + Ok(LuaImgRectI { left: 0, bottom: 0, right: this.width, top: this.height }) + }); + methods.add_method("GetInputDoD", |_, this, _inp: Value| { + Ok(LuaImgRectI { left: 0, bottom: 0, right: this.width, top: this.height }) + }); + methods.add_method("SetInputRoI", |_, _, (_inp, _rect): (Value, Value)| Ok(())); + } +} + +struct LuaToolSelf; + +impl UserData for LuaToolSelf { + fn add_fields>(fields: &mut F) { + fields.add_field_method_get("Status", |_, _| Ok("OK".to_owned())); + fields.add_field_method_get("Comp", |lua, _| { + let bridge = lua + .app_data_ref::() + .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; + let comp_tbl = lua.create_table()?; + comp_tbl.set("CurrentTime", bridge.time)?; + comp_tbl.set("GlobalStart", bridge.global_range[0])?; + comp_tbl.set("GlobalEnd", bridge.global_range[1])?; + comp_tbl.set("RenderStart", bridge.render_range[0])?; + comp_tbl.set("RenderEnd", bridge.render_range[1])?; + let dims = bridge.comp_dims; + comp_tbl.set( + "GetPrefs", + lua.create_function(move |lua, (_self, key): (Value, Option)| { + if let Some(k) = key + && k.contains("Width") + { + return Ok(Value::Integer(i64::from(dims[0]))); + } + let t = lua.create_table()?; + Ok(Value::Table(t)) + })?, + )?; + Ok(comp_tbl) + }); + } + + fn add_methods>(methods: &mut M) { + methods.add_method("AddInput", |_, _, (_label, id, attrs): (String, String, Option)| { + let mut data_type = "Number".to_owned(); + let mut default_num = 0.0f64; + let mut default_pt = [0.5f64, 0.5f64]; + let mut default_str = String::new(); + let mut link_main = None; + if let Some(t) = attrs { + if let Ok(dt) = t.get::("LINKID_DataType") { + data_type = dt; + } + if let Ok(v) = t.get::("INP_Default") { + default_num = v; + } + if let Ok(v) = t.get::("INP_DefaultX") { + default_pt[0] = v; + } + if let Ok(v) = t.get::("INP_DefaultY") { + default_pt[1] = v; + } + if let Ok(s) = t.get::("INPID_DefaultID") { + default_str = s; + } else if let Ok(s) = t.get::("INPS_DefaultText") { + default_str = s; + } + if let Ok(lm) = t.get::("LINK_Main") { + link_main = Some(lm); + } + } + Ok(LuaInput { id, data_type, default_num, default_pt, default_str, link_main }) + }); + methods.add_method("AddOutput", |_, _, (_label, _id, _attrs): (String, String, Option
)| { + Ok(LuaOutput) + }); + methods.add_method("BeginControlNest", |_, _, _: MultiValue| Ok(())); + methods.add_method("EndControlNest", |_, _, _: MultiValue| Ok(())); + methods.add_method("AddControlPage", |_, _, _: MultiValue| Ok(())); + methods.add_method("SetProgress", |_, _, _p: Option| Ok(())); + methods.add_method("SetData", |lua, _, (k, v): (String, Value)| { + if let Some(mut b) = lua.app_data_mut::() { + b.tool_data.insert(k, format!("{v:?}")); + } + Ok(()) + }); + methods.add_method("GetData", |lua, _, k: String| { + if let Some(b) = lua.app_data_ref::() { + if let Some(v) = b.tool_data.get(&k) { + return Ok(Value::String(lua.create_string(v)?)); + } + } + Ok(Value::Nil) + }); + methods.add_method( + "DoMultiProcess", + |lua, _, (init_fn, args_tbl, count, func): (Option, Option
, i32, Function)| { + let saved = apply_temp_globals(lua, args_tbl.as_ref())?; + if let Some(init) = init_fn { + init.call::<()>(())?; + } + for y in 0..count.max(0) { + func.call::<()>(y)?; + } + restore_temp_globals(lua, saved)?; + Ok(()) + }, + ); + } +} + + +// --------------------------------------------------------------------------- +// Helpers & Entry Point +// --------------------------------------------------------------------------- + +pub(super) fn val_to_f64(v: &Value) -> f64 { + match v { + Value::Number(n) => *n, + Value::Integer(i) => *i as f64, + Value::Boolean(b) => if *b { 1.0 } else { 0.0 }, + _ => 0.0, + } +} + +pub(super) fn val_to_i32(v: &Value) -> i32 { + val_to_f64(v).round() as i32 +} + +pub(super) fn apply_temp_globals(lua: &Lua, tbl: Option<&Table>) -> LuaResult> { + let mut saved = Vec::new(); + let Some(t) = tbl else { + return Ok(saved); + }; + let globals = lua.globals(); + for pair in t.pairs::() { + let (k, v) = pair?; + let prev = globals.get::(k.as_str())?; + saved.push((k.clone(), prev)); + globals.set(k, v)?; + } + Ok(saved) +} + +pub(super) fn restore_temp_globals(lua: &Lua, saved: Vec<(String, Value)>) -> LuaResult<()> { + let globals = lua.globals(); + for (k, v) in saved { + globals.set(k, v)?; + } + Ok(()) +} + +/// Executes a `.fuse` script inside a sandboxed Lua 5.4 environment, running +/// `FuRegisterClass`, `Create()`, and `Process(req)`. +/// +/// Always returns the (possibly refreshed) `CommandEncoder` alongside the execution result. +pub fn execute_fuse( + source: &str, + bridge: HostBridge, +) -> (Result, String>, wgpu::CommandEncoder) { + let result = execute_fuse_inner(source, bridge); + match result { + Ok((tex, enc)) => (Ok(tex), enc), + Err((msg, enc)) => (Err(msg), enc), + } +} + +fn execute_fuse_inner( + source: &str, + bridge: HostBridge, +) -> Result<(Option, wgpu::CommandEncoder), (String, wgpu::CommandEncoder)> { + let device_fallback = bridge.device.clone(); + let stdlib = StdLib::TABLE | StdLib::STRING | StdLib::MATH | StdLib::UTF8 | StdLib::COROUTINE; + let lua = match Lua::new_with(stdlib, LuaOptions::default()) { + Ok(l) => l, + Err(e) => { + let enc = bridge.encoder.unwrap_or_else(|| { + device_fallback.create_command_encoder(&Default::default()) + }); + return Err((format!("failed to create Lua VM: {e}"), enc)); + } + }; + + // Instruction budget guard against infinite loops in untrusted Fuses + let steps = Rc::new(RefCell::new(0usize)); + let steps_hook = steps.clone(); + lua.set_hook(HookTriggers::new().every_nth_instruction(10_000), move |_, _| { + let mut c = steps_hook.borrow_mut(); + *c += 1; + if *c > MAX_LUA_HOOK_STEPS { + return Err(mlua::Error::RuntimeError("Fuse exceeded Lua instruction budget".into())); + } + Ok(mlua::VmState::Continue) + }); + + let time = bridge.time; + let comp_dims = bridge.comp_dims; + let main_dims = bridge.main_input.as_ref().map_or(comp_dims, |t| t.size); + lua.set_app_data(bridge); + + let run_res: LuaResult> = (|| { + register_fusion_globals(&lua)?; + // Execute top-level Fuse script (runs FuRegisterClass and defines Create / Process) + lua.load(source).exec()?; + + let globals = lua.globals(); + globals.set("self", LuaToolSelf)?; + + // For CT_SourceTool fuses (like HexagonTiles.fuse), Fusion pre-creates OutImage & Width/Height globals. + let (src_w, src_h, is_source) = { + let b = lua.app_data_ref::().unwrap(); + let w = match b.params.get("Width") { + Some(EvalParam::Number(n)) if *n >= 1.0 => *n as u32, + _ => b.comp_dims[0], + }; + let h = match b.params.get("Height") { + Some(EvalParam::Number(n)) if *n >= 1.0 => *n as u32, + _ => b.comp_dims[1], + }; + (w, h, b.fuse_meta.class_type == "SourceTool") + }; + if is_source { + globals.set("OutImage", LuaOutput)?; + } + globals.set("Width", src_w as f64)?; + globals.set("Height", src_h as f64)?; + globals.set("Scale", 1.0f64)?; + globals.set("XAspect", 1.0f64)?; + globals.set("YAspect", 1.0f64)?; + globals.set("SourceDepth", 0i32)?; + + if let Ok(create_fn) = globals.get::("Create") { + create_fn.call::<()>(())?; + } + + let req = LuaRequest { + time, + precalc: false, + width: main_dims[0] as i32, + height: main_dims[1] as i32, + }; + if let Ok(process_fn) = globals.get::("Process") { + process_fn.call::<()>(req)?; + } else { + return Err(mlua::Error::RuntimeError("Fuse defines no Process(req) function".into())); + } + + let out_rc = lua + .app_data_ref::() + .and_then(|b| b.output_image.clone()); + if let Some(img_rc) = out_rc { + let bridge = lua.app_data_ref::().unwrap(); + let hash = bridge.content_hash_seed; + let tex = img_rc.borrow_mut().ensure_gpu(&bridge, hash); + Ok(Some(tex)) + } else { + Ok(None) + } + })(); + + let enc = lua + .remove_app_data::() + .and_then(|b| b.encoder) + .unwrap_or_else(|| device_fallback.create_command_encoder(&Default::default())); + + match run_res { + Ok(tex) => Ok((tex, enc)), + Err(e) => Err((e.to_string(), enc)), + } +} + +fn register_fusion_globals(lua: &Lua) -> LuaResult<()> { + let g = lua.globals(); + + // Constants + g.set("CT_Tool", "Tool")?; + g.set("CT_SourceTool", "SourceTool")?; + g.set("CT_ParticleTool", "ParticleTool")?; + g.set("CT_Modifier", "Modifier")?; + g.set("IMDP_8bitInt", 5i32)?; + g.set("IMDP_16bitInt", 6i32)?; + g.set("IMDP_16bitFloat", 7i32)?; + g.set("IMDP_32bitFloat", 8i32)?; + g.set("IMDP_32bitInt", 5i32)?; + g.set("IMDP_64bitInt", 6i32)?; + g.set("IMDP_64bitFloat", 7i32)?; + g.set("IMDP_128bitFloat", 8i32)?; + + g.set("TEX_FILTER_MODE_POINT", 0i32)?; + g.set("TEX_FILTER_MODE_LINEAR", 1i32)?; + g.set("TEX_ADDRESS_MODE_CLAMP", 0i32)?; + g.set("TEX_ADDRESS_MODE_BORDER", 1i32)?; + g.set("TEX_ADDRESS_MODE_WRAP", 2i32)?; + g.set("TEX_ADDRESS_MODE_MIRROR", 3i32)?; + g.set("TEX_ADDRESS_MODE_DUPLICATE", 0i32)?; + g.set("TEX_NORMALIZED_COORDS_FALSE", 0i32)?; + g.set("TEX_NORMALIZED_COORDS_TRUE", 1i32)?; + + g.set("FuPLATFORM_MAC", cfg!(target_os = "macos"))?; + g.set("FuPLATFORM_WINDOWS", cfg!(target_os = "windows"))?; + g.set("FuPLATFORM_LINUX", cfg!(target_os = "linux"))?; + + // Compatibility helpers (no-op dump/print/collectgarbage, unpack alias) + g.set("print", lua.create_function(|_, _: MultiValue| Ok(()))?)?; + g.set("dump", lua.create_function(|_, _: MultiValue| Ok(()))?)?; + g.set("collectgarbage", lua.create_function(|_, _: MultiValue| Ok(0))?)?; + if let Ok(tbl_mod) = g.get::
("table") + && let Ok(unpack_fn) = tbl_mod.get::("unpack") + { + g.set("unpack", unpack_fn)?; + } + + // FuRegisterClass(id, class_type, attrs) + g.set( + "FuRegisterClass", + lua.create_function(|lua, (id, class_type, attrs): (String, String, Option
)| { + if let Some(mut b) = lua.app_data_mut::() { + b.fuse_meta.id = id.clone(); + b.fuse_meta.class_type = class_type; + b.fuse_meta.name = id; + if let Some(t) = attrs { + if let Ok(n) = t.get::("REGS_Name") { + b.fuse_meta.name = n; + } else if let Ok(n) = t.get::("REG_Name") { + b.fuse_meta.name = n; + } + if let Ok(v) = t.get::("REG_OpNoMask") { + b.fuse_meta.op_no_mask = v; + } + if let Ok(v) = t.get::("REG_TimeVariant") { + b.fuse_meta.time_variant = v; + } + } + } + Ok(()) + })?, + )?; + + // Pixel({ R, G, B, A }) or Pixel(r, g, b, a) + g.set( + "Pixel", + lua.create_function(|_, args: MultiValue| { + let vals: Vec = args.into_iter().collect(); + let mut p = LuaPixel::default(); + if let Some(Value::Table(t)) = vals.first() { + if let Ok(v) = t.get::("R") { p.r = v as f32; } + if let Ok(v) = t.get::("G") { p.g = v as f32; } + if let Ok(v) = t.get::("B") { p.b = v as f32; } + if let Ok(v) = t.get::("A") { p.a = v as f32; } + } else if !vals.is_empty() { + p.r = val_to_f64(&vals[0]) as f32; + if vals.len() > 1 { p.g = val_to_f64(&vals[1]) as f32; } + if vals.len() > 2 { p.b = val_to_f64(&vals[2]) as f32; } + if vals.len() > 3 { p.a = val_to_f64(&vals[3]) as f32; } + } + Ok(p) + })?, + )?; + + // Point(x, y) + g.set( + "Point", + lua.create_function(|_, (x, y): (Option, Option)| { + Ok(LuaPoint { x: x.unwrap_or(0.0), y: y.unwrap_or(0.0) }) + })?, + )?; + + // Vector4(x, y, z, w) + g.set( + "Vector4", + lua.create_function(|_, (x, y, z, w): (Option, Option, Option, Option)| { + Ok(LuaVector4 { + x: x.unwrap_or(0.0), + y: y.unwrap_or(0.0), + z: z.unwrap_or(0.0), + w: w.unwrap_or(1.0), + }) + })?, + )?; + + // ImgRectI / FuRectInt + let make_rect = lua.create_function( + |_, (l, b, r, t): (Option, Option, Option, Option)| { + Ok(LuaImgRectI { + left: l.unwrap_or(0.0).round() as i32, + bottom: b.unwrap_or(0.0).round() as i32, + right: r.unwrap_or(0.0).round() as i32, + top: t.unwrap_or(0.0).round() as i32, + }) + }, + )?; + g.set("ImgRectI", make_rect.clone())?; + g.set("FuRectInt", make_rect)?; + + // Matrix4() + g.set("Matrix4", lua.create_function(|_, ()| Ok(LuaMatrix4::identity()))?)?; + + // Gradient("GP_SolidWhite" | "GP_SolidBlack") + g.set( + "Gradient", + lua.create_function(|_, preset: Option| { + let g = match preset.as_deref() { + Some("GP_SolidBlack") => Gradient { + stops: vec![model::GradientStop { pos: 0.0, rgba: [0.0, 0.0, 0.0, 1.0] }], + }, + _ => Gradient::default(), + }; + Ok(LuaGradient(g)) + })?, + )?; + + // Image(attrs) + g.set( + "Image", + lua.create_function(|lua, attrs: Option
| { + let (mut width, mut height, mut depth) = { + let b = lua.app_data_ref::().unwrap(); + (b.comp_dims[0], b.comp_dims[1], b.default_depth) + }; + let mut x_scale = 1.0; + let mut y_scale = 1.0; + let mut defer_alloc = false; + + if let Some(t) = attrs { + if let Ok(Value::UserData(like_ud)) = t.get::("IMG_Like") + && let Ok(like) = like_ud.borrow::() + { + let lb = like.0.borrow(); + width = lb.width; + height = lb.height; + depth = lb.depth; + x_scale = lb.x_scale; + y_scale = lb.y_scale; + } + if let Ok(w) = t.get::("IMG_Width") + && w >= 1.0 + { + width = w.round() as u32; + } + if let Ok(h) = t.get::("IMG_Height") + && h >= 1.0 + { + height = h.round() as u32; + } + if let Ok(d) = t.get::("IMG_Depth") + && let Some(bd) = fusion_imdp_to_depth(d) + { + depth = bd; + } + if let Ok(xs) = t.get::("IMG_XScale") { x_scale = xs; } + if let Ok(ys) = t.get::("IMG_YScale") { y_scale = ys; } + if let Ok(da) = t.get::("IMG_DeferAlloc") { defer_alloc = da; } + if let Ok(nd) = t.get::("IMG_NoData") + && nd + { + defer_alloc = true; + } + } + + let backing = if defer_alloc { + ImageBacking::Deferred + } else { + ImageBacking::Cpu(vec![[0.0; 4]; (width as usize) * (height as usize)]) + }; + Ok(LuaImage(Rc::new(RefCell::new(ImageInner { + width: width.max(1), + height: height.max(1), + depth, + x_scale, + y_scale, + is_mask: false, + backing, + })))) + })?, + )?; + + // DVIPComputeNode(req, kernel_name, source, params_name, params_def) + g.set( + "DVIPComputeNode", + lua.create_function( + |_, (_req, kernel_name, source, params_name, params_def): ( + Value, + String, + String, + Option, + Option, + )| { + let pdef = params_def.unwrap_or_default(); + let pname = params_name.unwrap_or_else(|| "DctlParams".to_owned()); + let init_bytes = parse_param_block(&pdef) + .map(|l| vec![0u8; l.buffer_size()]) + .unwrap_or_else(|_| vec![0u8; 16]); + Ok(LuaDvipNode(Rc::new(RefCell::new(DvipNodeInner { + kernel_name, + source, + params_name: pname, + params_def: pdef, + param_bytes: init_bytes, + inputs: Vec::new(), + outputs: Vec::new(), + normalized_coords: false, + linear_filter: false, + address_mode: 0, + error_log: String::new(), + })))) + }, + )?, + )?; + + Ok(()) +} diff --git a/crates/engine/src/fuse_runtime/lua_types.rs b/crates/engine/src/fuse_runtime/lua_types.rs new file mode 100644 index 0000000000000000000000000000000000000000..7d690838b394aeb9f1a1763879338285af2e06f2 --- /dev/null +++ b/crates/engine/src/fuse_runtime/lua_types.rs @@ -0,0 +1,636 @@ +//! Fusion Lua data types (`Pixel`, `Point`, `Vector4`, `ImgRectI`, `Matrix4`, `Gradient`, `Image`). + +use std::cell::RefCell; +use std::rc::Rc; + +use mlua::{ + Function, Lua, MetaMethod, MultiValue, Result as LuaResult, UserData, UserDataFields, + UserDataMethods, Value, +}; +use model::{BitDepth, Gradient}; + +use crate::cache::CachedTexture; + +use super::lua_host::{HostBridge, apply_temp_globals, restore_temp_globals, val_to_i32}; + +// --------------------------------------------------------------------------- +// Backing types for Fusion Lua UserData +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct LuaPixel { + pub(super) r: f32, + pub(super) g: f32, + pub(super) b: f32, + pub(super) a: f32, +} + +impl UserData for LuaPixel { + fn add_fields>(fields: &mut F) { + fields.add_field_method_get("R", |_, this| Ok(f64::from(this.r))); + fields.add_field_method_set("R", |_, this, v: f64| { + this.r = v as f32; + Ok(()) + }); + fields.add_field_method_get("G", |_, this| Ok(f64::from(this.g))); + fields.add_field_method_set("G", |_, this, v: f64| { + this.g = v as f32; + Ok(()) + }); + fields.add_field_method_get("B", |_, this| Ok(f64::from(this.b))); + fields.add_field_method_set("B", |_, this, v: f64| { + this.b = v as f32; + Ok(()) + }); + fields.add_field_method_get("A", |_, this| Ok(f64::from(this.a))); + fields.add_field_method_set("A", |_, this, v: f64| { + this.a = v as f32; + Ok(()) + }); + } + + fn add_methods>(methods: &mut M) { + methods.add_method_mut("Clear", |_, this, ()| { + *this = LuaPixel::default(); + Ok(()) + }); + } +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct LuaPoint { + pub(super) x: f64, + pub(super) y: f64, +} + +impl UserData for LuaPoint { + fn add_fields>(fields: &mut F) { + fields.add_field_method_get("X", |_, this| Ok(this.x)); + fields.add_field_method_set("X", |_, this, v: f64| { + this.x = v; + Ok(()) + }); + fields.add_field_method_get("Y", |_, this| Ok(this.y)); + fields.add_field_method_set("Y", |_, this, v: f64| { + this.y = v; + Ok(()) + }); + } + + fn add_methods>(methods: &mut M) { + methods.add_meta_method(MetaMethod::Add, |_, a, b: mlua::UserDataRef| { + Ok(LuaPoint { x: a.x + b.x, y: a.y + b.y }) + }); + methods.add_meta_method(MetaMethod::Sub, |_, a, b: mlua::UserDataRef| { + Ok(LuaPoint { x: a.x - b.x, y: a.y - b.y }) + }); + methods.add_meta_method(MetaMethod::Mul, |_, a, s: f64| { + Ok(LuaPoint { x: a.x * s, y: a.y * s }) + }); + } +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct LuaVector4 { + pub(super) x: f64, + pub(super) y: f64, + pub(super) z: f64, + pub(super) w: f64, +} + +impl UserData for LuaVector4 { + fn add_fields>(fields: &mut F) { + fields.add_field_method_get("X", |_, this| Ok(this.x)); + fields.add_field_method_get("Y", |_, this| Ok(this.y)); + fields.add_field_method_get("Z", |_, this| Ok(this.z)); + fields.add_field_method_get("W", |_, this| Ok(this.w)); + fields.add_field_method_set("X", |_, this, v: f64| { this.x = v; Ok(()) }); + fields.add_field_method_set("Y", |_, this, v: f64| { this.y = v; Ok(()) }); + fields.add_field_method_set("Z", |_, this, v: f64| { this.z = v; Ok(()) }); + fields.add_field_method_set("W", |_, this, v: f64| { this.w = v; Ok(()) }); + } + + fn add_methods>(methods: &mut M) { + methods.add_meta_method(MetaMethod::Mul, |_, v, rhs: Value| match rhs { + Value::UserData(ud) => { + if let Ok(m) = ud.borrow::() { + Ok(m.mul_row_vec(*v)) + } else { + Err(mlua::Error::RuntimeError("unsupported Vector4 multiplication".into())) + } + } + Value::Number(s) => Ok(LuaVector4 { x: v.x * s, y: v.y * s, z: v.z * s, w: v.w * s }), + Value::Integer(s) => { + let s = s as f64; + Ok(LuaVector4 { x: v.x * s, y: v.y * s, z: v.z * s, w: v.w * s }) + } + _ => Err(mlua::Error::RuntimeError("unsupported Vector4 multiplication".into())), + }); + } +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct LuaImgRectI { + pub(super) left: i32, + pub(super) bottom: i32, + pub(super) right: i32, + pub(super) top: i32, +} + +impl LuaImgRectI { + fn intersect(self, o: Self) -> Self { + let l = self.left.max(o.left); + let b = self.bottom.max(o.bottom); + let r = self.right.min(o.right).max(l); + let t = self.top.min(o.top).max(b); + Self { left: l, bottom: b, right: r, top: t } + } + + fn union(self, o: Self) -> Self { + Self { + left: self.left.min(o.left), + bottom: self.bottom.min(o.bottom), + right: self.right.max(o.right), + top: self.top.max(o.top), + } + } +} + +impl UserData for LuaImgRectI { + fn add_fields>(fields: &mut F) { + fields.add_field_method_get("left", |_, this| Ok(this.left)); + fields.add_field_method_get("bottom", |_, this| Ok(this.bottom)); + fields.add_field_method_get("right", |_, this| Ok(this.right)); + fields.add_field_method_get("top", |_, this| Ok(this.top)); + fields.add_field_method_set("left", |_, this, v: i32| { this.left = v; Ok(()) }); + fields.add_field_method_set("bottom", |_, this, v: i32| { this.bottom = v; Ok(()) }); + fields.add_field_method_set("right", |_, this, v: i32| { this.right = v; Ok(()) }); + fields.add_field_method_set("top", |_, this, v: i32| { this.top = v; Ok(()) }); + fields.add_field_method_get("ValidWindow", |_, this| Ok(*this)); + } + + fn add_methods>(methods: &mut M) { + methods.add_method("Width", |_, this, ()| Ok((this.right - this.left).max(0))); + methods.add_method("Height", |_, this, ()| Ok((this.top - this.bottom).max(0))); + methods.add_method("IsEmpty", |_, this, ()| { + Ok(this.right <= this.left || this.top <= this.bottom) + }); + methods.add_method("Intersect", |_, this, o: mlua::UserDataRef| { + Ok(this.intersect(*o)) + }); + methods.add_method("Union", |_, this, o: mlua::UserDataRef| { + Ok(this.union(*o)) + }); + methods.add_method_mut("Inflate", |_, this, (dx, dy): (f64, f64)| { + let ix = dx.ceil() as i32; + let iy = dy.ceil() as i32; + this.left -= ix; + this.right += ix; + this.bottom -= iy; + this.top += iy; + Ok(()) + }); + methods.add_method_mut("Offset", |_, this, (dx, dy): (i32, i32)| { + this.left += dx; + this.right += dx; + this.bottom += dy; + this.top += dy; + Ok(()) + }); + } +} + +/// Row-major 4x4 matrix matching Fusion's `Matrix4` (`v * m` row-vector convention). +#[derive(Clone, Copy, Debug)] +pub(super) struct LuaMatrix4 { + m: [f64; 16], +} + +impl LuaMatrix4 { + pub(super) fn identity() -> Self { + Self { + m: [ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ], + } + } + + fn mul(&self, rhs: &Self) -> Self { + let mut out = [0.0f64; 16]; + for r in 0..4 { + for c in 0..4 { + let mut sum = 0.0; + for k in 0..4 { + sum += self.m[r * 4 + k] * rhs.m[k * 4 + c]; + } + out[r * 4 + c] = sum; + } + } + Self { m: out } + } + + fn mul_row_vec(&self, v: LuaVector4) -> LuaVector4 { + let m = &self.m; + LuaVector4 { + x: v.x * m[0] + v.y * m[4] + v.z * m[8] + v.w * m[12], + y: v.x * m[1] + v.y * m[5] + v.z * m[9] + v.w * m[13], + z: v.x * m[2] + v.y * m[6] + v.z * m[10] + v.w * m[14], + w: v.x * m[3] + v.y * m[7] + v.z * m[11] + v.w * m[15], + } + } + + fn inverse(&self) -> Self { + // Gauss-Jordan inversion for 4x4 matrix + let mut a = [[0.0f64; 8]; 4]; + for r in 0..4 { + for c in 0..4 { + a[r][c] = self.m[r * 4 + c]; + } + a[r][4 + r] = 1.0; + } + for col in 0..4 { + let mut pivot = col; + for r in (col + 1)..4 { + if a[r][col].abs() > a[pivot][col].abs() { + pivot = r; + } + } + a.swap(col, pivot); + let div = a[col][col]; + if div.abs() < 1e-12 { + return Self::identity(); + } + for item in &mut a[col] { + *item /= div; + } + for r in 0..4 { + if r != col { + let f = a[r][col]; + for c in 0..8 { + a[r][c] -= f * a[col][c]; + } + } + } + } + let mut out = [0.0f64; 16]; + for r in 0..4 { + for c in 0..4 { + out[r * 4 + c] = a[r][4 + c]; + } + } + Self { m: out } + } +} + +impl UserData for LuaMatrix4 { + fn add_methods>(methods: &mut M) { + methods.add_method_mut("Identity", |_, this, ()| { + *this = Self::identity(); + Ok(()) + }); + methods.add_method_mut("Move", |_, this, (x, y, z): (f64, f64, f64)| { + let mut t = Self::identity(); + t.m[12] = x; + t.m[13] = y; + t.m[14] = z; + *this = this.mul(&t); + Ok(()) + }); + methods.add_method_mut("Scale", |_, this, (x, y, z): (f64, f64, f64)| { + let mut s = Self::identity(); + s.m[0] = x; + s.m[5] = y; + s.m[10] = z; + *this = this.mul(&s); + Ok(()) + }); + methods.add_method_mut("RotX", |_, this, deg: f64| { + let (s, c) = deg.to_radians().sin_cos(); + let mut r = Self::identity(); + r.m[5] = c; r.m[6] = s; r.m[9] = -s; r.m[10] = c; + *this = this.mul(&r); + Ok(()) + }); + methods.add_method_mut("RotY", |_, this, deg: f64| { + let (s, c) = deg.to_radians().sin_cos(); + let mut r = Self::identity(); + r.m[0] = c; r.m[2] = -s; r.m[8] = s; r.m[10] = c; + *this = this.mul(&r); + Ok(()) + }); + methods.add_method_mut("RotZ", |_, this, deg: f64| { + let (s, c) = deg.to_radians().sin_cos(); + let mut r = Self::identity(); + r.m[0] = c; r.m[1] = s; r.m[4] = -s; r.m[5] = c; + *this = this.mul(&r); + Ok(()) + }); + methods.add_method("Inverse", |_, this, ()| Ok(this.inverse())); + methods.add_meta_method(MetaMethod::Mul, |_, a, b: mlua::UserDataRef| { + Ok(a.mul(&b)) + }); + } +} + +#[derive(Clone, Debug)] +pub(super) struct LuaGradient(pub(super) Gradient); + +impl UserData for LuaGradient { + fn add_methods>(methods: &mut M) { + methods.add_method("QuickEvaluate", |_, this, (pos, _space): (f64, Option)| { + let c = this.0.sample(pos); + Ok(LuaPixel { r: c[0], g: c[1], b: c[2], a: c[3] }) + }); + } +} + +// --------------------------------------------------------------------------- +// Image userdata (zero-copy GPU backing + lazy CPU pixel buffer) +// --------------------------------------------------------------------------- + +#[derive(Clone)] +pub enum ImageBacking { + Gpu(CachedTexture), + Cpu(Vec<[f32; 4]>), + Deferred, +} + +pub struct ImageInner { + pub width: u32, + pub height: u32, + pub depth: BitDepth, + pub x_scale: f64, + pub y_scale: f64, + pub is_mask: bool, + pub backing: ImageBacking, +} + +impl ImageInner { + fn ensure_cpu(&mut self, lua: &Lua) -> LuaResult<&mut Vec<[f32; 4]>> { + if let ImageBacking::Gpu(ref tex) = self.backing { + let tex_clone = tex.clone(); + let pixels = { + let mut bridge = lua + .app_data_mut::() + .ok_or_else(|| mlua::Error::RuntimeError("missing HostBridge".into()))?; + bridge + .readback_gpu_to_fusion_y_up(&tex_clone) + .map_err(mlua::Error::RuntimeError)? + }; + self.width = tex_clone.size[0]; + self.height = tex_clone.size[1]; + self.backing = ImageBacking::Cpu(pixels); + } else if matches!(self.backing, ImageBacking::Deferred) { + let n = (self.width as usize).saturating_mul(self.height as usize); + self.backing = ImageBacking::Cpu(vec![[0.0; 4]; n]); + } + match &mut self.backing { + ImageBacking::Cpu(v) => Ok(v), + _ => unreachable!(), + } + } + + pub fn ensure_gpu(&mut self, bridge: &HostBridge, hash: u64) -> CachedTexture { + match &self.backing { + ImageBacking::Gpu(tex) => tex.clone(), + ImageBacking::Cpu(pixels) => { + let tex = bridge.upload_fusion_y_up_to_gpu( + self.width, + self.height, + self.depth, + pixels, + hash, + ); + self.backing = ImageBacking::Gpu(tex.clone()); + tex + } + ImageBacking::Deferred => { + let tex = bridge.alloc_gpu_tex([self.width, self.height], self.depth, hash); + self.backing = ImageBacking::Gpu(tex.clone()); + tex + } + } + } +} + +#[derive(Clone)] +pub(super) struct LuaImage(pub(super) Rc>); + +impl UserData for LuaImage { + fn add_fields>(fields: &mut F) { + fields.add_field_method_get("Width", |_, this| Ok(this.0.borrow().width)); + fields.add_field_method_get("Height", |_, this| Ok(this.0.borrow().height)); + fields.add_field_method_get("OriginalWidth", |_, this| Ok(this.0.borrow().width)); + fields.add_field_method_get("OriginalHeight", |_, this| Ok(this.0.borrow().height)); + fields.add_field_method_get("XScale", |_, this| Ok(this.0.borrow().x_scale)); + fields.add_field_method_get("YScale", |_, this| Ok(this.0.borrow().y_scale)); + fields.add_field_method_set("XScale", |_, this, v: f64| { this.0.borrow_mut().x_scale = v; Ok(()) }); + fields.add_field_method_set("YScale", |_, this, v: f64| { this.0.borrow_mut().y_scale = v; Ok(()) }); + fields.add_field_method_get("Depth", |_, this| Ok(depth_to_fusion_imdp(this.0.borrow().depth))); + fields.add_field_method_get("DataWindow", |_, this| { + let b = this.0.borrow(); + Ok(LuaImgRectI { left: 0, bottom: 0, right: b.width as i32, top: b.height as i32 }) + }); + fields.add_field_method_get("ValidWindow", |_, this| { + let b = this.0.borrow(); + Ok(LuaImgRectI { left: 0, bottom: 0, right: b.width as i32, top: b.height as i32 }) + }); + } + + fn add_methods>(methods: &mut M) { + methods.add_method("IsMask", |_, this, ()| Ok(this.0.borrow().is_mask)); + methods.add_method("GetPixel", |lua, this, (x, y, mut p): (i32, i32, mlua::UserDataRefMut)| { + let mut inner = this.0.borrow_mut(); + let w = inner.width as i32; + let h = inner.height as i32; + let px = inner.ensure_cpu(lua)?; + if x >= 0 && x < w && y >= 0 && y < h { + let c = px[(y * w + x) as usize]; + p.r = c[0]; p.g = c[1]; p.b = c[2]; p.a = c[3]; + } else { + *p = LuaPixel::default(); + } + Ok(()) + }); + methods.add_method("SetPixel", |lua, this, (x, y, p): (i32, i32, mlua::UserDataRef)| { + let mut inner = this.0.borrow_mut(); + let w = inner.width as i32; + let h = inner.height as i32; + let px = inner.ensure_cpu(lua)?; + if x >= 0 && x < w && y >= 0 && y < h { + px[(y * w + x) as usize] = [p.r, p.g, p.b, p.a]; + } + Ok(()) + }); + methods.add_method("SamplePixelB", |lua, this, (fx, fy, mut p): (f64, f64, mlua::UserDataRefMut)| { + let mut inner = this.0.borrow_mut(); + let w = inner.width as i32; + let h = inner.height as i32; + let px = inner.ensure_cpu(lua)?; + let x0 = (fx.floor() as i32).clamp(0, w - 1); + let y0 = (fy.floor() as i32).clamp(0, h - 1); + let x1 = (x0 + 1).min(w - 1); + let y1 = (y0 + 1).min(h - 1); + let tx = (fx - fx.floor()) as f32; + let ty = (fy - fy.floor()) as f32; + let c00 = px[(y0 * w + x0) as usize]; + let c10 = px[(y0 * w + x1) as usize]; + let c01 = px[(y1 * w + x0) as usize]; + let c11 = px[(y1 * w + x1) as usize]; + let mix = |a: f32, b: f32, t: f32| a + (b - a) * t; + p.r = mix(mix(c00[0], c10[0], tx), mix(c01[0], c11[0], tx), ty); + p.g = mix(mix(c00[1], c10[1], tx), mix(c01[1], c11[1], tx), ty); + p.b = mix(mix(c00[2], c10[2], tx), mix(c01[2], c11[2], tx), ty); + p.a = mix(mix(c00[3], c10[3], tx), mix(c01[3], c11[3], tx), ty); + Ok(()) + }); + methods.add_method("Fill", |lua, this, p: mlua::UserDataRef| { + let mut inner = this.0.borrow_mut(); + let px = inner.ensure_cpu(lua)?; + px.fill([p.r, p.g, p.b, p.a]); + Ok(()) + }); + methods.add_method("Clear", |lua, this, ()| { + let mut inner = this.0.borrow_mut(); + let px = inner.ensure_cpu(lua)?; + px.fill([0.0; 4]); + Ok(()) + }); + methods.add_method("CopyOf", |_, this, ()| { + let b = this.0.borrow(); + Ok(LuaImage(Rc::new(RefCell::new(ImageInner { + width: b.width, + height: b.height, + depth: b.depth, + x_scale: b.x_scale, + y_scale: b.y_scale, + is_mask: b.is_mask, + backing: b.backing.clone(), + })))) + }); + methods.add_method("Gain", |lua, this, (r, g, b, a): (f64, f64, f64, f64)| { + let mut inner = this.0.borrow_mut(); + let px = inner.ensure_cpu(lua)?; + for p in px.iter_mut() { + p[0] *= r as f32; + p[1] *= g as f32; + p[2] *= b as f32; + p[3] *= a as f32; + } + Ok(()) + }); + methods.add_method("Gamma", |lua, this, (r, g, b, a): (f64, f64, f64, f64)| { + let mut inner = this.0.borrow_mut(); + let px = inner.ensure_cpu(lua)?; + let inv = |v: f64| if v.abs() > 1e-6 { (1.0 / v) as f32 } else { 1.0 }; + let (ir, ig, ib, ia) = (inv(r), inv(g), inv(b), inv(a)); + for p in px.iter_mut() { + p[0] = p[0].max(0.0).powf(ir); + p[1] = p[1].max(0.0).powf(ig); + p[2] = p[2].max(0.0).powf(ib); + p[3] = p[3].max(0.0).powf(ia); + } + Ok(()) + }); + methods.add_method("MultiProcessPixels", |lua, this, args: MultiValue| { + let vals: Vec = args.into_iter().collect(); + if vals.len() < 7 { + return Err(mlua::Error::RuntimeError("MultiProcessPixels expects at least 7 arguments".into())); + } + let init_fn = match &vals[0] { Value::Function(f) => Some(f.clone()), _ => None }; + let env_tbl = match &vals[1] { Value::Table(t) => Some(t.clone()), _ => None }; + let x0 = val_to_i32(&vals[2]).max(0); + let y0 = val_to_i32(&vals[3]).max(0); + let rw = val_to_i32(&vals[4]).max(0); + let rh = val_to_i32(&vals[5]).max(0); + let (img2_opt, func): (Option, Function) = if vals.len() >= 8 { + let img2 = match &vals[6] { + Value::UserData(ud) => ud.borrow::().ok().map(|r| r.clone()), + _ => None, + }; + let f = match &vals[7] { + Value::Function(f) => f.clone(), + _ => return Err(mlua::Error::RuntimeError("MultiProcessPixels missing callback".into())), + }; + (img2, f) + } else { + let f = match &vals[6] { + Value::Function(f) => f.clone(), + _ => return Err(mlua::Error::RuntimeError("MultiProcessPixels missing callback".into())), + }; + (None, f) + }; + + let saved = apply_temp_globals(lua, env_tbl.as_ref())?; + if let Some(init) = init_fn { + init.call::<()>(())?; + } + + let mut inner = this.0.borrow_mut(); + let w = inner.width as i32; + let h = inner.height as i32; + let px1 = inner.ensure_cpu(lua)?; + let px2_opt: Option<(i32, i32, Vec<[f32; 4]>)> = if let Some(ref i2) = img2_opt { + let mut b2 = i2.0.borrow_mut(); + let w2 = b2.width as i32; + let h2 = b2.height as i32; + let data = b2.ensure_cpu(lua)?.clone(); + Some((w2, h2, data)) + } else { + None + }; + + let y_end = (y0 + rh).min(h); + let x_end = (x0 + rw).min(w); + for py in y0..y_end { + for px in x0..x_end { + let c1 = px1[(py * w + px) as usize]; + let p1_ud = lua.create_userdata(LuaPixel { r: c1[0], g: c1[1], b: c1[2], a: c1[3] })?; + let res: Value = if let Some((w2, h2, ref data2)) = px2_opt { + let c2 = if px < w2 && py < h2 { + data2[(py * w2 + px) as usize] + } else { + [0.0; 4] + }; + let p2_ud = lua.create_userdata(LuaPixel { r: c2[0], g: c2[1], b: c2[2], a: c2[3] })?; + func.call((px, py, p1_ud.clone(), p2_ud))? + } else { + func.call((px, py, p1_ud.clone()))? + }; + if let Value::UserData(out_ud) = res { + if let Ok(p) = out_ud.borrow::() { + px1[(py * w + px) as usize] = [p.r, p.g, p.b, p.a]; + } + } else if let Ok(p) = p1_ud.borrow::() { + px1[(py * w + px) as usize] = [p.r, p.g, p.b, p.a]; + } + } + } + restore_temp_globals(lua, saved)?; + Ok(()) + }); + } +} + +fn depth_to_fusion_imdp(d: BitDepth) -> i32 { + match d { + BitDepth::Int8 => 5, + BitDepth::Int16 => 6, + BitDepth::Float16 => 7, + BitDepth::Float32 => 8, + } +} + +pub(super) fn fusion_imdp_to_depth(v: i32) -> Option { + match v { + 1 | 5 => Some(BitDepth::Int8), + 2 | 6 => Some(BitDepth::Int16), + 3 | 7 => Some(BitDepth::Float16), + 4 | 8 => Some(BitDepth::Float32), + _ => None, + } +} + diff --git a/crates/engine/src/fuse_runtime/mod.rs b/crates/engine/src/fuse_runtime/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..9ee779d71fc45d47140e6cdc60efa757c9bb2e94 --- /dev/null +++ b/crates/engine/src/fuse_runtime/mod.rs @@ -0,0 +1,525 @@ +//! Fusion Lua + GPU-Accelerated DCTL Fuse Runtime. +//! +//! Provides automatic `.fuse` discovery (`FuseRegistry`), a pure-Rust DCTL→WGSL compute shader +//! transpiler ([`dctl`]), a sandboxed Lua 5.4 Fusion API host ([`lua_host`], native-only), and +//! `Engine::eval_fuse_runtime(...)` fallback integration for `Fuse.*` nodes. + +pub mod dctl; +mod dctl_expr; +mod dctl_parse; +#[cfg(not(target_arch = "wasm32"))] +mod lua_bridge; +#[cfg(not(target_arch = "wasm32"))] +mod lua_dvip; +#[cfg(not(target_arch = "wasm32"))] +pub mod lua_host; +#[cfg(not(target_arch = "wasm32"))] +mod lua_types; +#[cfg(test)] +mod tests; + +use std::collections::{HashMap, HashSet}; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use model::{Comp, Node, NodeId}; + +use crate::cache::{CachedTexture, EvalStats}; +use crate::eval::Engine; + +use self::dctl::ParamLayout; + +const MAX_DCTL_PIPELINES: usize = 64; + +/// Metadata captured from `FuRegisterClass(id, class_type, attrs)`. +#[derive(Clone, Debug, Default)] +pub struct FuseMeta { + pub id: String, + pub name: String, + pub class_type: String, + pub op_no_mask: bool, + pub time_variant: bool, +} + +/// Registered `.fuse` script entry inside [`FuseRegistry`]. +#[derive(Clone, Debug)] +pub struct FuseEntry { + pub id: String, + pub source: String, + pub source_hash: u64, + pub path: Option, +} + +/// Cached compiled WGSL compute pipeline for a DCTL kernel. +pub struct CompiledDctlPipeline { + pub pipeline: wgpu::ComputePipeline, + pub bgl: wgpu::BindGroupLayout, + pub param_layout: ParamLayout, + pub input_textures: Vec, + pub output_textures: Vec, +} + +/// Bounded cache of compiled DCTL `wgpu::ComputePipeline`s. +#[derive(Default)] +pub struct DctlPipelineCache { + entries: HashMap<(u64, wgpu::TextureFormat), (u64, Arc)>, + tick: u64, +} + +impl DctlPipelineCache { + pub fn get(&mut self, key: &(u64, wgpu::TextureFormat)) -> Option> { + self.tick = self.tick.wrapping_add(1); + let tick = self.tick; + let entry = self.entries.get_mut(key)?; + entry.0 = tick; + Some(entry.1.clone()) + } + + pub fn insert(&mut self, key: (u64, wgpu::TextureFormat), val: Arc) { + self.tick = self.tick.wrapping_add(1); + if self.entries.len() >= MAX_DCTL_PIPELINES + && let Some(oldest) = self + .entries + .iter() + .min_by_key(|(_, (t, _))| *t) + .map(|(k, _)| *k) + { + self.entries.remove(&oldest); + } + self.entries.insert(key, (self.tick, val)); + } + + pub fn clear(&mut self) { + self.entries.clear(); + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + +/// Registry of discovered and programmatically registered `.fuse` scripts plus the shared +/// compiled DCTL GPU pipeline cache. +pub struct FuseRegistry { + entries: HashMap, + #[cfg(not(target_arch = "wasm32"))] + scanned_comp_dirs: HashSet, + pub(crate) pipeline_cache: Arc>, + pub last_error: Option, +} + +impl Default for FuseRegistry { + fn default() -> Self { + Self::new() + } +} + +impl FuseRegistry { + /// Creates a registry and automatically discovers `.fuse` scripts from standard Fusion / + /// Reactor directories on native platforms. + pub fn new() -> Self { + #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] + let mut reg = Self::empty(); + #[cfg(not(target_arch = "wasm32"))] + reg.discover_default_dirs(); + reg + } + + /// Creates an empty registry without scanning disk (useful for isolated tests). + pub fn empty() -> Self { + Self { + entries: HashMap::new(), + #[cfg(not(target_arch = "wasm32"))] + scanned_comp_dirs: HashSet::new(), + pipeline_cache: Arc::new(Mutex::new(DctlPipelineCache::default())), + last_error: None, + } + } + + /// Normalizes a Fuse class name (`"Fuse.Tintensity"` or `"Tintensity"` -> `"tintensity"`). + pub fn normalize_key(kind: &str) -> String { + let stripped = kind.strip_prefix("Fuse.").unwrap_or(kind); + stripped.trim().to_ascii_lowercase() + } + + /// Registers an in-memory `.fuse` source under `id` (and also under any `FuRegisterClass` ID + /// declared inside `source`). + pub fn register_source(&mut self, id: &str, source: &str) { + let source_hash = hash_source(source); + let reg_id = extract_register_class_id(source); + let canonical = if !id.is_empty() { + id.strip_prefix("Fuse.").unwrap_or(id).to_owned() + } else { + reg_id.clone().unwrap_or_default() + }; + if canonical.is_empty() { + return; + } + let entry = FuseEntry { + id: canonical.clone(), + source: source.to_owned(), + source_hash, + path: None, + }; + self.entries.insert(Self::normalize_key(&canonical), entry.clone()); + if let Some(rid) = reg_id { + self.entries.insert(Self::normalize_key(&rid), entry); + } + } + + /// Registers a `.fuse` file from disk. Returns the registered class ID on success. + #[cfg(not(target_arch = "wasm32"))] + pub fn register_file(&mut self, path: &Path) -> Result { + let source = std::fs::read_to_string(path) + .map_err(|e| format!("failed to read {}: {e}", path.display()))?; + let source_hash = hash_source(&source); + let stem = path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_owned(); + let reg_id = extract_register_class_id(&source); + let canonical = reg_id.clone().unwrap_or_else(|| stem.clone()); + if canonical.is_empty() { + return Err(format!("could not determine Fuse ID for {}", path.display())); + } + let entry = FuseEntry { + id: canonical.clone(), + source, + source_hash, + path: Some(path.to_path_buf()), + }; + self.entries.insert(Self::normalize_key(&canonical), entry.clone()); + if !stem.is_empty() && Self::normalize_key(&stem) != Self::normalize_key(&canonical) { + self.entries.entry(Self::normalize_key(&stem)).or_insert(entry); + } + Ok(canonical) + } + + /// Recursively scans `dir` for `*.fuse` scripts and registers them. + #[cfg(not(target_arch = "wasm32"))] + pub fn scan_dir(&mut self, dir: &Path) { + let Ok(rd) = std::fs::read_dir(dir) else { + return; + }; + for item in rd.flatten() { + let p = item.path(); + if p.is_dir() { + self.scan_dir(&p); + } else if p + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("fuse")) + { + let _ = self.register_file(&p); + } + } + } + + /// Discovers Fuses from standard Reactor, system, and user Fusion Fuse directories. + #[cfg(not(target_arch = "wasm32"))] + pub fn discover_default_dirs(&mut self) { + let mut dirs: Vec = Vec::new(); + #[cfg(target_os = "macos")] + { + dirs.push(PathBuf::from( + "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses", + )); + dirs.push(PathBuf::from( + "/Library/Application Support/Blackmagic Design/Fusion/Fuses", + )); + if let Ok(home) = std::env::var("HOME") { + dirs.push( + PathBuf::from(&home) + .join("Library/Application Support/Blackmagic Design/Fusion/Fuses"), + ); + dirs.push( + PathBuf::from(&home) + .join("Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses"), + ); + } + } + #[cfg(target_os = "linux")] + { + dirs.push(PathBuf::from( + "/var/BlackmagicDesign/Fusion/Reactor/Deploy/Fuses", + )); + if let Ok(home) = std::env::var("HOME") { + dirs.push(PathBuf::from(&home).join(".fusion/BlackmagicDesign/Fusion/Fuses")); + } + } + #[cfg(target_os = "windows")] + { + if let Ok(prog) = std::env::var("ALLUSERSPROFILE") { + dirs.push( + PathBuf::from(prog) + .join("Blackmagic Design/Fusion/Reactor/Deploy/Fuses"), + ); + } + if let Ok(app) = std::env::var("APPDATA") { + dirs.push(PathBuf::from(app).join("Blackmagic Design/Fusion/Fuses")); + } + } + for d in dirs { + if d.is_dir() { + self.scan_dir(&d); + } + } + } + + /// Lazily scans `/Fuses` once per comp directory. + pub fn scan_comp_local(&mut self, comp_path: Option<&Path>) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(parent) = comp_path.and_then(Path::parent) { + let local_fuses = parent.join("Fuses"); + if self.scanned_comp_dirs.insert(local_fuses.clone()) && local_fuses.is_dir() { + self.scan_dir(&local_fuses); + } + } + #[cfg(target_arch = "wasm32")] + let _ = comp_path; + } + + pub fn has_fuse(&self, kind: &str) -> bool { + self.entries.contains_key(&Self::normalize_key(kind)) + } + + pub fn get(&self, kind: &str) -> Option<&FuseEntry> { + self.entries.get(&Self::normalize_key(kind)) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn clear_pipeline_cache(&self) { + if let Ok(mut c) = self.pipeline_cache.lock() { + c.clear(); + } + } +} + +fn hash_source(src: &str) -> u64 { + let mut h = DefaultHasher::new(); + src.hash(&mut h); + h.finish() +} + +/// Lightweight parser extracting the class ID string from `FuRegisterClass("MyFuse", ...)`. +pub fn extract_register_class_id(source: &str) -> Option { + let idx = source.find("FuRegisterClass")?; + let after = &source[idx + "FuRegisterClass".len()..]; + let open = after.find('(')?; + let args = after[open + 1..].trim_start(); + let quote = args.as_bytes().first().copied()?; + if quote != b'"' && quote != b'\'' { + return None; + } + let rest = &args[1..]; + let end = rest.find(quote as char)?; + let id = rest[..end].trim(); + (!id.is_empty()).then(|| id.to_owned()) +} + +// --------------------------------------------------------------------------- +// Engine integration +// --------------------------------------------------------------------------- + +impl Engine { + /// Attempts to evaluate a `Fuse.*` node using the registered Lua / GPU-DCTL Fuse runtime. + /// Returns `None` if no matching `.fuse` is registered or if execution fails (allowing the + /// caller to fall back cleanly to passthrough + `unsupported_nodes`). + #[allow(clippy::too_many_arguments)] + pub(crate) fn eval_fuse_runtime( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> Option { + self.eval_fuse_by_id( + &node.kind, comp, node, time, frame_i, comp_dims, enc, visiting, stats, + ) + } + + /// Evaluates `node` using the Fuse registered under `fuse_id`. + #[allow(clippy::too_many_arguments)] + pub fn eval_fuse_by_id( + &mut self, + fuse_id: &str, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> Option { + #[cfg(target_arch = "wasm32")] + { + let _ = (fuse_id, comp, node, time, frame_i, comp_dims, enc, visiting, stats); + None + } + #[cfg(not(target_arch = "wasm32"))] + { + self.fuse_registry.scan_comp_local(comp.path.as_deref()); + let entry = self.fuse_registry.get(fuse_id)?.clone(); + + // 1. Evaluate all connected flow-node image inputs + let mut img_ports: Vec<(String, NodeId)> = Vec::new(); + for (port, binding) in &node.inputs { + if let Some(src_name) = &binding.source_op + && let Some(src_id) = comp.find_node(src_name) + { + img_ports.push((port.clone(), src_id)); + } + } + img_ports.sort_by(|a, b| a.0.cmp(&b.0)); + + let mut upstream_images: HashMap = HashMap::new(); + for (port, src_id) in &img_ports { + let tex = self.eval_node(comp, *src_id, time, enc, visiting, stats); + upstream_images.insert(port.clone(), tex); + } + let main_input = ["Input", "Image", "Background", "Source", "MainInput1", "Image1"] + .iter() + .find_map(|p| upstream_images.get(*p).cloned()) + .or_else(|| { + img_ports + .iter() + .find(|(p, _)| p != "EffectMask") + .and_then(|(p, _)| upstream_images.get(p).cloned()) + }); + + // 2. Evaluate all scalar / point / text / gradient node parameters at `time` + let mut param_keys: Vec<&String> = node.inputs.keys().collect(); + param_keys.sort(); + let mut eval_params: HashMap = HashMap::new(); + let mut key_hasher = DefaultHasher::new(); + self.cache.gpu_salt.hash(&mut key_hasher); + self.hiq.hash(&mut key_hasher); + self.cache.node_salt(node.id).hash(&mut key_hasher); + "FuseRuntime".hash(&mut key_hasher); + entry.source_hash.hash(&mut key_hasher); + comp_dims.hash(&mut key_hasher); + (if time == 0.0 { 0.0 } else { time }).to_bits().hash(&mut key_hasher); + + for (port, _) in &img_ports { + port.hash(&mut key_hasher); + if let Some(tex) = upstream_images.get(port) { + tex.content_hash.hash(&mut key_hasher); + tex.size.hash(&mut key_hasher); + } + } + + for k in param_keys { + let binding = &node.inputs[k]; + if binding.source_op.as_deref().is_some_and(|s| comp.find_node(s).is_some()) { + continue; + } + k.hash(&mut key_hasher); + match &binding.value { + Some(model::ParamValue::Point(def)) => { + let pt = comp.eval_point(node, k, time, *def, &self.expr); + pt[0].to_bits().hash(&mut key_hasher); + pt[1].to_bits().hash(&mut key_hasher); + eval_params.insert(k.clone(), lua_host::EvalParam::Point(pt)); + } + Some(model::ParamValue::Text(s) | model::ParamValue::FuId(s)) => { + s.hash(&mut key_hasher); + eval_params.insert(k.clone(), lua_host::EvalParam::Text(s.clone())); + } + Some(model::ParamValue::Gradient(g)) => { + g.stops.len().hash(&mut key_hasher); + eval_params.insert(k.clone(), lua_host::EvalParam::Gradient(g.clone())); + } + _ => { + let def = binding + .value + .as_ref() + .and_then(model::ParamValue::as_f64) + .unwrap_or(0.0); + let v = comp.eval_number(node, k, time, def, &self.expr); + v.to_bits().hash(&mut key_hasher); + eval_params.insert(k.clone(), lua_host::EvalParam::Number(v)); + } + } + } + + let key = key_hasher.finish(); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return Some(hit); + } + + // 3. Execute sandboxed Lua + GPU DCTL Fuse + let upstream_depth = main_input.as_ref().map(|t| t.depth); + let default_depth = self.node_depth(comp, node, time, upstream_depth); + let taken_enc = std::mem::replace( + enc, + self.device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("fuse-runtime-placeholder"), + }), + ); + let bridge = lua_host::HostBridge { + device: self.device.clone(), + queue: self.queue.clone(), + encoder: Some(taken_enc), + dummy_tex: self.dummy.clone(), + pipeline_cache: self.fuse_registry.pipeline_cache.clone(), + supports_f32_filter: self.supports_f32_filter, + hiq: self.hiq, + default_depth, + comp_dims, + time, + global_range: comp.global_range, + render_range: comp.render_range, + upstream_images, + main_input, + params: eval_params, + fuse_meta: FuseMeta::default(), + output_image: None, + tool_data: HashMap::new(), + content_hash_seed: key, + }; + + let (res, returned_enc) = lua_host::execute_fuse(&entry.source, bridge); + *enc = returned_enc; + + match res { + Ok(Some(mut out_tex)) => { + self.fuse_registry.last_error = None; + out_tex.content_hash = key; + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + self.cache.insert(key, out_tex.clone(), node.id, frame_i); + Some(out_tex) + } + Ok(None) => { + self.fuse_registry.last_error = Some("Fuse did not call OutImage:Set".to_owned()); + None + } + Err(e) => { + self.fuse_registry.last_error = Some(e); + None + } + } + } + } +} diff --git a/crates/engine/src/fuse_runtime/tests.rs b/crates/engine/src/fuse_runtime/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..7244c80f1c27aabf0bab2f59f5ec6ceb634f0558 --- /dev/null +++ b/crates/engine/src/fuse_runtime/tests.rs @@ -0,0 +1,634 @@ +//! Comprehensive tests for DCTL→WGSL transpilation, sandboxed Fusion Lua execution, +//! real Reactor `.fuse` execution (GPU DCTL + CPU Lua), and `Engine::evaluate` fallback. + +use super::dctl::{ParamType, parse_param_block, transpile_dctl_to_wgsl}; +use super::{FuseRegistry, extract_register_class_id}; +use crate::{Engine, EvalStats}; +use model::Comp; +use std::collections::HashSet; +use std::path::Path; + +#[test] +fn dctl_param_block_layout_handles_arrays_vectors_and_typedef() { + let def = r#" + typedef struct { + float color[3]; + int mode; + float2 offset; + float4 tint; + unsigned int flags; + } MyParams; + "#; + let layout = parse_param_block(def).expect("parse param block"); + assert_eq!(layout.fields.len(), 5); + assert_eq!(layout.fields[0].name, "color"); + assert_eq!(layout.fields[0].array_len, Some(3)); + assert_eq!(layout.fields[0].offset, 0); + assert_eq!(layout.fields[0].size, 12); + + assert_eq!(layout.fields[1].name, "mode"); + assert_eq!(layout.fields[1].ty, ParamType::I32); + assert_eq!(layout.fields[1].offset, 12); + + assert_eq!(layout.fields[2].name, "offset"); + assert_eq!(layout.fields[2].ty, ParamType::Vec2F); + assert_eq!(layout.fields[2].offset, 16); + + assert_eq!(layout.fields[3].name, "tint"); + assert_eq!(layout.fields[3].ty, ParamType::Vec4F); + assert_eq!(layout.fields[3].offset, 32); + + assert_eq!(layout.fields[4].name, "flags"); + assert_eq!(layout.fields[4].ty, ParamType::U32); + assert_eq!(layout.fields[4].offset, 48); + assert_eq!(layout.total_size, 64); + + let mut buf = vec![0u8; layout.buffer_size()]; + layout.write_scalar(&mut buf, "color", Some(0), 0.25); + layout.write_scalar(&mut buf, "color", Some(1), 0.50); + layout.write_scalar(&mut buf, "color", Some(2), 0.75); + layout.write_scalar(&mut buf, "mode", None, 2.0); + assert!((layout.read_scalar(&buf, "color", Some(1)).unwrap() - 0.50).abs() < 1e-6); + assert_eq!(layout.read_scalar(&buf, "mode", None).unwrap(), 2.0); +} + +#[test] +fn dctl_transpiler_handles_helpers_intrinsics_swizzles_casts_and_compiles_on_wgpu() { + let dctl_src = r#" + typedef struct { + float gain; + float bias[3]; + int steps; + int compOrder; + } FullParams; + + __DEVICE__ float3 adjustColor(float3 c, float g, int steps) { + for (int i = 0; i < steps; i++) { + c.x = _clampf(c.x * g, 0.0f, 1.0f); + } + float s = _sinf(c.x) + _cosf(c.y) + _tanf(0.1f) + _atan2f(c.y, c.x + 0.01f); + float m = _sqrtf(_fabs(s)) + _powf(_fmaxf(c.z, 0.01f), 0.5f); + float f = _fmod(m, 1.0f) + _floorf(0.9f) + _ceilf(0.1f); + float e = _expf(0.0f) + _logf(1.0f) + _copysignf(0.1f, -1.0f); + float k = _saturatef(_mix(0.0f, 1.0f, 0.5f) + _fminf(f, e) * 0.0f); + return to_float3(c.x * k, c.y, c.z); + } + + __KERNEL__ void FullKernel(__CONSTANTREF__ FullParams *params, __TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) { + DEFINE_KERNEL_ITERATORS_XY(x, y); + float4 col = _tex2DVecN(src, x, y, params->compOrder); + float4 direct = _tex2DVec4(src, (float)x, (float)y); + float3 rgb = swi3(col, x, y, z); + float3 bias = to_float3_v(params->bias); + rgb = adjustColor(rgb + bias, params->gain, params->steps); + float4 outCol = make_float4(rgb.x, rgb.y, rgb.z, direct.w); + float4 swizzled = swi4(outCol, x, y, z, w); + if (params->steps > 0) { + _tex2DVec4Write(dst, x, y, swizzled); + } else { + _tex2DVec4Write(dst, x, y, to_float4(0.0f, 0.0f, 0.0f, 1.0f)); + } + } + "#; + + let transpiled = transpile_dctl_to_wgsl( + dctl_src, + "FullKernel", + Some("FullParams"), + None, + wgpu::TextureFormat::Rgba8Unorm, + ) + .expect("transpile full DCTL"); + + assert!(transpiled.wgsl.contains("@compute @workgroup_size(8, 8)")); + assert!(transpiled.wgsl.contains("fn adjustColor(")); + assert!(transpiled.wgsl.contains("params.gain")); + assert!(transpiled.wgsl.contains("((col).xyz)")); + assert!(transpiled.wgsl.contains("((outCol).xyzw)")); + assert!(transpiled.wgsl.contains("f32(x)")); + assert!(transpiled.wgsl.contains("textureStore(dst")); + assert_eq!(transpiled.input_textures, vec!["src"]); + assert_eq!(transpiled.output_textures, vec!["dst"]); + + #[cfg(not(target_arch = "wasm32"))] + if let Ok(eng) = Engine::new_headless() { + super::lua_host::compile_dctl_pipeline( + eng.device(), + &transpiled, + wgpu::TextureFormat::Rgba8Unorm, + ) + .expect("WGSL must compile cleanly in wgpu"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dctl_multi_input_fuse_executes_on_gpu_and_caches_pipeline() { + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let fuse_src = r#" +FuRegisterClass("BlendMixDctl", CT_Tool, { + REG_Name = "BlendMixDctl", + REG_OpNoMask = true, +}) + +MixParams = [[ + float mixAmt; + float tint[3]; + int swapRB; +]] + +MixKernel = [[ +__DEVICE__ float3 applyTint(float3 c, float3 t) { + c.x *= t.x; + c.y *= t.y; + c.z *= t.z; + return c; +} + +__KERNEL__ void MixKernel(__CONSTANTREF__ MixParams *params, __TEXTURE2D__ srcA, __TEXTURE2D__ srcB, __TEXTURE2D_WRITE__ dst) { + DEFINE_KERNEL_ITERATORS_XY(x, y); + float4 a = _tex2DVec4(srcA, x, y); + float4 b = _tex2DVec4(srcB, x, y); + float3 mixed = to_float3( + _mix(a.x, b.x, params->mixAmt), + _mix(a.y, b.y, params->mixAmt), + _mix(a.z, b.z, params->mixAmt) + ); + float3 tint = to_float3_v(params->tint); + mixed = applyTint(mixed, tint); + if (params->swapRB == 1) { + mixed = swi3(mixed, z, y, x); + } + _tex2DVec4Write(dst, x, y, to_float4(mixed.x, mixed.y, mixed.z, 1.0f)); +} +]] + +function Create() + InMix = self:AddInput("Mix", "Mix", { LINKID_DataType = "Number", INP_Default = 0.5 }) + InTintR = self:AddInput("TintR", "TintR", { LINKID_DataType = "Number", INP_Default = 1.0 }) + InTintG = self:AddInput("TintG", "TintG", { LINKID_DataType = "Number", INP_Default = 1.0 }) + InTintB = self:AddInput("TintB", "TintB", { LINKID_DataType = "Number", INP_Default = 1.0 }) + InSwap = self:AddInput("SwapRB", "SwapRB", { LINKID_DataType = "Number", INP_Default = 0 }) + InA = self:AddInput("InputA", "InputA", { LINKID_DataType = "Image", LINK_Main = 1 }) + InB = self:AddInput("InputB", "InputB", { LINKID_DataType = "Image", LINK_Main = 2 }) + OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 }) +end + +function Process(req) + local a = InA:GetValue(req) + local b = InB:GetValue(req) + local dst = Image{ IMG_Like = a, IMG_DeferAlloc = true } + local node = DVIPComputeNode(req, "MixKernel", MixKernel, "MixParams", MixParams) + local params = node:GetParamBlock(MixParams) + params.mixAmt = InMix:GetValue(req).Value + params.tint[0] = InTintR:GetValue(req).Value + params.tint[1] = InTintG:GetValue(req).Value + params.tint[2] = InTintB:GetValue(req).Value + params.swapRB = InSwap:GetValue(req).Value + node:SetParamBlock(params) + node:AddInput("srcA", a) + node:AddInput("srcB", b) + node:AddOutput("dst", dst) + local ok = node:RunSession(req) + if ok then + OutImage:Set(req, dst) + end +end +"#; + + eng.fuse_registry.register_source("BlendMixDctl", fuse_src); + let comp_src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BgA = Background { + Inputs = { + Width = Input { Value = 16, }, + Height = Input { Value = 16, }, + TopLeftRed = Input { Value = 0.8, }, + TopLeftGreen = Input { Value = 0.2, }, + TopLeftBlue = Input { Value = 0.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + BgB = Background { + Inputs = { + Width = Input { Value = 16, }, + Height = Input { Value = 16, }, + TopLeftRed = Input { Value = 0.0, }, + TopLeftGreen = Input { Value = 0.6, }, + TopLeftBlue = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + Mix1 = Fuse.BlendMixDctl { + Inputs = { + InputA = Input { SourceOp = "BgA", Source = "Output", }, + InputB = Input { SourceOp = "BgB", Source = "Output", }, + Mix = Input { Value = 0.5, }, + TintR = Input { Value = 0.5, }, + TintG = Input { Value = 1.0, }, + TintB = Input { Value = 1.0, }, + SwapRB = Input { Value = 1, }, + }, + }, + }, +} +"#; + + let comp = Comp::from_fusion_str(comp_src).expect("parse multi-input DCTL comp"); + let mix_id = comp.find_node("Mix1").unwrap(); + let (tex, stats) = eng.evaluate(&comp, mix_id, 0.0); + assert!( + stats.unsupported_nodes.is_empty(), + "Fuse.BlendMixDctl should execute natively, got unsupported: {:?}", + stats.unsupported_nodes + ); + let rgba = eng.readback_rgba(&tex).expect("readback"); + // Expected before swap: R = mix(0.8, 0.0, 0.5)*0.5 = 0.20, G = mix(0.2, 0.6, 0.5)*1.0 = 0.40, B = mix(0.0, 1.0, 0.5)*1.0 = 0.50 + // After SwapRB=1: R = 0.50 (128), G = 0.40 (102), B = 0.20 (51), A = 1.0 (255) + assert!((rgba[0] as i32 - 128).abs() <= 2, "R got {}", rgba[0]); + assert!((rgba[1] as i32 - 102).abs() <= 2, "G got {}", rgba[1]); + assert!((rgba[2] as i32 - 51).abs() <= 2, "B got {}", rgba[2]); + assert_eq!(rgba[3], 255); + assert!(eng.fuse_registry.pipeline_cache.lock().unwrap().len() >= 1); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn real_reactor_tintensity_fuse_executes_on_gpu() { + let tintensity_path = Path::new( + "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses/Color/Tintensity.fuse", + ); + if !tintensity_path.is_file() { + return; + } + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + assert!( + eng.fuse_registry.has_fuse("Fuse.Tintensity"), + "FuseRegistry::new() should auto-discover Reactor Tintensity.fuse" + ); + + // Input color: (0.2, 0.4, 0.6, 1.0). + // With PreGain=1.5, Red=0.5 (color picker adds color.r * col.r), PostGain=1.0: + // After PreGain: (0.3, 0.6, 0.9) + // After Color Picker (Red=0.5, Green=0, Blue=0): R = 0.3 + 0.5*0.3 = 0.45, G = 0.6, B = 0.9 + // Vibrance=0 => EvaluateVibrance adds 0 => (0.45, 0.6, 0.9, 1.0) -> (~115, ~153, ~230, 255) + let comp_src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 16, }, + Height = Input { Value = 16, }, + TopLeftRed = Input { Value = 0.2, }, + TopLeftGreen = Input { Value = 0.4, }, + TopLeftBlue = Input { Value = 0.6, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + TnT = Fuse.Tintensity { + Inputs = { + Image = Input { SourceOp = "BG", Source = "Output", }, + PreGain = Input { Value = 1.5, }, + Red = Input { Value = 0.5, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse Tintensity comp"); + let tnt_id = comp.find_node("TnT").unwrap(); + let (tex, stats) = eng.evaluate(&comp, tnt_id, 0.0); + assert!( + stats.unsupported_nodes.is_empty(), + "Fuse.Tintensity should execute natively on GPU, got unsupported: {:?}", + stats.unsupported_nodes + ); + let rgba = eng.readback_rgba(&tex).expect("readback Tintensity"); + assert!((rgba[0] as i32 - 115).abs() <= 3, "Tintensity R got {}", rgba[0]); + assert!((rgba[1] as i32 - 153).abs() <= 3, "Tintensity G got {}", rgba[1]); + assert!((rgba[2] as i32 - 230).abs() <= 3, "Tintensity B got {}", rgba[2]); + assert_eq!(rgba[3], 255); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn cpu_lua_fuse_image_pixel_apis_and_sandboxing_work() { + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let fuse_src = r#" +FuRegisterClass("CpuPixelDemo", CT_Tool, { + REG_Name = "CpuPixelDemo", + REG_TimeVariant = true, +}) + +function Create() + InBoost = self:AddInput("Boost", "Boost", { LINKID_DataType = "Number", INP_Default = 0.25 }) + InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 }) + OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 }) +end + +function Process(req) + -- Verify sandboxing: io and os are unavailable + assert(io == nil, "io must be sandboxed") + assert(os == nil, "os must be sandboxed") + + -- Verify Matrix4 and ImgRectI APIs + local m = Matrix4() + m:Identity() + m:Move(2, 3, 0) + local v = Vector4(1, 2, 0, 1) * m + assert(math.abs(v.X - 3) < 1e-6 and math.abs(v.Y - 5) < 1e-6) + local r = ImgRectI(0, 0, 8, 8):Intersect(ImgRectI(2, 2, 10, 10)) + assert(r:Width() == 6 and r:Height() == 6) + + local src = InImg:GetValue(req) + local boost = InBoost:GetValue(req).Value + local dst = Image({ IMG_Width = src.Width, IMG_Height = src.Height }) + dst:Fill(Pixel({ R = 0, G = 0, B = 0, A = 1 })) + local copy = dst:CopyOf() + copy:Clear() + local p = Pixel({ R = 0, G = 0, B = 0, A = 1 }) + for y = 0, src.Height - 1 do + for x = 0, src.Width - 1 do + src:GetPixel(x, y, p) + -- Flip R and B, add boost + frame-time nudge to G + local nr = p.B + local ng = math.min(1.0, p.G + boost + req.Time * 0.1) + local nb = p.R + p.R = nr + p.G = ng + p.B = nb + p.A = 1.0 + copy:SetPixel(x, y, p) + end + end + local rows_seen = 0 + self:DoMultiProcess(nil, {}, 2, function(y) rows_seen = rows_seen + 1 end) + assert(rows_seen == 2) + copy:MultiProcessPixels(nil, { delta = 0.0 }, 0, 0, src.Width, src.Height, function(x, y, px) + px.G = px.G + delta + return px + end) + OutImage:Set(req, copy) +end +"#; + eng.fuse_registry.register_source("CpuPixelDemo", fuse_src); + + let comp_src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 2 }, + GlobalRange = { 0, 2 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 16, }, + Height = Input { Value = 16, }, + TopLeftRed = Input { Value = 0.2, }, + TopLeftGreen = Input { Value = 0.3, }, + TopLeftBlue = Input { Value = 0.8, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + Demo = Fuse.CpuPixelDemo { + Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + Boost = Input { Value = 0.2, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse CPU Lua comp"); + let demo_id = comp.find_node("Demo").unwrap(); + + // Frame 0: R=0.8 (204), G=0.3+0.2=0.5 (128), B=0.2 (51) + let (tex0, stats0) = eng.evaluate(&comp, demo_id, 0.0); + assert!( + stats0.unsupported_nodes.is_empty(), + "CpuPixelDemo failed: {:?}", + eng.fuse_registry.last_error + ); + let px0 = eng.readback_rgba(&tex0).expect("readback frame 0"); + assert!((px0[0] as i32 - 204).abs() <= 2, "R0 got {}", px0[0]); + assert!((px0[1] as i32 - 128).abs() <= 2, "G0 got {}", px0[1]); + assert!((px0[2] as i32 - 51).abs() <= 2, "B0 got {}", px0[2]); + + // Frame 2: G = 0.3 + 0.2 + 0.2 = 0.7 (179) + let (tex2, _) = eng.evaluate(&comp, demo_id, 2.0); + let px2 = eng.readback_rgba(&tex2).expect("readback frame 2"); + assert!((px2[1] as i32 - 179).abs() <= 2, "G2 got {}", px2[1]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn real_reactor_hexagon_tiles_cpu_lua_matches_native_gpu_shader() { + let hex_path = Path::new( + "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses/Creator/HexagonTiles.fuse", + ); + if !hex_path.is_file() { + return; + } + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + assert!(eng.fuse_registry.has_fuse("HexagonTiles")); + + let comp_src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 0 }, + GlobalRange = { 0, 0 }, + Tools = ordered() { + Hex = Fuse.HexagonTiles { + Inputs = { + Width = Input { Value = 32, }, + Height = Input { Value = 32, }, + Size = Input { Value = 4.0, }, + BorderSize = Input { Value = 2.0, }, + Red1 = Input { Value = 0.2, }, + Green1 = Input { Value = 0.4, }, + Blue1 = Input { Value = 0.8, }, + Red2 = Input { Value = 0.9, }, + Green2 = Input { Value = 0.1, }, + Blue2 = Input { Value = 0.2, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse HexagonTiles comp"); + let hex_id = comp.find_node("Hex").unwrap(); + + // 1. Native fast-path GPU HexagonTiles output + let (gpu_tex, _) = eng.evaluate(&comp, hex_id, 0.0); + let gpu_rgba = eng.readback_rgba(&gpu_tex).expect("readback GPU HexagonTiles"); + + // 2. Real HexagonTiles.fuse executed via sandboxed Lua CPU runtime + let mut enc = eng.device().create_command_encoder(&Default::default()); + let mut visiting = HashSet::new(); + let mut stats = EvalStats::default(); + let lua_tex = eng + .eval_fuse_by_id( + "HexagonTiles", + &comp, + comp.node(hex_id), + 0.0, + 0, + [32, 32], + &mut enc, + &mut visiting, + &mut stats, + ) + .expect("HexagonTiles.fuse must succeed via Lua runtime"); + eng.queue().submit(Some(enc.finish())); + let lua_rgba = eng.readback_rgba(&lua_tex).expect("readback Lua HexagonTiles"); + + assert_eq!(gpu_rgba.len(), lua_rgba.len()); + // Allow rare float boundary tie on exact hexagon edge (<= 2% of pixels); interior must match within 2/255. + let mut mismatched = 0usize; + for (g, l) in gpu_rgba.chunks_exact(4).zip(lua_rgba.chunks_exact(4)) { + if (0..4).any(|c| (g[c] as i32 - l[c] as i32).abs() > 2) { + mismatched += 1; + } + } + let total = (32 * 32) as usize; + assert!( + mismatched * 100 <= total * 2, + "HexagonTiles.fuse Lua runtime diverged from GPU fast path on {mismatched}/{total} pixels" + ); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn engine_evaluate_fallback_runs_custom_dctl_and_gracefully_handles_broken_fuses() { + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let custom_demo = r#" +FuRegisterClass("CustomDemoDctl", CT_Tool, { REG_Name = "CustomDemoDctl" }) +DemoParams = [[ + float scaleR; + float addB; +]] +DemoKernel = [[ +__KERNEL__ void DemoKernel(__CONSTANTREF__ DemoParams *params, __TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) { + DEFINE_KERNEL_ITERATORS_XY(x, y); + float4 c = _tex2DVec4(src, x, y); + c.x = _saturatef(c.x * params->scaleR); + c.z = _saturatef(c.z + params->addB); + _tex2DVec4Write(dst, x, y, c); +} +]] +function Create() + InScaleR = self:AddInput("ScaleR", "ScaleR", { LINKID_DataType = "Number", INP_Default = 1.0 }) + InAddB = self:AddInput("AddB", "AddB", { LINKID_DataType = "Number", INP_Default = 0.0 }) + InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 }) + OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 }) +end +function Process(req) + local src = InImg:GetValue(req) + local dst = Image{ IMG_Like = src, IMG_DeferAlloc = true } + local node = DVIPComputeNode(req, "DemoKernel", DemoKernel, "DemoParams", DemoParams) + local p = node:GetParamBlock(DemoParams) + p.scaleR = InScaleR:GetValue(req).Value + p.addB = InAddB:GetValue(req).Value + node:SetParamBlock(p) + node:AddInput("src", src) + node:AddOutput("dst", dst) + if node:RunSession(req) then + OutImage:Set(req, dst) + end +end +"#; + let broken_dctl = r#" +FuRegisterClass("BrokenDemoDctl", CT_Tool, {}) +function Create() + InImg = self:AddInput("Input", "Input", { LINKID_DataType = "Image", LINK_Main = 1 }) + OutImage = self:AddOutput("Output", "Output", { LINKID_DataType = "Image", LINK_Main = 1 }) +end +function Process(req) + local src = InImg:GetValue(req) + local dst = Image{ IMG_Like = src, IMG_DeferAlloc = true } + local node = DVIPComputeNode(req, "Bad", "__KERNEL__ void Bad(__TEXTURE2D__ src, __TEXTURE2D_WRITE__ dst) { this is invalid wgsl syntax ???; }", "P", "") + node:AddInput("src", src) + node:AddOutput("dst", dst) + if node:RunSession(req) then + OutImage:Set(req, dst) + end +end +"#; + + eng.fuse_registry.register_source("CustomDemoDctl", custom_demo); + eng.fuse_registry.register_source("BrokenDemoDctl", broken_dctl); + assert_eq!(extract_register_class_id(custom_demo).as_deref(), Some("CustomDemoDctl")); + + let comp_src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 0 }, + GlobalRange = { 0, 0 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 16, }, + Height = Input { Value = 16, }, + TopLeftRed = Input { Value = 0.25, }, + TopLeftGreen = Input { Value = 0.50, }, + TopLeftBlue = Input { Value = 0.10, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + Demo = Fuse.CustomDemoDctl { + Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + ScaleR = Input { Value = 3.0, }, + AddB = Input { Value = 0.4, }, + }, + }, + Broken = Fuse.BrokenDemoDctl { + Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse fallback comp"); + + // 1. Registered CustomDemoDctl executes on GPU via fallback + let (tex, stats) = eng.evaluate(&comp, comp.find_node("Demo").unwrap(), 0.0); + assert!(stats.unsupported_nodes.is_empty()); + let px = eng.readback_rgba(&tex).expect("readback CustomDemoDctl"); + // R = 0.25*3 = 0.75 (191), G = 0.50 (128), B = 0.10+0.40 = 0.50 (128) + assert!((px[0] as i32 - 191).abs() <= 2, "R got {}", px[0]); + assert!((px[1] as i32 - 128).abs() <= 2, "G got {}", px[1]); + assert!((px[2] as i32 - 128).abs() <= 2, "B got {}", px[2]); + + // 2. Broken Fuse never panics and falls back cleanly to passthrough + unsupported_nodes + let (b_tex, b_stats) = eng.evaluate(&comp, comp.find_node("Broken").unwrap(), 0.0); + assert!( + b_stats.unsupported_nodes.iter().any(|s| s == "Fuse.BrokenDemoDctl"), + "broken fuse should be recorded in unsupported_nodes: {:?}", + b_stats.unsupported_nodes + ); + let b_px = eng.readback_rgba(&b_tex).expect("readback passthrough"); + assert!((b_px[0] as i32 - 64).abs() <= 2, "passthrough R got {}", b_px[0]); + assert!((b_px[1] as i32 - 128).abs() <= 2, "passthrough G got {}", b_px[1]); + + // 3. FuseRegistry::empty() starts empty + let empty_reg = FuseRegistry::empty(); + assert!(empty_reg.is_empty()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7817775a7e62a60b957431fd838597d8b25ee896..62c2352f30a21f2a5a83d83201bcd0a341fc0e6b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -6,6 +6,7 @@ pub mod custom_shader; pub mod eval; #[cfg(not(target_arch = "wasm32"))] pub mod export; +pub mod fuse_runtime; pub mod media; pub mod motion_blur; pub mod optflow; -- 2.54.1