1//! Fusion Lua + GPU-Accelerated DCTL Fuse Runtime.
2//!
3//! Provides automatic `.fuse` discovery (`FuseRegistry`), a pure-Rust DCTL→WGSL compute shader
4//! transpiler ([`dctl`]), a sandboxed Lua 5.4 Fusion API host ([`lua_host`], native-only), and
5//! `Engine::eval_fuse_runtime(...)` fallback integration for `Fuse.*` nodes.
6
7pub mod dctl;
8mod dctl_expr;
9mod dctl_parse;
10#[cfg(not(target_arch = "wasm32"))]
11mod lua_bridge;
12#[cfg(not(target_arch = "wasm32"))]
13mod lua_dvip;
14#[cfg(not(target_arch = "wasm32"))]
15pub mod lua_host;
16#[cfg(not(target_arch = "wasm32"))]
17mod lua_types;
18#[cfg(test)]
19mod tests;
20
21use std::collections::{HashMap, HashSet};
22use std::collections::hash_map::DefaultHasher;
23use std::hash::{Hash, Hasher};
24use std::path::{Path, PathBuf};
25use std::sync::{Arc, Mutex};
26
27use model::{Comp, Node, NodeId};
28
29use crate::cache::{CachedTexture, EvalStats};
30use crate::eval::Engine;
31
32use self::dctl::ParamLayout;
33
34const MAX_DCTL_PIPELINES: usize = 64;
35
36/// Metadata captured from `FuRegisterClass(id, class_type, attrs)`.
37#[derive(Clone, Debug, Default)]
38pub struct FuseMeta {
39 pub id: String,
40 pub name: String,
41 pub class_type: String,
42 pub op_no_mask: bool,
43 pub time_variant: bool,
44}
45
46/// Registered `.fuse` script entry inside [`FuseRegistry`].
47#[derive(Clone, Debug)]
48pub struct FuseEntry {
49 pub id: String,
50 pub source: String,
51 pub source_hash: u64,
52 pub path: Option<PathBuf>,
53}
54
55/// Cached compiled WGSL compute pipeline for a DCTL kernel.
56pub struct CompiledDctlPipeline {
57 pub pipeline: wgpu::ComputePipeline,
58 pub bgl: wgpu::BindGroupLayout,
59 pub param_layout: ParamLayout,
60 pub input_textures: Vec<String>,
61 pub output_textures: Vec<String>,
62}
63
64/// Bounded cache of compiled DCTL `wgpu::ComputePipeline`s.
65#[derive(Default)]
66pub struct DctlPipelineCache {
67 entries: HashMap<(u64, wgpu::TextureFormat), (u64, Arc<CompiledDctlPipeline>)>,
68 tick: u64,
69}
70
71impl DctlPipelineCache {
72 pub fn get(&mut self, key: &(u64, wgpu::TextureFormat)) -> Option<Arc<CompiledDctlPipeline>> {
73 self.tick = self.tick.wrapping_add(1);
74 let tick = self.tick;
75 let entry = self.entries.get_mut(key)?;
76 entry.0 = tick;
77 Some(entry.1.clone())
78 }
79
80 pub fn insert(&mut self, key: (u64, wgpu::TextureFormat), val: Arc<CompiledDctlPipeline>) {
81 self.tick = self.tick.wrapping_add(1);
82 if self.entries.len() >= MAX_DCTL_PIPELINES
83 && let Some(oldest) = self
84 .entries
85 .iter()
86 .min_by_key(|(_, (t, _))| *t)
87 .map(|(k, _)| *k)
88 {
89 self.entries.remove(&oldest);
90 }
91 self.entries.insert(key, (self.tick, val));
92 }
93
94 pub fn clear(&mut self) {
95 self.entries.clear();
96 }
97
98 pub fn len(&self) -> usize {
99 self.entries.len()
100 }
101
102 pub fn is_empty(&self) -> bool {
103 self.entries.is_empty()
104 }
105}
106
107/// Registry of discovered and programmatically registered `.fuse` scripts plus the shared
108/// compiled DCTL GPU pipeline cache.
109pub struct FuseRegistry {
110 entries: HashMap<String, FuseEntry>,
111 #[cfg(not(target_arch = "wasm32"))]
112 scanned_comp_dirs: HashSet<PathBuf>,
113 pub(crate) pipeline_cache: Arc<Mutex<DctlPipelineCache>>,
114 pub last_error: Option<String>,
115}
116
117impl Default for FuseRegistry {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123impl FuseRegistry {
124 /// Creates a registry and automatically discovers `.fuse` scripts from standard Fusion /
125 /// Reactor directories on native platforms.
126 pub fn new() -> Self {
127 #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
128 let mut reg = Self::empty();
129 #[cfg(not(target_arch = "wasm32"))]
130 reg.discover_default_dirs();
131 reg
132 }
133
134 /// Creates an empty registry without scanning disk (useful for isolated tests).
135 pub fn empty() -> Self {
136 Self {
137 entries: HashMap::new(),
138 #[cfg(not(target_arch = "wasm32"))]
139 scanned_comp_dirs: HashSet::new(),
140 pipeline_cache: Arc::new(Mutex::new(DctlPipelineCache::default())),
141 last_error: None,
142 }
143 }
144
145 /// Normalizes a Fuse class name (`"Fuse.Tintensity"` or `"Tintensity"` -> `"tintensity"`).
146 pub fn normalize_key(kind: &str) -> String {
147 let stripped = kind.strip_prefix("Fuse.").unwrap_or(kind);
148 stripped.trim().to_ascii_lowercase()
149 }
150
151 /// Registers an in-memory `.fuse` source under `id` (and also under any `FuRegisterClass` ID
152 /// declared inside `source`).
153 pub fn register_source(&mut self, id: &str, source: &str) {
154 let source_hash = hash_source(source);
155 let reg_id = extract_register_class_id(source);
156 let canonical = if !id.is_empty() {
157 id.strip_prefix("Fuse.").unwrap_or(id).to_owned()
158 } else {
159 reg_id.clone().unwrap_or_default()
160 };
161 if canonical.is_empty() {
162 return;
163 }
164 let entry = FuseEntry {
165 id: canonical.clone(),
166 source: source.to_owned(),
167 source_hash,
168 path: None,
169 };
170 self.entries.insert(Self::normalize_key(&canonical), entry.clone());
171 if let Some(rid) = reg_id {
172 self.entries.insert(Self::normalize_key(&rid), entry);
173 }
174 }
175
176 /// Registers a `.fuse` file from disk. Returns the registered class ID on success.
177 #[cfg(not(target_arch = "wasm32"))]
178 pub fn register_file(&mut self, path: &Path) -> Result<String, String> {
179 let source = std::fs::read_to_string(path)
180 .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
181 let source_hash = hash_source(&source);
182 let stem = path
183 .file_stem()
184 .and_then(|s| s.to_str())
185 .unwrap_or("")
186 .to_owned();
187 let reg_id = extract_register_class_id(&source);
188 let canonical = reg_id.clone().unwrap_or_else(|| stem.clone());
189 if canonical.is_empty() {
190 return Err(format!("could not determine Fuse ID for {}", path.display()));
191 }
192 let entry = FuseEntry {
193 id: canonical.clone(),
194 source,
195 source_hash,
196 path: Some(path.to_path_buf()),
197 };
198 self.entries.insert(Self::normalize_key(&canonical), entry.clone());
199 if !stem.is_empty() && Self::normalize_key(&stem) != Self::normalize_key(&canonical) {
200 self.entries.entry(Self::normalize_key(&stem)).or_insert(entry);
201 }
202 Ok(canonical)
203 }
204
205 /// Recursively scans `dir` for `*.fuse` scripts and registers them.
206 #[cfg(not(target_arch = "wasm32"))]
207 pub fn scan_dir(&mut self, dir: &Path) {
208 let Ok(rd) = std::fs::read_dir(dir) else {
209 return;
210 };
211 for item in rd.flatten() {
212 let p = item.path();
213 if p.is_dir() {
214 self.scan_dir(&p);
215 } else if p
216 .extension()
217 .and_then(|e| e.to_str())
218 .is_some_and(|e| e.eq_ignore_ascii_case("fuse"))
219 {
220 let _ = self.register_file(&p);
221 }
222 }
223 }
224
225 /// Discovers Fuses from standard Reactor, system, and user Fusion Fuse directories.
226 #[cfg(not(target_arch = "wasm32"))]
227 pub fn discover_default_dirs(&mut self) {
228 let mut dirs: Vec<PathBuf> = Vec::new();
229 #[cfg(target_os = "macos")]
230 {
231 dirs.push(PathBuf::from(
232 "/Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses",
233 ));
234 dirs.push(PathBuf::from(
235 "/Library/Application Support/Blackmagic Design/Fusion/Fuses",
236 ));
237 if let Ok(home) = std::env::var("HOME") {
238 dirs.push(
239 PathBuf::from(&home)
240 .join("Library/Application Support/Blackmagic Design/Fusion/Fuses"),
241 );
242 dirs.push(
243 PathBuf::from(&home)
244 .join("Library/Application Support/Blackmagic Design/Fusion/Reactor/Deploy/Fuses"),
245 );
246 }
247 }
248 #[cfg(target_os = "linux")]
249 {
250 dirs.push(PathBuf::from(
251 "/var/BlackmagicDesign/Fusion/Reactor/Deploy/Fuses",
252 ));
253 if let Ok(home) = std::env::var("HOME") {
254 dirs.push(PathBuf::from(&home).join(".fusion/BlackmagicDesign/Fusion/Fuses"));
255 }
256 }
257 #[cfg(target_os = "windows")]
258 {
259 if let Ok(prog) = std::env::var("ALLUSERSPROFILE") {
260 dirs.push(
261 PathBuf::from(prog)
262 .join("Blackmagic Design/Fusion/Reactor/Deploy/Fuses"),
263 );
264 }
265 if let Ok(app) = std::env::var("APPDATA") {
266 dirs.push(PathBuf::from(app).join("Blackmagic Design/Fusion/Fuses"));
267 }
268 }
269 for d in dirs {
270 if d.is_dir() {
271 self.scan_dir(&d);
272 }
273 }
274 }
275
276 /// Lazily scans `<comp_dir>/Fuses` once per comp directory.
277 pub fn scan_comp_local(&mut self, comp_path: Option<&Path>) {
278 #[cfg(not(target_arch = "wasm32"))]
279 if let Some(parent) = comp_path.and_then(Path::parent) {
280 let local_fuses = parent.join("Fuses");
281 if self.scanned_comp_dirs.insert(local_fuses.clone()) && local_fuses.is_dir() {
282 self.scan_dir(&local_fuses);
283 }
284 }
285 #[cfg(target_arch = "wasm32")]
286 let _ = comp_path;
287 }
288
289 pub fn has_fuse(&self, kind: &str) -> bool {
290 self.entries.contains_key(&Self::normalize_key(kind))
291 }
292
293 pub fn get(&self, kind: &str) -> Option<&FuseEntry> {
294 self.entries.get(&Self::normalize_key(kind))
295 }
296
297 pub fn len(&self) -> usize {
298 self.entries.len()
299 }
300
301 pub fn is_empty(&self) -> bool {
302 self.entries.is_empty()
303 }
304
305 pub fn clear_pipeline_cache(&self) {
306 if let Ok(mut c) = self.pipeline_cache.lock() {
307 c.clear();
308 }
309 }
310}
311
312fn hash_source(src: &str) -> u64 {
313 let mut h = DefaultHasher::new();
314 src.hash(&mut h);
315 h.finish()
316}
317
318/// Lightweight parser extracting the class ID string from `FuRegisterClass("MyFuse", ...)`.
319pub fn extract_register_class_id(source: &str) -> Option<String> {
320 let idx = source.find("FuRegisterClass")?;
321 let after = &source[idx + "FuRegisterClass".len()..];
322 let open = after.find('(')?;
323 let args = after[open + 1..].trim_start();
324 let quote = args.as_bytes().first().copied()?;
325 if quote != b'"' && quote != b'\'' {
326 return None;
327 }
328 let rest = &args[1..];
329 let end = rest.find(quote as char)?;
330 let id = rest[..end].trim();
331 (!id.is_empty()).then(|| id.to_owned())
332}
333
334// ---------------------------------------------------------------------------
335// Engine integration
336// ---------------------------------------------------------------------------
337
338impl Engine {
339 /// Attempts to evaluate a `Fuse.*` node using the registered Lua / GPU-DCTL Fuse runtime.
340 /// Returns `None` if no matching `.fuse` is registered or if execution fails (allowing the
341 /// caller to fall back cleanly to passthrough + `unsupported_nodes`).
342 #[allow(clippy::too_many_arguments)]
343 pub(crate) fn eval_fuse_runtime(
344 &mut self,
345 comp: &Comp,
346 node: &Node,
347 time: f64,
348 frame_i: i64,
349 comp_dims: [u32; 2],
350 enc: &mut wgpu::CommandEncoder,
351 visiting: &mut HashSet<(NodeId, i64)>,
352 stats: &mut EvalStats,
353 ) -> Option<CachedTexture> {
354 self.eval_fuse_by_id(
355 &node.kind, comp, node, time, frame_i, comp_dims, enc, visiting, stats,
356 )
357 }
358
359 /// Evaluates `node` using the Fuse registered under `fuse_id`.
360 #[allow(clippy::too_many_arguments)]
361 pub fn eval_fuse_by_id(
362 &mut self,
363 fuse_id: &str,
364 comp: &Comp,
365 node: &Node,
366 time: f64,
367 frame_i: i64,
368 comp_dims: [u32; 2],
369 enc: &mut wgpu::CommandEncoder,
370 visiting: &mut HashSet<(NodeId, i64)>,
371 stats: &mut EvalStats,
372 ) -> Option<CachedTexture> {
373 #[cfg(target_arch = "wasm32")]
374 {
375 let _ = (fuse_id, comp, node, time, frame_i, comp_dims, enc, visiting, stats);
376 None
377 }
378 #[cfg(not(target_arch = "wasm32"))]
379 {
380 self.fuse_registry.scan_comp_local(comp.path.as_deref());
381 let entry = self.fuse_registry.get(fuse_id)?.clone();
382
383 // 1. Evaluate all connected flow-node image inputs
384 let mut img_ports: Vec<(String, NodeId)> = Vec::new();
385 for (port, binding) in &node.inputs {
386 if let Some(src_name) = &binding.source_op
387 && let Some(src_id) = comp.find_node(src_name)
388 {
389 img_ports.push((port.clone(), src_id));
390 }
391 }
392 img_ports.sort_by(|a, b| a.0.cmp(&b.0));
393
394 let mut upstream_images: HashMap<String, CachedTexture> = HashMap::new();
395 for (port, src_id) in &img_ports {
396 let tex = self.eval_node(comp, *src_id, time, enc, visiting, stats);
397 upstream_images.insert(port.clone(), tex);
398 }
399 let main_input = ["Input", "Image", "Background", "Source", "MainInput1", "Image1"]
400 .iter()
401 .find_map(|p| upstream_images.get(*p).cloned())
402 .or_else(|| {
403 img_ports
404 .iter()
405 .find(|(p, _)| p != "EffectMask")
406 .and_then(|(p, _)| upstream_images.get(p).cloned())
407 });
408
409 // 2. Evaluate all scalar / point / text / gradient node parameters at `time`
410 let mut param_keys: Vec<&String> = node.inputs.keys().collect();
411 param_keys.sort();
412 let mut eval_params: HashMap<String, lua_host::EvalParam> = HashMap::new();
413 let mut key_hasher = DefaultHasher::new();
414 self.cache.gpu_salt.hash(&mut key_hasher);
415 self.hiq.hash(&mut key_hasher);
416 self.cache.node_salt(node.id).hash(&mut key_hasher);
417 "FuseRuntime".hash(&mut key_hasher);
418 entry.source_hash.hash(&mut key_hasher);
419 comp_dims.hash(&mut key_hasher);
420 (if time == 0.0 { 0.0 } else { time }).to_bits().hash(&mut key_hasher);
421
422 for (port, _) in &img_ports {
423 port.hash(&mut key_hasher);
424 if let Some(tex) = upstream_images.get(port) {
425 tex.content_hash.hash(&mut key_hasher);
426 tex.size.hash(&mut key_hasher);
427 }
428 }
429
430 for k in param_keys {
431 let binding = &node.inputs[k];
432 if binding.source_op.as_deref().is_some_and(|s| comp.find_node(s).is_some()) {
433 continue;
434 }
435 k.hash(&mut key_hasher);
436 match &binding.value {
437 Some(model::ParamValue::Point(def)) => {
438 let pt = comp.eval_point(node, k, time, *def, &self.expr);
439 pt[0].to_bits().hash(&mut key_hasher);
440 pt[1].to_bits().hash(&mut key_hasher);
441 eval_params.insert(k.clone(), lua_host::EvalParam::Point(pt));
442 }
443 Some(model::ParamValue::Text(s) | model::ParamValue::FuId(s)) => {
444 s.hash(&mut key_hasher);
445 eval_params.insert(k.clone(), lua_host::EvalParam::Text(s.clone()));
446 }
447 Some(model::ParamValue::Gradient(g)) => {
448 g.stops.len().hash(&mut key_hasher);
449 eval_params.insert(k.clone(), lua_host::EvalParam::Gradient(g.clone()));
450 }
451 _ => {
452 let def = binding
453 .value
454 .as_ref()
455 .and_then(model::ParamValue::as_f64)
456 .unwrap_or(0.0);
457 let v = comp.eval_number(node, k, time, def, &self.expr);
458 v.to_bits().hash(&mut key_hasher);
459 eval_params.insert(k.clone(), lua_host::EvalParam::Number(v));
460 }
461 }
462 }
463
464 let key = key_hasher.finish();
465 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
466 stats.cache_hits += 1;
467 return Some(hit);
468 }
469
470 // 3. Execute sandboxed Lua + GPU DCTL Fuse
471 let upstream_depth = main_input.as_ref().map(|t| t.depth);
472 let default_depth = self.node_depth(comp, node, time, upstream_depth);
473 let taken_enc = std::mem::replace(
474 enc,
475 self.device
476 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
477 label: Some("fuse-runtime-placeholder"),
478 }),
479 );
480 let bridge = lua_host::HostBridge {
481 device: self.device.clone(),
482 queue: self.queue.clone(),
483 encoder: Some(taken_enc),
484 dummy_tex: self.dummy.clone(),
485 pipeline_cache: self.fuse_registry.pipeline_cache.clone(),
486 supports_f32_filter: self.supports_f32_filter,
487 hiq: self.hiq,
488 default_depth,
489 comp_dims,
490 time,
491 global_range: comp.global_range,
492 render_range: comp.render_range,
493 upstream_images,
494 main_input,
495 params: eval_params,
496 fuse_meta: FuseMeta::default(),
497 output_image: None,
498 tool_data: HashMap::new(),
499 content_hash_seed: key,
500 };
501
502 let (res, returned_enc) = lua_host::execute_fuse(&entry.source, bridge);
503 *enc = returned_enc;
504
505 match res {
506 Ok(Some(mut out_tex)) => {
507 self.fuse_registry.last_error = None;
508 out_tex.content_hash = key;
509 stats.cache_misses += 1;
510 stats.nodes_evaluated += 1;
511 self.cache.insert(key, out_tex.clone(), node.id, frame_i);
512 Some(out_tex)
513 }
514 Ok(None) => {
515 self.fuse_registry.last_error = Some("Fuse did not call OutImage:Set".to_owned());
516 None
517 }
518 Err(e) => {
519 self.fuse_registry.last_error = Some(e);
520 None
521 }
522 }
523 }
524 }
525}